forked from e2guardian/e2guardian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionHandler.cpp
4526 lines (4082 loc) · 179 KB
/
ConnectionHandler.cpp
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
// Released under the GPL v2, with the OpenSSL exception described in the README file.
// INCLUDES
#ifdef HAVE_CONFIG_H
#include "e2config.h"
#endif
//#include "NaughtyFilter.hpp"
//#include "StoryBoard.hpp"
#include "ConnectionHandler.hpp"
#include "DataBuffer.hpp"
#include "UDSocket.hpp"
//#include "Auth.hpp"
#include "FDTunnel.hpp"
#include "BackedStore.hpp"
#include "Queue.hpp"
#include "ImageContainer.hpp"
#include "FDFuncs.hpp"
#include <signal.h>
#include <arpa/nameser.h>
#include <resolv.h>
#ifdef __SSLMITM
#include "CertificateAuthority.hpp"
#endif //__SSLMITM
#include <syslog.h>
#include <cerrno>
#include <cstdio>
#include <ctime>
#include <algorithm>
#include <netdb.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/time.h>
#include <strings.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <istream>
#include <sstream>
#include <memory>
#ifdef ENABLE_ORIG_IP
#include <linux/types.h>
#include <linux/netfilter_ipv4.h>
#endif
#ifdef __SSLMITM
#include "openssl/ssl.h"
#include "openssl/x509v3.h"
#include "String.hpp"
#endif
// GLOBALS
extern OptionContainer o;
extern bool is_daemonised;
extern std::atomic<bool> ttg;
extern thread_local std::string thread_id;
// IMPLEMENTATION
ConnectionHandler::ConnectionHandler()
: clienthost(NULL) {
// initialise SBauth structure
SBauth.filter_group = 0;
SBauth.is_authed = false;
SBauth.user_name = "";
}
// Custom exception class for POST filtering errors
class postfilter_exception : public std::runtime_error {
public:
postfilter_exception(const char *const &msg)
: std::runtime_error(msg) {};
};
//
// URL cache funcs
//
// check the URL cache to see if we've already flagged an address as clean
bool wasClean(HTTPHeader &header, String &url, const int fg) {
return false; // this function needs rewriting always return false
}
// add a known clean URL to the cache
void addToClean(String &url, const int fg) {
return; // this function needs rewriting
}
//
// ConnectionHandler class
//
void ConnectionHandler::peerDiag(const char *message, Socket &peersock) {
if (o.logconerror) {
//int peerport = peersock.getPeerSourcePort();
std::string peer_ip = peersock.getPeerIP();
int err = peersock.getErrno();
if (peersock.isTimedout())
syslog(LOG_INFO, "%s %s Client at %s Connection timedout - errno: %d", thread_id.c_str(), message,
peer_ip.c_str(), err);
else if (peersock.isHup())
syslog(LOG_INFO, "%s %s Client at %s has disconnected - errno: %d", thread_id.c_str(), message,
peer_ip.c_str(), err);
else if (peersock.sockError())
syslog(LOG_INFO, "%s %s Client at %s Connection socket error - errno: %d", thread_id.c_str(), message,
peer_ip.c_str(), err);
else if (peersock.isNoRead())
syslog(LOG_INFO, "%s %s cant read Client Connection at %s - errno: %d ", thread_id.c_str(), message,
peer_ip.c_str(), err);
else if (peersock.isNoWrite())
syslog(LOG_INFO, "%s %s cant write Client Connection at %s - errno: %d ", thread_id.c_str(), message,
peer_ip.c_str(), err);
else if (peersock.isNoOpp())
syslog(LOG_INFO, "%s %s Client Connection is no-op - errno: %d", thread_id.c_str(), message, err);
else
syslog(LOG_INFO, "%s %s Client Connection at %s problem - errno: %d", thread_id.c_str(), message,
peer_ip.c_str(), err);
}
}
void ConnectionHandler::upstreamDiag(const char *message, Socket &proxysock) {
if (o.logconerror) {
int err = proxysock.getErrno();
if (proxysock.isTimedout())
syslog(LOG_INFO, "%s %s upstream timedout - errno: %d:", thread_id.c_str(), message, err);
else if (proxysock.isHup())
syslog(LOG_INFO, "%s %s upstream has disconnected - errno: %d", thread_id.c_str(), message, err);
else if (proxysock.sockError())
syslog(LOG_INFO, "%s %s upstream socket error - errno: %d", thread_id.c_str(), message, err);
else if (proxysock.isNoRead())
syslog(LOG_INFO, "%s %s cant read upstream Connection - errno: %d ", thread_id.c_str(), message, err);
else if (proxysock.isNoWrite())
syslog(LOG_INFO, "%s %s cant write upstream Connection - errno: %d", thread_id.c_str(), message, err);
else if (proxysock.isNoOpp())
syslog(LOG_INFO, "%s %s upstream Connection is no-op - errno: %d", thread_id.c_str(), message, err);
else
syslog(LOG_INFO, "%s %s upstream Connection problem - errno: %d", thread_id.c_str(), message, err);
}
if (proxysock.isNoOpp())
proxysock.close();
}
// perform URL encoding on a string
std::string ConnectionHandler::miniURLEncode(const char *s) {
std::string encoded;
char *buf = new char[3];
unsigned char c;
for (int i = 0; i < (signed) strlen(s); i++) {
c = s[i];
// allowed characters in a url that have non special meaning
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) {
encoded += c;
continue;
}
// all other characters get encoded
sprintf(buf, "%02x", c);
encoded += "%";
encoded += buf;
}
delete[] buf;
return encoded;
}
// create a temporary bypass URL for the banned page
String ConnectionHandler::hashedURL(String *url, int filtergroup, std::string *clientip,
bool infectionbypass, std::string *user) {
// filter/virus bypass hashes last for a certain time only
//String timecode(time(NULL) + (infectionbypass ? (*ldl->fg[filtergroup]).infection_bypass_mode : (*ldl->fg[filtergroup]).bypass_mode));
String timecode(time(NULL) + (infectionbypass ? (*ldl->fg[filtergroup]).infection_bypass_mode
: (*ldl->fg[filtergroup]).bypass_mode));
// use the standard key in normal bypass mode, and the infection key in infection bypass mode
String magic(infectionbypass ? ldl->fg[filtergroup]->imagic.c_str() : ldl->fg[filtergroup]->magic.c_str());
magic += clientip->c_str();
if(ldl->fg[filtergroup]->bypass_v2)
magic += user->c_str();
magic += timecode;
String res(infectionbypass ? "GIBYPASS=" : "GBYPASS=");
if (!url->after("://").contains("/")) {
String newurl((*url));
newurl += "/";
res += newurl.md5(magic.toCharArray());
} else {
res += url->md5(magic.toCharArray());
}
res += timecode;
#ifdef E2DEBUG
std::cerr << thread_id << " -generate Bypass hashedurl data " << clientip->c_str() << " " << *url << " " << clientuser << " " << timecode << " result " << res << std::endl;
#endif
return res;
}
// create temporary bypass cookie
String ConnectionHandler::hashedCookie(String *url, const char *magic, std::string *clientip, int bypasstimestamp) {
String timecode(bypasstimestamp);
String data(magic);
data += clientip->c_str();
//if(ldl->fg[filtergroup]->bypass_v2)
data += clientuser;
data += timecode;
#ifdef E2DEBUG
std::cerr << thread_id << " -generate Bypass hashedCookie data " << clientip->c_str() << " " << *url << " " << clientuser << " " << timecode << std::endl;
#endif
String res(url->md5(data.toCharArray()));
res += timecode;
#ifdef E2DEBUG
std::cerr << thread_id << " -Bypass hashedCookie=" << res << std::endl;
#endif
return res;
}
// is this a temporary filter bypass URL?
int ConnectionHandler::isBypassURL(String url, const char *magic, const char *clientip, bool *isvirusbypass, std::string &user)
{
if ((url).length() <= 45)
return false; // Too short, can't be a bypass
// check to see if this is a bypass URL, and which type it is
bool filterbypass = false;
bool virusbypass = false;
if ((isvirusbypass == NULL) && ((url).contains("GBYPASS="))) {
filterbypass = true;
} else if ((isvirusbypass != NULL) && (url).contains("GIBYPASS=")) {
virusbypass = true;
}
if (!(filterbypass || virusbypass))
return 0;
#ifdef E2DEBUG
std::cerr << thread_id << "URL " << (filterbypass ? "GBYPASS" : "GIBYPASS") << " found checking..." << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
String url_left((url).before(filterbypass ? "GBYPASS=" : "GIBYPASS="));
url_left.chop(); // remove the ? or &
String url_right((url).after(filterbypass ? "GBYPASS=" : "GIBYPASS="));
String url_hash(url_right.subString(0, 32));
String url_time(url_right.after(url_hash.toCharArray()));
#ifdef E2DEBUG
std::cerr << thread_id << "URL: " << url_left << ", HASH: " << url_hash << ", TIME: " << url_time << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
String mymagic(magic);
mymagic += clientip;
if(ldl->fg[filtergroup]->bypass_v2)
mymagic += user;
mymagic += url_time;
String hashed(url_left.md5(mymagic.toCharArray()));
if(ldl->fg[filtergroup]->cgi_bypass_v2) {
mymagic = hashed;
hashed = mymagic.md5(ldl->fg[filtergroup]->cgi_magic.c_str());
}
if (hashed != url_hash) {
#ifdef E2DEBUG
std::cerr << thread_id << "URL " << (filterbypass ? "GBYPASS" : "GIBYPASS") << " hash mismatch" << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
return 0;
}
time_t timen = time(NULL);
time_t timeu = url_time.toLong();
if (timeu < 1) {
#ifdef E2DEBUG
std::cerr << thread_id << "URL " << (filterbypass ? "GBYPASS" : "GIBYPASS") << " bad time value" << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
return 1; // bad time value
}
if (timeu < timen) { // expired key
#ifdef E2DEBUG
std::cerr << thread_id << "URL " << (filterbypass ? "GBYPASS" : "GIBYPASS") << " expired" << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
return 1; // denotes expired but there
}
#ifdef E2DEBUG
std::cerr << thread_id << "URL " << (filterbypass ? "GBYPASS" : "GIBYPASS") << " not expired" << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
if (virusbypass)
(*isvirusbypass) = true;
return (int)timeu;
}
// is this a scan bypass URL? i.e. a "magic" URL for retrieving a previously scanned file
bool ConnectionHandler::isScanBypassURL(String url, const char *magic, const char *clientip)
{
if ((url).length() <= 45)
return false; // Too short, can't be a bypass
if (!(url).contains("GSBYPASS=")) { // If this is not a bypass url
return false;
}
#ifdef E2DEBUG
std::cerr << thread_id << "URL GSBYPASS found checking..." << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
String url_left((url).before("GSBYPASS="));
url_left.chop(); // remove the ? or &
String url_right((url).after("GSBYPASS="));
String url_hash(url_right.subString(0, 32));
#ifdef E2DEBUG
std::cerr << thread_id << "URL: " << url_left << ", HASH: " << url_hash << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
// format is:
// GSBYPASS=hash(ip+url+tempfilename+mime+disposition+secret)
// &N=tempfilename&M=mimetype&D=dispos
String tempfilename(url_right.after("&N="));
String tempfilemime(tempfilename.after("&M="));
String tempfiledis(tempfilemime.after("&D="));
tempfilemime = tempfilemime.before("&D=");
tempfilename = tempfilename.before("&M=");
String tohash(clientip + url_left + tempfilename + tempfilemime + tempfiledis + magic);
String hashed(tohash.md5());
if(ldl->fg[filtergroup]->cgi_bypass_v2) {
tohash = hashed;
hashed = tohash.md5(ldl->fg[filtergroup]->cgi_magic.c_str());
}
#ifdef E2DEBUG
std::cerr << thread_id << "checking hash: " << clientip << " " << url_left << " " << tempfilename << " "
<< " " << tempfilemime << " " << tempfiledis << " " << magic << " " << hashed << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
if (hashed == url_hash) {
return true;
}
#ifdef E2DEBUG
std::cerr << thread_id << "URL GSBYPASS HASH mismatch" << " Line: " << __LINE__ << " Function: " << __func__ << std::endl;
#endif
return false;
}
// send a file to the client - used during bypass of blocked downloads
off_t
ConnectionHandler::sendFile(Socket *peerconn, NaughtyFilter &cm, String &url, bool is_icap, ICAPHeader *icap_head) {
String filedis = cm.tempfiledis;
int fd = open(cm.tempfilename.toCharArray(), O_RDONLY);
if (fd < 0) { // file access error
syslog(LOG_ERR, "%sError reading file to send", thread_id.c_str());
#ifdef E2DEBUG
std::cerr << thread_id << " -Error reading file to send:" << cm.tempfilename << std::endl;
#endif
String fnf(o.language_list.getTranslation(1230));
String head("HTTP/1.1 404 " + fnf + "\r\nContent-Type: text/html\r\n\r\n");
String body("<HTML><HEAD><TITLE>" + fnf + "</TITLE></HEAD><BODY><H1>" + fnf + "</H1></BODY></HTML>\r\n");
if (is_icap) {
icap_head->out_res_header = head;
icap_head->out_res_body = body;
icap_head->out_res_hdr_flag = true;
icap_head->out_res_body_flag = true;
icap_head->respond(*peerconn);
} else {
peerconn->writeString(head.toCharArray());
peerconn->writeString(body.toCharArray());
}
return 0;
}
off_t filesize = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
String head("HTTP/1.1 200 OK\r\nContent-Type: " + cm.tempfilemime + "\r\nContent-Length: " + String(filesize));
if (filedis.length() == 0) {
filedis = url.before("?");
while (filedis.contains("/"))
filedis = filedis.after("/");
}
head += "\r\nContent-disposition: attachment; filename=" + filedis;
head += "\r\n\r\n";
if (is_icap) {
icap_head->out_res_header = head;
icap_head->out_res_hdr_flag = true;
icap_head->out_res_body_flag = true;
icap_head->respond(*peerconn);
} else {
if (!peerconn->writeString(head.toCharArray())) {
close(fd);
return 0;
}
}
// perform the actual sending
off_t sent = 0;
int rc;
//char *buffer = new char[250000];
char *buffer = new char[64000];
while (sent < filesize) {
rc = readEINTR(fd, buffer, 64000);
#ifdef E2DEBUG
std::cerr << thread_id << " -reading send file rc:" << rc << std::endl;
#endif
if (rc < 0) {
#ifdef E2DEBUG
std::cerr << thread_id << " -error reading send file so aborting" << std::endl;
#endif
delete[] buffer;
// throw std::exception/();
//cleanThrow("error reading send file", *peerconn);
return 0;
}
if (rc == 0) {
#ifdef E2DEBUG
std::cerr << thread_id << " -got zero bytes reading send file" << std::endl;
#endif
break; // should never happen
}
if (is_icap) {
if (!peerconn->writeChunk(buffer, rc, 100000)) {
delete[] buffer;
peerDiag("Error sending file to client", *peerconn);
return 0;
}
} else {
// as it's cached to disk the buffer must be reasonably big
if (!peerconn->writeToSocket(buffer, rc, 0, 100000)) {
delete[] buffer;
peerDiag("Error sending file to client", *peerconn);
return 0;
// throw std::exception();
}
}
sent += rc;
#ifdef E2DEBUG
std::cerr << thread_id << " -total sent from temp:" << sent << std::endl;
#endif
}
if (is_icap) {
String n;
peerconn->writeChunkTrailer(n);
}
delete[] buffer;
close(fd);
return sent;
}
int
ConnectionHandler::connectUpstream(Socket &sock, NaughtyFilter &cm, int port = 0) // connects to to proxy or directly
{
if (port == 0)
port = cm.request_header->port;
String sport(port);
int lerr_mess = 0;
int retry = -1;
bool may_be_loop = false;
for (auto it = o.check_ports.begin(); it != o.check_ports.end(); it++) {
if (*it == sport) {
may_be_loop = true;
break;
}
}
#ifdef E2DEBUG
std::cerr << thread_id << "May_be_loop = " << may_be_loop << " " << " port " << port << std::endl;
#endif
sock.setTimeout(o.connect_timeout);
while (++retry < o.connect_retries) {
lerr_mess = 0;
if (retry > 0) {
if (o.logconerror)
syslog(LOG_INFO, "%s retry %d to connect to %s", thread_id.c_str(), retry, cm.urldomain.c_str());
if (!sock.isTimedout())
usleep(1000); // don't hammer upstream
}
cm.upfailure = false;
if (cm.isdirect) {
String des_ip;
if (cm.isiphost)
des_ip = cm.urldomain;
if(o.use_original_ip_port && cm.got_orig_ip && (cm.connect_site == cm.urldomain))
des_ip = cm.orig_ip;
if(des_ip.length() > 0) {
if (may_be_loop) { // check check_ip list
bool do_break = false;
if (o.check_ip.size() > 0) {
for (auto it = o.check_ip.begin(); it != o.check_ip.end(); it++) {
if (*it == des_ip) {
do_break = true;
lerr_mess = 212;
break;
}
}
}
if (do_break) break;
may_be_loop = false;
}
#ifdef E2DEBUG
std::cerr << thread_id << "Connecting to IP " << des_ip << " port " << port << std::endl;
#endif
int rc = sock.connect(des_ip, port);
if (rc < 0) {
lerr_mess = 203;
continue;
}
return rc;
} else {
//dns lookup
struct addrinfo hints, *infoptr;
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
int rc = getaddrinfo(cm.connect_site.toCharArray(), NULL, &hints, &infoptr);
if (rc) // problem
{
#ifdef E2DEBUG
std::cerr << thread_id << "connectUpstream: getaddrinfo returned " << rc << " for " << cm.connect_site << " " << gai_strerror(rc) << std::endl;
#endif
bool rt = false;
switch (rc) {
case EAI_NONAME:
lerr_mess = 207;
break;
#ifdef EAI_NODATA
case EAI_NODATA:
lerr_mess = 208;
break;
#endif
case EAI_AGAIN:
lerr_mess = 209;
rt = true;
break;
case EAI_FAIL:
lerr_mess = 210;
break;
default:
lerr_mess = 210; //TODO this should have it's own message??
break;
}
sock.close();
if (rt) continue;
else break;
}
char t[256];
struct addrinfo *p;
for (p = infoptr; p != NULL; p = p->ai_next) {
getnameinfo(p->ai_addr, p->ai_addrlen, t, sizeof(t), NULL, 0, NI_NUMERICHOST);
if (may_be_loop) { // check check_ip list
bool do_break = false;
if (o.check_ip.size() > 0) {
for (auto it = o.check_ip.begin(); it != o.check_ip.end(); it++) {
if (*it == t) {
do_break = true;
lerr_mess = 212;
break;
}
}
}
if (do_break) break;
may_be_loop = false;
}
#ifdef E2DEBUG
std::cerr << thread_id << "Connecting to IP " << t << " port " <<
port << " after dns lookup" << std::endl;
#endif
int rc = sock.connect(t, port);
if (rc == 0) {
freeaddrinfo(infoptr);
#ifdef E2DEBUG
std::cerr << thread_id << "Got connection upfailure is " << cm.upfailure << std::endl;
#endif
return 0;
}
}
freeaddrinfo(infoptr);
if (may_be_loop) break;
lerr_mess = 203;
continue;
}
} else { //is via proxy
sock.setTimeout(o.proxy_timeout);
int rc = sock.connect(o.proxy_ip, o.proxy_port);
if (rc < 0) {
if (sock.isTimedout())
lerr_mess = 201;
else
lerr_mess = 202;
continue;
}
return rc;
}
}
// only get here if failed
cm.upfailure = true;
cm.message_no = lerr_mess;
cm.whatIsNaughty = o.language_list.getTranslation(lerr_mess);
cm.whatIsNaughtyLog = cm.whatIsNaughty;
cm.whatIsNaughtyCategories = "";
cm.whatIsNaughtyDisplayCategories = "";
cm.isItNaughty = true;
cm.blocktype = 3;
cm.isexception = false;
cm.isbypass = false;
return -1;
}
// pass data between proxy and client, filtering as we go.
// this is the only public function of ConnectionHandler
int ConnectionHandler::handlePeer(Socket &peerconn, String &ip, stat_rec *&dystat, unsigned int lc_type) {
persistent_authed = false;
is_real_user = false;
int rc = 0;
//#ifdef E2DEBUG
// for debug info only - TCP peer port
//thread_id = peerconn.getPeerSourcePort();
//#endif
Socket proxysock; // also used for direct connection
switch (lc_type) {
case CT_PROXY:
SBauth.is_proxy = true;
rc = handleConnection(peerconn, ip, false, proxysock, dystat);
break;
#ifdef __SSLMITM
case CT_THTTPS:
SBauth.is_transparent = true;
rc = handleTHTTPSConnection(peerconn, ip, proxysock, dystat);
break;
#endif
case CT_ICAP:
SBauth.is_icap = true;
rc = handleICAPConnection(peerconn, ip, proxysock, dystat);
break;
}
//if ( ldl->reload_id != load_id)
// rc = -1;
return rc;
}
int ConnectionHandler::handleConnection(Socket &peerconn, String &ip, bool ismitm, Socket &proxysock,
stat_rec *&dystat) {
struct timeval thestart;
gettimeofday(&thestart, NULL);
//peerconn.setTimeout(o.proxy_timeout);
peerconn.setTimeout(o.pcon_timeout);
// ldl = o.currentLists();
HTTPHeader docheader(__HEADER_RESPONSE); // to hold the returned page header from proxy
HTTPHeader header(__HEADER_REQUEST); // to hold the incoming client request headeri(ldl)
// set a timeout as we don't want blocking 4 eva
// this also sets how long a peerconn will wait for other requests
header.setTimeout(o.pcon_timeout);
docheader.setTimeout(o.exchange_timeout);
//int bypasstimestamp = 0;
// Content scanning plugins to use for request (POST) & response data
std::deque<CSPlugin *> requestscanners;
std::deque<CSPlugin *> responsescanners;
std::string clientip(ip.toCharArray()); // hold the clients ip
header.setClientIP(ip);
if (clienthost) delete clienthost;
clienthost = NULL; // and the hostname, if available
matchedip = false;
// clear list of parameters extracted from URL
urlparams.clear();
// clear out info about POST data
postparts.clear();
#ifdef E2DEBUG // debug stuff surprisingly enough
std::cerr << thread_id << " -got peer connection" << std::endl;
std::cerr << thread_id << clientip << std::endl;
#endif
try {
//int rc;
#ifdef E2DEBUG
int pcount = 0;
#endif
// assume all requests over the one persistent connection are from
// the same user. means we only need to query the auth plugin until
// we get credentials, then assume they are valid for all reqs. on
// the persistent connection.
std::string oldclientuser;
std::string room;
//int oldfg = 0;
bool authed = false;
//bool isbanneduser = false;
//bool isscanbypass = false;
//bool isbypass = false;
//bool isvirusbypass = false;
//int bypasstimestamp = 0;
//bool iscookiebypass = false;
AuthPlugin *auth_plugin = NULL;
// RFC states that connections are persistent
bool persistOutgoing = true;
bool persistPeer = true;
bool persistProxy = true;
String last_domain_port;
bool last_isdirect = false;
bool firsttime = true;
if (!header.in(&peerconn, true)) { // get header from client, allowing persistency
if (o.logconerror) {
if (peerconn.getFD() > -1) {
int err = peerconn.getErrno();
//int pport = peerconn.getPeerSourcePort();
std::string peerIP = peerconn.getPeerIP();
syslog(LOG_INFO, "%s No header recd from client at %s - errno: %d", thread_id.c_str(),
peerIP.c_str(), err);
#ifdef E2DEBUG
std::cerr << thread_id << " No header recd from client - errno: " << err << std::endl;
#endif
} else {
syslog(LOG_INFO, "%s Client connection closed early - no request header received",
thread_id.c_str());
}
}
firsttime = false;
persistPeer = false;
} else {
++dystat->reqs;
}
//
// End of set-up section
//
// Start of main loop
//
// maintain a persistent connection
while ((firsttime || persistPeer) && !ttg)
// while ((firsttime || persistPeer) && !reloadconfig)
{
#ifdef E2DEBUG
std::cerr << thread_id << " firsttime =" << firsttime << "ismitm =" << ismitm << " clientuser =" << clientuser << " group = " << filtergroup << std::endl;
#endif
ldl = o.currentLists();
NaughtyFilter checkme(header, docheader, SBauth);
checkme.listen_port = peerconn.getPort();
DataBuffer docbody;
docbody.setTimeout(o.exchange_timeout);
FDTunnel fdt;
if (firsttime) {
// reset flags & objects next time round the loop
firsttime = false;
gettimeofday(&thestart, NULL);
checkme.thestart = thestart;
// quick trick for the very first connection :-)
if (!ismitm)
persistProxy = false;
} else {
// another round...
#ifdef E2DEBUG
std::cerr << thread_id << " -persisting (count " << ++pcount << ")" << std::endl;
// syslog(LOG_ERR, "Served %d requests on this connection so far - ismitm=%d", pcount, ismitm);
std::cerr << thread_id << " - " << clientip << std::endl;
#endif
header.reset();
if (!header.in(&peerconn, true)) {
#ifdef E2DEBUG
std::cerr << thread_id << " -Persistent connection closed" << std::endl;
#endif
break;
}
++dystat->reqs;
// we will actually need to do *lots* of resetting of flags etc. here for pconns to work
gettimeofday(&thestart, NULL);
checkme.thestart = thestart;
checkme.bypasstimestamp = 0;
authed = false;
requestscanners.clear();
responsescanners.clear();
matchedip = false;
urlparams.clear();
postparts.clear();
checkme.mimetype = "-";
room = ""; // CHECK THIS - surely room is persistant?????
// reset docheader & docbody
// headers *should* take care of themselves on the next in()
// actually not entirely true for docheader - we may read
// certain properties of it (in denyAccess) before we've
// actually performed the next in(), so make sure we do a full
// reset now.
docheader.reset();
docbody.reset();
peerconn.resetChunk();
proxysock.resetChunk();
}
//
// do this normalisation etc just the once at the start.
checkme.setURL(ismitm);
if(o.log_requests) {
std::string fnt;
if(ismitm)
fnt = "MITM";
else if(header.isProxyRequest) {
fnt = "PROXY";
} else fnt = "TRANS";
doRQLog(clientuser, clientip, checkme, fnt);
}
if(!header.isProxyRequest) // is transparent http proxy
get_original_ip_port(peerconn,checkme);
//If proxy connection is not persistent..// do this later after checking if direct or via proxy
#ifdef E2DEBUG
std::cerr << thread_id << getpid() << "Start URL " << checkme.url.c_str() << "is_ssl=" << checkme.is_ssl << "ismitm=" << ismitm << std::endl;
#endif
// checks for bad URLs to prevent security holes/domain obfuscation.
if (header.malformedURL(checkme.url)) {
// The requested URL is malformed.
writeback_error(checkme, peerconn, 200, 0, "400 Bad Request");
proxysock.close(); // close connection to proxy
break;
}
// TODO this needs moving is proxy operation is still to be tested
if (checkme.urldomain == o.internal_test_url) {
peerconn.writeString(
"HTTP/1.1 200 \nContent-Type: text/html\n\n<HTML><HEAD><TITLE>e2guardian internal test</TITLE></HEAD><BODY><H1>e2guardian internal test OK</H1> ");
peerconn.writeString("</BODY></HTML>\n");
proxysock.close(); // close connection to proxy
break;
}
// total block list checking now done in pre-auth story
// don't let the client connection persist if the client doesn't want it to.
persistOutgoing = header.isPersistent();
// now check if in input proxy mode and direct upstream if upstream needs closing
if (persistProxy && last_isdirect &&
((last_domain_port != checkme.urldomainport)|| !o.no_proxy)) {
proxysock.close();
persistProxy = false;
}
last_domain_port = checkme.urldomainport;
last_isdirect = checkme.isdirect;
//
//
// Now check if machine is banned and room-based checking
//
//
// is this user banned?
//isbanneduser = false;
#ifdef NOTDEF
if(!ismitm) {
// pretend to use xforwarded for
clientip = "192.6.6.6";
ip = clientip;
}
#endif
if (!ismitm && o.use_xforwardedfor) {
bool use_xforwardedfor;
if (o.xforwardedfor_filter_ip.size() > 0) {
use_xforwardedfor = false;
for (unsigned int i = 0; i < o.xforwardedfor_filter_ip.size(); i++) {
if (strcmp(clientip.c_str(), o.xforwardedfor_filter_ip[i].c_str()) == 0) {
use_xforwardedfor = true;
break;
}
}
} else {
use_xforwardedfor = true;
}
if (use_xforwardedfor) {
std::string xforwardip(header.getXForwardedForIP());
if (xforwardip.length() > 6) {
clientip = xforwardip;
ip = clientip;
header.setClientIP(ip);
}
#ifdef E2DEBUG
std::cerr << thread_id << " -using x-forwardedfor:" << clientip << std::endl;
#endif
}
}
checkme.clientip = clientip;
// Look up reverse DNS name of client if needed
if (o.reverse_client_ip_lookups) {
getClientFromIP(clientip.c_str(),checkme.clienthost);
// std::unique_ptr<std::deque<String> > hostnames;
// hostnames.reset(ipToHostname(clientip.c_str()));
// checkme.clienthost = std::string(hostnames->front().toCharArray());
}
//CALL SB pre-authcheck
ldl->StoryA.runFunctEntry(ENT_STORYA_PRE_AUTH, checkme);
#ifdef E2DEBUG
std::cerr << "After StoryA pre-authcheck" << checkme.isexception << " mess_no "
<< checkme.message_no
<< " cat " << checkme.whatIsNaughtyCategories << std::endl;
#endif
checkme.isItNaughty = checkme.isBlocked;
bool isbannedip = checkme.isBlocked;
bool part_banned;
if (isbannedip) {
// matchedip = clienthost == NULL;
} else {
if (ldl->inRoom(clientip, room, &(checkme.clienthost), &isbannedip, &part_banned, &checkme.isexception,
checkme.urld)) {
#ifdef E2DEBUG
std::cerr << " isbannedip = " << isbannedip << "ispart_banned = " << part_banned << " isexception = " << checkme.isexception << std::endl;
#endif
if (isbannedip) {
// matchedip = clienthost == NULL;
checkme.isBlocked = checkme.isItNaughty = true;
}
if (checkme.isexception) {
// do reason codes etc
checkme.exceptionreason = o.language_list.getTranslation(630);
checkme.exceptionreason.append(room);
checkme.exceptionreason.append(o.language_list.getTranslation(631));
checkme.message_no = 632;
}
}
}
//
//
// Start of Authentication Checks
//
//
// don't have credentials for this connection yet? get some!
overide_persist = false;
if (!persistent_authed) {
bool only_ip_auth;
if (header.isProxyRequest) {
filtergroup = o.default_fg;
SBauth.is_proxy = true;
only_ip_auth = false;
} else {
filtergroup = o.default_trans_fg;
SBauth.is_transparent = true;
only_ip_auth = true;
}
SBauth.group_source = "def";
#ifdef E2DEBUG
std::cerr << thread_id << "isProxyRequest is " << header.isProxyRequest << " only_ip_auth is " << only_ip_auth << " needs proxy for auth plugin is " << o.auth_needs_proxy_in_plugin << std::endl;
#endif
if (!persistProxy && o.auth_needs_proxy_in_plugin && header.isProxyRequest) // open upstream connection early if required for ntml auth
{
if (connectUpstream(proxysock, checkme, header.port) < 0) {
if (checkme.isconnect && ldl->fg[filtergroup]->ssl_mitm && ldl->fg[filtergroup]->automitm &&