-
Notifications
You must be signed in to change notification settings - Fork 19
/
humble.py
2589 lines (2137 loc) · 105 KB
/
humble.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
#! /usr/bin/env python3
# 'humble' (HTTP Headers Analyzer)
# https://github.com/rfc-st/humble/
#
# MIT License
#
# Copyright (c) 2020-2024 Rafa 'Bluesman' Faura ([email protected])
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Advice:
# Use the information provided by 'humble' wisely. There is *far* more merit in
# helping others, learning and teaching than in attacking, harming or taking
# advantage. Do not just be a 'Script kiddie': if this really interests you
# learn, research and become a Security Analyst!.
# Greetings:
# Alba, Aleix, Alejandro (x3), Álvaro, Ana, Carlos (x3), David (x3), Eduardo,
# Eloy, Fernando, Gabriel, Íñigo, Joanna, Juan Carlos, Juán, Julián, Julio,
# Iván, Lourdes, Luis Joaquín, María Antonia, Marta, Miguel, Miguel Angel,
# Montse, Naiara, Pablo, Sergio, Ricardo & Rubén!.
# Standard Library imports
from time import time
from json import dump
from shutil import copyfile
from platform import system
from itertools import islice
from datetime import datetime
from csv import writer, QUOTE_ALL
from urllib.parse import urlparse
from subprocess import PIPE, Popen
from os import linesep, path, remove
from os.path import dirname, abspath
from collections import Counter, defaultdict
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import re
import ssl
import sys
import contextlib
import concurrent.futures
# Third-Party imports
from colorama import Fore, Style, init
from requests.adapters import HTTPAdapter
import requests
import tldextract
BANNER = ''' _ _ _
| |__ _ _ _ __ ___ | |__ | | ___
| '_ \\| | | | '_ ` _ \\| '_ \\| |/ _ \\
| | | | |_| | | | | | | |_) | | __/
|_| |_|\\__,_|_| |_| |_|_.__/|_|\\___|
'''
BOLD_STRINGS = ('[0.', 'HTTP R', '[1.', '[2.', '[3.', '[4.', '[5.', '[6.',
'[7.', '[Cabeceras')
CSV_SECTION = ('0section', '0headers', '1enabled', '2missing', '3fingerprint',
'4depinsecure', '5empty', '6compat', '7result')
DELETED_LINES = '\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[1A\x1b[2K'
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
EXP_HEADERS = ('activate-storage-access', 'critical-ch', 'document-policy',
'nel', 'no-vary-search', 'observe-browsing-topics',
'origin-agent-cluster', 'permissions-policy',
'reporting-endpoints', 'set-login', 'speculation-rules',
'supports-loading-mode')
FORCED_CIPHERS = ":".join(["HIGH", "!DH", "!aNULL"])
HTTP_SCHEMES = ('http:', 'https:')
HTTP_SERVER_CODES = (500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510,
511, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529,
530)
HUMBLE_DESC = "'humble' (HTTP Headers Analyzer)"
HUMBLE_DIRS = ('additional', 'l10n')
HUMBLE_FILES = ('analysis_h.txt', 'check_path_permissions', 'fingerprint.txt',
'guides.txt', 'details_es.txt', 'details.txt',
'user_agents.txt', 'insecure.txt', 'html_template.html',
'testssl.sh', 'analysis_grades.txt', 'analysis_grades_es.txt',
'license.txt', 'license_es.txt', 'testssl_windows.txt',
'testssl_windows_es.txt', 'security_guides.txt',
'security_guides_es.txt', 'security.txt')
JSON_SECTION = ('0section', '0headers', '5compat', '6result')
L10N_IDXS = {'grades': (10, 11), 'license': (12, 13), 'testssl': (14, 15),
'security_guides': (16, 17)}
OS_PATH = dirname(abspath(__file__))
PDF_CONDITIONS = ('Ref:', ':', '"', '(*) ')
RE_PATTERN = (r'\[(.*?)\]',
(r'^(?:\d{1,3}\.){3}\d{1,3}$|'
r'^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'),
(r'\.\./|/\.\.|\\\.\.|\\\.\\|'
r'%2e%2e%2f|%252e%252e%252f|%c0%ae%c0%ae%c0%af|'
r'%uff0e%uff0e%u2215|%uff0e%uff0e%u2216'), r'\[([^\]]+)\]',
r'\d{4}-\d{2}-\d{2}', r'\[(.*?)\]\n', r"'nonce-([^']+)'",
r'\(humble_pdf_style\)([^:]+):',
r'<meta\s+http-equiv=["\'](.*?)["\']\s+content=["\'](.*?)["\']\s'
r'*/?>', r'\(humble_sec_style\)([^:]+)',
r'\(humble_sec_style\)', r'(?: Nota : | Note : )')
REF_LINKS = (' Ref : ', ' Ref: ', 'Ref :', 'Ref: ', ' ref:')
SLICE_INT = (30, 43, 25, 24, -4, -5, 46, 31)
STYLE = (Style.BRIGHT, f"{Style.BRIGHT}{Fore.RED}", Fore.CYAN, Style.NORMAL,
Style.RESET_ALL, Fore.RESET, '(humble_pdf_style)',
f"(humble_sec_style){Fore.GREEN}", '(humble_sec_style)')
# Check https://testssl.sh/doc/testssl.1.html to choose your preferred options
TESTSSL_OPTIONS = ['-f', '-g', '-p', '-U', '-s', '--hints']
URL_LIST = (': https://caniuse.com/?search=', ' Ref : https://developers.clou\
dflare.com/support/troubleshooting/cloudflare-errors/troubleshooting-cloudflar\
e-5xx-errors/', ' Ref : https://developer.mozilla.org/en-US/docs/Web/HTTP/Sta\
tus/', 'https://raw.githubusercontent.com/rfc-st/humble/master/humble.py', 'ht\
tps://github.com/rfc-st/humble')
URL_STRING = ('rfc-st', ' URL : ', 'caniuse')
current_time = datetime.now().strftime("%Y/%m/%d - %H:%M:%S")
local_version = datetime.strptime('2024-12-04', '%Y-%m-%d').date()
class SSLContextAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
# Yes, certificates and hosts must always be checked/verified on HTTPS
# connections. However, within the scope of 'humble', I have chosen to
# disable these checks to allow the analysis of URLs in certain cases
# (e.g., development environments, hosts with outdated
# servers/software, self-signed certificates, etc.).
context = ssl._create_unverified_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.cert_reqs = ssl.CERT_NONE
context.set_ciphers(FORCED_CIPHERS)
kwargs['ssl_context'] = context
return super(SSLContextAdapter, self).init_poolmanager(*args, **kwargs)
def check_python_version():
exit(print_detail('[python_version]', 3)) if sys.version_info < (3, 8) \
else None
def check_updates(local_version):
try:
github_repo = requests.get(URL_LIST[3], timeout=10).text
github_date = re.search(RE_PATTERN[4], github_repo).group()
github_version = datetime.strptime(github_date, '%Y-%m-%d').date()
if github_version > local_version:
print(f"\n{get_detail('[humble_not_recent]')[:-1]}: \
'{local_version}'"f"\n\n{get_detail('[github_humble]', replace=True)}")
else:
print(f"\n{get_detail('[humble_recent]', replace=True)}")
except requests.exceptions.RequestException:
print_error_detail('[update_error]')
sys.exit()
def fng_statistics_top():
print(f"\n{STYLE[0]}{get_detail('[fng_stats]', replace=True)}\
{STYLE[4]}{get_detail('[fng_source]', replace=True)}\n")
with open(path.join(OS_PATH, HUMBLE_DIRS[0], HUMBLE_FILES[2]), 'r',
encoding='utf8') as fng_f:
fng_lines = fng_f.readlines()
fng_incl = sum(1 for _ in islice(fng_lines, SLICE_INT[0], None))
fng_statistics_top_groups(fng_lines, fng_incl)
sys.exit()
def fng_statistics_top_groups(fng_lines, fng_incl):
top_groups_pattern = re.compile(RE_PATTERN[3])
fng_top_groups = Counter(match.strip() for line in fng_lines for match in
top_groups_pattern.findall(line))
fng_statistics_top_result(fng_top_groups, fng_incl)
def fng_statistics_top_result(fng_top_groups, fng_incl):
max_ln_len = max(len(content) for content, _ in
fng_top_groups.most_common(20))
print(f"{get_detail('[fng_top]', replace=True)} {fng_incl}\
{get_detail('[fng_top_2]', replace=True)}\n")
for content, count in fng_top_groups.most_common(20):
fng_global_pct = round(count / fng_incl * 100, 2)
fng_padding = ' ' * (max_ln_len - len(content))
print(f" [{content}]: {fng_padding}{fng_global_pct:.2f}% ({count})")
def fng_statistics_term(fng_term):
print(f"\n{STYLE[0]}{get_detail('[fng_stats]', replace=True)}\
{STYLE[4]}{get_detail('[fng_source]', replace=True)}\n")
with open(path.join(OS_PATH, HUMBLE_DIRS[0], HUMBLE_FILES[2]), 'r',
encoding='utf8') as fng_source:
fng_lines = fng_source.readlines()
fng_incl = list(islice(fng_lines, SLICE_INT[0], None))
fng_groups, term_cnt = fng_statistics_term_groups(fng_incl, fng_term)
if not fng_groups:
print(f"{get_detail('[fng_zero]', replace=True)} '{fng_term}'.\n\n\
{get_detail('[fng_zero_2]', replace=True)}.\n")
sys.exit()
fng_statistics_term_content(fng_groups, fng_term, term_cnt, fng_incl)
def fng_statistics_term_groups(fng_incl, fng_term):
fng_matches = [match for line in fng_incl if
(match := re.search(RE_PATTERN[0], line)) and
fng_term.lower() in match[1].lower()]
fng_groups = sorted({match[1].strip() for match in fng_matches})
term_cnt = len(fng_matches)
return fng_groups, term_cnt
def fng_statistics_term_content(fng_groups, fng_term, term_cnt, fng_incl):
fng_pct = round(term_cnt / len(fng_incl) * 100, 2)
print(f"{get_detail('[fng_add]', replace=True)} '{fng_term}': {fng_pct}%\
({term_cnt}{get_detail('[pdf_footer2]', replace=True)} {len(fng_incl)})")
fng_statistics_term_sorted(fng_incl, fng_term.lower(), fng_groups)
def fng_statistics_term_sorted(fng_incl, fng_term, fng_groups):
for content in fng_groups:
print(f"\n [{STYLE[0]}{content}]")
content = content.lower()
for line in fng_incl:
line_l = line.lower()
if content in line_l and fng_term in line_l:
print(f" {line[:line.find('[')].strip()}")
sys.exit()
def print_l10n_file(args, l10n_file, slice_ln=False):
lang_idx = 1 if args.lang == 'es' else 0
l10n_file = HUMBLE_FILES[L10N_IDXS[l10n_file][lang_idx]]
l10n_slice = SLICE_INT[2] if args.lang == 'es' else SLICE_INT[3]
with open(path.join(OS_PATH, HUMBLE_DIRS[1], l10n_file), 'r',
encoding='utf8') as l10n_source:
l10n_sliced = islice(l10n_source, l10n_slice, None) \
if slice_ln else l10n_source
for line in l10n_sliced:
print(f" {STYLE[0]}{line}" if line.startswith('[') else f" \
{line}", end='')
sys.exit()
def testssl_command(testssl_temp_path, uri):
if not path.isdir(testssl_temp_path):
print_error_detail('[notestssl_path]')
testssl_final_path = path.join(testssl_temp_path, HUMBLE_FILES[9])
if not path.isfile(testssl_final_path):
print_error_detail('[notestssl_file]')
else:
testssl_command = [testssl_final_path] + TESTSSL_OPTIONS + [uri]
testssl_analysis(testssl_command)
sys.exit()
def testssl_analysis(testssl_command):
try:
process = Popen(testssl_command, stdout=PIPE, stderr=PIPE, text=True)
for ln in iter(process.stdout.readline, ''):
print(ln, end='')
if 'Done' in ln:
process.terminate()
process.wait()
break
if stderr := process.stderr.read():
print(stderr, end='')
except Exception:
print_error_detail('[testssl_error]')
def get_l10n_content():
l10n_path = path.join(OS_PATH, HUMBLE_DIRS[1], HUMBLE_FILES[4]
if args.lang == 'es' else HUMBLE_FILES[5])
with open(l10n_path, 'r', encoding='utf8') as l10n_content:
return l10n_content.readlines()
def get_analysis_results():
print_detail_l('[analysis_time]')
print(round(end - start, 2), end="")
print_detail_l('[analysis_time_sec]')
t_cnt = sum([m_cnt, f_cnt, i_cnt[0], e_cnt])
analysis_totals = save_analysis_results(t_cnt)
analysis_diff = compare_analysis_results(*analysis_totals, en_cnt=en_cnt,
m_cnt=m_cnt, f_cnt=f_cnt,
i_cnt=i_cnt, e_cnt=e_cnt,
t_cnt=t_cnt)
print("")
print_analysis_results(*analysis_diff, t_cnt=t_cnt)
analysis_grade = grade_analysis(en_cnt, m_cnt, f_cnt, i_cnt, e_cnt)
print(f"{get_detail(analysis_grade)}")
print_detail('[experimental_header]', 2)
def save_analysis_results(t_cnt):
with open(HUMBLE_FILES[0], 'a+', encoding='utf8') as all_analysis:
all_analysis.seek(0)
url_ln = [line for line in all_analysis if URL in line]
# Format of the analysis history file, ('analysis_h.txt'): Date, URL,
# Enabled, Missing, Fingerprint, Deprecated/Insecure, Empty headers and
# Total warnings (the four previous totals).
all_analysis.write(f"{current_time} ; {URL} ; {en_cnt} ; {m_cnt} ; \
{f_cnt} ; {i_cnt[0]} ; {e_cnt} ; {t_cnt}\n")
return get_analysis_totals(url_ln) if url_ln else ("First",) * 6
def get_analysis_totals(url_ln):
# To avoid errors with analyses performed before 11/28/204, the date on
# which enabled security headers began being considered when calculating
# differences between analyses of the same URL.
# Therefore, analyses performed before that date are assumed to have no
# security headers enabled.
# Ref: https://github.com/rfc-st/humble/commit/f7b376
updated_lines = []
for line in url_ln:
fields = line.strip().split(' ; ')
if len(fields) == 7:
fields.insert(2, '0')
updated_lines.append(' ; '.join(fields))
url_ln = updated_lines
analysis_date = max(line.split(" ; ")[0] for line in url_ln)
for line in url_ln:
if analysis_date in line:
*totals, = line.strip().split(' ; ')
break
return tuple(totals[2:])
def compare_analysis_results(*analysis_totals, en_cnt, m_cnt, f_cnt, i_cnt,
e_cnt, t_cnt):
if analysis_totals[0] == "First":
return [get_detail('[first_analysis]', replace=True)] * 6
current = [int(val) for val in analysis_totals]
differences = [en_cnt, m_cnt, f_cnt, i_cnt[0], e_cnt, t_cnt]
return [str(d - c) if (d - c) <= 0 else f'+{d - c}' for d, c in
zip(differences, current)]
def print_analysis_results(*diff, t_cnt):
literals = ['[enabled_cnt]', '[missing_cnt]', '[fng_cnt]',
'[insecure_cnt]', '[empty_cnt]', '[total_cnt]']
totals = [f"{en_cnt} ({diff[0]})\n", f"{m_cnt} ({diff[1]})",
f"{f_cnt} ({diff[2]})", f"{i_cnt[0]} \
({diff[3]})", f"{e_cnt} ({diff[4]})", f"{t_cnt} ({diff[5]})\n"]
print("")
for literal, total in zip(literals, totals):
print(f"{(print_detail_l(literal) or '')[:-1]}{total}")
# Use '-grd' parameter to show the checks to grade an analysis, along with
# advice for improvement.
def grade_analysis(en_cnt, m_cnt, f_cnt, i_cnt, e_cnt):
if en_cnt == 0:
return '[e_grade]'
if i_cnt and sum(i_cnt) > 0:
return '[d_grade]'
if m_cnt > 0:
return '[c_grade]'
if f_cnt > 0:
return '[b_grade]'
return '[a_grade]' if e_cnt > 0 else '[perfect_grade]'
def analysis_exists(filepath):
if not path.exists(filepath):
detail = '[no_analysis]' if URL else '[no_global_analysis]'
print_error_detail(detail)
def adjust_old_analysis(url_ln):
# To avoid errors with analyses performed before 11/28/204, the date on
# which enabled security headers began being written to the analysis
# history file ('analysis_h.txt') and considered for displaying statistics
# (via the '-a' parameter).
# Therefore, analyses performed before that date are assumed to have no
# security headers enabled.
# Ref: https://github.com/rfc-st/humble/commit/f7b376
updated_lines = []
for i in url_ln:
fields = i.strip().split(';')
if len(fields) == 7:
fields = [field.strip() for field in fields]
fields.insert(2, '0')
updated_lines.append(' ; '.join(fields) + '\n')
else:
updated_lines.append(i)
return updated_lines
def url_analytics(is_global=False):
url_scope = extract_global_metrics if is_global else get_analysis_metrics
with open(HUMBLE_FILES[0], 'r', encoding='utf8') as all_analysis:
analysis_metrics = url_scope(all_analysis)
l10n_det = '[global_stats_analysis]' if is_global else '[stats_analysis]'
url_string = '' if is_global else URL
print(f"\n{get_detail(l10n_det, replace=True)} {url_string}\n")
for key, value in analysis_metrics.items():
key_style = f"{STYLE[0]}{key}{STYLE[4]}" if not value or not \
key.startswith(' ') else key
print(f"{key_style}: {value}")
sys.exit()
def get_analysis_metrics(all_analysis):
url_ln = [line for line in all_analysis if URL in line]
if not url_ln:
print_error_detail('[no_analysis]')
adj_url_ln = adjust_old_analysis(url_ln)
total_a = len(adj_url_ln)
first_m = get_first_metrics(adj_url_ln)
second_m = [get_second_metrics(adj_url_ln, i, total_a) for i
in range(2, 7)]
third_m = get_third_metrics(adj_url_ln)
additional_m = get_additional_metrics(adj_url_ln)
fourth_m = get_highlights(adj_url_ln)
return print_metrics(total_a, first_m, second_m, third_m, additional_m,
fourth_m)
def get_first_metrics(adj_url_ln):
first_a = min(f"{line.split(' ; ')[0]}" for line in adj_url_ln)
latest_a = max(f"{line.split(' ; ')[0]}" for line in adj_url_ln)
date_w = [(line.split(" ; ")[0],
int(line.strip().split(" ; ")[-1])) for line in adj_url_ln]
best_d, best_w = min(date_w, key=lambda x: x[1])
worst_d, worst_w = max(date_w, key=lambda x: x[1])
return (first_a, latest_a, best_d, best_w, worst_d, worst_w)
def get_second_metrics(adj_url_ln, index, total_a):
metric_c = len([line for line in adj_url_ln if int(line.split(' ; ')
[index])
== 0])
return f"{metric_c / total_a:.0%} ({metric_c}\
{get_detail('[pdf_footer2]', replace=True)} {total_a})"
def get_third_metrics(adj_url_ln):
fields = [line.strip().split(';') for line in adj_url_ln]
total_enb, total_miss, total_fng, total_dep, total_ety = \
[sum(int(f[i]) for f in fields) for i in range(2, 7)]
num_a = len(adj_url_ln)
avg_enb, avg_miss, avg_fng, avg_dep, avg_ety = \
[t // num_a for t in (total_enb, total_miss, total_fng, total_dep,
total_ety)]
return (avg_enb, avg_miss, avg_fng, avg_dep, avg_ety)
def get_additional_metrics(adj_url_ln):
avg_w = int(sum(int(line.split(' ; ')[-1]) for line in adj_url_ln) /
len(adj_url_ln))
year_a, avg_w_y, month_a = extract_date_metrics(adj_url_ln)
return (avg_w, year_a, avg_w_y, month_a)
def extract_date_metrics(url_ln):
year_cnt, year_wng = defaultdict(int), defaultdict(int)
for line in url_ln:
date_str = line.split(' ; ')[0].split()[0]
year, _, _ = map(int, date_str.split('/'))
year_cnt[year] += 1
year_wng[year] += int(line.split(' ; ')[-1])
years_str = generate_date_groups(year_cnt, url_ln)
avg_wng_y = sum(year_wng.values()) // len(year_wng)
return years_str, avg_wng_y, year_wng
def generate_date_groups(year_cnt, url_ln):
years_str = []
for year in sorted(year_cnt.keys()):
year_str = f" {year}: {year_cnt[year]} \
{get_detail('[analysis_y]').rstrip()}"
month_cnts = get_month_counts(year, url_ln)
months_str = '\n'.join([f" ({count}){month_name.rstrip()}" for
month_name, count in month_cnts.items()])
year_str += f"\n{months_str}\n"
years_str.append(year_str)
return '\n'.join(years_str)
def get_month_counts(year, url_ln):
month_cnts = defaultdict(int)
for line in url_ln:
date_str = line.split(' ; ')[0].split()[0]
line_year, line_month, _ = map(int, date_str.split('/'))
if line_year == year:
month_cnts[get_detail(f'[month_{line_month:02d}]')] += 1
return month_cnts
def get_highlights(adj_url_ln):
sections = ['[enabled_cnt]', '[missing_cnt]', '[fng_cnt]',
'[insecure_cnt]', '[empty_cnt]']
fields_h = [2, 3, 4, 5, 6]
return [f"{print_detail_l(sections[i], analytics=True)}\n"
f" {print_detail_l('[best_analysis]', analytics=True)}: \
{calculate_highlights(adj_url_ln, fields_h[i], min if i != 0 else max)}\n"
f" {print_detail_l('[worst_analysis]', analytics=True)}: \
{calculate_highlights(adj_url_ln, fields_h[i], max if i != 0 else min)}\n"
for i in range(len(fields_h))]
def calculate_highlights(url_ln, field_index, func):
values = [int(line.split(';')[field_index].strip()) for line in url_ln]
target_value = func(values)
target_line = next(line for line in url_ln
if int(line.split(';')[field_index].strip()) ==
target_value)
return target_line.split(';')[0].strip()
def print_metrics(total_a, first_m, second_m, third_m, additional_m, fourth_m):
basic_m = get_basic_metrics(total_a, first_m)
error_m = get_security_metrics(second_m)
warning_m = get_warnings_metrics(additional_m)
averages_m = get_averages_metrics(third_m)
fourth_m = get_highlights_metrics(fourth_m)
analysis_year_m = get_date_metrics(additional_m)
totals_m = {**basic_m, **error_m, **warning_m, **averages_m, **fourth_m,
**analysis_year_m}
return {get_detail(key, replace=True): value for key, value in
totals_m.items()}
def get_basic_metrics(total_a, first_m):
return {'[main]': "", '[total_analysis]': total_a,
'[first_analysis_a]': first_m[0], '[latest_analysis]': first_m[1],
'[best_analysis]': f"{first_m[2]} \
{get_detail('[total_warnings]', replace=True)}{first_m[3]})",
'[worst_analysis]': f"{first_m[4]} \
{get_detail('[total_warnings]', replace=True)}{first_m[5]})\n"}
def get_security_metrics(second_m):
return {'[analysis_y]': "", '[no_enabled]': second_m[0],
'[no_missing]': second_m[1], '[no_fingerprint]': second_m[2],
'[no_ins_deprecated]': second_m[3],
'[no_empty]': f"{second_m[4]}\n"}
def get_warnings_metrics(additional_m):
return {'[averages]': "", '[average_warnings]': f"{additional_m[0]}",
'[average_warnings_year]': f"{additional_m[2]}\n"}
def get_averages_metrics(third_m):
return {'[average_enb]': f"{third_m[0]}",
'[average_miss]': f"{third_m[1]}",
'[average_fng]': f"{third_m[2]}", '[average_dep]': f"{third_m[3]}",
'[average_ety]': f"{third_m[4]}\n"}
def get_highlights_metrics(fourth_m):
return {'[highlights]': "\n" + "\n".join(fourth_m)}
def get_date_metrics(additional_m):
return {'[analysis_year_month]': f"\n{additional_m[1]}"}
def extract_global_metrics(all_analysis):
url_ln = list(all_analysis)
if not url_ln:
print_error_detail('[no_global_analysis]')
adj_url_ln = adjust_old_analysis(url_ln)
total_a = len(adj_url_ln)
first_m = get_global_first_metrics(adj_url_ln)
second_m = [get_second_metrics(adj_url_ln, i, total_a) for i
in range(2, 7)]
third_m = get_third_metrics(adj_url_ln)
additional_m = get_additional_metrics(adj_url_ln)
return print_global_metrics(total_a, first_m, second_m, third_m,
additional_m)
def get_global_first_metrics(adj_url_ln):
split_lines = [line.split(' ; ') for line in adj_url_ln]
url_lines = {}
for entry in split_lines:
url = entry[1]
url_lines[url] = url_lines.get(url, 0) + 1
return get_global_metrics(adj_url_ln, url_lines)
def get_global_metrics(url_ln, url_lines):
first_a = min(f"{line.split(' ; ')[0]}" for line in url_ln)
latest_a = max(f"{line.split(' ; ')[0]}" for line in url_ln)
unique_u = len({line.split(' ; ')[1] for line in url_ln})
most_analyzed_u = max(url_lines, key=url_lines.get)
most_analyzed_c = url_lines[most_analyzed_u]
most_analyzed_cu = f"({most_analyzed_c}) {most_analyzed_u}"
least_analyzed_u = min(url_lines, key=url_lines.get)
least_analyzed_c = url_lines[least_analyzed_u]
least_analyzed_cu = f"({least_analyzed_c}) {least_analyzed_u}"
fields = [-1, 2, 3, 4, 5, 6]
totals = [get_global_totals(url_ln, field) for field in fields]
return (first_a, latest_a, unique_u, most_analyzed_cu, least_analyzed_cu,
*(item for total in totals for item in total))
def get_global_totals(url_ln, field):
most_totals = max(url_ln, key=lambda line: int(line.split(' ; ')[field]))
least_totals = min(url_ln, key=lambda line: int(line.split(' ; ')[field]))
most_totals_c, most_totals_cu = most_totals.split(' ; ')[1], \
str(most_totals.split(' ; ')[field]).strip()
most_totals_p = f"({most_totals_cu}) {most_totals_c}"
least_totals_c, least_totals_cu = least_totals.split(' ; ')[1], \
str(least_totals.split(' ; ')[field]).strip()
least_totals_p = f"({least_totals_cu}) {least_totals_c}"
return (most_totals_p, least_totals_p)
def get_basic_global_metrics(total_a, first_m):
return {'[main]': "", '[total_analysis]': total_a,
'[total_global_analysis]': str(first_m[2]),
'[first_analysis_a]': first_m[0],
'[latest_analysis]': f"{first_m[1]}\n",
'[urls]': "", '[most_analyzed]': first_m[3],
'[least_analyzed]': f"{first_m[4]}\n",
'[most_enabled]': first_m[7],
'[least_enabled]': f"{first_m[8]}\n",
'[most_missing]': first_m[9],
'[least_missing]': f"{first_m[10]}\n",
'[most_fingerprints]': first_m[11],
'[least_fingerprints]': f"{first_m[12]}\n",
'[most_insecure]': first_m[13],
'[least_insecure]': f"{first_m[14]}\n",
'[most_empty]': first_m[15],
'[least_empty]': f"{first_m[16]}\n",
'[most_warnings]': first_m[5],
'[least_warnings]': f"{first_m[6]}\n"}
def print_global_metrics(total_a, first_m, second_m, third_m, additional_m):
basic_m = get_basic_global_metrics(total_a, first_m)
error_m = get_security_metrics(second_m)
warning_m = get_warnings_metrics(additional_m)
averages_m = get_averages_metrics(third_m)
analysis_year_m = get_date_metrics(additional_m)
totals_m = {**basic_m, **error_m, **warning_m, **averages_m,
**analysis_year_m}
return {get_detail(key, replace=True): value for key, value in
totals_m.items()}
def csp_store_values(csp_header, l_csp_broad_s, l_csp_ins_s, i_cnt):
csp_broad, csp_deprecated, csp_insecure = set(), set(), set()
csp_directives = csp_header.split(';')
for directive in csp_directives:
csp_dir = directive.strip()
csp_broad |= ({value for value in l_csp_broad_s if f' {value} ' in
f' {csp_dir} '})
csp_deprecated |= ({value for value in t_csp_dep if value in csp_dir})
csp_insecure |= ({value for value in l_csp_ins_s if value in csp_dir})
csp_check_values(csp_broad, csp_deprecated, csp_insecure, i_cnt)
return i_cnt
def csp_check_values(csp_broad, csp_deprecated, csp_insecure, i_cnt):
csp_print_deprecated(csp_deprecated) if csp_deprecated else None
csp_print_insecure(csp_insecure) if csp_insecure else None
csp_print_broad(csp_broad) if csp_broad else None
i_cnt[0] += sum(bool(csp) for csp in (csp_broad, csp_deprecated,
csp_insecure))
return i_cnt
def csp_print_deprecated(csp_deprecated):
print_detail_r('[icsi_d]', is_red=True) if args.brief else \
csp_print_warnings(csp_deprecated, '[icsi_d]', '[icsi_d_s]',
'[icsi_d_r]')
def csp_print_insecure(csp_insecure):
print_detail_r('[icsh_h]', is_red=True) if args.brief else \
csp_print_warnings(csp_insecure, '[icsh_h]', '[icsh]', '[icsh_b]')
if not args.brief:
print("")
def csp_print_broad(csp_broad):
print_detail_r('[icsw_h]', is_red=True) if args.brief else \
csp_print_warnings(csp_broad, '[icsw_h]', '[icsw]', '[icsw_b]')
def csp_print_warnings(csp_values, csp_title, csp_desc, csp_refs):
csp_values = ', '.join(f"'{value}'" for value in csp_values)
print_detail_r(f'{csp_title}', is_red=True)
print_detail_l(f'{csp_desc}')
print(csp_values)
print_detail(f'{csp_refs}')
def delete_lines(reliable=True):
if not reliable:
sys.stdout.write(DELETED_LINES)
sys.stdout.write(DELETED_LINES)
def print_export_path(filename, reliable):
delete_lines(reliable=False) if reliable else delete_lines()
print("")
print_detail_l('[report]')
print(path.abspath(filename))
def print_nowarnings():
print_detail('[no_warnings]')
def print_header(header):
print(f" {header}" if args.output else f"{STYLE[1]} {header}")
def print_fng_header(header):
if args.output:
print(f" {header}")
elif '[' in header:
prefix, _, suffix = header.partition(' [')
print(f"{STYLE[1]} {prefix}{STYLE[3]}{STYLE[5]} [{suffix}")
else:
print(f"{STYLE[1]} {header}")
def print_general_info(reliable, export_filename):
if not args.output:
delete_lines(reliable=False) if reliable else delete_lines()
print(f"\n{BANNER}\n ({URL_LIST[4]} | v.{local_version})")
elif args.output != 'pdf':
print(f"\n\n{HUMBLE_DESC}\n{URL_LIST[4]} | v.{local_version}\n")
print_basic_info(export_filename)
print_extended_info(args, reliable, status_code)
def print_basic_info(export_filename):
print(linesep.join(['']*2) if args.output == 'html' or not args.output
else "")
print_detail_r('[0section]')
print_detail_l('[analysis_date]')
print(f" {current_time}")
print(f'{URL_STRING[1]}{URL}')
if export_filename:
print_detail_l('[export_filename]')
print(f"{export_filename}")
def print_extended_info(args, reliable, status_code):
if args.skip_headers:
print_skipped_headers(args)
if args.output in ('csv', 'json'):
print(get_detail('[limited_analysis_note]', replace=True))
if (status_code is not None and 400 <= status_code <= 451) or reliable or \
args.redirects or args.skip_headers:
print_extra_info(reliable)
def print_extra_info(reliable):
if (status_code is not None and 400 <= status_code <= 451):
id_mode = f'[http_{status_code}]'
if detail := print_detail(id_mode, 0):
print(detail)
print(f"{URL_LIST[2]}{status_code}")
if reliable:
print(get_detail('[unreliable_analysis_note]', replace=True))
if args.redirects:
print(get_detail('[analysis_redirects_note]', replace=True))
def print_response_headers():
print(linesep.join(['']*2))
print_detail_r('[0headers]')
pdf_style = STYLE[6] if args.output == 'pdf' else ""
for key, value in sorted(headers.items()):
print(f" {pdf_style}{key}:", value) if args.output else \
print(f" {STYLE[2]}{key}:", value)
print('\n')
def print_details(short_d, long_d, id_mode, i_cnt):
print_detail_r(short_d, is_red=True)
if not args.brief:
print_detail(long_d, 2) if id_mode == 'd' else print_detail(long_d, 3)
i_cnt[0] += 1
return i_cnt
def print_detail(id_mode, num_lines=1):
idx = l10n_main.index(id_mode + '\n')
print(l10n_main[idx+1], end='')
for i in range(1, num_lines+1):
if idx+i+1 < len(l10n_main):
print(l10n_main[idx+i+1], end='')
def print_detail_l(id_mode, analytics=False):
for i, line in enumerate(l10n_main):
if line.startswith(id_mode):
if not analytics:
print(l10n_main[i+1].replace('\n', ''), end='')
else:
return l10n_main[i+1].replace('\n', '').replace(':', '')[1:]
def print_detail_r(id_mode, is_red=False):
style_str = STYLE[1] if is_red else STYLE[0]
for i, line in enumerate(l10n_main):
if line.startswith(id_mode):
if not args.output:
print(f"{style_str}{l10n_main[i+1]}", end='')
else:
print(l10n_main[i+1], end='')
if not is_red:
print("")
def get_detail(id_mode, replace=False):
for i, line in enumerate(l10n_main):
if line.startswith(id_mode):
return (l10n_main[i+1].replace('\n', '')) if replace else \
l10n_main[i+1]
def print_error_detail(id_mode):
print(f"\n{get_detail(id_mode, replace=True)}")
sys.exit()
def get_epilog_content(id_mode):
epilog_file_path = path.join(OS_PATH, HUMBLE_DIRS[1], HUMBLE_FILES[5])
with open(epilog_file_path, 'r', encoding='utf8') as epilog_source:
epilog_lines = epilog_source.readlines()
epilog_idx = epilog_lines.index(id_mode + '\n')
return ''.join(epilog_lines[epilog_idx+1:epilog_idx+14])
def get_fingerprint_headers():
with open(path.join(OS_PATH, HUMBLE_DIRS[0], HUMBLE_FILES[2]), 'r',
encoding='utf8') as fng_source:
l_fng_ex = [line.strip() for line in
islice(fng_source, SLICE_INT[0], None) if line.strip()]
l_fng = [line.split(' [')[0].strip() for line in l_fng_ex]
titled_fng = [item.title() for item in l_fng]
return l_fng_ex, l_fng, titled_fng
def print_fingerprint_headers(headers_l, l_fng_ex, titled_fng):
f_cnt = 0
sorted_headers = sorted({header.title() for header in headers_l})
for header in sorted_headers:
if header in titled_fng:
idx_fng = titled_fng.index(header)
get_fingerprint_detail(header, headers, idx_fng, l_fng_ex, args)
f_cnt += 1
return f_cnt
def get_fingerprint_detail(header, headers, idx_fng, l_fng_ex, args):
if not args.brief:
print_fng_header(l_fng_ex[idx_fng])
header_value = headers_l.get(header.lower()) if '-if' in sys.argv else\
headers[header]
if header_value:
print(f" {get_detail('[fng_value]', replace=True)} \
'{header_value}'")
else:
print(get_detail('[empty_fng]', replace=True))
print("")
else:
print_header(header)
def get_enabled_headers(args, headers_l, t_enabled):
headers_d = {key.title(): value for key, value in headers_l.items()}
t_enabled = sorted({header.title() for header in t_enabled})
enabled_headers = [header for header in t_enabled if header in headers_d]
for header in enabled_headers:
print_enabled_headers(args, header, headers_d)
None if enabled_headers else print_nosec_headers(args)
en_cnt = len(enabled_headers)
print('\n')
return en_cnt
def print_enabled_headers(args, header, headers_d):
exp_s = get_detail('[exp_header]', replace=True) if header.lower() in\
EXP_HEADERS else ""
header_display = f'{STYLE[8]}{exp_s}{header}' if args.output in \
('html', 'pdf') else f'{exp_s}{header}'
if args.output:
print(f' {header_display}' if args.brief else f' \
{header_display}: {headers_d[header]}')
else:
styled_header = f'{STYLE[7]}{header_display}{STYLE[5]}'[18:]
print(f' {styled_header}' if args.brief else f' {styled_header}: \
{headers_d[header]}')
def print_nosec_headers(args):
print_detail_l('[no_sec_headers]') if args.output else \
print_detail_r('[no_sec_headers]', is_red=True)
def print_missing_headers(args, headers_l, l_detail, l_miss):
m_cnt = 0
headers_set = set(headers_l)
l_miss_set = {header.lower() for header in l_miss}
skip_headers = args.skip_headers if args.skip_headers is not None else []
skip_missing = {header.lower() for header in skip_headers if
header.lower() in l_miss_set}
m_cnt, skip_missing = check_missing_headers(m_cnt, l_miss, l_detail,
headers_set, skip_missing)
return m_cnt, skip_missing
def check_missing_headers(m_cnt, l_miss, l_detail, headers_set, skip_missing):
for header, detail in zip(l_miss, l_detail):
if header.lower() not in headers_set and header.lower() not in \
skip_missing and 'x-frame-options' not in skip_missing:
exp_s = get_detail('[exp_header]', replace=True) if header.lower()\
in EXP_HEADERS else ""
print_header(f"{exp_s}{header}")
if not args.brief:
print_detail(detail, 2)
m_cnt += 1
return m_cnt, skip_missing
def check_frame_options(args, headers_l, l_miss, m_cnt, skip_missing):
skip_headers = {header.lower() for header in (args.skip_headers or [])}
if 'x-frame-options' in skip_headers:
skip_missing.add('x-frame-options')
xfo_missing = 'x-frame-options' not in skip_missing
xfo_not_set = 'x-frame-options' not in headers_l
csp_missing = 'frame-ancestors' not in headers_l.get(
'content-security-policy', '')
all_missing = all(header.lower() not in headers_l for header in l_miss)
if xfo_missing and ((xfo_not_set and csp_missing) or all_missing):
print_header('X-Frame-Options')
if not args.brief:
print_detail('[mxfo]', 2)
m_cnt += 1
l_miss.append('X-Frame-Options')
return m_cnt
def print_empty_headers(headers, l_empty):
e_cnt = 0
for key in sorted(headers):
if not headers[key]:
l_empty.append(f"{key}")
print_header(key)
e_cnt += 1
return e_cnt
def print_browser_compatibility(compat_headers):
style_blanks = " " if args.output == 'html' else " "
for key in compat_headers:
styled_header = key if args.output else f"{STYLE[2]}{key}{STYLE[5]}"
csp_key = 'contentsecuritypolicy2' if key == 'Content-Security-Policy'\
else key
print(f"{style_blanks}{styled_header}{URL_LIST[0]}{csp_key}")
def check_input_traversal(user_input):
input_traversal_ptrn = re.compile(RE_PATTERN[2])
if input_traversal_ptrn.search(user_input):
print(f"\n{get_detail('[args_input_traversal]', replace=True)}\
: ('{user_input}')")
sys.exit()
def check_path_permissions(output_path):
try:
open(path.join(output_path, HUMBLE_FILES[1]), 'w')
except PermissionError:
print(f"\n{get_detail('[args_nowr]', replace=True)}'{output_path}'")
sys.exit()
else:
remove(path.join(output_path, HUMBLE_FILES[1]))
def check_output_path(args, output_path):
check_input_traversal(args.output_path)
if args.output is None:
print_error_detail('[args_nooutputfmt]')
elif path.exists(output_path):
check_path_permissions(output_path)
else: