theProblemMaker
theProblemMaker

Reputation: 21

How to validate or Sanitize user inputs recieved from get URL in Node js

Im trying to do the checkmarx scan for my code. But I'm facing this error : This element’s value then flows through the code without being properly sanitized or validated and is eventually displayed to the user in method .then at line 145 ........ This may enable a Cross-Site-Scripting attack.

Im working with express js in which there is a method that accepts a request and response from server.

function method1(request,response){

const params = request.query; ------> this line gives a vulnerability

}

Pleasee Help me resolve this issue ASAP.Have searched for solutions but there are solns related to java or .net only.. I need solution for node/express js.

Thanks in advance

Upvotes: 2

Views: 16012

Answers (2)

Daniele
Daniele

Reputation: 892

You have to validate each param you use without accessing directly to request.query by creating and handling each variable separately.

For instance you want to check that customerId begins with a c and contactNumber is a number:

const customerId = request.query.customerId;
if (!customerId || /^c\d+/.test(customerId)) {
   return replyWrongParameters(response);
}
const contactNumber = parseInt(request.query.contactNumber);
if (isNaN(contactNumber)) {
  return replyWrongParameters(response);
}

If you want to use an external library, you may want to use https://www.npmjs.com/package/express-validation which takes care of the validation.

Upvotes: 1

yaloner
yaloner

Reputation: 758

From OWASP's Cross-site Scripting (XSS) page:

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

To learn in depth how to avoid Cross-site Scripting vulnerabilities, it is very recommended to go over OWASP's XSS (Cross Site Scripting) Prevention Cheat Sheet page.

For your specific node.js issue, you can use a dedicated sanitizer like bleach.

Good luck.

Upvotes: 0

Related Questions