summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAde Lee <alee@redhat.com>2014-05-27 14:12:38 -0400
committerAde Lee <alee@redhat.com>2014-05-29 11:29:44 -0400
commit6262dc33b72ea5703959b91dd95f13d732a5d391 (patch)
tree738b751867665b68288629745dcd33c9971b73d6
parenta353e5f81341830ea8a151e88ffc2be35aa40451 (diff)
downloadpki-6262dc33b72ea5703959b91dd95f13d732a5d391.tar.gz
pki-6262dc33b72ea5703959b91dd95f13d732a5d391.tar.xz
pki-6262dc33b72ea5703959b91dd95f13d732a5d391.zip
formatting fixes in python client code for pycharm
-rw-r--r--base/common/python/pki/__init__.py147
-rw-r--r--base/common/python/pki/account.py1
-rw-r--r--base/common/python/pki/client.py23
-rw-r--r--base/common/python/pki/cryptoutil.py109
-rw-r--r--base/common/python/pki/encoder.py17
-rw-r--r--base/common/python/pki/key.py232
-rw-r--r--base/common/python/pki/kraclient.py36
-rw-r--r--base/common/python/pki/system.py4
-rw-r--r--base/common/python/pki/systemcert.py20
-rw-r--r--base/common/python/pki/upgrade.py133
-rw-r--r--base/common/python/pki/util.py8
11 files changed, 427 insertions, 303 deletions
diff --git a/base/common/python/pki/__init__.py b/base/common/python/pki/__init__.py
index 7cab85e85..713f10e0e 100644
--- a/base/common/python/pki/__init__.py
+++ b/base/common/python/pki/__init__.py
@@ -18,9 +18,9 @@
# Copyright (C) 2013 Red Hat, Inc.
# All rights reserved.
#
-'''
+"""
This module contains top-level classes and functions used by the Dogtag project.
-'''
+"""
import os
import re
import requests
@@ -35,15 +35,17 @@ PACKAGE_VERSION = SHARE_DIR + '/VERSION'
CERT_HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"
CERT_FOOTER = "-----END NEW CERTIFICATE REQUEST-----"
+
def read_text(message,
- options=None, default=None, delimiter=':',
- allow_empty=True, case_sensitive=True):
- ''' get an input from the user. '''
+ options=None, default=None, delimiter=':',
+ allow_empty=True, case_sensitive=True):
+ """ get an input from the user. """
if default:
message = message + ' [' + default + ']'
message = message + delimiter + ' '
done = False
+ value = None
while not done:
value = raw_input(message)
value = value.strip()
@@ -51,7 +53,6 @@ def read_text(message,
if len(value) == 0: # empty value
if allow_empty:
value = default
- done = True
break
else: # non-empty value
@@ -66,14 +67,13 @@ def read_text(message,
done = True
break
else:
- done = True
break
return value
def implementation_version():
- ''' Return implementation version '''
+ """ Return implementation version """
with open(PACKAGE_VERSION, 'r') as input_file:
for line in input_file:
line = line.strip('\n')
@@ -94,63 +94,67 @@ def implementation_version():
raise Exception('Missing implementation version.')
+
#pylint: disable-msg=R0903
class Attribute(object):
- '''
+ """
Class representing a key/value pair.
This object is the basis of the representation of a ResourceMessage.
- '''
+ """
def __init__(self, name, value):
- ''' Constructor '''
+ """ Constructor """
self.name = name
self.value = value
+
#pylint: disable-msg=R0903
class AttributeList(object):
- '''
+ """
Class representing a list of attributes.
This class is needed because of a JavaMapper used in the REST API.
- '''
+ """
# pylint: disable-msg=C0103
def __init__(self):
- ''' Constructor '''
+ """ Constructor """
self.Attribute = []
+
class ResourceMessage(object):
- '''
+ """
This class is the basis for the various types of key requests.
It is essentially a list of attributes.
- '''
+ """
# pylint: disable-msg=C0103
def __init__(self, class_name):
- ''' Constructor '''
+ """ Constructor """
self.Attributes = AttributeList()
self.ClassName = class_name
def add_attribute(self, name, value):
- ''' Add an attribute to the list. '''
+ """ Add an attribute to the list. """
attr = Attribute(name, value)
self.Attributes.Attribute.append(attr)
def get_attribute_value(self, name):
- ''' Get the value of a given attribute '''
+ """ Get the value of a given attribute """
for attr in self.Attributes.Attribute:
if attr.name == name:
return attr.value
return None
+
class PKIException(Exception, ResourceMessage):
- '''
+ """
Base exception class for REST Interface
- '''
+ """
def __init__(self, message, exception=None, code=None, class_name=None):
- ''' Constructor '''
+ """ Constructor """
Exception.__init__(self, message)
ResourceMessage.__init__(self, class_name)
self.code = code
@@ -159,98 +163,119 @@ class PKIException(Exception, ResourceMessage):
@classmethod
def from_json(cls, json_value):
- ''' Construct exception from JSON '''
- ret = cls(json_value['Message'], json_value['Code'], json_value['ClassName'])
+ """ Construct exception from JSON """
+ ret = cls(json_value['Message'], json_value['Code'],
+ json_value['ClassName'])
for attr in json_value['Attributes']['Attribute']:
print str(attr)
ret.add_attribute(attr["name"], attr["value"])
return ret
+
class BadRequestException(PKIException):
- ''' Bad Request Exception: return code = 400 '''
+ """ Bad Request Exception: return code = 400 """
+
class ConflictingOperationException(PKIException):
- ''' Conflicting Operation Exception: return code = 409 '''
+ """ Conflicting Operation Exception: return code = 409 """
+
class ForbiddenException(PKIException):
- ''' Forbidden Exception: return code = 403 '''
+ """ Forbidden Exception: return code = 403 """
+
class HTTPGoneException(PKIException):
- ''' Gone Exception: return code = 410 '''
+ """ Gone Exception: return code = 410 """
+
class ResourceNotFoundException(PKIException):
- ''' Not Found Exception: return code = 404 '''
+ """ Not Found Exception: return code = 404 """
+
class UnauthorizedException(PKIException):
- ''' Unauthorized Exception: return code = 401 '''
+ """ Unauthorized Exception: return code = 401 """
+
class CertNotFoundException(ResourceNotFoundException):
- ''' Cert Not Found Exception: return code = 404 '''
+ """ Cert Not Found Exception: return code = 404 """
+
class GroupNotFoundException(ResourceNotFoundException):
- ''' Group Not Found Exception: return code = 404 '''
+ """ Group Not Found Exception: return code = 404 """
+
class KeyNotFoundException(ResourceNotFoundException):
- ''' Key Not Found Exception: return code 404 '''
+ """ Key Not Found Exception: return code 404 """
+
class ProfileNotFoundException(ResourceNotFoundException):
- ''' Profile Not Found Exception: return code = 404 '''
+ """ Profile Not Found Exception: return code = 404 """
+
class RequestNotFoundException(ResourceNotFoundException):
- ''' Request Not Found Exception: return code = 404 '''
+ """ Request Not Found Exception: return code = 404 """
+
class UserNotFoundException(ResourceNotFoundException):
- ''' User Not Found Exception: return code = 404 '''
+ """ User Not Found Exception: return code = 404 """
+
EXCEPTION_MAPPINGS = {
"com.netscape.certsrv.base.BadRequestException": BadRequestException,
- "com.netscape.certsrv.base.ConflictingOperationException": ConflictingOperationException,
+ "com.netscape.certsrv.base.ConflictingOperationException":
+ ConflictingOperationException,
"com.netscape.certsrv.base.ForbiddenException": ForbiddenException,
"com.netscape.certsrv.base.HTTPGoneException": HTTPGoneException,
- "com.netscape.certsrv.base.ResourceNotFoundException": ResourceNotFoundException,
+ "com.netscape.certsrv.base.ResourceNotFoundException":
+ ResourceNotFoundException,
"com.netscape.certsrv.cert.CertNotFoundException": CertNotFoundException,
"com.netscape.certsrv.group.GroupNotFoundException": GroupNotFoundException,
"com.netscape.certsrv.key.KeyNotFoundException": KeyNotFoundException,
- "com.netscape.certsrv.profile.ProfileNotFoundException": ProfileNotFoundException,
- "com.netscape.certsrv.request.RequestNotFoundException": RequestNotFoundException,
+ "com.netscape.certsrv.profile.ProfileNotFoundException":
+ ProfileNotFoundException,
+ "com.netscape.certsrv.request.RequestNotFoundException":
+ RequestNotFoundException,
"com.netscape.certsrv.base.UserNotFoundException": UserNotFoundException,
"com.netscape.certsrv.base.PKIException": PKIException}
+
def handle_exceptions():
- ''' Decorator handling exceptions from REST methods. '''
+ """ Decorator handling exceptions from REST methods. """
def exceptions_decorator(fn_call):
- ''' The actual decorator handler.'''
+ """ The actual decorator handler."""
def handler(inst, *args, **kwargs):
- ''' Decorator to catch and re-throw PKIExceptions.'''
+ """ Decorator to catch and re-throw PKIExceptions."""
try:
return fn_call(inst, *args, **kwargs)
except requests.exceptions.HTTPError as exc:
clazz = exc.response.json()['ClassName']
if clazz in EXCEPTION_MAPPINGS:
exception_class = EXCEPTION_MAPPINGS[clazz]
- pki_exception = exception_class.from_json(exc.response.json())
+ pki_exception = exception_class.from_json(
+ exc.response.json())
raise pki_exception
else:
raise exc
return handler
+
return exceptions_decorator
class PropertyFile(object):
- ''' Class to manage property files '''
+ """ Class to manage property files """
def __init__(self, filename, delimiter='='):
- ''' Constructor '''
+ """ Constructor """
self.filename = filename
self.delimiter = delimiter
self.lines = []
def read(self):
- ''' Read from property file '''
+ """ Read from property file """
self.lines = []
if not os.path.exists(self.filename):
@@ -263,31 +288,32 @@ class PropertyFile(object):
self.lines.append(line)
def write(self):
- ''' Write to property file '''
+ """ Write to property file """
# write all lines in the original order
with open(self.filename, 'w') as f_out:
for line in self.lines:
f_out.write(line + '\n')
def show(self):
- ''' Show contents of property file.'''
+ """ Show contents of property file."""
for line in self.lines:
print line
def insert_line(self, index, line):
- ''' Insert line in property file '''
+ """ Insert line in property file """
self.lines.insert(index, line)
def remove_line(self, index):
- ''' Remove line from property file '''
+ """ Remove line from property file """
self.lines.pop(index)
def index(self, name):
- ''' Find the index (position) of a property in a property file '''
+ """ Find the index (position) of a property in a property file """
for i, line in enumerate(self.lines):
# parse <key> <delimiter> <value>
- match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter, line)
+ match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter,
+ line)
if not match:
continue
@@ -300,13 +326,14 @@ class PropertyFile(object):
return -1
def get(self, name):
- ''' Get value for specified property '''
+ """ Get value for specified property """
result = None
for line in self.lines:
# parse <key> <delimiter> <value>
- match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter, line)
+ match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter,
+ line)
if not match:
continue
@@ -320,11 +347,12 @@ class PropertyFile(object):
return result
def set(self, name, value, index=None):
- ''' Set value for specified property '''
+ """ Set value for specified property """
for i, line in enumerate(self.lines):
# parse <key> <delimiter> <value>
- match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter, line)
+ match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter,
+ line)
if not match:
continue
@@ -342,11 +370,12 @@ class PropertyFile(object):
self.insert_line(index, name + self.delimiter + value)
def remove(self, name):
- ''' Remove property from property file '''
+ """ Remove property from property file """
for i, line in enumerate(self.lines):
# parse <key> <delimiter> <value>
- match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter, line)
+ match = re.match(r'^\s*(\S*)\s*%s\s*(.*)\s*$' % self.delimiter,
+ line)
if not match:
continue
diff --git a/base/common/python/pki/account.py b/base/common/python/pki/account.py
index be87f8343..1ab5b2ddb 100644
--- a/base/common/python/pki/account.py
+++ b/base/common/python/pki/account.py
@@ -19,6 +19,7 @@
# All rights reserved.
#
+
class AccountClient:
def __init__(self, connection):
diff --git a/base/common/python/pki/client.py b/base/common/python/pki/client.py
index d816053a6..fe9567404 100644
--- a/base/common/python/pki/client.py
+++ b/base/common/python/pki/client.py
@@ -21,14 +21,11 @@
import requests
+
class PKIConnection:
- def __init__(self,
- protocol='http',
- hostname='localhost',
- port='8080',
- subsystem='ca',
- accept='application/json'):
+ def __init__(self, protocol='http', hostname='localhost', port='8080',
+ subsystem='ca', accept='application/json'):
self.protocol = protocol
self.hostname = hostname
@@ -66,17 +63,19 @@ class PKIConnection:
def post(self, path, payload, headers=None, params=None):
r = self.session.post(
- self.serverURI + path,
- verify=False,
- data=payload,
- headers=headers,
- params=params)
+ self.serverURI + path,
+ verify=False,
+ data=payload,
+ headers=headers,
+ params=params)
r.raise_for_status()
return r
+
+
def main():
conn = PKIConnection()
headers = {'Content-type': 'application/json',
- 'Accept': 'application/json'}
+ 'Accept': 'application/json'}
conn.set_authentication_cert('/root/temp4.pem')
print conn.get("", headers).json()
diff --git a/base/common/python/pki/cryptoutil.py b/base/common/python/pki/cryptoutil.py
index f9c87155b..44adb3fb6 100644
--- a/base/common/python/pki/cryptoutil.py
+++ b/base/common/python/pki/cryptoutil.py
@@ -18,9 +18,9 @@
# Copyright (C) 2013 Red Hat, Inc.
# All rights reserved.
#
-'''
+"""
Module containing crypto classes.
-'''
+"""
import abc
import exceptions
import nss.nss as nss
@@ -31,81 +31,82 @@ import tempfile
class CryptoUtil(object):
- '''
+ """
Abstract class containing methods to do cryptographic operations.
- '''
+ """
__metaclass__ = abc.ABCMeta
def __init__(self):
- ''' Constructor '''
+ """ Constructor """
pass
@abc.abstractmethod
def initialize(self):
- ''' Initialization code '''
+ """ Initialization code """
pass
@staticmethod
@abc.abstractmethod
def generate_nonce_iv(mechanism):
- ''' Create a random initialization vector '''
+ """ Create a random initialization vector """
pass
@abc.abstractmethod
def generate_symmetric_key(self, mechanism=None, size=0):
- ''' Generate and return a symmetric key '''
+ """ Generate and return a symmetric key """
pass
@abc.abstractmethod
def generate_session_key(self):
- ''' Generate a session key to be used for wrapping data to the DRM
- This must return a 3DES 168 bit key '''
+ """ Generate a session key to be used for wrapping data to the DRM
+ This must return a 3DES 168 bit key """
pass
@abc.abstractmethod
def symmetric_wrap(self, data, wrapping_key, mechanism=None, nonce_iv=None):
- ''' encrypt data using a symmetric key (wrapping key)'''
+ """ encrypt data using a symmetric key (wrapping key)"""
pass
@abc.abstractmethod
- def symmetric_unwrap(self, data, wrapping_key, mechanism=None, nonce_iv=None):
- ''' decrypt data originally encrypted with symmetric key (wrapping key)
+ def symmetric_unwrap(self, data, wrapping_key, mechanism=None,
+ nonce_iv=None):
+ """ decrypt data originally encrypted with symmetric key (wrapping key)
We expect the data and nonce_iv values to be base64 encoded.
The mechanism is the type of key used to do the wrapping. It defaults
to a 56 bit DES3 key.
- '''
+ """
pass
@abc.abstractmethod
def asymmetric_wrap(self, data, wrapping_cert, mechanism=None):
- ''' encrypt a symmetric key with the public key of a transport cert.
+ """ encrypt a symmetric key with the public key of a transport cert.
The mechanism is the type of symmetric key, which defaults to a 56 bit
DES3 key.
- '''
+ """
pass
#abc.abstractmethod
def get_cert(self, cert_nick):
- ''' Get the certificate for the specified cert_nick. '''
+ """ Get the certificate for the specified cert_nick. """
pass
+
class NSSCryptoUtil(CryptoUtil):
- '''
+ """
Class that defines NSS implementation of CryptoUtil.
Requires an NSS database to have been set up and initialized.
Note that all inputs and outputs are unencoded.
- '''
+ """
@staticmethod
def setup_database(db_dir, password, over_write=False):
- ''' Create an NSS database '''
+ """ Create an NSS database """
if os.path.exists(db_dir):
if not over_write:
- raise exceptions.IOError(
- "Directory already exists.")
+ raise exceptions.IOError("Directory already exists.")
if os.path.isdir(db_dir):
shutil.rmtree(db_dir)
else:
@@ -120,23 +121,25 @@ class NSSCryptoUtil(CryptoUtil):
subprocess.check_call(command)
def __init__(self, certdb_dir, certdb_password):
- ''' Initialize nss and nss related parameters
+ """ Initialize nss and nss related parameters
This method expects a NSS database to have already been created at
certdb_dir with password certdb_password.
- '''
+ """
CryptoUtil.__init__(self)
self.certdb_dir = certdb_dir
self.certdb_password = certdb_password
self.nonce_iv = "e4:bb:3b:d3:c3:71:2e:58"
def initialize(self):
- ''' initialize the nss db. Must be done before any crypto operations '''
+ """
+ Initialize the nss db. Must be done before any crypto operations
+ """
nss.nss_init(self.certdb_dir)
def import_cert(self, cert_nick, cert, trust):
- ''' Import a certificate into the nss database
- '''
+ """ Import a certificate into the nss database
+ """
# certutil -A -d db_dir -n cert_nick -t trust -i cert_file -a
with tempfile.NamedTemporaryFile() as cert_file:
cert_file.write(cert)
@@ -148,7 +151,7 @@ class NSSCryptoUtil(CryptoUtil):
@staticmethod
def generate_nonce_iv(mechanism=nss.CKM_DES3_CBC_PAD):
- ''' Create a random initialization vector '''
+ """ Create a random initialization vector """
iv_length = nss.get_iv_length(mechanism)
if iv_length > 0:
iv_data = nss.generate_random(iv_length)
@@ -158,12 +161,14 @@ class NSSCryptoUtil(CryptoUtil):
@classmethod
def setup_contexts(cls, mechanism, sym_key, nonce_iv):
- ''' Set up contexts to do wrapping/unwrapping by symmetric keys. '''
+ """ Set up contexts to do wrapping/unwrapping by symmetric keys. """
# Get a PK11 slot based on the cipher
slot = nss.get_best_slot(mechanism)
if sym_key is None:
- sym_key = slot.key_gen(mechanism, None, slot.get_best_key_length(mechanism))
+ sym_key = slot.key_gen(mechanism,
+ None,
+ slot.get_best_key_length(mechanism))
# If initialization vector was supplied use it, otherwise set it to None
if nonce_iv:
@@ -188,68 +193,76 @@ class NSSCryptoUtil(CryptoUtil):
return encoding_ctx, decoding_ctx
def generate_symmetric_key(self, mechanism=nss.CKM_DES3_CBC_PAD, size=0):
- ''' Returns a symmetric key.
+ """ Returns a symmetric key.
Note that for fixed length keys, this length should be 0. If no length
is provided, then the function will either use 0 (for fixed length keys)
or the maximum available length for that algorithm and the token.
- '''
+ """
slot = nss.get_best_slot(mechanism)
if size == 0:
size = slot.get_best_key_length(mechanism)
return slot.key_gen(mechanism, None, size)
def generate_session_key(self):
- ''' Returns a session key to be used when wrapping secrets for the DRM
+ """ Returns a session key to be used when wrapping secrets for the DRM
This will return a 168 bit 3DES key.
- '''
+ """
return self.generate_symmetric_key(mechanism=nss.CKM_DES3_CBC_PAD)
- def symmetric_wrap(self, data, wrapping_key, mechanism=nss.CKM_DES3_CBC_PAD, nonce_iv=None):
- '''
+ def symmetric_wrap(self, data, wrapping_key, mechanism=nss.CKM_DES3_CBC_PAD,
+ nonce_iv=None):
+ """
:param data Data to be wrapped
:param wrapping_key Symmetric key to wrap data
Wrap (encrypt) data using the supplied symmetric key
- '''
+ """
if nonce_iv is None:
nonce_iv = nss.read_hex(self.nonce_iv)
- encoding_ctx, _decoding_ctx = self.setup_contexts(mechanism, wrapping_key, nonce_iv)
- wrapped_data = encoding_ctx.cipher_op(data) + encoding_ctx.digest_final()
+ encoding_ctx, _decoding_ctx = self.setup_contexts(mechanism,
+ wrapping_key,
+ nonce_iv)
+ wrapped_data = encoding_ctx.cipher_op(data) +\
+ encoding_ctx.digest_final()
return wrapped_data
- def symmetric_unwrap(self, data, wrapping_key, mechanism=nss.CKM_DES3_CBC_PAD, nonce_iv=None):
- '''
+ def symmetric_unwrap(self, data, wrapping_key,
+ mechanism=nss.CKM_DES3_CBC_PAD, nonce_iv=None):
+ """
:param data Data to be unwrapped
:param wrapping_key Symmetric key to unwrap data
:param nonce_iv iv data
Unwrap (decrypt) data using the supplied symmetric key
- '''
+ """
if nonce_iv is None:
nonce_iv = nss.read_hex(self.nonce_iv)
- _encoding_ctx, decoding_ctx = self.setup_contexts(mechanism, wrapping_key, nonce_iv)
+ _encoding_ctx, decoding_ctx = self.setup_contexts(mechanism,
+ wrapping_key,
+ nonce_iv)
unwrapped_data = decoding_ctx.cipher_op(data) \
+ decoding_ctx.digest_final()
return unwrapped_data
- def asymmetric_wrap(self, data, wrapping_cert, mechanism=nss.CKM_DES3_CBC_PAD):
- '''
+ def asymmetric_wrap(self, data, wrapping_cert,
+ mechanism=nss.CKM_DES3_CBC_PAD):
+ """
:param data Data to be wrapped
:param wrapping_cert Public key to wrap data
:param mechanism algorithm of symmetric key to be wrapped
Wrap (encrypt) data using the supplied asymmetric key
- '''
+ """
public_key = wrapping_cert.subject_public_key_info.public_key
return nss.pub_wrap_sym_key(mechanism, public_key, data)
def get_cert(self, cert_nick):
- '''
+ """
:param cert_nick Nickname for the certificate to be returned
Searches NSS database and returns SecItem object for this certificate.
- '''
+ """
return nss.find_cert_from_nickname(cert_nick)
diff --git a/base/common/python/pki/encoder.py b/base/common/python/pki/encoder.py
index e947bbc7c..0ed194d0d 100644
--- a/base/common/python/pki/encoder.py
+++ b/base/common/python/pki/encoder.py
@@ -3,6 +3,7 @@ import json
TYPES = {}
NOTYPES = {}
+
class CustomTypeEncoder(json.JSONEncoder):
"""A custom JSONEncoder class that knows how to encode core custom
objects.
@@ -10,20 +11,20 @@ class CustomTypeEncoder(json.JSONEncoder):
Custom objects are encoded as JSON object literals (ie, dicts) with
one key, 'TypeName' where 'TypeName' is the actual name of the
type to which the object belongs. That single key maps to another
- object literal which is just the __dict__ of the object encoded."""
+ object literal which is just the __dict__ of the object encoded.
- """Reason for ignoring the error
+ Reason for ignoring the error
E0202 - An attribute affected in json.encoder line 157 hide this method
reported by pylint:
The error is in json.encoder.JSONEncoder class.
- There is a default method (which is overridden here) and also a class attribute
- self.default initialized in the init method of the class.
+ There is a default method (which is overridden here) and also a class
+ attribute self.default initialized in the init method of the class.
The intention of such usage being that a custom default method object can
- be passed to init when creating an instance of JSONEncoder, which is then assigned
- to class's default method. (which is valid)
- But pylint raises an issue due to the usage of same name for a method and an attribute
- in which case the attribute definition hides the method.
+ be passed to init when creating an instance of JSONEncoder, which is then
+ assigned to class's default method. (which is valid)
+ But pylint raises an issue due to the usage of same name for a method and
+ an attribute in which case the attribute definition hides the method.
The reason and example for the issue: (top rated comment)
http://stackoverflow.com/questions/12949064/python-what-happens-
when-instance-variable-name-is-same-as-method-name
diff --git a/base/common/python/pki/key.py b/base/common/python/pki/key.py
index a70c25f20..337ae76ff 100644
--- a/base/common/python/pki/key.py
+++ b/base/common/python/pki/key.py
@@ -217,7 +217,9 @@ class KeyRequestInfoCollection(object):
@classmethod
def from_json(cls, json_value):
- """ Return a KeyRequestInfoCollection object from its JSON representation. """
+ """
+ Return a KeyRequestInfoCollection object from its JSON representation.
+ """
ret = cls()
infos = json_value['entries']
if not isinstance(infos, types.ListType):
@@ -248,7 +250,8 @@ class KeyRequestResponse(object):
ret = cls()
if 'RequestInfo' in json_value:
- ret.request_info = KeyRequestInfo.from_json(json_value['RequestInfo'])
+ ret.request_info = KeyRequestInfo.from_json(
+ json_value['RequestInfo'])
if 'KeyData' in json_value:
ret.key_data = KeyData.from_json(json_value['KeyData'])
@@ -268,20 +271,23 @@ class KeyArchivalRequest(pki.ResourceMessage):
Class representing the object sent to the DRM when archiving a secret.
"""
- def __init__(self, client_key_id=None, data_type=None, wrapped_private_data=None,
+ def __init__(self, client_key_id=None, data_type=None,
+ wrapped_private_data=None,
trans_wrapped_session_key=None, pki_archive_options=None,
algorithm_oid=None, symkey_params=None,
key_algorithm=None, key_size=None):
""" Constructor """
- pki.ResourceMessage.__init__(self,
- "com.netscape.certsrv.key.KeyArchivalRequest")
+ pki.ResourceMessage.__init__(
+ self,
+ "com.netscape.certsrv.key.KeyArchivalRequest")
self.add_attribute("clientKeyID", client_key_id)
self.add_attribute("dataType", data_type)
if wrapped_private_data is not None:
self.add_attribute("wrappedPrivateData", wrapped_private_data)
if trans_wrapped_session_key is not None:
- self.add_attribute("transWrappedSessionKey", trans_wrapped_session_key)
+ self.add_attribute("transWrappedSessionKey",
+ trans_wrapped_session_key)
if algorithm_oid is not None:
self.add_attribute("algorithmOID", algorithm_oid)
if symkey_params is not None:
@@ -310,11 +316,13 @@ class KeyRecoveryRequest(pki.ResourceMessage):
nonce_data=None, certificate=None,
passphrase=None):
""" Constructor """
- pki.ResourceMessage.__init__(self,
- "com.netscape.certsrv.key.KeyRecoveryRequest")
+ pki.ResourceMessage.__init__(
+ self,
+ "com.netscape.certsrv.key.KeyRecoveryRequest")
self.add_attribute("requestId", request_id)
self.add_attribute("transWrappedSessionKey", trans_wrapped_session_key)
- self.add_attribute("sessionWrappedPassphrase", session_wrapped_passphrase)
+ self.add_attribute("sessionWrappedPassphrase",
+ session_wrapped_passphrase)
self.add_attribute("nonceData", nonce_data)
self.add_attribute("certificate", certificate)
self.add_attribute("passphrase", passphrase)
@@ -337,8 +345,9 @@ class SymKeyGenerationRequest(pki.ResourceMessage):
def __init__(self, client_key_id=None, key_size=None, key_algorithm=None,
key_usages=None, trans_wrapped_session_key=None):
""" Constructor """
- pki.ResourceMessage.__init__(self,
- "com.netscape.certsrv.key.SymKeyGenerationRequest")
+ pki.ResourceMessage.__init__(
+ self,
+ "com.netscape.certsrv.key.SymKeyGenerationRequest")
key_usages = key_usages or []
self.add_attribute("clientKeyID", client_key_id)
self.add_attribute("keySize", key_size)
@@ -402,19 +411,24 @@ class KeyClient(object):
query_params = {'clientKeyID': client_key_id, 'status': status,
'maxResults': max_results, 'maxTime': max_time,
'start': start, 'size': size}
- response = self.connection.get(self.key_url, self.headers, params=query_params)
+ response = self.connection.get(self.key_url, self.headers,
+ params=query_params)
return KeyInfoCollection.from_json(response.json())
@pki.handle_exceptions()
- def list_requests(self, request_state=None, request_type=None, client_key_id=None,
- start=None, page_size=None, max_results=None, max_time=None):
+ def list_requests(self, request_state=None, request_type=None,
+ client_key_id=None,
+ start=None, page_size=None, max_results=None,
+ max_time=None):
""" List/Search key requests in the DRM.
- See KRAClient.list_requests for the valid values of request_state and
- request_type. Returns a KeyRequestInfoCollection object.
+ See KRAClient.list_requests for the valid values of request_state
+ and request_type. Returns a KeyRequestInfoCollection object.
"""
- query_params = {'requestState': request_state, 'requestType': request_type,
- 'clientKeyID': client_key_id, 'start': start, 'pageSize': page_size,
+ query_params = {'requestState': request_state,
+ 'requestType': request_type,
+ 'clientKeyID': client_key_id, 'start': start,
+ 'pageSize': page_size,
'maxResults': max_results, 'maxTime': max_time}
response = self.connection.get(self.key_requests_url, self.headers,
params=query_params)
@@ -501,12 +515,14 @@ class KeyClient(object):
raise TypeError("Request must be specified")
url = self.key_requests_url
- key_request = json.dumps(request, cls=encoder.CustomTypeEncoder, sort_keys=True)
+ key_request = json.dumps(request, cls=encoder.CustomTypeEncoder,
+ sort_keys=True)
response = self.connection.post(url, key_request, self.headers)
return KeyRequestResponse.from_json(response.json())
@pki.handle_exceptions()
- def generate_symmetric_key(self, client_key_id, algorithm=None, size=None, usages=None,
+ def generate_symmetric_key(self, client_key_id, algorithm=None, size=None,
+ usages=None,
trans_wrapped_session_key=None):
""" Generate and archive a symmetric key on the DRM.
@@ -527,7 +543,8 @@ class KeyClient(object):
key_usages=usages,
trans_wrapped_session_key=twsk)
raise NotImplementedError(
- "Returning the symmetric key in the same call is not yet implemented.")
+ "Returning the symmetric key in the same call is not yet "
+ "implemented.")
else:
request = SymKeyGenerationRequest(
client_key_id=client_key_id,
@@ -556,8 +573,9 @@ class KeyClient(object):
private_data is the raw secret to be archived.
It will be wrapped and sent to the DRM.
- The function returns a KeyRequestResponse object containing a KeyRequestInfo
- object with details about the archival request and key archived.
+ The function returns a KeyRequestResponse object containing a
+ KeyRequestInfo object with details about the archival request and
+ key archived.
"""
if (client_key_id is None) or (data_type is None):
raise TypeError("Client Key ID and data type must be specified")
@@ -565,7 +583,8 @@ class KeyClient(object):
if data_type == KeyClient.SYMMETRIC_KEY_TYPE:
if (key_algorithm is None) or (key_size is None):
raise TypeError(
- "For symmetric keys, key algorithm and key_size must be specified")
+ "For symmetric keys, key algorithm and key_size must "
+ "be specified")
if private_data is None:
raise TypeError("No data provided to be archived")
@@ -574,14 +593,19 @@ class KeyClient(object):
session_key = self.crypto.generate_session_key()
trans_wrapped_session_key = \
self.crypto.asymmetric_wrap(session_key, self.transport_cert)
- wrapped_private_data = self.crypto.symmetric_wrap(private_data, session_key, nonce_iv=nonce_iv)
+ wrapped_private_data = self.crypto.symmetric_wrap(private_data,
+ session_key,
+ nonce_iv=nonce_iv)
algorithm_oid = self.DES_EDE3_CBC_OID
symkey_params = base64.encodestring(nonce_iv)
- return self.archive_encrypted_data(client_key_id, data_type, wrapped_private_data,
- trans_wrapped_session_key, algorithm_oid,
- symkey_params, key_algorithm=key_algorithm,
+ return self.archive_encrypted_data(client_key_id, data_type,
+ wrapped_private_data,
+ trans_wrapped_session_key,
+ algorithm_oid,
+ symkey_params,
+ key_algorithm=key_algorithm,
key_size=key_size)
@pki.handle_exceptions()
@@ -595,10 +619,10 @@ class KeyClient(object):
data_type, key_algorithm and key_size.
The following parameters are also required:
- - wrapped_private_data - which is the secret wrapped by a session
- key (168 bit 3DES symmetric key)
- - trans_wrapped_session_key - the above session key wrapped by the
- DRM transport certificate public key.
+ - wrapped_private_data - which is the secret wrapped by a
+ session key (168 bit 3DES symmetric key)
+ - trans_wrapped_session_key - the above session key wrapped by
+ the DRM transport certificate public key.
- the algorithm_oid string for the symmetric key wrap
- the symkey_params for the symmetric key wrap
@@ -606,8 +630,9 @@ class KeyClient(object):
of the secret, or if the secret was generated on a separate client
machine and the wrapping was done there.
- The function returns a KeyRequestResponse object containing a KeyRequestInfo
- object with details about the archival request and key archived.
+ The function returns a KeyRequestResponse object containing a
+ KeyRequestInfo object with details about the archival request and
+ key archived.
"""
if (client_key_id is None) or (data_type is None):
raise TypeError("Client Key ID and data type must be specified")
@@ -615,11 +640,13 @@ class KeyClient(object):
if data_type == KeyClient.SYMMETRIC_KEY_TYPE:
if (key_algorithm is None) or (key_size is None):
raise TypeError(
- "For symmetric keys, key algorithm and key size must be specified")
+ "For symmetric keys, key algorithm and key size "
+ "must be specified")
if (encrypted_data is None) or (trans_wrapped_session_key is None) or \
(algorithm_oid is None) or (symkey_params is None):
- raise TypeError("All data and wrapping parameters must be specified")
+ raise TypeError(
+ "All data and wrapping parameters must be specified")
twsk = base64.encodestring(trans_wrapped_session_key)
data = base64.encodestring(encrypted_data)
@@ -645,8 +672,9 @@ class KeyClient(object):
pki_archive_options is the data to be archived wrapped in a
PKIArchiveOptions structure,
- The function returns a KeyRequestResponse object containing a KeyRequestInfo
- object with details about the archival request and key archived.
+ The function returns a KeyRequestResponse object containing a
+ KeyRequestInfo object with details about the archival request and
+ key archived.
"""
if (client_key_id is None) or (data_type is None):
raise TypeError("Client Key_ID and Data Type must be specified")
@@ -654,7 +682,8 @@ class KeyClient(object):
if data_type == KeyClient.SYMMETRIC_KEY_TYPE:
if (key_algorithm is None) or (key_size is None):
raise TypeError(
- "For symmetric keys, key algorithm and key_size must be specified")
+ "For symmetric keys, key algorithm and key_size "
+ "must be specified")
if pki_archive_options is None:
raise TypeError("No data provided to be archived")
@@ -668,27 +697,31 @@ class KeyClient(object):
return self.create_request(request)
@pki.handle_exceptions()
- def recover_key(self, key_id, request_id=None, session_wrapped_passphrase=None,
- trans_wrapped_session_key=None, b64certificate=None, nonce_data=None):
+ def recover_key(self, key_id, request_id=None,
+ session_wrapped_passphrase=None,
+ trans_wrapped_session_key=None, b64certificate=None,
+ nonce_data=None):
""" Create a request to recover a secret.
- To retrieve a symmetric key or passphrase, the only parameter that is required is
- the keyId. It is possible (but not required) to pass in the session keys/passphrase
- and nonceData for the retrieval at this time. Those parameters are documented
- in the docstring for retrieve_key below.
+ To retrieve a symmetric key or passphrase, the only parameter that
+ is required is the keyId. It is possible (but not required) to pass
+ in the session keys/passphrase and nonceData for the retrieval at
+ this time. Those parameters are documented in the docstring for
+ retrieve_key below.
- To retrieve an asymmetric key, the keyId and the the base-64 encoded certificate
- is required.
+ To retrieve an asymmetric key, the keyId and the the base-64 encoded
+ certificate is required.
"""
if key_id is None:
raise TypeError("Key ID must be defined")
- request = KeyRecoveryRequest(key_id=key_id,
- request_id=request_id,
- trans_wrapped_session_key=trans_wrapped_session_key,
- session_wrapped_passphrase=session_wrapped_passphrase,
- certificate=b64certificate,
- nonce_data=nonce_data)
+ request = KeyRecoveryRequest(
+ key_id=key_id,
+ request_id=request_id,
+ trans_wrapped_session_key=trans_wrapped_session_key,
+ session_wrapped_passphrase=session_wrapped_passphrase,
+ certificate=b64certificate,
+ nonce_data=nonce_data)
return self.create_request(request)
@pki.handle_exceptions()
@@ -706,7 +739,8 @@ class KeyClient(object):
raise TypeError("Key Recovery Request must be specified")
url = self.key_url + '/retrieve'
- key_request = json.dumps(data, cls=encoder.CustomTypeEncoder, sort_keys=True)
+ key_request = json.dumps(data, cls=encoder.CustomTypeEncoder,
+ sort_keys=True)
response = self.connection.post(url, key_request, self.headers)
key_data = KeyData.from_json(response.json())
return Key(key_data)
@@ -715,30 +749,33 @@ class KeyClient(object):
def retrieve_key(self, key_id, trans_wrapped_session_key=None):
""" Retrieve a secret (passphrase or symmetric key) from the DRM.
- This function generates a key recovery request, approves it, and retrieves
- the secret referred to by key_id. This assumes that only one approval is required
- to authorize the recovery.
+ This function generates a key recovery request, approves it, and
+ retrieves the secret referred to by key_id. This assumes that only one
+ approval is required to authorize the recovery.
- To ensure data security in transit, the data will be returned encrypted by a session
- key (168 bit 3DES symmetric key) - which is first wrapped (encrypted) by the public
- key of the DRM transport certificate before being sent to the DRM. The
- parameter trans_wrapped_session_key refers to this wrapped session key.
+ To ensure data security in transit, the data will be returned encrypted
+ by a session key (168 bit 3DES symmetric key) - which is first wrapped
+ (encrypted) by the public key of the DRM transport certificate before
+ being sent to the DRM. The parameter trans_wrapped_session_key refers
+ to this wrapped session key.
There are two ways of using this function:
1) trans_wrapped_session_key is not provided by caller.
- In this case, the function will call CryptoUtil methods to generate and wrap the
- session key. The function will return the KeyData object with a private_data attribute
- which stores the unwrapped key information.
+ In this case, the function will call CryptoUtil methods to generate and
+ wrap the session key. The function will return the KeyData object with
+ a private_data attribute which stores the unwrapped key information.
2) The trans_wrapped_session_key is provided by the caller.
- In this case, the function will simply pass the data to the DRM, and will return the secret
- wrapped in the session key. The secret will still need to be unwrapped by the caller.
+ In this case, the function will simply pass the data to the DRM, and
+ will return the secret wrapped in the session key. The secret will
+ still need to be unwrapped by the caller.
- The function will return the KeyData object, where the KeyData structure includes the
- wrapped secret and some nonce data to be used as a salt when unwrapping.
+ The function will return the KeyData object, where the KeyData structure
+ includes the wrapped secret and some nonce data to be used as a salt
+ when unwrapping.
"""
if key_id is None:
raise TypeError("Key ID must be specified")
@@ -748,8 +785,9 @@ class KeyClient(object):
if trans_wrapped_session_key is None:
key_provided = False
session_key = self.crypto.generate_session_key()
- trans_wrapped_session_key = self.crypto.asymmetric_wrap(session_key,
- self.transport_cert)
+ trans_wrapped_session_key = self.crypto.asymmetric_wrap(
+ session_key,
+ self.transport_cert)
response = self.recover_key(key_id)
request_id = response.get_request_id()
@@ -758,7 +796,8 @@ class KeyClient(object):
request = KeyRecoveryRequest(
key_id=key_id,
request_id=request_id,
- trans_wrapped_session_key=base64.encodestring(trans_wrapped_session_key))
+ trans_wrapped_session_key=base64.encodestring(
+ trans_wrapped_session_key))
key = self.retrieve_key_data(request)
if not key_provided:
@@ -773,38 +812,40 @@ class KeyClient(object):
trans_wrapped_session_key=None,
session_wrapped_passphrase=None,
nonce_data=None):
- """ Retrieve a secret (passphrase or symmetric key) from the DRM using a passphrase.
+ """ Retrieve a secret (passphrase or symmetric key) from the DRM using
+ a passphrase.
- This function generates a key recovery request, approves it, and retrieves
- the secret referred to by key_id. This assumes that only one approval is required
- to authorize the recovery.
+ This function generates a key recovery request, approves it, and
+ retrieves the secret referred to by key_id. This assumes that only one
+ approval is required to authorize the recovery.
- The secret is secured in transit by wrapping the secret with a passphrase using
- PBE encryption.
+ The secret is secured in transit by wrapping the secret with a
+ passphrase using PBE encryption.
There are two ways of using this function:
1) A passphrase is provided by the caller.
- In this case, CryptoUtil methods will be called to create the data to securely send the
- passphrase to the DRM. Basically, three pieces of data will be sent:
+ In this case, CryptoUtil methods will be called to create the data to
+ securely send the passphrase to the DRM. Basically, three pieces of
+ data will be sent:
- - the passphrase wrapped by a 168 bit 3DES symmetric key (the session key). This
- is referred to as the parameter session_wrapped_passphrase above.
+ - the passphrase wrapped by a 168 bit 3DES symmetric key (the session
+ key). This is referred to as the parameter session_wrapped_passphrase.
- - the session key wrapped with the public key in the DRM transport certificate. This
- is referred to as the trans_wrapped_session_key above.
+ - the session key wrapped with the public key in the DRM transport
+ certificate. This is referred to as the trans_wrapped_session_key.
- ivps nonce data, referred to as nonce_data
The function will return the tuple (KeyData, unwrapped_secret)
- 2) The caller provides the trans_wrapped_session_key, session_wrapped_passphrase
- and nonce_data.
+ 2) The caller provides the trans_wrapped_session_key,
+ session_wrapped_passphrase and nonce_data.
- In this case, the data will simply be passed to the DRM. The function will return
- the secret encrypted by the passphrase using PBE Encryption. The secret will still
- need to be decrypted by the caller.
+ In this case, the data will simply be passed to the DRM. The function
+ will return the secret encrypted by the passphrase using PBE Encryption.
+ The secret will still need to be decrypted by the caller.
The function will return the tuple (KeyData, None)
"""
@@ -814,9 +855,9 @@ class KeyClient(object):
def retrieve_key_by_pkcs12(self, key_id, certificate, passphrase):
""" Retrieve an asymmetric private key and return it as PKCS12 data.
- This function generates a key recovery request, approves it, and retrieves
- the secret referred to by key_id in a PKCS12 file. This assumes that only
- one approval is required to authorize the recovery.
+ This function generates a key recovery request, approves it, and
+ retrieves the secret referred to by key_id in a PKCS12 file. This
+ assumes that only one approval is required to authorize the recovery.
This function requires the following parameters:
- key_id : the ID of the key
@@ -826,7 +867,8 @@ class KeyClient(object):
The function returns a KeyData object.
"""
if (key_id is None) or (certificate is None) or (passphrase is None):
- raise TypeError("Key ID, certificate and passphrase must all be specified")
+ raise TypeError(
+ "Key ID, certificate and passphrase must all be specified")
response = self.recover_key(key_id, b64certificate=certificate)
request_id = response.get_request_id()
@@ -851,7 +893,8 @@ def main():
""" Some unit tests - basically printing different types of requests """
print "printing symkey generation request"
client_key_id = "vek 123"
- usages = [SymKeyGenerationRequest.DECRYPT_USAGE, SymKeyGenerationRequest.ENCRYPT_USAGE]
+ usages = [SymKeyGenerationRequest.DECRYPT_USAGE,
+ SymKeyGenerationRequest.ENCRYPT_USAGE]
gen_request = SymKeyGenerationRequest(client_key_id, 128, "AES", usages)
print json.dumps(gen_request, cls=encoder.CustomTypeEncoder, sort_keys=True)
@@ -863,7 +906,8 @@ def main():
print "printing key archival request"
archival_request = KeyArchivalRequest(client_key_id, "symmetricKey",
"MX123AABBCD", "AES", 128)
- print json.dumps(archival_request, cls=encoder.CustomTypeEncoder, sort_keys=True)
+ print json.dumps(archival_request, cls=encoder.CustomTypeEncoder,
+ sort_keys=True)
if __name__ == '__main__':
diff --git a/base/common/python/pki/kraclient.py b/base/common/python/pki/kraclient.py
index 4d62f38f9..e3daabdd3 100644
--- a/base/common/python/pki/kraclient.py
+++ b/base/common/python/pki/kraclient.py
@@ -19,34 +19,38 @@
# Copyright (C) 2013 Red Hat, Inc.
# All rights reserved.
#
-'''
+"""
Module containing KRAClient class. This class should be used by Python clients
to interact with the DRM to expose the functionality of the KeyClient and
-KeyRequestResouce REST APIs.
-'''
+KeyRequestResource REST APIs.
+"""
import pki.key as key
from pki.systemcert import SystemCertClient
+
class KRAClient(object):
- '''
- Client class that models interactions with a KRA using the Key and KeyRequest REST APIs.
- '''
+ """
+ Client class that models interactions with a KRA using the Key and
+ KeyRequest REST APIs.
+ """
def __init__(self, connection, crypto, transport_cert_nick=None):
- ''' Constructor
+ """ Constructor
:param connection - PKIConnection object with DRM connection info.
- :param crypto - CryptoUtil object. NSSCryptoUtil is provided by default.
- If a different crypto implementation is desired, a different
- subclass of CryptoUtil must be provided.
- :param transport_cert_nick - identifier for the DRM transport certificate. This will
- be passed to the CryptoUtil.get_cert() command to get a representation
- of the transport certificate usable for crypto operations.
- Note that for NSS databases, the database must have been initialized
- beforehand.
- '''
+ :param crypto - CryptoUtil object. NSSCryptoUtil is provided by
+ default. If a different crypto implementation is
+ desired, a different subclass of CryptoUtil must be
+ provided.
+ :param transport_cert_nick - identifier for the DRM transport
+ certificate. This will be passed to the
+ CryptoUtil.get_cert() command to get a representation
+ of the transport certificate usable for crypto ops.
+ Note that for NSS databases, the database must have been
+ initialized beforehand.
+ """
self.connection = connection
self.keys = key.KeyClient(connection, crypto, transport_cert_nick)
self.system_certs = SystemCertClient(connection)
diff --git a/base/common/python/pki/system.py b/base/common/python/pki/system.py
index 821f0dc96..a4b5c2fee 100644
--- a/base/common/python/pki/system.py
+++ b/base/common/python/pki/system.py
@@ -57,6 +57,7 @@ class SecurityDomainHost(object):
host.unsecure_port = json_value['Port']
return host
+
class SecurityDomainSubsystem(object):
def __init__(self):
self.name = None
@@ -130,7 +131,8 @@ class SystemConfigClient(object):
def configure(self, data):
headers = {'Content-type': 'application/json',
'Accept': 'application/json'}
- response = self.connection.post('/rest/installer/configure', data, headers)
+ response = self.connection.post('/rest/installer/configure', data,
+ headers)
return response.json()
diff --git a/base/common/python/pki/systemcert.py b/base/common/python/pki/systemcert.py
index 53fbad653..43da7fc35 100644
--- a/base/common/python/pki/systemcert.py
+++ b/base/common/python/pki/systemcert.py
@@ -18,20 +18,22 @@
# Copyright (C) 2013 Red Hat, Inc.
# All rights reserved.
#
-'''
+"""
Module containing the Python client classes for the SystemCert REST API
-'''
+"""
import pki
from pki.cert import CertData
+
class SystemCertClient(object):
- '''
- Class encapsulating and mirroring the functionality in the SystemCertResouce
- Java interface class defining the REST API for system certificate resources.
- '''
+ """
+ Class encapsulating and mirroring the functionality in the
+ SystemCertResource Java interface class defining the REST API for
+ system certificate resources.
+ """
def __init__(self, connection):
- ''' Constructor '''
+ """ Constructor """
#super(PKIResource, self).__init__(connection)
self.connection = connection
self.headers = {'Content-type': 'application/json',
@@ -40,8 +42,8 @@ class SystemCertClient(object):
@pki.handle_exceptions()
def get_transport_cert(self):
- ''' Return transport certificate '''
- url = self.cert_url + '/transport'
+ """ Return transport certificate """
+ url = self.cert_url + '/transport'
response = self.connection.get(url, self.headers)
cert_data = CertData.from_json(response.json())
return cert_data.encoded
diff --git a/base/common/python/pki/upgrade.py b/base/common/python/pki/upgrade.py
index ecdbfcf6b..5d6af821a 100644
--- a/base/common/python/pki/upgrade.py
+++ b/base/common/python/pki/upgrade.py
@@ -73,25 +73,22 @@ class Version(object):
else:
raise Exception('Unsupported version type: ' + str(type(obj)))
-
# release is ignored in comparisons
-
def __eq__(self, other):
return (self.major == other.major and
- self.minor == other.minor and
- self.patch == other.patch)
+ self.minor == other.minor and
+ self.patch == other.patch)
def __lt__(self, other):
if self.major < other.major:
return True
- if (self.major == other.major and
- self.minor < other.minor):
+ if self.major == other.major and self.minor < other.minor:
return True
if (self.major == other.major and
- self.minor == other.minor and
- self.patch < other.patch):
+ self.minor == other.minor and
+ self.patch < other.patch):
return True
return False
@@ -99,12 +96,12 @@ class Version(object):
def __repr__(self):
return self.version
+
class PKIUpgradeTracker(object):
- def __init__(self, name, filename,
- delimiter='=',
- version_key='PKI_VERSION',
- index_key='PKI_UPGRADE_INDEX'):
+ def __init__(self, name, filename, delimiter='=',
+ version_key='PKI_VERSION',
+ index_key='PKI_UPGRADE_INDEX'):
self.name = name
self.filename = filename
@@ -128,7 +125,8 @@ class PKIUpgradeTracker(object):
def set(self, version):
if verbose:
- print 'Setting ' + self.name + ' tracker to version ' + str(version) + '.'
+ print 'Setting ' + self.name + ' tracker to version ' +\
+ str(version) + '.'
self.set_version(version)
self.remove_index()
@@ -181,7 +179,7 @@ class PKIUpgradeTracker(object):
length = len(self.properties.lines)
if length > 0 and self.properties.lines[length - 1] != '':
self.properties.insert_line(length, '')
- length = length + 1
+ length += 1
# add index
self.properties.set(self.index_key, str(index), index=length)
@@ -221,7 +219,7 @@ class PKIUpgradeTracker(object):
length = len(self.properties.lines)
if length > 0 and self.properties.lines[length - 1] != '':
self.properties.insert_line(length, '')
- length = length + 1
+ length += 1
# add version
self.properties.set(self.version_key, str(version), index=length)
@@ -295,25 +293,32 @@ class PKIUpgradeScriptlet(object):
try:
if not self.can_upgrade():
- if verbose: print 'Skipping system.'
+ if verbose:
+ print 'Skipping system.'
return
- if verbose: print 'Upgrading system.'
+ if verbose:
+ print 'Upgrading system.'
self.upgrade_system()
self.update_tracker()
except Exception as e:
- if verbose: traceback.print_exc()
- else: print 'ERROR: ' + e.message
+ if verbose:
+ traceback.print_exc()
+ else:
+ print 'ERROR: ' + e.message
message = 'Failed upgrading system.'
if self.upgrader.silent:
print message
else:
- result = pki.read_text(message + ' Continue (Yes/No)',
- options=['Y', 'N'], default='Y', delimiter='?', case_sensitive=False).lower()
- if result == 'y': return
+ result = pki.read_text(
+ message + ' Continue (Yes/No)',
+ options=['Y', 'N'], default='Y', delimiter='?',
+ case_sensitive=False).lower()
+ if result == 'y':
+ return
raise pki.PKIException('Upgrade failed: ' + e.message, e)
@@ -328,20 +333,24 @@ class PKIUpgradeScriptlet(object):
if os.path.exists(oldfiles):
# restore all backed up files
- for sourcepath, _, filenames in os.walk(oldfiles): #unused item _ for dirnames
+ for sourcepath, _, filenames in os.walk(oldfiles):
+ #unused item _ for dirnames
destpath = sourcepath[len(oldfiles):]
- if destpath == '': destpath = '/'
+ if destpath == '':
+ destpath = '/'
if not os.path.isdir(destpath):
- if verbose: print 'Restoring ' + destpath
+ if verbose:
+ print 'Restoring ' + destpath
pki.util.copydirs(sourcepath, destpath)
for filename in filenames:
sourcefile = os.path.join(sourcepath, filename)
targetfile = os.path.join(destpath, filename)
- if verbose: print 'Restoring ' + targetfile
+ if verbose:
+ print 'Restoring ' + targetfile
pki.util.copyfile(sourcefile, targetfile)
newfiles = backup_dir + '/newfiles'
@@ -358,8 +367,10 @@ class PKIUpgradeScriptlet(object):
paths.reverse()
for path in paths:
- if not os.path.exists(path): continue
- if verbose: print 'Deleting ' + path
+ if not os.path.exists(path):
+ continue
+ if verbose:
+ print 'Deleting ' + path
if os.path.isfile(path):
os.remove(path)
@@ -389,7 +400,8 @@ class PKIUpgradeScriptlet(object):
pki.util.copydirs(sourceparent, destparent)
if os.path.isfile(path):
- if verbose: print 'Saving ' + path
+ if verbose:
+ print 'Saving ' + path
# do not overwrite initial backup
pki.util.copyfile(path, dest, overwrite=False)
@@ -399,22 +411,26 @@ class PKIUpgradeScriptlet(object):
relpath = sourcepath[len(path):]
destpath = dest + relpath
- if verbose: print 'Saving ' + sourcepath
+ if verbose:
+ print 'Saving ' + sourcepath
pki.util.copydirs(sourcepath, destpath)
for filename in filenames:
sourcefile = os.path.join(sourcepath, filename)
targetfile = os.path.join(destpath, filename)
- if verbose: print 'Saving ' + sourcefile
+ if verbose:
+ print 'Saving ' + sourcefile
# do not overwrite initial backup
- pki.util.copyfile(sourcefile, targetfile, overwrite=False)
+ pki.util.copyfile(sourcefile, targetfile,
+ overwrite=False)
else:
# otherwise, record the name
- if verbose: print 'Recording ' + path
+ if verbose:
+ print 'Recording ' + path
with open(backup_dir + '/newfiles', 'a') as f:
f.write(path + '\n')
@@ -430,7 +446,8 @@ class PKIUpgradeScriptlet(object):
class PKIUpgrader(object):
- def __init__(self, upgrade_dir=UPGRADE_DIR, version=None, index=None, silent=False):
+ def __init__(self, upgrade_dir=UPGRADE_DIR, version=None, index=None,
+ silent=False):
self.upgrade_dir = upgrade_dir
self.version = version
@@ -487,15 +504,14 @@ class PKIUpgrader(object):
version.next = target_version
# if no scriptlet version is specified, add all versions to the list
- # if scriptlet version is specified, add only that version to the list
+ # if scriptlet version is specified, add only that version to the
+ # list
if not self.version or str(version) == self.version:
versions.append(version)
return versions
-
def scriptlets(self, version):
-
scriptlets = []
version_dir = self.version_dir(version)
@@ -536,14 +552,15 @@ class PKIUpgrader(object):
return scriptlets
-
def get_tracker(self):
if self.system_tracker:
tracker = self.system_tracker
else:
- tracker = PKIUpgradeTracker('system', SYSTEM_TRACKER,
+ tracker = PKIUpgradeTracker(
+ 'system',
+ SYSTEM_TRACKER,
delimiter=': ',
version_key='Configuration-Version',
index_key='Scriptlet-Index')
@@ -557,7 +574,6 @@ class PKIUpgrader(object):
return tracker.get_version()
def get_target_version(self):
-
return Version(pki.implementation_version())
def is_complete(self):
@@ -569,7 +585,8 @@ class PKIUpgrader(object):
def upgrade_version(self, version):
- print 'Upgrading from version ' + str(version) + ' to ' + str(version.next) + ':'
+ print 'Upgrading from version ' + str(version) + ' to ' +\
+ str(version.next) + ':'
scriptlets = self.scriptlets(version)
@@ -589,8 +606,11 @@ class PKIUpgrader(object):
print message
else:
- result = pki.read_text(message + ' (Yes/No)',
- options=['Y', 'N'], default='Y', case_sensitive=False).lower()
+ result = pki.read_text(
+ message + ' (Yes/No)',
+ options=['Y', 'N'],
+ default='Y',
+ case_sensitive=False).lower()
if result == 'n':
raise pki.PKIException('Upgrade canceled.')
@@ -599,7 +619,7 @@ class PKIUpgrader(object):
scriptlet.init()
scriptlet.upgrade()
- except pki.PKIException as e:
+ except pki.PKIException:
raise
except Exception as e:
@@ -615,19 +635,21 @@ class PKIUpgrader(object):
print
- result = pki.read_text('Continue (Yes/No)',
- options=['Y', 'N'], default='Y', delimiter='?', case_sensitive=False).lower()
+ result = pki.read_text(
+ 'Continue (Yes/No)',
+ options=['Y', 'N'],
+ default='Y',
+ delimiter='?',
+ case_sensitive=False).lower()
if result == 'n':
raise pki.PKIException(message, e)
-
def upgrade(self):
versions = self.versions()
for version in versions:
-
self.upgrade_version(version)
print
@@ -638,7 +660,6 @@ class PKIUpgrader(object):
self.show_tracker()
print 'Upgrade incomplete.'
-
def revert_version(self, version):
print 'Reverting to version ' + str(version) + ':'
@@ -654,8 +675,10 @@ class PKIUpgrader(object):
print message
else:
- result = pki.read_text(message + ' (Yes/No)',
- options=['Y', 'N'], default='Y', case_sensitive=False).lower()
+ result = pki.read_text(
+ message + ' (Yes/No)',
+ options=['Y', 'N'], default='Y',
+ case_sensitive=False).lower()
if result == 'n':
raise pki.PKIException('Revert canceled.')
@@ -663,7 +686,7 @@ class PKIUpgrader(object):
try:
scriptlet.revert()
- except pki.PKIException as e:
+ except pki.PKIException:
raise
except Exception as e:
@@ -679,8 +702,9 @@ class PKIUpgrader(object):
print
- result = pki.read_text('Continue (Yes/No)',
- options=['Y', 'N'], default='Y', delimiter='?', case_sensitive=False).lower()
+ result = pki.read_text(
+ 'Continue (Yes/No)', options=['Y', 'N'],
+ default='Y', delimiter='?', case_sensitive=False).lower()
if result == 'n':
raise pki.PKIException(message, e)
@@ -720,7 +744,6 @@ class PKIUpgrader(object):
else:
print 'Upgrade incomplete.'
-
def set_tracker(self, version):
tracker = self.get_tracker()
diff --git a/base/common/python/pki/util.py b/base/common/python/pki/util.py
index a64f174f4..19f6be720 100644
--- a/base/common/python/pki/util.py
+++ b/base/common/python/pki/util.py
@@ -18,12 +18,15 @@
# Copyright (C) 2013 Red Hat, Inc.
# All rights reserved.
#
-''' Module containing utility functions and classes for the Dogtag python code '''
+"""
+Module containing utility functions and classes for the Dogtag python code
+"""
import os
import shutil
+
def copy(source, dest):
"""
Copy a file or a folder and its contents.
@@ -58,6 +61,7 @@ def copy(source, dest):
targetfile = os.path.join(destpath, filename)
copyfile(sourcefile, targetfile)
+
def copyfile(source, dest, overwrite=True):
"""
Copy a file or link while preserving its attributes.
@@ -82,6 +86,7 @@ def copyfile(source, dest, overwrite=True):
os.chmod(dest, stat.st_mode)
os.chown(dest, stat.st_uid, stat.st_gid)
+
def copydirs(source, dest):
"""
Copy a folder and its parents while preserving their attributes.
@@ -103,6 +108,7 @@ def copydirs(source, dest):
os.chmod(dest, stat.st_mode)
os.chown(dest, stat.st_uid, stat.st_gid)
+
def chown(path, uid, gid):
"""
Change ownership of a folder and its contents.