5

I need to download servers certificates as DER file. I am using python. I could connect to the server using this script but I need to download the certificate locally in my hard disk so I can parse it in the next stage.

import socket, ssl
import OpenSSL

hostname='www.google.com'
port=443

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname=hostname)
ssl_sock.connect((hostname, port))
ssl_sock.close()
print("ssl connection Done")

cert = ssl.get_server_certificate((hostname, port))

# OpenSSL
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
user2192774
  • 3,807
  • 17
  • 47
  • 62

2 Answers2

6

There is no need to explicitly connect to the server since get_server_certificate will already do this for you. The only thing you need thing you need is to convert the PEM returned by get_server_certificate into the DER you want to have:

import ssl
hostname='www.google.com'
port=443

f = open('cert.der','wb')
cert = ssl.get_server_certificate((hostname, port))
f.write(ssl.PEM_cert_to_DER_cert(cert))
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
1

You can save the DER file with a couple of intermediate transformations:

cert = ssl.get_server_certificate((hostname, port))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
der = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)
with open('/tmp/google.der', 'wb') as f: f.write(der)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Can you clarify a bit about `open('/tmp/google.der', 'wb') as f: f.write(der)`? I get error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/google.der'', although, I created tmp folder inside the project folder. I also tried `open('../tmp/google.der', 'wb')` but this did not solve the problem. – user2192774 Dec 15 '16 at 20:00
  • @user2192774 You get that error, probably, because your system doesn't have a `/tmp` directory. In that case, just do `open('google.der', 'wb)` instead. – Robᵩ Dec 15 '16 at 20:20