Created
May 2, 2016 14:12
-
-
Save takeshixx/2e84325ce653611b909409ec62c4954a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import socket | |
import ssl | |
import sys | |
try: | |
from pyasn1.codec.der import decoder | |
from pyasn1_modules import rfc2459 | |
except ImportError: | |
print('Run: pip install pyasn1 pyasn1-modules') | |
sys.exit(1) | |
HOST = 'www.troopers.de' | |
PORT = 443 | |
HTTP = b'''GET /troopers17 HTTP/1.1 | |
Host: www.troopers.de | |
''' | |
def get_socket(): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.settimeout(2) | |
ws = ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE) | |
try: | |
ws.connect((HOST, PORT)) | |
except ConnectionRefusedError as e: | |
print(e) | |
sys.exit(1) | |
return ws | |
def get_cert_info(cert): | |
_cert = decoder.decode(cert, asn1Spec=rfc2459.Certificate())[0] | |
tbs = _cert.getComponentByName('tbsCertificate') | |
subject = tbs.getComponentByName('subject') | |
issuer = tbs.getComponentByName('issuer') | |
cns = set() | |
issuer_cns = set() | |
for rdnss in subject: | |
for rdns in rdnss: | |
for name in rdns: | |
oid = name.getComponentByName('type') | |
value = name.getComponentByName('value') | |
if oid != rfc2459.id_at_commonName: | |
continue | |
value = decoder.decode(value, asn1Spec=rfc2459.DirectoryString())[0] | |
cns.add(value.getComponent()) | |
for rdnss in issuer: | |
for rdns in rdnss: | |
for name in rdns: | |
oid = name.getComponentByName('type') | |
value = name.getComponentByName('value') | |
if oid != rfc2459.id_at_commonName: | |
continue | |
value = decoder.decode(value, asn1Spec=rfc2459.DirectoryString())[0] | |
issuer_cns.add(value.getComponent()) | |
return str(list(cns)[0]), str(list(issuer_cns)[0]) | |
def verify_cert(cert): | |
common_name, issuer = get_cert_info(cert) | |
if common_name != 'www.troopers.de': | |
print('Invalid CommonName: {}'.format(common_name)) | |
return False | |
elif issuer != 'TeleSec ServerPass CA 2': | |
print('Invalid Issuer CommonName: {}'.format(issuer)) | |
return False | |
else: | |
return True | |
if __name__ == '__main__': | |
sock = get_socket() | |
cert = sock.getpeercert(binary_form=True) | |
if cert and verify_cert(cert): | |
sock.send(HTTP) | |
resp = b'' | |
while True: | |
try: | |
resp += sock.recv(4096) | |
except socket.timeout: | |
break | |
try: | |
head, body = resp.split(b'\r\n\r\n', 1) | |
except ValueError: | |
print(resp) | |
print(head) | |
else: | |
print('Invalid certificate, stahp!') | |
sock.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment