Metasploit

Generate Shellcode with Metasploit: The Basics of the Generate Command

Picture yourself inside msfconsole, working through a penetration test. You have identified a vulnerable service, confirmed the exploit works, but now you need a payload that actually gives you control of the target system. This is where the generate command becomes essential. Metasploit's built-in payload generator lets you craft custom shellcode without writing assembly from scratch. A detailed walkthrough from CodeLivly covers the fundamentals every security tester needs to understand.

The guide focuses on Windows bind shell payloads, explaining how to create basic shellcode, exclude problematic characters, and apply encoding to make your payloads more resilient. Whether you are new to exploit development or need a quick reference, understanding generate is a core skill for anyone working with Metasploit.

At a Glance

  • Metasploit's generate command outputs shellcode directly from msfconsole without external tools
  • Payload selection automatically enables the generate command along with pry and reload
  • The -b flag excludes specified characters (bad characters) from generated shellcode
  • The -e flag selects a specific encoder; shikata_ga_nai is common for x86 targets
  • Encoders add size to payloads but remove unwanted characters and add obfuscation
  • Output formats include raw binary, C, Ruby, Python, Java, EXE, DLL, and many others
  • The -x flag lets you wrap shellcode inside an existing executable template

The Generate Command Explained

When you select a payload in msfconsole, the framework automatically makes several commands available. Running help after selecting a payload shows generate among them. Simply typing generate without arguments outputs raw shellcode directly to the console, ready to be copied or redirected to a file using the -f option.

The command supports numerous flags that control exactly what gets generated. The -h switch displays the full help banner, showing options for encoding, bad character exclusion, encoder selection, output format, and template usage. For most straightforward cases, the defaults work fine. You get raw shellcode in the console, which you can then pipe into your exploit or save to disk.

Output formats matter depending on your workflow. The raw format outputs pure shellcode bytes, suitable for embedding directly in exploits. Formats like C and Ruby let you embed the shellcode in programs written in those languages. The EXE and EXE-small formats create standalone executables you can run on targets. VBA and VBS formats work for Microsoft Office macros, while ASP and WAR targets web servers.

Working with Bad Characters

Raw shellcode generated without options often contains characters that cause problems. Null bytes (x00) terminate strings in many programming languages and memory contexts, breaking exploits that rely on string functions. Other characters like 0xFF may trigger filters or corrupt data during transmission. Identifying and excluding these bad characters is crucial for reliable exploitation.

The -b flag takes a list of hex characters to exclude. For a simple null byte exclusion, you run generate -b 'x00'. Metasploit then regenerates the shellcode, replacing or encoding those characters so they no longer appear in the output. This process adds size to the payload. In the CodeLivly example, a basic Windows bind shell was 341 bytes. After null byte exclusion, it grew to 368 bytes.

Why the size increase? Metasploit cannot simply delete unwanted bytes. It must encode them in ways that achieve the same functional result without using the forbidden characters. This often involves mathematical operations that produce the same values through different byte sequences. The tradeoff is predictable: cleaner payloads at the cost of additional bytes.

Encoders and Obfuscation

When you exclude bad characters, Metasploit automatically selects an appropriate encoder to handle the transformation. The encoder takes your base shellcode and mutates it to remove unwanted bytes while preserving functionality. For x86 Windows payloads, shikata_ga_nai is the default choice. This polymorphic encoder produces different byte sequences on each run while maintaining the same end behavior.

The -e flag lets you specify a particular encoder explicitly. Different encoders suit different architectures and use cases. Some prioritize small size, others emphasize evasion. The -i flag controls encoding iterations, running the encoder multiple times for additional obfuscation. More iterations mean more size and more mutation, which helps evade signature-based detection but makes payloads larger and slower to execute.

Encoders serve two purposes. First, they remove bad characters that would break exploitation. Second, they change the payload's binary signature to avoid detection by antivirus and intrusion prevention systems. Neither guarantee evasion, but both increase your chances of successful execution in real-world environments.

Our Analysis

Understanding payload generation sits at the intersection of offensive security skills. This guide covers the mechanics without providing context that would enable unauthorized attacks. That balance matters for educational content.

The focus on Windows bind shells reflects legacy attack methodologies. A bind shell opens a listening port on the target, waiting for connections. This approach works when the target accepts incoming connections, but many modern environments block inbound connections at firewalls or NAT boundaries. Reverse shells, which connect back from the target to the attacker, typically succeed more often because outbound connections are less restricted.

Penetration testers need these skills for legitimate security assessments. Vulnerability researchers use shellcode generation to understand how flaws get exploited. The underlying techniques appear in defensive tools too, as security teams study how attacks work to build better protections.

What separates effective security testers from script kiddies is understanding why these tools work, not just how to run them. Studying generate options, bad character handling, and encoder selection builds intuition that applies across different tools and scenarios.

A Worked Example

Say you are testing a web application with a known remote code execution vulnerability. Your initial exploit works in the lab, but in production it fails. You suspect null bytes in your payload are truncating the command string sent to the server.

You select a Linux command shell payload in msfconsole. Running generate produces shellcode containing null bytes. You add the -b flag to exclude x00, then use -f to write the result to a file. The new payload runs successfully against the production system because the server now receives and executes the complete command string.

This scenario illustrates why bad character handling matters in real engagements. Small details like character exclusion determine whether an exploit works or silently fails.

Bottom Line

Metasploit's generate command automates shellcode creation for authorized security testing. The framework handles complexity that would otherwise require hand-crafting assembly language, letting testers focus on finding and exploiting vulnerabilities rather than writing low-level code.

Master the basics covered here, understand why bad characters matter, and know when encoders help or hurt your goals. These fundamentals transfer to any payload generation work you encounter.

Key takeaways

  • Generate outputs shellcode directly from msfconsole without external compilation
  • Bad character exclusion (-b) prevents payload corruption but adds size
  • Encoders (-e) provide obfuscation and handle character removal automatically
  • Multiple encoding passes (-i) increase evasion chances at the cost of payload size
  • Output format (-t) should match your delivery mechanism and target environment
  • The -x flag wraps shellcode inside existing executables for social engineering scenarios

Frequently asked questions

What is bad character exclusion in shellcode generation?

Certain bytes like null characters terminate strings and break exploits. The -b flag tells Metasploit to avoid these characters entirely, regenerating shellcode to achieve the same result through alternative byte sequences.

What does shikata_ga_nai encoder do?

It is a polymorphic x86 encoder that mutates shellcode on each generation while maintaining identical functionality. This makes static signature detection harder because the same shellcode appears different each time.

Can I generate shellcode for platforms other than Windows?

Yes. Metasploit supports payloads for Linux, macOS, Android, iOS, and many other platforms and architectures. Select the appropriate payload module and generate accordingly.

What output formats does generate support?

Common formats include raw binary, C, Ruby, Python, Perl, Java, JavaScript, DLL, EXE, EXE-small, ELF, Mach-O, VBA, VBS, ASP, and WAR. Choose based on your delivery method and target environment.

Is this information only appropriate for legitimate security testing?

Yes. Shellcode generation knowledge applies only to authorized penetration testing, vulnerability research, and security education. Unauthorized access to computer systems is illegal.

Related