Age Owner 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 : /* ------------------------------------------------------------ */
3163 heikki.linnakangas 111 EUB :
112 : void
3163 heikki.linnakangas 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
3163 heikki.linnakangas 119 EUB : * get completely confused.
120 : */
759 michael 121 UIC 0 : if (crypto_open_connections != 0)
3163 heikki.linnakangas 122 0 : return;
3163 heikki.linnakangas 123 EUB : #endif
124 :
3163 heikki.linnakangas 125 UIC 0 : pq_init_ssl_lib = do_ssl;
126 0 : pq_init_crypto_lib = do_crypto;
127 : }
3163 heikki.linnakangas 128 ECB :
129 : PostgresPollingStatusType
3163 heikki.linnakangas 130 GIC 305 : pgtls_open_client(PGconn *conn)
3163 heikki.linnakangas 131 ECB : {
132 : /* First time through? */
3163 heikki.linnakangas 133 GIC 305 : if (conn->ssl == NULL)
134 : {
135 : /*
136 : * Create a connection-specific SSL object, and load client
2153 bruce 137 ECB : * certificate, private key, and trusted CA certs.
138 : */
3163 heikki.linnakangas 139 GIC 116 : if (initialize_SSL(conn) != 0)
3163 heikki.linnakangas 140 ECB : {
141 : /* initialize_SSL already put a message in conn->errorMessage */
3163 heikki.linnakangas 142 GIC 4 : pgtls_close(conn);
143 4 : return PGRES_POLLING_FAILED;
144 : }
145 : }
3163 heikki.linnakangas 146 ECB :
147 : /* Begin or continue the actual handshake */
3163 heikki.linnakangas 148 GIC 301 : return open_client_SSL(conn);
149 : }
3163 heikki.linnakangas 150 ECB :
151 : ssize_t
3163 heikki.linnakangas 152 GIC 365 : pgtls_read(PGconn *conn, void *ptr, size_t len)
3163 heikki.linnakangas 153 ECB : {
154 : ssize_t n;
3163 heikki.linnakangas 155 GIC 365 : int result_errno = 0;
156 : char sebuf[PG_STRERROR_R_BUFLEN];
157 : int err;
2557 peter_e 158 ECB : unsigned long ecode;
159 :
3163 heikki.linnakangas 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),
2495 rhaas 169 ECB : * pro-actively clear the per-thread error queue now.
2557 peter_e 170 : */
3163 heikki.linnakangas 171 CBC 365 : SOCK_ERRNO_SET(0);
2557 peter_e 172 365 : ERR_clear_error();
3163 heikki.linnakangas 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
2495 rhaas 182 ECB : * ERR_get_error() may be called.
2557 peter_e 183 : */
2557 peter_e 184 GIC 365 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
3163 heikki.linnakangas 185 CBC 365 : switch (err)
3163 heikki.linnakangas 186 ECB : {
3163 heikki.linnakangas 187 GIC 175 : case SSL_ERROR_NONE:
188 175 : if (n < 0)
3163 heikki.linnakangas 189 EUB : {
190 : /* Not supposed to happen, so we don't translate the msg */
818 tgl 191 UIC 0 : appendPQExpBufferStr(&conn->errorMessage,
818 tgl 192 EUB : "SSL_read failed but did not provide error information\n");
193 : /* assume the connection is broken */
3163 heikki.linnakangas 194 LBC 0 : result_errno = ECONNRESET;
3163 heikki.linnakangas 195 ECB : }
3163 heikki.linnakangas 196 CBC 175 : break;
197 184 : case SSL_ERROR_WANT_READ:
3163 heikki.linnakangas 198 GBC 184 : n = 0;
3163 heikki.linnakangas 199 GIC 184 : break;
3163 heikki.linnakangas 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
3163 heikki.linnakangas 206 EUB : * wait, so don't risk it; busy-loop instead.
207 : */
3163 heikki.linnakangas 208 UBC 0 : goto rloop;
3163 heikki.linnakangas 209 UIC 0 : case SSL_ERROR_SYSCALL:
3163 heikki.linnakangas 210 UBC 0 : if (n < 0)
3163 heikki.linnakangas 211 EUB : {
3163 heikki.linnakangas 212 UIC 0 : result_errno = SOCK_ERRNO;
3163 heikki.linnakangas 213 UBC 0 : if (result_errno == EPIPE ||
214 : result_errno == ECONNRESET)
145 peter 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,
3163 heikki.linnakangas 221 EUB : sebuf, sizeof(sebuf)));
222 : }
223 : else
224 : {
145 peter 225 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
3163 heikki.linnakangas 226 ECB : /* assume the connection is broken */
3163 heikki.linnakangas 227 UIC 0 : result_errno = ECONNRESET;
3163 heikki.linnakangas 228 LBC 0 : n = -1;
229 : }
230 0 : break;
3163 heikki.linnakangas 231 CBC 6 : case SSL_ERROR_SSL:
232 : {
2557 peter_e 233 6 : char *errm = SSLerrmessage(ecode);
3163 heikki.linnakangas 234 ECB :
145 peter 235 GNC 6 : libpq_append_conn_error(conn, "SSL error: %s", errm);
3163 heikki.linnakangas 236 GBC 6 : SSLerrfree(errm);
237 : /* assume the connection is broken */
3163 heikki.linnakangas 238 GIC 6 : result_errno = ECONNRESET;
239 6 : n = -1;
240 6 : break;
241 : }
3163 heikki.linnakangas 242 UIC 0 : case SSL_ERROR_ZERO_RETURN:
3163 heikki.linnakangas 243 EUB :
244 : /*
2878 bruce 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.
3163 heikki.linnakangas 248 : */
145 peter 249 UNC 0 : libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
3163 heikki.linnakangas 250 UBC 0 : result_errno = ECONNRESET;
251 0 : n = -1;
3163 heikki.linnakangas 252 UIC 0 : break;
253 0 : default:
145 peter 254 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
3163 heikki.linnakangas 255 ECB : /* assume the connection is broken */
3163 heikki.linnakangas 256 UIC 0 : result_errno = ECONNRESET;
257 0 : n = -1;
258 0 : break;
3163 heikki.linnakangas 259 ECB : }
260 :
261 : /* ensure we return the intended errno to caller */
3163 heikki.linnakangas 262 GIC 365 : SOCK_ERRNO_SET(result_errno);
263 :
264 365 : return n;
3163 heikki.linnakangas 265 ECB : }
266 :
267 : bool
1907 peter_e 268 CBC 478 : pgtls_read_pending(PGconn *conn)
269 : {
1427 tgl 270 GIC 478 : return SSL_pending(conn->ssl) > 0;
271 : }
272 :
3163 heikki.linnakangas 273 ECB : ssize_t
3163 heikki.linnakangas 274 CBC 256 : pgtls_write(PGconn *conn, const void *ptr, size_t len)
3163 heikki.linnakangas 275 ECB : {
276 : ssize_t n;
3163 heikki.linnakangas 277 CBC 256 : int result_errno = 0;
1656 tgl 278 ECB : char sebuf[PG_STRERROR_R_BUFLEN];
279 : int err;
2557 peter_e 280 : unsigned long ecode;
3163 heikki.linnakangas 281 :
3163 heikki.linnakangas 282 GIC 256 : SOCK_ERRNO_SET(0);
2557 peter_e 283 256 : ERR_clear_error();
3163 heikki.linnakangas 284 GBC 256 : n = SSL_write(conn->ssl, ptr, len);
3163 heikki.linnakangas 285 GIC 256 : err = SSL_get_error(conn->ssl, n);
2557 peter_e 286 256 : ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
3163 heikki.linnakangas 287 GBC 256 : switch (err)
288 : {
3163 heikki.linnakangas 289 CBC 256 : case SSL_ERROR_NONE:
3163 heikki.linnakangas 290 GBC 256 : if (n < 0)
291 : {
292 : /* Not supposed to happen, so we don't translate the msg */
818 tgl 293 UIC 0 : appendPQExpBufferStr(&conn->errorMessage,
294 : "SSL_write failed but did not provide error information\n");
295 : /* assume the connection is broken */
3163 heikki.linnakangas 296 UBC 0 : result_errno = ECONNRESET;
3163 heikki.linnakangas 297 EUB : }
3163 heikki.linnakangas 298 GBC 256 : break;
3163 heikki.linnakangas 299 UBC 0 : case SSL_ERROR_WANT_READ:
3163 heikki.linnakangas 300 EUB :
301 : /*
2878 bruce 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.
3163 heikki.linnakangas 304 : */
3163 heikki.linnakangas 305 UBC 0 : n = 0;
306 0 : break;
3163 heikki.linnakangas 307 UIC 0 : case SSL_ERROR_WANT_WRITE:
308 0 : n = 0;
309 0 : break;
3163 heikki.linnakangas 310 UBC 0 : case SSL_ERROR_SYSCALL:
3163 heikki.linnakangas 311 UIC 0 : if (n < 0)
312 : {
313 0 : result_errno = SOCK_ERRNO;
314 0 : if (result_errno == EPIPE || result_errno == ECONNRESET)
145 peter 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.");
3163 heikki.linnakangas 318 EUB : else
145 peter 319 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
3163 heikki.linnakangas 320 EUB : SOCK_STRERROR(result_errno,
321 : sebuf, sizeof(sebuf)));
322 : }
323 : else
324 : {
145 peter 325 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
3163 heikki.linnakangas 326 EUB : /* assume the connection is broken */
3163 heikki.linnakangas 327 UBC 0 : result_errno = ECONNRESET;
328 0 : n = -1;
329 : }
330 0 : break;
3163 heikki.linnakangas 331 UIC 0 : case SSL_ERROR_SSL:
332 : {
2557 peter_e 333 0 : char *errm = SSLerrmessage(ecode);
334 :
145 peter 335 UNC 0 : libpq_append_conn_error(conn, "SSL error: %s", errm);
3163 heikki.linnakangas 336 UBC 0 : SSLerrfree(errm);
3163 heikki.linnakangas 337 EUB : /* assume the connection is broken */
3163 heikki.linnakangas 338 UBC 0 : result_errno = ECONNRESET;
339 0 : n = -1;
340 0 : break;
3163 heikki.linnakangas 341 EUB : }
3163 heikki.linnakangas 342 UIC 0 : case SSL_ERROR_ZERO_RETURN:
3163 heikki.linnakangas 343 EUB :
344 : /*
2878 bruce 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 : */
145 peter 349 UNC 0 : libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
3163 heikki.linnakangas 350 LBC 0 : result_errno = ECONNRESET;
3163 heikki.linnakangas 351 UIC 0 : n = -1;
352 0 : break;
353 0 : default:
145 peter 354 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
355 : /* assume the connection is broken */
3163 heikki.linnakangas 356 UIC 0 : result_errno = ECONNRESET;
357 0 : n = -1;
358 0 : break;
359 : }
360 :
361 : /* ensure we return the intended errno to caller */
3163 heikki.linnakangas 362 CBC 256 : SOCK_ERRNO_SET(result_errno);
363 :
364 256 : return n;
3163 heikki.linnakangas 365 EUB : }
366 :
53 michael 367 ECB : #if defined(HAVE_X509_GET_SIGNATURE_NID) || defined(HAVE_X509_GET_SIGNATURE_INFO)
368 : char *
1921 peter_e 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;
1921 peter_e 375 ECB : int algo_nid;
376 : char *cert_hash;
377 :
1921 peter_e 378 GIC 5 : *len = 0;
379 :
380 5 : if (!conn->peer)
1921 peter_e 381 UBC 0 : return NULL;
1921 peter_e 382 EUB :
1921 peter_e 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
53 michael 391 CBC 5 : if (!X509_get_signature_info(peer_cert, &algo_nid, NULL, NULL, NULL))
392 : #else
1921 peter_e 393 EUB : if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
394 : &algo_nid, NULL))
53 michael 395 : #endif
1921 peter_e 396 : {
145 peter 397 UNC 0 : libpq_append_conn_error(conn, "could not determine server certificate signature algorithm");
1921 peter_e 398 LBC 0 : return NULL;
399 : }
1921 peter_e 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
1921 peter_e 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 : */
1921 peter_e 407 CBC 5 : switch (algo_nid)
408 : {
1921 peter_e 409 UBC 0 : case NID_md5:
1921 peter_e 410 EUB : case NID_sha1:
1921 peter_e 411 UIC 0 : algo_type = EVP_sha256();
412 0 : break;
1921 peter_e 413 GIC 5 : default:
1921 peter_e 414 CBC 5 : algo_type = EVP_get_digestbynid(algo_nid);
415 5 : if (algo_type == NULL)
416 : {
145 peter 417 UNC 0 : libpq_append_conn_error(conn, "could not find digest for NID %s",
418 : OBJ_nid2sn(algo_nid));
1921 peter_e 419 LBC 0 : return NULL;
1921 peter_e 420 ECB : }
1921 peter_e 421 GIC 5 : break;
1921 peter_e 422 ECB : }
423 :
1921 peter_e 424 GIC 5 : if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
425 : {
145 peter 426 UNC 0 : libpq_append_conn_error(conn, "could not generate peer certificate hash");
1921 peter_e 427 UIC 0 : return NULL;
428 : }
429 :
430 : /* save result */
1921 peter_e 431 GIC 5 : cert_hash = malloc(hash_size);
432 5 : if (cert_hash == NULL)
433 : {
145 peter 434 UNC 0 : libpq_append_conn_error(conn, "out of memory");
1921 peter_e 435 UIC 0 : return NULL;
436 : }
1921 peter_e 437 GIC 5 : memcpy(cert_hash, hash, hash_size);
438 5 : *len = hash_size;
439 :
1921 peter_e 440 CBC 5 : return cert_hash;
441 : }
1656 tgl 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
3163 heikki.linnakangas 456 : * criteria (e.g., accepting self-signed or expired certs), but
457 : * for now we accept the default checks.
458 : */
459 : static int
3163 heikki.linnakangas 460 CBC 282 : verify_cb(int ok, X509_STORE_CTX *ctx)
461 : {
3163 heikki.linnakangas 462 GIC 282 : return ok;
3163 heikki.linnakangas 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
16 michael 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.
3163 heikki.linnakangas 498 ECB : */
499 : static int
1898 peter_e 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... */
3131 heikki.linnakangas 507 34 : if (name_entry == NULL)
3131 heikki.linnakangas 508 ECB : {
145 peter 509 UNC 0 : libpq_append_conn_error(conn, "SSL certificate's name entry is missing");
3131 heikki.linnakangas 510 UIC 0 : return -1;
511 : }
512 :
513 : /*
3131 heikki.linnakangas 514 ECB : * GEN_DNS can be only IA5String, equivalent to US ASCII.
515 : */
2397 heikki.linnakangas 516 EUB : #ifdef HAVE_ASN1_STRING_GET0_DATA
2397 heikki.linnakangas 517 GBC 34 : namedata = ASN1_STRING_get0_data(name_entry);
518 : #else
519 : namedata = ASN1_STRING_data(name_entry);
520 : #endif
3131 heikki.linnakangas 521 GIC 34 : len = ASN1_STRING_length(name_entry);
522 :
523 : /* OK to cast from unsigned to plain char, since it's all ASCII. */
1898 peter_e 524 CBC 34 : return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
525 : }
526 :
527 : /*
373 peter 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
373 peter 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 :
373 peter 540 ECB : /* Should not happen... */
373 peter 541 GIC 24 : if (addr_entry == NULL)
542 : {
145 peter 543 UNC 0 : libpq_append_conn_error(conn, "SSL certificate's address entry is missing");
373 peter 544 UIC 0 : return -1;
545 : }
546 :
373 peter 547 ECB : /*
548 : * GEN_IPADD is an OCTET STRING containing an IP address in network byte
373 peter 549 EUB : * order.
550 : */
551 : #ifdef HAVE_ASN1_STRING_GET0_DATA
373 peter 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 :
373 peter 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 : {
373 peter 564 ECB : struct in_addr dummy4;
565 : #ifdef HAVE_INET_PTON
566 : struct in6_addr dummy6;
567 : #endif
568 :
373 peter 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 : }
373 peter 575 ECB :
576 : /*
3131 heikki.linnakangas 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
1898 peter_e 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;
1898 peter_e 588 CBC 36 : int rc = 0;
373 peter 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 */
373 peter 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 : */
373 peter 615 GIC 36 : if (is_ip_address(host))
616 16 : host_type = GEN_IPADD;
617 : else
618 20 : host_type = GEN_DNS;
619 :
620 : /*
3131 heikki.linnakangas 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) *)
3131 heikki.linnakangas 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 :
3131 heikki.linnakangas 631 CBC 61 : for (i = 0; i < san_len; i++)
632 : {
633 50 : const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
373 peter 634 GIC 50 : char *alt_name = NULL;
3131 heikki.linnakangas 635 ECB :
373 peter 636 GIC 50 : if (name->type == host_type)
3131 heikki.linnakangas 637 ECB : {
638 : /*
373 peter 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 : */
373 peter 642 CBC 43 : check_cn = false;
643 : }
644 :
373 peter 645 GIC 50 : if (name->type == GEN_DNS)
646 : {
1898 peter_e 647 26 : (*names_examined)++;
1898 peter_e 648 CBC 26 : rc = openssl_verify_peer_name_matches_certificate_name(conn,
1809 tgl 649 GIC 26 : name->d.dNSName,
650 : &alt_name);
373 peter 651 ECB : }
373 peter 652 GIC 24 : else if (name->type == GEN_IPADD)
373 peter 653 ECB : {
373 peter 654 CBC 24 : (*names_examined)++;
655 24 : rc = openssl_verify_peer_name_matches_certificate_ip(conn,
373 peter 656 GIC 24 : name->d.iPAddress,
657 : &alt_name);
373 peter 658 ECB : }
659 :
373 peter 660 CBC 50 : if (alt_name)
373 peter 661 ECB : {
373 peter 662 CBC 50 : if (!*first_name)
373 peter 663 GIC 29 : *first_name = alt_name;
664 : else
665 21 : free(alt_name);
3131 heikki.linnakangas 666 ECB : }
667 :
1898 peter_e 668 CBC 50 : if (rc != 0)
373 peter 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 : */
373 peter 674 CBC 18 : check_cn = false;
3131 heikki.linnakangas 675 GIC 18 : break;
676 : }
677 : }
1082 michael 678 29 : sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
679 : }
2878 bruce 680 ECB :
3131 heikki.linnakangas 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 : */
373 peter 689 GIC 36 : if (check_cn)
690 : {
691 : X509_NAME *subject_name;
692 :
3131 heikki.linnakangas 693 10 : subject_name = X509_get_subject_name(conn->peer);
694 10 : if (subject_name != NULL)
3131 heikki.linnakangas 695 ECB : {
696 : int cn_index;
697 :
3131 heikki.linnakangas 698 GIC 10 : cn_index = X509_NAME_get_index_by_NID(subject_name,
3131 heikki.linnakangas 699 ECB : NID_commonName, -1);
3131 heikki.linnakangas 700 CBC 10 : if (cn_index >= 0)
701 : {
373 peter 702 GIC 8 : char *common_name = NULL;
703 :
1898 peter_e 704 CBC 8 : (*names_examined)++;
1165 alvherre 705 GIC 8 : rc = openssl_verify_peer_name_matches_certificate_name(conn,
1165 alvherre 706 CBC 8 : X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
707 : &common_name);
373 peter 708 ECB :
373 peter 709 GIC 8 : if (common_name)
373 peter 710 ECB : {
373 peter 711 CBC 8 : if (!*first_name)
712 6 : *first_name = common_name;
713 : else
373 peter 714 GIC 2 : free(common_name);
373 peter 715 ECB : }
716 : }
3131 heikki.linnakangas 717 : }
718 : }
719 :
1898 peter_e 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
2397 heikki.linnakangas 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
759 michael 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)
3163 heikki.linnakangas 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
3163 heikki.linnakangas 794 GIC 9302 : if (pthread_mutex_lock(&ssl_config_mutex))
3163 heikki.linnakangas 795 UIC 0 : return -1;
796 :
797 : #ifdef HAVE_CRYPTO_LOCK
798 : if (pq_init_crypto_lib)
799 : {
3163 heikki.linnakangas 800 ECB : /*
3163 heikki.linnakangas 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 :
759 michael 847 GIC 9302 : if (!ssl_lib_initialized && do_ssl)
848 : {
3163 heikki.linnakangas 849 116 : if (pq_init_ssl_lib)
850 : {
851 : #ifdef HAVE_OPENSSL_INIT_SSL
2397 852 116 : OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
2397 heikki.linnakangas 853 ECB : #else
854 : OPENSSL_config(NULL);
3163 855 : SSL_library_init();
856 : SSL_load_error_strings();
857 : #endif
858 : }
2375 heikki.linnakangas 859 GIC 116 : ssl_lib_initialized = true;
860 : }
861 :
862 : #ifdef ENABLE_THREAD_SAFETY
3163 863 9302 : pthread_mutex_unlock(&ssl_config_mutex);
864 : #endif
3163 heikki.linnakangas 865 CBC 9302 : return 0;
866 : }
867 :
868 : /*
3163 heikki.linnakangas 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
3163 heikki.linnakangas 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;
3163 heikki.linnakangas 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
3163 heikki.linnakangas 913 GIC 114 : }
914 :
915 : /*
916 : * Create per-connection SSL object, and load the client certificate,
917 : * private key, and trusted CA certs.
918 : *
3163 heikki.linnakangas 919 ECB : * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
920 : */
921 : static int
3163 heikki.linnakangas 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];
1656 tgl 928 ECB : char sebuf[PG_STRERROR_R_BUFLEN];
929 : bool have_homedir;
930 : bool have_cert;
931 : bool have_rootcert;
3163 heikki.linnakangas 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.
3163 heikki.linnakangas 938 ECB : */
3163 heikki.linnakangas 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) ||
780 peter 942 108 : !((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
943 4 : (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
3163 heikki.linnakangas 944 10 : have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
2118 tgl 945 ECB : else /* won't need it */
3163 heikki.linnakangas 946 CBC 106 : have_homedir = false;
3163 heikki.linnakangas 947 ECB :
2375 948 : /*
949 : * Create a new SSL_CTX object.
950 : *
951 : * We used to share a single SSL_CTX between all connections, but it was
2153 bruce 952 : * complicated if connections used different certificates. So now we
953 : * create a separate context for each connection, and accept the overhead.
954 : */
2375 heikki.linnakangas 955 GIC 116 : SSL_context = SSL_CTX_new(SSLv23_method());
956 116 : if (!SSL_context)
957 : {
2375 heikki.linnakangas 958 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
959 :
145 peter 960 UNC 0 : libpq_append_conn_error(conn, "could not create SSL context: %s", err);
2375 heikki.linnakangas 961 UIC 0 : SSLerrfree(err);
2375 heikki.linnakangas 962 UBC 0 : return -1;
963 : }
2375 heikki.linnakangas 964 EUB :
1226 andrew 965 : /*
1060 tgl 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 : */
1226 andrew 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);
1226 andrew 981 CBC 3 : SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
1226 andrew 982 ECB : }
983 :
984 : #ifdef HAVE_SSL_CTX_SET_CERT_CB
985 : /* Set up a certificate selection callback. */
16 michael 986 GNC 116 : SSL_CTX_set_cert_cb(SSL_context, cert_cb, conn);
987 : #endif
988 :
2375 heikki.linnakangas 989 ECB : /* Disable old protocol versions */
2375 heikki.linnakangas 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 */
1074 michael 993 GIC 116 : if (conn->ssl_min_protocol_version &&
994 116 : strlen(conn->ssl_min_protocol_version) != 0)
1167 michael 995 ECB : {
996 : int ssl_min_ver;
997 :
1074 michael 998 GIC 116 : ssl_min_ver = ssl_protocol_version_to_openssl(conn->ssl_min_protocol_version);
1167 michael 999 ECB :
1167 michael 1000 GIC 116 : if (ssl_min_ver == -1)
1001 : {
145 peter 1002 UNC 0 : libpq_append_conn_error(conn, "invalid value \"%s\" for minimum SSL protocol version",
1003 : conn->ssl_min_protocol_version);
1162 tgl 1004 UIC 0 : SSL_CTX_free(SSL_context);
1167 michael 1005 0 : return -1;
1167 michael 1006 ECB : }
1007 :
1167 michael 1008 CBC 116 : if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
1009 : {
1167 michael 1010 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1011 :
145 peter 1012 UNC 0 : libpq_append_conn_error(conn, "could not set minimum SSL protocol version: %s", err);
1162 tgl 1013 UIC 0 : SSLerrfree(err);
1162 tgl 1014 LBC 0 : SSL_CTX_free(SSL_context);
1167 michael 1015 UIC 0 : return -1;
1167 michael 1016 EUB : }
1017 : }
1018 :
1074 michael 1019 GBC 116 : if (conn->ssl_max_protocol_version &&
1020 2 : strlen(conn->ssl_max_protocol_version) != 0)
1167 michael 1021 EUB : {
1022 : int ssl_max_ver;
1023 :
1074 michael 1024 GIC 2 : ssl_max_ver = ssl_protocol_version_to_openssl(conn->ssl_max_protocol_version);
1167 michael 1025 ECB :
1167 michael 1026 CBC 2 : if (ssl_max_ver == -1)
1027 : {
145 peter 1028 UNC 0 : libpq_append_conn_error(conn, "invalid value \"%s\" for maximum SSL protocol version",
1074 michael 1029 ECB : conn->ssl_max_protocol_version);
1162 tgl 1030 UIC 0 : SSL_CTX_free(SSL_context);
1167 michael 1031 LBC 0 : return -1;
1032 : }
1167 michael 1033 EUB :
1167 michael 1034 GIC 2 : if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
1167 michael 1035 EUB : {
1167 michael 1036 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1037 :
145 peter 1038 UNC 0 : libpq_append_conn_error(conn, "could not set maximum SSL protocol version: %s", err);
1162 tgl 1039 UBC 0 : SSLerrfree(err);
1162 tgl 1040 UIC 0 : SSL_CTX_free(SSL_context);
1167 michael 1041 UBC 0 : return -1;
1167 michael 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 : */
2375 heikki.linnakangas 1049 GIC 116 : SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1050 :
1051 : /*
2375 heikki.linnakangas 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 : */
2375 heikki.linnakangas 1056 GIC 116 : if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1057 116 : strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
2375 heikki.linnakangas 1058 UIC 0 : else if (have_homedir)
2375 heikki.linnakangas 1059 LBC 0 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
2375 heikki.linnakangas 1060 ECB : else
2375 heikki.linnakangas 1061 UBC 0 : fnbuf[0] = '\0';
2375 heikki.linnakangas 1062 EUB :
4 dgustafsson 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 : {
4 dgustafsson 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 : }
4 dgustafsson 1082 GNC 3 : have_rootcert = true;
1083 : }
1084 226 : else if (fnbuf[0] != '\0' &&
1085 113 : stat(fnbuf, &buf) == 0)
2375 heikki.linnakangas 1086 GIC 99 : {
2375 heikki.linnakangas 1087 ECB : X509_STORE *cvstore;
1088 :
2375 heikki.linnakangas 1089 GIC 99 : if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1090 : {
2375 heikki.linnakangas 1091 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1092 :
145 peter 1093 UNC 0 : libpq_append_conn_error(conn, "could not read root certificate file \"%s\": %s",
1094 : fnbuf, err);
2375 heikki.linnakangas 1095 LBC 0 : SSLerrfree(err);
2375 heikki.linnakangas 1096 UIC 0 : SSL_CTX_free(SSL_context);
2375 heikki.linnakangas 1097 UBC 0 : return -1;
1098 : }
2375 heikki.linnakangas 1099 EUB :
2375 heikki.linnakangas 1100 GIC 99 : if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
2375 heikki.linnakangas 1101 EUB : {
697 tgl 1102 GBC 99 : char *fname = NULL;
1103 99 : char *dname = NULL;
1104 :
2375 heikki.linnakangas 1105 CBC 99 : if (conn->sslcrl && strlen(conn->sslcrl) > 0)
780 peter 1106 GIC 97 : fname = conn->sslcrl;
780 peter 1107 CBC 99 : if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
1108 99 : dname = conn->sslcrldir;
780 peter 1109 ECB :
1110 : /* defaults to use the default CRL file */
780 peter 1111 GIC 99 : if (!fname && !dname && have_homedir)
780 peter 1112 ECB : {
2375 heikki.linnakangas 1113 UIC 0 : snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
780 peter 1114 UBC 0 : fname = fnbuf;
1115 : }
2375 heikki.linnakangas 1116 EUB :
1117 : /* Set the flags to check against the complete CRL chain */
780 peter 1118 GBC 198 : if ((fname || dname) &&
1119 99 : X509_STORE_load_locations(cvstore, fname, dname) == 1)
2375 heikki.linnakangas 1120 EUB : {
2375 heikki.linnakangas 1121 GIC 5 : X509_STORE_set_flags(cvstore,
1122 : X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2375 heikki.linnakangas 1123 ECB : }
1124 :
1125 : /* if not found, silently ignore; we do not require CRL */
2375 heikki.linnakangas 1126 CBC 99 : ERR_clear_error();
1127 : }
1128 99 : have_rootcert = true;
2375 heikki.linnakangas 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.
2375 heikki.linnakangas 1136 EUB : */
2375 heikki.linnakangas 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
2375 heikki.linnakangas 1141 ECB : * pqGetHomeDirectory failed. That's a sufficiently unusual case
1142 : * that it seems worth having a specialized error message for it.
1143 : */
2375 heikki.linnakangas 1144 CBC 2 : if (fnbuf[0] == '\0')
145 peter 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
145 peter 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);
2375 heikki.linnakangas 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 */
3163 1157 114 : if (conn->sslcert && strlen(conn->sslcert) > 0)
2997 tgl 1158 CBC 114 : strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
3163 heikki.linnakangas 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 :
16 michael 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')
3163 heikki.linnakangas 1170 ECB : {
3163 heikki.linnakangas 1171 EUB : /* no home directory, proceed without a client cert */
3163 heikki.linnakangas 1172 UIC 0 : have_cert = false;
1173 : }
3163 heikki.linnakangas 1174 CBC 111 : else if (stat(fnbuf, &buf) != 0)
1175 : {
3163 heikki.linnakangas 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 : */
3163 heikki.linnakangas 1181 GIC 73 : if (errno != ENOENT && errno != ENOTDIR)
1182 : {
145 peter 1183 UNC 0 : libpq_append_conn_error(conn, "could not open certificate file \"%s\": %s",
1656 tgl 1184 UBC 0 : fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
2375 heikki.linnakangas 1185 0 : SSL_CTX_free(SSL_context);
3163 heikki.linnakangas 1186 UIC 0 : return -1;
3163 heikki.linnakangas 1187 EUB : }
3163 heikki.linnakangas 1188 GIC 73 : have_cert = false;
3163 heikki.linnakangas 1189 ECB : }
1190 : else
1191 : {
1192 : /*
1193 : * Cert file exists, so load it. Since OpenSSL doesn't provide the
2153 bruce 1194 : * equivalent of "SSL_use_certificate_chain_file", we have to load it
1195 : * into the SSL context, rather than the SSL object.
1196 : */
3163 heikki.linnakangas 1197 GBC 38 : if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1198 : {
2557 peter_e 1199 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
1200 :
145 peter 1201 UNC 0 : libpq_append_conn_error(conn, "could not read certificate file \"%s\": %s",
1202 : fnbuf, err);
3163 heikki.linnakangas 1203 UIC 0 : SSLerrfree(err);
2375 1204 0 : SSL_CTX_free(SSL_context);
3163 heikki.linnakangas 1205 LBC 0 : return -1;
1206 : }
3163 heikki.linnakangas 1207 EUB :
1208 : /* need to load the associated private key, too */
3163 heikki.linnakangas 1209 GBC 38 : have_cert = true;
2375 heikki.linnakangas 1210 EUB : }
1211 :
2375 heikki.linnakangas 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 : */
2375 heikki.linnakangas 1219 GIC 228 : if (!(conn->ssl = SSL_new(SSL_context)) ||
1220 228 : !SSL_set_app_data(conn->ssl, conn) ||
2375 heikki.linnakangas 1221 CBC 114 : !my_SSL_set_fd(conn, conn->sock))
1222 : {
2375 heikki.linnakangas 1223 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1224 :
145 peter 1225 UNC 0 : libpq_append_conn_error(conn, "could not establish SSL connection: %s", err);
2375 heikki.linnakangas 1226 UBC 0 : SSLerrfree(err);
1227 0 : SSL_CTX_free(SSL_context);
2375 heikki.linnakangas 1228 UIC 0 : return -1;
1229 : }
2375 heikki.linnakangas 1230 GIC 114 : conn->ssl_in_use = true;
2375 heikki.linnakangas 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 : */
2375 heikki.linnakangas 1237 GIC 114 : SSL_CTX_free(SSL_context);
1238 114 : SSL_context = NULL;
1239 :
1240 : /*
732 peter 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 : */
604 dgustafsson 1245 GBC 114 : if (conn->sslsni && conn->sslsni[0] == '1')
1246 : {
670 peter 1247 114 : const char *host = conn->connhost[conn->whichhost].host;
670 peter 1248 EUB :
670 peter 1249 GBC 114 : if (host && host[0] &&
1250 114 : !(strspn(host, "0123456789.") == strlen(host) ||
670 peter 1251 GIC 104 : strchr(host, ':')))
732 peter 1252 ECB : {
670 peter 1253 GIC 97 : if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1254 : {
670 peter 1255 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
1256 :
145 peter 1257 UNC 0 : libpq_append_conn_error(conn, "could not set SSL Server Name Indication (SNI): %s", err);
670 peter 1258 LBC 0 : SSLerrfree(err);
670 peter 1259 UIC 0 : return -1;
1260 : }
1261 : }
1262 : }
1263 :
1264 : /*
3163 heikki.linnakangas 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 : */
3163 heikki.linnakangas 1270 CBC 114 : if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
3163 heikki.linnakangas 1271 ECB : {
1272 : #ifdef USE_SSL_ENGINE
3163 heikki.linnakangas 1273 CBC 38 : if (strchr(conn->sslkey, ':')
1274 : #ifdef WIN32
3163 heikki.linnakangas 1275 EUB : && conn->sslkey[1] != ':'
1276 : #endif
1277 : )
1278 : {
1279 : /* Colon, but not in second character, treat as engine:key */
3163 heikki.linnakangas 1280 UIC 0 : char *engine_str = strdup(conn->sslkey);
1281 : char *engine_colon;
1282 :
1283 0 : if (engine_str == NULL)
1284 : {
145 peter 1285 UNC 0 : libpq_append_conn_error(conn, "out of memory");
3163 heikki.linnakangas 1286 UIC 0 : return -1;
1287 : }
1288 :
3163 heikki.linnakangas 1289 ECB : /* cannot return NULL because we already checked before strdup */
3163 heikki.linnakangas 1290 UIC 0 : engine_colon = strchr(engine_str, ':');
1291 :
2118 tgl 1292 LBC 0 : *engine_colon = '\0'; /* engine_str now has engine name */
3163 heikki.linnakangas 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 : {
2557 peter_e 1298 0 : char *err = SSLerrmessage(ERR_get_error());
3163 heikki.linnakangas 1299 EUB :
145 peter 1300 UNC 0 : libpq_append_conn_error(conn, "could not load SSL engine \"%s\": %s",
3163 heikki.linnakangas 1301 EUB : engine_str, err);
3163 heikki.linnakangas 1302 UIC 0 : SSLerrfree(err);
3163 heikki.linnakangas 1303 UBC 0 : free(engine_str);
1304 0 : return -1;
1305 : }
1306 :
3163 heikki.linnakangas 1307 UIC 0 : if (ENGINE_init(conn->engine) == 0)
3163 heikki.linnakangas 1308 EUB : {
2557 peter_e 1309 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
3163 heikki.linnakangas 1310 EUB :
145 peter 1311 UNC 0 : libpq_append_conn_error(conn, "could not initialize SSL engine \"%s\": %s",
3163 heikki.linnakangas 1312 EUB : engine_str, err);
3163 heikki.linnakangas 1313 UBC 0 : SSLerrfree(err);
3163 heikki.linnakangas 1314 UIC 0 : ENGINE_free(conn->engine);
3163 heikki.linnakangas 1315 UBC 0 : conn->engine = NULL;
3163 heikki.linnakangas 1316 UIC 0 : free(engine_str);
3163 heikki.linnakangas 1317 UBC 0 : return -1;
1318 : }
3163 heikki.linnakangas 1319 EUB :
3163 heikki.linnakangas 1320 UBC 0 : pkey = ENGINE_load_private_key(conn->engine, engine_colon,
3163 heikki.linnakangas 1321 EUB : NULL, NULL);
3163 heikki.linnakangas 1322 UIC 0 : if (pkey == NULL)
1323 : {
2557 peter_e 1324 UBC 0 : char *err = SSLerrmessage(ERR_get_error());
1325 :
145 peter 1326 UNC 0 : libpq_append_conn_error(conn, "could not read private SSL key \"%s\" from engine \"%s\": %s",
3163 heikki.linnakangas 1327 EUB : engine_colon, engine_str, err);
3163 heikki.linnakangas 1328 UIC 0 : SSLerrfree(err);
3163 heikki.linnakangas 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 : }
3163 heikki.linnakangas 1335 UIC 0 : if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
3163 heikki.linnakangas 1336 EUB : {
2557 peter_e 1337 UIC 0 : char *err = SSLerrmessage(ERR_get_error());
3163 heikki.linnakangas 1338 EUB :
145 peter 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);
3163 heikki.linnakangas 1341 UBC 0 : SSLerrfree(err);
3163 heikki.linnakangas 1342 UIC 0 : ENGINE_finish(conn->engine);
3163 heikki.linnakangas 1343 UBC 0 : ENGINE_free(conn->engine);
1344 0 : conn->engine = NULL;
1345 0 : free(engine_str);
1346 0 : return -1;
3163 heikki.linnakangas 1347 EUB : }
1348 :
3163 heikki.linnakangas 1349 UIC 0 : free(engine_str);
3163 heikki.linnakangas 1350 EUB :
3163 heikki.linnakangas 1351 UIC 0 : fnbuf[0] = '\0'; /* indicate we're not going to load from a
3163 heikki.linnakangas 1352 EUB : * file */
1353 : }
1354 : else
1355 : #endif /* USE_SSL_ENGINE */
1356 : {
1357 : /* PGSSLKEY is not an engine, treat it as a filename */
2997 tgl 1358 GBC 38 : strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
3163 heikki.linnakangas 1359 EUB : }
1360 : }
3163 heikki.linnakangas 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 : }
3163 heikki.linnakangas 1366 EUB : else
3163 heikki.linnakangas 1367 GIC 68 : fnbuf[0] = '\0';
1368 :
1369 114 : if (have_cert && fnbuf[0] != '\0')
1370 : {
1371 : /* read the client key from file */
1372 :
3163 heikki.linnakangas 1373 CBC 38 : if (stat(fnbuf, &buf) != 0)
1374 : {
495 dgustafsson 1375 UIC 0 : if (errno == ENOENT)
145 peter 1376 UNC 0 : libpq_append_conn_error(conn, "certificate present, but not private key file \"%s\"",
1377 : fnbuf);
495 dgustafsson 1378 ECB : else
145 peter 1379 UNC 0 : libpq_append_conn_error(conn, "could not stat private key file \"%s\": %m",
495 dgustafsson 1380 ECB : fnbuf);
3163 heikki.linnakangas 1381 UIC 0 : return -1;
3163 heikki.linnakangas 1382 ECB : }
1383 :
1384 : /* Key file must be a regular file */
405 tgl 1385 GIC 38 : if (!S_ISREG(buf.st_mode))
405 tgl 1386 ECB : {
145 peter 1387 UNC 0 : libpq_append_conn_error(conn, "private key file \"%s\" is not a regular file",
405 tgl 1388 EUB : fnbuf);
405 tgl 1389 UIC 0 : return -1;
1390 : }
405 tgl 1391 EUB :
1392 : /*
318 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
318 tgl 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
318 tgl 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__)
318 tgl 1415 GIC 76 : if (buf.st_uid == 0 ?
318 tgl 1416 UIC 0 : buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO) :
318 tgl 1417 GIC 38 : buf.st_mode & (S_IRWXG | S_IRWXO))
1418 : {
145 peter 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);
3163 heikki.linnakangas 1422 GIC 1 : return -1;
1423 : }
1424 : #endif
1425 :
1426 37 : if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
3163 heikki.linnakangas 1427 ECB : {
2557 peter_e 1428 GBC 3 : char *err = SSLerrmessage(ERR_get_error());
3163 heikki.linnakangas 1429 ECB :
1430 : /*
1226 andrew 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,
1060 tgl 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 : */
1226 andrew 1442 GIC 3 : if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1443 : {
145 peter 1444 GNC 1 : libpq_append_conn_error(conn, "could not load private key file \"%s\": %s",
1445 : fnbuf, err);
1226 andrew 1446 GIC 1 : SSLerrfree(err);
1447 1 : return -1;
1448 : }
1449 :
3163 heikki.linnakangas 1450 2 : SSLerrfree(err);
1451 : }
1452 : }
3163 heikki.linnakangas 1453 ECB :
1454 : /* verify that the cert and key go together */
3163 heikki.linnakangas 1455 CBC 148 : if (have_cert &&
3163 heikki.linnakangas 1456 GIC 36 : SSL_check_private_key(conn->ssl) != 1)
3163 heikki.linnakangas 1457 ECB : {
2557 peter_e 1458 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
1459 :
145 peter 1460 UNC 0 : libpq_append_conn_error(conn, "certificate does not match private key file \"%s\": %s",
1461 : fnbuf, err);
3163 heikki.linnakangas 1462 UIC 0 : SSLerrfree(err);
1463 0 : return -1;
1464 : }
3163 heikki.linnakangas 1465 ECB :
1466 : /*
1467 : * If a root cert was loaded, also set our certificate verification
2153 bruce 1468 EUB : * callback.
1469 : */
2375 heikki.linnakangas 1470 GBC 112 : if (have_rootcert)
3163 heikki.linnakangas 1471 GIC 100 : SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
3163 heikki.linnakangas 1472 EUB :
760 michael 1473 : /*
1474 : * Set compression option if necessary.
1475 : */
760 michael 1476 GIC 112 : if (conn->sslcompression && conn->sslcompression[0] == '0')
1477 112 : SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1478 : else
760 michael 1479 UIC 0 : SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
3163 heikki.linnakangas 1480 ECB :
3163 heikki.linnakangas 1481 CBC 112 : return 0;
1482 : }
1483 :
1484 : /*
1485 : * Attempt to negotiate SSL connection.
3163 heikki.linnakangas 1486 ECB : */
1487 : static PostgresPollingStatusType
3163 heikki.linnakangas 1488 GIC 301 : open_client_SSL(PGconn *conn)
3163 heikki.linnakangas 1489 EUB : {
1490 : int r;
3163 heikki.linnakangas 1491 ECB :
2557 peter_e 1492 GIC 301 : ERR_clear_error();
3163 heikki.linnakangas 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;
3163 heikki.linnakangas 1498 ECB :
2557 peter_e 1499 GIC 198 : ecode = ERR_get_error();
3163 heikki.linnakangas 1500 198 : switch (err)
1501 : {
3163 heikki.linnakangas 1502 CBC 189 : case SSL_ERROR_WANT_READ:
1503 189 : return PGRES_POLLING_READING;
3163 heikki.linnakangas 1504 ECB :
3163 heikki.linnakangas 1505 UIC 0 : case SSL_ERROR_WANT_WRITE:
3163 heikki.linnakangas 1506 LBC 0 : return PGRES_POLLING_WRITING;
1507 :
3163 heikki.linnakangas 1508 UIC 0 : case SSL_ERROR_SYSCALL:
3163 heikki.linnakangas 1509 ECB : {
1656 tgl 1510 : char sebuf[PG_STRERROR_R_BUFLEN];
1511 :
3163 heikki.linnakangas 1512 LBC 0 : if (r == -1)
145 peter 1513 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
2118 tgl 1514 UBC 0 : SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3163 heikki.linnakangas 1515 EUB : else
145 peter 1516 UNC 0 : libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
3163 heikki.linnakangas 1517 UIC 0 : pgtls_close(conn);
1518 0 : return PGRES_POLLING_FAILED;
1519 : }
3163 heikki.linnakangas 1520 GBC 9 : case SSL_ERROR_SSL:
3163 heikki.linnakangas 1521 EUB : {
2557 peter_e 1522 GBC 9 : char *err = SSLerrmessage(ecode);
1523 :
145 peter 1524 GNC 9 : libpq_append_conn_error(conn, "SSL error: %s", err);
3163 heikki.linnakangas 1525 GIC 9 : SSLerrfree(err);
1016 tgl 1526 CBC 9 : switch (ERR_GET_REASON(ecode))
1527 : {
1016 tgl 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 : */
1016 tgl 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:
1016 tgl 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
145 peter 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.",
1016 tgl 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 ?
1016 tgl 1560 EUB : conn->ssl_max_protocol_version :
1561 : MAX_OPENSSL_TLS_VERSION);
1016 tgl 1562 UIC 0 : break;
1016 tgl 1563 GIC 9 : default:
1016 tgl 1564 GBC 9 : break;
1565 : }
3163 heikki.linnakangas 1566 GIC 9 : pgtls_close(conn);
3163 heikki.linnakangas 1567 GBC 9 : return PGRES_POLLING_FAILED;
3163 heikki.linnakangas 1568 ECB : }
1569 :
3163 heikki.linnakangas 1570 UIC 0 : default:
145 peter 1571 UNC 0 : libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
3163 heikki.linnakangas 1572 UIC 0 : pgtls_close(conn);
3163 heikki.linnakangas 1573 UBC 0 : return PGRES_POLLING_FAILED;
3163 heikki.linnakangas 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 */
3163 heikki.linnakangas 1583 GIC 103 : conn->peer = SSL_get_peer_certificate(conn->ssl);
1584 103 : if (conn->peer == NULL)
1585 : {
1162 tgl 1586 LBC 0 : char *err = SSLerrmessage(ERR_get_error());
3163 heikki.linnakangas 1587 ECB :
145 peter 1588 UNC 0 : libpq_append_conn_error(conn, "certificate could not be obtained: %s", err);
3163 heikki.linnakangas 1589 UBC 0 : SSLerrfree(err);
1590 0 : pgtls_close(conn);
1591 0 : return PGRES_POLLING_FAILED;
3163 heikki.linnakangas 1592 EUB : }
1593 :
1898 peter_e 1594 GIC 103 : if (!pq_verify_peer_name_matches_certificate(conn))
3163 heikki.linnakangas 1595 ECB : {
3163 heikki.linnakangas 1596 GIC 13 : pgtls_close(conn);
3163 heikki.linnakangas 1597 CBC 13 : return PGRES_POLLING_FAILED;
3163 heikki.linnakangas 1598 ECB : }
1599 :
1600 : /* SSL handshake is complete */
3163 heikki.linnakangas 1601 GIC 90 : return PGRES_POLLING_OK;
3163 heikki.linnakangas 1602 ECB : }
1603 :
1604 : void
3163 heikki.linnakangas 1605 GIC 18901 : pgtls_close(PGconn *conn)
3163 heikki.linnakangas 1606 ECB : {
3163 heikki.linnakangas 1607 GIC 18901 : bool destroy_needed = false;
3163 heikki.linnakangas 1608 ECB :
759 michael 1609 GIC 18901 : if (conn->ssl_in_use)
3163 heikki.linnakangas 1610 ECB : {
759 michael 1611 GIC 114 : if (conn->ssl)
759 michael 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 :
759 michael 1619 GIC 114 : SSL_shutdown(conn->ssl);
759 michael 1620 CBC 114 : SSL_free(conn->ssl);
1621 114 : conn->ssl = NULL;
1622 114 : conn->ssl_in_use = false;
3163 heikki.linnakangas 1623 ECB :
759 michael 1624 GIC 114 : destroy_needed = true;
759 michael 1625 ECB : }
1626 :
759 michael 1627 GIC 114 : if (conn->peer)
759 michael 1628 ECB : {
759 michael 1629 GIC 103 : X509_free(conn->peer);
759 michael 1630 CBC 103 : conn->peer = NULL;
759 michael 1631 ECB : }
1632 :
1633 : #ifdef USE_SSL_ENGINE
759 michael 1634 GIC 114 : if (conn->engine)
759 michael 1635 ECB : {
759 michael 1636 UIC 0 : ENGINE_finish(conn->engine);
759 michael 1637 UBC 0 : ENGINE_free(conn->engine);
1638 0 : conn->engine = NULL;
759 michael 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 : */
759 michael 1649 GIC 18787 : if (conn->crypto_loaded)
759 michael 1650 LBC 0 : destroy_needed = true;
3163 heikki.linnakangas 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 : */
3163 heikki.linnakangas 1661 GIC 18901 : if (destroy_needed)
759 michael 1662 ECB : {
3163 heikki.linnakangas 1663 GIC 114 : destroy_ssl_system();
759 michael 1664 CBC 114 : conn->crypto_loaded = false;
759 michael 1665 ECB : }
3163 heikki.linnakangas 1666 GIC 18901 : }
3163 heikki.linnakangas 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 *
2557 peter_e 1683 GIC 18 : SSLerrmessage(unsigned long ecode)
3163 heikki.linnakangas 1684 ECB : {
1685 : const char *errreason;
1686 : char *errbuf;
1687 :
3163 heikki.linnakangas 1688 GIC 18 : errbuf = malloc(SSL_ERR_LEN);
3163 heikki.linnakangas 1689 CBC 18 : if (!errbuf)
3163 heikki.linnakangas 1690 LBC 0 : return ssl_nomem;
2557 peter_e 1691 GBC 18 : if (ecode == 0)
3163 heikki.linnakangas 1692 ECB : {
3163 heikki.linnakangas 1693 UIC 0 : snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
3163 heikki.linnakangas 1694 UBC 0 : return errbuf;
3163 heikki.linnakangas 1695 EUB : }
2557 peter_e 1696 GIC 18 : errreason = ERR_reason_error_string(ecode);
3163 heikki.linnakangas 1697 CBC 18 : if (errreason != NULL)
3163 heikki.linnakangas 1698 ECB : {
3163 heikki.linnakangas 1699 GIC 18 : strlcpy(errbuf, errreason, SSL_ERR_LEN);
3163 heikki.linnakangas 1700 CBC 18 : return errbuf;
3163 heikki.linnakangas 1701 ECB : }
2557 peter_e 1702 UIC 0 : snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
3163 heikki.linnakangas 1703 UBC 0 : return errbuf;
3163 heikki.linnakangas 1704 EUB : }
1705 :
1706 : static void
3163 heikki.linnakangas 1707 GIC 18 : SSLerrfree(char *buf)
3163 heikki.linnakangas 1708 ECB : {
3163 heikki.linnakangas 1709 GIC 18 : if (buf != ssl_nomem)
3163 heikki.linnakangas 1710 CBC 18 : free(buf);
1711 18 : }
3163 heikki.linnakangas 1712 ECB :
1713 : /* ------------------------------------------------------------ */
1714 : /* SSL information functions */
1715 : /* ------------------------------------------------------------ */
1716 :
1717 : /*
1718 : * Return pointer to OpenSSL object.
1719 : */
1720 : void *
3163 heikki.linnakangas 1721 UIC 0 : PQgetssl(PGconn *conn)
3163 heikki.linnakangas 1722 EUB : {
3163 heikki.linnakangas 1723 UIC 0 : if (!conn)
3163 heikki.linnakangas 1724 UBC 0 : return NULL;
1725 0 : return conn->ssl;
3163 heikki.linnakangas 1726 EUB : }
1727 :
1728 : void *
2987 heikki.linnakangas 1729 UIC 0 : PQsslStruct(PGconn *conn, const char *struct_name)
2987 heikki.linnakangas 1730 EUB : {
2987 heikki.linnakangas 1731 UIC 0 : if (!conn)
2987 heikki.linnakangas 1732 UBC 0 : return NULL;
1733 0 : if (strcmp(struct_name, "OpenSSL") == 0)
1734 0 : return conn->ssl;
1735 0 : return NULL;
2987 heikki.linnakangas 1736 EUB : }
1737 :
1738 : const char *const *
2710 tgl 1739 UIC 0 : PQsslAttributeNames(PGconn *conn)
2987 heikki.linnakangas 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 :
191 tgl 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 : }
2987 heikki.linnakangas 1763 EUB :
1764 : const char *
2987 heikki.linnakangas 1765 GIC 1 : PQsslAttribute(PGconn *conn, const char *attribute_name)
2987 heikki.linnakangas 1766 EUB : {
2987 heikki.linnakangas 1767 GIC 1 : if (!conn)
1768 : {
1769 : /* PQsslAttribute(NULL, "library") reports the default SSL library */
192 tgl 1770 GBC 1 : if (strcmp(attribute_name, "library") == 0)
1771 1 : return "OpenSSL";
2987 heikki.linnakangas 1772 UIC 0 : return NULL;
192 tgl 1773 EUB : }
1774 :
1775 : /* All attributes read as NULL for a non-encrypted connection */
2987 heikki.linnakangas 1776 UIC 0 : if (conn->ssl == NULL)
2987 heikki.linnakangas 1777 LBC 0 : return NULL;
1778 :
192 tgl 1779 0 : if (strcmp(attribute_name, "library") == 0)
192 tgl 1780 UIC 0 : return "OpenSSL";
1781 :
2987 heikki.linnakangas 1782 LBC 0 : if (strcmp(attribute_name, "key_bits") == 0)
2987 heikki.linnakangas 1783 ECB : {
1851 peter_e 1784 EUB : static char sslbits_str[12];
1785 : int sslbits;
1786 :
2987 heikki.linnakangas 1787 UIC 0 : SSL_get_cipher_bits(conn->ssl, &sslbits);
2987 heikki.linnakangas 1788 UBC 0 : snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1789 0 : return sslbits_str;
1790 : }
2987 heikki.linnakangas 1791 EUB :
2987 heikki.linnakangas 1792 UBC 0 : if (strcmp(attribute_name, "cipher") == 0)
2987 heikki.linnakangas 1793 UIC 0 : return SSL_get_cipher(conn->ssl);
2987 heikki.linnakangas 1794 EUB :
2987 heikki.linnakangas 1795 UIC 0 : if (strcmp(attribute_name, "compression") == 0)
760 michael 1796 0 : return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1797 :
2987 heikki.linnakangas 1798 0 : if (strcmp(attribute_name, "protocol") == 0)
2987 heikki.linnakangas 1799 UBC 0 : return SSL_get_version(conn->ssl);
2987 heikki.linnakangas 1800 EUB :
2878 bruce 1801 UBC 0 : return NULL; /* unknown attribute */
1802 : }
1803 :
3163 heikki.linnakangas 1804 EUB : /*
2974 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.
3163 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
3163 heikki.linnakangas 1823 GIC 2815 : my_sock_read(BIO *h, char *buf, int size)
1824 : {
1825 : int res;
1826 :
2397 1827 2815 : res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
3163 1828 2815 : BIO_clear_retry_flags(h);
1829 2815 : if (res < 0)
1830 : {
1831 : /* If we were interrupted, tell caller to retry */
2750 tgl 1832 373 : switch (SOCK_ERRNO)
1833 : {
1834 : #ifdef EAGAIN
3163 heikki.linnakangas 1835 CBC 373 : case EAGAIN:
1836 : #endif
1837 : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1838 : case EWOULDBLOCK:
3163 heikki.linnakangas 1839 ECB : #endif
1840 : case EINTR:
3163 heikki.linnakangas 1841 CBC 373 : BIO_set_retry_read(h);
3163 heikki.linnakangas 1842 GIC 373 : break;
1843 :
3163 heikki.linnakangas 1844 LBC 0 : default:
3163 heikki.linnakangas 1845 UIC 0 : break;
1846 : }
3163 heikki.linnakangas 1847 ECB : }
1848 :
3163 heikki.linnakangas 1849 GIC 2815 : return res;
1850 : }
1851 :
1852 : static int
3163 heikki.linnakangas 1853 CBC 687 : my_sock_write(BIO *h, const char *buf, int size)
3163 heikki.linnakangas 1854 ECB : {
1855 : int res;
3163 heikki.linnakangas 1856 EUB :
2397 heikki.linnakangas 1857 GBC 687 : res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
3163 heikki.linnakangas 1858 GIC 687 : BIO_clear_retry_flags(h);
421 tgl 1859 687 : if (res < 0)
1860 : {
2750 tgl 1861 ECB : /* If we were interrupted, tell caller to retry */
2750 tgl 1862 UIC 0 : switch (SOCK_ERRNO)
1863 : {
1864 : #ifdef EAGAIN
2750 tgl 1865 LBC 0 : case EAGAIN:
1866 : #endif
1867 : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1868 : case EWOULDBLOCK:
2750 tgl 1869 ECB : #endif
1870 : case EINTR:
2750 tgl 1871 LBC 0 : BIO_set_retry_write(h);
2750 tgl 1872 UIC 0 : break;
1873 :
2750 tgl 1874 UBC 0 : default:
2750 tgl 1875 UIC 0 : break;
1876 : }
3163 heikki.linnakangas 1877 EUB : }
1878 :
3163 heikki.linnakangas 1879 GIC 687 : return res;
1880 : }
1881 :
1882 : static BIO_METHOD *
3163 heikki.linnakangas 1883 GBC 114 : my_BIO_s_socket(void)
3163 heikki.linnakangas 1884 EUB : {
2397 heikki.linnakangas 1885 GIC 114 : if (!my_bio_methods)
3163 heikki.linnakangas 1886 EUB : {
2397 heikki.linnakangas 1887 GBC 114 : BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1888 : #ifdef HAVE_BIO_METH_NEW
1889 : int my_bio_index;
1890 :
2397 heikki.linnakangas 1891 CBC 114 : my_bio_index = BIO_get_new_index();
2397 heikki.linnakangas 1892 GIC 114 : if (my_bio_index == -1)
2397 heikki.linnakangas 1893 UIC 0 : return NULL;
600 dgustafsson 1894 GIC 114 : my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
2397 heikki.linnakangas 1895 CBC 114 : my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
2397 heikki.linnakangas 1896 GIC 114 : if (!my_bio_methods)
2397 heikki.linnakangas 1897 LBC 0 : return NULL;
1898 :
2397 heikki.linnakangas 1899 ECB : /*
1900 : * As of this writing, these functions never fail. But check anyway,
1901 : * like OpenSSL's own examples do.
1902 : */
2397 heikki.linnakangas 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) ||
2397 heikki.linnakangas 1905 GBC 228 : !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
2397 heikki.linnakangas 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)) ||
2118 tgl 1909 GBC 228 : !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
2397 heikki.linnakangas 1910 GIC 114 : !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1911 : {
2397 heikki.linnakangas 1912 UIC 0 : BIO_meth_free(my_bio_methods);
1913 0 : my_bio_methods = NULL;
1914 0 : return NULL;
2397 heikki.linnakangas 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
3163 heikki.linnakangas 1924 EUB : }
2397 heikki.linnakangas 1925 GBC 114 : return my_bio_methods;
3163 heikki.linnakangas 1926 EUB : }
1927 :
1928 : /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1929 : static int
3163 heikki.linnakangas 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 :
2397 1936 114 : bio_method = my_BIO_s_socket();
2397 heikki.linnakangas 1937 CBC 114 : if (bio_method == NULL)
1938 : {
2397 heikki.linnakangas 1939 UIC 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1940 0 : goto err;
1941 : }
2397 heikki.linnakangas 1942 CBC 114 : bio = BIO_new(bio_method);
3163 heikki.linnakangas 1943 GIC 114 : if (bio == NULL)
3163 heikki.linnakangas 1944 ECB : {
3163 heikki.linnakangas 1945 UIC 0 : SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1946 0 : goto err;
1947 : }
2397 heikki.linnakangas 1948 CBC 114 : BIO_set_data(bio, conn);
3163 heikki.linnakangas 1949 ECB :
3163 heikki.linnakangas 1950 GIC 114 : SSL_set_bio(conn->ssl, bio, bio);
3163 heikki.linnakangas 1951 GBC 114 : BIO_set_fd(bio, fd, BIO_NOCLOSE);
1952 114 : ret = 1;
3163 heikki.linnakangas 1953 GIC 114 : err:
3163 heikki.linnakangas 1954 CBC 114 : return ret;
3163 heikki.linnakangas 1955 ECB : }
1956 :
1226 andrew 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
1226 andrew 1960 ECB : * prevent openssl from ever prompting on stdin.
1961 : */
1962 : int
1058 andrew 1963 CBC 2 : PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
1226 andrew 1964 ECB : {
237 tgl 1965 CBC 2 : if (conn && conn->sslpassword)
1226 andrew 1966 ECB : {
1226 andrew 1967 GIC 2 : if (strlen(conn->sslpassword) + 1 > size)
1071 peter 1968 UIC 0 : fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1226 andrew 1969 GIC 2 : strncpy(buf, conn->sslpassword, size);
1060 tgl 1970 2 : buf[size - 1] = '\0';
1226 andrew 1971 2 : return strlen(buf);
1972 : }
1973 : else
1974 : {
1226 andrew 1975 LBC 0 : buf[0] = '\0';
1226 andrew 1976 UIC 0 : return 0;
1226 andrew 1977 ECB : }
1978 : }
1979 :
1058 andrew 1980 EUB : PQsslKeyPassHook_OpenSSL_type
1058 tgl 1981 LBC 0 : PQgetSSLKeyPassHook_OpenSSL(void)
1226 andrew 1982 ECB : {
1226 andrew 1983 LBC 0 : return PQsslKeyPassHook;
1984 : }
1985 :
1986 : void
1058 andrew 1987 UBC 0 : PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
1226 andrew 1988 EUB : {
1226 andrew 1989 UIC 0 : PQsslKeyPassHook = hook;
1990 0 : }
1991 :
1992 : /*
1226 andrew 1993 EUB : * Supply a password to decrypt a client certificate.
1994 : *
1060 heikki.linnakangas 1995 : * This must match OpenSSL type pem_password_cb.
1996 : */
1997 : static int
1226 andrew 1998 GIC 2 : PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1226 andrew 1999 EUB : {
1060 tgl 2000 GIC 2 : PGconn *conn = userdata;
1226 andrew 2001 EUB :
1226 andrew 2002 GBC 2 : if (PQsslKeyPassHook)
1226 andrew 2003 UIC 0 : return PQsslKeyPassHook(buf, size, conn);
2004 : else
1058 andrew 2005 GIC 2 : return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
2006 : }
2007 :
2008 : /*
2009 : * Convert TLS protocol version string to OpenSSL values
1167 michael 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 : *
1167 michael 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.
1167 michael 2017 ECB : */
2018 : static int
1167 michael 2019 GIC 118 : ssl_protocol_version_to_openssl(const char *protocol)
2020 : {
2021 118 : if (pg_strcasecmp("TLSv1", protocol) == 0)
1167 michael 2022 UIC 0 : return TLS1_VERSION;
2023 :
2024 : #ifdef TLS1_1_VERSION
1167 michael 2025 GIC 118 : if (pg_strcasecmp("TLSv1.1", protocol) == 0)
1167 michael 2026 UIC 0 : return TLS1_1_VERSION;
2027 : #endif
2028 :
2029 : #ifdef TLS1_2_VERSION
1167 michael 2030 GIC 118 : if (pg_strcasecmp("TLSv1.2", protocol) == 0)
1167 michael 2031 CBC 118 : return TLS1_2_VERSION;
2032 : #endif
1167 michael 2033 ECB :
1167 michael 2034 EUB : #ifdef TLS1_3_VERSION
1167 michael 2035 UIC 0 : if (pg_strcasecmp("TLSv1.3", protocol) == 0)
2036 0 : return TLS1_3_VERSION;
1167 michael 2037 ECB : #endif
1167 michael 2038 EUB :
1167 michael 2039 UIC 0 : return -1;
2040 : }
|