-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathbe-secure-openssl.c
More file actions
2506 lines (2245 loc) · 66.8 KB
/
be-secure-openssl.c
File metadata and controls
2506 lines (2245 loc) · 66.8 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
/*-------------------------------------------------------------------------
*
* be-secure-openssl.c
* functions for OpenSSL support in the backend.
*
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/libpq/be-secure-openssl.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include "common/hashfn.h"
#include "common/string.h"
#include "libpq/libpq.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/latch.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/wait_event.h"
/*
* 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/bn.h>
#include <openssl/conf.h>
#include <openssl/dh.h>
#ifndef OPENSSL_NO_ECDH
#include <openssl/ec.h>
#endif
#include <openssl/x509v3.h>
/*
* Simplehash for tracking configured hostnames to guard against duplicate
* entries. Each list of hosts is traversed and added to the hash during
* parsing and if a duplicate error is detected an error will be thrown.
*/
typedef struct
{
uint32 status;
const char *hostname;
} HostCacheEntry;
static uint32 host_cache_pointer(const char *key);
#define SH_PREFIX host_cache
#define SH_ELEMENT_TYPE HostCacheEntry
#define SH_KEY_TYPE const char *
#define SH_KEY hostname
#define SH_HASH_KEY(tb, key) host_cache_pointer(key)
#define SH_EQUAL(tb, a, b) (pg_strcasecmp(a, b) == 0)
#define SH_SCOPE static inline
#define SH_DECLARE
#define SH_DEFINE
#include "lib/simplehash.h"
/* default init hook can be overridden by a shared library */
static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart);
openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init;
static int port_bio_read(BIO *h, char *buf, int size);
static int port_bio_write(BIO *h, const char *buf, int size);
static BIO_METHOD *port_bio_method(void);
static int ssl_set_port_bio(Port *port);
static DH *load_dh_file(char *filename, bool isServerStart);
static DH *load_dh_buffer(const char *buffer, size_t len);
static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata);
static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
static int verify_cb(int ok, X509_STORE_CTX *ctx);
static void info_cb(const SSL *ssl, int type, int args);
static int alpn_cb(SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *userdata);
static bool initialize_dh(SSL_CTX *context, bool isServerStart);
static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
static const char *SSLerrmessageExt(unsigned long ecode, const char *replacement);
static const char *SSLerrmessage(unsigned long ecode);
static bool init_host_context(HostsLine *host, bool isServerStart);
static void host_context_cleanup_cb(void *arg);
#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
static int sni_clienthello_cb(SSL *ssl, int *al, void *arg);
#endif
static char *X509_NAME_to_cstring(X509_NAME *name);
static SSL_CTX *SSL_context = NULL;
static MemoryContext SSL_hosts_memcxt = NULL;
static struct hosts
{
/*
* List of HostsLine structures containing SSL configurations for
* connections with hostnames defined in the SNI extension.
*/
List *sni;
/* The SSL configuration to use for connections without SNI */
HostsLine *no_sni;
/*
* The default SSL configuration to use as a fallback in case no hostname
* matches the supplied hostname in the SNI extension.
*/
HostsLine *default_host;
} *SSL_hosts;
static bool dummy_ssl_passwd_cb_called = false;
static bool ssl_is_server_start;
static int ssl_protocol_version_to_openssl(int v);
static const char *ssl_protocol_version_to_string(int v);
struct CallbackErr
{
/*
* Storage for passing certificate verification error logging from the
* callback.
*/
char *cert_errdetail;
};
/* ------------------------------------------------------------ */
/* Public interface */
/* ------------------------------------------------------------ */
int
be_tls_init(bool isServerStart)
{
List *pg_hosts = NIL;
ListCell *line;
MemoryContext oldcxt;
MemoryContext host_memcxt = NULL;
MemoryContextCallback *host_memcxt_cb;
char *err_msg = NULL;
int res;
struct hosts *new_hosts;
SSL_CTX *context = NULL;
int ssl_ver_min = -1;
int ssl_ver_max = -1;
host_cache_hash *host_cache = NULL;
/*
* Since we don't know which host we're using until the ClientHello is
* sent, ssl_loaded_verify_locations *always* starts out as false. The
* only place it's set to true is in sni_clienthello_cb().
*/
ssl_loaded_verify_locations = false;
host_memcxt = AllocSetContextCreate(CurrentMemoryContext,
"hosts file parser context",
ALLOCSET_SMALL_SIZES);
oldcxt = MemoryContextSwitchTo(host_memcxt);
/* Allocate a tentative replacement for SSL_hosts. */
new_hosts = palloc0_object(struct hosts);
/*
* Register a reset callback for the memory context which is responsible
* for freeing OpenSSL managed allocations upon context deletion. The
* callback is allocated here to make sure it gets cleaned up along with
* the memory context it's registered for.
*/
host_memcxt_cb = palloc0_object(MemoryContextCallback);
host_memcxt_cb->func = host_context_cleanup_cb;
host_memcxt_cb->arg = new_hosts;
MemoryContextRegisterResetCallback(host_memcxt, host_memcxt_cb);
/*
* If ssl_sni is enabled, attempt to load and parse TLS configuration from
* the pg_hosts.conf file with the set of hosts returned as a list. If
* there are hosts configured they take precedence over the configuration
* in postgresql.conf. Make sure to allocate the parsed rows in their own
* memory context so that we can delete them easily in case parsing fails.
* If ssl_sni is disabled then set the state accordingly to make sure we
* instead parse the config from postgresql.conf.
*
* The reason for not doing everything in this if-else conditional is that
* we want to use the same processing of postgresql.conf for when ssl_sni
* is off as well as when it's on but the hostsfile is missing etc. Thus
* we set res to the state and continue with a new conditional instead of
* duplicating logic and risk it diverging over time.
*/
if (ssl_sni)
{
/*
* The GUC check hook should have already blocked this but to be on
* the safe side we doublecheck here.
*/
#ifndef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("ssl_sni is not supported with LibreSSL"));
goto error;
#endif
/* Attempt to load configuration from pg_hosts.conf */
res = load_hosts(&pg_hosts, &err_msg);
/*
* pg_hosts.conf is not required to contain configuration, but if it
* does we error out in case it fails to load rather than continue to
* try the postgresql.conf configuration to avoid silently falling
* back on an undesired configuration.
*/
if (res == HOSTSFILE_LOAD_FAILED)
{
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load \"%s\": %s", "pg_hosts.conf",
err_msg ? err_msg : "unknown error"));
goto error;
}
}
else
res = HOSTSFILE_DISABLED;
/*
* Loading and parsing the hosts file was successful, create configs for
* each host entry and add to the list of hosts to be checked during
* login.
*/
if (res == HOSTSFILE_LOAD_OK)
{
Assert(ssl_sni);
foreach(line, pg_hosts)
{
HostsLine *host = lfirst(line);
if (!init_host_context(host, isServerStart))
goto error;
/*
* The hostname in the config will be set to NULL for the default
* host as well as in configs used for non-SNI connections. Lists
* of hostnames in pg_hosts.conf are not allowed to contain the
* default '*' entry or a '/no_sni/' entry and this is checked
* during parsing. Thus we can inspect the head of the hostnames
* list for these since they will never be anywhere else.
*/
if (strcmp(linitial(host->hostnames), "*") == 0)
{
if (new_hosts->default_host)
{
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("multiple default hosts specified"),
errcontext("line %d of configuration file \"%s\"",
host->linenumber, host->sourcefile));
goto error;
}
new_hosts->default_host = host;
}
else if (strcmp(linitial(host->hostnames), "/no_sni/") == 0)
{
if (new_hosts->no_sni)
{
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("multiple no_sni hosts specified"),
errcontext("line %d of configuration file \"%s\"",
host->linenumber, host->sourcefile));
goto error;
}
new_hosts->no_sni = host;
}
else
{
/* Check the hostnames for duplicates */
if (!host_cache)
host_cache = host_cache_create(host_memcxt, 32, NULL);
foreach_ptr(char, hostname, host->hostnames)
{
HostCacheEntry *entry;
bool found;
entry = host_cache_insert(host_cache, hostname, &found);
if (found)
{
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("multiple entries for host \"%s\" specified",
hostname),
errcontext("line %d of configuration file \"%s\"",
host->linenumber, host->sourcefile));
goto error;
}
else
entry->hostname = pstrdup(hostname);
}
/*
* At this point we know we have a configuration with a list
* of distinct 1..n hostnames for literal string matching with
* the SNI extension from the user.
*/
new_hosts->sni = lappend(new_hosts->sni, host);
}
}
}
/*
* If SNI is disabled, then we load configuration from postgresql.conf. If
* SNI is enabled but the pg_hosts.conf file doesn't exist, or is empty,
* then we also load the config from postgresql.conf.
*/
else if (res == HOSTSFILE_DISABLED || res == HOSTSFILE_EMPTY || res == HOSTSFILE_MISSING)
{
HostsLine *pgconf = palloc0(sizeof(HostsLine));
#ifdef USE_ASSERT_CHECKING
if (res == HOSTSFILE_DISABLED)
Assert(ssl_sni == false);
#endif
pgconf->ssl_cert = ssl_cert_file;
pgconf->ssl_key = ssl_key_file;
pgconf->ssl_ca = ssl_ca_file;
pgconf->ssl_passphrase_cmd = ssl_passphrase_command;
pgconf->ssl_passphrase_reload = ssl_passphrase_command_supports_reload;
if (!init_host_context(pgconf, isServerStart))
goto error;
/*
* If postgresql.conf is used to configure SSL then by definition it
* will be the default context as we don't have per-host config.
*/
new_hosts->default_host = pgconf;
}
/*
* Make sure we have at least one configuration loaded to use, without
* that we cannot drive a connection so exit.
*/
if (new_hosts->sni == NIL && !new_hosts->default_host && !new_hosts->no_sni)
{
ereport(isServerStart ? FATAL : LOG,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("no SSL configurations loaded"),
/*- translator: The two %s contain filenames */
errhint("If ssl_sni is enabled then add configuration to \"%s\", else \"%s\"",
"pg_hosts.conf", "postgresql.conf"));
goto error;
}
#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
/*
* Create a new SSL context into which we'll load all the configuration
* settings. If we fail partway through, we can avoid memory leakage by
* freeing this context; we don't install it as active until the end.
*
* We use SSLv23_method() because it can negotiate use of the highest
* mutually supported protocol version, while alternatives like
* TLSv1_2_method() permit only one specific version. Note that we don't
* actually allow SSL v2 or v3, only TLS protocols (see below).
*/
context = SSL_CTX_new(SSLv23_method());
if (!context)
{
ereport(isServerStart ? FATAL : LOG,
(errmsg("could not create SSL context: %s",
SSLerrmessage(ERR_get_error()))));
goto error;
}
#else
/*
* If the client hello callback isn't supported we want to use the default
* context as the one to drive the handshake so avoid creating a new one
* and use the already existing default one instead.
*/
context = new_hosts->default_host->ssl_ctx;
/*
* Since we don't allocate a new SSL_CTX here like we do when SNI has been
* enabled we need to bump the reference count on context to avoid double
* free of the context when using the same cleanup logic across the cases.
*/
SSL_CTX_up_ref(context);
#endif
/*
* Disable OpenSSL's moving-write-buffer sanity check, because it causes
* unnecessary failures in nonblocking send cases.
*/
SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
if (ssl_min_protocol_version)
{
ssl_ver_min = ssl_protocol_version_to_openssl(ssl_min_protocol_version);
if (ssl_ver_min == -1)
{
ereport(isServerStart ? FATAL : LOG,
/*- translator: first %s is a GUC option name, second %s is its value */
(errmsg("\"%s\" setting \"%s\" not supported by this build",
"ssl_min_protocol_version",
GetConfigOption("ssl_min_protocol_version",
false, false))));
goto error;
}
if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
{
ereport(isServerStart ? FATAL : LOG,
(errmsg("could not set minimum SSL protocol version")));
goto error;
}
}
if (ssl_max_protocol_version)
{
ssl_ver_max = ssl_protocol_version_to_openssl(ssl_max_protocol_version);
if (ssl_ver_max == -1)
{
ereport(isServerStart ? FATAL : LOG,
/*- translator: first %s is a GUC option name, second %s is its value */
(errmsg("\"%s\" setting \"%s\" not supported by this build",
"ssl_max_protocol_version",
GetConfigOption("ssl_max_protocol_version",
false, false))));
goto error;
}
if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
{
ereport(isServerStart ? FATAL : LOG,
(errmsg("could not set maximum SSL protocol version")));
goto error;
}
}
/* Check compatibility of min/max protocols */
if (ssl_min_protocol_version &&
ssl_max_protocol_version)
{
/*
* No need to check for invalid values (-1) for each protocol number
* as the code above would have already generated an error.
*/
if (ssl_ver_min > ssl_ver_max)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not set SSL protocol version range"),
errdetail("\"%s\" cannot be higher than \"%s\"",
"ssl_min_protocol_version",
"ssl_max_protocol_version")));
goto error;
}
}
/*
* Disallow SSL session tickets. OpenSSL use both stateful and stateless
* tickets for TLSv1.3, and stateless ticket for TLSv1.2. SSL_OP_NO_TICKET
* is available since 0.9.8f but only turns off stateless tickets. In
* order to turn off stateful tickets we need SSL_CTX_set_num_tickets,
* which is available since OpenSSL 1.1.1. LibreSSL 3.5.4 (from OpenBSD
* 7.1) introduced this API for compatibility, but doesn't support session
* tickets at all so it's a no-op there.
*/
#ifdef HAVE_SSL_CTX_SET_NUM_TICKETS
SSL_CTX_set_num_tickets(context, 0);
#endif
SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
/* disallow SSL session caching, too */
SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
/* disallow SSL compression */
SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
/*
* Disallow SSL renegotiation. This concerns only TLSv1.2 and older
* protocol versions, as TLSv1.3 has no support for renegotiation.
* SSL_OP_NO_RENEGOTIATION is available in OpenSSL since 1.1.0h (via a
* backport from 1.1.1). SSL_OP_NO_CLIENT_RENEGOTIATION is available in
* LibreSSL since 2.5.1 disallowing all client-initiated renegotiation
* (this is usually on by default).
*/
#ifdef SSL_OP_NO_RENEGOTIATION
SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
#endif
#ifdef SSL_OP_NO_CLIENT_RENEGOTIATION
SSL_CTX_set_options(context, SSL_OP_NO_CLIENT_RENEGOTIATION);
#endif
/* set up ephemeral DH and ECDH keys */
if (!initialize_dh(context, isServerStart))
goto error;
if (!initialize_ecdh(context, isServerStart))
goto error;
/* set up the allowed cipher list for TLSv1.2 and below */
if (SSL_CTX_set_cipher_list(context, SSLCipherList) != 1)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not set the TLSv1.2 cipher list (no valid ciphers available)")));
goto error;
}
/*
* Set up the allowed cipher suites for TLSv1.3. If the GUC is an empty
* string we leave the allowed suites to be the OpenSSL default value.
*/
if (SSLCipherSuites[0])
{
/* set up the allowed cipher suites */
if (SSL_CTX_set_ciphersuites(context, SSLCipherSuites) != 1)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not set the TLSv1.3 cipher suites (no valid ciphers available)")));
goto error;
}
}
/* Let server choose order */
if (SSLPreferServerCiphers)
SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
/*
* Success! Replace any existing SSL_context and host configurations.
*/
if (SSL_context)
{
SSL_CTX_free(SSL_context);
SSL_context = NULL;
}
MemoryContextSwitchTo(oldcxt);
if (SSL_hosts_memcxt)
MemoryContextDelete(SSL_hosts_memcxt);
SSL_hosts_memcxt = host_memcxt;
SSL_hosts = new_hosts;
SSL_context = context;
return 0;
/*
* Clean up by releasing working SSL contexts as well as allocations
* performed during parsing. Since all our allocations are done in a
* local memory context all we need to do is delete it.
*/
error:
if (context)
SSL_CTX_free(context);
MemoryContextSwitchTo(oldcxt);
MemoryContextDelete(host_memcxt);
return -1;
}
/*
* host_context_cleanup_cb
*
* Memory context reset callback for clearing OpenSSL managed resources when
* hosts are reloaded and the previous set of configured hosts are freed. As
* all hosts are allocated in a single context we don't need to free each host
* individually, just resources managed by OpenSSL.
*/
static void
host_context_cleanup_cb(void *arg)
{
struct hosts *hosts = arg;
foreach_ptr(HostsLine, host, hosts->sni)
{
if (host->ssl_ctx != NULL)
SSL_CTX_free(host->ssl_ctx);
}
if (hosts->no_sni && hosts->no_sni->ssl_ctx)
SSL_CTX_free(hosts->no_sni->ssl_ctx);
if (hosts->default_host && hosts->default_host->ssl_ctx)
SSL_CTX_free(hosts->default_host->ssl_ctx);
}
static bool
init_host_context(HostsLine *host, bool isServerStart)
{
SSL_CTX *ctx = SSL_CTX_new(SSLv23_method());
static bool init_warned = false;
if (!ctx)
{
ereport(isServerStart ? FATAL : LOG,
(errmsg("could not create SSL context: %s",
SSLerrmessage(ERR_get_error()))));
goto error;
}
/*
* Call init hook (usually to set password callback) in case SNI hasn't
* been enabled. If SNI is enabled the hook won't operate on the actual
* TLS context used so it cannot function properly; we warn if one has
* been installed.
*
* If SNI is enabled, we set password callback based what was configured.
*/
if (!ssl_sni)
(*openssl_tls_init_hook) (ctx, isServerStart);
else
{
if (openssl_tls_init_hook != default_openssl_tls_init && !init_warned)
{
ereport(WARNING,
errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("SNI is enabled; installed TLS init hook will be ignored"),
/*- translator: first %s is a GUC, second %s contains a filename */
errhint("TLS init hooks are incompatible with SNI. "
"Set \"%s\" to \"off\" to make use of the hook "
"that is currently installed, or remove the hook "
"and use per-host passphrase commands in \"%s\".",
"ssl_sni", "pg_hosts.conf"));
init_warned = true;
}
/*
* Set up the password callback, if configured.
*/
if (isServerStart)
{
if (host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0])
{
SSL_CTX_set_default_passwd_cb(ctx, ssl_external_passwd_cb);
SSL_CTX_set_default_passwd_cb_userdata(ctx, host->ssl_passphrase_cmd);
}
}
else
{
/*
* If ssl_passphrase_reload is true then ssl_passphrase_cmd cannot
* be NULL due to their parsing order, but just in case and to
* self-document the code we replicate the nullness checks.
*/
if (host->ssl_passphrase_reload &&
(host->ssl_passphrase_cmd && host->ssl_passphrase_cmd[0]))
{
SSL_CTX_set_default_passwd_cb(ctx, ssl_external_passwd_cb);
SSL_CTX_set_default_passwd_cb_userdata(ctx, host->ssl_passphrase_cmd);
}
else
{
/*
* If reloading and no external command is configured,
* override OpenSSL's default handling of passphrase-protected
* files, because we don't want to prompt for a passphrase in
* an already-running server.
*/
SSL_CTX_set_default_passwd_cb(ctx, dummy_ssl_passwd_cb);
}
}
}
/*
* Load and verify server's certificate and private key
*/
if (SSL_CTX_use_certificate_chain_file(ctx, host->ssl_cert) != 1)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load server certificate file \"%s\": %s",
host->ssl_cert, SSLerrmessage(ERR_get_error()))));
goto error;
}
if (!check_ssl_key_file_permissions(host->ssl_key, isServerStart))
goto error;
/* used by the callback */
ssl_is_server_start = isServerStart;
/*
* OK, try to load the private key file.
*/
dummy_ssl_passwd_cb_called = false;
if (SSL_CTX_use_PrivateKey_file(ctx,
host->ssl_key,
SSL_FILETYPE_PEM) != 1)
{
if (dummy_ssl_passwd_cb_called)
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
host->ssl_key)));
else
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load private key file \"%s\": %s",
host->ssl_key, SSLerrmessage(ERR_get_error()))));
goto error;
}
if (SSL_CTX_check_private_key(ctx) != 1)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("check of private key failed: %s",
SSLerrmessage(ERR_get_error()))));
goto error;
}
/*
* Load CA store, so we can verify client certificates if needed.
*/
if (host->ssl_ca && host->ssl_ca[0])
{
STACK_OF(X509_NAME) * root_cert_list;
if (SSL_CTX_load_verify_locations(ctx, host->ssl_ca, NULL) != 1 ||
(root_cert_list = SSL_load_client_CA_file(host->ssl_ca)) == NULL)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load root certificate file \"%s\": %s",
host->ssl_ca, SSLerrmessage(ERR_get_error()))));
goto error;
}
/*
* Tell OpenSSL to send the list of root certs we trust to clients in
* CertificateRequests. This lets a client with a keystore select the
* appropriate client certificate to send to us. Also, this ensures
* that the SSL context will "own" the root_cert_list and remember to
* free it when no longer needed.
*/
SSL_CTX_set_client_CA_list(ctx, root_cert_list);
}
/*----------
* Load the Certificate Revocation List (CRL).
* http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
*----------
*/
if (ssl_crl_file[0] || ssl_crl_dir[0])
{
X509_STORE *cvstore = SSL_CTX_get_cert_store(ctx);
if (cvstore)
{
/* Set the flags to check against the complete CRL chain */
if (X509_STORE_load_locations(cvstore,
ssl_crl_file[0] ? ssl_crl_file : NULL,
ssl_crl_dir[0] ? ssl_crl_dir : NULL)
== 1)
{
X509_STORE_set_flags(cvstore,
X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
}
else if (ssl_crl_dir[0] == 0)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load SSL certificate revocation list file \"%s\": %s",
ssl_crl_file, SSLerrmessage(ERR_get_error()))));
goto error;
}
else if (ssl_crl_file[0] == 0)
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
ssl_crl_dir, SSLerrmessage(ERR_get_error()))));
goto error;
}
else
{
ereport(isServerStart ? FATAL : LOG,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
ssl_crl_file, ssl_crl_dir,
SSLerrmessage(ERR_get_error()))));
goto error;
}
}
}
host->ssl_ctx = ctx;
return true;
error:
if (ctx)
SSL_CTX_free(ctx);
return false;
}
void
be_tls_destroy(void)
{
if (SSL_context)
SSL_CTX_free(SSL_context);
SSL_context = NULL;
ssl_loaded_verify_locations = false;
}
int
be_tls_open_server(Port *port)
{
int r;
int err;
int waitfor;
unsigned long ecode;
bool give_proto_hint;
static struct CallbackErr err_context;
Assert(!port->ssl);
Assert(!port->peer);
if (!SSL_context)
{
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("could not initialize SSL connection: SSL context not set up")));
return -1;
}
/* set up debugging/info callback */
SSL_CTX_set_info_callback(SSL_context, info_cb);
/* enable ALPN */
SSL_CTX_set_alpn_select_cb(SSL_context, alpn_cb, port);
if (!(port->ssl = SSL_new(SSL_context)))
{
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("could not initialize SSL connection: %s",
SSLerrmessage(ERR_get_error()))));
return -1;
}
if (!ssl_set_port_bio(port))
{
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("could not set SSL socket: %s",
SSLerrmessage(ERR_get_error()))));
return -1;
}
/*
* If the underlying TLS library supports the client hello callback we use
* that in order to support host based configuration using the SNI TLS
* extension. If the user has disabled SNI via the ssl_sni GUC we still
* make use of the callback in order to have consistent handling of
* OpenSSL contexts, except in that case the callback will install the
* default configuration regardless of the hostname sent by the user in
* the handshake.
*
* In case the TLS library does not support the client hello callback, as
* of this writing LibreSSL does not, we need to install the client cert
* verification callback here (if the user configured a CA) since we
* cannot use the OpenSSL context update functionality.
*/
#ifdef HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
SSL_CTX_set_client_hello_cb(SSL_context, sni_clienthello_cb, NULL);
#else
if (SSL_hosts->default_host->ssl_ca && SSL_hosts->default_host->ssl_ca[0])
{
/*
* Always ask for SSL client cert, but don't fail if it's not
* presented. We might fail such connections later, depending on what
* we find in pg_hba.conf.
*/
SSL_set_verify(port->ssl,
(SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE),
verify_cb);
ssl_loaded_verify_locations = true;
}
#endif
err_context.cert_errdetail = NULL;
SSL_set_ex_data(port->ssl, 0, &err_context);
port->ssl_in_use = true;
aloop:
/*
* 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. An extension may have failed to clear the
* per-thread error queue following another call to an OpenSSL I/O
* routine.
*/
errno = 0;
ERR_clear_error();
r = SSL_accept(port->ssl);
if (r <= 0)
{
err = SSL_get_error(port->ssl, r);
/*
* Other clients of OpenSSL in the backend 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_get_error();
switch (err)
{
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
/* not allowed during connection establishment */
Assert(!port->noblock);
/*
* No need to care about timeouts/interrupts here. At this
* point authentication_timeout still employs
* StartupPacketTimeoutHandler() which directly exits.
*/
if (err == SSL_ERROR_WANT_READ)
waitfor = WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH;
else
waitfor = WL_SOCKET_WRITEABLE | WL_EXIT_ON_PM_DEATH;
(void) WaitLatchOrSocket(NULL, waitfor, port->sock, 0,
WAIT_EVENT_SSL_OPEN_SERVER);
goto aloop;
case SSL_ERROR_SYSCALL:
if (r < 0 && errno != 0)
ereport(COMMERROR,
(errcode_for_socket_access(),
errmsg("could not accept SSL connection: %m")));
else
ereport(COMMERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("could not accept SSL connection: EOF detected")));
break;
case SSL_ERROR_SSL:
switch (ERR_GET_REASON(ecode))
{
/*
* UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
* TLSV1_ALERT_PROTOCOL_VERSION have been observed
* when trying to communicate with an old OpenSSL
* library, or when the client and server specify
* disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
* occurs if there's a local misconfiguration (which
* can happen despite our checks, if openssl.cnf
* injects a limit we didn't account for). It's not
* very clear what would make OpenSSL return the other
* codes listed here, but a hint about protocol
* versions seems like it's appropriate for all.
*/
case SSL_R_NO_PROTOCOLS_AVAILABLE:
case SSL_R_UNSUPPORTED_PROTOCOL:
case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
case SSL_R_UNKNOWN_PROTOCOL:
case SSL_R_UNKNOWN_SSL_VERSION:
case SSL_R_UNSUPPORTED_SSL_VERSION:
case SSL_R_WRONG_SSL_VERSION:
case SSL_R_WRONG_VERSION_NUMBER:
case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
#ifdef SSL_R_VERSION_TOO_HIGH
case SSL_R_VERSION_TOO_HIGH:
#endif
#ifdef SSL_R_VERSION_TOO_LOW
case SSL_R_VERSION_TOO_LOW:
#endif