├── README.md ├── LICENSE ├── .gitignore └── getcert.py /README.md: -------------------------------------------------------------------------------- 1 | # Archived 2 | 3 | > Please take a look at [Cert Human: SSL Certificates for Humans](https://github.com/lifehackjim/cert_human) for an impressive rewrite of this project by [`lifehackjim`](https://github.com/lifehackjim) 4 | 5 | # 🐍 get-ca-py 6 | 7 | [![Code Style: Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) 8 | 9 | Extracting Certificate Authorities from a request. 10 | 11 | ## Usage 12 | 13 | ```bash 14 | λ python getcert.py -h 15 | usage: getcert.py [-h] [--verify] [--no-verify] URL 16 | 17 | Request any URL and dump the certificate chain 18 | 19 | positional arguments: 20 | URL Valid https URL to be handled by requests 21 | 22 | optional arguments: 23 | -h, --help show this help message and exit 24 | --verify Explicitly set SSL verification 25 | --no-verify Explicitly disable SSL verification 26 | ``` 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Josh Peak 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /getcert.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Get Certificates from a request and dump them. 5 | """ 6 | 7 | import argparse 8 | import sys 9 | 10 | import requests 11 | from requests.packages.urllib3.exceptions import InsecureRequestWarning 12 | 13 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 14 | 15 | """ 16 | Inspired by the answers from this Stackoverflow question: 17 | https://stackoverflow.com/questions/16903528/how-to-get-response-ssl-certificate-from-requests-in-python 18 | 19 | What follows is a series of patching the low level libraries in requests. 20 | """ 21 | 22 | """ 23 | https://stackoverflow.com/a/47931103/622276 24 | """ 25 | 26 | sock_requests = requests.packages.urllib3.contrib.pyopenssl.WrappedSocket 27 | 28 | 29 | def new_getpeercertchain(self, *args, **kwargs): 30 | x509 = self.connection.get_peer_cert_chain() 31 | return x509 32 | 33 | 34 | sock_requests.getpeercertchain = new_getpeercertchain 35 | 36 | """ 37 | https://stackoverflow.com/a/16904808/622276 38 | """ 39 | 40 | HTTPResponse = requests.packages.urllib3.response.HTTPResponse 41 | orig_HTTPResponse__init__ = HTTPResponse.__init__ 42 | 43 | 44 | def new_HTTPResponse__init__(self, *args, **kwargs): 45 | orig_HTTPResponse__init__(self, *args, **kwargs) 46 | try: 47 | self.peercertchain = self._connection.sock.getpeercertchain() 48 | except AttributeError: 49 | pass 50 | 51 | 52 | HTTPResponse.__init__ = new_HTTPResponse__init__ 53 | 54 | HTTPAdapter = requests.adapters.HTTPAdapter 55 | orig_HTTPAdapter_build_response = HTTPAdapter.build_response 56 | 57 | 58 | def new_HTTPAdapter_build_response(self, request, resp): 59 | response = orig_HTTPAdapter_build_response(self, request, resp) 60 | try: 61 | response.peercertchain = resp.peercertchain 62 | except AttributeError: 63 | pass 64 | return response 65 | 66 | 67 | HTTPAdapter.build_response = new_HTTPAdapter_build_response 68 | 69 | """ 70 | Attempt to wrap in a somewhat usable CLI 71 | """ 72 | 73 | 74 | def cli(args): 75 | parser = argparse.ArgumentParser(description="Request any URL and dump the certificate chain") 76 | parser.add_argument("url", metavar="URL", type=str, nargs=1, help="Valid https URL to be handled by requests") 77 | 78 | verify_parser = parser.add_mutually_exclusive_group(required=False) 79 | verify_parser.add_argument("--verify", dest="verify", action="store_true", help="Explicitly set SSL verification") 80 | verify_parser.add_argument( 81 | "--no-verify", dest="verify", action="store_false", help="Explicitly disable SSL verification" 82 | ) 83 | parser.set_defaults(verify=True) 84 | 85 | return vars(parser.parse_args(args)) 86 | 87 | 88 | def dump_pem(cert, outfile="ca-chain.crt"): 89 | """Use the CN to dump certificate to PEM format""" 90 | PyOpenSSL = requests.packages.urllib3.contrib.pyopenssl 91 | pem_data = PyOpenSSL.OpenSSL.crypto.dump_certificate(PyOpenSSL.OpenSSL.crypto.FILETYPE_PEM, cert) 92 | issuer = cert.get_issuer().get_components() 93 | 94 | print(pem_data.decode("utf-8")) 95 | 96 | with open(outfile, "a") as output: 97 | for part in issuer: 98 | output.write(part[0].decode("utf-8")) 99 | output.write("=") 100 | output.write(part[1].decode("utf-8")) 101 | output.write(",\t") 102 | output.write("\n") 103 | output.write(pem_data.decode("utf-8")) 104 | 105 | 106 | if __name__ == "__main__": 107 | cli_args = cli(sys.argv[1:]) 108 | 109 | url = cli_args["url"][0] 110 | req = requests.get(url, verify=cli_args["verify"]) 111 | for cert in req.peercertchain: 112 | dump_pem(cert) 113 | --------------------------------------------------------------------------------