Skip to content
Navigation Menu
{{ message }}
forked from juerkkil/secheaders
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsecurityheaders.py
More file actions
241 lines (198 loc) · 8.38 KB
/
Copy pathsecurityheaders.py
File metadata and controls
241 lines (198 loc) · 8.38 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
import httplib
import argparse
import socket
import ssl
import sys
from urlparse import urlparse
class SecurityHeaders():
def __init__(self):
pass
def evaluate_warn(self, header, contents):
""" Risk evaluation function.
Set header warning flag (1/0) according to its contents.
Args:
header (str): HTTP header name in lower-case
contents (str): Header contents (value)
"""
warn = 1
if header == 'x-frame-options':
if contents.lower() in ['deny', 'sameorigin']:
warn = 0
else:
warn = 1
if header == 'strict-transport-security':
warn = 0
""" Evaluating the warn of CSP contents may be a bit more tricky.
For now, just disable the warn if the header is defined
"""
if header == 'content-security-policy':
warn = 0
""" Raise the warn flag, if cross domain requests are allowed from any
origin """
if header == 'access-control-allow-origin':
if contents == '*':
warn = 1
else:
warn = 0
if header == 'x-xss-protection':
if contents.lower() in ['1', '1; mode=block']:
warn = 0
else:
warn = 1
if header == 'x-content-type-options':
if contents.lower() == 'nosniff':
warn = 0
else:
warn =1
""" Enable warning if backend version information is disclosed """
if header == 'x-powered-by' or header == 'server':
if len(contents) > 1:
warn = 1
else:
warn = 0
return {'defined': True, 'warn': warn, 'contents': contents}
def test_https(self, url):
parsed = urlparse(url)
protocol = parsed[0]
hostname = parsed[1]
path = parsed[2]
sslerror = False
conn = httplib.HTTPSConnection(hostname)
try:
conn.request('GET', '/')
res = conn.getresponse()
except socket.gaierror:
return {'supported': False, 'certvalid': False}
except ssl.CertificateError:
return {'supported': True, 'certvalid': False}
except:
sslerror = True
# if tls connection fails for unexcepted error, retry without verifying cert
if sslerror:
conn = httplib.HTTPSConnection(hostname, timeout=5, context = ssl._create_unverified_context() )
try:
conn.request('GET', '/')
res = conn.getresponse()
return {'supported': True, 'certvalid': False}
except:
return {'supported': False, 'certvalid': False}
return {'supported': True, 'certvalid': True}
def test_http_to_https(self, url, follow_redirects = 5):
parsed = urlparse(url)
protocol = parsed[0]
hostname = parsed[1]
path = parsed[2]
if not protocol:
protocol = 'http' # default to http if protocl scheme not specified
if protocol == 'https' and follow_redirects != 5:
return True
elif protocol == 'https' and follow_redirects == 5:
protocol = 'http'
if (protocol == 'http'):
conn = httplib.HTTPConnection(hostname)
try:
conn.request('HEAD', path)
res = conn.getresponse()
headers = res.getheaders()
except socket.gaierror:
print 'HTTP request failed'
return False
""" Follow redirect """
if (res.status >= 300 and res.status < 400 and follow_redirects > 0):
for header in headers:
if (header[0] == 'location'):
return self.test_http_to_https(header[1], follow_redirects - 1)
return False
def check_headers(self, url, follow_redirects = 0):
""" Make the HTTP request and check if any of the pre-defined
headers exists.
Args:
url (str): Target URL in format: scheme://hostname/path/to/file
follow_redirects (Optional[str]): How deep we follow the redirects,
value 0 disables redirects.
"""
""" Default return array """
retval = {
'x-frame-options': {'defined': False, 'warn': 1, 'contents': '' },
'strict-transport-security': {'defined': False, 'warn': 1, 'contents': ''},
'access-control-allow-origin': {'defined': False, 'warn': 0, 'contents': ''},
'content-security-policy': {'defined': False, 'warn': 1, 'contents': ''},
'x-xss-protection': {'defined': False, 'warn': 1, 'contents': ''},
'x-content-type-options': {'defined': False, 'warn': 1, 'contents': ''},
'x-powered-by': {'defined': False, 'warn': 0, 'contents': ''},
'server': {'defined': False, 'warn': 0, 'contents': ''}
}
parsed = urlparse(url)
protocol = parsed[0]
hostname = parsed[1]
path = parsed[2]
if (protocol == 'http'):
conn = httplib.HTTPConnection(hostname)
elif (protocol == 'https'):
# on error, retry without verifying cert
# in this context, we're not really interested in cert validity
conn = httplib.HTTPSConnection(hostname, context = ssl._create_unverified_context() )
else:
""" Unknown protocol scheme """
return {}
try:
conn.request('HEAD', path)
res = conn.getresponse()
headers = res.getheaders()
except socket.gaierror:
print 'HTTP request failed'
return False
""" Follow redirect """
if (res.status >= 300 and res.status < 400 and follow_redirects > 0):
for header in headers:
if (header[0] == 'location'):
return self.check_headers(header[1], follow_redirects - 1)
""" Loop through headers and evaluate the risk """
for header in headers:
if (header[0] in retval):
retval[header[0]] = self.evaluate_warn(header[0], header[1])
return retval
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Check HTTP security headers', \
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('url', metavar='URL', type=str, help='Target URL')
parser.add_argument('--max-redirects', dest='max_redirects', metavar='N', default=2, type=int, help='Max redirects, set 0 to disable')
args = parser.parse_args()
url = args.url
redirects = args.max_redirects
foo = SecurityHeaders()
parsed = urlparse(url)
if not parsed.scheme:
url = 'http://' + url # default to http if scheme not provided
headers = foo.check_headers(url, redirects)
if not headers:
sys.exit(1)
okColor = '\033[92m'
warnColor = '\033[93m'
endColor = '\033[0m'
for header, value in headers.iteritems():
if value['warn'] == 1:
if value['defined'] == False:
print 'Header \'' + header + '\' is missing ... [ ' + warnColor + 'WARN' + endColor + ' ]'
else:
print 'Header \'' + header + '\' contains value \'' + value['contents'] + '\'' + \
' ... [ ' + warnColor + 'WARN' + endColor + ' ]'
elif value['warn'] == 0:
if value['defined'] == False:
print 'Header \'' + header + '\' is missing ... [ ' + okColor + 'OK' + endColor +' ]'
else:
print 'Header \'' + header + '\' contains value \'' + value['contents'] + '\'' + \
' ... [ ' + okColor + 'OK' + endColor + ' ]'
https = foo.test_https(url)
if https['supported']:
print 'HTTPS supported ... [ ' + okColor + 'OK' + endColor + ' ]'
else:
print 'HTTPS supported ... [ ' + warnColor + 'FAIL' + endColor + ' ]'
if https['certvalid']:
print 'HTTPS valid certificate ... [ ' + okColor + 'OK' + endColor + ' ]'
else:
print 'HTTPS valid certificate ... [ ' + warnColor + 'FAIL' + endColor + ' ]'
if foo.test_http_to_https(url, 5):
print 'HTTP -> HTTPS redirect ... [ ' + okColor + 'OK' + endColor + ' ]'
else:
print 'HTTP -> HTTPS redirect ... [ ' + warnColor + 'FAIL' + endColor + ' ]'
You can’t perform that action at this time.
