Saturday, 29 September 2012

Test and Hack TeamMentor server with 3.2 RC5 code and SI library

Here is test server with the lastest build and SI Library  http://teammentor32.apphb.com (on AppHarbor's cloud)

There are tons of changes on this new 3.2 version and I've been working solidly on this release for the past 3 months. Some of the new features are REALY cool and I will try to blog about them (specially the automation/backend features provided by using the latest version of O2 FluentSharp APIs)

Tuesday, 25 September 2012

IE's efforts to break the internet

Everytime it takes me 5 minutes to install chrome on a new VM/EC2 it reminds me how much its UI and Security settings are a case study of what not to do (and this was on IE9, so a recent version of IE).

What I don't understand is why Google Chrome team doesn't give us couple direct download options (chrome.exe, chrome.exe.txt, chrome.exe.zip), so that it is even faster/easier to start using it.

It is amazing how IE went to be the best browser (and my preferred one) to the one I very rarely use. These days you run IE9 on a server and bing and google doesn't work, WTF!!!.  I understand the security issues, and I would be happy if it started some really low privilege process, but to break the internet!!! (I wonder how many websites work under IE Protected mode).

One the best quotes I heard recently was "why does IE goes out of its way to break the Internet?" :)

The only time I use IE these days is when I test TeamMentor against it, which is just another reminder of how much it sucks.

The way I look at it, every user has an emotional relationship with the tools/websites they use. The happier they are the more forgiving to little things they are. But they will only be happy with it if that tool/website does add value and helps with what the users is trying to do

Saturday, 22 September 2012

Trillions from MAYA (see the video, buy the book)

The Trillions Video is one of the most important videos that I have seen over the last couple years and one that gave me a nice warm felling that I'm doing the right thing with my O2 Platform development strategy.

They have now released a book Trillions: Thriving in the Emerging Information Ecology which I have started to read (on IPad's Kindle) and if you want to understand what will happen next, you NEED to read it.

A key message in the video and book is that to deal with new paradigms and systems,  we need complete new strategies, approaches, tools and ideas.

And that is exactly what I'm doing with O2 Platform. Instead of doing what just about every other Security tools vendors is doing (i.e. 'trying to create a 'blackbox' solution with some customisation features on top'), I'm creating an environment/platform where Scripting and Customisation are first-class citizens. In fact most of the O2 Platform is already 'scripts' and the expectation is that when facing the target application/website, the question is not 'do we really need to customise our technology/tools/approach?' but 'how fast can we customise our technology/tools/approach so that it actually represents reality?'. 

It's the customisation-time-delta that matters, and of course that the faster that happens, the more we (Application Security Knowledge) will scale :)

Back to Trillions, I see Application Security (and its complexity) as they see Trillions. Each node (from source-code to app's behaviour) is something that needs to be analysed, modeled, managed, controlled and (sometimes) fixed.

In fact, a business model that still yet to take hold in our industry is 'Security Tools/Technologies/APIs Customisation Services' (with clients paying for it and service companies providing it)

Btw, MAYA company and research is simply amazing and their focus on Design is a great inspiration  (what a great place to work that must be). Checkout their other videos (http://vimeo.com/mayanmaya) and research (http://www.maya.com/practices/research).

Even their name is really powerful, since MAYA means Most Advanced Yet Acceptable.

Finally, if you want to explain what 'Is An API?' to a non-developer audience, point them to MAYA's latest video on Containerization (I would love to have videos like this to example how SAST, DAST and even O2 works :)  )

O2's Findings Viewer on OSx viewing AppScan Source file

After O2 in OSx - Running TextBased C# REPL tool I was wondering if the O2's Findings Viewer Tool would also work on OSx, and I was pleasantly surprised when it did :)

Here it this tool in action showing the scan results of the SuperSecureBank application created by IBM's AppScan Source (OunceLab's engine).



O2 in OSx - Running TextBased C# REPL tool

So here it is, the first O2 C# REPL environment running natively on OSX  :)


You can download this 568k .NET 4.0 executable from Util - Text Based C# REPL v1.0.exe and it should work on your PC and Mac :)

As you can see on the screenshot above, to run in on the mac ou will need to have Mono installed (download it from here) and execute the exe using mono Util\ -\ Text\ Based\ C#\ REPL.exe or  mono "Util - Text Based C# REPL.exe"   (mono doesn't seem to register the *.exe extension)

Although there is no code-complete (the idea of this REPL is to keep it as simple as possible), a good number of O2 FluentSharp API's seem to be working ok.

For example here is a script that downloads a new DLL (MarkdownSharp.dll) and consumes it


There is also access to .NET's Lamba and Extension Methods:



Wednesday, 19 September 2012

Stand-alone executable for O2 Platform

There is a now a stand-alone executable for the O2 Platform (20Mbs) which has all the main dependencies and comes in 1 exe.

You can download it from: http://tiny.cc/O2Platform

Let me know if you have any issues running it

Note that this is not an installer, this exe file has all dependencies embedded and will extract them on first run.

You can put it on any folder (not the desktop since you will get a number of O2 folders in there :) ) or drive, and it should just run

Reply to 'I would like to help' request (with focus on SAST)

here is reply I sent today to an 'Hey how I can help/join/participate on the O2 Platform' question:

Hey .... , I would love you have you help (or join) the O2 Platform project , there are a lot of areas that you can help :)

To start I would ask you to focus on your C# skills and get your head around O2's REPL scripting environment, VisualStudio Plug-In and Cat.NET integration. We can move on to the Eclipse Plug-in later on.

I really think that we can change/improve the way developers consume Security Knowledge, and since you understand SAST and 'Static Analysis Technology', you can help me in the development of the next version of the Cat.NET VisualStudio Extension (for example: adding Guis for the Rules, adding support for MVC Frameworks, add support for 'offline/out-of-process' scans (on same box or in the cloud), etc...)

Btw, have you seen/tried the real-time scanner PoCs? It is a amazing learning tool for security vulnerabilities

All O2 source code is here: https://github.com/o2platform and there are tons of articles and blog posts at: http://o2platform.wordpress.com . Yes O2 needs a new website with a much better structure :) , I have the o2-platform.com domain for that purpose

There is a mailing list at https://lists.owasp.org/mailman/listinfo/owasp-o2-platform , and although , I'm thinking of moving it Google Groups, that is the best place to ask questions (and meet the other O2 developers, collaborators and users).

Let me know where you would like to start,

Monday, 6 August 2012

How does O2 compare with LinqPAD

(just got this question on this reddit thread, and here is my answer) 

There are a number of similarities, specially in the capability of quickly running C# scripts. Most of the differences come from the fact that they have are different approaches and development histories. LinqPAD (I think) was developed to help improving the execution and visualization of LINQ Queries, where the O2 Platform (and its REPL environment) was created to help to script application security analysis, and eventually O2 evolved into a full scripting and application development environment.
I can't really talk for LinqPAD (since I'm not part of it development team), but here is where I think O2 Platform provides extra value:
  • O2 tries to integrate with as many tools as possible, in fact you can consume LinqPAD from O2:
  • O2 is Open Source and has AutoCompletion support (which LinqPAD has on the paid-for-version)
  • O2's scripts are designed to create mini-tools. I.e. the idea is that once you finished a script you package it as a stand-alone script (with *.h2 extension) or an .exe. In fact the O2 Platform, is basically a collection of tools, GUIs, technology, and APIs developed using this C# REPL environment. For example the main O2 REPL environment exposes a WinForm's Panel Control which is 'feed' to the script so that it can be used while developing a GUI (with 1 line change to use Form Control and make it a stand-alone tool))
  • One core idea of the O2 REPL environment is that it should be used everywhere, since it provides real time feedback/coding-loop while developing or testing new ideas. For example I have already used it for:
  • The REPL environment can also be used to expose (or debug) objects on applications being developed. There is an 'Script_Me(...)' extension method that open up a new WinForms window with the 1st parameter (the 'this' value) being 'feed' to the REPL environment.
  • In fact I develop O2 in O2 :) , and I frankly find VisualStudio really painful to use (and slow). Although now that there is an O2 VisualStudio Extension that allows the REPL of VisualStudio itself, this might improve. You can download it from : O2 Platform for VisualStudio 2010
    • .... I really like the concept of '...the IDE is the Application...' where you also have real time REPL environments in IDEs or tools that provide rich funcionality
  • Using this REPL environment I also developed this pretty cool PoC Real-Time Vulnerability Feedback in VisualStudio which is closer to how I think we need to provide security information to developers (when compared with what we do now which is an out-of-band process)
  • Included in the O2's REPL environment is an Fluent API, which Is called Fluent# and is available at CodePlexor NUGet (note that these are a bit out of date with the current distribution of O2). This API really makes the O2's REPL environment powerful since you can execute quite complex tasks with only a few lines of code (its still C# , but there is extended use of C# Extension Methods to reduce the amount of code needed). You will see the Fluent# APIs in action, on most (if not all) O2 scripts.
    • Of Fluent# APIs and Extension Methods, I would stand out the Reflection and the WinForms APIs. The reflection one will give you easy access to any .Net assembly, class, method, property, field, enum (on disk or in memory) regardless of its public/private/internal status. The WinForms one will give you a thread-safe (very important feature) way to create and manipulate WinForm controls (if you look at the code behind most O2 scripts (including the C# REPL environment) you will see this API in action
  • Another powerful capability that you get from the O2 REPL environment is that the return value is viewed in a PropertyGrid which allows for a very organic growth of the script under development (although this might be a case of the workflow I use with O2 since LinqPAD result window is also quite mature and powerful)
  • A very powerful capability of O2's REPL environment which is hard to understand until experienced, is its data consumption and analysis capabilities. Due to .Net's powerful serialization and XML support, it is possible to script (and visualize) multiple data-transformations (with all steps stored as .NET Serialized objects)
  • There are many more features that exist in O2's and its REPL environment, and the best way for me to help you is if you have a particular problem that you are trying to so solve, please post the details here and I'll point you to the right direction (or to an existing script)
I would like to stress that that I don't view O2 as a competitor / replacement for LinqPAD!
If anything I want to make LinqPAD better and be able to integrate it's capabilities with other tools. My objective with O2 is not to invent all wheels, but to use the best possible technology to solve the problem at hand.
For example here is what I think LinqPAD does better: * it is more focused and mature * there is a better GUI to provide examples (we're trying to create a similar cook-book style for O2) * the tabbed interface for scripts allows for multiple script development in the same GUI * the GUI looks better, is more complete and shows its age (in a good way) * there are a couple more scripting options * built-in visualizers for LINQ queries * better help and support website
Finally, since the O2 Platform and its C# REPL environment are Open Source (https://github.com/o2platform), if you have some cycles we could do with some help :)

Friday, 3 August 2012

Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio)

Over the past months I have been using Rolsyn in a number of scenarios, creating in the process multiple O2 Platform tools which might be useful to new Roslyn users.

Here are the stand alone exes, all about 9Mb since they contain the Roslyn dlls and the O2 REPL Script environment as embedded resources.

The titles of these tools should give a good clue on what they do, but if you want me to expand on them (or how the script works), just add a comment to this post with your request/questions.

Note that you can run all these scripts using the latest version of the O2 Platform (just search for 'Roslyn' scripts).

If you are trying to get your head around Roslyn, the best one to try is the first one (PoC - Roslyn C# ScriptEngine Execute v1.0.exe) which is a nice REPL environment. Here is a post I wrote a while back that shows this tool in action: Video: Using O2's Roslyn-based C# REPL Script environment

Solving the problem of 'path too long error' using O2 tool

Download: Util - View O2.Platform.Scripts file length v1.0.exe
View: Script Source Code


Amazingly in 2012 windows still complains for paths bigger than 240 chars. Now that O2 can be easily installed from a single exe, there is a normal case where O2 will be started from path that is a big long (lets say more than 100 chars). This created a problem since the O2 temp dir would be created from that  path , and there were a number of scripts that (since I like to use verbose file names) would break the 240 char limit (which would make the unzip of the O2.Platform.Scripts folder to fail).

So to help me solve this, I wrote a quick tool that gives me a quick view of what files are bigger than a particular size.

Here is the tool in action before I renamed a bunch of O2 files:


As you can see there were 198 files whose path was bigger than 120.

This tool (which you can download from here or see the source code below), has a number of nice features:
  • Slider to select the depth to filter the loaded files
  • Loads files once, which gives a nice real-time fell when moving the slider
  • Allows drag n' drop of folders to load all files from it
  • Auto filters/removes files in .git directories
  • Context menu (on the file list) to open the parent folder of the selected file and to reload the files
Here is a screenshot of what the O2.Platform.Scripts folder looks like now, after a number of script renames (which took me a couple minutes to do):



Script Source Code:

Thursday, 2 August 2012

Please test: Stand-Alone version of O2 Platform and C# REPL environment

I just published a stand-alone version of the main O2 Platform GUI and its C# REPL environment, and if would be great if you took them for a test-drive before a wider release (namely the rest of the OWASP community).

You can download the O2 GUI (and its scripts) from: http://tiny.cc/O2Platform   (this is the same you would get if you installed O2 from GitHub)

You can download the C# REPL environment from http://tiny.cc/REPL  and read about it at this post: C# REPL Script Environment 

Let me know how it goes, and if have issues please use the 'Report Bug' feature from the Help menu (which will send an email to me with your logs)

Thanks

C# REPL Script Environment (new page)

I just added a new top level page to this blog with details about the C# REPL Script Environment that is the key to O2 Platform's powerful scripting capabilities. Please read it for more details

You can download the latest version from: http://tiny.cc/REPL and this is what it looks like:


repl.it great online REPL Environment

Just found http://repl.it/ and it looks really good.

They provide an online REPL for 16 of languages, and their UI feels really nice (specially the part of providing code samples)

Interestingly they don't support C#,  so maybe there is a good opportunity to use O2 to enable that :)

The source code of that website is at GitHub: https://github.com/replit

Ed on SecurityInnovation's focus on Application Security

Yeah it's Marketing but its actually quite a nice description of SI (Security Innovation) focus on Application Security.



One key concept are the 3 pillars of Secure SDL: Standards, Education and Assessment:














Here are a couple more videos on these 3 pilars (click on the each pillar to see them)

Wednesday, 1 August 2012

Good progress on VisualStudio Extension and couple more issues

Following from Adding an item to VisualStudio's Error List Window I've made quite a lot of progress on my VisualStudio Extension efforts, and have now created some really nice APIs and PoCs (if you want a sneak preview you can get it from the VisualStudioGallery: O2 Platform for VisualStudio 2010)

Here is where I'm am at the moment: 

  • My implementation is based on the Package and MEF objects (and the services I can get from there)
  • I now have a full REPL environment inside VisualStudio, so I can code VisualStudio dynamically :) (i.e when I'm working on my Extension I don't need to recompile the Extension assembly everytime I make a code change or want to try some DTE , MEF or WPF action)
  • I'm able to get an DTE object by using: packageObject.GetService(typeof(EnvDTE.DTE))  (I use a similar technique to get and ErrorListProvider, IVsUIShell, OleMenuCommandService objects)
    • In this case the packageObject implements Package and is marked with the [PackageRegistration(UseManagedResourcesOnly = true)]   attribute
  • Once I had the ErrorListProvider object (created using ErrorListProvider(packageObject) ) , I was able to add items to it 
  • To create windows I used the packageObject.CreateToolWindow(typeof(WindowPane_WPF), index++) ; 
    • The WindowPane_WPF is a class I added which implements ToolWindowPane and sets its Content to a vanila WPF grid (I also have a WindowPane_WinForms which sets the content to a System.Windows.Forms.Integration.WindowsFormsHost control
    • In order for this to work, I had to preregister them on packageObject classes with:
      • [ProvideToolWindow(typeof(WindowPane_WPF)     ,  MultiInstances = true,  Style=VsDockStyle.Linked, Orientation = ToolWindowOrientation.Top, Window=EnvDTE.Constants.vsWindowKindOutput)]
      • [ProvideToolWindow(typeof(WindowPane_WinForms), MultiInstances = true, Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.Top, Window = EnvDTE.Constants.vsWindowKindSolutionExplorer)]
  • A number of problems I had initially where caused by threading issues. My scripts run a separate thread and there where a number of cases where the request needs to be executed from the main VisualStudio thread (although I usually got weird COM errors which didn't point that way). I dealt with this problem by creating an extension method that used the Dispatcher object from System.Windows.Application.Current
  • I also had issues getting the Events I subscribed via the DTE.Events.BuildEvents callbacks, until I pinned the object DTE.Events.BuildEvents to a static variable in my class
  • I'm adding menus dinamically using dte.CommandBars["MenuBar"] (since I didn't want to hard code the menus in my extension dll)
  • I'm using the [ProvideAutoLoad(UIContextGuids80.NoSolution)]  on my packageObject to get a callback on VisualStudio load
  • I implemented a couple wrappers on some MEF exports which give me easy access to the WPF TextEditor: 
    • IWpfTextViewCreationListener (allows the manipulation of Code content and add new Adornments)
    • IWpfTextViewMarginProvider (allows adding a new margin or section to the Code provider)
Here are the issues/questions I currently have:
  • How to get a live instance of the AddIn object. I currently have a DTE object, but don't know where to get the EnvDTE.AddIn
    • This is the object that is passed as the addInInst parameter of the OnConnection method from the VsConnect : IDTExtensibility2, IDTCommandTarget  (I needed that in order to be able to correctly set the variables used by consumed add-ins
  • How to control the position of a new ToolWindowPane when created programatically.
    • If you noticed from the ProvideToolWindow attribute above, I use it to define the place where new instances of this window are created. My issue in that at the moment I don't seem to be able to set them programatically (specially the target Window GUID).
  • Faster way to add menu items. The dte.CommandBars works ok, but it still takes about a couple secs to do it (and it hangs the GUI) so, I was wondering if there was another way. I have access to the main WPF VisualStudio window, so maybe that will be faster. Note that I don't need to preregister these items as MenuCommands, I just want to get Action callback when they are clicked
  • Is the  [ProvideAutoLoad(UIContextGuids80.NoSolution)] the best way to get some code to run on VisualStudio load?

Friday, 27 July 2012

Adding an item to VisualStudio's Error List Window

I just spent a ridiculous amount of time trying to figure this out, so here is a solution for something that should be simple, I struggled to find a solution, but when I finally found the solution, it was not that bad.

Basically, what I'm trying to do is to add errors/items to the Error List in VisualStudio based on Code Analysis (either at solution or file level).

If you want to read the solution, it is here https://gist.github.com/3185313 (also included at the end of this post). This script was executed from an O2 REPL Script environment running inside VisualStudio.

The next text is from an email I wrote asking for help to a MS guru on VS Extensibility.

----start----

I was expecting this to be something like this (in pseudo C# code):

VisualStudio.Editor.OnTextChange(
      ()=>{ 
              var code = VisualStudio.Editor.GetCode();
              var errorListPane =  VisualStudio.ErrorPane;
              var issues = AnalyzeAndGetIssues(code);
              foreach(var issue in issues)
                   errorListPane.Add(issue.Text, issue.Span, issue.Severity)
          });

or even just simply:

VisualStudio.Editor.OnTextChange(
      (code)=>{ 
                  var issues = code.AnalyzeAndGetIssues();
                  VisualStudio.ErrorPane.add(issues)
              });

VisualStudio.Editor.OnCompile(
      (assemblies)=>{ 
                       var issues = assemblies.AnalyzeAndGetIssues();
                       VisualStudio.ErrorPane.add(issues)
                    });

Here is a thread about what I'm trying to do and with the same problems that I have: How to add parsing errors to ErrorList window?

Here is more information about what I have done already and what I can/can't do:

  • I have written an VS Add-in which gives me access to the DTE2 and AddIn objects inside a REPL environment on a running VisualStudio instance (think of it as a mix of Interactive Window + Roslyn REPL) 
  • I have a VSPackage/VSIX that gives me access to the Package object and MEF exports from a similar REPL environment. 
  • From the Addin I can create VisualStudio native dockable panels (with an WinForms or WPF control inside). Take a look at the video here http://diniscruz.blogspot.co.uk/2012/06/real-time-vulnerability-creation.html to see an Code Editor (from SharpDevelop) running natively in VisualStudio with a couple extra panels showing security vulnerabilities information (note that these controls are hosted natively in VisualStudio windows created using DTE's CreateToolWindow2 method) 
  • One of the problems I had was in gaining access to the live instance of the Error Panel, since in one of my tests I had the error: The service "Microsoft.VisualStudio.Shell.Interop.IVsTaskList" must be installed for this feature to work" 
  • I could try to access the actually ListView control via the WPF/WinForms GUI controls, but that would be a massive hack 
  • I was able to create a PoC that did exactly what I wanted using a variation of the Roslyn's CodeIssue example. This did exactly what I wanted since I had a callback from Roslyn that expected to receive a List of CodeIssue objects (which where then added to the VisualStudio Error List). I have looked at Roslyn code, but can't figure out its connection with the actually error list (there are too many layers of callbacks). 
  • One key objective that we have is to able to distribute our solution in one file installer. At the moment a VSIX seems like a perfect solution since it allows the easy distribution and install of VisualStudio plugins (vs the Addin model which requires the user to copy it to correct location)

----end----

Here are a number of  good resources on this topic (note: which helped find the solution):


solution

Friday, 20 July 2012

New O2 Feature to package scripts on WSDL and Notepad scripts

The latest version of O2 (all pushed to GitHub) contains a really powerful feature which is the ability to package most C# or H2 scripts as stand alone exes (i.e. 1 exe file with all dependencies)

You will find a new option on the invoke scripts popup and on the REPL editor which will fire up the 'exe creation workflow'

This means that from now on I will start publishing most O2 features and stand-alone tools, with the idea to create really powerful, useful, easy to use/deploy and focused tools.

To get you started, take a look at these 3 reddit posts:

FxCop Security rules : A nice to have feature on top of O2 platform

Check out this nice post from Michael Hidalgo on O2's blog : FxCop Security rules : A nice to have feature on top of O2 platform

And yes, I agree that we should add Fx-Cop to O2. 

So who wants to do it? This could actually be a good case study for how to add support for other tools to O2. I do this all the time, so it would be good if you guys also figured out how to do it too :)

Btw, if you want to write a blog post on the O2 Platform blog, let me know your wordpress account and I'll add you to it

Tuesday, 17 July 2012

Help in sorting out the Cat.NET's EnvDTE dependency

I've been under a rock for the past month coding away (more details later) and one of the modules I created was a stand-alone O2 Tool (one file) that exposes the Cat.NET engine outside VisualStudio.

You can get it from the latest version of O2 (GitHub) or from this DropBox download: Tool - Cat.Net outside VisualStudio v1.3.exe

You can see below how it is supposed to work, but I'm having an issue at the moment which would be great if somebody could help in.

Basically the problem is that there is an dependency on EnvDTE which only happens on certain installs.

I have been able to run this tool on VMs with and without VisualStudio installed, so there must be something else that installs EnvDTE on a box (like the one I was using at EC2).

The problem is that one of my users is not able to run the O2 scripts based on the O2's Cat.NET APIs, and we need to figure out what needs to be added (or removed) in order to make this work.

Monday, 25 June 2012

O2 Platform AppScan Standard Plugin (first version)

Using AppScan Standard SDK here is a simple Plug-in that adds O2 Platform's Log Viewer and C# REPL environment to this AppScan menu.



New page on 'Real-Time Vulnerability Feedback in VisualStudio'

If you read this blog online you will notice that there is a new page at the top called Real-Time Vulnerability Feedback in VisualStudio which consolidates the latest info and PoCs on this topic.

I think I might have hit a nerve with this PoC/Concept, since there has definitely been a spike in the traffic and interrest in the O2 Platform.

My strategy for O2 has always been to keep developing, improving and creating PoCs with what it can do. It is up to the community to pick it up and organically use it (or not).

Although this means that O2 usage and market penetration is slower, it also means that its progress is much more solid and scalable (i.e. O2 is a much better product today that it was 1 year ago)

So let's see what happens next, the PoC of providing Real Time Vulnerability Feedback inside an IDE is showing what the development environment should be like, and hopefully there will be enough momentum created by developers, clients and tool vendors to make this a reality :)

I'm doing my bit .... (... to change the way software is developed and make it more secure...)

:)

Any real-world Fortify RTA case studies out there?

One of the replies I got for my Dynamically patching ASP.NET code in real-time? (Why don't WAF vendors do it?)  post, was the question "is this something similar to HP RTA?" (see HP Fortify Real-Time Analyzer (RTA) and RTA Customization: The power of being inside the application )

The answer is Yes(ish).

RTA (which they call Real-Time Analysis), would fit into the 'In memory, on app that has been instrumented and allows dynamic function hooking' mode.

My understanding (and please correct me if I'm wrong) is that RTA works by inserting stubs in code (just like AOP) that gives you hooks into method calls.

So yes RTA will allow 'Dynamic Patches' to be created, but it requires applications to be set-up like that (which you would also get in .NET if you started the process under the Profiller).

One of the key concepts that I think should exist with the concept of 'Dynamic Patches' is that it should be a 'patch' i.e. it should be something that can be dynamically enabled and disabled.

That said, I've always been a fan of the RTA concept since it goes on the right path of allowing apps to be patched for security vulnerabilities.


So ... now that this product has been out for a while (5+ years?), are there any real-world case studies of RTA working?

Also, how much of a commercial success is RTA? Are customers actually buying it?

If there is a market, what are the competitors?

Sunday, 24 June 2012

Dynamically patching ASP.NET code in real-time? (Why don't WAF vendors do it?)

I was asked today "...Do you think it's feasible to dynamically patch code in real-time? Think agent on a host instead of a waf. Think real patches instead of virtual ones..." and my short answer is:

Yes it is! (if you looking for the technical details, skip to the middle of the post)

I have done that several times in the past, for example in Sharepoint where I wrote a PoC that applied a 'real-time' C# patch (without touching the disk) into a live/running instance of MOSS.

So if it is possible, "...why are all the WAF vendors still trying to operate on the data stream? There is so much more you could so by hooking the runtime...".

There are a number of reasons why the WAF vendors don't want to get into this world:

  1. The WAF vendors (just like the SAST ones) are still trying to ignore the Applications they are supposed to protect. By that I mean that their model is based in protecting ALL types of Apps, and not a Specific Application. Which means that they are not very good at trying to understand how an Application actually works. For example they want to ignore the need to consume:
    • an Spring/Structs configuration file 
    • an static analysis of an ASP.NET MVC application,
    • the directory listing of all Aspx pages
    • the current HttpModules mappings/behaviour
    • etc...
  2. The WAF vendors are still selling an 'infrastructure security' product vs an 'application security' product.
  3. Very few (if any) WAF vendor has an effective way for it to 'talk' with an Application and issue/receive commands (for example via an agent)
  4. Dynamically patching is hard to do and requires a lot of customisation and Unit-Testing environments (see below)
  5. The WAFs vendors don't believe that there is a market for this type of capabilities, so they are not investing on it (every time I ask them for this, I get the answer: "Its only you (Dinis) that wants this"). Of course that it is hard for a client to buy something that doesn't exists, but (just like in the SAST world) the clients are also to blame here since they should be putting pressure on the WAF vendors to do this.
Before I continue, I want to say that I am a BIG fan of WAFs and I think they provide a lot of value on the Virtual Patching world. I'm not really covering DAST+WAF on this post, but that is also a great workflow, and if you are into that world , you have to take a look at Ryan Barnett's amazing work with ModSecurity: See Dynamic DAST/WAF Integration: Realtime Virtual Patching and OWASP ModSecurity Core Rule Set Project 

Now from a client point of view, would it make sense to do Dynamic Patching and be able to fix vulnerabilities/bugs in a very selective, low touch and focused way!

Absolutely!

And the security guys, who usually have tantrums at the idea of doing dynamic patching (or WAF rules), are the ones not responsible for real-world applications with lots of moving parts, separate development teams and heavy deployment models (and even for the guys who have very nice and slick CI environments, I would argue that there are tons of cases where it will make a lot of sense to start a security fix process with a real-time patch).

I have done this before (live patching) using some pretty cool O2 Platform Foo, and what I found what that the dynamics of the 'conversation' between security guy and development team, were completely changed.

Here is the scenario, "...there is a security vulnerability in an application where it is possible to invoke from the GUI a feature inside a web control that is vulnerable to command injection..."

Without changing the code (which was not available since this was from a 3rd party component), the options were:
  • a) remove the control from the website (not acceptable solution from the business point of view)
  • b) detect the use of that control (on WAF or HttpModule) and redirect the user to a error page , since the vulnerability was in the main control's GUI, this was as good as option a) 
  • c) try to detect the code in transit and modify it - which was kinda doable, but made really hard by the sheer amount of webpage code, the dynamic nature of Javascript code used to build the control and the fact that this would need to be done on page rendering and page submission (there were a couple other factors with the HTML code created that made this really difficult).

BUT, when we added the capability to do a real-time .NET patch (where we can 'modify' any method on any class), this is what happened:
  • Suddenly, as the guy providing the advise, I started thinking about:
    • what is the 'best place in the code' to put the patch?
    • should I do input or output encoding/validation? (since its a case-by-case answer)
    • what are the side-effects of my patch?
    • how can I make the user experience as good as possible (where there are no GUI side effects)?
    • how to correctly/safely handle the cases where the dangerous functions (to be fixed) are used in a completely OK way by internal code?
  • If you look at the questions I was asking myself, I was starting to think 'as a developer' (remember that we usually just tell them what is wrong, or to use API XYZ to fix it)
  • As I wrote my patch, I found the need to have a set of unit-tests that covered the scenarios I was trying to fix. Because without them, how could I show the difference between 'This is an exploitable issue' vs 'Here is the app with the same user experience but without the exploitable scenario'
  • Once I had my Patch+UnitTests and gave them to the developers, the first thing they did was to do QA testing on the app running with the patched code (which surprised me the first time it happened, although it's pretty obvious in hindsight). 
    • Why did they do this? Well because they could! Suddenly, the security dude was basically saying "Hey here is a version of your site that 'should' behave like the previous version, but has a number of security fixes on it" . Naturally the first thing the developers wanted to do was to confirm that the app 'still behaved' like the original (non patched version)
    • And when they were happy that the proposed fixes had no side effect on the real app, they started to re-code my 'patch' in such a way that the behaviour of their new code and my 'dll injected' patch was the same (using the provided UnitTests to confirm it)


So technically speaking how can we 'dynamically patch' an ASP.NET application?

Let's say that we wanted to do what this guy asks for in this StackOverflow question: Programmatic MSIL injection 

Well, it depends where we are and how much control we have over the app's deployment:
  • In memory app, post JIT: This is the worse case scenario since the code we want to change has already been compiled/Jitted and already lives as unmanaged code:
    • Hook a debugger and automatically: breakpoint on the method, call patch, continue execution (this works quite well and unless the original app is very performance intensive, you would be surprised at its effectiveness). What is cool about this hook technique is that we can write the patch in C#
    • Hook the method via C++/Detours type injection - If the patch can be written in C++/Assembly this process is easier, if you want to write the patch in C# the process is much more complex
  • In memory app, pre JIT: If we can get our code to run before the code to fix has been Jitted (which might mean that you need to disable Native Image precompilation) you can do an In-Memory MSIL patch which:
    • is smaller than the original code: easier since you can do it via a simple memory copy (i.e. replace the original IL bytes with the 'patched' bytes)
    • is larger than the original code: harder since you will need to jump/call another method (ala detours)
  • In memory, on app that has been instrumented and allows dynamic function hooking: easy, but it's not very common to find an app set-up like this
  • In memory, on app that is running with the .NET profiler enabled: easy, but this has even worse performance implications than running with the debugger (and has the side effect that the app NEEDS to start under the profiller, where we can hook and detach a debugger into a live process)
  • Before load, without access to source code (not signed code): If you have access to the dlls you want to patch, and can modify them:
    • Use AOP like PostSharp:  This is a great way to do this since you get a LOT of plumbing provided by the the AOP framework (specially the method cross-cutting capabilities)
    • Direct MSIL patch on disk: Of which the Mono Cecil libraries are amazing
    • ILDASM decompile, patch IL,  ILASM compile: This should work, unless the original dll creator did unusual IL compilation or manipulation (like Microsoft with some of their core assemblies)
    • ILSPY decompile into C#, patch C# code,  Compile with VS: This depends a lot on the original code, and by now things tend to get quite messy
  • Before load, with access to source code  (not signed code): There are a number of options available here, of which the one I find more interesting is to use a Roslyn type refactoring to create the 'hook' functions that contain the patch (note that techniques like AOP are much easier to do with the code)
  • Before load, with signed code: Now if you want to modify an assembly which has been signed and used by other assemblies (who were compiled against the original signed assembly, not the patched one), one technique I've used in the past was to patch the CLR directly (i.e. the actually engine) to disable Strong Name Verification (it's actually a 2 byte patch: ret true; ). Note that by now (v4.0 of the .Net framework), there are probably better ways to load these 'patched' assemblies into memory that have the wrong strong name
I'm sure there other ways / techniques that could be used (like trying to do in memory Mocking and AOP), but the ones above are the ones I have used successfully :)

Note that I was using the O2 Platform when creating the PoCs described here :) (in fact there are a number of  current O2 modules and capabilities that were created during these engagements)

I will strongly advise anybody trying to do this, to use O2's REPL Scripting, or have a similar REPL environment. Since you will go crazy if you have to compile and press F5 every time you want to run your code/script/patch :)


Good books which actually focus on security code reviews (on .NET)

I was asked this question today via Twitter, so here are the books I would recommend for .NET developers looking to learn more about Application Security and do Code Reviews:

In SAST the issue is 'Trace Connection', not 'Scan Size'

One of the 'wrong problem to be solving' paradox that happens in the SAST world is the focus on making their engines able to 'scan large code bases'. It is not a coincidence that the key question I got from SAST engine guys on the Real-time Vulnerability Creation Feedback inside VisualStudio (with Greens and Reds) was 'Humm.... interresting but will is scale to large applications?' 

I actually blame the SAST clients for this, since they are the ones asking (and paying for) the wrong question:

 "How can you 'vendor xyz' scan my million lines of code application"

Instead they should be asking:

 "When you scan my code, can you connect the traces?"

'Connecting the traces' means that you are able to scan parts of the application separately and then connect them at a later stage.