diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa6dd51 --- /dev/null +++ b/.gitignore @@ -0,0 +1,249 @@ +# Created by https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode,vim +# Edit at https://www.toptal.com/developers/gitignore?templates=macos,python,visualstudiocode,vim + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# End of https://www.toptal.com/developers/gitignore/api/macos,python,visualstudiocode,vim diff --git a/README.md b/README.md index 57ff669..7fe1efb 100644 --- a/README.md +++ b/README.md @@ -5,35 +5,52 @@ Nagios/Icinga plugin. # Installation and requirements -You will need python 3.5 or newer, and the yaml, packaging and requests modules. Easiest -through the standard package manager: +You will need python 3.5 or newer, and the `yaml` and `requests` modules. +For exmaple through the standard package manager: + +```shell +apt-get install python3 python3-yaml python3-requests +``` + +or with a dedicated venv: ```sh - apt-get install python3 python3-yaml python3-requests python3-packaging +apt-get install python3-venv +python3 -m venv venv +. venv/bin/activate +pip install -U pip wheel +pip install pyyaml requests ``` # Features * Uses the [SSL Labs v3 API](https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api-docs-v3.md) -* Configurable warning/critical thresholds (default B and C) -* Caches results +* Configurable warning/critical threshold scores (default: `B/C`) +* Caching of results +* Proxy support # Usage ``` -usage: nagios-ssllabs-rating.py [-h] --host HOST [--warning WARNING] - [--critical CRITICAL] [--tempdir TEMPDIR] +usage: nagios-ssllabs-rating.py [-h] --host HOST [--proxy PROXY] + [--warning WARNING] + [--critical CRITICAL] + [--tempdir TEMPDIR] Check the rating of an HTTPS web site with the SSLLabs API. See -https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api-docs-v3.md +https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api- +docs-v3.md -optional arguments: +options: -h, --help show this help message and exit --host HOST The hostname/FQDN to check + --proxy PROXY The proxy to use when connecting to the SSLLabs + website --warning WARNING Rating that triggers a WARNING (default: B) --critical CRITICAL Rating that triggers a CRITICAL (default: C) - --tempdir TEMPDIR Directory to store cache files (default on this system: + --tempdir TEMPDIR Directory to store cache files (default on this + system: /tmp) ``` @@ -46,7 +63,7 @@ The rest of the output is extra information, meant for nagios as Default usage: -``` +```shell ~$ ./nagios-ssllabs-rating.py --host wiki.geant.org OK: SSLLabs rating is A See https://www.ssllabs.com/ssltest/analyze.html?d=wiki.geant.org @@ -88,7 +105,7 @@ testTime: 1594723519403 To get notified earlier, you can use lower thresholds ratings. For instance: -``` +```shell ~$ ./nagios-ssllabs-rating.py --host wiki.geant.org --warning A --critical B WARNING: SSLLabs rating is A See https://www.ssllabs.com/ssltest/analyze.html?d=wiki.geant.org @@ -127,6 +144,46 @@ status: READY testTime: 1594723519403 ``` +You can also supply an HTTP proxy explicitly: + +```shell +~$ ./nagios-ssllabs-rating.py --host about.geant.org --proxy http://localhost:8000 +OK: SSLLabs rating is A+ +See https://www.ssllabs.com/ssltest/analyze.html?d=about.geant.org + +API result: + +criteriaVersion: 2009q +endpoints: +- delegation: 1 + duration: 130042 + grade: A+ + gradeTrustIgnored: A+ + hasWarnings: false + ipAddress: 2001:798:3:0:0:0:0:132 + isExceptional: true + progress: 100 + serverName: security.geant.org + statusMessage: Ready +- delegation: 1 + duration: 130157 + grade: A+ + gradeTrustIgnored: A+ + hasWarnings: false + ipAddress: 83.97.93.30 + isExceptional: true + progress: 100 + serverName: tnc22.geant.org + statusMessage: Ready +engineVersion: 2.2.0 +host: about.geant.org +isPublic: false +port: 443 +protocol: http +startTime: 1699541305491 +status: READY +testTime: 1699541566057 +``` # Tips/gotchas @@ -146,8 +203,8 @@ When there are _no_ endpoints at all, this _is_ reported however (as CRITICAL): - * Starting up many probes at __exactly__ the same time will result in API throttling. Don't do that. * For use as a Nagios plugin, you can set the `tempdir` to something like `/var/cache/nagios3`, `/var/lib/nagios4/check_ssllabs/`, etc. +* TODO: migrate to v4 API diff --git a/nagios-ssllabs-rating.py b/nagios-ssllabs-rating.py index 983fb35..666926f 100755 --- a/nagios-ssllabs-rating.py +++ b/nagios-ssllabs-rating.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -# These come standard +# Standard import argparse import sys import os @@ -9,22 +9,18 @@ import hashlib import json -# These can be installed through apt/yum +# Install these import requests import yaml -from packaging import version - #from pprint import pprint - - -# TEMP logging... +# TEMP logging... # import logging -# logging.basicConfig( -# level=logging.DEBUG, -# format='%(asctime)s %(message)s', -# filename='/tmp/ssllabs.log' -# ) +# logging.basicconfig( +# level=logging.debug, +# format='%(asctime)s %(message)s', +# filename='/tmp/ssllabs.log' +# ) def nagios_exit(message, code): print(message) @@ -43,8 +39,7 @@ def report(results): # List of unique grades grades = list(set([ sub['grade'] for sub in results['endpoints'] if 'grade' in sub])) - grade = sorted(grades, key=lambda x: version.parse(x))[-1] - + grade = sorted(grades)[-1] # Endpoint inconsistency message if (len(statuses) > 1) or (len(grades) > 1): inconsistency_msg = " (but inconsistent across " + str(len(results['endpoints'])) + " endpoints)" @@ -53,9 +48,9 @@ def report(results): msg = "SSLLabs rating is " + grade + inconsistency_msg + info_line + debug_info - if version.parse(args.critical) <= version.parse(grade): + if args.critical <= grade: crit_msg.append(msg) - elif version.parse(args.warning) <= version.parse(grade): + elif args.warning <= grade: warn_msg.append(msg) else: ok_msg.append(msg) @@ -77,13 +72,16 @@ def report(results): tempdir = tempfile.gettempdir() parser = argparse.ArgumentParser( - description='Check the rating of an HTTPS web site with the SSLLabs API. ' + + description='Check the rating of an HTTPS web site with the SSLLabs API. ' + 'See https://github.com/ssllabs/ssllabs-scan/blob/master/ssllabs-api-docs-v3.md' ) parser.add_argument('--host', - help='The hostname/FQDN to check', + help='The hostname of the website to check', required=True ) + parser.add_argument('--proxy', + help='The proxy to use when connecting to the SSLLabs API', + ) parser.add_argument('--warning', help='Rating that triggers a WARNING (default: B)', default="B" @@ -97,9 +95,7 @@ def report(results): default=tempdir ) - args = parser.parse_args() - # start with clean slate ok_msg = [] @@ -114,9 +110,16 @@ def report(results): # Caching location cache_file = args.tempdir + "/ssllabs_check_" + hashlib.sha256(args.host.encode('utf-8')).hexdigest() + ".json" + # Proxy + if 'proxy' in args: + proxies = { 'https': args.proxy } + else: + proxies = None + api = "https://api.ssllabs.com/api/v3/" # Fetch API information for this IP address - api_status = requests.get(api + "info") + api_status = requests.get(api + "info", proxies=proxies) + # api_status = requests.get(api + "info") # logging.debug(api_status) current_assessments = api_status.json()["currentAssessments"] max_assessments = api_status.json()["maxAssessments"] @@ -146,7 +149,7 @@ def report(results): # Poll the API while True: - response = requests.get(api + "analyze?", params=params) + response = requests.get(api + "analyze?", params=params, proxies=proxies) if response.status_code != 200: break if response.json()['status'] in ['READY', 'ERROR']: @@ -160,7 +163,7 @@ def report(results): # pprint(results) # Store results with open(cache_file, "w") as fp: - json.dump(results, fp) + json.dump(results, fp, indent=2) # Report results report(results) else: