def get_certificates(): cert_list = [] try: certificates_dir, err = common.get_pki_dir() if err: raise Exception(err) if not certificates_dir: raise Exception('No certificates location defined') if not os.path.exists(certificates_dir): raise Exception('Certificates location does not exist') for dirname, dirnames, filenames in os.walk(certificates_dir): for subdirname in dirnames: cert_path = '%s/%s.cert'%(os.path.join(dirname, subdirname), subdirname) key_path = '%s/%s.key'%(os.path.join(dirname, subdirname), subdirname) if not os.path.exists(cert_path): continue cert_info, err = parse_certificate(cert_path) if err: continue d = {} d['name'] = subdirname d['certificate'] = cert_info cert_list.append(d) except Exception, e: return None, 'Error loading certificates : %s'%str(e)
def upload_certificate(d): try: pki_dir, err = common.get_pki_dir() if err: raise Exception(err) path = '%s/%s'%(pki_dir, d['name']) if os.path.exists(path): raise Exception('A key of that name already exists') os.mkdir(path) with open('%s/%s.cert'%(path, d['name']), 'w') as f: f.write('-----BEGIN PRIVATE KEY-----\n') key_lines = d['private_key'].split() if key_lines: for line in key_lines: f.write('%s\n'%line) f.write('-----END PRIVATE KEY-----\n') f.write('-----BEGIN CERTIFICATE-----\n') cert_lines = d['certificate'].split() if cert_lines: for line in cert_lines: f.write('%s\n'%line) f.write('-----END CERTIFICATE-----\n') except Exception, e: return False, 'Error uploading certificate : %s'%str(e)
def delete_certificate(name): try: pki_dir, err = common.get_pki_dir() if err: raise Exception(err) path = '%s/%s'%(pki_dir, name) if not os.path.exists(path): raise Exception('Specified certificate name does not exist') shutil.rmtree(path) except Exception, e: return False, 'Error deleting certificate : %s'%str(e)
def generate_self_signed_certificate(d): try: pki_dir, err = common.get_pki_dir() if err: raise Exception(err) path = '%s/%s'%(pki_dir, d['name']) if os.path.exists(path): raise Exception('A key of that name already exists') cmd = 'openssl req -new -newkey rsa:' if 'key_length' in d: key_length = int(d['key_length']) else: key_length = 1024 cmd = '%s%d'%(cmd, key_length) if 'days' in d: cmd = '%s -days %d'%(cmd, int(d['days'])) subj = '' if 'country' in d: subj = '%s/C=%s'%(subj, d['country']) if 'state' in d: subj = '%s/ST=%s'%(subj, d['state']) if 'location' in d: subj = '%s/L=%s'%(subj, d['location']) if 'o' in d: subj = '%s/O=%s'%(subj, d['o']) if 'ou' in d: subj = '%s/OU=%s'%(subj, d['ou']) if 'cn' in d: subj = '%s/CN=%s'%(subj, d['cn']) if 'email' in d: subj = '%s/emailAddress=%s'%(subj, d['email']) cmd += ' -nodes -x509 -subj %s -keyout %s/%s.cert -out %s/%s.cert'%(subj, path, d['name'], path, d['name']) #print cmd os.mkdir(path) lines, err = command.get_command_output(cmd) if err: if os.path.exists(path): shutil.rmtree(path) raise Exception(err) except Exception, e: return False, 'Error generating self signed certificate : %s'%str(e)