Browse Source

fix whitespaces and indentations

master
Edoardo Putti 6 years ago
parent
commit
d3723a9ef8
9 changed files with 124 additions and 117 deletions
  1. +8
    -7
      bin/ca-server
  2. +4
    -2
      ca_manager/lookup.py
  3. +6
    -3
      ca_manager/manager.py
  4. +16
    -15
      ca_manager/models/authority.py
  5. +11
    -11
      ca_manager/models/certificate.py
  6. +1
    -1
      ca_manager/models/customModel.py
  7. +5
    -4
      ca_manager/models/request.py
  8. +24
    -27
      ca_manager/models/ssh.py
  9. +49
    -47
      ca_manager/models/ssl.py

+ 8
- 7
bin/ca-server View File

@ -10,16 +10,16 @@ import uuid
from ca_manager.paths import *
__doc__= """
__doc__ = """
Procedure to spawn a shell for automation, used by Ansible
"""
logfile= os.path.join(REQUEST_USER_HOME, 'request_server.log')
logfile = os.path.join(REQUEST_USER_HOME, 'request_server.log')
logging.basicConfig(
filename = logfile,
format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level = logging.INFO,
filename=logfile,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO,
)
logger = logging.getLogger('request_server')
@ -32,6 +32,7 @@ def exit_good(response):
print(json.dumps(response))
sys.exit(0)
def exit_bad(reason):
logger.info('JSON rejected, send error; error %s', reason)
response = {
@ -80,7 +81,7 @@ def main():
stream.write(json.dumps(request))
logger.info('Stopping shell')
exit_good({ 'requestID': request_id })
exit_good({'requestID': request_id})
elif metarequest['type'] == 'get_certificate':
logger.info('Got a GET request')
@ -96,7 +97,7 @@ def main():
result_data = stream.read()
logger.info('Stopping shell')
exit_good({ 'requestID': request_id, 'result': result_data })
exit_good({'requestID': request_id, 'result': result_data})
else:
logger.info('Request type not supported: %s', metarequest['type'])


+ 4
- 2
ca_manager/lookup.py View File

@ -14,6 +14,7 @@ from .models.request import SignRequest
from .paths import *
class CALookup:
"""
Proxy to interact with authorities
@ -30,11 +31,10 @@ class CALookup:
def __iter__(self):
all_the_authorities = [ auth.select().iterator() for auth in self.allowed_auth]
all_the_authorities = [auth.select().iterator() for auth in self.allowed_auth]
return chain.from_iterable(all_the_authorities)
def __getitem__(self, ca_id):
for authority_type in self.allowed_auth:
@ -44,6 +44,7 @@ class CALookup:
except authority_type.DoesNotExist:
continue
class RequestLookup:
"""
Proxy to interact with the requests
@ -123,6 +124,7 @@ class RequestLookup:
def ssl(self):
pass
class CertificateLookup:
"""
Proxy to interact with certificates


+ 6
- 3
ca_manager/manager.py View File

@ -17,9 +17,11 @@ from .models.certificate import Certificate
from .paths import *
__doc__ = """
Define classes to interact with certificate requests and Certification Authority
Define classes to interact with certificate
requests and Certification Authority
"""
class CAManager(object):
"""
Middleware to interact with ssh-keygen
@ -45,6 +47,7 @@ class CAManager(object):
def ssl_ca_dir(self):
return os.path.join(self.path, 'ssl_cas')
def init_manager(paths):
"""
Initiate the manager by creating the
@ -68,6 +71,7 @@ def init_manager(paths):
if not os.path.exists(dirpath):
os.mkdir(dirpath)
def sign_request(ca_manager, request_id, authority_id):
authority, request = None, None
@ -90,7 +94,7 @@ def sign_request(ca_manager, request_id, authority_id):
print("You are about to sign the following request:\n %s\nwith the following CA:\n %s"%(request, authority))
confirm = input('Proceed? (type yes)> ')
if confirm != 'yes':
print ("user abort")
print("user abort")
return
try:
@ -112,7 +116,6 @@ if __name__ == '__main__':
RESULTS_PATH,
])
ca_manager = CAManager(MANAGER_PATH)
CAManagerShell(ca_manager).cmdloop()

+ 16
- 15
ca_manager/models/authority.py View File

@ -13,10 +13,11 @@ from .certificate import Certificate
from ..paths import *
__doc__= """
__doc__ = """
Module of base classes to handle authorities
"""
class Authority(CustomModel):
signed_certificates = ReverseGFK(Certificate, 'authority_type', 'authority_id')
@ -27,25 +28,25 @@ class Authority(CustomModel):
active = BooleanField()
ca_id = CharField(
index = True,
unique = True,
index=True,
unique=True,
)
creation_date = DateTimeField(
help_text = 'authority creation date',
help_text='authority creation date',
)
name = CharField(
index = True,
help_text = 'authority descriptive name',
index=True,
help_text='authority descriptive name',
)
serial = IntegerField(
help_text = 'next certificate serial number',
help_text='next certificate serial number',
)
isRoot = BooleanField(
help_text = 'is root authority?',
help_text='is root authority?',
)
def __bool__(self):
@ -67,12 +68,12 @@ class Authority(CustomModel):
stream.write(request.key_data)
cert = Certificate(
authority = self,
cert_id = request.req_id,
date_issued = datetime.now(),
receiver = request.receiver,
serial_number = self.serial,
path = request.cert_destination,
authority=self,
cert_id=request.req_id,
date_issued=datetime.now(),
receiver=request.receiver,
serial_number=self.serial,
path=request.cert_destination,
)
cert.validity_interval = self.generate_certificate(request)
@ -85,4 +86,4 @@ class Authority(CustomModel):
raise NotImplementedError()
def __repr__(self):
return ( "%s %s (%s), created on %s" % ( self.__class__.__name__, self.ca_id, self.name, self.creation_date) )
return ('%s %s (%s), created on %s' % (self.__class__.__name__, self.ca_id, self.name, self.creation_date))

+ 11
- 11
ca_manager/models/certificate.py View File

@ -20,35 +20,35 @@ class Certificate(CustomModel):
authority = GFKField('authority_type', 'authority_id')
cert_id = CharField(
index = True,
unique = True,
help_text = 'id shared with the sign request',
index=True,
unique=True,
help_text='id shared with the sign request',
)
date_issued = DateTimeField(
help_text = 'certificate\'s issue date',
help_text='certificate\'s issue date',
)
receiver = CharField(
help_text = 'hostname or list of user for this certificate',
help_text='hostname or list of user for this certificate',
)
serial_number = IntegerField(
help_text = 'certificate\'s progressive number',
help_text='certificate\'s progressive number',
)
validity_interval = CharField(
help_text = 'how long will the certificate be valid',
help_text='how long will the certificate be valid',
)
path = CharField(
help_text = 'certificate\'s path on filesystem',
help_text='certificate\'s path on filesystem',
)
revoked = BooleanField(
index = True,
default = False,
help_text = 'certificate lifecycle state',
index=True,
default=False,
help_text='certificate lifecycle state',
)
def __repr__(self):


+ 1
- 1
ca_manager/models/customModel.py View File

@ -5,7 +5,7 @@ from ..paths import *
custom_db = SqliteDatabase(os.path.join(MANAGER_PATH, 'ca_manager.db'))
class CustomModel(Model):
class Meta:
database = custom_db

+ 5
- 4
ca_manager/models/request.py View File

@ -5,16 +5,17 @@ import os.path
from ..paths import *
__doc__= """
__doc__ = """
Module of classes to handle sign requests
"""
class SignRequest(object):
def __init__(self, req_id):
self.req_id = req_id
def __repr__(self):
return ( "%s %s with fields: %s" % (self.__class__.__name__, self.req_id, self.fields))
return ('%s %s with fields: %s' % (self.__class__.__name__, self.req_id, self.fields))
def __bool__(self):
return os.path.exists(self.path)
@ -33,7 +34,7 @@ class SignRequest(object):
@property
def destination(self):
return os.path.join(OUTPUT_PATH, self.req_id + ".pub")
return os.path.join(OUTPUT_PATH, self.req_id + '.pub')
@property
def cert_destination(self):
@ -42,5 +43,5 @@ class SignRequest(object):
@property
def fields(self):
return [
("Hostname", self.host_name)
('Hostname', self.host_name)
]

+ 24
- 27
ca_manager/models/ssh.py View File

@ -11,6 +11,7 @@ from .certificate import Certificate
from .request import SignRequest
from ..paths import *
class UserSSHRequest(SignRequest):
def __init__(self, req_id, user_name, root_requested, key_data):
super(UserSSHRequest, self).__init__(req_id)
@ -21,13 +22,13 @@ class UserSSHRequest(SignRequest):
@property
def name(self):
return "User: %s [R:%d]" % (self.user_name, int(self.root_requested))
return 'User: %s [R:%d]' % (self.user_name, int(self.root_requested))
@property
def fields(self):
return [
("User name", self.user_name),
("Root access requested", 'yes' if self.root_requested else 'no')
('User name', self.user_name),
('Root access requested', 'yes' if self.root_requested else 'no')
]
@property
@ -45,12 +46,12 @@ class HostSSHRequest(SignRequest):
@property
def name(self):
return "Hostname: %s" % self.host_name
return 'Hostname: %s' % self.host_name
@property
def fields(self):
return [
("Hostname", self.host_name)
('Hostname', self.host_name)
]
@property
@ -60,7 +61,7 @@ class HostSSHRequest(SignRequest):
class SSHAuthority(Authority):
request_allowed = [ UserSSHRequest, HostSSHRequest, ]
request_allowed = [UserSSHRequest, HostSSHRequest, ]
key_algorithm = 'ed25519'
@ -85,14 +86,13 @@ class SSHAuthority(Authority):
self.isRoot = True
# let ssh-keygen do its job
subprocess.check_output(['ssh-keygen',
'-f', self.path,
'-t', self.key_algorithm,
'-C', self.name])
'-f', self.path,
'-t', self.key_algorithm,
'-C', self.name])
else:
raise ValueError('A CA with the same id already exists')
def generate_certificate(self, request):
"""
Sign a *SSHRequest with this certification authority
@ -103,31 +103,28 @@ class SSHAuthority(Authority):
ca_private_key = self.path
if type(request) == UserSSHRequest:
login_names = [ request.user_name, ]
login_names = [request.user_name, ]
if request.root_requested:
login_names.append('root')
subprocess.check_output(['ssh-keygen',
'-s', ca_private_key,
'-I', 'user_%s' % request.receiver,
'-n', ','.join(login_names),
'-V', self.user_validity,
'-z', str(self.serial),
pub_key_path])
'-s', ca_private_key,
'-I', 'user_%s' % request.receiver,
'-n', ','.join(login_names),
'-V', self.user_validity,
'-z', str(self.serial),
pub_key_path])
validity_interval = self.user_validity
elif type(request) == HostSSHRequest:
subprocess.check_output(['ssh-keygen',
'-s', ca_private_key,
'-I', 'host_%s' % request.receiver.replace('.', '_'),
'-h',
'-n', request.host_name,
'-V', self.host_validity,
'-z', str(self.serial),
pub_key_path])
'-s', ca_private_key,
'-I', 'host_%s' % request.receiver.replace('.', '_'),
'-h',
'-n', request.host_name,
'-V', self.host_validity,
'-z', str(self.serial),
pub_key_path])
validity_interval = self.host_validity
return validity_interval

+ 49
- 47
ca_manager/models/ssl.py View File

@ -14,6 +14,7 @@ from ..paths import *
import json
class HostSSLRequest(SignRequest):
def __init__(self, req_id, host_name, key_data):
super(HostSSLRequest, self).__init__(req_id)
@ -23,18 +24,19 @@ class HostSSLRequest(SignRequest):
@property
def name(self):
return "Hostname: %s" % self.host_name
return 'Hostname: %s' % self.host_name
@property
def fields(self):
return [
("Hostname", self.host_name)
('Hostname', self.host_name)
]
@property
def receiver(self):
return self.host_name
class CASSLRequest(SignRequest):
def __init__(self, req_id, ca_name, key_data):
super(CASSLRequest, self).__init__(req_id)
@ -44,20 +46,21 @@ class CASSLRequest(SignRequest):
@property
def name(self):
return "CA name: %s" % self.ca_name
return 'CA name: %s' % self.ca_name
@property
def fields(self):
return [
("CA name", self.ca_name)
('CA name', self.ca_name)
]
@property
def receiver(self):
return self.ca_name
class SSLAuthority(Authority):
request_allowed = [ HostSSLRequest, CASSLRequest, ]
request_allowed = [HostSSLRequest, CASSLRequest, ]
ca_key_algorithm = 'des3'
key_length = '4096'
@ -69,7 +72,7 @@ class SSLAuthority(Authority):
def generate(self):
if os.path.exists(self.path):
raise ValueError("A CA with the same id and type already exists")
raise ValueError('A CA with the same id and type already exists')
confirm = input('Is a root CA? [y/N]> ')
if confirm == 'y':
self.isRoot = True
@ -77,55 +80,54 @@ class SSLAuthority(Authority):
self.isRoot = False
subprocess.check_output(['openssl',
'genrsa',
'-%s'%self.ca_key_algorithm,
'-out', '%s'%(self.path),
self.key_length])
'genrsa',
'-%s' % self.ca_key_algorithm,
'-out', '%s' % (self.path),
self.key_length])
if self.isRoot:
subprocess.check_output(['openssl',
'req',
'-extensions', 'v3_root_ca',
'-config', os.path.join(os.path.dirname(os.path.abspath(getsourcefile(lambda:0))), '../openssl-config/openssl.cnf'),
'-new',
'-x509',
'-days', self.root_ca_validity,
'-key', self.path,
# '-extensions', 'v3_ca'
'-out', "%s.pub"%self.path,
# '-config', "%s.conf"%self.path
])
'req',
'-extensions', 'v3_root_ca',
'-config', os.path.join(os.path.dirname(os.path.abspath(getsourcefile(lambda:0))), '../openssl-config/openssl.cnf'),
'-new',
'-x509',
'-days', self.root_ca_validity,
'-key', self.path,
# '-extensions', 'v3_ca'
'-out', '%s.pub' % self.path,
# '-config', "%s.conf"%self.path
])
else:
subprocess.check_output(['openssl',
'req',
'-new',
#'-x509',
# '-days', self.ca_validity,
'-key', self.path,
# '-extensions', 'v3_ca'
'-out', "%s.csr"%self.path,
# '-config', "%s.conf"%self.path
])
'req',
'-new',
#'-x509',
# '-days', self.ca_validity,
'-key', self.path,
# '-extensions', 'v3_ca'
'-out', '%s.csr' % self.path,
# '-config', "%s.conf"%self.path
])
result_dict = {}
result_dict['keyType'] = 'ssl_ca'
result_dict['caName'] = self.ca_id
with open("%s.csr"%self.path, 'r') as f:
with open("%s.csr" % self.path, 'r') as f:
result_dict['keyData'] = "".join(f.readlines())
request = { 'type': 'sign_request', 'request': result_dict }
print("Please sign the following request:")
request = {'type': 'sign_request', 'request': result_dict}
print('Please sign the following request:')
print(json.dumps(request))
with open(self.path + '.serial', 'w') as stream:
stream.write(str(0))
def generate_certificate(self, request):
"""
Sign a *SSLRequest with this certification authority
"""
if not os.path.exists("%s.pub"%self.path) and not self.isRoot:
raise ValueError("The CA certificate '%s.pub' doesn't exists yet"%self.path)
if not os.path.exists('%s.pub' % self.path) and not self.isRoot:
raise ValueError("The CA certificate '%s.pub' doesn't exists yet" % self.path)
pub_key_path = request.destination
cert_path = request.cert_destination
@ -134,18 +136,18 @@ class SSLAuthority(Authority):
stream.write(request.key_data)
subprocess.check_output(['openssl',
'x509',
'-req',
'-days', self.ca_validity,
'-in', pub_key_path,
'-CA', "%s.pub"%self.path,
'-CAkey', self.path,
'-CAcreateserial',
'-out', cert_path,
'-%s'%self.key_algorithm])
'x509',
'-req',
'-days', self.ca_validity,
'-in', pub_key_path,
'-CA', '%s.pub' % self.path,
'-CAkey', self.path,
'-CAcreateserial',
'-out', cert_path,
'-%s' % self.key_algorithm])
if not self.isRoot:
with open(cert_path, "a") as cert_file:
with open("%s.pub"%self.path) as ca_cert_file:
with open(cert_path, 'a') as cert_file:
with open('%s.pub' % self.path) as ca_cert_file:
cert_file.writelines(ca_cert_file.readlines())
return self.ca_validity

Loading…
Cancel
Save