Back to index

python3.2  3.2.2
Functions
get-remote-certificate Namespace Reference

Functions

def fetch_server_certificate

Function Documentation

def get-remote-certificate.fetch_server_certificate (   host,
  port 
)

Definition at line 15 of file get-remote-certificate.py.

00015 
00016 def fetch_server_certificate (host, port):
00017 
00018     def subproc(cmd):
00019         from subprocess import Popen, PIPE, STDOUT
00020         proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
00021         status = proc.wait()
00022         output = proc.stdout.read()
00023         return status, output
00024 
00025     def strip_to_x509_cert(certfile_contents, outfile=None):
00026         m = re.search(br"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
00027                       br".*[\r]*^[-]+END CERTIFICATE[-]+)$",
00028                       certfile_contents, re.MULTILINE | re.DOTALL)
00029         if not m:
00030             return None
00031         else:
00032             tn = tempfile.mktemp()
00033             fp = open(tn, "wb")
00034             fp.write(m.group(1) + b"\n")
00035             fp.close()
00036             try:
00037                 tn2 = (outfile or tempfile.mktemp())
00038                 status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
00039                                          (tn, tn2))
00040                 if status != 0:
00041                     raise RuntimeError('OpenSSL x509 failed with status %s and '
00042                                        'output: %r' % (status, output))
00043                 fp = open(tn2, 'rb')
00044                 data = fp.read()
00045                 fp.close()
00046                 os.unlink(tn2)
00047                 return data
00048             finally:
00049                 os.unlink(tn)
00050 
00051     if sys.platform.startswith("win"):
00052         tfile = tempfile.mktemp()
00053         fp = open(tfile, "w")
00054         fp.write("quit\n")
00055         fp.close()
00056         try:
00057             status, output = subproc(
00058                 'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
00059                 (host, port, tfile))
00060         finally:
00061             os.unlink(tfile)
00062     else:
00063         status, output = subproc(
00064             'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
00065             (host, port))
00066     if status != 0:
00067         raise RuntimeError('OpenSSL connect failed with status %s and '
00068                            'output: %r' % (status, output))
00069     certtext = strip_to_x509_cert(output)
00070     if not certtext:
00071         raise ValueError("Invalid response received from server at %s:%s" %
00072                          (host, port))
00073     return certtext
00074 

Here is the call graph for this function: