Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File object in memory using Python

I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date.

To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later but I am sure there must be a way to do this without writing to disk.

Here's the portion that's downloading the certificates

CA_FILE = '/tmp/ca_certs.txt'

root_cert = urllib.urlopen('https://www.cacert.org/certs/root.txt')
class3_cert = urllib.urlopen('https://www.cacert.org/certs/class3.txt')

temp_file = open(CA_FILE, 'w')    
temp_file.write(root_cert.read())
temp_file.write(class3_cert.read())
temp_file.close()

EDIT

Here's the portion that uses the file to get the certificate

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 ssl_sock = ssl.wrap_socket(s, ca_certs=CA_FILE, cert_reqs=ssl.CERT_REQUIRED)
 ssl_sock.connect(('mail.google.com', 443))

 date = ssl_sock.getpeercert()['notAfter']
like image 256
Jim Avatar asked Jun 26 '26 00:06

Jim


2 Answers

the response from urllib is a file object. just use those wherever you are using the actual files instead. This is assuming that the code that consumes the file objects doesn't need to write to them of course.

like image 129
aaronasterling Avatar answered Jun 27 '26 14:06

aaronasterling


Wow, don't do this. You're hitting cacert's site every time? That's INCREDIBLY rude and needlessly eats their resources. It's also ridiculously bad security practice. You're supposed to get the root certificate once and validate that it's the correct root cert and not some forgery, otherwise you can't rely on the validity of certificates signed by it.

Cache their root cert, or better yet, install it with the rest of the root certificates on your system like you're supposed to.

like image 24
Nicholas Knight Avatar answered Jun 27 '26 14:06

Nicholas Knight