PageRenderTime 68ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/src/backend/libpq/auth.c

https://bitbucket.org/gencer/postgres
C | 2570 lines | 1701 code | 327 blank | 542 comment | 323 complexity | 0e467036f18b835589b1a5af750a00a8 MD5 | raw file
Possible License(s): AGPL-3.0
  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 < 0)
  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 >= 0)
  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, retval))));
  1581. }
  1582. pam_passwd = NULL; /* Unset pam_passwd */
  1583. return (retval == PAM_SUCCESS ? STATUS_OK : STATUS_ERROR);
  1584. }
  1585. #endif /* USE_PAM */
  1586. /*----------------------------------------------------------------
  1587. * LDAP authentication system
  1588. *----------------------------------------------------------------
  1589. */
  1590. #ifdef USE_LDAP
  1591. /*
  1592. * Initialize a connection to the LDAP server, including setting up
  1593. * TLS if requested.
  1594. */
  1595. static int
  1596. InitializeLDAPConnection(Port *port, LDAP **ldap)
  1597. {
  1598. int ldapversion = LDAP_VERSION3;
  1599. int r;
  1600. *ldap = ldap_init(port->hba->ldapserver, port->hba->ldapport);
  1601. if (!*ldap)
  1602. {
  1603. #ifndef WIN32
  1604. ereport(LOG,
  1605. (errmsg("could not initialize LDAP: %m")));
  1606. #else
  1607. ereport(LOG,
  1608. (errmsg("could not initialize LDAP: error code %d",
  1609. (int) LdapGetLastError())));
  1610. #endif
  1611. return STATUS_ERROR;
  1612. }
  1613. if ((r = ldap_set_option(*ldap, LDAP_OPT_PROTOCOL_VERSION, &ldapversion)) != LDAP_SUCCESS)
  1614. {
  1615. ldap_unbind(*ldap);
  1616. ereport(LOG,
  1617. (errmsg("could not set LDAP protocol version: %s", ldap_err2string(r))));
  1618. return STATUS_ERROR;
  1619. }
  1620. if (port->hba->ldaptls)
  1621. {
  1622. #ifndef WIN32
  1623. if ((r = ldap_start_tls_s(*ldap, NULL, NULL)) != LDAP_SUCCESS)
  1624. #else
  1625. static __ldap_start_tls_sA _ldap_start_tls_sA = NULL;
  1626. if (_ldap_start_tls_sA == NULL)
  1627. {
  1628. /*
  1629. * Need to load this function dynamically because it does not
  1630. * exist on Windows 2000, and causes a load error for the whole
  1631. * exe if referenced.
  1632. */
  1633. HANDLE ldaphandle;
  1634. ldaphandle = LoadLibrary("WLDAP32.DLL");
  1635. if (ldaphandle == NULL)
  1636. {
  1637. /*
  1638. * should never happen since we import other files from
  1639. * wldap32, but check anyway
  1640. */
  1641. ldap_unbind(*ldap);
  1642. ereport(LOG,
  1643. (errmsg("could not load wldap32.dll")));
  1644. return STATUS_ERROR;
  1645. }
  1646. _ldap_start_tls_sA = (__ldap_start_tls_sA) GetProcAddress(ldaphandle, "ldap_start_tls_sA");
  1647. if (_ldap_start_tls_sA == NULL)
  1648. {
  1649. ldap_unbind(*ldap);
  1650. ereport(LOG,
  1651. (errmsg("could not load function _ldap_start_tls_sA in wldap32.dll"),
  1652. errdetail("LDAP over SSL is not supported on this platform.")));
  1653. return STATUS_ERROR;
  1654. }
  1655. /*
  1656. * Leak LDAP handle on purpose, because we need the library to
  1657. * stay open. This is ok because it will only ever be leaked once
  1658. * per process and is automatically cleaned up on process exit.
  1659. */
  1660. }
  1661. if ((r = _ldap_start_tls_sA(*ldap, NULL, NULL, NULL, NULL)) != LDAP_SUCCESS)
  1662. #endif
  1663. {
  1664. ldap_unbind(*ldap);
  1665. ereport(LOG,
  1666. (errmsg("could not start LDAP TLS session: %s", ldap_err2string(r))));
  1667. return STATUS_ERROR;
  1668. }
  1669. }
  1670. return STATUS_OK;
  1671. }
  1672. /*
  1673. * Perform LDAP authentication
  1674. */
  1675. static int
  1676. CheckLDAPAuth(Port *port)
  1677. {
  1678. char *passwd;
  1679. LDAP *ldap;
  1680. int r;
  1681. char *fulluser;
  1682. if (!port->hba->ldapserver || port->hba->ldapserver[0] == '\0')
  1683. {
  1684. ereport(LOG,
  1685. (errmsg("LDAP server not specified")));
  1686. return STATUS_ERROR;
  1687. }
  1688. if (port->hba->ldapport == 0)
  1689. port->hba->ldapport = LDAP_PORT;
  1690. sendAuthRequest(port, AUTH_REQ_PASSWORD);
  1691. passwd = recv_password_packet(port);
  1692. if (passwd == NULL)
  1693. return STATUS_EOF; /* client wouldn't send password */
  1694. if (strlen(passwd) == 0)
  1695. {
  1696. ereport(LOG,
  1697. (errmsg("empty password returned by client")));
  1698. return STATUS_ERROR;
  1699. }
  1700. if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
  1701. /* Error message already sent */
  1702. return STATUS_ERROR;
  1703. if (port->hba->ldapbasedn)
  1704. {
  1705. /*
  1706. * First perform an LDAP search to find the DN for the user we are
  1707. * trying to log in as.
  1708. */
  1709. char *filter;
  1710. LDAPMessage *search_message;
  1711. LDAPMessage *entry;
  1712. char *attributes[2];
  1713. char *dn;
  1714. char *c;
  1715. int count;
  1716. /*
  1717. * Disallow any characters that we would otherwise need to escape,
  1718. * since they aren't really reasonable in a username anyway. Allowing
  1719. * them would make it possible to inject any kind of custom filters in
  1720. * the LDAP filter.
  1721. */
  1722. for (c = port->user_name; *c; c++)
  1723. {
  1724. if (*c == '*' ||
  1725. *c == '(' ||
  1726. *c == ')' ||
  1727. *c == '\\' ||
  1728. *c == '/')
  1729. {
  1730. ereport(LOG,
  1731. (errmsg("invalid character in user name for LDAP authentication")));
  1732. return STATUS_ERROR;
  1733. }
  1734. }
  1735. /*
  1736. * Bind with a pre-defined username/password (if available) for
  1737. * searching. If none is specified, this turns into an anonymous bind.
  1738. */
  1739. r = ldap_simple_bind_s(ldap,
  1740. port->hba->ldapbinddn ? port->hba->ldapbinddn : "",
  1741. port->hba->ldapbindpasswd ? port->hba->ldapbindpasswd : "");
  1742. if (r != LDAP_SUCCESS)
  1743. {
  1744. ereport(LOG,
  1745. (errmsg("could not perform initial LDAP bind for ldapbinddn \"%s\" on server \"%s\": %s",
  1746. port->hba->ldapbinddn, port->hba->ldapserver, ldap_err2string(r))));
  1747. return STATUS_ERROR;
  1748. }
  1749. /* Fetch just one attribute, else *all* attributes are returned */
  1750. attributes[0] = port->hba->ldapsearchattribute ? port->hba->ldapsearchattribute : "uid";
  1751. attributes[1] = NULL;
  1752. filter = psprintf("(%s=%s)",
  1753. attributes[0],
  1754. port->user_name);
  1755. r = ldap_search_s(ldap,
  1756. port->hba->ldapbasedn,
  1757. port->hba->ldapscope,
  1758. filter,
  1759. attributes,
  1760. 0,
  1761. &search_message);
  1762. if (r != LDAP_SUCCESS)
  1763. {
  1764. ereport(LOG,
  1765. (errmsg("could not search LDAP for filter \"%s\" on server \"%s\": %s",
  1766. filter, port->hba->ldapserver, ldap_err2string(r))));
  1767. pfree(filter);
  1768. return STATUS_ERROR;
  1769. }
  1770. count = ldap_count_entries(ldap, search_message);
  1771. if (count != 1)
  1772. {
  1773. if (count == 0)
  1774. ereport(LOG,
  1775. (errmsg("LDAP user \"%s\" does not exist", port->user_name),
  1776. errdetail("LDAP search for filter \"%s\" on server \"%s\" returned no entries.",
  1777. filter, port->hba->ldapserver)));
  1778. else
  1779. ereport(LOG,
  1780. (errmsg("LDAP user \"%s\" is not unique", port->user_name),
  1781. errdetail_plural("LDAP search for filter \"%s\" on server \"%s\" returned %d entry.",
  1782. "LDAP search for filter \"%s\" on server \"%s\" returned %d entries.",
  1783. count,
  1784. filter, port->hba->ldapserver, count)));
  1785. pfree(filter);
  1786. ldap_msgfree(search_message);
  1787. return STATUS_ERROR;
  1788. }
  1789. entry = ldap_first_entry(ldap, search_message);
  1790. dn = ldap_get_dn(ldap, entry);
  1791. if (dn == NULL)
  1792. {
  1793. int error;
  1794. (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
  1795. ereport(LOG,
  1796. (errmsg("could not get dn for the first entry matching \"%s\" on server \"%s\": %s",
  1797. filter, port->hba->ldapserver, ldap_err2string(error))));
  1798. pfree(filter);
  1799. ldap_msgfree(search_message);
  1800. return STATUS_ERROR;
  1801. }
  1802. fulluser = pstrdup(dn);
  1803. pfree(filter);
  1804. ldap_memfree(dn);
  1805. ldap_msgfree(search_message);
  1806. /* Unbind and disconnect from the LDAP server */
  1807. r = ldap_unbind_s(ldap);
  1808. if (r != LDAP_SUCCESS)
  1809. {
  1810. int error;
  1811. (void) ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &error);
  1812. ereport(LOG,
  1813. (errmsg("could not unbind after searching for user \"%s\" on server \"%s\": %s",
  1814. fulluser, port->hba->ldapserver, ldap_err2string(error))));
  1815. pfree(fulluser);
  1816. return STATUS_ERROR;
  1817. }
  1818. /*
  1819. * Need to re-initialize the LDAP connection, so that we can bind to
  1820. * it with a different username.
  1821. */
  1822. if (InitializeLDAPConnection(port, &ldap) == STATUS_ERROR)
  1823. {
  1824. pfree(fulluser);
  1825. /* Error message already sent */
  1826. return STATUS_ERROR;
  1827. }
  1828. }
  1829. else
  1830. fulluser = psprintf("%s%s%s",
  1831. port->hba->ldapprefix ? port->hba->ldapprefix : "",
  1832. port->user_name,
  1833. port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
  1834. r = ldap_simple_bind_s(ldap, fulluser, passwd);
  1835. ldap_unbind(ldap);
  1836. if (r != LDAP_SUCCESS)
  1837. {
  1838. ereport(LOG,
  1839. (errmsg("LDAP login failed for user \"%s\" on server \"%s\": %s",
  1840. fulluser, port->hba->ldapserver, ldap_err2string(r))));
  1841. pfree(fulluser);
  1842. return STATUS_ERROR;
  1843. }
  1844. pfree(fulluser);
  1845. return STATUS_OK;
  1846. }
  1847. #endif /* USE_LDAP */
  1848. /*----------------------------------------------------------------
  1849. * SSL client certificate authentication
  1850. *----------------------------------------------------------------
  1851. */
  1852. #ifdef USE_SSL
  1853. static int
  1854. CheckCertAuth(Port *port)
  1855. {
  1856. Assert(port->ssl);
  1857. /* Make sure we have received a username in the certificate */
  1858. if (port->peer_cn == NULL ||
  1859. strlen(port->peer_cn) <= 0)
  1860. {
  1861. ereport(LOG,
  1862. (errmsg("certificate authentication failed for user \"%s\": client certificate contains no user name",
  1863. port->user_name)));
  1864. return STATUS_ERROR;
  1865. }
  1866. /* Just pass the certificate CN to the usermap check */
  1867. return check_usermap(port->hba->usermap, port->user_name, port->peer_cn, false);
  1868. }
  1869. #endif
  1870. /*----------------------------------------------------------------
  1871. * RADIUS authentication
  1872. *----------------------------------------------------------------
  1873. */
  1874. /*
  1875. * RADIUS authentication is described in RFC2865 (and several
  1876. * others).
  1877. */
  1878. #define RADIUS_VECTOR_LENGTH 16
  1879. #define RADIUS_HEADER_LENGTH 20
  1880. typedef struct
  1881. {
  1882. uint8 attribute;
  1883. uint8 length;
  1884. uint8 data[1];
  1885. } radius_attribute;
  1886. typedef struct
  1887. {
  1888. uint8 code;
  1889. uint8 id;
  1890. uint16 length;
  1891. uint8 vector[RADIUS_VECTOR_LENGTH];
  1892. } radius_packet;
  1893. /* RADIUS packet types */
  1894. #define RADIUS_ACCESS_REQUEST 1
  1895. #define RADIUS_ACCESS_ACCEPT 2
  1896. #define RADIUS_ACCESS_REJECT 3
  1897. /* RAIDUS attributes */
  1898. #define RADIUS_USER_NAME 1
  1899. #define RADIUS_PASSWORD 2
  1900. #define RADIUS_SERVICE_TYPE 6
  1901. #define RADIUS_NAS_IDENTIFIER 32
  1902. /* RADIUS service types */
  1903. #define RADIUS_AUTHENTICATE_ONLY 8
  1904. /* Maximum size of a RADIUS packet we will create or accept */
  1905. #define RADIUS_BUFFER_SIZE 1024
  1906. /* Seconds to wait - XXX: should be in a config variable! */
  1907. #define RADIUS_TIMEOUT 3
  1908. static void
  1909. radius_add_attribute(radius_packet *packet, uint8 type, const unsigned char *data, int len)
  1910. {
  1911. radius_attribute *attr;
  1912. if (packet->length + len > RADIUS_BUFFER_SIZE)
  1913. {
  1914. /*
  1915. * With remotely realistic data, this can never happen. But catch it
  1916. * just to make sure we don't overrun a buffer. We'll just skip adding
  1917. * the broken attribute, which will in the end cause authentication to
  1918. * fail.
  1919. */
  1920. elog(WARNING,
  1921. "Adding attribute code %d with length %d to radius packet would create oversize packet, ignoring",
  1922. type, len);
  1923. return;
  1924. }
  1925. attr = (radius_attribute *) ((unsigned char *) packet + packet->length);
  1926. attr->attribute = type;
  1927. attr->length = len + 2; /* total size includes type and length */
  1928. memcpy(attr->data, data, len);
  1929. packet->length += attr->length;
  1930. }
  1931. static int
  1932. CheckRADIUSAuth(Port *port)
  1933. {
  1934. char *passwd;
  1935. char *identifier = "postgresql";
  1936. char radius_buffer[RADIUS_BUFFER_SIZE];
  1937. char receive_buffer[RADIUS_BUFFER_SIZE];
  1938. radius_packet *packet = (radius_packet *) radius_buffer;
  1939. radius_packet *receivepacket = (radius_packet *) receive_buffer;
  1940. int32 service = htonl(RADIUS_AUTHENTICATE_ONLY);
  1941. uint8 *cryptvector;
  1942. uint8 encryptedpassword[RADIUS_VECTOR_LENGTH];
  1943. int packetlength;
  1944. pgsocket sock;
  1945. #ifdef HAVE_IPV6
  1946. struct sockaddr_in6 localaddr;
  1947. struct sockaddr_in6 remoteaddr;
  1948. #else
  1949. struct sockaddr_in localaddr;
  1950. struct sockaddr_in remoteaddr;
  1951. #endif
  1952. struct addrinfo hint;
  1953. struct addrinfo *serveraddrs;
  1954. char portstr[128];
  1955. ACCEPT_TYPE_ARG3 addrsize;
  1956. fd_set fdset;
  1957. struct timeval endtime;
  1958. int i,
  1959. r;
  1960. /* Make sure struct alignment is correct */
  1961. Assert(offsetof(radius_packet, vector) == 4);
  1962. /* Verify parameters */
  1963. if (!port->hba->radiusserver || port->hba->radiusserver[0] == '\0')
  1964. {
  1965. ereport(LOG,
  1966. (errmsg("RADIUS server not specified")));
  1967. return STATUS_ERROR;
  1968. }
  1969. if (!port->hba->radiussecret || port->hba->radiussecret[0] == '\0')
  1970. {
  1971. ereport(LOG,
  1972. (errmsg("RADIUS secret not specified")));
  1973. return STATUS_ERROR;
  1974. }
  1975. if (port->hba->radiusport == 0)
  1976. port->hba->radiusport = 1812;
  1977. MemSet(&hint, 0, sizeof(hint));
  1978. hint.ai_socktype = SOCK_DGRAM;
  1979. hint.ai_family = AF_UNSPEC;
  1980. snprintf(portstr, sizeof(portstr), "%d", port->hba->radiusport);
  1981. r = pg_getaddrinfo_all(port->hba->radiusserver, portstr, &hint, &serveraddrs);
  1982. if (r || !serveraddrs)
  1983. {
  1984. ereport(LOG,
  1985. (errmsg("could not translate RADIUS server name \"%s\" to address: %s",
  1986. port->hba->radiusserver, gai_strerror(r))));
  1987. if (serveraddrs)
  1988. pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
  1989. return STATUS_ERROR;
  1990. }
  1991. /* XXX: add support for multiple returned addresses? */
  1992. if (port->hba->radiusidentifier && port->hba->radiusidentifier[0])
  1993. identifier = port->hba->radiusidentifier;
  1994. /* Send regular password request to client, and get the response */
  1995. sendAuthRequest(port, AUTH_REQ_PASSWORD);
  1996. passwd = recv_password_packet(port);
  1997. if (passwd == NULL)
  1998. return STATUS_EOF; /* client wouldn't send password */
  1999. if (strlen(passwd) == 0)
  2000. {
  2001. ereport(LOG,
  2002. (errmsg("empty password returned by client")));
  2003. return STATUS_ERROR;
  2004. }
  2005. if (strlen(passwd) > RADIUS_VECTOR_LENGTH)
  2006. {
  2007. ereport(LOG,
  2008. (errmsg("RADIUS authentication does not support passwords longer than 16 characters")));
  2009. return STATUS_ERROR;
  2010. }
  2011. /* Construct RADIUS packet */
  2012. packet->code = RADIUS_ACCESS_REQUEST;
  2013. packet->length = RADIUS_HEADER_LENGTH;
  2014. #ifdef USE_SSL
  2015. if (RAND_bytes(packet->vector, RADIUS_VECTOR_LENGTH) != 1)
  2016. {
  2017. ereport(LOG,
  2018. (errmsg("could not generate random encryption vector")));
  2019. return STATUS_ERROR;
  2020. }
  2021. #else
  2022. for (i = 0; i < RADIUS_VECTOR_LENGTH; i++)
  2023. /* Use a lower strengh random number of OpenSSL is not available */
  2024. packet->vector[i] = random() % 255;
  2025. #endif
  2026. packet->id = packet->vector[0];
  2027. radius_add_attribute(packet, RADIUS_SERVICE_TYPE, (unsigned char *) &service, sizeof(service));
  2028. radius_add_attribute(packet, RADIUS_USER_NAME, (unsigned char *) port->user_name, strlen(port->user_name));
  2029. radius_add_attribute(packet, RADIUS_NAS_IDENTIFIER, (unsigned char *) identifier, strlen(identifier));
  2030. /*
  2031. * RADIUS password attributes are calculated as: e[0] = p[0] XOR
  2032. * MD5(secret + vector)
  2033. */
  2034. cryptvector = palloc(RADIUS_VECTOR_LENGTH + strlen(port->hba->radiussecret));
  2035. memcpy(cryptvector, port->hba->radiussecret, strlen(port->hba->radiussecret));
  2036. memcpy(cryptvector + strlen(port->hba->radiussecret), packet->vector, RADIUS_VECTOR_LENGTH);
  2037. if (!pg_md5_binary(cryptvector, RADIUS_VECTOR_LENGTH + strlen(port->hba->radiussecret), encryptedpassword))
  2038. {
  2039. ereport(LOG,
  2040. (errmsg("could not perform MD5 encryption of password")));
  2041. pfree(cryptvector);
  2042. return STATUS_ERROR;
  2043. }
  2044. pfree(cryptvector);
  2045. for (i = 0; i < RADIUS_VECTOR_LENGTH; i++)
  2046. {
  2047. if (i < strlen(passwd))
  2048. encryptedpassword[i] = passwd[i] ^ encryptedpassword[i];
  2049. else
  2050. encryptedpassword[i] = '\0' ^ encryptedpassword[i];
  2051. }
  2052. radius_add_attribute(packet, RADIUS_PASSWORD, encryptedpassword, RADIUS_VECTOR_LENGTH);
  2053. /* Length need to be in network order on the wire */
  2054. packetlength = packet->length;
  2055. packet->length = htons(packet->length);
  2056. sock = socket(serveraddrs[0].ai_family, SOCK_DGRAM, 0);
  2057. if (sock < 0)
  2058. {
  2059. ereport(LOG,
  2060. (errmsg("could not create RADIUS socket: %m")));
  2061. pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
  2062. return STATUS_ERROR;
  2063. }
  2064. memset(&localaddr, 0, sizeof(localaddr));
  2065. #ifdef HAVE_IPV6
  2066. localaddr.sin6_family = serveraddrs[0].ai_family;
  2067. localaddr.sin6_addr = in6addr_any;
  2068. if (localaddr.sin6_family == AF_INET6)
  2069. addrsize = sizeof(struct sockaddr_in6);
  2070. else
  2071. addrsize = sizeof(struct sockaddr_in);
  2072. #else
  2073. localaddr.sin_family = serveraddrs[0].ai_family;
  2074. localaddr.sin_addr.s_addr = INADDR_ANY;
  2075. addrsize = sizeof(struct sockaddr_in);
  2076. #endif
  2077. if (bind(sock, (struct sockaddr *) & localaddr, addrsize))
  2078. {
  2079. ereport(LOG,
  2080. (errmsg("could not bind local RADIUS socket: %m")));
  2081. closesocket(sock);
  2082. pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
  2083. return STATUS_ERROR;
  2084. }
  2085. if (sendto(sock, radius_buffer, packetlength, 0,
  2086. serveraddrs[0].ai_addr, serveraddrs[0].ai_addrlen) < 0)
  2087. {
  2088. ereport(LOG,
  2089. (errmsg("could not send RADIUS packet: %m")));
  2090. closesocket(sock);
  2091. pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
  2092. return STATUS_ERROR;
  2093. }
  2094. /* Don't need the server address anymore */
  2095. pg_freeaddrinfo_all(hint.ai_family, serveraddrs);
  2096. /*
  2097. * Figure out at what time we should time out. We can't just use a single
  2098. * call to select() with a timeout, since somebody can be sending invalid
  2099. * packets to our port thus causing us to retry in a loop and never time
  2100. * out.
  2101. */
  2102. gettimeofday(&endtime, NULL);
  2103. endtime.tv_sec += RADIUS_TIMEOUT;
  2104. while (true)
  2105. {
  2106. struct timeval timeout;
  2107. struct timeval now;
  2108. int64 timeoutval;
  2109. gettimeofday(&now, NULL);
  2110. timeoutval = (endtime.tv_sec * 1000000 + endtime.tv_usec) - (now.tv_sec * 1000000 + now.tv_usec);
  2111. if (timeoutval <= 0)
  2112. {
  2113. ereport(LOG,
  2114. (errmsg("timeout waiting for RADIUS response")));
  2115. closesocket(sock);
  2116. return STATUS_ERROR;
  2117. }
  2118. timeout.tv_sec = timeoutval / 1000000;
  2119. timeout.tv_usec = timeoutval % 1000000;
  2120. FD_ZERO(&fdset);
  2121. FD_SET(sock, &fdset);
  2122. r = select(sock + 1, &fdset, NULL, NULL, &timeout);
  2123. if (r < 0)
  2124. {
  2125. if (errno == EINTR)
  2126. continue;
  2127. /* Anything else is an actual error */
  2128. ereport(LOG,
  2129. (errmsg("could not check status on RADIUS socket: %m")));
  2130. closesocket(sock);
  2131. return STATUS_ERROR;
  2132. }
  2133. if (r == 0)
  2134. {
  2135. ereport(LOG,
  2136. (errmsg("timeout waiting for RADIUS response")));
  2137. closesocket(sock);
  2138. return STATUS_ERROR;
  2139. }
  2140. /*
  2141. * Attempt to read the response packet, and verify the contents.
  2142. *
  2143. * Any packet that's not actually a RADIUS packet, or otherwise does
  2144. * not validate as an explicit reject, is just ignored and we retry
  2145. * for another packet (until we reach the timeout). This is to avoid
  2146. * the possibility to denial-of-service the login by flooding the
  2147. * server with invalid packets on the port that we're expecting the
  2148. * RADIUS response on.
  2149. */
  2150. addrsize = sizeof(remoteaddr);
  2151. packetlength = recvfrom(sock, receive_buffer, RADIUS_BUFFER_SIZE, 0,
  2152. (struct sockaddr *) & remoteaddr, &addrsize);
  2153. if (packetlength < 0)
  2154. {
  2155. ereport(LOG,
  2156. (errmsg("could not read RADIUS response: %m")));
  2157. return STATUS_ERROR;
  2158. }
  2159. #ifdef HAVE_IPV6
  2160. if (remoteaddr.sin6_port != htons(port->hba->radiusport))
  2161. #else
  2162. if (remoteaddr.sin_port != htons(port->hba->radiusport))
  2163. #endif
  2164. {
  2165. #ifdef HAVE_IPV6
  2166. ereport(LOG,
  2167. (errmsg("RADIUS response was sent from incorrect port: %d",
  2168. ntohs(remoteaddr.sin6_port))));
  2169. #else
  2170. ereport(LOG,
  2171. (errmsg("RADIUS response was sent from incorrect port: %d",
  2172. ntohs(remoteaddr.sin_port))));
  2173. #endif
  2174. continue;
  2175. }
  2176. if (packetlength < RADIUS_HEADER_LENGTH)
  2177. {
  2178. ereport(LOG,
  2179. (errmsg("RADIUS response too short: %d", packetlength)));
  2180. continue;
  2181. }
  2182. if (packetlength != ntohs(receivepacket->length))
  2183. {
  2184. ereport(LOG,
  2185. (errmsg("RADIUS response has corrupt length: %d (actual length %d)",
  2186. ntohs(receivepacket->length), packetlength)));
  2187. continue;
  2188. }
  2189. if (packet->id != receivepacket->id)
  2190. {
  2191. ereport(LOG,
  2192. (errmsg("RADIUS response is to a different request: %d (should be %d)",
  2193. receivepacket->id, packet->id)));
  2194. continue;
  2195. }
  2196. /*
  2197. * Verify the response authenticator, which is calculated as
  2198. * MD5(Code+ID+Length+RequestAuthenticator+Attributes+Secret)
  2199. */
  2200. cryptvector = palloc(packetlength + strlen(port->hba->radiussecret));
  2201. memcpy(cryptvector, receivepacket, 4); /* code+id+length */
  2202. memcpy(cryptvector + 4, packet->vector, RADIUS_VECTOR_LENGTH); /* request
  2203. * authenticator, from
  2204. * original packet */
  2205. if (packetlength > RADIUS_HEADER_LENGTH) /* there may be no
  2206. * attributes at all */
  2207. memcpy(cryptvector + RADIUS_HEADER_LENGTH, receive_buffer + RADIUS_HEADER_LENGTH, packetlength - RADIUS_HEADER_LENGTH);
  2208. memcpy(cryptvector + packetlength, port->hba->radiussecret, strlen(port->hba->radiussecret));
  2209. if (!pg_md5_binary(cryptvector,
  2210. packetlength + strlen(port->hba->radiussecret),
  2211. encryptedpassword))
  2212. {
  2213. ereport(LOG,
  2214. (errmsg("could not perform MD5 encryption of received packet")));
  2215. pfree(cryptvector);
  2216. continue;
  2217. }
  2218. pfree(cryptvector);
  2219. if (memcmp(receivepacket->vector, encryptedpassword, RADIUS_VECTOR_LENGTH) != 0)
  2220. {
  2221. ereport(LOG,
  2222. (errmsg("RADIUS response has incorrect MD5 signature")));
  2223. continue;
  2224. }
  2225. if (receivepacket->code == RADIUS_ACCESS_ACCEPT)
  2226. {
  2227. closesocket(sock);
  2228. return STATUS_OK;
  2229. }
  2230. else if (receivepacket->code == RADIUS_ACCESS_REJECT)
  2231. {
  2232. closesocket(sock);
  2233. return STATUS_ERROR;
  2234. }
  2235. else
  2236. {
  2237. ereport(LOG,
  2238. (errmsg("RADIUS response has invalid code (%d) for user \"%s\"",
  2239. receivepacket->code, port->user_name)));
  2240. continue;
  2241. }
  2242. } /* while (true) */
  2243. }