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

python 3 fixes #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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: 1 addition & 1 deletion calib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@

"""

from version import __version__
from .version import __version__

39 changes: 28 additions & 11 deletions calib/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class CertificateManager(object):
FILE_CA_CERT = 'ca.cert.pem'
FILE_CA_KEY = 'ca.key.pem'

def __init__(self, basePath = None, logger = None):
def __init__(self, basePath=None, logger=None):
"""Create a new CertificateManager
"""
self.basePath = os.path.expanduser(os.path.abspath(basePath)) or os.getcwd()
Expand All @@ -40,8 +40,13 @@ def __init__(self, basePath = None, logger = None):
if not os.path.isdir(self.basePath):
raise ValueError('Base path [%s] not found' % self.basePath)

def init(self):
def init(self, subjectAltNames=None):
"""Init the manager

subjectAltNames is an optional list of subjectAltNames you'd like to be
rendered into the openssl config file template.


NOTE:
This method will remove all files and directories in the base path
Returns:
Expand All @@ -55,24 +60,32 @@ def init(self):
shutil.rmtree(path)
else:
os.unlink(path)

# convert SANs to template string
# example format: DNS.1 = example.com
subjectAltNames = os.linesep.join(['DNS.{} = {}'.format(idx, san) for idx, san in enumerate(subjectAltNames or [], start=1)])

# Prepare dirs and files
self.logger.info('Prepare dirs and files')
for name in self.DIRS:
os.mkdir(os.path.join(self.basePath, name))
with open(os.path.join(self.basePath, self.FILE_INDEX), 'wb') as fd:

with open(os.path.join(self.basePath, self.FILE_INDEX), 'w'):
pass
with open(os.path.join(self.basePath, self.FILE_SERIAL), 'wb') as fd:
print >>fd, 1000

with open(os.path.join(self.basePath, self.FILE_SERIAL), 'w') as fd:
fd.write(str(1000) + os.linesep)

# Format the config file
env = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
trim_blocks = True,
lstrip_blocks = True
loader=jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
trim_blocks=True,
lstrip_blocks=True
)
template = env.get_template('openssl.config.template')
content = template.render(basePath = self.basePath)
with open(os.path.join(self.basePath, self.FILE_CONFIG), 'wb') as fd:
print >>fd, content
content = template.render(basePath=self.basePath, subjectAltNames=subjectAltNames)
with open(os.path.join(self.basePath, self.FILE_CONFIG), 'w') as fd:
fd.write(content + os.linesep)
# Done

def verifyCertificate(self, name):
Expand All @@ -91,13 +104,17 @@ def createRootCertificate(self, noPass = False, keyLength = 4096):
os.path.join(self.basePath, self.FILE_CONFIG), \
os.path.join(self.basePath, self.DIR_PRIVATE, self.FILE_CA_KEY), \
os.path.join(self.basePath, self.DIR_CERTS, self.FILE_CA_CERT)

if os.path.isfile(keyPath):
raise ValueError('CA key file exists at [%s]' % keyPath)

if os.path.isfile(certPath):
raise ValueError('CA certificate file exists at [%s]' % certPath)

# Generate the key
if subprocess.call([ 'openssl', 'genrsa', '-aes256', '-out', keyPath, str(keyLength) ] if not noPass else [ 'openssl', 'genrsa', '-out', keyPath, str(keyLength) ]) != 0:
raise ValueError('Failed to create root key')

# Generate the cert
if subprocess.call([ 'openssl', 'req', '-config', configPath, '-key', keyPath, '-new', '-x509', '-days', '7300', '-sha256', '-extensions', 'v3_ca', '-out', certPath ]) != 0:
raise ValueError('Failed to create root certifcate')
Expand Down
8 changes: 7 additions & 1 deletion calib/openssl.config.template
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ new_certs_dir = $dir/newcerts
database = $dir/index.txt
serial = $dir/serial
RANDFILE = $dir/private/.rand
copy_extensions = copy

# The root key and root certificate.
private_key = $dir/private/ca.key.pem
Expand Down Expand Up @@ -88,12 +89,16 @@ localityName_default =
organizationalUnitName_default =
emailAddress_default =

[ alternate_names ]
{{ subjectAltNames }}

[ v3_ca ]
# Extensions for a typical CA (`man x509v3_config`).
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
keyUsage = critical, digitalSignature, cRLSign, keyCertSign, keyEncipherment
subjectAltName = @alternate_names

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA (`man x509v3_config`).
Expand Down Expand Up @@ -121,6 +126,7 @@ subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alternate_names

[ crl_ext ]
# Extension for CRLs (`man x509v3_config`).
Expand Down
2 changes: 1 addition & 1 deletion calib/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
"""The version file
"""

__version__ = '0.1.1'
__version__ = '0.1.2'