-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathfe-secure-openssl.c
More file actions
1981 lines (1746 loc) · 52.5 KB
/
fe-secure-openssl.c
File metadata and controls
1981 lines (1746 loc) · 52.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* fe-secure-openssl.c
* OpenSSL support
*
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/interfaces/libpq/fe-secure-openssl.c
*
* NOTES
*
* We don't provide informational callbacks here (like
* info_cb() in be-secure-openssl.c), since there's no good mechanism to
* display such information to the user.
*
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include "libpq-fe.h"
#include "fe-auth.h"
#include "fe-secure-common.h"
#include "libpq-int.h"
#ifdef WIN32
#include "win32.h"
#else
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#endif
#include <sys/stat.h>
#ifdef WIN32
#include "pthread-win32.h"
#else
#include <pthread.h>
#endif
/*
* These SSL-related #includes must come after all system-provided headers.
* This ensures that OpenSSL can take care of conflicts with Windows'
* <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
* include <wincrypt.h>, but some other Windows headers do.)
*/
#include "common/openssl.h"
#include <openssl/ssl.h>
#include <openssl/conf.h>
#ifdef USE_SSL_ENGINE
#include <openssl/engine.h>
#endif
#include <openssl/x509v3.h>
static int verify_cb(int ok, X509_STORE_CTX *ctx);
static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn,
ASN1_STRING *name_entry,
char **store_name);
static int openssl_verify_peer_name_matches_certificate_ip(PGconn *conn,
ASN1_OCTET_STRING *addr_entry,
char **store_name);
static int initialize_SSL(PGconn *conn);
static PostgresPollingStatusType open_client_SSL(PGconn *conn);
static char *SSLerrmessage(unsigned long ecode);
static void SSLerrfree(char *buf);
static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
static int pgconn_bio_read(BIO *h, char *buf, int size);
static int pgconn_bio_write(BIO *h, const char *buf, int size);
static BIO_METHOD *pgconn_bio_method(void);
static int ssl_set_pgconn_bio(PGconn *conn);
static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook = NULL;
static int ssl_protocol_version_to_openssl(const char *protocol);
/* ------------------------------------------------------------ */
/* Procedures common to all secure sessions */
/* ------------------------------------------------------------ */
PostgresPollingStatusType
pgtls_open_client(PGconn *conn)
{
/* First time through? */
if (conn->ssl == NULL)
{
/*
* Create a connection-specific SSL object, and load client
* certificate, private key, and trusted CA certs.
*/
if (initialize_SSL(conn) != 0)
{
/* initialize_SSL already put a message in conn->errorMessage */
pgtls_close(conn);
return PGRES_POLLING_FAILED;
}
}
/* Begin or continue the actual handshake */
return open_client_SSL(conn);
}
ssize_t
pgtls_read(PGconn *conn, void *ptr, size_t len)
{
ssize_t n;
int result_errno = 0;
char sebuf[PG_STRERROR_R_BUFLEN];
int err;
unsigned long ecode;
rloop:
/*
* Prepare to call SSL_get_error() by clearing thread's OpenSSL error
* queue. In general, the current thread's error queue must be empty
* before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
* not work reliably. Since the possibility exists that other OpenSSL
* clients running in the same thread but not under our control will fail
* to call ERR_get_error() themselves (after their own I/O operations),
* pro-actively clear the per-thread error queue now.
*/
SOCK_ERRNO_SET(0);
ERR_clear_error();
n = SSL_read(conn->ssl, ptr, len);
err = SSL_get_error(conn->ssl, n);
/*
* Other clients of OpenSSL may fail to call ERR_get_error(), but we
* always do, so as to not cause problems for OpenSSL clients that don't
* call ERR_clear_error() defensively. Be sure that this happens by
* calling now. SSL_get_error() relies on the OpenSSL per-thread error
* queue being intact, so this is the earliest possible point
* ERR_get_error() may be called.
*/
ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
switch (err)
{
case SSL_ERROR_NONE:
if (n < 0)
{
/* Not supposed to happen, so we don't translate the msg */
appendPQExpBufferStr(&conn->errorMessage,
"SSL_read failed but did not provide error information\n");
/* assume the connection is broken */
result_errno = ECONNRESET;
}
break;
case SSL_ERROR_WANT_READ:
n = 0;
break;
case SSL_ERROR_WANT_WRITE:
/*
* Returning 0 here would cause caller to wait for read-ready,
* which is not correct since what SSL wants is wait for
* write-ready. The former could get us stuck in an infinite
* wait, so don't risk it; busy-loop instead.
*/
goto rloop;
case SSL_ERROR_SYSCALL:
if (n < 0 && SOCK_ERRNO != 0)
{
result_errno = SOCK_ERRNO;
if (result_errno == EPIPE ||
result_errno == ECONNRESET)
libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
"\tThis probably means the server terminated abnormally\n"
"\tbefore or while processing the request.");
else
libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
SOCK_STRERROR(result_errno,
sebuf, sizeof(sebuf)));
}
else
{
libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
}
break;
case SSL_ERROR_SSL:
{
char *errm = SSLerrmessage(ecode);
libpq_append_conn_error(conn, "SSL error: %s", errm);
SSLerrfree(errm);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
case SSL_ERROR_ZERO_RETURN:
/*
* Per OpenSSL documentation, this error code is only returned for
* a clean connection closure, so we should not report it as a
* server crash.
*/
libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
result_errno = ECONNRESET;
n = -1;
break;
default:
libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
/* ensure we return the intended errno to caller */
SOCK_ERRNO_SET(result_errno);
return n;
}
bool
pgtls_read_pending(PGconn *conn)
{
return SSL_pending(conn->ssl) > 0;
}
ssize_t
pgtls_write(PGconn *conn, const void *ptr, size_t len)
{
ssize_t n;
int result_errno = 0;
char sebuf[PG_STRERROR_R_BUFLEN];
int err;
unsigned long ecode;
SOCK_ERRNO_SET(0);
ERR_clear_error();
n = SSL_write(conn->ssl, ptr, len);
err = SSL_get_error(conn->ssl, n);
ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
switch (err)
{
case SSL_ERROR_NONE:
if (n < 0)
{
/* Not supposed to happen, so we don't translate the msg */
appendPQExpBufferStr(&conn->errorMessage,
"SSL_write failed but did not provide error information\n");
/* assume the connection is broken */
result_errno = ECONNRESET;
}
break;
case SSL_ERROR_WANT_READ:
/*
* Returning 0 here causes caller to wait for write-ready, which
* is not really the right thing, but it's the best we can do.
*/
n = 0;
break;
case SSL_ERROR_WANT_WRITE:
n = 0;
break;
case SSL_ERROR_SYSCALL:
/*
* If errno is still zero then assume it's a read EOF situation,
* and report EOF. (This seems possible because SSL_write can
* also do reads.)
*/
if (n < 0 && SOCK_ERRNO != 0)
{
result_errno = SOCK_ERRNO;
if (result_errno == EPIPE || result_errno == ECONNRESET)
libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
"\tThis probably means the server terminated abnormally\n"
"\tbefore or while processing the request.");
else
libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
SOCK_STRERROR(result_errno,
sebuf, sizeof(sebuf)));
}
else
{
libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
}
break;
case SSL_ERROR_SSL:
{
char *errm = SSLerrmessage(ecode);
libpq_append_conn_error(conn, "SSL error: %s", errm);
SSLerrfree(errm);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
case SSL_ERROR_ZERO_RETURN:
/*
* Per OpenSSL documentation, this error code is only returned for
* a clean connection closure, so we should not report it as a
* server crash.
*/
libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
result_errno = ECONNRESET;
n = -1;
break;
default:
libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
/* assume the connection is broken */
result_errno = ECONNRESET;
n = -1;
break;
}
/* ensure we return the intended errno to caller */
SOCK_ERRNO_SET(result_errno);
return n;
}
char *
pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
{
X509 *peer_cert;
const EVP_MD *algo_type;
unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
unsigned int hash_size;
int algo_nid;
char *cert_hash;
*len = 0;
if (!conn->peer)
return NULL;
peer_cert = conn->peer;
/*
* Get the signature algorithm of the certificate to determine the hash
* algorithm to use for the result. Prefer X509_get_signature_info(),
* introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
*/
#if HAVE_X509_GET_SIGNATURE_INFO
if (!X509_get_signature_info(peer_cert, &algo_nid, NULL, NULL, NULL))
#else
if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
&algo_nid, NULL))
#endif
{
libpq_append_conn_error(conn, "could not determine server certificate signature algorithm");
return NULL;
}
/*
* The TLS server's certificate bytes need to be hashed with SHA-256 if
* its signature algorithm is MD5 or SHA-1 as per RFC 5929
* (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
* is used, the same hash as the signature algorithm is used.
*/
switch (algo_nid)
{
case NID_md5:
case NID_sha1:
algo_type = EVP_sha256();
break;
default:
algo_type = EVP_get_digestbynid(algo_nid);
if (algo_type == NULL)
{
libpq_append_conn_error(conn, "could not find digest for NID %s",
OBJ_nid2sn(algo_nid));
return NULL;
}
break;
}
if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
{
libpq_append_conn_error(conn, "could not generate peer certificate hash");
return NULL;
}
/* save result */
cert_hash = malloc(hash_size);
if (cert_hash == NULL)
{
libpq_append_conn_error(conn, "out of memory");
return NULL;
}
memcpy(cert_hash, hash, hash_size);
*len = hash_size;
return cert_hash;
}
/* ------------------------------------------------------------ */
/* OpenSSL specific code */
/* ------------------------------------------------------------ */
/*
* Certificate verification callback
*
* This callback allows us to log intermediate problems during
* verification, but there doesn't seem to be a clean way to get
* our PGconn * structure. So we can't log anything!
*
* This callback also allows us to override the default acceptance
* criteria (e.g., accepting self-signed or expired certs), but
* for now we accept the default checks.
*/
static int
verify_cb(int ok, X509_STORE_CTX *ctx)
{
return ok;
}
#ifdef HAVE_SSL_CTX_SET_CERT_CB
/*
* Certificate selection callback
*
* This callback lets us choose the client certificate we send to the server
* after seeing its CertificateRequest. We only support sending a single
* hard-coded certificate via sslcert, so we don't actually set any certificates
* here; we just use it to record whether or not the server has actually asked
* for one and whether we have one to send.
*/
static int
cert_cb(SSL *ssl, void *arg)
{
PGconn *conn = arg;
conn->ssl_cert_requested = true;
/* Do we have a certificate loaded to send back? */
if (SSL_get_certificate(ssl))
conn->ssl_cert_sent = true;
/*
* Tell OpenSSL that the callback succeeded; we're not required to
* actually make any changes to the SSL handle.
*/
return 1;
}
#endif
/*
* OpenSSL-specific wrapper around
* pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
* into a plain C string.
*/
static int
openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
char **store_name)
{
int len;
const unsigned char *namedata;
/* Should not happen... */
if (name_entry == NULL)
{
libpq_append_conn_error(conn, "SSL certificate's name entry is missing");
return -1;
}
/*
* GEN_DNS can be only IA5String, equivalent to US ASCII.
*/
namedata = ASN1_STRING_get0_data(name_entry);
len = ASN1_STRING_length(name_entry);
/* OK to cast from unsigned to plain char, since it's all ASCII. */
return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
}
/*
* OpenSSL-specific wrapper around
* pq_verify_peer_name_matches_certificate_ip(), converting the
* ASN1_OCTET_STRING into a plain C string.
*/
static int
openssl_verify_peer_name_matches_certificate_ip(PGconn *conn,
ASN1_OCTET_STRING *addr_entry,
char **store_name)
{
int len;
const unsigned char *addrdata;
/* Should not happen... */
if (addr_entry == NULL)
{
libpq_append_conn_error(conn, "SSL certificate's address entry is missing");
return -1;
}
/*
* GEN_IPADD is an OCTET STRING containing an IP address in network byte
* order.
*/
addrdata = ASN1_STRING_get0_data(addr_entry);
len = ASN1_STRING_length(addr_entry);
return pq_verify_peer_name_matches_certificate_ip(conn, addrdata, len, store_name);
}
static bool
is_ip_address(const char *host)
{
struct in_addr dummy4;
#ifdef HAVE_INET_PTON
struct in6_addr dummy6;
#endif
return inet_aton(host, &dummy4)
#ifdef HAVE_INET_PTON
|| (inet_pton(AF_INET6, host, &dummy6) == 1)
#endif
;
}
/*
* Verify that the server certificate matches the hostname we connected to.
*
* The certificate's Common Name and Subject Alternative Names are considered.
*/
int
pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
int *names_examined,
char **first_name)
{
STACK_OF(GENERAL_NAME) * peer_san;
int i;
int rc = 0;
char *host = conn->connhost[conn->whichhost].host;
int host_type;
bool check_cn = true;
Assert(host && host[0]); /* should be guaranteed by caller */
/*
* We try to match the NSS behavior here, which is a slight departure from
* the spec but seems to make more intuitive sense:
*
* If connhost contains a DNS name, and the certificate's SANs contain any
* dNSName entries, then we'll ignore the Subject Common Name entirely;
* otherwise, we fall back to checking the CN. (This behavior matches the
* RFC.)
*
* If connhost contains an IP address, and the SANs contain iPAddress
* entries, we again ignore the CN. Otherwise, we allow the CN to match,
* EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
* client MUST NOT seek a match for a reference identifier of CN-ID if the
* presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
* application-specific identifier types supported by the client.")
*
* NOTE: Prior versions of libpq did not consider iPAddress entries at
* all, so this new behavior might break a certificate that has different
* IP addresses in the Subject CN and the SANs.
*/
if (is_ip_address(host))
host_type = GEN_IPADD;
else
host_type = GEN_DNS;
/*
* First, get the Subject Alternative Names (SANs) from the certificate,
* and compare them against the originally given hostname.
*/
peer_san = (STACK_OF(GENERAL_NAME) *)
X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
if (peer_san)
{
int san_len = sk_GENERAL_NAME_num(peer_san);
for (i = 0; i < san_len; i++)
{
const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
char *alt_name = NULL;
if (name->type == host_type)
{
/*
* This SAN is of the same type (IP or DNS) as our host name,
* so don't allow a fallback check of the CN.
*/
check_cn = false;
}
if (name->type == GEN_DNS)
{
(*names_examined)++;
rc = openssl_verify_peer_name_matches_certificate_name(conn,
name->d.dNSName,
&alt_name);
}
else if (name->type == GEN_IPADD)
{
(*names_examined)++;
rc = openssl_verify_peer_name_matches_certificate_ip(conn,
name->d.iPAddress,
&alt_name);
}
if (alt_name)
{
if (!*first_name)
*first_name = alt_name;
else
free(alt_name);
}
if (rc != 0)
{
/*
* Either we hit an error or a match, and either way we should
* not fall back to the CN.
*/
check_cn = false;
break;
}
}
sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
}
/*
* If there is no subjectAltName extension of the matching type, check the
* Common Name.
*
* (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
* dNSName is present, the CN must be ignored. We break this rule if host
* is an IP address; see the comment above.)
*/
if (check_cn)
{
X509_NAME *subject_name;
subject_name = X509_get_subject_name(conn->peer);
if (subject_name != NULL)
{
int cn_index;
cn_index = X509_NAME_get_index_by_NID(subject_name,
NID_commonName, -1);
if (cn_index >= 0)
{
char *common_name = NULL;
(*names_examined)++;
rc = openssl_verify_peer_name_matches_certificate_name(conn,
X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
&common_name);
if (common_name)
{
if (!*first_name)
*first_name = common_name;
else
free(common_name);
}
}
}
}
return rc;
}
/* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
static unsigned char alpn_protos[] = PG_ALPN_PROTOCOL_VECTOR;
#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
/*
* SSL Key Logging callback
*
* This callback lets the user store all key material to a file for debugging
* purposes. The file will be written using the NSS keylog format. LibreSSL
* 3.5 introduced stub function to set the callback for OpenSSL compatibility
* but the callback is never invoked.
*
* Error messages added to the connection object won't be printed anywhere if
* the connection is successful. Errors in processing keylogging are printed
* to stderr to overcome this.
*/
static void
SSL_CTX_keylog_cb(const SSL *ssl, const char *line)
{
int fd;
ssize_t rc;
PGconn *conn = SSL_get_app_data(ssl);
if (conn == NULL)
return;
fd = open(conn->sslkeylogfile, O_WRONLY | O_APPEND | O_CREAT, 0600);
if (fd == -1)
{
fprintf(stderr, libpq_gettext("WARNING: could not open SSL key logging file \"%s\": %m\n"),
conn->sslkeylogfile);
return;
}
/* line is guaranteed by OpenSSL to be NUL terminated */
rc = write(fd, line, strlen(line));
if (rc < 0)
fprintf(stderr, libpq_gettext("WARNING: could not write to SSL key logging file \"%s\": %m\n"),
conn->sslkeylogfile);
else
rc = write(fd, "\n", 1);
(void) rc; /* silence compiler warnings */
close(fd);
}
#endif
/*
* Create per-connection SSL object, and load the client certificate,
* private key, and trusted CA certs.
*
* Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
*/
static int
initialize_SSL(PGconn *conn)
{
SSL_CTX *SSL_context;
struct stat buf;
char homedir[MAXPGPATH];
char fnbuf[MAXPGPATH];
char sebuf[PG_STRERROR_R_BUFLEN];
bool have_homedir;
bool have_cert;
bool have_rootcert;
/*
* We'll need the home directory if any of the relevant parameters are
* defaulted. If pqGetHomeDirectory fails, act as though none of the
* files could be found.
*/
if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
!(conn->sslkey && strlen(conn->sslkey) > 0) ||
!(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
!((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
(conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
else /* won't need it */
have_homedir = false;
/*
* Create a new SSL_CTX object.
*
* We used to share a single SSL_CTX between all connections, but it was
* complicated if connections used different certificates. So now we
* create a separate context for each connection, and accept the overhead.
*/
SSL_context = SSL_CTX_new(SSLv23_method());
if (!SSL_context)
{
char *err = SSLerrmessage(ERR_get_error());
libpq_append_conn_error(conn, "could not create SSL context: %s", err);
SSLerrfree(err);
return -1;
}
/*
* Delegate the client cert password prompt to the libpq wrapper callback
* if any is defined.
*
* If the application hasn't installed its own and the sslpassword
* parameter is non-null, we install ours now to make sure we supply
* PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
*
* This will replace OpenSSL's default PEM_def_callback (which prompts on
* stdin), but we're only setting it for this SSL context so it's
* harmless.
*/
if (PQsslKeyPassHook
|| (conn->sslpassword && strlen(conn->sslpassword) > 0))
{
SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
}
#ifdef HAVE_SSL_CTX_SET_CERT_CB
/* Set up a certificate selection callback. */
SSL_CTX_set_cert_cb(SSL_context, cert_cb, conn);
#endif
/* Disable old protocol versions */
SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
/* Set the minimum and maximum protocol versions if necessary */
if (conn->ssl_min_protocol_version &&
strlen(conn->ssl_min_protocol_version) != 0)
{
int ssl_min_ver;
ssl_min_ver = ssl_protocol_version_to_openssl(conn->ssl_min_protocol_version);
if (ssl_min_ver == -1)
{
libpq_append_conn_error(conn, "invalid value \"%s\" for minimum SSL protocol version",
conn->ssl_min_protocol_version);
SSL_CTX_free(SSL_context);
return -1;
}
if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
{
char *err = SSLerrmessage(ERR_get_error());
libpq_append_conn_error(conn, "could not set minimum SSL protocol version: %s", err);
SSLerrfree(err);
SSL_CTX_free(SSL_context);
return -1;
}
}
if (conn->ssl_max_protocol_version &&
strlen(conn->ssl_max_protocol_version) != 0)
{
int ssl_max_ver;
ssl_max_ver = ssl_protocol_version_to_openssl(conn->ssl_max_protocol_version);
if (ssl_max_ver == -1)
{
libpq_append_conn_error(conn, "invalid value \"%s\" for maximum SSL protocol version",
conn->ssl_max_protocol_version);
SSL_CTX_free(SSL_context);
return -1;
}
if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
{
char *err = SSLerrmessage(ERR_get_error());
libpq_append_conn_error(conn, "could not set maximum SSL protocol version: %s", err);
SSLerrfree(err);
SSL_CTX_free(SSL_context);
return -1;
}
}
/*
* Disable OpenSSL's moving-write-buffer sanity check, because it causes
* unnecessary failures in nonblocking send cases.
*/
SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
/*
* If the root cert file exists, load it so we can perform certificate
* verification. If sslmode is "verify-full" we will also do further
* verification after the connection has been completed.
*/
if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
else if (have_homedir)
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
else
fnbuf[0] = '\0';
if (strcmp(fnbuf, "system") == 0)
{
/*
* The "system" sentinel value indicates that we should load whatever
* root certificates are installed for use by OpenSSL; these locations
* differ by platform. Note that the default system locations may be
* further overridden by the SSL_CERT_DIR and SSL_CERT_FILE
* environment variables.
*/
if (SSL_CTX_set_default_verify_paths(SSL_context) != 1)
{
char *err = SSLerrmessage(ERR_get_error());
libpq_append_conn_error(conn, "could not load system root certificate paths: %s",
err);
SSLerrfree(err);
SSL_CTX_free(SSL_context);
return -1;
}
have_rootcert = true;
}
else if (fnbuf[0] != '\0' &&
stat(fnbuf, &buf) == 0)
{
X509_STORE *cvstore;
if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
{
char *err = SSLerrmessage(ERR_get_error());
libpq_append_conn_error(conn, "could not read root certificate file \"%s\": %s",
fnbuf, err);
SSLerrfree(err);
SSL_CTX_free(SSL_context);
return -1;
}
if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
{
char *fname = NULL;
char *dname = NULL;
if (conn->sslcrl && strlen(conn->sslcrl) > 0)
fname = conn->sslcrl;
if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
dname = conn->sslcrldir;
/* defaults to use the default CRL file */
if (!fname && !dname && have_homedir)
{
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
fname = fnbuf;
}
/* Set the flags to check against the complete CRL chain */
if ((fname || dname) &&
X509_STORE_load_locations(cvstore, fname, dname) == 1)
{
X509_STORE_set_flags(cvstore,
X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
}
/* if not found, silently ignore; we do not require CRL */
ERR_clear_error();
}
have_rootcert = true;
}
else
{
/*
* stat() failed; assume root file doesn't exist. If sslmode is
* verify-ca or verify-full, this is an error. Otherwise, continue
* without performing any server cert verification.
*/
if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
{
/*
* The only way to reach here with an empty filename is if
* pqGetHomeDirectory failed. That's a sufficiently unusual case
* that it seems worth having a specialized error message for it.
*/
if (fnbuf[0] == '\0')
libpq_append_conn_error(conn, "could not get home directory to locate root certificate file\n"
"Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.");
else
libpq_append_conn_error(conn, "root certificate file \"%s\" does not exist\n"
"Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.", fnbuf);
SSL_CTX_free(SSL_context);
return -1;
}
have_rootcert = false;
}
/* Read the client certificate file */
if (conn->sslcert && strlen(conn->sslcert) > 0)
strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
else if (have_homedir)
snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
else
fnbuf[0] = '\0';
if (conn->sslcertmode[0] == 'd') /* disable */
{
/* don't send a client cert even if we have one */
have_cert = false;
}
else if (fnbuf[0] == '\0')
{
/* no home directory, proceed without a client cert */
have_cert = false;
}
else if (stat(fnbuf, &buf) != 0)
{
/*
* If file is not present, just go on without a client cert; server
* might or might not accept the connection. Any other error,
* however, is grounds for complaint.
*/
if (errno != ENOENT && errno != ENOTDIR)
{
libpq_append_conn_error(conn, "could not open certificate file \"%s\": %s",
fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));