From 6f74380818decd4970107d6c6fd9d539e19143e3 Mon Sep 17 00:00:00 2001 From: Ajit Awekar Date: Tue, 24 Nov 2026 12:39:35 +0530 Subject: [PATCH v4 4/5] Add GSS credential expiry to credential validation Register a CVT_GSS validator for GSSAPI/Kerberos sessions. A failed check records the user and the reason for the server log. be_gssapi_get_context_expired() calls gss_context_time() on the acceptor context kept on the Port to report whether the context lifetime has elapsed. That lifetime is fixed when the context is established and is bounded by the client's Kerberos ticket and the allowed clock skew; the server never sees the ticket again after authentication, so it is the context that is checked, not the ticket. This check is local, with no round trip to the KDC. Where MIT Kerberos is available, the KDC is also asked whether the principal is still usable, so that one disabled, expired or deleted there does not stay connected until its context runs out. No credential is sent: the check begins an initial-credentials exchange for the principal without a password or a prompter and looks only at the KDC's first answer. CLIENT_REVOKED, C_PRINCIPAL_UNKNOWN and NAME_EXP end the session. Anything else counts as valid, including a KDC that cannot be reached and a principal whose password has merely expired. That check blocks the backend, and the Kerberos library only takes its request timeout from krb5.conf, when a context is created; kdc_timeout and max_retries do not bound the wait. So credential_validation_kdc_timeout (default 5s) is written to a small temporary file that is put ahead of the real configuration through KRB5_CONFIG while the check runs. configure.ac and meson.build detect krb5.h and libkrb5 and define USE_KRB5_KDC_CHECK; configure needs to be regenerated. The KDC check is not built on Windows, nor without the MIT-only functions it relies on. Tests: kerberos/t/009_gss_continuous_validation.pl checks that an idle session is terminated once its GSS context expires, and, with the KDC check built, that sessions of a principal disabled or deleted at the KDC are terminated while another stays open, and that a KDC that does not answer leaves the session alone. PostgreSQL::Test::Kerberos gains clockskew and ticket-lifetime parameters, and prefixes its KDC files with the test script name so two scripts can share a build. --- configure.ac | 10 + doc/src/sgml/config.sgml | 47 +++- meson.build | 17 +- src/backend/libpq/auth-validate-methods.c | 50 ++++ src/backend/libpq/auth-validate.c | 2 + src/backend/libpq/auth.c | 148 +++++++++++ src/backend/libpq/be-secure-gssapi.c | 39 +++ src/backend/utils/misc/guc_parameters.dat | 10 + src/backend/utils/misc/postgresql.conf.sample | 1 + src/include/libpq/auth-validate.h | 1 + src/include/libpq/auth.h | 12 + src/include/libpq/libpq-be.h | 8 + src/include/pg_config.h.in | 4 + src/test/kerberos/meson.build | 1 + .../t/009_gss_continuous_validation.pl | 231 ++++++++++++++++++ src/test/perl/PostgreSQL/Test/Kerberos.pm | 40 ++- 16 files changed, 609 insertions(+), 12 deletions(-) create mode 100644 src/test/kerberos/t/009_gss_continuous_validation.pl diff --git a/configure.ac b/configure.ac index 18bbe596612..59262dc7744 100644 --- a/configure.ac +++ b/configure.ac @@ -1641,6 +1641,16 @@ if test "$with_gssapi" = yes ; then [AC_CHECK_HEADERS(gssapi_ext.h, [], [AC_MSG_ERROR([gssapi_ext.h header file is required for GSSAPI])])]) fi +# Credential validation can also ask the KDC whether a GSSAPI session's +# principal is still enabled. That uses the MIT Kerberos API directly, so it +# is only enabled where that library is found. +if test "$with_gssapi" = yes && test "$PORTNAME" != "win32"; then + AC_CHECK_HEADERS(krb5.h, [ + AC_SEARCH_LIBS(krb5_init_context_profile, [krb5], [ + AC_SEARCH_LIBS(krb5_get_init_creds_password, [krb5], [ + AC_DEFINE(USE_KRB5_KDC_CHECK, 1, [Define to 1 to check GSSAPI principals against the KDC during credential validation. (MIT Kerberos only)])])])]) +fi + PGAC_PATH_PROGS(OPENSSL, openssl) pgac_openssl_version="$($OPENSSL version 2> /dev/null || echo openssl not found)" AC_MSG_NOTICE([using openssl: $pgac_openssl_version]) diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 486a5db5a27..17ab48c20b4 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -1139,7 +1139,8 @@ include_dir 'conf.d' exists and has not passed its VALID UNTIL expiration; depending on the authentication method, an additional method-specific check is applied, such as expiration of an OAuth - bearer token or of the client certificate. The default is + bearer token, of the client certificate, or of the + GSSAPI security context. The default is off. @@ -1156,6 +1157,23 @@ include_dir 'conf.d' the session was established, will therefore not cause an already-open session to be terminated by this mechanism. + + For GSSAPI sessions, the check ends the session + when the lifetime of the security context set up at authentication + has elapsed. That lifetime is bounded by the client's Kerberos + ticket and the allowed clock skew; the server does not see the ticket + again after authentication, and renewing it does not extend an open + session. When PostgreSQL is built with + MIT Kerberos, the check also asks the Kerberos KDC whether the + principal is still usable, and ends the session if the KDC reports it + as disabled, expired or removed. No credential is sent for this. + The check contacts the KDC every time it runs, waiting at most + ; if the KDC + cannot be reached in that time the session is treated as valid. A + principal whose password has expired is not ended. This is not done + on Windows, and sessions that use SSPI are not + covered by the GSSAPI checks. + The re-validation period is controlled by . Validation is @@ -1209,6 +1227,33 @@ include_dir 'conf.d' + + credential_validation_kdc_timeout (integer) + + credential_validation_kdc_timeout configuration parameter + + + + + + Sets how long, for GSSAPI sessions, a credential + re-validation waits on the Kerberos KDC when it checks that the + session's principal is still usable. The limit applies to the whole + request, which the Kerberos library would otherwise keep retrying for + a long time. If the KDC does not answer in time the check is treated + as passed and the session is left open. If this value is specified + without units, it is taken as seconds. The valid range is from 1 + second to 60 seconds, and the default is 5 seconds. It has an effect + only when PostgreSQL was built with MIT + Kerberos support for this check. + + + Like , this + parameter can only be set at session start and cannot be changed + within a session. + + + password_encryption (enum) diff --git a/meson.build b/meson.build index 3238c849e1b..106e9fcca1b 100644 --- a/meson.build +++ b/meson.build @@ -813,7 +813,22 @@ if not gssapiopt.disabled() args: test_c_args, include_directories: postgres_inc) cdata.set('ENABLE_GSS', 1) - krb_srvtab = 'FILE:/@0@/krb5.keytab)'.format(get_option('sysconfdir')) + # Credential validation can also ask the KDC whether a session's principal + # is still enabled, using the MIT Kerberos API directly. The krb5-gssapi + # dependency above does not link libkrb5, so look it up separately. + krb5_kdc_dep = dependency('krb5', required: false) + if host_system != 'windows' and krb5_kdc_dep.found() and cc.check_header( + 'krb5.h', dependencies: [krb5_kdc_dep], required: false, + args: test_c_args, include_directories: postgres_inc) and cc.has_function( + 'krb5_init_context_profile', dependencies: [krb5_kdc_dep], + args: test_c_args, include_directories: postgres_inc) and cc.has_function( + 'krb5_get_init_creds_password', dependencies: [krb5_kdc_dep], + args: test_c_args, include_directories: postgres_inc) + cdata.set('USE_KRB5_KDC_CHECK', 1) + backend_deps += krb5_kdc_dep + endif + + krb_srvtab ='FILE:/@0@/krb5.keytab)'.format(get_option('sysconfdir')) cdata.set_quoted('PG_KRB_SRVTAB', krb_srvtab) elif gssapiopt.enabled() error('''could not find function 'gss_store_cred_into' required for GSSAPI''') diff --git a/src/backend/libpq/auth-validate-methods.c b/src/backend/libpq/auth-validate-methods.c index 9940ba314fe..fb09c29d0f6 100644 --- a/src/backend/libpq/auth-validate-methods.c +++ b/src/backend/libpq/auth-validate-methods.c @@ -21,6 +21,7 @@ #include "catalog/pg_authid.h" #include "libpq/auth-validate-methods.h" #include "libpq/auth-validate.h" +#include "libpq/auth.h" #include "libpq/libpq-be.h" #include "libpq/oauth.h" #include "miscadmin.h" @@ -30,6 +31,7 @@ /* Function declarations for internal use */ static bool validate_oauth_credentials(void); static bool validate_cert_credentials(void); +static bool validate_gss_credentials(void); /* * Initialize validation methods @@ -43,6 +45,7 @@ InitializeValidationMethods(void) */ RegisterCredentialValidator(CVT_OAUTH, validate_oauth_credentials); RegisterCredentialValidator(CVT_CERT, validate_cert_credentials); + RegisterCredentialValidator(CVT_GSS, validate_gss_credentials); } /* @@ -144,3 +147,50 @@ validate_cert_credentials(void) return true; } + +/* + * CVT_GSS validator: the GSS security context established at authentication + * has a lifetime that is fixed when the context is set up. It is bounded by + * the lifetime of the Kerberos ticket the client presented and by the allowed + * clock skew. The server never sees the ticket again after authentication, + * so it is the context that is checked, not the ticket. Once that lifetime + * has elapsed the credential that authenticated the session is no longer + * valid. This is checked locally from the context retained on the Port, with + * no round trip to the KDC. A session without a GSS context is treated as + * valid: there is nothing GSS-specific to check. + * + * Where MIT Kerberos is available the KDC is then also asked whether the + * principal is still enabled (see CheckKerberosPrincipalEnabled()), which + * does make a round trip, bounded by credential_validation_kdc_timeout. + */ +static bool +validate_gss_credentials(void) +{ +#ifdef ENABLE_GSS + Port *port = MyProcPort; + + if (port == NULL) + return true; + + if (be_gssapi_get_context_expired(port)) + { + SetCredentialValidationFailureDetail("GSSAPI check failed for user \"%s\": security context has expired", + port->user_name); + return false; + } + + /* The principal may also have been disabled or removed at the KDC */ + { + char reason[256]; + + if (!CheckKerberosPrincipalEnabled(port, reason, sizeof(reason))) + { + SetCredentialValidationFailureDetail("GSSAPI check failed for user \"%s\": the KDC no longer accepts the Kerberos principal (%s)", + port->user_name, reason); + return false; + } + } +#endif + + return true; +} diff --git a/src/backend/libpq/auth-validate.c b/src/backend/libpq/auth-validate.c index 264ef9a438f..f39f7e918d1 100644 --- a/src/backend/libpq/auth-validate.c +++ b/src/backend/libpq/auth-validate.c @@ -74,6 +74,8 @@ UserAuthToValidationType(UserAuth auth_method) return CVT_OAUTH; case uaCert: return CVT_CERT; + case uaGSS: + return CVT_GSS; default: /* diff --git a/src/backend/libpq/auth.c b/src/backend/libpq/auth.c index d84e35e8955..16cf3c93067 100644 --- a/src/backend/libpq/auth.c +++ b/src/backend/libpq/auth.c @@ -176,6 +176,7 @@ static int CheckCertAuth(Port *port); char *pg_krb_server_keyfile; bool pg_krb_caseins_users; bool pg_gss_accept_delegation; +int credential_validation_kdc_timeout; /*---------------------------------------------------------------- @@ -184,6 +185,11 @@ bool pg_gss_accept_delegation; */ #ifdef ENABLE_GSS #include "libpq/be-gssapi-common.h" +#ifdef USE_KRB5_KDC_CHECK +#include +#include "storage/fd.h" +#include "utils/wait_event.h" +#endif static int pg_GSS_checkauth(Port *port); static int pg_GSS_recvauth(Port *port); @@ -1209,6 +1215,148 @@ pg_GSS_checkauth(Port *port) return ret; } + +#ifdef USE_KRB5_KDC_CHECK + +/* + * The MIT Kerberos library takes its request timeout from krb5.conf, not from + * its API, and only reads it when a context is created. So the limit given by + * credential_validation_kdc_timeout is written to a small file of our own, + * which is put in front of the real configuration through KRB5_CONFIG for the + * duration of the check. + */ +static File kdc_timeout_conf_file; +static bool kdc_timeout_conf_ready = false; + +static const char * +kdc_timeout_conf_path(void) +{ + char buf[64]; + int len; + const char *path; + + if (kdc_timeout_conf_ready) + return FilePathName(kdc_timeout_conf_file); + + kdc_timeout_conf_file = OpenTemporaryFile(true); + len = snprintf(buf, sizeof(buf), + "[libdefaults]\n request_timeout = %ds\n", + credential_validation_kdc_timeout); + if (FileWrite(kdc_timeout_conf_file, buf, len, 0, + WAIT_EVENT_BUFFILE_WRITE) != len) + { + FileClose(kdc_timeout_conf_file); + return NULL; + } + + kdc_timeout_conf_ready = true; + path = FilePathName(kdc_timeout_conf_file); + + /* KRB5_CONFIG is a colon-separated list, so the path must not contain one */ + if (strchr(path, ':') != NULL) + return NULL; + return path; +} +#endif /* USE_KRB5_KDC_CHECK */ + +/* + * Ask the KDC whether the Kerberos principal this session authenticated as is + * still usable, for continuous credential validation. + * + * No credential is sent. We begin an initial-credentials exchange for the + * principal without a password or a prompter and look only at the KDC's first + * answer: a principal that has been disabled, deleted or has expired is + * refused outright, while an enabled one is merely asked for a password, which + * we cannot give, so the exchange stops locally. Returns false, and a + * description of the KDC's answer in reason, only in the former case. + * Everything else, including not being able to reach the KDC within + * credential_validation_kdc_timeout, counts as still valid. + * + * This is only built with MIT Kerberos; elsewhere it always reports the + * principal as valid. + */ +bool +CheckKerberosPrincipalEnabled(Port *port, char *reason, size_t reasonlen) +{ +#ifdef USE_KRB5_KDC_CHECK + krb5_context kctx; + krb5_principal client; + krb5_get_init_creds_opt *opt; + krb5_creds creds; + krb5_error_code ret; + const char *conf; + const char *orig; + char *saved = NULL; + char *combined; + bool result = true; + + if (port == NULL || port->gss == NULL || port->gss->princ == NULL) + return true; + + conf = kdc_timeout_conf_path(); + if (conf == NULL) + return true; + + /* + * Build everything that can fail on memory before touching the + * environment + */ + orig = getenv("KRB5_CONFIG"); + if (orig != NULL) + saved = pstrdup(orig); + combined = psprintf("%s:%s", conf, + (orig != NULL && orig[0] != '\0') ? orig : "/etc/krb5.conf"); + + setenv("KRB5_CONFIG", combined, 1); + ret = krb5_init_context(&kctx); + if (saved != NULL) + setenv("KRB5_CONFIG", saved, 1); + else + unsetenv("KRB5_CONFIG"); + pfree(combined); + if (saved != NULL) + pfree(saved); + + if (ret != 0) + return true; + + if (krb5_parse_name(kctx, port->gss->princ, &client) == 0) + { + if (krb5_get_init_creds_opt_alloc(kctx, &opt) == 0) + { + memset(&creds, 0, sizeof(creds)); + ret = krb5_get_init_creds_password(kctx, &creds, client, NULL, + NULL, NULL, 0, NULL, opt); + + if (ret == KRB5KDC_ERR_CLIENT_REVOKED || + ret == KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN || + ret == KRB5KDC_ERR_NAME_EXP) + { + const char *msg = krb5_get_error_message(kctx, ret); + + strlcpy(reason, msg, reasonlen); + krb5_free_error_message(kctx, msg); + result = false; + } + else if (ret == KRB5_KDC_UNREACH) + { + ereport(LOG, + (errmsg("could not reach the Kerberos KDC for credential validation of principal \"%s\"", + port->gss->princ))); + } + + krb5_free_cred_contents(kctx, &creds); + krb5_get_init_creds_opt_free(kctx, opt); + } + krb5_free_principal(kctx, client); + } + krb5_free_context(kctx); + + return result; +#else + return true; +#endif +} #endif /* ENABLE_GSS */ diff --git a/src/backend/libpq/be-secure-gssapi.c b/src/backend/libpq/be-secure-gssapi.c index eb841cb0c96..c9cc35ed15f 100644 --- a/src/backend/libpq/be-secure-gssapi.c +++ b/src/backend/libpq/be-secure-gssapi.c @@ -788,3 +788,42 @@ be_gssapi_get_delegation(Port *port) return port->gss->delegated_creds; } + +/* + * Report whether the GSSAPI security context established at authentication + * time has passed its expiration. + * + * The lifetime of the GSS context is fixed when it is established, and is + * bounded by the lifetime of the Kerberos ticket the client presented at + * connection time and by the allowed clock skew. The server does not have the + * ticket after authentication, so this checks the context, not the ticket. + * gss_context_time() reports how many seconds the context will remain valid; + * once that reaches zero (or the call reports GSS_S_CONTEXT_EXPIRED) the + * credential that authenticated this session has expired. This is a purely + * local check and involves no round-trip to the KDC. + * + * Returns true if a context is present and has expired, false otherwise. If + * no GSS context is present, or the lifetime cannot be read, the session is + * conservatively treated as not expired so that callers do not terminate it on + * the basis of missing or unreadable state. + */ +bool +be_gssapi_get_context_expired(Port *port) +{ + OM_uint32 major, + minor, + lifetime; + + if (!port || !port->gss || port->gss->ctx == GSS_C_NO_CONTEXT) + return false; + + major = gss_context_time(&minor, port->gss->ctx, &lifetime); + + if (major == GSS_S_CONTEXT_EXPIRED) + return true; + + if (GSS_ERROR(major)) + return false; + + return (lifetime == 0); +} diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat index dc9b02dc4c1..ed352a4f49a 100644 --- a/src/backend/utils/misc/guc_parameters.dat +++ b/src/backend/utils/misc/guc_parameters.dat @@ -587,6 +587,16 @@ max => '3600', }, +{ name => 'credential_validation_kdc_timeout', type => 'int', context => 'PGC_SU_BACKEND', group => 'CONN_AUTH_AUTH', + short_desc => 'Sets the maximum time in seconds that GSSAPI credential validation waits on the KDC.', + long_desc => 'Applies to the whole request to the Kerberos KDC.', + flags => 'GUC_UNIT_S', + variable => 'credential_validation_kdc_timeout', + boot_val => '5', + min => '1', + max => '60', +}, + { name => 'cursor_tuple_fraction', type => 'real', context => 'PGC_USERSET', group => 'QUERY_TUNING_OTHER', short_desc => 'Sets the planner\'s estimate of the fraction of a cursor\'s rows that will be retrieved.', flags => 'GUC_EXPLAIN', diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample index 5867c28f8e4..b7f7c86b954 100644 --- a/src/backend/utils/misc/postgresql.conf.sample +++ b/src/backend/utils/misc/postgresql.conf.sample @@ -935,6 +935,7 @@ #credential_validation_enabled = off # re-validate session credentials periodically #credential_validation_interval = 60 # revalidation interval in seconds (5-3600) +#credential_validation_kdc_timeout = 5 # max wait on the Kerberos KDC, in seconds (1-60) #------------------------------------------------------------------------------ # CUSTOMIZED OPTIONS diff --git a/src/include/libpq/auth-validate.h b/src/include/libpq/auth-validate.h index ed0b69e1eab..20944741441 100644 --- a/src/include/libpq/auth-validate.h +++ b/src/include/libpq/auth-validate.h @@ -24,6 +24,7 @@ typedef enum CredentialValidationType { CVT_OAUTH = 0, /* OAuth bearer token authentication */ CVT_CERT, /* TLS client certificate authentication */ + CVT_GSS, /* GSSAPI/Kerberos authentication */ CVT_COUNT /* Total number of credential validation types */ } CredentialValidationType; diff --git a/src/include/libpq/auth.h b/src/include/libpq/auth.h index be23c4ca3e4..c8de59b9c31 100644 --- a/src/include/libpq/auth.h +++ b/src/include/libpq/auth.h @@ -35,6 +35,7 @@ extern PGDLLIMPORT char *pg_krb_server_keyfile; extern PGDLLIMPORT bool pg_krb_caseins_users; extern PGDLLIMPORT bool pg_gss_accept_delegation; +extern PGDLLIMPORT int credential_validation_kdc_timeout; extern void ClientAuthentication(Port *port); extern void sendAuthRequest(Port *port, AuthRequest areq, const void *extradata, @@ -51,4 +52,15 @@ typedef char *(*auth_password_hook_typ) (char *input); /* Default LDAP password mutator hook, can be overridden by a shared library */ extern PGDLLIMPORT auth_password_hook_typ ldap_password_hook; +#ifdef ENABLE_GSS +/* + * Ask the KDC whether a GSSAPI session's Kerberos principal is still enabled, + * for continuous credential validation. Returns false, with a description in + * reason, only if the KDC refuses the principal; any other outcome, including + * not reaching the KDC in time, counts as valid. Always true unless built + * with USE_KRB5_KDC_CHECK. + */ +extern bool CheckKerberosPrincipalEnabled(Port *port, char *reason, size_t reasonlen); +#endif + #endif /* AUTH_H */ diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h index 9fdb20241a4..9b4b7e36384 100644 --- a/src/include/libpq/libpq-be.h +++ b/src/include/libpq/libpq-be.h @@ -369,6 +369,14 @@ extern bool be_gssapi_get_enc(Port *port); extern const char *be_gssapi_get_princ(Port *port); extern bool be_gssapi_get_delegation(Port *port); +/* + * Report whether the GSSAPI security context established at authentication + * time has passed its expiration (bounded by the client's Kerberos ticket + * lifetime and the allowed clock skew). Returns false when no GSS context is + * present. + */ +extern bool be_gssapi_get_context_expired(Port *port); + /* Read and write to a GSSAPI-encrypted connection. */ extern ssize_t be_gssapi_read(Port *port, void *ptr, size_t len); extern ssize_t be_gssapi_write(Port *port, const void *ptr, size_t len); diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in index 2e5ed6f5693..f86cc981e3a 100644 --- a/src/include/pg_config.h.in +++ b/src/include/pg_config.h.in @@ -695,6 +695,10 @@ /* Define to 1 to build with injection points. (--enable-injection-points) */ #undef USE_INJECTION_POINTS +/* Define to 1 to check GSSAPI principals against the KDC during credential + validation. (MIT Kerberos only) */ +#undef USE_KRB5_KDC_CHECK + /* Define to 1 to build with LDAP support. (--with-ldap) */ #undef USE_LDAP diff --git a/src/test/kerberos/meson.build b/src/test/kerberos/meson.build index 11aa732e69b..7d063956205 100644 --- a/src/test/kerberos/meson.build +++ b/src/test/kerberos/meson.build @@ -8,6 +8,7 @@ tests += { 'test_kwargs': {'priority': 40}, # kerberos tests are slow, start early 'tests': [ 't/001_auth.pl', + 't/009_gss_continuous_validation.pl', ], 'env': { 'with_gssapi': gssapi.found() ? 'yes' : 'no', diff --git a/src/test/kerberos/t/009_gss_continuous_validation.pl b/src/test/kerberos/t/009_gss_continuous_validation.pl new file mode 100644 index 00000000000..4ca5c53a138 --- /dev/null +++ b/src/test/kerberos/t/009_gss_continuous_validation.pl @@ -0,0 +1,231 @@ + +# Copyright (c) 2021-2026, PostgreSQL Global Development Group + +# Test continuous credential validation for GSSAPI/Kerberos sessions. +# +# A session authenticated with GSSAPI keeps running independently of the +# Kerberos ticket that established it; nothing re-checks the ticket once the +# connection is up. With credential_validation_enabled, the backend should +# periodically re-verify two things, and terminate the session when either +# fails: +# +# - the GSS security context (whose lifetime is bounded by the client's +# ticket and the allowed clock skew) has not expired; +# +# - the KDC still accepts the session's principal. This is checked without +# sending any credential, and is only built with MIT Kerberos. +# +# This test sets up a KDC and opens four idle GSS sessions: +# +# - test1 has a short-lived ticket, so its context expires; +# - test2 is disabled at the KDC and test3 is deleted from it; +# - test4 is left alone. +# +# It checks that the first three are terminated, each with the matching +# reason in the server log, and that test4 is not. It then stops the KDC to +# check that a KDC that does not answer within +# credential_validation_kdc_timeout leaves the session alone. +# +# Like 001_auth.pl this requires a full MIT Kerberos installation; see the +# README for details. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Utils; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Kerberos; +use Test::More; + +if ($ENV{with_gssapi} ne 'yes') +{ + plan skip_all => 'GSSAPI/Kerberos not supported by this build'; +} +elsif (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bkerberos\b/) +{ + plan skip_all => + 'Potentially unsafe test GSSAPI/Kerberos not enabled in PG_TEST_EXTRA'; +} + +# The KDC principal check is only built where MIT Kerberos is available; the +# rest of the test does not depend on it. +my $have_kdc_check = check_pg_config('#define USE_KRB5_KDC_CHECK 1'); + +# Timing parameters. The server-side GSS (acceptor) context lifetime is not +# the client's Kerberos ticket lifetime; it is bounded by the allowable clock +# skew. We therefore configure a small clock skew and a short ticket for +# test1, so that its GSS context expires shortly after authentication. The +# validation timer (minimum interval 5s) then notices within one more +# interval; the test waits for that to show up in the server log rather than +# sleeping a fixed time. +my $validation_interval = 5; +my $clockskew = 5; +my $ticket_lifetime = '4s'; +my $kdc_timeout = 2; + +my $host = 'auth-test-localhost.postgresql.example.com'; +my $hostaddr = '127.0.0.1'; +my $realm = 'EXAMPLE.COM'; +my $password = 'secret1'; + +note "setting up Kerberos"; + +my $krb = + PostgreSQL::Test::Kerberos->new($host, $hostaddr, $realm, + clockskew => $clockskew); +$krb->create_principal($_, $password) for qw(test1 test2 test3 test4); + +note "setting up PostgreSQL instance"; + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf( + 'postgresql.conf', qq{ +listen_addresses = '$hostaddr' +krb_server_keyfile = '$krb->{keytab}' +log_connections = all +log_min_messages = debug2 +lc_messages = 'C' +credential_validation_enabled = on +credential_validation_interval = $validation_interval +credential_validation_kdc_timeout = $kdc_timeout +}); +$node->start; + +$node->safe_psql('postgres', "CREATE USER $_;") + for qw(test1 test2 test3 test4); + +unlink($node->data_dir . '/pg_hba.conf'); +$node->append_conf( + 'pg_hba.conf', + qq{ +host all all $hostaddr/32 gss include_realm=0 +}); +$node->restart; + +note "running tests"; + +# Open an idle GSS-authenticated session as $user, with a ticket of the given +# lifetime (or the default), and return it with its backend pid. +# +# Use gssencmode=disable so that GSSAPI is used only for authentication and the +# transport stays in plaintext. With GSS transport encryption the expiring +# context would break the connection at the transport layer (and trigger a +# libpq reconnect) before the backend's credential validation runs; disabling +# it isolates the behavior under test -- the server terminating the session +# because its credentials expired. Validation also runs while a session waits +# for its next command, so a session is terminated without being sent anything +# further. +sub open_session +{ + my ($user, %ticket) = @_; + + $krb->create_ticket($user, $password, %ticket); + + my $session = $node->background_psql( + 'postgres', + connstr => $node->connstr('postgres') + . " user=$user host=$host hostaddr=$hostaddr gssencmode=disable", + on_error_stop => 0); + + my ($stdout, $ret) = $session->query("SELECT 'session-live';"); + like($stdout, qr/session-live/, "$user: session is live"); + + ($stdout, $ret) = $session->query('SELECT pg_backend_pid();'); + my $pid = $1 if $stdout =~ /(\d+)/; + ok(defined $pid, "$user: got the backend pid"); + + return ($session, $pid); +} + +my ($session1, $pid1) = open_session('test1', lifetime => $ticket_lifetime); +my ($session2, $pid2) = open_session('test2'); +my ($session3, $pid3) = open_session('test3'); +my ($session4, $pid4) = open_session('test4'); + +if ($have_kdc_check) +{ + # Disable one principal and delete another at the KDC. + system_or_bail('kadmin.local', '-q', 'modprinc +disallow_all_tix test2'); + system_or_bail('kadmin.local', '-q', 'delprinc -force test3'); +} + +# Wait for the server to terminate the sessions, rather than sleeping a fixed +# time. The patterns are scoped to each backend's pid. +note + "waiting for validation to notice the expired and the removed credentials..."; +ok( $node->wait_for_log( + qr/backend\[$pid1\].*FATAL:.*session credentials have expired/), + 'session with an expired GSS context is terminated'); + +# The server log, but not the client, says which check failed and for whom. +ok( $node->log_contains( + qr/backend\[$pid1\].*DETAIL:.*GSSAPI check failed for user "test1": security context has expired/ + ), + 'server log DETAIL identifies the user and the expired GSS context'); + +# A command sent after termination must not return a result. +my ($stdout, $ret); +eval { ($stdout, $ret) = $session1->query("SELECT 'after-expiry';"); }; +unlike($stdout // '', + qr/after-expiry/, 'command after expiry does not return a result'); +eval { $session1->quit; }; + +if ($have_kdc_check) +{ + ok( $node->wait_for_log( + qr/backend\[$pid2\].*FATAL:.*session credentials have expired/), + 'session of the disabled principal is terminated'); + ok( $node->wait_for_log( + qr/backend\[$pid3\].*FATAL:.*session credentials have expired/), + 'session of the deleted principal is terminated'); + + ok( $node->log_contains( + qr/backend\[$pid2\].*DETAIL:.*GSSAPI check failed for user "test2": the KDC no longer accepts the Kerberos principal \(Client's credentials have been revoked\)/ + ), + 'log DETAIL names the user and says the principal is disabled'); + ok( $node->log_contains( + qr/backend\[$pid3\].*DETAIL:.*GSSAPI check failed for user "test3": the KDC no longer accepts the Kerberos principal \(Client 'test3\@EXAMPLE.COM' not found in Kerberos database\)/ + ), + 'log DETAIL names the user and says the principal no longer exists'); +} + +# The untouched principal is still enabled, so its session must have survived +# all of those checks. +($stdout, $ret) = $session4->query("SELECT 'still-here';"); +like($stdout, qr/still-here/, + 'session of the untouched principal is still open'); + +if ($have_kdc_check) +{ + # A KDC that does not answer must not end the session, and must not hold + # the backend for longer than credential_validation_kdc_timeout. A + # stopped KDC keeps its sockets but never replies. + my $kdc_pid = slurp_file($PostgreSQL::Test::Kerberos::kdc_pidfile); + chomp $kdc_pid; + my $log_offset = -s $node->logfile; + kill 'STOP', $kdc_pid; + + note "waiting for validation to give up on the stopped KDC..."; + ok( $node->wait_for_log( + qr/backend\[$pid4\].*LOG:.*could not reach the Kerberos KDC for credential validation of principal "test4\@EXAMPLE.COM"/, + $log_offset), + 'an unreachable KDC is logged'); + + kill 'CONT', $kdc_pid; + + ($stdout, $ret) = $session4->query("SELECT 'survived-kdc-outage';"); + like($stdout, qr/survived-kdc-outage/, + 'session stays open when the KDC does not answer'); +} + +eval { $session4->quit; }; +eval { $session2->quit; }; +eval { $session3->quit; }; + +# The sessions must have actually authenticated via GSS for this to be a +# meaningful test of GSS credential validation. +ok( $node->log_contains( + qq{connection authenticated: identity="test1\@$realm" method=gss}), + 'session was authenticated with GSS'); + +done_testing(); diff --git a/src/test/perl/PostgreSQL/Test/Kerberos.pm b/src/test/perl/PostgreSQL/Test/Kerberos.pm index e861d93533e..39de8f918b8 100644 --- a/src/test/perl/PostgreSQL/Test/Kerberos.pm +++ b/src/test/perl/PostgreSQL/Test/Kerberos.pm @@ -8,6 +8,7 @@ package PostgreSQL::Test::Kerberos; use strict; use warnings FATAL => 'all'; +use File::Basename; use PostgreSQL::Test::Utils; use Test::More; @@ -62,15 +63,22 @@ INIT $krb5kdc = $krb5_sbin_dir . '/' . $krb5kdc; } - $krb5_conf = "${PostgreSQL::Test::Utils::tmp_check}/krb5.conf"; - $kdc_conf = "${PostgreSQL::Test::Utils::tmp_check}/kdc.conf"; - $krb5_cache = "${PostgreSQL::Test::Utils::tmp_check}/krb5cc"; - $krb5_log = "${PostgreSQL::Test::Utils::log_path}/krb5libs.log"; - $kdc_log = "${PostgreSQL::Test::Utils::log_path}/krb5kdc.log"; + # Derive a per-test prefix from the running script's name so that the KDC + # files, which live in the shared tmp_check/log directories, do not collide + # when more than one Kerberos test script is run in the same build (each + # script sets up its own KDC). This mirrors how Cluster.pm namespaces node + # data directories. + my $prefix = basename($0); + + $krb5_conf = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_krb5.conf"; + $kdc_conf = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_kdc.conf"; + $krb5_cache = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_krb5cc"; + $krb5_log = "${PostgreSQL::Test::Utils::log_path}/${prefix}_krb5libs.log"; + $kdc_log = "${PostgreSQL::Test::Utils::log_path}/${prefix}_krb5kdc.log"; $kdc_port = PostgreSQL::Test::Cluster::get_free_port(); - $kdc_datadir = "${PostgreSQL::Test::Utils::tmp_check}/krb5kdc"; - $kdc_pidfile = "${PostgreSQL::Test::Utils::tmp_check}/krb5kdc.pid"; - $keytab = "${PostgreSQL::Test::Utils::tmp_check}/krb5.keytab"; + $kdc_datadir = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_krb5kdc"; + $kdc_pidfile = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_krb5kdc.pid"; + $keytab = "${PostgreSQL::Test::Utils::tmp_check}/${prefix}_krb5.keytab"; } =pod @@ -102,7 +110,13 @@ Name of the Kerberos realm. sub new { my $class = shift; - my ($host, $hostaddr, $realm) = @_; + my ($host, $hostaddr, $realm, %params) = @_; + + # Optionally override the allowable clock skew. The acceptor's GSS context + # lifetime is bounded by this value, so tests that need a GSS context to + # expire quickly can set a small clock skew. + my $clockskew_line = + defined $params{clockskew} ? "clockskew = $params{clockskew}\n" : ""; my ($stdout, $krb5_version); run_log [ $krb5_config, '--version' ], '>' => \$stdout @@ -140,7 +154,8 @@ dns_lookup_kdc = false default_realm = $realm forwardable = false rdns = false - +dns_canonicalize_hostname = false +$clockskew_line [realms] $realm = { kdc = $hostaddr:$kdc_port @@ -222,6 +237,11 @@ sub create_ticket push @cmd, '-f' if ($params{forwardable}); + # Request a specific ticket lifetime (e.g. '10s') when asked. This is + # used to test behavior that depends on credentials expiring, such as + # continuous credential validation. + push @cmd, ('-l', $params{lifetime}) if (defined $params{lifetime}); + run_log [@cmd], \$password or BAIL_OUT($?); run_log [ $klist, '-f' ] or BAIL_OUT($?); } -- 2.52.0