-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtestcases.py
4426 lines (3896 loc) · 165 KB
/
testcases.py
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
"""
HTTP Server RFC Compliance Tests
"""
import sys
import re
import dpkt
from mitmproxy import http, net
from helpers.db_util import (
Violation,
Activity,
Level,
ReqResp,
ProbeTest,
DirectTest,
RetroTest,
Url,
)
from helpers.direct_util import build_request, one_req, get_codes
from helpers.util import parse_headers
from helpers import syntax_validation as checks
class continue_before_upgrade:
title = """
If a client sends both Upgrade and Expect 100-continue, a server must send a response with 100 first and then one with code 101
"""
description = """
If a server receives both an Upgrade and an Expect header field with the "100-continue" expectation (Section 10.1.1), the server MUST send a 100 (Continue) response before sending a 101 (Switching Protocols) response.
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-upgrade"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send both upgrade and expect 100-continue (apache only send 100 if request advertises content!)"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
req = build_request(
url.host,
url.port,
request_target=url.path,
connection_header=b"Connection: upgrade\r\n",
additional_headers=b"Upgrade: https\r\nExpect: 100-continue\r\n",
)
violation = Violation.INAPPLICABLE
extra = ""
codes = get_codes(one_req(url, dt, req))
if "101" in codes:
if "100" in codes:
if codes.index("100") < codes.index("101"):
violation = Violation.VALID
else:
violation = Violation.INVALID
extra += "100 not before 101"
else:
violation = Violation.INVALID
extra += "Upgrade only (no 100)"
elif "100" in codes:
extra += "100 without upgrade"
else:
extra += "No upgrade no 100"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Send 100 first and then 101"""
response.writer.write_status(100)
response.writer.end_headers()
response.writer.write_status(101)
response.writer.write_header("Connection", "upgrade")
response.writer.write_header("Upgrade", "https")
response.writer.end_headers()
def invalid(self, request, response):
"""Only sends 101 (Problem: does not work correctly as WPTserve sends an automatic response to Expect: 100-Continue)"""
response.writer.write_status(101)
response.writer.write_header("Connection", "upgrade")
response.writer.write_header("Upgrade", "https")
response.writer.end_headers()
class reject_fields_contaning_cr_lf_nul:
title = """
Reject messages with field values containing CR, LF or NUL (or replace with SP)
"""
description = """
Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the varying ways that implementations might parse and interpret those characters; a recipient of CR, LF, or NUL within a field value MUST either reject the message or replace each of those characters with SP before further processing or forwarding of that message.
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-field-values"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send request with NUL, CR, LF in field value. (Problem: we cannot know whether they are replaced with SP? Could only check this for proxies?)"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
violation = Violation.VALID
extra = ""
for inv in [b"\x00", b"\r", b"\n"]:
req = build_request(
url.host,
url.port,
request_target=url.path,
additional_headers=b"Invalid: a" + inv + b"\r\n",
)
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
violation = Violation.UNCLEAR
elif code != "400":
extra += f"{inv} results in {code}! "
violation = Violation.INVALID
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Ignore requests with CR/LF/NUL in field value. (ignore all)"""
return 400, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Do not ignore requests with CR/LF/NUL in field value."""
return 200, [], "<div>ABC</div>"
class code_400_after_bad_host_request:
title = """
Reply with 400 to requests with bad hosts
"""
description = """
A server MUST respond with a 400 (Bad Request) status code to any HTTP/1.1 request message that lacks a Host header field and to any request message that contains more than one Host header field line or a Host header field with an invalid field value.
"""
type = Level.REQUIREMENT
category = "HTTP Headers"
source = "https://www.rfc-editor.org/rfc/rfc9112#name-request-target"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send invalid host requests (no host, 2 hosts, invalid host) and check for 400 (http/1.1)"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
for host_header, desc in [
(b"", "no host"),
(
2
* (
b"Host: "
+ url.host.encode("utf-8")
+ b":"
+ str(url.port).encode("utf-8")
+ b"\r\n"
),
"2 hosts",
),
(b"Host: abc\r\n", "invalid host"),
]:
req = build_request(
url.host,
url.port,
request_target=url.path,
host_header=host_header,
additional_headers=b"inv: a\r\ninv: ab\r\n",
)
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
violation = Violation.UNCLEAR
elif code != "400":
extra += f"{desc} results in {code}! "
violation = Violation.INVALID
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""400 for no host, duplicate host, invalid host"""
host_headers = request.headers.get_list("host", default=[])
if len(host_headers) == 1 and host_headers[0] == b"leaking.via:5001":
return 200, [], "<div>ABC</div>"
return 400, [], ""
def invalid(self, request, response):
"""Never 400"""
return 200, [], "<div>ABC</div>"
class code_501_unknown_methods:
title = """
Servers should reply with code 501 for unknown request methods
"""
description = """
An origin server that receives a request method that is unrecognized or not implemented SHOULD respond with the 501 (Not Implemented) status code.
"""
type = Level.RECOMMENDATION
category = "HTTP Methods"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-overview"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Probe statuscode with invalid HTTP method"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
for method in [b"ABC"]:
req = build_request(
url.host, url.port, method=method, request_target=url.path
)
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
violation = Violation.UNCLEAR
elif code != "501":
extra += f"{method} results in {code}! "
violation = Violation.INVALID
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Return 200 for recognized HTTP method else 501"""
code = 501
if request.method in [
"GET",
"HEAD",
"POST",
"TRACE",
"PUT",
"PATCH",
"OPTIONS",
"DELETE",
"CONNECT",
]:
code = 200
return code, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Always return 200"""
return 200, [], "<div>ABC</div>"
class code_405_blocked_methods:
title = """
Servers should reply with code 405 when the request method is not allowed for the target resource
"""
description = """
An origin server that receives a request method that is recognized and implemented, but not allowed for the target resource, SHOULD respond with the 405 (Method Not Allowed) status code.
"""
type = Level.RECOMMENDATION
category = "HTTP Methods"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-overview"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Probe statuscode with some HTTP methods (e.g., CONNECT should probably be disallowed)"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
for method in [b"TRACE", b"CONNECT"]:
req = build_request(
url.host, url.port, method=method, request_target=url.path
)
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
if violation == Violation.VALID:
violation = Violation.UNCLEAR
extra += f"{method} results in invalid response! "
elif code != "405":
extra += f"{method} results in {code}! "
violation = Violation.INVALID
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Return 200 for GET/HEAD HTTP method else 405 (Problem: Connect does not reach here)"""
code = 405
if request.method in ["GET", "HEAD"]:
code = 200
return code, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Always return 200"""
return 200, [], "<div>ABC</div>"
class content_head_request:
title = """
No Message Body in Head
"""
description = """
The HEAD method is identical to GET except that the server MUST NOT send content in the response.
"""
type = Level.REQUIREMENT
category = "HTTP Methods"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-head"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send HEAD request and check if there is data after the headers."""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
req = build_request(url.host, url.port, method=b"HEAD", request_target=url.path)
resp = one_req(url, dt, req, head_response=True)[0][0]
if type(resp) == dpkt.UnpackError:
violation = Violation.UNCLEAR
extra = f"{resp}"
elif resp.data != b"":
violation = Violation.INVALID
extra = f"Additional data to head response: {resp.data}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Does not send body for head requests"""
return 200, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Sends body for head requests"""
response.send_body_for_head_request = True
return 200, [], "<div>ABC</div>"
class allow_crlf_start:
title = """
One CRLF infront of the request line should be allowed.
"""
description = """
In the interest of robustness, a server that is expecting to receive and parse a request-line SHOULD ignore at least one empty line (CRLF) received prior to the request-line.
"""
type = Level.RECOMMENDATION
category = "HTTP/1.1"
source = "https://www.rfc-editor.org/rfc/rfc9112#name-message-parsing"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send request with CRLF before start."""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
req = build_request(url.host, url.port, request_target=url.path)
req.req_raw = b"\r\n" + req.req_raw
resp = one_req(url, dt, req)[0][0]
if type(resp) == dpkt.http.Response:
if not (resp.status[0] in ["2", "3"] or resp.status == "404"):
violation = Violation.INVALID
extra = f"Status = {resp.status}"
else:
violation = Violation.INVALID
extra = f"{resp}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Allow all messages (Problem: wptserve/python closes connection directly; after first CRLF line)"""
return 200, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Reject all messages"""
return 400, [], "<div>ABC</div>"
class reject_msgs_with_whitespace_between_startline_and_first_header_field:
title = """
Reject messages with whitespace between start-line and first header-field
"""
description = """
A recipient that receives whitespace between the start-line and the first header field MUST either reject the message as invalid or consume each whitespace-preceded line without further processing of it (i.e., ignore the entire line, along with any subsequent lines preceded by whitespace, until a properly formed header field is received or the header section is terminated).
"""
type = Level.REQUIREMENT
category = "HTTP/1.1"
source = "https://www.rfc-editor.org/rfc/rfc9112#name-message-parsing"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send invalid request: whitespace in front of (all) headers."""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
req = build_request(url.host, url.port, request_target=url.path)
req.req_raw = b"\r\n ".join(req.req_raw.split(b"\r\n")[:-2]) + b"\r\n\r\n"
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
violation = Violation.UNCLEAR
elif code != "400":
violation = Violation.INVALID
extra = f"Status: {code}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Always reject (reject messages with whitespace between start-line and first-header)"""
return 400, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Always return 200"""
return 200, [], "<div>ABC</div>"
class code_400_if_msg_with_whitespace_between_header_field_and_colon:
title = """
Server must reject (400 status code) any message with a whitespace between header field and colon
(Problem: for real websites we cannot really distinguish between whether a proxy correctly removed the whitespaces or if a server incorrectly did not reject the message)
(Add a testcase for obs-line-folding: https://www.rfc-editor.org/rfc/rfc9112#name-obsolete-line-folding)
"""
description = """
A server MUST reject, with a response status code of 400 (Bad Request), any received request message that contains whitespace between a header field name and colon.
"""
type = Level.REQUIREMENT
category = "HTTP/1.1"
source = "https://www.rfc-editor.org/rfc/rfc9112#name-field-line-parsing"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT
def test(self, url: Url) -> DirectTest:
"""Send invalid request (whitespace between header and colon)"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
req = build_request(
url.host,
url.port,
request_target=url.path,
additional_headers=b"Space : Ohno\r\n",
)
code = get_codes(one_req(url, dt, req))[0]
if "invalid response" in repr(code):
violation = Violation.UNCLEAR
elif code != "400":
violation = Violation.INVALID
extra = f"Status: {code}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Reject messages with whitespace between header and colon (reject everything)"""
return 400, [], "<div>ABC</div>"
def invalid(self, request, response):
"""Always return the same response"""
return 200, [], "<div>ABC</div>"
class content_length_2XX_connect:
title = """
No content-length header allowed for 2XX responses to connect
"""
description = """
A server MUST NOT send a Content-Length header field in any 2xx (Successful) response to a CONNECT request (Section 9.3.6)
(Request does not include a cache-control header, but CONNECT is not cacheable)
(Add additional test invalid port in connect? (A server MUST reject a CONNECT request that targets an empty or invalid port number, typically by responding with a 400 (Bad Request) status code.))
"""
type = Level.REQUIREMENT
category = "HTTP Headers"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-content-length"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT_BASE
def test(self, url: Url) -> DirectTest:
"""Send connect requests and observe behavior."""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
r_host = url.host.encode("utf-8") + b":" + str(url.port).encode("utf-8")
req = build_request(
url.host,
url.port,
request_line=b"CONNECT " + r_host + b" HTTP/1.1\r\n",
headers=b"Host: " + r_host + b"\r\n\r\n",
)
resp = one_req(url, dt, req)[0][0]
if type(resp) == dpkt.http.Response:
if (
resp.status == "200"
and resp.headers.get("content-length", None) != None
):
violation = Violation.INVALID
else:
violation = Violation.INAPPLICABLE
extra = f"{resp}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Do not return CL for connect requests"""
return 200, [], "<div>abc</div>"
def invalid(self, request, response):
"""Return content-length for connect requests (Problem: CONNECT does not reach here!)"""
return 200, [("Content-Length", 14)], "<div>abc</div>"
class transfer_encoding_2XX_connect:
title = """
A server MUST NOT send a Transfer-Encoding header field in any 2xx (Successful) response to a CONNECT request (Section 9.3.6 of [HTTP])
"""
description = """
A server MUST NOT send a Transfer-Encoding header field in any 2xx (Successful) response to a CONNECT request (Section 9.3.6 of [HTTP])
(Request does not include a cache-control header, but CONNECT is not cacheable)
"""
type = Level.REQUIREMENT
category = "HTTP Headers"
source = "https://www.rfc-editor.org/rfc/rfc9112#field.transfer-encoding"
name = sys._getframe().f_code.co_name
activity = Activity.DIRECT_BASE
def test(self, url: Url) -> DirectTest:
"""Send connect and observe TE"""
dt = DirectTest.create(url=url, name=self.name, type=self.type)
extra = ""
violation = Violation.VALID
r_host = url.host.encode("utf-8") + b":" + str(url.port).encode("utf-8")
req = build_request(
url.host,
url.port,
request_line=b"CONNECT " + r_host + b" HTTP/1.1\r\n",
headers=b"Host: " + r_host + b"\r\n\r\n",
)
resp = one_req(url, dt, req)[0][0]
if type(resp) == dpkt.http.Response:
if (
resp.status == "200"
and resp.headers.get("transfer-encoding", None) != None
):
violation = Violation.INVALID
else:
violation = Violation.INAPPLICABLE
extra = f"{resp}"
dt.violation = violation
dt.extra = extra
dt.save()
return dt
def valid(self, request, response):
"""Do not send TE"""
return 200, [], "<div>abc</div>"
def invalid(self, request, response):
"""Send TE (problem: connect does not reach here)"""
return 200, [("Transfer-Encoding", "gzip")], "<div>abc</div>"
class response_directive_no_cache:
title = """
No token form in no-cache directive
"""
description = """
This directive uses the quoted-string form of the argument syntax. A sender SHOULD NOT generate the token form (even if quoting appears not to be needed for single-entry lists).
"""
type = Level.RECOMMENDATION
category = "Cache-Control"
source = "https://www.rfc-editor.org/rfc/rfc9111#name-no-cache-2"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
"""Check that char after no-cache=? is DQUOTE (assumes quote is closed correctly)"""
cc = flow.response.headers.get("Cache-Control", "")
next_chars = re.findall("no-cache=(.)", cc)
if not next_chars:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
for next_char in next_chars:
if next_char != '"':
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
def valid(self, request, response):
"""Valid no-cache directive (CC)"""
return 200, [("Cache-Control", 'no-cache="age"')], "<div>ABC</div>"
def invalid(self, request, response):
"""Invalid no-cache directive (CC)"""
return 200, [("Cache-Control", "no-cache=age")], "<div>ABC</div>"
class response_directive_private:
title = """
No token form in private directive
"""
description = """
This directive uses the quoted-string form of the argument syntax. A sender SHOULD NOT generate the token form (even if quoting appears not to be needed for single-entry lists).
"""
type = Level.RECOMMENDATION
category = "Cache-Control"
source = "https://www.rfc-editor.org/rfc/rfc9111#name-private"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
"""Check that char after private=? is DQUOTE"""
cc = flow.response.headers.get("Cache-Control", "")
next_chars = re.findall("private=(.)", cc)
if not next_chars:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
for next_char in next_chars:
if next_char != '"':
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
def valid(self, request, response):
"""Valid private directive (CC)"""
return 200, [("Cache-Control", 'private="x-frame-options"')], "<div>ABC</div>"
def invalid(self, request, response):
"""Invalid private directive (CC)"""
return 200, [("Cache-Control", "private=x-frame-options")], "<div>ABC</div>"
class response_directive_max_age:
title = """
No Quoted String in Max Age Directive
"""
description = """
This directive uses the token form of the argument syntax: e.g., 'max-age=5' not 'max-age="5"'. A sender MUST NOT generate the quoted-string form.
"""
type = Level.REQUIREMENT
category = "Cache-Control"
source = "https://www.rfc-editor.org/rfc/rfc9111#name-max-age-2"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
"""Check that char after max-age=? is not DQUOTE"""
cc = flow.response.headers.get("Cache-Control", "")
next_chars = re.findall("max-age=(.)", cc)
if not next_chars:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
for next_char in next_chars:
if next_char == '"':
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
def valid(self, request, response):
"""Valid max-age directive (CC)"""
return 200, [("Cache-Control", "max-age=5")], "<div>ABC</div>"
def invalid(self, request, response):
"""Invalid max-age directive (CC)"""
return 200, [("Cache-Control", 'max-age="5"')], "<div>ABC</div>"
class response_directive_s_maxage:
title = """
No Quoted String in S-Maxage directive
"""
description = """
This directive uses the token form of the argument syntax: e.g., 's-maxage=10' not 's-maxage="10"'. A sender MUST NOT generate the quoted-string form.
"""
type = Level.REQUIREMENT
category = "Cache-Control"
source = "https://www.rfc-editor.org/rfc/rfc9111#name-s-maxage"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
"""Check that char after s-maxage=? is not DQUOTE"""
cc = flow.response.headers.get("Cache-Control", "")
next_chars = re.findall("s-maxage=(.)", cc)
if not next_chars:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
for next_char in next_chars:
if next_char == '"':
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
def valid(self, request, response):
"""Valid s-maxage (CC)"""
return 200, [("Cache-Control", "s-maxage=10")], "<div>ABC</div>"
def invalid(self, request, response):
"""Invalid s-maxage (CC)"""
return 200, [("Cache-Control", 's-maxage="10"')], "<div>ABC</div>"
class duplicate_fields:
title = """
Fields (headers + trailers) are not allowed to occur several times unless their definition allows it
"""
description = """
A sender MUST NOT generate multiple field lines with the same name in a message (whether in the headers or trailers) or append a field line when a field line of the same name already exists in the message, unless that fields definition allows multiple field line values to be recombined as a comma-separated list (i.e., at least one alternative of the fields definition allows a comma-separated list, such as an ABNF rule of #(values) defined in Section 5.6.1).
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-field-order"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
allow_multiple_headers = {
b"set-cookie",
b"content-language",
b"vary",
b"server-timing",
b"link",
b"accept-ch",
b"cache-control",
b"p3p",
b"content-security-policy",
b"connection",
b"referrer-policy",
b"via",
b"alt-svc",
b"content-security-policy-report-only",
b"accept-ranges",
b"allow",
b"www-authenticate",
b"pragma",
}
allow_multiple_headers_custom = {
b"x-cache-lookup",
b"eagleeye-traceid",
b"x-feserver",
b"fss-proxy",
b"x-request-id",
b"x-cache",
b"x-upstream-address",
b"lb",
b"x-amz-cf-pop",
b"x-served-by",
b"x-edgeconnect-midmile-rtt",
b"x-edgeconnect-origin-mex-latency",
b"x-xss-protection",
b"x-powered-by",
b"x-backendhttpstatus",
b"x-node",
b"traceparent",
b"tracestate",
b"x-parent-response-time",
b"x-grn",
b"x-origin-cc",
b"x-origin-ttl",
b"x-ua-compatible",
b"x-goog-hash",
b"akamai-true-ttl",
b"x-air-pt",
b"x-amz-id-2",
b"x-amz-request-id",
b"x-vhost",
b"x-rid",
b"x-ngenix-cache",
b"xkey",
}
forbidden_multiple_headers = {
b"strict-transport-security",
b"x-frame-options",
b"x-content-type-options",
b"retry-after",
b"content-type",
b"server",
b"access-control-allow-origin",
b"expires",
b"age",
b"report-to",
}
keys = set()
all_duplicates = set()
for key, _ in flow.response.headers.fields:
"""Ignore capitalization of headers"""
key = key.lower()
if key in keys:
all_duplicates.add(key)
else:
keys.add(key)
allowed_duplicates = all_duplicates & (
allow_multiple_headers | allow_multiple_headers_custom
)
forbidden_duplicates = all_duplicates & forbidden_multiple_headers
unclear_duplicates = all_duplicates - (
allow_multiple_headers
| allow_multiple_headers_custom
| forbidden_multiple_headers
)
if len(all_duplicates):
extra = f"Duplicates-Forbidden: {forbidden_duplicates}, Unclear: {unclear_duplicates}, Allowed: {allowed_duplicates}"
if len(forbidden_duplicates):
violation = Violation.INVALID
elif len(unclear_duplicates):
violation = Violation.UNCLEAR
else:
violation = Violation.VALID
return ProbeTest(
name=self.name, type=self.type, violation=violation, extra=extra
)
else:
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
def valid(self, request, response):
"""Only headers that are allowed several times occur twice"""
return (
200,
[("Content-Language", "mi"), ("Content-Language", "en")],
"<div>ABC</div>",
)
def invalid(self, request, response):
"""Header that is not allowed to occur twice."""
return 200, [("x-frame-options", "DENY"), ("x-frame-options", "SAMEORIGIN")], "<div>ABC</div>"
class content_length_1XX_204:
title = """
No Content-Length Header Field allowed for 1xx and 204
"""
description = """
A server MUST NOT send a Content-Length header field in any response with a status code of 1xx (Informational) or 204 (No Content).
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-content-length"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
status = flow.response.status_code
if 100 <= status < 200 or status == 204:
if flow.response.headers.get("Content-Length"):
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
else:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.VALID
)
else:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
def valid(self, request, response):
"""Return 204 without CL."""
response.add_required_headers = False
response.writer.write_status(204)
response.writer.end_headers()
def invalid(self, request, response):
"""Return 204 with CL."""
return 204, [("Content-Length", 14)], "<div>ABC</div>"
class send_upgrade_426:
title = """
Send Upgrade Header field with 426
"""
description = """
A server that sends a 426 (Upgrade Required) response MUST send an Upgrade header field to indicate the acceptable protocols, in order of descending preference.
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-upgrade"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
if flow.response.status_code != 426:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
if flow.response.headers.get("Upgrade"):
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
else:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
def valid(self, request, response):
"""426 with upgrade header"""
return 426, [("Upgrade", "HTTPS")], "<div>ABC</div>"
def invalid(self, request, response):
"""426 without upgrade header"""
return 426, [], "<div>ABC</div>"
class send_upgrade_101:
title = """
Server that sends a 101 response MUST send an Upgrade header field
"""
description = """
The Upgrade header field is intended to provide a simple mechanism for transitioning from HTTP/1.1 to some other protocol on the same connection. A server that sends a 101 (Switching Protocols) response MUST send an Upgrade header field to indicate the new protocol(s) to which the connection is being switched.
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-upgrade"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
if flow.response.status_code != 101:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
if flow.response.headers.get("Upgrade"):
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
else:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
def valid(self, request, response):
"""101 with Upgrade"""
return 101, [("Upgrade", "HTTPS")], "<div>ABC</div>"
def invalid(self, request, response):
"""101 without upgrade"""
return 101, [], "<div>ABC</div>"
class switch_protocol_without_client:
title = """
A server MUST NOT switch to a protocol that was not indicated by the client in the corresponding request's Upgrade header field
"""
description = """
A server MUST NOT switch to a protocol that was not indicated by the client in the corresponding requests Upgrade header field.
"""
type = Level.REQUIREMENT
category = "HTTP"
source = "https://www.rfc-editor.org/rfc/rfc9110#name-upgrade"
name = sys._getframe().f_code.co_name
activity = Activity.PROXY
def test(self, flow: http.HTTPFlow) -> ProbeTest:
"""Compare request upgrade header if upgrade is performed."""
if flow.response.status_code != 101:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INAPPLICABLE
)
client_upgrade = flow.request.headers.get("upgrade")
server_upgrade = flow.response.headers.get("upgrade")
if client_upgrade == server_upgrade:
return ProbeTest(name=self.name, type=self.type, violation=Violation.VALID)
else:
return ProbeTest(
name=self.name, type=self.type, violation=Violation.INVALID
)
def valid(self, request, response):
"""Mirror client upgrade"""
upgrade = request.headers.get("Upgrade")
if upgrade is None:
return 200, [], ""
else:
return 101, [("Upgrade", upgrade)], ""
def invalid(self, request, response):
"""Distort client upgrade"""
return (
101,
[("Upgrade", f"!not{request.headers.get('Upgrade')}")],
"<div>ABC</div>",
)
class cookie_grammar:
title = """
Cookies should follow the cookie grammar
"""
description = """
Each cookie begins with a name-value-pair, followed by zero or more attribute-value pairs. Servers SHOULD NOT send Set-Cookie headers that fail to conform to the following grammar: …
"""
type = Level.ABNF
category = "HTTP Cookies"
source = "https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1"