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

Linking states using AngularJS and jQuery

Imagine I have a scenario with two different states: .state('page1', { url: '/page1', templateUrl: 'pages/templates/page1.html', controller: 'page1' }) .state('page2', { url: '/page2& ...

Have you ever wondered how to disable a tooltip in React Material UI after clicking on it? Let

I am working with a Material-UI tab component and I would like to include a tooltip feature. The issue I am facing is that the tooltip does not disappear when I click on the tab. It should hide after clicking on the tab. Currently, the tooltip remains vi ...

Express req.files returns null when using jQuery FormData

For client side functionality, I am utilizing Bootstrap and jQuery. On the server side, my technology stack includes node.js and express. The form structure is displayed below: <form id="signupform" action=""> <h2&g ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Tutorial on creating a subset of a series using jqplot

I am looking to display three series on the same canvas. The series are defined as follows: rec1 = [0, 0, 150, 200, 0 ]; rec2 = [60, 120, 179, 240, 300]; rec3 = [50, 100, 150, 200, 250]; Below are the source codes I am using to draw these series. $ ...

How can I remove the focus highlight from the MUI DatePicker while retaining it for the TextField?

I am currently working on developing a date picker using react.js with the MUI DatePicker library. The code I have implemented closely resembles what is provided in their documentation. However, upon rendering the component, I am encountering an issue whe ...

"Adding dots" in a slideshow using HTML, CSS, and JS

I'm currently working on a slideshow that includes navigation dots at the bottom. Although the slideshow is functioning properly, I am encountering an issue where only one dot appears instead of the intended three in a row. Despite my research and att ...

Sending KeyValuePair or IDictionary as payload to Web Api Controller using JavaScript

In my web api controller, I am trying to post two parameters: a flat int ID and an IDictionary (or similar equivalent). [HttpPost] public void DoStuff(int id, [FromBody]IDictionary<int, int> things) { } var things = new Array(); things.push({ 1: 10 ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

What is the process of manually loading webpack async chunks in the event that a dynamic import fails to load the file?

Async chunks in webpack can be created by using Dynamic Imports (for example: import('./ModuleA.js');). If the dynamic chunks fail to load, I want to retry loading them from another location. After grappling with the issue and delving into babel ...

When the user clicks on an element, my JavaScript code dynamically updates the CSS property by changing the window

When a tag is clicked in HTML triggering an onclick event, the CSS property that was updated in the JavaScript does not persist. The changes appear momentarily and then disappear once the window is refreshed. Javascript: <script type="text/javascript"& ...

Is there a simple method to automatically increase the version number of Mongoose documents with each update request?

I'm eager to utilize Mongooses document versioning feature with the "__v" key. Initially, I struggled with incrementing the version value until I learned that adding this.increment() when executing a query is necessary. Is there a method to have this ...

Uncovering the xpath of an element within an iframe using QTP

When attempting to set a value in the <input type="file" name="file007"> element using QTP, I encountered an issue. The element is located within an iframe, making it inaccessible through xpath on the page. <iframe id="file_007" src="javascript:& ...

Sending an asynchronous post request to a controller in Umbraco and receiving JSON data in response

I am currently in the process of integrating my existing MVC project into Umbraco. In my original project, I have asynchronous ajax calls to my controllers using jQuery. When implementing this functionality in Umbraco with a SurfaceController, the code wou ...

What steps are necessary to configure karma webdriver launcher to utilize my selenium server or grid?

Could someone assist in identifying what is causing the Karma javascript test runner to have issues connecting to and utilizing my selenium grid/server? I currently have a functioning selenium grid setup that I utilize with python selenium bindings for co ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...