1 /*-------------------------------------------------------------------------
2  *
3  * fe-auth.c
4  *	   The front-end (client) authorization routines
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  *	  src/interfaces/libpq/fe-auth.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 
15 /*
16  * INTERFACE ROUTINES
17  *	   frontend (client) routines:
18  *		pg_fe_sendauth			send authentication information
19  *		pg_fe_getauthname		get user's name according to the client side
20  *								of the authentication system
21  */
22 
23 #include "postgres_fe.h"
24 
25 #ifdef WIN32
26 #include "win32.h"
27 #else
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/param.h>			/* for MAXHOSTNAMELEN on most */
31 #include <sys/socket.h>
32 #ifdef HAVE_SYS_UCRED_H
33 #include <sys/ucred.h>
34 #endif
35 #ifndef  MAXHOSTNAMELEN
36 #include <netdb.h>				/* for MAXHOSTNAMELEN on some */
37 #endif
38 #include <pwd.h>
39 #endif
40 
41 #include "common/md5.h"
42 #include "libpq-fe.h"
43 #include "libpq/scram.h"
44 #include "fe-auth.h"
45 
46 
47 #ifdef ENABLE_GSS
48 /*
49  * GSSAPI authentication system.
50  */
51 
52 #if defined(WIN32) && !defined(_MSC_VER)
53 /*
54  * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW
55  * that contain the OIDs required. Redefine here, values copied
56  * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c
57  */
58 static const gss_OID_desc GSS_C_NT_HOSTBASED_SERVICE_desc =
59 {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x04"};
60 static GSS_DLLIMP gss_OID GSS_C_NT_HOSTBASED_SERVICE = &GSS_C_NT_HOSTBASED_SERVICE_desc;
61 #endif
62 
63 /*
64  * Fetch all errors of a specific type and append to "str".
65  */
66 static void
pg_GSS_error_int(PQExpBuffer str,const char * mprefix,OM_uint32 stat,int type)67 pg_GSS_error_int(PQExpBuffer str, const char *mprefix,
68 				 OM_uint32 stat, int type)
69 {
70 	OM_uint32	lmin_s;
71 	gss_buffer_desc lmsg;
72 	OM_uint32	msg_ctx = 0;
73 
74 	do
75 	{
76 		gss_display_status(&lmin_s, stat, type,
77 						   GSS_C_NO_OID, &msg_ctx, &lmsg);
78 		appendPQExpBuffer(str, "%s: ", mprefix);
79 		appendBinaryPQExpBuffer(str, lmsg.value, lmsg.length);
80 		appendPQExpBufferChar(str, '\n');
81 		gss_release_buffer(&lmin_s, &lmsg);
82 	} while (msg_ctx);
83 }
84 
85 /*
86  * GSSAPI errors contain two parts; put both into conn->errorMessage.
87  */
88 static void
pg_GSS_error(const char * mprefix,PGconn * conn,OM_uint32 maj_stat,OM_uint32 min_stat)89 pg_GSS_error(const char *mprefix, PGconn *conn,
90 			 OM_uint32 maj_stat, OM_uint32 min_stat)
91 {
92 	resetPQExpBuffer(&conn->errorMessage);
93 
94 	/* Fetch major error codes */
95 	pg_GSS_error_int(&conn->errorMessage, mprefix, maj_stat, GSS_C_GSS_CODE);
96 
97 	/* Add the minor codes as well */
98 	pg_GSS_error_int(&conn->errorMessage, mprefix, min_stat, GSS_C_MECH_CODE);
99 }
100 
101 /*
102  * Continue GSS authentication with next token as needed.
103  */
104 static int
pg_GSS_continue(PGconn * conn,int payloadlen)105 pg_GSS_continue(PGconn *conn, int payloadlen)
106 {
107 	OM_uint32	maj_stat,
108 				min_stat,
109 				lmin_s;
110 	gss_buffer_desc ginbuf;
111 	gss_buffer_desc goutbuf;
112 
113 	/*
114 	 * On first call, there's no input token. On subsequent calls, read the
115 	 * input token into a GSS buffer.
116 	 */
117 	if (conn->gctx != GSS_C_NO_CONTEXT)
118 	{
119 		ginbuf.length = payloadlen;
120 		ginbuf.value = malloc(payloadlen);
121 		if (!ginbuf.value)
122 		{
123 			printfPQExpBuffer(&conn->errorMessage,
124 							  libpq_gettext("out of memory allocating GSSAPI buffer (%d)\n"),
125 							  payloadlen);
126 			return STATUS_ERROR;
127 		}
128 		if (pqGetnchar(ginbuf.value, payloadlen, conn))
129 		{
130 			/*
131 			 * Shouldn't happen, because the caller should've ensured that the
132 			 * whole message is already in the input buffer.
133 			 */
134 			free(ginbuf.value);
135 			return STATUS_ERROR;
136 		}
137 	}
138 	else
139 	{
140 		ginbuf.length = 0;
141 		ginbuf.value = NULL;
142 	}
143 
144 	maj_stat = gss_init_sec_context(&min_stat,
145 									GSS_C_NO_CREDENTIAL,
146 									&conn->gctx,
147 									conn->gtarg_nam,
148 									GSS_C_NO_OID,
149 									GSS_C_MUTUAL_FLAG,
150 									0,
151 									GSS_C_NO_CHANNEL_BINDINGS,
152 									(ginbuf.value == NULL) ? GSS_C_NO_BUFFER : &ginbuf,
153 									NULL,
154 									&goutbuf,
155 									NULL,
156 									NULL);
157 
158 	if (ginbuf.value)
159 		free(ginbuf.value);
160 
161 	if (goutbuf.length != 0)
162 	{
163 		/*
164 		 * GSS generated data to send to the server. We don't care if it's the
165 		 * first or subsequent packet, just send the same kind of password
166 		 * packet.
167 		 */
168 		if (pqPacketSend(conn, 'p',
169 						 goutbuf.value, goutbuf.length) != STATUS_OK)
170 		{
171 			gss_release_buffer(&lmin_s, &goutbuf);
172 			return STATUS_ERROR;
173 		}
174 	}
175 	gss_release_buffer(&lmin_s, &goutbuf);
176 
177 	if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED)
178 	{
179 		pg_GSS_error(libpq_gettext("GSSAPI continuation error"),
180 					 conn,
181 					 maj_stat, min_stat);
182 		gss_release_name(&lmin_s, &conn->gtarg_nam);
183 		if (conn->gctx)
184 			gss_delete_sec_context(&lmin_s, &conn->gctx, GSS_C_NO_BUFFER);
185 		return STATUS_ERROR;
186 	}
187 
188 	if (maj_stat == GSS_S_COMPLETE)
189 		gss_release_name(&lmin_s, &conn->gtarg_nam);
190 
191 	return STATUS_OK;
192 }
193 
194 /*
195  * Send initial GSS authentication token
196  */
197 static int
pg_GSS_startup(PGconn * conn,int payloadlen)198 pg_GSS_startup(PGconn *conn, int payloadlen)
199 {
200 	OM_uint32	maj_stat,
201 				min_stat;
202 	int			maxlen;
203 	gss_buffer_desc temp_gbuf;
204 	char	   *host = conn->connhost[conn->whichhost].host;
205 
206 	if (!(host && host[0] != '\0'))
207 	{
208 		printfPQExpBuffer(&conn->errorMessage,
209 						  libpq_gettext("host name must be specified\n"));
210 		return STATUS_ERROR;
211 	}
212 
213 	if (conn->gctx)
214 	{
215 		printfPQExpBuffer(&conn->errorMessage,
216 						  libpq_gettext("duplicate GSS authentication request\n"));
217 		return STATUS_ERROR;
218 	}
219 
220 	/*
221 	 * Import service principal name so the proper ticket can be acquired by
222 	 * the GSSAPI system.
223 	 */
224 	maxlen = NI_MAXHOST + strlen(conn->krbsrvname) + 2;
225 	temp_gbuf.value = (char *) malloc(maxlen);
226 	if (!temp_gbuf.value)
227 	{
228 		printfPQExpBuffer(&conn->errorMessage,
229 						  libpq_gettext("out of memory\n"));
230 		return STATUS_ERROR;
231 	}
232 	snprintf(temp_gbuf.value, maxlen, "%s@%s",
233 			 conn->krbsrvname, host);
234 	temp_gbuf.length = strlen(temp_gbuf.value);
235 
236 	maj_stat = gss_import_name(&min_stat, &temp_gbuf,
237 							   GSS_C_NT_HOSTBASED_SERVICE, &conn->gtarg_nam);
238 	free(temp_gbuf.value);
239 
240 	if (maj_stat != GSS_S_COMPLETE)
241 	{
242 		pg_GSS_error(libpq_gettext("GSSAPI name import error"),
243 					 conn,
244 					 maj_stat, min_stat);
245 		return STATUS_ERROR;
246 	}
247 
248 	/*
249 	 * Initial packet is the same as a continuation packet with no initial
250 	 * context.
251 	 */
252 	conn->gctx = GSS_C_NO_CONTEXT;
253 
254 	return pg_GSS_continue(conn, payloadlen);
255 }
256 #endif							/* ENABLE_GSS */
257 
258 
259 #ifdef ENABLE_SSPI
260 /*
261  * SSPI authentication system (Windows only)
262  */
263 
264 static void
pg_SSPI_error(PGconn * conn,const char * mprefix,SECURITY_STATUS r)265 pg_SSPI_error(PGconn *conn, const char *mprefix, SECURITY_STATUS r)
266 {
267 	char		sysmsg[256];
268 
269 	if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
270 					  FORMAT_MESSAGE_FROM_SYSTEM,
271 					  NULL, r, 0,
272 					  sysmsg, sizeof(sysmsg), NULL) == 0)
273 		printfPQExpBuffer(&conn->errorMessage, "%s: SSPI error %x\n",
274 						  mprefix, (unsigned int) r);
275 	else
276 		printfPQExpBuffer(&conn->errorMessage, "%s: %s (%x)\n",
277 						  mprefix, sysmsg, (unsigned int) r);
278 }
279 
280 /*
281  * Continue SSPI authentication with next token as needed.
282  */
283 static int
pg_SSPI_continue(PGconn * conn,int payloadlen)284 pg_SSPI_continue(PGconn *conn, int payloadlen)
285 {
286 	SECURITY_STATUS r;
287 	CtxtHandle	newContext;
288 	ULONG		contextAttr;
289 	SecBufferDesc inbuf;
290 	SecBufferDesc outbuf;
291 	SecBuffer	OutBuffers[1];
292 	SecBuffer	InBuffers[1];
293 	char	   *inputbuf = NULL;
294 
295 	if (conn->sspictx != NULL)
296 	{
297 		/*
298 		 * On runs other than the first we have some data to send. Put this
299 		 * data in a SecBuffer type structure.
300 		 */
301 		inputbuf = malloc(payloadlen);
302 		if (!inputbuf)
303 		{
304 			printfPQExpBuffer(&conn->errorMessage,
305 							  libpq_gettext("out of memory allocating SSPI buffer (%d)\n"),
306 							  payloadlen);
307 			return STATUS_ERROR;
308 		}
309 		if (pqGetnchar(inputbuf, payloadlen, conn))
310 		{
311 			/*
312 			 * Shouldn't happen, because the caller should've ensured that the
313 			 * whole message is already in the input buffer.
314 			 */
315 			free(inputbuf);
316 			return STATUS_ERROR;
317 		}
318 
319 		inbuf.ulVersion = SECBUFFER_VERSION;
320 		inbuf.cBuffers = 1;
321 		inbuf.pBuffers = InBuffers;
322 		InBuffers[0].pvBuffer = inputbuf;
323 		InBuffers[0].cbBuffer = payloadlen;
324 		InBuffers[0].BufferType = SECBUFFER_TOKEN;
325 	}
326 
327 	OutBuffers[0].pvBuffer = NULL;
328 	OutBuffers[0].BufferType = SECBUFFER_TOKEN;
329 	OutBuffers[0].cbBuffer = 0;
330 	outbuf.cBuffers = 1;
331 	outbuf.pBuffers = OutBuffers;
332 	outbuf.ulVersion = SECBUFFER_VERSION;
333 
334 	r = InitializeSecurityContext(conn->sspicred,
335 								  conn->sspictx,
336 								  conn->sspitarget,
337 								  ISC_REQ_ALLOCATE_MEMORY,
338 								  0,
339 								  SECURITY_NETWORK_DREP,
340 								  (conn->sspictx == NULL) ? NULL : &inbuf,
341 								  0,
342 								  &newContext,
343 								  &outbuf,
344 								  &contextAttr,
345 								  NULL);
346 
347 	/* we don't need the input anymore */
348 	if (inputbuf)
349 		free(inputbuf);
350 
351 	if (r != SEC_E_OK && r != SEC_I_CONTINUE_NEEDED)
352 	{
353 		pg_SSPI_error(conn, libpq_gettext("SSPI continuation error"), r);
354 
355 		return STATUS_ERROR;
356 	}
357 
358 	if (conn->sspictx == NULL)
359 	{
360 		/* On first run, transfer retrieved context handle */
361 		conn->sspictx = malloc(sizeof(CtxtHandle));
362 		if (conn->sspictx == NULL)
363 		{
364 			printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n"));
365 			return STATUS_ERROR;
366 		}
367 		memcpy(conn->sspictx, &newContext, sizeof(CtxtHandle));
368 	}
369 
370 	/*
371 	 * If SSPI returned any data to be sent to the server (as it normally
372 	 * would), send this data as a password packet.
373 	 */
374 	if (outbuf.cBuffers > 0)
375 	{
376 		if (outbuf.cBuffers != 1)
377 		{
378 			/*
379 			 * This should never happen, at least not for Kerberos
380 			 * authentication. Keep check in case it shows up with other
381 			 * authentication methods later.
382 			 */
383 			printfPQExpBuffer(&conn->errorMessage, "SSPI returned invalid number of output buffers\n");
384 			return STATUS_ERROR;
385 		}
386 
387 		/*
388 		 * If the negotiation is complete, there may be zero bytes to send.
389 		 * The server is at this point not expecting any more data, so don't
390 		 * send it.
391 		 */
392 		if (outbuf.pBuffers[0].cbBuffer > 0)
393 		{
394 			if (pqPacketSend(conn, 'p',
395 							 outbuf.pBuffers[0].pvBuffer, outbuf.pBuffers[0].cbBuffer))
396 			{
397 				FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
398 				return STATUS_ERROR;
399 			}
400 		}
401 		FreeContextBuffer(outbuf.pBuffers[0].pvBuffer);
402 	}
403 
404 	/* Cleanup is handled by the code in freePGconn() */
405 	return STATUS_OK;
406 }
407 
408 /*
409  * Send initial SSPI authentication token.
410  * If use_negotiate is 0, use kerberos authentication package which is
411  * compatible with Unix. If use_negotiate is 1, use the negotiate package
412  * which supports both kerberos and NTLM, but is not compatible with Unix.
413  */
414 static int
pg_SSPI_startup(PGconn * conn,int use_negotiate,int payloadlen)415 pg_SSPI_startup(PGconn *conn, int use_negotiate, int payloadlen)
416 {
417 	SECURITY_STATUS r;
418 	TimeStamp	expire;
419 	char	   *host = conn->connhost[conn->whichhost].host;
420 
421 	if (conn->sspictx)
422 	{
423 		printfPQExpBuffer(&conn->errorMessage,
424 						  libpq_gettext("duplicate SSPI authentication request\n"));
425 		return STATUS_ERROR;
426 	}
427 
428 	/*
429 	 * Retrieve credentials handle
430 	 */
431 	conn->sspicred = malloc(sizeof(CredHandle));
432 	if (conn->sspicred == NULL)
433 	{
434 		printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n"));
435 		return STATUS_ERROR;
436 	}
437 
438 	r = AcquireCredentialsHandle(NULL,
439 								 use_negotiate ? "negotiate" : "kerberos",
440 								 SECPKG_CRED_OUTBOUND,
441 								 NULL,
442 								 NULL,
443 								 NULL,
444 								 NULL,
445 								 conn->sspicred,
446 								 &expire);
447 	if (r != SEC_E_OK)
448 	{
449 		pg_SSPI_error(conn, libpq_gettext("could not acquire SSPI credentials"), r);
450 		free(conn->sspicred);
451 		conn->sspicred = NULL;
452 		return STATUS_ERROR;
453 	}
454 
455 	/*
456 	 * Compute target principal name. SSPI has a different format from GSSAPI,
457 	 * but not more complex. We can skip the @REALM part, because Windows will
458 	 * fill that in for us automatically.
459 	 */
460 	if (!(host && host[0] != '\0'))
461 	{
462 		printfPQExpBuffer(&conn->errorMessage,
463 						  libpq_gettext("host name must be specified\n"));
464 		return STATUS_ERROR;
465 	}
466 	conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(host) + 2);
467 	if (!conn->sspitarget)
468 	{
469 		printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n"));
470 		return STATUS_ERROR;
471 	}
472 	sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, host);
473 
474 	/*
475 	 * Indicate that we're in SSPI authentication mode to make sure that
476 	 * pg_SSPI_continue is called next time in the negotiation.
477 	 */
478 	conn->usesspi = 1;
479 
480 	return pg_SSPI_continue(conn, payloadlen);
481 }
482 #endif							/* ENABLE_SSPI */
483 
484 /*
485  * Initialize SASL authentication exchange.
486  */
487 static int
pg_SASL_init(PGconn * conn,int payloadlen)488 pg_SASL_init(PGconn *conn, int payloadlen)
489 {
490 	char	   *initialresponse = NULL;
491 	int			initialresponselen;
492 	bool		done;
493 	bool		success;
494 	const char *selected_mechanism;
495 	PQExpBufferData mechanism_buf;
496 
497 	initPQExpBuffer(&mechanism_buf);
498 
499 	if (conn->sasl_state)
500 	{
501 		printfPQExpBuffer(&conn->errorMessage,
502 						  libpq_gettext("duplicate SASL authentication request\n"));
503 		goto error;
504 	}
505 
506 	/*
507 	 * Parse the list of SASL authentication mechanisms in the
508 	 * AuthenticationSASL message, and select the best mechanism that we
509 	 * support.  (Only SCRAM-SHA-256 is supported at the moment.)
510 	 */
511 	selected_mechanism = NULL;
512 	for (;;)
513 	{
514 		if (pqGets(&mechanism_buf, conn))
515 		{
516 			printfPQExpBuffer(&conn->errorMessage,
517 							  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
518 			goto error;
519 		}
520 		if (PQExpBufferDataBroken(mechanism_buf))
521 			goto oom_error;
522 
523 		/* An empty string indicates end of list */
524 		if (mechanism_buf.data[0] == '\0')
525 			break;
526 
527 		/*
528 		 * If we have already selected a mechanism, just skip through the rest
529 		 * of the list.
530 		 */
531 		if (selected_mechanism)
532 			continue;
533 
534 		/*
535 		 * Do we support this mechanism?
536 		 */
537 		if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0)
538 		{
539 			char	   *password;
540 
541 			conn->password_needed = true;
542 			password = conn->connhost[conn->whichhost].password;
543 			if (password == NULL)
544 				password = conn->pgpass;
545 			if (password == NULL || password[0] == '\0')
546 			{
547 				printfPQExpBuffer(&conn->errorMessage,
548 								  PQnoPasswordSupplied);
549 				goto error;
550 			}
551 
552 			conn->sasl_state = pg_fe_scram_init(conn->pguser, password);
553 			if (!conn->sasl_state)
554 				goto oom_error;
555 			selected_mechanism = SCRAM_SHA_256_NAME;
556 		}
557 	}
558 
559 	if (!selected_mechanism)
560 	{
561 		printfPQExpBuffer(&conn->errorMessage,
562 						  libpq_gettext("none of the server's SASL authentication mechanisms are supported\n"));
563 		goto error;
564 	}
565 
566 	/* Get the mechanism-specific Initial Client Response, if any */
567 	pg_fe_scram_exchange(conn->sasl_state,
568 						 NULL, -1,
569 						 &initialresponse, &initialresponselen,
570 						 &done, &success, &conn->errorMessage);
571 
572 	if (done && !success)
573 		goto error;
574 
575 	/*
576 	 * Build a SASLInitialResponse message, and send it.
577 	 */
578 	if (pqPutMsgStart('p', true, conn))
579 		goto error;
580 	if (pqPuts(selected_mechanism, conn))
581 		goto error;
582 	if (initialresponse)
583 	{
584 		if (pqPutInt(initialresponselen, 4, conn))
585 			goto error;
586 		if (pqPutnchar(initialresponse, initialresponselen, conn))
587 			goto error;
588 	}
589 	if (pqPutMsgEnd(conn))
590 		goto error;
591 	if (pqFlush(conn))
592 		goto error;
593 
594 	termPQExpBuffer(&mechanism_buf);
595 	if (initialresponse)
596 		free(initialresponse);
597 
598 	return STATUS_OK;
599 
600 error:
601 	termPQExpBuffer(&mechanism_buf);
602 	if (initialresponse)
603 		free(initialresponse);
604 	return STATUS_ERROR;
605 
606 oom_error:
607 	termPQExpBuffer(&mechanism_buf);
608 	if (initialresponse)
609 		free(initialresponse);
610 	printfPQExpBuffer(&conn->errorMessage,
611 					  libpq_gettext("out of memory\n"));
612 	return STATUS_ERROR;
613 }
614 
615 /*
616  * Exchange a message for SASL communication protocol with the backend.
617  * This should be used after calling pg_SASL_init to set up the status of
618  * the protocol.
619  */
620 static int
pg_SASL_continue(PGconn * conn,int payloadlen,bool final)621 pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
622 {
623 	char	   *output;
624 	int			outputlen;
625 	bool		done;
626 	bool		success;
627 	int			res;
628 	char	   *challenge;
629 
630 	/* Read the SASL challenge from the AuthenticationSASLContinue message. */
631 	challenge = malloc(payloadlen + 1);
632 	if (!challenge)
633 	{
634 		printfPQExpBuffer(&conn->errorMessage,
635 						  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
636 						  payloadlen);
637 		return STATUS_ERROR;
638 	}
639 
640 	if (pqGetnchar(challenge, payloadlen, conn))
641 	{
642 		free(challenge);
643 		return STATUS_ERROR;
644 	}
645 	/* For safety and convenience, ensure the buffer is NULL-terminated. */
646 	challenge[payloadlen] = '\0';
647 
648 	pg_fe_scram_exchange(conn->sasl_state,
649 						 challenge, payloadlen,
650 						 &output, &outputlen,
651 						 &done, &success, &conn->errorMessage);
652 	free(challenge);			/* don't need the input anymore */
653 
654 	if (final && !done)
655 	{
656 		if (outputlen != 0)
657 			free(output);
658 
659 		printfPQExpBuffer(&conn->errorMessage,
660 						  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
661 		return STATUS_ERROR;
662 	}
663 	if (outputlen != 0)
664 	{
665 		/*
666 		 * Send the SASL response to the server.
667 		 */
668 		res = pqPacketSend(conn, 'p', output, outputlen);
669 		free(output);
670 
671 		if (res != STATUS_OK)
672 			return STATUS_ERROR;
673 	}
674 
675 	if (done && !success)
676 		return STATUS_ERROR;
677 
678 	return STATUS_OK;
679 }
680 
681 /*
682  * Respond to AUTH_REQ_SCM_CREDS challenge.
683  *
684  * Note: this is dead code as of Postgres 9.1, because current backends will
685  * never send this challenge.  But we must keep it as long as libpq needs to
686  * interoperate with pre-9.1 servers.  It is believed to be needed only on
687  * Debian/kFreeBSD (ie, FreeBSD kernel with Linux userland, so that the
688  * getpeereid() function isn't provided by libc).
689  */
690 static int
pg_local_sendauth(PGconn * conn)691 pg_local_sendauth(PGconn *conn)
692 {
693 #ifdef HAVE_STRUCT_CMSGCRED
694 	char		buf;
695 	struct iovec iov;
696 	struct msghdr msg;
697 	struct cmsghdr *cmsg;
698 	union
699 	{
700 		struct cmsghdr hdr;
701 		unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
702 	}			cmsgbuf;
703 
704 	/*
705 	 * The backend doesn't care what we send here, but it wants exactly one
706 	 * character to force recvmsg() to block and wait for us.
707 	 */
708 	buf = '\0';
709 	iov.iov_base = &buf;
710 	iov.iov_len = 1;
711 
712 	memset(&msg, 0, sizeof(msg));
713 	msg.msg_iov = &iov;
714 	msg.msg_iovlen = 1;
715 
716 	/* We must set up a message that will be filled in by kernel */
717 	memset(&cmsgbuf, 0, sizeof(cmsgbuf));
718 	msg.msg_control = &cmsgbuf.buf;
719 	msg.msg_controllen = sizeof(cmsgbuf.buf);
720 	cmsg = CMSG_FIRSTHDR(&msg);
721 	cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
722 	cmsg->cmsg_level = SOL_SOCKET;
723 	cmsg->cmsg_type = SCM_CREDS;
724 
725 	if (sendmsg(conn->sock, &msg, 0) == -1)
726 	{
727 		char		sebuf[256];
728 
729 		printfPQExpBuffer(&conn->errorMessage,
730 						  "pg_local_sendauth: sendmsg: %s\n",
731 						  pqStrerror(errno, sebuf, sizeof(sebuf)));
732 		return STATUS_ERROR;
733 	}
734 	return STATUS_OK;
735 #else
736 	printfPQExpBuffer(&conn->errorMessage,
737 					  libpq_gettext("SCM_CRED authentication method not supported\n"));
738 	return STATUS_ERROR;
739 #endif
740 }
741 
742 static int
pg_password_sendauth(PGconn * conn,const char * password,AuthRequest areq)743 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
744 {
745 	int			ret;
746 	char	   *crypt_pwd = NULL;
747 	const char *pwd_to_send;
748 	char		md5Salt[4];
749 
750 	/* Read the salt from the AuthenticationMD5 message. */
751 	if (areq == AUTH_REQ_MD5)
752 	{
753 		if (pqGetnchar(md5Salt, 4, conn))
754 			return STATUS_ERROR;	/* shouldn't happen */
755 	}
756 
757 	/* Encrypt the password if needed. */
758 
759 	switch (areq)
760 	{
761 		case AUTH_REQ_MD5:
762 			{
763 				char	   *crypt_pwd2;
764 
765 				/* Allocate enough space for two MD5 hashes */
766 				crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
767 				if (!crypt_pwd)
768 				{
769 					printfPQExpBuffer(&conn->errorMessage,
770 									  libpq_gettext("out of memory\n"));
771 					return STATUS_ERROR;
772 				}
773 
774 				crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
775 				if (!pg_md5_encrypt(password, conn->pguser,
776 									strlen(conn->pguser), crypt_pwd2))
777 				{
778 					free(crypt_pwd);
779 					return STATUS_ERROR;
780 				}
781 				if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
782 									4, crypt_pwd))
783 				{
784 					free(crypt_pwd);
785 					return STATUS_ERROR;
786 				}
787 
788 				pwd_to_send = crypt_pwd;
789 				break;
790 			}
791 		case AUTH_REQ_PASSWORD:
792 			pwd_to_send = password;
793 			break;
794 		default:
795 			return STATUS_ERROR;
796 	}
797 	/* Packet has a message type as of protocol 3.0 */
798 	if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
799 		ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
800 	else
801 		ret = pqPacketSend(conn, 0, pwd_to_send, strlen(pwd_to_send) + 1);
802 	if (crypt_pwd)
803 		free(crypt_pwd);
804 	return ret;
805 }
806 
807 /*
808  * pg_fe_sendauth
809  *		client demux routine for processing an authentication request
810  *
811  * The server has sent us an authentication challenge (or OK). Send an
812  * appropriate response. The caller has ensured that the whole message is
813  * now in the input buffer, and has already read the type and length of
814  * it. We are responsible for reading any remaining extra data, specific
815  * to the authentication method. 'payloadlen' is the remaining length in
816  * the message.
817  */
818 int
pg_fe_sendauth(AuthRequest areq,int payloadlen,PGconn * conn)819 pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
820 {
821 	switch (areq)
822 	{
823 		case AUTH_REQ_OK:
824 			break;
825 
826 		case AUTH_REQ_KRB4:
827 			printfPQExpBuffer(&conn->errorMessage,
828 							  libpq_gettext("Kerberos 4 authentication not supported\n"));
829 			return STATUS_ERROR;
830 
831 		case AUTH_REQ_KRB5:
832 			printfPQExpBuffer(&conn->errorMessage,
833 							  libpq_gettext("Kerberos 5 authentication not supported\n"));
834 			return STATUS_ERROR;
835 
836 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
837 		case AUTH_REQ_GSS:
838 #if !defined(ENABLE_SSPI)
839 			/* no native SSPI, so use GSSAPI library for it */
840 		case AUTH_REQ_SSPI:
841 #endif
842 			{
843 				int			r;
844 
845 				pglock_thread();
846 
847 				/*
848 				 * If we have both GSS and SSPI support compiled in, use SSPI
849 				 * support by default. This is overridable by a connection
850 				 * string parameter. Note that when using SSPI we still leave
851 				 * the negotiate parameter off, since we want SSPI to use the
852 				 * GSSAPI kerberos protocol. For actual SSPI negotiate
853 				 * protocol, we use AUTH_REQ_SSPI.
854 				 */
855 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
856 				if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
857 					r = pg_GSS_startup(conn, payloadlen);
858 				else
859 					r = pg_SSPI_startup(conn, 0, payloadlen);
860 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
861 				r = pg_GSS_startup(conn, payloadlen);
862 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
863 				r = pg_SSPI_startup(conn, 0, payloadlen);
864 #endif
865 				if (r != STATUS_OK)
866 				{
867 					/* Error message already filled in. */
868 					pgunlock_thread();
869 					return STATUS_ERROR;
870 				}
871 				pgunlock_thread();
872 			}
873 			break;
874 
875 		case AUTH_REQ_GSS_CONT:
876 			{
877 				int			r;
878 
879 				pglock_thread();
880 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
881 				if (conn->usesspi)
882 					r = pg_SSPI_continue(conn, payloadlen);
883 				else
884 					r = pg_GSS_continue(conn, payloadlen);
885 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
886 				r = pg_GSS_continue(conn, payloadlen);
887 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
888 				r = pg_SSPI_continue(conn, payloadlen);
889 #endif
890 				if (r != STATUS_OK)
891 				{
892 					/* Error message already filled in. */
893 					pgunlock_thread();
894 					return STATUS_ERROR;
895 				}
896 				pgunlock_thread();
897 			}
898 			break;
899 #else							/* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
900 			/* No GSSAPI *or* SSPI support */
901 		case AUTH_REQ_GSS:
902 		case AUTH_REQ_GSS_CONT:
903 			printfPQExpBuffer(&conn->errorMessage,
904 							  libpq_gettext("GSSAPI authentication not supported\n"));
905 			return STATUS_ERROR;
906 #endif							/* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
907 
908 #ifdef ENABLE_SSPI
909 		case AUTH_REQ_SSPI:
910 
911 			/*
912 			 * SSPI has it's own startup message so libpq can decide which
913 			 * method to use. Indicate to pg_SSPI_startup that we want SSPI
914 			 * negotiation instead of Kerberos.
915 			 */
916 			pglock_thread();
917 			if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
918 			{
919 				/* Error message already filled in. */
920 				pgunlock_thread();
921 				return STATUS_ERROR;
922 			}
923 			pgunlock_thread();
924 			break;
925 #else
926 
927 			/*
928 			 * No SSPI support. However, if we have GSSAPI but not SSPI
929 			 * support, AUTH_REQ_SSPI will have been handled in the codepath
930 			 * for AUTH_REQ_GSSAPI above, so don't duplicate the case label in
931 			 * that case.
932 			 */
933 #if !defined(ENABLE_GSS)
934 		case AUTH_REQ_SSPI:
935 			printfPQExpBuffer(&conn->errorMessage,
936 							  libpq_gettext("SSPI authentication not supported\n"));
937 			return STATUS_ERROR;
938 #endif							/* !define(ENABLE_GSSAPI) */
939 #endif							/* ENABLE_SSPI */
940 
941 
942 		case AUTH_REQ_CRYPT:
943 			printfPQExpBuffer(&conn->errorMessage,
944 							  libpq_gettext("Crypt authentication not supported\n"));
945 			return STATUS_ERROR;
946 
947 		case AUTH_REQ_MD5:
948 		case AUTH_REQ_PASSWORD:
949 			{
950 				char	   *password;
951 
952 				conn->password_needed = true;
953 				password = conn->connhost[conn->whichhost].password;
954 				if (password == NULL)
955 					password = conn->pgpass;
956 				if (password == NULL || password[0] == '\0')
957 				{
958 					printfPQExpBuffer(&conn->errorMessage,
959 									  PQnoPasswordSupplied);
960 					return STATUS_ERROR;
961 				}
962 				if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
963 				{
964 					printfPQExpBuffer(&conn->errorMessage,
965 									  "fe_sendauth: error sending password authentication\n");
966 					return STATUS_ERROR;
967 				}
968 				break;
969 			}
970 
971 		case AUTH_REQ_SASL:
972 
973 			/*
974 			 * The request contains the name (as assigned by IANA) of the
975 			 * authentication mechanism.
976 			 */
977 			if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
978 			{
979 				/* pg_SASL_init already set the error message */
980 				return STATUS_ERROR;
981 			}
982 			break;
983 
984 		case AUTH_REQ_SASL_CONT:
985 		case AUTH_REQ_SASL_FIN:
986 			if (conn->sasl_state == NULL)
987 			{
988 				printfPQExpBuffer(&conn->errorMessage,
989 								  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
990 				return STATUS_ERROR;
991 			}
992 			if (pg_SASL_continue(conn, payloadlen,
993 								 (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
994 			{
995 				/* Use error message, if set already */
996 				if (conn->errorMessage.len == 0)
997 					printfPQExpBuffer(&conn->errorMessage,
998 									  "fe_sendauth: error in SASL authentication\n");
999 				return STATUS_ERROR;
1000 			}
1001 			break;
1002 
1003 		case AUTH_REQ_SCM_CREDS:
1004 			if (pg_local_sendauth(conn) != STATUS_OK)
1005 				return STATUS_ERROR;
1006 			break;
1007 
1008 		default:
1009 			printfPQExpBuffer(&conn->errorMessage,
1010 							  libpq_gettext("authentication method %u not supported\n"), areq);
1011 			return STATUS_ERROR;
1012 	}
1013 
1014 	return STATUS_OK;
1015 }
1016 
1017 
1018 /*
1019  * pg_fe_getauthname
1020  *
1021  * Returns a pointer to malloc'd space containing whatever name the user
1022  * has authenticated to the system.  If there is an error, return NULL,
1023  * and put a suitable error message in *errorMessage if that's not NULL.
1024  */
1025 char *
pg_fe_getauthname(PQExpBuffer errorMessage)1026 pg_fe_getauthname(PQExpBuffer errorMessage)
1027 {
1028 	char	   *result = NULL;
1029 	const char *name = NULL;
1030 
1031 #ifdef WIN32
1032 	/* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1033 	char		username[256 + 1];
1034 	DWORD		namesize = sizeof(username);
1035 #else
1036 	uid_t		user_id = geteuid();
1037 	char		pwdbuf[BUFSIZ];
1038 	struct passwd pwdstr;
1039 	struct passwd *pw = NULL;
1040 	int			pwerr;
1041 #endif
1042 
1043 	/*
1044 	 * Some users are using configure --enable-thread-safety-force, so we
1045 	 * might as well do the locking within our library to protect
1046 	 * pqGetpwuid(). In fact, application developers can use getpwuid() in
1047 	 * their application if they use the locking call we provide, or install
1048 	 * their own locking function using PQregisterThreadLock().
1049 	 */
1050 	pglock_thread();
1051 
1052 #ifdef WIN32
1053 	if (GetUserName(username, &namesize))
1054 		name = username;
1055 	else if (errorMessage)
1056 		printfPQExpBuffer(errorMessage,
1057 						  libpq_gettext("user name lookup failure: error code %lu\n"),
1058 						  GetLastError());
1059 #else
1060 	pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1061 	if (pw != NULL)
1062 		name = pw->pw_name;
1063 	else if (errorMessage)
1064 	{
1065 		if (pwerr != 0)
1066 			printfPQExpBuffer(errorMessage,
1067 							  libpq_gettext("could not look up local user ID %d: %s\n"),
1068 							  (int) user_id,
1069 							  pqStrerror(pwerr, pwdbuf, sizeof(pwdbuf)));
1070 		else
1071 			printfPQExpBuffer(errorMessage,
1072 							  libpq_gettext("local user with ID %d does not exist\n"),
1073 							  (int) user_id);
1074 	}
1075 #endif
1076 
1077 	if (name)
1078 	{
1079 		result = strdup(name);
1080 		if (result == NULL && errorMessage)
1081 			printfPQExpBuffer(errorMessage,
1082 							  libpq_gettext("out of memory\n"));
1083 	}
1084 
1085 	pgunlock_thread();
1086 
1087 	return result;
1088 }
1089 
1090 
1091 /*
1092  * PQencryptPassword -- exported routine to encrypt a password with MD5
1093  *
1094  * This function is equivalent to calling PQencryptPasswordConn with
1095  * "md5" as the encryption method, except that this doesn't require
1096  * a connection object.  This function is deprecated, use
1097  * PQencryptPasswordConn instead.
1098  */
1099 char *
PQencryptPassword(const char * passwd,const char * user)1100 PQencryptPassword(const char *passwd, const char *user)
1101 {
1102 	char	   *crypt_pwd;
1103 
1104 	crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1105 	if (!crypt_pwd)
1106 		return NULL;
1107 
1108 	if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1109 	{
1110 		free(crypt_pwd);
1111 		return NULL;
1112 	}
1113 
1114 	return crypt_pwd;
1115 }
1116 
1117 /*
1118  * PQencryptPasswordConn -- exported routine to encrypt a password
1119  *
1120  * This is intended to be used by client applications that wish to send
1121  * commands like ALTER USER joe PASSWORD 'pwd'.  The password need not
1122  * be sent in cleartext if it is encrypted on the client side.  This is
1123  * good because it ensures the cleartext password won't end up in logs,
1124  * pg_stat displays, etc.  We export the function so that clients won't
1125  * be dependent on low-level details like whether the encryption is MD5
1126  * or something else.
1127  *
1128  * Arguments are a connection object, the cleartext password, the SQL
1129  * name of the user it is for, and a string indicating the algorithm to
1130  * use for encrypting the password.  If algorithm is NULL, this queries
1131  * the server for the current 'password_encryption' value.  If you wish
1132  * to avoid that, e.g. to avoid blocking, you can execute
1133  * 'show password_encryption' yourself before calling this function, and
1134  * pass it as the algorithm.
1135  *
1136  * Return value is a malloc'd string.  The client may assume the string
1137  * doesn't contain any special characters that would require escaping.
1138  * On error, an error message is stored in the connection object, and
1139  * returns NULL.
1140  */
1141 char *
PQencryptPasswordConn(PGconn * conn,const char * passwd,const char * user,const char * algorithm)1142 PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user,
1143 					  const char *algorithm)
1144 {
1145 #define MAX_ALGORITHM_NAME_LEN 50
1146 	char		algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1147 	char	   *crypt_pwd = NULL;
1148 
1149 	if (!conn)
1150 		return NULL;
1151 
1152 	/* If no algorithm was given, ask the server. */
1153 	if (algorithm == NULL)
1154 	{
1155 		PGresult   *res;
1156 		char	   *val;
1157 
1158 		res = PQexec(conn, "show password_encryption");
1159 		if (res == NULL)
1160 		{
1161 			/* PQexec() should've set conn->errorMessage already */
1162 			return NULL;
1163 		}
1164 		if (PQresultStatus(res) != PGRES_TUPLES_OK)
1165 		{
1166 			/* PQexec() should've set conn->errorMessage already */
1167 			PQclear(res);
1168 			return NULL;
1169 		}
1170 		if (PQntuples(res) != 1 || PQnfields(res) != 1)
1171 		{
1172 			PQclear(res);
1173 			printfPQExpBuffer(&conn->errorMessage,
1174 							  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1175 			return NULL;
1176 		}
1177 		val = PQgetvalue(res, 0, 0);
1178 
1179 		if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1180 		{
1181 			PQclear(res);
1182 			printfPQExpBuffer(&conn->errorMessage,
1183 							  libpq_gettext("password_encryption value too long\n"));
1184 			return NULL;
1185 		}
1186 		strcpy(algobuf, val);
1187 		PQclear(res);
1188 
1189 		algorithm = algobuf;
1190 	}
1191 
1192 	/*
1193 	 * Also accept "on" and "off" as aliases for "md5", because
1194 	 * password_encryption was a boolean before PostgreSQL 10.  We refuse to
1195 	 * send the password in plaintext even if it was "off".
1196 	 */
1197 	if (strcmp(algorithm, "on") == 0 ||
1198 		strcmp(algorithm, "off") == 0)
1199 		algorithm = "md5";
1200 
1201 	/*
1202 	 * Ok, now we know what algorithm to use
1203 	 */
1204 	if (strcmp(algorithm, "scram-sha-256") == 0)
1205 	{
1206 		crypt_pwd = pg_fe_scram_build_verifier(passwd);
1207 	}
1208 	else if (strcmp(algorithm, "md5") == 0)
1209 	{
1210 		crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1211 		if (crypt_pwd)
1212 		{
1213 			if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1214 			{
1215 				free(crypt_pwd);
1216 				crypt_pwd = NULL;
1217 			}
1218 		}
1219 	}
1220 	else
1221 	{
1222 		printfPQExpBuffer(&conn->errorMessage,
1223 						  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1224 						  algorithm);
1225 		return NULL;
1226 	}
1227 
1228 	if (!crypt_pwd)
1229 		printfPQExpBuffer(&conn->errorMessage,
1230 						  libpq_gettext("out of memory\n"));
1231 
1232 	return crypt_pwd;
1233 }
1234