-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathratproxy.c
1785 lines (1274 loc) · 50.9 KB
/
ratproxy.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
/*
ratproxy
--------
A simple HTTP proxy to use for code audits of rich web 2.0 applications.
Meant to detect JSON-related and other script-accessible content problems as
you interact with the tested application and otherwise just mind your business.
Please use this tool responsibly and in good faith. Thanks.
Author: Michal Zalewski <[email protected]>
Copyright 2007, 2008 by Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <ctype.h>
#include <netdb.h>
#include <openssl/md5.h>
#include <time.h>
#include "config.h"
#include "types.h"
#include "debug.h"
#include "nlist.h"
#include "http.h"
#include "mime.h"
#include "ssl.h"
#include "string-inl.h"
static struct naive_list domains; /* Domains to keep track of */
static _u8 check_png, /* Check all PNG files? */
dump_urls, /* Dump all visited URLs? */
all_files, /* Report all file inclusions */
all_flash, /* Report all Flash documents */
get_xsrf, /* Report GET XSRF status */
bad_js, /* Report risky Javascript */
all_post, /* Report all POST requests */
all_cookie, /* Report all cookie URLs */
picky_cache, /* Be picky about chdrs */
use_double, /* Make 2, not 1 extra req */
try_attacks, /* Validate XSRF/XSS suspects */
fix_attacks, /* Correct XSRF/XSS fallout */
log_active, /* Log cross-domain content */
log_mixed, /* Log mixed content */
use_any, /* Listen on any address */
all_xss; /* Report all XSS suspects */
static _u32 use_port = DEFAULT_PORT; /* Proxy port to listen on */
_u8* use_proxy; /* Upstream proxy */
_u8* trace_dir; /* Trace directory */
_u32 proxy_port = 8080; /* Upstream proxy port */
_u8 use_len; /* Use length, not cksum */
static FILE* outfile; /* Output file descriptor */
/* Display usage information */
static void usage(_u8* argv0) {
debug("Usage: %s [ -w logfile ] [ -v logdir ] [ -p port ] [ -d domain ] [ -P host:port ] "
"[ -xtifkgmjscael2XCr ]\n"
" -w logfile - write results to a specified file (default: stdout)\n"
" -v logdir - write HTTP traces to a specified directory (default: none)\n"
" -p port - listen on a custom TCP port (default: 8080)\n"
" -d domain - analyze requests to specified domains only (default: all)\n"
" -P host:port - use upstream proxy for all requests (format host:port)\n"
" -r - accept remote connections (default: 127.0.0.1 only)\n"
" -l - use response length, not checksum, for identity check\n"
" -2 - perform two, not one, page identity check\n"
" -e - perform pedantic caching headers checks\n"
" -x - log all XSS candidates\n"
" -t - log all directory traversal candidates\n"
" -i - log all PNG files served inline\n"
" -f - log all Flash applications for analysis (add -v to decompile)\n"
" -s - log all POST requests for analysis\n"
" -c - log all cookie setting URLs for analysis\n"
" -g - perform XSRF token checks on all GET requests\n"
" -j - report on risky Javascript constructions\n"
" -m - log all active content referenced across domains\n"
" -X - disruptively validate XSRF, XSS protections\n"
" -C - try to auto-correct persistent side effects of -X\n"
" -k - flag HTTP requests as bad (for HTTPS-only applications)\n"
" -a - indiscriminately report all visited URLs\n\n"
"Example settings suitable for most tests:\n"
" 1) Low verbosity : -v <outdir> -w <outfile> -d <domain> -lfscm\n"
" 2) High verbosity : -v <outdir> -w <outfile> -d <domain> -lextifscgjm\n"
" 3) Active testing : -v <outdir> -w <outfile> -d <domain> -XClfscm\n\n"
"Multiple -d options are allowed. Consult the documentation for more.\n", argv0);
exit(1);
}
#define sayf(x...) fprintf(outfile,x)
/* Check hostname against a list of tracked ones. */
static _u8 host_ok(_u8* hname) {
_u32 i, hlen;
/* If no domains defined, accept all. */
if (!domains.c) return 1;
hlen = strlen(hname);
for (i=0;i<domains.c;i++) {
_u32 dlen = strlen(domains.v[i]);
if (dlen > hlen) continue;
if (!strcmp(hname + (hlen - dlen), domains.v[i])) return 1;
}
return 0;
}
/* Test for XSSable payload */
static _u8 xss_field(_u8* value, _u8 head) {
_u32 c = 0;
if (strlen(value) < (head ? MIN_XSS_HEAD : MIN_XSS_LEN)) return 0;
while (no_xss_text[c]) {
if (!strncasecmp(value,no_xss_text[c],strlen(no_xss_text[c]))) return 0;
c++;
}
return 1;
}
#define MOD_PRED 1
#define MOD_AUTH 2
#define MOD_ECHO 4
#define NOECHO(_x) ((_x) & ~MOD_ECHO)
#define ECHO(_x) ((_x) & MOD_ECHO)
/* Check if the page has a predictable URL, user-specific content, echoed parameters. */
static _u8 get_modifiers(struct http_request* req, struct http_response* res) {
FILE *server;
static struct http_response* mini = 0;
_u32 ret = 0;
_u32 fno = 0;
_u32 i;
/* Test for echoed query parameters in response body... */
if (res->is_text && res->payload_len) {
#ifdef CHECK_ECHO_PATH
if (req->path && strstr(res->payload,req->path)) ret = MOD_ECHO;
#endif /* CHECK_ECHO_PATH */
for (i=0;!ret && i<req->p.c;i++)
if (!req->p.fn[i][0] && xss_field(req->p.v2[i],0) && strstr(res->payload,req->p.v2[i]))
{ ret = MOD_ECHO; break; }
}
/* ...and in HTTP header values. */
for (i=0;!ret && i<req->p.c;i++)
if (!req->p.fn[i][0] && xss_field(req->p.v2[i],1)) {
_u32 j;
for (j=0;j<res->h.c;j++)
if (strstr(res->h.v2[j],req->p.v2[i])) { ret = MOD_ECHO; break; }
}
/* Check for predictable URLs. */
if (!req->xsrf_safe) ret |= MOD_PRED;
/* Check for authentication. */
/* Some field names may override our checks. */
while (auth_fields[fno]) {
_u32 i;
for (i=0;i<req->p.c;i++) {
if (auth_fields[fno][0] == '=') {
if (!strcasecmp(req->p.v1[i],auth_fields[fno] + 1)) return ret | MOD_AUTH;
} else {
if (rp_strcasestr(req->p.v1[i],auth_fields[fno])) return ret | MOD_AUTH;
}
}
fno++;
}
/* No cookies? Then do not resend. */
if (!req->cookies.c) return ret;
/* Try to verify that the request requires authentication by replaying it with
no cookies. This should have no side effects in sanely written applications. */
/* TODO: We should continue also if custom HTTP headers or HTTP auth is detected;
we currently bail out on this, however. */
if (!mini) {
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
mini = send_request(0,server,req,1);
if (req->from_ssl) ssl_shutdown();
checksum_response(mini);
if (use_double) {
_u64 temp = mini->cksum;
/* ...and do it again! */
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
mini = send_request(0,server,req,1);
if (req->from_ssl) ssl_shutdown();
checksum_response(mini);
/* If checksum changes over time, give up. */
if (temp != mini->cksum) mini->cksum = res->cksum;
}
}
if (mini->cksum != res->cksum) ret |= MOD_AUTH;
return ret;
}
/* DISRUPTIVE CHECK: Try removing XSRF protection, see what happens. */
static void try_replay_xsrf(struct http_request* req, struct http_response* res) {
FILE *server;
struct http_response* not;
struct http_request r2;
_u32 i;
_u8 got_token = 0;
if (!req->xsrf_safe || req->authsub) return;
memcpy(&r2,req,sizeof(struct http_request));
/* Duplicate parameter value pointer array, so that we may modify it at will. */
r2.p.v2 = malloc(r2.p.c * sizeof(_u8*));
if (!r2.p.v2) fatal("out of memory");
memcpy(r2.p.v2,req->p.v2,r2.p.c * sizeof(_u8*));
/* Do not run contains_token() checks on file fields. */
for (i=0;i<req->p.c;i++)
if (!req->p.fn[i][0] && contains_token(req->p.v1[i],req->p.v2[i])) {
got_token = 1;
r2.p.v2[i] = "0"; /* Clobber value. */
}
/* Ooops! */
if (!got_token) return;
/* Rebuild query / payload strings. */
reconstruct_request(&r2);
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
not = send_request(0,server,&r2,0);
if (req->from_ssl) ssl_shutdown();
/* Fix potential side effects of our request. */
if (fix_attacks) {
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
send_request(0,server,req,0); /* sink response */
if (req->from_ssl) ssl_shutdown();
}
checksum_response(not);
/* Clobbering all XSRF-ish tokens caused no change? */
if (not->cksum == res->cksum) req->xsrf_safe = 0;
}
/* DISRUPTIVE CHECK: Try injecting XSS payload, see what happens. */
static _u8 try_replay_xss(struct http_request* req, struct http_response* res) {
FILE *server;
struct http_response* not;
struct http_request r2;
_u32 i;
_u8 got_candidate = 0;
_u8* cur;
_u8 htmlstate = 0, htmlurl = 0;
if (!res->is_text) return 0;
memcpy(&r2,req,sizeof(struct http_request));
/* Duplicate parameter value pointer array, so that we may modify it at will. */
r2.p.v2 = malloc(r2.p.c * sizeof(_u8*));
if (!r2.p.v2) fatal("out of memory");
memcpy(r2.p.v2,req->p.v2,r2.p.c * sizeof(_u8*));
for (i=0;i<req->p.c;i++)
if (!req->p.fn[i][0] && xss_field(req->p.v2[i],0) && strstr(res->payload,req->p.v2[i])
#ifndef XSS_XSRF_TOKENS
&& !contains_token(req->p.v1[i],req->p.v2[i])
#endif /* !XSS_XSRF_TOKENS */
) {
/* This does not account for all scenarios possible XSS scenarios, but is a
pretty good all-around string. Since we want to minimize the number of
requests generated, it will have to do. */
r2.p.v2[i] = "qg:qg qg=-->qg\"qg>qg'qg>qg+qg<qg>";
got_candidate = 1;
}
if (!got_candidate) return 0;
/* Rebuild query / payload strings. */
reconstruct_request(&r2);
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
not = send_request(0,server,&r2,0);
if (req->from_ssl) ssl_shutdown();
/* Fix potential side effects of our request. */
if (fix_attacks) {
server = open_server_complete(0,req);
if (req->from_ssl) {
ssl_setup();
ssl_start(fileno(server),-1);
fclose(server);
server = fdopen(ssl_srv_tap,"w+");
}
send_request(0,server,req,0); /* sink response */
if (req->from_ssl) ssl_shutdown();
}
if (!not->payload_len) return 0;
detect_mime(not);
if (not->is_text)
detect_charset(not);
/* Do some minimal and dumbed down HTML parsing on the response to detect q9g
strings in dangerous configurations. */
#define HS_IN_TAG 1
#define HS_IN_DBLQ 2
#define HS_IN_SNGQ 4
#define HS_IN_COMM 8
#define HS_IN_CDATA 16
cur = not->payload;
while (*cur) {
/* Detect successful XSS attempts... */
if (!strncasecmp(cur,"qg",2)) {
/* <tag foo=bar onload=...> */
if (htmlstate == HS_IN_TAG && !strncasecmp(cur+2," qg=",4)) return 1;
/* <tag src=foo:bar...> */
if (htmlurl && !strncasecmp(cur+2,":qg",3)) return 1;
/* <tag><script>... */
if (htmlstate == 0 && !strncasecmp(cur+2,"<qg",3)) return 1;
/* <tag>+ADw-script+AD4-... */
if (htmlstate == 0 && (!not->charset || not->bad_cset) && !strncasecmp(cur+2,"+qg",3)) return 1;
/* <tag foo="bar"onload=...> */
if (htmlstate == (HS_IN_TAG|HS_IN_DBLQ) && !strncasecmp(cur+2,"\"qg",3)) return 1;
/* <tag foo='bar'onload=...> */
if (htmlstate == (HS_IN_TAG|HS_IN_SNGQ) && !strncasecmp(cur+2,"'qg",3)) return 1;
} else {
/* Handle CDATA blocks */
if (htmlstate == 0 && !strncasecmp(cur,"<![CDATA[",9)) { htmlstate = HS_IN_CDATA; cur += 9; continue; }
if (htmlstate == HS_IN_CDATA && !strncmp(cur,"]]>",3)) { htmlstate = 0; cur += 3; continue; }
/* Handle <!-- --> blocks (this depends on rendering mode, but hey). */
if (htmlstate == 0 && !strncmp(cur,"<!--",4)) { htmlstate = HS_IN_COMM; cur += 4; continue; }
if (htmlstate == HS_IN_COMM && !strncmp(cur,"-->",3)) { htmlstate = 0; cur += 3; continue; }
/* Detect what could pass for tag opening / closure... */
if (htmlstate == 0 && *cur == '<' && (isalpha(cur[1]) || cur[1] == '!' || cur[1] == '?')) { htmlstate = HS_IN_TAG; cur++; continue; }
if (htmlstate == HS_IN_TAG && *cur == '>') { htmlstate = 0; htmlurl = 0; cur++; continue; }
/* Handle double quotes around HTML parameters */
if (htmlstate == HS_IN_TAG && cur[-1] == '=' && *cur == '"') { htmlstate |= HS_IN_DBLQ; cur++; continue; }
if (htmlstate == (HS_IN_TAG|HS_IN_DBLQ) && *cur == '"') { htmlstate = HS_IN_TAG; cur++; continue; }
/* Handle single quotes around HTML parameters */
if (htmlstate == HS_IN_TAG && cur[-1] == '=' && *cur == '\'') { htmlstate |= HS_IN_SNGQ; cur++; continue; }
if (htmlstate == (HS_IN_TAG|HS_IN_SNGQ) && *cur == '\'') { htmlstate = HS_IN_TAG; cur++; continue; }
/* Special handling for SRC= and HREF= locations. */
if (htmlstate == HS_IN_TAG && isspace(cur[-1]) && !strncasecmp(cur,"href=",5)) {
htmlurl = 1; cur += 5; continue;
}
if (htmlstate == HS_IN_TAG && isspace(cur[-1]) && !strncasecmp(cur,"src=",4)) {
htmlurl = 1; cur += 4; continue;
}
/* Cancel mode if any character other than ", ', or qg: URL is encountered. */
if (htmlurl) htmlurl = 0;
}
cur++;
}
/* So, no XSS? Bummer. */
return 0;
}
/* Check for publicly cacheable documents. Returns 0 if not public,
1 if apparently meant to be public, 2 if partly protected. */
static _u8 is_public(struct http_request* req, struct http_response* res) {
_u8 http10intent;
/* "Expires" and "Pragma" should say the same. */
if (res->pr10intent && res->ex10intent && res->pr10intent != res->ex10intent) return 2;
http10intent = res->ex10intent ? res->ex10intent : res->pr10intent;
/* HTTP/1.0 and HTTP/1.1 intents should say the same. */
if (http10intent && res->cc11intent && http10intent != res->cc11intent) return 2;
/* [Picky] HTTP/1.0 and HTTP/1.1 intents should not appear at all, or appear at once */
if (picky_cache && (http10intent ^ res->cc11intent)) {
if (strcmp(req->method,"GET")) return 0; /* Non-GET requests won't be cached. */
return 2;
}
if (res->cc11intent == INTENT_PRIV || http10intent == INTENT_PRIV) return 0;
/* No interest in making this document private was expressed... */
if (strcmp(req->method,"GET")) return 0; /* Non-GET requests won't be cached. */
return 1;
}
static _u8 dump_fn[1024];
static _u8 dumped_already;
/* Save trace data to file, if requested. */
static _u8* save_trace(struct http_request* req, struct http_response* res) {
_s32 f;
_u32 i;
FILE* out;
if (!trace_dir) return "-";
/* Do not save the same request twice. */
if (dumped_already) return dump_fn;
dumped_already = 1;
sprintf(dump_fn,"%.512s/%08x-%04x.trace",trace_dir,(_u32)time(0),getpid());
f = open(dump_fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (f < 0) {
debug(">>> Unable to open trace file '%s'! <<<\n",dump_fn);
return "-";
}
out = fdopen(f,"w");
fprintf(out,"== REQUEST TO %s:%u (%u headers, %u byte payload) ==\n\n%s /%s%s%s HTTP/1.0\n",
req->host, req->port, req->h.c, req->payload_len,
req->method, req->path, req->query ? "?" : "", req->query ? req->query : (_u8*)"");
for (i=0;i<req->h.c;i++)
fprintf(out,"%s: %s\n", req->h.v1[i], req->h.v2[i]);
fprintf(out,"\n");
if (req->payload_len)
fwrite(req->payload,req->payload_len > MAXTRACEITEM ? MAXTRACEITEM : req->payload_len,1,out);
if (req->payload_len > MAXTRACEITEM)
fprintf(out,"\n*** DATA TRUNCATED DUE TO SIZE LIMITS ***");
fprintf(out,"\n\n== SERVER RESPONSE (%u headers, %u byte payload, detected MIME %s) ==\n\n"
"HTTP/1.0 %u \n",
res->h.c, res->payload_len, res->mime_type ? res->mime_type : (_u8*)"(none)",
res->code);
for (i=0;i<res->h.c;i++)
fprintf(out,"%s: %s\n", res->h.v1[i], res->h.v2[i]);
fprintf(out,"\n");
if (res->payload_len)
fwrite(res->payload,res->payload_len > MAXTRACEITEM ? MAXTRACEITEM : res->payload_len,1,out);
if (res->payload_len > MAXTRACEITEM)
fprintf(out,"\n*** DATA TRUNCATED DUE TO SIZE LIMITS ***");
fprintf(out,"\n\n== END OF TRANSACTION ==\n");
fclose(out);
close(f);
return dump_fn;
}
/* Use Flare to decode Flash file, if available. */
static void decode_flash(struct http_response* res) {
_s32 f, pid;
_u8 tmp[1024];
struct stat st;
if (!dumped_already || !res->payload_len) return; /* ? */
sprintf(tmp,"%s.swf",dump_fn);
f = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (f < 0) return;
write(f, res->payload, res->payload_len);
close(f);
if (!(pid = fork())) {
/* Flare is way too noisy, let's close stderr. */
close(2);
execl("./flare","flare",tmp,NULL);
execlp("flare","flare",tmp,NULL);
exit(1);
}
if (pid > 0) waitpid(pid, (int*)&f, 0);
unlink(tmp);
sprintf(tmp,"%s.flr",dump_fn);
if (stat(tmp,&st) || !st.st_size) unlink(tmp);
/* So we should have a non-zero length .flr file next to a trace file
now; ratproxy-report.sh will detect this. */
}
/* A "fuzzy" comparator to avoid reporting "refresher" cookies where some minor parameters
were changed as new cookie arrivals; but to detect blanking or other major overwrites. */
static _u8 unique_cookies(struct naive_list2* reqc, struct naive_list2* resc) {
_u32 i,j;
if (!resc->c) return 0; /* No cookies set at all. */
if (!reqc->c) return 1; /* All set cookies must be new. */
for (i=0;i<resc->c;i++) {
for (j=0;j<reqc->c;j++) {
if (!strcasecmp(resc->v1[i],reqc->v1[j]) && /* Same name */
strlen(resc->v2[i]) == strlen(reqc->v2[j])) /* Same length */
break; /* ...must be a refresher cookie. */
}
/* No refresher cookie matches for one cookie? Good enough. */
if (j == reqc->c) return 1;
}
/* All cookies were refreshers. */
return 0;
}
/* Cookie renderer, for reporting purposes. */
static _u8* make_cookies(struct naive_list2* reqc, struct naive_list2* resc) {
_u8* ret = 0;
_u32 i,j;
_u8 had_some = 0;
if (!resc->c) return "-";
#define ALLOC_STRCAT(dest,src) do { \
_u32 _sl = strlen(src); \
_u32 _dl = 0; \
if (dest) _dl = strlen(dest); \
dest = realloc(dest,_sl + _dl + 1); \
if (!dest) fatal("out of memory"); \
strcpy(dest + _dl, src); \
} while (0)
for (i=0;i<resc->c;i++) {
/* Render only newly set cookies! */
for (j=0;j<reqc->c;j++) {
if (!strcasecmp(resc->v1[i],reqc->v1[j]) && /* Same name */
strlen(resc->v2[i]) == strlen(reqc->v2[j])) /* Same length */
break; /* ...must be a refresher cookie. */
}
if (j == reqc->c) {
if (!had_some) had_some = 1; else ALLOC_STRCAT(ret,"; ");
ALLOC_STRCAT(ret,resc->v1[i]);
ALLOC_STRCAT(ret,"=");
ALLOC_STRCAT(ret,resc->v2[i]);
}
}
return ret ? ret : (_u8*)"-";
}
/* Check for safe JSON prologues. */
static _u8 is_json_safe(_u8* str) {
_u32 i = 0;
while (json_safe[i]) {
if (!strncmp(str,json_safe[i],strlen(json_safe[i]))) return 1;
i++;
}
return 0;
}
/* Check for scripts that appear to be standalone or empty (as opposed to
JSON-like dynamically generated response snippets for on-page execution). */
static _u8 standalone_script(_u8* str) {
if (!str) return 1; /* Empty */
skip_more:
while (*str && isspace(*str)) str++;
if (!strncmp(str,"/*",2)) {
str = strstr(str+2, "*/");
if (!str) return 1; /* Empty */
goto skip_more;
}
if (!strncmp(str,"//",2)) {
str += 2;
while (*str && strchr("\r\n",*str)) str++;
goto skip_more;
}
if (*str == '(') { str++; goto skip_more; }
if (!*str) return 1; /* Empty */
/* This is not very scientific - in fact, there is no good way to
settle this - but should be a pretty good predictor in most cases. */
if (!strncasecmp(str,"var",3) && isspace(str[3])) return 1; /* Script */
if (!strncasecmp(str,"function",8) && isspace(str[8])) return 1; /* Script */
return 0; /* Probably JSON */
}
/* The main request handling and routing routine. */
static void handle_client(FILE* client) {
FILE *server;
struct http_request* req;
struct http_response* res;
_u8 m;
_u32 i;
_u8 got_xss = 0;
#define BEST_MIME (res->sniffed_mime ? res->sniffed_mime : \
(res->mime_type ? res->mime_type : (_u8*)""))
/* TODO: Ideally, S() shouldn't do HTML escaping in machine
output (just filter | and control chars); but this requires
ratproxy-report.sh to be reworked. */
// Request printer macros - since most of the data does not change.
#define SHOW_REF_MSG(warn,mesg,mod) \
sayf("%u|%u|%s|-|%u|%u|%s|http%s://%s:%u/%s%s%s|-|%s|-|%s|-|-|-\n", \
warn, mod, mesg, res->code, res->payload_len, res->mime_type ? \
res->mime_type : (_u8*)"-", req->from_ssl ? "s" : "", S(req->host,0), req->port, \
S(req->path,0), req->query ? "?" : "", req->query ? \
S(req->query,0) : (_u8*)"", save_trace(req,res), S(req->referer,0))
#define SHOW_MSG(warn,mesg,off_par,mod) \
sayf("%u|%u|%s|%s|%u|%u|%s|%s|%s|%s|%s|http%s://%s:%u/%s%s%s|%s|%s|%s\n", \
warn, mod ,mesg, off_par ? S(off_par,0) : (_u8*)"-", \
res->code, res->payload_len, \
res->mime_type ? S(res->mime_type,0) : (_u8*)"-", \
res->sniffed_mime ? S(res->sniffed_mime,0) : (_u8*)"-", \
res->charset ? S(res->charset,0) : (_u8*)"-", \
save_trace(req,res), \
S(req->method,0), req->from_ssl ? "s" : "", S(req->host,0), \
req->port, S(req->path,0), req->query ? "?" : "", \
req->query ? S(req->query,0) : (_u8*)"", \
S(make_cookies(&req->cookies,&res->cookies),0), \
req->payload_len ? S(stringify_payload(req),0) : (_u8*)"-", \
res->payload_len ? S(res->payload,0) : (_u8*)"-")
/* First, let's collect and complete the request */
req = collect_request(client,0,0);
server = open_server_complete(client, req);
if (req->is_connect) {
ssl_setup();
ssl_start(fileno(server),fileno(client));
fclose(client); fclose(server);
client = fdopen(ssl_cli_tap,"w+");
server = fdopen(ssl_srv_tap,"w+");
if (!client || !server) fatal("out of memory");
req = collect_request(client, req->host, req->port);
}
res = send_request(client, server, req, 0);
send_response(client,res);
if (req->from_ssl) ssl_shutdown();
/* Now, if the target is not within the set of tested domains,
there are several things we want to check if it originated
from within the tested locations. */
if (!host_ok(req->host)) {
_u8 *refq;
if (!req->ref_host) goto skip_tests;
/* Requests between non-analyzed sites do not concern us. */
if (!host_ok(req->ref_host)) goto skip_tests;
/* Referer token leakage test: contains_token() succeeds on "Referer" query */
if ((refq=strchr(req->referer,'?'))) {
struct naive_list_p p = { 0, 0, 0, 0, 0 };
_u32 i;
parse_urlencoded(&p,refq + 1);
for (i=0;i<p.c;i++)
if (contains_token(p.v1[i],p.v2[i])) break;
if (i != p.c)
SHOW_REF_MSG(3,"Referer may leak session tokens",1);
}
/* Cross-domain script inclusion check */
detect_mime(res);
if (rp_strcasestr(BEST_MIME,"script") ||
!strcasecmp(BEST_MIME,"application/json")|| !strcasecmp(BEST_MIME,"text/css"))
SHOW_REF_MSG(3,"External code inclusion",1);
/* POST requests between domains - outgoing. */
if (strcmp(req->method,"GET")) {
SHOW_REF_MSG(2,"Cross-domain POST requests",0);
} else if (log_active) {
i = 0;
while (active_mime[i]) {
if (!strcasecmp(BEST_MIME,active_mime[i])) {
SHOW_REF_MSG(1,"References to external active content",1);
break;
}
i++;
}
}
goto skip_tests;
}
/* All right, everything below pertains to checks on URLs within
the tested domain. Let's do some basic information gathering first. */
checksum_response(res);
detect_mime(res);
if (res->is_text)
detect_charset(res);
if (dump_urls) SHOW_MSG(0,"!All visited URLs",0,0);
/* If requested to do so, we need to log non-HTTPS traffic and
prioritize it depending on document type. */
if (log_mixed && !req->from_ssl) {
m = get_modifiers(req,res);
if (!strcasecmp(BEST_MIME,"text/html") || rp_strcasestr(BEST_MIME,"script") ||
!strcasecmp(BEST_MIME,"application/json") ||
!strcasecmp(BEST_MIME,"text/css") || !strcasecmp(BEST_MIME,"application/xhtml+xml"))
SHOW_MSG(2,"Potential mixed content",0,m);
else SHOW_MSG(0,"Potential mixed content",0,m);
}
/* If instructed to do so, adjust XSRF "safety" rating based on packet
replay now. */
if (try_attacks) try_replay_xsrf(req,res);
/***********************
* HEADER BASED CHECKS *
***********************/
if (res->code < 200 || res->code >= 400) {
switch (NOECHO(m = get_modifiers(req,res))) {
/* No big deal, but warrants an investigation; more important if
the content is user-specific. */
case 0:
case MOD_PRED:
SHOW_MSG(0,"HTTP errors",0,m); break;
case MOD_AUTH:
case MOD_PRED | MOD_AUTH:
SHOW_MSG(1,"HTTP errors",0,m); break;
}
}
/* Detect 302 with Location: that contains req->query or req->payload,
and lacks XSRF token? */
if (res->location && (req->query || req->payload) && !req->xsrf_safe) {
_u8* hname = strdup(res->location), *y;
if (!hname) fatal("out of memory");
if (!strncasecmp(hname,"http://",7)) hname += 7; else
if (!strncasecmp(hname,"https://",8)) hname += 8;
y = hname;
while (isalnum(*y) || *y == '-' || *y == '.') y++;
*y = 0;
if (hname[0] && ((req->query && rp_strcasestr(req->query,hname)) ||
(req->payload && rp_strcasestr(req->payload,hname)))) {
SHOW_MSG(3,"HTTP redirector",0,1);
}
}
/* If not a HTTP redirector, examine for HTML redirection anyway */
if (!res->location && (req->query || req->payload) && res->payload && !req->xsrf_safe) {
_u8* mref=rp_strcasestr(res->payload,"HTTP-EQUIV=\"Refresh\"");
_u8* hname = mref ? rp_strcasestr(mref + 20, ";URL=") : 0;
if (hname) {
_u8* mrefend = strchr(mref + 20,'>'), *y;
if (mrefend && hname < mrefend) {
hname = strdup(hname + 5);
if (!hname) fatal("out of memory");
if (!strncasecmp(hname,"http://",7)) hname += 7; else
if (!strncasecmp(hname,"https://",8)) hname += 8;
y = hname;
while (isalnum(*y) || *y == '-' || *y == '.') y++;
*y = 0;
if (hname[0] && ((req->query && rp_strcasestr(req->query,hname)) ||
(req->payload && rp_strcasestr(req->payload,hname)))) {
SHOW_MSG(3,"HTML META redirector",0,1);
}
}
}
}
if (req->multipart) {
m = get_modifiers(req,res);
SHOW_MSG(0,"File upload forms",0,m);
}
if (all_post && req->payload && strcasecmp(req->method,"GET")) {
m = get_modifiers(req,res);
SHOW_MSG(0,"All POST requests",0,m);
}
if (unique_cookies(&req->cookies,&res->cookies) && !req->xsrf_safe && (req->payload || req->query)) {
m = get_modifiers(req,res);
SHOW_MSG(2,"Cookie issuer with no XSRF protection",0,m);
/* TODO: Maybe check if query data copied over to cookies. */
}
if (all_cookie && unique_cookies(&req->cookies,&res->cookies)) {
m = get_modifiers(req,res);
SHOW_MSG(0,"All cookie setting URLs",0,m);