-
Notifications
You must be signed in to change notification settings - Fork 2
/
snip.c
1442 lines (1313 loc) · 54.6 KB
/
snip.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 (c) 2017 J Cody Baker. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include <event2/thread.h>
#include <event2/event.h>
#include <event2/dns.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include "config.h"
#include "compat.h"
#include "snip.h"
#include "tls.h"
#include "log.h"
#include "net_util.h"
#include "sys_util.h"
#include <pthread.h>
// Globals for signal handlers
int snip_should_reload = 0;
// Constants
const struct timeval snip_shutdown_timeout = {5, 0};
// If we need to send an alert prior to parsing a version from the ClientHello, use this version.
static const snip_tls_version_t SNIP_TLS_ALERT_VERSION_DEFAULT = {3, 1}; // TLS 1.0
// TLS < 1.0 does not support server_name extension.
static const snip_tls_version_t SNIP_TLS_MINIMUM_SERVER_NAME_VERSION = {3, 1}; // TLS 1.0
// TLS 1.2 incorporates server_name into the RFC
static const snip_tls_version_t SNIP_TLS_GUARANTEED_SERVER_NAME_VERSION = {3, 3}; // TLS 1.2
/**
* Describe the life cycle of a socket.
*/
typedef enum snip_socket_state_e {
snip_socket_state_initial = 0,
snip_socket_state_connecting,
// server sockets start in connected after accept().
snip_socket_state_connected,
// a socket which is both finished sending, and has received an eof is automatically close()'d.
snip_socket_state_output_finished,
snip_socket_state_input_eof,
snip_socket_state_input_discard,
snip_socket_state_finished,
snip_socket_state_error
} snip_socket_state_t;
typedef enum snip_session_state_e {
snip_session_state_initial = 0,
snip_session_state_waiting_for_tls_client_hello,
snip_session_state_sni_hostname_found,
snip_session_state_no_sni_hostname_found,
snip_session_state_proxying,
snip_session_state_tls_protocol_error,
snip_session_state_waiting_for_connect
} snip_session_state_t;
/**
* Master context for TLS SNIp.
*/
typedef struct snip_context_e {
snip_config_t *config;
struct evdns_base *dns_base;
struct event_base *event_base;
pthread_t event_thread;
pthread_cond_t work_for_main_thread;
pthread_mutex_t context_lock;
int argc;
char **argv;
int shutting_down;
SNIP_BOOLEAN dropped_privileges;
uint64_t next_id;
} snip_context_t;
typedef struct snip_session_s {
uint64_t id;
// Reference back to the master context.
snip_context_t *context;
// These fields describe the inbound connection from the client.
struct bufferevent *client_bev;
snip_socket_state_t client_state;
struct sockaddr_storage client_address; // Hold the address locally in this structure.
size_t client_address_length;
char client_address_string[INET6_ADDRSTRLEN_WITH_PORT];
char client_local_address_string[INET6_ADDRSTRLEN_WITH_PORT];
// General description of this session
char *description;
// These field describe the
struct bufferevent *target_bev;
snip_socket_state_t target_state;
char *target_hostname;
uint16_t target_port;
struct sockaddr_storage target_address; // Hold the address locally in this structure.
size_t target_address_len;
char target_address_string[INET6_ADDRSTRLEN_WITH_PORT];
// Reference to the listener which created this session.
snip_config_listener_t *listener;
snip_tls_record_t current_record;
// Offset from the head of the input buffer where we should try reading our next record.
size_t current_record_parse_offset;
// Offset inside the current record where the next message fragment begins.
size_t current_record_read_offset;
snip_tls_handshake_message_parser_context_t handshake_message_parser_context;
snip_tls_handshake_message_t current_handshake_message;
snip_session_state_t state;
size_t sni_hostname_length;
const char *sni_hostname;
snip_tls_version_t client_version;
} snip_session_t;
// Local definitions
/**
* Handle disconnections and errors on the client channel.
* @param bev
* @param events
* @param ctx
*/
static void
snip_client_event_cb(
struct bufferevent *bev,
short events,
void *ctx
);
/**
* Handle disconnections and errors on the target channel.
* @param bev
* @param events
* @param ctx
*/
static void
snip_target_event_cb(
struct bufferevent *bev,
short events,
void *ctx
);
/**
* Handle incoming data on the client-connection.
* @param bev
* @param ctx
*/
static void
snip_client_read_cb(
struct bufferevent *bev,
void *ctx
);
/**
* Apply the given route to the open client connection.
* @param session
* @param route
*/
void
snip_session_apply_route(snip_session_t *session, snip_config_route_t *route);
/**
* Create an snip_session_t record.
* @return
*/
snip_session_t *
snip_session_create() {
snip_session_t *session = (snip_session_t *) malloc(sizeof(snip_session_t));
memset(session, '\0', sizeof(snip_session_t));
snip_tls_handshake_message_parser_context_init(&(session->handshake_message_parser_context));
return session;
}
/**
* Release, and if appropriate cleanup/free a snip_session_t record.
* @param session
*/
void
snip_session_destroy(
snip_session_t *session
) {
if(session->client_bev) {
bufferevent_free(session->client_bev);
}
if(session->target_bev) {
bufferevent_free(session->target_bev);
}
if(session->sni_hostname) {
free((void *) session->sni_hostname);
}
if(session->description) {
free(session->description);
}
if(session->listener) {
snip_config_release(session->listener->config);
session->listener = NULL;
}
if(session->target_hostname) {
free(session->target_hostname);
}
snip_tls_handshake_message_parser_context_reset(&(session->handshake_message_parser_context));
free(session);
}
/**
* Stop sending data and signal the shutdown on the target channel.
* @param session
*/
SNIP_BOOLEAN
snip_target_shutdown_input(snip_session_t *session) {
if(session->target_bev) {
if(session->target_state == snip_socket_state_connected ||
session->target_state == snip_socket_state_input_discard)
{
shutdown(bufferevent_getfd(session->target_bev), SHUT_RD);
return FALSE;
}
else if(session->target_state == snip_socket_state_output_finished) {
snip_session_destroy(session);
return TRUE;
}
}
return FALSE;
}
/**
* Stop sending data and signal the shutdown on the client channel.
* @param session
*/
SNIP_BOOLEAN
snip_client_shutdown_input(snip_session_t *session) {
if(session->client_bev) {
if(session->client_state == snip_socket_state_connected ||
session->client_state == snip_socket_state_input_discard)
{
shutdown(bufferevent_getfd(session->client_bev), SHUT_RD);
session->client_state = snip_socket_state_input_eof;
return FALSE;
}
else if(session->client_state == snip_socket_state_output_finished) {
snip_session_destroy(session);
return TRUE;
}
}
return FALSE;
}
/**
* Generate a description of the current connection state and store it in session->description.
* @param session
*/
void
snip_pair_set_description(snip_session_t *session) {
// This should only get longer each time, but lets be safe.
if(session->description) {
free(session->description);
session->description = NULL;
}
if(session->target_hostname) {
const char *format = "%016llX (%s->%s->%s:%hu)";
int needed = snprintf(NULL,
0,
format,
session->id,
session->client_address_string,
session->client_local_address_string,
session->target_hostname,
session->target_port
);
if(needed > 0) {
session->description = malloc((size_t) needed + 1);
memset(session->description, '\0', needed + 1);
needed = snprintf(session->description,
needed + 1,
format,
session->id,
session->client_address_string,
session->client_local_address_string,
session->target_hostname,
session->target_port
);
}
if(needed < 0) {
snip_log_fatal(SNIP_EXIT_ERROR_ASSERTION_FAILED, "Error creating description.");
}
}
else {
const char *format = "%016llX (%s->%s->!)";
int needed = snprintf(NULL,
0,
format,
session->id,
session->client_address_string,
session->client_local_address_string
);
if(needed > 0) {
session->description = malloc((size_t) needed + 1);
memset(session->description, '\0', needed + 1);
needed = snprintf(session->description,
needed + 1,
format,
session->id,
session->client_address_string,
session->client_local_address_string
);
}
if(needed < 0) {
snip_log_fatal(SNIP_EXIT_ERROR_ASSERTION_FAILED, "Error creating description.");
}
}
}
/**
* Determin the port we should connect to on the target. If the route we resolved doesn't specify a port, we return
* the port the client connected on.
* @param session
* @return
*/
uint16_t
snip_route_get_target_port(snip_session_t *session, snip_config_route_t *route) {
if(route->port) {
return route->port;
}
return session->listener->bind_port;
}
/**
* Handle incoming data on the client-connection.
* @param bev
* @param ctx
*/
static void
snip_target_read_cb(
struct bufferevent *bev,
void *ctx
) {
snip_session_t *session = (snip_session_t *) ctx;
struct evbuffer *input_from_target = bufferevent_get_input(bev);
if(session->client_bev) {
bufferevent_write_buffer(session->client_bev, input_from_target);
}
else {
// We close the read-stream when the matching output-buffer is gone, but that could still be pending. Discard.
struct evbuffer *input = bufferevent_get_input(bev);
evbuffer_drain(input, evbuffer_get_length(input));
}
}
/**
* Callback triggered when the output buffer on a bufferevent_socket is finished flushing.
* @param bev
* @param ctx
*/
void
snip_shutdown_write_buffer_on_flushed(struct bufferevent *bev, void *ctx) {
snip_session_t *session = (snip_session_t *) ctx;
// Safe to call this because we've already flushed the write buffer to 0.
shutdown(bufferevent_getfd(bev), SHUT_WR);
if(bev == session->target_bev) {
if(session->target_state == snip_socket_state_input_eof ||
session->target_state == snip_socket_state_input_discard)
{
session->target_state = snip_socket_state_finished;
session->target_bev = NULL;
bufferevent_free(bev);
}
else if(session->target_state == snip_socket_state_connected) {
session->target_state = snip_socket_state_output_finished;
}
}
else if(bev == session->client_bev) {
if(session->client_state == snip_socket_state_input_eof ||
session->client_state == snip_socket_state_input_discard)
{
session->client_state = snip_socket_state_finished;
session->client_bev = NULL;
bufferevent_free(bev);
}
else if(session->client_state == snip_socket_state_connected) {
session->client_state = snip_socket_state_output_finished;
}
}
else {
// This shouldn't happen, but if it does we should know it does.
snip_log_fatal(SNIP_EXIT_ERROR_ASSERTION_FAILED, "%s: Unexpected output-drained event.", session->description);
return;
}
if((!session->target_bev || session->target_state == snip_socket_state_output_finished) &&
(!session->client_bev || session->client_state == snip_socket_state_output_finished))
{
snip_session_destroy(session);
}
}
/**
* Finish writing any buffered data to the client socket, shutdown the output stream, and reevaluate.
* @param session
*/
void
snip_client_finish_writing(snip_session_t *session) {
struct evbuffer *output = bufferevent_get_output(session->client_bev);
size_t output_length = evbuffer_get_length(output);
if(session->target_bev) {
bufferevent_write_buffer(session->client_bev, bufferevent_get_input(session->target_bev));
}
bufferevent_setcb(
session->client_bev,
session->client_state != snip_socket_state_input_eof ? snip_client_read_cb : NULL,
output_length ? snip_shutdown_write_buffer_on_flushed : NULL, // write cb, triggered when the write buf is 0
snip_client_event_cb,
(void *) session
);
if(!output_length) {
// If the output buffer is already empty we won't get the callback and need to shut it down now.
snip_shutdown_write_buffer_on_flushed(session->client_bev, (void *) session);
}
}
/**
* Finish writing any buffered data to the target socket, shutdown the output stream, and reevaluate.
* @param session
*/
void
snip_target_finish_writing(snip_session_t *session) {
struct evbuffer *output = bufferevent_get_output(session->target_bev);
size_t output_length = evbuffer_get_length(output);
if (session->client_bev) {
bufferevent_write_buffer(session->target_bev, bufferevent_get_input(session->client_bev));
}
bufferevent_setcb(
session->target_bev,
session->target_state != snip_socket_state_input_eof ? snip_target_read_cb : NULL,
output_length ? snip_shutdown_write_buffer_on_flushed : NULL, // write cb, triggered when the write buf is 0
snip_target_event_cb,
(void *) session
);
if(!output_length) {
// If the output buffer is already empty we won't get the callback and need to shut it down now.
snip_shutdown_write_buffer_on_flushed(session->target_bev, (void *) session);
}
}
/**
* Handle disconnections and errors on the target channel.
* @param bev
* @param events
* @param ctx
*/
static void
snip_target_event_cb(
struct bufferevent *bev,
short events,
void *ctx
) {
snip_session_t *session = (snip_session_t *) ctx;
if(events & BEV_EVENT_CONNECTED) {
session->state = snip_session_state_proxying;
session->target_state = snip_socket_state_connected;
session->target_address_len = sizeof(struct sockaddr_storage);
int rv = getpeername(bufferevent_getfd(bev),
(struct sockaddr *) &(session->target_address),
(socklen_t *) &(session->target_address_len));
if(rv < 0 ||
(snip_sockaddr_to_string(session->target_address_string, (struct sockaddr *) &(session->target_address)) < 0))
{
// This should all be pretty safe, but JIC.
session->target_state = snip_socket_state_error;
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: Target connection succeeded but its address could not be decoded.",
session->description
);
snip_session_destroy(session);
}
snip_log(SNIP_LOG_LEVEL_INFO,
"%s: Target connection to (%s) succeeded.",
session->description,
session->target_address_string
);
// Ok we have what we need from the listener.
snip_config_release(session->listener->config);
session->listener = NULL;
}
else if (events & BEV_EVENT_ERROR) {
int dns_error = bufferevent_socket_get_dns_error(bev);
if(dns_error) {
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: Unable to resolve target DNS: (%d) - %s.",
session->description,
dns_error,
evutil_gai_strerror(dns_error));
}
else {
int error_number = EVUTIL_SOCKET_ERROR();
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: Target connection socket error (%d) - %s.",
session->description,
error_number,
evutil_socket_error_to_string(error_number)
);
// If there's anything left on the write buffer, nab it before we shutdown.
if(session->target_state >= snip_socket_state_connected)
{
session->target_state = snip_socket_state_error;
// If the client is still around, lets clean up our relationship with it.
if(session->client_bev) {
// We won't be able to output any more client-input. Stop reading.
if (session->client_state == snip_socket_state_connected ||
session->client_state == snip_socket_state_output_finished) {
if(snip_client_shutdown_input(session)) {
return;
}
}
// Similarly, we're done reading from the target. Finish writing to the client.
if (session->client_state == snip_socket_state_connected ||
session->client_state == snip_socket_state_input_eof ||
session->client_state == snip_socket_state_input_discard) {
snip_client_finish_writing(session);
}
bufferevent_free(session->target_bev);
session->target_bev = NULL;
}
}
else {
// If we never connected, there's nothing to relay. We may ultimately want to offer more polite failure
// notices here.
snip_session_apply_route(session, snip_get_route_for_proxy_connect_failure(session->listener));
}
}
}
else if (events & BEV_EVENT_EOF) {
snip_log(SNIP_LOG_LEVEL_INFO,
"%s: Target ended input.",
session->description
);
session->target_state = snip_socket_state_input_eof;
// Schedule any remaining target input for output
if(session->client_bev) {
snip_client_finish_writing(session);
}
}
}
/**
* Apply the given route to the open client connection.
* @param session
* @param route
*/
void
snip_session_apply_route(snip_session_t *session, snip_config_route_t *route) {
snip_context_t *context = session->context;
struct evbuffer *input_from_client = bufferevent_get_input(session->client_bev);
if(route->action == snip_route_action_proxy) {
session->target_state = snip_socket_state_connecting;
session->target_bev = bufferevent_socket_new(context->event_base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(
session->target_bev,
snip_target_read_cb,
NULL,
snip_target_event_cb,
(void*) session
);
bufferevent_enable(session->target_bev, EV_READ|EV_WRITE);
/* Copy all the data from the input buffer to the output buffer. */
bufferevent_write_buffer(session->target_bev, input_from_client);
session->target_port = snip_route_get_target_port(session, route);
session->target_hostname = snip_route_and_sni_hostname_to_target_hostname(route, session->sni_hostname);
snip_pair_set_description(session);
int address_family = AF_UNSPEC;
if(context->config->disable_ipv6) {
address_family = AF_INET;
}
else if(context->config->disable_ipv4) {
address_family = AF_INET6;
}
if(bufferevent_socket_connect_hostname(
session->target_bev,
context->dns_base,
address_family,
session->target_hostname,
session->target_port))
{
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: Error opening target connection to '%s'.",
session->description,
session->target_hostname);
snip_session_apply_route(session, snip_get_route_for_proxy_connect_failure(session->listener));
return;
};
session->state = snip_session_state_waiting_for_connect;
return;
}
else if(route->action == snip_route_action_send_file) {
if(session->client_state == snip_socket_state_connected) {
session->client_state = snip_socket_state_input_discard;
int source_file = open(route->send_file, O_RDONLY);
if(source_file < 0) {
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: failed to open source file: (%d) %s.",
session->description,
errno,
strerror(errno)
);
snip_session_apply_route(session, snip_get_route_for_proxy_connect_failure(session->listener));
return;
}
evbuffer_add_file(bufferevent_get_output(session->client_bev), source_file, 0, -1);
snip_client_finish_writing(session);
}
return;
}
else if(route->action == snip_route_action_send_text) {
if(session->client_state == snip_socket_state_connected) {
session->client_state = snip_socket_state_input_discard;
evbuffer_add(bufferevent_get_output(session->client_bev), route->send_text, strlen(route->send_text));
snip_client_finish_writing(session);
}
return;
}
else if(route->action == snip_route_action_tls_close_notify ||
route->action == snip_route_action_tls_fatal_unrecognized_name ||
route->action == snip_route_action_tls_fatal_internal_error ||
route->action == snip_route_action_tls_fatal_decode_error ||
route->action == snip_route_action_tls_fatal_protocol_version ||
route->action == snip_route_action_tls_fatal_handshake_failure)
{
if(session->client_state == snip_socket_state_connected ||
session->client_state == snip_socket_state_input_eof)
{
if(snip_client_shutdown_input(session)) {
return;
}
snip_tls_alert_t alert;
alert.level = snip_tls_alert_level_fatal;
if(route->action == snip_route_action_tls_close_notify) {
alert.description = snip_tls_alert_description_close_notify;
}
else if(route->action == snip_route_action_tls_fatal_unrecognized_name) {
// TLS 1.2 (3,3) incorporates the server_name extension. We can definitely send the "unrecognized_name"
// alert. If we don't have a client_version, we haven't gotten a ClientHello BUT the config is telling
// us to send this. DO IT!
if(SNIP_TLS_COMPARE_TLS_VERSION(session->client_version, >, SNIP_TLS_GUARANTEED_SERVER_NAME_VERSION) ||
session->client_version.major == 0)
{
alert.description = snip_tls_alert_description_unrecognized_name;
}
// These versions 1.1 and 1.0 MAY include the extension. Only send it if we got an sni_hostname from
// the client.
else if(SNIP_TLS_COMPARE_TLS_VERSION(session->client_version,
>,
SNIP_TLS_MINIMUM_SERVER_NAME_VERSION) &&
session->sni_hostname)
{
alert.description = snip_tls_alert_description_unrecognized_name;
}
// These versions don't look to support SNI. Send an internal error.
else
{
// These
alert.description = snip_tls_alert_description_internal_error;
}
}
else if(route->action == snip_route_action_tls_fatal_internal_error) {
alert.description = snip_tls_alert_description_internal_error;
}
else if(route->action == snip_route_action_tls_fatal_decode_error) {
alert.description = snip_tls_alert_description_decode_error;
}
else if(route->action == snip_route_action_tls_fatal_protocol_version) {
alert.description = snip_tls_alert_description_protocol_version;
}
else if(route->action == snip_route_action_tls_fatal_handshake_failure) {
alert.description = snip_tls_alert_description_handshake_failure;
}
snip_tls_alert_encode(
bufferevent_get_output(session->client_bev),
&alert,
session->client_version.major ? &session->client_version : &SNIP_TLS_ALERT_VERSION_DEFAULT);
snip_client_finish_writing(session);
}
}
else {
// TODO - Right now we're implementing all other actions as a hangup. Implement TLS Alert protocol.
snip_log(SNIP_LOG_LEVEL_INFO, "%s: Hanging up.", session->description);
if(session->client_state == snip_socket_state_connected) {
session->client_state = snip_socket_state_input_discard;
}
snip_session_destroy(session);
}
}
/**
* Determine if the input buffer looks to contain HTTP data.
* @param session
* @return TRUE if we suspect HTTP, FALSE otherwise.
*/
SNIP_BOOLEAN
snip_session_is_client_http(snip_session_t *session) {
// So it looks like this isn't TLS, or at least isn't a version we know. It may be that the client
// connected with HTTP, in which case we can at least provide a helpful error. Apache does something
// similar.
struct evbuffer *input = bufferevent_get_input(session->client_bev);
const size_t HTTP_HINT_LENGTH = 5;
if(evbuffer_get_length(input) < HTTP_HINT_LENGTH) {
return FALSE;
}
const unsigned char *buffer = evbuffer_pullup(input, HTTP_HINT_LENGTH);
if(buffer && (!memcmp(buffer, "GET /", HTTP_HINT_LENGTH) ||
!memcmp(buffer, "POST ", HTTP_HINT_LENGTH) ||
!memcmp(buffer, "HEAD ", HTTP_HINT_LENGTH)))
{
return TRUE;
}
return FALSE;
}
/**
* Handle incoming data on the client-connection.
* @param bev
* @param ctx
*/
static void
snip_client_read_cb(
struct bufferevent *bev,
void *ctx
) {
snip_session_t *session = (snip_session_t *) ctx;
// Initially we're just peeking on the request, so we don't remove anything from the input buffer until we
// understand where the client is trying to get, and have connected to their ultimate destination.
snip_context_t *context = session->context;
struct evbuffer *input_from_client = bufferevent_get_input(bev);
while(TRUE) {
// In a few cases we want to hold the read channel open, but discard anything the remote sends.
if(session->client_state == snip_socket_state_input_discard ||
session->client_state == snip_socket_state_input_eof)
{
evbuffer_drain(input_from_client, evbuffer_get_length(input_from_client));
return;
}
if(session->state == snip_session_state_initial) {
snip_tls_record_reset(&(session->current_record));
session->state = snip_session_state_waiting_for_tls_client_hello;
}
else if (session->state == snip_session_state_waiting_for_tls_client_hello) {
snip_parser_state_t record_parser_state = snip_tls_record_get_next(
input_from_client,
&(session->current_record_parse_offset),
&(session->current_record));
if(record_parser_state == snip_parser_state_error) {
session->state = snip_session_state_tls_protocol_error;
}
else if(record_parser_state == snip_parser_state_more_data_needed) {
// We added the data we have, but it didn't make a full record. Wait for more. Stay in the same state.
return;
}
else if(record_parser_state == snip_parser_state_parsed) {
if(session->current_record.content_type == snip_tls_record_type_handshake) {
// Cool, this is what we're expecting.
snip_parser_state_t handshake_message_parse_state = snip_tls_handshake_message_parser_add_record(
&(session->handshake_message_parser_context),
&(session->current_handshake_message),
&(session->current_record),
&(session->current_record_read_offset)
);
if(handshake_message_parse_state == snip_parser_state_more_data_needed) {
// The record did not contain a complete message. We're still waiting for the TLS ClientHello.
// If we restart this state-handler, we can read more data in.
continue;
}
else if(handshake_message_parse_state == snip_parser_state_parsed) {
// The first message MUST be a ClientHello.
if(session->current_handshake_message.type != snip_tls_handshake_message_type_client_hello) {
session->state = snip_session_state_tls_protocol_error;
continue;
}
// Blobs referenced in this client_hello are only safe until we manip the input evbuffer.
snip_tls_client_hello_t client_hello;
snip_tls_client_hello_reset(&client_hello);
snip_parser_state_t client_hello_parse_state =
snip_tls_client_hello_parser(&(session->current_handshake_message), &client_hello);
if(client_hello_parse_state != snip_parser_state_parsed) {
session->state = snip_session_state_tls_protocol_error;
continue;
}
// Save this for logging.
session->client_version = client_hello.client_version;
snip_parser_state_t server_name_parse_state = snip_tls_client_hello_find_server_name(
&client_hello,
snip_tls_client_hello_server_name_type_hostname,
(const unsigned char * *) &( session->sni_hostname),
&(session->sni_hostname_length)
);
// We're done with this message. Cleanup.
snip_tls_handshake_message_parser_context_reset(&session->handshake_message_parser_context);
snip_tls_handshake_message_reset(&session->current_handshake_message);
snip_log(SNIP_LOG_LEVEL_DEBUG,
"%s: Got ClientHello TLS(%hhu,%hhu) SNI: '%s'.",
session->description,
session->client_version.major,
session->client_version.minor,
session->sni_hostname);
if(server_name_parse_state == snip_parser_state_parsed) {
session->state = snip_session_state_sni_hostname_found;
continue;
}
else if(server_name_parse_state == snip_parser_state_not_found) {
session->state = snip_session_state_no_sni_hostname_found;
continue;
}
else {
session->state = snip_session_state_tls_protocol_error;
continue;
}
}
}
else if(session->current_record.content_type == snip_tls_record_type_alert) {
}
else {
session->state = snip_session_state_tls_protocol_error;
}
}
}
else if(session->state == snip_session_state_sni_hostname_found) {
snip_session_apply_route(session,
snip_find_route_for_sni_hostname(session->listener, session->sni_hostname));
}
else if (session->state == snip_session_state_no_sni_hostname_found) {
snip_session_apply_route(session, snip_get_route_for_no_sni(session->listener));
}
else if(session->state == snip_session_state_proxying ||
session->state == snip_session_state_waiting_for_connect)
{
bufferevent_write_buffer(session->target_bev, input_from_client);
return;
}
else if(session->state == snip_session_state_tls_protocol_error) {
if(snip_session_is_client_http(session)) {
// This content looks like HTTP, we can direct them an HTTP server, or display an error, or redirect.
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: TLS Protocol Error. Input looks like HTTP.",
session->description
);
snip_session_apply_route(session, snip_get_route_for_http_fallback(session->listener));
}
else {
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: TLS Protocol Error.",
session->description
);
snip_session_apply_route(session, snip_get_route_for_tls_error(session->listener));
}
return;
}
}
}
/**
* Handle disconnections and errors on the client channel.
* @param bev
* @param events
* @param ctx
*/
static void
snip_client_event_cb(
struct bufferevent *bev,
short events,
void *ctx
) {
snip_session_t *session = (snip_session_t *) ctx;
if (events & BEV_EVENT_ERROR) {
int error_number = EVUTIL_SOCKET_ERROR();
snip_log(SNIP_LOG_LEVEL_WARNING,
"%s: Client connection failed: Socket error (%d) - %s.",
session->description,
error_number,
evutil_socket_error_to_string(error_number)
);
session->client_state = snip_socket_state_error;
// If the target is active, lets clean up our relationship with it.
if(session->target_bev) {
// We won't be able to output any more target-input. Stop reading from the target.
if (session->target_state== snip_socket_state_connected ||
session->target_state== snip_socket_state_output_finished) {
snip_target_shutdown_input(session);
}
// Similarly, we're done reading from the client. Finish writing to the target.
if (session->target_state == snip_socket_state_connected ||
session->target_state == snip_socket_state_input_eof ||
session->target_state == snip_socket_state_input_discard)
{
snip_target_finish_writing(session);
}
bufferevent_free(session->client_bev);
session->client_bev = NULL;
}
else {
// If we never connected, there's nothing to relay. We may ultimately want to offer more polite failure
// notices here.
snip_session_destroy(session);
}
}
else if (events & BEV_EVENT_EOF) {
snip_log(SNIP_LOG_LEVEL_INFO, "%s: Client connection input ended.", session->description);
session->client_state = snip_socket_state_input_eof;
// Schedule any remaining client input for output
if(session->target_bev) {
snip_target_finish_writing(session);
}
}
}
/**
* Called when a new connection happens on the listener.
* @param evconn
* @param fd
* @param address
* @param socklen
* @param ctx
*/
static void
snip_accept_incoming_cb(
struct evconnlistener *evconn,
evutil_socket_t fd,
struct sockaddr *address,
int socklen,
void *ctx
) {
struct event_base *base = evconnlistener_get_base(evconn);
snip_config_listener_t *listener = (snip_config_listener_t *) ctx;
snip_context_t *context = listener->config->context;
// Save it all to the pair
snip_session_t *session = snip_session_create();
snip_config_retain(listener->config);
session->id = context->next_id++;
session->listener = listener;
// We release the listener/config when we establish a destination. We still want to hold a way back to the context.
session->context = listener->config->context;
session->client_bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(session->client_bev, snip_client_read_cb, NULL, snip_client_event_cb, (void *) session);
memcpy(session->client_local_address_string,
listener->bind_address_string,
sizeof(session->client_local_address_string));