PostgreSQL Source Code  git master
fe-auth.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <fcntl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netdb.h>
#include <pwd.h>
#include "common/md5.h"
#include "libpq-fe.h"
#include "libpq/scram.h"
#include "fe-auth.h"
Include dependency graph for fe-auth.c:

Go to the source code of this file.

Macros

#define MAX_ALGORITHM_NAME_LEN   50
 

Functions

static int pg_SASL_init (PGconn *conn, int payloadlen)
 
static int pg_SASL_continue (PGconn *conn, int payloadlen, bool final)
 
static int pg_local_sendauth (PGconn *conn)
 
static int pg_password_sendauth (PGconn *conn, const char *password, AuthRequest areq)
 
int pg_fe_sendauth (AuthRequest areq, int payloadlen, PGconn *conn)
 
char * pg_fe_getauthname (PQExpBuffer errorMessage)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
char * PQencryptPasswordConn (PGconn *conn, const char *passwd, const char *user, const char *algorithm)
 

Macro Definition Documentation

◆ MAX_ALGORITHM_NAME_LEN

#define MAX_ALGORITHM_NAME_LEN   50

Referenced by PQencryptPasswordConn().

Function Documentation

◆ pg_fe_getauthname()

char* pg_fe_getauthname ( PQExpBuffer  errorMessage)

Definition at line 1058 of file fe-auth.c.

References libpq_gettext, name, pglock_thread, pgunlock_thread, pqGetpwuid(), pqStrerror(), printfPQExpBuffer(), and username.

Referenced by connectOptions2(), and conninfo_add_defaults().

1059 {
1060  char *result = NULL;
1061  const char *name = NULL;
1062 
1063 #ifdef WIN32
1064  /* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1065  char username[256 + 1];
1066  DWORD namesize = sizeof(username);
1067 #else
1068  uid_t user_id = geteuid();
1069  char pwdbuf[BUFSIZ];
1070  struct passwd pwdstr;
1071  struct passwd *pw = NULL;
1072  int pwerr;
1073 #endif
1074 
1075  /*
1076  * Some users are using configure --enable-thread-safety-force, so we
1077  * might as well do the locking within our library to protect
1078  * pqGetpwuid(). In fact, application developers can use getpwuid() in
1079  * their application if they use the locking call we provide, or install
1080  * their own locking function using PQregisterThreadLock().
1081  */
1082  pglock_thread();
1083 
1084 #ifdef WIN32
1085  if (GetUserName(username, &namesize))
1086  name = username;
1087  else if (errorMessage)
1088  printfPQExpBuffer(errorMessage,
1089  libpq_gettext("user name lookup failure: error code %lu\n"),
1090  GetLastError());
1091 #else
1092  pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1093  if (pw != NULL)
1094  name = pw->pw_name;
1095  else if (errorMessage)
1096  {
1097  if (pwerr != 0)
1098  printfPQExpBuffer(errorMessage,
1099  libpq_gettext("could not look up local user ID %d: %s\n"),
1100  (int) user_id,
1101  pqStrerror(pwerr, pwdbuf, sizeof(pwdbuf)));
1102  else
1103  printfPQExpBuffer(errorMessage,
1104  libpq_gettext("local user with ID %d does not exist\n"),
1105  (int) user_id);
1106  }
1107 #endif
1108 
1109  if (name)
1110  {
1111  result = strdup(name);
1112  if (result == NULL && errorMessage)
1113  printfPQExpBuffer(errorMessage,
1114  libpq_gettext("out of memory\n"));
1115  }
1116 
1117  pgunlock_thread();
1118 
1119  return result;
1120 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
#define pglock_thread()
Definition: libpq-int.h:563
static char * username
Definition: initdb.c:132
int uid_t
Definition: win32_port.h:241
const char * name
Definition: encode.c:521
int pqGetpwuid(uid_t uid, struct passwd *resultbuf, char *buffer, size_t buflen, struct passwd **result)
Definition: thread.c:95
#define pgunlock_thread()
Definition: libpq-int.h:564
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ pg_fe_sendauth()

int pg_fe_sendauth ( AuthRequest  areq,
int  payloadlen,
PGconn conn 
)

Definition at line 851 of file fe-auth.c.

References AUTH_REQ_CRYPT, AUTH_REQ_GSS, AUTH_REQ_GSS_CONT, AUTH_REQ_KRB4, AUTH_REQ_KRB5, AUTH_REQ_MD5, AUTH_REQ_OK, AUTH_REQ_PASSWORD, AUTH_REQ_SASL, AUTH_REQ_SASL_CONT, AUTH_REQ_SASL_FIN, AUTH_REQ_SCM_CREDS, AUTH_REQ_SSPI, pg_conn::connhost, pg_conn::errorMessage, PQExpBufferData::len, libpq_gettext, password, pg_conn_host::password, pg_conn::password_needed, pg_local_sendauth(), pg_password_sendauth(), pg_SASL_continue(), pg_SASL_init(), pg_strcasecmp(), pglock_thread, pg_conn::pgpass, pgunlock_thread, PQnoPasswordSupplied, printfPQExpBuffer(), pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and pg_conn::whichhost.

Referenced by PQconnectPoll().

852 {
853  switch (areq)
854  {
855  case AUTH_REQ_OK:
856  break;
857 
858  case AUTH_REQ_KRB4:
860  libpq_gettext("Kerberos 4 authentication not supported\n"));
861  return STATUS_ERROR;
862 
863  case AUTH_REQ_KRB5:
865  libpq_gettext("Kerberos 5 authentication not supported\n"));
866  return STATUS_ERROR;
867 
868 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
869  case AUTH_REQ_GSS:
870 #if !defined(ENABLE_SSPI)
871  /* no native SSPI, so use GSSAPI library for it */
872  case AUTH_REQ_SSPI:
873 #endif
874  {
875  int r;
876 
877  pglock_thread();
878 
879  /*
880  * If we have both GSS and SSPI support compiled in, use SSPI
881  * support by default. This is overridable by a connection
882  * string parameter. Note that when using SSPI we still leave
883  * the negotiate parameter off, since we want SSPI to use the
884  * GSSAPI kerberos protocol. For actual SSPI negotiate
885  * protocol, we use AUTH_REQ_SSPI.
886  */
887 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
888  if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
889  r = pg_GSS_startup(conn, payloadlen);
890  else
891  r = pg_SSPI_startup(conn, 0, payloadlen);
892 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
893  r = pg_GSS_startup(conn, payloadlen);
894 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
895  r = pg_SSPI_startup(conn, 0, payloadlen);
896 #endif
897  if (r != STATUS_OK)
898  {
899  /* Error message already filled in. */
900  pgunlock_thread();
901  return STATUS_ERROR;
902  }
903  pgunlock_thread();
904  }
905  break;
906 
907  case AUTH_REQ_GSS_CONT:
908  {
909  int r;
910 
911  pglock_thread();
912 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
913  if (conn->usesspi)
914  r = pg_SSPI_continue(conn, payloadlen);
915  else
916  r = pg_GSS_continue(conn, payloadlen);
917 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
918  r = pg_GSS_continue(conn, payloadlen);
919 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
920  r = pg_SSPI_continue(conn, payloadlen);
921 #endif
922  if (r != STATUS_OK)
923  {
924  /* Error message already filled in. */
925  pgunlock_thread();
926  return STATUS_ERROR;
927  }
928  pgunlock_thread();
929  }
930  break;
931 #else /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
932  /* No GSSAPI *or* SSPI support */
933  case AUTH_REQ_GSS:
934  case AUTH_REQ_GSS_CONT:
936  libpq_gettext("GSSAPI authentication not supported\n"));
937  return STATUS_ERROR;
938 #endif /* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
939 
940 #ifdef ENABLE_SSPI
941  case AUTH_REQ_SSPI:
942 
943  /*
944  * SSPI has it's own startup message so libpq can decide which
945  * method to use. Indicate to pg_SSPI_startup that we want SSPI
946  * negotiation instead of Kerberos.
947  */
948  pglock_thread();
949  if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
950  {
951  /* Error message already filled in. */
952  pgunlock_thread();
953  return STATUS_ERROR;
954  }
955  pgunlock_thread();
956  break;
957 #else
958 
959  /*
960  * No SSPI support. However, if we have GSSAPI but not SSPI
961  * support, AUTH_REQ_SSPI will have been handled in the codepath
962  * for AUTH_REQ_GSSAPI above, so don't duplicate the case label in
963  * that case.
964  */
965 #if !defined(ENABLE_GSS)
966  case AUTH_REQ_SSPI:
968  libpq_gettext("SSPI authentication not supported\n"));
969  return STATUS_ERROR;
970 #endif /* !define(ENABLE_GSSAPI) */
971 #endif /* ENABLE_SSPI */
972 
973 
974  case AUTH_REQ_CRYPT:
976  libpq_gettext("Crypt authentication not supported\n"));
977  return STATUS_ERROR;
978 
979  case AUTH_REQ_MD5:
980  case AUTH_REQ_PASSWORD:
981  {
982  char *password;
983 
984  conn->password_needed = true;
985  password = conn->connhost[conn->whichhost].password;
986  if (password == NULL)
987  password = conn->pgpass;
988  if (password == NULL || password[0] == '\0')
989  {
992  return STATUS_ERROR;
993  }
994  if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
995  {
997  "fe_sendauth: error sending password authentication\n");
998  return STATUS_ERROR;
999  }
1000  break;
1001  }
1002 
1003  case AUTH_REQ_SASL:
1004 
1005  /*
1006  * The request contains the name (as assigned by IANA) of the
1007  * authentication mechanism.
1008  */
1009  if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1010  {
1011  /* pg_SASL_init already set the error message */
1012  return STATUS_ERROR;
1013  }
1014  break;
1015 
1016  case AUTH_REQ_SASL_CONT:
1017  case AUTH_REQ_SASL_FIN:
1018  if (conn->sasl_state == NULL)
1019  {
1021  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1022  return STATUS_ERROR;
1023  }
1024  if (pg_SASL_continue(conn, payloadlen,
1025  (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1026  {
1027  /* Use error message, if set already */
1028  if (conn->errorMessage.len == 0)
1030  "fe_sendauth: error in SASL authentication\n");
1031  return STATUS_ERROR;
1032  }
1033  break;
1034 
1035  case AUTH_REQ_SCM_CREDS:
1036  if (pg_local_sendauth(conn) != STATUS_OK)
1037  return STATUS_ERROR;
1038  break;
1039 
1040  default:
1042  libpq_gettext("authentication method %u not supported\n"), areq);
1043  return STATUS_ERROR;
1044  }
1045 
1046  return STATUS_OK;
1047 }
static char password[100]
Definition: streamutil.c:45
#define AUTH_REQ_SSPI
Definition: pqcomm.h:174
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static int pg_local_sendauth(PGconn *conn)
Definition: fe-auth.c:723
#define AUTH_REQ_SASL_FIN
Definition: pqcomm.h:177
bool password_needed
Definition: libpq-int.h:407
#define AUTH_REQ_OK
Definition: pqcomm.h:165
#define AUTH_REQ_GSS
Definition: pqcomm.h:172
static int pg_SASL_init(PGconn *conn, int payloadlen)
Definition: fe-auth.c:486
static int pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
Definition: fe-auth.c:775
#define STATUS_ERROR
Definition: c.h:954
#define pglock_thread()
Definition: libpq-int.h:563
#define PQnoPasswordSupplied
Definition: libpq-fe.h:512
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
static int pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
Definition: fe-auth.c:653
pg_conn_host * connhost
Definition: libpq-int.h:397
void * sasl_state
Definition: libpq-int.h:454
#define AUTH_REQ_CRYPT
Definition: pqcomm.h:169
#define STATUS_OK
Definition: c.h:953
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define AUTH_REQ_KRB5
Definition: pqcomm.h:167
#define AUTH_REQ_SASL_CONT
Definition: pqcomm.h:176
#define AUTH_REQ_KRB4
Definition: pqcomm.h:166
char * pgpass
Definition: libpq-int.h:344
#define AUTH_REQ_SASL
Definition: pqcomm.h:175
#define AUTH_REQ_GSS_CONT
Definition: pqcomm.h:173
#define pgunlock_thread()
Definition: libpq-int.h:564
int whichhost
Definition: libpq-int.h:396
#define libpq_gettext(x)
Definition: libpq-int.h:685
#define AUTH_REQ_SCM_CREDS
Definition: pqcomm.h:171
char * password
Definition: libpq-int.h:312

◆ pg_local_sendauth()

static int pg_local_sendauth ( PGconn conn)
static

Definition at line 723 of file fe-auth.c.

References buf, pg_conn::errorMessage, libpq_gettext, pqStrerror(), printfPQExpBuffer(), pg_conn::sock, STATUS_ERROR, and STATUS_OK.

Referenced by pg_fe_sendauth().

724 {
725 #ifdef HAVE_STRUCT_CMSGCRED
726  char buf;
727  struct iovec iov;
728  struct msghdr msg;
729  struct cmsghdr *cmsg;
730  union
731  {
732  struct cmsghdr hdr;
733  unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
734  } cmsgbuf;
735 
736  /*
737  * The backend doesn't care what we send here, but it wants exactly one
738  * character to force recvmsg() to block and wait for us.
739  */
740  buf = '\0';
741  iov.iov_base = &buf;
742  iov.iov_len = 1;
743 
744  memset(&msg, 0, sizeof(msg));
745  msg.msg_iov = &iov;
746  msg.msg_iovlen = 1;
747 
748  /* We must set up a message that will be filled in by kernel */
749  memset(&cmsgbuf, 0, sizeof(cmsgbuf));
750  msg.msg_control = &cmsgbuf.buf;
751  msg.msg_controllen = sizeof(cmsgbuf.buf);
752  cmsg = CMSG_FIRSTHDR(&msg);
753  cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
754  cmsg->cmsg_level = SOL_SOCKET;
755  cmsg->cmsg_type = SCM_CREDS;
756 
757  if (sendmsg(conn->sock, &msg, 0) == -1)
758  {
759  char sebuf[256];
760 
762  "pg_local_sendauth: sendmsg: %s\n",
763  pqStrerror(errno, sebuf, sizeof(sebuf)));
764  return STATUS_ERROR;
765  }
766  return STATUS_OK;
767 #else
769  libpq_gettext("SCM_CRED authentication method not supported\n"));
770  return STATUS_ERROR;
771 #endif
772 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
char * pqStrerror(int errnum, char *strerrbuf, size_t buflen)
Definition: thread.c:61
#define STATUS_ERROR
Definition: c.h:954
static char * buf
Definition: pg_test_fsync.c:67
#define STATUS_OK
Definition: c.h:953
pgsocket sock
Definition: libpq-int.h:400
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ pg_password_sendauth()

static int pg_password_sendauth ( PGconn conn,
const char *  password,
AuthRequest  areq 
)
static

Definition at line 775 of file fe-auth.c.

References AUTH_REQ_MD5, AUTH_REQ_PASSWORD, pg_conn::errorMessage, free, libpq_gettext, malloc, MD5_PASSWD_LEN, password, pg_md5_encrypt(), PG_PROTOCOL_MAJOR, pg_conn::pguser, pqGetnchar(), pqPacketSend(), printfPQExpBuffer(), pg_conn::pversion, and STATUS_ERROR.

Referenced by pg_fe_sendauth().

776 {
777  int ret;
778  char *crypt_pwd = NULL;
779  const char *pwd_to_send;
780  char md5Salt[4];
781 
782  /* Read the salt from the AuthenticationMD5 message. */
783  if (areq == AUTH_REQ_MD5)
784  {
785  if (pqGetnchar(md5Salt, 4, conn))
786  return STATUS_ERROR; /* shouldn't happen */
787  }
788 
789  /* Encrypt the password if needed. */
790 
791  switch (areq)
792  {
793  case AUTH_REQ_MD5:
794  {
795  char *crypt_pwd2;
796 
797  /* Allocate enough space for two MD5 hashes */
798  crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
799  if (!crypt_pwd)
800  {
802  libpq_gettext("out of memory\n"));
803  return STATUS_ERROR;
804  }
805 
806  crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
807  if (!pg_md5_encrypt(password, conn->pguser,
808  strlen(conn->pguser), crypt_pwd2))
809  {
810  free(crypt_pwd);
811  return STATUS_ERROR;
812  }
813  if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
814  4, crypt_pwd))
815  {
816  free(crypt_pwd);
817  return STATUS_ERROR;
818  }
819 
820  pwd_to_send = crypt_pwd;
821  break;
822  }
823  case AUTH_REQ_PASSWORD:
824  pwd_to_send = password;
825  break;
826  default:
827  return STATUS_ERROR;
828  }
829  /* Packet has a message type as of protocol 3.0 */
830  if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
831  ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
832  else
833  ret = pqPacketSend(conn, 0, pwd_to_send, strlen(pwd_to_send) + 1);
834  if (crypt_pwd)
835  free(crypt_pwd);
836  return ret;
837 }
static char password[100]
Definition: streamutil.c:45
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define STATUS_ERROR
Definition: c.h:954
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:195
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
#define AUTH_REQ_MD5
Definition: pqcomm.h:170
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
char * pguser
Definition: libpq-int.h:343
#define AUTH_REQ_PASSWORD
Definition: pqcomm.h:168
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
ProtocolVersion pversion
Definition: libpq-int.h:404
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:3974
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ pg_SASL_continue()

static int pg_SASL_continue ( PGconn conn,
int  payloadlen,
bool  final 
)
static

Definition at line 653 of file fe-auth.c.

References pg_conn::errorMessage, free, libpq_gettext, malloc, output(), pg_fe_scram_exchange(), pqGetnchar(), pqPacketSend(), printfPQExpBuffer(), pg_conn::sasl_state, STATUS_ERROR, STATUS_OK, and success.

Referenced by pg_fe_sendauth().

654 {
655  char *output;
656  int outputlen;
657  bool done;
658  bool success;
659  int res;
660  char *challenge;
661 
662  /* Read the SASL challenge from the AuthenticationSASLContinue message. */
663  challenge = malloc(payloadlen + 1);
664  if (!challenge)
665  {
667  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
668  payloadlen);
669  return STATUS_ERROR;
670  }
671 
672  if (pqGetnchar(challenge, payloadlen, conn))
673  {
674  free(challenge);
675  return STATUS_ERROR;
676  }
677  /* For safety and convenience, ensure the buffer is NULL-terminated. */
678  challenge[payloadlen] = '\0';
679 
681  challenge, payloadlen,
682  &output, &outputlen,
683  &done, &success, &conn->errorMessage);
684  free(challenge); /* don't need the input anymore */
685 
686  if (final && !done)
687  {
688  if (outputlen != 0)
689  free(output);
690 
692  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
693  return STATUS_ERROR;
694  }
695  if (outputlen != 0)
696  {
697  /*
698  * Send the SASL response to the server.
699  */
700  res = pqPacketSend(conn, 'p', output, outputlen);
701  free(output);
702 
703  if (res != STATUS_OK)
704  return STATUS_ERROR;
705  }
706 
707  if (done && !success)
708  return STATUS_ERROR;
709 
710  return STATUS_OK;
711 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static void output(uint64 loop_count)
#define STATUS_ERROR
Definition: c.h:954
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:195
#define malloc(a)
Definition: header.h:50
void pg_fe_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success, PQExpBuffer errorMessage)
static bool success
Definition: pg_basebackup.c:99
void * sasl_state
Definition: libpq-int.h:454
#define STATUS_OK
Definition: c.h:953
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:3974
#define libpq_gettext(x)
Definition: libpq-int.h:685

◆ pg_SASL_init()

static int pg_SASL_init ( PGconn conn,
int  payloadlen 
)
static

Definition at line 486 of file fe-auth.c.

References pg_conn::connhost, PQExpBufferData::data, error(), pg_conn::errorMessage, free, initPQExpBuffer(), libpq_gettext, password, pg_conn_host::password, pg_conn::password_needed, pg_fe_scram_exchange(), pg_fe_scram_init(), pg_conn::pgpass, pgtls_get_finished(), pg_conn::pguser, PQExpBufferDataBroken, pqFlush(), pqGets(), PQnoPasswordSupplied, pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqPuts(), printfPQExpBuffer(), pg_conn::sasl_state, SCRAM_SHA256_NAME, SCRAM_SHA256_PLUS_NAME, pg_conn::ssl_in_use, STATUS_ERROR, STATUS_OK, success, termPQExpBuffer(), and pg_conn::whichhost.

Referenced by pg_fe_sendauth().

487 {
488  char *initialresponse = NULL;
489  int initialresponselen;
490  bool done;
491  bool success;
492  const char *selected_mechanism;
493  PQExpBufferData mechanism_buf;
494  char *tls_finished = NULL;
495  size_t tls_finished_len = 0;
496  char *password;
497 
498  initPQExpBuffer(&mechanism_buf);
499 
500  if (conn->sasl_state)
501  {
503  libpq_gettext("duplicate SASL authentication request\n"));
504  goto error;
505  }
506 
507  /*
508  * Parse the list of SASL authentication mechanisms in the
509  * AuthenticationSASL message, and select the best mechanism that we
510  * support. SCRAM-SHA-256-PLUS and SCRAM-SHA-256 are the only ones
511  * supported at the moment, listed by order of decreasing importance.
512  */
513  selected_mechanism = NULL;
514  for (;;)
515  {
516  if (pqGets(&mechanism_buf, conn))
517  {
519  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
520  goto error;
521  }
522  if (PQExpBufferDataBroken(mechanism_buf))
523  goto oom_error;
524 
525  /* An empty string indicates end of list */
526  if (mechanism_buf.data[0] == '\0')
527  break;
528 
529  /*
530  * Select the mechanism to use. Pick SCRAM-SHA-256-PLUS over anything
531  * else. Pick SCRAM-SHA-256 if nothing else has already been picked.
532  * If we add more mechanisms, a more refined priority mechanism might
533  * become necessary.
534  */
535  if (conn->ssl_in_use &&
536  strcmp(mechanism_buf.data, SCRAM_SHA256_PLUS_NAME) == 0)
537  selected_mechanism = SCRAM_SHA256_PLUS_NAME;
538  else if (strcmp(mechanism_buf.data, SCRAM_SHA256_NAME) == 0 &&
539  !selected_mechanism)
540  selected_mechanism = SCRAM_SHA256_NAME;
541  }
542 
543  if (!selected_mechanism)
544  {
546  libpq_gettext("none of the server's SASL authentication mechanisms are supported\n"));
547  goto error;
548  }
549 
550  /*
551  * Now that the SASL mechanism has been chosen for the exchange,
552  * initialize its state information.
553  */
554 
555  /*
556  * First, select the password to use for the exchange, complaining if
557  * there isn't one. Currently, all supported SASL mechanisms require a
558  * password, so we can just go ahead here without further distinction.
559  */
560  conn->password_needed = true;
561  password = conn->connhost[conn->whichhost].password;
562  if (password == NULL)
563  password = conn->pgpass;
564  if (password == NULL || password[0] == '\0')
565  {
568  goto error;
569  }
570 
571 #ifdef USE_SSL
572  /*
573  * Get data for channel binding.
574  */
575  if (strcmp(selected_mechanism, SCRAM_SHA256_PLUS_NAME) == 0)
576  {
577  tls_finished = pgtls_get_finished(conn, &tls_finished_len);
578  if (tls_finished == NULL)
579  goto oom_error;
580  }
581 #endif
582 
583  /*
584  * Initialize the SASL state information with all the information
585  * gathered during the initial exchange.
586  *
587  * Note: Only tls-unique is supported for the moment.
588  */
589  conn->sasl_state = pg_fe_scram_init(conn->pguser,
590  password,
591  conn->ssl_in_use,
592  selected_mechanism,
593  tls_finished,
594  tls_finished_len);
595  if (!conn->sasl_state)
596  goto oom_error;
597 
598  /* Get the mechanism-specific Initial Client Response, if any */
600  NULL, -1,
601  &initialresponse, &initialresponselen,
602  &done, &success, &conn->errorMessage);
603 
604  if (done && !success)
605  goto error;
606 
607  /*
608  * Build a SASLInitialResponse message, and send it.
609  */
610  if (pqPutMsgStart('p', true, conn))
611  goto error;
612  if (pqPuts(selected_mechanism, conn))
613  goto error;
614  if (initialresponse)
615  {
616  if (pqPutInt(initialresponselen, 4, conn))
617  goto error;
618  if (pqPutnchar(initialresponse, initialresponselen, conn))
619  goto error;
620  }
621  if (pqPutMsgEnd(conn))
622  goto error;
623  if (pqFlush(conn))
624  goto error;
625 
626  termPQExpBuffer(&mechanism_buf);
627  if (initialresponse)
628  free(initialresponse);
629 
630  return STATUS_OK;
631 
632 error:
633  termPQExpBuffer(&mechanism_buf);
634  if (initialresponse)
635  free(initialresponse);
636  return STATUS_ERROR;
637 
638 oom_error:
639  termPQExpBuffer(&mechanism_buf);
640  if (initialresponse)
641  free(initialresponse);
643  libpq_gettext("out of memory\n"));
644  return STATUS_ERROR;
645 }
int pqFlush(PGconn *conn)
Definition: fe-misc.c:961
static char password[100]
Definition: streamutil.c:45
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
static void error(void)
Definition: sql-dyntest.c:147
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:163
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
bool password_needed
Definition: libpq-int.h:407
void * pg_fe_scram_init(const char *username, const char *password, bool ssl_in_use, const char *sasl_mechanism, char *tls_finished_message, size_t tls_finished_len)
Definition: fe-auth-scram.c:93
int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
Definition: fe-misc.c:519
#define STATUS_ERROR
Definition: c.h:954
#define PQnoPasswordSupplied
Definition: libpq-fe.h:512
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:307
void pg_fe_scram_exchange(void *opaq, char *input, int inputlen, char **output, int *outputlen, bool *done, bool *success, PQExpBuffer errorMessage)
pg_conn_host * connhost
Definition: libpq-int.h:397
static bool success
Definition: pg_basebackup.c:99
bool ssl_in_use
Definition: libpq-int.h:457
void * sasl_state
Definition: libpq-int.h:454
#define SCRAM_SHA256_NAME
Definition: scram.h:17
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:179
#define STATUS_OK
Definition: c.h:953
char * pguser
Definition: libpq-int.h:343
PQExpBufferData errorMessage
Definition: libpq-int.h:493
#define free(a)
Definition: header.h:65
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:246
char * pgpass
Definition: libpq-int.h:344
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:587
char * pgtls_get_finished(PGconn *conn, size_t *len)
#define SCRAM_SHA256_PLUS_NAME
Definition: scram.h:18
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
int whichhost
Definition: libpq-int.h:396
#define libpq_gettext(x)
Definition: libpq-int.h:685
char * password
Definition: libpq-int.h:312

◆ PQencryptPassword()

char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

Definition at line 1132 of file fe-auth.c.

References free, malloc, MD5_PASSWD_LEN, and pg_md5_encrypt().

1133 {
1134  char *crypt_pwd;
1135 
1136  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1137  if (!crypt_pwd)
1138  return NULL;
1139 
1140  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1141  {
1142  free(crypt_pwd);
1143  return NULL;
1144  }
1145 
1146  return crypt_pwd;
1147 }
#define malloc(a)
Definition: header.h:50
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
static char * user
Definition: pg_regress.c:93

◆ PQencryptPasswordConn()

char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

Definition at line 1174 of file fe-auth.c.

References pg_conn::errorMessage, free, libpq_gettext, malloc, MAX_ALGORITHM_NAME_LEN, MD5_PASSWD_LEN, pg_fe_scram_build_verifier(), pg_md5_encrypt(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQnfields(), PQntuples(), PQresultStatus(), printfPQExpBuffer(), and val.

Referenced by exec_command_password(), and main().

1176 {
1177 #define MAX_ALGORITHM_NAME_LEN 50
1178  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1179  char *crypt_pwd = NULL;
1180 
1181  if (!conn)
1182  return NULL;
1183 
1184  /* If no algorithm was given, ask the server. */
1185  if (algorithm == NULL)
1186  {
1187  PGresult *res;
1188  char *val;
1189 
1190  res = PQexec(conn, "show password_encryption");
1191  if (res == NULL)
1192  {
1193  /* PQexec() should've set conn->errorMessage already */
1194  return NULL;
1195  }
1196  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1197  {
1198  /* PQexec() should've set conn->errorMessage already */
1199  PQclear(res);
1200  return NULL;
1201  }
1202  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1203  {
1204  PQclear(res);
1206  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1207  return NULL;
1208  }
1209  val = PQgetvalue(res, 0, 0);
1210 
1211  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1212  {
1213  PQclear(res);
1215  libpq_gettext("password_encryption value too long\n"));
1216  return NULL;
1217  }
1218  strcpy(algobuf, val);
1219  PQclear(res);
1220 
1221  algorithm = algobuf;
1222  }
1223 
1224  /*
1225  * Also accept "on" and "off" as aliases for "md5", because
1226  * password_encryption was a boolean before PostgreSQL 10. We refuse to
1227  * send the password in plaintext even if it was "off".
1228  */
1229  if (strcmp(algorithm, "on") == 0 ||
1230  strcmp(algorithm, "off") == 0)
1231  algorithm = "md5";
1232 
1233  /*
1234  * Ok, now we know what algorithm to use
1235  */
1236  if (strcmp(algorithm, "scram-sha-256") == 0)
1237  {
1238  crypt_pwd = pg_fe_scram_build_verifier(passwd);
1239  }
1240  else if (strcmp(algorithm, "md5") == 0)
1241  {
1242  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1243  if (crypt_pwd)
1244  {
1245  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1246  {
1247  free(crypt_pwd);
1248  crypt_pwd = NULL;
1249  }
1250  }
1251  }
1252  else
1253  {
1255  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1256  algorithm);
1257  return NULL;
1258  }
1259 
1260  if (!crypt_pwd)
1262  libpq_gettext("out of memory\n"));
1263 
1264  return crypt_pwd;
1265 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2732
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3118
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2724
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
#define malloc(a)
Definition: header.h:50
#define MAX_ALGORITHM_NAME_LEN
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf)
Definition: md5.c:323
PQExpBufferData errorMessage
Definition: libpq-int.h:493
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define MD5_PASSWD_LEN
Definition: md5.h:19
#define free(a)
Definition: header.h:65
char * pg_fe_scram_build_verifier(const char *password)
static char * user
Definition: pg_regress.c:93
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897
long val
Definition: informix.c:689
#define libpq_gettext(x)
Definition: libpq-int.h:685