Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create pylint.yml #19

Merged
merged 2 commits into from
Oct 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Pylint

on: [push]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pylint
- name: Analysing the code with pylint
run: |
pylint $(git ls-files '*.py')
7 changes: 7 additions & 0 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[FORMAT]
max-line-length=120

[MESSAGES CONTROL]
disable=missing-module-docstring,
missing-function-docstring,
missing-class-docstring
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
Python script to check HTTP security headers


Same functionality as securityheaders.io but as Python script. Also checks some server/version headers. Written and tested using Python 3.4.
Same functionality as securityheaders.io but as Python script. Also checks some server/version headers. Written and tested using Python 3.8.

With minor modifications could be used as a library for other projects.

**NOTE**: The project renamed (2024-10-19) from **securityheaders** to **secheaders** to avoid confusion with PyPI package with similar name.

## Installation

The following assumes you have Python installed and command `python` refers to python version >= 3.4.
The following assumes you have Python installed and command `python` refers to python version >= 3.8.

### Run without installation

Expand Down Expand Up @@ -57,7 +59,3 @@ HTTPS supported ... [ OK ]
HTTPS valid certificate ... [ OK ]
HTTP -> HTTPS redirect ... [ WARN ]
```

## Note

The project renamed (2024-10-19) from **securityheaders** to **secheaders** to avoid confusion with PyPI package with similar name.
37 changes: 3 additions & 34 deletions secheaders/constants.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from . import utils

# If no URL scheme defined, what to use by default
DEFAULT_URL_SCHEME = 'https'
DEFAULT_TIMEOUT = 10
Expand All @@ -17,6 +15,9 @@

EVAL_WARN = 0
EVAL_OK = 1
OK_COLOR = '\033[92m'
END_COLOR = '\033[0m'
WARN_COLOR = '\033[93m'

# There are no universal rules for "safe" and "unsafe" CSP directives, but we apply some common sense here to
# catch some risky configurations
Expand All @@ -41,35 +42,3 @@
HEADER_STRUCTURED_LIST = [ # Response headers that define multiple values as comma-sparated list
'permissions-policy',
]

SECURITY_HEADERS_DICT = {
'x-frame-options': {
'recommended': True,
'eval_func': utils.eval_x_frame_options,
},
'strict-transport-security': {
'recommended': True,
'eval_func': utils.eval_sts,
},
'content-security-policy': {
'recommended': True,
'eval_func': utils.eval_csp,
},
'x-content-type-options': {
'recommended': True,
'eval_func': utils.eval_content_type_options,
},
'x-xss-protection': {
# X-XSS-Protection is deprecated; not supported anymore, and may be even dangerous in older browsers
'recommended': False,
'eval_func': utils.eval_x_xss_protection,
},
'referrer-policy': {
'recommended': True,
'eval_func': utils.eval_referrer_policy,
},
'permissions-policy': {
'recommended': True,
'eval_func': utils.eval_permissions_policy,
}
}
128 changes: 79 additions & 49 deletions secheaders/securityheaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,72 @@

from . import utils
from .constants import DEFAULT_TIMEOUT, DEFAULT_URL_SCHEME, EVAL_WARN, REQUEST_HEADERS, HEADER_STRUCTURED_LIST, \
SECURITY_HEADERS_DICT, SERVER_VERSION_HEADERS
SERVER_VERSION_HEADERS
from .exceptions import SecurityHeadersException, InvalidTargetURL, UnableToConnect


class SecurityHeaders():
SECURITY_HEADERS_DICT = {
'x-frame-options': {
'recommended': True,
'eval_func': utils.eval_x_frame_options,
},
'strict-transport-security': {
'recommended': True,
'eval_func': utils.eval_sts,
},
'content-security-policy': {
'recommended': True,
'eval_func': utils.eval_csp,
},
'x-content-type-options': {
'recommended': True,
'eval_func': utils.eval_content_type_options,
},
'x-xss-protection': {
# X-XSS-Protection is deprecated; not supported anymore, and may be even dangerous in older browsers
'recommended': False,
'eval_func': utils.eval_x_xss_protection,
},
'referrer-policy': {
'recommended': True,
'eval_func': utils.eval_referrer_policy,
},
'permissions-policy': {
'recommended': True,
'eval_func': utils.eval_permissions_policy,
}
}

def __init__(self, url, max_redirects=2, no_check_certificate=False):
parsed = urlparse(url)
if not parsed.scheme and not parsed.netloc:
url = "{}://{}".format(DEFAULT_URL_SCHEME, url)
url = f"{DEFAULT_URL_SCHEME}://{url}"
parsed = urlparse(url)
if not parsed.scheme and not parsed.netloc:
raise InvalidTargetURL("Unable to parse the URL")

self.protocol_scheme = parsed.scheme
self.hostname = parsed.netloc
self.path = parsed.path
self.verify_ssl = False if no_check_certificate else True
self.verify_ssl = not no_check_certificate
self.target_url: ParseResult = self._follow_redirect_until_response(url, max_redirects) if max_redirects > 0 \
else parsed
self.headers = {}

def test_https(self):
redirect_supported = self._test_http_to_https()

conn = http.client.HTTPSConnection(self.hostname, context=ssl.create_default_context(),
timeout=DEFAULT_TIMEOUT)
try:
conn.request('GET', '/')
except (socket.gaierror, socket.timeout, ConnectionRefusedError):
return {'supported': False, 'certvalid': False}
return {'supported': False, 'certvalid': False, 'redirect': redirect_supported}
except ssl.SSLError:
return {'supported': True, 'certvalid': False}
return {'supported': True, 'certvalid': False, 'redirect': redirect_supported}

return {'supported': True, 'certvalid': True}
return {'supported': True, 'certvalid': True, 'redirect': redirect_supported}

def _follow_redirect_until_response(self, url, follow_redirects=5):
temp_url = urlparse(url)
Expand All @@ -48,7 +82,7 @@ def _follow_redirect_until_response(self, url, follow_redirects=5):
if temp_url.scheme == 'http':
conn = http.client.HTTPConnection(temp_url.netloc, timeout=DEFAULT_TIMEOUT)
elif temp_url.scheme == 'https':
ctx = ssl.create_default_context() if self.verify_ssl else ssl._create_stdlib_context()
ctx = ssl.create_default_context() if self.verify_ssl else ssl._create_stdlib_context() # pylint: disable=protected-access
conn = http.client.HTTPSConnection(temp_url.netloc, context=ctx, timeout=DEFAULT_TIMEOUT)
else:
raise InvalidTargetURL("Unsupported protocol scheme")
Expand All @@ -57,7 +91,7 @@ def _follow_redirect_until_response(self, url, follow_redirects=5):
conn.request('GET', temp_url.path, headers=REQUEST_HEADERS)
res = conn.getresponse()
except (socket.gaierror, socket.timeout, ConnectionRefusedError) as e:
raise UnableToConnect("Connection failed {}".format(temp_url.netloc)) from e
raise UnableToConnect(f"Connection failed {temp_url.netloc}") from e
except ssl.SSLError as e:
raise UnableToConnect("SSL Error") from e

Expand All @@ -77,9 +111,9 @@ def _follow_redirect_until_response(self, url, follow_redirects=5):
# More than x redirects, stop here
return temp_url

def test_http_to_https(self, follow_redirects=5):
url = "http://{}{}".format(self.hostname, self.path)
target_url = self._follow_redirect_until_response(url)
def _test_http_to_https(self, follow_redirects=5):
url = f"http://{self.hostname}{self.path}"
target_url = self._follow_redirect_until_response(url, follow_redirects)
if target_url and target_url.scheme == 'https':
return True

Expand All @@ -92,7 +126,7 @@ def open_connection(self, target_url):
if self.verify_ssl:
ctx = ssl.create_default_context()
else:
ctx = ssl._create_stdlib_context()
ctx = ssl._create_stdlib_context() # pylint: disable=protected-access
conn = http.client.HTTPSConnection(target_url.hostname, context=ctx, timeout=DEFAULT_TIMEOUT)
else:
raise InvalidTargetURL("Unsupported protocol scheme")
Expand All @@ -107,14 +141,14 @@ def fetch_headers(self):
conn.request('GET', self.target_url.path, headers=REQUEST_HEADERS)
res = conn.getresponse()
except (socket.gaierror, socket.timeout, ConnectionRefusedError, ssl.SSLError) as e:
raise UnableToConnect("Connection failed {}".format(self.target_url.hostname)) from e
raise UnableToConnect(f"Connection failed {self.target_url.hostname}") from e

headers = res.getheaders()
for h in headers:
key = h[0].lower()
if key in HEADER_STRUCTURED_LIST and key in self.headers:
# Scenario described in RFC 2616 section 4.2
self.headers[key] += ', {}'.format(h[1])
self.headers[key] += f', {h[1]}'
else:
self.headers[key] = h[1]

Expand All @@ -125,22 +159,20 @@ def check_headers(self):
if not self.headers:
raise SecurityHeadersException("Headers not fetched successfully")

""" Loop through headers and evaluate the risk """
for header in SECURITY_HEADERS_DICT:
for header, settings in self.SECURITY_HEADERS_DICT.items():
if header in self.headers:
eval_func = SECURITY_HEADERS_DICT[header].get('eval_func')
eval_func = settings.get('eval_func')
if not eval_func:
raise SecurityHeadersException("No evaluation function found for header: {}".format(header))
raise SecurityHeadersException(f"No evaluation function found for header: {header}")
res, notes = eval_func(self.headers[header])
retval[header] = {
'defined': True,
'warn': res == EVAL_WARN,
'contents': self.headers[header],
'notes': notes,
}

else:
warn = SECURITY_HEADERS_DICT[header].get('recommended')
warn = settings.get('recommended')
retval[header] = {'defined': False, 'warn': warn, 'contents': None, 'notes': []}

for header in SERVER_VERSION_HEADERS:
Expand All @@ -155,6 +187,32 @@ def check_headers(self):

return retval

def output_cli(headers, https):
for header, value in headers.items():
if value['warn']:
if not value['defined']:
utils.print_warning(f"Header '{header}' is missing")
else:
utils.print_warning(f"Header '{header}' contains value '{value['contents']}")
for note in value['notes']:
print(f" * {note}")
else:
if not value['defined']:
utils.print_ok(f"Header '{header}' is missing")
else:
utils.print_ok(f"Header '{header}' contains a proper value")

msg_map = {
'supported': 'HTTPS supported',
'certvalid': 'HTTPS valid certificate',
'redirect': 'HTTP -> HTTPS automatic redirect',
}
for key in https:
if https[key]:
utils.print_ok(msg_map[key])
else:
utils.print_warning(msg_map[key])


def main():
parser = argparse.ArgumentParser(description='Check HTTP security headers',
Expand All @@ -177,36 +235,8 @@ def main():
print("Failed to fetch headers, exiting...")
sys.exit(1)

for header, value in headers.items():
if value['warn']:
if not value['defined']:
utils.print_warning("Header '{}' is missing".format(header))
else:
utils.print_warning("Header '{}' contains value '{}".format(header, value['contents']))
for n in value['notes']:
print(" * {}".format(n))
else:
if not value['defined']:
utils.print_ok("Header '{}' is missing".format(header))
else:
utils.print_ok("Header '{}' contains a proper value".format(header))

https = header_check.test_https()
if https['supported']:
utils.print_ok("HTTPS supported")
else:
utils.print_warning("HTTPS supported")

if https['certvalid']:
utils.print_ok("HTTPS valid certificate")
else:
utils.print_warning("HTTPS valid certificate")

if header_check.test_http_to_https():
utils.print_ok("HTTP -> HTTPS redirect")
else:
utils.print_warning("HTTP -> HTTPS redirect")

output_cli(headers, https)

if __name__ == "__main__":
main()
Loading
Loading