This repository has been archived by the owner on Aug 11, 2020. It is now read-only.
forked from bumptech/stud
-
Notifications
You must be signed in to change notification settings - Fork 9
/
stud.c
2067 lines (1757 loc) · 64.4 KB
/
stud.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 2011 Bump Technologies, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BUMP TECHNOLOGIES, INC. ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BUMP TECHNOLOGIES, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Bump Technologies, Inc.
*
**/
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <pwd.h>
#include <limits.h>
#include <syslog.h>
#include <stdarg.h>
#include <ctype.h>
#include <sched.h>
#include <signal.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/engine.h>
#include <openssl/asn1.h>
#include <ev.h>
#include "ringbuffer.h"
#include "shctx.h"
#include "configuration.h"
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif
/* For Mac OS X */
#ifndef TCP_KEEPIDLE
# ifdef TCP_KEEPALIVE
# define TCP_KEEPIDLE TCP_KEEPALIVE
# endif
#endif
#ifndef SOL_TCP
# define SOL_TCP IPPROTO_TCP
#endif
/* Do we have SNI support? */
#ifndef OPENSSL_NO_TLSEXT
#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
#define OPENSSL_NO_TLSEXT
#endif
#endif
/* Globals */
static struct ev_loop *loop;
static struct addrinfo *backaddr;
static pid_t master_pid;
static ev_io listener;
static int listener_socket;
static int child_num;
static pid_t *child_pids;
static SSL_CTX *default_ctx;
static SSL_SESSION *client_session;
#ifdef USE_SHARED_CACHE
static ev_io shcupd_listener;
static int shcupd_socket;
struct addrinfo *shcupd_peers[MAX_SHCUPD_PEERS+1];
static unsigned char shared_secret[SHA_DIGEST_LENGTH];
#endif /*USE_SHARED_CACHE*/
long openssl_version;
int create_workers;
stud_config *CONFIG;
static char tcp_proxy_line[128] = "";
/* What agent/state requests the shutdown--for proper half-closed
* handling */
typedef enum _SHUTDOWN_REQUESTOR {
SHUTDOWN_HARD,
SHUTDOWN_CLEAR,
SHUTDOWN_SSL
} SHUTDOWN_REQUESTOR;
#ifndef OPENSSL_NO_TLSEXT
/*
* SSL context linked list. Someday it might be nice to have a more clever data
* structure here, but assuming the number of SNI certs is small it probably
* doesn't matter.
*/
typedef struct ctx_list {
char *servername;
SSL_CTX *ctx;
struct ctx_list *next;
} ctx_list;
static ctx_list *sni_ctxs;
#endif /* OPENSSL_NO_TLSEXT */
/*
* Proxied State
*
* All state associated with one proxied connection
*/
typedef struct proxystate {
ringbuffer ring_ssl2clear; /* Pushing bytes from secure to clear stream */
ringbuffer ring_clear2ssl; /* Pushing bytes from clear to secure stream */
ev_io ev_r_ssl; /* Secure stream write event */
ev_io ev_w_ssl; /* Secure stream read event */
ev_io ev_r_handshake; /* Secure stream handshake write event */
ev_io ev_w_handshake; /* Secure stream handshake read event */
ev_io ev_w_connect; /* Backend connect event */
ev_io ev_r_clear; /* Clear stream write event */
ev_io ev_w_clear; /* Clear stream read event */
ev_io ev_proxy; /* proxy read event */
int fd_up; /* Upstream (client) socket */
int fd_down; /* Downstream (backend) socket */
int clear_connected:1; /* Clear stream is connected */
int sent_xff:1; /* Have sent X-Forwarded-For header */
int want_shutdown:1; /* Connection is half-shutdown */
int handshaked:1; /* Initial handshake happened */
int renegotiation:1; /* Renegotation is occuring */
int read_proxy_line:1;/* Read the HAProxy line from upstream */
SSL *ssl; /* OpenSSL SSL state */
struct sockaddr_storage remote_ip; /* Remote ip returned from `accept` or HAProxy line */
} proxystate;
#define LOG(...) \
do { \
if (!CONFIG->QUIET) fprintf(stdout, __VA_ARGS__); \
if (CONFIG->SYSLOG) syslog(LOG_INFO, __VA_ARGS__); \
} while(0)
#define ERR(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
if (CONFIG->SYSLOG) syslog(LOG_ERR, __VA_ARGS__); \
} while(0)
#define NULL_DEV "/dev/null"
/* Set a file descriptor (socket) to non-blocking mode */
static void setnonblocking(int fd) {
int flag = 1;
assert(ioctl(fd, FIONBIO, &flag) == 0);
}
/* set a tcp socket to use TCP Keepalive */
static void settcpkeepalive(int fd) {
int optval = 1;
socklen_t optlen = sizeof(optval);
if(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0) {
ERR("Error activating SO_KEEPALIVE on client socket: %s", strerror(errno));
}
optval = CONFIG->TCP_KEEPALIVE_TIME;
optlen = sizeof(optval);
#ifdef TCP_KEEPIDLE
if(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &optval, optlen) < 0) {
ERR("Error setting TCP_KEEPIDLE on client socket: %s", strerror(errno));
}
#endif
}
static void fail(const char* s) {
perror(s);
exit(1);
}
void die (char *fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
exit(1);
}
#ifndef OPENSSL_NO_DH
static int init_dh(SSL_CTX *ctx, const char *cert) {
DH *dh;
BIO *bio;
assert(cert);
bio = BIO_new_file(cert, "r");
if (!bio) {
ERR_print_errors_fp(stderr);
return -1;
}
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
if (!dh) {
ERR("{core} Note: no DH parameters found in %s\n", cert);
return -1;
}
LOG("{core} Using DH parameters from %s\n", cert);
SSL_CTX_set_tmp_dh(ctx, dh);
LOG("{core} DH initialized with %d bit key\n", 8*DH_size(dh));
DH_free(dh);
#ifndef OPENSSL_NO_EC
#ifdef NID_X9_62_prime256v1
EC_KEY *ecdh = NULL;
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
SSL_CTX_set_tmp_ecdh(ctx, ecdh);
EC_KEY_free(ecdh);
LOG("{core} ECDH Initialized with NIST P-256\n");
#endif /* NID_X9_62_prime256v1 */
#endif /* OPENSSL_NO_EC */
return 0;
}
#endif /* OPENSSL_NO_DH */
/* This callback function is executed while OpenSSL processes the SSL
* handshake and does SSL record layer stuff. It's used to trap
* client-initiated renegotiations.
*/
static void info_callback(const SSL *ssl, int where, int ret) {
(void)ret;
if (where & SSL_CB_HANDSHAKE_START) {
proxystate *ps = (proxystate *)SSL_get_app_data(ssl);
if (ps->handshaked) {
ps->renegotiation = 1;
LOG("{core} SSL renegotiation asked by client\n");
}
}
}
#ifdef USE_SHARED_CACHE
/* Handle incoming message updates */
static void handle_shcupd(struct ev_loop *loop, ev_io *w, int revents) {
(void) revents;
unsigned char msg[SHSESS_MAX_ENCODED_LEN], hash[EVP_MAX_MD_SIZE];
ssize_t r;
unsigned int hash_len;
uint32_t encdate;
long now = (time_t)ev_now(loop);
while ( ( r = recv(w->fd, msg, sizeof(msg), 0) ) > 0 ) {
/* msg len must be greater than 1 Byte of data + sig length */
if (r < (int)(1+sizeof(shared_secret)))
continue;
/* compute sig */
r -= sizeof(shared_secret);
HMAC(EVP_sha1(), shared_secret, sizeof(shared_secret), msg, r, hash, &hash_len);
if (hash_len != sizeof(shared_secret)) /* should never append */
continue;
/* check sign */
if(memcmp(msg+r, hash, hash_len))
continue;
/* msg len must be greater than 1 Byte of data + encdate length */
if (r < (int)(1+sizeof(uint32_t)))
continue;
/* drop too unsync updates */
r -= sizeof(uint32_t);
encdate = *((uint32_t *)&msg[r]);
if (!(abs((int)(int32_t)now-ntohl(encdate)) < SSL_CTX_get_timeout(default_ctx)))
continue;
shctx_sess_add(msg, r, now);
}
}
/* Send remote updates messages callback */
void shcupd_session_new(unsigned char *msg, unsigned int len, long cdate) {
unsigned int hash_len;
struct addrinfo **pai = shcupd_peers;
uint32_t ncdate;
/* add session creation encoded date to footer */
ncdate = htonl((uint32_t)cdate);
memcpy(msg+len, &ncdate, sizeof(ncdate));
len += sizeof(ncdate);
/* add msg sign */
HMAC(EVP_sha1(), shared_secret, sizeof(shared_secret),
msg, len, msg+len, &hash_len);
len += hash_len;
/* send msg to peers */
while (*pai) {
sendto(shcupd_socket, msg, len, 0, (*pai)->ai_addr, (*pai)->ai_addrlen);
pai++;
}
}
/* Compute a sha1 secret from an ASN1 rsa private key */
static int compute_secret(RSA *rsa, unsigned char *secret) {
unsigned char *buf,*p;
unsigned int length;
length = i2d_RSAPrivateKey(rsa, NULL);
if (length <= 0)
return -1;
p = buf = (unsigned char *)malloc(length*sizeof(unsigned char));
if (!buf)
return -1;
i2d_RSAPrivateKey(rsa,&p);
SHA1(buf, length, secret);
free(buf);
return 0;
}
/* Create udp socket to receive and send updates */
static int create_shcupd_socket() {
struct addrinfo *ai, hints;
struct addrinfo **pai = shcupd_peers;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
const int gai_err = getaddrinfo(CONFIG->SHCUPD_IP, CONFIG->SHCUPD_PORT,
&hints, &ai);
if (gai_err != 0) {
ERR("{getaddrinfo}: [%s]\n", gai_strerror(gai_err));
exit(1);
}
/* check if peers inet family addresses match */
while (*pai) {
if ((*pai)->ai_family != ai->ai_family) {
ERR("Share host and peers inet family differs\n");
exit(1);
}
pai++;
}
int s = socket(ai->ai_family, SOCK_DGRAM, IPPROTO_UDP);
if (s == -1)
fail("{socket: shared cache updates}");
int t = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &t, sizeof(int));
#ifdef SO_REUSEPORT
setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &t, sizeof(int));
#endif
setnonblocking(s);
if (ai->ai_addr->sa_family == AF_INET) {
struct ip_mreqn mreqn;
memset(&mreqn, 0, sizeof(mreqn));
mreqn.imr_multiaddr.s_addr = ((struct sockaddr_in *)ai->ai_addr)->sin_addr.s_addr;
if (CONFIG->SHCUPD_MCASTIF) {
if (isalpha(*CONFIG->SHCUPD_MCASTIF)) { /* appears to be an iface name */
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
if (strlen(CONFIG->SHCUPD_MCASTIF) > IFNAMSIZ) {
ERR("Error iface name is too long [%s]\n",CONFIG->SHCUPD_MCASTIF);
exit(1);
}
memcpy(ifr.ifr_name, CONFIG->SHCUPD_MCASTIF, strlen(CONFIG->SHCUPD_MCASTIF));
if (ioctl(s, SIOCGIFINDEX, &ifr)) {
fail("{ioctl: SIOCGIFINDEX}");
}
mreqn.imr_ifindex = ifr.ifr_ifindex;
}
else if (strchr(CONFIG->SHCUPD_MCASTIF,'.')) { /* appears to be an ipv4 address */
mreqn.imr_address.s_addr = inet_addr(CONFIG->SHCUPD_MCASTIF);
}
else { /* appears to be an iface index */
mreqn.imr_ifindex = atoi(CONFIG->SHCUPD_MCASTIF);
}
}
if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0) {
if (errno != EINVAL) { /* EINVAL if it is not a multicast address,
not an error we consider unicast */
fail("{setsockopt: IP_ADD_MEMBERSIP}");
}
}
else { /* this is a multicast address */
unsigned char loop = 0;
if(setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) < 0) {
fail("{setsockopt: IP_MULTICAST_LOOP}");
}
}
/* optional set sockopts for sending to multicast msg */
if (CONFIG->SHCUPD_MCASTIF &&
setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) < 0) {
fail("{setsockopt: IP_MULTICAST_IF}");
}
if (CONFIG->SHCUPD_MCASTTTL) {
unsigned char ttl;
ttl = (unsigned char)atoi(CONFIG->SHCUPD_MCASTTTL);
if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0) {
fail("{setsockopt: IP_MULTICAST_TTL}");
}
}
}
#ifdef IPV6_ADD_MEMBERSHIP
else if (ai->ai_addr->sa_family == AF_INET6) {
struct ipv6_mreq mreq;
memset(&mreq, 0, sizeof(mreq));
memcpy(&mreq.ipv6mr_multiaddr, &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr,
sizeof(mreq.ipv6mr_multiaddr));
if (CONFIG->SHCUPD_MCASTIF) {
if (isalpha(*CONFIG->SHCUPD_MCASTIF)) { /* appears to be an iface name */
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
if (strlen(CONFIG->SHCUPD_MCASTIF) > IFNAMSIZ) {
ERR("Error iface name is too long [%s]\n",CONFIG->SHCUPD_MCASTIF);
exit(1);
}
memcpy(ifr.ifr_name, CONFIG->SHCUPD_MCASTIF, strlen(CONFIG->SHCUPD_MCASTIF));
if (ioctl(s, SIOCGIFINDEX, &ifr)) {
fail("{ioctl: SIOCGIFINDEX}");
}
mreq.ipv6mr_interface = ifr.ifr_ifindex;
}
else { /* option appears to be an iface index */
mreq.ipv6mr_interface = atoi(CONFIG->SHCUPD_MCASTIF);
}
}
if (setsockopt(s, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
if (errno != EINVAL) { /* EINVAL if it is not a multicast address,
not an error we consider unicast */
fail("{setsockopt: IPV6_ADD_MEMBERSIP}");
}
}
else { /* this is a multicast address */
unsigned int loop = 0;
if(setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop)) < 0) {
fail("{setsockopt: IPV6_MULTICAST_LOOP}");
}
}
/* optional set sockopts for sending to multicast msg */
if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_IF,
&mreq.ipv6mr_interface, sizeof(mreq.ipv6mr_interface)) < 0) {
fail("{setsockopt: IPV6_MULTICAST_IF}");
}
if (CONFIG->SHCUPD_MCASTTTL) {
int hops;
hops = atoi(CONFIG->SHCUPD_MCASTTTL);
if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, sizeof(hops)) < 0) {
fail("{setsockopt: IPV6_MULTICAST_HOPS}");
}
}
}
#endif /* IPV6_ADD_MEMBERSHIP */
if (bind(s, ai->ai_addr, ai->ai_addrlen)) {
fail("{bind-socket}");
}
freeaddrinfo(ai);
return s;
}
#endif /*USE_SHARED_CACHE */
/*
* callback method for openssl config password handling, effectively just
* copies the user data pointer contents to the buffer. We pass the pointer
* to the config password entry in to the calling method
*/
int cfg_pw_callback(char *buf, int size, int rwflag, void *u) {
char *pw = (char*)u;
int pwlen = strlen(pw);
if (pwlen > size || pwlen <= 0) {
LOG("(config file password callback) Invalid config file password entry.");
return 0;
}
memset(buf, '\0', size);
memcpy(buf, pw, size);
return strlen(pw);
}
RSA *load_rsa_privatekey(SSL_CTX *ctx, const char *file) {
BIO *bio;
RSA *rsa;
bio = BIO_new_file(file, "r");
if (!bio) {
ERR_print_errors_fp(stderr);
return NULL;
}
if (CONFIG->PEM_KEYPASS != NULL) {
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, cfg_pw_callback,
(void*)CONFIG->PEM_KEYPASS);
} else {
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL,
ctx->default_passwd_callback, ctx->default_passwd_callback_userdata);
}
BIO_free(bio);
return rsa;
}
#ifndef OPENSSL_NO_TLSEXT
int is_servername_match(const char *servername, char *certname) {
if (strcasecmp(servername, certname) == 0) {
return 1;
} else {
if (strlen(certname) > 2 && strstr(certname, "*.") == certname) {
char *dot = strstr(servername, ".");
char *after_subdomain = strcasestr(servername, &certname[1]);
if (dot && dot == after_subdomain && strlen(after_subdomain) == strlen(&certname[1])) {
return 1;
}
}
}
return 0;
}
/*
* Switch the context of the current SSL object to the most appropriate one
* based on the SNI header
*/
int sni_switch_ctx(SSL *ssl, int *al, void *data) {
(void)data;
(void)al;
const char *servername;
const ctx_list *cl;
servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if (!servername) return SSL_TLSEXT_ERR_NOACK;
// For now, just compare servernames as case insensitive strings. Someday,
// it might be nice to Do The Right Thing around star certs.
for (cl = sni_ctxs; cl != NULL; cl = cl->next) {
if (is_servername_match(servername, cl->servername)) {
SSL_set_SSL_CTX(ssl, cl->ctx);
return SSL_TLSEXT_ERR_NOACK;
}
}
return SSL_TLSEXT_ERR_NOACK;
}
#endif /* OPENSSL_NO_TLSEXT */
/*
* Initialize an SSL context
*/
SSL_CTX *make_ctx(const char *pemfile) {
SSL_CTX *ctx;
RSA *rsa;
long ssloptions = SSL_OP_NO_SSLv2 | SSL_OP_ALL |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
#ifdef SSL_OP_NO_COMPRESSION
ssloptions |= SSL_OP_NO_COMPRESSION;
#endif
if (CONFIG->ETYPE == ENC_TLS) {
ctx = SSL_CTX_new((CONFIG->PMODE == SSL_CLIENT) ?
TLSv1_client_method() : TLSv1_server_method());
} else if (CONFIG->ETYPE == ENC_SSL) {
ctx = SSL_CTX_new((CONFIG->PMODE == SSL_CLIENT) ?
SSLv23_client_method() : SSLv23_server_method());
} else {
assert(CONFIG->ETYPE == ENC_TLS || CONFIG->ETYPE == ENC_SSL);
return NULL; // Won't happen, but gcc was complaining
}
SSL_CTX_set_options(ctx, ssloptions);
SSL_CTX_set_info_callback(ctx, info_callback);
if (CONFIG->CIPHER_SUITE) {
if (SSL_CTX_set_cipher_list(ctx, CONFIG->CIPHER_SUITE) != 1) {
ERR_print_errors_fp(stderr);
}
}
if (CONFIG->PREFER_SERVER_CIPHERS) {
SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
}
if (CONFIG->PMODE == SSL_CLIENT) {
return ctx;
}
/* SSL_SERVER Mode stuff */
if (SSL_CTX_use_certificate_chain_file(ctx, pemfile) <= 0) {
ERR_print_errors_fp(stderr);
exit(1);
}
rsa = load_rsa_privatekey(ctx, pemfile);
if (!rsa) {
ERR("Error loading rsa private key\n");
exit(1);
}
if (SSL_CTX_use_RSAPrivateKey(ctx, rsa) <= 0) {
ERR_print_errors_fp(stderr);
exit(1);
}
#ifndef OPENSSL_NO_DH
init_dh(ctx, pemfile);
#endif /* OPENSSL_NO_DH */
#ifndef OPENSSL_NO_TLSEXT
if (!SSL_CTX_set_tlsext_servername_callback(ctx, sni_switch_ctx)) {
ERR("Error setting up SNI support\n");
}
#endif /* OPENSSL_NO_TLSEXT */
#ifdef USE_SHARED_CACHE
if (CONFIG->SHARED_CACHE) {
if (shared_context_init(ctx, CONFIG->SHARED_CACHE) < 0) {
ERR("Unable to alloc memory for shared cache.\n");
exit(1);
}
if (CONFIG->SHCUPD_PORT) {
if (compute_secret(rsa, shared_secret) < 0) {
ERR("Unable to compute shared secret.\n");
exit(1);
}
/* Force tls tickets cause keys differs */
SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
if (*shcupd_peers) {
shsess_set_new_cbk(shcupd_session_new);
}
}
}
#endif
RSA_free(rsa);
return ctx;
}
/* Init library and load specified certificate.
* Establishes a SSL_ctx, to act as a template for
* each connection */
void init_openssl() {
SSL_library_init();
SSL_load_error_strings();
assert(CONFIG->CERT_FILES != NULL);
// The first file (i.e., the last file listed in config) is always the
// "default" cert
default_ctx = make_ctx(CONFIG->CERT_FILES->CERT_FILE);
#ifndef OPENSSL_NO_TLSEXT
{
struct cert_files *cf;
int i;
SSL_CTX *ctx;
X509 *x509;
BIO *f;
STACK_OF(GENERAL_NAME) *names = NULL;
GENERAL_NAME *name;
#define PUSH_CTX(asn1_str, ctx) \
do { \
struct ctx_list *cl; \
cl = calloc(1, sizeof(*cl)); \
ASN1_STRING_to_UTF8((unsigned char **)&cl->servername, asn1_str); \
cl->ctx = ctx; \
cl->next = sni_ctxs; \
sni_ctxs = cl; \
} while (0)
// Go through the list of PEMs and make some SSL contexts for them. We also
// keep track of the names associated with each cert so we can do SNI on
// them later
for (cf = CONFIG->CERT_FILES->NEXT; cf != NULL; cf = cf->NEXT) {
ctx = make_ctx(cf->CERT_FILE);
f = BIO_new(BIO_s_file());
// TODO: error checking
if (!BIO_read_filename(f, cf->CERT_FILE)) {
ERR("Could not read cert '%s'\n", cf->CERT_FILE);
}
x509 = PEM_read_bio_X509_AUX(f, NULL, NULL, NULL);
BIO_free(f);
// First, look for Subject Alternative Names
names = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL);
for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
name = sk_GENERAL_NAME_value(names, i);
if (name->type == GEN_DNS) {
PUSH_CTX(name->d.dNSName, ctx);
}
}
if (sk_GENERAL_NAME_num(names) > 0) {
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
// If we actally found some, don't bother looking any further
continue;
} else if (names != NULL) {
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
}
// Now we're left looking at the CN on the cert
X509_NAME *x509_name = X509_get_subject_name(x509);
i = X509_NAME_get_index_by_NID(x509_name, NID_commonName, -1);
if (i < 0) {
ERR("Could not find Subject Alternative Names or a CN on cert %s\n",
cf->CERT_FILE);
}
X509_NAME_ENTRY *x509_entry = X509_NAME_get_entry(x509_name, i);
PUSH_CTX(x509_entry->value, ctx);
}
}
#undef APPEND_CTX
#endif /* OPENSSL_NO_TLSEXT */
if (CONFIG->ENGINE) {
ENGINE *e = NULL;
ENGINE_load_builtin_engines();
if (!strcmp(CONFIG->ENGINE, "auto"))
ENGINE_register_all_complete();
else {
if ((e = ENGINE_by_id(CONFIG->ENGINE)) == NULL ||
!ENGINE_init(e) ||
!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
ERR_print_errors_fp(stderr);
exit(1);
}
LOG("{core} will use OpenSSL engine %s.\n", ENGINE_get_id(e));
ENGINE_finish(e);
ENGINE_free(e);
}
}
}
static void prepare_proxy_line(struct sockaddr* ai_addr) {
tcp_proxy_line[0] = 0;
char tcp6_address_string[INET6_ADDRSTRLEN];
if (ai_addr->sa_family == AF_INET) {
struct sockaddr_in* addr = (struct sockaddr_in*)ai_addr;
size_t res = snprintf(tcp_proxy_line,
sizeof(tcp_proxy_line),
"PROXY %%s %%s %s %%hu %hu\r\n",
inet_ntoa(addr->sin_addr),
ntohs(addr->sin_port));
assert(res < sizeof(tcp_proxy_line));
}
else if (ai_addr->sa_family == AF_INET6 ) {
struct sockaddr_in6* addr = (struct sockaddr_in6*)ai_addr;
inet_ntop(AF_INET6,&(addr->sin6_addr),tcp6_address_string,INET6_ADDRSTRLEN);
size_t res = snprintf(tcp_proxy_line,
sizeof(tcp_proxy_line),
"PROXY %%s %%s %s %%hu %hu\r\n",
tcp6_address_string,
ntohs(addr->sin6_port));
assert(res < sizeof(tcp_proxy_line));
}
else {
ERR("The --write-proxy mode is not implemented for this address family.\n");
exit(1);
}
}
char *prepare_xff_line(struct sockaddr* ai_addr) {
static char xff_line[128];
xff_line[0] = 0;
char tcp6_address_string[INET6_ADDRSTRLEN];
if (ai_addr->sa_family == AF_INET) {
struct sockaddr_in* addr = (struct sockaddr_in*)ai_addr;
size_t res = snprintf(xff_line,
sizeof(xff_line),
"X-Forwarded-For: %s\r\nX-Forwarded-Proto: https\r\n",
inet_ntoa(addr->sin_addr));
assert(res < sizeof(xff_line));
return xff_line;
}
else if (ai_addr->sa_family == AF_INET6 ) {
struct sockaddr_in6* addr = (struct sockaddr_in6*)ai_addr;
inet_ntop(AF_INET6,&(addr->sin6_addr),tcp6_address_string,INET6_ADDRSTRLEN);
size_t res = snprintf(xff_line,
sizeof(xff_line),
"X-Forwarded-For: %s\r\nX-Forwarded-Proto: https\r\n",
tcp6_address_string);
assert(res < sizeof(xff_line));
return xff_line;
}
else {
ERR("The --write-xff mode is not implemented for this address family.\n");
exit(1);
}
return NULL;
}
/* Create the bound socket in the parent process */
static int create_main_socket() {
struct addrinfo *ai, hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
const int gai_err = getaddrinfo(CONFIG->FRONT_IP, CONFIG->FRONT_PORT,
&hints, &ai);
if (gai_err != 0) {
ERR("{getaddrinfo}: [%s]\n", gai_strerror(gai_err));
exit(1);
}
int s = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
if (s == -1)
fail("{socket: main}");
int t = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &t, sizeof(int));
#ifdef SO_REUSEPORT
setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &t, sizeof(int));
#endif
setnonblocking(s);
if (bind(s, ai->ai_addr, ai->ai_addrlen)) {
fail("{bind-socket}");
}
#ifndef NO_DEFER_ACCEPT
#if TCP_DEFER_ACCEPT
int timeout = 1;
setsockopt(s, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(int) );
#endif /* TCP_DEFER_ACCEPT */
#endif
prepare_proxy_line(ai->ai_addr);
freeaddrinfo(ai);
listen(s, CONFIG->BACKLOG);
return s;
}
/* Initiate a clear-text nonblocking connect() to the backend IP on behalf
* of a newly connected upstream (encrypted) client*/
static int create_back_socket() {
int s = socket(backaddr->ai_family, SOCK_STREAM, IPPROTO_TCP);
if (s == -1)
return -1;
int flag = 1;
int ret = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
if (ret == -1) {
perror("Couldn't setsockopt to backend (TCP_NODELAY)\n");
}
setnonblocking(s);
return s;
}
/* Only enable a libev ev_io event if the proxied connection still
* has both up and down connected */
static void safe_enable_io(proxystate *ps, ev_io *w) {
if (!ps->want_shutdown)
ev_io_start(loop, w);
}
/* Only enable a libev ev_io event if the proxied connection still
* has both up and down connected */
static void shutdown_proxy(proxystate *ps, SHUTDOWN_REQUESTOR req) {
if (ps->want_shutdown || req == SHUTDOWN_HARD) {
ev_io_stop(loop, &ps->ev_w_ssl);
ev_io_stop(loop, &ps->ev_r_ssl);
ev_io_stop(loop, &ps->ev_w_handshake);
ev_io_stop(loop, &ps->ev_r_handshake);
ev_io_stop(loop, &ps->ev_w_connect);
ev_io_stop(loop, &ps->ev_w_clear);
ev_io_stop(loop, &ps->ev_r_clear);
ev_io_stop(loop, &ps->ev_proxy);
close(ps->fd_up);
close(ps->fd_down);
// Clear the SSL error queue - it might contain details
// of errors that we haven't consumed for whatever reason.
// If we don't, future calls to SSL_get_error will lead to
// weird/confusing results that can throw off the handling
// of normal conditions like SSL_ERROR_WANT_READ.
ERR_clear_error();
SSL_set_shutdown(ps->ssl, SSL_SENT_SHUTDOWN);
SSL_free(ps->ssl);
free(ps);
}
else {
ps->want_shutdown = 1;
if (req == SHUTDOWN_CLEAR && ringbuffer_is_empty(&ps->ring_clear2ssl))
shutdown_proxy(ps, SHUTDOWN_HARD);
else if (req == SHUTDOWN_SSL && ringbuffer_is_empty(&ps->ring_ssl2clear))
shutdown_proxy(ps, SHUTDOWN_HARD);
}
}
/* Handle various socket errors */
static void handle_socket_errno(proxystate *ps, int backend) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
return;
if (errno == ECONNRESET)
ERR("{%s} Connection reset by peer\n", backend ? "backend" : "client");
else if (errno == ETIMEDOUT)
ERR("{%s} Connection to backend timed out\n", backend ? "backend" : "client");
else if (errno == EPIPE)
ERR("{%s} Broken pipe to backend (EPIPE)\n", backend ? "backend" : "client");
else
perror("{backend} [errno]");
shutdown_proxy(ps, SHUTDOWN_CLEAR);
}