1 /*-------------------------------------------------------------------------
4 * Server-side implementation of the SASL SCRAM-SHA-256 mechanism.
6 * See the following RFCs for more details:
7 * - RFC 5802: https://tools.ietf.org/html/rfc5802
8 * - RFC 5803: https://tools.ietf.org/html/rfc5803
9 * - RFC 7677: https://tools.ietf.org/html/rfc7677
11 * Here are some differences:
13 * - Username from the authentication exchange is not used. The client
14 * should send an empty string as the username.
16 * - If the password isn't valid UTF-8, or contains characters prohibited
17 * by the SASLprep profile, we skip the SASLprep pre-processing and use
18 * the raw bytes in calculating the hash.
20 * - If channel binding is used, the channel binding type is always
21 * "tls-server-end-point". The spec says the default is "tls-unique"
22 * (RFC 5802, section 6.1. Default Channel Binding), but there are some
23 * problems with that. Firstly, not all SSL libraries provide an API to
24 * get the TLS Finished message, required to use "tls-unique". Secondly,
25 * "tls-unique" is not specified for TLS v1.3, and as of this writing,
26 * it's not clear if there will be a replacement. We could support both
27 * "tls-server-end-point" and "tls-unique", but for our use case,
28 * "tls-unique" doesn't really have any advantages. The main advantage
29 * of "tls-unique" would be that it works even if the server doesn't
30 * have a certificate, but PostgreSQL requires a server certificate
31 * whenever SSL is used, anyway.
34 * The password stored in pg_authid consists of the iteration count, salt,
35 * StoredKey and ServerKey.
40 * One notable difference to the SCRAM specification is that while the
41 * specification dictates that the password is in UTF-8, and prohibits
42 * certain characters, we are more lenient. If the password isn't a valid
43 * UTF-8 string, or contains prohibited characters, the raw bytes are used
44 * to calculate the hash instead, without SASLprep processing. This is
45 * because PostgreSQL supports other encodings too, and the encoding being
46 * used during authentication is undefined (client_encoding isn't set until
47 * after authentication). In effect, we try to interpret the password as
48 * UTF-8 and apply SASLprep processing, but if it looks invalid, we assume
49 * that it's in some other encoding.
51 * In the worst case, we misinterpret a password that's in a different
52 * encoding as being Unicode, because it happens to consists entirely of
53 * valid UTF-8 bytes, and we apply Unicode normalization to it. As long
54 * as we do that consistently, that will not lead to failed logins.
55 * Fortunately, the UTF-8 byte sequences that are ignored by SASLprep
56 * don't correspond to any commonly used characters in any of the other
57 * supported encodings, so it should not lead to any significant loss in
58 * entropy, even if the normalization is incorrectly applied to a
64 * Don't reveal user information to an unauthenticated client. We don't
65 * want an attacker to be able to probe whether a particular username is
66 * valid. In SCRAM, the server has to read the salt and iteration count
67 * from the user's password verifier, and send it to the client. To avoid
68 * revealing whether a user exists, when the client tries to authenticate
69 * with a username that doesn't exist, or doesn't have a valid SCRAM
70 * verifier in pg_authid, we create a fake salt and iteration count
71 * on-the-fly, and proceed with the authentication with that. In the end,
72 * we'll reject the attempt, as if an incorrect password was given. When
73 * we are performing a "mock" authentication, the 'doomed' flag in
76 * In the error messages, avoid printing strings from the client, unless
77 * you check that they are pure ASCII. We don't want an unauthenticated
78 * attacker to be able to spam the logs with characters that are not valid
79 * to the encoding being used, whatever that is. We cannot avoid that in
80 * general, after logging in, but let's do what we can here.
83 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
84 * Portions Copyright (c) 1994, Regents of the University of California
86 * src/backend/libpq/auth-scram.c
88 *-------------------------------------------------------------------------
94 #include "access/xlog.h"
95 #include "catalog/pg_authid.h"
96 #include "catalog/pg_control.h"
97 #include "common/base64.h"
98 #include "common/saslprep.h"
99 #include "common/scram-common.h"
100 #include "common/sha2.h"
101 #include "libpq/auth.h"
102 #include "libpq/crypt.h"
103 #include "libpq/scram.h"
104 #include "miscadmin.h"
105 #include "utils/builtins.h"
106 #include "utils/timestamp.h"
109 * Status data for a SCRAM authentication exchange. This should be kept
110 * internal to this file.
115 SCRAM_AUTH_SALT_SENT,
121 scram_state_enum state;
123 const char *username; /* username from startup packet */
126 bool channel_binding_in_use;
129 char *salt; /* base64-encoded */
130 uint8 StoredKey[SCRAM_KEY_LEN];
131 uint8 ServerKey[SCRAM_KEY_LEN];
133 /* Fields of the first message from client */
135 char *client_first_message_bare;
136 char *client_username;
139 /* Fields from the last message from client */
140 char *client_final_message_without_proof;
141 char *client_final_nonce;
142 char ClientProof[SCRAM_KEY_LEN];
144 /* Fields generated in the server */
145 char *server_first_message;
149 * If something goes wrong during the authentication, or we are performing
150 * a "mock" authentication (see comments at top of file), the 'doomed'
151 * flag is set. A reason for the failure, for the server log, is put in
158 static void read_client_first_message(scram_state *state, char *input);
159 static void read_client_final_message(scram_state *state, char *input);
160 static char *build_server_first_message(scram_state *state);
161 static char *build_server_final_message(scram_state *state);
162 static bool verify_client_proof(scram_state *state);
163 static bool verify_final_nonce(scram_state *state);
164 static bool parse_scram_verifier(const char *verifier, int *iterations,
165 char **salt, uint8 *stored_key, uint8 *server_key);
166 static void mock_scram_verifier(const char *username, int *iterations,
167 char **salt, uint8 *stored_key, uint8 *server_key);
168 static bool is_scram_printable(char *p);
169 static char *sanitize_char(char c);
170 static char *sanitize_str(const char *s);
171 static char *scram_mock_salt(const char *username);
174 * pg_be_scram_get_mechanisms
176 * Get a list of SASL mechanisms that this module supports.
178 * For the convenience of building the FE/BE packet that lists the
179 * mechanisms, the names are appended to the given StringInfo buffer,
180 * separated by '\0' bytes.
183 pg_be_scram_get_mechanisms(Port *port, StringInfo buf)
186 * Advertise the mechanisms in decreasing order of importance. So the
187 * channel-binding variants go first, if they are supported. Channel
188 * binding is only supported with SSL, and only if the SSL implementation
189 * has a function to get the certificate's hash.
191 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
192 if (port->ssl_in_use)
194 appendStringInfoString(buf, SCRAM_SHA_256_PLUS_NAME);
195 appendStringInfoChar(buf, '\0');
198 appendStringInfoString(buf, SCRAM_SHA_256_NAME);
199 appendStringInfoChar(buf, '\0');
205 * Initialize a new SCRAM authentication exchange status tracker. This
206 * needs to be called before doing any exchange. It will be filled later
207 * after the beginning of the exchange with verifier data.
209 * 'selected_mech' identifies the SASL mechanism that the client selected.
210 * It should be one of the mechanisms that we support, as returned by
211 * pg_be_scram_get_mechanisms().
213 * 'shadow_pass' is the role's password verifier, from pg_authid.rolpassword.
214 * The username was provided by the client in the startup message, and is
215 * available in port->user_name. If 'shadow_pass' is NULL, we still perform
216 * an authentication exchange, but it will fail, as if an incorrect password
220 pg_be_scram_init(Port *port,
221 const char *selected_mech,
222 const char *shadow_pass)
227 state = (scram_state *) palloc0(sizeof(scram_state));
229 state->state = SCRAM_AUTH_INIT;
232 * Parse the selected mechanism.
234 * Note that if we don't support channel binding, either because the SSL
235 * implementation doesn't support it or we're not using SSL at all, we
236 * would not have advertised the PLUS variant in the first place. If the
237 * client nevertheless tries to select it, it's a protocol violation like
238 * selecting any other SASL mechanism we don't support.
240 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
241 if (strcmp(selected_mech, SCRAM_SHA_256_PLUS_NAME) == 0 && port->ssl_in_use)
242 state->channel_binding_in_use = true;
245 if (strcmp(selected_mech, SCRAM_SHA_256_NAME) == 0)
246 state->channel_binding_in_use = false;
249 (errcode(ERRCODE_PROTOCOL_VIOLATION),
250 errmsg("client selected an invalid SASL authentication mechanism")));
253 * Parse the stored password verifier.
257 int password_type = get_password_type(shadow_pass);
259 if (password_type == PASSWORD_TYPE_SCRAM_SHA_256)
261 if (parse_scram_verifier(shadow_pass, &state->iterations, &state->salt,
262 state->StoredKey, state->ServerKey))
267 * The password looked like a SCRAM verifier, but could not be
271 (errmsg("invalid SCRAM verifier for user \"%s\"",
272 state->port->user_name)));
273 got_verifier = false;
279 * The user doesn't have SCRAM verifier. (You cannot do SCRAM
280 * authentication with an MD5 hash.)
282 state->logdetail = psprintf(_("User \"%s\" does not have a valid SCRAM verifier."),
283 state->port->user_name);
284 got_verifier = false;
290 * The caller requested us to perform a dummy authentication. This is
291 * considered normal, since the caller requested it, so don't set log
294 got_verifier = false;
298 * If the user did not have a valid SCRAM verifier, we still go through
299 * the motions with a mock one, and fail as if the client supplied an
300 * incorrect password. This is to avoid revealing information to an
305 mock_scram_verifier(state->port->user_name, &state->iterations,
306 &state->salt, state->StoredKey, state->ServerKey);
307 state->doomed = true;
314 * Continue a SCRAM authentication exchange.
316 * 'input' is the SCRAM payload sent by the client. On the first call,
317 * 'input' contains the "Initial Client Response" that the client sent as
318 * part of the SASLInitialResponse message, or NULL if no Initial Client
319 * Response was given. (The SASL specification distinguishes between an
320 * empty response and non-existing one.) On subsequent calls, 'input'
321 * cannot be NULL. For convenience in this function, the caller must
322 * ensure that there is a null terminator at input[inputlen].
324 * The next message to send to client is saved in 'output', for a length
325 * of 'outputlen'. In the case of an error, optionally store a palloc'd
326 * string at *logdetail that will be sent to the postmaster log (but not
330 pg_be_scram_exchange(void *opaq, char *input, int inputlen,
331 char **output, int *outputlen, char **logdetail)
333 scram_state *state = (scram_state *) opaq;
339 * If the client didn't include an "Initial Client Response" in the
340 * SASLInitialResponse message, send an empty challenge, to which the
341 * client will respond with the same data that usually comes in the
342 * Initial Client Response.
346 Assert(state->state == SCRAM_AUTH_INIT);
348 *output = pstrdup("");
350 return SASL_EXCHANGE_CONTINUE;
354 * Check that the input length agrees with the string length of the input.
355 * We can ignore inputlen after this.
359 (errcode(ERRCODE_PROTOCOL_VIOLATION),
360 errmsg("malformed SCRAM message"),
361 errdetail("The message is empty.")));
362 if (inputlen != strlen(input))
364 (errcode(ERRCODE_PROTOCOL_VIOLATION),
365 errmsg("malformed SCRAM message"),
366 errdetail("Message length does not match input length.")));
368 switch (state->state)
370 case SCRAM_AUTH_INIT:
373 * Initialization phase. Receive the first message from client
374 * and be sure that it parsed correctly. Then send the challenge
377 read_client_first_message(state, input);
379 /* prepare message to send challenge */
380 *output = build_server_first_message(state);
382 state->state = SCRAM_AUTH_SALT_SENT;
383 result = SASL_EXCHANGE_CONTINUE;
386 case SCRAM_AUTH_SALT_SENT:
389 * Final phase for the server. Receive the response to the
390 * challenge previously sent, verify, and let the client know that
391 * everything went well (or not).
393 read_client_final_message(state, input);
395 if (!verify_final_nonce(state))
397 (errcode(ERRCODE_PROTOCOL_VIOLATION),
398 errmsg("invalid SCRAM response"),
399 errdetail("Nonce does not match.")));
402 * Now check the final nonce and the client proof.
404 * If we performed a "mock" authentication that we knew would fail
405 * from the get go, this is where we fail.
407 * The SCRAM specification includes an error code,
408 * "invalid-proof", for authentication failure, but it also allows
409 * erroring out in an application-specific way. We choose to do
410 * the latter, so that the error message for invalid password is
411 * the same for all authentication methods. The caller will call
412 * ereport(), when we return SASL_EXCHANGE_FAILURE with no output.
414 * NB: the order of these checks is intentional. We calculate the
415 * client proof even in a mock authentication, even though it's
416 * bound to fail, to thwart timing attacks to determine if a role
417 * with the given name exists or not.
419 if (!verify_client_proof(state) || state->doomed)
421 result = SASL_EXCHANGE_FAILURE;
425 /* Build final message for client */
426 *output = build_server_final_message(state);
429 result = SASL_EXCHANGE_SUCCESS;
430 state->state = SCRAM_AUTH_FINISHED;
434 elog(ERROR, "invalid SCRAM exchange state");
435 result = SASL_EXCHANGE_FAILURE;
438 if (result == SASL_EXCHANGE_FAILURE && state->logdetail && logdetail)
439 *logdetail = state->logdetail;
442 *outputlen = strlen(*output);
448 * Construct a verifier string for SCRAM, stored in pg_authid.rolpassword.
450 * The result is palloc'd, so caller is responsible for freeing it.
453 pg_be_scram_build_verifier(const char *password)
457 char saltbuf[SCRAM_DEFAULT_SALT_LEN];
461 * Normalize the password with SASLprep. If that doesn't work, because
462 * the password isn't valid UTF-8 or contains prohibited characters, just
463 * proceed with the original password. (See comments at top of file.)
465 rc = pg_saslprep(password, &prep_password);
466 if (rc == SASLPREP_SUCCESS)
467 password = (const char *) prep_password;
469 /* Generate random salt */
470 if (!pg_strong_random(saltbuf, SCRAM_DEFAULT_SALT_LEN))
472 (errcode(ERRCODE_INTERNAL_ERROR),
473 errmsg("could not generate random salt")));
475 result = scram_build_verifier(saltbuf, SCRAM_DEFAULT_SALT_LEN,
476 SCRAM_DEFAULT_ITERATIONS, password);
479 pfree(prep_password);
485 * Verify a plaintext password against a SCRAM verifier. This is used when
486 * performing plaintext password authentication for a user that has a SCRAM
487 * verifier stored in pg_authid.
490 scram_verify_plain_password(const char *username, const char *password,
491 const char *verifier)
497 uint8 salted_password[SCRAM_KEY_LEN];
498 uint8 stored_key[SCRAM_KEY_LEN];
499 uint8 server_key[SCRAM_KEY_LEN];
500 uint8 computed_key[SCRAM_KEY_LEN];
504 if (!parse_scram_verifier(verifier, &iterations, &encoded_salt,
505 stored_key, server_key))
508 * The password looked like a SCRAM verifier, but could not be parsed.
511 (errmsg("invalid SCRAM verifier for user \"%s\"", username)));
515 salt = palloc(pg_b64_dec_len(strlen(encoded_salt)));
516 saltlen = pg_b64_decode(encoded_salt, strlen(encoded_salt), salt);
520 (errmsg("invalid SCRAM verifier for user \"%s\"", username)));
524 /* Normalize the password */
525 rc = pg_saslprep(password, &prep_password);
526 if (rc == SASLPREP_SUCCESS)
527 password = prep_password;
529 /* Compute Server Key based on the user-supplied plaintext password */
530 scram_SaltedPassword(password, salt, saltlen, iterations, salted_password);
531 scram_ServerKey(salted_password, computed_key);
534 pfree(prep_password);
537 * Compare the verifier's Server Key with the one computed from the
538 * user-supplied password.
540 return memcmp(computed_key, server_key, SCRAM_KEY_LEN) == 0;
545 * Parse and validate format of given SCRAM verifier.
547 * Returns true if the SCRAM verifier has been parsed, and false otherwise.
550 parse_scram_verifier(const char *verifier, int *iterations, char **salt,
551 uint8 *stored_key, uint8 *server_key)
557 char *iterations_str;
561 char *decoded_salt_buf;
564 * The verifier is of form:
566 * SCRAM-SHA-256$<iterations>:<salt>$<storedkey>:<serverkey>
568 v = pstrdup(verifier);
569 if ((scheme_str = strtok(v, "$")) == NULL)
570 goto invalid_verifier;
571 if ((iterations_str = strtok(NULL, ":")) == NULL)
572 goto invalid_verifier;
573 if ((salt_str = strtok(NULL, "$")) == NULL)
574 goto invalid_verifier;
575 if ((storedkey_str = strtok(NULL, ":")) == NULL)
576 goto invalid_verifier;
577 if ((serverkey_str = strtok(NULL, "")) == NULL)
578 goto invalid_verifier;
580 /* Parse the fields */
581 if (strcmp(scheme_str, "SCRAM-SHA-256") != 0)
582 goto invalid_verifier;
585 *iterations = strtol(iterations_str, &p, 10);
586 if (*p || errno != 0)
587 goto invalid_verifier;
590 * Verify that the salt is in Base64-encoded format, by decoding it,
591 * although we return the encoded version to the caller.
593 decoded_salt_buf = palloc(pg_b64_dec_len(strlen(salt_str)));
594 decoded_len = pg_b64_decode(salt_str, strlen(salt_str), decoded_salt_buf);
596 goto invalid_verifier;
597 *salt = pstrdup(salt_str);
600 * Decode StoredKey and ServerKey.
602 if (pg_b64_dec_len(strlen(storedkey_str) != SCRAM_KEY_LEN))
603 goto invalid_verifier;
604 decoded_len = pg_b64_decode(storedkey_str, strlen(storedkey_str),
605 (char *) stored_key);
606 if (decoded_len != SCRAM_KEY_LEN)
607 goto invalid_verifier;
609 if (pg_b64_dec_len(strlen(serverkey_str) != SCRAM_KEY_LEN))
610 goto invalid_verifier;
611 decoded_len = pg_b64_decode(serverkey_str, strlen(serverkey_str),
612 (char *) server_key);
613 if (decoded_len != SCRAM_KEY_LEN)
614 goto invalid_verifier;
625 mock_scram_verifier(const char *username, int *iterations, char **salt,
626 uint8 *stored_key, uint8 *server_key)
632 /* Generate deterministic salt */
633 raw_salt = scram_mock_salt(username);
635 encoded_salt = (char *) palloc(pg_b64_enc_len(SCRAM_DEFAULT_SALT_LEN) + 1);
636 encoded_len = pg_b64_encode(raw_salt, SCRAM_DEFAULT_SALT_LEN, encoded_salt);
637 encoded_salt[encoded_len] = '\0';
639 *salt = encoded_salt;
640 *iterations = SCRAM_DEFAULT_ITERATIONS;
642 /* StoredKey and ServerKey are not used in a doomed authentication */
643 memset(stored_key, 0, SCRAM_KEY_LEN);
644 memset(server_key, 0, SCRAM_KEY_LEN);
648 * Read the value in a given SCRAM exchange message for given attribute.
651 read_attr_value(char **input, char attr)
653 char *begin = *input;
658 (errcode(ERRCODE_PROTOCOL_VIOLATION),
659 errmsg("malformed SCRAM message"),
660 errdetail("Expected attribute \"%c\" but found \"%s\".",
661 attr, sanitize_char(*begin))));
666 (errcode(ERRCODE_PROTOCOL_VIOLATION),
667 errmsg("malformed SCRAM message"),
668 errdetail("Expected character \"=\" for attribute \"%c\".", attr)));
672 while (*end && *end != ',')
687 is_scram_printable(char *p)
690 * Printable characters, as defined by SCRAM spec: (RFC 5802)
692 * printable = %x21-2B / %x2D-7E
693 * ;; Printable ASCII except ",".
694 * ;; Note that any "printable" is also
695 * ;; a valid "value".
700 if (*p < 0x21 || *p > 0x7E || *p == 0x2C /* comma */ )
707 * Convert an arbitrary byte to printable form. For error messages.
709 * If it's a printable ASCII character, print it as a single character.
710 * otherwise, print it in hex.
712 * The returned pointer points to a static buffer.
715 sanitize_char(char c)
719 if (c >= 0x21 && c <= 0x7E)
720 snprintf(buf, sizeof(buf), "'%c'", c);
722 snprintf(buf, sizeof(buf), "0x%02x", (unsigned char) c);
727 * Convert an arbitrary string to printable form, for error messages.
729 * Anything that's not a printable ASCII character is replaced with
730 * '?', and the string is truncated at 30 characters.
732 * The returned pointer points to a static buffer.
735 sanitize_str(const char *s)
737 static char buf[30 + 1];
740 for (i = 0; i < sizeof(buf) - 1; i++)
747 if (c >= 0x21 && c <= 0x7E)
757 * Read the next attribute and value in a SCRAM exchange message.
759 * Returns NULL if there is attribute.
762 read_any_attr(char **input, char *attr_p)
764 char *begin = *input;
769 * attr-val = ALPHA "=" value
770 * ;; Generic syntax of any attribute sent
771 * ;; by server or client
774 if (!((attr >= 'A' && attr <= 'Z') ||
775 (attr >= 'a' && attr <= 'z')))
777 (errcode(ERRCODE_PROTOCOL_VIOLATION),
778 errmsg("malformed SCRAM message"),
779 errdetail("Attribute expected, but found invalid character \"%s\".",
780 sanitize_char(attr))));
787 (errcode(ERRCODE_PROTOCOL_VIOLATION),
788 errmsg("malformed SCRAM message"),
789 errdetail("Expected character \"=\" for attribute \"%c\".", attr)));
793 while (*end && *end != ',')
808 * Read and parse the first message from client in the context of a SCRAM
809 * authentication exchange message.
811 * At this stage, any errors will be reported directly with ereport(ERROR).
814 read_client_first_message(scram_state *state, char *input)
816 char *channel_binding_type;
818 input = pstrdup(input);
821 * The syntax for the client-first-message is: (RFC 5802)
823 * saslname = 1*(value-safe-char / "=2C" / "=3D")
824 * ;; Conforms to <value>.
826 * authzid = "a=" saslname
827 * ;; Protocol specific.
829 * cb-name = 1*(ALPHA / DIGIT / "." / "-")
830 * ;; See RFC 5056, Section 7.
831 * ;; E.g., "tls-server-end-point" or
834 * gs2-cbind-flag = ("p=" cb-name) / "n" / "y"
835 * ;; "n" -> client doesn't support channel binding.
836 * ;; "y" -> client does support channel binding
837 * ;; but thinks the server does not.
838 * ;; "p" -> client requires channel binding.
839 * ;; The selected channel binding follows "p=".
841 * gs2-header = gs2-cbind-flag "," [ authzid ] ","
842 * ;; GS2 header for SCRAM
843 * ;; (the actual GS2 header includes an optional
844 * ;; flag to indicate that the GSS mechanism is not
845 * ;; "standard", but since SCRAM is "standard", we
846 * ;; don't include that flag).
848 * username = "n=" saslname
849 * ;; Usernames are prepared using SASLprep.
851 * reserved-mext = "m=" 1*(value-char)
852 * ;; Reserved for signaling mandatory extensions.
853 * ;; The exact syntax will be defined in
856 * nonce = "r=" c-nonce [s-nonce]
857 * ;; Second part provided by server.
859 * c-nonce = printable
861 * client-first-message-bare =
862 * [reserved-mext ","]
863 * username "," nonce ["," extensions]
865 * client-first-message =
866 * gs2-header client-first-message-bare
869 * n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL
871 * The "n,," in the beginning means that the client doesn't support
872 * channel binding, and no authzid is given. "n=user" is the username.
873 * However, in PostgreSQL the username is sent in the startup packet, and
874 * the username in the SCRAM exchange is ignored. libpq always sends it
875 * as an empty string. The last part, "r=fyko+d2lbbFgONRv9qkxdawL" is
881 * Read gs2-cbind-flag. (For details see also RFC 5802 Section 6 "Channel
884 state->cbind_flag = *input;
890 * The client does not support channel binding or has simply
891 * decided to not use it. In that case just let it go.
893 if (state->channel_binding_in_use)
895 (errcode(ERRCODE_PROTOCOL_VIOLATION),
896 errmsg("malformed SCRAM message"),
897 errdetail("The client selected SCRAM-SHA-256-PLUS, but the SCRAM message does not include channel binding data.")));
902 (errcode(ERRCODE_PROTOCOL_VIOLATION),
903 errmsg("malformed SCRAM message"),
904 errdetail("Comma expected, but found character \"%s\".",
905 sanitize_char(*input))));
911 * The client supports channel binding and thinks that the server
912 * does not. In this case, the server must fail authentication if
913 * it supports channel binding.
915 if (state->channel_binding_in_use)
917 (errcode(ERRCODE_PROTOCOL_VIOLATION),
918 errmsg("malformed SCRAM message"),
919 errdetail("The client selected SCRAM-SHA-256-PLUS, but the SCRAM message does not include channel binding data.")));
921 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
922 if (state->port->ssl_in_use)
924 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
925 errmsg("SCRAM channel binding negotiation error"),
926 errdetail("The client supports SCRAM channel binding but thinks the server does not. "
927 "However, this server does support channel binding.")));
932 (errcode(ERRCODE_PROTOCOL_VIOLATION),
933 errmsg("malformed SCRAM message"),
934 errdetail("Comma expected, but found character \"%s\".",
935 sanitize_char(*input))));
941 * The client requires channel binding. Channel binding type
942 * follows, e.g., "p=tls-server-end-point".
944 if (!state->channel_binding_in_use)
946 (errcode(ERRCODE_PROTOCOL_VIOLATION),
947 errmsg("malformed SCRAM message"),
948 errdetail("The client selected SCRAM-SHA-256 without channel binding, but the SCRAM message includes channel binding data.")));
950 channel_binding_type = read_attr_value(&input, 'p');
953 * The only channel binding type we support is
954 * tls-server-end-point.
956 if (strcmp(channel_binding_type, "tls-server-end-point") != 0)
958 (errcode(ERRCODE_PROTOCOL_VIOLATION),
959 (errmsg("unsupported SCRAM channel-binding type \"%s\"",
960 sanitize_str(channel_binding_type)))));
964 (errcode(ERRCODE_PROTOCOL_VIOLATION),
965 errmsg("malformed SCRAM message"),
966 errdetail("Unexpected channel-binding flag \"%s\".",
967 sanitize_char(*input))));
971 * Forbid optional authzid (authorization identity). We don't support it.
975 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
976 errmsg("client uses authorization identity, but it is not supported")));
979 (errcode(ERRCODE_PROTOCOL_VIOLATION),
980 errmsg("malformed SCRAM message"),
981 errdetail("Unexpected attribute \"%s\" in client-first-message.",
982 sanitize_char(*input))));
985 state->client_first_message_bare = pstrdup(input);
988 * Any mandatory extensions would go here. We don't support any.
990 * RFC 5802 specifies error code "e=extensions-not-supported" for this,
991 * but it can only be sent in the server-final message. We prefer to fail
992 * immediately (which the RFC also allows).
996 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
997 errmsg("client requires an unsupported SCRAM extension")));
1000 * Read username. Note: this is ignored. We use the username from the
1001 * startup message instead, still it is kept around if provided as it
1002 * proves to be useful for debugging purposes.
1004 state->client_username = read_attr_value(&input, 'n');
1006 /* read nonce and check that it is made of only printable characters */
1007 state->client_nonce = read_attr_value(&input, 'r');
1008 if (!is_scram_printable(state->client_nonce))
1010 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1011 errmsg("non-printable characters in SCRAM nonce")));
1014 * There can be any number of optional extensions after this. We don't
1015 * support any extensions, so ignore them.
1017 while (*input != '\0')
1018 read_any_attr(&input, NULL);
1024 * Verify the final nonce contained in the last message received from
1025 * client in an exchange.
1028 verify_final_nonce(scram_state *state)
1030 int client_nonce_len = strlen(state->client_nonce);
1031 int server_nonce_len = strlen(state->server_nonce);
1032 int final_nonce_len = strlen(state->client_final_nonce);
1034 if (final_nonce_len != client_nonce_len + server_nonce_len)
1036 if (memcmp(state->client_final_nonce, state->client_nonce, client_nonce_len) != 0)
1038 if (memcmp(state->client_final_nonce + client_nonce_len, state->server_nonce, server_nonce_len) != 0)
1045 * Verify the client proof contained in the last message received from
1046 * client in an exchange.
1049 verify_client_proof(scram_state *state)
1051 uint8 ClientSignature[SCRAM_KEY_LEN];
1052 uint8 ClientKey[SCRAM_KEY_LEN];
1053 uint8 client_StoredKey[SCRAM_KEY_LEN];
1057 /* calculate ClientSignature */
1058 scram_HMAC_init(&ctx, state->StoredKey, SCRAM_KEY_LEN);
1059 scram_HMAC_update(&ctx,
1060 state->client_first_message_bare,
1061 strlen(state->client_first_message_bare));
1062 scram_HMAC_update(&ctx, ",", 1);
1063 scram_HMAC_update(&ctx,
1064 state->server_first_message,
1065 strlen(state->server_first_message));
1066 scram_HMAC_update(&ctx, ",", 1);
1067 scram_HMAC_update(&ctx,
1068 state->client_final_message_without_proof,
1069 strlen(state->client_final_message_without_proof));
1070 scram_HMAC_final(ClientSignature, &ctx);
1072 /* Extract the ClientKey that the client calculated from the proof */
1073 for (i = 0; i < SCRAM_KEY_LEN; i++)
1074 ClientKey[i] = state->ClientProof[i] ^ ClientSignature[i];
1076 /* Hash it one more time, and compare with StoredKey */
1077 scram_H(ClientKey, SCRAM_KEY_LEN, client_StoredKey);
1079 if (memcmp(client_StoredKey, state->StoredKey, SCRAM_KEY_LEN) != 0)
1086 * Build the first server-side message sent to the client in a SCRAM
1087 * communication exchange.
1090 build_server_first_message(scram_state *state)
1093 * The syntax for the server-first-message is: (RFC 5802)
1095 * server-first-message =
1096 * [reserved-mext ","] nonce "," salt ","
1097 * iteration-count ["," extensions]
1099 * nonce = "r=" c-nonce [s-nonce]
1100 * ;; Second part provided by server.
1102 * c-nonce = printable
1104 * s-nonce = printable
1106 * salt = "s=" base64
1108 * iteration-count = "i=" posit-number
1109 * ;; A positive number.
1113 * r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096
1118 * Per the spec, the nonce may consist of any printable ASCII characters.
1119 * For convenience, however, we don't use the whole range available,
1120 * rather, we generate some random bytes, and base64 encode them.
1122 char raw_nonce[SCRAM_RAW_NONCE_LEN];
1125 if (!pg_strong_random(raw_nonce, SCRAM_RAW_NONCE_LEN))
1127 (errcode(ERRCODE_INTERNAL_ERROR),
1128 errmsg("could not generate random nonce")));
1130 state->server_nonce = palloc(pg_b64_enc_len(SCRAM_RAW_NONCE_LEN) + 1);
1131 encoded_len = pg_b64_encode(raw_nonce, SCRAM_RAW_NONCE_LEN, state->server_nonce);
1132 state->server_nonce[encoded_len] = '\0';
1134 state->server_first_message =
1135 psprintf("r=%s%s,s=%s,i=%u",
1136 state->client_nonce, state->server_nonce,
1137 state->salt, state->iterations);
1139 return pstrdup(state->server_first_message);
1144 * Read and parse the final message received from client.
1147 read_client_final_message(scram_state *state, char *input)
1150 char *channel_binding;
1157 begin = p = pstrdup(input);
1160 * The syntax for the server-first-message is: (RFC 5802)
1162 * gs2-header = gs2-cbind-flag "," [ authzid ] ","
1163 * ;; GS2 header for SCRAM
1164 * ;; (the actual GS2 header includes an optional
1165 * ;; flag to indicate that the GSS mechanism is not
1166 * ;; "standard", but since SCRAM is "standard", we
1167 * ;; don't include that flag).
1169 * cbind-input = gs2-header [ cbind-data ]
1170 * ;; cbind-data MUST be present for
1171 * ;; gs2-cbind-flag of "p" and MUST be absent
1172 * ;; for "y" or "n".
1174 * channel-binding = "c=" base64
1175 * ;; base64 encoding of cbind-input.
1177 * proof = "p=" base64
1179 * client-final-message-without-proof =
1180 * channel-binding "," nonce [","
1183 * client-final-message =
1184 * client-final-message-without-proof "," proof
1189 * Read channel binding. This repeats the channel-binding flags and is
1190 * then followed by the actual binding data depending on the type.
1192 channel_binding = read_attr_value(&p, 'c');
1193 if (state->channel_binding_in_use)
1195 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
1196 const char *cbind_data = NULL;
1197 size_t cbind_data_len = 0;
1198 size_t cbind_header_len;
1200 size_t cbind_input_len;
1202 int b64_message_len;
1204 Assert(state->cbind_flag == 'p');
1206 /* Fetch hash data of server's SSL certificate */
1207 cbind_data = be_tls_get_certificate_hash(state->port,
1210 /* should not happen */
1211 if (cbind_data == NULL || cbind_data_len == 0)
1212 elog(ERROR, "could not get server certificate hash");
1214 cbind_header_len = strlen("p=tls-server-end-point,,"); /* p=type,, */
1215 cbind_input_len = cbind_header_len + cbind_data_len;
1216 cbind_input = palloc(cbind_input_len);
1217 snprintf(cbind_input, cbind_input_len, "p=tls-server-end-point,,");
1218 memcpy(cbind_input + cbind_header_len, cbind_data, cbind_data_len);
1220 b64_message = palloc(pg_b64_enc_len(cbind_input_len) + 1);
1221 b64_message_len = pg_b64_encode(cbind_input, cbind_input_len,
1223 b64_message[b64_message_len] = '\0';
1226 * Compare the value sent by the client with the value expected by the
1229 if (strcmp(channel_binding, b64_message) != 0)
1231 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1232 (errmsg("SCRAM channel binding check failed"))));
1234 /* shouldn't happen, because we checked this earlier already */
1235 elog(ERROR, "channel binding not supported by this build");
1241 * If we are not using channel binding, the binding data is expected
1242 * to always be "biws", which is "n,," base64-encoded, or "eSws",
1243 * which is "y,,". We also have to check whether the flag is the same
1244 * one that the client originally sent.
1246 if (!(strcmp(channel_binding, "biws") == 0 && state->cbind_flag == 'n') &&
1247 !(strcmp(channel_binding, "eSws") == 0 && state->cbind_flag == 'y'))
1249 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1250 (errmsg("unexpected SCRAM channel-binding attribute in client-final-message"))));
1253 state->client_final_nonce = read_attr_value(&p, 'r');
1255 /* ignore optional extensions */
1259 value = read_any_attr(&p, &attr);
1260 } while (attr != 'p');
1262 client_proof = palloc(pg_b64_dec_len(strlen(value)));
1263 if (pg_b64_decode(value, strlen(value), client_proof) != SCRAM_KEY_LEN)
1265 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1266 errmsg("malformed SCRAM message"),
1267 errdetail("Malformed proof in client-final-message.")));
1268 memcpy(state->ClientProof, client_proof, SCRAM_KEY_LEN);
1269 pfree(client_proof);
1273 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1274 errmsg("malformed SCRAM message"),
1275 errdetail("Garbage found at the end of client-final-message.")));
1277 state->client_final_message_without_proof = palloc(proof - begin + 1);
1278 memcpy(state->client_final_message_without_proof, input, proof - begin);
1279 state->client_final_message_without_proof[proof - begin] = '\0';
1283 * Build the final server-side message of an exchange.
1286 build_server_final_message(scram_state *state)
1288 uint8 ServerSignature[SCRAM_KEY_LEN];
1289 char *server_signature_base64;
1293 /* calculate ServerSignature */
1294 scram_HMAC_init(&ctx, state->ServerKey, SCRAM_KEY_LEN);
1295 scram_HMAC_update(&ctx,
1296 state->client_first_message_bare,
1297 strlen(state->client_first_message_bare));
1298 scram_HMAC_update(&ctx, ",", 1);
1299 scram_HMAC_update(&ctx,
1300 state->server_first_message,
1301 strlen(state->server_first_message));
1302 scram_HMAC_update(&ctx, ",", 1);
1303 scram_HMAC_update(&ctx,
1304 state->client_final_message_without_proof,
1305 strlen(state->client_final_message_without_proof));
1306 scram_HMAC_final(ServerSignature, &ctx);
1308 server_signature_base64 = palloc(pg_b64_enc_len(SCRAM_KEY_LEN) + 1);
1309 siglen = pg_b64_encode((const char *) ServerSignature,
1310 SCRAM_KEY_LEN, server_signature_base64);
1311 server_signature_base64[siglen] = '\0';
1314 * The syntax for the server-final-message is: (RFC 5802)
1316 * verifier = "v=" base64
1317 * ;; base-64 encoded ServerSignature.
1319 * server-final-message = (server-error / verifier)
1324 return psprintf("v=%s", server_signature_base64);
1329 * Deterministically generate salt for mock authentication, using a SHA256
1330 * hash based on the username and a cluster-level secret key. Returns a
1331 * pointer to a static buffer of size SCRAM_DEFAULT_SALT_LEN.
1334 scram_mock_salt(const char *username)
1337 static uint8 sha_digest[PG_SHA256_DIGEST_LENGTH];
1338 char *mock_auth_nonce = GetMockAuthenticationNonce();
1341 * Generate salt using a SHA256 hash of the username and the cluster's
1342 * mock authentication nonce. (This works as long as the salt length is
1343 * not larger the SHA256 digest length. If the salt is smaller, the caller
1344 * will just ignore the extra data.)
1346 StaticAssertStmt(PG_SHA256_DIGEST_LENGTH >= SCRAM_DEFAULT_SALT_LEN,
1347 "salt length greater than SHA256 digest length");
1349 pg_sha256_init(&ctx);
1350 pg_sha256_update(&ctx, (uint8 *) username, strlen(username));
1351 pg_sha256_update(&ctx, (uint8 *) mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
1352 pg_sha256_final(&ctx, sha_digest);
1354 return (char *) sha_digest;