angular js security

43
Testing AngularJS Security José Manuel Ortega @jmortegac

Upload: jose-manuel-ortega-candel

Post on 22-Jan-2018

285 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Angular js security

Testing

AngularJS

SecurityJosé Manuel Ortega

@jmortegac

Page 2: Angular js security

iNDEX

• Authenticate users API

• Securing Admin pages

• CSRF,XSS Prevention

• Sanitize Module

• Security Audit Tools

• OWASP

Page 3: Angular js security

Authenticate users API

POST /register

POST /login

POST /logout

GET /status # returns 401 or the authenticated user

Page 4: Angular js security

Login controller

Page 5: Angular js security

Session service

Represent the user’s session

Page 6: Angular js security

Session service

Page 7: Angular js security

Session management global config

$rootScope.$on('Auth:Required', function() {

$location.path('/login');

});

$rootScope.$on('Auth:Login', function() {

$location.path('/');

});

$rootScope.$on('Auth:Logout', function() {

StorageService.clear(); // clear user info

$rootScope.$broadcast('Auth:Required');});

Page 8: Angular js security

Authentication Interceptor config

factory('AuthInterceptor', ['$q', '$rootScope', function($q, $rootScope) {

return {

'responseError': function(rejection) {

if (rejection.status === 401) {

$rootScope.$broadcast('Auth:Required');

}

return $q.reject(rejection);

}

}

}])

Page 9: Angular js security

Authentication controller

Page 10: Angular js security

Auth Service

Page 11: Angular js security

Securing admin pages

.service("AuthService", function() {

var data = {};

data.checkAuth = function() {return true;}

return data;

})

.when("/admin", {

templateUrl: “admin.html",

controller: “adminController",

resolve: {

checkAuth: function(AuthService){

return AuthService.checkAuth();

}

}

})

Page 12: Angular js security

Securing admin pages

controller(“adminController", function ($scope, checkAuth) {

$scope.isAuthenticated = checkAuth;

});

Page 13: Angular js security

Browser risks

• Cross Site Scripting(XSS)

• Cross-Site Request Forgery(CSRF)

Page 14: Angular js security

CSRF Prevention

• XSRF token

• Inject in HTTP Forms

• Protected from Cross-Site Request Forgery attack

• XSRF-TOKEN → HTTP HEADER X-XSRF-TOKEN

• Set a domain cookie in the request

• Validate the header with the content the cookie

• Used for authorize requests from the user

Page 15: Angular js security

CSRF Prevention

Page 16: Angular js security

XSRF Token

Page 17: Angular js security

XSRF Token

• When using $http ,Angular automatically look for

a cookie called XSRF-TOKEN

• If this cookie is found,when make a request add

this information in the request-header

• This header is sent to the server,at the token can

be validated

• The API can verify that the token is correct for the

current user

• Server sends success or failure

Page 18: Angular js security

Module CSURF

app.js

var csrf = require("csurf"); //require package

app.use(csrf()); //initialize

//middleware for every http request

app.use(function(req, res, next) {

res.cookie("XSRF-TOKEN", req.csrfToken());

next();});

Page 19: Angular js security

CSRF Interceptor

'responseError': function(rejection) {

var statusCode = rejection.status;

var config = rejection.config;

// Check if XSRF token is invalid

if (statusCode === 403 && rejection.data === 'XsrfToken.Invalid') {

// Handle invalid token

}

return $q.reject(rejection);

}

}

Http Interceptor - Handle invalid token responses

Page 20: Angular js security

CSRF Interceptor

var deferred = $q.defer();

var req = {config: config, deferred: deferred}

if (angular.isUndefined($rootScope.pendingRequests)) {

$rootScope.pendingRequests = [];

}

$rootScope.pendingRequests.push(req);

// Raise an event

$rootScope.$broadcast('XsrfToken:Invalid');

return deferred.promise;

Store the original request and the promise

Page 21: Angular js security

CSRF Interceptor

$rootScope.$on('XsrfToken:Invalid', function() {

Security.status().then(function() {

$rootScope.$broadcast('XsrfToken:Valid');

});

});

Store the original request and the promise

Page 22: Angular js security

CSRF Interceptor

$rootScope.$on('XsrfToken:Valid', function() {

var i, requests = $rootScope.pendingRequests ?

$rootScope.pendingRequests : [];

for (i = 0; i < requests.length; i++) {

retry(requests.pop());

}

function retry(req) {

$http(req.config).then(function(response) {

req.deferred.resolve(response);

});

}

});

Resume the pending requests

Page 23: Angular js security

XSS Protection

For XSS protection, AngularJS uses Strict Contextual Escaping (SCE). We

need to include $sce service to the code. SCE defines a trust in different

context.

Since 1.3, the HTML compiler will escape all {{}} & ngbind by

default

https://www.ng-book.com/p/Security

http://java.dzone.com/articles/angularjs-how-handle-xss

Page 24: Angular js security

Sanitize

• The ngSanitize module provides functionality to sanitize

HTML.

• Avoid Cross Site Scripting(XSS) attacks

• Requires angular-sanitize.js

• Provides ng-bind-html directive for sanitize HTML filtering

the javascript code

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-

sanitize.js"></script>

Page 25: Angular js security

ngSanitize && SCE

• The input is sanitized by parsing the HTML into tokens.

• All safe tokens are then serialized back to properly

escaped html string

• SCE(Strict Contextual Escaping) is a mode in wich

AngularJS requires binding in certain contexts to result

in a value that is marked as safe to use for that context.

Page 26: Angular js security

Strict Contextual Escaping Service

Page 27: Angular js security

Strict Contextual Escaping Service

var data ='<b onmouseover="alert(\'over\')">trust

me</b>:<script>alert("XSS");</script> <xss>XSS</xss>';

$scope.untrusted = data;

$scope.sanitized = $sanitize(data);

$scope.trusted = $sce.trustAsHtml(data);

{{ untrusted }}

<span ng-bind-html="sanitized"></span>

<span ng-bind-html="trusted"></span>

Page 28: Angular js security

ng-bind-html .vs. ng-bind

<div ng-bind-html="to_trusted(msg)">

</div>

• ng-bind-htmlAutomatically uses $sanitize

• <p ng-bind="msg"></p> Hello, <b>World</b>!

• <p ng-bind-html="msg"></p> Hello, World!

Page 29: Angular js security

Retire.js

• Detecting components and JavaScript libraries with

known vulnerabilities

• https://raw.githubusercontent.com/RetireJS/retire.js/m

aster/repository/jsrepository.json

• Retire.js has these parts:• A command line scanner

• A grunt plugin

• A Chrome plugin

• A Firefox plugin

• Burp and OWASP Zap plugin

Page 30: Angular js security

Build a secure HTTPS Server

var https = require('https');

var privateKey =

fs.readFileSync('cert/privatekey.pem').toString();

var certificate =

fs.readFileSync('cert/certificate.pem').toString();

var credentials = {key: privateKey, cert: certificate};

var secureServer = https.createServer(credentials, app);

secureServer.listen(config.server.securePort); //443

Page 31: Angular js security

Build a secure HTTPS Server

https-redirect-server

https://www.npmjs.com/package/https-redirect-server

A node module to redirect all traffic to https and a

secure port.

Page 32: Angular js security

Security Audit Tools

Page 33: Angular js security

Securing Headers

Page 34: Angular js security

Security Audit Tools

Page 35: Angular js security

Security Audit Tools

Page 36: Angular js security

Security Audit Tools

Page 37: Angular js security

JWT

• JSON Web Token

• Avoid CSRF and XSS

• angular-jwt

Page 38: Angular js security

JWT

• Store the token from service response

• Sending the token at each request with interceptor

$http(...).then(function(response) {

currentToken.jwt =response.data.access_token;

}

angular.module('myApp')

.config(function ($httpProvider,jwtInterceptorProvider) {

jwtInterceptorProvider.tokenGetter=['currentToken',function(current

Token) {return currentToken.jwt;}];

$httpProvider.interceptors.push('jwtInterceptor');

});

Page 39: Angular js security

OWASP

• Open Web Application Security Project

• Online community dedicated to web application security

• Identify Vulnerabilities

• Document Best Practices

• Repository with use cases

• https://github.com/hakanson/ng-owasp

Page 40: Angular js security

Recommendations

• Access control input validation and security decisions

must be made on the server.

• Handle untrusted data with care

• Use contextual encoding and avoid building code from

strings.

• Protect your services

• Learn how to use security HTTP headers

Page 41: Angular js security

Conclusions

• Angular is a purely client side framework

• There are risks in the client that are discret to the

network and server

• The client and the network are not in your control!

• Protect the server!

Page 42: Angular js security

Links & References

https://docs.angularjs.org/api/ng/service/$sce

https://docs.angularjs.org/guide/security

https://docs.angularjs.org/api/ngSanitize

https://code.google.com/p/mustache-security/wiki/AngularJS.wiki

https://www.ng-book.com/p/Security

https://github.com/fnakstad/angular-client-side-auth

https://github.com/auth0/angular-jwt

http://retirejs.github.io/retire.js

https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project

Page 43: Angular js security

Youtube videos

Security in the world of JS frameworks

https://www.youtube.com/watch?v=4Qs5mqa4ioU

Top 10 Security Risks for AngularJS Applications

https://www.youtube.com/watch?v=6uloYE87pkk

JS Security - A Pentesters Perspective

https://www.youtube.com/watch?v=LVamMYljS4Q