Lab Exercise deserialization

This is a lab exercise on developing secure software. For more information, see the introduction to the labs.

Task

Please change the code below to prevent insecure deserialization vulnerability.

Background

Insecure Deserialization happens when the application’s deserialization process is exploited, allowing an attacker to manipulate the serialized data and pass harmful data into the application code.

The safest way to prevent this vulnerability is to not accept serialized objects from untrusted sources (user-controllable data). However, if you must accept them, there are some mitigations you can implement. In this lab, we will apply a couple of them.

Task Information

The code below is called after an application login page. After login, a cookie is set up with the user profile, then in the homepage the cookie is deserialized and uses the username in a greeting message.

If you take a closer look at this code, you’ll see that it’s using eval() to deserialize the data from the cookie. This can be very dangerous as eval() evaluates a string as JavaScript code, which means any code inside that string will be executed, opening the possibility of Remote Code Execution (RCE) and Code Injection attacks.

For this lab we want to fix this by using an approach that prevents executing code from the attacker. We will also add some simple input validation to make sure the data we receive from inside the JSON data is what we are expecting.

  1. Replace eval() with JSON.parse(). JSON.parse( ) does not execute any JavaScript code like functions or methods, making it a much more secure approach for deserialization.
  2. Besides checking if data.username exists, perform simple validations of its value. Ensure it is a string (typeof data.username == 'string') and that it's less than 20 characters long (data.username.length < 20).

Use the “hint” and “give up” buttons if necessary.

Interactive Lab ()

Change the code below, adding the mitigation steps to prevent Insecure Deserialization:

  1. Use a deserialization approach that prevents code execution of untrusted code.
  2. Validate the username making sure a reply is only sent if it's a string and less than 20 characters.
const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();

app.use(express.json());
app.use(cookieParser());

app.get('/', (req, res) => {
  if (req.cookies.profile) {
    try {
      const base64Decoded = Buffer.from(
        req.cookies.profile, 'base64').toString('utf8');
      

      
            // To prevent XSS, avoid res.send with untrusted data
            res.render('index', {username: data.username});
      }

    } catch (err) {
      res.send('An error occurred.');
    }
  } else {
    res.send("Please Login");
  }
});


This lab was developed by Camila Vilarinho.