forked from haproxy/haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssl_sock.c
7707 lines (6708 loc) · 224 KB
/
ssl_sock.c
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
/*
* SSL/TLS transport layer over SOCK_STREAM sockets
*
* Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Acknowledgement:
* We'd like to specially thank the Stud project authors for a very clean
* and well documented code which helped us understand how the OpenSSL API
* ought to be used in non-blocking mode. This is one difficult part which
* is not easy to get from the OpenSSL doc, and reading the Stud code made
* it much more obvious than the examples in the OpenSSL package. Keep up
* the good works, guys !
*
* Stud is an extremely efficient and scalable SSL/TLS proxy which combines
* particularly well with haproxy. For more info about this project, visit :
* https://github.com/bumptech/stud
*
*/
/* Note: do NOT include openssl/xxx.h here, do it in openssl-compat.h */
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <import/ebpttree.h>
#include <import/ebsttree.h>
#include <import/lru.h>
#include <haproxy/api.h>
#include <haproxy/arg.h>
#include <haproxy/base64.h>
#include <haproxy/channel.h>
#include <haproxy/chunk.h>
#include <haproxy/cli.h>
#include <haproxy/connection.h>
#include <haproxy/dynbuf.h>
#include <haproxy/errors.h>
#include <haproxy/fd.h>
#include <haproxy/freq_ctr.h>
#include <haproxy/frontend.h>
#include <haproxy/global.h>
#include <haproxy/http_rules.h>
#include <haproxy/log.h>
#include <haproxy/openssl-compat.h>
#include <haproxy/pattern-t.h>
#include <haproxy/proto_tcp.h>
#include <haproxy/proxy.h>
#include <haproxy/server.h>
#include <haproxy/shctx.h>
#include <haproxy/ssl_ckch.h>
#include <haproxy/ssl_crtlist.h>
#include <haproxy/ssl_sock.h>
#include <haproxy/ssl_utils.h>
#include <haproxy/stats.h>
#include <haproxy/stream-t.h>
#include <haproxy/stream_interface.h>
#include <haproxy/task.h>
#include <haproxy/ticks.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/vars.h>
#include <haproxy/xprt_quic.h>
#include <haproxy/xxhash.h>
/* ***** READ THIS before adding code here! *****
*
* Due to API incompatibilities between multiple OpenSSL versions and their
* derivatives, it's often tempting to add macros to (re-)define certain
* symbols. Please do not do this here, and do it in common/openssl-compat.h
* exclusively so that the whole code consistently uses the same macros.
*
* Whenever possible if a macro is missing in certain versions, it's better
* to conditionally define it in openssl-compat.h than using lots of ifdefs.
*/
int sslconns = 0;
int totalsslconns = 0;
int nb_engines = 0;
static struct eb_root cert_issuer_tree = EB_ROOT; /* issuers tree from "issuers-chain-path" */
struct global_ssl global_ssl = {
#ifdef LISTEN_DEFAULT_CIPHERS
.listen_default_ciphers = LISTEN_DEFAULT_CIPHERS,
#endif
#ifdef CONNECT_DEFAULT_CIPHERS
.connect_default_ciphers = CONNECT_DEFAULT_CIPHERS,
#endif
#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
.listen_default_ciphersuites = LISTEN_DEFAULT_CIPHERSUITES,
.connect_default_ciphersuites = CONNECT_DEFAULT_CIPHERSUITES,
#endif
.listen_default_ssloptions = BC_SSL_O_NONE,
.connect_default_ssloptions = SRV_SSL_O_NONE,
.listen_default_sslmethods.flags = MC_SSL_O_ALL,
.listen_default_sslmethods.min = CONF_TLSV_NONE,
.listen_default_sslmethods.max = CONF_TLSV_NONE,
.connect_default_sslmethods.flags = MC_SSL_O_ALL,
.connect_default_sslmethods.min = CONF_TLSV_NONE,
.connect_default_sslmethods.max = CONF_TLSV_NONE,
#ifdef DEFAULT_SSL_MAX_RECORD
.max_record = DEFAULT_SSL_MAX_RECORD,
#endif
.default_dh_param = SSL_DEFAULT_DH_PARAM,
.ctx_cache = DEFAULT_SSL_CTX_CACHE,
.capture_buffer_size = 0,
.extra_files = SSL_GF_ALL,
.extra_files_noext = 0,
#ifdef HAVE_SSL_KEYLOG
.keylog = 0
#endif
};
static BIO_METHOD *ha_meth;
DECLARE_STATIC_POOL(ssl_sock_ctx_pool, "ssl_sock_ctx_pool", sizeof(struct ssl_sock_ctx));
/* ssl stats module */
enum {
SSL_ST_SESS,
SSL_ST_REUSED_SESS,
SSL_ST_FAILED_HANDSHAKE,
SSL_ST_STATS_COUNT /* must be the last member of the enum */
};
static struct name_desc ssl_stats[] = {
[SSL_ST_SESS] = { .name = "ssl_sess",
.desc = "Total number of ssl sessions established" },
[SSL_ST_REUSED_SESS] = { .name = "ssl_reused_sess",
.desc = "Total number of ssl sessions reused" },
[SSL_ST_FAILED_HANDSHAKE] = { .name = "ssl_failed_handshake",
.desc = "Total number of failed handshake" },
};
static struct ssl_counters {
long long sess;
long long reused_sess;
long long failed_handshake;
} ssl_counters;
static void ssl_fill_stats(void *data, struct field *stats)
{
struct ssl_counters *counters = data;
stats[SSL_ST_SESS] = mkf_u64(FN_COUNTER, counters->sess);
stats[SSL_ST_REUSED_SESS] = mkf_u64(FN_COUNTER, counters->reused_sess);
stats[SSL_ST_FAILED_HANDSHAKE] = mkf_u64(FN_COUNTER, counters->failed_handshake);
}
static struct stats_module ssl_stats_module = {
.name = "ssl",
.fill_stats = ssl_fill_stats,
.stats = ssl_stats,
.stats_count = SSL_ST_STATS_COUNT,
.counters = &ssl_counters,
.counters_size = sizeof(ssl_counters),
.domain_flags = MK_STATS_PROXY_DOMAIN(STATS_PX_CAP_FE|STATS_PX_CAP_LI|STATS_PX_CAP_BE|STATS_PX_CAP_SRV),
.clearable = 1,
};
INITCALL1(STG_REGISTER, stats_register_module, &ssl_stats_module);
/* ssl_sock_io_cb is exported to see it resolved in "show fd" */
struct task *ssl_sock_io_cb(struct task *, void *, unsigned int);
static int ssl_sock_handshake(struct connection *conn, unsigned int flag);
/* Methods to implement OpenSSL BIO */
static int ha_ssl_write(BIO *h, const char *buf, int num)
{
struct buffer tmpbuf;
struct ssl_sock_ctx *ctx;
int ret;
ctx = BIO_get_data(h);
tmpbuf.size = num;
tmpbuf.area = (void *)(uintptr_t)buf;
tmpbuf.data = num;
tmpbuf.head = 0;
ret = ctx->xprt->snd_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, num, 0);
if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_WR_SH))) {
BIO_set_retry_write(h);
ret = -1;
} else if (ret == 0)
BIO_clear_retry_flags(h);
return ret;
}
static int ha_ssl_gets(BIO *h, char *buf, int size)
{
return 0;
}
static int ha_ssl_puts(BIO *h, const char *str)
{
return ha_ssl_write(h, str, strlen(str));
}
static int ha_ssl_read(BIO *h, char *buf, int size)
{
struct buffer tmpbuf;
struct ssl_sock_ctx *ctx;
int ret;
ctx = BIO_get_data(h);
tmpbuf.size = size;
tmpbuf.area = buf;
tmpbuf.data = 0;
tmpbuf.head = 0;
ret = ctx->xprt->rcv_buf(ctx->conn, ctx->xprt_ctx, &tmpbuf, size, 0);
if (ret == 0 && !(ctx->conn->flags & (CO_FL_ERROR | CO_FL_SOCK_RD_SH))) {
BIO_set_retry_read(h);
ret = -1;
} else if (ret == 0)
BIO_clear_retry_flags(h);
return ret;
}
static long ha_ssl_ctrl(BIO *h, int cmd, long arg1, void *arg2)
{
int ret = 0;
switch (cmd) {
case BIO_CTRL_DUP:
case BIO_CTRL_FLUSH:
ret = 1;
break;
}
return ret;
}
static int ha_ssl_new(BIO *h)
{
BIO_set_init(h, 1);
BIO_set_data(h, NULL);
BIO_clear_flags(h, ~0);
return 1;
}
static int ha_ssl_free(BIO *data)
{
return 1;
}
#if defined(USE_THREAD) && (HA_OPENSSL_VERSION_NUMBER < 0x10100000L)
static HA_RWLOCK_T *ssl_rwlocks;
unsigned long ssl_id_function(void)
{
return (unsigned long)tid;
}
void ssl_locking_function(int mode, int n, const char * file, int line)
{
if (mode & CRYPTO_LOCK) {
if (mode & CRYPTO_READ)
HA_RWLOCK_RDLOCK(SSL_LOCK, &ssl_rwlocks[n]);
else
HA_RWLOCK_WRLOCK(SSL_LOCK, &ssl_rwlocks[n]);
}
else {
if (mode & CRYPTO_READ)
HA_RWLOCK_RDUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
else
HA_RWLOCK_WRUNLOCK(SSL_LOCK, &ssl_rwlocks[n]);
}
}
static int ssl_locking_init(void)
{
int i;
ssl_rwlocks = malloc(sizeof(HA_RWLOCK_T)*CRYPTO_num_locks());
if (!ssl_rwlocks)
return -1;
for (i = 0 ; i < CRYPTO_num_locks() ; i++)
HA_RWLOCK_INIT(&ssl_rwlocks[i]);
CRYPTO_set_id_callback(ssl_id_function);
CRYPTO_set_locking_callback(ssl_locking_function);
return 0;
}
#endif
__decl_thread(HA_SPINLOCK_T ckch_lock);
/* mimic what X509_STORE_load_locations do with store_ctx */
static int ssl_set_cert_crl_file(X509_STORE *store_ctx, char *path)
{
X509_STORE *store = NULL;
struct cafile_entry *ca_e = ssl_store_get_cafile_entry(path, 0);
if (ca_e)
store = ca_e->ca_store;
if (store_ctx && store) {
int i;
X509_OBJECT *obj;
STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
obj = sk_X509_OBJECT_value(objs, i);
switch (X509_OBJECT_get_type(obj)) {
case X509_LU_X509:
X509_STORE_add_cert(store_ctx, X509_OBJECT_get0_X509(obj));
break;
case X509_LU_CRL:
X509_STORE_add_crl(store_ctx, X509_OBJECT_get0_X509_CRL(obj));
break;
default:
break;
}
}
return 1;
}
return 0;
}
/* SSL_CTX_load_verify_locations substitute, internally call X509_STORE_load_locations */
static int ssl_set_verify_locations_file(SSL_CTX *ctx, char *path)
{
X509_STORE *store_ctx = SSL_CTX_get_cert_store(ctx);
return ssl_set_cert_crl_file(store_ctx, path);
}
/*
Extract CA_list from CA_file already in tree.
Duplicate ca_name is tracking with ebtree. It's simplify openssl compatibility.
Return a shared ca_list: SSL_dup_CA_list must be used before set it on SSL_CTX.
*/
static STACK_OF(X509_NAME)* ssl_get_client_ca_file(char *path)
{
struct ebmb_node *eb;
struct cafile_entry *ca_e;
eb = ebst_lookup(&cafile_tree, path);
if (!eb)
return NULL;
ca_e = ebmb_entry(eb, struct cafile_entry, node);
if (ca_e->ca_list == NULL) {
int i;
unsigned long key;
struct eb_root ca_name_tree = EB_ROOT;
struct eb64_node *node, *back;
struct {
struct eb64_node node;
X509_NAME *xname;
} *ca_name;
STACK_OF(X509_OBJECT) *objs;
STACK_OF(X509_NAME) *skn;
X509 *x;
X509_NAME *xn;
skn = sk_X509_NAME_new_null();
/* take x509 from cafile_tree */
objs = X509_STORE_get0_objects(ca_e->ca_store);
for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
x = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
if (!x)
continue;
xn = X509_get_subject_name(x);
if (!xn)
continue;
/* Check for duplicates. */
key = X509_NAME_hash(xn);
for (node = eb64_lookup(&ca_name_tree, key), ca_name = NULL;
node && ca_name == NULL;
node = eb64_next(node)) {
ca_name = container_of(node, typeof(*ca_name), node);
if (X509_NAME_cmp(xn, ca_name->xname) != 0)
ca_name = NULL;
}
/* find a duplicate */
if (ca_name)
continue;
ca_name = calloc(1, sizeof *ca_name);
xn = X509_NAME_dup(xn);
if (!ca_name ||
!xn ||
!sk_X509_NAME_push(skn, xn)) {
free(ca_name);
X509_NAME_free(xn);
sk_X509_NAME_pop_free(skn, X509_NAME_free);
sk_X509_NAME_free(skn);
skn = NULL;
break;
}
ca_name->node.key = key;
ca_name->xname = xn;
eb64_insert(&ca_name_tree, &ca_name->node);
}
ca_e->ca_list = skn;
/* remove temporary ca_name tree */
node = eb64_first(&ca_name_tree);
while (node) {
ca_name = container_of(node, typeof(*ca_name), node);
back = eb64_next(node);
eb64_delete(node);
free(ca_name);
node = back;
}
}
return ca_e->ca_list;
}
struct pool_head *pool_head_ssl_capture __read_mostly = NULL;
int ssl_capture_ptr_index = -1;
int ssl_app_data_index = -1;
#ifdef HAVE_SSL_KEYLOG
int ssl_keylog_index = -1;
struct pool_head *pool_head_ssl_keylog __read_mostly = NULL;
struct pool_head *pool_head_ssl_keylog_str __read_mostly = NULL;
#endif
int ssl_client_crt_ref_index = -1;
#if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
#endif
#ifndef OPENSSL_NO_ENGINE
unsigned int openssl_engines_initialized;
struct list openssl_engines = LIST_HEAD_INIT(openssl_engines);
struct ssl_engine_list {
struct list list;
ENGINE *e;
};
#endif
#ifndef OPENSSL_NO_DH
static int ssl_dh_ptr_index = -1;
static DH *global_dh = NULL;
static DH *local_dh_1024 = NULL;
static DH *local_dh_2048 = NULL;
static DH *local_dh_4096 = NULL;
static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
#endif /* OPENSSL_NO_DH */
#if (defined SSL_CTRL_SET_TLSEXT_HOSTNAME && !defined SSL_NO_GENERATE_CERTIFICATES)
/* X509V3 Extensions that will be added on generated certificates */
#define X509V3_EXT_SIZE 5
static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
"basicConstraints",
"nsComment",
"subjectKeyIdentifier",
"authorityKeyIdentifier",
"keyUsage",
};
static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
"CA:FALSE",
"\"OpenSSL Generated Certificate\"",
"hash",
"keyid,issuer:always",
"nonRepudiation,digitalSignature,keyEncipherment"
};
/* LRU cache to store generated certificate */
static struct lru64_head *ssl_ctx_lru_tree = NULL;
static unsigned int ssl_ctx_lru_seed = 0;
static unsigned int ssl_ctx_serial;
__decl_rwlock(ssl_ctx_lru_rwlock);
#endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
/* The order here matters for picking a default context,
* keep the most common keytype at the bottom of the list
*/
const char *SSL_SOCK_KEYTYPE_NAMES[] = {
"dsa",
"ecdsa",
"rsa"
};
static struct shared_context *ssl_shctx = NULL; /* ssl shared session cache */
static struct eb_root *sh_ssl_sess_tree; /* ssl shared session tree */
/* Dedicated callback functions for heartbeat and clienthello.
*/
#ifdef TLS1_RT_HEARTBEAT
static void ssl_sock_parse_heartbeat(struct connection *conn, int write_p, int version,
int content_type, const void *buf, size_t len,
SSL *ssl);
#endif
static void ssl_sock_parse_clienthello(struct connection *conn, int write_p, int version,
int content_type, const void *buf, size_t len,
SSL *ssl);
#ifdef HAVE_SSL_KEYLOG
static void ssl_init_keylog(struct connection *conn, int write_p, int version,
int content_type, const void *buf, size_t len,
SSL *ssl);
#endif
/* List head of all registered SSL/TLS protocol message callbacks. */
struct list ssl_sock_msg_callbacks = LIST_HEAD_INIT(ssl_sock_msg_callbacks);
/* Registers the function <func> in order to be called on SSL/TLS protocol
* message processing. It will return 0 if the function <func> is not set
* or if it fails to allocate memory.
*/
int ssl_sock_register_msg_callback(ssl_sock_msg_callback_func func)
{
struct ssl_sock_msg_callback *cbk;
if (!func)
return 0;
cbk = calloc(1, sizeof(*cbk));
if (!cbk) {
ha_alert("out of memory in ssl_sock_register_msg_callback().\n");
return 0;
}
cbk->func = func;
LIST_APPEND(&ssl_sock_msg_callbacks, &cbk->list);
return 1;
}
/* Used to register dedicated SSL/TLS protocol message callbacks.
*/
static int ssl_sock_register_msg_callbacks(void)
{
#ifdef TLS1_RT_HEARTBEAT
if (!ssl_sock_register_msg_callback(ssl_sock_parse_heartbeat))
return ERR_ABORT;
#endif
if (global_ssl.capture_buffer_size > 0) {
if (!ssl_sock_register_msg_callback(ssl_sock_parse_clienthello))
return ERR_ABORT;
}
#ifdef HAVE_SSL_KEYLOG
if (global_ssl.keylog > 0) {
if (!ssl_sock_register_msg_callback(ssl_init_keylog))
return ERR_ABORT;
}
#endif
return ERR_NONE;
}
/* Used to free all SSL/TLS protocol message callbacks that were
* registered by using ssl_sock_register_msg_callback().
*/
static void ssl_sock_unregister_msg_callbacks(void)
{
struct ssl_sock_msg_callback *cbk, *cbkback;
list_for_each_entry_safe(cbk, cbkback, &ssl_sock_msg_callbacks, list) {
LIST_DELETE(&cbk->list);
free(cbk);
}
}
SSL *ssl_sock_get_ssl_object(struct connection *conn)
{
if (!ssl_sock_is_ssl(conn))
return NULL;
return ((struct ssl_sock_ctx *)(conn->xprt_ctx))->ssl;
}
/*
* This function gives the detail of the SSL error. It is used only
* if the debug mode and the verbose mode are activated. It dump all
* the SSL error until the stack was empty.
*/
static forceinline void ssl_sock_dump_errors(struct connection *conn)
{
unsigned long ret;
if (unlikely(global.mode & MODE_DEBUG)) {
while(1) {
ret = ERR_get_error();
if (ret == 0)
return;
fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
conn->handle.fd, ret,
ERR_func_error_string(ret), ERR_reason_error_string(ret));
}
}
}
#ifndef OPENSSL_NO_ENGINE
int ssl_init_single_engine(const char *engine_id, const char *def_algorithms)
{
int err_code = ERR_ABORT;
ENGINE *engine;
struct ssl_engine_list *el;
/* grab the structural reference to the engine */
engine = ENGINE_by_id(engine_id);
if (engine == NULL) {
ha_alert("ssl-engine %s: failed to get structural reference\n", engine_id);
goto fail_get;
}
if (!ENGINE_init(engine)) {
/* the engine couldn't initialise, release it */
ha_alert("ssl-engine %s: failed to initialize\n", engine_id);
goto fail_init;
}
if (ENGINE_set_default_string(engine, def_algorithms) == 0) {
ha_alert("ssl-engine %s: failed on ENGINE_set_default_string\n", engine_id);
goto fail_set_method;
}
el = calloc(1, sizeof(*el));
if (!el)
goto fail_alloc;
el->e = engine;
LIST_INSERT(&openssl_engines, &el->list);
nb_engines++;
if (global_ssl.async)
global.ssl_used_async_engines = nb_engines;
return 0;
fail_alloc:
fail_set_method:
/* release the functional reference from ENGINE_init() */
ENGINE_finish(engine);
fail_init:
/* release the structural reference from ENGINE_by_id() */
ENGINE_free(engine);
fail_get:
return err_code;
}
#endif
#ifdef SSL_MODE_ASYNC
/*
* openssl async fd handler
*/
void ssl_async_fd_handler(int fd)
{
struct ssl_sock_ctx *ctx = fdtab[fd].owner;
/* fd is an async enfine fd, we must stop
* to poll this fd until it is requested
*/
fd_stop_recv(fd);
fd_cant_recv(fd);
/* crypto engine is available, let's notify the associated
* connection that it can pursue its processing.
*/
tasklet_wakeup(ctx->wait_event.tasklet);
}
/*
* openssl async delayed SSL_free handler
*/
void ssl_async_fd_free(int fd)
{
SSL *ssl = fdtab[fd].owner;
OSSL_ASYNC_FD all_fd[32];
size_t num_all_fds = 0;
int i;
/* We suppose that the async job for a same SSL *
* are serialized. So if we are awake it is
* because the running job has just finished
* and we can remove all async fds safely
*/
SSL_get_all_async_fds(ssl, NULL, &num_all_fds);
if (num_all_fds > 32) {
send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
return;
}
SSL_get_all_async_fds(ssl, all_fd, &num_all_fds);
for (i=0 ; i < num_all_fds ; i++)
fd_stop_both(all_fd[i]);
/* Now we can safely call SSL_free, no more pending job in engines */
SSL_free(ssl);
_HA_ATOMIC_DEC(&sslconns);
_HA_ATOMIC_DEC(&jobs);
}
/*
* function used to manage a returned SSL_ERROR_WANT_ASYNC
* and enable/disable polling for async fds
*/
static inline void ssl_async_process_fds(struct ssl_sock_ctx *ctx)
{
OSSL_ASYNC_FD add_fd[32];
OSSL_ASYNC_FD del_fd[32];
SSL *ssl = ctx->ssl;
size_t num_add_fds = 0;
size_t num_del_fds = 0;
int i;
SSL_get_changed_async_fds(ssl, NULL, &num_add_fds, NULL,
&num_del_fds);
if (num_add_fds > 32 || num_del_fds > 32) {
send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
return;
}
SSL_get_changed_async_fds(ssl, add_fd, &num_add_fds, del_fd, &num_del_fds);
/* We remove unused fds from the fdtab */
for (i=0 ; i < num_del_fds ; i++)
fd_stop_both(del_fd[i]);
/* We add new fds to the fdtab */
for (i=0 ; i < num_add_fds ; i++) {
fd_insert(add_fd[i], ctx, ssl_async_fd_handler, tid_bit);
}
num_add_fds = 0;
SSL_get_all_async_fds(ssl, NULL, &num_add_fds);
if (num_add_fds > 32) {
send_log(NULL, LOG_EMERG, "haproxy: openssl returns too many async fds. It seems a bug. Process may crash\n");
return;
}
/* We activate the polling for all known async fds */
SSL_get_all_async_fds(ssl, add_fd, &num_add_fds);
for (i=0 ; i < num_add_fds ; i++) {
fd_want_recv(add_fd[i]);
/* To ensure that the fd cache won't be used
* We'll prefer to catch a real RD event
* because handling an EAGAIN on this fd will
* result in a context switch and also
* some engines uses a fd in blocking mode.
*/
fd_cant_recv(add_fd[i]);
}
}
#endif
#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP && !defined HAVE_ASN1_TIME_TO_TM)
/*
* This function returns the number of seconds elapsed
* since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
* date presented un ASN1_GENERALIZEDTIME.
*
* In parsing error case, it returns -1.
*/
static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
{
long epoch;
char *p, *end;
const unsigned short month_offset[12] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
unsigned long year, month;
if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
p = (char *)d->data;
end = p + d->length;
if (end - p < 4) return -1;
year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
p += 4;
if (end - p < 2) return -1;
month = 10 * (p[0] - '0') + p[1] - '0';
if (month < 1 || month > 12) return -1;
/* Compute the number of seconds since 1 jan 1970 and the beginning of current month
We consider leap years and the current month (<marsh or not) */
epoch = ( ((year - 1970) * 365)
+ ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
- ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
+ month_offset[month-1]
) * 24 * 60 * 60;
p += 2;
if (end - p < 2) return -1;
/* Add the number of seconds of completed days of current month */
epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
p += 2;
if (end - p < 2) return -1;
/* Add the completed hours of the current day */
epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
p += 2;
if (end - p < 2) return -1;
/* Add the completed minutes of the current hour */
epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
p += 2;
if (p == end) return -1;
/* Test if there is available seconds */
if (p[0] < '0' || p[0] > '9')
goto nosec;
if (end - p < 2) return -1;
/* Add the seconds of the current minute */
epoch += 10 * (p[0] - '0') + p[1] - '0';
p += 2;
if (p == end) return -1;
/* Ignore seconds float part if present */
if (p[0] == '.') {
do {
if (++p == end) return -1;
} while (p[0] >= '0' && p[0] <= '9');
}
nosec:
if (p[0] == 'Z') {
if (end - p != 1) return -1;
return epoch;
}
else if (p[0] == '+') {
if (end - p != 5) return -1;
/* Apply timezone offset */
return epoch - ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
}
else if (p[0] == '-') {
if (end - p != 5) return -1;
/* Apply timezone offset */
return epoch + ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
}
return -1;
}
#endif
#if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
/*
* struct alignment works here such that the key.key is the same as key_data
* Do not change the placement of key_data
*/
struct certificate_ocsp {
struct ebmb_node key;
unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
unsigned int key_length;
struct buffer response;
int refcount;
long expire;
};
struct ocsp_cbk_arg {
int is_single;
int single_kt;
union {
struct certificate_ocsp *s_ocsp;
/*
* m_ocsp will have multiple entries dependent on key type
* Entry 0 - DSA
* Entry 1 - ECDSA
* Entry 2 - RSA
*/
struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
};
};
static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
/* This function starts to check if the OCSP response (in DER format) contained
* in chunk 'ocsp_response' is valid (else exits on error).
* If 'cid' is not NULL, it will be compared to the OCSP certificate ID
* contained in the OCSP Response and exits on error if no match.
* If it's a valid OCSP Response:
* If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
* pointed by 'ocsp'.
* If 'ocsp' is NULL, the function looks up into the OCSP response's
* containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
* from the response) and exits on error if not found. Finally, If an OCSP response is
* already present in the container, it will be overwritten.
*
* Note: OCSP response containing more than one OCSP Single response is not
* considered valid.
*
* Returns 0 on success, 1 in error case.
*/
static int ssl_sock_load_ocsp_response(struct buffer *ocsp_response,
struct certificate_ocsp *ocsp,
OCSP_CERTID *cid, char **err)
{
OCSP_RESPONSE *resp;
OCSP_BASICRESP *bs = NULL;
OCSP_SINGLERESP *sr;
OCSP_CERTID *id;
unsigned char *p = (unsigned char *) ocsp_response->area;
int rc , count_sr;
ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
int reason;
int ret = 1;
#ifdef HAVE_ASN1_TIME_TO_TM
struct tm nextupd_tm = {0};
#endif
resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p,
ocsp_response->data);
if (!resp) {
memprintf(err, "Unable to parse OCSP response");
goto out;
}
rc = OCSP_response_status(resp);
if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
memprintf(err, "OCSP response status not successful");
goto out;
}
bs = OCSP_response_get1_basic(resp);
if (!bs) {
memprintf(err, "Failed to get basic response from OCSP Response");
goto out;
}
count_sr = OCSP_resp_count(bs);
if (count_sr > 1) {
memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
goto out;
}
sr = OCSP_resp_get0(bs, 0);
if (!sr) {
memprintf(err, "Failed to get OCSP single response");
goto out;
}
id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
memprintf(err, "OCSP single response: certificate status is unknown");
goto out;
}
if (!nextupd) {
memprintf(err, "OCSP single response: missing nextupdate");
goto out;
}
rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
if (!rc) {
memprintf(err, "OCSP single response: no longer valid.");
goto out;
}
if (cid) {
if (OCSP_id_cmp(id, cid)) {
memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
goto out;
}
}
if (!ocsp) {
unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
unsigned char *p;
rc = i2d_OCSP_CERTID(id, NULL);
if (!rc) {
memprintf(err, "OCSP single response: Unable to encode Certificate ID");
goto out;
}
if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
memprintf(err, "OCSP single response: Certificate ID too long");
goto out;
}
p = key;
memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
i2d_OCSP_CERTID(id, &p);
ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
if (!ocsp) {
memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
goto out;
}
}
/* According to comments on "chunk_dup", the
previous chunk buffer will be freed */