Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Begin making examples Python 3 compatible #245

Merged
merged 14 commits into from
May 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ __pycache__
doc/_build/
.coverage
.eggs
examples/simple/*.cert
examples/simple/*.pkey
10 changes: 6 additions & 4 deletions examples/certgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def createCertRequest(pkey, digest="sha256", **name):
Create a certificate request.

Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is md5
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
arguments are:
C - Country name
Expand All @@ -45,14 +45,14 @@ def createCertRequest(pkey, digest="sha256", **name):
req = crypto.X509Req()
subj = req.get_subject()

for (key,value) in name.items():
for key, value in name.items():
setattr(subj, key, value)

req.set_pubkey(pkey)
req.sign(pkey, digest)
return req

def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter), digest="md5"):
def createCertificate(req, issuerCertKey, serial, validityPeriod, digest="sha256"):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to PEP 3113 tuple unpacking is deprecated.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it’s actually even removed in Python 3 (which kind of sucks when doing Twisted)

"""
Generate a certificate given a certificate request.

Expand All @@ -64,9 +64,11 @@ def createCertificate(req, (issuerCert, issuerKey), serial, (notBefore, notAfter
starts being valid
notAfter - Timestamp (relative to now) when the certificate
stops being valid
digest - Digest method to use for signing, default is md5
digest - Digest method to use for signing, default is sha256
Returns: The signed certificate in an X509 object
"""
issuerCert, issuerKey = issuerCertKey
notBefore, notAfter = validityPeriod
cert = crypto.X509()
cert.set_serial_number(serial)
cert.gmtime_adj_notBefore(notBefore)
Expand Down
15 changes: 11 additions & 4 deletions examples/mk_simple_certs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,22 @@
cakey = createKeyPair(TYPE_RSA, 2048)
careq = createCertRequest(cakey, CN='Certificate Authority')
cacert = createCertificate(careq, (careq, cakey), 0, (0, 60*60*24*365*5)) # five years

print('Creating Certificate Authority private key in "simple/CA.pkey"')
open('simple/CA.pkey', 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey))
with open('simple/CA.pkey', 'w') as capkey:
capkey.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey).decode('utf-8'))
print('Creating Certificate Authority certificate in "simple/CA.cert"')
open('simple/CA.cert', 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cacert))
with open('simple/CA.cert', 'w') as ca:
ca.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cacert).decode('utf-8'))

for (fname, cname) in [('client', 'Simple Client'), ('server', 'Simple Server')]:
pkey = createKeyPair(TYPE_RSA, 2048)
req = createCertRequest(pkey, CN=cname)
cert = createCertificate(req, (cacert, cakey), 1, (0, 60*60*24*365*5)) # five years
print('Creating Certificate %s private key in "simple/%s.pkey"' % (fname, fname))
open('simple/%s.pkey' % (fname,), 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
with open('simple/%s.pkey' % (fname,), 'w') as leafpkey:
leafpkey.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
print('Creating Certificate %s certificate in "simple/%s.cert"' % (fname, fname))
open('simple/%s.cert' % (fname,), 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
with open('simple/%s.cert' % (fname,), 'w') as leafcert:
leafcert.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))

13 changes: 7 additions & 6 deletions examples/simple/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
Simple SSL client, using blocking I/O
"""

from OpenSSL import SSL
from OpenSSL import SSL, crypto
import sys, os, select, socket

def verify_cb(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
certsubject = crypto.X509Name(cert.get_subject())
commonname = certsubject.commonName
print('Got certificate: ' + commonname)
return ok

if len(sys.argv) < 3:
print 'Usage: python[2] client.py HOST PORT'
print('Usage: python client.py HOST PORT')
sys.exit(1)

dir = os.path.dirname(sys.argv[0])
Expand All @@ -41,10 +42,10 @@ def verify_cb(conn, cert, errnum, depth, ok):
break
try:
sock.send(line)
sys.stdout.write(sock.recv(1024))
sys.stdout.write(sock.recv(1024).decode('utf-8'))
sys.stdout.flush()
except SSL.Error:
print 'Connection died unexpectedly'
print('Connection died unexpectedly')
break


Expand Down
29 changes: 15 additions & 14 deletions examples/simple/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@
Simple echo server, using nonblocking I/O
"""

from OpenSSL import SSL
from OpenSSL import SSL, crypto
import sys, os, select, socket


def verify_cb(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
certsubject = crypto.X509Name(cert.get_subject())
commonname = certsubject.commonName
print(('Got certificate: ' + commonname))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these changes needed, particularly the crypto.X509Name(...) bit?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I should have made a comment to clarify :).

This is what you get on master:
Got certificate: <X509Name object '/CN=Certificate Authority'>
Got certificate: <X509Name object '/CN=Simple Server'>

This is what you get with that:
Got certificate: Certificate Authority
Got certificate: Simple Server

I think that is the direction the orig author was going in when he said: "# This obviously has to be updated". I can remove the comment if you agree. I suppose there are less spoofable things that we could use to identify the certs in addition to the CN, like the fingerprint.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah please get rid of the comment. there’s nothing obvious about it.

return ok

if len(sys.argv) < 2:
print 'Usage: python[2] server.py PORT'
print('Usage: python server.py PORT')
sys.exit(1)

dir = os.path.dirname(sys.argv[0])
Expand All @@ -44,40 +45,40 @@ def verify_cb(conn, cert, errnum, depth, ok):

def dropClient(cli, errors=None):
if errors:
print 'Client %s left unexpectedly:' % (clients[cli],)
print ' ', errors
print('Client %s left unexpectedly:' % (clients[cli],))
print(' ', errors)
else:
print 'Client %s left politely' % (clients[cli],)
print('Client %s left politely' % (clients[cli],))
del clients[cli]
if writers.has_key(cli):
if cli in writers:
del writers[cli]
if not errors:
cli.shutdown()
cli.close()

while 1:
try:
r,w,_ = select.select([server]+clients.keys(), writers.keys(), [])
r, w, _ = select.select([server] + list(clients.keys()), list(writers.keys()), [])
except:
break

for cli in r:
if cli == server:
cli,addr = server.accept()
print 'Connection from %s' % (addr,)
print('Connection from %s' % (addr,))
clients[cli] = addr

else:
try:
ret = cli.recv(1024)
ret = cli.recv(1024).decode('utf-8')
except (SSL.WantReadError, SSL.WantWriteError, SSL.WantX509LookupError):
pass
except SSL.ZeroReturnError:
dropClient(cli)
except SSL.Error, errors:
except SSL.Error as errors:
dropClient(cli, errors)
else:
if not writers.has_key(cli):
if cli not in writers:
writers[cli] = ''
writers[cli] = writers[cli] + ret

Expand All @@ -88,7 +89,7 @@ def dropClient(cli, errors=None):
pass
except SSL.ZeroReturnError:
dropClient(cli)
except SSL.Error, errors:
except SSL.Error as errors:
dropClient(cli, errors)
else:
writers[cli] = writers[cli][ret:]
Expand Down