def create_certificate(self, csr, issuer_options): adcs_server = current_app.config.get('ADCS_SERVER') adcs_user = current_app.config.get('ADCS_USER') adcs_pwd = current_app.config.get('ADCS_PWD') adcs_auth_method = current_app.config.get('ADCS_AUTH_METHOD') adcs_template = current_app.config.get('ADCS_TEMPLATE') ca_server = Certsrv(adcs_server, adcs_user, adcs_pwd, auth_method=adcs_auth_method) current_app.logger.info("Requesting CSR: {0}".format(csr)) current_app.logger.info("Issuer options: {0}".format(issuer_options)) cert, req_id = ca_server.get_cert(csr, adcs_template, encoding='b64').decode('utf-8').replace('\r\n', '\n') chain = ca_server.get_ca_cert(encoding='b64').decode('utf-8').replace('\r\n', '\n') return cert, chain, req_id
def enroll(self, csr): """ enroll certificate from via MS certsrv """ self.logger.debug('CAhandler.enroll({0})'.format(self.template)) cert_bundle = None error = None cert_raw = None if self.host and self.user and self.password and self.template: # setup certserv ca_server = Certsrv(self.host, self.user, self.password, self.auth_method, self.ca_bundle) # check connection and credentials auth_check = self._check_credentials(ca_server) if auth_check: # recode csr csr = textwrap.fill(b64_url_recode(self.logger, csr), 64) + '\n' # get ca_chain try: ca_pkcs7 = convert_byte_to_string(ca_server.get_chain(encoding='b64')) ca_pem = self._pkcs7_to_pem(ca_pkcs7) # replace crlf with lf # ca_pem = ca_pem.replace('\r\n', '\n') except BaseException as err_: ca_pem = None self.logger.error('ca_server.get_chain() failed with error: {0}'.format(err_)) try: cert_raw = convert_byte_to_string(ca_server.get_cert(csr, self.template)) # replace crlf with lf cert_raw = cert_raw.replace('\r\n', '\n') except BaseException as err_: cert_raw = None self.logger.error('ca_server.get_cert() failed with error: {0}'.format(err_)) if ca_pem and cert_raw: cert_bundle = cert_raw + ca_pem cert_raw = cert_raw.replace('-----BEGIN CERTIFICATE-----\n', '') cert_raw = cert_raw.replace('-----END CERTIFICATE-----\n', '') cert_raw = cert_raw.replace('\n', '') else: self.logger.error('cert bundling failed') error = 'cert bundling failed' else: self.logger.error('Connection or Credentialcheck failed') error = 'Connection or Credentialcheck failed.' else: self.logger.error('Config incomplete') error = 'Config incomplete' self.logger.debug('Certificate.enroll() ended') return(error, cert_bundle, cert_raw, None)
def create_certificate(self, csr, issuer_options): adcs_server = current_app.config.get("ADCS_SERVER") adcs_user = current_app.config.get("ADCS_USER") adcs_pwd = current_app.config.get("ADCS_PWD") adcs_auth_method = current_app.config.get("ADCS_AUTH_METHOD") adcs_template = current_app.config.get("ADCS_TEMPLATE") ca_server = Certsrv(adcs_server, adcs_user, adcs_pwd, auth_method=adcs_auth_method) current_app.logger.info("Requesting CSR: {0}".format(csr)) current_app.logger.info("Issuer options: {0}".format(issuer_options)) cert = (ca_server.get_cert(csr, adcs_template, encoding="b64").decode("utf-8").replace( "\r\n", "\n")) chain = (ca_server.get_ca_cert(encoding="b64").decode("utf-8").replace( "\r\n", "\n")) return cert, chain, None
def enroll(self, csr): """ enroll certificate from via MS certsrv """ self.logger.debug('CAhandler.enroll()') cert_bundle = None error = None cert_raw = None if self.host and self.user and self.password and self.template: # setup certserv ca_server = Certsrv(self.host, self.user, self.password, self.auth_method, self.ca_bundle) # check connection and credentials auth_check = ca_server.check_credentials() if auth_check: # recode csr csr = textwrap.fill(b64_url_recode(self.logger, csr), 64) + '\n' # get ca_chain ca_pem = ca_server.get_chain(encoding='b64') cert_raw = ca_server.get_cert(csr, self.template) if cert_raw: cert_bundle = cert_raw + ca_pem cert_raw = cert_raw.replace( '-----BEGIN CERTIFICATE-----\n', '') cert_raw = cert_raw.replace('-----END CERTIFICATE-----\n', '') cert_raw = cert_raw.replace('\n', '') else: error = 'Enrollment failed' else: error = 'Connection or Credentialcheck failed.' else: error = 'Config incomplete' self.logger.debug('Certificate.enroll() ended') return (error, cert_bundle, cert_raw)
def create_certificate(self, csr, issuer_options): adcs_server = current_app.config.get("ADCS_SERVER") adcs_user = current_app.config.get("ADCS_USER") adcs_pwd = current_app.config.get("ADCS_PWD") adcs_auth_method = current_app.config.get("ADCS_AUTH_METHOD") # if there is a config variable ADCS_TEMPLATE_<upper(authority.name)> take the value as Cert template # else default to ADCS_TEMPLATE to be compatible with former versions authority = issuer_options.get("authority").name.upper() adcs_template = current_app.config.get( "ADCS_TEMPLATE_{0}".format(authority), current_app.config.get("ADCS_TEMPLATE")) ca_server = Certsrv(adcs_server, adcs_user, adcs_pwd, auth_method=adcs_auth_method) current_app.logger.info("Requesting CSR: {0}".format(csr)) current_app.logger.info("Issuer options: {0}".format(issuer_options)) cert = (ca_server.get_cert(csr, adcs_template, encoding="b64").decode("utf-8").replace( "\r\n", "\n")) chain = (ca_server.get_ca_cert(encoding="b64").decode("utf-8").replace( "\r\n", "\n")) return cert, chain, None
def install_msca_signed(self, ca_server: str, ca_user: str, ca_pass: str): # Create folder date = datetime.now().strftime('%Y%m%d%H%M%S') cert_dir = self.output_folder / date if not cert_dir.exists(): cert_dir.mkdir(parents=True) # File names cert_cfg_file = 'rui.cfg' cert_key_file = 'rui.key' cert_csr_file = 'rui.csr' cert_crt_file = 'rui.crt' cert_chain_file = 'rui-chain.crt' cert_crt_bak_file = 'rui.crt.bak' cert_key_bak_file = 'rui.key.bak' ca_crt_file = '../ca.crt' # Create local paths local_cfg = cert_dir / cert_cfg_file local_csr = cert_dir / cert_csr_file local_key = cert_dir / cert_key_file local_crt = cert_dir / cert_crt_file local_chain = cert_dir / cert_chain_file local_crt_bak = cert_dir / cert_crt_bak_file local_key_bak = cert_dir / cert_key_bak_file local_ca_crt = cert_dir / ca_crt_file # Remote temporary files remote_cfg = str(self.remote_tmp / cert_cfg_file) remote_csr = str(self.remote_tmp / cert_csr_file) remote_crt = str(self.remote_tmp / cert_crt_file) remote_chain = str(self.remote_tmp / cert_chain_file) remote_key = str(self.remote_tmp / cert_key_file) remote_ca_crt = str(self.remote_tmp / ca_crt_file) # Get the Microsoft Certificate Authority file ca_crt = get_msca_root_cert(hostname=ca_server, username=ca_user, password=ca_pass) local_ca_crt.write_bytes(ca_crt.public_bytes(encoding=serialization.Encoding.PEM)) # Connect to Microsoft Certificate Authority cert_srv = Certsrv(server=ca_server, username=ca_user, password=ca_pass, cafile=str(local_ca_crt)) cert_srv.check_credentials() self.connection.put(local=local_ca_crt, remote=remote_ca_crt) # Create host cfg config = create_cert_config(host=self.esx_server) local_cfg.write_text(config) self.connection.put(local=local_cfg, remote=remote_cfg) # Create certificate request cmd = f'openssl req -new -nodes -out {remote_csr} -keyout {remote_key} -config {remote_cfg}' result = self.connection.run(f"{cmd}", pty=True, hide=True) self.connection.get(local=local_csr, remote=remote_csr) self.connection.get(local=local_key, remote=remote_key) # Get signed certificate csr_bytes = local_csr.read_bytes() crt_bytes = cert_srv.get_cert(csr_bytes, 'WebServer') local_crt.write_bytes(crt_bytes) self.connection.put(local=local_crt, remote=remote_crt) # Create certificate chain cmd = f'cat {remote_crt} {remote_ca_crt} > {remote_chain}' result = self.connection.run(f'{cmd}', pty=True, hide=True) self.connection.get(local=local_chain, remote=remote_chain) # Backup current crt and key self.connection.get(local=local_crt_bak, remote=self.esx_crt) self.connection.get(local=local_key_bak, remote=self.esx_key) # Deploy new crt and key self.connection.put(local=local_chain, remote=self.esx_crt) self.connection.put(local=local_key, remote=self.esx_key) # Reboot host self.__reboot()
def generateCsr(email, dn): # get UPN and dn t = dn.split('|') # Add stop to dn dn = t[0] + ',end=end' userupn = t[1].encode() # browse UPN to generate CSR unit = dn.split(',') csr_cn_parts = [] csr_cn_partstmp = [] last = '' for u in unit: t = u.split('=') (name, value) = (t[0], t[1]) print((name, value)) # the x509 lib need to inverse OU orders, don't knwo why if name != last and len(csr_cn_partstmp) > 0: for element in reversed(csr_cn_partstmp): csr_cn_parts.append(element) csr_cn_partstmp = [] last = name if name == 'OU': csr_cn_partstmp.append( x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, value)) elif name == 'DC': csr_cn_partstmp.append( x509.NameAttribute(NameOID.DOMAIN_COMPONENT, value)) elif name == 'CN': csr_cn_partstmp.append( x509.NameAttribute(NameOID.COMMON_NAME, value)) csr_cn_parts = [x509.NameAttribute(NameOID.EMAIL_ADDRESS, email) ] + csr_cn_parts # Generate a key key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) bupn = b"\x0C" + bytes([len(userupn)]) + userupn # generate csr custom_oid_user_principal_name = x509.ObjectIdentifier( "1.3.6.1.4.1.311.20.2.3") csr = x509.CertificateSigningRequestBuilder( ).subject_name(x509.Name(csr_cn_parts)).add_extension( x509.SubjectAlternativeName([ x509.OtherName( custom_oid_user_principal_name, bupn ), # ASN.1 encoded string= (bytes) \x0C (UTF 8 String) + len(ASCII) + ASCII en hex ]), critical=False, ).sign(key, hashes.SHA256(), default_backend()) pem_req = csr.public_bytes(serialization.Encoding.PEM) # Get the cert from the ADCS server pem_req = csr.public_bytes(serialization.Encoding.PEM) ca_server = Certsrv("XXXXX", "XXXXXX", PASSWORD, auth_method="ntlm") pem_cert = ca_server.get_cert(pem_req, "User_ADFS_Script") # Print the key pem_key = key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) print(pem_key.decode()) print(pem_cert.decode())