Python with SSL Library

最後更新: 2020-02-10

 


Intro

 

#!/bin/usr/env python

import ssl
import M2Crypto
import OpenSSL

# Get SSL
# The call will attempt to validate the server certificate against that set of root certificates, 
# and will fail if the validation attempt fails.
cert = ssl.get_server_certificate(('www.google.com', 443))

# M2Crypto
x509 = M2Crypto.X509.load_cert_string(cert)
print x509.get_subject().as_text()

# Output
# 'C=US, ST=California, L=Mountain View, O=Google Inc, CN=www.google.com'

# OpenSSL
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
print x509.get_subject().get_components()

# Output
#[('C', 'US'),
# ('ST', 'California'),
# ('L', 'Mountain View'),
# ('O', 'Google Inc'),
# ('CN', 'www.google.com')]

P.S.

以上 Example 有機會出現以下 Error, 原因係 TLS 用戶端不支援 SNI

OU=No SNI provided; please fix your client., CN=invalid2.invalid

 


設定 SNI

 

行用 class ssl.SSLContext(protocol) 去實現

hostname = "www.google.com"

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)

conn = ssl.create_connection((hostname, 443))
sock = context.wrap_socket(conn, server_hostname=hostname)
cert = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True))
x509 = M2Crypto.X509.load_cert_string(cert)
print x509.get_not_after().get_datetime()

PROTOCOL_* constants defined in this module.

ssl.PROTOCOL_TLS

Selects the highest protocol version that both the client and server support.

Despite the name, this option can select “TLS”

 


UNSUPPORTED_PROTOCOL

 

ssl.SSLError: [SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:727)
  • ssl.PROTOCOL_TLS
  • ssl.PROTOCOL_TLSv1
  • ssl.PROTOCOL_TLSv1_1
  • ssl.PROTOCOL_TLSv1_2

由 "ssl.PROTOCOL_TLS" 改成 "ssl.PROTOCOL_TLSv1"

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)

 


M2Crypto

 

m2crypto - Python wrapper for the OpenSSL library

pip

pip install m2crypto

# Debain

apt-get install python-m2crypto

 

x509

x509.get_subject().as_text()
x509.get_not_after().get_datetime()