TLA Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * fe-secure-openssl.c
4 : * OpenSSL support
5 : *
6 : *
7 : * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
8 : * Portions Copyright (c) 1994, Regents of the University of California
9 : *
10 : *
11 : * IDENTIFICATION
12 : * src/interfaces/libpq/fe-secure-openssl.c
13 : *
14 : * NOTES
15 : *
16 : * We don't provide informational callbacks here (like
17 : * info_cb() in be-secure-openssl.c), since there's no good mechanism to
18 : * display such information to the user.
19 : *
20 : *-------------------------------------------------------------------------
21 : */
22 :
23 : #include "postgres_fe.h"
24 :
25 : #include <signal.h>
26 : #include <fcntl.h>
27 : #include <ctype.h>
28 :
29 : #include "libpq-fe.h"
30 : #include "fe-auth.h"
31 : #include "fe-secure-common.h"
32 : #include "libpq-int.h"
33 :
34 : #ifdef WIN32
35 : #include "win32.h"
36 : #else
37 : #include <sys/socket.h>
38 : #include <unistd.h>
39 : #include <netdb.h>
40 : #include <netinet/in.h>
41 : #include <netinet/tcp.h>
42 : #include <arpa/inet.h>
43 : #endif
44 :
45 : #include <sys/stat.h>
46 :
47 : #ifdef ENABLE_THREAD_SAFETY
48 : #ifdef WIN32
49 : #include "pthread-win32.h"
50 : #else
51 : #include <pthread.h>
52 : #endif
53 : #endif
54 :
55 : /*
56 : * These SSL-related #includes must come after all system-provided headers.
57 : * This ensures that OpenSSL can take care of conflicts with Windows'
58 : * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
59 : * include <wincrypt.h>, but some other Windows headers do.)
60 : */
61 : #include "common/openssl.h"
62 : #include <openssl/conf.h>
63 : #ifdef USE_SSL_ENGINE
64 : #include <openssl/engine.h>
65 : #endif
66 : #include <openssl/x509v3.h>
67 :
68 :
69 : static int verify_cb(int ok, X509_STORE_CTX *ctx);
70 : static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn,
71 : ASN1_STRING *name_entry,
72 : char **store_name);
73 : static int openssl_verify_peer_name_matches_certificate_ip(PGconn *conn,
74 : ASN1_OCTET_STRING *addr_entry,
75 : char **store_name);
76 : static void destroy_ssl_system(void);
77 : static int initialize_SSL(PGconn *conn);
78 : static PostgresPollingStatusType open_client_SSL(PGconn *conn);
79 : static char *SSLerrmessage(unsigned long ecode);
80 : static void SSLerrfree(char *buf);
81 : static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
82 :
83 : static int my_sock_read(BIO *h, char *buf, int size);
84 : static int my_sock_write(BIO *h, const char *buf, int size);
85 : static BIO_METHOD *my_BIO_s_socket(void);
86 : static int my_SSL_set_fd(PGconn *conn, int fd);
87 :
88 :
89 : static bool pq_init_ssl_lib = true;
90 : static bool pq_init_crypto_lib = true;
91 :
92 : static bool ssl_lib_initialized = false;
93 :
94 : #ifdef ENABLE_THREAD_SAFETY
95 : static long crypto_open_connections = 0;
96 :
97 : #ifndef WIN32
98 : static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
99 : #else
100 : static pthread_mutex_t ssl_config_mutex = NULL;
101 : static long win32_ssl_create_mutex = 0;
102 : #endif
103 : #endif /* ENABLE_THREAD_SAFETY */
104 :
105 : static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook = NULL;
106 : static int ssl_protocol_version_to_openssl(const char *protocol);
107 :
108 : /* ------------------------------------------------------------ */
109 : /* Procedures common to all secure sessions */
110 : /* ------------------------------------------------------------ */
111 EUB :
112 : void
113 UIC 0 : pgtls_init_library(bool do_ssl, int do_crypto)
114 : {
115 : #ifdef ENABLE_THREAD_SAFETY
116 :
117 : /*
118 : * Disallow changing the flags while we have open connections, else we'd
119 EUB : * get completely confused.
120 : */
121 UIC 0 : if (crypto_open_connections != 0)
122 0 : return;
123 EUB : #endif
124 :
125 UIC 0 : pq_init_ssl_lib = do_ssl;
126 0 : pq_init_crypto_lib = do_crypto;
127 : }
128 ECB :
129 : PostgresPollingStatusType
130 GIC 305 : pgtls_open_client(PGconn *conn)
131 ECB : {
132 : /* First time through? */
133 GIC 305 : if (conn->ssl == NULL)
134 : {
135 : /*
136 : * Create a connection-specific SSL object, and load client
137 ECB : * certificate, private key, and trusted CA certs.
138 : */
139 GIC 116 : if (initialize_SSL(conn) != 0)
140 ECB : {
141 : /* initialize_SSL already put a message in conn->errorMessage */
142 GIC 4 : pgtls_close(conn);
143 4 : return PGRES_POLLING_FAILED;
144 : }
145 : }
146 ECB :
147 : /* Begin or continue the actual handshake */
148 GIC 301 : return open_client_SSL(conn);
149 : }
150 ECB :
151 : ssize_t
152 GIC 365 : pgtls_read(PGconn *conn, void *ptr, size_t len)
153 ECB : {
154 : ssize_t n;
155 GIC 365 : int result_errno = 0;
156 : char sebuf[PG_STRERROR_R_BUFLEN];
157 : int err;
158 ECB : unsigned long ecode;
159 :
160 GIC 365 : rloop:
161 :
162 : /*
163 : * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
164 : * queue. In general, the current thread's error queue must be empty
165 : * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
166 : * not work reliably. Since the possibility exists that other OpenSSL
167 : * clients running in the same thread but not under our control will fail
168 : * to call ERR_get_error() themselves (after their own I/O operations),
169 ECB : * pro-actively clear the per-thread error queue now.
170 : */
171 CBC 365 : SOCK_ERRNO_SET(0);
172 365 : ERR_clear_error();
173 GIC 365 : n = SSL_read(conn->ssl, ptr, len);
174 365 : err = SSL_get_error(conn->ssl, n);
175 :
176 : /*
177 : * Other clients of OpenSSL may fail to call ERR_get_error(), but we
178 : * always do, so as to not cause problems for OpenSSL clients that don't
179 : * call ERR_clear_error() defensively. Be sure that this happens by
180 : * calling now. SSL_get_error() relies on the OpenSSL per-thread error
181 : * queue being intact, so this is the earliest possible point
182 ECB : * ERR_get_error() may be called.
183 : */
184 GIC 365 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
185 CBC 365 : switch (err)
186 ECB : {
187 GIC 175 : case SSL_ERROR_NONE:
188 175 : if (n < 0)
189 EUB : {
190 : /* Not supposed to happen, so we don't translate the msg */
191 UIC 0 : appendPQExpBufferStr(&conn->errorMessage,
192 EUB : "SSL_read failed but did not provide error information\n");
193 : /* assume the connection is broken */
194 LBC 0 : result_errno = ECONNRESET;
195 ECB : }
196 CBC 175 : break;
197 184 : case SSL_ERROR_WANT_READ:
198 GBC 184 : n = 0;
199 GIC 184 : break;
200 UIC 0 : case SSL_ERROR_WANT_WRITE:
201 :
202 : /*
203 : * Returning 0 here would cause caller to wait for read-ready,
204 : * which is not correct since what SSL wants is wait for
205 : * write-ready. The former could get us stuck in an infinite
206 EUB : * wait, so don't risk it; busy-loop instead.
207 : */
208 UBC 0 : goto rloop;
209 UIC 0 : case SSL_ERROR_SYSCALL:
210 UBC 0 : if (n < 0)
211 EUB : {
212 UIC 0 : result_errno = SOCK_ERRNO;
213 UBC 0 : if (result_errno == EPIPE ||
214 : result_errno == ECONNRESET)
215 UNC 0 : libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
216 : "\tThis probably means the server terminated abnormally\n"
217 : "\tbefore or while processing the request.");
218 : else
219 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
220 : SOCK_STRERROR(result_errno,
221 EUB : sebuf, sizeof(sebuf)));
222 : }
223 : else
224 : {
225 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
226 ECB : /* assume the connection is broken */
227 UIC 0 : result_errno = ECONNRESET;
228 LBC 0 : n = -1;
229 : }
230 0 : break;
231 CBC 6 : case SSL_ERROR_SSL:
232 : {
233 6 : char *errm = SSLerrmessage(ecode);
234 ECB :
235 GNC 6 : libpq_append_conn_error(conn, "SSL error: %s", errm);
236 GBC 6 : SSLerrfree(errm);
237 : /* assume the connection is broken */
238 GIC 6 : result_errno = ECONNRESET;
239 6 : n = -1;
240 6 : break;
241 : }
242 UIC 0 : case SSL_ERROR_ZERO_RETURN:
243 EUB :
244 : /*
245 : * Per OpenSSL documentation, this error code is only returned for
246 : * a clean connection closure, so we should not report it as a
247 : * server crash.
248 : */
249 UNC 0 : libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
250 UBC 0 : result_errno = ECONNRESET;
251 0 : n = -1;
252 UIC 0 : break;
253 0 : default:
254 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
255 ECB : /* assume the connection is broken */
256 UIC 0 : result_errno = ECONNRESET;
257 0 : n = -1;
258 0 : break;
259 ECB : }
260 :
261 : /* ensure we return the intended errno to caller */
262 GIC 365 : SOCK_ERRNO_SET(result_errno);
263 :
264 365 : return n;
265 ECB : }
266 :
267 : bool
268 CBC 478 : pgtls_read_pending(PGconn *conn)
269 : {
270 GIC 478 : return SSL_pending(conn->ssl) > 0;
271 : }
272 :
273 ECB : ssize_t
274 CBC 256 : pgtls_write(PGconn *conn, const void *ptr, size_t len)
275 ECB : {
276 : ssize_t n;
277 CBC 256 : int result_errno = 0;
278 ECB : char sebuf[PG_STRERROR_R_BUFLEN];
279 : int err;
280 : unsigned long ecode;
281 :
282 GIC 256 : SOCK_ERRNO_SET(0);
283 256 : ERR_clear_error();
284 GBC 256 : n = SSL_write(conn->ssl, ptr, len);
285 GIC 256 : err = SSL_get_error(conn->ssl, n);
286 256 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
287 GBC 256 : switch (err)
288 : {
289 CBC 256 : case SSL_ERROR_NONE:
290 GBC 256 : if (n < 0)
291 : {
292 : /* Not supposed to happen, so we don't translate the msg */
293 UIC 0 : appendPQExpBufferStr(&conn->errorMessage,
294 : "SSL_write failed but did not provide error information\n");
295 : /* assume the connection is broken */
296 UBC 0 : result_errno = ECONNRESET;
297 EUB : }
298 GBC 256 : break;
299 UBC 0 : case SSL_ERROR_WANT_READ:
300 EUB :
301 : /*
302 : * Returning 0 here causes caller to wait for write-ready, which
303 : * is not really the right thing, but it's the best we can do.
304 : */
305 UBC 0 : n = 0;
306 0 : break;
307 UIC 0 : case SSL_ERROR_WANT_WRITE:
308 0 : n = 0;
309 0 : break;
310 UBC 0 : case SSL_ERROR_SYSCALL:
311 UIC 0 : if (n < 0)
312 : {
313 0 : result_errno = SOCK_ERRNO;
314 0 : if (result_errno == EPIPE || result_errno == ECONNRESET)
315 UNC 0 : libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
316 : "\tThis probably means the server terminated abnormally\n"
317 : "\tbefore or while processing the request.");
318 EUB : else
319 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
320 EUB : SOCK_STRERROR(result_errno,
321 : sebuf, sizeof(sebuf)));
322 : }
323 : else
324 : {
325 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
326 EUB : /* assume the connection is broken */
327 UBC 0 : result_errno = ECONNRESET;
328 0 : n = -1;
329 : }
330 0 : break;
331 UIC 0 : case SSL_ERROR_SSL:
332 : {
333 0 : char *errm = SSLerrmessage(ecode);
334 :
335 UNC 0 : libpq_append_conn_error(conn, "SSL error: %s", errm);
336 UBC 0 : SSLerrfree(errm);
337 EUB : /* assume the connection is broken */
338 UBC 0 : result_errno = ECONNRESET;
339 0 : n = -1;
340 0 : break;
341 EUB : }
342 UIC 0 : case SSL_ERROR_ZERO_RETURN:
343 EUB :
344 : /*
345 : * Per OpenSSL documentation, this error code is only returned for
346 : * a clean connection closure, so we should not report it as a
347 : * server crash.
348 : */
349 UNC 0 : libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
350 LBC 0 : result_errno = ECONNRESET;
351 UIC 0 : n = -1;
352 0 : break;
353 0 : default:
354 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
355 : /* assume the connection is broken */
356 UIC 0 : result_errno = ECONNRESET;
357 0 : n = -1;
358 0 : break;
359 : }
360 :
361 : /* ensure we return the intended errno to caller */
362 CBC 256 : SOCK_ERRNO_SET(result_errno);
363 :
364 256 : return n;
365 EUB : }
366 :
367 ECB : #if defined(HAVE_X509_GET_SIGNATURE_NID) || defined(HAVE_X509_GET_SIGNATURE_INFO)
368 : char *
369 GIC 5 : pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
370 : {
371 : X509 *peer_cert;
372 : const EVP_MD *algo_type;
373 : unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
374 : unsigned int hash_size;
375 ECB : int algo_nid;
376 : char *cert_hash;
377 :
378 GIC 5 : *len = 0;
379 :
380 5 : if (!conn->peer)
381 UBC 0 : return NULL;
382 EUB :
383 GIC 5 : peer_cert = conn->peer;
384 :
385 : /*
386 : * Get the signature algorithm of the certificate to determine the hash
387 : * algorithm to use for the result. Prefer X509_get_signature_info(),
388 : * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
389 : */
390 : #if HAVE_X509_GET_SIGNATURE_INFO
391 CBC 5 : if (!X509_get_signature_info(peer_cert, &algo_nid, NULL, NULL, NULL))
392 : #else
393 EUB : if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
394 : &algo_nid, NULL))
395 : #endif
396 : {
397 UNC 0 : libpq_append_conn_error(conn, "could not determine server certificate signature algorithm");
398 LBC 0 : return NULL;
399 : }
400 EUB :
401 : /*
402 : * The TLS server's certificate bytes need to be hashed with SHA-256 if
403 : * its signature algorithm is MD5 or SHA-1 as per RFC 5929
404 ECB : * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
405 : * is used, the same hash as the signature algorithm is used.
406 : */
407 CBC 5 : switch (algo_nid)
408 : {
409 UBC 0 : case NID_md5:
410 EUB : case NID_sha1:
411 UIC 0 : algo_type = EVP_sha256();
412 0 : break;
413 GIC 5 : default:
414 CBC 5 : algo_type = EVP_get_digestbynid(algo_nid);
415 5 : if (algo_type == NULL)
416 : {
417 UNC 0 : libpq_append_conn_error(conn, "could not find digest for NID %s",
418 : OBJ_nid2sn(algo_nid));
419 LBC 0 : return NULL;
420 ECB : }
421 GIC 5 : break;
422 ECB : }
423 :
424 GIC 5 : if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
425 : {
426 UNC 0 : libpq_append_conn_error(conn, "could not generate peer certificate hash");
427 UIC 0 : return NULL;
428 : }
429 :
430 : /* save result */
431 GIC 5 : cert_hash = malloc(hash_size);
432 5 : if (cert_hash == NULL)
433 : {
434 UNC 0 : libpq_append_conn_error(conn, "out of memory");
435 UIC 0 : return NULL;
436 : }
437 GIC 5 : memcpy(cert_hash, hash, hash_size);
438 5 : *len = hash_size;
439 :
440 CBC 5 : return cert_hash;
441 : }
442 ECB : #endif /* HAVE_X509_GET_SIGNATURE_NID */
443 :
444 : /* ------------------------------------------------------------ */
445 : /* OpenSSL specific code */
446 : /* ------------------------------------------------------------ */
447 :
448 : /*
449 : * Certificate verification callback
450 : *
451 : * This callback allows us to log intermediate problems during
452 : * verification, but there doesn't seem to be a clean way to get
453 : * our PGconn * structure. So we can't log anything!
454 : *
455 : * This callback also allows us to override the default acceptance
456 : * criteria (e.g., accepting self-signed or expired certs), but
457 : * for now we accept the default checks.
458 : */
459 : static int
460 CBC 282 : verify_cb(int ok, X509_STORE_CTX *ctx)
461 : {
462 GIC 282 : return ok;
463 ECB : }
464 :
465 : #ifdef HAVE_SSL_CTX_SET_CERT_CB
466 : /*
467 : * Certificate selection callback
468 : *
469 : * This callback lets us choose the client certificate we send to the server
470 : * after seeing its CertificateRequest. We only support sending a single
471 : * hard-coded certificate via sslcert, so we don't actually set any certificates
472 : * here; we just use it to record whether or not the server has actually asked
473 : * for one and whether we have one to send.
474 : */
475 : static int
476 GNC 103 : cert_cb(SSL *ssl, void *arg)
477 : {
478 103 : PGconn *conn = arg;
479 :
480 103 : conn->ssl_cert_requested = true;
481 :
482 : /* Do we have a certificate loaded to send back? */
483 103 : if (SSL_get_certificate(ssl))
484 36 : conn->ssl_cert_sent = true;
485 :
486 : /*
487 : * Tell OpenSSL that the callback succeeded; we're not required to
488 : * actually make any changes to the SSL handle.
489 : */
490 103 : return 1;
491 : }
492 : #endif
493 :
494 : /*
495 : * OpenSSL-specific wrapper around
496 : * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
497 : * into a plain C string.
498 ECB : */
499 : static int
500 GIC 34 : openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
501 : char **store_name)
502 : {
503 : int len;
504 : const unsigned char *namedata;
505 :
506 : /* Should not happen... */
507 34 : if (name_entry == NULL)
508 ECB : {
509 UNC 0 : libpq_append_conn_error(conn, "SSL certificate's name entry is missing");
510 UIC 0 : return -1;
511 : }
512 :
513 : /*
514 ECB : * GEN_DNS can be only IA5String, equivalent to US ASCII.
515 : */
516 EUB : #ifdef HAVE_ASN1_STRING_GET0_DATA
517 GBC 34 : namedata = ASN1_STRING_get0_data(name_entry);
518 : #else
519 : namedata = ASN1_STRING_data(name_entry);
520 : #endif
521 GIC 34 : len = ASN1_STRING_length(name_entry);
522 :
523 : /* OK to cast from unsigned to plain char, since it's all ASCII. */
524 CBC 34 : return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
525 : }
526 :
527 : /*
528 ECB : * OpenSSL-specific wrapper around
529 : * pq_verify_peer_name_matches_certificate_ip(), converting the
530 : * ASN1_OCTET_STRING into a plain C string.
531 : */
532 : static int
533 GIC 24 : openssl_verify_peer_name_matches_certificate_ip(PGconn *conn,
534 : ASN1_OCTET_STRING *addr_entry,
535 : char **store_name)
536 : {
537 : int len;
538 : const unsigned char *addrdata;
539 :
540 ECB : /* Should not happen... */
541 GIC 24 : if (addr_entry == NULL)
542 : {
543 UNC 0 : libpq_append_conn_error(conn, "SSL certificate's address entry is missing");
544 UIC 0 : return -1;
545 : }
546 :
547 ECB : /*
548 : * GEN_IPADD is an OCTET STRING containing an IP address in network byte
549 EUB : * order.
550 : */
551 : #ifdef HAVE_ASN1_STRING_GET0_DATA
552 GIC 24 : addrdata = ASN1_STRING_get0_data(addr_entry);
553 : #else
554 : addrdata = ASN1_STRING_data(addr_entry);
555 : #endif
556 24 : len = ASN1_STRING_length(addr_entry);
557 :
558 CBC 24 : return pq_verify_peer_name_matches_certificate_ip(conn, addrdata, len, store_name);
559 : }
560 :
561 : static bool
562 36 : is_ip_address(const char *host)
563 : {
564 ECB : struct in_addr dummy4;
565 : #ifdef HAVE_INET_PTON
566 : struct in6_addr dummy6;
567 : #endif
568 :
569 GIC 36 : return inet_aton(host, &dummy4)
570 : #ifdef HAVE_INET_PTON
571 36 : || (inet_pton(AF_INET6, host, &dummy6) == 1)
572 : #endif
573 : ;
574 : }
575 ECB :
576 : /*
577 : * Verify that the server certificate matches the hostname we connected to.
578 : *
579 : * The certificate's Common Name and Subject Alternative Names are considered.
580 : */
581 : int
582 GIC 36 : pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
583 : int *names_examined,
584 : char **first_name)
585 : {
586 : STACK_OF(GENERAL_NAME) * peer_san;
587 : int i;
588 CBC 36 : int rc = 0;
589 GIC 36 : char *host = conn->connhost[conn->whichhost].host;
590 : int host_type;
591 36 : bool check_cn = true;
592 :
593 36 : Assert(host && host[0]); /* should be guaranteed by caller */
594 ECB :
595 : /*
596 : * We try to match the NSS behavior here, which is a slight departure from
597 : * the spec but seems to make more intuitive sense:
598 : *
599 : * If connhost contains a DNS name, and the certificate's SANs contain any
600 : * dNSName entries, then we'll ignore the Subject Common Name entirely;
601 : * otherwise, we fall back to checking the CN. (This behavior matches the
602 : * RFC.)
603 : *
604 : * If connhost contains an IP address, and the SANs contain iPAddress
605 : * entries, we again ignore the CN. Otherwise, we allow the CN to match,
606 : * EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
607 : * client MUST NOT seek a match for a reference identifier of CN-ID if the
608 : * presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
609 : * application-specific identifier types supported by the client.")
610 : *
611 : * NOTE: Prior versions of libpq did not consider iPAddress entries at
612 : * all, so this new behavior might break a certificate that has different
613 : * IP addresses in the Subject CN and the SANs.
614 : */
615 GIC 36 : if (is_ip_address(host))
616 16 : host_type = GEN_IPADD;
617 : else
618 20 : host_type = GEN_DNS;
619 :
620 : /*
621 ECB : * First, get the Subject Alternative Names (SANs) from the certificate,
622 : * and compare them against the originally given hostname.
623 : */
624 : peer_san = (STACK_OF(GENERAL_NAME) *)
625 GIC 36 : X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
626 :
627 36 : if (peer_san)
628 : {
629 29 : int san_len = sk_GENERAL_NAME_num(peer_san);
630 :
631 CBC 61 : for (i = 0; i < san_len; i++)
632 : {
633 50 : const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
634 GIC 50 : char *alt_name = NULL;
635 ECB :
636 GIC 50 : if (name->type == host_type)
637 ECB : {
638 : /*
639 : * This SAN is of the same type (IP or DNS) as our host name,
640 : * so don't allow a fallback check of the CN.
641 : */
642 CBC 43 : check_cn = false;
643 : }
644 :
645 GIC 50 : if (name->type == GEN_DNS)
646 : {
647 26 : (*names_examined)++;
648 CBC 26 : rc = openssl_verify_peer_name_matches_certificate_name(conn,
649 GIC 26 : name->d.dNSName,
650 : &alt_name);
651 ECB : }
652 GIC 24 : else if (name->type == GEN_IPADD)
653 ECB : {
654 CBC 24 : (*names_examined)++;
655 24 : rc = openssl_verify_peer_name_matches_certificate_ip(conn,
656 GIC 24 : name->d.iPAddress,
657 : &alt_name);
658 ECB : }
659 :
660 CBC 50 : if (alt_name)
661 ECB : {
662 CBC 50 : if (!*first_name)
663 GIC 29 : *first_name = alt_name;
664 : else
665 21 : free(alt_name);
666 ECB : }
667 :
668 CBC 50 : if (rc != 0)
669 ECB : {
670 : /*
671 : * Either we hit an error or a match, and either way we should
672 : * not fall back to the CN.
673 : */
674 CBC 18 : check_cn = false;
675 GIC 18 : break;
676 : }
677 : }
678 29 : sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
679 : }
680 ECB :
681 : /*
682 : * If there is no subjectAltName extension of the matching type, check the
683 : * Common Name.
684 : *
685 : * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
686 : * dNSName is present, the CN must be ignored. We break this rule if host
687 : * is an IP address; see the comment above.)
688 : */
689 GIC 36 : if (check_cn)
690 : {
691 : X509_NAME *subject_name;
692 :
693 10 : subject_name = X509_get_subject_name(conn->peer);
694 10 : if (subject_name != NULL)
695 ECB : {
696 : int cn_index;
697 :
698 GIC 10 : cn_index = X509_NAME_get_index_by_NID(subject_name,
699 ECB : NID_commonName, -1);
700 CBC 10 : if (cn_index >= 0)
701 : {
702 GIC 8 : char *common_name = NULL;
703 :
704 CBC 8 : (*names_examined)++;
705 GIC 8 : rc = openssl_verify_peer_name_matches_certificate_name(conn,
706 CBC 8 : X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
707 : &common_name);
708 ECB :
709 GIC 8 : if (common_name)
710 ECB : {
711 CBC 8 : if (!*first_name)
712 6 : *first_name = common_name;
713 : else
714 GIC 2 : free(common_name);
715 ECB : }
716 : }
717 : }
718 : }
719 :
720 CBC 36 : return rc;
721 : }
722 :
723 : #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
724 : /*
725 : * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
726 ECB : * does its own locking, and doesn't need these anymore. The
727 : * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
728 : * were made obsolete, so we assume that if CRYPTO_lock() exists,
729 : * the callbacks are still required.)
730 : */
731 :
732 : static unsigned long
733 : pq_threadidcallback(void)
734 : {
735 : /*
736 : * This is not standards-compliant. pthread_self() returns pthread_t, and
737 : * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
738 : * it, so we have to do it.
739 : */
740 : return (unsigned long) pthread_self();
741 : }
742 :
743 : static pthread_mutex_t *pq_lockarray;
744 :
745 : static void
746 : pq_lockingcallback(int mode, int n, const char *file, int line)
747 : {
748 : /*
749 : * There's no way to report a mutex-primitive failure, so we just Assert
750 : * in development builds, and ignore any errors otherwise. Fortunately
751 : * this is all obsolete in modern OpenSSL.
752 : */
753 : if (mode & CRYPTO_LOCK)
754 : {
755 : if (pthread_mutex_lock(&pq_lockarray[n]))
756 : Assert(false);
757 : }
758 : else
759 : {
760 : if (pthread_mutex_unlock(&pq_lockarray[n]))
761 : Assert(false);
762 : }
763 : }
764 : #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
765 :
766 : /*
767 : * Initialize SSL library.
768 : *
769 : * In threadsafe mode, this includes setting up libcrypto callback functions
770 : * to do thread locking.
771 : *
772 : * If the caller has told us (through PQinitOpenSSL) that he's taking care
773 : * of libcrypto, we expect that callbacks are already set, and won't try to
774 : * override it.
775 : */
776 : int
777 GIC 9302 : pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
778 : {
779 : #ifdef ENABLE_THREAD_SAFETY
780 : #ifdef WIN32
781 : /* Also see similar code in fe-connect.c, default_threadlock() */
782 : if (ssl_config_mutex == NULL)
783 ECB : {
784 : while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
785 : /* loop, another thread own the lock */ ;
786 : if (ssl_config_mutex == NULL)
787 : {
788 : if (pthread_mutex_init(&ssl_config_mutex, NULL))
789 : return -1;
790 : }
791 : InterlockedExchange(&win32_ssl_create_mutex, 0);
792 : }
793 : #endif
794 GIC 9302 : if (pthread_mutex_lock(&ssl_config_mutex))
795 UIC 0 : return -1;
796 :
797 : #ifdef HAVE_CRYPTO_LOCK
798 : if (pq_init_crypto_lib)
799 : {
800 ECB : /*
801 EUB : * If necessary, set up an array to hold locks for libcrypto.
802 : * libcrypto will tell us how big to make this array.
803 : */
804 : if (pq_lockarray == NULL)
805 : {
806 : int i;
807 :
808 : pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
809 : if (!pq_lockarray)
810 : {
811 : pthread_mutex_unlock(&ssl_config_mutex);
812 : return -1;
813 : }
814 : for (i = 0; i < CRYPTO_num_locks(); i++)
815 : {
816 : if (pthread_mutex_init(&pq_lockarray[i], NULL))
817 : {
818 : free(pq_lockarray);
819 : pq_lockarray = NULL;
820 : pthread_mutex_unlock(&ssl_config_mutex);
821 : return -1;
822 : }
823 : }
824 : }
825 :
826 : if (do_crypto && !conn->crypto_loaded)
827 : {
828 : if (crypto_open_connections++ == 0)
829 : {
830 : /*
831 : * These are only required for threaded libcrypto
832 : * applications, but make sure we don't stomp on them if
833 : * they're already set.
834 : */
835 : if (CRYPTO_get_id_callback() == NULL)
836 : CRYPTO_set_id_callback(pq_threadidcallback);
837 : if (CRYPTO_get_locking_callback() == NULL)
838 : CRYPTO_set_locking_callback(pq_lockingcallback);
839 : }
840 :
841 : conn->crypto_loaded = true;
842 : }
843 : }
844 : #endif /* HAVE_CRYPTO_LOCK */
845 : #endif /* ENABLE_THREAD_SAFETY */
846 :
847 GIC 9302 : if (!ssl_lib_initialized && do_ssl)
848 : {
849 116 : if (pq_init_ssl_lib)
850 : {
851 : #ifdef HAVE_OPENSSL_INIT_SSL
852 116 : OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
853 ECB : #else
854 : OPENSSL_config(NULL);
855 : SSL_library_init();
856 : SSL_load_error_strings();
857 : #endif
858 : }
859 GIC 116 : ssl_lib_initialized = true;
860 : }
861 :
862 : #ifdef ENABLE_THREAD_SAFETY
863 9302 : pthread_mutex_unlock(&ssl_config_mutex);
864 : #endif
865 CBC 9302 : return 0;
866 : }
867 :
868 : /*
869 ECB : * This function is needed because if the libpq library is unloaded
870 : * from the application, the callback functions will no longer exist when
871 : * libcrypto is used by other parts of the system. For this reason,
872 : * we unregister the callback functions when the last libpq
873 : * connection is closed. (The same would apply for OpenSSL callbacks
874 : * if we had any.)
875 : *
876 : * Callbacks are only set when we're compiled in threadsafe mode, so
877 : * we only need to remove them in this case. They are also not needed
878 : * with OpenSSL 1.1.0 anymore.
879 : */
880 : static void
881 GIC 114 : destroy_ssl_system(void)
882 : {
883 : #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
884 : /* Mutex is created in pgtls_init() */
885 : if (pthread_mutex_lock(&ssl_config_mutex))
886 : return;
887 ECB :
888 : if (pq_init_crypto_lib && crypto_open_connections > 0)
889 : --crypto_open_connections;
890 :
891 : if (pq_init_crypto_lib && crypto_open_connections == 0)
892 : {
893 : /*
894 : * No connections left, unregister libcrypto callbacks, if no one
895 : * registered different ones in the meantime.
896 : */
897 : if (CRYPTO_get_locking_callback() == pq_lockingcallback)
898 : CRYPTO_set_locking_callback(NULL);
899 : if (CRYPTO_get_id_callback() == pq_threadidcallback)
900 : CRYPTO_set_id_callback(NULL);
901 :
902 : /*
903 : * We don't free the lock array. If we get another connection in this
904 : * process, we will just re-use them with the existing mutexes.
905 : *
906 : * This means we leak a little memory on repeated load/unload of the
907 : * library.
908 : */
909 : }
910 :
911 : pthread_mutex_unlock(&ssl_config_mutex);
912 : #endif
913 GIC 114 : }
914 :
915 : /*
916 : * Create per-connection SSL object, and load the client certificate,
917 : * private key, and trusted CA certs.
918 : *
919 ECB : * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
920 : */
921 : static int
922 GIC 116 : initialize_SSL(PGconn *conn)
923 : {
924 : SSL_CTX *SSL_context;
925 : struct stat buf;
926 : char homedir[MAXPGPATH];
927 : char fnbuf[MAXPGPATH];
928 ECB : char sebuf[PG_STRERROR_R_BUFLEN];
929 : bool have_homedir;
930 : bool have_cert;
931 : bool have_rootcert;
932 GIC 116 : EVP_PKEY *pkey = NULL;
933 :
934 : /*
935 : * We'll need the home directory if any of the relevant parameters are
936 : * defaulted. If pqGetHomeDirectory fails, act as though none of the
937 : * files could be found.
938 ECB : */
939 GIC 116 : if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
940 116 : !(conn->sslkey && strlen(conn->sslkey) > 0) ||
941 108 : !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
942 108 : !((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
943 4 : (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
944 10 : have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
945 ECB : else /* won't need it */
946 CBC 106 : have_homedir = false;
947 ECB :
948 : /*
949 : * Create a new SSL_CTX object.
950 : *
951 : * We used to share a single SSL_CTX between all connections, but it was
952 : * complicated if connections used different certificates. So now we
953 : * create a separate context for each connection, and accept the overhead.
954 : */
955 GIC 116 : SSL_context = SSL_CTX_new(SSLv23_method());
956 116 : if (!SSL_context)
957 : {
958 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
959 :
960 UNC 0 : libpq_append_conn_error(conn, "could not create SSL context: %s", err);
961 UIC 0 : SSLerrfree(err);
962 UBC 0 : return -1;
963 : }
964 EUB :
965 : /*
966 : * Delegate the client cert password prompt to the libpq wrapper callback
967 : * if any is defined.
968 : *
969 : * If the application hasn't installed its own and the sslpassword
970 : * parameter is non-null, we install ours now to make sure we supply
971 : * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
972 : *
973 : * This will replace OpenSSL's default PEM_def_callback (which prompts on
974 : * stdin), but we're only setting it for this SSL context so it's
975 : * harmless.
976 : */
977 GIC 116 : if (PQsslKeyPassHook
978 116 : || (conn->sslpassword && strlen(conn->sslpassword) > 0))
979 : {
980 3 : SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
981 CBC 3 : SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
982 ECB : }
983 :
984 : #ifdef HAVE_SSL_CTX_SET_CERT_CB
985 : /* Set up a certificate selection callback. */
986 GNC 116 : SSL_CTX_set_cert_cb(SSL_context, cert_cb, conn);
987 : #endif
988 :
989 ECB : /* Disable old protocol versions */
990 CBC 116 : SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
991 :
992 : /* Set the minimum and maximum protocol versions if necessary */
993 GIC 116 : if (conn->ssl_min_protocol_version &&
994 116 : strlen(conn->ssl_min_protocol_version) != 0)
995 ECB : {
996 : int ssl_min_ver;
997 :
998 GIC 116 : ssl_min_ver = ssl_protocol_version_to_openssl(conn->ssl_min_protocol_version);
999 ECB :
1000 GIC 116 : if (ssl_min_ver == -1)
1001 : {
1002 UNC 0 : libpq_append_conn_error(conn, "invalid value \"%s\" for minimum SSL protocol version",
1003 : conn->ssl_min_protocol_version);
1004 UIC 0 : SSL_CTX_free(SSL_context);
1005 0 : return -1;
1006 ECB : }
1007 :
1008 CBC 116 : if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
1009 : {
1010 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1011 :
1012 UNC 0 : libpq_append_conn_error(conn, "could not set minimum SSL protocol version: %s", err);
1013 UIC 0 : SSLerrfree(err);
1014 LBC 0 : SSL_CTX_free(SSL_context);
1015 UIC 0 : return -1;
1016 EUB : }
1017 : }
1018 :
1019 GBC 116 : if (conn->ssl_max_protocol_version &&
1020 2 : strlen(conn->ssl_max_protocol_version) != 0)
1021 EUB : {
1022 : int ssl_max_ver;
1023 :
1024 GIC 2 : ssl_max_ver = ssl_protocol_version_to_openssl(conn->ssl_max_protocol_version);
1025 ECB :
1026 CBC 2 : if (ssl_max_ver == -1)
1027 : {
1028 UNC 0 : libpq_append_conn_error(conn, "invalid value \"%s\" for maximum SSL protocol version",
1029 ECB : conn->ssl_max_protocol_version);
1030 UIC 0 : SSL_CTX_free(SSL_context);
1031 LBC 0 : return -1;
1032 : }
1033 EUB :
1034 GIC 2 : if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
1035 EUB : {
1036 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1037 :
1038 UNC 0 : libpq_append_conn_error(conn, "could not set maximum SSL protocol version: %s", err);
1039 UBC 0 : SSLerrfree(err);
1040 UIC 0 : SSL_CTX_free(SSL_context);
1041 UBC 0 : return -1;
1042 EUB : }
1043 : }
1044 :
1045 : /*
1046 : * Disable OpenSSL's moving-write-buffer sanity check, because it causes
1047 : * unnecessary failures in nonblocking send cases.
1048 : */
1049 GIC 116 : SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1050 :
1051 : /*
1052 ECB : * If the root cert file exists, load it so we can perform certificate
1053 : * verification. If sslmode is "verify-full" we will also do further
1054 : * verification after the connection has been completed.
1055 : */
1056 GIC 116 : if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1057 116 : strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1058 UIC 0 : else if (have_homedir)
1059 LBC 0 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1060 ECB : else
1061 UBC 0 : fnbuf[0] = '\0';
1062 EUB :
1063 GNC 116 : if (strcmp(fnbuf, "system") == 0)
1064 : {
1065 : /*
1066 : * The "system" sentinel value indicates that we should load whatever
1067 : * root certificates are installed for use by OpenSSL; these locations
1068 : * differ by platform. Note that the default system locations may be
1069 : * further overridden by the SSL_CERT_DIR and SSL_CERT_FILE
1070 : * environment variables.
1071 : */
1072 3 : if (SSL_CTX_set_default_verify_paths(SSL_context) != 1)
1073 : {
1074 UNC 0 : char *err = SSLerrmessage(ERR_get_error());
1075 :
1076 0 : libpq_append_conn_error(conn, "could not load system root certificate paths: %s",
1077 : err);
1078 0 : SSLerrfree(err);
1079 0 : SSL_CTX_free(SSL_context);
1080 0 : return -1;
1081 : }
1082 GNC 3 : have_rootcert = true;
1083 : }
1084 226 : else if (fnbuf[0] != '\0' &&
1085 113 : stat(fnbuf, &buf) == 0)
1086 GIC 99 : {
1087 ECB : X509_STORE *cvstore;
1088 :
1089 GIC 99 : if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1090 : {
1091 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1092 :
1093 UNC 0 : libpq_append_conn_error(conn, "could not read root certificate file \"%s\": %s",
1094 : fnbuf, err);
1095 LBC 0 : SSLerrfree(err);
1096 UIC 0 : SSL_CTX_free(SSL_context);
1097 UBC 0 : return -1;
1098 : }
1099 EUB :
1100 GIC 99 : if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1101 EUB : {
1102 GBC 99 : char *fname = NULL;
1103 99 : char *dname = NULL;
1104 :
1105 CBC 99 : if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1106 GIC 97 : fname = conn->sslcrl;
1107 CBC 99 : if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
1108 99 : dname = conn->sslcrldir;
1109 ECB :
1110 : /* defaults to use the default CRL file */
1111 GIC 99 : if (!fname && !dname && have_homedir)
1112 ECB : {
1113 UIC 0 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1114 UBC 0 : fname = fnbuf;
1115 : }
1116 EUB :
1117 : /* Set the flags to check against the complete CRL chain */
1118 GBC 198 : if ((fname || dname) &&
1119 99 : X509_STORE_load_locations(cvstore, fname, dname) == 1)
1120 EUB : {
1121 GIC 5 : X509_STORE_set_flags(cvstore,
1122 : X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1123 ECB : }
1124 :
1125 : /* if not found, silently ignore; we do not require CRL */
1126 CBC 99 : ERR_clear_error();
1127 : }
1128 99 : have_rootcert = true;
1129 ECB : }
1130 : else
1131 : {
1132 : /*
1133 : * stat() failed; assume root file doesn't exist. If sslmode is
1134 : * verify-ca or verify-full, this is an error. Otherwise, continue
1135 : * without performing any server cert verification.
1136 EUB : */
1137 GBC 14 : if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1138 : {
1139 : /*
1140 : * The only way to reach here with an empty filename is if
1141 ECB : * pqGetHomeDirectory failed. That's a sufficiently unusual case
1142 : * that it seems worth having a specialized error message for it.
1143 : */
1144 CBC 2 : if (fnbuf[0] == '\0')
1145 UNC 0 : libpq_append_conn_error(conn, "could not get home directory to locate root certificate file\n"
1146 : "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.");
1147 : else
1148 GNC 2 : libpq_append_conn_error(conn, "root certificate file \"%s\" does not exist\n"
1149 : "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.", fnbuf);
1150 GIC 2 : SSL_CTX_free(SSL_context);
1151 2 : return -1;
1152 : }
1153 12 : have_rootcert = false;
1154 : }
1155 :
1156 : /* Read the client certificate file */
1157 114 : if (conn->sslcert && strlen(conn->sslcert) > 0)
1158 CBC 114 : strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1159 UIC 0 : else if (have_homedir)
1160 0 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1161 : else
1162 0 : fnbuf[0] = '\0';
1163 :
1164 GNC 114 : if (conn->sslcertmode[0] == 'd') /* disable */
1165 : {
1166 : /* don't send a client cert even if we have one */
1167 3 : have_cert = false;
1168 : }
1169 111 : else if (fnbuf[0] == '\0')
1170 ECB : {
1171 EUB : /* no home directory, proceed without a client cert */
1172 UIC 0 : have_cert = false;
1173 : }
1174 CBC 111 : else if (stat(fnbuf, &buf) != 0)
1175 : {
1176 ECB : /*
1177 : * If file is not present, just go on without a client cert; server
1178 : * might or might not accept the connection. Any other error,
1179 : * however, is grounds for complaint.
1180 : */
1181 GIC 73 : if (errno != ENOENT && errno != ENOTDIR)
1182 : {
1183 UNC 0 : libpq_append_conn_error(conn, "could not open certificate file \"%s\": %s",
1184 UBC 0 : fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
1185 0 : SSL_CTX_free(SSL_context);
1186 UIC 0 : return -1;
1187 EUB : }
1188 GIC 73 : have_cert = false;
1189 ECB : }
1190 : else
1191 : {
1192 : /*
1193 : * Cert file exists, so load it. Since OpenSSL doesn't provide the
1194 : * equivalent of "SSL_use_certificate_chain_file", we have to load it
1195 : * into the SSL context, rather than the SSL object.
1196 : */
1197 GBC 38 : if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1198 : {
1199 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
1200 :
1201 UNC 0 : libpq_append_conn_error(conn, "could not read certificate file \"%s\": %s",
1202 : fnbuf, err);
1203 UIC 0 : SSLerrfree(err);
1204 0 : SSL_CTX_free(SSL_context);
1205 LBC 0 : return -1;
1206 : }
1207 EUB :
1208 : /* need to load the associated private key, too */
1209 GBC 38 : have_cert = true;
1210 EUB : }
1211 :
1212 ECB : /*
1213 : * The SSL context is now loaded with the correct root and client
1214 : * certificates. Create a connection-specific SSL object. The private key
1215 : * is loaded directly into the SSL object. (We could load the private key
1216 : * into the context, too, but we have done it this way historically, and
1217 : * it doesn't really matter.)
1218 : */
1219 GIC 228 : if (!(conn->ssl = SSL_new(SSL_context)) ||
1220 228 : !SSL_set_app_data(conn->ssl, conn) ||
1221 CBC 114 : !my_SSL_set_fd(conn, conn->sock))
1222 : {
1223 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1224 :
1225 UNC 0 : libpq_append_conn_error(conn, "could not establish SSL connection: %s", err);
1226 UBC 0 : SSLerrfree(err);
1227 0 : SSL_CTX_free(SSL_context);
1228 UIC 0 : return -1;
1229 : }
1230 GIC 114 : conn->ssl_in_use = true;
1231 ECB :
1232 : /*
1233 : * SSL contexts are reference counted by OpenSSL. We can free it as soon
1234 : * as we have created the SSL object, and it will stick around for as long
1235 : * as it's actually needed.
1236 : */
1237 GIC 114 : SSL_CTX_free(SSL_context);
1238 114 : SSL_context = NULL;
1239 :
1240 : /*
1241 ECB : * Set Server Name Indication (SNI), if enabled by connection parameters.
1242 : * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1243 : * or IPv6).
1244 : */
1245 GBC 114 : if (conn->sslsni && conn->sslsni[0] == '1')
1246 : {
1247 114 : const char *host = conn->connhost[conn->whichhost].host;
1248 EUB :
1249 GBC 114 : if (host && host[0] &&
1250 114 : !(strspn(host, "0123456789.") == strlen(host) ||
1251 GIC 104 : strchr(host, ':')))
1252 ECB : {
1253 GIC 97 : if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1254 : {
1255 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1256 :
1257 UNC 0 : libpq_append_conn_error(conn, "could not set SSL Server Name Indication (SNI): %s", err);
1258 LBC 0 : SSLerrfree(err);
1259 UIC 0 : return -1;
1260 : }
1261 : }
1262 : }
1263 :
1264 : /*
1265 ECB : * Read the SSL key. If a key is specified, treat it as an engine:key
1266 : * combination if there is colon present - we don't support files with
1267 : * colon in the name. The exception is if the second character is a colon,
1268 : * in which case it can be a Windows filename with drive specification.
1269 : */
1270 CBC 114 : if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1271 ECB : {
1272 : #ifdef USE_SSL_ENGINE
1273 CBC 38 : if (strchr(conn->sslkey, ':')
1274 : #ifdef WIN32
1275 EUB : && conn->sslkey[1] != ':'
1276 : #endif
1277 : )
1278 : {
1279 : /* Colon, but not in second character, treat as engine:key */
1280 UIC 0 : char *engine_str = strdup(conn->sslkey);
1281 : char *engine_colon;
1282 :
1283 0 : if (engine_str == NULL)
1284 : {
1285 UNC 0 : libpq_append_conn_error(conn, "out of memory");
1286 UIC 0 : return -1;
1287 : }
1288 :
1289 ECB : /* cannot return NULL because we already checked before strdup */
1290 UIC 0 : engine_colon = strchr(engine_str, ':');
1291 :
1292 LBC 0 : *engine_colon = '\0'; /* engine_str now has engine name */
1293 UIC 0 : engine_colon++; /* engine_colon now has key name */
1294 :
1295 0 : conn->engine = ENGINE_by_id(engine_str);
1296 0 : if (conn->engine == NULL)
1297 : {
1298 0 : char *err = SSLerrmessage(ERR_get_error());
1299 EUB :
1300 UNC 0 : libpq_append_conn_error(conn, "could not load SSL engine \"%s\": %s",
1301 EUB : engine_str, err);
1302 UIC 0 : SSLerrfree(err);
1303 UBC 0 : free(engine_str);
1304 0 : return -1;
1305 : }
1306 :
1307 UIC 0 : if (ENGINE_init(conn->engine) == 0)
1308 EUB : {
1309 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1310 EUB :
1311 UNC 0 : libpq_append_conn_error(conn, "could not initialize SSL engine \"%s\": %s",
1312 EUB : engine_str, err);
1313 UBC 0 : SSLerrfree(err);
1314 UIC 0 : ENGINE_free(conn->engine);
1315 UBC 0 : conn->engine = NULL;
1316 UIC 0 : free(engine_str);
1317 UBC 0 : return -1;
1318 : }
1319 EUB :
1320 UBC 0 : pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1321 EUB : NULL, NULL);
1322 UIC 0 : if (pkey == NULL)
1323 : {
1324 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1325 :
1326 UNC 0 : libpq_append_conn_error(conn, "could not read private SSL key \"%s\" from engine \"%s\": %s",
1327 EUB : engine_colon, engine_str, err);
1328 UIC 0 : SSLerrfree(err);
1329 UBC 0 : ENGINE_finish(conn->engine);
1330 0 : ENGINE_free(conn->engine);
1331 0 : conn->engine = NULL;
1332 0 : free(engine_str);
1333 0 : return -1;
1334 : }
1335 UIC 0 : if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1336 EUB : {
1337 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1338 EUB :
1339 UNC 0 : libpq_append_conn_error(conn, "could not load private SSL key \"%s\" from engine \"%s\": %s",
1340 : engine_colon, engine_str, err);
1341 UBC 0 : SSLerrfree(err);
1342 UIC 0 : ENGINE_finish(conn->engine);
1343 UBC 0 : ENGINE_free(conn->engine);
1344 0 : conn->engine = NULL;
1345 0 : free(engine_str);
1346 0 : return -1;
1347 EUB : }
1348 :
1349 UIC 0 : free(engine_str);
1350 EUB :
1351 UIC 0 : fnbuf[0] = '\0'; /* indicate we're not going to load from a
1352 EUB : * file */
1353 : }
1354 : else
1355 : #endif /* USE_SSL_ENGINE */
1356 : {
1357 : /* PGSSLKEY is not an engine, treat it as a filename */
1358 GBC 38 : strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1359 EUB : }
1360 : }
1361 GBC 76 : else if (have_homedir)
1362 : {
1363 : /* No PGSSLKEY specified, load default file */
1364 8 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1365 : }
1366 EUB : else
1367 GIC 68 : fnbuf[0] = '\0';
1368 :
1369 114 : if (have_cert && fnbuf[0] != '\0')
1370 : {
1371 : /* read the client key from file */
1372 :
1373 CBC 38 : if (stat(fnbuf, &buf) != 0)
1374 : {
1375 UIC 0 : if (errno == ENOENT)
1376 UNC 0 : libpq_append_conn_error(conn, "certificate present, but not private key file \"%s\"",
1377 : fnbuf);
1378 ECB : else
1379 UNC 0 : libpq_append_conn_error(conn, "could not stat private key file \"%s\": %m",
1380 ECB : fnbuf);
1381 UIC 0 : return -1;
1382 ECB : }
1383 :
1384 : /* Key file must be a regular file */
1385 GIC 38 : if (!S_ISREG(buf.st_mode))
1386 ECB : {
1387 UNC 0 : libpq_append_conn_error(conn, "private key file \"%s\" is not a regular file",
1388 EUB : fnbuf);
1389 UIC 0 : return -1;
1390 : }
1391 EUB :
1392 : /*
1393 : * Refuse to load world-readable key files. We accept root-owned
1394 : * files with mode 0640 or less, so that we can access system-wide
1395 : * certificates if we have a supplementary group membership that
1396 : * allows us to read 'em. For files with non-root ownership, require
1397 ECB : * mode 0600 or less. We need not check the file's ownership exactly;
1398 : * if we're able to read it despite it having such restrictive
1399 EUB : * permissions, it must have the right ownership.
1400 : *
1401 : * Note: be very careful about tightening these rules. Some people
1402 : * expect, for example, that a client process running as root should
1403 : * be able to use a non-root-owned key file.
1404 : *
1405 : * Note that roughly similar checks are performed in
1406 : * src/backend/libpq/be-secure-common.c so any changes here may need
1407 : * to be made there as well. However, this code caters for the case
1408 : * of current user == root, while that code does not.
1409 : *
1410 : * Ideally we would do similar permissions checks on Windows, but it
1411 : * is not clear how that would work since Unix-style permissions may
1412 : * not be available.
1413 : */
1414 : #if !defined(WIN32) && !defined(__CYGWIN__)
1415 GIC 76 : if (buf.st_uid == 0 ?
1416 UIC 0 : buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO) :
1417 GIC 38 : buf.st_mode & (S_IRWXG | S_IRWXO))
1418 : {
1419 GNC 1 : libpq_append_conn_error(conn,
1420 : "private key file \"%s\" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root",
1421 : fnbuf);
1422 GIC 1 : return -1;
1423 : }
1424 : #endif
1425 :
1426 37 : if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1427 ECB : {
1428 GBC 3 : char *err = SSLerrmessage(ERR_get_error());
1429 ECB :
1430 : /*
1431 : * We'll try to load the file in DER (binary ASN.1) format, and if
1432 : * that fails too, report the original error. This could mask
1433 : * issues where there's something wrong with a DER-format cert,
1434 : * but we'd have to duplicate openssl's format detection to be
1435 : * smarter than this. We can't just probe for a leading -----BEGIN
1436 : * because PEM can have leading non-matching lines and blanks.
1437 : * OpenSSL doesn't expose its get_name(...) and its PEM routines
1438 : * don't differentiate between failure modes in enough detail to
1439 : * let us tell the difference between "not PEM, try DER" and
1440 : * "wrong password".
1441 : */
1442 GIC 3 : if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1443 : {
1444 GNC 1 : libpq_append_conn_error(conn, "could not load private key file \"%s\": %s",
1445 : fnbuf, err);
1446 GIC 1 : SSLerrfree(err);
1447 1 : return -1;
1448 : }
1449 :
1450 2 : SSLerrfree(err);
1451 : }
1452 : }
1453 ECB :
1454 : /* verify that the cert and key go together */
1455 CBC 148 : if (have_cert &&
1456 GIC 36 : SSL_check_private_key(conn->ssl) != 1)
1457 ECB : {
1458 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
1459 :
1460 UNC 0 : libpq_append_conn_error(conn, "certificate does not match private key file \"%s\": %s",
1461 : fnbuf, err);
1462 UIC 0 : SSLerrfree(err);
1463 0 : return -1;
1464 : }
1465 ECB :
1466 : /*
1467 : * If a root cert was loaded, also set our certificate verification
1468 EUB : * callback.
1469 : */
1470 GBC 112 : if (have_rootcert)
1471 GIC 100 : SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1472 EUB :
1473 : /*
1474 : * Set compression option if necessary.
1475 : */
1476 GIC 112 : if (conn->sslcompression && conn->sslcompression[0] == '0')
1477 112 : SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1478 : else
1479 UIC 0 : SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1480 ECB :
1481 CBC 112 : return 0;
1482 : }
1483 :
1484 : /*
1485 : * Attempt to negotiate SSL connection.
1486 ECB : */
1487 : static PostgresPollingStatusType
1488 GIC 301 : open_client_SSL(PGconn *conn)
1489 EUB : {
1490 : int r;
1491 ECB :
1492 GIC 301 : ERR_clear_error();
1493 301 : r = SSL_connect(conn->ssl);
1494 301 : if (r <= 0)
1495 : {
1496 198 : int err = SSL_get_error(conn->ssl, r);
1497 : unsigned long ecode;
1498 ECB :
1499 GIC 198 : ecode = ERR_get_error();
1500 198 : switch (err)
1501 : {
1502 CBC 189 : case SSL_ERROR_WANT_READ:
1503 189 : return PGRES_POLLING_READING;
1504 ECB :
1505 UIC 0 : case SSL_ERROR_WANT_WRITE:
1506 LBC 0 : return PGRES_POLLING_WRITING;
1507 :
1508 UIC 0 : case SSL_ERROR_SYSCALL:
1509 ECB : {
1510 : char sebuf[PG_STRERROR_R_BUFLEN];
1511 :
1512 LBC 0 : if (r == -1)
1513 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
1514 UBC 0 : SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1515 EUB : else
1516 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
1517 UIC 0 : pgtls_close(conn);
1518 0 : return PGRES_POLLING_FAILED;
1519 : }
1520 GBC 9 : case SSL_ERROR_SSL:
1521 EUB : {
1522 GBC 9 : char *err = SSLerrmessage(ecode);
1523 :
1524 GNC 9 : libpq_append_conn_error(conn, "SSL error: %s", err);
1525 GIC 9 : SSLerrfree(err);
1526 CBC 9 : switch (ERR_GET_REASON(ecode))
1527 : {
1528 ECB : /*
1529 : * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1530 : * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1531 : * when trying to communicate with an old OpenSSL
1532 : * library, or when the client and server specify
1533 : * disjoint protocol ranges.
1534 : * NO_PROTOCOLS_AVAILABLE occurs if there's a
1535 : * local misconfiguration (which can happen
1536 : * despite our checks, if openssl.cnf injects a
1537 : * limit we didn't account for). It's not very
1538 : * clear what would make OpenSSL return the other
1539 : * codes listed here, but a hint about protocol
1540 : * versions seems like it's appropriate for all.
1541 : */
1542 UIC 0 : case SSL_R_NO_PROTOCOLS_AVAILABLE:
1543 : case SSL_R_UNSUPPORTED_PROTOCOL:
1544 : case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1545 : case SSL_R_UNKNOWN_PROTOCOL:
1546 : case SSL_R_UNKNOWN_SSL_VERSION:
1547 : case SSL_R_UNSUPPORTED_SSL_VERSION:
1548 EUB : case SSL_R_WRONG_SSL_VERSION:
1549 : case SSL_R_WRONG_VERSION_NUMBER:
1550 : case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1551 : #ifdef SSL_R_VERSION_TOO_HIGH
1552 : case SSL_R_VERSION_TOO_HIGH:
1553 : case SSL_R_VERSION_TOO_LOW:
1554 : #endif
1555 UNC 0 : libpq_append_conn_error(conn, "This may indicate that the server does not support any SSL protocol version between %s and %s.",
1556 UIC 0 : conn->ssl_min_protocol_version ?
1557 : conn->ssl_min_protocol_version :
1558 : MIN_OPENSSL_TLS_VERSION,
1559 0 : conn->ssl_max_protocol_version ?
1560 EUB : conn->ssl_max_protocol_version :
1561 : MAX_OPENSSL_TLS_VERSION);
1562 UIC 0 : break;
1563 GIC 9 : default:
1564 GBC 9 : break;
1565 : }
1566 GIC 9 : pgtls_close(conn);
1567 GBC 9 : return PGRES_POLLING_FAILED;
1568 ECB : }
1569 :
1570 UIC 0 : default:
1571 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
1572 UIC 0 : pgtls_close(conn);
1573 UBC 0 : return PGRES_POLLING_FAILED;
1574 EUB : }
1575 : }
1576 :
1577 : /*
1578 : * We already checked the server certificate in initialize_SSL() using
1579 : * SSL_CTX_set_verify(), if root.crt exists.
1580 : */
1581 :
1582 : /* get server certificate */
1583 GIC 103 : conn->peer = SSL_get_peer_certificate(conn->ssl);
1584 103 : if (conn->peer == NULL)
1585 : {
1586 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
1587 ECB :
1588 UNC 0 : libpq_append_conn_error(conn, "certificate could not be obtained: %s", err);
1589 UBC 0 : SSLerrfree(err);
1590 0 : pgtls_close(conn);
1591 0 : return PGRES_POLLING_FAILED;
1592 EUB : }
1593 :
1594 GIC 103 : if (!pq_verify_peer_name_matches_certificate(conn))
1595 ECB : {
1596 GIC 13 : pgtls_close(conn);
1597 CBC 13 : return PGRES_POLLING_FAILED;
1598 ECB : }
1599 :
1600 : /* SSL handshake is complete */
1601 GIC 90 : return PGRES_POLLING_OK;
1602 ECB : }
1603 :
1604 : void
1605 GIC 18901 : pgtls_close(PGconn *conn)
1606 ECB : {
1607 GIC 18901 : bool destroy_needed = false;
1608 ECB :
1609 GIC 18901 : if (conn->ssl_in_use)
1610 ECB : {
1611 GIC 114 : if (conn->ssl)
1612 ECB : {
1613 : /*
1614 : * We can't destroy everything SSL-related here due to the
1615 : * possible later calls to OpenSSL routines which may need our
1616 : * thread callbacks, so set a flag here and check at the end.
1617 : */
1618 :
1619 GIC 114 : SSL_shutdown(conn->ssl);
1620 CBC 114 : SSL_free(conn->ssl);
1621 114 : conn->ssl = NULL;
1622 114 : conn->ssl_in_use = false;
1623 ECB :
1624 GIC 114 : destroy_needed = true;
1625 ECB : }
1626 :
1627 GIC 114 : if (conn->peer)
1628 ECB : {
1629 GIC 103 : X509_free(conn->peer);
1630 CBC 103 : conn->peer = NULL;
1631 ECB : }
1632 :
1633 : #ifdef USE_SSL_ENGINE
1634 GIC 114 : if (conn->engine)
1635 ECB : {
1636 UIC 0 : ENGINE_finish(conn->engine);
1637 UBC 0 : ENGINE_free(conn->engine);
1638 0 : conn->engine = NULL;
1639 EUB : }
1640 : #endif
1641 : }
1642 : else
1643 : {
1644 : /*
1645 : * In the non-SSL case, just remove the crypto callbacks if the
1646 : * connection has then loaded. This code path has no dependency on
1647 : * any pending SSL calls.
1648 : */
1649 GIC 18787 : if (conn->crypto_loaded)
1650 LBC 0 : destroy_needed = true;
1651 EUB : }
1652 :
1653 : /*
1654 : * This will remove our crypto locking hooks if this is the last
1655 : * connection using libcrypto which means we must wait to call it until
1656 : * after all the potential SSL calls have been made, otherwise we can end
1657 : * up with a race condition and possible deadlocks.
1658 : *
1659 : * See comments above destroy_ssl_system().
1660 : */
1661 GIC 18901 : if (destroy_needed)
1662 ECB : {
1663 GIC 114 : destroy_ssl_system();
1664 CBC 114 : conn->crypto_loaded = false;
1665 ECB : }
1666 GIC 18901 : }
1667 ECB :
1668 :
1669 : /*
1670 : * Obtain reason string for passed SSL errcode
1671 : *
1672 : * ERR_get_error() is used by caller to get errcode to pass here.
1673 : *
1674 : * Some caution is needed here since ERR_reason_error_string will
1675 : * return NULL if it doesn't recognize the error code. We don't
1676 : * want to return NULL ever.
1677 : */
1678 : static char ssl_nomem[] = "out of memory allocating error description";
1679 :
1680 : #define SSL_ERR_LEN 128
1681 :
1682 : static char *
1683 GIC 18 : SSLerrmessage(unsigned long ecode)
1684 ECB : {
1685 : const char *errreason;
1686 : char *errbuf;
1687 :
1688 GIC 18 : errbuf = malloc(SSL_ERR_LEN);
1689 CBC 18 : if (!errbuf)
1690 LBC 0 : return ssl_nomem;
1691 GBC 18 : if (ecode == 0)
1692 ECB : {
1693 UIC 0 : snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1694 UBC 0 : return errbuf;
1695 EUB : }
1696 GIC 18 : errreason = ERR_reason_error_string(ecode);
1697 CBC 18 : if (errreason != NULL)
1698 ECB : {
1699 GIC 18 : strlcpy(errbuf, errreason, SSL_ERR_LEN);
1700 CBC 18 : return errbuf;
1701 ECB : }
1702 UIC 0 : snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1703 UBC 0 : return errbuf;
1704 EUB : }
1705 :
1706 : static void
1707 GIC 18 : SSLerrfree(char *buf)
1708 ECB : {
1709 GIC 18 : if (buf != ssl_nomem)
1710 CBC 18 : free(buf);
1711 18 : }
1712 ECB :
1713 : /* ------------------------------------------------------------ */
1714 : /* SSL information functions */
1715 : /* ------------------------------------------------------------ */
1716 :
1717 : /*
1718 : * Return pointer to OpenSSL object.
1719 : */
1720 : void *
1721 UIC 0 : PQgetssl(PGconn *conn)
1722 EUB : {
1723 UIC 0 : if (!conn)
1724 UBC 0 : return NULL;
1725 0 : return conn->ssl;
1726 EUB : }
1727 :
1728 : void *
1729 UIC 0 : PQsslStruct(PGconn *conn, const char *struct_name)
1730 EUB : {
1731 UIC 0 : if (!conn)
1732 UBC 0 : return NULL;
1733 0 : if (strcmp(struct_name, "OpenSSL") == 0)
1734 0 : return conn->ssl;
1735 0 : return NULL;
1736 EUB : }
1737 :
1738 : const char *const *
1739 UIC 0 : PQsslAttributeNames(PGconn *conn)
1740 EUB : {
1741 : static const char *const openssl_attrs[] = {
1742 : "library",
1743 : "key_bits",
1744 : "cipher",
1745 : "compression",
1746 : "protocol",
1747 : NULL
1748 : };
1749 : static const char *const empty_attrs[] = {NULL};
1750 :
1751 UNC 0 : if (!conn)
1752 : {
1753 : /* Return attributes of default SSL library */
1754 0 : return openssl_attrs;
1755 : }
1756 :
1757 : /* No attrs for unencrypted connection */
1758 0 : if (conn->ssl == NULL)
1759 0 : return empty_attrs;
1760 :
1761 0 : return openssl_attrs;
1762 : }
1763 EUB :
1764 : const char *
1765 GIC 1 : PQsslAttribute(PGconn *conn, const char *attribute_name)
1766 EUB : {
1767 GIC 1 : if (!conn)
1768 : {
1769 : /* PQsslAttribute(NULL, "library") reports the default SSL library */
1770 GBC 1 : if (strcmp(attribute_name, "library") == 0)
1771 1 : return "OpenSSL";
1772 UIC 0 : return NULL;
1773 EUB : }
1774 :
1775 : /* All attributes read as NULL for a non-encrypted connection */
1776 UIC 0 : if (conn->ssl == NULL)
1777 LBC 0 : return NULL;
1778 :
1779 0 : if (strcmp(attribute_name, "library") == 0)
1780 UIC 0 : return "OpenSSL";
1781 :
1782 LBC 0 : if (strcmp(attribute_name, "key_bits") == 0)
1783 ECB : {
1784 EUB : static char sslbits_str[12];
1785 : int sslbits;
1786 :
1787 UIC 0 : SSL_get_cipher_bits(conn->ssl, &sslbits);
1788 UBC 0 : snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1789 0 : return sslbits_str;
1790 : }
1791 EUB :
1792 UBC 0 : if (strcmp(attribute_name, "cipher") == 0)
1793 UIC 0 : return SSL_get_cipher(conn->ssl);
1794 EUB :
1795 UIC 0 : if (strcmp(attribute_name, "compression") == 0)
1796 0 : return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1797 :
1798 0 : if (strcmp(attribute_name, "protocol") == 0)
1799 UBC 0 : return SSL_get_version(conn->ssl);
1800 EUB :
1801 UBC 0 : return NULL; /* unknown attribute */
1802 : }
1803 :
1804 EUB : /*
1805 : * Private substitute BIO: this does the sending and receiving using
1806 : * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1807 : * functions to disable SIGPIPE and give better error messages on I/O errors.
1808 : *
1809 : * These functions are closely modelled on the standard socket BIO in OpenSSL;
1810 : * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1811 : * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1812 : * to retry; do we need to adopt their logic for that?
1813 : */
1814 :
1815 : #ifndef HAVE_BIO_GET_DATA
1816 : #define BIO_get_data(bio) (bio->ptr)
1817 : #define BIO_set_data(bio, data) (bio->ptr = data)
1818 : #endif
1819 :
1820 : static BIO_METHOD *my_bio_methods;
1821 :
1822 : static int
1823 GIC 2815 : my_sock_read(BIO *h, char *buf, int size)
1824 : {
1825 : int res;
1826 :
1827 2815 : res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1828 2815 : BIO_clear_retry_flags(h);
1829 2815 : if (res < 0)
1830 : {
1831 : /* If we were interrupted, tell caller to retry */
1832 373 : switch (SOCK_ERRNO)
1833 : {
1834 : #ifdef EAGAIN
1835 CBC 373 : case EAGAIN:
1836 : #endif
1837 : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1838 : case EWOULDBLOCK:
1839 ECB : #endif
1840 : case EINTR:
1841 CBC 373 : BIO_set_retry_read(h);
1842 GIC 373 : break;
1843 :
1844 LBC 0 : default:
1845 UIC 0 : break;
1846 : }
1847 ECB : }
1848 :
1849 GIC 2815 : return res;
1850 : }
1851 :
1852 : static int
1853 CBC 687 : my_sock_write(BIO *h, const char *buf, int size)
1854 ECB : {
1855 : int res;
1856 EUB :
1857 GBC 687 : res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1858 GIC 687 : BIO_clear_retry_flags(h);
1859 687 : if (res < 0)
1860 : {
1861 ECB : /* If we were interrupted, tell caller to retry */
1862 UIC 0 : switch (SOCK_ERRNO)
1863 : {
1864 : #ifdef EAGAIN
1865 LBC 0 : case EAGAIN:
1866 : #endif
1867 : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1868 : case EWOULDBLOCK:
1869 ECB : #endif
1870 : case EINTR:
1871 LBC 0 : BIO_set_retry_write(h);
1872 UIC 0 : break;
1873 :
1874 UBC 0 : default:
1875 UIC 0 : break;
1876 : }
1877 EUB : }
1878 :
1879 GIC 687 : return res;
1880 : }
1881 :
1882 : static BIO_METHOD *
1883 GBC 114 : my_BIO_s_socket(void)
1884 EUB : {
1885 GIC 114 : if (!my_bio_methods)
1886 EUB : {
1887 GBC 114 : BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1888 : #ifdef HAVE_BIO_METH_NEW
1889 : int my_bio_index;
1890 :
1891 CBC 114 : my_bio_index = BIO_get_new_index();
1892 GIC 114 : if (my_bio_index == -1)
1893 UIC 0 : return NULL;
1894 GIC 114 : my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1895 CBC 114 : my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1896 GIC 114 : if (!my_bio_methods)
1897 LBC 0 : return NULL;
1898 :
1899 ECB : /*
1900 : * As of this writing, these functions never fail. But check anyway,
1901 : * like OpenSSL's own examples do.
1902 : */
1903 CBC 228 : if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1904 228 : !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1905 GBC 228 : !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1906 CBC 228 : !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1907 228 : !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1908 228 : !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1909 GBC 228 : !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1910 GIC 114 : !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1911 : {
1912 UIC 0 : BIO_meth_free(my_bio_methods);
1913 0 : my_bio_methods = NULL;
1914 0 : return NULL;
1915 ECB : }
1916 : #else
1917 : my_bio_methods = malloc(sizeof(BIO_METHOD));
1918 : if (!my_bio_methods)
1919 : return NULL;
1920 : memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1921 : my_bio_methods->bread = my_sock_read;
1922 : my_bio_methods->bwrite = my_sock_write;
1923 : #endif
1924 EUB : }
1925 GBC 114 : return my_bio_methods;
1926 EUB : }
1927 :
1928 : /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1929 : static int
1930 GIC 114 : my_SSL_set_fd(PGconn *conn, int fd)
1931 : {
1932 114 : int ret = 0;
1933 : BIO *bio;
1934 : BIO_METHOD *bio_method;
1935 :
1936 114 : bio_method = my_BIO_s_socket();
1937 CBC 114 : if (bio_method == NULL)
1938 : {
1939 UIC 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1940 0 : goto err;
1941 : }
1942 CBC 114 : bio = BIO_new(bio_method);
1943 GIC 114 : if (bio == NULL)
1944 ECB : {
1945 UIC 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1946 0 : goto err;
1947 : }
1948 CBC 114 : BIO_set_data(bio, conn);
1949 ECB :
1950 GIC 114 : SSL_set_bio(conn->ssl, bio, bio);
1951 GBC 114 : BIO_set_fd(bio, fd, BIO_NOCLOSE);
1952 114 : ret = 1;
1953 GIC 114 : err:
1954 CBC 114 : return ret;
1955 ECB : }
1956 :
1957 EUB : /*
1958 : * This is the default handler to return a client cert password from
1959 : * conn->sslpassword. Apps may install it explicitly if they want to
1960 ECB : * prevent openssl from ever prompting on stdin.
1961 : */
1962 : int
1963 CBC 2 : PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
1964 ECB : {
1965 CBC 2 : if (conn && conn->sslpassword)
1966 ECB : {
1967 GIC 2 : if (strlen(conn->sslpassword) + 1 > size)
1968 UIC 0 : fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1969 GIC 2 : strncpy(buf, conn->sslpassword, size);
1970 2 : buf[size - 1] = '\0';
1971 2 : return strlen(buf);
1972 : }
1973 : else
1974 : {
1975 LBC 0 : buf[0] = '\0';
1976 UIC 0 : return 0;
1977 ECB : }
1978 : }
1979 :
1980 EUB : PQsslKeyPassHook_OpenSSL_type
1981 LBC 0 : PQgetSSLKeyPassHook_OpenSSL(void)
1982 ECB : {
1983 LBC 0 : return PQsslKeyPassHook;
1984 : }
1985 :
1986 : void
1987 UBC 0 : PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
1988 EUB : {
1989 UIC 0 : PQsslKeyPassHook = hook;
1990 0 : }
1991 :
1992 : /*
1993 EUB : * Supply a password to decrypt a client certificate.
1994 : *
1995 : * This must match OpenSSL type pem_password_cb.
1996 : */
1997 : static int
1998 GIC 2 : PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1999 EUB : {
2000 GIC 2 : PGconn *conn = userdata;
2001 EUB :
2002 GBC 2 : if (PQsslKeyPassHook)
2003 UIC 0 : return PQsslKeyPassHook(buf, size, conn);
2004 : else
2005 GIC 2 : return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
2006 : }
2007 :
2008 : /*
2009 : * Convert TLS protocol version string to OpenSSL values
2010 ECB : *
2011 : * If a version is passed that is not supported by the current OpenSSL version,
2012 : * then we return -1. If a non-negative value is returned, subsequent code can
2013 : * assume it is working with a supported version.
2014 : *
2015 EUB : * Note: this is rather similar to the backend routine in be-secure-openssl.c,
2016 : * so make sure to update both routines if changing this one.
2017 ECB : */
2018 : static int
2019 GIC 118 : ssl_protocol_version_to_openssl(const char *protocol)
2020 : {
2021 118 : if (pg_strcasecmp("TLSv1", protocol) == 0)
2022 UIC 0 : return TLS1_VERSION;
2023 :
2024 : #ifdef TLS1_1_VERSION
2025 GIC 118 : if (pg_strcasecmp("TLSv1.1", protocol) == 0)
2026 UIC 0 : return TLS1_1_VERSION;
2027 : #endif
2028 :
2029 : #ifdef TLS1_2_VERSION
2030 GIC 118 : if (pg_strcasecmp("TLSv1.2", protocol) == 0)
2031 CBC 118 : return TLS1_2_VERSION;
2032 : #endif
2033 ECB :
2034 EUB : #ifdef TLS1_3_VERSION
2035 UIC 0 : if (pg_strcasecmp("TLSv1.3", protocol) == 0)
2036 0 : return TLS1_3_VERSION;
2037 ECB : #endif
2038 EUB :
2039 UIC 0 : return -1;
2040 : }
|