<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace Site Server v5.11.81 (http://www.squarespace.com/) on Thu, 24 May 2012 12:39:28 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><title>Chargen</title><subtitle>Chargen</subtitle><id>http://chargen.matasano.com/chargen/</id><link rel="alternate" type="application/xhtml+xml" href="http://chargen.matasano.com/chargen/"/><link rel="self" type="application/atom+xml" href="http://chargen.matasano.com/chargen/atom.xml"/><updated>2010-05-19T20:22:13Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.11.81 (http://www.squarespace.com/)">Squarespace</generator><entry><title>Flint 1.1.0 Available</title><id>http://chargen.matasano.com/chargen/2010/5/17/flint-110-available.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2010/5/17/flint-110-available.html"/><author><name>Joel Cornelius</name></author><published>2010-05-17T19:51:55Z</published><updated>2010-05-17T19:51:55Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>
Hey. Joel here. A small number of changes have been introduced into Flint 1.1.0. The largest among these is the ability to display the processing status of your firewall rules. This is particularly useful if you have large rulesets or configurations that involve multiple mappings between internal and external realms.</p> 
</br>
<p>
For such rulesets, Flint can appear to be unresponsive due to the massive amount of processing required. The benefit of this feature is that it lets you know Flint is still hard at work, and which stage it&#8217;s currently working in. </p> </br>
<p>As in all previous versions of Flint, you will be redirected to the overview page following processing. Although the content on this page has not been modified in v.1.1.0, you may notice the url has changed to include the sha of the current firewall. This enables bookmarking the test results of your firewall configurations so you can view them later without having to re-process. </p>
</br>
<p>
Additionally, the UI for running new reports has been changed slightly. The new report popup has been embedded into the new report page, along with a small set of instructions on how to load rules into Flint. </p> 
</br>
<p>
At the time of this writing, version 1.1.0 is only available through out git repository. Check out <a href="http://runplaybook.com/flint">http://runplaybook.com/flint</a> for more detailed instructions on how to install Flint via git. For those of you interested in the Flint VM, we should have one for 1.1.0 available by the end of the week. </p>
]]></content></entry><entry><title>Flint 1.0.6 released.</title><id>http://chargen.matasano.com/chargen/2010/4/15/flint-106-released.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2010/4/15/flint-106-released.html"/><author><name>Craig Brozefsky</name></author><published>2010-04-15T19:20:42Z</published><updated>2010-04-15T19:20:42Z</updated><content type="html" xml:lang="en-US"><![CDATA[This 1.0.6 release a small update to Flint, fixing some parser bugs that Jacob Kitchel helped us track down.  You can get Flint at <a href="http://runplaybook.com/flint">http://runplaybook.com/flint</a>
]]></content></entry><entry><title>Flint 1.0.5 Released, and a new website too!</title><category term="Flint shaolin"/><category term="flint"/><id>http://chargen.matasano.com/chargen/2010/4/2/flint-105-released-and-a-new-website-too.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2010/4/2/flint-105-released-and-a-new-website-too.html"/><author><name>Craig Brozefsky</name></author><published>2010-04-02T20:04:26Z</published><updated>2010-04-02T20:04:26Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p><span class="full-image-float-right ssNonEditable"><span><img width=200 src="http://chargen.matasano.com/storage/post-images/commaguy.png?__SQUARESPACE_CACHEVERSION=1270239174090" alt=""/></span></span></p>

<p>You can see it all at: <a href="http://runplaybook.com/flint">http://runplaybook.com/flint</a></p>

<p>This release of Flint includes:</p>

<ul>
<li>Our new Flint mascot</li>
<li>Log viewer and more verbose error messages</li>
<li>Ability to map network interfaces to specific security realms</li>
<li>Choose which checks run against your firewall</li>
<li>In-place updates via git</li>
</ul>

<p>We also want to give a shout out to the following users who have helped us find and kill bugs:</p>

<ul>
<li>Jacob Kitchel</li>
<li>Sam Quigley</li>
<li>John Hoffoss</li>
<li>Karsten Iwen</li>
</ul>
]]></content></entry><entry><title>Getting Started with Flint</title><category term="README"/><category term="flint"/><category term="flint"/><category term="introduction"/><id>http://chargen.matasano.com/chargen/2010/3/2/getting-started-with-flint.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2010/3/2/getting-started-with-flint.html"/><author><name>Craig Brozefsky</name></author><published>2010-03-02T21:34:22Z</published><updated>2010-03-02T21:34:22Z</updated><summary type="html" xml:lang="en-US"><![CDATA[<p>In case you haven&#8217;t heard, Matasano has released a new open-source product, Flint.  Flint is firewall checkup.  In short, it is a small web application, written in Ruby, served up in Sinatra.  You upload a firewall configuration, and it:</p>

<ul>
<li>Runs a set of &#8220;checks&#8221; to make sure you didn&#8217;t shoot yourself in the foot.</li>
<li>Gives you a &#8220;report card&#8221; view of these checks</li>
<li>Figured protocols that can pass thru the firewall, and which hosts can talk to which.</li>
</ul>
]]></summary></entry><entry><title>Exercises for a burgeoning Army of Ninjas</title><id>http://chargen.matasano.com/chargen/2010/1/20/exercises-for-a-burgeoning-army-of-ninjas.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2010/1/20/exercises-for-a-burgeoning-army-of-ninjas.html"/><author><name>stephen</name></author><published>2010-01-20T23:36:00Z</published><updated>2010-01-20T23:36:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>At SourceBoston 2009 fellow New Yorker Dan Guido did a talk entitled <a href="http://www.sourceconference.com/bos09pubs/army_of_ninjas.pdf">&#8220;So You Want to Train an Army of Ninjas&#8221;</a>. Dan&#8217;s talk was on his experience organizing the CSAW competitions at NYU:Polytechnic. If you are unfamiliar with the annual awesomeness that the <a href="http://isis.poly.edu/">ISIS program</a> at NYU:Poly puts together, you can read more about the whole event <a href="http://www.poly.edu/csaw-CTF">here</a>. To <a href="http://twitter.com/dguido/status/4419086235">quote someone on twitter</a> &#8220;If all of school was like [the program at NYU:Poly] maybe I wouldn&#8217;t have dropped out.&#8221;</p>
<p>This is an excellent little video summary of the competition:</p>
<p style="text-align: left;"><object width="400" height="225"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8671084&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8671084&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="225"></embed></object></p>
<p><a href="http://vimeo.com/8671084">CSAW 2009 - The Judge&#8217;s Perspective</a> from <a href="http://vimeo.com/nyupoly">NYU-Poly</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>The competition portion of the event is loosely modeled after the Defcon Capture the Flag competitions of recent years. This past year, the CSAW-CTF competition brought talent from all around the world together during the <a href="http://www.dhs.gov/files/programs/gc_1158611596104.shtm">National Cyber Security Awareness Mont</a>h which is celebrated at NYU:Poly as <a href="http://www.poly.edu/csaw">CSAW&nbsp;(Cyber Security Awareness Week)</a>&nbsp;</p>
<p>In 2008 when I was asked by Dan to help out I was very eager. That year, my involvement with CSAW-CTF was limited to just a few small challenges (instead I focused on teaching a Reverse Engineering class at NYU that year which <a href="http://dvlabs.tippingpoint.com/team/aportnoy">Aaron Portnoy</a>&nbsp;took over for this year).&nbsp;This year (2009) however, I went a little more &#8220;head down&#8221; and spent a bit more time designing, coding, and building reverse engineering challenges for the CSAW-CTF.&nbsp; This blog post is about those challenges.</p>
<p>Times have changed, and these competitions have evolved and matured much like the rest of our &#8220;industry&#8221;.&nbsp; They are no longer about who can whip out their graffiti&#8217;d laptops, mount their sticker laden <a href="http://en.wikipedia.org/wiki/Iomega_Zip_drive">Zip drives</a> from linux, and use gcc to compile stuff from their <a href="http://en.wikipedia.org/wiki/Packet_Storm">packetstorm</a>, <a href="http://web.archive.org/web/*/http://technotronic.com">rhino9</a>, <a href="http://web.archive.org/web/*/http://www.rootshell.org">rootshell.org,</a> or hack.co.za archives. Times have changed. The games are different now and don&#8217;t so much deserve to be the target of smug self-righteous vitriol from jaded old security folks.</p>
<p>This became really obvious to me in 2005 when Kenshoto premiered a new kind of Capture the Flag for Defcon that year. Players that year said that they could really tell that despite Kenshoto&#8217;s showmanship (and at times, ostentatiousness), all the members (mostly <a href="http://twitter.com/invisig0th">invisig0th</a>, who is responsible for really spear-heading the whole effort) really loved what they did and wanted to share in the fun of software exploitation and reversing.&nbsp; All the challenges were custom made and well documented. They required source auditing skill, custom shellcode payloads, and reverse engineering skill. During the qualifying rounds (a month or so before Defcon) there was also an interactive scoreboard, <a href="http://en.wikipedia.org/wiki/MUD">MUD</a> and IRC channel for all the players and organizers to use. This drew players in to world of the game a bit more and allowed teams and organizers to &#8220;hang out&#8221; all in one place and keep up-to-date on scores and rankings.&nbsp;</p>
<p>That year, and in the following years following, some big hitters came out to play:&nbsp;<a href="http://taossa.com/">Mark Dowd and John McDonald</a>&nbsp;(who ruxxed the quals round in 2005); <a href="https://www.blackhat.com/html/bh-dc-09/train-bh-dc-09-ce.html">Chris Eagle and the Naval Post-Graduate Warfare College</a>; <a href="http://www.cs.ucsb.edu/~vigna/hacking.html">Giovanni Vigna</a> and <a href="http://www.cs.ucsb.edu/~vigna/defcon.html">the UCSB team</a>; the SAIC team, the Novell Team, some great international teams; and number of Fortune 500 technology companies (and government agencies) that wished to remain nameless ;-) Kenshoto and <a href="http://www.viega.org/">John Viega</a> (a Kenshoto member) even got <a href="http://web.archive.org/web/20050415020436/www.popsci.com/popsci/computers/article/0,20967,1047679-2,00.html">an article in Popular Science</a> that year.</p>
<p>Having been a member of Kenshoto, I really wanted to bring a bit of that spirit to the NYU:Poly CSAW-CTF. The NYU-Poly competitions&nbsp;had a number of different competition categories which included Web Security, Application Security, Forensics, and&nbsp; Embedded Systems.&nbsp;</p>
<p><object id="otvPlayer" width="400" height="268">
<param name="movie" value="http://cdn.abclocal.go.com/static/flash/embeddedPlayer/swf/otvEmLoader.swf?version=&station=wabc&section=&mediaId=7153747&cdnRoot=http://cdn.abclocal.go.com&webRoot=http://abclocal.go.com&site=" ></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowNetworking" value="all"></param>
<param name="allowFullScreen" value="true"></param>
<embed id="otvPlayer" width="400" height="268" type="application/x-shockwave-flash" 
	allowscriptaccess="always" allownetworking="all" allowfullscreen="true" 
	src="http://cdn.abclocal.go.com/static/flash/embeddedPlayer/swf/otvEmLoader.swf?version=&station=wabc&section=&mediaId=7153747&cdnRoot=http://cdn.abclocal.go.com&webRoot=http://abclocal.go.com&site=">
</embed>
</object></p>
<p>Myself, <a href="http://trailofbits.com/">Dino Dai Zovi</a> (who <a href="http://trailofbits.com/2009/11/16/csaw-ctf-2009/">blogged briefly about his CSAW experience</a> and even <a href="http://abclocal.go.com/wabc/story?section=news/education&amp;id=7153459">talked about it on the local news</a>), and <a href="http://zerodaysolutions.com/">Dean DeBeer</a>&nbsp;were all responsible for <a href="http://www.poly.edu/csaw-judges">judging and organizing</a> the &#8220;Application Security&#8221; parts of the competition. Dino Dai Zovi (an alumnus of Matasano and fellow New Yorker) designed all the Software Exploitation challenges and I designed all the Reverse Engineering challenges.</p>
<p>You can read about the full format of the competition <a href="http://www.poly.edu/csaw-CTF">online at the csaw website</a>, but essentially the competition happened in two waves: (1) a qualifying round where anyone could participate, and (2) a final round where all the top teams that qualified and were enrolled at universities within the US would be flown to New York and put up in a fancy hotel to participate in the final round held on the NYU:Poly campuses.</p>
<p><span style="font-size: 200%;"><span style="text-decoration: underline;">The Scoring System:</span></span></p>
<p>First things first. How to keep track of scores? A stupid web app? The honor system? Email based submissions?Due to the sheer number of participants I decided that any kind of manual or qualitative scoring system would be a nightmare. Reverse engineering challenges seemed to lend themselves nicely&nbsp; to &#8220;token&#8221; based scoring so I decided to go that route and to build an automated scoring system. The scoreboard was written in Python and ran as the default shell for an &#8220;open&#8221; user account to be shared amongst all participants. Competitors were dropped into the BBS-style scoreboard system when they ssh&#8217;d into the box.<img src="http://chargen.matasano.com/storage/screenshots/login_screen.png?__SQUARESPACE_CACHEVERSION=1264100331938" alt="" />They would then authenticate to the scoreboard system itself (which maintained it&#8217;s own credentials).</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/login_screen.png?__SQUARESPACE_CACHEVERSION=1264104636614" alt="" /></span></span></p>
<p>The scoring system internally used a client/server model. The server ran at a higher privilege level than the client and communication between the two was all done using <a href="http://pyro.sourceforge.net/">python RMI</a>.&nbsp;This was intended to localize the damage if anyone had a clever way of breaking out of the python interpreter. If they were, it would be harder to directly access the scoring database files directly, because all those operations were performed by the server on behalf of the client who made requests via RMI. The scoring system allowed competitors to check scores, <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/flagui.png">read about flags and challenges</a>, and submit/check their answers.</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/flag_checking.png?__SQUARESPACE_CACHEVERSION=1264104789986" alt="" /></span></span></p>
<p>Other than that there isn&#8217;t anything really noteworthy about the scoring system. Source code for that is all <a href="http://github.com/s7ephen/CSAW_2009/tree/master/scoring/ ">available online here</a>. Now let&#8217;s get on to the Reversing challenges.</p>
<p>For the qualifying round of the competition I put together 8 challenges. The 9th and final challenge would be completely different than all the others and was saved for the Final Round which took place on the NYU:Poly campuses. Each of the 8 challenges were framed as forensics based malware challenges, each having its own fictional &#8220;backstory&#8221;. Every challenge was distributed in binary form and it was up to the competitor to extract tokens from the binary by reversing or otherwise modifying execution of the executable. Each binary employed what I hoped to be progressively more difficult anti-debugging and anti-reversing techniques and combinations thereof. Let&#8217;s individually review each technique before summarizing how they were combined to form each challenge.</p>
<p><span style="text-decoration: underline; font-size: 200%;">The Tricks and Techniques:</span></p>
<p><strong><span style="text-decoration: underline;">Premature Exit:</span></strong></p>
<p>Before a critical call is made a call to <a href="http://msdn.microsoft.com/en-us/library/ms682658(VS.85).aspx">ExitProcess</a> is made. Thus normal execution of the binary will seem to just cause the program to run and exit. Debugging the process however will reveal that more code exists after the call to <a href="http://msdn.microsoft.com/en-us/library/ms682658(VS.85).aspx">ExitProcess</a>.</p>
<p><span style="text-decoration: underline;"><strong>BeingDebugged (custom):</strong></span></p>
<p>Traditionally this technique involves having the process make a call to <a href="http://msdn.microsoft.com/en-us/library/ms680345(VS.85).aspx">IsDebuggerPresent()</a> to see if it is being debugged. &nbsp;This is the standard way to do this using the Microsoft APIs.&nbsp;However many anti-anti-debugging patches for debuggers such as OllyDBG have modules that will intercept this call by setting a breakpoint on it down in kernel32.dll. So instead of using the Microsoft API I wrote some inline <a href="http://github.com/s7ephen/CSAW_2009/blob/master/6/source/6.cpp#L16">assembly</a>&nbsp;that pulled this boolean value directly out of PEB. This way, the only way to catch that &#8220;Being Debugged&#8221; was being checked was to set a Break-on-Access in PEB itself, something I don&#8217;t think any of the common debugger plugins do. My hope was that this would make the process a bit more manual for the competitors.</p>
<p><strong><span style="text-decoration: underline;">String Obfuscation:</span></strong></p>
<p>&nbsp; Many strings that get statically compiled into binaries sit in the BSS section of the executable. You can use canned tools like unix &#8220;strings&#8221;, IDA, or even simple shell scripts to pull this stuff out. Even simple string obfuscation like XOR is easily spottable in disassembly. So what I wanted to do was to write a string obfuscater that would &#8220;raise the bar&#8221; high enough that reversing the scheme itself would be more difficult than doing the challenge itself, so I settled on some simple encryption. &nbsp;To achieve this I was originally going to use RC4 and execute it as a shellcode buffer, so I wrote <a href="http://github.com/s7ephen/CSAW_2009/blob/master/evil/rc4.asm">RC4 in NASM</a>.&nbsp;</p>
<p>&nbsp;The reason I chose to do this as shellcode originally is because I thought it would be easier to polymorph the algorithm as shellcode than it was to polymorph it as compiled C code.&nbsp;I eventually found out a way to achieve this with C code (as you will read below) and abandoned the shellcode idea. Instead I wrote (*ahem* stole) an RC4 implementation written in C that I vainly called <a href="http://github.com/s7ephen/CSAW_2009/blob/master/1/source/sa7_win.h">sa7ori-encode</a>.&nbsp;I generously borrowed from the i<a href="http://www.columbia.edu/~ariel/ssleay/rrc4.html">nfamous cipherpunks mailinglist ARC4 leak</a>&nbsp;to write this code.&nbsp;With the crypto scheme implemented, the challenge then became how to make the algorithm look &#8220;different each time&#8221;. For this I used a combination of Inlining, Call Obfuscation, &#8220;Polymorphic&#8221; C Code Blobs, and &#8220;Here Strings&#8221; (all described a bit more below).</p>
<p><strong><span style="text-decoration: underline;">Inlining:</span></strong></p>
<p>&nbsp; Inlining (for those of you who are un-familar) is a way for a C developer to specify (using the compiler directive <a href="http://msdn.microsoft.com/en-us/library/z8y1yy88(VS.80).aspx">__forceinline</a>) that when a function is called that execution is not redirected into it using the traditional &#8220;call&#8221; instruction.<span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/inlining_screenshot.png?__SQUARESPACE_CACHEVERSION=1264101912653" alt="" /></span></span>&nbsp;Instead, with inlining wherever a function would normally have been called, the full body of code for that function is &#8220;pasted&#8221; into the place where it is referenced. This is extremely inefficient because it makes binaries MUCH larger but for that reason it also makes reversing a bit more painful.</p>
<p><strong><span style="text-decoration: underline;">Timing Tricks:</span></strong></p>
<p>&nbsp;&nbsp; I had always heard about these timing tricks but the most interesting use of them was in <a href="http://expertmiami.blogspot.com/">Kostya Kortchinsky</a> and Fabrice Desclaux&#8217;s EXCELLENT presentation entitled <a href="http://www.recon.cx/en/f/vskype-part1.pdf">Vanilla Skype</a> where they discussed some of the anti-debugging tricks they encountered while <a href="http://www.recon.cx/en/f/vskype-part2.pdf">completely reverse engineering Skype</a>.&nbsp;(This, by the way, among my favorite presentations of all time.) The idea is simple, x86 CPUs since the Pentium support an instruction called <a href="http://en.wikipedia.org/wiki/Time_Stamp_Counter">RDTSC</a>&nbsp;which reads a time value from a timer that started inside the CPU when it was powered on. This can be used as a &#8220;stopwatch&#8221; to measure the time delta between bits of code.</p>
<p>This is particularly useful if you want to detect if there is a debugger attached. By starting the proverbial &#8220;stopwatch&#8221;, then throwing an exception that only a debugger can handle, and then checking the &#8220;stopwatch&#8221; after the exception is handled, a program can essentially time how long the debugger (and thusly the human operating the debugger) took to handle the exception.&nbsp;By setting the threshold for this time impossibly low for a human to react to you can effectively detect if there is a &#8220;man in the loop&#8221;.&nbsp; The RDTSC instruction is wrapped by the Microsoft API function &#8220;<a href="http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx">GetTickCount()</a>&#8221;.</p>
<p><strong><span style="text-decoration: underline;">Self-Caught Exceptions (to cause code branching):</span></strong></p>
<p>This technique involves using registered exception handlers to redirect execution in your application. Instead of just calling a function by name, you register the function you wish to call as an exception handler, and then trigger an exception. If a debugger is attached, it catches the exception before the exception handler (which is actually a function critical to the normal operation of the program) executes and thus the program does not continue properly when the debugger has handled the exception and resumed execution.</p>
<p><strong><span style="text-decoration: underline;">Debugger Required Exceptions:</span></strong></p>
<p>&nbsp; This simple technique caused an exception (division by zero, &#8220;call 0&#8221;, etc.) that required the reverser to have his debugger attached so he could jump over or NOP out the exception. This is effectively like the premature exit. In the VM supplied to the competitors (which had remote Kernel debugging enabled) this had the unintended consequence of freezing the entire VM if they didn&#8217;t have a debugger attached ;-).</p>
<p><span style="text-decoration: underline;"><strong>Call Obfuscation (AntiDisassembly, kinda):</strong></span></p>
<p>&nbsp; To obscure the area around a function call&nbsp; I decided to use a combination of inline assembly and a property of C include files. C include files (.h) files essentially just &#8220;paste&#8221; in the code from the .h wherever it is referenced in the C code. In this case I put inline assembly in the .h.</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/evil.png?__SQUARESPACE_CACHEVERSION=1264104749819" alt="" /></span></span></p>
<p>The inline assembly uses the _emit macro to build a large blob of seemingly random bytes that could not be disassembled properly. <span class="thumbnail-image-inline ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fevil.png%3F__SQUARESPACE_CACHEVERSION%3D1264102173281',578,431);"></a></span></span>Using the <a href=" http://msdn.microsoft.com/en-us/library/b0084kay(VS.71).aspx">__COUNTER__</a> Visual Studio Macro.&nbsp;<a href="http://www.dontstuffbeansupyournose.com/?page_id=2">Stephen Lawler</a>&nbsp;gave me the idea for this trick, unfortunately it can only be used once per function. You can see an example of <a href="http://github.com/s7ephen/CSAW_2009/blob/master/evil/evil.h">how I implemented it here</a>. This code was further modified to make it &#8220;polymorphic&#8221; which is discussed below.&nbsp;</p>
<p><strong><span style="text-decoration: underline;">Polymorphic C code (kinda&#8230;.well, ok not really :-):</span></strong></p>
<p>&nbsp;My CS vernacular stinks, so I couldn&#8217;t really think of a way to describe what I was doing here. To replace my idea to use polymorphic shellcode as the string obfuscater I instead found (what I think to be) a neat way to do this in C. The main use for this was to make the blob generated by the &#8220;Call Obfuscation&#8221; trick (see above) pseudo-random and thus a little more difficult to &#8220;eyeball&#8221; in disassembly.&nbsp; Visual Studio has a very useful feature that allows you to create&nbsp; variables at compile-time with the /D compile option for <a href="http://msdn.microsoft.com/en-us/library/ms235639(VS.80).aspx">cl.exe</a>.&nbsp;This will create a variable with a value specified (at compile time) that is then accessible from within code. For example, take the line of C code:&nbsp;</p>
<p>#define MYCTR (__COUNTER_ _ + MYOFFSET)</p>
<p>The variable MYOFFSET is not defined anywhere within the source code. Instead it is actually defined at compile time with this:</p>
<p>cl /nologo /Ob2 /Z7 /DMYOFFSET=251 6.cpp /c</p>
<p>I then modified the &#8220;Call Obfuscation&#8221; code (from the previous section) to use this trick. This made the anti-disassembling blob &#8220;polymorphic&#8221; between compiles as long as the seed value for &#8220;MYOFFSET&#8221; was modified accordingly.&nbsp;</p>
<p>&nbsp;<span class="thumbnail-image-block ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fpolymorph_inlineasm_between_compiles_annotated.png%3F__SQUARESPACE_CACHEVERSION%3D1264104020913',1050,1680);"><img src="http://chargen.matasano.com/storage/thumbnails/4458867-5462479-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104435697" alt="" /></a></span><span class="thumbnail-caption" style="width: 300px;">Annotated visual of polymorphs between compiles</span></span></p>
<p>In the end it came out <a href="http://github.com/s7ephen/CSAW_2009/blob/master/6/source/evil.h">something like this</a>&nbsp;which could be used in the code like so:&nbsp;<a href="http://github.com/s7ephen/CSAW_2009/blob/master/4/source/4.cpp#L102">#include &#8220;evil.h&#8221;</a> to screw up disassembly of the compiled code. An annotated visual screenshot of this <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/polymorph_inlineasm_between_compiles_annotated.png">process is here</a>.</p>
<p><span style="text-decoration: underline;"><strong>TLS Execution:</strong></span></p>
<p>I learned about this Thread Local Storage (TLS) execution trick some years ago in <a href="http://www.hexblog.com/2005/10/tls_callbacks.html">one of Ilfak&#8217;s blogposts</a>.&nbsp;It is a way (on Windows) to have a piece of your code execute before the main part of your executable (the entry point) is jumped into. The impact of this is that the code will even execute before a debugger can attach to it even if it starts the target program! Combined with anti-debugging tricks this can be really useful. It requires using an awesome custom linker though.</p>
<p><strong><span style="text-decoration: underline;">Use of &#8220;Here Strings&#8221;:</span></strong></p>
<p>&nbsp; My name for these probably sucks, but once again language fails me and I don&#8217;t know the correct term for this (if they even have one). In languages like Ruby or Python they are called &#8220;here strings&#8221; or &#8220;doc strings&#8221;. However, in languages like C even static strings get squirreled away in the BSS and then a pointer to them is used in the code. What I wanted was a way to reference a string buffer DIRECTLY where it was or as a really small relative offset. The reason I wanted this was to change the way the call into the string obfuscation functions looked, and to confuse disassembly. To achieve this I used a combination of inline assembly and _emit bytes. I wrote <a href="http://github.com/s7ephen/CSAW_2009/blob/master/utils/sa7encode.py">a small python script</a>&nbsp;to take a string as input.It would generate a random key for my encryption scheme and then generate the ciphertext (based on the plaintext input and the generated key).</p>
<p><span class="thumbnail-image-block ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Foutput_of_sa7encode.png%3F__SQUARESPACE_CACHEVERSION%3D1264104094023',747,614);"><img src="http://chargen.matasano.com/storage/thumbnails/4458867-5462867-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104094024" alt="" /></a></span></span></p>
<p>It would then generate a bit of inline assembly that represented the string as inline asm _emit bytes that exposed pointers to these buffers in the ebx and eax registers respectively. I could then just <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/output_of_sa7encode.png">cut and paste the output</a> of this Python script <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/inline_asm_ciphertext_and_key_buffers.png">into my C code</a> and use the &#8220;strings&#8221; by referencing pointer variables that referenced labels in the inline assembly. Instead of defining my ciphertext and key buffers like this (as I would normally in C):</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/ciphertext_and_key_buffers.png?__SQUARESPACE_CACHEVERSION=1264104183844" alt="" /></span></span></p>
<p>I could access them as inline assembly &#8220;here strings&#8221; like this:</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/inline_asm_ciphertext_and_key_buffers.png?__SQUARESPACE_CACHEVERSION=1264104232190" alt="" /></span></span></p>
<p>If you dont get what I mean, sample output of this Python <a href="http://github.com/s7ephen/CSAW_2009/blob/master/6/source/flag.txt">script is here</a>.</p>
<p style="text-align: left;"><span style="font-size: 200%;"><span style="text-decoration: underline;">The Challenges:</span></span></p>
<p>Now that you have an understanding of the collection of anti-debugging and anti-reversing tricks I was pulling from, let&#8217;s take a look at how I combined and mixed them together to create different reversing challenges. The challenges themselves I thought were pretty neat.</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/1/README.TXT">Challenge #1</a>: &#8220;JumpIt&#8221;</p>
<p>The backstory for for this challenge <a href="http://github.com/s7ephen/CSAW_2009/blob/master/1/README.TXT">you can read here</a>. (In fact, each challenge name in this post will link directly to the backstory if you want to read them.) The first of these challenges was intended to be fairly simple. The &#8220;key&#8221; for the challenge was just a static string that was popped up in a User32 MessageBox(). The trick was that the reverser had to jump over a call to ExitProcess to get the popup. Simple stuff. A guy named LordParody made <a href="http://lordparody.wordpress.com/2009/11/19/9/">a video tutorial of it even</a>.</p>
<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/koek_42M1Mg&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/koek_42M1Mg&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p>Tricks Employed: Premature Exit</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/2/README.TXT"><span style="text-decoration: none;">Challenge #2</span></a>: &#8220;BeingDebugged&#8221;</p>
<p>This executable checks to see if it is being debugged before and after it causes itself to crash. If the reverser subverts it, the flag is displayed to them.</p>
<p>Tricks Employed: String Obfuscation, Being Debugged (custom), Debugger Required Exceptions, Inlining</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/2/README.TXT">Challenge #3</a>: &#8220;Hey I know you!&#8221;</p>
<p>When it starts, this executable checks to see if a process of a specific name is running, if it isn&#8217;t it exits. The reverser must find the name and start a process of this name to be displayed the key. One think you might find interesting about this one is that I did not use <a href="http://msdn.microsoft.com/en-us/library/ms682629(VS.85).aspx">EnumProcesses()</a> instead I p<a href="http://github.com/s7ephen/CSAW_2009/blob/master/3/source/3.cpp#L58">arse structures directly from ZwQuerySystemInformation</a>. I borrowed this from <a href="http://www.dontstuffbeansupyournose.com/?p=58">TheMina</a>. This was a good exercise.</p>
<p>Tricks Employed: String Obfuscation, Here Strings</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/4/README.TXT">Challenge #4</a>: &#8220;Hey I know you too!&#8221;</p>
<p>This is the same as Challenge #3 except with some more tricks thrown in and different keys.</p>
<p>Tricks Employed: String Obfuscation, Inlining, Being Debugged (custom), Here Strings, Polymorphic C Code, Call Obfuscation</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/5/README.TXT">Challenge #5</a>: &#8220;Are You My Mama?&#8221;</p>
<p>This is a DLL that exports several functions. These exports are irrelevant because the DLL (upon being loaded) checks to see if the process loading it matches a name it expects, if not, it kills the process entirely. Reversers must satisfy or subvert this check to get the flag.</p>
<p>Tricks Employed: String Obfuscation, Here Strings, Inlining, Polymorphic C Code, Call Obfuscation</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/6/README.TXT">Challenge #6</a>: &#8220;Timing Matters&#8221;</p>
<p>This executable checks if it is being debugged before and after it rides a sled of software breakpoints. The reverser must satisfy or subvert these checks to get the flag.</p>
<p>Tricks Employed: String Obfuscation, Being Debugged (custom), Timing Tricks, Here Strings, Inlining, Polymorphic C Code, Call Obfuscation</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/7/README.TXT">Challenge #7</a>: &#8220;Spin Lock&#8221;</p>
<p>A DLL contains 5 <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/challenge7_tumblers.png">exported functions (each called &#8220;tumblers&#8221;)</a>. Each function takes a character buffer as input and outputs an obfuscated version of the same buffer.</p>
<p><span class="thumbnail-image-block ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fchallenge7_tumblers.png%3F__SQUARESPACE_CACHEVERSION%3D1264103830099',700,1105);"><img src="http://chargen.matasano.com/storage/thumbnails/4458867-5462807-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104398218" alt="" /></a></span><span class="thumbnail-caption" style="width: 300px;">Exported DLL functions</span></span></p>
<p>These &#8220;tumblers&#8221; must be strung together to decrypt the contents of a packet capture file (which contain the flag). Additionally (like Challenge #5) this DLL will not be loaded by just any executable, it needs to be loaded by an executable of a specific name!</p>
<p>Tricks Employed: Inlining, Polymorphic C Code, Call Obfuscation, challenge specific string obfuscation</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/8/README.TXT">Challenge #8</a>: &#8220;You have bad BHO!&#8221;</p>
<p>This was a <a href="http://en.wikipedia.org/wiki/Browser_Helper_Object">Browser Helper Object</a>. For those unfamiliar with these, it is another term for &#8220;<a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/bho_installed.png">Internet Explorer Plugin</a>&#8220;.This particular one was intended to simulate the basic functionality of a banking trojan, watching which sites you surfed to.</p>
<p><span class="thumbnail-image-block ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fbho_running.png%3F__SQUARESPACE_CACHEVERSION%3D1264103716741',700,1105);"><img src="http://chargen.matasano.com/storage/thumbnails/4458867-5462764-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104384508" alt="" /></a></span><span class="thumbnail-caption" style="width: 300px;">The Browser Helper Object is watching&#8230;</span></span></p>
<p>To unlock the flag you needed to reverse it to find out which site it wanted you to surf to!</p>
<p>Tricks Employed: String Obfuscation, challenge specific string obfuscation</p>
<p><a href="http://github.com/s7ephen/CSAW_2009/blob/master/CSAW_Final_Challenge/Readme.txt">The Final Challenge</a>: &#8220;The Fin&#8221;</p>
<p><span class="thumbnail-image-float-left ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fdriver_challenge.png%3F__SQUARESPACE_CACHEVERSION%3D1264103546290',700,1105);"><img style="width: 150px;" src="http://chargen.matasano.com/storage/thumbnails/4458867-5462721-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104361321" alt="" /></a></span><span class="thumbnail-caption" style="width: 150px;">loading the driver</span></span>This final challenge (unbeknownst to the competitors until the day of the competition) was a Windows Kernel Driver. The kernel driver (installed on XP SP2 machine) needed to be reversed to locate the IOCTLs it was listening for. Even a few of the IOCTLs it was listening for resulted in some <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/driver_a_correct_ioctl.png">taunting messages</a> (like <a href="http://dl.dropbox.com/u/2595211/CSAW_blogpost_pics/driver_bluescreen.png">custom blue screens of death</a>). Since this challenge as given on-site at NYU:Poly it was evaluated qualitatively.</p>
<p><span class="thumbnail-image-float-right ssNonEditable"><span><a href="javascript:showFullImage('/display/ShowImage?imageUrl=%2Fstorage%2Fdriver_solution.png%3F__SQUARESPACE_CACHEVERSION%3D1264104322278',340,671);"><img src="http://chargen.matasano.com/storage/thumbnails/4458867-5462941-thumbnail.jpg?__SQUARESPACE_CACHEVERSION=1264104348858" alt="" /></a></span><span class="thumbnail-caption" style="width: 152px;">Solution<span style="font-family: Verdana, Arial, Helvetica, sans-serif; line-height: normal; font-size: 12px;">.</span></span></span></p>
<p>&nbsp;</p>
<p>Some&nbsp;<a href="http://github.com/s7ephen/dontstuffbeansupyournose.com/raw/master/ucon09/Intro_NT_kernel_security_stuff.pdf">kernel reversing materials</a>&nbsp;were provided that demonstrated all the techniques needed. Additionally, during the course of the challenges&nbsp;<a href="http://github.com/s7ephen/CSAW_2009/tree/master/CSAW_Final_Challenge/hints_and_solution/">incremental hints</a>&nbsp;were given.</p>
<p>Tricks Employed: String Obfuscation, Here Strings, Call Obfuscation, Inlining, Polymorphic C Code</p>
<p>&nbsp;</p>
<p><span style="font-size: 200%;"><span style="text-decoration: underline;">The Outcome:</span></span></p>
<p>Many of the teams solved many of the first 8 qualifying challenges. Unfortunately, no one was able to solve the Final Challenge entirely. The listing of all the <a href="http://www.poly.edu/csaw-CTF">final rankings are here</a>. A number of teams were able to obtain some points for explaining their process and providing some cursory information they obtained while reversing. Alex&nbsp;Radocea (of RPI) eventually solved it a month or so later and messaged me online ;-).</p>
<p>The competition was closed out with a big <a href="http://www.facebook.com/event.php?eid=117192723421">awards ceremony</a>. (If you chose to watch the video below, the &#8220;Application Security&#8221; awards begin at 15:25).</p>
<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8573829&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=8573829&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object></p>
<p><a href="http://vimeo.com/8573829">CSAW 2009 - Awards Ceremony</a> from <a href="http://vimeo.com/nyupoly">NYU-Poly</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
<p>There are also p<a href="http://www.poly.edu/galleries/2009/11/16/csaw-2009-awards-day">hoto galleries of the awards ceremony here</a>.</p>
<p>We at Matasano are particularly proud of the team RPISEC (http://rpisec.net/) who ranked 2nd place behind the Carnegie Mellon Team. The RPISEC team had (Alexandru Radocea, Ryan Govostes, and Adam Comella) who are all Matasano interns. (Inquire about the Matasano internship program by emailing careers@matasano.com)</p>
<p><span style="text-decoration: underline; font-size: 200%;">Conclusions:</span></p>
<p>In conclusion, the whole experience of building these challenge for CSAW was a good one. In hindsight, I wish I had done a better job on making the difficulty progression a bit more even. In other words, I&nbsp; don&#8217;t think I mixed and matched the different &#8220;Tips and Techniques&#8221; (summarized earlier) well enough to achieve an good gradient of difficulty.&nbsp; For example, I spent so much time on writing the string obfuscator/encryptor but I forgot to use it in one or two places that could have really benefitted from it, such as the executable names in Challenge #3. Likewise, I spent a lot of time building the &#8220;polymorphic call obfuscator&#8221; and did not use it in some of the earlier challenges like Challenge #2. Another huge oversight on my behalf was not obscuring the call to MessageBoxA well. I could&#8217;ve used my call obfuscator or made an indirect call, but I simply forgot to add this. A few people recognized this pattern and just jumped to the MessageBoxA call. :-( I guess these are all things you can only learn in retrospect.</p>
<p>Nonetheless, a lesson well learned, all of which I can take into my experience for CSAW-CTF 2010. &nbsp;Feel free to try your hand at any of <a href="http://github.com/s7ephen/Csaw_2009">these challenges</a>.&nbsp;The binaries are <a href="http://github.com/s7ephen/Csaw_2009">posted in github</a>. Everything you need is in there along with the source (which the contestants obviously didn&#8217;t have so ignore it if you are doing the challenges ;-). Just download onto a Windows XP SP2 machine. Drop me a line to let me know what you think, or if you needs help. Thanks for reading.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content></entry><entry><title>Protecting the Laptop Herd</title><category term="SpaXeWars"/><category term="nostalgia"/><category term="playbook"/><category term="ralex"/><id>http://chargen.matasano.com/chargen/2009/12/21/protecting-the-laptop-herd.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2009/12/21/protecting-the-laptop-herd.html"/><author><name>Craig Brozefsky</name></author><published>2009-12-21T21:26:19Z</published><updated>2009-12-21T21:26:19Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Greetings from the Playbook Development team, deep in the Ruby Mines
of Matasano.  I&#8217;m Craig Brozefsky, lead developer, and senior
curmudgeon.  Back when OSX was still called <a href="http://3.bp.blogspot.com/_Dzo41Iq2vQs/R5e_MxK-KaI/AAAAAAAAAA4/F5OotzCyVFc/s400/jobs-next-computer.jpg">NeXTStep</a>, but after the
fall of suck.com, I was an ObjC hacker.  I have fond memories of the
time, despite the daily <a href="http://nextstuff.info/mirrors/next-ftp.peak.org/next/apps/games/xox/">SpaXewars</a> beatings at the hands of my
co-developer, Jesse.  So, when Tom informed the team we would be
adding support for OSX Host Firewalls and needed to whip up a native
OSX application, I saw my chance to pretend I was 10 years younger.</p>

<h3>Playbook as Border Collie</h3>

<p>Back then, developers used workstations &#8212; I had a Sun E1 and a
<a href="http://simson.net/hacks/cubefire.gif">NeXTCube</a>.  They heated your
office, irradiated your head with giant
<a href="http://kiestphoto.com/contests/kiestphoto-crt2.jpg">CRT</a>
tubes, and had
<a href="http://www.ubergizmo.com/photos/2006/7/maltron-keyboard.jpg">keyboards</a>
so big you could take naps under them!</p>

<p>Now it is customary to issue employees a laptop so they can work from
bed.  This is a great advance.  They are small, make your thighs
sweaty, ruin your eyesight, and torque your wrists &#8212; in bed.  A
single modern laptop can run the half-dozen virtual machines needed
for modern web development using portable standards like CSS and HTML.</p>

<p>This proliferation of machines which move in and out of the office
present a challenge to the company&#8217;s <a href="http://media.steampowered.com/steamcommunity/public/images/avatars/b2/b2beaa6f0c930bff304c99ad7218126558eafd0c_full.jpg">Hall Monitors</a>, or network
security ops as they like to call themselves.  If Bob uses the company
laptop at home, in bed, then we can&#8217;t enforce company web surfing
policy at all times.  That machine could have <a href="http://www.eternal-september.org/">anything</a> on it when it plugs back into the office network!</p>

<p>Luckily, the laptop has its own firewall built in, we just need a way
for the Hall Monitors to manage the rules.  Provided such a mechanism,
they could key protect laptops with blacklists of drive-by malware
sites, limit incoming connections to known services, limit outgoing
connections to specific services.  Then the next time Bob is getting
cream cheese and sesame seeds all over the keyboard while checking
email at the cafe, his host firewall is blocking the SMB attack
launched by the unemployed financial analyst turned greasy-haired
hacker in the corner.  This is the stuff Hall Monitor dreams are made
of.</p>

<h3>Chaos Breeds Requirements Docs</h3>

<p>An employee&#8217;s laptop is somewhat sacred, so we didn&#8217;t want to have
creds for each laptop in some central database.  Eric threatened
mutiny at such a prospect anyways, perhaps out of fear we would use
the creds to scan his laptop and find the pirated set of Little House
novels in his <code>~/.snekrit</code> directory.</p>

<p>Since I only arrive in the office on time on prime Julian dates or
when Tom is buying dinner, we could not realiably schedule a push from
our dogfood Playbook instance to each laptop.  Inspired by NCSA Mosaic
and the awesome power of HTTP technology, We opted to write a client
that would run under each user&#8217;s account and pull rules down from a
Playbook server.</p>

<p>As Cory mentioned, Matasano has been an Apple shop since 1925, so it
was natural that we added support for OSX&#8217;s ipfw first.  We could
torture our own employees with the early releases, all under the guise
of protecting them.</p>

<h3>Keep Talking</h3>

<p>We worked up a list of requirements for the client and server
communications.</p>

<ol>
<li>Client and Server must be authenticated</li>
<li>Comms must be encrypted</li>
<li>Laptops should not require a Playbook login</li>
<li>Enrolling a new laptop should be easy</li>
<li>Revoking a laptop should be easy</li>
</ol>

<p>We wanted the authentication to be automated, not dependent upon user
password choice, and verifiable in both directions.  The obvious
solution here is SSL with certificate-based authentication on both
sides.  Since Playbook is accessed via an Apache instance, using
Phusion Passenger, we can rely on Apache to verify the client
certificate.</p>

<p>To manage the client certificates we built our own CA based on the
<a href="http://segment7.net/projects/ruby/QuickCert/">QuickCert</a> Gem.  We
create a key and certificate for each client.</p>

<p>We need to tell Apache to require a valid client certificate for
requests to the pull controller, and to only accept one signed by our
Playbook CA.  Also, in order to allow us to manage Client Certificates
without dealing with revocations, we pass along the certificate in the
request headers.</p>

<pre><code>&lt;Location /pull&gt;
  SSLVerifyClient require
  SSLOptions +StrictRequire +StdEnvVars +ExportCertData
  RequestHeader set X-Client-Cert %{SSL_CLIENT_CERT}e
  SSLVerifyDepth  1
&lt;/Location&gt;
</code></pre>

<p>We don&#8217;t want to require a valid client certificate when the laptop is
enrolling, aka downloading, the native client.</p>

<pre><code>&lt;Location /pull/enroll&gt;
  SSLVerifyClient none
&lt;/Location&gt;
</code></pre>

<p>Lastly, we tell Apache were the CA Certificate for our client pull
subsystem is located.</p>

<pre><code>&lt;IfDefine production&gt;
  SSLCACertificateFile "../../data/client_pull_ca_production/cacert.pem"
&lt;/IfDefine&gt;
</code></pre>

<p>Our controller needs to make sure the client certificate supplied to
us is the same one we have on file for the host in question.  The
<code>HTTP_X_CLIENT_CERT</code> entry in the envrionment table contains the
certificate, so we normalize it and generate an SHA1 checksum.  That
is compared with a normalized SHA1 checksum of our certificate on
file.</p>

<p>Here is the relevant method:</p>

<pre><code>def check_cert(fw)
  cert = request.cgi.env_table['HTTP_X_CLIENT_CERT']
  if cert.blank?
    raise "No client certificate provided"
  end
  if fw.client_pull_certificate.blank?
    raise "Firewall does not have a client pull certificate"
  end

  cc = cert.gsub(/\s/,"")
  fc = fw.client_pull_certificate.gsub(/\s/,"")

  if SHA1::sha1(cc).to_s != SHA1::sha1(fc).to_s
    raise "Client pull certificate does not match."
  end
end
</code></pre>

<h3>Ragel Rock</h3>

<p>Before I came to Matasano, I was a Java hacker at the <a href="http://ccl.northwestern.edu">Center for
Connected Learning an Computer-Based
Modeling</a>, where my job was working on
<a href="http://ccl.northwestern.edu/netlogo">NetLogo</a>.  This involved work on
lexers, parsers, interpreters, compilers, and other aspects of
programming language design.  I liked that alot.  In Playbook, we&#8217;re
interested in the lexing and parsing, and some analysis of a range of
firewall languages.</p>

<p>Writing lexers and parsers is, well, boring and rewarding at the same
time.  It&#8217;s a tedious cataloging of the &#8220;parts of speech&#8221; and grammar
rules of a language.  If you have good documentation for your target
language, it is mind-numbing. With poor or no documentation it is
maddening.  Pray to whatever gods or old ones you believe in that the
language is regular and not just &#8220;defined by implementation&#8221;.  Despite
this, it is rewarding when done, because you have a really useful tool
for analyzing the target language.</p>

<p>This is precisely the kind of task where a good tool for building your
lexers and parsers can save you thousands of dollars in time and
prescription sedatives.</p>

<p>Adding IPFW rules support to Playbook took an afternoon thank to
<a href="http://www.complang.org/ragel/">Ragel</a> and our own lexer toolkit
built on top of it, Ralex.  Ragel lets you define reusable finite
state-machines &#8212; it&#8217;s like regular expressions turned inside out with
hooks all over.  Or, as the projct site says:</p>

<blockquote>
  <p>Ragel compiles executable finite state machines from regular
  languages. Ragel targets C, C++, Objective-C, D, Java and Ruby. Ragel
  state machines can not only recognize byte sequences as regular
  expression machines do, but can also execute code at arbitrary points
  in the recognition of a regular language. Code embedding is done
  using inline operators that do not disrupt the regular language
  syntax.</p>
</blockquote>

<p>Ralex is our own class which includes a set of Ragel state-machines
that match tokens common to firewall rule languages, and then some
book-keeping code that takes a string and a set of keywords, and gives
you a token stream usable as
<a href="http://i.loveruby.net/en/projects/racc/doc/">RACC</a> input.</p>

<p>When we want to write a rule tagger and parser for a new rule
language, we start with the base Ralex clss:</p>

<pre><code>class RalexIpfw &lt; Ralex

%%{ 

 machine ralex_ipfw;
 include ralex_base "ralex_base.rl";
</code></pre>

<p>Next then we define any new lexemes needed for this specific rule
language.  Usualy this is limited to idiosyncratic representations of
percentages/bandwidth limits or port/IP ranges.  </p>

<pre><code>hexnumber = '0x' @collect_token hexdigit+
  @collect_token
  &gt;{ start_token(:HEXNUMBER) }
;   

probability = '.' &gt;collect_token digit+
   @collect_token
  &gt;{ start_token(:NUMBER) }
;


ipwithmask = ipaddr ":" @collect_token ipaddr
  %{ start_token(:IPWITHMASK)}
;

macwithmask = macaddr "/" @collect_token digit+ @collect_token
  &gt;{ start_token(:MACWITHMASK)}
;

portset = ( alnum | '\-' | digit )+ '-' @collect_token ( alnum | '\-' | digit )+
  @collect_token    
  &gt;{ start_token(:PORTSET) }
;

slashcomment = '/' '/' &gt;collect_token &gt;getcomment ;


bandwidth = digit+ @collect_token ('K' | 'M') @collect_token ('bit' | 'Byte') @collect_token '/s' @collect_token    
  &gt;{ start_token(:BANDWIDTH) }
;
</code></pre>

<p>Lastly we identify which state-machines we want to use when parsing a
rule:</p>

<pre><code>token = ( id
         | ipaddr
         | ipnet
         | ipwithmask
     | macaddr
         | macwithmask
         | portset
         | bandwidth
         | hexnumber
         | number
         | percentage
         | bytecount
         | ralex_specials
         | slashcomment
         | hashcomment
         | probability
         | quote ) %{ finish_token; };
</code></pre>

<p>After we have our Ralex class for the new firewall language, we then
build two RACC parsers on top of that.  One tags significant rule
elements, like addresses and ports, which drives our rule indexing
engine.  The second one does full rule parsing and performs syntax
checks and generates a ASTish representation of rules for use in or
analysis tools.</p>

<p>Since we have a bunch of these written for other rule languages
already, it&#8217;s pretty easy to put a new one together.  The most time
consuming, mind-numbing bit is encoding all the keywords in the rule
languages, which we currently have to triple code cause I&#8217;ve been to
lazy to refactor.</p>

<p>This whole process is driven by a bunch of test macros we have for
taking examples rules and deriving tests for the tokenizer, tagger,
and parser classes.</p>

<pre><code>it "should handle ip address representations" do

    token_test("from 192.2.2.2 to any",
               [[:FROM, "from"], [:IPADDR, "192.2.2.2"],
                [:TO, "to"], [:ANY, "any"]])
    # masklen
    token_test("from 192.168.1.0/25 to me",
               [[:FROM, "from"], [:IPADDR, "192.168.1.0/25"],
                [:TO, "to"], [:ME, "me"]])

....

it "should tag addresses and ports " do
    parse_test("add deny ip from 123.45.67.0/24 to my.host.org",
               ["add", "deny", "ip", "from", IPAddr.new("123.45.67.0/255.255.255.0"),
                "to", Hostname.new("my.host.org")])

    parse_test("add deny ip from 123.45.67.0/24 to my.host.org 80",
               ["add", "deny", "ip", "from", IPAddr.new("123.45.67.0/255.255.255.0"),
                "to", Hostname.new("my.host.org"), PortNumber.new(80)])
</code></pre>

<p>At the end of the afternoon I had my tokenizer, and a tagger.  We
don&#8217;t have a full parser yet, so there are no syntax checks for IPFW
in the 3.0 release.  After defining a new Firewall and Line (as in
rule line) class for IPFW, I had working models, and was ready to
start on the controller and the OSX client.</p>

<h3>Back to the salt mines, for now.</h3>

<p>That concludes the server portion of our program, in the next episode
I&#8217;ll gush a bit about ObjC, and reveal the inner secrets of our OSX
client.</p>
]]></content></entry><entry><title>Introducing Playbook 3.0</title><id>http://chargen.matasano.com/chargen/2009/12/17/introducing-playbook-30.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2009/12/17/introducing-playbook-30.html"/><author><name>Thomas Ptacek</name></author><published>2009-12-17T20:15:02Z</published><updated>2009-12-17T20:15:02Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Let me tell you how good at marketing we are. We are so good at marketing that we are releasing a product right in time for the Christmas holidays &#8212;- in fact, just 7 days before Christmas break! As students of IT products know, the week before Christmas is an ideal time to capture the attention of enterprise buyers.</p>

<p>And on that note, allow me to introduce <a href="http://runplaybook.com/new/index.html">Playbook 3.0</a>!</p>

<h3>What&#8217;s Playbook?</h3>

<p>New to Playbook? Here&#8217;s the elevator pitch: Playbook is the last product you&#8217;d think a vulnerability research team would build. It doesn&#8217;t decompile MIPS C code. It can&#8217;t spot vulnerabilities in VOIP implementations. It doesn&#8217;t harden the Flash runtime. It barely contains any compiler code at all! Instead, it takes the working lives of people who have to deal with firewall rules and tries to make them better.</p>

<p>If you write code, you&#8217;re familiar with things like Trac and Github. You check your code into version control, you browse and review it in a web interface, you document it in a wiki, and you file tickets for bugs. Every dev team uses something like it.</p>

<p>Playbook takes the same workflow and bends it to firewall management.</p>

<p>Playbook is a web interface to versioned-controlled firewall configurations, which it can slurp up straight out of running firewalls. It parses and understands firewall rules, detects errors, and (most importantly) indexes rule terms so you can find addresses and networks across large numbers of firewalls. It handles end-user requests for rule changes so you don&#8217;t have to pick up the phone to talk to the Sharepoint admin. It provides for peer review and approval. And when rules are staged and ready, it offers push-button deployment so you don&#8217;t have log in to 100 remote devices.</p>

<h3>What&#8217;s New?</h3>

<p>Playbook 3.0 does these things better: it has a better UI, it&#8217;s faster, the rule editor gracefully handles huge rulesets without dumping you into a big text edit window, and (here&#8217;s a big feature we&#8217;ll talk about later) it now handles host rules for OS X desktops and laptops.</p>

<p>We&#8217;re beta testing 3.0 right now. Interested? Our first three qualified beta testers (you qualify if you have production firewalls) get a permanent free starter license. <a href="http://runplaybook.com/eval-signup"">Sign up here</a>. Questions? <a href="http://chargen.matasano.com/playbook-faq/">Start here with the FAQ</a>.</p>

<p>We&#8217;ve been quiet on the blog lately, and here&#8217;s one of the reasons. Craig will have more to say about Playbook 3.0 shortly, and then we&#8217;ll have another major announcement about products early in January. Stay tuned! </p>
]]></content></entry><entry><title>Ninja Threat Modeling</title><id>http://chargen.matasano.com/chargen/2009/11/2/ninja-threat-modeling.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2009/11/2/ninja-threat-modeling.html"/><author><name>Cory S.</name></author><published>2009-11-02T21:38:00Z</published><updated>2009-11-02T21:38:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<h3>Conquer your fear</h3>
<p>Like it or not, developing an attack plan for a penetration test requires standing up a rudimentary threat model. Not surprisingly, threat modeling often produces discomfort in the stomach and uncertainty in the heart of many testers, but you&#8217;ve got to cowboy up and do it.</p>
<p><span><span class="full-image-block ssNonEditable"><span><img src="http://chargen.matasano.com/storage/ntm.jpg?__SQUARESPACE_CACHEVERSION=1261282571977" alt="" /></span></span><br /></span></p>
<p>You need to determine where you&#8217;re going to spend your limited testing time, which tools you want to pull out of your arsenal, and how to prioritize your findings after the test is complete. Testing an application while blind to the context of how it could be abused in a real world environment is a sure-fire recipe for disaster and embarrassment.   <br /><br /> Start with an application overview sitting peacefully on your desk. A sudden bang, a quick diversion, a cloud of smoke - and a test plan appears in its place. Fear no more, for the guide to ninja threat modeling is here.</p>
<h3>SDL: This isn&#8217;t the threat model you&#8217;re looking for</h3>
<p>You&#8217;ve probably heard of threat models before, especially in traditional security development lifecycle circles. In that context, the threat models are generated in the requirements/design phase, which is much earlier in the process. It has spawned not just one, but two, Visio-driven tool sets from Microsoft and countless data-flow diagrams, attack trees, consulting engagements, and perplexed developers. When performed by a skilled and experienced team member, the model can be used to identify architectural weaknesses, guide default application behavior, and outline functional requirements for the product. <br /><br />However, by the time you&#8217;re in the verification phase of the lifecycle, generating a formal threat model starts to yield diminishing returns. We recommend taking a short-cut with a set of assumptions that have served us well over the years.</p>
<h3>Software would be great if it wasn&#8217;t for the users:   <br />Client-side code assumptions</h3>
<ul>
<li>The attacker will have unfettered access to the client and will instrument all of the functionality (this includes the &#8220;secret&#8221; admin and debug functions), and all of the client-side controls will be removed.</li>
<li>If it accesses the network, there&#8217;s a man-in-the-middle.</li>
<li>All input will be malformed and unexpected - even from the trusted end user: who will happily introduce input from untrusted sources.</li>
<li>The source code is completely exposed - including any secrets stored in the code.</li>
<li>If the application runs at a privilege level that the attacker desires, he will attempt to abuse it for nefarious purposes.</li>
<li>Don&#8217;t assume the code you&#8217;re testing is the attacker&#8217;s final destination in his path of exploitation. If the code weakens the system&#8217;s security posture in any way, the attacker will abuse it.</li>
</ul>
<h3>I&#8217;m sorry, Dave. I&#8217;m afraid I can&#8217;t do that:<br /> Server-side code assumptions</h3>
<ul>
<li>All of the assumptions for client-side code hold for server-side code as well. This includes the source code disclosure assumption if you&#8217;rere shipping product. If you&#8217;re running SaaS, it&#8217;s more of a question of when, not if.</li>
<li>The attacker is going to sit on the same network segment as the application. There&#8217;s no firewall or filters. There&#8217;s a special place in hell reserved for products that require firewalls or filtering to protect themselves against attack.</li>
<li>The naming service that the product relies upon will be compromised.</li>
<li>The switching and routing fabrics will be compromised.</li>
<li>If you have more than one defined user, one user will want to do things as the other user.</li>
<li>If you have more than one defined role, a user in one role will want to perform functions in the other role.</li>
<li>An attacker may want to cover their tracks. If he can do it with subtlety, he will take that path if it is easy to do.</li>
<li>If it is exposed to the Internet, some yahoo will want to make it crash with an asymmetric attack (think packet of death or attack amplification).</li>
<li>If the application runs on a multi-user system, other users on the system will attempt to subvert the application through any and all resources they can access (such as the file system, shared frameworks, IPC, and others) .</li>
<li>If the application uses URIs (HTTP/FTP/SMTP/ITMS, whatever), an attacker has compromised the innocent client and has access to the session command channel.</li>
</ul>
<h3>A return to olde SDL land?</h3>
<p>With these assumptions in place, you could go ahead and do some basic data flow analysis. You should be able identify key entry points in the application where data and functionality cross trust boundaries. If you want to stay in step with Microsoft, feel free to pull out the STRIDE* model and apply the threat types to each entry point, keeping in mind the assumptions m= entioned above. With the threat landscape outlined, you&#8217;ll find the STRIDE process will go faster than simply working from a blank data flow diagram without context.<br /><br />However, ninja threat modeling uses data flow analysis as a clean-up task, rather than the opening salvo. We&#8217;re impatient and want to know the answer to the question, &#8220;What entry points should we really care about?&#8221; right away.</p>
<p><span>* As required by the SDL powers-that-be, I am obligated to mention STRIDE threat types (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege) in all communications relating to threat modeling at least once.</span></p>
<h3>Where there&#8217;s smoke, there&#8217;s fire</h3>
<p>A heat-seeking approach to drive your test plan is just what you need. When we blather on about entry points, trust boundaries, and threat vectors, what we&#8217;re really thinking is &#8220;Where can I do the most damage in the shortest period of time?&#8221;   <br /><br />The ninja threat model  relies on two techniques: incident and vulnerability history and the commission of deadly sins.</p>
<h3>Those who cannot learn from history are doomed to repeat it</h3>
<p>The first technique examines how the product or similar products have been abused in the past. Don&#8217;t just look up old advisories or bug reports - look for incident data. Did a product have a vulnerability that allowed malicious code to spread? Was the vulnerability discovered and abused by a 16-year-old to make lots of friends on the social networking platform of the day? <br /><br />Examine these abuse cases and make sure you can recreate them against the application you&#8217;re testing. At the root of each one, there should be a vulnerability, a threat actor, and an impacted asset. If you&#8217;re stuck with dry vulnerability advisories, sometimes the researcher will have a good grasp on the impact of the finding and will document it well. In other cases, you have to watch out for advisories with overreaching statements or extreme speculation.<br /><br />What&#8217;s nice about these types of derived threats is a good amount of the test planning is already done for you and can be lifted wholesale. Watch out for tunnel vision, though - time, platform specifics, or other dependencies may have limited the avenues available to the researcher or intruder. Make sure you&#8217;rere looking for the pattern that indicates the flaw is present, not just performing a pattern match on yesterday&#8217;s exploit.</p>
<h3>Where DIY should be DDIY - Don&#8217;t Do it Yourself</h3>
<p>The second technique focuses on what developers get wrong most of the time - otherwise known as the &#8220;Deadly Sins&#8221;. The vulnerabilities introduced by these common flaws are mentioned for a reason: they get abused by threat actors on a regular basis. <br /><br />Every security outfit has a list of their deadly sins, including Microsoft, SANS, OWASP, and Matasano, because lists are just that cool. We think ours is better for one major reason - our Deadly Sins are features rather than defects. As a result, our work fits into ninja threat modeling much cleaner than a laundry list of vulnerabilities.<br /><br />It&#8217;s an issue of perspective and language. Developers don&#8217;t roll out of bed in the morning and say, &#8220;I&#8217;m going to code up a few SQL Injection vulnerabilities today!&#8221; Instead, they say, &#8220;I&#8217;m going to write the Advanced Search module for the Report Engine today!&#8221; When you hear this, your utter lack of faith in your development brethren should kick into overdrive and you should be busily entering &#8220;Test for SQL Injection here, here, and here&#8221; in your test plan.<br /><br />We&#8217;ve appended our list of Deadly Sins for Web Applications for easy reference. Parts of it also apply to other sorts of applications. When you see these features, get out your red pen, add another page to your test plan, and start outlining how many different ways developers get these things wrong and how to test for it.</p>
<h3>Time for the test plan</h3>
<p>After wrapping up the heat-seeking exercises, it&#8217;s time to sanity check your work with data flow analysis including the selective application of STRIDE mentioned earlier. Hopefully, the overlap should be extensive. If it isn&#8217;t, you may be dealing with something that hasn&#8217;t been tested extensively and may bear some interesting fruit. On the other hand, you may have been assigned the most boring application known to mankind. Congratulations!<br /><br />After following this approach, you should have a good definition of the application&#8217;s attack surface and the threat landscape which you will be attempting to recreate. As a result, you should be able to produce a meaningful test plan with a threat model that is defensible and sufficient to guide your engagement. You might even get away with doing one without a single Visio diagram.</p>
<h1><span><strong>Deadly Features for Web Applications</strong></span></h1>
<p>&nbsp;</p>
<p><span>1. Security</span></p>
<ul>
<li>Encryption</li>
<li>Hierarchical role/privilege management</li>
<li>Password storage</li>
<li>Password reset</li>
</ul>
<p><br /><span>2. E-mail functionality</span><br /><br /><span>3. Thick Clients: Web Applications In Name Only (WINOs)<br /><br />4. File Upload/Download<br /><br />5. Templating and Content-Controlled Code<br /><br />6. Advanced Search</span><br /><br /></p>
<h1><span><strong>More Deadly Features for Applications</strong></span></h1>
<p>&nbsp;</p>
<p><span>7. Persistent network sockets that accept arbitrary connections<br /><br />8. Installers<br /><br />9. Use of plug-ins or third party software to write directly to the DOM<br /><br />10. Single Sign-On   Authentication Hand-offs</span></p>
<p>&nbsp;</p>
]]></content></entry><entry><title>A C++ Challenge - The Conclusion</title><id>http://chargen.matasano.com/chargen/2009/10/15/a-c-challenge-the-conclusion.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2009/10/15/a-c-challenge-the-conclusion.html"/><author><name>Chris</name></author><published>2009-10-16T00:04:55Z</published><updated>2009-10-16T00:04:55Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>The contest is over! We got some good submissions and as expected a few security researchers found the bug rather quickly. The sample code had numerous defects, however not all were exploitable. Here are our top 3 correct submissions in order they were received:<br /><br /><strong>1st</strong> Drew Yao: With the quickest submission and first exploit. He exploited the bug on OSX Snow Leopard<br /><strong>2nd</strong> Kevin Easton: Sent in code that produces an exploit file<br /><strong>3rd</strong> Evin Robertson: With a great fuzzing technique for initially finding the bug (valgrind a.out /dev/urandom)<br /><br /><strong>Other correct entries:</strong><br />Joe Damato - Joe did a great write up on the challenge <a href="http://timetobleed.com/defeating-the-matasano-c-challenge-with-aslr-enabled/">here</a><br />Rachel Blum<br />Anonymous 1<br />Anonymous 2<br /><br />In addition to our contest submissions, we promised we would provide an answer to our vulnerability challenge, and here it is. The example code has a lot of issues. Everything from missing NULL pointer checks to a missing free. The bug we were looking for is the size overflow in the argument to our new operator. Our program opens up a binary file and reads some values out of it using a _stream structure. From those first few values we get an integer &#8216;s-&gt;num_of_streams&#8217;, which of course we sanity check before using it as an argument to a memory allocator. Unfortunately our sanity check is broken in the following if statement:<br /><br />&nbsp;&nbsp; &nbsp;if(s-&gt;num_of_streams &gt;= INT_MAX / (int)sizeof(int)) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;safe_count = MAX_STREAMS;<br />&nbsp;&nbsp; &nbsp;} else {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;safe_count = s-&gt;num_of_streams;<br />&nbsp;&nbsp; &nbsp;}<br /><br />The problem with this check is that our Object class is not sizeof(int). We assign safe_count the value of &#8216;s-&gt;num_of_streams&#8217; and go on our way. Following this bad check we call the C++ new operator to allocate an array of class instances representing each stream in our file. Unfortunately g++/libstdc++&#8217;s new operator allows for overflow to occur. This happens because we are asking for new to allocate &#8216;safe_count * sizeof(Obj)&#8217;. This a known issue, but more on that later.<br /><br />So now we&#8217;ve allocated a smaller number of class instances than &#8216;safe_count&#8217; specifies. Following the allocation of our class instances a meta data structure is placed on the heap using malloc(), zeroed out and a function pointer is setup. Now we enter a for loop using our attacker controlled safe_count value. This is where our problems begin, our for loop allocates a temporary buffer with each iteration copying a stream from the file into it, a DWORD is read from the stream and the parse_stream() method is called for each class instance we allocated earlier. The parse_stream() method sets the class member variable &#8216;type&#8217; to the value of the parse_stream() method &#8216;t&#8217; argument. The location of class member variable &#8216;type&#8217; should be in the heap because we allocated the class instance using the new operator. Unfortunately this is done for more class instances then we actually allocated earlier. This allows us to overwrite the function pointer in the &#8216;imd&#8217; structure, by way of the parse_stream() method, and gain code execution. This happens because the parse_stream() method effectively performs a 4-byte overwrite into heap memory that contains the &#8216;imd&#8217; structure.<br /><br />The fix here should start at the sanity check of s-&gt;num_of_streams. We should declare num_of_streams unsigned. This value should then be validated such that s-&gt;num_of_streams is not greater then MAX_STREAMS.<br /><br />We originally wanted to share a similar real-world code pattern but that bug isn&#8217;t officially patched yet and we wanted to get this post out. But thats OK because we can still talk about the core issue.<br /><br />As our example showed you can easily misuse the new operator. This is a known issue in <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351">libstdc</a> and was mentioned as far back as 2002 in <a href="http://www.blackhat.com/presentations/bh-usa-02/bh-us-02-iss-sourceaudit.ppt">this</a> Blackhat presentation. Using new to allocate some storage space may be common but there is another similarly dangerous but slightly less used code pattern here, and thats using new to allocate an array of class instances. Most developers have learned to carefully inspect the size of an allocation before copying user data to it. But allocating too few classes can result in similar memory corruption and have subtle but exploitable consequences when all the right stars are aligned, and thats what this challenge was all about.<br /><br />In the real world vulnerability we found exploitation was not as straight forward and may not even be possible. But the reason for that is actually an interesting story in itself (and by interesting I mean dry and boring). If the Obj class in our challenge had a constructor things would have been far different. Let&#8217;s add a simple constructor to our example:<br /><br />&nbsp;&nbsp; &nbsp;Obj(){ length = 0; }<br /><br />To understand why this changes things you need to dive down and disassemble the code. Long story short, even though we tricked our application into allocating 8 classes, g++ compiles the code in such a way that constructors are called for every class instance we requested, all 357913943 of them! Now if the constructor does something like set some class member variables to NULL then our chances of exploitation are pretty slim. This is because our process will essentially rip through its own heap writing NULL bytes until it hits the end of the heap and crashes. Thats quite a destructive constructor! When a constructor like this isn&#8217;t present our fake class instances become an API for writing into arbitrary memory. Thats how you gain code execution in our challenge.</p>
<p>Some of our commentors made the point that this was not C++, but merely C with classes. To those commentors I would like to say &#8216;welcome to the real world&#8217;. Code patterns like this are why security vulnerabilities exist!</p>
<p>This code pattern raises some interesting areas for exploitation since your non-existent class instance(s) are basically an API for writing into arbitrary memory locations in the heap. Bad allocations from the new operator are a known problem, Michael Howard at <a href="http://blogs.msdn.com/oldnewthing/archive/2004/01/29/64389.aspx">MSFT has written</a> about this issue before and MSFT did something about it! MSVC produces better code that doesn&#8217;t allow the integer overflow in the new operator to occur. Unfortunately g++ users are stuck with this issue for the forseeable future.</p>
]]></content></entry><entry><title>Corporate Pentesters: Fill Out Survey, Get Big Poster</title><id>http://chargen.matasano.com/chargen/2009/10/14/corporate-pentesters-fill-out-survey-get-big-poster.html</id><link rel="alternate" type="text/html" href="http://chargen.matasano.com/chargen/2009/10/14/corporate-pentesters-fill-out-survey-get-big-poster.html"/><author><name>Thomas Ptacek</name></author><published>2009-10-15T02:20:38Z</published><updated>2009-10-15T02:20:38Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p><em>[Update: That was fast! We&#8217;re at 97 submissions. 3 more and we go to lottery mode. For the rest of the week, if you fill out the survey, you will almost certainly get a poster. We&#8217;d give everyone a poster, but they cost a couple bucks a piece to ship.]</em></p>

<p>A few weeks ago we ran a survey for firewall operators. The results were a huge win for us. But most of our readers aren&#8217;t firewall operators. A lot of you are company pentesters, though. Are you part of a company application security team? Fill out a survey, and we&#8217;ll send you a poster. It will look marginally better and be significantly bigger than the picture below.</p>

<p><img src="http://chargen.matasano.com/storage/poster-small.gif" alt="Poster" title="" /></p>

<p><a href="http://www.matasano.com/survey-10-14">Take the survey here</a>. It&#8217;ll take you less than 5 minutes. </p>

<p>The first 100 responses will get posters, and we&#8217;ll ship 50 more posters by lottery if we go over 100 responses (we&#8217;ll let you know in this post if that happens).</p>
]]></content></entry></feed>
