From 78b7343eaa77f7a9600b7aa3277248a3a4d38e46 Mon Sep 17 00:00:00 2001 From: Ajit Awekar Date: Mon, 23 Nov 2026 16:42:50 +0530 Subject: [PATCH v4 2/5] Add TLS client certificate expiry and revocation checks Register a CVT_CERT validator so a session authenticated with a client certificate is terminated once that certificate expires (notAfter) or is revoked. The peer certificate is kept on the Port, so both checks are local, with no network round trip. Revocation is checked by be_tls_get_peer_cert_revoked(), which re-reads ssl_crl_file on demand; the handshake-time check never repeats. Scope is deliberately narrow: the leaf certificate against ssl_crl_file only, not the chain or ssl_crl_dir, and any lookup failure fails open. A certificate required alongside another primary method (clientcert=verify-full) is re-checked too, using a new Port field that outlives the HbaLine it is copied from. Tests: ssl/t/005_cert_continuous_validation.pl covers expiry and mid-session CRL revocation. The revocation case uses a committed client certificate and CRL generated by sslfiles.mk; only the short-lived expiry certificates are issued at run time, since they have no fixed dates to commit. --- doc/src/sgml/config.sgml | 14 + src/backend/libpq/auth-validate-methods.c | 43 ++- src/backend/libpq/auth-validate.c | 22 ++ src/backend/libpq/auth.c | 7 + src/backend/libpq/be-secure-openssl.c | 112 ++++++ src/include/libpq/libpq-be.h | 24 +- src/test/ssl/conf/client-midsession.config | 15 + .../ssl/conf/client_ca_short_lived.config | 27 ++ src/test/ssl/meson.build | 1 + src/test/ssl/ssl/client-midsession.crl | 11 + src/test/ssl/ssl/client-midsession.crt | 19 + src/test/ssl/ssl/client-midsession.key | 28 ++ src/test/ssl/ssl/root+client-midsession.crl | 22 ++ src/test/ssl/sslfiles.mk | 12 +- .../ssl/t/005_cert_continuous_validation.pl | 338 ++++++++++++++++++ src/test/ssl/t/SSL/Backend/OpenSSL.pm | 2 +- 16 files changed, 693 insertions(+), 4 deletions(-) create mode 100644 src/test/ssl/conf/client-midsession.config create mode 100644 src/test/ssl/conf/client_ca_short_lived.config create mode 100644 src/test/ssl/ssl/client-midsession.crl create mode 100644 src/test/ssl/ssl/client-midsession.crt create mode 100644 src/test/ssl/ssl/client-midsession.key create mode 100644 src/test/ssl/ssl/root+client-midsession.crl create mode 100644 src/test/ssl/t/005_cert_continuous_validation.pl diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index f193691eb1e..486a5db5a27 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -1142,6 +1142,20 @@ include_dir 'conf.d' bearer token or of the client certificate. The default is off. + + For client-certificate sessions, this method-specific check also + re-checks certificate revocation on each cycle, independently of the + one-time check already performed at connection time (see + ). This periodic re-check has a + narrower scope than the connection-time check, however: it only + consults , not + , and it only checks the client's + own certificate, not any intermediate certificate authorities in + its chain. A certificate revoked only via + ssl_crl_dir, or an intermediate CA revoked after + the session was established, will therefore not cause an + already-open session to be terminated by this mechanism. + The re-validation period is controlled by . Validation is diff --git a/src/backend/libpq/auth-validate-methods.c b/src/backend/libpq/auth-validate-methods.c index e94ebb2626d..4a3c3635404 100644 --- a/src/backend/libpq/auth-validate-methods.c +++ b/src/backend/libpq/auth-validate-methods.c @@ -26,13 +26,20 @@ #include "utils/syscache.h" #include "utils/timestamp.h" +/* Function declarations for internal use */ +static bool validate_cert_credentials(void); + /* * Initialize validation methods */ void InitializeValidationMethods(void) { - /* No method-specific validators are registered yet. */ + /* + * Register method-specific validators. Password methods need none -- + * ValidateRoleValidity() covers every session's baseline check. + */ + RegisterCredentialValidator(CVT_CERT, validate_cert_credentials); } /* @@ -81,3 +88,37 @@ ValidateRoleValidity(void) ReleaseSysCache(tuple); return result; } + +/* + * CVT_CERT validator: the peer cert is retained on Port, so its notAfter + * and revocation status can be re-checked locally, no round-trip needed. + * No cert on the session (shouldn't happen) is treated as valid. + */ +static bool +validate_cert_credentials(void) +{ +#ifdef USE_SSL + Port *port = MyProcPort; + + if (port == NULL || !port->ssl_in_use || port->peer == NULL) + return true; + + /* The session is no longer valid once the client certificate expires */ + if (be_tls_get_peer_cert_expired(port)) + { + SetCredentialValidationFailureDetail("client certificate check failed for user \"%s\": certificate has expired", + port->user_name); + return false; + } + + /* Nor is it valid once the certificate has been revoked via CRL */ + if (be_tls_get_peer_cert_revoked(port)) + { + SetCredentialValidationFailureDetail("client certificate check failed for user \"%s\": certificate has been revoked", + port->user_name); + return false; + } +#endif + + return true; +} diff --git a/src/backend/libpq/auth-validate.c b/src/backend/libpq/auth-validate.c index 003dc825445..264ef9a438f 100644 --- a/src/backend/libpq/auth-validate.c +++ b/src/backend/libpq/auth-validate.c @@ -285,5 +285,27 @@ CheckCredentialValidity(void) (int) MyClientConnectionInfo.auth_method); } + /* + * A client cert can be required alongside a different primary method + * (clientcert=verify-full); re-check CVT_CERT here too in that case. + * Reads hba_clientcert, not hba->clientcert (freed by now; see + * libpq-be.h). + */ + if (result && + validation_type != CVT_CERT && + validators[CVT_CERT] != NULL && + MyProcPort != NULL && + MyProcPort->hba_clientcert != clientCertOff) + { + elog(DEBUG1, "credential validation: also rechecking CVT_CERT (clientcert required alongside auth method %d)", + (int) MyClientConnectionInfo.auth_method); + result = validators[CVT_CERT] (); + + if (!result && credential_validation_detail[0] == '\0') + SetCredentialValidationFailureDetail("client certificate re-check failed for user \"%s\" (auth method %d)", + MyProcPort->user_name, + (int) MyClientConnectionInfo.auth_method); + } + return result; } diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c index 12bf153d66f..d84e35e8955 100644 --- a/src/backend/libpq/auth.c +++ b/src/backend/libpq/auth.c @@ -356,6 +356,13 @@ set_authn_id(Port *port, const char *id) MyClientConnectionInfo.authn_id = MemoryContextStrdup(TopMemoryContext, id); MyClientConnectionInfo.auth_method = port->hba->auth_method; + /* + * Copy out what we need from "hba" while valid -- it's freed early in + * this backend's startup, well before the session ends (see + * hba_clientcert's comment in libpq-be.h). + */ + port->hba_clientcert = port->hba->clientcert; + if (log_connections & LOG_CONNECTION_AUTHENTICATION) { ereport(LOG, diff --git a/src/backend/libpq/be-secure-openssl.c b/src/backend/libpq/be-secure-openssl.c index fbd4f1173bc..60d67a97684 100644 --- a/src/backend/libpq/be-secure-openssl.c +++ b/src/backend/libpq/be-secure-openssl.c @@ -2339,6 +2339,118 @@ be_tls_get_peer_serial(Port *port, char *ptr, size_t len) ptr[0] = '\0'; } +/* + * Returns true if the peer cert's notAfter has already passed. An absent + * or unparsable notAfter is conservatively treated as not expired, so we + * never terminate a session over an unreadable field. + */ +bool +be_tls_get_peer_cert_expired(Port *port) +{ + const ASN1_TIME *not_after; + + if (port->peer == NULL) + return false; + + not_after = X509_get0_notAfter(port->peer); + if (not_after == NULL) + return false; + + /* + * X509_cmp_current_time() returns -1 for a past time (expired), 1 for + * future, 0 on parse error. + */ + return (X509_cmp_current_time(not_after) < 0); +} + +/* + * Re-checks the peer cert against ssl_crl_file on demand (cached by + * mtime), unlike the one-time handshake-time CRL check. Leaf cert and + * ssl_crl_file only (not chain/ssl_crl_dir); fails open on any error. + */ +bool +be_tls_get_peer_cert_revoked(Port *port) +{ + static char cached_path[MAXPGPATH] = {0}; + static time_t cached_mtime = 0; + static STACK_OF(X509_CRL) * cached_crls = NULL; + + struct stat st; + bool revoked = false; + int i; + + if (port->peer == NULL) + return false; + + if (ssl_crl_file[0] == '\0') + return false; + + if (stat(ssl_crl_file, &st) != 0) + return false; + + /* + * Reload when the path or mtime changed. A failed load leaves + * cached_crls as an empty non-NULL stack, so a broken file is retried + * only once per distinct mtime, not every call. + */ + if (cached_crls == NULL || + strcmp(cached_path, ssl_crl_file) != 0 || + cached_mtime != st.st_mtime) + { + X509_STORE *store; + STACK_OF(X509_CRL) * new_crls = NULL; + + if (cached_crls != NULL) + sk_X509_CRL_pop_free(cached_crls, X509_CRL_free); + + /* + * Load into a throwaway store and fetch only the peer's issuer's + * CRL(s), reusing the same OpenSSL primitives be_tls_init() uses at + * handshake time instead of hand-parsing. + */ + store = X509_STORE_new(); + if (store != NULL) + { + if (X509_STORE_load_locations(store, ssl_crl_file, NULL) == 1) + { + X509_STORE_CTX *storectx = X509_STORE_CTX_new(); + + if (storectx != NULL) + { + if (X509_STORE_CTX_init(storectx, store, NULL, NULL) == 1) + new_crls = X509_STORE_CTX_get1_crls(storectx, + X509_get_issuer_name(port->peer)); + X509_STORE_CTX_free(storectx); + } + } + X509_STORE_free(store); + } + + cached_crls = new_crls != NULL ? new_crls : sk_X509_CRL_new_null(); + cached_mtime = st.st_mtime; + strlcpy(cached_path, ssl_crl_file, sizeof(cached_path)); + } + + for (i = 0; i < sk_X509_CRL_num(cached_crls); i++) + { + X509_CRL *crl = sk_X509_CRL_value(cached_crls, i); + X509_REVOKED *r; + + /* + * 1 = revoked; 2 = removeFromCRL (delta-CRL-only, shouldn't appear in + * a base CRL). Treat either as revoked -- the safer, fail-closed + * reading. + */ + if (X509_CRL_get0_by_cert(crl, &r, port->peer) != 0) + { + revoked = true; + break; + } + } + + return revoked; +} + char * be_tls_get_certificate_hash(Port *port, size_t *len) { diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h index 921b2daa4ff..9fdb20241a4 100644 --- a/src/include/libpq/libpq-be.h +++ b/src/include/libpq/libpq-be.h @@ -160,10 +160,19 @@ typedef struct Port char *application_name; /* - * Information that needs to be held during the authentication cycle. + * Held during authentication only: "hba" points into a context every + * backend deletes early in startup. Anything needed later (like + * hba_clientcert below) must be copied out before that happens. */ HbaLine *hba; + /* + * Whether this session's HBA line required a client cert, copied out of + * hba->clientcert by set_authn_id() while "hba" is still valid. Safe to + * read for the session's lifetime, unlike "hba" itself. + */ + ClientCertMode hba_clientcert; + /* * TCP keepalive and user timeout settings. * @@ -321,6 +330,19 @@ extern void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len); extern void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len); extern void be_tls_get_peer_serial(Port *port, char *ptr, size_t len); +/* + * Report whether the client certificate's validity period (notAfter) has + * already passed. Returns false when no peer certificate is present. + */ +extern bool be_tls_get_peer_cert_expired(Port *port); + +/* + * Report whether the client certificate appears on the CRL configured via + * ssl_crl_file. Best-effort addition to, not a replacement for, the + * revocation check already done at handshake time; fails open. + */ +extern bool be_tls_get_peer_cert_revoked(Port *port); + /* * Get the server certificate hash for SCRAM channel binding type * tls-server-end-point. diff --git a/src/test/ssl/conf/client-midsession.config b/src/test/ssl/conf/client-midsession.config new file mode 100644 index 00000000000..876e27f2c21 --- /dev/null +++ b/src/test/ssl/conf/client-midsession.config @@ -0,0 +1,15 @@ +# An OpenSSL format CSR config file for creating a client certificate. +# +# This is identical to the client.config certificate, but this one is revoked +# only by client-midsession.crl, not by client.crl. It lets a test connect +# with a certificate that is valid at connection time and then revoke it +# while the session is open. + +[ req ] +distinguished_name = req_distinguished_name +prompt = no + +[ req_distinguished_name ] +CN = ssltestuser + +# no extensions in client certs diff --git a/src/test/ssl/conf/client_ca_short_lived.config b/src/test/ssl/conf/client_ca_short_lived.config new file mode 100644 index 00000000000..09f78af71b9 --- /dev/null +++ b/src/test/ssl/conf/client_ca_short_lived.config @@ -0,0 +1,27 @@ +# Configuration for operating the client CA at test time, to issue client +# certificates that expire a few seconds after they are issued. +# +# This signs with the committed client CA (the same certificate and key that +# cas.config uses), but keeps its index, serial and issued-certificate state +# in a scratch directory named by the SSL_TEST_CA_DIR environment variable, +# so that running a test never touches the committed ssl/ directory. Paths +# are relative to src/test/ssl, as in cas.config. +# +# Certificates issued this way can't be committed: their validity is relative +# to the time the test runs, so there are no fixed dates to generate them +# with. Everything else the tests use is generated by sslfiles.mk. + +[ short_lived_client_ca ] +certificate = ./ssl/client_ca.crt +private_key = ./ssl/client_ca.key +database = $ENV::SSL_TEST_CA_DIR/index.txt +serial = $ENV::SSL_TEST_CA_DIR/serial.txt +new_certs_dir = $ENV::SSL_TEST_CA_DIR/newcerts +default_md = sha256 +default_days = 1 +policy = policy_match +email_in_dn = no +unique_subject = no + +[ policy_match ] +commonName = supplied diff --git a/src/test/ssl/meson.build b/src/test/ssl/meson.build index d7e7ce23433..cff390e1a9d 100644 --- a/src/test/ssl/meson.build +++ b/src/test/ssl/meson.build @@ -14,6 +14,7 @@ tests += { 't/002_scram.pl', 't/003_sslinfo.pl', 't/004_sni.pl', + 't/005_cert_continuous_validation.pl', ], }, } diff --git a/src/test/ssl/ssl/client-midsession.crl b/src/test/ssl/ssl/client-midsession.crl new file mode 100644 index 00000000000..693705e38d4 --- /dev/null +++ b/src/test/ssl/ssl/client-midsession.crl @@ -0,0 +1,11 @@ +-----BEGIN X509 CRL----- +MIIBpzCBkDANBgkqhkiG9w0BAQsFADBCMUAwPgYDVQQDDDdUZXN0IENBIGZvciBQ +b3N0Z3JlU1FMIFNTTCByZWdyZXNzaW9uIHRlc3QgY2xpZW50IGNlcnRzFw0yNjEx +MjMwOTQ2NTFaGA8yMDU0MDQxMDA5NDY1MVowGzAZAgggJhEjFRZRABcNMjYxMTIz +MDk0NjUxWjANBgkqhkiG9w0BAQsFAAOCAQEAluk1aQd18PeqdaJwHyjIUm9V1xjj +xbOiTRMcDfGZVs1lAk877rnjfQBokET3Mc//pCCAr7XmqUlWI/uG4BlC4XZXdUfz +wNghXP92rKJJkghgohrUd0uB4+hrBJ8IX6vTkE2K1YHqTZ32XtJXE9JjAGM6v72P +Og0tbrKwdvCHMnOzXU7auZx7vqo5W6+vvf4HOigHf73pYR1aqq/qhfDKF1z5WHll +gUBjL/2rvZvMDnNvTxMX9Fh7Wfs2eiCYi/CoVVAvcES71jziqBcmQYwVOiQG19EW +fhG4pltKRTW94semW5lfr8J05Q/uOrbK3jTmpj7+1QRWd5gjBxlfVPg9Tw== +-----END X509 CRL----- diff --git a/src/test/ssl/ssl/client-midsession.crt b/src/test/ssl/ssl/client-midsession.crt new file mode 100644 index 00000000000..032cedb3337 --- /dev/null +++ b/src/test/ssl/ssl/client-midsession.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDHjCCAgagAwIBAgIIICYRIxUWUQAwDQYJKoZIhvcNAQELBQAwQjFAMD4GA1UE +Aww3VGVzdCBDQSBmb3IgUG9zdGdyZVNRTCBTU0wgcmVncmVzc2lvbiB0ZXN0IGNs +aWVudCBjZXJ0czAgFw0yMzA2MjkwMTAxMDFaGA8yMDUwMDEwMTAxMDEwMVowFjEU +MBIGA1UEAwwLc3NsdGVzdHVzZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQC/n1a/NuVjJL0crQUsrDv/qd6Qkd8mH7afpgOBpSX+gVnTihJ7jds0JEIT +VQxctVdemosL10qBIc6zRX7uGDChmeItyD+6q+B8Gdyifye58PJuLJVeHttSJK23 +hynb731tdUCtkk1Y25srrSoVFay3phlcqbs4bU5K3ENvwjoykzL/gzb9EC7/qfk9 +RHfo5giCwym5OfnBLjNsLbyLL4zuhXIovEChl86GnDK8kiDEL+GgcUiyxzfJ7nzG +bHPrLo/Yyz9qgA5pDr28b8nDU7OrZM3viMrrHYTnqW+jvz4Jz7V3IKxjksR+7QQZ +LiBjwNGytf/18qk8pWhKNzWbeUNNAgMBAAGjQjBAMB0GA1UdDgQWBBQHbowlHpTd +yrRM4Pd0NI0UscaVtzAfBgNVHSMEGDAWgBSfpOvSyZnesAOwMDQigWEVS72tNjAN +BgkqhkiG9w0BAQsFAAOCAQEAYn/OTBqMmhauf9yhQCsxIknxU2gsDds4CszZP1Ty +77RNmfQ9Cqon/i5RnIbe+bel0vm6B0XBGxHEuJuChJk6/rWp4wUdCTRiQpPQ1MI7 +S+6hBGBQzWG/7vzpRo/p7yM9CJUQLTAylz9OwV2Lts/zuUSTdXN5l8mDJ6XkH3ON +dh/kZEBgN3tb7MIJuBEF60hH3rkg4S6CkdJ/xlz37VDBjPrxbCnit950cmB/maU4 +1u+uHHKl+mYro+tu9xTt79BnuZ4q3paEuKOuFGOr13elmGJ4C5qefhDX7hqUjycJ +7k3YFm6rffYEAtqVGjD+dhCIDJzHlWaXhD+6LFSMGbftHw== +-----END CERTIFICATE----- diff --git a/src/test/ssl/ssl/client-midsession.key b/src/test/ssl/ssl/client-midsession.key new file mode 100644 index 00000000000..786e0f47f7b --- /dev/null +++ b/src/test/ssl/ssl/client-midsession.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/n1a/NuVjJL0c +rQUsrDv/qd6Qkd8mH7afpgOBpSX+gVnTihJ7jds0JEITVQxctVdemosL10qBIc6z +RX7uGDChmeItyD+6q+B8Gdyifye58PJuLJVeHttSJK23hynb731tdUCtkk1Y25sr +rSoVFay3phlcqbs4bU5K3ENvwjoykzL/gzb9EC7/qfk9RHfo5giCwym5OfnBLjNs +LbyLL4zuhXIovEChl86GnDK8kiDEL+GgcUiyxzfJ7nzGbHPrLo/Yyz9qgA5pDr28 +b8nDU7OrZM3viMrrHYTnqW+jvz4Jz7V3IKxjksR+7QQZLiBjwNGytf/18qk8pWhK +NzWbeUNNAgMBAAECggEABAcT2jILsUFI7kzesnkuS6nk4TIHuDPrcUCai0OO4GIU +osMgr1Mke9yVPPXJLDutifICoS2VxdARmagIynVctFDZNbAjUsehEMq0XgABNEHR +vqoWO6O3ZWsa8aQYJ6TJhJ71zJAqKwd2o/zgSRArELMfjliM9FsrzZwCmNtCwORY +2qF5rfnqrGabNCPiIyS8XguA6hSCGUnCBllhmMOlZyxB244JXgb6D3STwEeI0qYW +ujAny6n9DS0vH1uz795L2xntpzlW0knhuRe1fzH0P5pCq1eG4UiBx4G4NyKTILUW +eaXMyt/V/RQJE+F3bHFl1RiBp4HHHpoOouxrwFimIQKBgQDhfYH6cXmPk1kWlh1J +ILo2MPPyFnGBBQXNvy3anMloVolaSLAO15txU2x5LgpeBOVV+bWYWJaDzO5t/JTk +EyG7kQtl5lM2jMU0+oV5L/7SNDuehOl6J3GiiM+rvOO3wIxCx/GqINf/DuaUYs1R +VePZdvR7rgratoW6eMiMRoQDPQKBgQDZjLj6fJwrlVXiPEbRTCTZs36RkZtfCJD4 +GdQgWQc9ENivL+MjMDqbAXKXG/9VELUOnqu1luiOOzbTfxKDMX2YRY80RdNxn2K2 +wjTqGbSxmaIefFV+hGmeiPHKbu8s18QEnvbNWw0gJTfvT1HKtCI8/zNkf8Oi90UV +DtfRDYUBUQKBgCPfTaBEESywKkoXk40gsb8RRp3KyD/YRrYWpfrTWo9IxQ0h5zBV +SJtcxDL7Chcu/DUTRrp3zWomXgANYLpv+LvYNVH+tFpHRtBI0pcW9ZkHSjzLtEEE +qWVMEo2lvSxsa2PsXxvLodEn07LjjPpViav86qQKahulUdz6fh0i0rmZAoGBAJ5y +M7ecUlIb7fVcWWfOwXgdly2Gk1bf8lYA2dLFhNQhFPBjPFdApS6IG2GbbpgSFwyS +3BTh2HbfAcuAXYdX4FWrM+WqhZnXsBnT0J5AIq7HaqAxhkMjRZnFu/ToXyKV85o5 +/R8MFb833ElbyAKOt/EdHd0wgNiMp6/yo5UK97hBAoGACHetXkvZDjAtwiGDnuRL +AKhCJVqNmVTXbRayp5h1XhrRzCVvgL/EXBaFeLa3lcREN4rlbsgVoRgWsx5N7NhW +kgfF2I42db5Rfu0bdM02N23NlHg6beR+rL7s/6WRUdjVB6aJaWcMyyStlJ7tA36j +/JIHIDkzamcT91HBen7d/jU= +-----END PRIVATE KEY----- diff --git a/src/test/ssl/ssl/root+client-midsession.crl b/src/test/ssl/ssl/root+client-midsession.crl new file mode 100644 index 00000000000..b2b2e589cb5 --- /dev/null +++ b/src/test/ssl/ssl/root+client-midsession.crl @@ -0,0 +1,22 @@ +-----BEGIN X509 CRL----- +MIIBhTBvMA0GCSqGSIb3DQEBCwUAMEAxPjA8BgNVBAMMNVRlc3Qgcm9vdCBDQSBm +b3IgUG9zdGdyZVNRTCBTU0wgcmVncmVzc2lvbiB0ZXN0IHN1aXRlFw0yMTAzMDMy +MjEyMDdaFw00ODA3MTkyMjEyMDdaMA0GCSqGSIb3DQEBCwUAA4IBAQACkv0Nnerr +ZkacIUbRaANYLIsYAGfKuBYDAp4I4CCC2hvXL64KLDMZbVfB4vp3hvM2FZdT2AwT +SBNr2rpYp7Coc3GeCoWPcClgSrABD3Z5GY1YAdLGiXVKaH3CmdJTznhEPagE4z5R +40qbmw8RU062ZbyFamBO7VTY7IFBA8PxuTgAH/3OYa5Jne8umyPQT5fKnqyRBz/A +6/b5RCxuPOWFm0MJKrEaAeLk6eaCxUUqXQP+8mHscphqZTOynjAW0NPH+/x2NpxS +/C5LTeOzJ28k8X434h323G18n/CFERWnhW1UyR1Pt6oSGMZqU5UwbSrwTsf8tSSc ++GrJP3XxJ1OC +-----END X509 CRL----- +-----BEGIN X509 CRL----- +MIIBpzCBkDANBgkqhkiG9w0BAQsFADBCMUAwPgYDVQQDDDdUZXN0IENBIGZvciBQ +b3N0Z3JlU1FMIFNTTCByZWdyZXNzaW9uIHRlc3QgY2xpZW50IGNlcnRzFw0yNjEx +MjMwOTQ2NTFaGA8yMDU0MDQxMDA5NDY1MVowGzAZAgggJhEjFRZRABcNMjYxMTIz +MDk0NjUxWjANBgkqhkiG9w0BAQsFAAOCAQEAluk1aQd18PeqdaJwHyjIUm9V1xjj +xbOiTRMcDfGZVs1lAk877rnjfQBokET3Mc//pCCAr7XmqUlWI/uG4BlC4XZXdUfz +wNghXP92rKJJkghgohrUd0uB4+hrBJ8IX6vTkE2K1YHqTZ32XtJXE9JjAGM6v72P +Og0tbrKwdvCHMnOzXU7auZx7vqo5W6+vvf4HOigHf73pYR1aqq/qhfDKF1z5WHll +gUBjL/2rvZvMDnNvTxMX9Fh7Wfs2eiCYi/CoVVAvcES71jziqBcmQYwVOiQG19EW +fhG4pltKRTW94semW5lfr8J05Q/uOrbK3jTmpj7+1QRWd5gjBxlfVPg9Tw== +-----END X509 CRL----- diff --git a/src/test/ssl/sslfiles.mk b/src/test/ssl/sslfiles.mk index f32c53a76a1..7cc796e3927 100644 --- a/src/test/ssl/sslfiles.mk +++ b/src/test/ssl/sslfiles.mk @@ -35,7 +35,7 @@ SERVERS := server-cn-and-alt-names \ server-no-names \ server-revoked CLIENTS := client client-dn client-revoked client_ext client-long \ - client-revoked-utf8 + client-midsession client-revoked-utf8 # # To add a new non-standard certificate, add it to SPECIAL_CERTS and then add @@ -62,6 +62,7 @@ COMBINATIONS := \ ssl/root+server.crl \ ssl/root+client_ca.crt \ ssl/root+client.crl \ + ssl/root+client-midsession.crl \ ssl/client+client_ca.crt \ ssl/server-cn-only+server_ca.crt @@ -70,6 +71,7 @@ STANDARD_CERTS := $(CERTIFICATES:%=ssl/%.crt) STANDARD_KEYS := $(CERTIFICATES:%=ssl/%.key) CRLS := ssl/root.crl \ ssl/client.crl \ + ssl/client-midsession.crl \ ssl/server.crl SSLFILES := \ @@ -159,6 +161,7 @@ ssl/server-cn-only+server_ca.crt: ssl/server-cn-only.crt ssl/server_ca.crt # chain, even if some of them are empty. ssl/root+server.crl: ssl/root.crl ssl/server.crl ssl/root+client.crl: ssl/root.crl ssl/client.crl +ssl/root+client-midsession.crl: ssl/root.crl ssl/client-midsession.crl $(COMBINATIONS): cat $^ > $@ @@ -244,6 +247,13 @@ ssl/client.crl: ssl/client-revoked.crt ssl/client-revoked-utf8.crt ssl/client_ca $(OPENSSL) ca -config conf/cas.config -name client_ca -revoke ssl/client-revoked-utf8.crt $(OPENSSL) ca -config conf/cas.config -name client_ca -gencrl -out $@ +# Revokes only client-midsession.crt (plus whatever else this run's client_ca +# state already holds, which is harmless). Used to revoke a certificate +# while a session that authenticated with it is still open. +ssl/client-midsession.crl: ssl/client-midsession.crt ssl/client_ca.crt | $(client_ca_state_files) + $(OPENSSL) ca -config conf/cas.config -name client_ca -revoke ssl/client-midsession.crt + $(OPENSSL) ca -config conf/cas.config -name client_ca -gencrl -out $@ + # # CRL hash directories # diff --git a/src/test/ssl/t/005_cert_continuous_validation.pl b/src/test/ssl/t/005_cert_continuous_validation.pl new file mode 100644 index 00000000000..775dc6d4446 --- /dev/null +++ b/src/test/ssl/t/005_cert_continuous_validation.pl @@ -0,0 +1,338 @@ +# Copyright (c) 2021-2026, PostgreSQL Global Development Group + +# Test continuous credential validation for TLS client certificate +# authentication: a session that authenticated with a client certificate +# must be terminated once that certificate passes its notAfter date, even +# though the certificate was valid at connection time. + +use strict; +use warnings FATAL => 'all'; +use Cwd qw(abs_path); +use POSIX qw(strftime); +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +use FindBin; +use lib $FindBin::RealBin; + +use SSL::Server; + +if ($ENV{with_ssl} ne 'openssl') +{ + plan skip_all => 'OpenSSL not supported by this build'; +} +if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bssl\b/) +{ + plan skip_all => + 'Potentially unsafe test SSL not enabled in PG_TEST_EXTRA'; +} + +my $ssl_server = SSL::Server->new(); + +# This is the hostname used to connect to the server. +my $SERVERHOSTADDR = '127.0.0.1'; +# This is the pattern to use in pg_hba.conf to match incoming connections. +my $SERVERHOSTCIDR = '127.0.0.1/32'; + +# How long the runtime-generated client certificate stays valid, and how +# often the server re-validates credentials. The certificate must outlive +# connection setup but expire well within the test's wait window. +my $cert_validity_secs = 10; +my $validation_interval = 5; # minimum allowed by the GUC + +# 1. Initialize and start the cluster with continuous validation enabled. +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +$node->append_conf('postgresql.conf', + "credential_validation_enabled = on\n"); +$node->append_conf('postgresql.conf', + "credential_validation_interval = $validation_interval\n"); +$node->start; + +# 2. Configure the server for SSL. This creates the "ssltestuser" role and +# the "certdb"/"verifydb" databases. Regardless of the base auth method +# passed here, the generated HBA always serves "certdb" with plain "cert" +# (client-certificate-only) authentication; "verifydb" instead combines the +# base auth method with "clientcert=verify-full", which is what Test 2 below +# uses to exercise a certificate re-check alongside a non-cert primary auth +# method. ssltestuser's password is set here so scram-sha-256 works on +# "verifydb". +my $password = 'ssltestpass'; +$ssl_server->configure_test_server_for_ssl( + $node, $SERVERHOSTADDR, + $SERVERHOSTCIDR, 'scram-sha-256', + password => $password, + password_enc => 'scram-sha-256'); +$ssl_server->switch_server_cert($node, certfile => 'server-cn-only'); + +# Extract the bare key path from a "sslkey=..." connection-string fragment. +# SSL::Server's sslkey() hands back a 0600 copy of the committed key, which +# libpq requires (the checked-out files are not 0600). +sub keypath +{ + my ($name) = @_; + my $frag = $ssl_server->sslkey($name); + $frag =~ s/^\s*sslkey=//; + return $frag; +} +my $client_key = keypath('client.key'); + +# The short-lived certificates of Tests 1 and 2 are issued by the committed +# client CA, configured in conf/client_ca_short_lived.config. That is the one +# thing that can't be generated by sslfiles.mk: a certificate that expires +# seconds after it is issued has no fixed dates to commit. The config keeps +# its index/serial/issued-cert state in a scratch directory, named through +# the environment so no path has to be written into a config file (OpenSSL +# treats backslashes in config files as escapes, which would mangle a Windows +# path; forward slashes work for file access there too). +my $ca_dir = PostgreSQL::Test::Utils::tempdir(); +mkdir "$ca_dir/newcerts" or die "could not create newcerts dir: $!"; +PostgreSQL::Test::Utils::append_to_file("$ca_dir/index.txt", ''); +PostgreSQL::Test::Utils::append_to_file("$ca_dir/serial.txt", "1000\n"); +($ENV{SSL_TEST_CA_DIR} = $ca_dir) =~ s{\\}{/}g; + +# Mint a short-lived client certificate for CN=ssltestuser, signed by the +# committed test client CA. We use "openssl ca -startdate/-enddate" (rather +# than "x509 -req -not_after") because those options work back to OpenSSL +# 1.1.1, which core still supports. +sub mint_short_lived_client_cert +{ + my ($label) = @_; + my $tempdir = PostgreSQL::Test::Utils::tempdir(); + + # notBefore is set well in the past to avoid any clock-skew rejection at + # connect time; notAfter is a few seconds out so the certificate expires + # while the session is alive. + my $now = time(); + my $startdate = strftime("%Y%m%d%H%M%SZ", gmtime($now - 300)); + my $enddate = + strftime("%Y%m%d%H%M%SZ", gmtime($now + $cert_validity_secs)); + + PostgreSQL::Test::Utils::system_or_bail( + 'openssl', 'req', '-new', + '-config' => 'conf/client.config', + '-key' => $client_key, + '-out' => "$tempdir/$label.csr"); + + PostgreSQL::Test::Utils::system_or_bail( + 'openssl', 'ca', '-batch', '-notext', + '-config' => 'conf/client_ca_short_lived.config', + '-name' => 'short_lived_client_ca', + '-startdate' => $startdate, + '-enddate' => $enddate, + '-in' => "$tempdir/$label.csr", + '-out' => "$tempdir/$label.crt"); + + # The path ends up in a libpq connection string, where a backslash is an + # escape character; a Windows tempdir such as "C:\...\tmp_test_xxxx" + # would be mangled and libpq would send no certificate at all. Forward + # slashes work for file access on Windows too. + (my $crt = "$tempdir/$label.crt") =~ s{\\}{/}g; + return $crt; +} + +############################################################################# +# Tests 1 and 2 both need "a session whose client certificate naturally +# expires mid-session, revalidated after one interval elapses". They use +# independent certificates/sessions (though the same underlying +# "ssltestuser" role on the wire), so both certificates are minted and both +# sessions opened up front, and they share one wait for the certificate +# expiry + validation interval to elapse (together with Test 3's revocation, +# below), rather than each test waiting out its own separate window. Because +# both use the exact same +# failure text ("certificate has expired" for "ssltestuser"), each assertion +# below is scoped to its own session's backend PID (via a log-line-prefix +# match), so Test 1's and Test 2's log lines can never satisfy each other's +# checks. +############################################################################# + +############################################################################# +# Test 1: a session authenticated purely with a client certificate ("cert" +# HBA method) is terminated once that certificate passes its notAfter date. +############################################################################# +note "=== Test 1: pure client-certificate authentication ==="; + +my $cert1 = mint_short_lived_client_cert('short1'); + +my $connstr1 = + "host=$SERVERHOSTADDR port=" . $node->port . " dbname=certdb " + . "user=ssltestuser sslmode=verify-ca " + . "sslrootcert=ssl/root+server_ca.crt " + . "sslcert=$cert1 sslkey=$client_key"; + +my $session1 = $node->background_psql( + 'certdb', + connstr => $connstr1, + on_error_stop => 0); + +# The certificate is still valid, so the session works normally. +my ($stdout, $ret) = $session1->query('SELECT 1 AS success;'); +like($stdout, qr/1/, 'cert session works while certificate is valid'); +is($ret, 0, 'no error on initial query for cert session'); + +my $pid1; +($stdout, $ret) = $session1->query('SELECT pg_backend_pid();'); +$pid1 = $1 if $stdout =~ /(\d+)/; +ok(defined $pid1, 'got session1 backend pid'); + +############################################################################# +# Test 2: a session authenticated with a *different* primary auth method +# (scram-sha-256) that also required a client certificate +# ("clientcert=verify-full") must still be terminated once that certificate +# expires. Regression test for a gap where CheckCredentialValidity() only +# ran the validator for the primary auth method (CVT_COUNT for scram-sha-256, +# i.e. none), so a certificate required only as a second factor was never +# rechecked, even though the session's continued trust still depended on it. +############################################################################# +note "=== Test 2: scram-sha-256 + clientcert=verify-full also rechecks the certificate ==="; + +my $cert2 = mint_short_lived_client_cert('short2'); + +$ENV{PGPASSWORD} = $password; +my $connstr2 = + "host=$SERVERHOSTADDR port=" . $node->port . " dbname=verifydb " + . "user=ssltestuser sslmode=verify-ca " + . "sslrootcert=ssl/root+server_ca.crt " + . "sslcert=$cert2 sslkey=$client_key"; + +my $session2 = $node->background_psql( + 'verifydb', + connstr => $connstr2, + on_error_stop => 0); + +($stdout, $ret) = $session2->query('SELECT 1 AS success;'); +like($stdout, qr/1/, + '2FA (scram + clientcert) session works while certificate is valid'); +is($ret, 0, 'no error on initial query for 2FA session'); + +my $pid2; +($stdout, $ret) = $session2->query('SELECT pg_backend_pid();'); +$pid2 = $1 if $stdout =~ /(\d+)/; +ok(defined $pid2, 'got session2 backend pid'); + +############################################################################# +# Test 3: a session authenticated with a client certificate must be +# terminated once that certificate is revoked via CRL, even though it was +# never expired and even though nothing forces the already-forked backend +# serving this session to reload the CRL that was (or wasn't) in effect +# when it started -- only the postmaster and freshly-forked backends reload +# ssl_crl_file on SIGHUP. This exercises be_tls_get_peer_cert_revoked()'s +# own direct, on-demand re-read of ssl_crl_file, not the handshake-time CRL +# check that already existed. +# +# The session is opened and the certificate revoked here, in the same +# window as the Test 1/2 certificates' expiry, so the three terminations +# are waited for together rather than one after another. +############################################################################# +note "=== Test 3: client certificate revoked via CRL mid-session ==="; + +# Use the long-lived, committed "client-midsession" certificate (valid until +# 2050), so this test exercises revocation specifically, not expiry. The +# server's default CRL (root+client.crl) does not revoke it; +# root+client-midsession.crl, also committed and generated by sslfiles.mk, +# does. +my $connstr3 = + "host=$SERVERHOSTADDR port=" . $node->port . " dbname=certdb " + . "user=ssltestuser sslmode=verify-ca " + . "sslrootcert=ssl/root+server_ca.crt " + . "sslcert=ssl/client-midsession.crt " + . $ssl_server->sslkey('client-midsession.key'); + +my $session3 = $node->background_psql( + 'certdb', + connstr => $connstr3, + on_error_stop => 0); + +($stdout, $ret) = $session3->query('SELECT 1 AS success;'); +like($stdout, qr/1/, 'cert session works before the certificate is revoked'); +is($ret, 0, 'no error on initial query for the revocation test session'); + +my $pid3; +($stdout, $ret) = $session3->query('SELECT pg_backend_pid();'); +$pid3 = $1 if $stdout =~ /(\d+)/; +ok(defined $pid3, 'got session3 backend pid'); + +# Publish the CRL that revokes that certificate. Reload only: a restart +# would terminate the session instead of exercising the periodic check. +(my $revoked_crl = abs_path('ssl/root+client-midsession.crl')) =~ s{\\}{/}g; +$ssl_server->switch_server_cert($node, + certfile => 'server-cn-only', + crlfile => $revoked_crl, + restart => 'no'); +$node->reload; + +# Wait for each backend's termination to show up in the log, rather than +# sleeping a fixed time: the test proceeds as soon as the FATAL appears. +# Credential validation also runs while a session sits idle waiting for the +# next message, so none of the sessions needs to be queried again for this. +# Each pattern is scoped to its own backend PID, since the expiry FATALs of +# Tests 1 and 2 carry the same text. +note "waiting for the certificates to expire and the revocation to be noticed..."; +$node->wait_for_log( + qr/backend\[$pid3\].*FATAL:.*session credentials have expired/); +$node->wait_for_log( + qr/backend\[$pid1\].*FATAL:.*session credentials have expired/); +$node->wait_for_log( + qr/backend\[$pid2\].*FATAL:.*session credentials have expired/); + +############################################################################# +# Test 1 checks +############################################################################# +eval { $session1->query('SELECT 2 AS failure_expected;'); }; + +my $log_contents = slurp_file($node->logfile); +like( + $log_contents, + qr/backend\[$pid1\].*FATAL:.*session credentials have expired/, + 'cert session terminated after the client certificate expired'); + +# The DETAIL line (server log only, never sent to the client) should name +# the exact user and reason, so an admin doesn't have to guess which +# session/user this PID belonged to or which validator rejected it. +like( + $log_contents, + qr/backend\[$pid1\].*DETAIL:.*client certificate check failed for user "ssltestuser": certificate has expired/, + 'server log DETAIL identifies the user and the certificate-expiry reason'); + +eval { $session1->quit; }; + +############################################################################# +# Test 2 checks +############################################################################# +eval { $session2->query('SELECT 2 AS failure_expected;'); }; + +$log_contents = slurp_file($node->logfile); +like( + $log_contents, + qr/backend\[$pid2\].*FATAL:.*session credentials have expired/, + '2FA session terminated after the client certificate expired, despite scram-sha-256 being the primary auth method' +); +like( + $log_contents, + qr/backend\[$pid2\].*DETAIL:.*client certificate check failed for user "ssltestuser": certificate has expired/, + 'server log DETAIL identifies the certificate-expiry reason, even though scram-sha-256 was the primary auth method' +); + +eval { $session2->quit; }; + +############################################################################# +# Test 3 checks +############################################################################# +eval { $session3->query('SELECT 2 AS failure_expected;'); }; + +$log_contents = slurp_file($node->logfile); +like( + $log_contents, + qr/backend\[$pid3\].*FATAL:.*session credentials have expired/, + 'cert session terminated after the client certificate was revoked via CRL' +); +like( + $log_contents, + qr/backend\[$pid3\].*DETAIL:.*client certificate check failed for user "ssltestuser": certificate has been revoked/, + 'server log DETAIL distinguishes revocation from expiry'); + +eval { $session3->quit; }; + +$node->stop; +done_testing(); diff --git a/src/test/ssl/t/SSL/Backend/OpenSSL.pm b/src/test/ssl/t/SSL/Backend/OpenSSL.pm index 6060771c1a8..b52987a9c8a 100644 --- a/src/test/ssl/t/SSL/Backend/OpenSSL.pm +++ b/src/test/ssl/t/SSL/Backend/OpenSSL.pm @@ -91,7 +91,7 @@ sub init "client-der.key", "client-encrypted-pem.key", "client-encrypted-der.key", "client-dn.key", "client_ext.key", "client-long.key", - "client-revoked-utf8.key"); + "client-revoked-utf8.key", "client-midsession.key"); foreach my $keyfile (@keys) { copy("ssl/$keyfile", "$cert_tempdir/$keyfile") -- 2.52.0