PostgreSQL Source Code  git master
auth-scram.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/xlog.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_control.h"
#include "common/base64.h"
#include "common/saslprep.h"
#include "common/scram-common.h"
#include "common/sha2.h"
#include "libpq/auth.h"
#include "libpq/crypt.h"
#include "libpq/scram.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/timestamp.h"
Include dependency graph for auth-scram.c:

Go to the source code of this file.

Data Structures

struct  scram_state
 

Enumerations

enum  scram_state_enum { SCRAM_AUTH_INIT, SCRAM_AUTH_SALT_SENT, SCRAM_AUTH_FINISHED }
 

Functions

static void read_client_first_message (scram_state *state, const char *input)
 
static void read_client_final_message (scram_state *state, const char *input)
 
static char * build_server_first_message (scram_state *state)
 
static char * build_server_final_message (scram_state *state)
 
static bool verify_client_proof (scram_state *state)
 
static bool verify_final_nonce (scram_state *state)
 
static void mock_scram_verifier (const char *username, int *iterations, char **salt, uint8 *stored_key, uint8 *server_key)
 
static bool is_scram_printable (char *p)
 
static char * sanitize_char (char c)
 
static char * sanitize_str (const char *s)
 
static char * scram_mock_salt (const char *username)
 
void pg_be_scram_get_mechanisms (Port *port, StringInfo buf)
 
void * pg_be_scram_init (Port *port, const char *selected_mech, const char *shadow_pass)
 
int pg_be_scram_exchange (void *opaq, const char *input, int inputlen, char **output, int *outputlen, char **logdetail)
 
char * pg_be_scram_build_verifier (const char *password)
 
bool scram_verify_plain_password (const char *username, const char *password, const char *verifier)
 
bool parse_scram_verifier (const char *verifier, int *iterations, char **salt, uint8 *stored_key, uint8 *server_key)
 
static char * read_attr_value (char **input, char attr)
 
static char * read_any_attr (char **input, char *attr_p)
 

Enumeration Type Documentation

◆ scram_state_enum

Enumerator
SCRAM_AUTH_INIT 
SCRAM_AUTH_SALT_SENT 
SCRAM_AUTH_FINISHED 

Definition at line 112 of file auth-scram.c.

Function Documentation

◆ build_server_final_message()

static char * build_server_final_message ( scram_state state)
static

Definition at line 1334 of file auth-scram.c.

References scram_state::client_final_message_without_proof, scram_state::client_first_message_bare, elog, ERROR, palloc(), pg_b64_enc_len(), pg_b64_encode(), psprintf(), scram_HMAC_final(), scram_HMAC_init(), scram_HMAC_update(), SCRAM_KEY_LEN, scram_state::server_first_message, and scram_state::ServerKey.

Referenced by pg_be_scram_exchange().

1335 {
1336  uint8 ServerSignature[SCRAM_KEY_LEN];
1337  char *server_signature_base64;
1338  int siglen;
1339  scram_HMAC_ctx ctx;
1340 
1341  /* calculate ServerSignature */
1342  scram_HMAC_init(&ctx, state->ServerKey, SCRAM_KEY_LEN);
1343  scram_HMAC_update(&ctx,
1345  strlen(state->client_first_message_bare));
1346  scram_HMAC_update(&ctx, ",", 1);
1347  scram_HMAC_update(&ctx,
1348  state->server_first_message,
1349  strlen(state->server_first_message));
1350  scram_HMAC_update(&ctx, ",", 1);
1351  scram_HMAC_update(&ctx,
1353  strlen(state->client_final_message_without_proof));
1354  scram_HMAC_final(ServerSignature, &ctx);
1355 
1356  siglen = pg_b64_enc_len(SCRAM_KEY_LEN);
1357  /* don't forget the zero-terminator */
1358  server_signature_base64 = palloc(siglen + 1);
1359  siglen = pg_b64_encode((const char *) ServerSignature,
1360  SCRAM_KEY_LEN, server_signature_base64,
1361  siglen);
1362  if (siglen < 0)
1363  elog(ERROR, "could not encode server signature");
1364  server_signature_base64[siglen] = '\0';
1365 
1366  /*------
1367  * The syntax for the server-final-message is: (RFC 5802)
1368  *
1369  * verifier = "v=" base64
1370  * ;; base-64 encoded ServerSignature.
1371  *
1372  * server-final-message = (server-error / verifier)
1373  * ["," extensions]
1374  *
1375  *------
1376  */
1377  return psprintf("v=%s", server_signature_base64);
1378 }
int pg_b64_encode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:49
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
unsigned char uint8
Definition: c.h:356
char * client_final_message_without_proof
Definition: auth-scram.c:140
#define ERROR
Definition: elog.h:43
char * server_first_message
Definition: auth-scram.c:145
void scram_HMAC_final(uint8 *result, scram_HMAC_ctx *ctx)
Definition: scram-common.c:85
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
void scram_HMAC_init(scram_HMAC_ctx *ctx, const uint8 *key, int keylen)
Definition: scram-common.c:35
void scram_HMAC_update(scram_HMAC_ctx *ctx, const char *str, int slen)
Definition: scram-common.c:75
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226
uint8 ServerKey[SCRAM_KEY_LEN]
Definition: auth-scram.c:131
#define SCRAM_KEY_LEN
Definition: scram-common.h:23
char * client_first_message_bare
Definition: auth-scram.c:135

◆ build_server_first_message()

static char * build_server_first_message ( scram_state state)
static

Definition at line 1124 of file auth-scram.c.

References scram_state::client_nonce, ereport, errcode(), errmsg(), ERROR, scram_state::iterations, palloc(), pg_b64_enc_len(), pg_b64_encode(), pg_strong_random(), psprintf(), pstrdup(), scram_state::salt, SCRAM_RAW_NONCE_LEN, scram_state::server_first_message, and scram_state::server_nonce.

Referenced by pg_be_scram_exchange().

1125 {
1126  /*------
1127  * The syntax for the server-first-message is: (RFC 5802)
1128  *
1129  * server-first-message =
1130  * [reserved-mext ","] nonce "," salt ","
1131  * iteration-count ["," extensions]
1132  *
1133  * nonce = "r=" c-nonce [s-nonce]
1134  * ;; Second part provided by server.
1135  *
1136  * c-nonce = printable
1137  *
1138  * s-nonce = printable
1139  *
1140  * salt = "s=" base64
1141  *
1142  * iteration-count = "i=" posit-number
1143  * ;; A positive number.
1144  *
1145  * Example:
1146  *
1147  * r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096
1148  *------
1149  */
1150 
1151  /*
1152  * Per the spec, the nonce may consist of any printable ASCII characters.
1153  * For convenience, however, we don't use the whole range available,
1154  * rather, we generate some random bytes, and base64 encode them.
1155  */
1156  char raw_nonce[SCRAM_RAW_NONCE_LEN];
1157  int encoded_len;
1158 
1159  if (!pg_strong_random(raw_nonce, SCRAM_RAW_NONCE_LEN))
1160  ereport(ERROR,
1161  (errcode(ERRCODE_INTERNAL_ERROR),
1162  errmsg("could not generate random nonce")));
1163 
1164  encoded_len = pg_b64_enc_len(SCRAM_RAW_NONCE_LEN);
1165  /* don't forget the zero-terminator */
1166  state->server_nonce = palloc(encoded_len + 1);
1167  encoded_len = pg_b64_encode(raw_nonce, SCRAM_RAW_NONCE_LEN,
1168  state->server_nonce, encoded_len);
1169  if (encoded_len < 0)
1170  ereport(ERROR,
1171  (errcode(ERRCODE_INTERNAL_ERROR),
1172  errmsg("could not encode random nonce")));
1173  state->server_nonce[encoded_len] = '\0';
1174 
1175  state->server_first_message =
1176  psprintf("r=%s%s,s=%s,i=%u",
1177  state->client_nonce, state->server_nonce,
1178  state->salt, state->iterations);
1179 
1180  return pstrdup(state->server_first_message);
1181 }
int pg_b64_encode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:49
char * pstrdup(const char *in)
Definition: mcxt.c:1161
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:570
char * client_nonce
Definition: auth-scram.c:137
#define ERROR
Definition: elog.h:43
int iterations
Definition: auth-scram.c:128
char * salt
Definition: auth-scram.c:129
char * server_first_message
Definition: auth-scram.c:145
#define ereport(elevel, rest)
Definition: elog.h:141
#define SCRAM_RAW_NONCE_LEN
Definition: scram-common.h:33
bool pg_strong_random(void *buf, size_t len)
char * server_nonce
Definition: auth-scram.c:146
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ is_scram_printable()

static bool is_scram_printable ( char *  p)
static

Definition at line 721 of file auth-scram.c.

Referenced by read_client_first_message().

722 {
723  /*------
724  * Printable characters, as defined by SCRAM spec: (RFC 5802)
725  *
726  * printable = %x21-2B / %x2D-7E
727  * ;; Printable ASCII except ",".
728  * ;; Note that any "printable" is also
729  * ;; a valid "value".
730  *------
731  */
732  for (; *p; p++)
733  {
734  if (*p < 0x21 || *p > 0x7E || *p == 0x2C /* comma */ )
735  return false;
736  }
737  return true;
738 }

◆ mock_scram_verifier()

static void mock_scram_verifier ( const char *  username,
int *  iterations,
char **  salt,
uint8 stored_key,
uint8 server_key 
)
static

Definition at line 647 of file auth-scram.c.

References elog, ERROR, palloc(), pg_b64_enc_len(), pg_b64_encode(), SCRAM_DEFAULT_ITERATIONS, SCRAM_DEFAULT_SALT_LEN, SCRAM_KEY_LEN, and scram_mock_salt().

Referenced by pg_be_scram_init().

649 {
650  char *raw_salt;
651  char *encoded_salt;
652  int encoded_len;
653 
654  /* Generate deterministic salt */
655  raw_salt = scram_mock_salt(username);
656 
657  encoded_len = pg_b64_enc_len(SCRAM_DEFAULT_SALT_LEN);
658  /* don't forget the zero-terminator */
659  encoded_salt = (char *) palloc(encoded_len + 1);
660  encoded_len = pg_b64_encode(raw_salt, SCRAM_DEFAULT_SALT_LEN, encoded_salt,
661  encoded_len);
662 
663  /*
664  * Note that we cannot reveal any information to an attacker here so the
665  * error message needs to remain generic. This should never fail anyway
666  * as the salt generated for mock authentication uses the cluster's nonce
667  * value.
668  */
669  if (encoded_len < 0)
670  elog(ERROR, "could not encode salt");
671  encoded_salt[encoded_len] = '\0';
672 
673  *salt = encoded_salt;
674  *iterations = SCRAM_DEFAULT_ITERATIONS;
675 
676  /* StoredKey and ServerKey are not used in a doomed authentication */
677  memset(stored_key, 0, SCRAM_KEY_LEN);
678  memset(server_key, 0, SCRAM_KEY_LEN);
679 }
static char * scram_mock_salt(const char *username)
Definition: auth-scram.c:1387
int pg_b64_encode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:49
#define ERROR
Definition: elog.h:43
#define SCRAM_DEFAULT_SALT_LEN
Definition: scram-common.h:40
static char * username
Definition: initdb.c:133
#define SCRAM_DEFAULT_ITERATIONS
Definition: scram-common.h:46
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226
#define SCRAM_KEY_LEN
Definition: scram-common.h:23

◆ parse_scram_verifier()

bool parse_scram_verifier ( const char *  verifier,
int *  iterations,
char **  salt,
uint8 stored_key,
uint8 server_key 
)

Definition at line 556 of file auth-scram.c.

References palloc(), pg_b64_dec_len(), pg_b64_decode(), pstrdup(), and SCRAM_KEY_LEN.

Referenced by get_password_type(), pg_be_scram_init(), and scram_verify_plain_password().

558 {
559  char *v;
560  char *p;
561  char *scheme_str;
562  char *salt_str;
563  char *iterations_str;
564  char *storedkey_str;
565  char *serverkey_str;
566  int decoded_len;
567  char *decoded_salt_buf;
568  char *decoded_stored_buf;
569  char *decoded_server_buf;
570 
571  /*
572  * The verifier is of form:
573  *
574  * SCRAM-SHA-256$<iterations>:<salt>$<storedkey>:<serverkey>
575  */
576  v = pstrdup(verifier);
577  if ((scheme_str = strtok(v, "$")) == NULL)
578  goto invalid_verifier;
579  if ((iterations_str = strtok(NULL, ":")) == NULL)
580  goto invalid_verifier;
581  if ((salt_str = strtok(NULL, "$")) == NULL)
582  goto invalid_verifier;
583  if ((storedkey_str = strtok(NULL, ":")) == NULL)
584  goto invalid_verifier;
585  if ((serverkey_str = strtok(NULL, "")) == NULL)
586  goto invalid_verifier;
587 
588  /* Parse the fields */
589  if (strcmp(scheme_str, "SCRAM-SHA-256") != 0)
590  goto invalid_verifier;
591 
592  errno = 0;
593  *iterations = strtol(iterations_str, &p, 10);
594  if (*p || errno != 0)
595  goto invalid_verifier;
596 
597  /*
598  * Verify that the salt is in Base64-encoded format, by decoding it,
599  * although we return the encoded version to the caller.
600  */
601  decoded_len = pg_b64_dec_len(strlen(salt_str));
602  decoded_salt_buf = palloc(decoded_len);
603  decoded_len = pg_b64_decode(salt_str, strlen(salt_str),
604  decoded_salt_buf, decoded_len);
605  if (decoded_len < 0)
606  goto invalid_verifier;
607  *salt = pstrdup(salt_str);
608 
609  /*
610  * Decode StoredKey and ServerKey.
611  */
612  decoded_len = pg_b64_dec_len(strlen(storedkey_str));
613  decoded_stored_buf = palloc(decoded_len);
614  decoded_len = pg_b64_decode(storedkey_str, strlen(storedkey_str),
615  decoded_stored_buf, decoded_len);
616  if (decoded_len != SCRAM_KEY_LEN)
617  goto invalid_verifier;
618  memcpy(stored_key, decoded_stored_buf, SCRAM_KEY_LEN);
619 
620  decoded_len = pg_b64_dec_len(strlen(serverkey_str));
621  decoded_server_buf = palloc(decoded_len);
622  decoded_len = pg_b64_decode(serverkey_str, strlen(serverkey_str),
623  decoded_server_buf, decoded_len);
624  if (decoded_len != SCRAM_KEY_LEN)
625  goto invalid_verifier;
626  memcpy(server_key, decoded_server_buf, SCRAM_KEY_LEN);
627 
628  return true;
629 
630 invalid_verifier:
631  *salt = NULL;
632  return false;
633 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int pg_b64_dec_len(int srclen)
Definition: base64.c:239
int pg_b64_decode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:116
void * palloc(Size size)
Definition: mcxt.c:924
#define SCRAM_KEY_LEN
Definition: scram-common.h:23

◆ pg_be_scram_build_verifier()

char* pg_be_scram_build_verifier ( const char *  password)

Definition at line 451 of file auth-scram.c.

References ereport, errcode(), errmsg(), ERROR, pfree(), pg_saslprep(), pg_strong_random(), SASLPREP_SUCCESS, scram_build_verifier(), SCRAM_DEFAULT_ITERATIONS, and SCRAM_DEFAULT_SALT_LEN.

Referenced by encrypt_password().

452 {
453  char *prep_password;
454  pg_saslprep_rc rc;
455  char saltbuf[SCRAM_DEFAULT_SALT_LEN];
456  char *result;
457 
458  /*
459  * Normalize the password with SASLprep. If that doesn't work, because
460  * the password isn't valid UTF-8 or contains prohibited characters, just
461  * proceed with the original password. (See comments at top of file.)
462  */
463  rc = pg_saslprep(password, &prep_password);
464  if (rc == SASLPREP_SUCCESS)
465  password = (const char *) prep_password;
466 
467  /* Generate random salt */
469  ereport(ERROR,
470  (errcode(ERRCODE_INTERNAL_ERROR),
471  errmsg("could not generate random salt")));
472 
475 
476  if (prep_password)
477  pfree(prep_password);
478 
479  return result;
480 }
static char password[100]
Definition: streamutil.c:55
int errcode(int sqlerrcode)
Definition: elog.c:570
pg_saslprep_rc pg_saslprep(const char *input, char **output)
Definition: saslprep.c:1071
pg_saslprep_rc
Definition: saslprep.h:20
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define SCRAM_DEFAULT_SALT_LEN
Definition: scram-common.h:40
bool pg_strong_random(void *buf, size_t len)
#define SCRAM_DEFAULT_ITERATIONS
Definition: scram-common.h:46
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * scram_build_verifier(const char *salt, int saltlen, int iterations, const char *password)
Definition: scram-common.c:192

◆ pg_be_scram_exchange()

int pg_be_scram_exchange ( void *  opaq,
const char *  input,
int  inputlen,
char **  output,
int *  outputlen,
char **  logdetail 
)

Definition at line 328 of file auth-scram.c.

References Assert, build_server_final_message(), build_server_first_message(), scram_state::doomed, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, scram_state::logdetail, pstrdup(), read_client_final_message(), read_client_first_message(), SASL_EXCHANGE_CONTINUE, SASL_EXCHANGE_FAILURE, SASL_EXCHANGE_SUCCESS, SCRAM_AUTH_FINISHED, SCRAM_AUTH_INIT, SCRAM_AUTH_SALT_SENT, scram_state::state, verify_client_proof(), and verify_final_nonce().

Referenced by CheckSCRAMAuth().

330 {
331  scram_state *state = (scram_state *) opaq;
332  int result;
333 
334  *output = NULL;
335 
336  /*
337  * If the client didn't include an "Initial Client Response" in the
338  * SASLInitialResponse message, send an empty challenge, to which the
339  * client will respond with the same data that usually comes in the
340  * Initial Client Response.
341  */
342  if (input == NULL)
343  {
344  Assert(state->state == SCRAM_AUTH_INIT);
345 
346  *output = pstrdup("");
347  *outputlen = 0;
348  return SASL_EXCHANGE_CONTINUE;
349  }
350 
351  /*
352  * Check that the input length agrees with the string length of the input.
353  * We can ignore inputlen after this.
354  */
355  if (inputlen == 0)
356  ereport(ERROR,
357  (errcode(ERRCODE_PROTOCOL_VIOLATION),
358  errmsg("malformed SCRAM message"),
359  errdetail("The message is empty.")));
360  if (inputlen != strlen(input))
361  ereport(ERROR,
362  (errcode(ERRCODE_PROTOCOL_VIOLATION),
363  errmsg("malformed SCRAM message"),
364  errdetail("Message length does not match input length.")));
365 
366  switch (state->state)
367  {
368  case SCRAM_AUTH_INIT:
369 
370  /*
371  * Initialization phase. Receive the first message from client
372  * and be sure that it parsed correctly. Then send the challenge
373  * to the client.
374  */
375  read_client_first_message(state, input);
376 
377  /* prepare message to send challenge */
379 
380  state->state = SCRAM_AUTH_SALT_SENT;
381  result = SASL_EXCHANGE_CONTINUE;
382  break;
383 
385 
386  /*
387  * Final phase for the server. Receive the response to the
388  * challenge previously sent, verify, and let the client know that
389  * everything went well (or not).
390  */
391  read_client_final_message(state, input);
392 
393  if (!verify_final_nonce(state))
394  ereport(ERROR,
395  (errcode(ERRCODE_PROTOCOL_VIOLATION),
396  errmsg("invalid SCRAM response"),
397  errdetail("Nonce does not match.")));
398 
399  /*
400  * Now check the final nonce and the client proof.
401  *
402  * If we performed a "mock" authentication that we knew would fail
403  * from the get go, this is where we fail.
404  *
405  * The SCRAM specification includes an error code,
406  * "invalid-proof", for authentication failure, but it also allows
407  * erroring out in an application-specific way. We choose to do
408  * the latter, so that the error message for invalid password is
409  * the same for all authentication methods. The caller will call
410  * ereport(), when we return SASL_EXCHANGE_FAILURE with no output.
411  *
412  * NB: the order of these checks is intentional. We calculate the
413  * client proof even in a mock authentication, even though it's
414  * bound to fail, to thwart timing attacks to determine if a role
415  * with the given name exists or not.
416  */
417  if (!verify_client_proof(state) || state->doomed)
418  {
419  result = SASL_EXCHANGE_FAILURE;
420  break;
421  }
422 
423  /* Build final message for client */
425 
426  /* Success! */
427  result = SASL_EXCHANGE_SUCCESS;
428  state->state = SCRAM_AUTH_FINISHED;
429  break;
430 
431  default:
432  elog(ERROR, "invalid SCRAM exchange state");
433  result = SASL_EXCHANGE_FAILURE;
434  }
435 
436  if (result == SASL_EXCHANGE_FAILURE && state->logdetail && logdetail)
437  *logdetail = state->logdetail;
438 
439  if (*output)
440  *outputlen = strlen(*output);
441 
442  return result;
443 }
static void output(uint64 loop_count)
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define SASL_EXCHANGE_FAILURE
Definition: scram.h:22
#define SASL_EXCHANGE_SUCCESS
Definition: scram.h:21
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
static void read_client_first_message(scram_state *state, const char *input)
Definition: auth-scram.c:848
static bool verify_client_proof(scram_state *state)
Definition: auth-scram.c:1083
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
scram_state_enum state
Definition: auth-scram.c:121
#define Assert(condition)
Definition: c.h:732
Definition: regguts.h:298
static char * build_server_final_message(scram_state *state)
Definition: auth-scram.c:1334
static void read_client_final_message(scram_state *state, const char *input)
Definition: auth-scram.c:1188
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
static bool verify_final_nonce(scram_state *state)
Definition: auth-scram.c:1062
char * logdetail
Definition: auth-scram.c:155
static char * build_server_first_message(scram_state *state)
Definition: auth-scram.c:1124
#define SASL_EXCHANGE_CONTINUE
Definition: scram.h:20

◆ pg_be_scram_get_mechanisms()

void pg_be_scram_get_mechanisms ( Port port,
StringInfo  buf 
)

Definition at line 181 of file auth-scram.c.

References appendStringInfoChar(), appendStringInfoString(), SCRAM_SHA_256_NAME, SCRAM_SHA_256_PLUS_NAME, and Port::ssl_in_use.

Referenced by CheckSCRAMAuth().

182 {
183  /*
184  * Advertise the mechanisms in decreasing order of importance. So the
185  * channel-binding variants go first, if they are supported. Channel
186  * binding is only supported with SSL, and only if the SSL implementation
187  * has a function to get the certificate's hash.
188  */
189 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
190  if (port->ssl_in_use)
191  {
193  appendStringInfoChar(buf, '\0');
194  }
195 #endif
197  appendStringInfoChar(buf, '\0');
198 }
#define SCRAM_SHA_256_NAME
Definition: scram-common.h:19
bool ssl_in_use
Definition: libpq-be.h:190
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:163
#define SCRAM_SHA_256_PLUS_NAME
Definition: scram-common.h:20
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:175

◆ pg_be_scram_init()

void* pg_be_scram_init ( Port port,
const char *  selected_mech,
const char *  shadow_pass 
)

Definition at line 218 of file auth-scram.c.

References _, scram_state::channel_binding_in_use, scram_state::doomed, ereport, errcode(), errmsg(), ERROR, get_password_type(), scram_state::iterations, LOG, scram_state::logdetail, mock_scram_verifier(), palloc0(), parse_scram_verifier(), PASSWORD_TYPE_SCRAM_SHA_256, port, scram_state::port, psprintf(), scram_state::salt, SCRAM_AUTH_INIT, SCRAM_SHA_256_NAME, SCRAM_SHA_256_PLUS_NAME, scram_state::ServerKey, Port::ssl_in_use, scram_state::state, scram_state::StoredKey, and Port::user_name.

Referenced by CheckSCRAMAuth().

221 {
223  bool got_verifier;
224 
225  state = (scram_state *) palloc0(sizeof(scram_state));
226  state->port = port;
227  state->state = SCRAM_AUTH_INIT;
228 
229  /*
230  * Parse the selected mechanism.
231  *
232  * Note that if we don't support channel binding, either because the SSL
233  * implementation doesn't support it or we're not using SSL at all, we
234  * would not have advertised the PLUS variant in the first place. If the
235  * client nevertheless tries to select it, it's a protocol violation like
236  * selecting any other SASL mechanism we don't support.
237  */
238 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
239  if (strcmp(selected_mech, SCRAM_SHA_256_PLUS_NAME) == 0 && port->ssl_in_use)
240  state->channel_binding_in_use = true;
241  else
242 #endif
243  if (strcmp(selected_mech, SCRAM_SHA_256_NAME) == 0)
244  state->channel_binding_in_use = false;
245  else
246  ereport(ERROR,
247  (errcode(ERRCODE_PROTOCOL_VIOLATION),
248  errmsg("client selected an invalid SASL authentication mechanism")));
249 
250  /*
251  * Parse the stored password verifier.
252  */
253  if (shadow_pass)
254  {
255  int password_type = get_password_type(shadow_pass);
256 
257  if (password_type == PASSWORD_TYPE_SCRAM_SHA_256)
258  {
259  if (parse_scram_verifier(shadow_pass, &state->iterations, &state->salt,
260  state->StoredKey, state->ServerKey))
261  got_verifier = true;
262  else
263  {
264  /*
265  * The password looked like a SCRAM verifier, but could not be
266  * parsed.
267  */
268  ereport(LOG,
269  (errmsg("invalid SCRAM verifier for user \"%s\"",
270  state->port->user_name)));
271  got_verifier = false;
272  }
273  }
274  else
275  {
276  /*
277  * The user doesn't have SCRAM verifier. (You cannot do SCRAM
278  * authentication with an MD5 hash.)
279  */
280  state->logdetail = psprintf(_("User \"%s\" does not have a valid SCRAM verifier."),
281  state->port->user_name);
282  got_verifier = false;
283  }
284  }
285  else
286  {
287  /*
288  * The caller requested us to perform a dummy authentication. This is
289  * considered normal, since the caller requested it, so don't set log
290  * detail.
291  */
292  got_verifier = false;
293  }
294 
295  /*
296  * If the user did not have a valid SCRAM verifier, we still go through
297  * the motions with a mock one, and fail as if the client supplied an
298  * incorrect password. This is to avoid revealing information to an
299  * attacker.
300  */
301  if (!got_verifier)
302  {
303  mock_scram_verifier(state->port->user_name, &state->iterations,
304  &state->salt, state->StoredKey, state->ServerKey);
305  state->doomed = true;
306  }
307 
308  return state;
309 }
Port * port
Definition: auth-scram.c:125
#define SCRAM_SHA_256_NAME
Definition: scram-common.h:19
uint8 StoredKey[SCRAM_KEY_LEN]
Definition: auth-scram.c:130
PasswordType get_password_type(const char *shadow_pass)
Definition: crypt.c:92
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:570
bool ssl_in_use
Definition: libpq-be.h:190
#define LOG
Definition: elog.h:26
#define ERROR
Definition: elog.h:43
int iterations
Definition: auth-scram.c:128
char * salt
Definition: auth-scram.c:129
#define SCRAM_SHA_256_PLUS_NAME
Definition: scram-common.h:20
char * user_name
Definition: libpq-be.h:141
static void mock_scram_verifier(const char *username, int *iterations, char **salt, uint8 *stored_key, uint8 *server_key)
Definition: auth-scram.c:647
#define ereport(elevel, rest)
Definition: elog.h:141
static int port
Definition: pg_regress.c:92
scram_state_enum state
Definition: auth-scram.c:121
void * palloc0(Size size)
Definition: mcxt.c:955
Definition: regguts.h:298
int errmsg(const char *fmt,...)
Definition: elog.c:784
bool parse_scram_verifier(const char *verifier, int *iterations, char **salt, uint8 *stored_key, uint8 *server_key)
Definition: auth-scram.c:556
char * logdetail
Definition: auth-scram.c:155
bool channel_binding_in_use
Definition: auth-scram.c:126
uint8 ServerKey[SCRAM_KEY_LEN]
Definition: auth-scram.c:131
#define _(x)
Definition: elog.c:84

◆ read_any_attr()

static char* read_any_attr ( char **  input,
char *  attr_p 
)
static

Definition at line 796 of file auth-scram.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, and sanitize_char().

Referenced by read_client_final_message(), and read_client_first_message().

797 {
798  char *begin = *input;
799  char *end;
800  char attr = *begin;
801 
802  /*------
803  * attr-val = ALPHA "=" value
804  * ;; Generic syntax of any attribute sent
805  * ;; by server or client
806  *------
807  */
808  if (!((attr >= 'A' && attr <= 'Z') ||
809  (attr >= 'a' && attr <= 'z')))
810  ereport(ERROR,
811  (errcode(ERRCODE_PROTOCOL_VIOLATION),
812  errmsg("malformed SCRAM message"),
813  errdetail("Attribute expected, but found invalid character \"%s\".",
814  sanitize_char(attr))));
815  if (attr_p)
816  *attr_p = attr;
817  begin++;
818 
819  if (*begin != '=')
820  ereport(ERROR,
821  (errcode(ERRCODE_PROTOCOL_VIOLATION),
822  errmsg("malformed SCRAM message"),
823  errdetail("Expected character \"=\" for attribute \"%c\".", attr)));
824  begin++;
825 
826  end = begin;
827  while (*end && *end != ',')
828  end++;
829 
830  if (*end)
831  {
832  *end = '\0';
833  *input = end + 1;
834  }
835  else
836  *input = end;
837 
838  return begin;
839 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
static char * sanitize_char(char c)
Definition: auth-scram.c:749
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ read_attr_value()

static char* read_attr_value ( char **  input,
char  attr 
)
static

Definition at line 685 of file auth-scram.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, and sanitize_char().

Referenced by read_client_final_message(), and read_client_first_message().

686 {
687  char *begin = *input;
688  char *end;
689 
690  if (*begin != attr)
691  ereport(ERROR,
692  (errcode(ERRCODE_PROTOCOL_VIOLATION),
693  errmsg("malformed SCRAM message"),
694  errdetail("Expected attribute \"%c\" but found \"%s\".",
695  attr, sanitize_char(*begin))));
696  begin++;
697 
698  if (*begin != '=')
699  ereport(ERROR,
700  (errcode(ERRCODE_PROTOCOL_VIOLATION),
701  errmsg("malformed SCRAM message"),
702  errdetail("Expected character \"=\" for attribute \"%c\".", attr)));
703  begin++;
704 
705  end = begin;
706  while (*end && *end != ',')
707  end++;
708 
709  if (*end)
710  {
711  *end = '\0';
712  *input = end + 1;
713  }
714  else
715  *input = end;
716 
717  return begin;
718 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
static char * sanitize_char(char c)
Definition: auth-scram.c:749
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ read_client_final_message()

static void read_client_final_message ( scram_state state,
const char *  input 
)
static

Definition at line 1188 of file auth-scram.c.

References Assert, scram_state::cbind_flag, scram_state::channel_binding_in_use, scram_state::client_final_message_without_proof, scram_state::client_final_nonce, scram_state::ClientProof, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, palloc(), pfree(), pg_b64_dec_len(), pg_b64_decode(), pg_b64_enc_len(), pg_b64_encode(), scram_state::port, pstrdup(), read_any_attr(), read_attr_value(), SCRAM_KEY_LEN, snprintf, and value.

Referenced by pg_be_scram_exchange().

1189 {
1190  char attr;
1191  char *channel_binding;
1192  char *value;
1193  char *begin,
1194  *proof;
1195  char *p;
1196  char *client_proof;
1197  int client_proof_len;
1198 
1199  begin = p = pstrdup(input);
1200 
1201  /*------
1202  * The syntax for the server-first-message is: (RFC 5802)
1203  *
1204  * gs2-header = gs2-cbind-flag "," [ authzid ] ","
1205  * ;; GS2 header for SCRAM
1206  * ;; (the actual GS2 header includes an optional
1207  * ;; flag to indicate that the GSS mechanism is not
1208  * ;; "standard", but since SCRAM is "standard", we
1209  * ;; don't include that flag).
1210  *
1211  * cbind-input = gs2-header [ cbind-data ]
1212  * ;; cbind-data MUST be present for
1213  * ;; gs2-cbind-flag of "p" and MUST be absent
1214  * ;; for "y" or "n".
1215  *
1216  * channel-binding = "c=" base64
1217  * ;; base64 encoding of cbind-input.
1218  *
1219  * proof = "p=" base64
1220  *
1221  * client-final-message-without-proof =
1222  * channel-binding "," nonce [","
1223  * extensions]
1224  *
1225  * client-final-message =
1226  * client-final-message-without-proof "," proof
1227  *------
1228  */
1229 
1230  /*
1231  * Read channel binding. This repeats the channel-binding flags and is
1232  * then followed by the actual binding data depending on the type.
1233  */
1234  channel_binding = read_attr_value(&p, 'c');
1235  if (state->channel_binding_in_use)
1236  {
1237 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
1238  const char *cbind_data = NULL;
1239  size_t cbind_data_len = 0;
1240  size_t cbind_header_len;
1241  char *cbind_input;
1242  size_t cbind_input_len;
1243  char *b64_message;
1244  int b64_message_len;
1245 
1246  Assert(state->cbind_flag == 'p');
1247 
1248  /* Fetch hash data of server's SSL certificate */
1249  cbind_data = be_tls_get_certificate_hash(state->port,
1250  &cbind_data_len);
1251 
1252  /* should not happen */
1253  if (cbind_data == NULL || cbind_data_len == 0)
1254  elog(ERROR, "could not get server certificate hash");
1255 
1256  cbind_header_len = strlen("p=tls-server-end-point,,"); /* p=type,, */
1257  cbind_input_len = cbind_header_len + cbind_data_len;
1258  cbind_input = palloc(cbind_input_len);
1259  snprintf(cbind_input, cbind_input_len, "p=tls-server-end-point,,");
1260  memcpy(cbind_input + cbind_header_len, cbind_data, cbind_data_len);
1261 
1262  b64_message_len = pg_b64_enc_len(cbind_input_len);
1263  /* don't forget the zero-terminator */
1264  b64_message = palloc(b64_message_len + 1);
1265  b64_message_len = pg_b64_encode(cbind_input, cbind_input_len,
1266  b64_message, b64_message_len);
1267  if (b64_message_len < 0)
1268  elog(ERROR, "could not encode channel binding data");
1269  b64_message[b64_message_len] = '\0';
1270 
1271  /*
1272  * Compare the value sent by the client with the value expected by the
1273  * server.
1274  */
1275  if (strcmp(channel_binding, b64_message) != 0)
1276  ereport(ERROR,
1277  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
1278  (errmsg("SCRAM channel binding check failed"))));
1279 #else
1280  /* shouldn't happen, because we checked this earlier already */
1281  elog(ERROR, "channel binding not supported by this build");
1282 #endif
1283  }
1284  else
1285  {
1286  /*
1287  * If we are not using channel binding, the binding data is expected
1288  * to always be "biws", which is "n,," base64-encoded, or "eSws",
1289  * which is "y,,". We also have to check whether the flag is the same
1290  * one that the client originally sent.
1291  */
1292  if (!(strcmp(channel_binding, "biws") == 0 && state->cbind_flag == 'n') &&
1293  !(strcmp(channel_binding, "eSws") == 0 && state->cbind_flag == 'y'))
1294  ereport(ERROR,
1295  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1296  (errmsg("unexpected SCRAM channel-binding attribute in client-final-message"))));
1297  }
1298 
1299  state->client_final_nonce = read_attr_value(&p, 'r');
1300 
1301  /* ignore optional extensions */
1302  do
1303  {
1304  proof = p - 1;
1305  value = read_any_attr(&p, &attr);
1306  } while (attr != 'p');
1307 
1308  client_proof_len = pg_b64_dec_len(strlen(value));
1309  client_proof = palloc(client_proof_len);
1310  if (pg_b64_decode(value, strlen(value), client_proof,
1311  client_proof_len) != SCRAM_KEY_LEN)
1312  ereport(ERROR,
1313  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1314  errmsg("malformed SCRAM message"),
1315  errdetail("Malformed proof in client-final-message.")));
1316  memcpy(state->ClientProof, client_proof, SCRAM_KEY_LEN);
1317  pfree(client_proof);
1318 
1319  if (*p != '\0')
1320  ereport(ERROR,
1321  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1322  errmsg("malformed SCRAM message"),
1323  errdetail("Garbage found at the end of client-final-message.")));
1324 
1325  state->client_final_message_without_proof = palloc(proof - begin + 1);
1326  memcpy(state->client_final_message_without_proof, input, proof - begin);
1327  state->client_final_message_without_proof[proof - begin] = '\0';
1328 }
Port * port
Definition: auth-scram.c:125
int pg_b64_encode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:49
char * pstrdup(const char *in)
Definition: mcxt.c:1161
static struct @144 value
int errcode(int sqlerrcode)
Definition: elog.c:570
char ClientProof[SCRAM_KEY_LEN]
Definition: auth-scram.c:142
char * client_final_message_without_proof
Definition: auth-scram.c:140
int pg_b64_dec_len(int srclen)
Definition: base64.c:239
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int pg_b64_decode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:116
char cbind_flag
Definition: auth-scram.c:134
char * client_final_nonce
Definition: auth-scram.c:141
#define Assert(condition)
Definition: c.h:732
static char * read_any_attr(char **input, char *attr_p)
Definition: auth-scram.c:796
int pg_b64_enc_len(int srclen)
Definition: base64.c:224
static char * read_attr_value(char **input, char attr)
Definition: auth-scram.c:685
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
bool channel_binding_in_use
Definition: auth-scram.c:126
#define SCRAM_KEY_LEN
Definition: scram-common.h:23
#define snprintf
Definition: port.h:192

◆ read_client_first_message()

static void read_client_first_message ( scram_state state,
const char *  input 
)
static

Definition at line 848 of file auth-scram.c.

References scram_state::cbind_flag, scram_state::channel_binding_in_use, scram_state::client_first_message_bare, scram_state::client_nonce, scram_state::client_username, ereport, errcode(), errdetail(), errmsg(), ERROR, is_scram_printable(), scram_state::port, pstrdup(), read_any_attr(), read_attr_value(), sanitize_char(), sanitize_str(), and Port::ssl_in_use.

Referenced by pg_be_scram_exchange().

849 {
850  char *p = pstrdup(input);
851  char *channel_binding_type;
852 
853 
854  /*------
855  * The syntax for the client-first-message is: (RFC 5802)
856  *
857  * saslname = 1*(value-safe-char / "=2C" / "=3D")
858  * ;; Conforms to <value>.
859  *
860  * authzid = "a=" saslname
861  * ;; Protocol specific.
862  *
863  * cb-name = 1*(ALPHA / DIGIT / "." / "-")
864  * ;; See RFC 5056, Section 7.
865  * ;; E.g., "tls-server-end-point" or
866  * ;; "tls-unique".
867  *
868  * gs2-cbind-flag = ("p=" cb-name) / "n" / "y"
869  * ;; "n" -> client doesn't support channel binding.
870  * ;; "y" -> client does support channel binding
871  * ;; but thinks the server does not.
872  * ;; "p" -> client requires channel binding.
873  * ;; The selected channel binding follows "p=".
874  *
875  * gs2-header = gs2-cbind-flag "," [ authzid ] ","
876  * ;; GS2 header for SCRAM
877  * ;; (the actual GS2 header includes an optional
878  * ;; flag to indicate that the GSS mechanism is not
879  * ;; "standard", but since SCRAM is "standard", we
880  * ;; don't include that flag).
881  *
882  * username = "n=" saslname
883  * ;; Usernames are prepared using SASLprep.
884  *
885  * reserved-mext = "m=" 1*(value-char)
886  * ;; Reserved for signaling mandatory extensions.
887  * ;; The exact syntax will be defined in
888  * ;; the future.
889  *
890  * nonce = "r=" c-nonce [s-nonce]
891  * ;; Second part provided by server.
892  *
893  * c-nonce = printable
894  *
895  * client-first-message-bare =
896  * [reserved-mext ","]
897  * username "," nonce ["," extensions]
898  *
899  * client-first-message =
900  * gs2-header client-first-message-bare
901  *
902  * For example:
903  * n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL
904  *
905  * The "n,," in the beginning means that the client doesn't support
906  * channel binding, and no authzid is given. "n=user" is the username.
907  * However, in PostgreSQL the username is sent in the startup packet, and
908  * the username in the SCRAM exchange is ignored. libpq always sends it
909  * as an empty string. The last part, "r=fyko+d2lbbFgONRv9qkxdawL" is
910  * the client nonce.
911  *------
912  */
913 
914  /*
915  * Read gs2-cbind-flag. (For details see also RFC 5802 Section 6 "Channel
916  * Binding".)
917  */
918  state->cbind_flag = *p;
919  switch (*p)
920  {
921  case 'n':
922 
923  /*
924  * The client does not support channel binding or has simply
925  * decided to not use it. In that case just let it go.
926  */
927  if (state->channel_binding_in_use)
928  ereport(ERROR,
929  (errcode(ERRCODE_PROTOCOL_VIOLATION),
930  errmsg("malformed SCRAM message"),
931  errdetail("The client selected SCRAM-SHA-256-PLUS, but the SCRAM message does not include channel binding data.")));
932 
933  p++;
934  if (*p != ',')
935  ereport(ERROR,
936  (errcode(ERRCODE_PROTOCOL_VIOLATION),
937  errmsg("malformed SCRAM message"),
938  errdetail("Comma expected, but found character \"%s\".",
939  sanitize_char(*p))));
940  p++;
941  break;
942  case 'y':
943 
944  /*
945  * The client supports channel binding and thinks that the server
946  * does not. In this case, the server must fail authentication if
947  * it supports channel binding.
948  */
949  if (state->channel_binding_in_use)
950  ereport(ERROR,
951  (errcode(ERRCODE_PROTOCOL_VIOLATION),
952  errmsg("malformed SCRAM message"),
953  errdetail("The client selected SCRAM-SHA-256-PLUS, but the SCRAM message does not include channel binding data.")));
954 
955 #ifdef HAVE_BE_TLS_GET_CERTIFICATE_HASH
956  if (state->port->ssl_in_use)
957  ereport(ERROR,
958  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
959  errmsg("SCRAM channel binding negotiation error"),
960  errdetail("The client supports SCRAM channel binding but thinks the server does not. "
961  "However, this server does support channel binding.")));
962 #endif
963  p++;
964  if (*p != ',')
965  ereport(ERROR,
966  (errcode(ERRCODE_PROTOCOL_VIOLATION),
967  errmsg("malformed SCRAM message"),
968  errdetail("Comma expected, but found character \"%s\".",
969  sanitize_char(*p))));
970  p++;
971  break;
972  case 'p':
973 
974  /*
975  * The client requires channel binding. Channel binding type
976  * follows, e.g., "p=tls-server-end-point".
977  */
978  if (!state->channel_binding_in_use)
979  ereport(ERROR,
980  (errcode(ERRCODE_PROTOCOL_VIOLATION),
981  errmsg("malformed SCRAM message"),
982  errdetail("The client selected SCRAM-SHA-256 without channel binding, but the SCRAM message includes channel binding data.")));
983 
984  channel_binding_type = read_attr_value(&p, 'p');
985 
986  /*
987  * The only channel binding type we support is
988  * tls-server-end-point.
989  */
990  if (strcmp(channel_binding_type, "tls-server-end-point") != 0)
991  ereport(ERROR,
992  (errcode(ERRCODE_PROTOCOL_VIOLATION),
993  (errmsg("unsupported SCRAM channel-binding type \"%s\"",
994  sanitize_str(channel_binding_type)))));
995  break;
996  default:
997  ereport(ERROR,
998  (errcode(ERRCODE_PROTOCOL_VIOLATION),
999  errmsg("malformed SCRAM message"),
1000  errdetail("Unexpected channel-binding flag \"%s\".",
1001  sanitize_char(*p))));
1002  }
1003 
1004  /*
1005  * Forbid optional authzid (authorization identity). We don't support it.
1006  */
1007  if (*p == 'a')
1008  ereport(ERROR,
1009  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1010  errmsg("client uses authorization identity, but it is not supported")));
1011  if (*p != ',')
1012  ereport(ERROR,
1013  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1014  errmsg("malformed SCRAM message"),
1015  errdetail("Unexpected attribute \"%s\" in client-first-message.",
1016  sanitize_char(*p))));
1017  p++;
1018 
1019  state->client_first_message_bare = pstrdup(p);
1020 
1021  /*
1022  * Any mandatory extensions would go here. We don't support any.
1023  *
1024  * RFC 5802 specifies error code "e=extensions-not-supported" for this,
1025  * but it can only be sent in the server-final message. We prefer to fail
1026  * immediately (which the RFC also allows).
1027  */
1028  if (*p == 'm')
1029  ereport(ERROR,
1030  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1031  errmsg("client requires an unsupported SCRAM extension")));
1032 
1033  /*
1034  * Read username. Note: this is ignored. We use the username from the
1035  * startup message instead, still it is kept around if provided as it
1036  * proves to be useful for debugging purposes.
1037  */
1038  state->client_username = read_attr_value(&p, 'n');
1039 
1040  /* read nonce and check that it is made of only printable characters */
1041  state->client_nonce = read_attr_value(&p, 'r');
1042  if (!is_scram_printable(state->client_nonce))
1043  ereport(ERROR,
1044  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1045  errmsg("non-printable characters in SCRAM nonce")));
1046 
1047  /*
1048  * There can be any number of optional extensions after this. We don't
1049  * support any extensions, so ignore them.
1050  */
1051  while (*p != '\0')
1052  read_any_attr(&p, NULL);
1053 
1054  /* success! */
1055 }
Port * port
Definition: auth-scram.c:125
char * pstrdup(const char *in)
Definition: mcxt.c:1161
static bool is_scram_printable(char *p)
Definition: auth-scram.c:721
int errcode(int sqlerrcode)
Definition: elog.c:570
bool ssl_in_use
Definition: libpq-be.h:190
char * client_nonce
Definition: auth-scram.c:137
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
char * client_username
Definition: auth-scram.c:136
#define ereport(elevel, rest)
Definition: elog.h:141
char cbind_flag
Definition: auth-scram.c:134
static char * sanitize_str(const char *s)
Definition: auth-scram.c:769
static char * read_any_attr(char **input, char *attr_p)
Definition: auth-scram.c:796
static char * sanitize_char(char c)
Definition: auth-scram.c:749
static char * read_attr_value(char **input, char attr)
Definition: auth-scram.c:685
int errmsg(const char *fmt,...)
Definition: elog.c:784
bool channel_binding_in_use
Definition: auth-scram.c:126
char * client_first_message_bare
Definition: auth-scram.c:135

◆ sanitize_char()

static char * sanitize_char ( char  c)
static

Definition at line 749 of file auth-scram.c.

References buf, and snprintf.

Referenced by read_any_attr(), read_attr_value(), and read_client_first_message().

750 {
751  static char buf[5];
752 
753  if (c >= 0x21 && c <= 0x7E)
754  snprintf(buf, sizeof(buf), "'%c'", c);
755  else
756  snprintf(buf, sizeof(buf), "0x%02x", (unsigned char) c);
757  return buf;
758 }
char * c
static char * buf
Definition: pg_test_fsync.c:68
#define snprintf
Definition: port.h:192

◆ sanitize_str()

static char * sanitize_str ( const char *  s)
static

Definition at line 769 of file auth-scram.c.

References buf, and i.

Referenced by read_client_first_message().

770 {
771  static char buf[30 + 1];
772  int i;
773 
774  for (i = 0; i < sizeof(buf) - 1; i++)
775  {
776  char c = s[i];
777 
778  if (c == '\0')
779  break;
780 
781  if (c >= 0x21 && c <= 0x7E)
782  buf[i] = c;
783  else
784  buf[i] = '?';
785  }
786  buf[i] = '\0';
787  return buf;
788 }
char * c
static char * buf
Definition: pg_test_fsync.c:68
int i

◆ scram_mock_salt()

static char * scram_mock_salt ( const char *  username)
static

Definition at line 1387 of file auth-scram.c.

References GetMockAuthenticationNonce(), MOCK_AUTH_NONCE_LEN, PG_SHA256_DIGEST_LENGTH, pg_sha256_final(), pg_sha256_init(), pg_sha256_update(), SCRAM_DEFAULT_SALT_LEN, and StaticAssertStmt.

Referenced by mock_scram_verifier().

1388 {
1389  pg_sha256_ctx ctx;
1390  static uint8 sha_digest[PG_SHA256_DIGEST_LENGTH];
1391  char *mock_auth_nonce = GetMockAuthenticationNonce();
1392 
1393  /*
1394  * Generate salt using a SHA256 hash of the username and the cluster's
1395  * mock authentication nonce. (This works as long as the salt length is
1396  * not larger the SHA256 digest length. If the salt is smaller, the caller
1397  * will just ignore the extra data.)
1398  */
1400  "salt length greater than SHA256 digest length");
1401 
1402  pg_sha256_init(&ctx);
1403  pg_sha256_update(&ctx, (uint8 *) username, strlen(username));
1404  pg_sha256_update(&ctx, (uint8 *) mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
1405  pg_sha256_final(&ctx, sha_digest);
1406 
1407  return (char *) sha_digest;
1408 }
#define PG_SHA256_DIGEST_LENGTH
Definition: sha2.h:62
unsigned char uint8
Definition: c.h:356
void pg_sha256_init(pg_sha256_ctx *context)
Definition: sha2.c:268
#define MOCK_AUTH_NONCE_LEN
Definition: pg_control.h:28
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:842
#define SCRAM_DEFAULT_SALT_LEN
Definition: scram-common.h:40
void pg_sha256_update(pg_sha256_ctx *context, const uint8 *data, size_t len)
Definition: sha2.c:465
static char * username
Definition: initdb.c:133
char * GetMockAuthenticationNonce(void)
Definition: xlog.c:4812
void pg_sha256_final(pg_sha256_ctx *context, uint8 *digest)
Definition: sha2.c:566

◆ scram_verify_plain_password()

bool scram_verify_plain_password ( const char *  username,
const char *  password,
const char *  verifier 
)

Definition at line 488 of file auth-scram.c.

References ereport, errmsg(), LOG, palloc(), parse_scram_verifier(), pfree(), pg_b64_dec_len(), pg_b64_decode(), pg_saslprep(), SASLPREP_SUCCESS, SCRAM_KEY_LEN, scram_SaltedPassword(), and scram_ServerKey().

Referenced by plain_crypt_verify().

490 {
491  char *encoded_salt;
492  char *salt;
493  int saltlen;
494  int iterations;
495  uint8 salted_password[SCRAM_KEY_LEN];
496  uint8 stored_key[SCRAM_KEY_LEN];
497  uint8 server_key[SCRAM_KEY_LEN];
498  uint8 computed_key[SCRAM_KEY_LEN];
499  char *prep_password;
500  pg_saslprep_rc rc;
501 
502  if (!parse_scram_verifier(verifier, &iterations, &encoded_salt,
503  stored_key, server_key))
504  {
505  /*
506  * The password looked like a SCRAM verifier, but could not be parsed.
507  */
508  ereport(LOG,
509  (errmsg("invalid SCRAM verifier for user \"%s\"", username)));
510  return false;
511  }
512 
513  saltlen = pg_b64_dec_len(strlen(encoded_salt));
514  salt = palloc(saltlen);
515  saltlen = pg_b64_decode(encoded_salt, strlen(encoded_salt), salt,
516  saltlen);
517  if (saltlen < 0)
518  {
519  ereport(LOG,
520  (errmsg("invalid SCRAM verifier for user \"%s\"", username)));
521  return false;
522  }
523 
524  /* Normalize the password */
525  rc = pg_saslprep(password, &prep_password);
526  if (rc == SASLPREP_SUCCESS)
527  password = prep_password;
528 
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);
532 
533  if (prep_password)
534  pfree(prep_password);
535 
536  /*
537  * Compare the verifier's Server Key with the one computed from the
538  * user-supplied password.
539  */
540  return memcmp(computed_key, server_key, SCRAM_KEY_LEN) == 0;
541 }
static char password[100]
Definition: streamutil.c:55
unsigned char uint8
Definition: c.h:356
void scram_SaltedPassword(const char *password, const char *salt, int saltlen, int iterations, uint8 *result)
Definition: scram-common.c:104
pg_saslprep_rc pg_saslprep(const char *input, char **output)
Definition: saslprep.c:1071
#define LOG
Definition: elog.h:26
int pg_b64_dec_len(int srclen)
Definition: base64.c:239
void scram_ServerKey(const uint8 *salted_password, uint8 *result)
Definition: scram-common.c:173
pg_saslprep_rc
Definition: saslprep.h:20
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ereport(elevel, rest)
Definition: elog.h:141
int pg_b64_decode(const char *src, int len, char *dst, int dstlen)
Definition: base64.c:116
static char * username
Definition: initdb.c:133
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:784
bool parse_scram_verifier(const char *verifier, int *iterations, char **salt, uint8 *stored_key, uint8 *server_key)
Definition: auth-scram.c:556
#define SCRAM_KEY_LEN
Definition: scram-common.h:23

◆ verify_client_proof()

static bool verify_client_proof ( scram_state state)
static

Definition at line 1083 of file auth-scram.c.

References scram_state::client_final_message_without_proof, scram_state::client_first_message_bare, scram_state::ClientProof, i, scram_H(), scram_HMAC_final(), scram_HMAC_init(), scram_HMAC_update(), SCRAM_KEY_LEN, scram_state::server_first_message, and scram_state::StoredKey.

Referenced by pg_be_scram_exchange().

1084 {
1085  uint8 ClientSignature[SCRAM_KEY_LEN];
1086  uint8 ClientKey[SCRAM_KEY_LEN];
1087  uint8 client_StoredKey[SCRAM_KEY_LEN];
1088  scram_HMAC_ctx ctx;
1089  int i;
1090 
1091  /* calculate ClientSignature */
1092  scram_HMAC_init(&ctx, state->StoredKey, SCRAM_KEY_LEN);
1093  scram_HMAC_update(&ctx,
1095  strlen(state->client_first_message_bare));
1096  scram_HMAC_update(&ctx, ",", 1);
1097  scram_HMAC_update(&ctx,
1098  state->server_first_message,
1099  strlen(state->server_first_message));
1100  scram_HMAC_update(&ctx, ",", 1);
1101  scram_HMAC_update(&ctx,
1103  strlen(state->client_final_message_without_proof));
1104  scram_HMAC_final(ClientSignature, &ctx);
1105 
1106  /* Extract the ClientKey that the client calculated from the proof */
1107  for (i = 0; i < SCRAM_KEY_LEN; i++)
1108  ClientKey[i] = state->ClientProof[i] ^ ClientSignature[i];
1109 
1110  /* Hash it one more time, and compare with StoredKey */
1111  scram_H(ClientKey, SCRAM_KEY_LEN, client_StoredKey);
1112 
1113  if (memcmp(client_StoredKey, state->StoredKey, SCRAM_KEY_LEN) != 0)
1114  return false;
1115 
1116  return true;
1117 }
void scram_H(const uint8 *input, int len, uint8 *result)
Definition: scram-common.c:147
uint8 StoredKey[SCRAM_KEY_LEN]
Definition: auth-scram.c:130
unsigned char uint8
Definition: c.h:356
char ClientProof[SCRAM_KEY_LEN]
Definition: auth-scram.c:142
char * client_final_message_without_proof
Definition: auth-scram.c:140
char * server_first_message
Definition: auth-scram.c:145
void scram_HMAC_final(uint8 *result, scram_HMAC_ctx *ctx)
Definition: scram-common.c:85
void scram_HMAC_init(scram_HMAC_ctx *ctx, const uint8 *key, int keylen)
Definition: scram-common.c:35
void scram_HMAC_update(scram_HMAC_ctx *ctx, const char *str, int slen)
Definition: scram-common.c:75
int i
#define SCRAM_KEY_LEN
Definition: scram-common.h:23
char * client_first_message_bare
Definition: auth-scram.c:135

◆ verify_final_nonce()

static bool verify_final_nonce ( scram_state state)
static

Definition at line 1062 of file auth-scram.c.

References scram_state::client_final_nonce, scram_state::client_nonce, and scram_state::server_nonce.

Referenced by pg_be_scram_exchange().

1063 {
1064  int client_nonce_len = strlen(state->client_nonce);
1065  int server_nonce_len = strlen(state->server_nonce);
1066  int final_nonce_len = strlen(state->client_final_nonce);
1067 
1068  if (final_nonce_len != client_nonce_len + server_nonce_len)
1069  return false;
1070  if (memcmp(state->client_final_nonce, state->client_nonce, client_nonce_len) != 0)
1071  return false;
1072  if (memcmp(state->client_final_nonce + client_nonce_len, state->server_nonce, server_nonce_len) != 0)
1073  return false;
1074 
1075  return true;
1076 }
char * client_nonce
Definition: auth-scram.c:137
char * client_final_nonce
Definition: auth-scram.c:141
char * server_nonce
Definition: auth-scram.c:146