forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps.py
More file actions
1475 lines (1234 loc) · 49.7 KB
/
https.py
File metadata and controls
1475 lines (1234 loc) · 49.7 KB
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
import re
import sys
import datetime
import requests
import OpenSSL
import json
import logging
import base64
import urllib
import publicsuffix2 as publicsuffix
from cryptography.hazmat.primitives.serialization import Encoding
from sslyze.server_connectivity import ServerConnectivityTester
from sslyze.errors import ConnectionToServerFailed
from sslyze.scanner import Scanner, ServerScanRequest, ScanCommandExtraArgumentsDict
from sslyze.plugins.scan_commands import ScanCommand
from sslyze.server_setting import (
ServerNetworkLocation,
ServerNetworkLocationViaDirectConnection,
)
from sslyze.plugins.certificate_info._certificate_utils import (
extract_dns_subject_alternative_names,
)
from .models import Domain, Endpoint
from .query_crlite import query_crlite
suffix_list = None
preload_pending = None
preload_list = None
STORE = "Mozilla"
def result_for(domain):
# Because it will inform many other judgments, first identify
# an acceptable "canonical" URL for the domain.
domain.canonical = canonical_endpoint(
domain.http, domain.httpwww, domain.https, domain.httpswww
)
# First, the basic fields the CSV will use.
result = {
"Domain": domain.domain,
"Base Domain": parent_domain_for(domain.domain),
"Canonical URL": domain.canonical.url,
"Live": is_live(domain),
"Redirect": is_redirect_domain(domain),
"Redirect To": redirects_to(domain),
"HTTPS Live": is_https_live(domain),
"HTTPS Full Connection": is_full_connection(domain),
"HTTPS Client Auth Required": is_client_auth_required(domain),
"Valid HTTPS": is_valid_https(domain),
"HTTPS Publicly Trusted": is_publicly_trusted(domain),
"HTTPS Custom Truststore Trusted": is_custom_trusted(domain),
"Defaults to HTTPS": is_defaults_to_https(domain),
"Downgrades HTTPS": is_downgrades_https(domain),
"Strictly Forces HTTPS": is_strictly_forces_https(domain),
"HTTPS Bad Chain": is_bad_chain(domain),
"HTTPS Bad Hostname": is_bad_hostname(domain),
"HTTPS Expired Cert": is_expired_cert(domain),
"HTTPS Self Signed Cert": is_self_signed_cert(domain),
"HTTPS Cert Revoked": is_revoked_cert(domain),
"HTTPS Cert Chain Length": cert_chain_length(domain),
"HTTPS Probably Missing Intermediate Cert": is_missing_intermediate_cert(
domain
),
"HSTS": is_hsts(domain),
"HSTS Header": hsts_header(domain),
"HSTS Max Age": hsts_max_age(domain),
"HSTS Entire Domain": is_hsts_entire_domain(domain),
"HSTS Preload Ready": is_hsts_preload_ready(domain),
"HSTS Preload Pending": is_hsts_preload_pending(domain),
"HSTS Preloaded": is_hsts_preloaded(domain),
"Base Domain HSTS Preloaded": is_parent_hsts_preloaded(domain),
"Domain Supports HTTPS": is_domain_supports_https(domain),
"Domain Enforces HTTPS": is_domain_enforces_https(domain),
"Domain Uses Strong HSTS": is_domain_strong_hsts(domain),
"IP": get_domain_ip(domain),
"Server Header": get_domain_server_header(domain),
"Server Version": get_domain_server_version(domain),
"Notes": get_domain_notes(domain),
"Unknown Error": did_domain_error(domain),
}
return result
def canonical_endpoint(http, httpwww, https, httpswww):
"""
Given behavior for the 4 endpoints, make a best guess
as to which is the "canonical" site for the domain.
Most of the domain-level decisions rely on this guess in some way.
A domain is "canonically" at www if:
* at least one of its www endpoints responds
* both root endpoints are either down or redirect *somewhere*
* either both root endpoints are down, *or* at least one
root endpoint redirect should immediately go to
an *internal* www endpoint
This is meant to affirm situations like:
http:// -> https:// -> https://www
https:// -> http:// -> https://www
and meant to avoid affirming situations like:
http:// -> http://non-www,
http://www -> http://non-www
or like:
https:// -> 200, http:// -> http://www
"""
at_least_one_www_used = httpswww.live or httpwww.live
def root_unused(endpoint):
return (
endpoint.redirect
or (not endpoint.live)
or endpoint.https_bad_hostname
or (not str(endpoint.status).startswith("2")) # harmless for http endpoints
)
def root_down(endpoint):
return (
(not endpoint.live)
or endpoint.https_bad_hostname
or (
(not str(endpoint.status).startswith("2"))
and (not str(endpoint.status).startswith("3"))
)
)
all_roots_unused = root_unused(https) and root_unused(http)
all_roots_down = root_down(https) and root_down(http)
is_www = (
at_least_one_www_used
and all_roots_unused
and (
all_roots_down
or https.redirect_immediately_to_www
or http.redirect_immediately_to_www
)
)
# A domain is "canonically" at https if:
# * at least one of its https endpoints is live and
# doesn't have an invalid hostname
# * both http endpoints are either down or redirect *somewhere*
# * at least one http endpoint redirects immediately to
# an *internal* https endpoint
# This is meant to affirm situations like:
# http:// -> http://www -> https://
# https:// -> http:// -> https://www
# and meant to avoid affirming situations like:
# http:// -> http://non-www
# http://www -> http://non-www
# or:
# http:// -> 200, http://www -> https://www
#
# It allows a site to be canonically HTTPS if the cert has
# a valid hostname but invalid chain issues.
def https_used(endpoint):
return endpoint.live and (not endpoint.https_bad_hostname)
def http_unused(endpoint):
return (
endpoint.redirect
or (not endpoint.live)
or (not str(endpoint.status).startswith("2"))
)
def http_upgrades(endpoint):
return endpoint.redirect_immediately_to_https and (
not endpoint.redirect_immediately_to_external
)
at_least_one_https_endpoint = https_used(https) or https_used(httpswww)
all_http_unused = http_unused(http) and http_unused(httpwww)
both_http_down = (not http.live) and (not httpwww.live)
at_least_one_http_upgrades = http_upgrades(http) or http_upgrades(httpwww)
is_https = (
at_least_one_https_endpoint
and all_http_unused
and (both_http_down or at_least_one_http_upgrades)
)
if is_www and is_https:
return httpswww
elif is_www and (not is_https):
return httpwww
elif (not is_www) and is_https:
return https
elif (not is_www) and (not is_https):
return http
def is_live(domain):
"""
Domain is "live" if *any* endpoint is live.
"""
http, httpwww, https, httpswww = (
domain.http,
domain.httpwww,
domain.https,
domain.httpswww,
)
return http.live or httpwww.live or https.live or httpswww.live
def is_https_live(domain):
"""
Domain is https live if any https endpoint is live.
"""
https, httpswww = domain.https, domain.httpswww
return https.live or httpswww.live
def is_full_connection(domain):
"""
Domain is "fully connected" if any https endpoint is fully connected.
"""
https, httpswww = domain.https, domain.httpswww
return https.https_full_connection or httpswww.https_full_connection
def is_client_auth_required(domain):
"""
Domain requires client authentication if *any* HTTPS endpoint requires it for full TLS connection.
"""
https, httpswww = domain.https, domain.httpswww
return https.https_client_auth_required or httpswww.https_client_auth_required
def is_redirect_or_down(endpoint):
"""
Endpoint is a redirect or down if it is a redirect to an external site or it is down in any of 3 ways:
it is not live, it is HTTPS and has a bad hostname in the cert, or it responds with a 4xx error code
"""
return (
endpoint.redirect_eventually_to_external
or (not endpoint.live)
or (endpoint.protocol == "https" and endpoint.https_bad_hostname)
or (endpoint.status is not None and endpoint.status >= 400)
)
def is_redirect(endpoint):
"""
Endpoint is a redirect if it is a redirect to an external site
"""
return endpoint.redirect_eventually_to_external
def is_redirect_domain(domain):
"""
Domain is "a redirect domain" if at least one endpoint is
a redirect, and all endpoints are either redirects or down.
"""
http, httpwww, https, httpswww = (
domain.http,
domain.httpwww,
domain.https,
domain.httpswww,
)
return is_live(domain) and (
(
is_redirect(http)
or is_redirect(httpwww)
or is_redirect(https)
or is_redirect(httpswww)
)
and is_redirect_or_down(https)
and is_redirect_or_down(httpswww)
and is_redirect_or_down(httpwww)
and is_redirect_or_down(http)
)
def is_http_redirect_domain(domain):
"""
Domain is "an http redirect domain" if at least one http endpoint
is a redirect, and all other http endpoints are either redirects
or down.
"""
http, httpwww, = (
domain.http,
domain.httpwww,
)
return is_live(domain) and (
(is_redirect(http) or is_redirect(httpwww))
and is_redirect_or_down(httpwww)
and is_redirect_or_down(http)
)
def redirects_to(domain):
"""
If a domain is a "redirect domain", where does it redirect to?
"""
canonical = domain.canonical
if is_redirect_domain(domain):
return canonical.redirect_eventually_to
else:
return None
def is_valid_https(domain):
"""
A domain has "valid HTTPS" if it responds on port 443 at its canonical
hostname with an unexpired valid certificate for the hostname.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
# Evaluate the HTTPS version of the canonical hostname
if canonical.host == "root":
evaluate = https
else:
evaluate = httpswww
return evaluate.live and evaluate.https_valid
def is_defaults_to_https(domain):
"""
A domain "defaults to HTTPS" if its canonical endpoint uses HTTPS.
"""
canonical = domain.canonical
return canonical.protocol == "https"
def is_downgrades_https(domain):
"""
Domain downgrades if HTTPS is supported in some way, but
its canonical HTTPS endpoint immediately redirects internally to HTTP.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
# The domain "supports" HTTPS if any HTTPS endpoint responds with
# a certificate valid for its hostname.
supports_https = (https.live and (not https.https_bad_hostname)) or (
httpswww.live and (not httpswww.https_bad_hostname)
)
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
# Explicitly convert to bool to avoid unintentionally returning None,
# which may happen if the site doesn't redirect.
return bool(
supports_https
and canonical_https.redirect_immediately_to_http
and (not canonical_https.redirect_immediately_to_external)
)
def is_strictly_forces_https(domain):
"""
A domain "Strictly Forces HTTPS" if one of the HTTPS endpoints is
"live", and if both *HTTP* endpoints are either:
* down, or
* redirect immediately to an HTTPS URI.
This is different than whether a domain "Defaults" to HTTPS.
* An HTTP redirect can go to HTTPS on another domain, as long
as it's immediate.
* A domain with an invalid cert can still be enforcing HTTPS.
"""
http, httpwww, https, httpswww = (
domain.http,
domain.httpwww,
domain.https,
domain.httpswww,
)
def down_or_redirects(endpoint):
return (not endpoint.live) or endpoint.redirect_immediately_to_https
https_somewhere = https.live or httpswww.live
all_http_unused = down_or_redirects(http) and down_or_redirects(httpwww)
return https_somewhere and all_http_unused
def is_publicly_trusted(domain):
"""
A domain has a "Publicly Trusted" certificate if its canonical
endpoint has a publicly trusted certificate.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
# Evaluate the HTTPS version of the canonical hostname
if canonical.host == "root":
evaluate = https
else:
evaluate = httpswww
return evaluate.live and evaluate.https_public_trusted
def is_custom_trusted(domain):
"""
A domain has a "Custom Trusted" certificate if its canonical
endpoint has a certificate that is trusted by the custom
truststore.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
# Evaluate the HTTPS version of the canonical hostname
if canonical.host == "root":
evaluate = https
else:
evaluate = httpswww
return evaluate.live and evaluate.https_custom_trusted
def is_bad_chain(domain):
"""
Domain has a bad chain if its canonical https endpoint has a bad
chain
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_bad_chain
def is_bad_hostname(domain):
"""
Domain has a bad hostname if its canonical https endpoint fails
hostname validation
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_bad_hostname
def is_expired_cert(domain):
"""
Returns if its canonical https endpoint has an expired cert
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_expired_cert
def is_self_signed_cert(domain):
"""
Returns if its canonical https endpoint has a self-signed cert cert
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_self_signed_cert
def is_revoked_cert(domain):
"""
Returns if its canonical https endpoint has a revoked cert
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_cert_revoked
def cert_chain_length(domain):
"""
Returns the cert chain length for the canonical HTTPS endpoint
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_cert_chain_len
def is_missing_intermediate_cert(domain):
"""
Returns whether the served cert chain is probably missing the
needed intermediate certificate for the canonical HTTPS endpoint
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.https_missing_intermediate_cert
def is_hsts(domain):
"""
Domain has HSTS if its canonical HTTPS endpoint has HSTS.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.hsts
def hsts_header(domain):
"""
Domain's HSTS header is its canonical endpoint's header.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.hsts_header
def hsts_max_age(domain):
"""
Domain's HSTS max-age is its canonical endpoint's max-age.
"""
canonical, https, httpswww = domain.canonical, domain.https, domain.httpswww
if canonical.host == "www":
canonical_https = httpswww
else:
canonical_https = https
return canonical_https.hsts_max_age
def is_hsts_entire_domain(domain):
"""
Whether a domain's ROOT endpoint includes all subdomains.
"""
https = domain.https
return https.hsts_all_subdomains
def is_hsts_preload_ready(domain):
"""
Whether a domain's ROOT endpoint is preload-ready.
"""
https = domain.https
eighteen_weeks = (https.hsts_max_age is not None) and (
https.hsts_max_age >= 10886400
)
preload_ready = eighteen_weeks and https.hsts_all_subdomains and https.hsts_preload
return preload_ready
def is_hsts_preload_pending(domain):
"""
Whether a domain is formally pending inclusion in Chrome's HSTS preload
list.
If preload_pending is None, the caches have not been initialized, so do
that.
"""
if preload_pending is None:
logging.debug("`preload_pending` has not yet been initialized!")
raise RuntimeError(
"`initialize_external_data()` must be called explicitly before "
"using this function"
)
return domain.domain in preload_pending
def is_hsts_preloaded(domain):
"""
Whether a domain is contained in Chrome's HSTS preload list.
If preload_list is None, the caches have not been initialized, so do that.
"""
if preload_list is None:
logging.debug("`preload_list` has not yet been initialized!")
raise RuntimeError(
"`initialize_external_data()` must be called explicitly before "
"using this function"
)
return domain.domain in preload_list
def is_parent_hsts_preloaded(domain):
"""
Whether a domain's parent domain is in Chrome's HSTS preload list.
"""
return is_hsts_preloaded(Domain(parent_domain_for(domain.domain)))
def parent_domain_for(hostname):
"""
For "x.y.domain.gov", return "domain.gov".
If suffix_list is None, the caches have not been initialized, so do that.
"""
if suffix_list is None:
logging.debug("`suffix_list` has not yet been initialized!")
raise RuntimeError(
"`initialize_external_data()` must be called explicitly before "
"using this function"
)
return suffix_list.get_public_suffix(hostname)
def is_domain_supports_https(domain):
"""
A domain 'Supports HTTPS' when it doesn't downgrade and has valid HTTPS,
or when it doesn't downgrade and has a bad chain but not a bad hostname.
Domains with a bad chain "support" HTTPS but user-side errors should be expected.
"""
return ((not is_downgrades_https(domain)) and is_valid_https(domain)) or (
(not is_downgrades_https(domain))
and is_bad_chain(domain)
and (not is_bad_hostname(domain))
)
def is_domain_enforces_https(domain):
"""A domain that 'Enforces HTTPS' must 'Support HTTPS' and default to
HTTPS. For websites (where Redirect is false) they are allowed to
eventually redirect to an https:// URI. For "redirect domains"
(domains where the Redirect value is true) they must immediately
redirect clients to an https:// URI (even if that URI is on
another domain) in order to be said to enforce HTTPS.
"""
return (
is_domain_supports_https(domain)
and is_strictly_forces_https(domain)
and (is_defaults_to_https(domain) or is_http_redirect_domain(domain))
)
def is_domain_strong_hsts(domain):
if is_hsts(domain) and hsts_max_age(domain):
return is_hsts(domain) and hsts_max_age(domain) >= 31536000
else:
return None
def get_domain_ip(domain):
"""
Get the IP for the domain. Any IP that responded is good enough.
"""
if domain.canonical.ip is not None:
return domain.canonical.ip
if domain.https.ip is not None:
return domain.https.ip
if domain.httpswww.ip is not None:
return domain.httpswww.ip
if domain.httpwww.ip is not None:
return domain.httpwww.ip
if domain.http.ip is not None:
return domain.http.ip
return None
def get_domain_server_header(domain):
"""
Get the Server header from the response for the domain.
"""
if domain.canonical.server_header is not None:
return domain.canonical.server_header.replace(",", ";")
if domain.https.server_header is not None:
return domain.https.server_header.replace(",", ";")
if domain.httpswww.server_header is not None:
return domain.httpswww.server_header.replace(",", ";")
if domain.httpwww.server_header is not None:
return domain.httpwww.server_header.replace(",", ";")
if domain.http.server_header is not None:
return domain.http.server_header.replace(",", ";")
return None
def get_domain_server_version(domain):
"""
Get the Server version based on the Server header for the web server.
"""
if domain.canonical.server_version is not None:
return domain.canonical.server_version
if domain.https.server_version is not None:
return domain.https.server_version
if domain.httpswww.server_version is not None:
return domain.httpswww.server_version
if domain.httpwww.server_version is not None:
return domain.httpwww.server_version
if domain.http.server_version is not None:
return domain.http.server_version
return None
def get_domain_notes(domain):
"""
Combine all domain notes if there are any.
"""
all_notes = (
domain.http.notes
+ domain.httpwww.notes
+ domain.https.notes
+ domain.httpswww.notes
)
all_notes = all_notes.replace(",", ";")
return all_notes
def did_domain_error(domain):
"""
Checks if the domain had an Unknown error somewhere
The main purpos of this is to flag any odd websites for
further debugging with other tools.
"""
http, httpwww, https, httpswww = (
domain.http,
domain.httpwww,
domain.https,
domain.httpswww,
)
return (
http.unknown_error
or httpwww.unknown_error
or https.unknown_error
or httpswww.unknown_error
)
def run(domains):
results = {}
initialize_external_data()
for base_domain in domains:
domain = Domain(base_domain)
domain.http = Endpoint("http", "root", base_domain)
domain.httpwww = Endpoint("http", "www", base_domain)
domain.https = Endpoint("https", "root", base_domain)
domain.httpswww = Endpoint("https", "www", base_domain)
# Analyze HTTP endpoint responsiveness and behavior.
basic_check(domain.http)
basic_check(domain.httpwww)
basic_check(domain.https)
basic_check(domain.httpswww)
# Analyze HSTS header, if present, on each HTTPS endpoint.
hsts_check(domain.https)
hsts_check(domain.httpswww)
results[base_domain] = result_for(domain)
return results
def ping(url, allow_redirects=False, verify=True):
return requests.get(
url, allow_redirects=allow_redirects, verify=verify, stream=True
)
def basic_check(endpoint):
"""
Test the endpoint. At first:
* Don't follow redirects. (Will only follow if necessary.)
If it's a 3XX, we'll ping again to follow redirects. This is
necessary to reliably scope any errors (e.g. TLS errors) to
the original endpoint.
* Validate certificates. (Will figure out error if necessary.)
"""
req = None
try:
with ping(endpoint.url) as req:
endpoint.live = True
if endpoint.protocol == "https":
endpoint.https_full_connection = True
endpoint.https_valid = True
except requests.exceptions.SSLError as err:
if "bad handshake" in str(err) and (
"sslv3 alert handshake failure" in str(err)
or ("Unexpected EOF" in str(err))
):
logging.debug(
"{}: Error completing TLS handshake usually due to required client authentication.".format(
endpoint.url
)
)
endpoint.live = True
if endpoint.protocol == "https":
# The https can still be valid with a handshake error,
# sslyze will run later and check if it is not valid
endpoint.https_valid = True
endpoint.https_full_connection = False
else:
logging.debug(
"{}: Error connecting over SSL/TLS or validating certificate.".format(
endpoint.url
)
)
# Retry with certificate validation disabled.
try:
with ping(endpoint.url, verify=False) as req:
endpoint.live = True
if endpoint.protocol == "https":
endpoint.https_full_connection = True
# sslyze later will actually check if the cert is valid
endpoint.https_valid = True
except requests.exceptions.SSLError as err:
# If it's a protocol error or other, it's not a full connection,
# but it is live.
endpoint.live = True
if endpoint.protocol == "https":
endpoint.https_full_connection = False
# HTTPS may still be valid, sslyze will double-check later
endpoint.https_valid = True
logging.debug(
"{}: Unexpected SSL protocol (or other) error during retry.".format(
endpoint.url
)
)
# continue on to SSLyze to check the connection
except requests.exceptions.RequestException as err:
endpoint.live = False
logging.debug(
"{}: Unexpected requests exception during retry.".format(
endpoint.url
)
)
return
except OpenSSL.SSL.Error as err:
endpoint.live = False
logging.debug(
"{}: Unexpected OpenSSL exception during retry.".format(
endpoint.url
)
)
return
except Exception as err:
endpoint.unknown_error = True
logging.debug(
"{}: Unexpected other unknown exception during requests retry.".format(
endpoint.url
)
)
return
# If it was a certificate error of any kind, it's live,
# unless SSLyze encounters a connection error later
endpoint.live = True
except requests.exceptions.ConnectionError as err:
# We can get this for some endpoints that are actually live,
# so if it's https let's try sslyze to be sure
if endpoint.protocol == "https":
# https check later will set whether the endpoint is live and valid
endpoint.https_full_connection = False
endpoint.https_valid = True
else:
endpoint.live = False
logging.debug("{}: Error connecting.".format(endpoint.url))
# And this is the parent of ConnectionError and other things.
# For example, "too many redirects".
# See https://github.com/kennethreitz/requests/blob/master/requests/exceptions.py
except requests.exceptions.RequestException as err:
endpoint.live = False
logging.debug("{}: Unexpected other requests exception.".format(endpoint.url))
return
except Exception as err:
endpoint.unknown_error = True
logging.debug(
"{}: Unexpected other unknown exception during initial request.".format(
endpoint.url
)
)
return
# Run SSLyze to see if there are any errors
if endpoint.protocol == "https":
https_check(endpoint)
# Double-check in case sslyze failed the first time, but the regular conneciton succeeded
if endpoint.live is False and req is not None:
logging.debug(
"{}: Trying sslyze again since it connected once already.".format(
endpoint.url
)
)
endpoint.live = True
endpoint.https_valid = True
https_check(endpoint)
if endpoint.live is False:
# sslyze failed so back everything out and don't continue analyzing the existing response
req = None
endpoint.https_valid = False
endpoint.https_full_connection = False
if req is None:
# Ensure that full_connection is set to False if we didn't get a response
if endpoint.protocol == "https":
endpoint.https_full_connection = False
return
# try to get IP address if we can
try:
if req.raw.closed is False:
ip = req.raw._connection.sock.socket.getpeername()[0]
if endpoint.ip is None:
endpoint.ip = ip
else:
if endpoint.ip != ip:
logging.debug(
"{}: Endpoint IP is already {}, but requests IP is {}.".format(
endpoint.url, endpoint.ip, ip
)
)
except Exception:
# if the socket has already closed, it will throw an exception, but this is just best effort, so ignore it
logging.debug("Error closing socket")
# Endpoint is live, analyze the response.
endpoint.headers = req.headers
endpoint.status = req.status_code
if req.headers.get("Server") is not None:
endpoint.server_header = req.headers.get("Server")
# *** in the future add logic to convert header to server version if known
if (req.headers.get("Location") is not None) and str(endpoint.status).startswith(
"3"
):
endpoint.redirect = True
logging.debug("{}: Found redirect.".format(endpoint.url))
if endpoint.redirect:
try:
location_header = req.headers.get("Location")
# Absolute redirects (e.g. "https://example.com/Index.aspx")
if location_header.startswith("http:") or location_header.startswith(
"https:"
):
immediate = location_header
# Relative redirects (e.g. "Location: /Index.aspx").
# Construct absolute URI, relative to original request.
else:
immediate = urllib.parse.urljoin(endpoint.url, location_header)
# Chase down the ultimate destination, ignoring any certificate warnings.
ultimate_req = None
except Exception as err:
endpoint.unknown_error = True
logging.debug(
"{}: Unexpected other unknown exception when handling Requests Header.".format(
endpoint.url