fe-secure.c 31.7 KB
Newer Older
B
Bruce Momjian 已提交
1 2
/*-------------------------------------------------------------------------
 *
3
 * fe-secure.c
B
Bruce Momjian 已提交
4 5 6 7 8
 *	  functions related to setting up a secure connection to the backend.
 *	  Secure connections are expected to provide confidentiality,
 *	  message integrity and endpoint authentication.
 *
 *
P
 
PostgreSQL Daemon 已提交
9
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
B
Bruce Momjian 已提交
10 11 12 13
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
14
 *	  $PostgreSQL: pgsql/src/interfaces/libpq/fe-secure.c,v 1.73 2005/10/24 15:38:37 momjian Exp $
B
Bruce Momjian 已提交
15
 *
B
Bruce Momjian 已提交
16
 * NOTES
17 18
 *	  [ Most of these notes are wrong/obsolete, but perhaps not all ]
 *
B
Bruce Momjian 已提交
19 20 21 22 23 24 25
 *	  The client *requires* a valid server certificate.  Since
 *	  SSH tunnels provide anonymous confidentiality, the presumption
 *	  is that sites that want endpoint authentication will use the
 *	  direct SSL support, while sites that are comfortable with
 *	  anonymous connections will use SSH tunnels.
 *
 *	  This code verifies the server certificate, to detect simple
B
Bruce Momjian 已提交
26
 *	  "man-in-the-middle" and "impersonation" attacks.	The
B
Bruce Momjian 已提交
27 28
 *	  server certificate, or better yet the CA certificate used
 *	  to sign the server certificate, should be present in the
29
 *	  "~/.postgresql/root.crt" file.  If this file isn't
B
Bruce Momjian 已提交
30
 *	  readable, or the server certificate can't be validated,
31
 *	  pqsecure_open_client() will return an error code.
B
Bruce Momjian 已提交
32 33 34 35 36
 *
 *	  Additionally, the server certificate's "common name" must
 *	  resolve to the other end of the socket.  This makes it
 *	  substantially harder to pull off a "man-in-the-middle" or
 *	  "impersonation" attack even if the server's private key
B
Bruce Momjian 已提交
37
 *	  has been stolen.	This check limits acceptable network
B
Bruce Momjian 已提交
38 39 40 41 42
 *	  layers to Unix sockets (weird, but legal), TCPv4 and TCPv6.
 *
 *	  Unfortunately neither the current front- or back-end handle
 *	  failure gracefully, resulting in the backend hiccupping.
 *	  This points out problems in each (the frontend shouldn't even
43
 *	  try to do SSL if pqsecure_initialize() fails, and the backend
B
Bruce Momjian 已提交
44
 *	  shouldn't crash/recover if an SSH negotiation fails.  The
B
Bruce Momjian 已提交
45
 *	  backend definitely needs to be fixed, to prevent a "denial
B
Bruce Momjian 已提交
46
 *	  of service" attack, but I don't know enough about how the
B
Bruce Momjian 已提交
47 48 49
 *	  backend works (especially that pre-SSL negotiation) to identify
 *	  a fix.
 *
50 51 52
 *	  ...
 *
 *	  Unlike the server's static private key, the client's
53
 *	  static private key (~/.postgresql/postgresql.key)
B
Bruce Momjian 已提交
54
 *	  should normally be stored encrypted.	However we still
55 56
 *	  support EPH since it's useful for other reasons.
 *
57 58 59 60 61 62 63 64 65
 *	  ...
 *
 *	  Client certificates are supported, if the server requests
 *	  or requires them.  Client certificates can be used for
 *	  authentication, to prevent sessions from being hijacked,
 *	  or to allow "road warriors" to access the database while
 *	  keeping it closed to everyone else.
 *
 *	  The user's certificate and private key are located in
66
 *		~/.postgresql/postgresql.crt
67
 *	  and
68
 *		~/.postgresql/postgresql.key
69 70
 *	  respectively.
 *
71 72 73 74 75 76
 *	  ...
 *
 *	  We don't provide informational callbacks here (like
 *	  info_cb() in be-secure.c), since there's mechanism to
 *	  display that information to the client.
 *
B
Bruce Momjian 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"

#include <signal.h>
#include <fcntl.h>
#include <ctype.h>

#include "libpq-fe.h"
#include "libpq-int.h"
#include "fe-auth.h"
#include "pqsignal.h"

#ifdef WIN32
#include "win32.h"
#else
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
#include <arpa/inet.h>
#endif
103
#include <sys/stat.h>
B
Bruce Momjian 已提交
104

105
#ifdef ENABLE_THREAD_SAFETY
106 107 108
#ifdef WIN32
#include "pthread-win32.h"
#else
109 110
#include <pthread.h>
#endif
111
#endif
112

B
Bruce Momjian 已提交
113 114 115 116 117 118
#ifndef HAVE_STRDUP
#include "strdup.h"
#endif

#ifdef USE_SSL
#include <openssl/ssl.h>
119
#include <openssl/dh.h>
B
Bruce Momjian 已提交
120
#endif   /* USE_SSL */
B
Bruce Momjian 已提交
121 122 123


#ifdef USE_SSL
124 125 126 127 128 129 130 131 132 133 134 135 136

#ifndef WIN32
#define USERCERTFILE	".postgresql/postgresql.crt"
#define USERKEYFILE		".postgresql/postgresql.key"
#define ROOTCERTFILE	".postgresql/root.crt"
#define DHFILEPATTERN	"%s/.postgresql/dh%d.pem"
#else
/* On Windows, the "home" directory is already PostgreSQL-specific */
#define USERCERTFILE	"postgresql.crt"
#define USERKEYFILE		"postgresql.key"
#define ROOTCERTFILE	"root.crt"
#define DHFILEPATTERN	"%s/dh%d.pem"
#endif
B
Bruce Momjian 已提交
137

B
Bruce Momjian 已提交
138
#ifdef NOT_USED
B
Bruce Momjian 已提交
139
static int	verify_peer(PGconn *);
B
Bruce Momjian 已提交
140
#endif
141
static int	verify_cb(int ok, X509_STORE_CTX *ctx);
B
Bruce Momjian 已提交
142 143 144 145
static DH  *load_dh_file(int keylength);
static DH  *load_dh_buffer(const char *, size_t);
static DH  *tmp_dh_cb(SSL *s, int is_export, int keylength);
static int	client_cert_cb(SSL *, X509 **, EVP_PKEY **);
146
static int	init_ssl_system(PGconn *conn);
B
Bruce Momjian 已提交
147
static int	initialize_SSL(PGconn *);
B
Bruce Momjian 已提交
148
static void destroy_SSL(void);
149
static PostgresPollingStatusType open_client_SSL(PGconn *);
B
Bruce Momjian 已提交
150
static void close_SSL(PGconn *);
151 152
static char *SSLerrmessage(void);
static void SSLerrfree(char *buf);
B
Bruce Momjian 已提交
153 154 155
#endif

#ifdef USE_SSL
156
static bool pq_initssllib = true;
157

B
Bruce Momjian 已提交
158 159 160
static SSL_CTX *SSL_context = NULL;
#endif

161
/* ------------------------------------------------------------ */
B
Bruce Momjian 已提交
162
/*						 Hardcoded values						*/
163 164 165 166 167 168 169
/* ------------------------------------------------------------ */

/*
 *	Hardcoded DH parameters, used in empheral DH keying.
 *	As discussed above, EDH protects the confidentiality of
 *	sessions even if the static private key is compromised,
 *	so we are *highly* motivated to ensure that we can use
B
Bruce Momjian 已提交
170
 *	EDH even if the user... or an attacker... deletes the
171
 *	~/.postgresql/dh*.pem files.
172 173 174 175
 *
 *	It's not critical that users have EPH keys, but it doesn't
 *	hurt and if it's missing someone will demand it, so....
 */
176 177
#ifdef USE_SSL

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
static const char file_dh512[] =
"-----BEGIN DH PARAMETERS-----\n\
MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
-----END DH PARAMETERS-----\n";

static const char file_dh1024[] =
"-----BEGIN DH PARAMETERS-----\n\
MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
-----END DH PARAMETERS-----\n";

static const char file_dh2048[] =
"-----BEGIN DH PARAMETERS-----\n\
MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
-----END DH PARAMETERS-----\n";

static const char file_dh4096[] =
"-----BEGIN DH PARAMETERS-----\n\
MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
-----END DH PARAMETERS-----\n";
215 216
#endif

B
Bruce Momjian 已提交
217
/* ------------------------------------------------------------ */
B
Bruce Momjian 已提交
218
/*			 Procedures common to all secure sessions			*/
B
Bruce Momjian 已提交
219 220
/* ------------------------------------------------------------ */

221 222

/*
223 224
 *	Exported function to allow application to tell us it's already
 *	initialized OpenSSL.
225 226 227 228 229 230 231 232 233
 */
void
PQinitSSL(int do_init)
{
#ifdef USE_SSL
	pq_initssllib = do_init;
#endif
}

B
Bruce Momjian 已提交
234 235 236 237
/*
 *	Initialize global context
 */
int
B
Bruce Momjian 已提交
238
pqsecure_initialize(PGconn *conn)
B
Bruce Momjian 已提交
239
{
B
Bruce Momjian 已提交
240
	int			r = 0;
B
Bruce Momjian 已提交
241 242 243 244 245 246 247 248 249 250 251 252

#ifdef USE_SSL
	r = initialize_SSL(conn);
#endif

	return r;
}

/*
 *	Destroy global context
 */
void
B
Bruce Momjian 已提交
253
pqsecure_destroy(void)
B
Bruce Momjian 已提交
254 255 256 257 258 259 260 261 262
{
#ifdef USE_SSL
	destroy_SSL();
#endif
}

/*
 *	Attempt to negotiate secure session.
 */
263
PostgresPollingStatusType
B
Bruce Momjian 已提交
264
pqsecure_open_client(PGconn *conn)
B
Bruce Momjian 已提交
265 266
{
#ifdef USE_SSL
267 268 269 270 271 272 273
	/* First time through? */
	if (conn->ssl == NULL)
	{
		if (!(conn->ssl = SSL_new(SSL_context)) ||
			!SSL_set_app_data(conn->ssl, conn) ||
			!SSL_set_fd(conn->ssl, conn->sock))
		{
B
Bruce Momjian 已提交
274 275
			char	   *err = SSLerrmessage();

276
			printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
277
				   libpq_gettext("could not establish SSL connection: %s\n"),
278 279
							  err);
			SSLerrfree(err);
280 281 282
			close_SSL(conn);
			return PGRES_POLLING_FAILED;
		}
B
Bruce Momjian 已提交
283

284
		/*
B
Bruce Momjian 已提交
285 286
		 * Initialize errorMessage to empty.  This allows open_client_SSL() to
		 * detect whether client_cert_cb() has stored a message.
287 288
		 */
		resetPQExpBuffer(&conn->errorMessage);
289 290 291 292 293 294
	}
	/* Begin or continue the actual handshake */
	return open_client_SSL(conn);
#else
	/* shouldn't get here */
	return PGRES_POLLING_FAILED;
B
Bruce Momjian 已提交
295 296 297 298 299 300 301
#endif
}

/*
 *	Close secure session.
 */
void
B
Bruce Momjian 已提交
302
pqsecure_close(PGconn *conn)
B
Bruce Momjian 已提交
303 304 305 306 307 308 309 310 311 312 313
{
#ifdef USE_SSL
	if (conn->ssl)
		close_SSL(conn);
#endif
}

/*
 *	Read data from a secure connection.
 */
ssize_t
B
Bruce Momjian 已提交
314
pqsecure_read(PGconn *conn, void *ptr, size_t len)
B
Bruce Momjian 已提交
315
{
B
Bruce Momjian 已提交
316
	ssize_t		n;
B
Bruce Momjian 已提交
317 318 319 320

#ifdef USE_SSL
	if (conn->ssl)
	{
321 322
		int			err;

B
Bruce Momjian 已提交
323
rloop:
B
Bruce Momjian 已提交
324
		n = SSL_read(conn->ssl, ptr, len);
325 326
		err = SSL_get_error(conn->ssl, n);
		switch (err)
B
Bruce Momjian 已提交
327
		{
B
Bruce Momjian 已提交
328 329 330
			case SSL_ERROR_NONE:
				break;
			case SSL_ERROR_WANT_READ:
331 332
				n = 0;
				break;
333
			case SSL_ERROR_WANT_WRITE:
B
Bruce Momjian 已提交
334

335
				/*
B
Bruce Momjian 已提交
336 337 338 339
				 * Returning 0 here would cause caller to wait for read-ready,
				 * which is not correct since what SSL wants is wait for
				 * write-ready.  The former could get us stuck in an infinite
				 * wait, so don't risk it; busy-loop instead.
340
				 */
341
				goto rloop;
B
Bruce Momjian 已提交
342
			case SSL_ERROR_SYSCALL:
B
Bruce Momjian 已提交
343 344 345 346 347
				{
					char		sebuf[256];

					if (n == -1)
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
348 349
									libpq_gettext("SSL SYSCALL error: %s\n"),
							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
B
Bruce Momjian 已提交
350
					else
351
					{
B
Bruce Momjian 已提交
352
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
353
						 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
354

355
						SOCK_ERRNO_SET(ECONNRESET);
356 357
						n = -1;
					}
B
Bruce Momjian 已提交
358 359
					break;
				}
B
Bruce Momjian 已提交
360
			case SSL_ERROR_SSL:
361
				{
B
Bruce Momjian 已提交
362 363
					char	   *err = SSLerrmessage();

364
					printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
365
									  libpq_gettext("SSL error: %s\n"), err);
366 367
					SSLerrfree(err);
				}
B
Bruce Momjian 已提交
368 369
				/* fall through */
			case SSL_ERROR_ZERO_RETURN:
370
				SOCK_ERRNO_SET(ECONNRESET);
B
Bruce Momjian 已提交
371 372
				n = -1;
				break;
373 374
			default:
				printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
375
						  libpq_gettext("unrecognized SSL error code: %d\n"),
376
								  err);
377
				n = -1;
378
				break;
B
Bruce Momjian 已提交
379 380 381 382
		}
	}
	else
#endif
B
Bruce Momjian 已提交
383
		n = recv(conn->sock, ptr, len, 0);
B
Bruce Momjian 已提交
384 385 386 387 388 389 390 391

	return n;
}

/*
 *	Write data to a secure connection.
 */
ssize_t
B
Bruce Momjian 已提交
392
pqsecure_write(PGconn *conn, const void *ptr, size_t len)
B
Bruce Momjian 已提交
393
{
B
Bruce Momjian 已提交
394
	ssize_t		n;
B
Bruce Momjian 已提交
395 396

#ifndef WIN32
397
#ifdef ENABLE_THREAD_SAFETY
398 399
	sigset_t	osigmask;
	bool		sigpipe_pending;
400
	bool		got_epipe = false;
B
Bruce Momjian 已提交
401

402

403 404
	if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0)
		return -1;
405
#else
B
Bruce Momjian 已提交
406
	pqsigfunc	oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
B
Bruce Momjian 已提交
407 408 409
#endif   /* ENABLE_THREAD_SAFETY */
#endif   /* WIN32 */

B
Bruce Momjian 已提交
410 411 412
#ifdef USE_SSL
	if (conn->ssl)
	{
413 414
		int			err;

B
Bruce Momjian 已提交
415
		n = SSL_write(conn->ssl, ptr, len);
416 417
		err = SSL_get_error(conn->ssl, n);
		switch (err)
B
Bruce Momjian 已提交
418
		{
B
Bruce Momjian 已提交
419 420
			case SSL_ERROR_NONE:
				break;
421
			case SSL_ERROR_WANT_READ:
B
Bruce Momjian 已提交
422

423 424
				/*
				 * Returning 0 here causes caller to wait for write-ready,
B
Bruce Momjian 已提交
425 426
				 * which is not really the right thing, but it's the best we
				 * can do.
427 428 429
				 */
				n = 0;
				break;
B
Bruce Momjian 已提交
430
			case SSL_ERROR_WANT_WRITE:
431 432
				n = 0;
				break;
B
Bruce Momjian 已提交
433
			case SSL_ERROR_SYSCALL:
B
Bruce Momjian 已提交
434 435
				{
					char		sebuf[256];
436

B
Bruce Momjian 已提交
437
					if (n == -1)
438
					{
439
#if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
440 441
						if (SOCK_ERRNO == EPIPE)
							got_epipe = true;
442
#endif
B
Bruce Momjian 已提交
443
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
444 445
									libpq_gettext("SSL SYSCALL error: %s\n"),
							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
446
					}
B
Bruce Momjian 已提交
447
					else
448
					{
B
Bruce Momjian 已提交
449
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
450
						 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
451
						SOCK_ERRNO_SET(ECONNRESET);
452 453
						n = -1;
					}
B
Bruce Momjian 已提交
454 455
					break;
				}
B
Bruce Momjian 已提交
456
			case SSL_ERROR_SSL:
457
				{
B
Bruce Momjian 已提交
458 459
					char	   *err = SSLerrmessage();

460
					printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
461
									  libpq_gettext("SSL error: %s\n"), err);
462 463
					SSLerrfree(err);
				}
B
Bruce Momjian 已提交
464 465
				/* fall through */
			case SSL_ERROR_ZERO_RETURN:
466
				SOCK_ERRNO_SET(ECONNRESET);
B
Bruce Momjian 已提交
467 468
				n = -1;
				break;
469 470
			default:
				printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
471
						  libpq_gettext("unrecognized SSL error code: %d\n"),
472
								  err);
473
				n = -1;
474
				break;
B
Bruce Momjian 已提交
475 476 477 478
		}
	}
	else
#endif
479
	{
B
Bruce Momjian 已提交
480
		n = send(conn->sock, ptr, len, 0);
481
#if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
482 483 484 485
		if (n < 0 && SOCK_ERRNO == EPIPE)
			got_epipe = true;
#endif
	}
B
Bruce Momjian 已提交
486

487
#ifndef WIN32
488
#ifdef ENABLE_THREAD_SAFETY
489
	pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe);
490
#else
B
Bruce Momjian 已提交
491
	pqsignal(SIGPIPE, oldsighandler);
B
Bruce Momjian 已提交
492 493
#endif   /* ENABLE_THREAD_SAFETY */
#endif   /* WIN32 */
B
Bruce Momjian 已提交
494 495 496 497 498

	return n;
}

/* ------------------------------------------------------------ */
B
Bruce Momjian 已提交
499
/*						  SSL specific code						*/
B
Bruce Momjian 已提交
500 501
/* ------------------------------------------------------------ */
#ifdef USE_SSL
502

B
Bruce Momjian 已提交
503 504 505 506 507 508 509 510 511 512 513 514
/*
 *	Certificate verification callback
 *
 *	This callback allows us to log intermediate problems during
 *	verification, but there doesn't seem to be a clean way to get
 *	our PGconn * structure.  So we can't log anything!
 *
 *	This callback also allows us to override the default acceptance
 *	criteria (e.g., accepting self-signed or expired certs), but
 *	for now we accept the default checks.
 */
static int
B
Bruce Momjian 已提交
515
verify_cb(int ok, X509_STORE_CTX *ctx)
B
Bruce Momjian 已提交
516 517 518 519
{
	return ok;
}

B
Bruce Momjian 已提交
520
#ifdef NOT_USED
B
Bruce Momjian 已提交
521 522 523 524
/*
 *	Verify that common name resolves to peer.
 */
static int
B
Bruce Momjian 已提交
525
verify_peer(PGconn *conn)
B
Bruce Momjian 已提交
526 527 528 529
{
	struct hostent *h = NULL;
	struct sockaddr addr;
	struct sockaddr_in *sin;
B
Bruce Momjian 已提交
530 531
	socklen_t	len;
	char	  **s;
B
Bruce Momjian 已提交
532 533 534 535 536 537
	unsigned long l;

	/* get the address on the other side of the socket */
	len = sizeof(addr);
	if (getpeername(conn->sock, &addr, &len) == -1)
	{
B
Bruce Momjian 已提交
538 539
		char		sebuf[256];

B
Bruce Momjian 已提交
540
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
541
						  libpq_gettext("error querying socket: %s\n"),
B
Bruce Momjian 已提交
542
						  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
B
Bruce Momjian 已提交
543 544 545 546 547 548 549
		return -1;
	}

	/* weird, but legal case */
	if (addr.sa_family == AF_UNIX)
		return 0;

550 551
	{
		struct hostent hpstr;
552
		char		buf[BUFSIZ];
B
Bruce Momjian 已提交
553
		int			herrno = 0;
B
Bruce Momjian 已提交
554

555
		/*
B
Bruce Momjian 已提交
556 557 558
		 * Currently, pqGethostbyname() is used only on platforms that don't
		 * have getaddrinfo().	If you enable this function, you should
		 * convert the pqGethostbyname() function call to use getaddrinfo().
559
		 */
560
		pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
B
Bruce Momjian 已提交
561
						&h, &herrno);
562
	}
B
Bruce Momjian 已提交
563

B
Bruce Momjian 已提交
564
	/* what do we know about the peer's common name? */
565
	if (h == NULL)
B
Bruce Momjian 已提交
566 567
	{
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
568
		  libpq_gettext("could not get information about host \"%s\": %s\n"),
B
Bruce Momjian 已提交
569
						  conn->peer_cn, hstrerror(h_errno));
B
Bruce Momjian 已提交
570 571 572 573 574 575
		return -1;
	}

	/* does the address match? */
	switch (addr.sa_family)
	{
B
Bruce Momjian 已提交
576 577 578 579 580 581 582 583
		case AF_INET:
			sin = (struct sockaddr_in *) & addr;
			for (s = h->h_addr_list; *s != NULL; s++)
			{
				if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
					return 0;
			}
			break;
B
Bruce Momjian 已提交
584

B
Bruce Momjian 已提交
585 586
		default:
			printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
587
							  libpq_gettext("unsupported protocol\n"));
B
Bruce Momjian 已提交
588
			return -1;
B
Bruce Momjian 已提交
589 590
	}

B
Bruce Momjian 已提交
591 592 593 594
	/*
	 * the prior test should be definitive, but in practice it sometimes
	 * fails.  So we also check the aliases.
	 */
B
Bruce Momjian 已提交
595 596
	for (s = h->h_aliases; *s != NULL; s++)
	{
597
		if (pg_strcasecmp(conn->peer_cn, *s) == 0)
B
Bruce Momjian 已提交
598 599 600 601 602 603
			return 0;
	}

	/* generate protocol-aware error message */
	switch (addr.sa_family)
	{
B
Bruce Momjian 已提交
604 605 606 607 608
		case AF_INET:
			sin = (struct sockaddr_in *) & addr;
			l = ntohl(sin->sin_addr.s_addr);
			printfPQExpBuffer(&conn->errorMessage,
							  libpq_gettext(
609
											"server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
B
Bruce Momjian 已提交
610
						 conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
B
Bruce Momjian 已提交
611 612 613 614 615
							  (l >> 8) % 0x100, l % 0x100);
			break;
		default:
			printfPQExpBuffer(&conn->errorMessage,
							  libpq_gettext(
B
Bruce Momjian 已提交
616
			 "server common name \"%s\" does not resolve to peer address\n"),
B
Bruce Momjian 已提交
617
							  conn->peer_cn);
B
Bruce Momjian 已提交
618 619 620 621
	}

	return -1;
}
B
Bruce Momjian 已提交
622
#endif   /* NOT_USED */
B
Bruce Momjian 已提交
623

624 625 626 627
/*
 *	Load precomputed DH parameters.
 *
 *	To prevent "downgrade" attacks, we perform a number of checks
B
Bruce Momjian 已提交
628
 *	to verify that the DBA-generated DH parameters file contains
629 630
 *	what we expect it to contain.
 */
B
Bruce Momjian 已提交
631 632
static DH  *
load_dh_file(int keylength)
633
{
634
	char		homedir[MAXPGPATH];
635
	char		fnbuf[MAXPGPATH];
636 637
	FILE	   *fp;
	DH		   *dh;
B
Bruce Momjian 已提交
638
	int			codes;
639

640
	if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
B
Bruce Momjian 已提交
641
		return NULL;
642 643

	/* attempt to open file.  It's not an error if it doesn't exist. */
644
	snprintf(fnbuf, sizeof(fnbuf), DHFILEPATTERN, homedir, keylength);
645

646 647 648 649 650 651 652 653 654
	if ((fp = fopen(fnbuf, "r")) == NULL)
		return NULL;

/*	flock(fileno(fp), LOCK_SH); */
	dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
/*	flock(fileno(fp), LOCK_UN); */
	fclose(fp);

	/* is the prime the correct size? */
B
Bruce Momjian 已提交
655
	if (dh != NULL && 8 * DH_size(dh) < keylength)
656 657 658 659 660 661 662 663 664
		dh = NULL;

	/* make sure the DH parameters are usable */
	if (dh != NULL)
	{
		if (DH_check(dh, &codes))
			return NULL;
		if (codes & DH_CHECK_P_NOT_PRIME)
			return NULL;
B
Bruce Momjian 已提交
665
		if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
666 667 668 669 670 671 672 673 674 675 676 677 678
			(codes & DH_CHECK_P_NOT_SAFE_PRIME))
			return NULL;
	}

	return dh;
}

/*
 *	Load hardcoded DH parameters.
 *
 *	To prevent problems if the DH parameters files don't even
 *	exist, we can load DH parameters hardcoded into this file.
 */
B
Bruce Momjian 已提交
679 680
static DH  *
load_dh_buffer(const char *buffer, size_t len)
681
{
B
Bruce Momjian 已提交
682 683
	BIO		   *bio;
	DH		   *dh = NULL;
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

	bio = BIO_new_mem_buf((char *) buffer, len);
	if (bio == NULL)
		return NULL;
	dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
	BIO_free(bio);

	return dh;
}

/*
 *	Generate an empheral DH key.  Because this can take a long
 *	time to compute, we can use precomputed parameters of the
 *	common key sizes.
 *
 *	Since few sites will bother to precompute these parameter
 *	files, we also provide a fallback to the parameters provided
 *	by the OpenSSL project.
 *
 *	These values can be static (once loaded or computed) since
 *	the OpenSSL library can efficiently generate random keys from
 *	the information provided.
 */
B
Bruce Momjian 已提交
707 708
static DH  *
tmp_dh_cb(SSL *s, int is_export, int keylength)
709
{
B
Bruce Momjian 已提交
710 711 712 713 714 715
	DH		   *r = NULL;
	static DH  *dh = NULL;
	static DH  *dh512 = NULL;
	static DH  *dh1024 = NULL;
	static DH  *dh2048 = NULL;
	static DH  *dh4096 = NULL;
716 717 718

	switch (keylength)
	{
B
Bruce Momjian 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
		case 512:
			if (dh512 == NULL)
				dh512 = load_dh_file(keylength);
			if (dh512 == NULL)
				dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
			r = dh512;
			break;

		case 1024:
			if (dh1024 == NULL)
				dh1024 = load_dh_file(keylength);
			if (dh1024 == NULL)
				dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
			r = dh1024;
			break;

		case 2048:
			if (dh2048 == NULL)
				dh2048 = load_dh_file(keylength);
			if (dh2048 == NULL)
				dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
			r = dh2048;
			break;

		case 4096:
			if (dh4096 == NULL)
				dh4096 = load_dh_file(keylength);
			if (dh4096 == NULL)
				dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
			r = dh4096;
			break;

		default:
			if (dh == NULL)
				dh = load_dh_file(keylength);
			r = dh;
755 756 757
	}

	/* this may take a long time, but it may be necessary... */
B
Bruce Momjian 已提交
758
	if (r == NULL || 8 * DH_size(r) < keylength)
759
		r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
B
Bruce Momjian 已提交
760

761 762 763
	return r;
}

764 765 766 767 768
/*
 *	Callback used by SSL to load client cert and key.
 *	This callback is only called when the server wants a
 *	client cert.
 *
769
 *	Must return 1 on success, 0 on no data or error.
770 771
 */
static int
B
Bruce Momjian 已提交
772
client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
773
{
774
	char		homedir[MAXPGPATH];
775
	struct stat buf;
B
Bruce Momjian 已提交
776

777 778 779
#ifndef WIN32
	struct stat buf2;
#endif
780
	char		fnbuf[MAXPGPATH];
B
Bruce Momjian 已提交
781 782 783
	FILE	   *fp;
	PGconn	   *conn = (PGconn *) SSL_get_app_data(ssl);
	int			(*cb) () = NULL;	/* how to read user password */
B
Bruce Momjian 已提交
784
	char		sebuf[256];
785

786
	if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
787
	{
B
Bruce Momjian 已提交
788
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
789
						  libpq_gettext("could not get user information\n"));
790
		return 0;
791 792 793
	}

	/* read the user certificate */
794
	snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERCERTFILE);
795 796
	if ((fp = fopen(fnbuf, "r")) == NULL)
	{
B
Bruce Momjian 已提交
797
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
798
			   libpq_gettext("could not open certificate file \"%s\": %s\n"),
799
						  fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
800
		return 0;
801 802 803
	}
	if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
	{
B
Bruce Momjian 已提交
804 805
		char	   *err = SSLerrmessage();

B
Bruce Momjian 已提交
806
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
807
			   libpq_gettext("could not read certificate file \"%s\": %s\n"),
808 809
						  fnbuf, err);
		SSLerrfree(err);
810
		fclose(fp);
811
		return 0;
812 813 814 815
	}
	fclose(fp);

	/* read the user key */
816
	snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERKEYFILE);
817 818
	if (stat(fnbuf, &buf) == -1)
	{
B
Bruce Momjian 已提交
819
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
820
						  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
B
Bruce Momjian 已提交
821
						  fnbuf);
822 823
		return 0;
	}
824
#ifndef WIN32
825
	if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
826
		buf.st_uid != geteuid())
827
	{
B
Bruce Momjian 已提交
828
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
829
			libpq_gettext("private key file \"%s\" has wrong permissions\n"),
830 831
						  fnbuf);
		return 0;
832
	}
833
#endif
834 835
	if ((fp = fopen(fnbuf, "r")) == NULL)
	{
B
Bruce Momjian 已提交
836
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
837
			   libpq_gettext("could not open private key file \"%s\": %s\n"),
838
						  fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
839
		return 0;
840
	}
841
#ifndef WIN32
842 843 844
	if (fstat(fileno(fp), &buf2) == -1 ||
		buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
	{
B
Bruce Momjian 已提交
845
		printfPQExpBuffer(&conn->errorMessage,
846 847
						  libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
		return 0;
848
	}
849
#endif
850 851
	if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
	{
B
Bruce Momjian 已提交
852 853
		char	   *err = SSLerrmessage();

B
Bruce Momjian 已提交
854
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
855
			   libpq_gettext("could not read private key file \"%s\": %s\n"),
856 857
						  fnbuf, err);
		SSLerrfree(err);
858
		fclose(fp);
859
		return 0;
860 861 862
	}
	fclose(fp);

863 864 865
	/* verify that the cert and key go together */
	if (!X509_check_private_key(*x509, *pkey))
	{
B
Bruce Momjian 已提交
866 867
		char	   *err = SSLerrmessage();

B
Bruce Momjian 已提交
868
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
869
						  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
870 871
						  fnbuf, err);
		SSLerrfree(err);
872
		return 0;
873 874
	}

875 876 877
	return 1;
}

878 879 880 881 882
#ifdef ENABLE_THREAD_SAFETY

static unsigned long
pq_threadidcallback(void)
{
883
	/*
B
Bruce Momjian 已提交
884 885 886
	 * This is not starndard-compliant.  pthread_self() returns pthread_t, and
	 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
	 * it, so we have to do it.
887
	 */
B
Bruce Momjian 已提交
888
	return (unsigned long) pthread_self();
889 890 891
}

static pthread_mutex_t *pq_lockarray;
892

893 894 895
static void
pq_lockingcallback(int mode, int n, const char *file, int line)
{
B
Bruce Momjian 已提交
896
	if (mode & CRYPTO_LOCK)
897
		pthread_mutex_lock(&pq_lockarray[n]);
B
Bruce Momjian 已提交
898
	else
899 900
		pthread_mutex_unlock(&pq_lockarray[n]);
}
B
Bruce Momjian 已提交
901
#endif   /* ENABLE_THREAD_SAFETY */
902 903 904 905 906

static int
init_ssl_system(PGconn *conn)
{
#ifdef ENABLE_THREAD_SAFETY
907
#ifndef WIN32
B
Bruce Momjian 已提交
908
	static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
909
#else
910 911 912
	static pthread_mutex_t init_mutex = NULL;
	static long mutex_initlock = 0;

B
Bruce Momjian 已提交
913 914 915 916
	if (init_mutex == NULL)
	{
		while (InterlockedExchange(&mutex_initlock, 1) == 1)
			 /* loop, another thread own the lock */ ;
917 918
		if (init_mutex == NULL)
			pthread_mutex_init(&init_mutex, NULL);
B
Bruce Momjian 已提交
919
		InterlockedExchange(&mutex_initlock, 0);
920
	}
921
#endif
922
	pthread_mutex_lock(&init_mutex);
B
Bruce Momjian 已提交
923 924 925 926 927

	if (pq_initssllib && pq_lockarray == NULL)
	{
		int			i;

928 929
		CRYPTO_set_id_callback(pq_threadidcallback);

B
Bruce Momjian 已提交
930 931 932
		pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
		if (!pq_lockarray)
		{
933 934 935
			pthread_mutex_unlock(&init_mutex);
			return -1;
		}
B
Bruce Momjian 已提交
936
		for (i = 0; i < CRYPTO_num_locks(); i++)
937 938 939 940 941 942 943
			pthread_mutex_init(&pq_lockarray[i], NULL);

		CRYPTO_set_locking_callback(pq_lockingcallback);
	}
#endif
	if (!SSL_context)
	{
B
Bruce Momjian 已提交
944 945
		if (pq_initssllib)
		{
946 947 948 949 950 951
			SSL_library_init();
			SSL_load_error_strings();
		}
		SSL_context = SSL_CTX_new(TLSv1_method());
		if (!SSL_context)
		{
B
Bruce Momjian 已提交
952 953
			char	   *err = SSLerrmessage();

954
			printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
955
						 libpq_gettext("could not create SSL context: %s\n"),
956 957 958 959 960 961 962 963 964 965 966 967 968
							  err);
			SSLerrfree(err);
#ifdef ENABLE_THREAD_SAFETY
			pthread_mutex_unlock(&init_mutex);
#endif
			return -1;
		}
	}
#ifdef ENABLE_THREAD_SAFETY
	pthread_mutex_unlock(&init_mutex);
#endif
	return 0;
}
B
Bruce Momjian 已提交
969

B
Bruce Momjian 已提交
970 971 972 973
/*
 *	Initialize global SSL context.
 */
static int
B
Bruce Momjian 已提交
974
initialize_SSL(PGconn *conn)
B
Bruce Momjian 已提交
975 976
{
	struct stat buf;
977
	char		homedir[MAXPGPATH];
978
	char		fnbuf[MAXPGPATH];
B
Bruce Momjian 已提交
979

B
Bruce Momjian 已提交
980
	if (init_ssl_system(conn))
981
		return -1;
B
Bruce Momjian 已提交
982

983
	/* Set up to verify server cert, if root.crt is present */
984
	if (pqGetHomeDirectory(homedir, sizeof(homedir)))
B
Bruce Momjian 已提交
985
	{
986
		snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOTCERTFILE);
987
		if (stat(fnbuf, &buf) == 0)
B
Bruce Momjian 已提交
988
		{
989 990 991
			if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
			{
				char	   *err = SSLerrmessage();
B
Bruce Momjian 已提交
992

993 994 995 996 997 998
				printfPQExpBuffer(&conn->errorMessage,
								  libpq_gettext("could not read root certificate file \"%s\": %s\n"),
								  fnbuf, err);
				SSLerrfree(err);
				return -1;
			}
B
Bruce Momjian 已提交
999

1000
			SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
B
Bruce Momjian 已提交
1001 1002 1003
		}
	}

1004 1005 1006 1007
	/* set up empheral DH keys */
	SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
	SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE);

1008 1009 1010
	/* set up mechanism to provide client certificate, if available */
	SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);

B
Bruce Momjian 已提交
1011 1012 1013 1014 1015 1016 1017
	return 0;
}

/*
 *	Destroy global SSL context.
 */
static void
B
Bruce Momjian 已提交
1018
destroy_SSL(void)
B
Bruce Momjian 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
{
	if (SSL_context)
	{
		SSL_CTX_free(SSL_context);
		SSL_context = NULL;
	}
}

/*
 *	Attempt to negotiate SSL connection.
 */
1030
static PostgresPollingStatusType
B
Bruce Momjian 已提交
1031
open_client_SSL(PGconn *conn)
B
Bruce Momjian 已提交
1032
{
B
Bruce Momjian 已提交
1033
	int			r;
B
Bruce Momjian 已提交
1034

1035 1036
	r = SSL_connect(conn->ssl);
	if (r <= 0)
B
Bruce Momjian 已提交
1037
	{
B
Bruce Momjian 已提交
1038
		int			err = SSL_get_error(conn->ssl, r);
1039

1040
		switch (err)
1041 1042 1043
		{
			case SSL_ERROR_WANT_READ:
				return PGRES_POLLING_READING;
B
Bruce Momjian 已提交
1044

1045 1046 1047 1048
			case SSL_ERROR_WANT_WRITE:
				return PGRES_POLLING_WRITING;

			case SSL_ERROR_SYSCALL:
B
Bruce Momjian 已提交
1049 1050 1051 1052 1053
				{
					char		sebuf[256];

					if (r == -1)
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
1054 1055
									libpq_gettext("SSL SYSCALL error: %s\n"),
							SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
B
Bruce Momjian 已提交
1056 1057
					else
						printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
1058
						 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
B
Bruce Momjian 已提交
1059 1060 1061
					close_SSL(conn);
					return PGRES_POLLING_FAILED;
				}
1062
			case SSL_ERROR_SSL:
1063
				{
1064 1065 1066 1067 1068
					/*
					 * If there are problems with the local certificate files,
					 * these will be detected by client_cert_cb() which is
					 * called from SSL_connect().  We want to return that
					 * error message and not the rather unhelpful error that
B
Bruce Momjian 已提交
1069
					 * OpenSSL itself returns.	So check to see if an error
1070 1071 1072 1073 1074
					 * message was already stored.
					 */
					if (conn->errorMessage.len == 0)
					{
						char	   *err = SSLerrmessage();
B
Bruce Momjian 已提交
1075

1076 1077 1078 1079 1080
						printfPQExpBuffer(&conn->errorMessage,
										  libpq_gettext("SSL error: %s\n"),
										  err);
						SSLerrfree(err);
					}
1081 1082 1083
					close_SSL(conn);
					return PGRES_POLLING_FAILED;
				}
1084 1085 1086

			default:
				printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
1087
						  libpq_gettext("unrecognized SSL error code: %d\n"),
1088
								  err);
1089 1090 1091
				close_SSL(conn);
				return PGRES_POLLING_FAILED;
		}
B
Bruce Momjian 已提交
1092 1093 1094
	}

	/* check the certificate chain of the server */
B
Bruce Momjian 已提交
1095

1096 1097
#ifdef NOT_USED
	/* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
B
Bruce Momjian 已提交
1098

B
Bruce Momjian 已提交
1099 1100 1101 1102
	/*
	 * this eliminates simple man-in-the-middle attacks and simple
	 * impersonations
	 */
B
Bruce Momjian 已提交
1103 1104 1105 1106
	r = SSL_get_verify_result(conn->ssl);
	if (r != X509_V_OK)
	{
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
1107
				   libpq_gettext("certificate could not be validated: %s\n"),
B
Bruce Momjian 已提交
1108
						  X509_verify_cert_error_string(r));
B
Bruce Momjian 已提交
1109
		close_SSL(conn);
1110
		return PGRES_POLLING_FAILED;
B
Bruce Momjian 已提交
1111
	}
1112
#endif
B
Bruce Momjian 已提交
1113 1114 1115 1116 1117

	/* pull out server distinguished and common names */
	conn->peer = SSL_get_peer_certificate(conn->ssl);
	if (conn->peer == NULL)
	{
B
Bruce Momjian 已提交
1118 1119
		char	   *err = SSLerrmessage();

B
Bruce Momjian 已提交
1120
		printfPQExpBuffer(&conn->errorMessage,
B
Bruce Momjian 已提交
1121
					libpq_gettext("certificate could not be obtained: %s\n"),
1122 1123
						  err);
		SSLerrfree(err);
B
Bruce Momjian 已提交
1124
		close_SSL(conn);
1125
		return PGRES_POLLING_FAILED;
B
Bruce Momjian 已提交
1126 1127 1128
	}

	X509_NAME_oneline(X509_get_subject_name(conn->peer),
B
Bruce Momjian 已提交
1129 1130
					  conn->peer_dn, sizeof(conn->peer_dn));
	conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
B
Bruce Momjian 已提交
1131 1132

	X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
B
Bruce Momjian 已提交
1133
							  NID_commonName, conn->peer_cn, SM_USER);
B
Bruce Momjian 已提交
1134 1135 1136
	conn->peer_cn[SM_USER] = '\0';

	/* verify that the common name resolves to peer */
B
Bruce Momjian 已提交
1137

1138 1139
#ifdef NOT_USED
	/* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
B
Bruce Momjian 已提交
1140

B
Bruce Momjian 已提交
1141 1142
	/*
	 * this is necessary to eliminate man-in-the-middle attacks and
B
Bruce Momjian 已提交
1143 1144
	 * impersonations where the attacker somehow learned the server's private
	 * key
B
Bruce Momjian 已提交
1145
	 */
B
Bruce Momjian 已提交
1146 1147 1148
	if (verify_peer(conn) == -1)
	{
		close_SSL(conn);
1149
		return PGRES_POLLING_FAILED;
B
Bruce Momjian 已提交
1150
	}
1151
#endif
B
Bruce Momjian 已提交
1152

1153 1154
	/* SSL handshake is complete */
	return PGRES_POLLING_OK;
B
Bruce Momjian 已提交
1155 1156 1157 1158 1159 1160
}

/*
 *	Close SSL connection.
 */
static void
B
Bruce Momjian 已提交
1161
close_SSL(PGconn *conn)
B
Bruce Momjian 已提交
1162 1163 1164 1165 1166 1167 1168
{
	if (conn->ssl)
	{
		SSL_shutdown(conn->ssl);
		SSL_free(conn->ssl);
		conn->ssl = NULL;
	}
1169 1170 1171 1172 1173 1174

	if (conn->peer)
	{
		X509_free(conn->peer);
		conn->peer = NULL;
	}
B
Bruce Momjian 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183
}

/*
 * Obtain reason string for last SSL error
 *
 * Some caution is needed here since ERR_reason_error_string will
 * return NULL if it doesn't recognize the error code.  We don't
 * want to return NULL ever.
 */
1184
static char ssl_nomem[] = "Out of memory allocating error description";
B
Bruce Momjian 已提交
1185 1186

#define SSL_ERR_LEN 128
1187 1188

static char *
B
Bruce Momjian 已提交
1189 1190
SSLerrmessage(void)
{
B
Bruce Momjian 已提交
1191 1192
	unsigned long errcode;
	const char *errreason;
B
Bruce Momjian 已提交
1193
	char	   *errbuf;
B
Bruce Momjian 已提交
1194

1195 1196 1197
	errbuf = malloc(SSL_ERR_LEN);
	if (!errbuf)
		return ssl_nomem;
B
Bruce Momjian 已提交
1198
	errcode = ERR_get_error();
B
Bruce Momjian 已提交
1199 1200
	if (errcode == 0)
	{
1201 1202 1203
		strcpy(errbuf, "No SSL error reported");
		return errbuf;
	}
B
Bruce Momjian 已提交
1204
	errreason = ERR_reason_error_string(errcode);
B
Bruce Momjian 已提交
1205 1206 1207 1208
	if (errreason != NULL)
	{
		strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
		errbuf[SSL_ERR_LEN - 1] = '\0';
1209 1210 1211
		return errbuf;
	}
	snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
B
Bruce Momjian 已提交
1212 1213 1214
	return errbuf;
}

1215 1216 1217 1218 1219 1220
static void
SSLerrfree(char *buf)
{
	if (buf != ssl_nomem)
		free(buf);
}
B
Bruce Momjian 已提交
1221

B
Bruce Momjian 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
/*
 *	Return pointer to SSL object.
 */
SSL *
PQgetssl(PGconn *conn)
{
	if (!conn)
		return NULL;
	return conn->ssl;
}
B
Bruce Momjian 已提交
1232
#else							/* !USE_SSL */
1233

1234 1235 1236 1237 1238
void *
PQgetssl(PGconn *conn)
{
	return NULL;
}
B
Bruce Momjian 已提交
1239
#endif   /* USE_SSL */
1240

1241
#if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1242

1243
/*
B
Bruce Momjian 已提交
1244
 *	Block SIGPIPE for this thread.	This prevents send()/write() from exiting
1245
 *	the application.
1246
 */
1247 1248
int
pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1249
{
B
Bruce Momjian 已提交
1250 1251 1252
	sigset_t	sigpipe_sigset;
	sigset_t	sigset;

1253 1254 1255 1256
	sigemptyset(&sigpipe_sigset);
	sigaddset(&sigpipe_sigset, SIGPIPE);

	/* Block SIGPIPE and save previous mask for later reset */
1257 1258 1259
	SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
	if (SOCK_ERRNO)
		return -1;
1260 1261 1262

	/* We can have a pending SIGPIPE only if it was blocked before */
	if (sigismember(osigset, SIGPIPE))
1263
	{
1264 1265 1266
		/* Is there a pending SIGPIPE? */
		if (sigpending(&sigset) != 0)
			return -1;
B
Bruce Momjian 已提交
1267

1268 1269
		if (sigismember(&sigset, SIGPIPE))
			*sigpipe_pending = true;
1270
		else
1271
			*sigpipe_pending = false;
1272
	}
1273 1274
	else
		*sigpipe_pending = false;
B
Bruce Momjian 已提交
1275

1276
	return 0;
1277
}
B
Bruce Momjian 已提交
1278

1279
/*
1280
 *	Discard any pending SIGPIPE and reset the signal mask.
1281 1282
 *
 * Note: we are effectively assuming here that the C library doesn't queue
B
Bruce Momjian 已提交
1283
 * up multiple SIGPIPE events.	If it did, then we'd accidentally leave
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
 * ours in the queue when an event was already pending and we got another.
 * As long as it doesn't queue multiple events, we're OK because the caller
 * can't tell the difference.
 *
 * The caller should say got_epipe = FALSE if it is certain that it
 * didn't get an EPIPE error; in that case we'll skip the clear operation
 * and things are definitely OK, queuing or no.  If it got one or might have
 * gotten one, pass got_epipe = TRUE.
 *
 * We do not want this to change errno, since if it did that could lose
B
Bruce Momjian 已提交
1294
 * the error code from a preceding send().	We essentially assume that if
1295
 * we were able to do pq_block_sigpipe(), this can't fail.
1296
 */
1297 1298
void
pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1299
{
B
Bruce Momjian 已提交
1300 1301 1302
	int			save_errno = SOCK_ERRNO;
	int			signo;
	sigset_t	sigset;
B
Bruce Momjian 已提交
1303

1304
	/* Clear SIGPIPE only if none was pending */
1305
	if (got_epipe && !sigpipe_pending)
1306
	{
1307 1308
		if (sigpending(&sigset) == 0 &&
			sigismember(&sigset, SIGPIPE))
1309
		{
B
Bruce Momjian 已提交
1310 1311
			sigset_t	sigpipe_sigset;

1312 1313
			sigemptyset(&sigpipe_sigset);
			sigaddset(&sigpipe_sigset, SIGPIPE);
1314

1315 1316 1317
			sigwait(&sigpipe_sigset, &signo);
		}
	}
B
Bruce Momjian 已提交
1318

1319
	/* Restore saved block mask */
1320 1321 1322
	pthread_sigmask(SIG_SETMASK, osigset, NULL);

	SOCK_ERRNO_SET(save_errno);
1323
}
1324

B
Bruce Momjian 已提交
1325
#endif   /* ENABLE_THREAD_SAFETY */