SlideShare una empresa de Scribd logo
1 de 43
Testing
AngularJS
Security
José Manuel Ortega
@jmortegac
iNDEX
• Authenticate users API
• Securing Admin pages
• CSRF,XSS Prevention
• Sanitize Module
• Security Audit Tools
• OWASP
Authenticate users API
POST /register
POST /login
POST /logout
GET /status # returns 401 or the authenticated user
Login controller
Session service
Represent the user’s session
Session service
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');
});
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);
}
}
}])
Authentication controller
Auth Service
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();
}
}
})
Securing admin pages
controller(“adminController", function ($scope, checkAuth) {
$scope.isAuthenticated = checkAuth;
});
Browser risks
• Cross Site Scripting(XSS)
• Cross-Site Request Forgery(CSRF)
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
CSRF Prevention
XSRF Token
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
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();});
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
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
CSRF Interceptor
$rootScope.$on('XsrfToken:Invalid', function() {
Security.status().then(function() {
$rootScope.$broadcast('XsrfToken:Valid');
});
});
Store the original request and the promise
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
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
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>
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.
Strict Contextual Escaping Service
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>
ng-bind-html .vs. ng-bind
<div ng-bind-html="to_trusted(msg)">
</div>
• ng-bind-htmlAutomatically uses $sanitize
• <p ng-bind="msg"></p> Hello, <b>World</b>!
• <p ng-bind-html="msg"></p> Hello, World!
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
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
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.
Security Audit Tools
Securing Headers
Security Audit Tools
Security Audit Tools
Security Audit Tools
JWT
• JSON Web Token
• Avoid CSRF and XSS
• angular-jwt
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');
});
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
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
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!
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
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

Más contenido relacionado

La actualidad más candente

HTTP For the Good or the Bad
HTTP For the Good or the BadHTTP For the Good or the Bad
HTTP For the Good or the BadXavier Mertens
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Zend by Rogue Wave Software
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesSpin Lai
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Ivan Piskunov
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptDenis Kolegov
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeAndrea Cardinale
 
End to end web security
End to end web securityEnd to end web security
End to end web securityGeorge Boobyer
 
HTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC EditionHTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC EditionXavier Mertens
 
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ..."Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...PROIDEA
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & moreMattias Geniar
 
Threat stack aws
Threat stack awsThreat stack aws
Threat stack awsJen Andre
 
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
[OPD 2019] Side-Channels on the Web:
Attacks and DefensesOWASP
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stackBram Vogelaar
 
What should a hacker know about WebDav?
What should a hacker know about WebDav?What should a hacker know about WebDav?
What should a hacker know about WebDav?Mikhail Egorov
 
Mitigating CSRF with two lines of codes
Mitigating CSRF with two lines of codesMitigating CSRF with two lines of codes
Mitigating CSRF with two lines of codesMinhaz A V
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in VaultGlynnForrest
 
Practical django secuirty
Practical django secuirtyPractical django secuirty
Practical django secuirtyAndy Dai
 

La actualidad más candente (20)

HTTP For the Good or the Bad
HTTP For the Good or the BadHTTP For the Good or the Bad
HTTP For the Good or the Bad
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
 
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018) Speed up web APIs with Expressive and Swoole (PHP Day 2018)
Speed up web APIs with Expressive and Swoole (PHP Day 2018)
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best Practices
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
 
Waf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScriptWaf.js: How to Protect Web Applications using JavaScript
Waf.js: How to Protect Web Applications using JavaScript
 
Logstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtimeLogstash for SEO: come monitorare i Log del Web Server in realtime
Logstash for SEO: come monitorare i Log del Web Server in realtime
 
End to end web security
End to end web securityEnd to end web security
End to end web security
 
HTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC EditionHTTP For the Good or the Bad - FSEC Edition
HTTP For the Good or the Bad - FSEC Edition
 
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ..."Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
"Revenge of The Script Kiddies: Current Day Uses of Automated Scripts by Top ...
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & more
 
Threat stack aws
Threat stack awsThreat stack aws
Threat stack aws
 
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
[OPD 2019] Side-Channels on the Web:
Attacks and Defenses
 
Bootstrapping multidc observability stack
Bootstrapping multidc observability stackBootstrapping multidc observability stack
Bootstrapping multidc observability stack
 
What should a hacker know about WebDav?
What should a hacker know about WebDav?What should a hacker know about WebDav?
What should a hacker know about WebDav?
 
Mitigating CSRF with two lines of codes
Mitigating CSRF with two lines of codesMitigating CSRF with two lines of codes
Mitigating CSRF with two lines of codes
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
Practical django secuirty
Practical django secuirtyPractical django secuirty
Practical django secuirty
 

Similar a Angular js security

Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Nordic APIs
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the frameworkGOG.com dev team
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server Masahiro Nagano
 
Make WordPress realtime.
Make WordPress realtime.Make WordPress realtime.
Make WordPress realtime.Josh Hillier
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012D
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-TrendsPayPal
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaJon Moore
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Paco de la Cruz
 
Secure PHP Coding - Part 2
Secure PHP Coding - Part 2Secure PHP Coding - Part 2
Secure PHP Coding - Part 2Vinoth Kumar
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experiencedrajkamaltibacademy
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggStreamNative
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
 

Similar a Angular js security (20)

Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Symfony without the framework
Symfony without the frameworkSymfony without the framework
Symfony without the framework
 
Frontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and How
 
How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server How to build a High Performance PSGI/Plack Server
How to build a High Performance PSGI/Plack Server
 
Make WordPress realtime.
Make WordPress realtime.Make WordPress realtime.
Make WordPress realtime.
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-Trends
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Roll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and LuaRoll Your Own API Management Platform with nginx and Lua
Roll Your Own API Management Platform with nginx and Lua
 
Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)Azure Durable Functions (2019-04-27)
Azure Durable Functions (2019-04-27)
 
Secure PHP Coding - Part 2
Secure PHP Coding - Part 2Secure PHP Coding - Part 2
Secure PHP Coding - Part 2
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris Kellogg
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 

Más de Jose Manuel Ortega Candel

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfJose Manuel Ortega Candel
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfJose Manuel Ortega Candel
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfJose Manuel Ortega Candel
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfJose Manuel Ortega Candel
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudJose Manuel Ortega Candel
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Jose Manuel Ortega Candel
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Jose Manuel Ortega Candel
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sJose Manuel Ortega Candel
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Jose Manuel Ortega Candel
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanJose Manuel Ortega Candel
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamJose Manuel Ortega Candel
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsJose Manuel Ortega Candel
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorJose Manuel Ortega Candel
 

Más de Jose Manuel Ortega Candel (20)

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdf
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdf
 
Computación distribuida usando Python
Computación distribuida usando PythonComputación distribuida usando Python
Computación distribuida usando Python
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloud
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8s
 
Implementing cert-manager in K8s
Implementing cert-manager in K8sImplementing cert-manager in K8s
Implementing cert-manager in K8s
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)
 
Python para equipos de ciberseguridad
Python para equipos de ciberseguridad Python para equipos de ciberseguridad
Python para equipos de ciberseguridad
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue Team
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source tools
 
Python Memory Management 101(Europython)
Python Memory Management 101(Europython)Python Memory Management 101(Europython)
Python Memory Management 101(Europython)
 
SecDevOps containers
SecDevOps containersSecDevOps containers
SecDevOps containers
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collector
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Angular js security

  • 2. iNDEX • Authenticate users API • Securing Admin pages • CSRF,XSS Prevention • Sanitize Module • Security Audit Tools • OWASP
  • 3. Authenticate users API POST /register POST /login POST /logout GET /status # returns 401 or the authenticated user
  • 5. Session service Represent the user’s session
  • 7. 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'); });
  • 8. 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); } } }])
  • 11. 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(); } } })
  • 12. Securing admin pages controller(“adminController", function ($scope, checkAuth) { $scope.isAuthenticated = checkAuth; });
  • 13. Browser risks • Cross Site Scripting(XSS) • Cross-Site Request Forgery(CSRF)
  • 14. 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
  • 17. 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
  • 18. 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();});
  • 19. 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
  • 20. 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
  • 21. CSRF Interceptor $rootScope.$on('XsrfToken:Invalid', function() { Security.status().then(function() { $rootScope.$broadcast('XsrfToken:Valid'); }); }); Store the original request and the promise
  • 22. 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
  • 23. 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
  • 24. 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>
  • 25. 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.
  • 27. 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>
  • 28. ng-bind-html .vs. ng-bind <div ng-bind-html="to_trusted(msg)"> </div> • ng-bind-htmlAutomatically uses $sanitize • <p ng-bind="msg"></p> Hello, <b>World</b>! • <p ng-bind-html="msg"></p> Hello, World!
  • 29. 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
  • 30. 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
  • 31. 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.
  • 37. JWT • JSON Web Token • Avoid CSRF and XSS • angular-jwt
  • 38. 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'); });
  • 39. 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
  • 40. 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
  • 41. 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!
  • 43. 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