Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to object properties pollution and disrupt the normal behavior of the application. How can this code be fixed?

var QueryString = function () {
// An anonymous function that is executed immediately and 
// the return value is assigned to QueryString!
var query_string = {};

const allowed = new Set([
    'rqid',
    'rowId',
    'sid',
    'RequestId',
    'RequestTypeID',
    'mode',
    'id',
    'requestIdList',
]);

var query = DOMPurify.sanitize(window.location.search.substring(1));
var vars = query.split("&");

for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");

    // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
        if (allowed.has(pair[0])) {
            query_string[pair[0]] = decodeURIComponent(pair[1]);
        }
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
        if (allowed.has(pair[0])) {
            var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
            query_string[pair[0]] = arr;
        }
        // If third or later entry with this name
    } else {
        if (allowed.has(pair[0])) {
            query_string[pair[0]].push(decodeURIComponent(pair[1]));

        }
    }
}

return query_string;

}();

Answer №1

I achieved success, here is the updated version of my code:

var QueryString = function () {
// This function is anonymous, runs immediately and 
// assigns the return value to QueryString variable!
var query_string_help = {};
var query_string = new Map();

const allowed = new Set([
    'rqid',
    'rowId',
    'sid',
    'RequestId',
    'RequestTypeID',
    'mode',
    'id',
    'requestIdList',
]);

var query = DOMPurify.sanitize(window.location.search.substring(1));
var vars = query.split("&");

for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");


    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1] || '');

    // If it's the first entry with this name
    if (!query_string.has(key)) {
        if (allowed.has(key)) {
            query_string.set(key, value);
        }
    } else {
        // If it's the second or later entry with this name
        if (allowed.has(key)) {
            var existingValue = query_string.get(key);
            if (Array.isArray(existingValue)) {
                existingValue.push(value);
                query_string.set(key, existingValue);
            } else {
                query_string.set(key, [existingValue, value]);
            }
        }
    }

}

query_string_help = Object.fromEntries(query_string)

return query_string_help;
}();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I create a JSON string that exactly matches the data source needed for a pie chart? Any tips

received JSON string: "{Date:'15/05/2015',y:'6'}, {Date:'01/08/2015',y:'6'}, {Date:'02/08/2015',y:'6'}, {Date:'08/08/2015',y:'72'}, {Date:'09/08/2015',y:&apo ...

Revive the design of a website

As I work on creating my own homepage, I came across someone else's page that I really liked. I decided to download the page source and open it locally in my browser. However, I noticed that while the contents were all there, the style (frames, positi ...

effective method for iterating through JSON data using JavaScript or jQuery

Upon receiving a JSON object from the server, it looks like this: { "0": { "id": "1252380", "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?", ...

Enhance user interactivity on your website by incorporating jQuery and CSS for

<table id="tab"> <tr aaa="one" bbb="ooo"><td>xxx</td><</tr> <tr aaa="two" bbb="one"><td>xxx</td><</tr> <tr aaa="three" bbb="one"><td>xxx</td><</tr> ...

Leveraging multer for handling a FormData object in a node.js server

Having trouble with an HTML form that includes two buttons among other text input areas. The front-end javascript code is set up to handle the submit action by creating a FormData object to store the file and sending it via a jQuery AJAX request to a node. ...

Using JQuery's onChange event triggers actions based on the current values of input fields. However, in some

I am currently tackling an issue with a module that is designed to automatically select the only valid value from a Multi- or Single selection field when there is just one valid option and an empty choice available. Initially, everything was working smoot ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Ensure that all MongoDB write operations have been completed before proceeding with a find operation

I am in need of a store js object that can manage a mongodb collection in a specific way: store.insert(thing); // triggered from a pubsub system without waiting for the insert to complete store.get(); // should return a promise that resolves to the items ...

Search for the next input using jQuery, then trigger a select event on keypress excluding any buttons

Is there a way to modify my code so that when the user presses "enter", it selects the next visible input or select element, without including buttons in this selection? $(document).on('keypress', 'input, select', function (e) { if (e. ...

Automatically navigate to a different page using JavaScript after 5 seconds without interrupting the execution of other code

Is there a way to redirect to a specific URL after 5 seconds without halting the execution of other code on the page? I want all the other code to run first before triggering the redirection. Wrapping the entire page in a setTimeout block is not an option. ...

"Learn how to transfer a selected value from a parent ASP.NET dropdownlist to a textbox in a popup window using JavaScript

I'm struggling to pass the value from a dropdown list in the parent ASPX form to a textbox in the child ASPX form. Parent JavaScript: The first script is used to open the popup window <script type="text/javascript"> var popup; ...

How to hide an image in the React carousel display

I am having an issue with my Carousel, specifically with the image not being displayed even though I have set up the data in a const called items. Here is how my const looks: var items = [ { url:'../../assets/img/hors1.jpg', ...

Looking for answers to a question about Handlebars in Node.js? Click on the following link to explore more

After successfully parsing my Shopify product items into a MongoDB database using a model, I am attempting to display them to the user using the express-handlebars package. However, I've encountered a small issue. I'm utilizing <td><a ...

What are the reasons behind my item not triggering an alert even after I have created it, saved it, and attempted to alert it?

I am currently working on a code that allows users to input information which is then stored in an object. However, despite my efforts, when I attempt to retrieve the saved object by alerting one of its values, it indicates that the object does not exist. ...

Ways to compare two arrays based on a specific field using JavaScript

I have two arrays, known as array 'a' and array 'b'. var a = [ [1,'jake','abc',0 ], ['r', 'jenny','dbf',0] , ['r', 'white','dbf',0] ] var b = [ ['s&ap ...