From f8d8581ed882b79b512daaa7f71ca19c8eafcaef Mon Sep 17 00:00:00 2001 From: Daniel Gustafsson Date: Fri, 31 Jan 2025 15:47:28 +0100 Subject: require_auth: prepare for multiple SASL mechanisms Prior to this patch, the require_auth implementation assumed that the AuthenticationSASL protocol message was using SCRAM-SHA-256. In preparation for future SASL mechanisms, like OAUTHBEARER, split the implementation into two tiers: the first checks the acceptable AUTH_REQ_* codes, and the second checks acceptable mechanisms if AUTH_REQ_SASL et.al are permitted. conn->allowed_sasl_mechs contains a list of pointers to acceptable mechanisms, and pg_SASL_init() will bail if the selected mechanism isn't contained in this array. Since there's only one mechansism supported right now, one branch of the second tier cannot be exercised yet and is protected by an Assert(false) call. This assertion will need to be removed when the next mechanism is added. This patch is extracted from a larger body of work aimed at adding support for OAUTHBEARER in libpq. Author: Jacob Champion Reviewed-by: Daniel Gustafsson Reviewed-by: Peter Eisentraut Discussion: https://postgr.es/m/CAOYmi+kJqzo6XsR9TEhvVfeVNQ-TyFM5LATypm9yoQVYk=4Wrw@mail.gmail.com --- src/interfaces/libpq/fe-auth.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'src/interfaces/libpq/fe-auth.c') diff --git a/src/interfaces/libpq/fe-auth.c b/src/interfaces/libpq/fe-auth.c index 7e478489b71..70753d8ec29 100644 --- a/src/interfaces/libpq/fe-auth.c +++ b/src/interfaces/libpq/fe-auth.c @@ -543,6 +543,35 @@ pg_SASL_init(PGconn *conn, int payloadlen) goto error; } + /* Make sure require_auth is satisfied. */ + if (conn->require_auth) + { + bool allowed = false; + + for (int i = 0; i < lengthof(conn->allowed_sasl_mechs); i++) + { + if (conn->sasl == conn->allowed_sasl_mechs[i]) + { + allowed = true; + break; + } + } + + if (!allowed) + { + /* + * TODO: this is dead code until a second SASL mechanism is added; + * the connection can't have proceeded past check_expected_areq() + * if no SASL methods are allowed. + */ + Assert(false); + + libpq_append_conn_error(conn, "authentication method requirement \"%s\" failed: server requested %s authentication", + conn->require_auth, selected_mechanism); + goto error; + } + } + if (conn->channel_binding[0] == 'r' && /* require */ strcmp(selected_mechanism, SCRAM_SHA_256_PLUS_NAME) != 0) { -- cgit v1.2.3