0% found this document useful (0 votes)
4 views

M5 - Securing Node-based application

The document outlines essential security concepts and techniques for web applications, focusing on the top OWASP vulnerabilities, data encryption methods, and authentication practices. It discusses the importance of using HTTPS, JWT for authentication, and middleware for authorization and securing request headers. Additionally, it emphasizes best practices for securing applications, such as avoiding exposure of sensitive data and regularly auditing dependencies.

Uploaded by

chedy salhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

M5 - Securing Node-based application

The document outlines essential security concepts and techniques for web applications, focusing on the top OWASP vulnerabilities, data encryption methods, and authentication practices. It discusses the importance of using HTTPS, JWT for authentication, and middleware for authorization and securing request headers. Additionally, it emphasizes best practices for securing applications, such as avoiding exposure of sensitive data and regularly auditing dependencies.

Uploaded by

chedy salhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

M5 - Security concepts and techniques

5.1 Introduction (Security awareness)


Top 10 OWASP vulnerabilities

 Broken access control authorization


 Sensitive data exposure
 SQL/JavaScript Injection
 Identification and authentication failure
 Software and data integrity
https://owasp.org/www-project-top-ten/
Interpreted language runtime: JavaScript (accessing running server means access to the
complete running source code)
Node and NPM modules vulnerabilities
Keep an eye on security updates
https://expressjs.com/en/advanced/security-updates.html
5.2 Data Encryption
Encrypt application data
What's Encryption?
Also called encoding or hashing is the process where we encode sensitive data to prevent
attackers accessing these data if they were stored in raw or plain text format.
Using the crypto module
crypto is a built-in Node module that allows cryptographic operations or processes.

const crypto = require("crypto");

const encryptPassword = (password) => {


// Creating a unique salt for a particular user
this.salt = crypto.randomBytes(16).toString('hex');
return crypto // Hashing salt and password, 64 length and sha512 digest
.pbkdf2Sync(password, this.salt, 1000, 64, 'sha5'))
.toString('hex');
};
// Test the encryption function
console.log(encryptPassword("abc"))

Using bcrypt module


bcrypt is a 3rd-party Node module that allows encryption, encoding and decoding.

 const bcrypt = require("bcrypt");

 const encryptPassword = (password) => {


 // Creating a unique salt for a particular user
 this.salt = crypto.randomBytes(16).toString('hex');
 return bcrypt // Hashing salt and password, 64 length and sha512
digest
 .hash(password, this.salt, 1000, 64, 'sha5'))
 .toString('hex');
 };

 // Test the encryption function


 console.log(encryptPassword("abc"))

 Encryption in transit
 HTTPS: Hypertext Transfer Protocol Secure is an extension of the Hypertext Transfer
Protocol. It uses encryption for secure communication over a computer network and is
widely used on the Internet. In HTTPS, the communication protocol is encrypted using
Transport Layer Security TLS or, formerly, Secure Sockets Layer (SSL)
 If your app deals with or transmits sensitive data, use TLS to secure the connection and
the data. This technology encrypts data before it is sent from the client to the server,
thus preventing some common (and easy) hacks
SSL CERTIFICATE
You require an SSL certificate and an SSL key to do it. We created a self-signed SSL certificate
and added it to the Trusted Root Certificate Authorities Store.
Generate your own: using openssl, rsa command line tools in Unix-like platform

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout
./demo.key -out demo.crt

For Windows environments, use Putty, which comes with PuttyGen; a GUI for creating keys and
certificates.
It's also possible to create your own self-signed certificate using openssl CLI.

# create a key (tutorial. key)


$ openssl genrsa -out demo.key 2048
# Create a Certificate Signing Request (CSR).
# Fill in the required details.
# Make sure that the common name is localhost.
$ openssl req -new -key demo.key -out demo.csr

# create a self-signed certificate (demo.crt)


$ openssl x509 -in demo.csr -out demo.crt -req -signkey demo.key -days 365

Another way to get a ready certificate from a public service provider such as : Let's encrypt.

Configure server to use HTTPS

const fs = require("fs");
const https = require("https");
const express = require("express");

const app = express();

// Load key and certificate


let key = fs.readFileSync(__dirname + '/
let cert = fs.readFileSync(__dirname + '

// Prepare server creation parameters


const parameters = { key: key, cert: cer

// Maps incoming HTTPS GET at /api


app.get( "/api", (req, res) => {
res.send("Communication through HTTP
});

let server = https.createServer(paramete

server.listen(8443)

Here is how you web server should


send as certificate

5.3 Authentication middleware


Identifying request's user identity,
who the user is, prevent
anonymous access
Authentication techniques
 Basic (Deprecated)
 Cookie, Session
 Token bearer: JWT
 OpenID Connect: 3rd-party provider, also known formerly as OAuth 2.0
 MFA: Multi-Factor Authentication
 OTP: One-Time Password
 SSO: Single Sign-On
JsonWebToken (JWT) authentication
JWT or Json web-token, is a token-based authentication mechanism almost used for stateless
software applications. each issued JWT has an encoded JSON payload, expiration datetime, ...

Writing authentication middleware

const express = require("express");

const app = express();

// Implenting Authentication middleware


const isAuthenticated = (req, res, next) = {
// Retrieve token from request headers
let token = req.params.authorization;
// if not valid token return 401: UNAUTHORIZED
// (else?) call the next middleware
next();
}

// Use the authentication middleware for all requests


app.use(isAuthenticated);

// Use the authentication middleware for a specific route


app.post( "/api/v1/posts" , isAuthenticated, (req, res) => {
// isAuthenticated will be executed before
// Once isAuthenticated call next() call-back
});

app.listen(3000)

5.4 Adding Authorization


Verifying whenever request's client is allowed or permitted to access some data or perform
certain actions,
Writing authorization middleware

const express = require("express");

const app = express();

// Implementing authorization middleware


const isAdmin = (req, res, next) = {
// Retrieve token from request headers
let token = req.params.authorization;
// if not valid token return 401: UNAUTHORIZED
// decode token, get user id, find user by id
// if user.role is not admin return 403: FORBIDDEN
// (else?) call next middleware
next();
}

// Use the authorization middleware for a specific route


app.delete( "/api/v1/users" , isAdmin, (req, res) => {
// isAdmin will be executed before
// Once isAdmin call next() call-back
});

app.listen(3000)

Application
Role-based authentication policy
Try to implement a hasRole(string role) middleware that checks if the request user has the in
args given role.
5.5 Securing request headers
CORS: Cross-Origin Resource Sharing

const express = require("express");


const cors = require("cors");

const app = express();

// use cors middleware


app.use(cors("*");

app.listen(3000)

Application:
Create your CORS middleware
Create a middleware that sets cors policy for your API, and use it for all requests.
Push your work to npm once you've got satisfied by your implementation.
Use Helmet: Helmet can help protect your app from some well-known web vulnerabilities by
setting HTTP headers appropriately. It's a collection of several smaller middleware functions
that set security-related HTTP response headers. Some examples include

const express = require("express");


import helmet from "helmet" ;

const app = express();

// override default helmet settings


app.use(helmet({
contentSecurityPolicy: false
}));

// use helmet default middleware


app.use(helmet());
/* Default headers settings
Cross-Origin-Resource-Policy: same-origin
https: 'unsafe-inline';upgrade-insecure-requests
Content-Security-Policy: default-src 'self';base-uri 'self'...
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 0

*/

app.listen(3000)
Other known vulnerabilities
XSS: Cross-site scripting (JavaScript injection) where attackers try to send a malicious
JavaScript code and try to execute it on your running server.
CSRF: Cross-site Request Forgery
Cross-Site Request Forgery (CSRF) is an attack that forces a user to execute unwanted actions
on a web application in which they’re currently logged in.

5.6 Securing practices & concerns


Here are some security rules to follow and regularly check
Never trust end-user (or client) requests
Never share or expose sensitive data
Encryption everywhere in-store and in-transit (transport layer)
Least of privilege rule
Defend against SQL injection attacks by using parameterized queries or prepared statements.
Use the open source sqlmap tool to detect SQL injection vulnerabilities in your app.
Do not expose secrets and keys
Use the nmap and sslyze tools to test the configuration of your SSL ciphers, keys, and
renegotiation as well as the validity of your certificate.
Malicious 3rd-party modules awareness, regularly audit your project node modules.
Do not return reference to modules like fs, process, module, ...
Do not eval(string) prevent penetrated or reverse engineered.

Explore more related topics


 npm audit
 OWASP annual reports
 Deno vs. Node
 msal-node from Microsoft
W6 - Securing Node APIs with JWT
Back to the W5 API project.
Your mission is to secure the API against common security issues and known vulnerabilities
already covered in this module.
1. First, add password encryption before saving the user's objects to the database.
2. Then, add an auth module with two methods or functions generateToken(user) and
verifyToken(token) that generate and validate a JWT for a given user identity which will be used
later by the auth router.
3. Add an auth router that should map HTTP Post requests at /api/v1/auth, which accept
credentials (username, and password) and return a token in case of valid credentials, and a 400
Bad Request response if not.
4. Add an authentication middleware, and use it for securing all your application endpoints.
5. Implement access control by setting up an authorization mechanism using a hasRole(role)
middleware or function.

You might also like