From 6481706f5945f93ad5a45eb3591eb638204fa2b8 Mon Sep 17 00:00:00 2001 From: brent s Date: Tue, 18 Dec 2018 07:24:29 -0500 Subject: [PATCH] checking in - packaging preliminary --- LICENSE.txt | 11 +++++ README.html | 35 +++++++++++++++ README.md | 47 ++++++++++++++++++++ certparser.py | 120 ++++---------------------------------------------- 4 files changed, 101 insertions(+), 112 deletions(-) create mode 100644 LICENSE.txt create mode 100644 README.html create mode 100644 README.md diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..f361188 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,11 @@ +Copyright 2018 Brent Saner + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.html b/README.html new file mode 100644 index 0000000..d30220e --- /dev/null +++ b/README.html @@ -0,0 +1,35 @@ + + + + + + + + +

Certparser

+ +

What is it?

+ +

Certparser is a fairly small module that will parse an X.509 certificate (commonly referred to as “HTTPS certificates”, “SSL certificates” (even though proper modern implementations should be using TLS), etc.), either locally as a file (or input stream, etc.) or remote (across a small subset of protocols which will expand with time). X.509 is a complex thing, so if I missed part of it let me know! (RFC numbers and sections very welcome.)

+ +

It can be invoked directly as a command:

+ +

bash +./certparser.py +

+ +

(See ./certparser.py --help for more information on usage.)

+ +

Or as a python module:

+ +

```python +import certparser

+ +

parser = certparser.CertParse(‘square-r00t.net’) +print(parser.cert) # prints the fetched certificate +print(parser.certinfo) # prints the parsed certificate information +```

+ +

(See pydoc certparser for more information on usage.)

+ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..45753a5 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# Certparser + + +## What is it? +Certparser is a fairly small module that will parse an X.509 certificate. These are commonly referred to as "HTTPS certificates", "SSL certificates" (even though proper modern implementations should be using TLS), etc. + +Certparser can operate on either a local file (or input stream, etc.) or remote (across a small subset of protocols which will expand with time). + +X.509 is a complex thing, so if I missed part of it please [let me know](https://bugs.square-r00t.net/index.php?project=12)! (RFC numbers and sections *very* welcome.) + + +## Quickstart +It can be invoked directly as a command: + +```bash +./certparser.py +``` + +(See `./certparser.py --help` for more information on usage.) + +Or as a python module: + +```python +import certparser + +parser = certparser.CertParse('square-r00t.net') +print(parser.cert) # prints the fetched certificate +print(parser.certinfo) # prints the parsed certificate information +``` + +(See `pydoc certparser` for more information on usage.) + + +## Requirements +Currently, only the following non-stdlib modules are required: + +* [pyOpenSSL](https://pyopenssl.org/en/stable/) +* [validators](https://validators.readthedocs.io/en/latest/) + +As parsing work continues and features/protocols are added, the following will **probably** be used (but are NOT currently): + +* [pyasn1](https://github.com/etingof/pyasn1) +* [jinja2](http://jinja.pocoo.org/) + +And the following will be required optionally (but recommended): + +* [lxml](https://lxml.de/) diff --git a/certparser.py b/certparser.py index 7372595..e866442 100755 --- a/certparser.py +++ b/certparser.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 # stdlib -import argparse import collections import copy import datetime @@ -12,41 +11,25 @@ import json import os import pprint import re -import shutil -import socket import ssl from urllib import parse # PyPi/PIP -# These are handled automagically. -# If you'd rather install them via your distro's package manager (YOU SHOULD), -# then install them first then run this script. -# Otherwise you'll have to use pip to remove them. -thrd_prty = {'OpenSSL': 'pyOpenSSL', - #'pyasn1': 'pyasn1', - #'jinja2': 'Jinja2', - 'validators': 'validators'} +import OpenSSL -cols = shutil.get_terminal_size((80, 20)).columns - -for mod in thrd_prty: - try: - globals()[mod] = importlib.import_module(mod) - except ImportError: - import pip - pip.main(['install', '--quiet', '--quiet', '--quiet', - '--user', thrd_prty[mod]]) - globals()[mod] = importlib.import_module(mod) class CertParse(object): - def __init__(self, target, port = 443, force = None, cert_type = 'pem', - json_fmt = False, starttls = False, extensions = False, + def __init__(self, target, + port = 443, + force = None, + cert_type = 'pem', + starttls = False, + extensions = False, alt_names = False): self.target = target self.port = port self.force_type = force self.cert_type = cert_type self.starttls = starttls - self.json_fmt = json_fmt self.extensions = extensions self.alt_names = alt_names self.cert = None @@ -329,35 +312,6 @@ class CertParse(object): domain = parse.urlparse(url).netloc return(domain) - def validIP(self, ip): - is_valid = False - try: - ipaddress.ip_address(self.target) - is_valid = True - except ValueError: - pass - return(is_valid) - - def validDomain(self, domain): - is_valid = False - if not isinstance(validators.domain(domain), - validators.utils.ValidationFailure): - is_valid = True - return(is_valid) - - def validURL(self, url): - is_valid = False - if not isinstance(validators.url(url), - validators.utils.ValidationFailure): - is_valid = True - return(is_valid) - - def validPath(self, path): - is_valid = False - if os.path.isfile(path): - is_valid = True - return(is_valid) - def get_type(self): if self.force_type: # Just run the validator and some cleanup. @@ -409,66 +363,8 @@ class CertParse(object): 'resource it is')) return() -def parseArgs(): - args = argparse.ArgumentParser() - args.add_argument('-e', '--extensions', - dest = 'extensions', - action = 'store_true', - help = ('If specified, include ALL extension info ' + - '(this DRASTICALLY increases the output. You ' + - 'have been warned)')) - args.add_argument('-a', '--alt-names', - dest = 'alt_names', - action = 'store_true', - help = ('If specified, ONLY include the SAN (Subject ' + - 'Alt Name) extension. This is highly ' + - 'recommended over -e/--extensions. Ignored if ' + - '-e/--extensions is set (as the SANs are ' + - 'included in that)')) - args.add_argument('-j','--json', - dest = 'json_fmt', - action = 'store_true', - help = ('If specified, return the results in JSON')) - args.add_argument('-f', '--force', - choices = ['url', 'domain', 'ip', 'file'], - default = None, - help = ('If specified, force the TARGET to be parsed ' + - 'as the given type')) - args.add_argument('-p', '--port', - dest = 'port', - type = int, - default = 443, - help = ('Use a port other than 443 (only used for ' + - 'URL/domain/IP address targets)')) - args.add_argument('-t', '--cert-type', - dest = 'cert_type', - default = 'pem', - choices = ['pem', 'asn1'], - help = ('The type of certificate (only used for ' - 'file targets). Note that "DER"-encoded ' + - 'certificates should use "asn1". The default ' + - 'is pem')) -# TODO: I think the starttls process depends on the protocol? If so, this... -# won't be feasible. -# args.add_argument('-s', '--starttls', -# dest = 'starttls', -# action = 'store_true', -# help = ('If specified, initiate STARTTLS on the ' + -# 'target instead of pure SSL/TLS')) - args.add_argument('TARGET', - help = ('The target to gather cert info for. Can be a ' + - 'filepath (to the certificate, not key etc.), ' + - 'a URL/domain, or IP address')) - return(args) - -def main(): - args = vars(parseArgs().parse_args()) - args['target'] = copy.deepcopy(args['TARGET']) - del(args['TARGET']) +def main(args): p = CertParse(**args) p.getCert() p.parseCert() p.print() - -if __name__ == '__main__': - main()