Commit 7f9e56cf authored by Vincent Pelletier's avatar Vincent Pelletier Committed by Vincent Pelletier

all: Reduce differences with python3.

Using only 2to3 conversions which are python2-compatible.
parent 719959e0
...@@ -625,7 +625,7 @@ class CertificateAuthority(object): ...@@ -625,7 +625,7 @@ class CertificateAuthority(object):
self._renewCAIfNeeded() self._renewCAIfNeeded()
result = [] result = []
iter_key_pair = iter(self._ca_key_pairs_list) iter_key_pair = iter(self._ca_key_pairs_list)
first_key_pair = iter_key_pair.next() first_key_pair = next(iter_key_pair)
previous_crt_pem = utils.dump_certificate(first_key_pair['crt']) previous_crt_pem = utils.dump_certificate(first_key_pair['crt'])
previous_key = first_key_pair['key'] previous_key = first_key_pair['key']
for key_pair in iter_key_pair: for key_pair in iter_key_pair:
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
""" """
Caucase - Certificate Authority for Users, Certificate Authority for SErvices Caucase - Certificate Authority for Users, Certificate Authority for SErvices
""" """
from __future__ import absolute_import from __future__ import absolute_import, print_function
import argparse import argparse
import datetime import datetime
import httplib import httplib
...@@ -63,7 +63,7 @@ class RetryingCaucaseClient(CaucaseClient): ...@@ -63,7 +63,7 @@ class RetryingCaucaseClient(CaucaseClient):
httplib.IncompleteRead, httplib.IncompleteRead,
): ):
connection.close() # Resets HTTPConnection state machine. connection.close() # Resets HTTPConnection state machine.
print 'Got a network error, retrying in a bit...' print('Got a network error, retrying in a bit...')
traceback.print_exc() traceback.print_exc()
self._until(datetime.datetime.now() + datetime.timedelta(0, 10)) self._until(datetime.datetime.now() + datetime.timedelta(0, 10))
...@@ -94,7 +94,7 @@ class CLICaucaseClient(object): ...@@ -94,7 +94,7 @@ class CLICaucaseClient(object):
csr_pem = utils.getCertRequest(csr_path) csr_pem = utils.getCertRequest(csr_path)
# Quick sanity check # Quick sanity check
utils.load_certificate_request(csr_pem) utils.load_certificate_request(csr_pem)
print self._client.createCertificateSigningRequest(csr_pem), csr_path print(self._client.createCertificateSigningRequest(csr_pem), csr_path)
def getCSR(self, csr_id_path_list): def getCSR(self, csr_id_path_list):
""" """
...@@ -113,45 +113,47 @@ class CLICaucaseClient(object): ...@@ -113,45 +113,47 @@ class CLICaucaseClient(object):
crt_id = int(crt_id) crt_id = int(crt_id)
try: try:
crt_pem = self._client.getCertificate(crt_id) crt_pem = self._client.getCertificate(crt_id)
except CaucaseError, e: except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND: if e.args[0] != httplib.NOT_FOUND:
raise raise
try: try:
self._client.getCertificateSigningRequest(crt_id) self._client.getCertificateSigningRequest(crt_id)
except CaucaseError, e: except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND: if e.args[0] != httplib.NOT_FOUND:
raise raise
print crt_id, 'not found - maybe CSR was rejected ?' print(crt_id, 'not found - maybe CSR was rejected ?')
error = True error = True
else: else:
print crt_id, 'CSR still pending' print(crt_id, 'CSR still pending')
warning = True warning = True
else: else:
print crt_id, print(crt_id, end=' ')
if utils.isCertificateAutoSigned(utils.load_certificate( if utils.isCertificateAutoSigned(utils.load_certificate(
crt_pem, crt_pem,
ca_list, ca_list,
None, None,
)): )):
print 'was (originally) automatically approved' print('was (originally) automatically approved')
else: else:
print 'was (originally) manually approved' print('was (originally) manually approved')
if os.path.exists(crt_path): if os.path.exists(crt_path):
try: try:
key_pem = utils.getKey(crt_path) key_pem = utils.getKey(crt_path)
except ValueError: except ValueError:
print >>sys.stderr, ( print(
'Expected to find exactly one privatekey key in %s, skipping' % ( 'Expected to find exactly one privatekey key in %s, skipping' % (
crt_path, crt_path,
) ),
file=sys.stderr,
) )
error = True error = True
continue continue
try: try:
utils.validateCertAndKey(crt_pem, key_pem) utils.validateCertAndKey(crt_pem, key_pem)
except ValueError: except ValueError:
print >>sys.stderr, ( print(
'Key in %s does not match retrieved certificate, skipping' 'Key in %s does not match retrieved certificate, skipping',
file=sys.stderr,
) )
error = True error = True
continue continue
...@@ -167,10 +169,11 @@ class CLICaucaseClient(object): ...@@ -167,10 +169,11 @@ class CLICaucaseClient(object):
try: try:
crt, key, _ = utils.getKeyPair(crt_path, key_path) crt, key, _ = utils.getKeyPair(crt_path, key_path)
except ValueError: except ValueError:
print >>sys.stderr, ( print(
'Could not find (exactly) one matching key pair in %s, skipping' % ( 'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x] [x for x in set((crt_path, key_path)) if x],
) ),
file=sys.stderr,
) )
error = True error = True
continue continue
...@@ -196,10 +199,11 @@ class CLICaucaseClient(object): ...@@ -196,10 +199,11 @@ class CLICaucaseClient(object):
key_path, key_path,
) )
except ValueError: except ValueError:
print >>sys.stderr, ( print(
'Could not find (exactly) one matching key pair in %s, skipping' % ( 'Could not find (exactly) one matching key pair in %s, skipping' % (
[x for x in set((crt_path, key_path)) if x] [x for x in set((crt_path, key_path)) if x],
) ),
file=sys.stderr,
) )
error = True error = True
continue continue
...@@ -210,12 +214,13 @@ class CLICaucaseClient(object): ...@@ -210,12 +214,13 @@ class CLICaucaseClient(object):
None, None,
) )
except exceptions.CertificateVerificationError: except exceptions.CertificateVerificationError:
print crt_path, ( print(
'was not signed by this CA, revoked or otherwise invalid, skipping' crt_path,
'was not signed by this CA, revoked or otherwise invalid, skipping',
) )
continue continue
if renewal_deadline < old_crt.not_valid_after: if renewal_deadline < old_crt.not_valid_after:
print crt_path, 'did not reach renew threshold, not renewing' print(crt_path, 'did not reach renew threshold, not renewing')
continue continue
new_key_pem, new_crt_pem = self._client.renewCertificate( new_key_pem, new_crt_pem = self._client.renewCertificate(
old_crt=old_crt, old_crt=old_crt,
...@@ -237,18 +242,22 @@ class CLICaucaseClient(object): ...@@ -237,18 +242,22 @@ class CLICaucaseClient(object):
""" """
--list-csr --list-csr
""" """
print '-- pending', mode, 'CSRs --' print('-- pending', mode, 'CSRs --')
print '%20s | %s' % ( print(
'%20s | %s' % (
'csr_id', 'csr_id',
'subject preview (fetch csr and check full content !)', 'subject preview (fetch csr and check full content !)',
),
) )
for entry in self._client.getPendingCertificateRequestList(): for entry in self._client.getPendingCertificateRequestList():
csr = utils.load_certificate_request(entry['csr']) csr = utils.load_certificate_request(entry['csr'])
print '%20s | %r' % ( print(
'%20s | %r' % (
entry['id'], entry['id'],
csr.subject, csr.subject,
),
) )
print '-- end of pending', mode, 'CSRs --' print('-- end of pending', mode, 'CSRs --')
def signCSR(self, csr_id_list): def signCSR(self, csr_id_list):
""" """
...@@ -291,10 +300,11 @@ class CLICaucaseClient(object): ...@@ -291,10 +300,11 @@ class CLICaucaseClient(object):
# authenticated revocations). # authenticated revocations).
crt_pem = utils.getCert(crt_path) crt_pem = utils.getCert(crt_path)
except ValueError: except ValueError:
print >>sys.stderr, ( print(
'Could not load a single certificate in %s, skipping' % ( 'Could not load a single certificate in %s, skipping' % (
crt_path, crt_path,
) ),
file=sys.stderr,
) )
self._client.revokeCertificate(crt_pem) self._client.revokeCertificate(crt_pem)
return error return error
...@@ -506,9 +516,10 @@ def main(argv=None): ...@@ -506,9 +516,10 @@ def main(argv=None):
sign_with_csr_id_set.intersection(args.reject_csr) or sign_with_csr_id_set.intersection(args.reject_csr) or
sign_csr_id_set.intersection(sign_with_csr_id_set) sign_csr_id_set.intersection(sign_with_csr_id_set)
): ):
print >>sys.stderr, ( print(
'A given CSR_ID cannot be in more than one of --sign-csr, ' 'A given CSR_ID cannot be in more than one of --sign-csr, '
'--sign-csr-with and --reject-csr' '--sign-csr-with and --reject-csr',
file=sys.stderr,
) )
raise SystemExit(STATUS_ERROR) raise SystemExit(STATUS_ERROR)
...@@ -733,16 +744,16 @@ def updater(argv=None, until=utils.until): ...@@ -733,16 +744,16 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca) ca_crt_pem_list=utils.getCertList(args.cas_ca)
) )
if args.crt and not utils.hasOneCert(args.crt): if args.crt and not utils.hasOneCert(args.crt):
print 'Bootstraping...' print('Bootstraping...')
csr_pem = utils.getCertRequest(args.csr) csr_pem = utils.getCertRequest(args.csr)
# Quick sanity check before bothering server # Quick sanity check before bothering server
utils.load_certificate_request(csr_pem) utils.load_certificate_request(csr_pem)
csr_id = client.createCertificateSigningRequest(csr_pem) csr_id = client.createCertificateSigningRequest(csr_pem)
print 'Waiting for signature of', csr_id print('Waiting for signature of', csr_id)
while True: while True:
try: try:
crt_pem = client.getCertificate(csr_id) crt_pem = client.getCertificate(csr_id)
except CaucaseError, e: except CaucaseError as e:
if e.args[0] != httplib.NOT_FOUND: if e.args[0] != httplib.NOT_FOUND:
raise raise
# If server does not know our CSR anymore, getCSR will raise. # If server does not know our CSR anymore, getCSR will raise.
...@@ -756,11 +767,12 @@ def updater(argv=None, until=utils.until): ...@@ -756,11 +767,12 @@ def updater(argv=None, until=utils.until):
crt_file.write(crt_pem) crt_file.write(crt_pem)
updated = True updated = True
break break
print 'Bootstrap done' print('Bootstrap done')
next_deadline = datetime.datetime.utcnow() next_deadline = datetime.datetime.utcnow()
while True: while True:
print 'Next wake-up at', next_deadline.strftime( print(
'%Y-%m-%d %H:%M:%S +0000' 'Next wake-up at',
next_deadline.strftime('%Y-%m-%d %H:%M:%S +0000'),
) )
now = until(next_deadline) now = until(next_deadline)
next_deadline = now + max_sleep next_deadline = now + max_sleep
...@@ -773,7 +785,7 @@ def updater(argv=None, until=utils.until): ...@@ -773,7 +785,7 @@ def updater(argv=None, until=utils.until):
ca_crt_pem_list=utils.getCertList(args.cas_ca) ca_crt_pem_list=utils.getCertList(args.cas_ca)
) )
if RetryingCaucaseClient.updateCAFile(ca_url, args.ca): if RetryingCaucaseClient.updateCAFile(ca_url, args.ca):
print 'Got new CA' print('Got new CA')
updated = True updated = True
# Note: CRL expiration should happen several time during CA renewal # Note: CRL expiration should happen several time during CA renewal
# period, so it should not be needed to keep track of CA expiration # period, so it should not be needed to keep track of CA expiration
...@@ -783,7 +795,7 @@ def updater(argv=None, until=utils.until): ...@@ -783,7 +795,7 @@ def updater(argv=None, until=utils.until):
for x in utils.getCertList(args.ca) for x in utils.getCertList(args.ca)
] ]
if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list): if RetryingCaucaseClient.updateCRLFile(ca_url, args.crl, ca_crt_list):
print 'Got new CRL' print('Got new CRL')
updated = True updated = True
next_deadline = min( next_deadline = min(
next_deadline, next_deadline,
...@@ -793,7 +805,7 @@ def updater(argv=None, until=utils.until): ...@@ -793,7 +805,7 @@ def updater(argv=None, until=utils.until):
crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key) crt_pem, key_pem, key_path = utils.getKeyPair(args.crt, args.key)
crt = utils.load_certificate(crt_pem, ca_crt_list, None) crt = utils.load_certificate(crt_pem, ca_crt_list, None)
if crt.not_valid_after - threshold <= now: if crt.not_valid_after - threshold <= now:
print 'Renewing', args.crt print('Renewing', args.crt)
new_key_pem, new_crt_pem = client.renewCertificate( new_key_pem, new_crt_pem = client.renewCertificate(
old_crt=crt, old_crt=crt,
old_key=utils.load_privatekey(key_pem), old_key=utils.load_privatekey(key_pem),
...@@ -823,7 +835,7 @@ def updater(argv=None, until=utils.until): ...@@ -823,7 +835,7 @@ def updater(argv=None, until=utils.until):
if args.on_renew is not None: if args.on_renew is not None:
status = os.system(args.on_renew) status = os.system(args.on_renew)
if status: if status:
print >>sys.stderr, 'Renewal hook exited with status:', status print('Renewal hook exited with status:', status, file=sys.stderr)
raise SystemExit(STATUS_ERROR) raise SystemExit(STATUS_ERROR)
updated = False updated = False
except (utils.SleepInterrupt, SystemExit): except (utils.SleepInterrupt, SystemExit):
...@@ -880,7 +892,7 @@ def rerequest(argv=None): ...@@ -880,7 +892,7 @@ def rerequest(argv=None):
), ),
) )
key_pem = utils.dump_privatekey(key) key_pem = utils.dump_privatekey(key)
orig_umask = os.umask(0177) orig_umask = os.umask(0o177)
try: try:
with open(args.key, 'w') as key_file: with open(args.key, 'w') as key_file:
key_file.write(key_pem) key_file.write(key_pem)
...@@ -914,11 +926,14 @@ def key_id(argv=None): ...@@ -914,11 +926,14 @@ def key_id(argv=None):
) )
args = parser.parse_args(argv) args = parser.parse_args(argv)
for key_path in args.private_key: for key_path in args.private_key:
print key_path, x509.SubjectKeyIdentifier.from_public_key( print(
key_path,
x509.SubjectKeyIdentifier.from_public_key(
utils.load_privatekey(open(key_path).read()).public_key(), utils.load_privatekey(open(key_path).read()).public_key(),
).digest.encode('hex') ).digest.encode('hex'),
)
for backup_path in args.backup: for backup_path in args.backup:
print backup_path print(backup_path)
with open(backup_path) as backup_file: with open(backup_path) as backup_file:
magic = backup_file.read(8) magic = backup_file.read(8)
if magic != 'caucase\0': if magic != 'caucase\0':
...@@ -928,4 +943,4 @@ def key_id(argv=None): ...@@ -928,4 +943,4 @@ def key_id(argv=None):
backup_file.read(struct.calcsize('<I')), backup_file.read(struct.calcsize('<I')),
) )
for key_entry in json.loads(backup_file.read(header_len))['key_list']: for key_entry in json.loads(backup_file.read(header_len))['key_list']:
print ' ', key_entry['id'] print(' ', key_entry['id'])
...@@ -107,7 +107,7 @@ def canConnect(address): # pragma: no cover ...@@ -107,7 +107,7 @@ def canConnect(address): # pragma: no cover
""" """
try: try:
socket.create_connection(address) socket.create_connection(address)
except socket.error, e: except socket.error as e:
if e.errno == errno.ECONNREFUSED: if e.errno == errno.ECONNREFUSED:
return False return False
raise raise
...@@ -334,7 +334,7 @@ class CaucaseTest(unittest.TestCase): ...@@ -334,7 +334,7 @@ class CaucaseTest(unittest.TestCase):
new_key_path, new_key_path,
), ),
) )
except SystemExit, e: except SystemExit as e:
return e.code # pragma: no cover return e.code # pragma: no cover
except: # pylint: disable=bare-except except: # pylint: disable=bare-except
return 1 return 1
...@@ -896,7 +896,7 @@ class CaucaseTest(unittest.TestCase): ...@@ -896,7 +896,7 @@ class CaucaseTest(unittest.TestCase):
client = CaucaseClient(self._caucase_url + '/cas') client = CaucaseClient(self._caucase_url + '/cas')
try: try:
client.createCertificateSigningRequest('Not actually a CSR') client.createCertificateSigningRequest('Not actually a CSR')
except CaucaseError, e: except CaucaseError as e:
self.assertEqual(e.args[0], 400, e) self.assertEqual(e.args[0], 400, e)
else: # pragma: no cover else: # pragma: no cover
raise AssertionError('Did not raise CaucaseError(400, ...)') raise AssertionError('Did not raise CaucaseError(400, ...)')
......
...@@ -264,7 +264,7 @@ def _verifyCertificateChain(cert, trusted_cert_list, crl): ...@@ -264,7 +264,7 @@ def _verifyCertificateChain(cert, trusted_cert_list, crl):
except ( except (
crypto.X509StoreContextError, crypto.X509StoreContextError,
crypto.Error, crypto.Error,
), e: ) as e:
raise CertificateVerificationError( raise CertificateVerificationError(
'Certificate verification error: %s' % str(e), 'Certificate verification error: %s' % str(e),
) )
......
...@@ -572,13 +572,13 @@ class Application(object): ...@@ -572,13 +572,13 @@ class Application(object):
raise InsufficientStorage raise InsufficientStorage
except exceptions.NotJSON: except exceptions.NotJSON:
raise BadRequest('Invalid json payload') raise BadRequest('Invalid json payload')
except exceptions.CertificateAuthorityException, e: except exceptions.CertificateAuthorityException as e:
raise BadRequest(str(e)) raise BadRequest(str(e))
except Exception: except Exception:
environ['wsgi.errors'].write('Unhandled exception\n') environ['wsgi.errors'].write('Unhandled exception\n')
traceback.print_exc(file=environ['wsgi.errors']) traceback.print_exc(file=environ['wsgi.errors'])
raise ApplicationError raise ApplicationError
except ApplicationError, e: except ApplicationError as e:
status = e.status status = e.status
header_list = e.response_headers header_list = e.response_headers
result = [str(x) for x in e.args] result = [str(x) for x in e.args]
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment