Archive for the ‘Security Testing’ Category

Porting Watcher checks to ModSecurity rules!

January 10th, 2012 by

Earlier this year, Ryan Barnett at TrustWave’s Spiderlabs started porting some of Watcher’s checks to ModSecurity.   After we chatted about this, I decided to get involved.  We always liked the idea of a server-side scanner watching the Web traffic, and since ModSecurity sits right in the sweet spot it all made sense to focus some effort there.

So over the past few months we’ve been working to port more of Watcher’s passive Web scanning checks to theModSecurity open source Web Application Firewall.  It seems to be working out, as some of the rules have made it into the latest release of ModSecurity’s Core Rule Set v2.2.3 as well as some earlier rule sets.  There’s more to come.  Please send any feedback to me or Ryan, and look for more rules to be added very soon.

Microsoft “Roslyn” based REPL injection.

December 12th, 2011 by

Microsoft recently released their new Compiler API codename “Roslyn”. If you haven’t checked it out yet you should. Here’s the link: http://msdn.microsoft.com/en-us/roslyn/.

I wanted to get my hands a little dirty and play with the new API. I’ve been meaning to look into Managed DLL injection for a while to get code execution for process interrogation. There are times when we’re testing that we want to interrogate a process for framework level information. For whatever reasons we sometimes can’t compile the target with hooks. So it would be nice to have a way to execute code. Roslyn’s CSX files look like a great way to accomplish this so that’s what I’m trying to expose.

Currently this only works on 32 bit processes.

Let’s start by describing the architecture as there are 3 things going on. The major components are the Injector, Unmanaged Injectee and Managed Injectee. The injector is the controller in this scenario; he’s responsible for the injection into the managed process and communication between the components. Communication is handled via named pipes.

The injector uses a well-documented dll injection technique via CreateRemoteThread and LoadLibrary. This loads the unmanaged dll into the Managed process. The unmanaged DLL actually handles the Managed DLL injection. I wont go into unmanaged dll injection as it’s pretty well document technique. I assume the reader understands these concepts.

From this point I assume the unmanaged DLL has been injected into the managed process.

After the unmanaged DLL is injected I need to make sure the correct version of the CLR is loaded. To accomplish this use the CLR hosting API’s to determine the version of the CLR that is loaded by the process (Provided there is one loaded). The host process must be running .Net 4.0 to support the Roslyn API. Because the early versions of the hosting API’s are deprecated I need to check to see if the .net 4.0 mscoree is loaded “msvcr100_clr0400.dll”. I check via a GetModuleHandle. If it exists we know we are running .Net 4.0 and know the CLR is already running. Two birds down with a single stone.

hMod = GetModuleHandle(L"msvcr100_clr0400.dll");

Once we know the CLR is loaded and it’s 4.0 we can get a handle to the CLSID_CLRMetaHost via:

hr = CLRCreateInstance( CLSID_CLRMetaHost,
IID_ICLRMetaHost,
(LPVOID*)&pMetaHost );

From the meta host we can get a handle to the running RunTimeHost via:

ICLRRuntimeHost *pClrHost = NULL;
runTimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID *)&pClrHost);

This will return a handle to the current RuntimeHost (Or load the runtime if it isn’t running). The next call is to load my Managed DLL plus call the entry method.

pClrHost->ExecuteInDefaultAppDomain(L"InjectedManagedDll_Net_4.dll", L"InjectedManagedDll_Net_4.InjectedClass", L"Test", L"TestArg" , &ret);

This loads the Managed DLL into the process. Once the Managed DLL’s Test method is called I create a managed thread.

public static int Test(string param)
{
new Thread(new ThreadStart(ThreadFunc)).Start();
return 666;
}

This thread then generates a few more threads and sets up the NamedPipe communication pipe and reports to the server things are setup.

static void ThreadFunc()
{
try
{
PipeClient.Instance.Start("CNIPipe");
}
catch (Exception e)
{
PipeClient.Instance.LogMessageToServer(e.Message);
}
}

I then expose some simple messages back and forth between the injector and injectee and expose a simple REPL loosely based on this guy’s implementation: http://visualstudiomagazine.com/articles/2011/11/16/the-roslyn-scripting-api.aspx.

private ScriptHost()
{

HashSetassemblys = new HashSet();
assemblys.Add(Assembly.GetCallingAssembly());
assemblys.Add(Assembly.GetEntryAssembly());
assemblys.Add(Assembly.GetExecutingAssembly());

Listnamespaces = new List() { "System", "System.Collections", "System.Collections.Generic" };

ScriptEngine = new ScriptEngine(assemblys.ToList(), namespaces);

Session = Session.Create(this);
}

public object Execute(string code)
{
return ScriptEngine.Execute(code, Session);
}

This gets you a basic REPL inside another process. Next steps include making sure the communication API between the host and injectee are more well formed and able to handle both 32 and 64 bit processes. Stay tuned!

XML Hell presentation at Blue Hat v11

October 24th, 2011 by

At Microsoft BlueHat v11 I’ll be delivering an internal-only briefing along with Matt Swann.  While I can’t go into the confidential details of the talk, there are some things I want to mention that are more general and already public information.  There’s significant attack surface when it comes to parsing XML documents, and processing contextual information in those documents.  The threats are not limited to any one tech stack, and can be found in most of the popular ones.  To name the main exploit scenarios we see and test for regarding XML:

  • Information Disclosure (file system access)
  • Logical Abuse
  • Injection and XSS
  • Denial of Service
  • Remote Code Execution

I might blog about each one of these in turn because they’re each a little different and unfortunately the mitigation is not as simple as “validate input”.

X5S V2.0…. its coming!

January 3rd, 2011 by

So, It’s been awhile since we’ve done any public updates to X5S. Over the last year, I’ve improved the algorithm and process significantly. Be on the look out, it should be released within the next couple of weeks (Sometime in Jan. 11).

Some of the improvements include:
* Better Algorithms for doing checks
* Better output format .. Now uses a tree view.. Going to add better support for reporting too..
* Cleaner UI (Easier to use)
* Re-factored the code to be cleaner/make more sense and easier to maintain. It’s much easier to understand/work with.. before was mostly prototyped code/ Alpha code.
* Changed how test cases are defined for more control over the types of injects
* Added a fuzzing mode that will take data from a file and inject it where canaries would normally be injected. (This can be slow with lots of injections)
* Added a replay from Fiddler capture.. (Replays the capture while fuzzing/injecting on the requests).

* many many more minor/significant changes.. =)

Check back soon for a release date!

List of characters for testing Unicode transformations and best-fit mapping to dangerous ASCII

December 20th, 2010 by

I’m attaching two CSV files for use in test cases and tools.  The uni2asc.csv contains all of the Unicode characters that map to something ASCII < 0×80.  The bestfit.csv  contains all of the known best-fit  mappings to dangerous ASCII between legacy charsets and Unicode.

uni2asc.csv – for straight Unicode to Unicode mappings
bestfit.csv – for legacy charset to Unicode mappings

I gave these to Gareth so they may wind up in HackVertor.

The Unicode database contains meta data about every character, including compatibility mappings, normalization mappings, case mappings, and other decomposition data.  It’s useful for testing to know what special Unicode characters may transform to dangerous ASCII.  For example:

  • U+2134 SCRIPT SMALL O character will transform to the U+006F LATIN SMALL LETTER in certain cases

Of course, if you’re testing for SQL injection or XSS you probably want to know what transforms to dangerous characters like ‘ and <.  We attempted to automate some of this in our x5s tool which has done a good job so far, and we have a big update for that coming soon.

In the bestfit.csv file you’ll find all of best-fit mappings from Unicode to dangerous ASCII < 0×80 (and vice versa) in many of the legacy charsets from http://unicode.org/Public/MAPPINGS/.  There’s some wild legacy stuff in here.  For example:

  • In APL-ISO-IR-68, 0×27 maps to 0x5D in Unicode, and vice versa.

If you put these to use anywhere please let me know so I can pass the word along.

In APL-ISO-IR-68, 0×27 maps to 0x5D in Unicode, and vice versa.

We’re Hiring: Application Security Consultant and Researcher

December 18th, 2010 by

Want to put your security research skills to the test in Seattle? We’re looking for junior and senior appsec consultants and vulnerability researchers to join Casaba – good work/life balance, salary plus profit sharing, 100% health coverage, and some other things I’m surely forgetting. Oh ya we’re a small company in our 8th year, there’s no middle management and the only politics are outside the office.

You should fit at least 2 of the following profiles:

- Web-application vulnerability researcher – You’re able to find flaws and exploitable bugs in the most popular and complex products on the Internet. Of course you intimately understand the W3 protocols and can find XSS, CSRF, cross-domain and nasty browser-quirk-related vulns in about the time it takes to pour a cup of coffee. You can also manage a code review of C#, Rails, or Java and document bugs and remediations. When you get bored you spend a night finding cross-domain Same Origin Policy holes in every major browser.

- Reverse Engineer – You’re able to disassemble and debug even hardened binaries, analyze and dissect a black-box communication protocol, and build a rogue client or server. You’re of course a master of your chosen programming language, and can script up IDA, PyDbg, and Immunity. You don’t even need to respond to this job posting, because you’ve already hacked into my laptop and dropped your resume on my desktop.

- Fuzzer - You find more bugs than a pond full of frogs on a warm summer night. At any given moment you have 15 fuzzers running in parallel across a herd of VM’s. You live for finding zero-days in anything that has a network stack or a file parser. If the art of fuzzing suddenly became useless you’d probably leave the tech world behind and move to the beach to surf forever.

- Builder – You like to break stuff but would really rather build it. When there’s a new vulnerability discovered you get excited to build a tool to test for and exploit it. If it’s related to a browser, protocol, or language you never studied before, even better because now you have an excuse to learn something. If a colleague asks if you can help with a test harness you ask for her short list of requirements. Nothing’s out of reach, but you’re not all over the map either. You’re focused and have one or two major research goals of your own.

Please email ‘chris’ (my first name) @casaba.com with at least two profiles that describe you and whether you’re a fit for a junior or senior level position.

Juniors generally have 1-3 years professional experience, have been to some conferences and have released some tool, paper, or vulnerability. Seniors have done those things and are regular speakers at industry conferences, have their name on a book, and are also capable of managing projects, small teams, and client relationships.

Watcher 1.4.0 released

May 25th, 2010 by

A new update to the Watcher passive Web-vulnerability scanner has been released. Based on user feedback we’ve built out the Wiki documentation on Codeplex with more details about the issues identified by each Watcher check. Inside the tool, a reference is now included as a link back to the Wiki. I hope to improve the documentation on the Wiki and welcome all your suggestions.

A new check has been added to detect when domain lowering occurs through javascript, typically done by setting document.domain equal to the parent domain. We’ve also made some more efforts at noise-reduction, by enabling some of the noise-reduction configurations by default, namely in the cookie and VIEWSTATE checks.

Watcher 1.3.0 released

February 25th, 2010 by

A new update to the Watcher passive vulnerability detection and security testing tool has been released. Watcher is an open source addon to the Fiddler Web proxy that aids developers, auditors, and penetration testers in finding Web-application security issues as well as hot-spots for deeper review. Among other things, we’ve added new checks to identify the insecure ViewState issues as recently reported by Trustwave’s SpiderLabs [1].

Download Watcher from CodePlex. A short list of new features and improvements includes:

  • A separate, optional component to export results to Team Foundation Server.
  • New check to identify insecure ASP.NET VIEWSTATE configurations subject to tampering and pervasive XSS attacks.
  • New check to identify insecure JavaServer MyFaces ViewState subject to tampering and XSS attacks.
  • New check for Silverlight EnableHtmlAccess.
  • Export results to HTML report.
  • Compliance mappings to Microsoft SDL.
  • If no origin domain is specified, each response domain will be treated as the origin, enabling better cross-domain analysis.
  • Assorted bug fixes and improvements.

Bryan Sullivan and Patrick Toomey’s ViewStateViewer plugin [2] provided inspiration for detecting ASP.NET VIEWSTATE MAC protection. When testing .NET 4.0 we discovered a change in the MAC implementation which has also been accounted for in this check. David Byrne from Trustwave [1] provided most of the methodology ideas for detecting insecure JavaServer MyFaces ViewState.

In addition to the main developers (Robert Mooney and Samuel Bucholtz), we wanted to thank everyone who helped or provided suggestions for this release:

Hidetake Jo
Bryan Sullivan
David Byrne
Jason D. Montgomery
Dave Wichers

[1] Trustwave advisory https://www.trustwave.com/spiderlabs/advisories/TWSL2010-001.txt
[2] ViewStateViewer plugin for Fiddler http://labs.neohapsis.com/2009/08/03/viewstateviewer-a-gui-tool-for-deserializingreserializing-viewstate/

Microsoft CCI Framework for Deobfuscating .Net binaries. (Part 2)

February 4th, 2010 by

So yesterday I talked a about using CCI to remove attributes from .Net binaries. Specifically the SupressIldasm attribute. I promised I’d put up some more code highlighting the framework’s benefits. So some more detail on the binary I’m working with. It has been ran through Babel -> Netz -> Babel again. My goals have been to reverse Debabel-> Unpack Netz -> Rebuild the .exe -> debabel again, although the first stage of babel could be skipped, but why not analyze it.

Babel uses a couple of simple techniques to prevent programs like reflector from analyzing protected binaries. These techniques are also found in other protections, so it’s useful to understand why the work and how they work, they are really very simple.

Today I’ll cover a simple but annoying technique being employed; inserting junk bytes. Babel inserts junk bytes into the IL stream of each method. When reflected it causes the disassembler to fail as it does not recognize the byte sequences it can’t continue.

Below is an example of a method ildasm’ed after removing the “suppressIldasm” attribute from the previous post.

View Code CSHARP
.class public auto ansi beforefieldinit netz.NetzStarter
       extends [mscorlib]System.Object
{
  .field private static initonly string Property0
  .field private static initonly string Property1
  .field private static initonly string Property2
  .field private static class [System]System.Collections.Specialized.HybridDictionary Property3
  .field private static class [mscorlib]System.Resources.ResourceManager Property4
  .field private static class [mscorlib]System.Collections.ArrayList Property5
  .field private static bool Property6
  .method public hidebysig specialname rtspecialname
          instance void  .ctor() cil managed
  {
    // Code size       14 (0xe)
    .maxstack  8
    IL_0000:  br         IL_0007
 
    IL_0005:  unused
    IL_0006:  unused
    IL_0007:  ldarg.0
    IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
    IL_000d:  ret
  } // end of method NetzStarter::.ctor

As you can see it does an absolute jump over some “unused” bytes which are really invalid bytes. This way the logic of the program is maintained while confusing the disassembler. One technique I’ve read to handle this is to use a hex editor to look for the absolute jump op code and nop out those bytes. However this is unreliable as babel inserts bytes not just at the start of the method.

Microsoft CCI to the rescue again!.

So lets use CCI to handle rebuilding the binary by replacing invalid bytes with nops. This way we can now view this application in reflector and be able to navigate it. Below is the mutator class i wrote to handle NOP’ing invalid bytes. Again a very simple solution. Now the code is visible in reflector using the IL view. At least you get the “browsing” functionality and easily go to functions and view their dependencies and cross-references.

View Code CSHARP
public class InvalidCodeNOPReplace : MetadataMutator
{
	public InvalidCodeNOPReplace(IMetadataHost host)
	    : base(host)
	{
 
	}
 
	public override List<IOperation> Visit(List<IOperation> operations)
	{
	    operations = Utilities.ReplaceInvalidOpCodeAsNOP(operations);
 
	    return base.Visit(operations);
	}
}
 
public static List<IOperation> ReplaceInvalidOpCodeAsNOP(List<IOperation> ops)
{
    List<IOperation> newOps = new List<IOperation>();
    foreach (IOperation op in ops)
    {
 
	if (!IsValidOpCode(op.OperationCode))
	{
	    Operation o = new Operation();
	    o.Location = op.Location;
	    o.Offset = op.Offset;
	    o.OperationCode = OperationCode.Nop;
	    o.Value = 0x0;
	    newOps.Add(o);
	}
	else
	{
	    newOps.Add(op);
	}
    }
    return newOps;
}
 
private static void populateOpCodeDic(){
   OpCodes = new Dictionary<OperationCode,int>();
   foreach(int i in Enum.GetValues(typeof(OperationCode)))
   {
     OpCodes[(OperationCode)i] = i;
   }
}
public static bool IsValidOpCode(OperationCode opCode)
{
       if (OpCodes == null)
       {
            populateOpCodeDic();
       }
       return OpCodes.ContainsKey(opCode);
}

Unfortunately reconstructing the C# source doesn’t work at this stage due to the nops and invalid branching structure. However, I’m trying to work out a middle layer which can take a methodbody’s operations list, abstract it out, turn it in to a control flow graph, optimize it and rewrite. However i’m still stuck at the rewriting part. I hit a small snag in the logic I haven’t had time to work out just yet. Hopefully then the C# can be reconstructed.

Tomorrow I’ll post some simple methods to get readable names out of the method/properties/class names to make following logic easier.

*Edit forgot to add the IsValidOpCode method.

**Edit had to readd disappearing generic types.. Ugh!

Unibomber tool for specialized XSS testing

July 28th, 2009 by

John Hernandez has been working hard at Casaba to build a specialized testing tool that automates some of the unique techniques we use to find cross-sites scripting bugs (XSS). At Black Hat I'm planning to demo what we have so far. It automates the testing process greatly, by auto-injecting a canary and ID into each input be it query string, HTTP header, or POST parameter. By combining injection with 'output encoding' detection, you get automation that assists pen-testers in finding vulnerability hotspots.

Because it basically bombs a Web-app with a slew of Unicode characters to find XSS bugs we named it the Unibomber.

Appended to the canary is a special character – special because it can transform into a 'dangerous' character through normalization, casing, or best-fit mapping operations. So we end up injecting these special characters all over the place and then detecting where they get transformed and displayed as output.

The beauty is that we can find both reflected and persistent XSS bugs this way. It's not a one-click tool though, this is intended for use by an experienced person who knows how to find and exploit a clever XSS bug.

Anyone who looks for XSS will likely find some good bugs with the Unibomber. We sure have!