i Server side Javascript injection (ssjs) – All things in moderation

Server side Javascript injection (ssjs)

  • INTRODUCTION
    Injection flaws occur when untrusted data is sent to an interpreter as part a command or query. The attacker’s hostile data can trick the interpreter in to executing unintended commands or accessing data without proper authorization. Server side javascript injection is flaw ,when attacker can inject javascript code and execute on server.
  • SERVER SIDE JS INJECTION
    • Vulnerability
      When eval() , setTimeout() ,  setInterval(), Function() are used to process user provided inputs , it can be exploited by an attacker ot inject and execute malcious Javascript code on server.
      Example code:

      var http = require('http');
      http.createServer(function (request, response) {
        if (request.method === 'POST') {
          var data = '';
          request.addListener('data', function(chunk) { data += chunk; });
          request.addListener('end', function() {
            var bankData = eval("(" + data + ")");
            bankQuery(bankData.balance);
         });
        }
      });

      Web applications using JavaScript eval() function to parse the incoming data without any type of input valicaton are vulnerable to this attack. An attacker can inject arbitrary JavaScript code to be executed on the server. Similarly  setTimeout() , adn setInterval() functions can take code in string format as  a first argument causing ussues as eval().

      • Denial of service

        An effective denial-of-service attack can be executed simply by sending the commands below to eval()function:

        while(1)
        

        This input will cause the target server’s event loop to use 100% of its processor time and unable to process any other incoming requests until process is restarted.

        An alternative DoS attack would be to simply exit or kill the running process:

        process.exit()
        

        or

        process.kill(process.pid) 
      • File system access

        Another potential goal of an attacker might be to read the contents of files from the server. For example, following two commands list the contents of the current directory and parent directory respectively:

        res.end(require('fs').readdirSync('.').toString())
        
        res.end(require('fs').readdirSync('..').toString()) 
        

        Once file names are obtained, an attacker can issue the command below to view the actual contents of a file:

        res.end(require('fs').readFileSync(filename))

        Attacker can write write on server,  the code below , attacker prepends the string “hacked” to the start of the currently executing file
            var fs = require(‘fs’); 
            var currentFile = process.argv[1];
             fs.writeFileSync(currentFile,  ‘hacked’ + fs.readFileSync(currentFile));

        Finally,  Note that it is also possible to create arbitrary files on the target server,including binary executable files:

        require(‘fs’).writeFileSync(filename,data,’base64′);

      • Execution of Binary Files
        An attacker can further exploit this vulnerability by writing and executing harmful binary files using fs and child_process modules:

        require(‘child_process’).spawn(filename);

    • How to prevent it ?

      To prevent server-side js injection attacks:

      • Validate user inputs on server side before processing
      • Do not use eval()function to parse user inputs. Avoid using other commands with similar effect, such as setTimeOut(), setInterval(), and Function().
      • For parsing JSON input, instead of using eval(), use a safer alternative such as JSON.parse(). For type conversions use type related parseXXX()methods.
      • Include "use strict"at the beginning of a function, which enables strict mode within the enclosing function scope.
  • NOSQL INJECTION
    • Nosql injection ( using nodejs and mongodb)

      The code vulnerability :

      app.post('/', function(req, res) {
       User.findOne({user: req.body.user, pass: req.body.pass}, function (err, user) {
      
      if (err) {
      return res.render('index', {message: err.message});
      }
      // ---
      if (!user) {
       return res.render('index', {message: 'Sorry!'});
      }// ---
      return res.render('index', {message: 'Welcome back ' + user.name + '!!!'}); });
      });
      
      

      While here we are no longer dealing with query language, an attacker can still achieve the same results as SQL injection by supplying JSON input object as below:

      {
          "username": "admin",
          "password": {$gt: ""}
      }
      

      In MongoDB, $gtselects those documents where the value of the field is greater than (i.e. >) the specified value. Thus above statement compares password in database with empty string for greatness, which returns true.

      The same results can be achieved using other comparison operator such as $ne

      Example payload( this payload has url encoded)

      user%5B%24gt%5D=&pass%5B%24gt%5D=
    • Blind NoSQL injection
      It’s very instesting , you can refer to great article about it :blind nosql injection
    • How to prevent it:

      Here are some measures to prevent SQL / NoSQL injection attacks, or minimize impact if it happens:

      • Prepared Statements: For SQL calls, use prepared statements instead of building dynamic queries using string concatenation.
      • Input Validation: Validate inputs to detect malicious values. For NoSQL databases, also validate input types against expected types
      • Least Privilege: To minimize the potential damage of a successful injection attack, do not assign DBA or admin type access rights to your application accounts. Similarly minimize the privileges of the operating system account that the database process runs under
  • REFERENCES
    http://blog.websecurify.com/2014/08/hacking-nodejs-and-mongodb.html
    https://ckarande.gitbooks.io/owasp-nodegoat-tutorial/content/tutorial/a1_-_server_side_js_injection.html
    https://media.blackhat.com/bh-us-11/Sullivan/BH_US_11_Sullivan_Server_Side_WP.pdf

Leave a Reply