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, connection: "ExtendedLdapConnection") -> None:
"""
Initialize the extended strategy with a connection.
Args:
connection: The ExtendedLdapConnection to use
"""
super().__init__(connection)
self._connection = connection
# Override the default receiving method to use the custom implementation
self.receiving = self._receiving
self.sequence_number = 0 |
Initialize the extended strategy with a connection.
Args:
connection: The ExtendedLdapConnection to use
| __init__ | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def sending(self, ldap_message: Any) -> None:
"""
Send an LDAP message, optionally encrypting it first.
Args:
ldap_message: The LDAP message to send
Raises:
socket.error: If sending fails
"""
try:
encoded_message = cast(bytes, ldap3_encode(ldap_message))
# Encrypt the message if required and not in SASL progress
if self._connection.should_encrypt and not self.connection.sasl_in_progress:
encoded_message = self._connection._encrypt(encoded_message)
self.sequence_number += 1
self.connection.socket.sendall(encoded_message)
except socket.error as e:
self.connection.last_error = f"socket sending error: {e}"
logging.error(f"Failed to send LDAP message: {e}")
handle_error()
raise
# Update usage statistics if enabled
if self.connection.usage:
self.connection._usage.update_transmitted_message(
self.connection.request, len(encoded_message)
) |
Send an LDAP message, optionally encrypting it first.
Args:
ldap_message: The LDAP message to send
Raises:
socket.error: If sending fails
| sending | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _receiving(self) -> List[bytes]: # type: ignore
"""
Receive data over the socket and handle message encryption/decryption.
Returns:
List of received LDAP messages
Raises:
Exception: On socket or receive errors
"""
messages = []
receiving = True
unprocessed = b""
data = b""
get_more_data = True
sasl_total_bytes_received = 0
sasl_received_data = b""
sasl_next_packet = b""
sasl_buffer_length = -1
while receiving:
if get_more_data:
try:
data = self.connection.socket.recv(self.socket_size)
except (OSError, socket.error, AttributeError) as e:
self.connection.last_error = f"error receiving data: {e}"
try:
self.close()
except (socket.error, LDAPExceptionError):
pass
logging.error(f"Failed to receive LDAP message: {e}")
handle_error()
raise
# Handle encrypted messages (from NTLM or Kerberos)
if (
self._connection.should_encrypt
and not self.connection.sasl_in_progress
):
data = sasl_next_packet + data
if sasl_received_data == b"" or sasl_next_packet:
# Get the size of the encrypted message
sasl_buffer_length = int.from_bytes(data[0:4], "big")
data = data[4:]
sasl_next_packet = b""
sasl_total_bytes_received += len(data)
sasl_received_data += data
# Check if we have received the complete encrypted message
if sasl_total_bytes_received >= sasl_buffer_length:
# Handle multi-packet SASL messages
# When the LDAP response is split across multiple TCP packets,
# the SASL buffer length might not match our socket buffer size
sasl_next_packet = sasl_received_data[sasl_buffer_length:]
# Decrypt the received message
sasl_received_data = self._connection._decrypt(
sasl_received_data[:sasl_buffer_length]
)
sasl_total_bytes_received = 0
unprocessed += sasl_received_data
sasl_received_data = b""
else:
unprocessed += data
if len(data) > 0:
# Try to compute the message length
length = BaseStrategy.compute_ldap_message_size(unprocessed)
if length == -1: # too few data to decode message length
get_more_data = True
continue
if len(unprocessed) < length:
get_more_data = True
else:
messages.append(unprocessed[:length])
unprocessed = unprocessed[length:]
get_more_data = False
if len(unprocessed) == 0:
receiving = False
else:
receiving = False
return messages |
Receive data over the socket and handle message encryption/decryption.
Returns:
List of received LDAP messages
Raises:
Exception: On socket or receive errors
| _receiving | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def __init__(
self, target: Target, *args: Any, channel_binding: bool = True, **kwargs: Any
) -> None:
"""
Initialize an extended LDAP connection with the specified target.
Args:
target: Target object containing connection details
channel_binding: Whether to use channel binding (default: True)
*args: Additional positional arguments for the parent class
**kwargs: Additional keyword arguments for the parent class
"""
super().__init__(*args, **kwargs)
# Replace standard strategy with extended strategy
self.strategy = ExtendedStrategy(self)
# Store target and connection properties
self.target = target
self.channel_binding = channel_binding
self.negotiated_flags = 0
# Encryption-related attributes
self.ntlm_cipher: Optional[NTLMCipher] = None
self.kerberos_cipher: Optional[KerberosCipher] = None
self.should_encrypt = False
# Alias important methods from strategy for direct access
self.send = self.strategy.send
self.open = self.strategy.open
self.get_response = self.strategy.get_response
self.post_send_single_response = self.strategy.post_send_single_response
self.post_send_search = self.strategy.post_send_search |
Initialize an extended LDAP connection with the specified target.
Args:
target: Target object containing connection details
channel_binding: Whether to use channel binding (default: True)
*args: Additional positional arguments for the parent class
**kwargs: Additional keyword arguments for the parent class
| __init__ | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _encrypt(self, data: bytes) -> bytes:
"""
Encrypt LDAP message data using the appropriate cipher.
Args:
data: Plaintext data to encrypt
Returns:
Encrypted data with appropriate headers and signatures
"""
if self.ntlm_cipher is not None:
# NTLM encryption
signature, data = self.ntlm_cipher.encrypt(data)
data = signature.getData() + data
data = len(data).to_bytes(4, byteorder="big", signed=False) + data
elif self.kerberos_cipher is not None:
# Kerberos encryption
data, signature = self.kerberos_cipher.encrypt(
data, self.strategy.sequence_number
)
data = signature + data
data = len(data).to_bytes(4, byteorder="big", signed=False) + data
return data |
Encrypt LDAP message data using the appropriate cipher.
Args:
data: Plaintext data to encrypt
Returns:
Encrypted data with appropriate headers and signatures
| _encrypt | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _decrypt(self, data: bytes) -> bytes:
"""
Decrypt LDAP message data using the appropriate cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext data
"""
if self.ntlm_cipher is not None:
# NTLM decryption
_, data = self.ntlm_cipher.decrypt(data)
elif self.kerberos_cipher is not None:
# Kerberos decryption
data = self.kerberos_cipher.decrypt(data)
return data |
Decrypt LDAP message data using the appropriate cipher.
Args:
data: Encrypted data to decrypt
Returns:
Decrypted plaintext data
| _decrypt | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def do_ntlm_bind(self, controls: Any) -> Dict[str, Any]:
"""
Perform NTLM bind operation with optional controls.
This method implements the complete NTLM authentication flow:
1. Sicily package discovery to verify NTLM support
2. NTLM negotiate message exchange
3. Challenge/response handling with optional channel binding
4. Session key establishment and encryption setup
Args:
controls: Optional LDAP controls to apply during the bind operation
Returns:
Result of the bind operation
Raises:
Exception: If NTLM authentication fails or is not supported
"""
self.last_error = None # type: ignore
with self.connection_lock:
if not self.sasl_in_progress:
self.sasl_in_progress = True # NTLM uses SASL-like authentication flow
try:
# Step 1: Sicily package discovery to check for NTLM support
request = rfc4511.BindRequest()
request["version"] = rfc4511.Version(self.version)
request["name"] = ""
request[
"authentication"
] = rfc4511.AuthenticationChoice().setComponentByName(
"sicilyPackageDiscovery", rfc4511.SicilyPackageDiscovery("")
)
response = self.post_send_single_response(
self.send("bindRequest", request, controls)
)
result = response[0]
if not "server_creds" in result:
raise Exception(
"Server did not return available authentication packages during discovery request"
)
# Check if NTLM is supported
sicily_packages = result["server_creds"].decode().split(";")
if not "NTLM" in sicily_packages:
logging.error(
f"NTLM authentication not available on server. Supported packages: {sicily_packages}"
)
raise Exception("NTLM not available on server")
# Step 2: Send NTLM negotiate message
use_signing = self.target.ldap_signing and not self.server.ssl
logging.debug(
f"Using NTLM signing: {use_signing} (LDAP signing: {self.target.ldap_signing}, SSL: {self.server.ssl})"
)
negotiate = ntlm_negotiate(use_signing)
request = rfc4511.BindRequest()
request["version"] = rfc4511.Version(self.version)
request["name"] = "NTLM"
request[
"authentication"
] = rfc4511.AuthenticationChoice().setComponentByName(
"sicilyNegotiate", rfc4511.SicilyNegotiate(negotiate.getData())
)
response = self.post_send_single_response(
self.send("bindRequest", request, controls)
)
result = response[0]
if result["result"] != RESULT_SUCCESS:
logging.error(f"NTLM negotiate failed: {result}")
return result
if not "server_creds" in result:
logging.error(
"Server did not return NTLM challenge during bind request"
)
raise Exception(
"Server did not return NTLM challenge during bind request"
)
# Step 3: Process challenge and prepare authenticate response
challenge = NTLMAuthChallenge()
challenge.fromString(result["server_creds"])
channel_binding_data = None
use_channel_binding = (
self.target.ldap_channel_binding and self.server.ssl
)
logging.debug(
f"Using channel binding signing: {use_channel_binding} (LDAP channel binding: {self.target.ldap_channel_binding}, SSL: {self.server.ssl})"
)
if use_channel_binding:
if not isinstance(self.socket, ssl.SSLSocket):
raise Exception(
"LDAP server is using SSL but the connection is not an SSL socket"
)
logging.debug(
"Using LDAP channel binding for NTLM authentication"
)
# Extract channel binding data from SSL socket
channel_binding_data = get_channel_binding_data_from_ssl_socket(
self.socket
)
# Generate NTLM authenticate message
challenge_response, session_key, negotiated_flags = (
ntlm_authenticate(
negotiate,
challenge,
self.target.username,
self.target.password or "",
self.target.domain,
self.target.nthash,
channel_binding_data=channel_binding_data,
)
)
# Step 4: Set up encryption if negotiated
self.negotiated_flags = negotiated_flags
self.should_encrypt = (
negotiated_flags & NTLMSSP_NEGOTIATE_SEAL
== NTLMSSP_NEGOTIATE_SEAL
)
if self.should_encrypt:
self.ntlm_cipher = NTLMCipher(
negotiated_flags,
session_key,
)
# Step 5: Complete authentication with the NTLM authenticate message
request = rfc4511.BindRequest()
request["version"] = rfc4511.Version(self.version)
request["name"] = ""
request[
"authentication"
] = rfc4511.AuthenticationChoice().setComponentByName(
"sicilyResponse",
rfc4511.SicilyResponse(challenge_response.getData()),
)
response = self.post_send_single_response(
self.send("bindRequest", request, controls)
)
result = response[0]
if result["result"] != RESULT_SUCCESS:
logging.error(f"LDAP NTLM authentication failed: {result}")
else:
logging.debug(f"LDAP NTLM authentication successful")
return result
finally:
self.sasl_in_progress = False
else:
raise Exception("SASL authentication already in progress") |
Perform NTLM bind operation with optional controls.
This method implements the complete NTLM authentication flow:
1. Sicily package discovery to verify NTLM support
2. NTLM negotiate message exchange
3. Challenge/response handling with optional channel binding
4. Session key establishment and encryption setup
Args:
controls: Optional LDAP controls to apply during the bind operation
Returns:
Result of the bind operation
Raises:
Exception: If NTLM authentication fails or is not supported
| do_ntlm_bind | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def __init__(
self,
target: Target,
schannel_auth: Optional[Tuple[x509.Certificate, PrivateKeyTypes]] = None,
) -> None:
"""
Initialize an LDAP connection with the specified target.
Args:
target: Target object containing connection details
ldap_pfx: Optional tuple containing LDAP PFX file path and password
"""
self.target = target
self.schannel_auth = schannel_auth
self.use_ssl = target.ldap_scheme == "ldaps"
# Determine port based on scheme and target configuration
if self.use_ssl:
self.port = int(target.ldap_port) if target.ldap_port is not None else 636
else:
self.port = int(target.ldap_port) if target.ldap_port is not None else 389
# Connection-related attributes
self.default_path: Optional[str] = None
self.configuration_path: Optional[str] = None
self.ldap_server: Optional[ldap3.Server] = None
self.ldap_conn: Optional[Union["ExtendedLdapConnection", ldap3.Connection]] = (
None
)
self.domain: Optional[str] = None
# Caching and tracking
self.sid_map: Dict[str, LDAPEntry] = {}
self._domain_sid: Optional[str] = None
self._users: Dict[str, LDAPEntry] = {}
self._user_sids: Dict[str, Set[str]] = {}
self.warned_missing_domain_sid_lookup: bool = False |
Initialize an LDAP connection with the specified target.
Args:
target: Target object containing connection details
ldap_pfx: Optional tuple containing LDAP PFX file path and password
| __init__ | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def connect(self) -> None:
"""
Connect to the LDAP server with the specified SSL/TLS version.
This method establishes a connection to the LDAP server and handles
authentication using the credentials from the target object.
It supports multiple authentication methods:
- Kerberos
- NTLM
- Simple bind
Raises:
Exception: If connection or authentication fails
"""
if self.target.target_ip is None:
raise Exception("Target IP is not set")
if self.schannel_auth is not None:
return self.schannel_connect()
# Format user credentials
user = f"{self.target.domain}\\{self.target.username}"
user_upn = f"{self.target.username}@{self.target.domain}"
# Create server object based on scheme
if self.use_ssl:
# Configure TLS for LDAPS
tls = ldap3.Tls(
validate=ssl.CERT_NONE,
version=ssl.PROTOCOL_TLS_CLIENT,
ciphers="ALL:@SECLEVEL=0",
ssl_options=[ssl.OP_ALL],
)
ldap_server = ldap3.Server(
self.target.target_ip,
use_ssl=True,
port=self.port,
get_info=ldap3.ALL,
tls=tls,
connect_timeout=self.target.timeout,
)
else:
ldap_server = ldap3.Server(
self.target.target_ip,
use_ssl=False,
port=self.port,
get_info=ldap3.ALL,
connect_timeout=self.target.timeout,
)
# Authentication based on method
if self.target.do_kerberos:
logging.debug("Authenticating to LDAP server using Kerberos authentication")
# Create connection for Kerberos authentication
ldap_conn = ExtendedLdapConnection(
self.target,
ldap_server,
receive_timeout=self.target.timeout * 10,
)
self._kerberos_login(ldap_conn)
else:
auth_method = "SIMPLE" if self.target.do_simple else "NTLM"
logging.debug(
f"Authenticating to LDAP server using {auth_method} authentication"
)
# Set up credentials for NTLM or simple authentication
if self.target.hashes is not None:
ldap_pass = f"{self.target.lmhash}:{self.target.nthash}"
else:
ldap_pass = self.target.password
# Create connection
ldap_conn = ExtendedLdapConnection(
self.target,
ldap_server,
user=user_upn if self.target.do_simple else user,
password=ldap_pass,
authentication=ldap3.SIMPLE if self.target.do_simple else ldap3.NTLM,
auto_referrals=False,
receive_timeout=self.target.timeout * 10,
)
# Perform bind operation if not already bound
if not ldap_conn.bound:
bind_result = ldap_conn.bind()
if not bind_result:
result = ldap_conn.result
self._check_ldap_result(result)
# Get schema information if not already available
if ldap_server.schema is None:
ldap_server.get_info_from_server(ldap_conn)
if ldap_conn.result["result"] != RESULT_SUCCESS:
if ldap_conn.result["message"].split(":")[0] == "000004DC":
raise Exception(
"Failed to bind to LDAP. This is most likely due to an invalid username"
)
if ldap_server.schema is None:
raise Exception("Failed to get LDAP schema")
logging.debug(f"Bound to {ldap_server}")
# Store connection objects and directory paths
self.ldap_conn = ldap_conn
self.ldap_server = ldap_server
self.default_path = self.ldap_server.info.other["defaultNamingContext"][0]
self.configuration_path = self.ldap_server.info.other[
"configurationNamingContext"
][0]
logging.debug(f"Default path: {self.default_path}")
logging.debug(f"Configuration path: {self.configuration_path}")
# Extract domain name from LDAP service name
self.domain = self.ldap_server.info.other["ldapServiceName"][0].split("@")[-1] |
Connect to the LDAP server with the specified SSL/TLS version.
This method establishes a connection to the LDAP server and handles
authentication using the credentials from the target object.
It supports multiple authentication methods:
- Kerberos
- NTLM
- Simple bind
Raises:
Exception: If connection or authentication fails
| connect | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _kerberos_login(self, connection: "ExtendedLdapConnection") -> None:
"""
Perform Kerberos authentication to LDAP server.
Args:
connection: LDAP connection object
Raises:
Exception: If Kerberos authentication fails
"""
# Ensure connection is open
if connection.closed:
connection.open(read_server_info=True)
# Setup channel binding if enabled and using SSL
channel_binding_data = None
if self.target.ldap_channel_binding and connection.server.ssl:
logging.debug("Using LDAP channel binding for Kerberos authentication")
if not isinstance(connection.socket, ssl.SSLSocket):
raise Exception(
"LDAP server is using SSL but the connection is not an SSL socket"
)
# Extract channel binding data from SSL socket
channel_binding_data = get_channel_binding_data_from_ssl_socket(
connection.socket
)
# Get Kerberos Type 1 message
cipher, session_key, blob, username = get_kerberos_type1(
self.target,
target_name=self.target.remote_name or "",
channel_binding_data=channel_binding_data,
signing=self.target.ldap_signing and not connection.server.ssl,
)
# Create SASL bind request
request = bind_operation(
connection.version,
ldap3.SASL,
username,
None,
"GSS-SPNEGO",
blob,
)
# Send bind request and process response
connection.sasl_in_progress = True
response = connection.post_send_single_response(
connection.send("bindRequest", request, None)
)
connection.sasl_in_progress = False
result = response[0]
if result["result"] != RESULT_SUCCESS:
logging.error(f"LDAP Kerberos authentication failed: {result}")
else:
logging.debug(f"LDAP Kerberos authentication successful")
self._check_ldap_result(result)
# Set up encryption if signing is requested
if self.target.ldap_signing and not connection.server.ssl:
connection.kerberos_cipher = KerberosCipher(cipher, session_key)
connection.should_encrypt = self.target.ldap_signing
connection.bound = True |
Perform Kerberos authentication to LDAP server.
Args:
connection: LDAP connection object
Raises:
Exception: If Kerberos authentication fails
| _kerberos_login | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _check_ldap_result(self, result: Dict[str, Any]) -> None:
"""
Handle LDAP errors based on the result dictionary.
Args:
result: Result dictionary from the LDAP bind operation
Raises:
Exception: If an error occurs during the LDAP operation
"""
if result["result"] != RESULT_SUCCESS:
if (
result["result"] == RESULT_INVALID_CREDENTIALS
and result["message"].split(":")[0] == "80090346"
):
raise Exception(
(
"LDAP authentication refused because channel binding policy was not satisfied. "
"Try one of these options:\n"
"- Remove '-no-ldap-channel-binding'\n"
"- Use '-ldap-scheme ldap' to disable TLS encryption\n"
"- Use '-ldap-simple-auth' for SIMPLE bind authentication"
)
)
elif (
result["result"] == RESULT_STRONGER_AUTH_REQUIRED
and result["message"].split(":")[0] == "00002028"
):
raise Exception(
"LDAP authentication refused because LDAP signing is required. "
"Try one of these options:\n"
"- Remove '-no-ldap-signing' to enable LDAP signing\n"
"- Use '-ldap-scheme ldaps' to use TLS encryption\n"
"- Use '-ldap-simple-auth' for SIMPLE bind authentication"
)
raise Exception(f"Kerberos authentication failed: {result}") |
Handle LDAP errors based on the result dictionary.
Args:
result: Result dictionary from the LDAP bind operation
Raises:
Exception: If an error occurs during the LDAP operation
| _check_ldap_result | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def add(self, *args: Any, **kwargs: Any) -> Any:
"""
Add a new entry to the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP add operation
**kwargs: Keyword arguments to pass to the underlying LDAP add operation
Returns:
Result of the add operation
Raises:
Exception: If LDAP connection is not established
"""
if not self.ldap_conn:
raise Exception("LDAP connection is not established")
self.ldap_conn.add(*args, **kwargs)
return self.ldap_conn.result |
Add a new entry to the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP add operation
**kwargs: Keyword arguments to pass to the underlying LDAP add operation
Returns:
Result of the add operation
Raises:
Exception: If LDAP connection is not established
| add | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def delete(self, *args: Any, **kwargs: Any) -> Any:
"""
Delete an entry from the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP delete operation
**kwargs: Keyword arguments to pass to the underlying LDAP delete operation
Returns:
Result of the delete operation
Raises:
Exception: If LDAP connection is not established
"""
if not self.ldap_conn:
raise Exception("LDAP connection is not established")
self.ldap_conn.delete(*args, **kwargs)
return self.ldap_conn.result |
Delete an entry from the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP delete operation
**kwargs: Keyword arguments to pass to the underlying LDAP delete operation
Returns:
Result of the delete operation
Raises:
Exception: If LDAP connection is not established
| delete | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def modify(self, *args: Any, **kwargs: Any) -> Any:
"""
Modify an existing entry in the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP modify operation
**kwargs: Keyword arguments to pass to the underlying LDAP modify operation
Returns:
Result of the modify operation
Raises:
Exception: If LDAP connection is not established
"""
if not self.ldap_conn:
raise Exception("LDAP connection is not established")
self.ldap_conn.modify(*args, **kwargs)
return self.ldap_conn.result |
Modify an existing entry in the LDAP directory.
Args:
*args: Arguments to pass to the underlying LDAP modify operation
**kwargs: Keyword arguments to pass to the underlying LDAP modify operation
Returns:
Result of the modify operation
Raises:
Exception: If LDAP connection is not established
| modify | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def search(
self,
search_filter: str,
attributes: Union[str, List[str]] = ldap3.ALL_ATTRIBUTES,
search_base: Optional[str] = None,
query_sd: bool = False,
**kwargs: Any,
) -> List[LDAPEntry]:
"""
Search the LDAP directory with the given filter and return matching entries.
Args:
search_filter: LDAP search filter string
attributes: List of attributes to retrieve or ldap3.ALL_ATTRIBUTES
search_base: Base DN for the search, defaults to domain base
query_sd: Whether to query security descriptors
**kwargs: Additional arguments for the search operation
Returns:
List of matching LDAP entries
Raises:
Exception: If LDAP connection is not established
"""
if search_base is None:
search_base = self.default_path
# Set security descriptor control if requested
if query_sd:
controls = security_descriptor_control(sdflags=0x5)
else:
controls = None
if self.ldap_conn is None:
raise Exception("LDAP connection is not established")
# Perform paged search to handle large result sets
results = self.ldap_conn.extend.standard.paged_search(
search_base=search_base,
search_filter=search_filter,
attributes=attributes,
controls=controls,
paged_size=200,
generator=True,
**kwargs,
)
if self.ldap_conn.result["result"] != 0:
logging.warning(
f"LDAP search {search_filter!r} failed: "
f"({self.ldap_conn.result['description']}) {self.ldap_conn.result['message']}"
)
return []
# Convert search results to LDAPEntry objects
entries = list(
map(
lambda entry: LDAPEntry(**entry),
filter(
lambda entry: entry["type"] == "searchResEntry",
results,
),
)
)
return entries |
Search the LDAP directory with the given filter and return matching entries.
Args:
search_filter: LDAP search filter string
attributes: List of attributes to retrieve or ldap3.ALL_ATTRIBUTES
search_base: Base DN for the search, defaults to domain base
query_sd: Whether to query security descriptors
**kwargs: Additional arguments for the search operation
Returns:
List of matching LDAP entries
Raises:
Exception: If LDAP connection is not established
| search | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def get_user(
self, username: str, silent: bool = False, *args: Any, **kwargs: Any
) -> Optional[LDAPEntry]:
"""
Find a user by samAccountName.
This method searches for a user by samAccountName and automatically
handles computer account naming ($) if needed.
Args:
username: Username to search for (samAccountName)
silent: Whether to suppress error logging for missing users
*args: Additional arguments for the search
**kwargs: Additional keyword arguments for the search
Returns:
User entry or None if not found
"""
def _get_user(username: str, *args: Any, **kwargs: Any) -> Optional[LDAPEntry]:
"""Helper function to search for a user, with caching."""
sanitized_username = username.lower().strip()
# Return cached result if available
if sanitized_username in self._users:
return self._users[sanitized_username]
# Search for the user
results = self.search(f"(sAMAccountName={username})", *args, **kwargs)
if len(results) != 1:
return None
# Cache the result
self._users[sanitized_username] = results[0]
return results[0]
# Try without $ suffix first
user = _get_user(username, *args, **kwargs)
# Try with $ suffix (for computer accounts)
if user is None and not username.endswith("$"):
user = _get_user(f"{username}$", *args, **kwargs)
# Log error if user not found and silent mode is not enabled
if user is None and not silent:
logging.error(f"Could not find user {username!r}")
return user |
Find a user by samAccountName.
This method searches for a user by samAccountName and automatically
handles computer account naming ($) if needed.
Args:
username: Username to search for (samAccountName)
silent: Whether to suppress error logging for missing users
*args: Additional arguments for the search
**kwargs: Additional keyword arguments for the search
Returns:
User entry or None if not found
| get_user | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def _get_user(username: str, *args: Any, **kwargs: Any) -> Optional[LDAPEntry]:
"""Helper function to search for a user, with caching."""
sanitized_username = username.lower().strip()
# Return cached result if available
if sanitized_username in self._users:
return self._users[sanitized_username]
# Search for the user
results = self.search(f"(sAMAccountName={username})", *args, **kwargs)
if len(results) != 1:
return None
# Cache the result
self._users[sanitized_username] = results[0]
return results[0] | Helper function to search for a user, with caching. | _get_user | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def domain_sid(self) -> Optional[str]:
"""
Get the domain's security identifier (SID).
The domain SID is the base identifier used for all domain security principals.
Returns:
Domain SID or None if not found
"""
# Return cached value if available
if self._domain_sid is not None:
return self._domain_sid
# Query domain object for SID
results = self.search(
"(objectClass=domain)",
attributes=["objectSid"],
)
if len(results) != 1:
return None
result = results[0]
domain_sid = result.get("objectSid")
# Cache the result
self._domain_sid = domain_sid
return domain_sid |
Get the domain's security identifier (SID).
The domain SID is the base identifier used for all domain security principals.
Returns:
Domain SID or None if not found
| domain_sid | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def get_user_sids(
self,
username: str,
user_sid: Optional[str] = None,
user_dn: Optional[str] = None,
) -> Set[str]:
"""
Get all SIDs associated with a user, including groups.
This method collects all security identifiers (SIDs) that apply to a user,
including the user's personal SID, well-known SIDs, primary group SID,
and all group memberships (direct and nested).
Args:
username: Username to look up
user_sid: Optional SID to use if user lookup fails
user_dn: Optional DN to use if user lookup fails
Returns:
Set of SIDs the user belongs to
"""
# Return cached value if available
sanitized_username = username.lower().strip()
if sanitized_username in self._user_sids:
return self._user_sids[sanitized_username]
# Get user object or create minimal one if not found
user = self.get_user(username)
if not user:
user = {"objectSid": user_sid, "distinguishedName": user_dn}
if not user_sid:
logging.warning(
"User SID can't be retrieved. For more accurate results, add it manually with -sid"
)
# Start with basic SIDs
sids: Set[str] = set()
# Add user's own SID
object_sid = user.get("objectSid")
if object_sid:
sids.add(object_sid)
# Add well-known SIDs: Everyone, Authenticated Users, Users
sids |= {"S-1-1-0", "S-1-5-11", "S-1-5-32-545"}
# Add primary group (usually Domain Users)
primary_group_id = user.get("primaryGroupID")
if primary_group_id is not None and self.domain_sid:
sids.add(f"{self.domain_sid}-{primary_group_id}")
# Add Domain Users and Domain Computers group
if self.domain_sid:
logging.debug(
"Adding 'Domain Users' and 'Domain Computers' to list of current user's SIDs"
)
sids.add(f"{self.domain_sid}-513") # Domain Users
sids.add(f"{self.domain_sid}-515") # Domain Computers
# Collect DNs to search for group membership
dns = [user.get("distinguishedName")]
for sid in sids:
object_entry = self.lookup_sid(sid)
if "dn" in object_entry:
dns.append(object_entry["dn"])
# Build LDAP query for nested group membership (LDAP_MATCHING_RULE_IN_CHAIN)
member_of_queries = []
for dn in dns:
if dn: # Skip None values
member_of_queries.append(f"(member:1.2.840.113556.1.4.1941:={dn})")
if member_of_queries:
try:
# Query for nested group membership
groups = self.search(
f"(|{''.join(member_of_queries)})",
attributes="objectSid",
)
# Add all group SIDs to the set
for group in groups:
sid = group.get("objectSid")
if sid is not None:
sids.add(sid)
except Exception as e:
logging.warning(f"Failed to get user SIDs: {e}")
logging.warning("Try increasing -timeout parameter value")
handle_error(True)
# Cache the results
self._user_sids[sanitized_username] = sids
# Debug output of collected SIDs
logging.debug(f"User {username!r} has {len(sids)} SIDs:")
for sid in sids:
logging.debug(f" {sid}")
return sids |
Get all SIDs associated with a user, including groups.
This method collects all security identifiers (SIDs) that apply to a user,
including the user's personal SID, well-known SIDs, primary group SID,
and all group memberships (direct and nested).
Args:
username: Username to look up
user_sid: Optional SID to use if user lookup fails
user_dn: Optional DN to use if user lookup fails
Returns:
Set of SIDs the user belongs to
| get_user_sids | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def lookup_sid(self, sid: str) -> LDAPEntry:
"""
Look up an object by its SID.
This method finds an Active Directory object by its security identifier,
or returns a synthetic entry for well-known SIDs.
Args:
sid: Security identifier to look up
Returns:
LDAPEntry for the object, or a synthetic entry for well-known SIDs
Raises:
Exception: If LDAP connection is not established
"""
# Return cached value if available
if sid in self.sid_map:
return self.sid_map[sid]
# Handle well-known SIDs
if sid in WELLKNOWN_SIDS:
if self.domain is None and not self.warned_missing_domain_sid_lookup:
self.warned_missing_domain_sid_lookup = True
logging.warning(
"Domain is not set for LDAP connection. This may cause issues when looking up SIDs"
)
# Create synthetic entry for well-known SID
entry = LDAPEntry(
**{
"attributes": {
"objectSid": f"{(self.domain or '').upper()}-{sid}",
"objectType": WELLKNOWN_SIDS[sid][1].capitalize(),
"name": f"{self.domain}\\{WELLKNOWN_SIDS[sid][0]}",
}
}
)
self.sid_map[sid] = entry
return entry
# For regular SIDs, query the directory
attributes = [
"sAMAccountType",
"name",
"objectSid",
"distinguishedName",
"objectClass",
]
if self.ldap_conn is None:
raise Exception("LDAP connection is not established")
# Only request msDS-GroupMSAMembership when it exists in the schema
if (
self.ldap_conn.server.schema
and "msDS-GroupMSAMembership"
in self.ldap_conn.server.schema.attribute_types
):
attributes.append("msDS-GroupMSAMembership")
# Search for object with the given SID
results = self.search(
f"(objectSid={sid})",
attributes=attributes,
)
# Handle results
if len(results) != 1:
logging.warning(f"Failed to lookup object with SID {sid!r}")
# Create synthetic entry for unknown SID
entry = LDAPEntry(
**{
"attributes": {
"objectSid": sid,
"name": sid,
"objectType": "Unknown",
}
}
)
else:
# Process found entry
entry = results[0]
entry.set("name", f"{self.domain}\\{entry.get('name')}")
entry.set("objectType", get_account_type(entry))
# Cache the result
self.sid_map[sid] = entry
return entry |
Look up an object by its SID.
This method finds an Active Directory object by its security identifier,
or returns a synthetic entry for well-known SIDs.
Args:
sid: Security identifier to look up
Returns:
LDAPEntry for the object, or a synthetic entry for well-known SIDs
Raises:
Exception: If LDAP connection is not established
| lookup_sid | python | ly4k/Certipy | certipy/lib/ldap.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ldap.py | MIT |
def set_verbose(is_verbose: bool) -> None:
"""
Set the verbosity level for logging.
Args:
is_verbose: Boolean indicating whether to enable verbose logging
"""
global _IS_VERBOSE
_IS_VERBOSE = is_verbose # type: ignore |
Set the verbosity level for logging.
Args:
is_verbose: Boolean indicating whether to enable verbose logging
| set_verbose | python | ly4k/Certipy | certipy/lib/logger.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/logger.py | MIT |
def format(self, record: _logging.LogRecord) -> str:
"""
Format the log record by adding an appropriate bullet point.
Args:
record: The log record to format
Returns:
Formatted log message with bullet point prefix
"""
# Add bullet point based on log level, defaulting to "[-]" for unknown levels
record.bullet = BULLET_POINTS.get(record.levelno, "[-]")
# Call parent formatter to apply the format string
return super().format(record) |
Format the log record by adding an appropriate bullet point.
Args:
record: The log record to format
Returns:
Formatted log message with bullet point prefix
| format | python | ly4k/Certipy | certipy/lib/logger.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/logger.py | MIT |
def init(
level: int = _logging.INFO, logger_name: str = "certipy", propagate: bool = False
) -> None:
"""
Initialize the Certipy logger with the appropriate formatter.
Args:
level: Log level to set (default: INFO)
logger_name: Name of the logger to configure (default: "certipy")
propagate: Whether to propagate logs to parent loggers (default: False)
Note:
This function configures a logger that:
- Outputs to stdout with bullet-point prefixed messages
- Has the specified log level (INFO by default)
- Can be isolated from parent loggers (default behavior)
Example:
# Standard initialization
init()
# Initialize with debug level
init(level=logging.DEBUG)
"""
# Create stdout handler
handler = _logging.StreamHandler(sys.stdout)
# Apply the custom formatter
handler.setFormatter(Formatter())
# Configure the logger
logger = _logging.getLogger(logger_name)
# Remove existing handlers if any (to avoid duplicates on re-initialization)
if logger.handlers:
logger.handlers.clear()
# Add the new handler
logger.addHandler(handler)
logger.setLevel(level)
logger.propagate = propagate |
Initialize the Certipy logger with the appropriate formatter.
Args:
level: Log level to set (default: INFO)
logger_name: Name of the logger to configure (default: "certipy")
propagate: Whether to propagate logs to parent loggers (default: False)
Note:
This function configures a logger that:
- Outputs to stdout with bullet-point prefixed messages
- Has the specified log level (INFO by default)
- Can be isolated from parent loggers (default behavior)
Example:
# Standard initialization
init()
# Initialize with debug level
init(level=logging.DEBUG)
| init | python | ly4k/Certipy | certipy/lib/logger.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/logger.py | MIT |
def compute_response(
server_challenge: bytes,
client_challenge: bytes,
target_info: bytes,
domain: str,
user: str,
password: str,
nt_hash: str = "",
channel_binding_data: Optional[bytes] = None,
service: str = "HOST",
) -> Tuple[bytes, bytes, bytes, bytes]:
"""
Compute NTLMv2 response based on the provided parameters.
Args:
server_challenge: Challenge received from the server
client_challenge: Client-generated random challenge
target_info: Target information provided by the server
domain: Domain name for authentication
user: Username for authentication
password: Password for authentication
nt_hash: NT hash if available, otherwise password will be used
channel_binding_data: Channel binding data for EPA compliance
service: Service name for the SPN
Returns:
Tuple containing:
- NT challenge response
- LM challenge response
- Session base key
- Target hostname
Raises:
ValueError: If target information is missing DNS hostname
"""
# Generate response key
response_key_nt = NTOWFv2(user, password, domain, bytes.fromhex(nt_hash) if nt_hash else "") # type: ignore
av_pairs = AV_PAIRS(target_info)
# Add SPN (target name)
if av_pairs[NTLMSSP_AV_DNS_HOSTNAME] is None:
raise ValueError("NTLMSSP_AV_DNS_HOSTNAME not found in target info")
hostname = cast(Tuple[int, bytes], av_pairs[NTLMSSP_AV_DNS_HOSTNAME])[1]
spn = f"{service}/".encode("utf-16le") + hostname
av_pairs[NTLMSSP_AV_TARGET_NAME] = spn
# Add timestamp if not already present
if av_pairs[NTLMSSP_AV_TIME] is None:
timestamp = struct.pack(
"<q", (116444736000000000 + calendar.timegm(time.gmtime()) * 10000000)
)
av_pairs[NTLMSSP_AV_TIME] = timestamp
# Add channel bindings if provided
if channel_binding_data:
av_pairs[NTLMSSP_AV_CHANNEL_BINDINGS] = channel_binding_data
# Construct temp data for NT proof calculation
temp = (
b"\x01" # RespType
+ b"\x01" # HiRespType
+ b"\x00" * 2 # Reserved1
+ b"\x00" * 4 # Reserved2
+ cast(Tuple[int, bytes], av_pairs[NTLMSSP_AV_TIME])[1] # Timestamp
+ client_challenge # ChallengeFromClient
+ b"\x00" * 4 # Reserved
+ av_pairs.getData() # AvPairs
)
# Calculate response components
nt_proof_str = hmac_md5(response_key_nt, server_challenge + temp)
nt_challenge_response = nt_proof_str + temp
lm_challenge_response = (
hmac_md5(response_key_nt, server_challenge + client_challenge)
+ client_challenge
)
session_base_key = hmac_md5(response_key_nt, nt_proof_str)
# Handle anonymous authentication
if not user and not password:
nt_challenge_response = b""
lm_challenge_response = b""
return nt_challenge_response, lm_challenge_response, session_base_key, hostname |
Compute NTLMv2 response based on the provided parameters.
Args:
server_challenge: Challenge received from the server
client_challenge: Client-generated random challenge
target_info: Target information provided by the server
domain: Domain name for authentication
user: Username for authentication
password: Password for authentication
nt_hash: NT hash if available, otherwise password will be used
channel_binding_data: Channel binding data for EPA compliance
service: Service name for the SPN
Returns:
Tuple containing:
- NT challenge response
- LM challenge response
- Session base key
- Target hostname
Raises:
ValueError: If target information is missing DNS hostname
| compute_response | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.py | MIT |
def ntlm_negotiate(
signing_required: bool = False,
use_ntlmv2: bool = True,
version: Optional[bytes] = None,
) -> NTLMAuthNegotiate:
"""
Generate an NTLMSSP Type 1 negotiation message.
Args:
signing_required: Whether signing is required for the connection
use_ntlmv2: Whether to use NTLMv2 (should be True for modern systems)
version: OS version to include in the message
Returns:
NTLMAuthNegotiate object representing the Type 1 message
"""
# Create base negotiate message with standard flags
auth = NTLMAuthNegotiate()
auth["flags"] = (
NTLMSSP_NEGOTIATE_NTLM
| NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY
| NTLMSSP_NEGOTIATE_UNICODE
| NTLMSSP_REQUEST_TARGET
| NTLMSSP_NEGOTIATE_128
| NTLMSSP_NEGOTIATE_56
)
# Add security flags if signing is required
if signing_required:
auth["flags"] |= (
NTLMSSP_NEGOTIATE_KEY_EXCH
| NTLMSSP_NEGOTIATE_SIGN
| NTLMSSP_NEGOTIATE_ALWAYS_SIGN
| NTLMSSP_NEGOTIATE_SEAL
)
# Add NTLMv2 target info flag
if use_ntlmv2:
auth["flags"] |= NTLMSSP_NEGOTIATE_TARGET_INFO
# Add version if specified
if version:
auth["flags"] |= NTLMSSP_NEGOTIATE_VERSION
auth["os_version"] = version
return auth |
Generate an NTLMSSP Type 1 negotiation message.
Args:
signing_required: Whether signing is required for the connection
use_ntlmv2: Whether to use NTLMv2 (should be True for modern systems)
version: OS version to include in the message
Returns:
NTLMAuthNegotiate object representing the Type 1 message
| ntlm_negotiate | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.py | MIT |
def ntlm_authenticate(
type1: NTLMAuthNegotiate,
challenge: NTLMAuthChallenge,
user: str,
password: str,
domain: str,
nt_hash: str = "",
channel_binding_data: Optional[bytes] = None,
service: str = "HOST",
version: Optional[bytes] = None,
) -> Tuple[NTLMAuthChallengeResponse, bytes, int]:
"""
Generate an NTLMSSP Type 3 authentication message in response to a server challenge.
Args:
type1: The Type 1 negotiate message that was sent
challenge: The Type 2 challenge message received from the server
user: Username for authentication
password: Password for authentication
domain: Domain name for authentication
nt_hash: NT hash if available, otherwise password will be used
channel_binding_data: Channel binding data for EPA compliance
service: Service name for the SPN
version: OS version to include in the message
Returns:
Tuple containing:
- NTLMAuthChallengeResponse object (Type 3 message)
- Exported session key for further operations
- Negotiated flags
"""
# Get response flags from the initial negotiate message
response_flags = type1["flags"]
# Generate client challenge (8 random bytes)
client_challenge = struct.pack("<Q", random.getrandbits(64))
# Extract target info from the challenge
target_info = challenge["TargetInfoFields"]
# Compute the NTLM response components
nt_response, lm_response, session_base_key, hostname = compute_response(
challenge["challenge"],
client_challenge,
target_info,
domain,
user,
password,
nt_hash,
channel_binding_data,
service,
)
# Adjust response flags based on server capabilities
security_flags = [
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY,
NTLMSSP_NEGOTIATE_128,
NTLMSSP_NEGOTIATE_KEY_EXCH,
NTLMSSP_NEGOTIATE_SEAL,
NTLMSSP_NEGOTIATE_SIGN,
NTLMSSP_NEGOTIATE_ALWAYS_SIGN,
]
for flag in security_flags:
if not (challenge["flags"] & flag):
response_flags &= ~flag
# Calculate the key exchange key
key_exchange_key = KXKEY(
challenge["flags"],
session_base_key,
lm_response,
challenge["challenge"],
password,
"",
nt_hash,
True,
)
# Handle key exchange if required
if challenge["flags"] & NTLMSSP_NEGOTIATE_KEY_EXCH:
# Generate random session key
exported_session_key = "".join(
random.choices(string.ascii_letters + string.digits, k=16)
).encode()
encrypted_random_session_key = generateEncryptedSessionKey(
key_exchange_key, exported_session_key
)
else:
encrypted_random_session_key = None
exported_session_key = key_exchange_key
# Create and populate the challenge response
challenge_response = NTLMAuthChallengeResponse(
user, password, challenge["challenge"]
)
challenge_response["flags"] = response_flags
challenge_response["domain_name"] = domain.encode("utf-16le")
challenge_response["host_name"] = hostname
challenge_response["lanman"] = lm_response if lm_response else b"\x00"
challenge_response["ntlm"] = nt_response
# Add version if specified
if version:
challenge_response["Version"] = version
# Add session key if key exchange is enabled
if encrypted_random_session_key:
challenge_response["session_key"] = encrypted_random_session_key
return challenge_response, exported_session_key, response_flags |
Generate an NTLMSSP Type 3 authentication message in response to a server challenge.
Args:
type1: The Type 1 negotiate message that was sent
challenge: The Type 2 challenge message received from the server
user: Username for authentication
password: Password for authentication
domain: Domain name for authentication
nt_hash: NT hash if available, otherwise password will be used
channel_binding_data: Channel binding data for EPA compliance
service: Service name for the SPN
version: OS version to include in the message
Returns:
Tuple containing:
- NTLMAuthChallengeResponse object (Type 3 message)
- Exported session key for further operations
- Negotiated flags
| ntlm_authenticate | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.py | MIT |
def __init__(
self,
target: Target,
service: str = DEFAULT_SERVICE,
channel_binding: bool = False,
):
"""
Initialize the NTLM authentication handler.
Args:
target: Target object containing connection and authentication details
service: Service principal name prefix to use (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 NTLM authentication handler.
Args:
target: Target object containing connection and authentication details
service: Service principal name prefix to use (default: "HTTP")
channel_binding: Whether to use channel binding for EPA compliance
| __init__ | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.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 NTLM authentication protocol flow by:
1. Sending the initial request
2. If authentication is required, starting the NTLM flow
3. Completing the NTLM handshake
Args:
request: The HTTPX request to authenticate
Yields:
Modified requests with appropriate authentication headers
Raises:
ValueError: If authentication fails or server responses are invalid
"""
# 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 the NTLM flow
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 NTLM authentication protocol flow by:
1. Sending the initial request
2. If authentication is required, starting the NTLM flow
3. Completing the NTLM handshake
Args:
request: The HTTPX request to authenticate
Yields:
Modified requests with appropriate authentication headers
Raises:
ValueError: If authentication fails or server responses are invalid
| auth_flow | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.py | MIT |
def retry_with_auth(
self, request: httpx.Request, response: httpx.Response
) -> Generator[httpx.Request, httpx.Response, None]:
"""
Retry the request with NTLM authentication.
Implements the complete NTLM authentication flow:
1. Send Type 1 (Negotiate) message
2. Process Type 2 (Challenge) message from server
3. Send Type 3 (Authenticate) message
Args:
request: The original HTTPX request
response: The HTTPX response requiring authentication
Yields:
Modified requests with appropriate authentication headers
Raises:
ValueError: If authentication fails or server responses are invalid
"""
# Determine header names based on status code (proxy vs direct)
is_proxy_auth = response.status_code == 407
authenticate_header_name = (
"Proxy-Authenticate" if is_proxy_auth else "WWW-Authenticate"
)
authorization_header_name = (
"Proxy-Authorization" if is_proxy_auth else "Authorization"
)
# Check if server sent authentication challenge
authenticate_header = response.headers.get(authenticate_header_name)
if authenticate_header is None:
raise ValueError("No authentication challenge returned from server")
# Step 1: Generate Type 1 (Negotiate) message
type1 = ntlm_negotiate()
# Get the authentication method (NTLM, Negotiate, etc.)
authentication_method = get_authentication_method(authenticate_header)
# Encode Type 1 message
auth = base64.b64encode(type1.getData()).decode()
# Add Type 1 message to request header
request.headers[authorization_header_name] = f"{authentication_method} {auth}"
# Send request with Type 1 message
response = yield request
# Handle cookies if present
if response.headers.get("Set-Cookie") is not None:
request.headers["Cookie"] = response.headers["Set-Cookie"]
# Get Type 2 (Challenge) message from server
authenticate_header = response.headers.get(authenticate_header_name)
if authenticate_header is None:
raise ValueError("No authentication challenge returned from server")
# Extract the server challenge from the authentication header
try:
# Find the challenge portion of the header
server_challenge_base64 = next(
s.strip()[len(authentication_method) :]
for s in (val.lstrip() for val in authenticate_header.split(","))
if s.startswith(authentication_method)
).strip()
except Exception:
raise ValueError(
f"Failed to parse authentication header: {authenticate_header!r}"
)
# Decode the challenge
try:
server_challenge = base64.b64decode(server_challenge_base64)
except Exception as e:
raise ValueError(
f"Failed to decode server challenge: {authenticate_header!r} - {e}"
)
# Check if challenge is wrapped in SPNEGO
if (
server_challenge
and struct.unpack("B", server_challenge[:1])[0]
== SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP
):
resp = SPNEGO_NegTokenResp(server_challenge)
type2 = resp["ResponseToken"]
else:
type2 = server_challenge
if not type2:
# This means that the server is not using NTLM
# and we should not continue with NTLM authentication
logging.debug(
"Server did not return a valid NTLM challenge. The server may have disabled NTLM authentication."
)
raise NtlmNotSupportedError("Server did not return a valid NTLM challenge.")
# Parse Type 2 message
challenge = NTLMAuthChallenge()
try:
challenge.fromString(type2)
except Exception as e:
raise ValueError(
f"Failed to parse server challenge: {authenticate_header!r} - {e}"
)
# Get channel binding data if enabled
channel_binding_data: Optional[bytes] = None
if self.channel_binding:
channel_binding_data = get_channel_binding_data_from_response(response)
# Step 3: Generate Type 3 (Authentication) message
type3, _, _ = ntlm_authenticate(
type1,
challenge,
self.target.username,
self.target.password or "",
self.target.domain,
self.target.nthash,
channel_binding_data=channel_binding_data,
service=self.service,
)
# Encode and add Type 3 message to request
auth = base64.b64encode(type3.getData()).decode()
request.headers[authorization_header_name] = f"{authentication_method} {auth}"
# Send authenticated request
yield request |
Retry the request with NTLM authentication.
Implements the complete NTLM authentication flow:
1. Send Type 1 (Negotiate) message
2. Process Type 2 (Challenge) message from server
3. Send Type 3 (Authenticate) message
Args:
request: The original HTTPX request
response: The HTTPX response requiring authentication
Yields:
Modified requests with appropriate authentication headers
Raises:
ValueError: If authentication fails or server responses are invalid
| retry_with_auth | python | ly4k/Certipy | certipy/lib/ntlm.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/ntlm.py | MIT |
def __init__(self, p: int, g: int):
"""Initialize a new DH instance with random private key."""
self.p = p
self.g = g
self.private_key = os.urandom(32)
self.private_key_int = int.from_bytes(self.private_key, byteorder="big")
self.dh_nonce = os.urandom(32) | Initialize a new DH instance with random private key. | __init__ | python | ly4k/Certipy | certipy/lib/pkinit.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/pkinit.py | MIT |
def get_public_key(self) -> int:
"""
Calculate the public key.
Returns:
Public key value (g^x mod p)
Raises:
ValueError: If p and g are not set
"""
# y = g^x mod p
return pow(self.g, self.private_key_int, self.p) |
Calculate the public key.
Returns:
Public key value (g^x mod p)
Raises:
ValueError: If p and g are not set
| get_public_key | python | ly4k/Certipy | certipy/lib/pkinit.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/pkinit.py | MIT |
def exchange(self, peer_public_key: int) -> bytes:
"""
Perform key exchange with peer's public key.
Args:
peer_public_key: Peer's public key value
Returns:
The shared secret as bytes
"""
shared_key_int = pow(peer_public_key, self.private_key_int, self.p)
# Convert to bytes, ensuring even length
hex_key = hex(shared_key_int)[2:]
if len(hex_key) % 2 != 0:
hex_key = "0" + hex_key
shared_key = bytes.fromhex(hex_key)
return shared_key |
Perform key exchange with peer's public key.
Args:
peer_public_key: Peer's public key value
Returns:
The shared secret as bytes
| exchange | python | ly4k/Certipy | certipy/lib/pkinit.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/pkinit.py | MIT |
def sign_authpack(
data: bytes,
key: rsa.RSAPrivateKey,
cert: Union[x509.Certificate, asn1x509.Certificate],
) -> bytes:
"""
Create a signed CMS structure containing the AuthPack.
Args:
data: The AuthPack data to sign
key: RSA private key for signing
cert: Certificate to include in the signed data
Returns:
ASN.1 DER encoded CMS signed data
"""
# Convert certificate to asn1crypto format if needed
if isinstance(cert, x509.Certificate):
cert = asn1x509.Certificate.load(cert_to_der(cert))
# Create digest algorithm identifier for SHA-1
digest_algorithm = {"algorithm": asn1algos.DigestAlgorithmId("sha1")}
# Create signer info
signer_info = {
"version": "v1",
"sid": asn1cms.IssuerAndSerialNumber(
{
"issuer": cert.issuer,
"serial_number": cert.serial_number,
}
),
"digest_algorithm": asn1algos.DigestAlgorithm(digest_algorithm),
"signed_attrs": [
asn1cms.CMSAttribute({"type": "content_type", "values": [PKINIT_OID]}),
asn1cms.CMSAttribute(
{"type": "message_digest", "values": [hash_digest(data, hashes.SHA1)]}
),
],
"signature_algorithm": asn1algos.SignedDigestAlgorithm(
{"algorithm": "sha1_rsa"}
),
"signature": bytes(),
}
# Create the signature
signer_info["signature"] = rsa_pkcs1v15_sign(
asn1cms.CMSAttributes(signer_info["signed_attrs"]).dump(),
key,
hash_algorithm=hashes.SHA1,
)
# Create encapsulated content info
encapsulated_content_info = {"content_type": PKINIT_OID, "content": data}
# Create the signed data structure
signed_data = {
"version": "v3",
"digest_algorithms": [asn1algos.DigestAlgorithm(digest_algorithm)],
"encap_content_info": asn1cms.EncapsulatedContentInfo(
encapsulated_content_info
),
"certificates": [cert],
"signer_infos": asn1cms.SignerInfos([asn1cms.SignerInfo(signer_info)]),
}
# Create the content info wrapper
content_info = {
"content_type": CMS_SIGNED_DATA_OID,
"content": asn1cms.SignedData(signed_data),
}
# Return DER-encoded ContentInfo
return asn1cms.ContentInfo(content_info).dump() |
Create a signed CMS structure containing the AuthPack.
Args:
data: The AuthPack data to sign
key: RSA private key for signing
cert: Certificate to include in the signed data
Returns:
ASN.1 DER encoded CMS signed data
| sign_authpack | python | ly4k/Certipy | certipy/lib/pkinit.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/pkinit.py | MIT |
def build_pkinit_as_req(
username: str, domain: str, key: rsa.RSAPrivateKey, cert: x509.Certificate
) -> Tuple[bytes, DirtyDH]:
"""
Build a PKINIT AS-REQ message.
Args:
username: Client username
domain: Domain/realm name
key: RSA private key for signing
cert: Client certificate
Returns:
A tuple containing:
- The encoded AS-REQ message
- The DirtyDH object for later key exchange
"""
# Get current time
now = datetime.datetime.now(datetime.timezone.utc)
# Build KDC-REQ-BODY
kdc_req_body_data = {
"kdc-options": KDCOptions({"forwardable", "renewable", "renewable-ok"}),
"cname": PrincipalName(
{"name-type": NameType.PRINCIPAL, "name-string": [username]}
),
"realm": domain.upper(),
"sname": PrincipalName(
{
"name-type": NameType.SRV_INST,
"name-string": ["krbtgt", domain.upper()],
}
),
"till": (now + datetime.timedelta(days=1)).replace(microsecond=0),
"rtime": (now + datetime.timedelta(days=1)).replace(microsecond=0),
"nonce": getrandbits(31),
"etype": [EncType.AES256, EncType.AES128], # Prefer stronger ciphers
}
kdc_req_body = KdcReqBody(kdc_req_body_data)
# Calculate checksum of the KDC-REQ-BODY
checksum = hash_digest(kdc_req_body.dump(), hashes.SHA1)
# Build PKAuthenticator
authenticator = {
"cusec": now.microsecond,
"ctime": now.replace(microsecond=0),
"nonce": getrandbits(31),
"paChecksum": checksum,
}
# Set up Diffie-Hellman
diffie = DirtyDH.from_dict(DH_PARAMS)
# Create DH domain parameters structure
dh_params = {
"p": diffie.p,
"g": diffie.g,
"q": 0, # Not used but required by some implementations
}
# Create public key algorithm identifier for DH
public_key_algorithm = {
"algorithm": DH_KEY_AGREEMENT_OID,
"parameters": asn1keys.DomainParameters(dh_params),
}
# Create subject public key info structure
subject_public_key_info = {
"algorithm": asn1keys.PublicKeyAlgorithm(public_key_algorithm),
"public_key": diffie.get_public_key(),
}
# Build AuthPack
authpack_data = {
"pkAuthenticator": PKAuthenticator(authenticator),
"clientPublicValue": asn1keys.PublicKeyInfo(subject_public_key_info),
"clientDHNonce": diffie.dh_nonce,
}
# Encode and sign the AuthPack
authpack = AuthPack(authpack_data)
signed_authpack = sign_authpack(authpack.dump(), key, cert)
# Build PA-PK-AS-REQ
pa_pk_as_req = PaPkAsReq()
pa_pk_as_req["signedAuthPack"] = signed_authpack
# Prepare PA-DATA entries
# PA-PAC-REQUEST to request a PAC
pa_data_pac = {
"padata-type": e2i(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST),
"padata-value": PaPacRequest({"include-pac": True}).dump(),
}
# PA-PK-AS-REQ for PKINIT
pa_data_pk = {
"padata-type": e2i(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ),
"padata-value": pa_pk_as_req.dump(),
}
# Build AS-REQ
asreq = {
"pvno": 5, # Kerberos version 5
"msg-type": 10, # AS-REQ
"padata": [pa_data_pac, pa_data_pk],
"req-body": kdc_req_body,
}
# Return the encoded AS-REQ and the Diffie-Hellman object
return AsReq(asreq).dump(), diffie |
Build a PKINIT AS-REQ message.
Args:
username: Client username
domain: Domain/realm name
key: RSA private key for signing
cert: Client certificate
Returns:
A tuple containing:
- The encoded AS-REQ message
- The DirtyDH object for later key exchange
| build_pkinit_as_req | python | ly4k/Certipy | certipy/lib/pkinit.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/pkinit.py | MIT |
def __init__(self, *args, **kwargs) -> None: # type: ignore
"""
Initialize a registry entry.
Args:
**kwargs: Key-value pairs to initialize the entry with
"""
super().__init__(self, *args, **kwargs)
if "attributes" not in self:
self["attributes"] = {} |
Initialize a registry entry.
Args:
**kwargs: Key-value pairs to initialize the entry with
| __init__ | python | ly4k/Certipy | certipy/lib/registry.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/registry.py | MIT |
def get_raw(self, key: str) -> Union[bytes, List[bytes], None]:
"""
Get a raw (bytes) representation of an attribute value.
Args:
key: The attribute name to retrieve
Returns:
Raw data as bytes, list of bytes, or None if not found
Notes:
- String values are encoded to bytes
- List values have each item encoded to bytes
- Other values are returned as-is
"""
data = self.get(key)
if isinstance(data, str):
return data.encode()
elif isinstance(data, list):
return [x.encode() if isinstance(x, str) else x for x in data]
return data |
Get a raw (bytes) representation of an attribute value.
Args:
key: The attribute name to retrieve
Returns:
Raw data as bytes, list of bytes, or None if not found
Notes:
- String values are encoded to bytes
- List values have each item encoded to bytes
- Other values are returned as-is
| get_raw | python | ly4k/Certipy | certipy/lib/registry.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/registry.py | MIT |
def __init__(self, domain: str, sids: List[str], scheme: str = "file") -> None:
"""
Initialize a registry connection.
Args:
domain: Domain name for the connection
sids: List of security identifiers to track
scheme: Connection scheme, defaults to "file"
"""
self.domain: str = domain
self.sids: List[str] = sids
self.sid_map: Dict[str, RegEntry] = {}
self.scheme: str = scheme |
Initialize a registry connection.
Args:
domain: Domain name for the connection
sids: List of security identifiers to track
scheme: Connection scheme, defaults to "file"
| __init__ | python | ly4k/Certipy | certipy/lib/registry.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/registry.py | MIT |
def get_user_sids(
self,
_username: str,
_user_sid: Optional[str] = None,
_user_dn: Optional[str] = None,
) -> List[str]:
"""
Get user security identifiers.
Args:
_username: Username (not used in this implementation)
_user_sid: User's primary SID (not used in this implementation)
_user_dn: User's distinguished name (not used in this implementation)
Returns:
List of SIDs associated with this connection
Notes:
The parameters are kept for API compatibility but not used.
This implementation simply returns the SIDs provided at initialization.
"""
return self.sids |
Get user security identifiers.
Args:
_username: Username (not used in this implementation)
_user_sid: User's primary SID (not used in this implementation)
_user_dn: User's distinguished name (not used in this implementation)
Returns:
List of SIDs associated with this connection
Notes:
The parameters are kept for API compatibility but not used.
This implementation simply returns the SIDs provided at initialization.
| get_user_sids | python | ly4k/Certipy | certipy/lib/registry.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/registry.py | MIT |
def lookup_sid(self, sid: str) -> RegEntry:
"""
Look up a security identifier and return corresponding registry entry.
Args:
sid: Security identifier to look up
Returns:
RegEntry object representing the SID
Notes:
- Checks cached entries first
- Then checks well-known SIDs
- Then checks well-known RIDs
- Finally creates a base entry if not found elsewhere
"""
# Check if we've already cached this SID
if sid in self.sid_map:
return self.sid_map[sid]
# Check well-known SIDs
if sid in WELLKNOWN_SIDS:
name, obj_type = WELLKNOWN_SIDS[sid]
entry = RegEntry(
**{
"attributes": {
"objectSid": f"{self.domain.upper()}-{sid}",
"objectType": obj_type.capitalize(),
"name": f"{self.domain}\\{name}",
}
}
)
self.sid_map[sid] = entry
return entry
# Check if this is a well-known RID
rid = sid.split("-")[-1]
if rid in WELLKNOWN_RIDS:
name, obj_type = WELLKNOWN_RIDS[rid]
entry = RegEntry(
**{
"attributes": {
"objectSid": f"{self.domain.upper()}-{sid}",
"objectType": obj_type.capitalize(),
"name": f"{self.domain}\\{name}",
}
}
)
self.sid_map[sid] = entry
return entry
# Create a generic entry for unknown SIDs
entry = RegEntry(
**{
"attributes": {
"objectSid": sid,
"name": sid,
"objectType": "Base",
}
}
)
# Cache this entry for future lookups
self.sid_map[sid] = entry
return entry |
Look up a security identifier and return corresponding registry entry.
Args:
sid: Security identifier to look up
Returns:
RegEntry object representing the SID
Notes:
- Checks cached entries first
- Then checks well-known SIDs
- Then checks well-known RIDs
- Finally creates a base entry if not found elsewhere
| lookup_sid | python | ly4k/Certipy | certipy/lib/registry.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/registry.py | MIT |
def __init__(self, interface: IRemUnknown2):
"""
Initialize the ICertRequestD interface.
Args:
interface: IRemUnknown2 interface from DCOM connection
"""
super().__init__(interface)
self._iid = IID_ICertRequestD |
Initialize the ICertRequestD interface.
Args:
interface: IRemUnknown2 interface from DCOM connection
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __init__(
self, error_string: Any = None, error_code: Any = None, packet: Any = None
):
"""
Initialize the DCERPCSessionError.
Args:
error_string: Error description
error_code: Numeric error code
packet: The RPC packet that caused the error
"""
rpcrt.DCERPCException.__init__(self, error_string, error_code, packet) |
Initialize the DCERPCSessionError.
Args:
error_string: Error description
error_code: Numeric error code
packet: The RPC packet that caused the error
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __str__(self) -> str:
"""
Format the error message with translated error code.
Returns:
Human-readable error message
"""
self.error_code &= 0xFFFFFFFF # type: ignore
error_msg = translate_error_code(self.error_code)
return f"RequestSessionError: {error_msg}" |
Format the error message with translated error code.
Returns:
Human-readable error message
| __str__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def handle_rpc_retrieve_response(
response: Dict[str, Any],
) -> Optional[x509.Certificate]:
"""
Process the RPC certificate retrieval response.
Args:
response: The RPC response dictionary
Returns:
Certificate object if successful, None otherwise
"""
error_code = response["pdwDisposition"]
if error_code == DISPOSITION_SUCCESS:
logging.info("Successfully retrieved certificate")
cert = der_to_cert(b"".join(response["pctbEncodedCert"]["pb"]))
return cert
# Handle non-success cases
if error_code == DISPOSITION_PENDING:
logging.warning("Certificate request is still pending approval")
else:
error_msg = translate_error_code(error_code)
disposition_message = b"".join(response["pctbDispositionMessage"]["pb"]).decode(
"utf-16le"
)
if "unknown error code" in error_msg:
logging.error(
f"Got unknown error while retrieving certificate: ({error_msg}): {disposition_message}"
)
else:
logging.error(f"Got error while retrieving certificate: {error_msg}")
return None |
Process the RPC certificate retrieval response.
Args:
response: The RPC response dictionary
Returns:
Certificate object if successful, None otherwise
| handle_rpc_retrieve_response | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def handle_rpc_request_response(
response: Dict[str, Any],
) -> Union[x509.Certificate, int]:
"""
Process the RPC certificate request response.
Args:
response: The RPC response dictionary
Returns:
Certificate object if immediately successful, or request ID if pending/failed
"""
error_code = response["pdwDisposition"]
request_id = response["pdwRequestId"]
# Always log the request ID
logging.info(f"Request ID is {request_id}")
# Handle success case
if error_code == DISPOSITION_SUCCESS:
logging.info("Successfully requested certificate")
cert = der_to_cert(b"".join(response["pctbEncodedCert"]["pb"]))
return cert
# Handle non-success cases
if error_code == DISPOSITION_PENDING:
logging.warning("Certificate request is pending approval")
else:
error_msg = translate_error_code(error_code)
disposition_message = b"".join(response["pctbDispositionMessage"]["pb"]).decode(
"utf-16le"
)
if "unknown error code" in error_msg:
logging.error(
f"Got unknown error while requesting certificate: ({error_msg}): {disposition_message}"
)
else:
logging.error(f"Got error while requesting certificate: {error_msg}")
return request_id |
Process the RPC certificate request response.
Args:
response: The RPC response dictionary
Returns:
Certificate object if immediately successful, or request ID if pending/failed
| handle_rpc_request_response | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def handle_request_response(
cert: x509.Certificate,
key: PrivateKeyTypes,
username: str,
subject: Optional[str] = None,
alt_sid: Optional[str] = None,
out: Optional[str] = None,
pfx_password: Optional[str] = None,
) -> Tuple[bytes, str]:
"""
Process a successful certificate request by saving the certificate and private key.
Args:
cert: The issued certificate
key: The private key
username: The username associated with the certificate
subject: Optional subject name
alt_sid: Optional alternate SID
out: Optional output filename
pfx_password: Optional PFX password
Returns:
Tuple of (pfx_data, output_filename)
"""
# Log subject info if available
if subject:
subject_str = ",".join(map(lambda x: x.rfc4514_string(), cert.subject.rdns))
logging.info(f"Got certificate with subject: {subject_str}")
# Extract and display certificate information
identities = get_identities_from_certificate(cert)
print_certificate_identities(identities)
# Check and log object SID information
object_sid = get_object_sid_from_certificate(cert)
if object_sid is not None:
logging.info(f"Certificate object SID is {object_sid!r}")
else:
logging.info("Certificate has no object SID")
if not alt_sid:
logging.info(
"Try using -sid to set the object SID or see the wiki for more details"
)
# Determine output filename
out_filename = _determine_output_filename(out, identities, username)
# Create PFX and save to file
pfx = create_pfx(key, cert, pfx_password)
outfile = f"{out_filename}.pfx"
logging.info(f"Saving certificate and private key to {outfile!r}")
saved_path = try_to_save_file(pfx, outfile)
logging.info(f"Wrote certificate and private key to {saved_path!r}")
return pfx, saved_path |
Process a successful certificate request by saving the certificate and private key.
Args:
cert: The issued certificate
key: The private key
username: The username associated with the certificate
subject: Optional subject name
alt_sid: Optional alternate SID
out: Optional output filename
pfx_password: Optional PFX password
Returns:
Tuple of (pfx_data, output_filename)
| handle_request_response | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def handle_retrieve(
cert: x509.Certificate,
request_id: int,
username: str,
out: Optional[str] = None,
pfx_password: Optional[str] = None,
) -> bool:
"""
Process a retrieved certificate by saving it with the private key if available.
Args:
cert: The retrieved certificate
request_id: The certificate request ID
username: The username associated with the certificate
out: Optional output filename
pfx_password: Optional PFX password
Returns:
True if successful
"""
# Extract and display certificate information
identities = get_identities_from_certificate(cert)
print_certificate_identities(identities)
# Check and log object SID information
object_sid = get_object_sid_from_certificate(cert)
if object_sid is not None:
logging.info(f"Certificate object SID is {object_sid!r}")
else:
logging.info("Certificate has no object SID")
# Determine output filename
out_filename = _determine_output_filename(out, identities, username)
# Try to find matching private key and save as PFX if found
try:
key_path = f"{request_id}.key"
with open(key_path, "rb") as f:
key = pem_to_key(f.read())
logging.info(f"Loaded private key from {key_path!r}")
pfx = create_pfx(key, cert, pfx_password)
output_path = f"{out_filename}.pfx"
logging.info(f"Saving certificate and private key to {output_path!r}")
saved_path = try_to_save_file(pfx, output_path)
logging.info(f"Wrote certificate and private key to {saved_path!r}")
except Exception:
# If no key found, save just the certificate as PEM
logging.warning(
"Could not find matching private key. Saving certificate as PEM"
)
handle_error(True)
output_path = f"{out_filename}.crt"
logging.info(f"Saving certificate to {output_path!r}")
saved_path = try_to_save_file(cert_to_pem(cert), output_path)
logging.info(f"Wrote certificate to {saved_path!r}")
return True |
Process a retrieved certificate by saving it with the private key if available.
Args:
cert: The retrieved certificate
request_id: The certificate request ID
username: The username associated with the certificate
out: Optional output filename
pfx_password: Optional PFX password
Returns:
True if successful
| handle_retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def handle_pending_key_save(
request_id: int, key: PrivateKeyTypes, out: Optional[str] = None
) -> None:
"""
Offer to save the private key for pending certificate requests.
Args:
request_id: The certificate request ID
key: The private key to save
out: Optional output filename for the private key
"""
should_save = input("Would you like to save the private key? (y/N): ")
if should_save.strip().lower() == "y":
output_path = f"{out if out is not None else str(request_id)}.key"
try:
logging.info(f"Saving private key to {output_path!r}")
saved_path = try_to_save_file(key_to_pem(key), output_path)
logging.info(f"Wrote private key to {saved_path!r}")
except Exception as e:
logging.error(f"Failed to save private key: {e}")
handle_error() |
Offer to save the private key for pending certificate requests.
Args:
request_id: The certificate request ID
key: The private key to save
out: Optional output filename for the private key
| handle_pending_key_save | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def web_request(
session: httpx.Client,
username: str,
csr: Union[str, bytes, x509.CertificateSigningRequest],
attributes_list: List[str],
template: str,
key: PrivateKeyTypes,
out: Optional[str] = None,
) -> Optional[x509.Certificate]:
"""
Request a certificate via the web enrollment interface.
Args:
session: HTTP session client
username: Username for the certificate
csr: Certificate signing request (bytes or object)
attributes_list: List of certificate attributes
template: Certificate template name
key: Private key for the certificate
out: Optional output filename
Returns:
Certificate if immediately issued, None otherwise
"""
# Convert CSR to PEM format if needed
if isinstance(csr, x509.CertificateSigningRequest):
csr_pem = csr_to_pem(csr).decode()
elif isinstance(csr, bytes):
csr_pem = der_to_pem(csr, "CERTIFICATE REQUEST")
else:
# Already in PEM format
csr_pem = csr
attributes = "\n".join(attributes_list)
# Build request parameters
params = {
"Mode": "newreq",
"CertAttrib": attributes,
"CertRequest": csr_pem,
"TargetStoreFlags": "0",
"SaveCert": "yes",
"ThumbPrint": "",
}
logging.info(
f"Requesting certificate for {username!r} based on the template {template!r}"
)
# Send certificate request
try:
res = session.post("/certsrv/certfnsh.asp", data=params)
content = res.text
# Handle HTTP errors
if res.status_code != 200:
logging.error(f"Failed to request certificate (HTTP {res.status_code})")
_log_response_if_verbose(content)
return None
# Check for successful issuance (certificate ready for download)
request_id_matches = re.findall(r"certnew.cer\?ReqID=([0-9]+)&", content)
if request_id_matches:
request_id = int(request_id_matches[0])
logging.info(f"Certificate issued with request ID {request_id}")
return web_retrieve(session, request_id)
# Handle various error conditions
if "template that is not supported" in content:
logging.error(f"Template {template!r} is not supported by AD CS")
else:
# Try to find request ID in other format
request_id_matches = re.findall(r"Your Request Id is ([0-9]+)", content)
if request_id_matches:
request_id = int(request_id_matches[0])
logging.info(f"Request ID is {request_id}")
if "Certificate Pending" in content:
logging.warning("Certificate request is pending approval")
elif '"Denied by Policy Module"' in content:
_handle_policy_denial(session, request_id)
else:
_handle_other_errors(content)
else:
_handle_other_errors(content)
# For pending requests, save the private key if requested
request_id_matches = re.findall(r"Your Request Id is ([0-9]+)", content)
if request_id_matches:
request_id = int(request_id_matches[0])
handle_pending_key_save(request_id, key, out)
return None
except Exception as e:
logging.error(f"Error during web certificate request: {e}")
handle_error()
return None |
Request a certificate via the web enrollment interface.
Args:
session: HTTP session client
username: Username for the certificate
csr: Certificate signing request (bytes or object)
attributes_list: List of certificate attributes
template: Certificate template name
key: Private key for the certificate
out: Optional output filename
Returns:
Certificate if immediately issued, None otherwise
| web_request | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def web_retrieve(
session: httpx.Client,
request_id: int,
) -> Optional[x509.Certificate]:
"""
Retrieve a certificate via the web enrollment interface.
Args:
session: HTTP session client
request_id: The certificate request ID
Returns:
Certificate if successfully retrieved, None otherwise
"""
logging.info(f"Retrieving certificate for request ID: {request_id}")
try:
# Request the certificate
res = session.get("/certsrv/certnew.cer", params={"ReqID": request_id})
if res.status_code != 200:
logging.error(f"Error retrieving certificate (HTTP {res.status_code})")
_log_response_if_verbose(res.text)
return None
# Handle PEM-format certificate
if b"BEGIN CERTIFICATE" in res.content:
return pem_to_cert(res.content)
# Handle DER-format certificate
if res.headers.get("Content-Type") == "application/pkix-cert":
return der_to_cert(res.content)
# Handle error conditions
content = res.text
if "Taken Under Submission" in content:
logging.warning("Certificate request is pending approval")
elif "The requested property value is empty" in content:
logging.warning(f"Unknown request ID {request_id}")
else:
# Try to extract error code
error_codes = re.findall(r" (0x[0-9a-fA-F]+) \(", content)
try:
error_code_int = int(error_codes[0], 16)
msg = translate_error_code(error_code_int)
logging.warning(f"Got error from AD CS: {msg}")
except Exception:
logging.warning("Got unknown error from AD CS")
_log_response_if_verbose(content)
return None
except Exception as e:
logging.error(f"Error during web certificate retrieval: {e}")
handle_error()
return None |
Retrieve a certificate via the web enrollment interface.
Args:
session: HTTP session client
request_id: The certificate request ID
Returns:
Certificate if successfully retrieved, None otherwise
| web_retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def _determine_output_filename(
out: Optional[str], identities: List[Tuple[str, str]], username: str
) -> str:
"""
Determine the output filename to use for saving certificates/keys.
Args:
out: User-specified output name (if any)
identities: List of certificate identities
username: The username associated with the certificate
Returns:
The output filename (without extension)
"""
if out is not None:
return out.removesuffix(".pfx")
# Try to derive filename from certificate identity
cert_username, _ = cert_id_to_parts(identities) # type: ignore
if cert_username is not None:
return cert_username.rstrip("$").lower()
# Fallback to provided username
return username.rstrip("$").lower() |
Determine the output filename to use for saving certificates/keys.
Args:
out: User-specified output name (if any)
identities: List of certificate identities
username: The username associated with the certificate
Returns:
The output filename (without extension)
| _determine_output_filename | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def _handle_policy_denial(session: httpx.Client, request_id: int) -> None:
"""
Handle certificate request denied by policy.
Args:
session: HTTP session client
request_id: The certificate request ID
"""
try:
res = session.get("/certsrv/certnew.cer", params={"ReqID": request_id})
error_codes = re.findall(
r"(0x[a-zA-Z0-9]+) \([-]?[0-9]+ ", res.text, flags=re.MULTILINE
)
if error_codes:
error_msg = translate_error_code(int(error_codes[0], 16))
logging.error(f"Certificate request denied: {error_msg}")
else:
logging.error(
"Certificate request denied by policy module (no error code available)"
)
_log_response_if_verbose(res.text)
except Exception as e:
logging.error(f"Error retrieving denial details: {e}")
handle_error(True) |
Handle certificate request denied by policy.
Args:
session: HTTP session client
request_id: The certificate request ID
| _handle_policy_denial | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def _handle_other_errors(content: str) -> None:
"""
Handle other certificate request errors.
Args:
content: Response content
"""
error_code_matches = re.findall(
r"Denied by Policy Module (0x[0-9a-fA-F]+),", content
)
try:
if error_code_matches:
error_code = int(error_code_matches[0], 16)
msg = translate_error_code(error_code)
logging.error(f"Got error from AD CS: {msg}")
else:
# Try other error code formats
error_codes = re.findall(r"Error Number: (0x[0-9a-fA-F]+)", content)
if error_codes:
error_code = int(error_codes[0], 16)
msg = translate_error_code(error_code)
logging.error(f"Got error from AD CS: {msg}")
else:
logging.error("Unknown error from AD CS")
_log_response_if_verbose(content)
except Exception:
logging.error("Failed to parse error message from AD CS")
_log_response_if_verbose(content) |
Handle other certificate request errors.
Args:
content: Response content
| _handle_other_errors | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def _log_response_if_verbose(content: str) -> None:
"""
Log response content if verbose logging is enabled.
Args:
content: Response content to log
"""
if is_verbose():
print(content)
else:
logging.warning("Use -debug to print the response") |
Log response content if verbose logging is enabled.
Args:
content: Response content to log
| _log_response_if_verbose | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __init__(self, parent: "Request"):
"""
Initialize the DCOM request interface.
Args:
parent: The parent Request object
"""
self.parent = parent
self._dcom: Optional[DCOMConnection] = None |
Initialize the DCOM request interface.
Args:
parent: The parent Request object
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def dcom(self) -> DCOMConnection:
"""
Get or establish a DCOM connection to the certificate authority.
Returns:
Active DCOM connection
Raises:
Exception: If target is not set or connection fails
"""
if self._dcom is not None:
return self._dcom
self._dcom = get_dcom_connection(self.parent.target)
return self._dcom |
Get or establish a DCOM connection to the certificate authority.
Returns:
Active DCOM connection
Raises:
Exception: If target is not set or connection fails
| dcom | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def retrieve(self, request_id: int) -> Optional[x509.Certificate]:
"""
Retrieve a certificate by request ID via DCOM.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, None on failure
"""
# Prepare empty blob for request
empty = CERTTRANSBLOB()
empty["cb"] = 0
empty["pb"] = NULL
# Build the request structure
request = CertServerRequestD()
request["dwFlags"] = 0
request["pwszAuthority"] = checkNullString(self.parent.ca)
request["pdwRequestId"] = request_id
request["pwszAttributes"] = empty
request["pctbRequest"] = empty
logging.info(f"Retrieving certificate with ID {request_id}")
# Create and configure the DCOM interface
i_cert_req = self.dcom.CoCreateInstanceEx(CLSID_ICertRequest, IID_ICertRequestD)
i_cert_req.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore
# Submit the request
cert_req_d = ICertRequestD(i_cert_req)
response = cert_req_d.request(request)
result = handle_rpc_request_response(response)
if isinstance(result, int):
return None
return result |
Retrieve a certificate by request ID via DCOM.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, None on failure
| retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __init__(self, parent: "Request"):
"""
Initialize the RPC request interface.
Args:
parent: The parent Request object
"""
self.parent = parent
self._dce = None |
Initialize the RPC request interface.
Args:
parent: The parent Request object
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def dce(self) -> Optional[rpcrt.DCERPC_v5]:
"""
Get or establish an RPC connection to the certificate authority.
Returns:
Active RPC connection
Raises:
Exception: If target is not set or connection fails
"""
if self._dce is not None:
return self._dce
if not MSRPC_UUID_ICPR:
# Should never happen
raise Exception("Failed to get MSRPC UUID for ICertRequest")
self._dce = get_dce_rpc(
MSRPC_UUID_ICPR,
"\\pipe\\cert",
self.parent.target,
timeout=self.parent.target.timeout,
dynamic=self.parent.dynamic,
)
return self._dce |
Get or establish an RPC connection to the certificate authority.
Returns:
Active RPC connection
Raises:
Exception: If target is not set or connection fails
| dce | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def dce_request(self, request: NDRCALL) -> Dict[str, Any]:
"""
Send a DCE RPC request and handle the response.
This wrapper method properly handles the DCE RPC request to ensure static
code analysis tools correctly understand the return value. The underlying
impacket.dcerpc.v5.rpcrt.DCERPC_v5.request method has type annotation
issues that cause some analyzers to think it never returns.
Args:
request: The RPC request structure to send
Returns:
Dict containing the parsed response
Raises:
Exception: If the DCE RPC connection isn't established or request fails
"""
if self.dce is None:
raise Exception("Failed to get DCE RPC connection")
# Call the underlying request method with error checking disabled
# We manually handle errors to provide better error messages
return self.dce.request(request, checkError=False) |
Send a DCE RPC request and handle the response.
This wrapper method properly handles the DCE RPC request to ensure static
code analysis tools correctly understand the return value. The underlying
impacket.dcerpc.v5.rpcrt.DCERPC_v5.request method has type annotation
issues that cause some analyzers to think it never returns.
Args:
request: The RPC request structure to send
Returns:
Dict containing the parsed response
Raises:
Exception: If the DCE RPC connection isn't established or request fails
| dce_request | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def retrieve(self, request_id: int) -> Optional[x509.Certificate]:
"""
Retrieve a certificate by request ID via RPC.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, False on failure
"""
# Prepare empty blob for request
empty = CERTTRANSBLOB()
empty["cb"] = 0
empty["pb"] = NULL
# Build the request structure
request = CertServerRequest()
request["dwFlags"] = 0
request["pwszAuthority"] = checkNullString(self.parent.ca)
request["pdwRequestId"] = request_id
request["pctbAttribs"] = empty
request["pctbRequest"] = empty
logging.info(f"Retrieving certificate with ID {request_id}")
# Submit the request
response = self.dce_request(request)
# Process the response
return handle_rpc_retrieve_response(response) |
Retrieve a certificate by request ID via RPC.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, False on failure
| retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __init__(self, parent: "Request"):
"""
Initialize the Web Enrollment request interface.
Args:
parent: The parent Request object
"""
self.parent = parent
self.target = self.parent.target
self._session = None
self.base_url = "" |
Initialize the Web Enrollment request interface.
Args:
parent: The parent Request object
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def session(self) -> Optional[httpx.Client]:
"""
Get or establish an HTTP session to the certificate authority.
Returns:
Active HTTP session, or None if connection failed
Raises:
Exception: If target is not set or connection fails
"""
if self._session is not None:
return self._session
# Try the specified scheme and port first
scheme = self.parent.http_scheme or "https"
port = self.parent.http_port or (443 if scheme == "https" else 80)
base_url = f"{scheme}://{self.target.target_ip}:{port}"
# Create a session with httpx with appropriate authentication
if self.target.do_kerberos:
session = httpx.Client(
base_url=base_url,
auth=HttpxKerberosAuth(
self.target, channel_binding=not self.parent.no_channel_binding
),
timeout=self.target.timeout,
verify=False,
)
else:
session = httpx.Client(
base_url=base_url,
auth=HttpxNtlmAuth(
self.target, channel_binding=not self.parent.no_channel_binding
),
timeout=self.target.timeout,
verify=False,
)
logging.info(f"Checking for Web Enrollment on {base_url!r}")
success = self._try_connection(session)
# If the first attempt fails, try the alternative scheme
if not success:
alt_scheme = "http" if scheme == "https" else "https"
alt_port = 80 if alt_scheme == "http" else 443
base_url = f"{alt_scheme}://{self.target.target_ip}:{alt_port}"
logging.info(f"Trying to connect to Web Enrollment interface {base_url!r}")
session.base_url = base_url
success = self._try_connection(session)
if not success:
logging.error("Could not connect to Web Enrollment")
return None
self.base_url = base_url
self._session = session
return self._session |
Get or establish an HTTP session to the certificate authority.
Returns:
Active HTTP session, or None if connection failed
Raises:
Exception: If target is not set or connection fails
| session | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def _try_connection(self, session: httpx.Client) -> bool:
"""
Try to connect to the Web Enrollment interface.
Args:
session: HTTP session to use
base_url: Base URL to connect to
Returns:
True if connection was successful, False otherwise
"""
headers = {
"User-Agent": USER_AGENT,
}
host_value = self.target.remote_name or self.target.target_ip
if host_value:
headers["Host"] = host_value
try:
res = session.get(
"/certsrv/",
headers=headers,
timeout=self.target.timeout,
follow_redirects=False,
)
if res.status_code == 200:
return True
elif res.status_code == 401:
logging.error(
f"Unauthorized for Web Enrollment at {session.base_url!r}"
)
else:
logging.warning(
f"Failed to authenticate to Web Enrollment at {session.base_url!r}"
)
logging.debug(f"Got status code: {res.status_code!r}")
if is_verbose():
print(res.text)
except Exception as e:
logging.warning(f"Failed to connect to Web Enrollment interface: {e}")
handle_error(True)
return False |
Try to connect to the Web Enrollment interface.
Args:
session: HTTP session to use
base_url: Base URL to connect to
Returns:
True if connection was successful, False otherwise
| _try_connection | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def retrieve(self, request_id: int) -> Optional[x509.Certificate]:
"""
Retrieve a certificate by request ID via Web Enrollment.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, None on failure
"""
if self.session is None:
raise Exception("Failed to get HTTP session")
return web_retrieve(
self.session,
request_id,
) |
Retrieve a certificate by request ID via Web Enrollment.
Args:
request_id: The request ID to retrieve
Returns:
Certificate object if successful, None on failure
| retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def __init__(
self,
target: Target,
ca: Optional[str] = None,
template: str = "User",
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,
retrieve: Optional[int] = None,
on_behalf_of: Optional[str] = None,
pfx: Optional[str] = None,
pfx_password: Optional[str] = None,
key_size: int = 2048,
archive_key: bool = False,
cax_cert: bool = False,
renew: bool = False,
out: Optional[str] = None,
key: Optional[rsa.RSAPrivateKey] = None,
web: bool = False,
dcom: bool = False,
http_scheme: Optional[str] = None,
http_port: Optional[int] = None,
no_channel_binding: bool = False,
dynamic_endpoint: bool = False,
**kwargs, # type: ignore
):
"""
Initialize a certificate request object.
Args:
target: Target information including host and authentication
ca: Certificate Authority name
template: Certificate template name
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
retrieve: Request ID to retrieve
on_behalf_of: Username to request on behalf of
pfx: Path to PKCS#12/PFX file
pfx_password: Password for PFX file
key_size: RSA key size in bits
archive_key: Whether to archive the private key
cax_cert: Whether to retrieve the CAX certificate
renew: Whether to renew an existing certificate
out: Output file path
key: Pre-generated RSA key
web: Use Web Enrollment instead of RPC
dcom: Use DCOM instead of RPC
port: Port for Web Enrollment
scheme: Scheme for Web Enrollment (http/https)
dynamic_endpoint: Use dynamic RPC endpoint
"""
# Core parameters
self.target = target
self.ca = ca
self.template = template
self.alt_upn = upn
self.alt_dns = dns
self.alt_sid = sid
self.subject = subject
self.request_id = int(retrieve) if retrieve else None
self.on_behalf_of = on_behalf_of
self.pfx = pfx
self.pfx_password = pfx_password
self.key_size = key_size
self.archive_key = archive_key
self.cax_cert = cax_cert
self.renew = renew
self.out = out
self.key = key
# 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
# Connection parameters
self.web = web
self.dcom = dcom
self.http_port = http_port
self.http_scheme = http_scheme
self.no_channel_binding = no_channel_binding
# Handle default ports based on scheme
if not self.http_port and self.http_scheme:
if self.http_scheme == "http":
self.http_port = 80
elif self.http_scheme == "https":
self.http_port = 443
self.dynamic = dynamic_endpoint
self.kwargs = kwargs
# Interface is initialized on demand
self._interface = None |
Initialize a certificate request object.
Args:
target: Target information including host and authentication
ca: Certificate Authority name
template: Certificate template name
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
retrieve: Request ID to retrieve
on_behalf_of: Username to request on behalf of
pfx: Path to PKCS#12/PFX file
pfx_password: Password for PFX file
key_size: RSA key size in bits
archive_key: Whether to archive the private key
cax_cert: Whether to retrieve the CAX certificate
renew: Whether to renew an existing certificate
out: Output file path
key: Pre-generated RSA key
web: Use Web Enrollment instead of RPC
dcom: Use DCOM instead of RPC
port: Port for Web Enrollment
scheme: Scheme for Web Enrollment (http/https)
dynamic_endpoint: Use dynamic RPC endpoint
| __init__ | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def interface(self) -> RequestInterface:
"""
Get the appropriate request interface based on configuration.
Returns:
Configured request interface instance
"""
if self._interface is not None:
return self._interface
# Select interface based on configuration
if self.web:
self._interface = WebRequestInterface(self)
elif self.dcom:
self._interface = DCOMRequestInterface(self)
else:
self._interface = RPCRequestInterface(self)
return self._interface |
Get the appropriate request interface based on configuration.
Returns:
Configured request interface instance
| interface | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def retrieve(self) -> bool:
"""
Retrieve a certificate by request ID.
Returns:
True if successful, False otherwise
"""
if self.request_id is None:
logging.error("No request ID specified")
return False
request_id = int(self.request_id)
# Retrieve the certificate using the appropriate interface
cert = self.interface.retrieve(request_id)
if cert is False or cert is None:
logging.error("Failed to retrieve certificate")
return False
handle_retrieve(
cert, request_id, self.target.username, self.out, self.pfx_password
)
return True |
Retrieve a certificate by request ID.
Returns:
True if successful, False otherwise
| retrieve | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def request(self) -> Union[bool, Tuple[bytes, str]]:
"""
Request a new certificate from AD CS.
Returns:
PFX data and filename if successful, False otherwise
"""
# Determine username for certificate
username = self.target.username
# Validate request options
if sum(map(bool, [self.archive_key, self.on_behalf_of, self.renew])) > 1:
logging.error(
"Combinations of -renew, -on-behalf-of, and -archive-key are currently not supported"
)
return False
# Handle on-behalf-of requests
if self.on_behalf_of:
username = self.on_behalf_of
if self.on_behalf_of.count("\\") > 0:
parts = username.split("\\")
username = "\\".join(parts[1:])
domain = parts[0]
if "." in domain:
logging.warning(
"Domain part of '-on-behalf-of' should not be a FQDN"
)
# Handle certificate renewal
renewal_cert = None
renewal_key = None
if self.renew:
if self.pfx is None:
logging.error(
"A certificate and private key (-pfx) is required for renewal"
)
return False
with open(self.pfx, "rb") as f:
renewal_key, renewal_cert = load_pfx(f.read())
if not renewal_key or not renewal_cert:
logging.error("Failed to load certificate and private key from PFX")
return False
# Create the CSR
csr, key = create_csr(
username,
alt_dns=self.alt_dns,
alt_upn=self.alt_upn,
alt_sid=self.alt_sid,
subject=self.subject,
key_size=self.key_size,
application_policies=self.application_policies,
smime=self.smime,
key=self.key,
renewal_cert=renewal_cert,
)
self.key = key
# Convert CSR to DER format
csr_der = csr_to_der(csr)
# Handle key archival
if self.archive_key:
ca = CA(self.target, self.ca)
logging.info("Trying to retrieve CAX certificate")
cax_cert = ca.get_exchange_certificate()
logging.info("Retrieved CAX certificate")
csr_der = create_key_archival(der_to_csr(csr_der), self.key, cax_cert)
# Handle certificate renewal
if self.renew:
if not renewal_cert or not renewal_key:
logging.error(
"A certificate and private key (-pfx) is required for renewal"
)
return False
if not isinstance(renewal_key, rsa.RSAPrivateKey):
logging.error("Currently only RSA keys are supported for renewal")
return False
csr_der = create_renewal(csr_der, renewal_cert, renewal_key)
# Handle on-behalf-of requests
if self.on_behalf_of:
if self.pfx is None:
logging.error(
"A certificate and private key (-pfx) is required for on-behalf-of requests"
)
return False
with open(self.pfx, "rb") as f:
agent_key, agent_cert = load_pfx(f.read())
if agent_key is None or agent_cert is None:
logging.error(
f"Failed to load certificate and private key from {self.pfx}"
)
return False
if not isinstance(agent_key, rsa.RSAPrivateKey):
logging.error(
"Currently only RSA keys are supported for on-behalf-of requests"
)
return False
csr_der = create_on_behalf_of(
csr_der, self.on_behalf_of, agent_cert, agent_key
)
# Construct attributes list
attributes = create_csr_attributes(
self.template,
self.alt_dns,
self.alt_upn,
self.alt_sid,
self.application_policies,
)
# Submit the certificate request
cert = self.interface.request(csr_der, attributes)
if cert is False or cert is None:
logging.error("Failed to request certificate")
return False
return handle_request_response(
cert,
key,
username,
subject=self.subject,
alt_sid=self.alt_sid,
out=self.out,
pfx_password=self.pfx_password,
) |
Request a new certificate from AD CS.
Returns:
PFX data and filename if successful, False otherwise
| request | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def get_cax(self) -> Union[bool, bytes]:
"""
Retrieve the CAX (Exchange) certificate.
Returns:
CAX certificate in DER format if successful, False otherwise
"""
ca = CA(self.target, self.ca)
logging.info("Trying to retrieve CAX certificate")
cax_cert = ca.get_exchange_certificate()
logging.info("Retrieved CAX certificate")
cax_cert_der = cert_to_der(cax_cert)
return cax_cert_der |
Retrieve the CAX (Exchange) certificate.
Returns:
CAX certificate in DER format if successful, False otherwise
| get_cax | python | ly4k/Certipy | certipy/lib/req.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/req.py | MIT |
def get_dcom_connection(target: Target) -> DCOMConnection:
"""
Establish a DCOM connection to the target.
Args:
target: Target object containing connection parameters
Returns:
DCOMConnection object for the target
Notes:
Uses Kerberos authentication if target.do_kerberos is True
"""
tgs = None
username = target.username
domain = target.domain
logging.debug(f"Trying to get DCOM connection for: {target.target_ip!r}")
# Get Kerberos ticket if needed
if target.do_kerberos:
if not target.remote_name:
logging.warning("Target remote name is not set.")
kdc_rep, cipher, session_key, username, domain = get_tgs(
target,
target_name=target.remote_name,
)
tgs = {"KDC_REP": kdc_rep, "cipher": cipher, "sessionKey": session_key}
# Create DCOM connection
dcom = DCOMConnection(
target.target_ip,
username=username,
password=target.password or "",
domain=domain,
lmhash=target.lmhash,
nthash=target.nthash,
TGS=tgs,
doKerberos=target.do_kerberos,
kdcHost=target.dc_ip,
)
return dcom |
Establish a DCOM connection to the target.
Args:
target: Target object containing connection parameters
Returns:
DCOMConnection object for the target
Notes:
Uses Kerberos authentication if target.do_kerberos is True
| get_dcom_connection | python | ly4k/Certipy | certipy/lib/rpc.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/rpc.py | MIT |
def get_dce_rpc_from_string_binding(
string_binding: str,
target: Target,
timeout: int = 5,
target_ip: Optional[str] = None,
remote_name: Optional[str] = None,
auth_level: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
) -> rpcrt.DCERPC_v5:
"""
Create a DCE RPC connection from a string binding.
Args:
string_binding: The RPC string binding (e.g., "ncacn_np:server[pipe]")
target: Target object containing authentication parameters
timeout: Connection timeout in seconds
target_ip: Override target IP address (uses target.target_ip if None)
remote_name: Override remote name (uses target.remote_name if None)
auth_level: Authentication level for the connection
Returns:
Configured DCERPC_v5 object (not connected)
Notes:
The returned object needs to be connected with dce.connect()
"""
if target_ip is None:
target_ip = target.target_ip or ""
if remote_name is None:
remote_name = target.remote_name
# Create RPC transport
rpctransport = transport.DCERPCTransportFactory(string_binding)
rpctransport.setRemoteHost(target_ip)
rpctransport.setRemoteName(remote_name)
rpctransport.set_connect_timeout(timeout)
rpctransport.set_kerberos(target.do_kerberos, kdcHost=target.dc_ip)
username = target.username
domain = target.domain
tgs = None
# Get Kerberos ticket if needed
if target.do_kerberos:
if not remote_name:
logging.warning("Target remote name is not set.")
kdc_rep, cipher, session_key, username, domain = get_tgs(
target,
target_name=remote_name,
)
tgs = {"KDC_REP": kdc_rep, "cipher": cipher, "sessionKey": session_key}
# Set credentials on the transport
rpctransport.set_credentials(
username,
target.password,
domain,
target.lmhash,
target.nthash,
TGS=tgs,
)
# Get DCE RPC object and configure it
dce = rpctransport.get_dce_rpc()
dce.set_auth_level(auth_level)
if target.do_kerberos:
dce.set_auth_type(rpcrt.RPC_C_AUTHN_GSS_NEGOTIATE)
return dce |
Create a DCE RPC connection from a string binding.
Args:
string_binding: The RPC string binding (e.g., "ncacn_np:server[pipe]")
target: Target object containing authentication parameters
timeout: Connection timeout in seconds
target_ip: Override target IP address (uses target.target_ip if None)
remote_name: Override remote name (uses target.remote_name if None)
auth_level: Authentication level for the connection
Returns:
Configured DCERPC_v5 object (not connected)
Notes:
The returned object needs to be connected with dce.connect()
| get_dce_rpc_from_string_binding | python | ly4k/Certipy | certipy/lib/rpc.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/rpc.py | MIT |
def get_dynamic_endpoint(
interface: bytes, target: str, timeout: int = 5
) -> Optional[str]:
"""
Resolve a dynamic endpoint for an RPC interface.
Args:
interface: RPC interface identifier (UUID)
target: Target hostname or IP address
timeout: Connection timeout in seconds
Returns:
Resolved endpoint string or None if resolution fails
Notes:
Uses the endpoint mapper (port 135) to resolve the dynamic endpoint
"""
string_binding = f"ncacn_ip_tcp:{target}[135]"
rpctransport = transport.DCERPCTransportFactory(string_binding)
rpctransport.set_connect_timeout(timeout)
dce = rpctransport.get_dce_rpc()
interface_str = uuid.bin_to_string(interface)
logging.debug(f"Trying to resolve dynamic endpoint {interface_str}")
# Connect to endpoint mapper
try:
dce.connect()
except Exception as e:
logging.warning(f"Failed to connect to endpoint mapper: {e}")
handle_error(True)
return None
# Try to resolve endpoint
try:
endpoint = epm.hept_map(target, interface, protocol="ncacn_ip_tcp", dce=dce)
logging.debug(f"Resolved dynamic endpoint {interface_str} to {endpoint}")
return endpoint
except Exception as e:
logging.warning(f"Failed to resolve dynamic endpoint {interface_str}: {e}")
handle_error(True)
return None |
Resolve a dynamic endpoint for an RPC interface.
Args:
interface: RPC interface identifier (UUID)
target: Target hostname or IP address
timeout: Connection timeout in seconds
Returns:
Resolved endpoint string or None if resolution fails
Notes:
Uses the endpoint mapper (port 135) to resolve the dynamic endpoint
| get_dynamic_endpoint | python | ly4k/Certipy | certipy/lib/rpc.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/rpc.py | MIT |
def get_dce_rpc(
interface: bytes,
named_pipe: str,
target: Target,
timeout: int = 5,
dynamic: bool = False,
auth_level_np: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
auth_level_dyn: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
) -> Optional[rpcrt.DCERPC_v5]:
"""
Get a connected DCE RPC interface.
This function attempts to connect to an RPC interface using either named pipes
or dynamic endpoints. It will try multiple methods if the first fails.
Args:
interface: RPC interface identifier (UUID)
named_pipe: Named pipe path to connect to
target: Target object containing connection parameters
timeout: Connection timeout in seconds
dynamic: If True, try dynamic endpoint first, otherwise try named pipe first
auth_level_np: Authentication level for named pipe connections
auth_level_dyn: Authentication level for dynamic endpoint connections
Returns:
Connected DCERPC_v5 object or None if all connection attempts fail
"""
def _try_binding(string_binding: str, auth_level: int) -> Optional[rpcrt.DCERPC_v5]:
"""Try to connect to a specific string binding."""
dce = get_dce_rpc_from_string_binding(
string_binding, target, timeout, auth_level=auth_level
)
logging.debug(f"Trying to connect to endpoint: {string_binding}")
try:
dce.connect()
except Exception as e:
if is_verbose():
logging.warning(f"Failed to connect to endpoint {string_binding}: {e}")
handle_error(True)
return None
logging.debug(f"Connected to endpoint: {string_binding}")
# Bind to the interface
try:
_ = dce.bind(interface)
return dce
except Exception as e:
if is_verbose():
logging.warning(f"Failed to bind to interface: {e}")
handle_error(True)
return None
def _try_np() -> Optional[rpcrt.DCERPC_v5]:
"""Try named pipe connection."""
if not target.target_ip:
logging.error("Target IP is not set")
return None
string_binding = f"ncacn_np:{target.target_ip}[{named_pipe}]"
return _try_binding(string_binding, auth_level=auth_level_np)
def _try_dyn() -> Optional[rpcrt.DCERPC_v5]:
"""Try dynamic endpoint connection."""
if not target.target_ip:
logging.error("Target IP is not set")
return None
string_binding = get_dynamic_endpoint(interface, target.target_ip, timeout)
if string_binding is None:
# Possible errors:
# - TCP Port 135 is firewalled off
# - Service is not running
logging.error(
f"Failed to get dynamic TCP endpoint for {uuid.bin_to_string(interface)}"
)
return None
return _try_binding(string_binding, auth_level=auth_level_dyn)
# Determine which method to try first
methods = [_try_dyn, _try_np] if dynamic else [_try_np, _try_dyn]
# Try connection methods in order
for method in methods:
dce = method()
if dce is not None:
return dce
return None |
Get a connected DCE RPC interface.
This function attempts to connect to an RPC interface using either named pipes
or dynamic endpoints. It will try multiple methods if the first fails.
Args:
interface: RPC interface identifier (UUID)
named_pipe: Named pipe path to connect to
target: Target object containing connection parameters
timeout: Connection timeout in seconds
dynamic: If True, try dynamic endpoint first, otherwise try named pipe first
auth_level_np: Authentication level for named pipe connections
auth_level_dyn: Authentication level for dynamic endpoint connections
Returns:
Connected DCERPC_v5 object or None if all connection attempts fail
| get_dce_rpc | python | ly4k/Certipy | certipy/lib/rpc.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/rpc.py | MIT |
def _try_binding(string_binding: str, auth_level: int) -> Optional[rpcrt.DCERPC_v5]:
"""Try to connect to a specific string binding."""
dce = get_dce_rpc_from_string_binding(
string_binding, target, timeout, auth_level=auth_level
)
logging.debug(f"Trying to connect to endpoint: {string_binding}")
try:
dce.connect()
except Exception as e:
if is_verbose():
logging.warning(f"Failed to connect to endpoint {string_binding}: {e}")
handle_error(True)
return None
logging.debug(f"Connected to endpoint: {string_binding}")
# Bind to the interface
try:
_ = dce.bind(interface)
return dce
except Exception as e:
if is_verbose():
logging.warning(f"Failed to bind to interface: {e}")
handle_error(True)
return None | Try to connect to a specific string binding. | _try_binding | python | ly4k/Certipy | certipy/lib/rpc.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/rpc.py | MIT |
def __init__(self, security_descriptor: bytes):
"""
Initialize a security descriptor parser.
Args:
security_descriptor: Binary representation of a security descriptor
"""
if self.RIGHTS_TYPE is None:
raise NotImplementedError("Subclasses must define RIGHTS_TYPE")
# Parse the security descriptor
self.sd = ldaptypes.SR_SECURITY_DESCRIPTOR()
self.sd.fromString(security_descriptor)
# Extract owner SID
self.owner = format_sid(self.sd["OwnerSid"].getData())
# Dictionary to store access control entries by SID
self.aces: Dict[str, Dict[str, Any]] = {}
# Parse the ACEs
self._parse_aces() |
Initialize a security descriptor parser.
Args:
security_descriptor: Binary representation of a security descriptor
| __init__ | python | ly4k/Certipy | certipy/lib/security.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/security.py | MIT |
def _parse_aces(self) -> None:
"""
Parse the access control entries from the security descriptor.
This method extracts both standard rights and extended rights.
"""
aces = self.sd["Dacl"]["Data"]
# TODO: Handle DENIED ACEs
for ace in aces:
sid = format_sid(ace["Ace"]["Sid"].getData())
# Initialize entry for this SID if not already present
if sid not in self.aces:
self.aces[sid] = {
"rights": self.RIGHTS_TYPE(0),
"extended_rights": [],
"inherited": bool(ace["AceFlags"] & INHERITED_ACE),
}
# Process standard access allowed ACE
if ace["AceType"] == ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:
self.aces[sid]["rights"] |= self.RIGHTS_TYPE(ace["Ace"]["Mask"]["Mask"])
# Process object-specific ACE (for extended rights)
elif ace["AceType"] == ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE and ace[
"Ace"
]["Mask"].hasPriv(
ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS
):
self.aces[sid]["rights"] |= self.RIGHTS_TYPE(ace["Ace"]["Mask"]["Mask"])
# Extract the specific extended right (identified by UUID)
if ace["Ace"].hasFlag(
ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT
):
uuid = bin_to_string(ace["Ace"]["ObjectType"]).lower()
else:
# If no specific GUID is provided, this grants all extended rights
# https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/1522b774-6464-41a3-87a5-1e5633c3fbbb
uuid = EXTENDED_RIGHTS_NAME_MAP["All-Extended-Rights"]
self.aces[sid]["extended_rights"].append(uuid) |
Parse the access control entries from the security descriptor.
This method extracts both standard rights and extended rights.
| _parse_aces | python | ly4k/Certipy | certipy/lib/security.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/security.py | MIT |
def _parse_aces(self) -> None:
"""
Parse the access control entries from the security descriptor.
CA security descriptors have a simpler structure than AD security descriptors.
"""
aces = self.sd["Dacl"]["Data"]
for ace in aces:
sid = format_sid(ace["Ace"]["Sid"].getData())
if sid not in self.aces:
self.aces[sid] = {
"rights": self.RIGHTS_TYPE(0),
"extended_rights": [], # CAs don't use extended rights, but keeping for consistency
"inherited": bool(ace["AceFlags"] & INHERITED_ACE),
}
if ace["AceType"] == ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:
mask = self.RIGHTS_TYPE(ace["Ace"]["Mask"]["Mask"])
self.aces[sid]["rights"] |= mask |
Parse the access control entries from the security descriptor.
CA security descriptors have a simpler structure than AD security descriptors.
| _parse_aces | python | ly4k/Certipy | certipy/lib/security.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/security.py | MIT |
def is_admin_sid(sid: str) -> bool:
"""
Check if a security identifier (SID) belongs to an administrative group.
This function identifies built-in administrator accounts and groups by their well-known SIDs.
Args:
sid: The security identifier to check
Returns:
True if the SID belongs to an administrative group, False otherwise
Common Admin SIDs:
- S-1-5-21-*-498: Enterprise Read-Only Domain Controllers group
- S-1-5-21-*-500: Built-in Administrator account
- S-1-5-21-*-502: Krbtgt account
- S-1-5-21-*-512: Domain Admins group
- S-1-5-21-*-516: Domain Controllers group
- S-1-5-21-*-518: Schema Admins group
- S-1-5-21-*-519: Enterprise Admins group
- S-1-5-21-*-521: Read-only Domain Controllers group
- S-1-5-32-544: Built-in Administrators group
- S-1-5-9: Enterprise Domain Controllers
"""
admin_rid_pattern = "^S-1-5-21-.+-(498|500|502|512|516|518|519|521)$"
builtin_admin_sids = ["S-1-5-9", "S-1-5-32-544"]
return re.match(admin_rid_pattern, sid) is not None or sid in builtin_admin_sids |
Check if a security identifier (SID) belongs to an administrative group.
This function identifies built-in administrator accounts and groups by their well-known SIDs.
Args:
sid: The security identifier to check
Returns:
True if the SID belongs to an administrative group, False otherwise
Common Admin SIDs:
- S-1-5-21-*-498: Enterprise Read-Only Domain Controllers group
- S-1-5-21-*-500: Built-in Administrator account
- S-1-5-21-*-502: Krbtgt account
- S-1-5-21-*-512: Domain Admins group
- S-1-5-21-*-516: Domain Controllers group
- S-1-5-21-*-518: Schema Admins group
- S-1-5-21-*-519: Enterprise Admins group
- S-1-5-21-*-521: Read-only Domain Controllers group
- S-1-5-32-544: Built-in Administrators group
- S-1-5-9: Enterprise Domain Controllers
| is_admin_sid | python | ly4k/Certipy | certipy/lib/security.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/security.py | MIT |
def create_authenticated_users_sd() -> ldaptypes.SR_SECURITY_DESCRIPTOR:
"""
Create a security descriptor for the "Authenticated Users" group.
This security descriptor grants the "Authenticated Users" group
the right to read the object and its properties.
"""
sd = ldaptypes.SR_SECURITY_DESCRIPTOR()
sd["Revision"] = b"\x01"
sd["Sbz1"] = b"\x00"
sd["Control"] = (
SE_DACL_PRESENT
| SE_DACL_AUTO_INHERITED
| SE_SACL_AUTO_INHERITED
| SE_DACL_PROTECTED
| SE_SELF_RELATIVE
)
sd["OwnerSid"] = ldaptypes.LDAP_SID()
sd["OwnerSid"].fromCanonical("S-1-5-11")
sd["GroupSid"] = b""
sd["Sacl"] = b""
ace = ldaptypes.ACE()
ace["AceType"] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE
ace["AceFlags"] = 0
ace_data = ldaptypes.ACCESS_ALLOWED_ACE()
ace_data["Mask"] = ldaptypes.ACCESS_MASK()
ace_data["Mask"]["Mask"] = CertificateRights.GENERIC_ALL
ace_data["Sid"] = ldaptypes.LDAP_SID()
ace_data["Sid"].fromCanonical("S-1-5-11")
ace["Ace"] = ace_data
acl = ldaptypes.ACL()
acl["AclRevision"] = 2
acl["Sbz1"] = 0
acl["Sbz2"] = 0
acl.aces = []
acl.aces.append(ace)
sd["Dacl"] = acl
# Convert aces to data
sd_data = sd.getData()
sd = ldaptypes.SR_SECURITY_DESCRIPTOR()
sd.fromString(sd_data)
return sd |
Create a security descriptor for the "Authenticated Users" group.
This security descriptor grants the "Authenticated Users" group
the right to read the object and its properties.
| create_authenticated_users_sd | python | ly4k/Certipy | certipy/lib/security.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/security.py | MIT |
def to_list(self) -> List["IntFlag"]:
"""
Decompose flag into list of individual flags.
Returns:
List of individual flag members
"""
if not self._value_:
return []
# Get all individual flags that make up this value
return [
flag for flag in self.__class__ if flag.value and flag.value & self._value_
] |
Decompose flag into list of individual flags.
Returns:
List of individual flag members
| to_list | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def to_str_list(self) -> List[str]:
"""
Return list of flag names.
Returns:
List of flag names
"""
return [
to_pascal_case(flag.name)
for flag in self.to_list()
if flag.name is not None
] |
Return list of flag names.
Returns:
List of flag names
| to_str_list | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def __str__(self) -> str:
"""
Smart string representation that handles combinations gracefully.
Returns:
Human-readable string representation of the flag(s)
"""
# Handle named values
if self.name is not None:
return to_pascal_case(self.name)
# Handle empty flags
if not self._value_:
return ""
# Get individual flags
flags = self.to_list()
# If no decomposition was possible, return the raw value
if not flags:
return repr(self._value_)
# Return comma-separated list of flag names
return ", ".join(
to_pascal_case(flag.name) for flag in flags if flag.name is not None
) |
Smart string representation that handles combinations gracefully.
Returns:
Human-readable string representation of the flag(s)
| __str__ | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def to_list(self) -> List["Flag"]:
"""
Decompose flag into list of individual flags.
Returns:
List of individual flag members
"""
if not self._value_:
return []
# Get all individual flags that make up this value
return [
flag for flag in self.__class__ if flag.value and flag.value & self._value_
] |
Decompose flag into list of individual flags.
Returns:
List of individual flag members
| to_list | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def to_str_list(self) -> List[str]:
"""
Return list of flag names.
Returns:
List of flag names
"""
return [
to_pascal_case(flag.name)
for flag in self.to_list()
if flag.name is not None
] |
Return list of flag names.
Returns:
List of flag names
| to_str_list | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def __str__(self) -> str:
"""
Smart string representation that handles combinations gracefully.
Returns:
Human-readable string representation of the flag(s)
"""
# Handle named values
if self.name is not None:
return to_pascal_case(self.name)
# Handle empty flags
if not self._value_:
return ""
# Get individual flags
flags = self.to_list()
# If no decomposition was possible, return the raw value
if not flags:
return repr(self._value_)
# Return comma-separated list of flag names
return ", ".join(
to_pascal_case(flag.name) for flag in flags if flag.name is not None
) |
Smart string representation that handles combinations gracefully.
Returns:
Human-readable string representation of the flag(s)
| __str__ | python | ly4k/Certipy | certipy/lib/structs.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/structs.py | MIT |
def __init__(
self,
resolver: "DnsResolver",
domain: str = "",
username: str = "",
password: Optional[str] = None,
remote_name: str = "",
hashes: Optional[str] = None,
lmhash: str = "",
nthash: str = "",
do_kerberos: bool = False,
do_simple: bool = False,
aes: Optional[str] = None,
dc_ip: Optional[str] = None,
dc_host: Optional[str] = None,
target_ip: Optional[str] = None,
timeout: int = 5,
ldap_scheme: str = "ldaps",
ldap_port: Optional[int] = None,
ldap_channel_binding: bool = True,
ldap_signing: bool = True,
ldap_user_dn: Optional[str] = None,
) -> None:
"""
Initialize a Target with the specified connection parameters.
Args:
resolver: DNS resolver for hostname resolution
domain: Domain name (empty string if not specified)
username: Username (empty string if not specified)
password: Password (None if not specified)
remote_name: Remote target name (empty string if not specified)
hashes: NTLM hashes in format LM:NT
lmhash: LM hash
nthash: NT hash
do_kerberos: Use Kerberos authentication
do_simple: Use simple authentication
aes: AES key for Kerberos authentication
dc_ip: Domain controller IP
dc_host: Domain controller hostname
target_ip: Target IP address
timeout: Connection timeout in seconds
ldap_scheme: LDAP scheme (default is ldaps)
ldap_port: LDAP port to use
ldap_channel_binding: Use LDAP channel binding
ldap_signing: Use LDAP signing
ldap_user_dn: LDAP user distinguished name
"""
self.resolver = resolver
self.domain: str = domain
self.username: str = username
self.password: Optional[str] = password
self.remote_name: str = remote_name
self.hashes: Optional[str] = hashes
self.lmhash: str = lmhash
self.nthash: str = nthash
self.do_kerberos: bool = do_kerberos
self.do_simple: bool = do_simple
self.aes: Optional[str] = aes
self.dc_ip: Optional[str] = dc_ip
self.dc_host: Optional[str] = dc_host
self.target_ip: Optional[str] = target_ip
self.timeout: int = timeout
self.ldap_scheme: str = ldap_scheme
self.ldap_port: Optional[int] = ldap_port
self.ldap_channel_binding: bool = ldap_channel_binding
self.ldap_signing: bool = ldap_signing
self.ldap_user_dn: Optional[str] = ldap_user_dn |
Initialize a Target with the specified connection parameters.
Args:
resolver: DNS resolver for hostname resolution
domain: Domain name (empty string if not specified)
username: Username (empty string if not specified)
password: Password (None if not specified)
remote_name: Remote target name (empty string if not specified)
hashes: NTLM hashes in format LM:NT
lmhash: LM hash
nthash: NT hash
do_kerberos: Use Kerberos authentication
do_simple: Use simple authentication
aes: AES key for Kerberos authentication
dc_ip: Domain controller IP
dc_host: Domain controller hostname
target_ip: Target IP address
timeout: Connection timeout in seconds
ldap_scheme: LDAP scheme (default is ldaps)
ldap_port: LDAP port to use
ldap_channel_binding: Use LDAP channel binding
ldap_signing: Use LDAP signing
ldap_user_dn: LDAP user distinguished name
| __init__ | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def from_options(
options: argparse.Namespace,
dc_as_target: bool = False,
require_username: bool = True,
) -> "Target":
"""
Create a Target from command line options.
Args:
options: Command line options
dc_as_target: Whether to use DC as target
Returns:
Target: Configured target object
Raises:
Exception: If no target can be determined
"""
# Domain controller options
dc_ip = options.dc_ip if hasattr(options, "dc_ip") else None
dc_host = options.dc_host if hasattr(options, "dc_host") else None
# Target machine options
target_ip = options.target_ip if hasattr(options, "target_ip") else None
target = options.target if hasattr(options, "target") else None
# DNS options
ns = options.ns if hasattr(options, "ns") else dc_ip
dns_tcp = options.dns_tcp if hasattr(options, "dns_tcp") else False
# Connection options
timeout = options.timeout if hasattr(options, "timeout") else 10
# Authentication options
principal = options.username if hasattr(options, "username") else None
password = options.password if hasattr(options, "password") else None
hashes = options.hashes if hasattr(options, "hashes") else None
do_kerberos = options.do_kerberos if hasattr(options, "do_kerberos") else False
do_simple = options.do_simple if hasattr(options, "do_simple") else False
aes = options.aes if hasattr(options, "aes") else None
no_pass = options.no_pass if hasattr(options, "no_pass") else False
# LDAP options
ldap_scheme = (
options.ldap_scheme if hasattr(options, "ldap_scheme") else "ldaps"
)
ldap_port = options.ldap_port if hasattr(options, "ldap_port") else None
no_ldap_channel_binding = (
options.no_ldap_channel_binding
if hasattr(options, "no_ldap_channel_binding")
else False
)
no_ldap_signing = (
options.no_ldap_signing if hasattr(options, "no_ldap_signing") else False
)
ldap_user_dn = (
options.ldap_user_dn if hasattr(options, "ldap_user_dn") else None
)
# Parse username and domain from principal format (user@DOMAIN)
domain = ""
username = ""
if principal is not None:
parts = principal.split("@")
if len(parts) == 1:
username = parts[0]
else:
username = "@".join(parts[:-1])
domain = parts[-1]
# Handle Kerberos authentication
if do_kerberos:
principal = get_kerberos_principal()
if principal:
username, domain = principal
# Normalize domain and username
domain = domain.upper()
username = username.upper()
if require_username and len(username) == 0:
logging.error("Username is not specified")
# Handle password input
if (
not password
and username != ""
and hashes is None
and aes is None
and no_pass is not True
and do_kerberos is not True
):
from getpass import getpass
password = getpass("Password:")
# Parse hashes if provided
lmhash = ""
nthash = ""
if hashes is not None:
hash_parts = hashes.split(":")
if len(hash_parts) == 1:
nthash = hash_parts[0]
lmhash = nthash
else:
lmhash, nthash = hash_parts
if len(lmhash) == 0:
lmhash = nthash
# AES key implies Kerberos
if aes is not None:
do_kerberos = True
# Determine remote target name
remote_name = target or ""
if do_kerberos and not remote_name:
logging.warning(
"Target name (-target) not specified and Kerberos authentication is used. This might fail"
)
if dc_as_target:
if not remote_name and dc_host:
remote_name = dc_host
if not remote_name:
logging.debug(
f"Target name (-target) and DC host (-dc-host) not specified. Using domain {domain!r} as target name. This might fail for cross-realm operations"
)
remote_name = domain
if not target_ip and dc_ip:
target_ip = dc_ip
if not dc_host:
dc_host = remote_name
else:
if not dc_host and domain:
if do_kerberos:
logging.warning(
"DC host (-dc-host) not specified and Kerberos authentication is used. This might fail"
)
logging.debug(
"DC host (-dc-host) not specified. Using domain as DC host"
)
dc_host = domain
if not remote_name:
if target_ip:
remote_name = target_ip
elif dc_host:
remote_name = dc_host
elif dc_ip:
remote_name = dc_ip
elif domain:
remote_name = domain
else:
raise Exception("Could not find a target in the specified options")
# Configure LDAP optinos
if ldap_port is None:
if ldap_scheme == "ldap":
ldap_port = 389
else:
ldap_port = 636
# Adjust DC IP if needed
if dc_as_target and dc_ip is None and is_ip(remote_name):
dc_ip = remote_name
# Handle target IP
if is_ip(remote_name):
target_ip = remote_name
ns = ns or dc_ip
logging.debug(f"Nameserver: {ns!r}")
logging.debug(f"DC IP: {dc_ip!r}")
logging.debug(f"DC Host: {dc_host!r}")
logging.debug(f"Target IP: {target_ip!r}")
logging.debug(f"Remote Name: {remote_name!r}")
logging.debug(f"Domain: {domain!r}")
logging.debug(f"Username: {username!r}")
resolver = DnsResolver.create(ns=ns, dc_ip=dc_ip, dns_tcp=dns_tcp)
if target_ip is None:
target_ip = resolver.resolve(remote_name)
# Ensure DC IP is resolved
if dc_ip is None and dc_host:
dc_ip = resolver.resolve(dc_host)
# Create target instance
target = Target(
resolver,
domain=domain,
username=username,
password=password,
remote_name=remote_name,
hashes=hashes,
lmhash=lmhash,
nthash=nthash,
aes=aes,
do_kerberos=do_kerberos,
do_simple=do_simple,
dc_ip=dc_ip,
dc_host=dc_host,
target_ip=target_ip,
timeout=timeout,
ldap_scheme=ldap_scheme,
ldap_channel_binding=not no_ldap_channel_binding,
ldap_signing=not no_ldap_signing,
ldap_port=ldap_port,
ldap_user_dn=ldap_user_dn,
)
return target |
Create a Target from command line options.
Args:
options: Command line options
dc_as_target: Whether to use DC as target
Returns:
Target: Configured target object
Raises:
Exception: If no target can be determined
| from_options | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def __init__(self) -> None:
"""Initialize a new DNS resolver with default settings."""
self.resolver: Resolver = Resolver()
self.use_tcp: bool = False
self.mappings: Dict[str, str] = {} | Initialize a new DNS resolver with default settings. | __init__ | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def from_options(options: argparse.Namespace, target: "Target") -> "DnsResolver":
"""
Create a DnsResolver from command line options.
Args:
options: The command line options
target: The Target object
Returns:
DnsResolver: A configured DNS resolver
"""
resolver = DnsResolver()
# We can't put all possible nameservers in the list of nameservers, since
# the resolver will fail if one of them fails
nameserver = options.ns
if nameserver is None:
nameserver = target.dc_ip
if nameserver is not None:
resolver.resolver.nameservers = [nameserver]
resolver.use_tcp = options.dns_tcp
return resolver |
Create a DnsResolver from command line options.
Args:
options: The command line options
target: The Target object
Returns:
DnsResolver: A configured DNS resolver
| from_options | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def create(
ns: Optional[str] = None,
dc_ip: Optional[str] = None,
dns_tcp: bool = False,
) -> "DnsResolver":
"""
Create a DnsResolver with specified parameters.
Args:
target: Target object which may contain DC IP information
ns: Nameserver to use
dns_tcp: Whether to use TCP for DNS queries
Returns:
DnsResolver: A configured DNS resolver
"""
resolver = DnsResolver()
# We can't put all possible nameservers in the list of nameservers, since
# the resolver will fail if one of them fails
nameserver = ns or dc_ip
if nameserver is not None:
resolver.resolver.nameservers = [nameserver]
resolver.use_tcp = dns_tcp
return resolver |
Create a DnsResolver with specified parameters.
Args:
target: Target object which may contain DC IP information
ns: Nameserver to use
dns_tcp: Whether to use TCP for DNS queries
Returns:
DnsResolver: A configured DNS resolver
| create | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def resolve(self, hostname: str) -> str:
"""
Resolve hostname to IP address using DNS or local resolution.
Uses cache for previously resolved hostnames.
Args:
hostname: The hostname to resolve
Returns:
str: The resolved IP address or the original hostname if resolution fails
"""
# Try to resolve the hostname with DNS first, then try a local resolve
if hostname in self.mappings:
logging.debug(
f"Resolved {hostname!r} from cache: {self.mappings[hostname]}"
)
return self.mappings[hostname]
if is_ip(hostname):
return hostname
ip_addr = None
if not self.resolver.nameservers:
logging.debug(f"Trying to resolve {hostname!r} locally")
else:
logging.debug(
f"Trying to resolve {hostname!r} at {self.resolver.nameservers[0]!r}"
)
# Try DNS resolution first
try:
answers = self.resolver.resolve(hostname, tcp=self.use_tcp)
if answers:
ip_addr = str(answers[0])
except Exception as e:
logging.warning(f"DNS resolution failed: {e}")
handle_error(True)
pass
# Fall back to socket resolution
if ip_addr is None:
try:
ip_addr = socket.gethostbyname(hostname)
except Exception:
ip_addr = None
if ip_addr is None:
logging.warning(f"Failed to resolve: {hostname}")
return hostname
self.mappings[hostname] = ip_addr
return ip_addr |
Resolve hostname to IP address using DNS or local resolution.
Uses cache for previously resolved hostnames.
Args:
hostname: The hostname to resolve
Returns:
str: The resolved IP address or the original hostname if resolution fails
| resolve | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def is_ip(hostname: Optional[str]) -> bool:
"""
Check if the given hostname is an IP address.
Args:
hostname: The hostname to check
Returns:
bool: True if the hostname is an IP address, False otherwise
"""
if hostname is None:
return False
try:
_ = socket.inet_aton(hostname)
return True
except Exception:
return False |
Check if the given hostname is an IP address.
Args:
hostname: The hostname to check
Returns:
bool: True if the hostname is an IP address, False otherwise
| is_ip | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def get_kerberos_principal() -> Optional[Tuple[str, str]]:
"""
Get Kerberos principal information from the KRB5CCNAME environment variable.
Returns:
Tuple containing (username, domain) or None if not available
"""
krb5ccname = os.getenv("KRB5CCNAME")
if krb5ccname is None:
logging.warning("KRB5CCNAME environment variable not set")
return None
try:
ccache = CCache.loadFile(krb5ccname)
except Exception:
return None
if ccache is None:
return None
if ccache.principal is None:
logging.error("No principal found in CCache file")
return None
if ccache.principal.realm is None:
logging.error("No realm/domain found in CCache file")
return None
domain = ccache.principal.realm["data"].decode("utf-8")
logging.debug(f"Domain retrieved from CCache: {domain}")
username = "/".join(map(lambda x: x["data"].decode(), ccache.principal.components))
logging.debug(f"Username retrieved from CCache: {username}")
return username, domain |
Get Kerberos principal information from the KRB5CCNAME environment variable.
Returns:
Tuple containing (username, domain) or None if not available
| get_kerberos_principal | python | ly4k/Certipy | certipy/lib/target.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/target.py | MIT |
def filetime_to_span(filetime: bytes) -> int:
"""
Convert Windows FILETIME to time span in seconds.
Windows FILETIME is a 64-bit value representing the number of
100-nanosecond intervals since January 1, 1601 UTC.
When used for validity periods, negative values represent time remaining.
Args:
filetime: Windows FILETIME as 8 bytes
Returns:
Time span in seconds (absolute value)
Raises:
struct.error: If the input bytes cannot be unpacked as a 64-bit integer
"""
# Unpack the 8-byte FILETIME as a 64-bit integer (little-endian)
(span,) = struct.unpack("<q", filetime)
# Convert from 100-nanosecond intervals to seconds
span *= FILETIME_CONVERSION_FACTOR
return int(span) |
Convert Windows FILETIME to time span in seconds.
Windows FILETIME is a 64-bit value representing the number of
100-nanosecond intervals since January 1, 1601 UTC.
When used for validity periods, negative values represent time remaining.
Args:
filetime: Windows FILETIME as 8 bytes
Returns:
Time span in seconds (absolute value)
Raises:
struct.error: If the input bytes cannot be unpacked as a 64-bit integer
| filetime_to_span | python | ly4k/Certipy | certipy/lib/time.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/time.py | MIT |
def span_to_filetime(span: int) -> bytes:
"""
Convert a time span in seconds to Windows FILETIME format.
This function converts the time span to a 64-bit integer representing
the number of 100-nanosecond intervals since January 1, 1601 UTC.
Args:
span: Time span in seconds (positive integer)
Returns:
Windows FILETIME as 8 bytes
Raises:
ValueError: If the input span is negative
"""
if span < 0:
raise ValueError("Span must be a positive integer")
# Convert seconds to 100-nanosecond intervals
filetime = int(span / FILETIME_CONVERSION_FACTOR)
# Pack as little-endian 64-bit integer
return struct.pack("<q", filetime) |
Convert a time span in seconds to Windows FILETIME format.
This function converts the time span to a 64-bit integer representing
the number of 100-nanosecond intervals since January 1, 1601 UTC.
Args:
span: Time span in seconds (positive integer)
Returns:
Windows FILETIME as 8 bytes
Raises:
ValueError: If the input span is negative
| span_to_filetime | python | ly4k/Certipy | certipy/lib/time.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/time.py | MIT |
def span_to_str(span: int) -> str:
"""
Convert a time span in seconds to a human-readable string.
The function converts the span to the largest appropriate unit
(years, months, weeks, days, or hours) for readability.
Args:
span: Time span in seconds (positive integer)
Returns:
Human-readable time span (e.g., "1 year", "2 months", "3 weeks")
Empty string if span is negative or zero
"""
if span <= 0:
return ""
# Time unit conversion table
# (seconds_per_unit, singular_name, plural_name)
time_units = [
(SECONDS_PER_YEAR, "year", "years"),
(SECONDS_PER_MONTH, "month", "months"),
(SECONDS_PER_WEEK, "week", "weeks"),
(SECONDS_PER_DAY, "day", "days"),
(SECONDS_PER_HOUR, "hour", "hours"),
]
# Find the largest unit that divides span evenly
for seconds_per_unit, singular, plural in time_units:
if span % seconds_per_unit == 0 and span // seconds_per_unit >= 1:
unit_count = span // seconds_per_unit
return f"{unit_count} {singular if unit_count == 1 else plural}"
# If no exact match, return in seconds
return f"{span} seconds" |
Convert a time span in seconds to a human-readable string.
The function converts the span to the largest appropriate unit
(years, months, weeks, days, or hours) for readability.
Args:
span: Time span in seconds (positive integer)
Returns:
Human-readable time span (e.g., "1 year", "2 months", "3 weeks")
Empty string if span is negative or zero
| span_to_str | python | ly4k/Certipy | certipy/lib/time.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/time.py | MIT |
def filetime_to_str(filetime: bytes) -> str:
"""
Convert Windows FILETIME to a human-readable time span string.
This is a convenience function that combines filetime_to_span()
and span_to_str() operations.
Args:
filetime: Windows FILETIME as bytes
Returns:
Human-readable time span string
Example:
>>> filetime_bytes = struct.pack("<q", -315360000000000) # 1 year in FILETIME format
>>> filetime_to_str(filetime_bytes)
'1 year'
"""
try:
span = filetime_to_span(filetime)
return span_to_str(span)
except (struct.error, TypeError, ValueError) as e:
# Handle potential errors in the FILETIME format
return f"Invalid FILETIME format: {str(e)}" |
Convert Windows FILETIME to a human-readable time span string.
This is a convenience function that combines filetime_to_span()
and span_to_str() operations.
Args:
filetime: Windows FILETIME as bytes
Returns:
Human-readable time span string
Example:
>>> filetime_bytes = struct.pack("<q", -315360000000000) # 1 year in FILETIME format
>>> filetime_to_str(filetime_bytes)
'1 year'
| filetime_to_str | python | ly4k/Certipy | certipy/lib/time.py | https://github.com/ly4k/Certipy/blob/master/certipy/lib/time.py | MIT |
def __init__(self, serial: str, adb: ADBWrapper):
"""Initialize device.
Args:
serial: Device serial number
adb: ADB wrapper instance
"""
self._serial = serial
self._adb = adb
self._properties_cache: Dict[str, str] = {} | Initialize device.
Args:
serial: Device serial number
adb: ADB wrapper instance
| __init__ | python | droidrun/droidrun | droidrun/adb/device.py | https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py | MIT |
async def tap(self, x: int, y: int) -> None:
"""Tap at coordinates.
Args:
x: X coordinate
y: Y coordinate
"""
await self._adb.shell(self._serial, f"input tap {x} {y}") | Tap at coordinates.
Args:
x: X coordinate
y: Y coordinate
| tap | python | droidrun/droidrun | droidrun/adb/device.py | https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py | MIT |
async def swipe(
self,
start_x: int,
start_y: int,
end_x: int,
end_y: int,
duration_ms: int = 300
) -> None:
"""Perform swipe gesture.
Args:
start_x: Starting X coordinate
start_y: Starting Y coordinate
end_x: Ending X coordinate
end_y: Ending Y coordinate
duration_ms: Swipe duration in milliseconds
"""
await self._adb.shell(
self._serial,
f"input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}"
) | Perform swipe gesture.
Args:
start_x: Starting X coordinate
start_y: Starting Y coordinate
end_x: Ending X coordinate
end_y: Ending Y coordinate
duration_ms: Swipe duration in milliseconds
| swipe | python | droidrun/droidrun | droidrun/adb/device.py | https://github.com/droidrun/droidrun/blob/master/droidrun/adb/device.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.