Entries in Static Analysis (4)


Enumerating .NET MVC Application Endpoints with Roslyn

When performing security code reviews of .NET web applications, one of the first goals for the reviewer should be to enumerate the external facing attack surface. For ASPX based applications this is achieved by enumerating all files with an aspx or ascx extension. Additionally, the ‘web.config’ file should be parsed for any exposed HttpModules, HttpHandlers and configured web services. Over the years, more and more applications have been transitioning to .NET MVC. With this transition the process for enumerating endpoints becomes a bit trickier.

When encountering a .NET MVC web application, Controllers handle the processing of incoming requests and are tied to exposed URL endpoints in the application. To successfully enumerate an application’s web attack surface, finding all classes that inherit from Controller base classes and enumerating their public methods is required. Additionally, .NET MVC introduces Filter Attributes that can be set at a Global, Controller (class) or Action (method) level.

For example, the DataController class in the code snippet below exposes an action named Index() that returns the current time. This action is decorated with the OutputCache action filter.

Therefore, prior to executing the code within the method, the logic of the ‘OutputCache’ action attribute will be executed first. There are out of the box Filter Attributes provided by .NET, or you can create your own. The ‘HttpGet’ attribute set on the method scopes the request to accepting only ‘GET’ requests. The ‘Route’ method defines the URL endpoint a user would need to hit in order to be routed to run the ‘Index()’ method.

Snippet 1 – Controllers\DataController.cs

public class DataController : Controller
	public string Index(){
		return DateTime.Now.ToString("T");

It is very common for applications to use Filter Attributes to handle security related tasks. Some frequently observed examples of security related logic are:

  • Authentication enforcement

  • User/role based access control

  • CSRF token validation

  • Cache control headers

  • Setting of HTTP security headers

Having the ability to enumerate all exposed application endpoints and their associated Filter Attributes becomes very powerful during a manual security code review. The code reviewer will have the ability to quickly identify the application’s attack surface and identify gaps in security coverage based on the Filter Attributes assigned.


In order to perform our enumeration we used the .NET Compiler Platform (Roslyn) which provides open-source C# and Visual Basic compilers with powerful code analysis APIs. It enables building code analysis tools with the same APIs used by Visual Studio. It is a workable ‘compiler as a service’ API – that is to say that it exposes the C# compiler as an API for developers to call and work with the syntax tree. The APIs allow us to automate the enumeration process very accurately compared to simply using regex based ‘grepping’.

The Roslyn APIs are available by default within Visual Studio 2015. Alternatively, it can be installed through NuGet by installing the ‘Microsoft.CodeAnalysis’ package.

Using the APIs, we can iterate through all ‘*.cs’ files within a given directory and parse each file using the ‘CSharpSyntaxTree.ParseText’ method. This method turns the parsed file into a syntax tree that can then be analyzed.

using (var stream = File.OpenRead(path))
    var tree = CSharpSyntaxTree.ParseText(
        SourceText.From(stream), path: path);

    SyntaxNode root = tree.GetRoot();

In order to identify the classes that inherit from a Controller class, you can traverse the syntax tree and check the base type of the class.

public bool inheritsFromController(SyntaxNode root, String args) {
    bool isValid = false;
    try {
        isValid = root.DescendantNodes()
            .Equals("ApiController") || 

Retrieving the class declaration for the Controller and all of its public methods can be performed using the following code.

ClassDeclarationSyntax controller =
.First(); //Get all the public methods in this class IEnumerable<MethodDeclarationSyntax> methods = from m in root.DescendantNodes() .OfType<MethodDeclarationSyntax>() where m.Modifiers.ToString().Contains("public") select m;

Now that the Controller and its public methods are enumerated we can extract the attribute assigned at both the class and method levels. The attributes can be retrieved by reading the ‘AttributeLists’ value of the ClassDeclarationSyntax and/or MethodDeclarationSyntax objects.

Public methods with a route defined are potential entry points to the application and can be invoked through HTTP requests. Before invoking the code within the method, the request will be processed by the filter attributes defined globally, at the controller level and at the method level.

.NET MVC Enumeration Tool

We are releasing a tool that utilizes the Roslyn API to automate the enumeration of .NET MVC controller entry points. The tool runs against a given directory and identifies:

  • All classes that inherit from a Controller class

  • All public methods within Controller class

  • Attributes assigned to a method including the ones set at the class level

The basic usage of the script is as follows:

> DotNetMVCEnumerator.exe -h

Usage: DotNetMVCEnumerator.exe

[-d Directory To Scan  *Required]

[-a Attribute Name to Search]

[-n Attribute Name To Perform Negative Search]

[-o File Name to Output Results as CSV]

[-h Display Usage Help Text]

Sample Usage 1 - Scan code within a directory and write output to the ‘results.csv’ file.

> DotNetMVCEnumerator.exe -d “C:\Code” -o results.csv

Sample Usage 2 - Scan code and only include results of methods containing the ‘CSRFTokenValidate’ attribute filter. The output is written to the console and to the ‘results.csv’ file.

> DotNetMVCEnumerator.exe -d “C:\Code” -o results.csv -a CSRFTokenValidate

Sample Usage 3 - Scan code and only include results of methods missing the ‘Authorize’ filter attribute. The output is written to the console and to the ‘results.csv’ file.

> DotNetMVCEnumerator.exe -d “C:\Code” -o results.csv -n Authorize

The tool is very useful to quickly identify any methods that may be missing authorization controls enforced through filter attributes. The CSV output is very helpful during manual code reviews in order to:

  • Quickly identify test/debug or administrative functionality that is accidentally exposed based on the name of the Controller or method name or URL route path.

  • Identify classes that are missing filter attributes and therefore may be missing the enforcement of security controls.

  • Keep track of your manual code review progress by leaving comments in the spreadsheets as each external entry point is reviewed.

Excel can be used to perform column based filtering based on your needs. 

The source code and binary for the tool can be found on our Github repository:


Auditing Scala for Insecure Code with FindBugs

Here at GDS we have noticed an increase in the use of the Scala programming language by our clients. We have been looking for good tools to perform static analysis of Scala to facilitate our code audits. Although there are static analysis tools for Scala, they are not capable of identifying security issues with their out of the box rule-sets. In this blog post we cover how FindBugs can be leveraged to scan Scala for the purposes of identifying insecure code patterns.

Why FindBugs?
FindBugs is an open source static analysis tool that detects bugs in Java applications. Unlike static analysis tools PMD or Jlint, FindBugs operates on bytecode rather than source code. Because Scala classes compile to Java bytecode, this means we can run FindBugs against them! Additionally, FindBugs exposes a plugin interface making it possible to write custom bug detectors to find vulnerabilities in Scala applications. It is possible to run FindBugs without custom detectors against a Scala code base, however there will certainly be false positives and false negatives since the bug detectors are tuned against javac compiler generated bytecode. To start finding security flaws we need to write Scala specific detectors. Finally, because FindBugs is a well-known open source project already common to developer toolchains, the learning curve for extending is potentially reduced and existing development workflows do not need to be altered. It is also worth mentioning that FindBugs is integrated into the enterprise security static analysis tool Fortify SCA, and so the approach we suggest here could be a low cost alternative for these organizations. 

Implementing Your First Security Detector
We will implement a very small ‘Hello World’ detector which does nothing more than to flag every time a dangerous MongoDB function is executed. We will be writing a rule targeting Casbah, the official MongoDB driver for Scala. The Casbah library has an ‘eval’ method which can lead to the execution of arbitrary Javascript code if unvalidated user input is passed in. We will walk through how to write a rule to identify potential insecure usage of the Casbah ‘eval’ method within Scala applications.

For an introductory tutorial on how to write custom detector for FindBugs have a look at For the rest of this blog post it will be assumed that you know the basics shown in the above link.

  • Since we are operating on bytecode we will extend the BytecodeScanningDetector
  • We will override the visit method, since it is called every time new code is executed.
  • When we find the ‘eval’ method we will log a bug using the standard FindBugs logging interface.

We start with extending the BytecodeScanningDetector so Findbugs knows what code we are interested in.

public class HelloworldRule extends BytecodeScanningDetector {

Next, we declare the function we are looking for. Invokevirtual means that a new function is being invoked.
private final String VULNERABLE_METHOD = "com.mongodb.casbah.MongoDB.eval";
private final String FUNCTION_DECLARATION = "invokevirtual";
BugReporter bugReporter;

We also need to define a constructor which will take in a ‘bugreporter’ object which is used to report back found bugs to FindBugs.
public HelloworldRule(BugReporter bugReporter) {
 this.bugReporter = bugReporter;

Next we chose to implement the visit function. The documentation around this method is a bit shorthanded but the returned object “represents a chunk of Java byte code contained in a method” according to the Javadocs. Using this method allows us to analyze a function line by line.
public void visit(Code someObj) {
 ByteSequence stream = new ByteSequence(someObj.getCode());
 while (stream.available() > 0) {
   String line = Utility.codeToString(stream, someObj.getConstantPool(), true);

 We use two helper functions to identify the function call. getCommand will give us the current instruction being executed. In this example we are mainly interested in the invokevirtual instruction mentioned above. 
String command = getCommand(line);

We also use getFunction to parse out a function signature. It might look like the following:
com.mongodb.casbah.MongoClient$.apply (Ljava/lang/String;I)Lcom/mongodb/casbah/MongoClient
The signature will always start with the full package name followed by the function name. For this example, this is all we need. For more involved rules, the function arguments could also be analyzed.
String function = getFunction(line);
 if(command.equals(FUNCTION_DECLARATION) &&   
   function.startsWith(VULNERABLE_METHOD)) {

If the function matches what we are looking for we will log a bug. We state that it’s a normal priority bug and we pass in an identifier which we will define below.
    BugInstance instance = new BugInstance("MONGO_INJECTION",

protected String getCommand(String line) {
 String[] parts = line.split("\\t");
 return (parts.length > 0) ? parts[0] : "";

protected String getFunction(String line) {
 String[] parts = line.split("\\t");
 return (parts.length > 1) ? parts[1] : "";

We also need to reference our new rule so FindBugs knows where to find it. Create a new folder in the project directory and name it “etc”. Create a new file called findbugs.xml in this folder. In here we can reference the rule by adding the following text:

  <Detector class="com.package.HelloworldRule" speed="fast" />

Lastly we need to give a short description of our plugin. Create a new file called messages.xml in that same folder. Put the following content in there:

  <Detector class="com.package.HelloworldRule">
      <p> A Simple Mongo Injection Detection Rule</p>

The plugin is now ready to go, let’s give it a test!

Running FindBugs is pretty simple, all you need to do is to download the Jar and specify the source to run against. Adding new plugins is simple as well. You can either supply the plugin jar as a command line argument or you can add it to the default plugins folder for FindBugs. For this example we’ll add it on the command line:

java -jar /path-to-findbugs/findbugs.jar -textui -pluginList /path-to-your-new-jar.jar -home . -auxclasspath /path-to-scala-installation/:casbah-alldep.jar /path-to-class-files/

It is important to specify the auxclasspath option since this is how we will specify the classpath to the Scala installation. If the auxclasspath is not set, running Findbugs on Scala code will result in various errors. Additionally we add the Casbah jar to the path since it is a dependency to our sample application. Any other dependencies to the application being scanned should be added to the auxclasspath option when running FindBugs. The sample output below shows how FindBugs will report usage of the Casbah eval function within a Scala application.

M S GDS: A Simple Mongo Injection Detection Rule.       At CasbahExample.scala:[line 18]

This is just a short introduction on how to leverage FindBugs to analyze Scala code. Hopefully this code can be used as a foundation to write more involved and more complex rules. Popular web frameworks such as Play and Vert.x run in Scala and FindBugs can certainly be used to evaluate them.

The code referenced in this blog post can be found on our GitHub page:  


Building Fortify Custom Rules for Spring MVC

Looking for a Fortify rule that combines the power of structural rules with dataflow analysis capabilities? The (currently not well documented) CharacterizationRule is an awesome type of rule that will let you go beyond the restrictions of traditional dataflow analysis rules by allowing you to define dataflow parsing instructions based upon a code structural match.

Here’s an example of a rule, used against a Java Spring controller class, that will identify tainted data from parameters mapped using Spring specific annotations. This can be used to identify XSS flaws using static analysis that were only previously identified through dynamic testing.

<CharacterizationRule formatVersion="3.17" language="java">
        Function f: f.parameters contains [Variable v: v.annotations[0] matches "org.springframework.web.bind.annotation.RequestParam" ]
        TaintEntrypoint(v, {+XSS})

Used on a class similar to the following, this would essentially add the taint flag ‘XSS’ to any parameters specified with the @RequestParam mapping annotation (fully qualified class names being required) contained within the query string of the requested controller.


@RequestMapping(value = "/url")

public class PageController  {

@RequestMapping(value = "/action", method = RequestMethod.GET)

public String action(@RequestParam(value = "q", required = false) final String parameter )  {

As mentioned earlier, this type of rule is currently not fully documented but some syntax guidance is available within Fortify SCA’s structural type system documentation. You can also leverage the Fortify custom rule editor to benefit from syntax completion and XML structure validation.


Securing Development with PMD 

Back in April I presented my Securing Development with PMD (Teaching an Old Dog New Tricks) presentation at OWASP AppSec DC. The main idea was to demonstrate how security can be integrated into development without introducing new tools to existing developer toolsets. As an example, I discussed how PMD, a well-known open source static analysis tool that finds code quality issues in Java source code, can be extended with custom rules to find common application security bugs. With minimal change to existing PMD deployments and without having to learn to use another new tool, Java developers can identify and remediate both code quality and security bugs together. You can download my presentation here and the latest version of the GDS Secure Coding Ruleset for PMD can be found on our GitHub web page here. I encourage developers as well as pen-testers to use and improve the ruleset. Enjoy!