PageRenderTime 76ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/src/backend/libpq/auth.c

https://github.com/bbt123/postgres
C | 2570 lines | 1701 code | 327 blank | 542 comment | 326 complexity | a4bc06690bf58daab7715edae6faf4ca MD5 | raw file
Possible License(s): AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /*-------------------------------------------------------------------------
  2. *
  3. * auth.c
  4. * Routines to handle network authentication
  5. *
  6. * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
  7. * Portions Copyright (c) 1994, Regents of the University of California
  8. *
  9. *
  10. * IDENTIFICATION
  11. * src/backend/libpq/auth.c
  12. *
  13. *-------------------------------------------------------------------------
  14. */
  15. #include "postgres.h"
  16. #include <sys/param.h>
  17. #include <sys/socket.h>
  18. #include <netinet/in.h>
  19. #include <arpa/inet.h>
  20. #include <unistd.h>
  21. #include "libpq/auth.h"
  22. #include "libpq/crypt.h"
  23. #include "libpq/ip.h"
  24. #include "libpq/libpq.h"
  25. #include "libpq/pqformat.h"
  26. #include "libpq/md5.h"
  27. #include "miscadmin.h"
  28. #include "replication/walsender.h"
  29. #include "storage/ipc.h"
  30. /*----------------------------------------------------------------
  31. * Global authentication functions
  32. *----------------------------------------------------------------
  33. */
  34. static void sendAuthRequest(Port *port, AuthRequest areq);
  35. static void auth_failed(Port *port, int status, char *logdetail);
  36. static char *recv_password_packet(Port *port);
  37. static int recv_and_check_password_packet(Port *port, char **logdetail);
  38. /*----------------------------------------------------------------
  39. * Ident authentication
  40. *----------------------------------------------------------------
  41. */
  42. /* Max size of username ident server can return */
  43. #define IDENT_USERNAME_MAX 512
  44. /* Standard TCP port number for Ident service. Assigned by IANA */
  45. #define IDENT_PORT 113
  46. static int ident_inet(hbaPort *port);
  47. #ifdef HAVE_UNIX_SOCKETS
  48. static int auth_peer(hbaPort *port);
  49. #endif
  50. /*----------------------------------------------------------------
  51. * PAM authentication
  52. *----------------------------------------------------------------
  53. */
  54. #ifdef USE_PAM
  55. #ifdef HAVE_PAM_PAM_APPL_H
  56. #include <pam/pam_appl.h>
  57. #endif
  58. #ifdef HAVE_SECURITY_PAM_APPL_H
  59. #include <security/pam_appl.h>
  60. #endif
  61. #define PGSQL_PAM_SERVICE "postgresql" /* Service name passed to PAM */
  62. static int CheckPAMAuth(Port *port, char *user, char *password);
  63. static int pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
  64. struct pam_response ** resp, void *appdata_ptr);
  65. static struct pam_conv pam_passw_conv = {
  66. &pam_passwd_conv_proc,
  67. NULL
  68. };
  69. static char *pam_passwd = NULL; /* Workaround for Solaris 2.6 brokenness */
  70. static Port *pam_port_cludge; /* Workaround for passing "Port *port" into
  71. * pam_passwd_conv_proc */
  72. #endif /* USE_PAM */
  73. /*----------------------------------------------------------------
  74. * LDAP authentication
  75. *----------------------------------------------------------------
  76. */
  77. #ifdef USE_LDAP
  78. #ifndef WIN32
  79. /* We use a deprecated function to keep the codepath the same as win32. */
  80. #define LDAP_DEPRECATED 1
  81. #include <ldap.h>
  82. #else
  83. #include <winldap.h>
  84. /* Correct header from the Platform SDK */
  85. typedef
  86. ULONG (*__ldap_start_tls_sA) (
  87. IN PLDAP ExternalHandle,
  88. OUT PULONG ServerReturnValue,
  89. OUT LDAPMessage **result,
  90. IN PLDAPControlA * ServerControls,
  91. IN PLDAPControlA * ClientControls
  92. );
  93. #endif
  94. static int CheckLDAPAuth(Port *port);
  95. #endif /* USE_LDAP */
  96. /*----------------------------------------------------------------
  97. * Cert authentication
  98. *----------------------------------------------------------------
  99. */
  100. #ifdef USE_SSL
  101. static int CheckCertAuth(Port *port);
  102. #endif
  103. /*----------------------------------------------------------------
  104. * Kerberos and GSSAPI GUCs
  105. *----------------------------------------------------------------
  106. */
  107. char *pg_krb_server_keyfile;
  108. bool pg_krb_caseins_users;
  109. /*----------------------------------------------------------------
  110. * GSSAPI Authentication
  111. *----------------------------------------------------------------
  112. */
  113. #ifdef ENABLE_GSS
  114. #if defined(HAVE_GSSAPI_H)
  115. #include <gssapi.h>
  116. #else
  117. #include <gssapi/gssapi.h>
  118. #endif
  119. static int pg_GSS_recvauth(Port *port);
  120. #endif /* ENABLE_GSS */
  121. /*----------------------------------------------------------------
  122. * SSPI Authentication
  123. *----------------------------------------------------------------
  124. */
  125. #ifdef ENABLE_SSPI
  126. typedef SECURITY_STATUS
  127. (WINAPI * QUERY_SECURITY_CONTEXT_TOKEN_FN) (
  128. PCtxtHandle, void **);
  129. static int pg_SSPI_recvauth(Port *port);
  130. #endif
  131. /*----------------------------------------------------------------
  132. * RADIUS Authentication
  133. *----------------------------------------------------------------
  134. */
  135. #ifdef USE_SSL
  136. #include <openssl/rand.h>
  137. #endif
  138. static int CheckRADIUSAuth(Port *port);
  139. /*
  140. * Maximum accepted size of GSS and SSPI authentication tokens.
  141. *
  142. * Kerberos tickets are usually quite small, but the TGTs issued by Windows
  143. * domain controllers include an authorization field known as the Privilege
  144. * Attribute Certificate (PAC), which contains the user's Windows permissions
  145. * (group memberships etc.). The PAC is copied into all tickets obtained on
  146. * the basis of this TGT (even those issued by Unix realms which the Windows
  147. * realm trusts), and can be several kB in size. The maximum token size
  148. * accepted by Windows systems is determined by the MaxAuthToken Windows
  149. * registry setting. Microsoft recommends that it is not set higher than
  150. * 65535 bytes, so that seems like a reasonable limit for us as well.
  151. */
  152. #define PG_MAX_AUTH_TOKEN_LENGTH 65535
  153. /*----------------------------------------------------------------
  154. * Global authentication functions
  155. *----------------------------------------------------------------
  156. */
  157. /*
  158. * This hook allows plugins to get control following client authentication,
  159. * but before the user has been informed about the results. It could be used
  160. * to record login events, insert a delay after failed authentication, etc.
  161. */
  162. ClientAuthentication_hook_type ClientAuthentication_hook = NULL;
  163. /*
  164. * Tell the user the authentication failed, but not (much about) why.
  165. *
  166. * There is a tradeoff here between security concerns and making life
  167. * unnecessarily difficult for legitimate users. We would not, for example,
  168. * want to report the password we were expecting to receive...
  169. * But it seems useful to report the username and authorization method
  170. * in use, and these are items that must be presumed known to an attacker
  171. * anyway.
  172. * Note that many sorts of failure report additional information in the
  173. * postmaster log, which we hope is only readable by good guys. In
  174. * particular, if logdetail isn't NULL, we send that string to the log.
  175. */
  176. static void
  177. auth_failed(Port *port, int status, char *logdetail)
  178. {
  179. const char *errstr;
  180. char *cdetail;
  181. int errcode_return = ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION;
  182. /*
  183. * If we failed due to EOF from client, just quit; there's no point in
  184. * trying to send a message to the client, and not much point in logging
  185. * the failure in the postmaster log. (Logging the failure might be
  186. * desirable, were it not for the fact that libpq closes the connection
  187. * unceremoniously if challenged for a password when it hasn't got one to
  188. * send. We'll get a useless log entry for every psql connection under
  189. * password auth, even if it's perfectly successful, if we log STATUS_EOF
  190. * events.)
  191. */
  192. if (status == STATUS_EOF)
  193. proc_exit(0);
  194. switch (port->hba->auth_method)
  195. {
  196. case uaReject:
  197. case uaImplicitReject:
  198. errstr = gettext_noop("authentication failed for user \"%s\": host rejected");
  199. break;
  200. case uaTrust:
  201. errstr = gettext_noop("\"trust\" authentication failed for user \"%s\"");
  202. break;
  203. case uaIdent:
  204. errstr = gettext_noop("Ident authentication failed for user \"%s\"");
  205. break;
  206. case uaPeer:
  207. errstr = gettext_noop("Peer authentication failed for user \"%s\"");
  208. break;
  209. case uaPassword:
  210. case uaMD5:
  211. errstr = gettext_noop("password authentication failed for user \"%s\"");
  212. /* We use it to indicate if a .pgpass password failed. */
  213. errcode_return = ERRCODE_INVALID_PASSWORD;
  214. break;
  215. case uaGSS:
  216. errstr = gettext_noop("GSSAPI authentication failed for user \"%s\"");
  217. break;
  218. case uaSSPI:
  219. errstr = gettext_noop("SSPI authentication failed for user \"%s\"");
  220. break;
  221. case uaPAM:
  222. errstr = gettext_noop("PAM authentication failed for user \"%s\"");
  223. break;
  224. case uaLDAP:
  225. errstr = gettext_noop("LDAP authentication failed for user \"%s\"");
  226. break;
  227. case uaCert:
  228. errstr = gettext_noop("certificate authentication failed for user \"%s\"");
  229. break;
  230. case uaRADIUS:
  231. errstr = gettext_noop("RADIUS authentication failed for user \"%s\"");
  232. break;
  233. default:
  234. errstr = gettext_noop("authentication failed for user \"%s\": invalid authentication method");
  235. break;
  236. }
  237. cdetail = psprintf(_("Connection matched pg_hba.conf line %d: \"%s\""),
  238. port->hba->linenumber, port->hba->rawline);
  239. if (logdetail)
  240. logdetail = psprintf("%s\n%s", logdetail, cdetail);
  241. else
  242. logdetail = cdetail;
  243. ereport(FATAL,
  244. (errcode(errcode_return),
  245. errmsg(errstr, port->user_name),
  246. logdetail ? errdetail_log("%s", logdetail) : 0));
  247. /* doesn't return */
  248. }
  249. /*
  250. * Client authentication starts here. If there is an error, this
  251. * function does not return and the backend process is terminated.
  252. */
  253. void
  254. ClientAuthentication(Port *port)
  255. {
  256. int status = STATUS_ERROR;
  257. char *logdetail = NULL;
  258. /*
  259. * Get the authentication method to use for this frontend/database
  260. * combination. Note: we do not parse the file at this point; this has
  261. * already been done elsewhere. hba.c dropped an error message into the
  262. * server logfile if parsing the hba config file failed.
  263. */
  264. hba_getauthmethod(port);
  265. /*
  266. * Enable immediate response to SIGTERM/SIGINT/timeout interrupts. (We
  267. * don't want this during hba_getauthmethod() because it might have to do
  268. * database access, eg for role membership checks.)
  269. */
  270. ImmediateInterruptOK = true;
  271. /* And don't forget to detect one that already arrived */
  272. CHECK_FOR_INTERRUPTS();
  273. /*
  274. * This is the first point where we have access to the hba record for the
  275. * current connection, so perform any verifications based on the hba
  276. * options field that should be done *before* the authentication here.
  277. */
  278. if (port->hba->clientcert)
  279. {
  280. /*
  281. * When we parse pg_hba.conf, we have already made sure that we have
  282. * been able to load a certificate store. Thus, if a certificate is
  283. * present on the client, it has been verified against our root
  284. * certificate store, and the connection would have been aborted
  285. * already if it didn't verify ok.
  286. */
  287. #ifdef USE_SSL
  288. if (!port->peer)
  289. {
  290. ereport(FATAL,
  291. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  292. errmsg("connection requires a valid client certificate")));
  293. }
  294. #else
  295. /*
  296. * hba.c makes sure hba->clientcert can't be set unless OpenSSL is
  297. * present.
  298. */
  299. Assert(false);
  300. #endif
  301. }
  302. /*
  303. * Now proceed to do the actual authentication check
  304. */
  305. switch (port->hba->auth_method)
  306. {
  307. case uaReject:
  308. /*
  309. * An explicit "reject" entry in pg_hba.conf. This report exposes
  310. * the fact that there's an explicit reject entry, which is
  311. * perhaps not so desirable from a security standpoint; but the
  312. * message for an implicit reject could confuse the DBA a lot when
  313. * the true situation is a match to an explicit reject. And we
  314. * don't want to change the message for an implicit reject. As
  315. * noted below, the additional information shown here doesn't
  316. * expose anything not known to an attacker.
  317. */
  318. {
  319. char hostinfo[NI_MAXHOST];
  320. pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
  321. hostinfo, sizeof(hostinfo),
  322. NULL, 0,
  323. NI_NUMERICHOST);
  324. if (am_walsender)
  325. {
  326. #ifdef USE_SSL
  327. ereport(FATAL,
  328. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  329. errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\", %s",
  330. hostinfo, port->user_name,
  331. port->ssl ? _("SSL on") : _("SSL off"))));
  332. #else
  333. ereport(FATAL,
  334. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  335. errmsg("pg_hba.conf rejects replication connection for host \"%s\", user \"%s\"",
  336. hostinfo, port->user_name)));
  337. #endif
  338. }
  339. else
  340. {
  341. #ifdef USE_SSL
  342. ereport(FATAL,
  343. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  344. errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\", %s",
  345. hostinfo, port->user_name,
  346. port->database_name,
  347. port->ssl ? _("SSL on") : _("SSL off"))));
  348. #else
  349. ereport(FATAL,
  350. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  351. errmsg("pg_hba.conf rejects connection for host \"%s\", user \"%s\", database \"%s\"",
  352. hostinfo, port->user_name,
  353. port->database_name)));
  354. #endif
  355. }
  356. break;
  357. }
  358. case uaImplicitReject:
  359. /*
  360. * No matching entry, so tell the user we fell through.
  361. *
  362. * NOTE: the extra info reported here is not a security breach,
  363. * because all that info is known at the frontend and must be
  364. * assumed known to bad guys. We're merely helping out the less
  365. * clueful good guys.
  366. */
  367. {
  368. char hostinfo[NI_MAXHOST];
  369. pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
  370. hostinfo, sizeof(hostinfo),
  371. NULL, 0,
  372. NI_NUMERICHOST);
  373. #define HOSTNAME_LOOKUP_DETAIL(port) \
  374. (port->remote_hostname ? \
  375. (port->remote_hostname_resolv == +1 ? \
  376. errdetail_log("Client IP address resolved to \"%s\", forward lookup matches.", \
  377. port->remote_hostname) : \
  378. port->remote_hostname_resolv == 0 ? \
  379. errdetail_log("Client IP address resolved to \"%s\", forward lookup not checked.", \
  380. port->remote_hostname) : \
  381. port->remote_hostname_resolv == -1 ? \
  382. errdetail_log("Client IP address resolved to \"%s\", forward lookup does not match.", \
  383. port->remote_hostname) : \
  384. port->remote_hostname_resolv == -2 ? \
  385. errdetail_log("Could not translate client host name \"%s\" to IP address: %s.", \
  386. port->remote_hostname, \
  387. gai_strerror(port->remote_hostname_errcode)) : \
  388. 0) \
  389. : (port->remote_hostname_resolv == -2 ? \
  390. errdetail_log("Could not resolve client IP address to a host name: %s.", \
  391. gai_strerror(port->remote_hostname_errcode)) : \
  392. 0))
  393. if (am_walsender)
  394. {
  395. #ifdef USE_SSL
  396. ereport(FATAL,
  397. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  398. errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\", %s",
  399. hostinfo, port->user_name,
  400. port->ssl ? _("SSL on") : _("SSL off")),
  401. HOSTNAME_LOOKUP_DETAIL(port)));
  402. #else
  403. ereport(FATAL,
  404. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  405. errmsg("no pg_hba.conf entry for replication connection from host \"%s\", user \"%s\"",
  406. hostinfo, port->user_name),
  407. HOSTNAME_LOOKUP_DETAIL(port)));
  408. #endif
  409. }
  410. else
  411. {
  412. #ifdef USE_SSL
  413. ereport(FATAL,
  414. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  415. errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\", %s",
  416. hostinfo, port->user_name,
  417. port->database_name,
  418. port->ssl ? _("SSL on") : _("SSL off")),
  419. HOSTNAME_LOOKUP_DETAIL(port)));
  420. #else
  421. ereport(FATAL,
  422. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  423. errmsg("no pg_hba.conf entry for host \"%s\", user \"%s\", database \"%s\"",
  424. hostinfo, port->user_name,
  425. port->database_name),
  426. HOSTNAME_LOOKUP_DETAIL(port)));
  427. #endif
  428. }
  429. break;
  430. }
  431. case uaGSS:
  432. #ifdef ENABLE_GSS
  433. sendAuthRequest(port, AUTH_REQ_GSS);
  434. status = pg_GSS_recvauth(port);
  435. #else
  436. Assert(false);
  437. #endif
  438. break;
  439. case uaSSPI:
  440. #ifdef ENABLE_SSPI
  441. sendAuthRequest(port, AUTH_REQ_SSPI);
  442. status = pg_SSPI_recvauth(port);
  443. #else
  444. Assert(false);
  445. #endif
  446. break;
  447. case uaPeer:
  448. #ifdef HAVE_UNIX_SOCKETS
  449. status = auth_peer(port);
  450. #else
  451. Assert(false);
  452. #endif
  453. break;
  454. case uaIdent:
  455. status = ident_inet(port);
  456. break;
  457. case uaMD5:
  458. if (Db_user_namespace)
  459. ereport(FATAL,
  460. (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
  461. errmsg("MD5 authentication is not supported when \"db_user_namespace\" is enabled")));
  462. sendAuthRequest(port, AUTH_REQ_MD5);
  463. status = recv_and_check_password_packet(port, &logdetail);
  464. break;
  465. case uaPassword:
  466. sendAuthRequest(port, AUTH_REQ_PASSWORD);
  467. status = recv_and_check_password_packet(port, &logdetail);
  468. break;
  469. case uaPAM:
  470. #ifdef USE_PAM
  471. status = CheckPAMAuth(port, port->user_name, "");
  472. #else
  473. Assert(false);
  474. #endif /* USE_PAM */
  475. break;
  476. case uaLDAP:
  477. #ifdef USE_LDAP
  478. status = CheckLDAPAuth(port);
  479. #else
  480. Assert(false);
  481. #endif
  482. break;
  483. case uaCert:
  484. #ifdef USE_SSL
  485. status = CheckCertAuth(port);
  486. #else
  487. Assert(false);
  488. #endif
  489. break;
  490. case uaRADIUS:
  491. status = CheckRADIUSAuth(port);
  492. break;
  493. case uaTrust:
  494. status = STATUS_OK;
  495. break;
  496. }
  497. if (ClientAuthentication_hook)
  498. (*ClientAuthentication_hook) (port, status);
  499. if (status == STATUS_OK)
  500. sendAuthRequest(port, AUTH_REQ_OK);
  501. else
  502. auth_failed(port, status, logdetail);
  503. /* Done with authentication, so we should turn off immediate interrupts */
  504. ImmediateInterruptOK = false;
  505. }
  506. /*
  507. * Send an authentication request packet to the frontend.
  508. */
  509. static void
  510. sendAuthRequest(Port *port, AuthRequest areq)
  511. {
  512. StringInfoData buf;
  513. pq_beginmessage(&buf, 'R');
  514. pq_sendint(&buf, (int32) areq, sizeof(int32));
  515. /* Add the salt for encrypted passwords. */
  516. if (areq == AUTH_REQ_MD5)
  517. pq_sendbytes(&buf, port->md5Salt, 4);
  518. #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
  519. /*
  520. * Add the authentication data for the next step of the GSSAPI or SSPI
  521. * negotiation.
  522. */
  523. else if (areq == AUTH_REQ_GSS_CONT)
  524. {
  525. if (port->gss->outbuf.length > 0)
  526. {
  527. elog(DEBUG4, "sending GSS token of length %u",
  528. (unsigned int) port->gss->outbuf.length);
  529. pq_sendbytes(&buf, port->gss->outbuf.value, port->gss->outbuf.length);
  530. }
  531. }
  532. #endif
  533. pq_endmessage(&buf);
  534. /*
  535. * Flush message so client will see it, except for AUTH_REQ_OK, which need
  536. * not be sent until we are ready for queries.
  537. */
  538. if (areq != AUTH_REQ_OK)
  539. pq_flush();
  540. }
  541. /*
  542. * Collect password response packet from frontend.
  543. *
  544. * Returns NULL if couldn't get password, else palloc'd string.
  545. */
  546. static char *
  547. recv_password_packet(Port *port)
  548. {
  549. StringInfoData buf;
  550. if (PG_PROTOCOL_MAJOR(port->proto) >= 3)
  551. {
  552. /* Expect 'p' message type */
  553. int mtype;
  554. mtype = pq_getbyte();
  555. if (mtype != 'p')
  556. {
  557. /*
  558. * If the client just disconnects without offering a password,
  559. * don't make a log entry. This is legal per protocol spec and in
  560. * fact commonly done by psql, so complaining just clutters the
  561. * log.
  562. */
  563. if (mtype != EOF)
  564. ereport(COMMERROR,
  565. (errcode(ERRCODE_PROTOCOL_VIOLATION),
  566. errmsg("expected password response, got message type %d",
  567. mtype)));
  568. return NULL; /* EOF or bad message type */
  569. }
  570. }
  571. else
  572. {
  573. /* For pre-3.0 clients, avoid log entry if they just disconnect */
  574. if (pq_peekbyte() == EOF)
  575. return NULL; /* EOF */
  576. }
  577. initStringInfo(&buf);
  578. if (pq_getmessage(&buf, 1000)) /* receive password */
  579. {
  580. /* EOF - pq_getmessage already logged a suitable message */
  581. pfree(buf.data);
  582. return NULL;
  583. }
  584. /*
  585. * Apply sanity check: password packet length should agree with length of
  586. * contained string. Note it is safe to use strlen here because
  587. * StringInfo is guaranteed to have an appended '\0'.
  588. */
  589. if (strlen(buf.data) + 1 != buf.len)
  590. ereport(COMMERROR,
  591. (errcode(ERRCODE_PROTOCOL_VIOLATION),
  592. errmsg("invalid password packet size")));
  593. /* Do not echo password to logs, for security. */
  594. ereport(DEBUG5,
  595. (errmsg("received password packet")));
  596. /*
  597. * Return the received string. Note we do not attempt to do any
  598. * character-set conversion on it; since we don't yet know the client's
  599. * encoding, there wouldn't be much point.
  600. */
  601. return buf.data;
  602. }
  603. /*----------------------------------------------------------------
  604. * MD5 authentication
  605. *----------------------------------------------------------------
  606. */
  607. /*
  608. * Called when we have sent an authorization request for a password.
  609. * Get the response and check it.
  610. * On error, optionally store a detail string at *logdetail.
  611. */
  612. static int
  613. recv_and_check_password_packet(Port *port, char **logdetail)
  614. {
  615. char *passwd;
  616. int result;
  617. passwd = recv_password_packet(port);
  618. if (passwd == NULL)
  619. return STATUS_EOF; /* client wouldn't send password */
  620. result = md5_crypt_verify(port, port->user_name, passwd, logdetail);
  621. pfree(passwd);
  622. return result;
  623. }
  624. /*----------------------------------------------------------------
  625. * GSSAPI authentication system
  626. *----------------------------------------------------------------
  627. */
  628. #ifdef ENABLE_GSS
  629. #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
  630. /*
  631. * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
  632. * that contain the OIDs required. Redefine here, values copied
  633. * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
  634. */
  635. static const gss_OID_desc GSS_C_NT_USER_NAME_desc =
  636. {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x02"};
  637. static GSS_DLLIMP gss_OID GSS_C_NT_USER_NAME = &GSS_C_NT_USER_NAME_desc;
  638. #endif
  639. static void
  640. pg_GSS_error(int severity, char *errmsg, OM_uint32 maj_stat, OM_uint32 min_stat)
  641. {
  642. gss_buffer_desc gmsg;
  643. OM_uint32 lmin_s,
  644. msg_ctx;
  645. char msg_major[128],
  646. msg_minor[128];
  647. /* Fetch major status message */
  648. msg_ctx = 0;
  649. gss_display_status(&lmin_s, maj_stat, GSS_C_GSS_CODE,
  650. GSS_C_NO_OID, &msg_ctx, &gmsg);
  651. strlcpy(msg_major, gmsg.value, sizeof(msg_major));
  652. gss_release_buffer(&lmin_s, &gmsg);
  653. if (msg_ctx)
  654. /*
  655. * More than one message available. XXX: Should we loop and read all
  656. * messages? (same below)
  657. */
  658. ereport(WARNING,
  659. (errmsg_internal("incomplete GSS error report")));
  660. /* Fetch mechanism minor status message */
  661. msg_ctx = 0;
  662. gss_display_status(&lmin_s, min_stat, GSS_C_MECH_CODE,
  663. GSS_C_NO_OID, &msg_ctx, &gmsg);
  664. strlcpy(msg_minor, gmsg.value, sizeof(msg_minor));
  665. gss_release_buffer(&lmin_s, &gmsg);
  666. if (msg_ctx)
  667. ereport(WARNING,
  668. (errmsg_internal("incomplete GSS minor error report")));
  669. /*
  670. * errmsg_internal, since translation of the first part must be done
  671. * before calling this function anyway.
  672. */
  673. ereport(severity,
  674. (errmsg_internal("%s", errmsg),
  675. errdetail_internal("%s: %s", msg_major, msg_minor)));
  676. }
  677. static int
  678. pg_GSS_recvauth(Port *port)
  679. {
  680. OM_uint32 maj_stat,
  681. min_stat,
  682. lmin_s,
  683. gflags;
  684. int mtype;
  685. int ret;
  686. StringInfoData buf;
  687. gss_buffer_desc gbuf;
  688. /*
  689. * GSS auth is not supported for protocol versions before 3, because it
  690. * relies on the overall message length word to determine the GSS payload
  691. * size in AuthenticationGSSContinue and PasswordMessage messages. (This
  692. * is, in fact, a design error in our GSS support, because protocol
  693. * messages are supposed to be parsable without relying on the length
  694. * word; but it's not worth changing it now.)
  695. */
  696. if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
  697. ereport(FATAL,
  698. (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
  699. errmsg("GSSAPI is not supported in protocol version 2")));
  700. if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0)
  701. {
  702. /*
  703. * Set default Kerberos keytab file for the Krb5 mechanism.
  704. *
  705. * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv()
  706. * not always available.
  707. */
  708. if (getenv("KRB5_KTNAME") == NULL)
  709. {
  710. size_t kt_len = strlen(pg_krb_server_keyfile) + 14;
  711. char *kt_path = malloc(kt_len);
  712. if (!kt_path)
  713. {
  714. ereport(LOG,
  715. (errcode(ERRCODE_OUT_OF_MEMORY),
  716. errmsg("out of memory")));
  717. return STATUS_ERROR;
  718. }
  719. snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
  720. putenv(kt_path);
  721. }
  722. }
  723. /*
  724. * We accept any service principal that's present in our keytab. This
  725. * increases interoperability between kerberos implementations that see
  726. * for example case sensitivity differently, while not really opening up
  727. * any vector of attack.
  728. */
  729. port->gss->cred = GSS_C_NO_CREDENTIAL;
  730. /*
  731. * Initialize sequence with an empty context
  732. */
  733. port->gss->ctx = GSS_C_NO_CONTEXT;
  734. /*
  735. * Loop through GSSAPI message exchange. This exchange can consist of
  736. * multiple messags sent in both directions. First message is always from
  737. * the client. All messages from client to server are password packets
  738. * (type 'p').
  739. */
  740. do
  741. {
  742. mtype = pq_getbyte();
  743. if (mtype != 'p')
  744. {
  745. /* Only log error if client didn't disconnect. */
  746. if (mtype != EOF)
  747. ereport(COMMERROR,
  748. (errcode(ERRCODE_PROTOCOL_VIOLATION),
  749. errmsg("expected GSS response, got message type %d",
  750. mtype)));
  751. return STATUS_ERROR;
  752. }
  753. /* Get the actual GSS token */
  754. initStringInfo(&buf);
  755. if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
  756. {
  757. /* EOF - pq_getmessage already logged error */
  758. pfree(buf.data);
  759. return STATUS_ERROR;
  760. }
  761. /* Map to GSSAPI style buffer */
  762. gbuf.length = buf.len;
  763. gbuf.value = buf.data;
  764. elog(DEBUG4, "Processing received GSS token of length %u",
  765. (unsigned int) gbuf.length);
  766. maj_stat = gss_accept_sec_context(
  767. &min_stat,
  768. &port->gss->ctx,
  769. port->gss->cred,
  770. &gbuf,
  771. GSS_C_NO_CHANNEL_BINDINGS,
  772. &port->gss->name,
  773. NULL,
  774. &port->gss->outbuf,
  775. &gflags,
  776. NULL,
  777. NULL);
  778. /* gbuf no longer used */
  779. pfree(buf.data);
  780. elog(DEBUG5, "gss_accept_sec_context major: %d, "
  781. "minor: %d, outlen: %u, outflags: %x",
  782. maj_stat, min_stat,
  783. (unsigned int) port->gss->outbuf.length, gflags);
  784. if (port->gss->outbuf.length != 0)
  785. {
  786. /*
  787. * Negotiation generated data to be sent to the client.
  788. */
  789. elog(DEBUG4, "sending GSS response token of length %u",
  790. (unsigned int) port->gss->outbuf.length);
  791. sendAuthRequest(port, AUTH_REQ_GSS_CONT);
  792. gss_release_buffer(&lmin_s, &port->gss->outbuf);
  793. }
  794. if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
  795. {
  796. gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER);
  797. pg_GSS_error(ERROR,
  798. gettext_noop("accepting GSS security context failed"),
  799. maj_stat, min_stat);
  800. }
  801. if (maj_stat == GSS_S_CONTINUE_NEEDED)
  802. elog(DEBUG4, "GSS continue needed");
  803. } while (maj_stat == GSS_S_CONTINUE_NEEDED);
  804. if (port->gss->cred != GSS_C_NO_CREDENTIAL)
  805. {
  806. /*
  807. * Release service principal credentials
  808. */
  809. gss_release_cred(&min_stat, &port->gss->cred);
  810. }
  811. /*
  812. * GSS_S_COMPLETE indicates that authentication is now complete.
  813. *
  814. * Get the name of the user that authenticated, and compare it to the pg
  815. * username that was specified for the connection.
  816. */
  817. maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL);
  818. if (maj_stat != GSS_S_COMPLETE)
  819. pg_GSS_error(ERROR,
  820. gettext_noop("retrieving GSS user name failed"),
  821. maj_stat, min_stat);
  822. /*
  823. * Split the username at the realm separator
  824. */
  825. if (strchr(gbuf.value, '@'))
  826. {
  827. char *cp = strchr(gbuf.value, '@');
  828. /*
  829. * If we are not going to include the realm in the username that is
  830. * passed to the ident map, destructively modify it here to remove the
  831. * realm. Then advance past the separator to check the realm.
  832. */
  833. if (!port->hba->include_realm)
  834. *cp = '\0';
  835. cp++;
  836. if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm))
  837. {
  838. /*
  839. * Match the realm part of the name first
  840. */
  841. if (pg_krb_caseins_users)
  842. ret = pg_strcasecmp(port->hba->krb_realm, cp);
  843. else
  844. ret = strcmp(port->hba->krb_realm, cp);
  845. if (ret)
  846. {
  847. /* GSS realm does not match */
  848. elog(DEBUG2,
  849. "GSSAPI realm (%s) and configured realm (%s) don't match",
  850. cp, port->hba->krb_realm);
  851. gss_release_buffer(&lmin_s, &gbuf);
  852. return STATUS_ERROR;
  853. }
  854. }
  855. }
  856. else if (port->hba->krb_realm && strlen(port->hba->krb_realm))
  857. {
  858. elog(DEBUG2,
  859. "GSSAPI did not return realm but realm matching was requested");
  860. gss_release_buffer(&lmin_s, &gbuf);
  861. return STATUS_ERROR;
  862. }
  863. ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value,
  864. pg_krb_caseins_users);
  865. gss_release_buffer(&lmin_s, &gbuf);
  866. return ret;
  867. }
  868. #endif /* ENABLE_GSS */
  869. /*----------------------------------------------------------------
  870. * SSPI authentication system
  871. *----------------------------------------------------------------
  872. */
  873. #ifdef ENABLE_SSPI
  874. static void
  875. pg_SSPI_error(int severity, const char *errmsg, SECURITY_STATUS r)
  876. {
  877. char sysmsg[256];
  878. if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, 0,
  879. sysmsg, sizeof(sysmsg), NULL) == 0)
  880. ereport(severity,
  881. (errmsg_internal("%s", errmsg),
  882. errdetail_internal("SSPI error %x", (unsigned int) r)));
  883. else
  884. ereport(severity,
  885. (errmsg_internal("%s", errmsg),
  886. errdetail_internal("%s (%x)", sysmsg, (unsigned int) r)));
  887. }
  888. static int
  889. pg_SSPI_recvauth(Port *port)
  890. {
  891. int mtype;
  892. StringInfoData buf;
  893. SECURITY_STATUS r;
  894. CredHandle sspicred;
  895. CtxtHandle *sspictx = NULL,
  896. newctx;
  897. TimeStamp expiry;
  898. ULONG contextattr;
  899. SecBufferDesc inbuf;
  900. SecBufferDesc outbuf;
  901. SecBuffer OutBuffers[1];
  902. SecBuffer InBuffers[1];
  903. HANDLE token;
  904. TOKEN_USER *tokenuser;
  905. DWORD retlen;
  906. char accountname[MAXPGPATH];
  907. char domainname[MAXPGPATH];
  908. DWORD accountnamesize = sizeof(accountname);
  909. DWORD domainnamesize = sizeof(domainname);
  910. SID_NAME_USE accountnameuse;
  911. HMODULE secur32;
  912. QUERY_SECURITY_CONTEXT_TOKEN_FN _QuerySecurityContextToken;
  913. /*
  914. * SSPI auth is not supported for protocol versions before 3, because it
  915. * relies on the overall message length word to determine the SSPI payload
  916. * size in AuthenticationGSSContinue and PasswordMessage messages. (This
  917. * is, in fact, a design error in our SSPI support, because protocol
  918. * messages are supposed to be parsable without relying on the length
  919. * word; but it's not worth changing it now.)
  920. */
  921. if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
  922. ereport(FATAL,
  923. (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
  924. errmsg("SSPI is not supported in protocol version 2")));
  925. /*
  926. * Acquire a handle to the server credentials.
  927. */
  928. r = AcquireCredentialsHandle(NULL,
  929. "negotiate",
  930. SECPKG_CRED_INBOUND,
  931. NULL,
  932. NULL,
  933. NULL,
  934. NULL,
  935. &sspicred,
  936. &expiry);
  937. if (r != SEC_E_OK)
  938. pg_SSPI_error(ERROR, _("could not acquire SSPI credentials"), r);
  939. /*
  940. * Loop through SSPI message exchange. This exchange can consist of
  941. * multiple messags sent in both directions. First message is always from
  942. * the client. All messages from client to server are password packets
  943. * (type 'p').
  944. */
  945. do
  946. {
  947. mtype = pq_getbyte();
  948. if (mtype != 'p')
  949. {
  950. /* Only log error if client didn't disconnect. */
  951. if (mtype != EOF)
  952. ereport(COMMERROR,
  953. (errcode(ERRCODE_PROTOCOL_VIOLATION),
  954. errmsg("expected SSPI response, got message type %d",
  955. mtype)));
  956. return STATUS_ERROR;
  957. }
  958. /* Get the actual SSPI token */
  959. initStringInfo(&buf);
  960. if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH))
  961. {
  962. /* EOF - pq_getmessage already logged error */
  963. pfree(buf.data);
  964. return STATUS_ERROR;
  965. }
  966. /* Map to SSPI style buffer */
  967. inbuf.ulVersion = SECBUFFER_VERSION;
  968. inbuf.cBuffers = 1;
  969. inbuf.pBuffers = InBuffers;
  970. InBuffers[0].pvBuffer = buf.data;
  971. InBuffers[0].cbBuffer = buf.len;
  972. InBuffers[0].BufferType = SECBUFFER_TOKEN;
  973. /* Prepare output buffer */
  974. OutBuffers[0].pvBuffer = NULL;
  975. OutBuffers[0].BufferType = SECBUFFER_TOKEN;
  976. OutBuffers[0].cbBuffer = 0;
  977. outbuf.cBuffers = 1;
  978. outbuf.pBuffers = OutBuffers;
  979. outbuf.ulVersion = SECBUFFER_VERSION;
  980. elog(DEBUG4, "Processing received SSPI token of length %u",
  981. (unsigned int) buf.len);
  982. r = AcceptSecurityContext(&sspicred,
  983. sspictx,
  984. &inbuf,
  985. ASC_REQ_ALLOCATE_MEMORY,
  986. SECURITY_NETWORK_DREP,
  987. &newctx,
  988. &outbuf,
  989. &contextattr,
  990. NULL);
  991. /* input buffer no longer used */
  992. pfree(buf.data);
  993. if (outbuf.cBuffers > 0 && outbuf.pBuffers[0].cbBuffer > 0)
  994. {
  995. /*
  996. * Negotiation generated data to be sent to the client.
  997. */
  998. elog(DEBUG4, "sending SSPI response token of length %u",
  999. (unsigned int) outbuf.pBuffers[0].cbBuffer);
  1000. port->gss->outbuf.length = outbuf.pBuffers[0].cbBuffer;
  1001. port->gss->outbuf.value = outbuf.pBuffers[0].pvBuffer;
  1002. sendAuthRequest(port, AUTH_REQ_GSS_CONT);
  1003. FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
  1004. }
  1005. if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
  1006. {
  1007. if (sspictx != NULL)
  1008. {
  1009. DeleteSecurityContext(sspictx);
  1010. free(sspictx);
  1011. }
  1012. FreeCredentialsHandle(&sspicred);
  1013. pg_SSPI_error(ERROR,
  1014. _("could not accept SSPI security context"), r);
  1015. }
  1016. /*
  1017. * Overwrite the current context with the one we just received. If
  1018. * sspictx is NULL it was the first loop and we need to allocate a
  1019. * buffer for it. On subsequent runs, we can just overwrite the buffer
  1020. * contents since the size does not change.
  1021. */
  1022. if (sspictx == NULL)
  1023. {
  1024. sspictx = malloc(sizeof(CtxtHandle));
  1025. if (sspictx == NULL)
  1026. ereport(ERROR,
  1027. (errmsg("out of memory")));
  1028. }
  1029. memcpy(sspictx, &newctx, sizeof(CtxtHandle));
  1030. if (r == SEC_I_CONTINUE_NEEDED)
  1031. elog(DEBUG4, "SSPI continue needed");
  1032. } while (r == SEC_I_CONTINUE_NEEDED);
  1033. /*
  1034. * Release service principal credentials
  1035. */
  1036. FreeCredentialsHandle(&sspicred);
  1037. /*
  1038. * SEC_E_OK indicates that authentication is now complete.
  1039. *
  1040. * Get the name of the user that authenticated, and compare it to the pg
  1041. * username that was specified for the connection.
  1042. *
  1043. * MingW is missing the export for QuerySecurityContextToken in the
  1044. * secur32 library, so we have to load it dynamically.
  1045. */
  1046. secur32 = LoadLibrary("SECUR32.DLL");
  1047. if (secur32 == NULL)
  1048. ereport(ERROR,
  1049. (errmsg_internal("could not load secur32.dll: error code %lu",
  1050. GetLastError())));
  1051. _QuerySecurityContextToken = (QUERY_SECURITY_CONTEXT_TOKEN_FN)
  1052. GetProcAddress(secur32, "QuerySecurityContextToken");
  1053. if (_QuerySecurityContextToken == NULL)
  1054. {
  1055. FreeLibrary(secur32);
  1056. ereport(ERROR,
  1057. (errmsg_internal("could not locate QuerySecurityContextToken in secur32.dll: error code %lu",
  1058. GetLastError())));
  1059. }
  1060. r = (_QuerySecurityContextToken) (sspictx, &token);
  1061. if (r != SEC_E_OK)
  1062. {
  1063. FreeLibrary(secur32);
  1064. pg_SSPI_error(ERROR,
  1065. _("could not get token from SSPI security context"), r);
  1066. }
  1067. FreeLibrary(secur32);
  1068. /*
  1069. * No longer need the security context, everything from here on uses the
  1070. * token instead.
  1071. */
  1072. DeleteSecurityContext(sspictx);
  1073. free(sspictx);
  1074. if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
  1075. ereport(ERROR,
  1076. (errmsg_internal("could not get token user size: error code %lu",
  1077. GetLastError())));
  1078. tokenuser = malloc(retlen);
  1079. if (tokenuser == NULL)
  1080. ereport(ERROR,
  1081. (errmsg("out of memory")));
  1082. if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
  1083. ereport(ERROR,
  1084. (errmsg_internal("could not get user token: error code %lu",
  1085. GetLastError())));
  1086. if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
  1087. domainname, &domainnamesize, &accountnameuse))
  1088. ereport(ERROR,
  1089. (errmsg_internal("could not look up account SID: error code %lu",
  1090. GetLastError())));
  1091. free(tokenuser);
  1092. /*
  1093. * Compare realm/domain if requested. In SSPI, always compare case
  1094. * insensitive.
  1095. */
  1096. if (port->hba->krb_realm && strlen(port->hba->krb_realm))
  1097. {
  1098. if (pg_strcasecmp(port->hba->krb_realm, domainname) != 0)
  1099. {
  1100. elog(DEBUG2,
  1101. "SSPI domain (%s) and configured domain (%s) don't match",
  1102. domainname, port->hba->krb_realm);
  1103. return STATUS_ERROR;
  1104. }
  1105. }
  1106. /*
  1107. * We have the username (without domain/realm) in accountname, compare to
  1108. * the supplied value. In SSPI, always compare case insensitive.
  1109. *
  1110. * If set to include realm, append it in <username>@<realm> format.
  1111. */
  1112. if (port->hba->include_realm)
  1113. {
  1114. char *namebuf;
  1115. int retval;
  1116. namebuf = psprintf("%s@%s", accountname, domainname);
  1117. retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
  1118. pfree(namebuf);
  1119. return retval;
  1120. }
  1121. else
  1122. return check_usermap(port->hba->usermap, port->user_name, accountname, true);
  1123. }
  1124. #endif /* ENABLE_SSPI */
  1125. /*----------------------------------------------------------------
  1126. * Ident authentication system
  1127. *----------------------------------------------------------------
  1128. */
  1129. /*
  1130. * Parse the string "*ident_response" as a response from a query to an Ident
  1131. * server. If it's a normal response indicating a user name, return true
  1132. * and store the user name at *ident_user. If it's anything else,
  1133. * return false.
  1134. */
  1135. static bool
  1136. interpret_ident_response(const char *ident_response,
  1137. char *ident_user)
  1138. {
  1139. const char *cursor = ident_response; /* Cursor into *ident_response */
  1140. /*
  1141. * Ident's response, in the telnet tradition, should end in crlf (\r\n).
  1142. */
  1143. if (strlen(ident_response) < 2)
  1144. return false;
  1145. else if (ident_response[strlen(ident_response) - 2] != '\r')
  1146. return false;
  1147. else
  1148. {
  1149. while (*cursor != ':' && *cursor != '\r')
  1150. cursor++; /* skip port field */
  1151. if (*cursor != ':')
  1152. return false;
  1153. else
  1154. {
  1155. /* We're positioned to colon before response type field */
  1156. char response_type[80];
  1157. int i; /* Index into *response_type */
  1158. cursor++; /* Go over colon */
  1159. while (pg_isblank(*cursor))
  1160. cursor++; /* skip blanks */
  1161. i = 0;
  1162. while (*cursor != ':' && *cursor != '\r' && !pg_isblank(*cursor) &&
  1163. i < (int) (sizeof(response_type) - 1))
  1164. response_type[i++] = *cursor++;
  1165. response_type[i] = '\0';
  1166. while (pg_isblank(*cursor))
  1167. cursor++; /* skip blanks */
  1168. if (strcmp(response_type, "USERID") != 0)
  1169. return false;
  1170. else
  1171. {
  1172. /*
  1173. * It's a USERID response. Good. "cursor" should be pointing
  1174. * to the colon that precedes the operating system type.
  1175. */
  1176. if (*cursor != ':')
  1177. return false;
  1178. else
  1179. {
  1180. cursor++; /* Go over colon */
  1181. /* Skip over operating system field. */
  1182. while (*cursor != ':' && *cursor != '\r')
  1183. cursor++;
  1184. if (*cursor != ':')
  1185. return false;
  1186. else
  1187. {
  1188. int i; /* Index into *ident_user */
  1189. cursor++; /* Go over colon */
  1190. while (pg_isblank(*cursor))
  1191. cursor++; /* skip blanks */
  1192. /* Rest of line is user name. Copy it over. */
  1193. i = 0;
  1194. while (*cursor != '\r' && i < IDENT_USERNAME_MAX)
  1195. ident_user[i++] = *cursor++;
  1196. ident_user[i] = '\0';
  1197. return true;
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. /*
  1205. * Talk to the ident server on host "remote_ip_addr" and find out who
  1206. * owns the tcp connection from his port "remote_port" to port
  1207. * "local_port_addr" on host "local_ip_addr". Return the user name the
  1208. * ident server gives as "*ident_user".
  1209. *
  1210. * IP addresses and port numbers are in network byte order.
  1211. *
  1212. * But iff we're unable to get the information from ident, return false.
  1213. */
  1214. static int
  1215. ident_inet(hbaPort *port)
  1216. {
  1217. const SockAddr remote_addr = port->raddr;
  1218. const SockAddr local_addr = port->laddr;
  1219. char ident_user[IDENT_USERNAME_MAX + 1];
  1220. pgsocket sock_fd; /* File descriptor for socket on which we talk
  1221. * to Ident */
  1222. int rc; /* Return code from a locally called function */
  1223. bool ident_return;
  1224. char remote_addr_s[NI_MAXHOST];
  1225. char remote_port[NI_MAXSERV];
  1226. char local_addr_s[NI_MAXHOST];
  1227. char local_port[NI_MAXSERV];
  1228. char ident_port[NI_MAXSERV];
  1229. char ident_query[80];
  1230. char ident_response[80 + IDENT_USERNAME_MAX];
  1231. struct addrinfo *ident_serv = NULL,
  1232. *la = NULL,
  1233. hints;
  1234. /*
  1235. * Might look a little weird to first convert it to text and then back to
  1236. * sockaddr, but it's protocol independent.
  1237. */
  1238. pg_getnameinfo_all(&remote_addr.addr, remote_addr.salen,
  1239. remote_addr_s, sizeof(remote_addr_s),
  1240. remote_port, sizeof(remote_port),
  1241. NI_NUMERICHOST | NI_NUMERICSERV);
  1242. pg_getnameinfo_all(&local_addr.addr, local_addr.salen,
  1243. local_addr_s, sizeof(local_addr_s),
  1244. local_port, sizeof(local_port),
  1245. NI_NUMERICHOST | NI_NUMERICSERV);
  1246. snprintf(ident_port, sizeof(ident_port), "%d", IDENT_PORT);
  1247. hints.ai_flags = AI_NUMERICHOST;
  1248. hints.ai_family = remote_addr.addr.ss_family;
  1249. hints.ai_socktype = SOCK_STREAM;
  1250. hints.ai_protocol = 0;
  1251. hints.ai_addrlen = 0;
  1252. hints.ai_canonname = NULL;
  1253. hints.ai_addr = NULL;
  1254. hints.ai_next = NULL;
  1255. rc = pg_getaddrinfo_all(remote_addr_s, ident_port, &hints, &ident_serv);
  1256. if (rc || !ident_serv)
  1257. {
  1258. if (ident_serv)
  1259. pg_freeaddrinfo_all(hints.ai_family, ident_serv);
  1260. return STATUS_ERROR; /* we don't expect this to happen */
  1261. }
  1262. hints.ai_flags = AI_NUMERICHOST;
  1263. hints.ai_family = local_addr.addr.ss_family;
  1264. hints.ai_socktype = SOCK_STREAM;
  1265. hints.ai_protocol = 0;
  1266. hints.ai_addrlen = 0;
  1267. hints.ai_canonname = NULL;
  1268. hints.ai_addr = NULL;
  1269. hints.ai_next = NULL;
  1270. rc = pg_getaddrinfo_all(local_addr_s, NULL, &hints, &la);
  1271. if (rc || !la)
  1272. {
  1273. if (la)
  1274. pg_freeaddrinfo_all(hints.ai_family, la);
  1275. return STATUS_ERROR; /* we don't expect this to happen */
  1276. }
  1277. sock_fd = socket(ident_serv->ai_family, ident_serv->ai_socktype,
  1278. ident_serv->ai_protocol);
  1279. if (sock_fd == PGINVALID_SOCKET)
  1280. {
  1281. ereport(LOG,
  1282. (errcode_for_socket_access(),
  1283. errmsg("could not create socket for Ident connection: %m")));
  1284. ident_return = false;
  1285. goto ident_inet_done;
  1286. }
  1287. /*
  1288. * Bind to the address which the client originally contacted, otherwise
  1289. * the ident server won't be able to match up the right connection. This
  1290. * is necessary if the PostgreSQL server is running on an IP alias.
  1291. */
  1292. rc = bind(sock_fd, la->ai_addr, la->ai_addrlen);
  1293. if (rc != 0)
  1294. {
  1295. ereport(LOG,
  1296. (errcode_for_socket_access(),
  1297. errmsg("could not bind to local address \"%s\": %m",
  1298. local_addr_s)));
  1299. ident_return = false;
  1300. goto ident_inet_done;
  1301. }
  1302. rc = connect(sock_fd, ident_serv->ai_addr,
  1303. ident_serv->ai_addrlen);
  1304. if (rc != 0)
  1305. {
  1306. ereport(LOG,
  1307. (errcode_for_socket_access(),
  1308. errmsg("could not connect to Ident server at address \"%s\", port %s: %m",
  1309. remote_addr_s, ident_port)));
  1310. ident_return = false;
  1311. goto ident_inet_done;
  1312. }
  1313. /* The query we send to the Ident server */
  1314. snprintf(ident_query, sizeof(ident_query), "%s,%s\r\n",
  1315. remote_port, local_port);
  1316. /* loop in case send is interrupted */
  1317. do
  1318. {
  1319. rc = send(sock_fd, ident_query, strlen(ident_query), 0);
  1320. } while (rc < 0 && errno == EINTR);
  1321. if (rc < 0)
  1322. {
  1323. ereport(LOG,
  1324. (errcode_for_socket_access(),
  1325. errmsg("could not send query to Ident server at address \"%s\", port %s: %m",
  1326. remote_addr_s, ident_port)));
  1327. ident_return = false;
  1328. goto ident_inet_done;
  1329. }
  1330. do
  1331. {
  1332. rc = recv(sock_fd, ident_response, sizeof(ident_response) - 1, 0);
  1333. } while (rc < 0 && errno == EINTR);
  1334. if (rc < 0)
  1335. {
  1336. ereport(LOG,
  1337. (errcode_for_socket_access(),
  1338. errmsg("could not receive response from Ident server at address \"%s\", port %s: %m",
  1339. remote_addr_s, ident_port)));
  1340. ident_return = false;
  1341. goto ident_inet_done;
  1342. }
  1343. ident_response[rc] = '\0';
  1344. ident_return = interpret_ident_response(ident_response, ident_user);
  1345. if (!ident_return)
  1346. ereport(LOG,
  1347. (errmsg("invalidly formatted response from Ident server: \"%s\"",
  1348. ident_response)));
  1349. ident_inet_done:
  1350. if (sock_fd != PGINVALID_SOCKET)
  1351. closesocket(sock_fd);
  1352. pg_freeaddrinfo_all(remote_addr.addr.ss_family, ident_serv);
  1353. pg_freeaddrinfo_all(local_addr.addr.ss_family, la);
  1354. if (ident_return)
  1355. /* Success! Check the usermap */
  1356. return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
  1357. return STATUS_ERROR;
  1358. }
  1359. /*
  1360. * Ask kernel about the credentials of the connecting process,
  1361. * determine the symbolic name of the corresponding user, and check
  1362. * if valid per the usermap.
  1363. *
  1364. * Iff authorized, return STATUS_OK, otherwise return STATUS_ERROR.
  1365. */
  1366. #ifdef HAVE_UNIX_SOCKETS
  1367. static int
  1368. auth_peer(hbaPort *port)
  1369. {
  1370. char ident_user[IDENT_USERNAME_MAX + 1];
  1371. uid_t uid;
  1372. gid_t gid;
  1373. struct passwd *pw;
  1374. if (getpeereid(port->sock, &uid, &gid) != 0)
  1375. {
  1376. /* Provide special error message if getpeereid is a stub */
  1377. if (errno == ENOSYS)
  1378. ereport(LOG,
  1379. (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
  1380. errmsg("peer authentication is not supported on this platform")));
  1381. else
  1382. ereport(LOG,
  1383. (errcode_for_socket_access(),
  1384. errmsg("could not get peer credentials: %m")));
  1385. return STATUS_ERROR;
  1386. }
  1387. errno = 0; /* clear errno before call */
  1388. pw = getpwuid(uid);
  1389. if (!pw)
  1390. {
  1391. ereport(LOG,
  1392. (errmsg("failed to look up local user id %ld: %s",
  1393. (long) uid, errno ? strerror(errno) : _("user does not exist"))));
  1394. return STATUS_ERROR;
  1395. }
  1396. strlcpy(ident_user, pw->pw_name, IDENT_USERNAME_MAX + 1);
  1397. return check_usermap(port->hba->usermap, port->user_name, ident_user, false);
  1398. }
  1399. #endif /* HAVE_UNIX_SOCKETS */
  1400. /*----------------------------------------------------------------
  1401. * PAM authentication system
  1402. *----------------------------------------------------------------
  1403. */
  1404. #ifdef USE_PAM
  1405. /*
  1406. * PAM conversation function
  1407. */
  1408. static int
  1409. pam_passwd_conv_proc(int num_msg, const struct pam_message ** msg,
  1410. struct pam_response ** resp, void *appdata_ptr)
  1411. {
  1412. char *passwd;
  1413. struct pam_response *reply;
  1414. int i;
  1415. if (appdata_ptr)
  1416. passwd = (char *) appdata_ptr;
  1417. else
  1418. {
  1419. /*
  1420. * Workaround for Solaris 2.6 where the PAM library is broken and does
  1421. * not pass appdata_ptr to the conversation routine
  1422. */
  1423. passwd = pam_passwd;
  1424. }
  1425. *resp = NULL; /* in case of error exit */
  1426. if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
  1427. return PAM_CONV_ERR;
  1428. /*
  1429. * Explicitly not using palloc here - PAM will free this memory in
  1430. * pam_end()
  1431. */
  1432. if ((reply = calloc(num_msg, sizeof(struct pam_response))) == NULL)
  1433. {
  1434. ereport(LOG,
  1435. (errcode(ERRCODE_OUT_OF_MEMORY),
  1436. errmsg("out of memory")));
  1437. return PAM_CONV_ERR;
  1438. }
  1439. for (i = 0; i < num_msg; i++)
  1440. {
  1441. switch (msg[i]->msg_style)
  1442. {
  1443. case PAM_PROMPT_ECHO_OFF:
  1444. if (strlen(passwd) == 0)
  1445. {
  1446. /*
  1447. * Password wasn't passed to PAM the first time around -
  1448. * let's go ask the client to send a password, which we
  1449. * then stuff into PAM.
  1450. */
  1451. sendAuthRequest(pam_port_cludge, AUTH_REQ_PASSWORD);
  1452. passwd = recv_password_packet(pam_port_cludge);
  1453. if (passwd == NULL)
  1454. {
  1455. /*
  1456. * Client didn't want to send password. We
  1457. * intentionally do not log anything about this.
  1458. */
  1459. goto fail;
  1460. }
  1461. if (strlen(passwd) == 0)
  1462. {
  1463. ereport(LOG,
  1464. (errmsg("empty password returned by client")));
  1465. goto fail;
  1466. }
  1467. }
  1468. if ((reply[i].resp = strdup(passwd)) == NULL)
  1469. goto fail;
  1470. reply[i].resp_retcode = PAM_SUCCESS;
  1471. break;
  1472. case PAM_ERROR_MSG:
  1473. ereport(LOG,
  1474. (errmsg("error from underlying PAM layer: %s",
  1475. msg[i]->msg)));
  1476. /* FALL THROUGH */
  1477. case PAM_TEXT_INFO:
  1478. /* we don't bother to log TEXT_INFO messages */
  1479. if ((reply[i].resp = strdup("")) == NULL)
  1480. goto fail;
  1481. reply[i].resp_retcode = PAM_SUCCESS;
  1482. break;
  1483. default:
  1484. elog(LOG, "unsupported PAM conversation %d/\"%s\"",
  1485. msg[i]->msg_style,
  1486. msg[i]->msg ? msg[i]->msg : "(none)");
  1487. goto fail;
  1488. }
  1489. }
  1490. *resp = reply;
  1491. return PAM_SUCCESS;
  1492. fail:
  1493. /* free up whatever we allocated */
  1494. for (i = 0; i < num_msg; i++)
  1495. {
  1496. if (reply[i].resp != NULL)
  1497. free(reply[i].resp);
  1498. }
  1499. free(reply);
  1500. return PAM_CONV_ERR;
  1501. }
  1502. /*
  1503. * Check authentication against PAM.
  1504. */
  1505. static int
  1506. CheckPAMAuth(Port *port, char *user, char *password)
  1507. {
  1508. int retval;
  1509. pam_handle_t *pamh = NULL;
  1510. /*
  1511. * We can't entirely rely on PAM to pass through appdata --- it appears
  1512. * not to work on at least Solaris 2.6. So use these ugly static
  1513. * variables instead.
  1514. */
  1515. pam_passwd = password;
  1516. pam_port_cludge = port;
  1517. /*
  1518. * Set the application data portion of the conversation struct. This is
  1519. * later used inside the PAM conversation to pass the password to the
  1520. * authentication module.
  1521. */
  1522. pam_passw_conv.appdata_ptr = (char *) password; /* from password above,
  1523. * not allocated */
  1524. /* Optionally, one can set the service name in pg_hba.conf */
  1525. if (port->hba->pamservice && port->hba->pamservice[0] != '\0')
  1526. retval = pam_start(port->hba->pamservice, "pgsql@",
  1527. &pam_passw_conv, &pamh);
  1528. else
  1529. retval = pam_start(PGSQL_PAM_SERVICE, "pgsql@",
  1530. &pam_passw_conv, &pamh);
  1531. if (retval != PAM_SUCCESS)
  1532. {
  1533. ereport(LOG,
  1534. (errmsg("could not create PAM authenticator: %s",
  1535. pam_strerror(pamh, retval))));
  1536. pam_passwd = NULL; /* Unset pam_passwd */
  1537. return STATUS_ERROR;
  1538. }
  1539. retval = pam_set_item(pamh, PAM_USER, user);
  1540. if (retval != PAM_SUCCESS)
  1541. {
  1542. ereport(LOG,
  1543. (errmsg("pam_set_item(PAM_USER) failed: %s",
  1544. pam_strerror(pamh, retval))));
  1545. pam_passwd = NULL; /* Unset pam_passwd */
  1546. return STATUS_ERROR;
  1547. }
  1548. retval = pam_set_item(pamh, PAM_CONV, &pam_passw_conv);
  1549. if (retval != PAM_SUCCESS)
  1550. {
  1551. ereport(LOG,
  1552. (errmsg("pam_set_item(PAM_CONV) failed: %s",
  1553. pam_strerror(pamh, retval))));
  1554. pam_passwd = NULL; /* Unset pam_passwd */
  1555. return STATUS_ERROR;
  1556. }
  1557. retval = pam_authenticate(pamh, 0);
  1558. if (retval != PAM_SUCCESS)
  1559. {
  1560. ereport(LOG,
  1561. (errmsg("pam_authenticate failed: %s",
  1562. pam_strerror(pamh, retval))));
  1563. pam_passwd = NULL; /* Unset pam_passwd */
  1564. return STATUS_ERROR;
  1565. }
  1566. retval = pam_acct_mgmt(pamh, 0);
  1567. if (retval != PAM_SUCCESS)
  1568. {
  1569. ereport(LOG,
  1570. (errmsg("pam_acct_mgmt failed: %s",
  1571. pam_strerror(pamh, retval))));
  1572. pam_passwd = NULL; /* Unset pam_passwd */
  1573. return STATUS_ERROR;
  1574. }
  1575. retval = pam_end(pamh, retval);
  1576. if (retval != PAM_SUCCESS)
  1577. {
  1578. ereport(LOG,
  1579. (errmsg("could not release PAM authenticator: %s",
  1580. pam_strerror(pamh

Large files files are truncated, but you can click here to view the full file