8

Python script to check on SSL certificates

 2 years ago
source link: https://gist.github.com/gdamjan/55a8b9eec6cf7b771f92021d93b87b2c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

This helped me out of a jam. thank you.

Appreciate all your efforts! Thanks!

Hi,
the script is useful, but it's possible put these values:
('damjan.softver.org.mk', 443),
('expired.badssl.com', 443),
('wrong.host.badssl.com', 443),
('ca.ocsr.nl', 443),
('faß.de', 443),
('самодеј.мкд', 443),
inside a text file? I mean exist an elegant way to read lines of file into list?

Author

gdamjan commented on Aug 18, 2019

@redmine-cosi:

sure, why not. open a file, read line by line, and split on : or empty space, or anything. maybe use csv module?

Uhm, Things are really complicated for me right now :( I tried so:
...
with open("cert-list.csv") as filecsv:
HOSTS = csv.reader(filecsv, delimiter=',')
for row, line in enumerate(HOSTS):
a = '{}'.format(line)
print(a)
print (type(line))
print (type(row))
...
my .csv file:
pd.trust.it, 443
dev.scinetwork.it, 443
cs.fibc.it, 443
ouput:
['pd.trust.it', ' 443']
<class 'list'>
<class 'int'>
['dev.scinetwork.it', ' 443']
<class 'list'>
<class 'int'>
['cs.fibc.it', ' 443']
<class 'list'>
<class 'int'>
Traceback (most recent call last):
File "cert-ssl-check.py", line 100, in
for hostinfo in e.map(lambda x: get_certificate(x[0], x[1]), HOSTS):
File "/usr/lib/python3.5/concurrent/futures/_base.py", line 548, in map
fs = [self.submit(fn, *args) for args in zip(*iterables)]
File "/usr/lib/python3.5/concurrent/futures/_base.py", line 548, in
fs = [self.submit(fn, *args) for args in zip(*iterables)]
ValueError: I/O operation on closed file.

Author

gdamjan commented on Aug 19, 2019

I don't think gist comments are the best place to learn python

Are you able to distinguish the certificate type from this info e.g. ('OV SSL', 'EV SSL', 'DV SSL') ?

Author

gdamjan commented on Sep 4, 2019

Are you able to distinguish the certificate type from this info e.g. ('OV SSL', 'EV SSL', 'DV SSL') ?

afaik yes, if you give me an example site with those attributes I can take a look how to extract those from the cert info

wiperpaul commented on Sep 5, 2019

edited

For example PayPal.com has an expensive EV(Extended Validation) SSL cert but the only indication I've been able to find is occasionally sites have 'Extended Validation Server' in their CN field.

This isn't standard either, some just have a name like 'Google Trust Services' like for Google.com.

Edit - I just found this post clearing some of this up for me, https://security.stackexchange.com/questions/88721/how-to-detect-whether-a-ca-used-ev-for-a-certificate-using-openssl

Author

gdamjan commented on Sep 5, 2019

https://en.wikipedia.org/wiki/Extended_Validation_Certificate

EV certificates are different from domain-validated certificates and organization-validation certificates in that they can be issued only by a subset of certificate authorities (CAs) and require verification of the requesting entity's legal identity before certificate issuance.

so you'll need to have a list of the CAs

Hi gdamjan,

I am trying to get the following information from a certificate through python:

  • Issuer Name

  • Valid From

  • Valid To

  • Site Name

And I was trying your script only to get the following error:

AttributeError: 'X509' object has no attribute 'issuer'

Please Help
Thanks and Regards.

Author

gdamjan commented on Feb 20, 2020

those are all in the script above

Can you help regarding this issue also:
AttributeError: 'X509' object has no attribute 'issuer'
Thanks

Are you able to distinguish the certificate type from this info e.g. ('OV SSL', 'EV SSL', 'DV SSL') ?

You may go through the extensions (certificate.get_extension(i)) and search for the EV policy id:

2.23.140.1.2.1 DV
2.23.140.1.2.2 OV
2.23.140.1.1   EV

Author

gdamjan commented on Jul 9, 2020

edited

@simon-wessel cool.

So, def get_certificate(hostname, port): returns the HostInfo object. Its .cert field has the .extensions list.

An example:

def cert_type(cert):
    for ext in cert.extensions:
        if ext.oid.dotted_string == '2.23.140.1.2.1':
            return 'DV type'
        if ext.oid.dotted_string == '2.23.140.1.2.2':
            return 'OV type'
        if ext.oid.dotted_string == '2.23.140.1.1':
            return 'EV' type
    return 'Normal certificate type'

host = get_certificate('example.net')
cert_type(host.cert)

This works great at a basic level, I'm new with python, I struggled a bit figuring out where to run PIP from to get pyopenssl and the other dependencies installed to run it , but it was easy if when you install python, you get pip installed from the beginning , obviously you set the path variable, then you just use pip from the windows CMD and it works. I would like this code to have a separate alerts field in the output for certs expiring in 60 days I would also like to figure out getting email built into it.

How do we get the results in json format?

Author

gdamjan commented on Sep 22, 2020

How do we get the results in json format?

json.dumps(host._as_dict())

How do we get the results in json format?

json.dumps(host._as_dict())

Thanks - but this is what I get

Code:
host = get_certificate('google.co.nz', 443)
print(host)
json.dumps(host._as_dict())

Error:
HostInfo(cert=<Certificate(subject=<Name(C=US,ST=California,L=Mountain View,O=Google LLC,CN=*.google.co.nz)>, ...)>, hostname='google.co.nz', peername=('142.250.66.195', 443))
Traceback (most recent call last):
File ".\ssl-check.py", line 110, in
print_basic_info(hostinfo)
File ".\ssl-check.py", line 91, in print_basic_info
json.dumps(host._as_dict())
AttributeError: 'HostInfo' object has no attribute '_as_dict'

I am able to build the json manually but am thinking of a cooler option. :)

Author

gdamjan commented on Sep 23, 2020

._asdict()

I'm running into a suspected firewall issue when I attempt to access few hosts, and the script is failing and erroring out with:

Traceback (most recent call last):
  File "/usr/local/adm/checkcerts.py", line 53, in get_certificate
    sock.connect((hostname, port))
TimeoutError: [Errno 110] Connection timed out

For the specific hosts in my issue, I intend to address the issue with my networking team, but does anyone have a good suggestion for handling that error in the script?

alfonsrv commented on Mar 13, 2021

edited

Insanely dope script. namedtuple just blew my mind.
Any idea on how to verify the chain?

I am having problems with the verify_cert option is this working correctly and is there a way to check a self signed certificate?

skk294 commented on Aug 4, 2021

edited

nice, saved my day

suharevA commented on Dec 4, 2021

edited

How to add the output of the organization that issued the certificate to the script. For example
(O) Let's Encrypt

Everything. Figured it out
names_o = cert.issuer.get_attributes_for_oid(NameOID.ORGANIZATION_NAME)

when I get a list of sites and one of them does not have a TLS certificate configured, it generates an error:
sock.connect((hostname, port))
BlockingIOError: [Errno 11] Resource temporarily unavailable


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK