/
openssl.c
2392 lines (2061 loc) · 76.9 KB
/
openssl.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
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* Enable POSIX features beyond c99 for modern pthread and standard strerror_r() */
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif
/* Avoid GNU extensions, in particular the incompatible alternative strerror_r() */
#undef _GNU_SOURCE
#include "platform/platform.h"
#include "platform/platform_fmt.h"
#include "core/util.h"
#include <proton/error.h>
#include <proton/tls.h>
// openssl on windows expects the user to have already included
// winsock.h
#ifdef _MSC_VER
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#if _WIN32_WINNT < 0x0501
#error "Proton requires Windows API support for XP or later."
#endif
#include <winsock2.h>
#include <mswsock.h>
#include <Ws2tcpip.h>
#endif
#include <openssl/ssl.h>
#include <openssl/dh.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
/** @file
* Standalone raw buffer based SSL/TLS support API.
*
* This file is heavily based on the original Proton SSL layer for
* AMQP connections and the buffer management logic in
* raw_connection.c.
*/
enum {
default_eresult_buffer_count = 4,
default_dresult_buffer_count = 4,
default_decrypt_buffer_count = 4,
default_encrypt_buffer_count = 4
};
typedef enum {
buff_empty = 0,
buff_decrypt_pending = 1, // application buffers for decryption
buff_decrypt_done = 2,
buff_encrypt_pending = 3, // application buffers for encryption
buff_encrypt_done = 4,
buff_eresult_blank = 5,
buff_eresult_encrypted = 6,
buff_dresult_blank = 7,
buff_dresult_decrypted = 8
} buff_type;
typedef uint16_t buff_ptr; // This is always the index+1 so that 0 can be special
typedef struct pbuffer_t {
uintptr_t context;
char *bytes;
uint32_t capacity;
uint32_t size;
uint32_t offset;
buff_ptr next;
uint8_t type; // For debugging
} pbuffer_t;
typedef struct pn_tls_session_t pn_tls_session_t;
static int tls_ex_data_index;
struct pn_tls_config_t {
SSL_CTX *ctx;
char *keyfile_pw;
// settings used for all connections
char *trusted_CAs;
char *ciphers;
int ref_count;
#ifdef SSL_SECOP_PEER
int default_seclevel;
#endif
pn_tls_mode_t mode;
pn_tls_verify_mode_t verify_mode;
bool has_certificate; // true when certificate configured
unsigned char *alpn_list;
unsigned int alpn_list_len;
};
struct pn_tls_t {
pbuffer_t *eresult_buffers;
pbuffer_t *dresult_buffers;
pbuffer_t *encrypt_buffers;
pbuffer_t *decrypt_buffers;
size_t eresult_buffer_count;
size_t dresult_buffer_count;
size_t encrypt_buffer_count;
size_t decrypt_buffer_count;
uint16_t encrypt_buffer_empty_count;
uint16_t decrypt_buffer_empty_count;
uint16_t eresult_encrypted_count;
uint16_t eresult_empty_count;
uint16_t dresult_decrypted_count;
uint16_t dresult_empty_count;
// Lists within encrypt_buffers
buff_ptr encrypt_first_empty; // unordered: no encryp_last_empty
buff_ptr encrypt_first_pending;
buff_ptr encrypt_last_pending;
buff_ptr encrypt_first_done;
buff_ptr encrypt_last_done;
// Lists within decrypt_buffers
buff_ptr decrypt_first_empty; // unordered.
buff_ptr decrypt_first_pending;
buff_ptr decrypt_last_pending;
buff_ptr decrypt_first_done;
buff_ptr decrypt_last_done;
// Lists within eresult_buffers
buff_ptr eresult_first_empty; // unordered.
buff_ptr eresult_first_blank; // unordered.
buff_ptr eresult_first_encrypted;
buff_ptr eresult_last_encrypted;
// Lists within dresult_buffers
buff_ptr dresult_first_empty; // unordered.
buff_ptr dresult_first_blank; // unordered.
buff_ptr dresult_first_decrypted;
buff_ptr dresult_last_decrypted;
uint32_t encrypt_pending_offset; // if set, points to remaining bytes to consume in working buffer.
uint32_t decrypt_pending_offset;
pn_tls_mode_t mode;
pn_tls_verify_mode_t verify_mode;
pn_tls_config_t *domain;
const char *session_id;
const char *peer_hostname;
SSL *ssl;
BIO *bio_ssl_io; // SSL "half" of network-facing BIO
BIO *bio_net_io; // socket-side "half" of network-facing BIO
// buffers for holding unprocessed bytes to be en/decoded when BIO is able to process them.
int pn_tls_err; // TLS errors are fatal to the session, including session tickets/psks
int openssl_err_type; // From SSL_get_error()
unsigned long openssl_err; // From ERR_get_error()
int os_errno; // In case the OS can supply error context not available from OpenSSL
bool ssl_shutdown; // BIO_ssl_shutdown() called on socket.
bool ssl_closed; // shutdown complete, or SSL error
bool dec_closed; // Peer's TLS closure record received. Clean EOF of inbound decrypted data.
bool enc_closed; // Self TLS closure record sent or pending flush.
bool enc_rblocked;
bool enc_wblocked;
bool dec_rblocked;
bool dec_wblocked;
bool dec_rpending; // At least one decrypted byte immediately readable.
bool handshake_ok;
bool can_shutdown;
bool started;
bool stopped;
bool validating;
const char *validate_error;
char *subject;
X509 *peer_certificate;
unsigned char *alpn_list;
unsigned int alpn_list_len;
};
static void encrypt(pn_tls_t *);
static void decrypt(pn_tls_t *);
static int pn_tls_alpn_cb(SSL *ssn, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg);
static void release_buffers(pn_tls_t *
);
static void tls_initialize_buffers(pn_tls_t *tls) {
// Link together free lists
for (buff_ptr i = 1; i<=tls->encrypt_buffer_count; i++) {
tls->encrypt_buffers[i-1].next = i==tls->encrypt_buffer_count ? 0 : i+1;
tls->encrypt_buffers[i-1].type = buff_empty;
}
for (buff_ptr i = 1; i<=tls->decrypt_buffer_count; i++) {
tls->decrypt_buffers[i-1].next = i==tls->decrypt_buffer_count ? 0 : i+1;
tls->decrypt_buffers[i-1].type = buff_empty;
}
for (buff_ptr i = 1; i<=tls->eresult_buffer_count; i++) {
tls->eresult_buffers[i-1].next = i==tls->eresult_buffer_count ? 0 : i+1;
tls->eresult_buffers[i-1].type = buff_empty;
}
for (buff_ptr i = 1; i<=tls->dresult_buffer_count; i++) {
tls->dresult_buffers[i-1].next = i==tls->dresult_buffer_count ? 0 : i+1;
tls->dresult_buffers[i-1].type = buff_empty;
}
tls->encrypt_buffer_empty_count = tls->encrypt_buffer_count;
tls->decrypt_buffer_empty_count = tls->decrypt_buffer_count;
tls->eresult_empty_count = tls->eresult_buffer_count;
tls->dresult_empty_count = tls->dresult_buffer_count;
tls->eresult_first_empty = 1;
tls->dresult_first_empty = 1;
tls->encrypt_first_empty = 1;
tls->decrypt_first_empty = 1;
}
bool pni_tls_validate(pn_tls_t *tls) {
// encrypt input buffers: empty + 2 ordered sublists
tls->validate_error = "encrypt empty list";
size_t e_empty_count = 0;
for (buff_ptr i = tls->encrypt_first_empty; i; i = tls->encrypt_buffers[i-1].next) {
if (tls->encrypt_buffers[i-1].type != buff_empty) return false;
e_empty_count++;
}
if (e_empty_count != tls->encrypt_buffer_empty_count) return false;
tls->validate_error = "encrypt pending list";
size_t e_pending_count = 0;
for (buff_ptr i = tls->encrypt_first_pending; i; i = tls->encrypt_buffers[i-1].next) {
if (tls->encrypt_buffers[i-1].type != buff_encrypt_pending) return false;
e_pending_count++;
}
tls->validate_error = "encrypt done list";
size_t e_done_count = 0;
for (buff_ptr i = tls->encrypt_first_done; i; i = tls->encrypt_buffers[i-1].next) {
if (tls->encrypt_buffers[i-1].type != buff_encrypt_done) return false;
e_done_count++;
}
tls->validate_error = "encrypt pointers and counts";
if (e_empty_count+e_pending_count+e_done_count != tls->encrypt_buffer_count) return false;
if (!tls->encrypt_first_pending && tls->encrypt_last_pending) return false;
if (tls->encrypt_last_pending &&
(tls->encrypt_buffers[tls->encrypt_last_pending-1].type != buff_encrypt_pending || tls->encrypt_buffers[tls->encrypt_last_pending-1].next != 0)) return false;
if (!tls->encrypt_first_done && tls->encrypt_last_done) return false;
if (tls->encrypt_last_done &&
(tls->encrypt_buffers[tls->encrypt_last_done-1].type != buff_encrypt_done || tls->encrypt_buffers[tls->encrypt_last_done-1].next != 0)) return false;
// decrypt input buffers: empty + 2 ordered sublists
tls->validate_error = "decrypt empty list";
size_t d_empty_count = 0;
for (buff_ptr i = tls->decrypt_first_empty; i; i = tls->decrypt_buffers[i-1].next) {
if (tls->decrypt_buffers[i-1].type != buff_empty) return false;
d_empty_count++;
}
if (d_empty_count != tls->decrypt_buffer_empty_count) return false;
tls->validate_error = "decrypt pending list";
size_t d_pending_count = 0;
for (buff_ptr i = tls->decrypt_first_pending; i; i = tls->decrypt_buffers[i-1].next) {
if (tls->decrypt_buffers[i-1].type != buff_decrypt_pending) return false;
d_pending_count++;
}
tls->validate_error = "decrypt done list";
size_t d_done_count = 0;
for (buff_ptr i = tls->decrypt_first_done; i; i = tls->decrypt_buffers[i-1].next) {
if (tls->decrypt_buffers[i-1].type != buff_decrypt_done) return false;
d_done_count++;
}
tls->validate_error = "decrypt pointers and counts";
if (d_empty_count+d_pending_count+d_done_count != tls->decrypt_buffer_count) return false;
if (!tls->decrypt_first_pending && tls->decrypt_last_pending) return false;
if (tls->decrypt_last_pending &&
(tls->decrypt_buffers[tls->decrypt_last_pending-1].type != buff_decrypt_pending || tls->decrypt_buffers[tls->decrypt_last_pending-1].next != 0)) return false;
if (!tls->decrypt_first_done && tls->decrypt_last_done) return false;
if (tls->decrypt_last_done &&
(tls->decrypt_buffers[tls->decrypt_last_done-1].type != buff_decrypt_done || tls->decrypt_buffers[tls->decrypt_last_done-1].next != 0)) return false;
// encrypt result buffers: empty + unordered blank + ordered "encrypted"
tls->validate_error = "eresult empty list";
size_t e_r_empty_count = 0;
for (buff_ptr i = tls->eresult_first_empty; i; i = tls->eresult_buffers[i-1].next) {
if (tls->eresult_buffers[i-1].type != buff_empty) return false;
e_r_empty_count++;
}
if (e_r_empty_count != tls->eresult_empty_count) return false;
tls->validate_error = "eresult blank list";
size_t e_blank_count = 0;
for (buff_ptr i = tls->eresult_first_blank; i; i = tls->eresult_buffers[i-1].next) {
if (tls->eresult_buffers[i-1].type != buff_eresult_blank) return false;
e_blank_count++;
}
tls->validate_error = "eresult encrypted list";
size_t e_encrypted_count = 0;
for (buff_ptr i = tls->eresult_first_encrypted; i; i = tls->eresult_buffers[i-1].next) {
if (tls->eresult_buffers[i-1].type != buff_eresult_encrypted) return false;
e_encrypted_count++;
}
if (e_encrypted_count != tls->eresult_encrypted_count) return false;
tls->validate_error = "encrypt pointers and counts";
if (e_r_empty_count+e_blank_count+e_encrypted_count != tls->eresult_buffer_count) return false;
if (!tls->eresult_first_encrypted && tls->eresult_last_encrypted) return false;
if (tls->eresult_last_encrypted &&
(tls->eresult_buffers[tls->eresult_last_encrypted-1].type != buff_eresult_encrypted || tls->eresult_buffers[tls->eresult_last_encrypted-1].next != 0)) return false;
// decrypt result buffers: empty + unordered blank + ordered "decrypted"
tls->validate_error = "dresult empty list";
size_t d_r_empty_count = 0;
for (buff_ptr i = tls->dresult_first_empty; i; i = tls->dresult_buffers[i-1].next) {
if (tls->dresult_buffers[i-1].type != buff_empty) return false;
d_r_empty_count++;
}
if (d_r_empty_count != tls->dresult_empty_count) return false;
tls->validate_error = "dresult blank list";
size_t d_blank_count = 0;
for (buff_ptr i = tls->dresult_first_blank; i; i = tls->dresult_buffers[i-1].next) {
if (tls->dresult_buffers[i-1].type != buff_dresult_blank) return false;
d_blank_count++;
}
tls->validate_error = "dresult decrypted list";
size_t d_decrypted_count = 0;
for (buff_ptr i = tls->dresult_first_decrypted; i; i = tls->dresult_buffers[i-1].next) {
if (tls->dresult_buffers[i-1].type != buff_dresult_decrypted) return false;
d_decrypted_count++;
}
if (d_decrypted_count != tls->dresult_decrypted_count) return false;
tls->validate_error = "decrypt pointers and counts";
if (d_r_empty_count+d_blank_count+d_decrypted_count != tls->dresult_buffer_count) return false;
if (!tls->dresult_first_decrypted && tls->dresult_last_decrypted) return false;
if (tls->dresult_last_decrypted &&
(tls->dresult_buffers[tls->dresult_last_decrypted-1].type != buff_dresult_decrypted || tls->dresult_buffers[tls->dresult_last_decrypted-1].next != 0)) return false;
tls->validate_error = NULL;
return true;
}
static void validate_strict(pn_tls_t *tls) {
if (!pni_tls_validate(tls)) {
fprintf(stderr, "TLS internal validation error: %s", tls->validate_error);
fflush(stderr);
abort();
}
}
static void tls_fatal(pn_tls_t *tls, int ssl_err_type, int pn_tls_err) {
if (!tls->pn_tls_err) {
// no previous error to overwrite
tls->pn_tls_err = pn_tls_err;
tls->openssl_err_type = ssl_err_type;
tls->openssl_err = ERR_get_error();
tls->enc_wblocked = true;
tls->dec_rblocked = true;
tls->dec_wblocked = true;
tls->enc_closed = true;
if (ssl_err_type == SSL_ERROR_SYSCALL) {
// OpenSSL requires immediate halt
tls->can_shutdown = false;
tls->enc_rblocked = true;
} else {
if (tls->enc_rblocked) {
// Maybe new output generated.
ERR_clear_error(); // TODO: revisit need.
tls->enc_rblocked = (BIO_pending(tls->bio_net_io) == 0);
}
}
if (ssl_err_type == SSL_ERROR_SYSCALL)
tls->os_errno = errno; // Save this in case it helps error reporting.
} else {
// TODO: handle a subsequent fatal error here. Just log it?
}
// TODO: use tracing here to provide additional error info from the ERR_get_error error queue.
// Must be done here while in same thread as caller.
ERR_clear_error();
}
int pn_tls_get_session_error(pn_tls_t* tls) {
return tls->pn_tls_err;
}
size_t pn_tls_get_session_error_string(pn_tls_t* tls, char *buf, size_t buf_len) {
if (!buf || !buf_len || !tls->pn_tls_err)
return 0;
if (tls->openssl_err)
ERR_error_string_n(tls->openssl_err, buf, buf_len); // Null terminated.
else {
if (tls->openssl_err_type == SSL_ERROR_SYSCALL) {
// OpenSSL doesn't know the cause of the error. Memory corruption or starvation?
// Byte stream in input buffers from peer not the same as it sent?
// errno may help identify cause.
if (tls->os_errno) {
char oserr[1024];
int e = strerror_r(tls->os_errno, oserr, sizeof(oserr));
if (e) snprintf(oserr, sizeof(oserr), "unknown system error %d", tls->os_errno);
snprintf(buf, buf_len, "external error: %s", oserr);
} else {
snprintf(buf, buf_len, "external error: bad TLS stream data");
}
} else {
// Presumably this never happens, always accompanied by tls->openssl_err, but if not:
snprintf(buf, buf_len, "OpenSSL generic error type %d", tls->openssl_err_type);
}
}
return strlen(buf);
}
size_t pn_tls_get_encrypt_input_buffer_capacity(pn_tls_t *tls) {
if (tls->enc_closed || tls->stopped || tls->pn_tls_err)
return 0;
return tls->encrypt_buffer_empty_count;
}
size_t pn_tls_get_decrypt_input_buffer_capacity(pn_tls_t *tls) {
if (tls->dec_closed || tls->stopped || tls->pn_tls_err)
return 0;
return tls->decrypt_buffer_empty_count;
}
size_t pn_tls_get_encrypt_output_buffer_capacity(pn_tls_t *tls) { return tls->eresult_empty_count; }
size_t pn_tls_get_decrypt_output_buffer_capacity(pn_tls_t *tls) { return tls->dresult_empty_count; }
size_t pn_tls_get_decrypt_output_buffer_count(pn_tls_t *tls) {
return tls->dresult_decrypted_count;
}
size_t pn_tls_get_encrypt_output_buffer_count(pn_tls_t *tls) {
return tls->eresult_encrypted_count;
}
uint32_t pn_tls_get_last_decrypt_output_buffer_size(pn_tls_t *tls) {
return tls->dresult_last_decrypted ? tls->dresult_buffers[tls->dresult_last_decrypted-1].size : 0;
}
uint32_t pn_tls_get_last_encrypt_output_buffer_size(pn_tls_t *tls) {
return tls->eresult_last_encrypted ? tls->eresult_buffers[tls->eresult_last_encrypted-1].size : 0;
}
// define two sets of allowable ciphers: those that require authentication, and those
// that do not require authentication (anonymous). See ciphers(1).
#define CIPHERS_AUTHENTICATE "ALL:!aNULL:!eNULL:@STRENGTH"
#define CIPHERS_ANONYMOUS "ALL:aNULL:!eNULL:@STRENGTH"
/* */
static int keyfile_pw_cb(char *buf, int size, int rwflag, void *userdata);
static int init_ssl_socket(pn_tls_t *, pn_tls_config_t *);
static void release_ssl_socket( pn_tls_t * );
static X509 *get_peer_certificate(pn_tls_t *ssl);
//TODO: convenience for embedded existing logging. Replace ASAP.
#define PN_LEVEL_NONE 0
#define PN_LEVEL_CRITICAL 1
#define PN_LEVEL_ERROR 2
#define PN_LEVEL_WARNING 4
#define PN_LEVEL_INFO 8
#define PN_LEVEL_DEBUG 16
#define PN_LEVEL_TRACE 32
#define PN_LEVEL_FRAME 64
#define PN_LEVEL_RAW 128
#define PN_LEVEL_ALL 65535
static void ssl_log(void *v, int sev, const char *fmt, ...)
{
#ifdef at_least_some_logging
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
#endif
}
static void ssl_log_flush(void *v, int sev)
{
char buf[128]; // see "man ERR_error_string_n()"
unsigned long err = ERR_get_error();
while (err) {
ERR_error_string_n(err, buf, sizeof(buf));
ssl_log(v, sev, "%s", buf);
err = ERR_get_error();
}
}
// log an error and dump the SSL error stack
static void ssl_log_error(const char *fmt, ...)
{
}
// Next three not exported from Proton core. Copied for now.
static char *pni_strdup(const char *src)
{
if (!src) return NULL;
char *dest = (char *) malloc(strlen(src)+1);
if (!dest) return NULL;
return strcpy(dest, src);
}
static int pni_strcasecmp(const char *a, const char *b)
{
int diff;
while (*b) {
char aa = *a++, bb = *b++;
diff = tolower(aa)-tolower(bb);
if ( diff!=0 ) return diff;
}
return *a;
}
static int pni_strncasecmp(const char* a, const char* b, size_t len)
{
int diff = 0;
while (*b && len > 0) {
char aa = *a++, bb = *b++;
diff = tolower(aa)-tolower(bb);
if ( diff!=0 ) return diff;
--len;
};
return len==0 ? diff : *a;
}
/* match the DNS name pattern from the peer certificate against our configured peer
hostname */
static bool match_dns_pattern( const char *hostname,
const char *pattern, int plen )
{
int slen = (int) strlen(hostname);
if (memchr( pattern, '*', plen ) == NULL)
return (plen == slen &&
pni_strncasecmp( pattern, hostname, plen ) == 0);
/* dns wildcarded pattern - RFC2818 */
char plabel[64]; /* max label length < 63 - RFC1034 */
char slabel[64];
while (plen > 0 && slen > 0) {
const char *cptr;
int len;
cptr = (const char *) memchr( pattern, '.', plen );
len = (cptr) ? cptr - pattern : plen;
if (len > (int) sizeof(plabel) - 1) return false;
memcpy( plabel, pattern, len );
plabel[len] = 0;
if (cptr) ++len; // skip matching '.'
pattern += len;
plen -= len;
cptr = (const char *) memchr( hostname, '.', slen );
len = (cptr) ? cptr - hostname : slen;
if (len > (int) sizeof(slabel) - 1) return false;
memcpy( slabel, hostname, len );
slabel[len] = 0;
if (cptr) ++len; // skip matching '.'
hostname += len;
slen -= len;
char *star = strchr( plabel, '*' );
if (!star) {
if (pni_strcasecmp( plabel, slabel )) return false;
} else {
*star = '\0';
char *prefix = plabel;
int prefix_len = strlen(prefix);
char *suffix = star + 1;
int suffix_len = strlen(suffix);
if (prefix_len && pni_strncasecmp( prefix, slabel, prefix_len )) return false;
if (suffix_len && pni_strncasecmp( suffix,
slabel + (strlen(slabel) - suffix_len),
suffix_len )) return false;
}
}
return plen == slen;
}
// Certificate chain verification callback: return 1 if verified,
// 0 if remote cannot be verified (fail handshake).
//
static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
if (!preverify_ok || X509_STORE_CTX_get_error_depth(ctx) != 0)
// already failed, or not at peer cert in chain
return preverify_ok;
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
SSL *ssn = (SSL *) X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
if (!ssn) {
ssl_log(NULL, PN_LEVEL_ERROR, "Error: unexpected error - SSL session info not available for peer verify!");
return 0; // fail connection
}
pn_tls_t *ssl = (pn_tls_t *)SSL_get_ex_data(ssn, tls_ex_data_index);
if (!ssl) {
// TODO: replace: ssl_log(transport, PN_LEVEL_ERROR, "Error: unexpected error - SSL context info not available for peer verify!");
return 0; // fail connection
}
if (ssl->verify_mode != PN_TLS_VERIFY_PEER_NAME) return preverify_ok;
if (!ssl->peer_hostname) {
ssl_log(NULL, PN_LEVEL_ERROR, "Error: configuration error: PN_TLS_VERIFY_PEER_NAME configured, but no peer hostname set!");
return 0; // fail connection
}
ssl_log(NULL, PN_LEVEL_TRACE, "Checking identifying name in peer cert against '%s'", ssl->peer_hostname);
bool matched = false;
/* first check any SubjectAltName entries, as per RFC2818 */
GENERAL_NAMES *sans = (GENERAL_NAMES *) X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
if (sans) {
int name_ct = sk_GENERAL_NAME_num( sans );
int i;
for (i = 0; !matched && i < name_ct; ++i) {
GENERAL_NAME *name = sk_GENERAL_NAME_value( sans, i );
if (name->type == GEN_DNS) {
ASN1_STRING *asn1 = name->d.dNSName;
if (asn1 && asn1->data && asn1->length) {
unsigned char *str;
int len = ASN1_STRING_to_UTF8( &str, asn1 );
if (len >= 0) {
ssl_log(NULL, PN_LEVEL_TRACE, "SubjectAltName (dns) from peer cert = '%.*s'", len, str );
matched = match_dns_pattern( ssl->peer_hostname, (const char *)str, len );
OPENSSL_free( str );
}
}
}
}
GENERAL_NAMES_free( sans );
}
/* if no general names match, try the CommonName from the subject */
X509_NAME *name = X509_get_subject_name(cert);
int i = -1;
while (!matched && (i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) {
X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
ASN1_STRING *name_asn1 = X509_NAME_ENTRY_get_data(ne);
if (name_asn1) {
unsigned char *str;
int len = ASN1_STRING_to_UTF8( &str, name_asn1);
if (len >= 0) {
ssl_log(NULL, PN_LEVEL_TRACE, "commonName from peer cert = '%.*s'", len, str);
matched = match_dns_pattern( ssl->peer_hostname, (const char *)str, len );
OPENSSL_free(str);
}
}
}
if (!matched) {
ssl_log(NULL, PN_LEVEL_ERROR, "Error: no name matching %s found in peer cert - rejecting handshake.",
ssl->peer_hostname);
preverify_ok = 0;
#ifdef X509_V_ERR_APPLICATION_VERIFICATION
X509_STORE_CTX_set_error( ctx, X509_V_ERR_APPLICATION_VERIFICATION );
#endif
} else {
ssl_log(NULL, PN_LEVEL_TRACE, "Name from peer cert matched - peer is valid.");
}
return preverify_ok;
}
// Temporary: PROTON-2544 for build. Next release: replace or remove DH_xxx() functions.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// This was introduced in v1.1
#if OPENSSL_VERSION_NUMBER < 0x10100000
int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
dh->p = p;
dh->q = q;
dh->g = g;
return 1;
}
#endif
// this code was generated using the command:
// "openssl dhparam -C -2 2048"
static DH *get_dh2048(void)
{
static const unsigned char dhp_2048[]={
0xAE,0xF7,0xE9,0x66,0x26,0x7A,0xAC,0x0A,0x6F,0x1E,0xCD,0x81,
0xBD,0x0A,0x10,0x7E,0xFA,0x2C,0xF5,0x2D,0x98,0xD4,0xE7,0xD9,
0xE4,0x04,0x8B,0x06,0x85,0xF2,0x0B,0xA3,0x90,0x15,0x56,0x0C,
0x8B,0xBE,0xF8,0x48,0xBB,0x29,0x63,0x75,0x12,0x48,0x9D,0x7E,
0x7C,0x24,0xB4,0x3A,0x38,0x7E,0x97,0x3C,0x77,0x95,0xB0,0xA2,
0x72,0xB6,0xE9,0xD8,0xB8,0xFA,0x09,0x1B,0xDC,0xB3,0x80,0x6E,
0x32,0x0A,0xDA,0xBB,0xE8,0x43,0x88,0x5B,0xAB,0xC3,0xB2,0x44,
0xE1,0x95,0x85,0x0A,0x0D,0x13,0xE2,0x02,0x1E,0x96,0x44,0xCF,
0xA0,0xD8,0x46,0x32,0x68,0x63,0x7F,0x68,0xB3,0x37,0x52,0xCE,
0x3A,0x4E,0x48,0x08,0x7F,0xD5,0x53,0x00,0x59,0xA8,0x2C,0xCB,
0x51,0x64,0x3D,0x5F,0xEF,0x0E,0x5F,0xE6,0xAF,0xD9,0x1E,0xA2,
0x35,0x64,0x37,0xD7,0x4C,0xC9,0x24,0xFD,0x2F,0x75,0xBB,0x3A,
0x15,0x82,0x76,0x4D,0xC2,0x8B,0x1E,0xB9,0x4B,0xA1,0x33,0xCF,
0xAA,0x3B,0x7C,0xC2,0x50,0x60,0x6F,0x45,0x69,0xD3,0x6B,0x88,
0x34,0x9B,0xE4,0xF8,0xC6,0xC7,0x5F,0x10,0xA1,0xBA,0x01,0x8C,
0xDA,0xD1,0xA3,0x59,0x9C,0x97,0xEA,0xC3,0xF6,0x02,0x55,0x5C,
0x92,0x1A,0x39,0x67,0x17,0xE2,0x9B,0x27,0x8D,0xE8,0x5C,0xE9,
0xA5,0x94,0xBB,0x7E,0x16,0x6F,0x53,0x5A,0x6D,0xD8,0x03,0xC2,
0xAC,0x7A,0xCD,0x22,0x98,0x8E,0x33,0x2A,0xDE,0xAB,0x12,0xC0,
0x0B,0x7C,0x0C,0x20,0x70,0xD9,0x0B,0xAE,0x0B,0x2F,0x20,0x9B,
0xA4,0xED,0xFD,0x49,0x0B,0xE3,0x4A,0xF6,0x28,0xB3,0x98,0xB0,
0x23,0x1C,0x09,0x33,
};
static const unsigned char dhg_2048[]={
0x02,
};
DH *dh = DH_new();
BIGNUM *dhp_bn, *dhg_bn;
if (dh == NULL)
return NULL;
dhp_bn = BN_bin2bn(dhp_2048, sizeof (dhp_2048), NULL);
dhg_bn = BN_bin2bn(dhg_2048, sizeof (dhg_2048), NULL);
if (dhp_bn == NULL || dhg_bn == NULL
|| !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn)) {
DH_free(dh);
BN_free(dhp_bn);
BN_free(dhg_bn);
return NULL;
}
return dh;
}
typedef struct {
char *id;
SSL_SESSION *session;
} ssl_cache_data;
#define SSL_CACHE_SIZE 4
static int ssl_cache_ptr = 0;
static ssl_cache_data ssl_cache[SSL_CACHE_SIZE];
static void ssn_init(void) {
ssl_cache_data s = {NULL, NULL};
for (int i=0; i<SSL_CACHE_SIZE; i++) {
ssl_cache[i] = s;
}
}
static void ssn_restore(pn_tls_t *ssl) {
if (!ssl->session_id) return;
for (int i = ssl_cache_ptr;;) {
i = (i==0) ? SSL_CACHE_SIZE-1 : i-1;
if (ssl_cache[i].id == NULL) return;
if (strcmp(ssl_cache[i].id, ssl->session_id) == 0) {
ssl_log( NULL, PN_LEVEL_TRACE, "Restoring previous session id=%s", ssl->session_id );
int rc = SSL_set_session( ssl->ssl, ssl_cache[i].session );
if (rc != 1) {
ssl_log( NULL, PN_LEVEL_WARNING, "Session restore failed, id=%s", ssl->session_id );
}
return;
}
if (i == ssl_cache_ptr) return;
}
}
/** Public API - visible to application code */
static bool ensure_initialized(void);
static bool pni_init_ssl_domain( pn_tls_config_t * domain, pn_tls_mode_t mode )
{
if (!ensure_initialized()) {
ssl_log_error("Unable to initialize OpenSSL library");
return false;
}
domain->ref_count = 1;
domain->mode = mode;
// enable all supported protocol versions, then explicitly disable the
// known vulnerable ones. This should allow us to use the latest version
// of the TLS standard that the installed library supports.
switch(mode) {
case PN_TLS_MODE_CLIENT:
domain->ctx = SSL_CTX_new(SSLv23_client_method()); // and TLSv1+
if (!domain->ctx) {
ssl_log_error("Unable to initialize OpenSSL context.");
return false;
}
SSL_CTX_set_session_cache_mode(domain->ctx, SSL_SESS_CACHE_CLIENT);
// By default, require peer name verification - this is a safe default
if (pn_tls_config_set_peer_authentication( domain, PN_TLS_VERIFY_PEER_NAME, NULL )) {
SSL_CTX_free(domain->ctx);
return false;
}
break;
case PN_TLS_MODE_SERVER:
domain->ctx = SSL_CTX_new(SSLv23_server_method()); // and TLSv1+
if (!domain->ctx) {
ssl_log_error("Unable to initialize OpenSSL context.");
return false;
}
// By default, allow anonymous ciphers and do no authentication so certificates are
// not required 'out of the box'; authenticating the client can be done by SASL.
if (pn_tls_config_set_peer_authentication( domain, PN_TLS_ANONYMOUS_PEER, NULL )) {
SSL_CTX_free(domain->ctx);
return false;
}
break;
default:
ssl_log(NULL, PN_LEVEL_ERROR, "Invalid value for pn_tls_mode_t: %d", mode);
return false;
}
// By default set up system default certificates
if (!SSL_CTX_set_default_verify_paths(domain->ctx)){
ssl_log_error("Failed to set default certificate paths");
SSL_CTX_free(domain->ctx);
return false;
};
const long reject_insecure =
SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
// Mitigate the CRIME vulnerability
# ifdef SSL_OP_NO_COMPRESSION
| SSL_OP_NO_COMPRESSION
# endif
;
SSL_CTX_set_options(domain->ctx, reject_insecure);
# ifdef SSL_SECOP_PEER
domain->default_seclevel = SSL_CTX_get_security_level(domain->ctx);
# endif
DH *dh = get_dh2048();
if (dh) {
SSL_CTX_set_tmp_dh(domain->ctx, dh);
DH_free(dh);
SSL_CTX_set_options(domain->ctx, SSL_OP_SINGLE_DH_USE);
}
return true;
}
// PROTON-2544: see earlier related push. Temporary only.
#pragma GCC diagnostic pop
pn_tls_config_t *pn_tls_config( pn_tls_mode_t mode )
{
pn_tls_config_t *domain = (pn_tls_config_t *) calloc(1, sizeof(pn_tls_config_t));
if (!domain) return NULL;
if (!pni_init_ssl_domain(domain, mode)) {
free(domain);
return NULL;
}
return domain;
}
void pn_tls_config_free( pn_tls_config_t *domain )
{
if (--domain->ref_count == 0) {
SSL_CTX_free(domain->ctx);
free(domain->keyfile_pw);
free(domain->trusted_CAs);
free(domain->ciphers);
free(domain->alpn_list);
free(domain);
}
}
int pn_tls_config_set_credentials( pn_tls_config_t *domain,
const char *certificate_file,
const char *private_key_file,
const char *password)
{
if (!domain || !domain->ctx) return -1;
if (SSL_CTX_use_certificate_chain_file(domain->ctx, certificate_file) != 1) {
ssl_log_error("SSL_CTX_use_certificate_chain_file( %s ) failed", certificate_file);
return -3;
}
if (password) {
domain->keyfile_pw = pni_strdup(password); // @todo: obfuscate me!!!
SSL_CTX_set_default_passwd_cb(domain->ctx, keyfile_pw_cb);
SSL_CTX_set_default_passwd_cb_userdata(domain->ctx, domain->keyfile_pw);
}
if (SSL_CTX_use_PrivateKey_file(domain->ctx, private_key_file, SSL_FILETYPE_PEM) != 1) {
ssl_log_error("SSL_CTX_use_PrivateKey_file( %s ) failed", private_key_file);
return -4;
}
if (SSL_CTX_check_private_key(domain->ctx) != 1) {
ssl_log_error("The key file %s is not consistent with the certificate %s",
private_key_file, certificate_file);
return -5;
}
domain->has_certificate = true;
// bug in older versions of OpenSSL: servers may request client cert even if anonymous
// cipher was negotiated. TLSv1 will reject such a request. Hack: once a cert is
// configured, allow only authenticated ciphers.
if (!domain->ciphers && !SSL_CTX_set_cipher_list( domain->ctx, CIPHERS_AUTHENTICATE )) {
ssl_log_error("Failed to set cipher list to %s", CIPHERS_AUTHENTICATE);
return -6;
}
return 0;
}
int pn_tls_config_set_impl_ciphers(pn_tls_config_t *domain, const char *ciphers)
{
if (!SSL_CTX_set_cipher_list(domain->ctx, ciphers)) {
ssl_log_error("Failed to set cipher list to %s", ciphers);
return -6;
}
if (domain->ciphers) free(domain->ciphers);
domain->ciphers = pni_strdup(ciphers);
return 0;
}
int pn_tls_config_set_trusted_certs(pn_tls_config_t *domain,
const char *certificate_db)
{
if (!domain) return -1;
// certificates can be either a file or a directory, which determines how it is passed
// to SSL_CTX_load_verify_locations()
struct stat sbuf;
if (stat( certificate_db, &sbuf ) != 0) {
ssl_log(NULL, PN_LEVEL_ERROR, "stat(%s) failed: %s", certificate_db, strerror(errno));
return -1;
}
const char *file;
const char *dir;
if (S_ISDIR(sbuf.st_mode)) {
dir = certificate_db;
file = NULL;
} else {
dir = NULL;
file = certificate_db;
}
if (SSL_CTX_load_verify_locations( domain->ctx, file, dir ) != 1) {
ssl_log_error("SSL_CTX_load_verify_locations( %s ) failed", certificate_db);
return -1;
}
return 0;
}
int pn_tls_config_set_peer_authentication(pn_tls_config_t *domain,
const pn_tls_verify_mode_t mode,
const char *trusted_CAs)
{