forked from bumptech/stud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stud.c
1901 lines (1608 loc) · 55.9 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 <ctype.h>
#include <sched.h>
#include <signal.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/engine.h>
#include <ev.h>
#include "ringbuffer.h"
#include "shctx.h"
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif
/* For Mac OS X */
#ifndef TCP_KEEPIDLE
# define TCP_KEEPIDLE TCP_KEEPALIVE
#endif
#ifndef SOL_TCP
# define SOL_TCP IPPROTO_TCP
#endif
#ifdef USE_SHARED_CACHE
#ifndef MAX_SHCUPD_PEERS
# define MAX_SHCUPD_PEERS 15
#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 *ssl_ctx;
#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];
typedef struct shcupd_peer_opt {
const char *ip;
const char *port;
} shcupd_peer_opt;
#endif /*USE_SHARED_CACHE*/
long openssl_version;
int create_workers;
/* Command line Options */
typedef enum {
ENC_TLS,
ENC_SSL
} ENC_TYPE;
typedef struct stud_options {
ENC_TYPE ETYPE;
int WRITE_IP_OCTET;
int WRITE_PROXY_LINE;
const char* CHROOT;
uid_t UID;
gid_t GID;
const char *FRONT_IP;
const char *FRONT_PORT;
const char *BACK_IP;
const char *BACK_PORT;
long NCORES;
const char *CERT_FILE;
const char *CIPHER_SUITE;
const char *ENGINE;
int BACKLOG;
#ifdef USE_SHARED_CACHE
int SHARED_CACHE;
const char *SHCUPD_IP;
const char *SHCUPD_PORT;
shcupd_peer_opt SHCUPD_PEERS[MAX_SHCUPD_PEERS+1];
const char *SHCUPD_MCASTIF;
const char *SHCUPD_MCASTTTL;
#endif
int QUIET;
int SYSLOG;
int TCP_KEEPALIVE_TIME;
int DAEMONIZE;
int PREFER_SERVER_CIPHERS;
} stud_options;
static stud_options OPTIONS = {
ENC_TLS, // ETYPE
0, // WRITE_IP_OCTET
0, // WRITE_PROXY_LINE
NULL, // CHROOT
0, // UID
0, // GID
NULL, // FRONT_IP
"8443", // FRONT_PORT
"127.0.0.1", // BACK_IP
"8000", // BACK_PORT
1, // NCORES
NULL, // CERT_FILE
NULL, // CIPHER_SUITE
NULL, // ENGINE
100, // BACKLOG
#ifdef USE_SHARED_CACHE
0, // SHARED_CACHE
NULL, // SHCUPD_IP
NULL, // SHCUPD_PORT
{ { NULL, NULL } }, // SHCUPD_PEERS
NULL, // SHCUPD_MCASTIF
NULL, // SHCUPD_MCASTTTL
#endif
0, // QUIET
0, // SYSLOG
3600, // TCP_KEEPALIVE_TIME
0, // DAEMONIZE
0 // PREFER_SERVER_CIPHERS
};
static char tcp_proxy_line[128] = "";
/* What agent/state requests the shutdown--for proper half-closed
* handling */
typedef enum _SHUTDOWN_REQUESTOR {
SHUTDOWN_HARD,
SHUTDOWN_DOWN,
SHUTDOWN_UP
} SHUTDOWN_REQUESTOR;
/*
* Proxied State
*
* All state associated with one proxied connection
*/
typedef struct proxystate {
ringbuffer ring_down; /* pushing bytes from client to backend */
ringbuffer ring_up; /* pushing bytes from backend to client */
ev_io ev_r_up; /* Upstream write event */
ev_io ev_w_up; /* Upstream read event */
ev_io ev_r_handshake; /* Downstream write event */
ev_io ev_w_handshake; /* Downstream read event */
ev_io ev_r_down; /* Downstream write event */
ev_io ev_w_down; /* Downstream read event */
int fd_up; /* Upstream (client) socket */
int fd_down; /* Downstream (backend) socket */
int want_shutdown:1; /* Connection is half-shutdown */
int handshaked:1; /* Initial handshake happened */
int renegotiation:1; /* Renegotation is occuring */
SSL *ssl; /* OpenSSL SSL state */
struct sockaddr_storage remote_ip; /* Remote ip returned from `accept` */
} proxystate;
#define LOG(...) \
do { \
if (!OPTIONS.QUIET) fprintf(stdout, __VA_ARGS__); \
if (OPTIONS.SYSLOG) syslog(LOG_INFO, __VA_ARGS__); \
} while(0)
#define ERR(...) \
do { \
fprintf(stderr, __VA_ARGS__); \
if (OPTIONS.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 = OPTIONS.TCP_KEEPALIVE_TIME;
optlen = sizeof(optval);
if(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &optval, optlen) < 0) {
ERR("Error setting TCP_KEEPIDLE on client socket: %s", strerror(errno));
}
}
static void fail(const char* s) {
perror(s);
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(ssl_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(OPTIONS.SHCUPD_IP, OPTIONS.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 (OPTIONS.SHCUPD_MCASTIF) {
if (isalpha(*OPTIONS.SHCUPD_MCASTIF)) { /* appears to be an iface name */
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
if (strlen(OPTIONS.SHCUPD_MCASTIF) > IFNAMSIZ) {
ERR("Error iface name is too long [%s]\n",OPTIONS.SHCUPD_MCASTIF);
exit(1);
}
memcpy(ifr.ifr_name, OPTIONS.SHCUPD_MCASTIF, strlen(OPTIONS.SHCUPD_MCASTIF));
if (ioctl(s, SIOCGIFINDEX, &ifr)) {
fail("{ioctl: SIOCGIFINDEX}");
}
mreqn.imr_ifindex = ifr.ifr_ifindex;
}
else if (strchr(OPTIONS.SHCUPD_MCASTIF,'.')) { /* appears to be an ipv4 address */
mreqn.imr_address.s_addr = inet_addr(OPTIONS.SHCUPD_MCASTIF);
}
else { /* appears to be an iface index */
mreqn.imr_ifindex = atoi(OPTIONS.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 (OPTIONS.SHCUPD_MCASTIF &&
setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) < 0) {
fail("{setsockopt: IP_MULTICAST_IF}");
}
if (OPTIONS.SHCUPD_MCASTTTL) {
unsigned char ttl;
ttl = (unsigned char)atoi(OPTIONS.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 (OPTIONS.SHCUPD_MCASTIF) {
if (isalpha(*OPTIONS.SHCUPD_MCASTIF)) { /* appears to be an iface name */
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
if (strlen(OPTIONS.SHCUPD_MCASTIF) > IFNAMSIZ) {
ERR("Error iface name is too long [%s]\n",OPTIONS.SHCUPD_MCASTIF);
exit(1);
}
memcpy(ifr.ifr_name, OPTIONS.SHCUPD_MCASTIF, strlen(OPTIONS.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(OPTIONS.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 (OPTIONS.SHCUPD_MCASTTTL) {
int hops;
hops = atoi(OPTIONS.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 */
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;
}
rsa = PEM_read_bio_RSAPrivateKey(bio, NULL,
ctx->default_passwd_callback, ctx->default_passwd_callback_userdata);
BIO_free(bio);
return rsa;
}
/* Init library and load specified certificate.
* Establishes a SSL_ctx, to act as a template for
* each connection */
static SSL_CTX * init_openssl() {
SSL_library_init();
SSL_load_error_strings();
SSL_CTX *ctx = NULL;
RSA *rsa;
long ssloptions = SSL_OP_NO_SSLv2 | SSL_OP_ALL |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
if (OPTIONS.ETYPE == ENC_TLS)
ctx = SSL_CTX_new(TLSv1_server_method());
else if (OPTIONS.ETYPE == ENC_SSL)
ctx = SSL_CTX_new(SSLv23_server_method());
else
assert(OPTIONS.ETYPE == ENC_TLS || OPTIONS.ETYPE == ENC_SSL);
#ifdef SSL_OP_NO_COMPRESSION
ssloptions |= SSL_OP_NO_COMPRESSION;
#endif
SSL_CTX_set_options(ctx, ssloptions);
SSL_CTX_set_info_callback(ctx, info_callback);
if (SSL_CTX_use_certificate_chain_file(ctx, OPTIONS.CERT_FILE) <= 0) {
ERR_print_errors_fp(stderr);
exit(1);
}
rsa = load_rsa_privatekey(ctx, OPTIONS.CERT_FILE);
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, OPTIONS.CERT_FILE);
#endif /* OPENSSL_NO_DH */
if (OPTIONS.ENGINE) {
ENGINE *e = NULL;
ENGINE_load_builtin_engines();
if (!strcmp(OPTIONS.ENGINE, "auto"))
ENGINE_register_all_complete();
else {
if ((e = ENGINE_by_id(OPTIONS.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);
}
}
if (OPTIONS.CIPHER_SUITE)
if (SSL_CTX_set_cipher_list(ctx, OPTIONS.CIPHER_SUITE) != 1)
ERR_print_errors_fp(stderr);
if (OPTIONS.PREFER_SERVER_CIPHERS)
SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
#ifdef USE_SHARED_CACHE
if (OPTIONS.SHARED_CACHE) {
if (shared_context_init(ctx, OPTIONS.SHARED_CACHE) < 0) {
ERR("Unable to alloc memory for shared cache.\n");
exit(1);
}
if (OPTIONS.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;
}
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);
}
}
/* 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(OPTIONS.FRONT_IP, OPTIONS.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}");
}
#if TCP_DEFER_ACCEPT
int timeout = 1;
setsockopt(s, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(int) );
#endif /* TCP_DEFER_ACCEPT */
prepare_proxy_line(ai->ai_addr);
freeaddrinfo(ai);
listen(s, OPTIONS.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");
}
int t = 1;
setnonblocking(s);
t = connect(s, backaddr->ai_addr, backaddr->ai_addrlen);
if (t == 0 || errno == EINPROGRESS || errno == EINTR)
return s;
perror("{backend-connect}");
return -1;
}
/* 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_up);
ev_io_stop(loop, &ps->ev_r_up);
ev_io_stop(loop, &ps->ev_w_handshake);
ev_io_stop(loop, &ps->ev_r_handshake);
ev_io_stop(loop, &ps->ev_w_down);
ev_io_stop(loop, &ps->ev_r_down);
close(ps->fd_up);
close(ps->fd_down);
SSL_set_shutdown(ps->ssl, SSL_SENT_SHUTDOWN);
SSL_free(ps->ssl);
free(ps);
}
else {
ps->want_shutdown = 1;
if (req == SHUTDOWN_DOWN && ringbuffer_is_empty(&ps->ring_up))
shutdown_proxy(ps, SHUTDOWN_HARD);
else if (req == SHUTDOWN_UP && ringbuffer_is_empty(&ps->ring_down))
shutdown_proxy(ps, SHUTDOWN_HARD);
}
}
/* Handle various socket errors */
static void handle_socket_errno(proxystate *ps) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
return;
if (errno == ECONNRESET)
ERR("{backend} Connection reset by peer\n");
else if (errno == ETIMEDOUT)
ERR("{backend} Connection to backend timed out\n");
else if (errno == EPIPE)
ERR("{backend} Broken pipe to backend (EPIPE)\n");
else
perror("{backend} [errno]");
shutdown_proxy(ps, SHUTDOWN_DOWN);
}
/* Read some data from the backend when libev says data is available--
* write it into the upstream buffer and make sure the write event is
* enabled for the upstream socket */
static void back_read(struct ev_loop *loop, ev_io *w, int revents) {
(void) revents;
int t;
proxystate *ps = (proxystate *)w->data;
if (ps->want_shutdown) {
ev_io_stop(loop, &ps->ev_r_down);
return;
}
int fd = w->fd;
char * buf = ringbuffer_write_ptr(&ps->ring_up);
t = recv(fd, buf, RING_DATA_LEN, 0);
if (t > 0) {
ringbuffer_write_append(&ps->ring_up, t);
if (ringbuffer_is_full(&ps->ring_up))
ev_io_stop(loop, &ps->ev_r_down);
safe_enable_io(ps, &ps->ev_w_up);
}
else if (t == 0) {
LOG("{backend} Connection closed\n");
shutdown_proxy(ps, SHUTDOWN_DOWN);
}
else {
assert(t == -1);
handle_socket_errno(ps);
}
}
/* Write some data, previously received on the secure upstream socket,
* out of the downstream buffer and onto the backend socket */
static void back_write(struct ev_loop *loop, ev_io *w, int revents) {
(void) revents;
int t;
proxystate *ps = (proxystate *)w->data;
int fd = w->fd;
int sz;
assert(!ringbuffer_is_empty(&ps->ring_down));
char *next = ringbuffer_read_next(&ps->ring_down, &sz);
t = send(fd, next, sz, MSG_NOSIGNAL);
if (t > 0) {
if (t == sz) {
ringbuffer_read_pop(&ps->ring_down);
safe_enable_io(ps, &ps->ev_r_up);
if (ringbuffer_is_empty(&ps->ring_down)) {
if (ps->want_shutdown) {
shutdown_proxy(ps, SHUTDOWN_HARD);
return; // dealloc'd
}
ev_io_stop(loop, &ps->ev_w_down);
}
}
else {
ringbuffer_read_skip(&ps->ring_down, t);
}
}
else {
assert(t == -1);
handle_socket_errno(ps);
}
}
static void start_handshake(proxystate *ps, int err);
/* Continue/complete the asynchronous connect() before starting data transmission
* between front/backend */
static void handle_connect(struct ev_loop *loop, ev_io *w, int revents) {
(void) revents;
int t;
proxystate *ps = (proxystate *)w->data;
char tcp6_address_string[INET6_ADDRSTRLEN];
size_t written = 0;
t = connect(ps->fd_down, backaddr->ai_addr, backaddr->ai_addrlen);
if (!t || errno == EISCONN || !errno) {
/* INIT */
ev_io_stop(loop, &ps->ev_w_down);
ev_io_init(&ps->ev_r_down, back_read, ps->fd_down, EV_READ);
ev_io_init(&ps->ev_w_down, back_write, ps->fd_down, EV_WRITE);
start_handshake(ps, SSL_ERROR_WANT_READ); /* for client-first handshake */
ev_io_start(loop, &ps->ev_r_down);
if (OPTIONS.WRITE_PROXY_LINE) {
char *ring_pnt = ringbuffer_write_ptr(&ps->ring_down);
assert(ps->remote_ip.ss_family == AF_INET ||
ps->remote_ip.ss_family == AF_INET6);
if(ps->remote_ip.ss_family == AF_INET) {
struct sockaddr_in* addr = (struct sockaddr_in*)&ps->remote_ip;
written = snprintf(ring_pnt,
RING_DATA_LEN,
tcp_proxy_line,
"TCP4",
inet_ntoa(addr->sin_addr),
ntohs(addr->sin_port));
}
else if (ps->remote_ip.ss_family == AF_INET6) {
struct sockaddr_in6* addr = (struct sockaddr_in6*)&ps->remote_ip;
inet_ntop(AF_INET6,&(addr->sin6_addr),tcp6_address_string,INET6_ADDRSTRLEN);
written = snprintf(ring_pnt,
RING_DATA_LEN,
tcp_proxy_line,
"TCP6",
tcp6_address_string,
ntohs(addr->sin6_port));
}
ringbuffer_write_append(&ps->ring_down, written);
ev_io_start(loop, &ps->ev_w_down);
}
else if (OPTIONS.WRITE_IP_OCTET) {
char *ring_pnt = ringbuffer_write_ptr(&ps->ring_down);
assert(ps->remote_ip.ss_family == AF_INET ||
ps->remote_ip.ss_family == AF_INET6);
*ring_pnt++ = (unsigned char) ps->remote_ip.ss_family;
if (ps->remote_ip.ss_family == AF_INET6) {
memcpy(ring_pnt, &((struct sockaddr_in6 *) &ps->remote_ip)
->sin6_addr.s6_addr, 16U);
ringbuffer_write_append(&ps->ring_down, 1U + 16U);
} else {
memcpy(ring_pnt, &((struct sockaddr_in *) &ps->remote_ip)
->sin_addr.s_addr, 4U);
ringbuffer_write_append(&ps->ring_down, 1U + 4U);
}
ev_io_start(loop, &ps->ev_w_down);
}
}
else if (errno == EINPROGRESS || errno == EINTR || errno == EALREADY) {
/* do nothing, we'll get phoned home again... */
}
else {
perror("{backend-connect}");
shutdown_proxy(ps, SHUTDOWN_HARD);
}
}
/* Upon receiving a signal from OpenSSL that a handshake is required, re-wire
* the read/write events to hook up to the handshake handlers */
static void start_handshake(proxystate *ps, int err) {
ev_io_stop(loop, &ps->ev_r_up);
ev_io_stop(loop, &ps->ev_w_up);
if (err == SSL_ERROR_WANT_READ)
ev_io_start(loop, &ps->ev_r_handshake);
else if (err == SSL_ERROR_WANT_WRITE)
ev_io_start(loop, &ps->ev_w_handshake);
}
/* After OpenSSL is done with a handshake, re-wire standard read/write handlers
* for data transmission */
static void end_handshake(proxystate *ps) {
ev_io_stop(loop, &ps->ev_r_handshake);
ev_io_stop(loop, &ps->ev_w_handshake);
/* Disable renegotiation (CVE-2009-3555) */
if (ps->ssl->s3) {
ps->ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
}
ps->handshaked = 1;
/* if incoming buffer is not full */
if (!ringbuffer_is_full(&ps->ring_down))
safe_enable_io(ps, &ps->ev_r_up);
/* if outgoing buffer is not empty */
if (!ringbuffer_is_empty(&ps->ring_up))