/
Project_Search_Based_WebFuzzer.ipynb
1801 lines (1801 loc) · 92.8 KB
/
Project_Search_Based_WebFuzzer.ipynb
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Project 3 - Search-Based Web Fuzzer "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import bookutils.setup"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n",
"\n",
"Fuzzing web applications can be challenging. A simple web form requires a specific input format for each field, this format needs to be fulfilled for a valid web interaction (e.g. an email field is expected to fulfill the following regex pattern `r'^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$')`.\n",
"\n",
"In this project, we demonstrate how to apply a search-based algorithm to generate specific test inputs for web interfaces. The generated inputs should exercise the web application by fulfilling the input validation requirements of all fields required to reach specific web pages (both normal and error pages). \n",
"\n",
"The task is to employ a genetic algorithm (GA) for fuzzing, your implementation is expected to generate inputs that match the expected pattern or constraints of the input field (e.g. email fuzzingbook@gmail.com fulfils the expected email regex pattern `r'^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$')`. This is to be achieved by searching the input space starting from an initially (random) input. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from WebFuzzer import init_db, ORDERS_DB, SimpleHTTPRequestHandler \n",
"from http.server import HTTPServer, HTTPStatus "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Objective\n",
"\n",
"The goal of this project is to _implement a search-based fuzzing algorithm that generates specifically formatted inputs which fulfil the input validation requirements of a web form_. \n",
"\n",
"You will apply techniques learned in the lecture ([SBST](SBST.ipynb) and [WebFuzzer](WebFuzzer.ipynb)) to automatically fill web forms by producing inputs that improve the reachability of web pages. \n",
"\n",
"The goal of your Fuzzer is to cleverly search the input space until the input validation format of the input field is achieved. Consequently, fulfilling (or not fulfilling) such input validation schemes achieves the reachability of specific web pages and improves the coverage of the site map. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Web Application\n",
"\n",
"We create a (HTML only) web application for placing an order of items, similar to the order form in the [WebFuzzer](WebFuzzer.ipynb) lecture.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Input Validation\n",
"\n",
"We create a `ProjectHTTPRequestHandler` class that provides a web order form with input validation schemes for all input formats. \n",
"\n",
"First, we create a sample set of regex for input validation of each input field in our order form. \n",
"\n",
"__Note that your implementation shall be evaluated with a _secret set of regex_ other than the ones provided below.__\n",
"\n",
"For some input fields, we have provided other sample regexes you may use to test your implementation, other regexes are provided to inform you of the nature of the regexes which may be used to evaluate your final solution. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"itemList = r'^(tshirt|drill|lockset)$'\n",
"name_regex = [r'^[A-Z][a-z]+ [A-Z][a-z]+ [A-Z][a-z]+$', r'^[A-Z][a-z]+ [A-Z]\\. [A-Z][a-z]+$', \\\n",
" r'^[A-Z][a-z]+ [A-Z][a-z]+$', r'[a-z]+ [a-z]+$']\n",
"email_regex = [r'^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$', r'^([a-z0-9_\\.-]+)@cispa\\.saarland$', \\\n",
" r'^([a-z0-9_\\.-]+)@gmail\\.com$', r'^([a-z0-9_\\.-]+)@hotmail\\.co\\.uk$']\n",
"zip_regex = [r'^\\d{5}$', r'\\d{3}-\\d{4}', r'\\d{5}([ \\-]\\d{4})?', \\\n",
" r'[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJ-NPRSTV-Z][ ]?\\d[ABCEGHJ-NPRSTV-Z]\\d']\n",
"city_regex = [r'[A-Z]\\w{2,9}$', r'^[a-zA-Z]+(?:[\\s-][a-zA-Z]+)*$', r'^\\p{Lu}\\p{L}*(?:[\\s-]\\p{Lu}\\p{L}*)*$', r'\\w{2,12}$']\n",
"terms_regex = r'on'\n",
"\n",
"list_regex = [itemList, name_regex[0], email_regex[0], city_regex[0], zip_regex[0], terms_regex]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We define diagnostic error messages for each error page."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"error_msg_list = [\"INCOMPLETE INPUT: \\n All fields have to be filled \",\\\n",
" \"INVALID INPUT: \\n Item is not in item list\",\\\n",
" \"INVALID INPUT: \\n Name does not match expected pattern :\\n \",\\\n",
" \"INVALID INPUT: \\n Email does not match expected pattern :\\n \",\\\n",
" \"INVALID INPUT: \\n City does not match expected pattern :\\n \",\\\n",
" \"INVALID INPUT: \\n Zip does not match expected pattern :\\n \",\\\n",
" \"INVALID INPUT: \\n Terms and Conditions have to be checked \"\n",
" ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We override the `handle_order()` method, to validate the values of each input field using the pre-defined regex patterns above. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import re\n",
"\n",
"class ProjectHTTPRequestHandler(SimpleHTTPRequestHandler):\n",
" def handle_order(self): \n",
" values = self.get_field_values()\n",
"\n",
" if len(values) < 6:\n",
" error_type = error_msg_list[0]\n",
" self.internal_server_error(error_type)\n",
" \n",
" elif re.match(list_regex[0], values[\"item\"]) and re.match(list_regex[1], values[\"name\"]) and \\\n",
" re.match(list_regex[2], values[\"email\"]) and re.match(list_regex[4], values[\"zip\"]) and \\\n",
" re.match(list_regex[3], values[\"city\"]) and re.match(list_regex[5], values[\"terms\"]):\n",
" self.store_order(values)\n",
" self.send_order_received(values)\n",
"\n",
" elif not re.match(list_regex[0], values[\"item\"]):\n",
" error_type = error_msg_list[1]\n",
" self.internal_server_error(error_type) \n",
" \n",
" elif not re.match(list_regex[1], values[\"name\"]):\n",
" error_type = error_msg_list[2] + name_regex[0] \n",
" self.internal_server_error(error_type)\n",
" \n",
" elif not re.match(list_regex[2], values[\"email\"]):\n",
" error_type = error_msg_list[3] + email_regex[0]\n",
" self.internal_server_error(error_type)\n",
" \n",
" elif not re.match(list_regex[3], values[\"city\"]):\n",
" error_type = error_msg_list[5] + city_regex[0]\n",
" self.internal_server_error(error_type)\n",
" \n",
" elif not re.match(list_regex[4], values[\"zip\"]):\n",
" error_type = error_msg_list[4] + zip_regex[0]\n",
" self.internal_server_error(error_type)\n",
" \n",
" elif not re.match(list_regex[5], values[\"terms\"]):\n",
" error_type = error_msg_list[6]\n",
" self.internal_server_error(error_type)\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Internal Errors\n",
"For diagnostic (and identification) purposes, the internal server error pages include the error message indicating the input validation scheme that failed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"HTML_INTERNAL_SERVER_ERROR = \"\"\"\n",
"<html><body>\n",
"<div style=\"border:3px; border-style:solid; border-color:#FF0000; padding: 1em;\">\n",
" <strong id=\"title\" style=\"font-size: x-large\">Internal Server Error</strong>\n",
" <p>\n",
" The server has encountered an internal error. Go to our <a href=\"/\">order form</a>.\n",
" <pre>{error_message}</pre>\n",
" </p>\n",
"</div>\n",
"</body></html>\n",
" \"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"import traceback\n",
"\n",
"class ProjectHTTPRequestHandler(ProjectHTTPRequestHandler):\n",
" def internal_server_error(self, error_type=None):\n",
" self.send_response(HTTPStatus.OK, \"Internal Error\")\n",
"\n",
" self.send_header(\"Content-type\", \"text/html\")\n",
" self.end_headers()\n",
"\n",
" exc = traceback.format_exc()\n",
" self.log_message(\"%s\", exc.strip())\n",
"\n",
" message = HTML_INTERNAL_SERVER_ERROR.format(error_message=error_type)\n",
" self.wfile.write(message.encode(\"utf8\"))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from bookutils import HTML \n",
"HTML(HTML_INTERNAL_SERVER_ERROR)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Storing Orders"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similar to the [WebFuzzer](WebFuzzer.ipynb) lecture, we store orders using a *database* stored in the file `orders.db`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"FUZZINGBOOK_SWAG = {\n",
" \"tshirt\": \"One FuzzingBook T-Shirt\",\n",
" \"drill\": \"One FuzzingBook Rotary Hammer\",\n",
" \"lockset\": \"One FuzzingBook Lock Set\"\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import sqlite3, os\n",
"\n",
"class ProjectHTTPRequestHandler(ProjectHTTPRequestHandler):\n",
" def store_order(self, values):\n",
" db = sqlite3.connect(ORDERS_DB)\n",
" db.execute(\"INSERT INTO orders VALUES (?, ?, ?, ?, ?, ?)\",\n",
" (values['item'], values['name'], values['email'], values['city'], values['zip'], values['terms']))\n",
" db.commit()\n",
"\n",
" def send_order_received(self, values):\n",
" # Should use html.escape()\n",
" values[\"item_name\"] = FUZZINGBOOK_SWAG[values[\"item\"]]\n",
" confirmation = HTML_ORDER_RECEIVED.format(**values).encode(\"utf8\")\n",
"\n",
" self.send_response(HTTPStatus.OK, \"Order received\")\n",
" self.send_header(\"Content-type\", \"text/html\")\n",
" self.end_headers()\n",
" self.wfile.write(confirmation)\n",
" \n",
"\"\"\"\n",
"\n",
" def send_order_received(self, values):\n",
" sanitized_values = {}\n",
" for field in values:\n",
" sanitized_values[field] = html.escape(values[field])\n",
" sanitized_values[\"item_name\"] = html.escape(\n",
" FUZZINGBOOK_SWAG[values[\"item\"]])\n",
"\n",
" confirmation = HTML_ORDER_RECEIVED.format(\n",
" **sanitized_values).encode(\"utf8\")\n",
"\n",
" self.send_response(HTTPStatus.OK, \"Order received\")\n",
" self.send_header(\"Content-type\", \"text/html\")\n",
" self.end_headers()\n",
" self.wfile.write(confirmation)\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def init_db():\n",
" if os.path.exists(ORDERS_DB):\n",
" os.remove(ORDERS_DB)\n",
"\n",
" db_connection = sqlite3.connect(ORDERS_DB)\n",
" db_connection.execute(\"DROP TABLE IF EXISTS orders\")\n",
" db_connection.execute(\"CREATE TABLE orders (item text, name text, email text, city text, zip text, terms text)\")\n",
" db_connection.commit()\n",
"\n",
" return db_connection\n",
"\n",
"db = init_db()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(db.execute(\"SELECT * FROM orders\").fetchall())\n",
"\n",
"db.execute(\"INSERT INTO orders \" +\n",
" \"VALUES ('lockset', 'Jane Lee Doe', 'jane@doe.com', 'Saarbrucken', '66125', 'on')\")\n",
"db.commit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(db.execute(\"SELECT * FROM orders\").fetchall())\n",
"\n",
"\n",
"db.execute(\"DELETE FROM orders WHERE name = 'Walter White'\")\n",
"db.commit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(db.execute(\"SELECT * FROM orders\").fetchall())"
]
},
{
"cell_type": "markdown",
"metadata": {
"toc-hr-collapsed": false
},
"source": [
"### Order Confirmation\n",
"\n",
"Once we have gotten an order, we show a confirmation page, which is instantiated with the customer information submitted before."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"button": false,
"new_sheet": false,
"run_control": {
"read_only": false
},
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"HTML_ORDER_RECEIVED = \"\"\"\n",
"<html><body>\n",
"<div style=\"border:3px; border-style:solid; border-color:#FF0000; padding: 1em;\">\n",
" <strong id=\"title\" style=\"font-size: x-large\">Thank you for your Fuzzingbook Order!</strong>\n",
" <p id=\"confirmation\">\n",
" We will send <strong>{item_name}</strong> to {name} in {city}, {zip}<br>\n",
" A confirmation mail will be sent to {email}.\n",
" </p>\n",
" <p>\n",
" Want more swag? Use our <a href=\"/\">order form</a>!\n",
" </p>\n",
"</div>\n",
"</body></html>\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Logging \n",
"\n",
"Similar to the [WebFuzzer](WebFuzzer.ipynb) lecture, we provide a logging infrastructure for debugging purposes. We implement the following:\n",
"- `print_httpd_messages()` prints all messages accumulated in the queue\n",
"- `clear_httpd_messages()` discards all pending messages\n",
"- `log_message()` store messages in the queue "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from multiprocess import Queue, Process"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from bookutils import rich_output, terminal_escape, unicode_escape, HTML"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"HTTPD_MESSAGE_QUEUE = Queue()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def display_httpd_message(message):\n",
" if rich_output():\n",
" display(\n",
" HTML(\n",
" '<pre style=\"background: NavajoWhite;\">' +\n",
" message +\n",
" \"</pre>\"))\n",
" else:\n",
" print(terminal_escape(message))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def print_httpd_messages():\n",
" while not HTTPD_MESSAGE_QUEUE.empty():\n",
" message = HTTPD_MESSAGE_QUEUE.get()\n",
" display_httpd_message(message)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def clear_httpd_messages():\n",
" while not HTTPD_MESSAGE_QUEUE.empty():\n",
" HTTPD_MESSAGE_QUEUE.get()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class ProjectHTTPRequestHandler(ProjectHTTPRequestHandler):\n",
" def log_message(self, format, *args):\n",
" message = (\"%s - - [%s] %s\\n\" %\n",
" (self.address_string(),\n",
" self.log_date_time_string(),\n",
" format % args))\n",
" HTTPD_MESSAGE_QUEUE.put(message)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Extend `webbrowser()` method to prints log messages produced by the server:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from Carver import webbrowser as simple_webbrowser\n",
"\n",
"def webbrowser(url, mute=False):\n",
" try:\n",
" contents = simple_webbrowser(url)\n",
" finally:\n",
" if not mute:\n",
" print_httpd_messages()\n",
" else:\n",
" clear_httpd_messages()\n",
"\n",
" return contents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running the Web Application\n",
"Similar to the [WebFuzzer](WebFuzzer.ipynb) lecture, to run the web application we implement the following:\n",
"\n",
"* `run_httpd_forever()`\n",
"* `start_httpd()`\n",
"* `print_url()`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def run_httpd_forever(handler_class):\n",
" host = \"127.0.0.1\" # localhost IP\n",
" for port in range(8800, 9000):\n",
" httpd_address = (host, port)\n",
"\n",
" try:\n",
" httpd = HTTPServer(httpd_address, handler_class)\n",
" break\n",
" except OSError:\n",
" continue\n",
"\n",
" httpd_url = \"http://\" + host + \":\" + repr(port)\n",
" HTTPD_MESSAGE_QUEUE.put(httpd_url)\n",
" httpd.serve_forever()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def start_httpd(handler_class=ProjectHTTPRequestHandler):\n",
" clear_httpd_messages()\n",
"\n",
" httpd_process = Process(target=run_httpd_forever, args=(handler_class,))\n",
" httpd_process.start()\n",
"\n",
" httpd_url = HTTPD_MESSAGE_QUEUE.get()\n",
" return httpd_process, httpd_url"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"httpd_process, httpd_url = start_httpd(ProjectHTTPRequestHandler)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def print_url(url):\n",
" if rich_output():\n",
" display(HTML('<pre><a href=\"%s\">%s</a></pre>' % (url, url)))\n",
" else:\n",
" print(terminal_escape(url))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print_url(httpd_url)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note**: The above URL only works if you are running the Jupyter notebook server on the local host."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Testing the Web Application\n",
"### Input Format\n",
"\n",
"When the user clicks `Submit` on the order form, the Web browser creates and retrieves a URL of the form:\n",
"\n",
"```\n",
"<hostname>/order?item=value_1&name=value_2&email=value_3&city=value_4&zip=value_5&terms=value_6\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We test standard behavior:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"standard_order = \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=on\"\n",
"contents = webbrowser(httpd_url + standard_order)\n",
"HTML(contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert contents.find(\"Thank you\") and contents.find(\"We will send\") and contents.find(\"A confirmation mail will be sent to\") > 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We test erroneous behavior - terms and conditions not checked:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"error_order = \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=off\"\n",
"contents = webbrowser(httpd_url + error_order)\n",
"HTML(contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert contents.find(\"Internal Server Error\") and contents.find(error_msg_list[6]) > 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We test incomplete order behavior:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"incomplete_order = \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104\"\n",
"contents = webbrowser(httpd_url + incomplete_order)\n",
"HTML(contents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert contents.find(\"Internal Server Error\") and contents.find(error_msg_list[0]) > 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To test for another input validaion regex (e.g. the second regex pattern for each field - index 1), use:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"list_regex = [itemList, name_regex[1], email_regex[1], city_regex[1], zip_regex[1], terms_regex]\n",
"httpd_process, httpd_url = start_httpd(ProjectHTTPRequestHandler)\n",
"print_url(httpd_url)\n",
"new_regex_standard_order = \"/order?item=tshirt&name=Jane+L.+Doe&email=doe%40cispa.saarland&city=Seattle&zip=984-1234&terms=on\"\n",
"contents = webbrowser(httpd_url + new_regex_standard_order)\n",
"HTML(contents)\n",
"assert contents.find(\"Thank you\") and contents.find(\"We will send\") and contents.find(\"A confirmation mail will be sent to\") > 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we reset the server to use the first set of regex for input validation (index 0):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"list_regex = [itemList, name_regex[0], email_regex[0], city_regex[0], zip_regex[0], terms_regex]\n",
"httpd_process, httpd_url = start_httpd(ProjectHTTPRequestHandler)\n",
"print_url(httpd_url)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Test for the first set of regex again:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"contents = webbrowser(httpd_url + standard_order)\n",
"assert contents.find(\"Thank you\") and contents.find(\"We will send\") and contents.find(\"A confirmation mail will be sent to\") > 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Coverage of Web App \n",
"In this project, the coverage of the web app is defined as _web reachability_, i.e. the number of reached pages on the site. \n",
"\n",
"We reachability is a proxy measurement of the number of validation schemes passed/failed and also a proxy measurement of brach coverage in the `handle_order()` method. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Obtaining Coverage\n",
"\n",
"We define the `target_list` for each web page accordingly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"target_list:\n",
" ISE_Name = Internal Server Error Web Page for \"Name\" field error, analogously for ISE_Item, ISE_City, etc..\n",
" ISE_INC = Internal Server Error Web Page for \"Incomplete Input\" \n",
" PNF = Page Not Found Web Page\n",
" CONF = CONFIRMATION_PAGE\n",
"\"\"\"\n",
"\n",
"target_list = [\"ISE_INC\", \"ISE_Item\", \"ISE_Name\", \"ISE_Email\", \"ISE_Zip\", \"ISE_City\",\"ISE_Terms\", \"CONF\", \"PNF\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To obtain the overall coverage achieved by the GA's resulting population, we implement the following web reachability function. \n",
"\n",
"For each target, we compute:\n",
"* _validity_ score: the number of valid inputs in the generated population that reach the target, and\n",
"* _reachability_ score: we score the number of inputs that reach the each page. \n",
"\n",
"The reachability scores for the number of inputs reaching the targeted is based on the perceived difficulty to reach the page:\n",
"* 2 points for each input reaching an error page\n",
"* 5 points for each input reaching the confirmation page\n",
"* 1 point for each input reaching the page not found page\n",
"\n",
"**Note**: we expect each run of your genetic algorithm to produce 10 inputs maximum."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def get_web_reachability(orders, target):\n",
" num_reached_pages = dict() \n",
" reachability, validity = 0, 0\n",
" conf_msg = [\"Thank you\", \"We will send\", \"A confirmation mail will be sent to\"]\n",
" page_not_found = \"This page does not exist\"\n",
" \n",
" for order in orders:\n",
" clear_httpd_messages()\n",
" contents = webbrowser(httpd_url + order, mute=True)\n",
" HTML(contents)\n",
"\n",
" # obtain 2 reachability points for each input reaching an error page\n",
" if contents.find(\"Internal Server Error\") > 0:\n",
" if target_list.index(target) <= 6:\n",
" msg = error_msg_list[target_list.index(target)]\n",
" if contents.find(msg) > 0: \n",
" if not msg in num_reached_pages:\n",
" num_reached_pages[msg] = 2\n",
" else:\n",
" num_reached_pages[msg] += 2\n",
" validity += 1\n",
"\n",
" # obtain 5 reachability points for each input reaching confirmation page\n",
" if target == target_list[7] and contents.find(conf_msg[0]) > 0 and contents.find(conf_msg[1]) > 0 \\\n",
" and contents.find(conf_msg[2]) > 0:\n",
" if not conf_msg[0] in num_reached_pages:\n",
" num_reached_pages[conf_msg[0]] = 5\n",
" else:\n",
" num_reached_pages[conf_msg[0]] += 5\n",
" validity += 1\n",
" \n",
" # obtain 1 reachability point for each input reaching a non-existent page\n",
" if target == target_list[8] and contents.find(page_not_found) > 0:\n",
" if not page_not_found in num_reached_pages:\n",
" num_reached_pages[page_not_found] = 1\n",
" else:\n",
" num_reached_pages[page_not_found] += 1\n",
" validity += 1\n",
" \n",
" \n",
" if len(num_reached_pages) > 0:\n",
" reachability = sum(num_reached_pages.values())\n",
" return reachability, validity"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We test the `get_web_reachability` function for the `confirmation` page target with a sample list of test order URLs. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"test_orders = [\"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=off\",\\\n",
" \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=on\",\\\n",
" \"/order\", \"/none\",\\\n",
" \"/order?item=lockset&name=Jane+lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=on\",\\\n",
" \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40cispa.saarland&city=Seattle&zip=98104&terms=on\",\\\n",
" \"/order?item=book&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=on\",\\\n",
" \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=98104&terms=on\",\\\n",
" \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Seattle&zip=498104&terms=on\",\\\n",
" \"/order?item=tshirt&name=Jane+Lee+Doe&email=doe%40example.com&city=Neunkirchen&zip=98104&terms=on\",\\\n",
" ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Test for the reachability of confirmation page (\"CONF\") using the above order inputs:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"get_web_reachability(test_orders, \"CONF\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Search Based Fuzzing\n",
"\n",
"We demonstrate how a specific input format can be generated with a simple search-based algorithm and a naive fitness function. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We assume an input url with an invalid name format error:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import random, string\n",
"invalid_name_order = \"/order?item=tshirt&name=Jane+Lee+Doe1&email=doe%40example.com&city=Seattle&zip=98104&terms=on\"\n",
"contents = webbrowser(httpd_url + invalid_name_order)\n",
"HTML(contents)\n",
"assert contents.find(\"Internal Server Error\") and contents.find(error_msg_list[2]) > 0"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import urllib.parse\n",
"test_name = urllib.parse.parse_qs(invalid_name_order, keep_blank_values=True)[\"name\"][0] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We implement a naive distance function for \"name\" input field:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def naive_calculate_name_distance(name):\n",
" name_regex = r'[A-Z][a-z]+ [A-Z][a-z]+ [A-Z][a-z]+'\n",
" res = 1\n",
" if len(name.split()) == 3 and check_ascii_letters(name) and \\\n",
" check_word_size(name) and name.istitle():\n",
" res = 0\n",
" else:\n",
" if len(name.split()) == 3:\n",
" res -= 0.4\n",
" if check_ascii_letters(name):\n",
" res -= 0.35\n",
" if check_word_size(name):\n",
" res -= 0.15\n",
" if name.istitle():\n",
" res -= 0.10\n",
" return res \n",
"\n",
"def check_ascii_letters(name):\n",
" res = True\n",
" for char in name.replace(\" \", \"\"):\n",
" if not (char in string.ascii_letters):\n",
" res = False\n",
" break\n",
" return res\n",
"\n",
"def check_word_size(name):\n",
" res = True\n",
" for word in name.split():\n",
" if len(word) < 2:\n",
" res = False\n",
" break\n",
" return res"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [