1 /*-------------------------------------------------------------------------
2  *
3  * fe-auth.c
4  *	   The front-end (client) authorization routines
5  *
6  * Portions Copyright (c) 1996-2018, 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 "common/scram-common.h"
43 #include "libpq-fe.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 	char	   *password;
497 
498 	initPQExpBuffer(&mechanism_buf);
499 
500 	if (conn->sasl_state)
501 	{
502 		printfPQExpBuffer(&conn->errorMessage,
503 						  libpq_gettext("duplicate SASL authentication request\n"));
504 		goto error;
505 	}
506 
507 	/*
508 	 * Parse the list of SASL authentication mechanisms in the
509 	 * AuthenticationSASL message, and select the best mechanism that we
510 	 * support.  SCRAM-SHA-256-PLUS and SCRAM-SHA-256 are the only ones
511 	 * supported at the moment, listed by order of decreasing importance.
512 	 */
513 	selected_mechanism = NULL;
514 	for (;;)
515 	{
516 		if (pqGets(&mechanism_buf, conn))
517 		{
518 			printfPQExpBuffer(&conn->errorMessage,
519 							  "fe_sendauth: invalid authentication request from server: invalid list of authentication mechanisms\n");
520 			goto error;
521 		}
522 		if (PQExpBufferDataBroken(mechanism_buf))
523 			goto oom_error;
524 
525 		/* An empty string indicates end of list */
526 		if (mechanism_buf.data[0] == '\0')
527 			break;
528 
529 		/*
530 		 * Select the mechanism to use.  Pick SCRAM-SHA-256-PLUS over anything
531 		 * else if a channel binding type is set and if the client supports
532 		 * it. Pick SCRAM-SHA-256 if nothing else has already been picked.  If
533 		 * we add more mechanisms, a more refined priority mechanism might
534 		 * become necessary.
535 		 */
536 		if (strcmp(mechanism_buf.data, SCRAM_SHA_256_PLUS_NAME) == 0)
537 		{
538 			if (conn->ssl_in_use)
539 			{
540 				/*
541 				 * The server has offered SCRAM-SHA-256-PLUS, which is only
542 				 * supported by the client if a hash of the peer certificate
543 				 * can be created.
544 				 */
545 #ifdef HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
546 				selected_mechanism = SCRAM_SHA_256_PLUS_NAME;
547 #endif
548 			}
549 			else
550 			{
551 				/*
552 				 * The server offered SCRAM-SHA-256-PLUS, but the connection
553 				 * is not SSL-encrypted. That's not sane. Perhaps SSL was
554 				 * stripped by a proxy? There's no point in continuing,
555 				 * because the server will reject the connection anyway if we
556 				 * try authenticate without channel binding even though both
557 				 * the client and server supported it. The SCRAM exchange
558 				 * checks for that, to prevent downgrade attacks.
559 				 */
560 				printfPQExpBuffer(&conn->errorMessage,
561 								  libpq_gettext("server offered SCRAM-SHA-256-PLUS authentication over a non-SSL connection\n"));
562 				goto error;
563 			}
564 		}
565 		else if (strcmp(mechanism_buf.data, SCRAM_SHA_256_NAME) == 0 &&
566 				 !selected_mechanism)
567 			selected_mechanism = SCRAM_SHA_256_NAME;
568 	}
569 
570 	if (!selected_mechanism)
571 	{
572 		printfPQExpBuffer(&conn->errorMessage,
573 						  libpq_gettext("none of the server's SASL authentication mechanisms are supported\n"));
574 		goto error;
575 	}
576 
577 	/*
578 	 * Now that the SASL mechanism has been chosen for the exchange,
579 	 * initialize its state information.
580 	 */
581 
582 	/*
583 	 * First, select the password to use for the exchange, complaining if
584 	 * there isn't one.  Currently, all supported SASL mechanisms require a
585 	 * password, so we can just go ahead here without further distinction.
586 	 */
587 	conn->password_needed = true;
588 	password = conn->connhost[conn->whichhost].password;
589 	if (password == NULL)
590 		password = conn->pgpass;
591 	if (password == NULL || password[0] == '\0')
592 	{
593 		printfPQExpBuffer(&conn->errorMessage,
594 						  PQnoPasswordSupplied);
595 		goto error;
596 	}
597 
598 	/*
599 	 * Initialize the SASL state information with all the information gathered
600 	 * during the initial exchange.
601 	 *
602 	 * Note: Only tls-unique is supported for the moment.
603 	 */
604 	conn->sasl_state = pg_fe_scram_init(conn,
605 										password,
606 										selected_mechanism);
607 	if (!conn->sasl_state)
608 		goto oom_error;
609 
610 	/* Get the mechanism-specific Initial Client Response, if any */
611 	pg_fe_scram_exchange(conn->sasl_state,
612 						 NULL, -1,
613 						 &initialresponse, &initialresponselen,
614 						 &done, &success);
615 
616 	if (done && !success)
617 		goto error;
618 
619 	/*
620 	 * Build a SASLInitialResponse message, and send it.
621 	 */
622 	if (pqPutMsgStart('p', true, conn))
623 		goto error;
624 	if (pqPuts(selected_mechanism, conn))
625 		goto error;
626 	if (initialresponse)
627 	{
628 		if (pqPutInt(initialresponselen, 4, conn))
629 			goto error;
630 		if (pqPutnchar(initialresponse, initialresponselen, conn))
631 			goto error;
632 	}
633 	if (pqPutMsgEnd(conn))
634 		goto error;
635 	if (pqFlush(conn))
636 		goto error;
637 
638 	termPQExpBuffer(&mechanism_buf);
639 	if (initialresponse)
640 		free(initialresponse);
641 
642 	return STATUS_OK;
643 
644 error:
645 	termPQExpBuffer(&mechanism_buf);
646 	if (initialresponse)
647 		free(initialresponse);
648 	return STATUS_ERROR;
649 
650 oom_error:
651 	termPQExpBuffer(&mechanism_buf);
652 	if (initialresponse)
653 		free(initialresponse);
654 	printfPQExpBuffer(&conn->errorMessage,
655 					  libpq_gettext("out of memory\n"));
656 	return STATUS_ERROR;
657 }
658 
659 /*
660  * Exchange a message for SASL communication protocol with the backend.
661  * This should be used after calling pg_SASL_init to set up the status of
662  * the protocol.
663  */
664 static int
pg_SASL_continue(PGconn * conn,int payloadlen,bool final)665 pg_SASL_continue(PGconn *conn, int payloadlen, bool final)
666 {
667 	char	   *output;
668 	int			outputlen;
669 	bool		done;
670 	bool		success;
671 	int			res;
672 	char	   *challenge;
673 
674 	/* Read the SASL challenge from the AuthenticationSASLContinue message. */
675 	challenge = malloc(payloadlen + 1);
676 	if (!challenge)
677 	{
678 		printfPQExpBuffer(&conn->errorMessage,
679 						  libpq_gettext("out of memory allocating SASL buffer (%d)\n"),
680 						  payloadlen);
681 		return STATUS_ERROR;
682 	}
683 
684 	if (pqGetnchar(challenge, payloadlen, conn))
685 	{
686 		free(challenge);
687 		return STATUS_ERROR;
688 	}
689 	/* For safety and convenience, ensure the buffer is NULL-terminated. */
690 	challenge[payloadlen] = '\0';
691 
692 	pg_fe_scram_exchange(conn->sasl_state,
693 						 challenge, payloadlen,
694 						 &output, &outputlen,
695 						 &done, &success);
696 	free(challenge);			/* don't need the input anymore */
697 
698 	if (final && !done)
699 	{
700 		if (outputlen != 0)
701 			free(output);
702 
703 		printfPQExpBuffer(&conn->errorMessage,
704 						  libpq_gettext("AuthenticationSASLFinal received from server, but SASL authentication was not completed\n"));
705 		return STATUS_ERROR;
706 	}
707 	if (outputlen != 0)
708 	{
709 		/*
710 		 * Send the SASL response to the server.
711 		 */
712 		res = pqPacketSend(conn, 'p', output, outputlen);
713 		free(output);
714 
715 		if (res != STATUS_OK)
716 			return STATUS_ERROR;
717 	}
718 
719 	if (done && !success)
720 		return STATUS_ERROR;
721 
722 	return STATUS_OK;
723 }
724 
725 /*
726  * Respond to AUTH_REQ_SCM_CREDS challenge.
727  *
728  * Note: this is dead code as of Postgres 9.1, because current backends will
729  * never send this challenge.  But we must keep it as long as libpq needs to
730  * interoperate with pre-9.1 servers.  It is believed to be needed only on
731  * Debian/kFreeBSD (ie, FreeBSD kernel with Linux userland, so that the
732  * getpeereid() function isn't provided by libc).
733  */
734 static int
pg_local_sendauth(PGconn * conn)735 pg_local_sendauth(PGconn *conn)
736 {
737 #ifdef HAVE_STRUCT_CMSGCRED
738 	char		buf;
739 	struct iovec iov;
740 	struct msghdr msg;
741 	struct cmsghdr *cmsg;
742 	union
743 	{
744 		struct cmsghdr hdr;
745 		unsigned char buf[CMSG_SPACE(sizeof(struct cmsgcred))];
746 	}			cmsgbuf;
747 
748 	/*
749 	 * The backend doesn't care what we send here, but it wants exactly one
750 	 * character to force recvmsg() to block and wait for us.
751 	 */
752 	buf = '\0';
753 	iov.iov_base = &buf;
754 	iov.iov_len = 1;
755 
756 	memset(&msg, 0, sizeof(msg));
757 	msg.msg_iov = &iov;
758 	msg.msg_iovlen = 1;
759 
760 	/* We must set up a message that will be filled in by kernel */
761 	memset(&cmsgbuf, 0, sizeof(cmsgbuf));
762 	msg.msg_control = &cmsgbuf.buf;
763 	msg.msg_controllen = sizeof(cmsgbuf.buf);
764 	cmsg = CMSG_FIRSTHDR(&msg);
765 	cmsg->cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
766 	cmsg->cmsg_level = SOL_SOCKET;
767 	cmsg->cmsg_type = SCM_CREDS;
768 
769 	if (sendmsg(conn->sock, &msg, 0) == -1)
770 	{
771 		char		sebuf[256];
772 
773 		printfPQExpBuffer(&conn->errorMessage,
774 						  "pg_local_sendauth: sendmsg: %s\n",
775 						  pqStrerror(errno, sebuf, sizeof(sebuf)));
776 		return STATUS_ERROR;
777 	}
778 	return STATUS_OK;
779 #else
780 	printfPQExpBuffer(&conn->errorMessage,
781 					  libpq_gettext("SCM_CRED authentication method not supported\n"));
782 	return STATUS_ERROR;
783 #endif
784 }
785 
786 static int
pg_password_sendauth(PGconn * conn,const char * password,AuthRequest areq)787 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
788 {
789 	int			ret;
790 	char	   *crypt_pwd = NULL;
791 	const char *pwd_to_send;
792 	char		md5Salt[4];
793 
794 	/* Read the salt from the AuthenticationMD5 message. */
795 	if (areq == AUTH_REQ_MD5)
796 	{
797 		if (pqGetnchar(md5Salt, 4, conn))
798 			return STATUS_ERROR;	/* shouldn't happen */
799 	}
800 
801 	/* Encrypt the password if needed. */
802 
803 	switch (areq)
804 	{
805 		case AUTH_REQ_MD5:
806 			{
807 				char	   *crypt_pwd2;
808 
809 				/* Allocate enough space for two MD5 hashes */
810 				crypt_pwd = malloc(2 * (MD5_PASSWD_LEN + 1));
811 				if (!crypt_pwd)
812 				{
813 					printfPQExpBuffer(&conn->errorMessage,
814 									  libpq_gettext("out of memory\n"));
815 					return STATUS_ERROR;
816 				}
817 
818 				crypt_pwd2 = crypt_pwd + MD5_PASSWD_LEN + 1;
819 				if (!pg_md5_encrypt(password, conn->pguser,
820 									strlen(conn->pguser), crypt_pwd2))
821 				{
822 					free(crypt_pwd);
823 					return STATUS_ERROR;
824 				}
825 				if (!pg_md5_encrypt(crypt_pwd2 + strlen("md5"), md5Salt,
826 									4, crypt_pwd))
827 				{
828 					free(crypt_pwd);
829 					return STATUS_ERROR;
830 				}
831 
832 				pwd_to_send = crypt_pwd;
833 				break;
834 			}
835 		case AUTH_REQ_PASSWORD:
836 			pwd_to_send = password;
837 			break;
838 		default:
839 			return STATUS_ERROR;
840 	}
841 	/* Packet has a message type as of protocol 3.0 */
842 	if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
843 		ret = pqPacketSend(conn, 'p', pwd_to_send, strlen(pwd_to_send) + 1);
844 	else
845 		ret = pqPacketSend(conn, 0, pwd_to_send, strlen(pwd_to_send) + 1);
846 	if (crypt_pwd)
847 		free(crypt_pwd);
848 	return ret;
849 }
850 
851 /*
852  * pg_fe_sendauth
853  *		client demux routine for processing an authentication request
854  *
855  * The server has sent us an authentication challenge (or OK). Send an
856  * appropriate response. The caller has ensured that the whole message is
857  * now in the input buffer, and has already read the type and length of
858  * it. We are responsible for reading any remaining extra data, specific
859  * to the authentication method. 'payloadlen' is the remaining length in
860  * the message.
861  */
862 int
pg_fe_sendauth(AuthRequest areq,int payloadlen,PGconn * conn)863 pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
864 {
865 	switch (areq)
866 	{
867 		case AUTH_REQ_OK:
868 			break;
869 
870 		case AUTH_REQ_KRB4:
871 			printfPQExpBuffer(&conn->errorMessage,
872 							  libpq_gettext("Kerberos 4 authentication not supported\n"));
873 			return STATUS_ERROR;
874 
875 		case AUTH_REQ_KRB5:
876 			printfPQExpBuffer(&conn->errorMessage,
877 							  libpq_gettext("Kerberos 5 authentication not supported\n"));
878 			return STATUS_ERROR;
879 
880 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
881 		case AUTH_REQ_GSS:
882 #if !defined(ENABLE_SSPI)
883 			/* no native SSPI, so use GSSAPI library for it */
884 		case AUTH_REQ_SSPI:
885 #endif
886 			{
887 				int			r;
888 
889 				pglock_thread();
890 
891 				/*
892 				 * If we have both GSS and SSPI support compiled in, use SSPI
893 				 * support by default. This is overridable by a connection
894 				 * string parameter. Note that when using SSPI we still leave
895 				 * the negotiate parameter off, since we want SSPI to use the
896 				 * GSSAPI kerberos protocol. For actual SSPI negotiate
897 				 * protocol, we use AUTH_REQ_SSPI.
898 				 */
899 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
900 				if (conn->gsslib && (pg_strcasecmp(conn->gsslib, "gssapi") == 0))
901 					r = pg_GSS_startup(conn, payloadlen);
902 				else
903 					r = pg_SSPI_startup(conn, 0, payloadlen);
904 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
905 				r = pg_GSS_startup(conn, payloadlen);
906 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
907 				r = pg_SSPI_startup(conn, 0, payloadlen);
908 #endif
909 				if (r != STATUS_OK)
910 				{
911 					/* Error message already filled in. */
912 					pgunlock_thread();
913 					return STATUS_ERROR;
914 				}
915 				pgunlock_thread();
916 			}
917 			break;
918 
919 		case AUTH_REQ_GSS_CONT:
920 			{
921 				int			r;
922 
923 				pglock_thread();
924 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
925 				if (conn->usesspi)
926 					r = pg_SSPI_continue(conn, payloadlen);
927 				else
928 					r = pg_GSS_continue(conn, payloadlen);
929 #elif defined(ENABLE_GSS) && !defined(ENABLE_SSPI)
930 				r = pg_GSS_continue(conn, payloadlen);
931 #elif !defined(ENABLE_GSS) && defined(ENABLE_SSPI)
932 				r = pg_SSPI_continue(conn, payloadlen);
933 #endif
934 				if (r != STATUS_OK)
935 				{
936 					/* Error message already filled in. */
937 					pgunlock_thread();
938 					return STATUS_ERROR;
939 				}
940 				pgunlock_thread();
941 			}
942 			break;
943 #else							/* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
944 			/* No GSSAPI *or* SSPI support */
945 		case AUTH_REQ_GSS:
946 		case AUTH_REQ_GSS_CONT:
947 			printfPQExpBuffer(&conn->errorMessage,
948 							  libpq_gettext("GSSAPI authentication not supported\n"));
949 			return STATUS_ERROR;
950 #endif							/* defined(ENABLE_GSS) || defined(ENABLE_SSPI) */
951 
952 #ifdef ENABLE_SSPI
953 		case AUTH_REQ_SSPI:
954 
955 			/*
956 			 * SSPI has it's own startup message so libpq can decide which
957 			 * method to use. Indicate to pg_SSPI_startup that we want SSPI
958 			 * negotiation instead of Kerberos.
959 			 */
960 			pglock_thread();
961 			if (pg_SSPI_startup(conn, 1, payloadlen) != STATUS_OK)
962 			{
963 				/* Error message already filled in. */
964 				pgunlock_thread();
965 				return STATUS_ERROR;
966 			}
967 			pgunlock_thread();
968 			break;
969 #else
970 
971 			/*
972 			 * No SSPI support. However, if we have GSSAPI but not SSPI
973 			 * support, AUTH_REQ_SSPI will have been handled in the codepath
974 			 * for AUTH_REQ_GSSAPI above, so don't duplicate the case label in
975 			 * that case.
976 			 */
977 #if !defined(ENABLE_GSS)
978 		case AUTH_REQ_SSPI:
979 			printfPQExpBuffer(&conn->errorMessage,
980 							  libpq_gettext("SSPI authentication not supported\n"));
981 			return STATUS_ERROR;
982 #endif							/* !define(ENABLE_GSSAPI) */
983 #endif							/* ENABLE_SSPI */
984 
985 
986 		case AUTH_REQ_CRYPT:
987 			printfPQExpBuffer(&conn->errorMessage,
988 							  libpq_gettext("Crypt authentication not supported\n"));
989 			return STATUS_ERROR;
990 
991 		case AUTH_REQ_MD5:
992 		case AUTH_REQ_PASSWORD:
993 			{
994 				char	   *password;
995 
996 				conn->password_needed = true;
997 				password = conn->connhost[conn->whichhost].password;
998 				if (password == NULL)
999 					password = conn->pgpass;
1000 				if (password == NULL || password[0] == '\0')
1001 				{
1002 					printfPQExpBuffer(&conn->errorMessage,
1003 									  PQnoPasswordSupplied);
1004 					return STATUS_ERROR;
1005 				}
1006 				if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
1007 				{
1008 					printfPQExpBuffer(&conn->errorMessage,
1009 									  "fe_sendauth: error sending password authentication\n");
1010 					return STATUS_ERROR;
1011 				}
1012 				break;
1013 			}
1014 
1015 		case AUTH_REQ_SASL:
1016 
1017 			/*
1018 			 * The request contains the name (as assigned by IANA) of the
1019 			 * authentication mechanism.
1020 			 */
1021 			if (pg_SASL_init(conn, payloadlen) != STATUS_OK)
1022 			{
1023 				/* pg_SASL_init already set the error message */
1024 				return STATUS_ERROR;
1025 			}
1026 			break;
1027 
1028 		case AUTH_REQ_SASL_CONT:
1029 		case AUTH_REQ_SASL_FIN:
1030 			if (conn->sasl_state == NULL)
1031 			{
1032 				printfPQExpBuffer(&conn->errorMessage,
1033 								  "fe_sendauth: invalid authentication request from server: AUTH_REQ_SASL_CONT without AUTH_REQ_SASL\n");
1034 				return STATUS_ERROR;
1035 			}
1036 			if (pg_SASL_continue(conn, payloadlen,
1037 								 (areq == AUTH_REQ_SASL_FIN)) != STATUS_OK)
1038 			{
1039 				/* Use error message, if set already */
1040 				if (conn->errorMessage.len == 0)
1041 					printfPQExpBuffer(&conn->errorMessage,
1042 									  "fe_sendauth: error in SASL authentication\n");
1043 				return STATUS_ERROR;
1044 			}
1045 			break;
1046 
1047 		case AUTH_REQ_SCM_CREDS:
1048 			if (pg_local_sendauth(conn) != STATUS_OK)
1049 				return STATUS_ERROR;
1050 			break;
1051 
1052 		default:
1053 			printfPQExpBuffer(&conn->errorMessage,
1054 							  libpq_gettext("authentication method %u not supported\n"), areq);
1055 			return STATUS_ERROR;
1056 	}
1057 
1058 	return STATUS_OK;
1059 }
1060 
1061 
1062 /*
1063  * pg_fe_getauthname
1064  *
1065  * Returns a pointer to malloc'd space containing whatever name the user
1066  * has authenticated to the system.  If there is an error, return NULL,
1067  * and put a suitable error message in *errorMessage if that's not NULL.
1068  */
1069 char *
pg_fe_getauthname(PQExpBuffer errorMessage)1070 pg_fe_getauthname(PQExpBuffer errorMessage)
1071 {
1072 	char	   *result = NULL;
1073 	const char *name = NULL;
1074 
1075 #ifdef WIN32
1076 	/* Microsoft recommends buffer size of UNLEN+1, where UNLEN = 256 */
1077 	char		username[256 + 1];
1078 	DWORD		namesize = sizeof(username);
1079 #else
1080 	uid_t		user_id = geteuid();
1081 	char		pwdbuf[BUFSIZ];
1082 	struct passwd pwdstr;
1083 	struct passwd *pw = NULL;
1084 	int			pwerr;
1085 #endif
1086 
1087 	/*
1088 	 * Some users are using configure --enable-thread-safety-force, so we
1089 	 * might as well do the locking within our library to protect
1090 	 * pqGetpwuid(). In fact, application developers can use getpwuid() in
1091 	 * their application if they use the locking call we provide, or install
1092 	 * their own locking function using PQregisterThreadLock().
1093 	 */
1094 	pglock_thread();
1095 
1096 #ifdef WIN32
1097 	if (GetUserName(username, &namesize))
1098 		name = username;
1099 	else if (errorMessage)
1100 		printfPQExpBuffer(errorMessage,
1101 						  libpq_gettext("user name lookup failure: error code %lu\n"),
1102 						  GetLastError());
1103 #else
1104 	pwerr = pqGetpwuid(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
1105 	if (pw != NULL)
1106 		name = pw->pw_name;
1107 	else if (errorMessage)
1108 	{
1109 		if (pwerr != 0)
1110 			printfPQExpBuffer(errorMessage,
1111 							  libpq_gettext("could not look up local user ID %d: %s\n"),
1112 							  (int) user_id,
1113 							  pqStrerror(pwerr, pwdbuf, sizeof(pwdbuf)));
1114 		else
1115 			printfPQExpBuffer(errorMessage,
1116 							  libpq_gettext("local user with ID %d does not exist\n"),
1117 							  (int) user_id);
1118 	}
1119 #endif
1120 
1121 	if (name)
1122 	{
1123 		result = strdup(name);
1124 		if (result == NULL && errorMessage)
1125 			printfPQExpBuffer(errorMessage,
1126 							  libpq_gettext("out of memory\n"));
1127 	}
1128 
1129 	pgunlock_thread();
1130 
1131 	return result;
1132 }
1133 
1134 
1135 /*
1136  * PQencryptPassword -- exported routine to encrypt a password with MD5
1137  *
1138  * This function is equivalent to calling PQencryptPasswordConn with
1139  * "md5" as the encryption method, except that this doesn't require
1140  * a connection object.  This function is deprecated, use
1141  * PQencryptPasswordConn instead.
1142  */
1143 char *
PQencryptPassword(const char * passwd,const char * user)1144 PQencryptPassword(const char *passwd, const char *user)
1145 {
1146 	char	   *crypt_pwd;
1147 
1148 	crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1149 	if (!crypt_pwd)
1150 		return NULL;
1151 
1152 	if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1153 	{
1154 		free(crypt_pwd);
1155 		return NULL;
1156 	}
1157 
1158 	return crypt_pwd;
1159 }
1160 
1161 /*
1162  * PQencryptPasswordConn -- exported routine to encrypt a password
1163  *
1164  * This is intended to be used by client applications that wish to send
1165  * commands like ALTER USER joe PASSWORD 'pwd'.  The password need not
1166  * be sent in cleartext if it is encrypted on the client side.  This is
1167  * good because it ensures the cleartext password won't end up in logs,
1168  * pg_stat displays, etc.  We export the function so that clients won't
1169  * be dependent on low-level details like whether the encryption is MD5
1170  * or something else.
1171  *
1172  * Arguments are a connection object, the cleartext password, the SQL
1173  * name of the user it is for, and a string indicating the algorithm to
1174  * use for encrypting the password.  If algorithm is NULL, this queries
1175  * the server for the current 'password_encryption' value.  If you wish
1176  * to avoid that, e.g. to avoid blocking, you can execute
1177  * 'show password_encryption' yourself before calling this function, and
1178  * pass it as the algorithm.
1179  *
1180  * Return value is a malloc'd string.  The client may assume the string
1181  * doesn't contain any special characters that would require escaping.
1182  * On error, an error message is stored in the connection object, and
1183  * returns NULL.
1184  */
1185 char *
PQencryptPasswordConn(PGconn * conn,const char * passwd,const char * user,const char * algorithm)1186 PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user,
1187 					  const char *algorithm)
1188 {
1189 #define MAX_ALGORITHM_NAME_LEN 50
1190 	char		algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1191 	char	   *crypt_pwd = NULL;
1192 
1193 	if (!conn)
1194 		return NULL;
1195 
1196 	/* If no algorithm was given, ask the server. */
1197 	if (algorithm == NULL)
1198 	{
1199 		PGresult   *res;
1200 		char	   *val;
1201 
1202 		res = PQexec(conn, "show password_encryption");
1203 		if (res == NULL)
1204 		{
1205 			/* PQexec() should've set conn->errorMessage already */
1206 			return NULL;
1207 		}
1208 		if (PQresultStatus(res) != PGRES_TUPLES_OK)
1209 		{
1210 			/* PQexec() should've set conn->errorMessage already */
1211 			PQclear(res);
1212 			return NULL;
1213 		}
1214 		if (PQntuples(res) != 1 || PQnfields(res) != 1)
1215 		{
1216 			PQclear(res);
1217 			printfPQExpBuffer(&conn->errorMessage,
1218 							  libpq_gettext("unexpected shape of result set returned for SHOW\n"));
1219 			return NULL;
1220 		}
1221 		val = PQgetvalue(res, 0, 0);
1222 
1223 		if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1224 		{
1225 			PQclear(res);
1226 			printfPQExpBuffer(&conn->errorMessage,
1227 							  libpq_gettext("password_encryption value too long\n"));
1228 			return NULL;
1229 		}
1230 		strcpy(algobuf, val);
1231 		PQclear(res);
1232 
1233 		algorithm = algobuf;
1234 	}
1235 
1236 	/*
1237 	 * Also accept "on" and "off" as aliases for "md5", because
1238 	 * password_encryption was a boolean before PostgreSQL 10.  We refuse to
1239 	 * send the password in plaintext even if it was "off".
1240 	 */
1241 	if (strcmp(algorithm, "on") == 0 ||
1242 		strcmp(algorithm, "off") == 0)
1243 		algorithm = "md5";
1244 
1245 	/*
1246 	 * Ok, now we know what algorithm to use
1247 	 */
1248 	if (strcmp(algorithm, "scram-sha-256") == 0)
1249 	{
1250 		crypt_pwd = pg_fe_scram_build_verifier(passwd);
1251 	}
1252 	else if (strcmp(algorithm, "md5") == 0)
1253 	{
1254 		crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1255 		if (crypt_pwd)
1256 		{
1257 			if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd))
1258 			{
1259 				free(crypt_pwd);
1260 				crypt_pwd = NULL;
1261 			}
1262 		}
1263 	}
1264 	else
1265 	{
1266 		printfPQExpBuffer(&conn->errorMessage,
1267 						  libpq_gettext("unrecognized password encryption algorithm \"%s\"\n"),
1268 						  algorithm);
1269 		return NULL;
1270 	}
1271 
1272 	if (!crypt_pwd)
1273 		printfPQExpBuffer(&conn->errorMessage,
1274 						  libpq_gettext("out of memory\n"));
1275 
1276 	return crypt_pwd;
1277 }
1278