Drew Drew - 7 months ago 67
Python Question

Python STDOUT to file with openssl subprocess

I am trying to write a python script to automate the process of checking for SSL renegotiation through openSSL and output the results to a file. I have run into 2 problems.

My first problem is that the output from the initial handshake gets written to the file, however the actual renegotiation part does not. It is instead displayed on the console.

subprocess.call("echo \"R\" | openssl s_client -connect example.com:443",
shell=True, stdout=FILE)


My other problem (although this may be the wrong spot for it) is that I cannot get the openSSL command to work for sending the GET command.

subprocess.call("echo -e \"GET / HTTP/1.1\r\n\r\n\" | openssl s_client -connect
example.com:443", shell=True)


Again, the initial connection is set up but then openSSL exists, it does not process the GET request.

Any help would be greatly appreciated. Thanks.

Answer

There's no reason to use shell=True for inputs. Instead, use stdin=subprocess.PIPE. Also, note that your request is not valid since HTTP 1.1 requires the Host header. Additionally, I can't think of a reason to use the command line openssl instead of the ssl module.

That being said, here's a working example:

import subprocess

f = open('http_answer', 'w')
_,log = subprocess.Popen(
    ['openssl', 's_client', '-quiet', '-connect', 'twitter.com:443'],
    stdout=f, stderr=subprocess.PIPE, stdin=subprocess.PIPE
).communicate('GET / HTTP/1.0\r\n\r\n')
print('Output of SSL:\n' + log)