-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathchtls.c
1978 lines (1841 loc) · 65.4 KB
/
chtls.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
/* Copyright © 2005, 2017-2023 Björn Victor (bjorn@victor.se) */
/* Bridge program for various Chaosnet implementations. */
/*
Licensed 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.
*/
#include "cbridge.h"
#include <openssl/x509v3.h>
// when to start warning about approaching cert expiry
#define TLS_CERT_EXPIRY_WARNING_DAYS 90
static int tls_cert_expiry_warning_days = TLS_CERT_EXPIRY_WARNING_DAYS;
extern u_short tls_myaddrs[];
extern int tls_n_myaddrs;
extern char tls_ca_file[];
extern char tls_key_file[];
extern char tls_cert_file[];
extern char tls_crl_file[];
extern int do_tls_ipv6;
extern int do_tls_server;
extern int tls_server_port;
extern int tls_debug;
static int tls_tcp_ursock; /* ur-socket to listen on (for server end) */
static int tls_write_record(struct tls_dest *td, u_char *buf, int len);
static void tls_wait_for_reconnect_signal(struct tls_dest *td);
static int validate_crl_file();
// Find the tls_myaddrs matching the other address
static u_short my_tls_myaddr(u_short other)
{
for (int i = 0; i < tls_n_myaddrs; i++) {
if ((tls_myaddrs[i] & 0xff00) == (other & 0xff00))
return tls_myaddrs[i];
}
return 0;
}
int
parse_tls_config_line()
{
char *tok = NULL;
while ((tok = strtok(NULL, " \t\r\n")) != NULL) {
if (strncmp(tok,"key",sizeof("key")) == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no key file specified\n"); return -1; }
strncpy(tls_key_file, tok, PATH_MAX);
} else if (strncmp(tok,"cert",sizeof("cert")) == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no cert file specified\n"); return -1; }
strncpy(tls_cert_file, tok, PATH_MAX);
} else if (strncmp(tok,"ca-chain",sizeof("ca-chain")) == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no ca-chain file specified\n"); return -1; }
strncpy(tls_ca_file, tok, PATH_MAX);
} else if (strncmp(tok,"crl",sizeof("crl")) == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no crl file specified\n"); return -1; }
strncpy(tls_crl_file, tok, PATH_MAX);
} else if (strcmp(tok,"expirywarn") == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no value for expirywarn specified\n"); return -1; }
if ((sscanf(tok, "%d", &tls_cert_expiry_warning_days) != 1) ||
(tls_cert_expiry_warning_days < 0) || (tls_cert_expiry_warning_days > 730)) {
fprintf(stderr,"tls: bad value %s for expirywarn specified\n", tok);
return -1;
}
} else if ((strncmp(tok,"myaddr",sizeof("myaddr")) == 0) ||
(strncmp(tok,"myaddrs",sizeof("myaddrs")) == 0)) {
tok = strtok(NULL, " \t\r\n");
if (tok == NULL) { fprintf(stderr,"tls: no address for myaddrs specified\n"); return -1; }
char *sp, *ep;
for (sp = tok, ep = index(tok, ','); ep != NULL; sp = ep+1, ep = index(ep+1, ',')) {
if (tls_n_myaddrs > TLSDEST_MAX) {
fprintf(stderr,"Error in tls \"myaddrs\" setting - too many addresses listed, max %d\n", TLSDEST_MAX);
return -1;
}
*ep = '\0'; // zap comma
if (strlen(sp) == 0) {
fprintf(stderr,"Syntax error in tls \"myaddrs\" setting - empty address?\n");
return -1;
}
if ((sscanf(sp, "%ho", &tls_myaddrs[tls_n_myaddrs]) != 1) || !valid_chaos_host_address(tls_myaddrs[tls_n_myaddrs])) {
fprintf(stderr,"tls: bad octal value %s for myaddrs specified\n", sp);
return -1;
}
tls_n_myaddrs++;
}
// add the single/last one
if (strlen(sp) == 0) {
fprintf(stderr,"Syntax error in tls \"myaddrs\" setting - empty address?\n");
return -1;
} else if ((sscanf(sp, "%ho", &tls_myaddrs[tls_n_myaddrs]) != 1) || !valid_chaos_host_address(tls_myaddrs[tls_n_myaddrs])) {
fprintf(stderr,"tls: bad octal value %s for myaddrs specified\n", sp);
return -1;
}
tls_n_myaddrs++;
}
else if (strncmp(tok,"server",sizeof("server")) == 0) {
tok = strtok(NULL, " \t\r\n");
if (tok != NULL)
tls_server_port = atoi(tok);
do_tls_server = 1;
} else if (strncmp(tok,"ipv6",sizeof("ipv6")) == 0) {
do_tls_ipv6 = 1;
} else if (strcasecmp(tok, "debug") == 0) {
tok = strtok(NULL, " \t\r\n");
if ((tok == NULL) || (strcasecmp(tok,"on") == 0) || (strcasecmp(tok,"yes") == 0))
tls_debug = 1;
else if ((strcasecmp(tok,"off") == 0) || (strcasecmp(tok,"no") == 0))
tls_debug = 0;
else {
fprintf(stderr,"tls: bad 'debug' arg %s specified\n", tok);
return -1;
}
} else {
fprintf(stderr,"bad tls keyword %s\n", tok);
return -1;
}
}
if ((tls_n_myaddrs == 0) && (mychaddr[0] != 0)) {
if (do_tls_server)
fprintf(stderr,"tls: server, but no myaddr parameter - defaulting to %#o\n", mychaddr[0]);
// default - see send_empty_sns below
tls_myaddrs[tls_n_myaddrs++] = mychaddr[0];
}
if (verbose) {
printf("Using TLS myaddrs %#o",tls_myaddrs[0]);
for (int i = 1; i < tls_n_myaddrs; i++)
printf(",%#o", tls_myaddrs[i]);
printf(", keyfile \"%s\", certfile \"%s\", ca-chain \"%s\"\n", tls_key_file, tls_cert_file, tls_ca_file);
if (do_tls_server)
printf(" and starting TLS server at port %d (%s)\n", tls_server_port, do_tls_ipv6 ? "IPv6+IPv4" : "IPv4");
}
return 0;
}
// send an empty SNS packet, just to let the other (server) end know our Chaos address and set up the route
void
send_empty_sns(struct tls_dest *td, u_short onbehalfof)
{
u_char pkt[CH_PK_MAXLEN];
struct chaos_header *ch = (struct chaos_header *)pkt;
// use correct source for this link
u_short src = td->tls_myaddr > 0 ? td->tls_myaddr : my_tls_myaddr(td->tls_addr);
u_short dst = td->tls_addr;
struct chroute *rt = find_in_routing_table(dst, 1, 0);
if (rt == NULL) {
if (tls_debug) fprintf(stderr,"Can't send SNS to %#o - no route found!\n", dst);
return;
} else if (onbehalfof != 0) {
src = onbehalfof;
} else
if (rt->rt_myaddr > 0)
src = rt->rt_myaddr;
if (verbose || debug || tls_debug)
fprintf(stderr,"Sending SNS from %#o (obh %#o) to %#o\n", src, onbehalfof, dst);
memset(pkt, 0, sizeof(pkt));
set_ch_opcode(ch, CHOP_SNS);
set_ch_destaddr(ch, dst);
set_ch_srcaddr(ch, src);
set_ch_nbytes(ch, 0);
send_chaos_pkt((u_char *)ch, ch_nbytes(ch)+CHAOS_HEADERSIZE);
}
// One server thread which listens for new connections,
// Client links: connect and wait for writers to ask for re-connection.
// One input thread which selects on all tls_sock fields.
// For input thread and for writers (through forward_on_link)
// - If error on client link, ask for re-connection
// - If error on server link, close/disable it (and wait for client to reconnect)
// @@@@ Probably tons of memory leaks in SSL library.
// @@@@ try mtrace()?
// See https://wiki.openssl.org/index.php/Simple_TLS_Server,
// https://github.com/CloudFundoo/SSL-TLS-clientserver
void init_openssl()
{
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
}
#if 0
// not used
static void cleanup_openssl()
{
EVP_cleanup();
}
#endif
// Returns the CN string of the cert - note that this is an internal pointer so make a copy if you need it
static u_char *
tls_get_cert_cn(X509 *cert)
{
// see https://github.com/iSECPartners/ssl-conservatory/blob/master/openssl/openssl_hostname_validation.c
int common_name_loc = -1;
X509_NAME_ENTRY *common_name_entry = NULL;
ASN1_STRING *common_name_asn1 = NULL;
char *common_name_str = NULL;
// Find the position of the CN field in the Subject field of the certificate
common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) cert), NID_commonName, -1);
if (common_name_loc < 0) {
if (tls_debug)
fprintf(stderr,"TLS get_cert_cn: can't find CN");
return NULL;
}
// Extract the CN field
common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) cert), common_name_loc);
if (common_name_entry == NULL) {
if (tls_debug)
fprintf(stderr,"TLS get_cert_cn: can't extract CN");
return NULL;
}
// Convert the CN field to a C string
common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
if (common_name_asn1 == NULL) {
if (tls_debug)
fprintf(stderr,"TLS get_cert_cn: can't convert CN to C string");
return NULL;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
common_name_str = (char *) ASN1_STRING_data(common_name_asn1);
#else
common_name_str = (char *) ASN1_STRING_get0_data(common_name_asn1);
#endif
// Make sure there isn't an embedded NUL character in the CN
if (ASN1_STRING_length(common_name_asn1) != strlen(common_name_str)) {
if (tls_debug)
fprintf(stderr,"TLS get_cert_cn: malformed CN (NUL in CN)\n");
return NULL; // MalformedCertificate;
}
return (u_char *)common_name_str;
}
static char *
get_dp_url(DIST_POINT *dp)
{
GENERAL_NAMES *gens;
GENERAL_NAME *gen;
int i, gtype;
ASN1_STRING *uri;
if (!dp->distpoint || dp->distpoint->type != 0)
return NULL;
gens = dp->distpoint->name.fullname;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
uri = (ASN1_STRING *)GENERAL_NAME_get0_value(gen, >ype);
if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
char *uptr = (char *)ASN1_STRING_get0_data(uri);
#else
char *uptr = (char *)ASN1_STRING_data(uri);
#endif
return uptr;
}
}
return NULL;
}
static char *
get_cert_crl_dp(X509 *cert)
{
STACK_OF(DIST_POINT) *crldp;
char *urlptr;
crldp = (STACK_OF(DIST_POINT) *)X509_get_ext_d2i(cert, NID_crl_distribution_points, NULL, NULL);
if (crldp == NULL) {
if (tls_debug) fprintf(stderr,"%s: no crl distribution points in cert\n", __func__);
return NULL;
}
int i;
for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
urlptr = get_dp_url(dp);
if (urlptr != NULL) {
return urlptr;
}
}
if (tls_debug) fprintf(stderr,"%s: found no crl distribution point in cert?\n", __func__);
return NULL;
}
static SSL_CTX *tls_create_some_context(const SSL_METHOD *method)
{
SSL_CTX *ctx;
ctx = SSL_CTX_new(method);
if (!ctx) {
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
return ctx;
}
static SSL_CTX *tls_create_client_context()
{
const SSL_METHOD *method;
method = SSLv23_client_method();
return tls_create_some_context(method);
}
static SSL_CTX *tls_create_server_context()
{
const SSL_METHOD *method;
method = SSLv23_server_method();
return tls_create_some_context(method);
}
static void tls_configure_context(SSL_CTX *ctx)
{
// Auto-select elliptic curve
#ifdef SSL_CTX_set_ecdh_auto
SSL_CTX_set_ecdh_auto(ctx, 1);
#endif
/* Set the key and cert */
if (SSL_CTX_use_certificate_file(ctx, tls_cert_file, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
if (SSL_CTX_use_PrivateKey_file(ctx, tls_key_file, SSL_FILETYPE_PEM) <= 0 ) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Check key and cert
if (SSL_CTX_check_private_key(ctx) != 1) {
fprintf(stderr,"Private key and certificate do not match\n");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Load CA cert chain
if (!SSL_CTX_load_verify_locations(ctx, tls_ca_file, NULL)) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Make sure to verify the peer (both server and client)
// Consider adding a callback to validate CN/subjectAltName?
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
// go up to "higher level CA"
SSL_CTX_set_verify_depth(ctx, 2);
// Set up for CRL checking
if (strlen(tls_crl_file) > 0) {
// Make a new store with X509_STORE_new to get stuff initialized properly.
// X509_STORE *store = SSL_CTX_get_cert_store(ctx);
X509_STORE *store = X509_STORE_new();
// This means we need to reload locations set up above
if (X509_STORE_load_locations(store, tls_ca_file, NULL) == 0) {
fprintf(stderr,"Failed to load CA file %s\n", tls_ca_file);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
FILE *crl_fd = fopen(tls_crl_file,"r");
if (crl_fd == NULL) {
// This should already be checked in main()
fprintf(stderr,"%%%% Can not open CRL file %s\n", tls_crl_file);
perror("fopen");
exit(EXIT_FAILURE);
}
// Read the crl data
X509_CRL *crl = PEM_read_X509_CRL(crl_fd, NULL, NULL, NULL);
fclose(crl_fd);
if (crl == NULL) {
fprintf(stderr,"%s: Failed to read CRL from file %s\n", __func__, tls_crl_file);
exit(EXIT_FAILURE);
}
if (X509_STORE_add_crl(store, crl) == 0) {
fprintf(stderr,"%%%% %s: Failed to add CRL to store\n", __func__);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
X509_STORE_set_get_issuer(store, X509_STORE_CTX_get1_issuer);
// Verify the leaf cert against CRL
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
// Update the SSL CTX store
SSL_CTX_set_cert_store(ctx, store);
// Now set up the verification params
if (SSL_CTX_set_purpose(ctx, X509_PURPOSE_ANY) == 0) { // @@@@ sloppy: server or client, depending
fprintf(stderr,"%%%% %s: Failed to set purpose\n", __func__);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
}
// Routes, tlsdest etc
void print_tlsdest_config()
{
int i, j;
char ip[INET6_ADDRSTRLEN];
PTLOCKN(tlsdest_lock,"tlsdest_lock");
printf("TLS destination config: %d links\n", tlsdest_len);
for (i = 0; i < tlsdest_len; i++) {
if (tlsdest[i].tls_sa.tls_saddr.sa_family != 0) {
ip46_ntoa(&tlsdest[i].tls_sa.tls_saddr, ip, sizeof(ip));
} else
strcpy(ip, "[none]");
printf(" dest %#o, name %s, myaddr %#o, ",
tlsdest[i].tls_addr,
tlsdest[i].tls_name,
tlsdest[i].tls_myaddr);
if (tlsdest[i].tls_serverp) printf("(server) ");
printf("host %s port %d",
ip,
ntohs((tlsdest[i].tls_sa.tls_saddr.sa_family == AF_INET
? tlsdest[i].tls_sa.tls_sin.sin_port
: tlsdest[i].tls_sa.tls_sin6.sin6_port)));
if (tlsdest[i].tls_muxed[0] != 0) {
printf(" mux %o",tlsdest[i].tls_muxed[0]);
for (j = 1; j < CHTLS_MAXMUX && tlsdest[i].tls_muxed[j] != 0; j++)
printf(",%o", tlsdest[i].tls_muxed[j]);
}
printf("\n");
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
}
// Should only be called by server (clients have their routes set up by config)
static struct chroute *
add_tls_route(int tindex, u_short srcaddr)
{
struct chroute * rt = NULL;
if (!tlsdest[tindex].tls_serverp) {
fprintf(stderr,"%%%% TLS: add_tls_route called by client code for index %d\n",
tindex);
abort();
}
PTLOCKN(rttbl_lock,"rttbl_lock");
// find any old entry (only host route, also nopath)
rt = find_in_routing_table(srcaddr, 1, 1);
if (rt != NULL) {
// old route exists
if (((rt->rt_link != LINK_TLS) || (rt->rt_type == RT_NOPATH)) && (rt->rt_type != RT_STATIC)) {
// @@@@ only if configured to switch link types
if (tls_debug || debug)
fprintf(stderr,"TLS: Old %s route to %#o found (type %s), updating to TLS Dynamic\n",
rt_linkname(rt->rt_link), srcaddr, rt_typename(rt->rt_type));
rt->rt_link = LINK_TLS;
rt->rt_type = RT_DYNAMIC;
rt->rt_cost = RTCOST_ASYNCH;
rt->rt_cost_updated = time(NULL);
} else if ((rt->rt_type == RT_STATIC) && (tls_debug || debug)) {
fprintf(stderr,"TLS: not updating static route to %#o via %#o (%s)\n",
srcaddr, rt->rt_braddr, rt_linkname(rt->rt_link));
}
} else if ((srcaddr & 0xff00) == (tlsdest[tindex].tls_myaddr & 0xff00)) {
// make a routing entry for host srcaddr through tls link at tlsindex
rt = add_to_routing_table(srcaddr, 0, tlsdest[tindex].tls_myaddr, RT_DYNAMIC, LINK_TLS, RTCOST_ASYNCH);
} else if (my_tls_myaddr(srcaddr) != 0) {
// Not same subnet as existing route, or new
u_short new = my_tls_myaddr(srcaddr);
if (tls_debug) fprintf(stderr,"TLS: adding NEW route using myaddr %#o for index %d\n", new, tindex);
rt = add_to_routing_table(srcaddr, 0, new, RT_DYNAMIC, LINK_TLS, RTCOST_ASYNCH);
} else {
if (1 || tls_debug)
fprintf(stderr,"%%%% TLS: asked to add route to %#o but wrong subnet (not matching tls_myaddrs) - not updating\n", srcaddr);
}
PTUNLOCKN(rttbl_lock,"rttbl_lock");
// Done with routing, now work on tlsdest
PTLOCKN(tlsdest_lock,"tlsdest_lock");
if (tlsdest[tindex].tls_addr == 0) {
if (tls_debug) fprintf(stderr,"TLS route addition updates tlsdest addr from %#o to %#o and myaddr from %#o to %#o\n",
tlsdest[tindex].tls_addr, srcaddr, tlsdest[tindex].tls_myaddr, my_tls_myaddr(srcaddr));
tlsdest[tindex].tls_addr = srcaddr;
tlsdest[tindex].tls_myaddr = my_tls_myaddr(srcaddr); // matching myaddr
}
else if (((tlsdest[tindex].tls_addr >> 8) == (srcaddr >> 8)) && (tlsdest[tindex].tls_addr != srcaddr)) {
// add multiplexed dest @@@@ maybe let this be configurable?
int j;
for (j = 0; j < CHTLS_MAXMUX && tlsdest[tindex].tls_muxed[j] != 0; j++);
if (j < CHTLS_MAXMUX) {
if (tls_debug) fprintf(stderr,"Adding %#o to mux list %d of tlsdest %d\n", srcaddr, j, tindex);
tlsdest[tindex].tls_muxed[j] = srcaddr;
tlsdest[tindex].tls_myaddr = my_tls_myaddr(srcaddr); // make sure myaddr matches
} else
fprintf(stderr,"%%%% Warning: Can not add %#o to mux list of tlsdest %d - list full, increase CHTLS_MAXMUX?\n", srcaddr, tindex);
} else if ((tlsdest[tindex].tls_addr != 0) && (tlsdest[tindex].tls_addr != srcaddr)) {
char ip[INET6_ADDRSTRLEN];
fprintf(stderr,"%%%% TLS link %d %s (%s) chaos address already known but route not found - updating from %#o to %#o\n",
tindex, tlsdest[tindex].tls_name, ip46_ntoa(&tlsdest[tindex].tls_sa.tls_saddr, ip, sizeof(ip)),
tlsdest[tindex].tls_addr, srcaddr);
// This is OK. Use the most recent.
tlsdest[tindex].tls_addr = srcaddr;
tlsdest[tindex].tls_myaddr = my_tls_myaddr(srcaddr); // matching myaddr
} else {
// nothing
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
return rt;
}
static void
close_tlsdest(struct tls_dest *td)
{
PTLOCKN(tlsdest_lock,"tlsdest_lock");
if ((td->tls_sock != 0) && td->tls_serverp) {
char ip6[INET6_ADDRSTRLEN];
fprintf(stderr,"TLS client %s connection closing: IP %s\n",
td->tls_name, ip46_ntoa(&td->tls_sa.tls_saddr, ip6, sizeof(ip6)));
}
if (td->tls_serverp) {
// forget remote sockaddr
memset((void *)&td->tls_sa.tls_saddr, 0, sizeof(td->tls_sa.tls_saddr));
// forget remote chaos addr
td->tls_addr = 0;
// forget any mux list
memset((void *)&td->tls_muxed, 0, sizeof(td->tls_muxed));
}
if (td->tls_ssl != NULL) {
SSL_free(td->tls_ssl);
td->tls_ssl = NULL;
}
if (td->tls_sock != 0) {
close(td->tls_sock);
td->tls_sock = 0;
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
}
void
close_tls_route(struct chroute *rt)
{
int i;
struct tls_dest *td = NULL;
if ((rt->rt_link == LINK_TLS) && (rt->rt_type != RT_NOPATH)) {
PTLOCKN(tlsdest_lock,"tlsdest_lock");
for (i = 0; i < tlsdest_len; i++) {
if (tlsdest[i].tls_addr == rt->rt_braddr) {
td = &tlsdest[i];
break;
}
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
if (td != NULL) {
if (tls_debug) fprintf(stderr,"TLS: closing link to bridge addr %#o\n", rt->rt_braddr);
close_tlsdest(td);
} else if (tls_debug) fprintf(stderr,"%%%% TLS: can't find TLS link to bridge addr %#o to close\n", rt->rt_braddr);
} else
fprintf(stderr,"%%%% TLS: asked to close TLS link to bridge addr %#o which is link %s type %s\n", rt->rt_braddr,
rt_linkname(rt->rt_link), rt_typename(rt->rt_type));
}
static void
update_client_tlsdest(struct tls_dest *td, u_char *server_cn, int tsock, SSL *ssl)
{
// defining the client link adds the tlsdest entry, but need to fill in and initialize mutex/conds
// fill in tls_name, tls_sock, tls_ssl
PTLOCKN(tlsdest_lock,"tlsdest_lock");
#if 0
// don't - we need the "IP name" of the server
if (server_cn != NULL)
strncpy(td->tls_name, (char *)server_cn, TLSDEST_NAME_LEN);
#endif
td->tls_serverp = 0;
td->tls_sock = tsock;
td->tls_ssl = ssl;
// initiate these
if (pthread_mutex_init(&td->tcp_reconnect_mutex, NULL) != 0)
perror("pthread_mutex_init(update_client_tlsdest)");
if (pthread_cond_init(&td->tcp_reconnect_cond, NULL) != 0)
perror("pthread_cond_init(update_client_tlsdest)");
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
}
static void
add_server_tlsdest(u_char *name, int sock, SSL *ssl, struct sockaddr *sa, int sa_len, u_short chaddr)
{
// no tlsdest exists for server end, until it is connected
struct tls_dest *td = NULL;
PTLOCKN(tlsdest_lock,"tlsdest_lock");
// look for name in tlsdest and reuse entry if it is closed
int i;
for (i = 0; i < tlsdest_len; i++) {
if ((tlsdest[i].tls_name[0] != '\0') && tlsdest[i].tls_serverp && (strncmp(tlsdest[i].tls_name, (char *)name, TLSDEST_NAME_LEN) == 0)) {
td = &tlsdest[i];
break;
}
}
if (td != NULL) {
if (tls_debug) fprintf(stderr,"Reusing tlsdest for %s\n", name);
// update sock and ssl
td->tls_sock = sock;
td->tls_ssl = ssl;
// get sockaddr
memcpy((void *)&td->tls_sa.tls_saddr, sa, sa_len);
} else {
// crete a new entry
if (tlsdest_len >= TLSDEST_MAX) {
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
fprintf(stderr,"%%%% tlsdest is full! Increase TLSDEST_MAX\n");
return;
}
if (tls_debug) {
char ip6[INET6_ADDRSTRLEN];
fprintf(stderr,"Adding new TLS destination %s from %s port %d chaddr %#o myaddr %#o\n", name,
ip46_ntoa(sa, ip6, sizeof(ip6)),
ntohs((sa->sa_family == AF_INET
? ((struct sockaddr_in *)sa)->sin_port
: ((struct sockaddr_in6 *)sa)->sin6_port)),
chaddr, my_tls_myaddr(chaddr));
}
memset(&tlsdest[tlsdest_len], 0, sizeof(struct tls_dest));
// get sockaddr
memcpy(&tlsdest[tlsdest_len].tls_sa, sa, sa_len);
if (name != NULL)
strncpy((char *)&tlsdest[tlsdest_len].tls_name, (char *)name, TLSDEST_NAME_LEN);
tlsdest[tlsdest_len].tls_serverp = 1;
tlsdest[tlsdest_len].tls_sock = sock;
tlsdest[tlsdest_len].tls_ssl = ssl;
tlsdest[tlsdest_len].tls_addr = chaddr;
tlsdest[tlsdest_len].tls_myaddr = my_tls_myaddr(chaddr);
tlsdest_len++;
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
if (verbose) print_tlsdest_config();
// add route when first pkt comes in, see tls_input
}
// TCP low-level things
static int tcp_server_accept(int sock, struct sockaddr_storage *saddr, u_int *sa_len)
{
struct sockaddr_storage caddr;
int fd;
u_int clen = sizeof(caddr);
u_int *slen = &clen;
struct sockaddr *sa = (struct sockaddr *)&caddr;
if ((saddr != NULL) && (*sa_len != 0)) {
// fill in sockaddr
sa = (struct sockaddr *)saddr;
slen = sa_len;
}
if ((fd = accept(sock, (struct sockaddr *)sa, slen)) < 0) {
perror("accept");
fprintf(stderr,"errno = %d\n", errno);
// @@@@ better error handling, back off and try again? what could go wrong here?
exit(1);
}
// @@@@ log stuff about the connection?
if (tls_debug) {
char ip6[INET6_ADDRSTRLEN];
fprintf(stderr,"TCP accept connection from %s port %d\n", ip46_ntoa(sa, ip6, sizeof(ip6)),
ntohs((sa->sa_family == AF_INET
? ((struct sockaddr_in *)sa)->sin_port
: ((struct sockaddr_in6 *)sa)->sin6_port)));
}
return fd;
}
static int tcp_bind_socket(int type, u_short port)
{
int sock;
if ((sock = socket(do_tls_ipv6 ? AF_INET6 : AF_INET, type, 0)) < 0) {
perror("socket (TCP) failed");
exit(1);
}
// @@@@ SO_REUSEADDR or SO_REUSEPORT
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR)");
if (tls_debug)
fprintf(stderr,"binding socket type %d (%s), %s, to port %d\n",
type, (type == SOCK_DGRAM ? "dgram" : (type == SOCK_STREAM ? "stream" : "?")),
do_tls_ipv6 ? "IPv6" : "IPv4",
port);
if (do_tls_ipv6) {
struct sockaddr_in6 sin6;
#if 0
// For TLS, allow both IPv4 and IPv6
int one = 1;
if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)) < 0)
perror("setsockopt(IPV6_V6ONLY)");
#endif
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(port);
memcpy(&sin6.sin6_addr, &in6addr_any, sizeof(in6addr_any));
if (bind(sock, (struct sockaddr *)&sin6, sizeof(sin6)) < 0) {
perror("bind(v6) failed");
exit(1);
}
} else {
struct sockaddr_in sin;
memset(&sin,0,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = INADDR_ANY;
if (bind(sock,(struct sockaddr *)&sin, sizeof(sin)) < 0) {
perror("bind() failed");
exit(1);
}
}
return sock;
}
// TCP connector, with backoff
static int tcp_client_connect(struct sockaddr *sin)
{
int sock, unlucky = 1, foo;
u_long ntimes = 0;
char ip[INET6_ADDRSTRLEN];
(void)ip46_ntoa(sin, ip, sizeof(ip));
while (unlucky) {
if (tls_debug) fprintf(stderr,"TCP connect: socket family %d (%s)\n",
sin->sa_family,
(sin->sa_family == AF_INET ? "IPv4" :
(sin->sa_family == AF_INET6 ? "IPv6" : "??")));
if ((sock = socket(sin->sa_family, SOCK_STREAM, 0)) < 0) {
perror("socket(tcp)");
exit(1);
}
if (tls_debug) {
fprintf(stderr,"TCP connect: connecting to %s port %d\n", ip,
ntohs((sin->sa_family == AF_INET
? ((struct sockaddr_in *)sin)->sin_port
: ((struct sockaddr_in6 *)sin)->sin6_port)));
}
if (connect(sock, sin, (sin->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) < 0) {
if (tls_debug) {
perror("connect (tcp)");
fprintf(stderr,"connect errno %d\n", errno);
}
// back off and try again - the other end might be down
if (tls_debug)
fprintf(stderr,"TCP connect: trying again in %d s\n", unlucky);
else if (ntimes == 3)
fprintf(stderr,"%%%% TLS: connection to %s failed %lu times, trying again in %d s\n", ip, ntimes, unlucky);
if ((foo = sleep(unlucky)) != 0) {
fprintf(stderr,"TCP connect: sleep returned %d\n", foo);
}
// Backoff: increase sleep until 30s, then go back to 10s
unlucky++;
ntimes++;
if (unlucky > 30) {
unlucky /= 3;
// This happens the first time after sleeping 465 seconds + connection timeouts
// then every 275 seconds + timeouts
fprintf(stderr,"%%%% TLS: connection to %s failed %lu times, but still retrying - is the server up?\n",
ip, ntimes);
}
if (close(sock) < 0)
perror("close(tcp_client_connect)");
continue;
}
else
unlucky = 0;
}
// log stuff about the connection
if (tls_debug) {
char ip[INET6_ADDRSTRLEN];
fprintf(stderr,"TCP connect: connected to %s port %d\n", ip,
ntohs((sin->sa_family == AF_INET
? ((struct sockaddr_in *)sin)->sin_port
: ((struct sockaddr_in6 *)sin)->sin6_port)));
}
return sock;
}
// TLS level things.
// TLS client connector thread.
// Take struct tls_dest *td
// Create a client context, connect to server, make TLS connection, fill in td, (add route?)
// and wait for others to ask for reconnection.
// Iterate.
void *tls_connector(void *arg)
{
struct tls_dest *td = (struct tls_dest *)arg;
SSL *ssl;
SSL_CTX *ctx = tls_create_client_context();
tls_configure_context(ctx);
int crl_expiry_warned = 0;
while (1) {
// @@@@ re-parse tlsdest?
if (tls_debug) {
char ip[INET6_ADDRSTRLEN];
fprintf(stderr,"TLS client: connecting to %s port %d\n",
ip46_ntoa(&td->tls_sa.tls_saddr, ip, sizeof(ip)),
ntohs((td->tls_sa.tls_saddr.sa_family == AF_INET
? ((struct sockaddr_in *)&td->tls_sa.tls_sin)->sin_port
: ((struct sockaddr_in6 *)&td->tls_sa.tls_sin6)->sin6_port)));
}
// connect to server
int tsock = tcp_client_connect((struct sockaddr *)(td->tls_sa.tls_saddr.sa_family == AF_INET ? (void *)&td->tls_sa.tls_sin : (void *)&td->tls_sa.tls_sin6));
if (tls_debug) {
char ip[INET6_ADDRSTRLEN];
fprintf(stderr,"TLS client: connected to %s (%s port %d)\n", td->tls_name,
ip46_ntoa(&td->tls_sa.tls_saddr, ip, sizeof(ip)),
ntohs((td->tls_sa.tls_saddr.sa_family == AF_INET
? ((struct sockaddr_in *)&td->tls_sa.tls_sin)->sin_port
: ((struct sockaddr_in6 *)&td->tls_sa.tls_sin6)->sin6_port)));
}
if (strlen(tls_crl_file) > 0) {
// Validate the CRL file. If it has expired, don't open the connection since validation will fail anyway.
if (validate_crl_file() < 0) {
if (crl_expiry_warned == 0) {
fprintf(stderr,"%%%% CRL file %s has expired - you must download a fresh copy.\n", tls_crl_file);
// But only warn once
crl_expiry_warned = 1;
}
close(tsock);
sleep(30); // Wait a while for it to get updated.
continue; // Try again
} else
crl_expiry_warned = 0; // If it hasn't expired, we haven't warned (it might now be updated)
}
if ((ssl = SSL_new(ctx)) == NULL) {
fprintf(stderr,"tls_connector: SSL_new failed");
ERR_print_errors_fp(stderr);
close(tsock);
continue; // try again
}
SSL_set_fd(ssl, tsock);
int v = 0;
if ((v = SSL_connect(ssl)) <= 0) {
fprintf(stderr,"%%%% Error: TLS connect (%s) failed (probably cert problem?)\n", td->tls_name);
ERR_print_errors_fp(stderr);
close(tsock);
SSL_free(ssl);
// just sleep and retry - maybe conn was dropped between connect and SSL_connect
// @@@@ count the number of times, and warn occasionally
sleep(3);
continue;
#if 0
// or just let this thread die?
pthread_exit(&(int){ 1 });
exit(1);
// don't just keep trying!
// continue;
#endif
}
X509 *ssl_server_cert = SSL_get_peer_certificate(ssl);
if(ssl_server_cert) {
long verifyresult;
verifyresult = SSL_get_verify_result(ssl);
if(verifyresult != X509_V_OK) {
X509_free(ssl_server_cert);
SSL_free(ssl);
close(tsock);
// @@@@ warn?
continue;
}
u_char *server_cn = tls_get_cert_cn(ssl_server_cert);
#if CHAOS_DNS
if (server_cn) {
u_short claddrs[4];
int i, naddrs = dns_addrs_of_name(server_cn, (u_short *)&claddrs, 4);
if (tls_debug) {
fprintf(stderr, "TLS server CN %s has %d Chaos address(es): ", server_cn, naddrs);
for (i = 0; i < naddrs; i++)
fprintf(stderr,"%#o ", claddrs[i]);
fprintf(stderr,"\n");
}
int found = 0;
// @@@@ check for private subnet addresses, which should not be in DNS?
for (i = 0; i < naddrs; i++) {
if (claddrs[i] == td->tls_addr) {
found = 1;
break;
}
}
if (!found) {
if (tls_debug || verbose || debug) {
if (naddrs < -1)
fprintf(stderr,"%%%% TLS: DNS error while looking up server CN:\n");
fprintf(stderr, "%% Warning: TLS server CN %s doesn't match Chaos address in TLS dest (%#o)\n", server_cn, td->tls_addr);
// one day, do something
}
X509_free(ssl_server_cert);
// just sleep and retry - maybe temporary DNS failure?
// @@@@ count the number of times, and warn occasionally
sleep(15);
continue;
#if 0
// close and terminate
SSL_free(ssl);
close(tsock);
pthread_exit(&(int){ 1 });
#endif
}
} else {
if (1 || tls_debug || verbose || debug) {
fprintf(stderr, "%%%% Error: TLS server has no CN in cert, for TLS dest %#o\n", td->tls_addr);
}
X509_free(ssl_server_cert);
// close and terminate
SSL_free(ssl);
close(tsock);
pthread_exit(&(int){ 1 });
}
#endif
// create tlsdest, fill in stuff
update_client_tlsdest(td, server_cn, tsock, ssl);
X509_free(ssl_server_cert);
// Send a SNS pkt to get route initiated (tell server about our Chaos address)
// SNS is supposed to be only for existing connections, but we
// can abuse it since the recipient is a cbridge - we handle it.
send_empty_sns(td, 0);
if (td->tls_muxed[0] != 0) {
// also send a SNS on behalf of all the muxed addresses, to add them to the tls routes of the server end
send_empty_sns(td, td->tls_muxed[0]);
int j;
for (j = 1; j < CHTLS_MAXMUX && td->tls_muxed[j] != 0; j++)
send_empty_sns(td, td->tls_muxed[j]);
}
// wait for someone to ask us to reconnect
tls_wait_for_reconnect_signal(td);
// close the old, go back and open new
close_tlsdest(td);
} else {
fprintf(stderr,"%%%% Fatal error: TLS client: no server cert (%s), closing\n", td->tls_name);
SSL_free(ssl);
close(tsock);
pthread_exit(&(int){ 1 });
exit(1);
// continue;
}
}
}
// signalling stuff
// @@@@ keep track of how often this is called, and if more than N times/second, back off,
// since it might be a sign of persistent errors.
static void tls_please_reopen_tcp(struct tls_dest *td, int inputp)
// called by tls_write_record, tls_read_record on failure
{
u_short chaddr = td->tls_addr;
// Remove the tls_ssl as soon as possible, to avoid other breakage
PTLOCKN(tlsdest_lock,"tlsdest_lock");
if (td->tls_ssl != NULL) {
SSL_free(td->tls_ssl);
td->tls_ssl = NULL;
}
PTUNLOCKN(tlsdest_lock,"tlsdest_lock");
// Count this as a lost/aborted pkt.
// Lost (on input):
// "The number of incoming packets from this subnet lost because the
// host had not yet read a previous packet out of the interface and
// consequently the interface could not capture the packet"
// Aborted (on output):
// "The number of transmissions to this subnet aborted by
// collisions or because the receiver was busy."
if ((chaddr >> 8) == 0) {
if (1 || tls_debug) {
fprintf(stderr,"TLS: bad call to tls_please_reopen_tcp: td %p tls_addr %#o (%#x), inputp %d, name \"%s\"\n",
td, chaddr, chaddr, inputp, td->tls_name);
print_tlsdest_config();