XSS is much more than just <script>alert(1)</script>. Thousands of unique vectors can be built and more complex payloads to evade filters and WAFs. In these slides, cool techniques to bypass them are described, from HTML to javascript. See also http://brutelogic.com.br/blog
Architecting Secure and Compliant Applications with MongoDB MongoDB
High profile security breaches have become embarrassingly common, but ultimately avoidable. Now more than ever, database security is a critical component of any production application. In this talk we'll learn to secure your deployment in accordance with best practices and compliance regulations. We'll explore the MongoDB Enterprise features which ensure HIPAA and PCI compliance, and protect you against attack, data exposure and a damaged reputation.
Building Secure User Interfaces With JWTs (JSON Web Tokens)Stormpath
With new tools like Angular.js and Node.js, it is easier than ever to build User Interfaces and Single-Page Applications (SPAs) backed by APIs.
But how to do it securely? Web browsers are woefully insecure, and hand-rolled APIs are risky.
In this presentation, Robert Damphousse, lead front-end developer at Stormpath, covers web browser security issues, technical best practices and how you can mitigate potential risks. Enjoy!
Topics Covered:
1. Security Concerns for Modern Web Apps
2. Cookies, The Right Way
3. Session ID Problems
4. Token Authentication to the rescue!
5. Angular Examples
XSS is much more than just <script>alert(1)</script>. Thousands of unique vectors can be built and more complex payloads to evade filters and WAFs. In these slides, cool techniques to bypass them are described, from HTML to javascript. See also http://brutelogic.com.br/blog
Architecting Secure and Compliant Applications with MongoDB MongoDB
High profile security breaches have become embarrassingly common, but ultimately avoidable. Now more than ever, database security is a critical component of any production application. In this talk we'll learn to secure your deployment in accordance with best practices and compliance regulations. We'll explore the MongoDB Enterprise features which ensure HIPAA and PCI compliance, and protect you against attack, data exposure and a damaged reputation.
Building Secure User Interfaces With JWTs (JSON Web Tokens)Stormpath
With new tools like Angular.js and Node.js, it is easier than ever to build User Interfaces and Single-Page Applications (SPAs) backed by APIs.
But how to do it securely? Web browsers are woefully insecure, and hand-rolled APIs are risky.
In this presentation, Robert Damphousse, lead front-end developer at Stormpath, covers web browser security issues, technical best practices and how you can mitigate potential risks. Enjoy!
Topics Covered:
1. Security Concerns for Modern Web Apps
2. Cookies, The Right Way
3. Session ID Problems
4. Token Authentication to the rescue!
5. Angular Examples
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...GeeksLab Odessa
Web Security: Cookies, Domains and CORS
Юрий Чайковский
О предложенном еще в 1995 году и актуальным до сегодняшнего дня принципе одинакового источника (Same-origin policy) и о применении и ограничениях при междоменных запросах. Пример CSRF атак, а также правила конфигурации сервера для защиты от них. О последних нововведениях, касающихся контроля происхождения контента для предотвращения XSS атак. Кроме того:
- Принцип одинакового источника.
- Использование междоменных запросов.
- CSRF атаки (с демонстрацией).
- Классификация браузерных запросов.
- Ограничения междоменных запросов.
- Серверный контроль доступа.
- Особенности Internet Explorer 8, 9.
- Принцип безопасности контента (CSP).
It's silly to write the same functionality over and over again. Auth is the most often implemented functionality at web projects. Let's check how can we speed up development by using one of auth provider: Amazon Cognito, Google Firebase or Auth0. On code level we will use custom React Hooks.
Learn how to exploit security vulnerabilities that are commonly found in the arsenal of malicious attackers. We won't simply talk about issues like XSS, CSRF and SQL Injection, but will have live demos showing how hackers exploit these potentially devastating defects using freely available tools. You'll see how to hack a real world open source application and explore bugs in commonly used open source frameworks. We also look at the source code and see how to fix these issues using secure coding principles. We will also discuss best practices that can be used to build security into your SDLC. Java developers and architects will learn how to find and fix security issues in their applications before hackers do.
PHP Experience 2016 - [Palestra] Json Web Token (JWT)iMasters
Ivan Rosolen, Head de Inovação na Arizona, fez a palestra "Json Web Token (JWT)", no PHP Experience 2016.
O iMasters PHP Experience 2016 aconteceu nos dias 21 e 22 de Março de 2015, no Hotel Tivoli em São Paulo-SP
http://phpexperience2016.imasters.com.br/
Running a MongoDB cluster is usually smooth sailing, but as your load increases you may notice things start to slow down. This talk will run through a few of the options you have to notice problems, and the ways to fix them. We’ll be focussing mainly on running a cluster inside EC2, as the challenges are slightly different, but you should learn something regardless of where you’re hosted.
Super simple application security with Apache ShiroMarakana Inc.
Les Hazlewood, founder of the Apache Shiro project, covers the benefits of using Shiro as an application security framework.
Check out the video for this presentation, as well as more training resources for Java here: http://marakana.com/forums/java/general/183.html
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. In this presentation Rob will start with an insecure application and incrementally Spring Security 4 to demonstrate how easily you can secure your application. Throughout the presentation, new features found in Spring Security 4 will be highlighted. Whether you are new to Spring Security or are wanting to learn what is new in Spring Security 4, this presentation is a must!
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...GeeksLab Odessa
Web Security: Cookies, Domains and CORS
Юрий Чайковский
О предложенном еще в 1995 году и актуальным до сегодняшнего дня принципе одинакового источника (Same-origin policy) и о применении и ограничениях при междоменных запросах. Пример CSRF атак, а также правила конфигурации сервера для защиты от них. О последних нововведениях, касающихся контроля происхождения контента для предотвращения XSS атак. Кроме того:
- Принцип одинакового источника.
- Использование междоменных запросов.
- CSRF атаки (с демонстрацией).
- Классификация браузерных запросов.
- Ограничения междоменных запросов.
- Серверный контроль доступа.
- Особенности Internet Explorer 8, 9.
- Принцип безопасности контента (CSP).
It's silly to write the same functionality over and over again. Auth is the most often implemented functionality at web projects. Let's check how can we speed up development by using one of auth provider: Amazon Cognito, Google Firebase or Auth0. On code level we will use custom React Hooks.
Learn how to exploit security vulnerabilities that are commonly found in the arsenal of malicious attackers. We won't simply talk about issues like XSS, CSRF and SQL Injection, but will have live demos showing how hackers exploit these potentially devastating defects using freely available tools. You'll see how to hack a real world open source application and explore bugs in commonly used open source frameworks. We also look at the source code and see how to fix these issues using secure coding principles. We will also discuss best practices that can be used to build security into your SDLC. Java developers and architects will learn how to find and fix security issues in their applications before hackers do.
PHP Experience 2016 - [Palestra] Json Web Token (JWT)iMasters
Ivan Rosolen, Head de Inovação na Arizona, fez a palestra "Json Web Token (JWT)", no PHP Experience 2016.
O iMasters PHP Experience 2016 aconteceu nos dias 21 e 22 de Março de 2015, no Hotel Tivoli em São Paulo-SP
http://phpexperience2016.imasters.com.br/
Running a MongoDB cluster is usually smooth sailing, but as your load increases you may notice things start to slow down. This talk will run through a few of the options you have to notice problems, and the ways to fix them. We’ll be focussing mainly on running a cluster inside EC2, as the challenges are slightly different, but you should learn something regardless of where you’re hosted.
Super simple application security with Apache ShiroMarakana Inc.
Les Hazlewood, founder of the Apache Shiro project, covers the benefits of using Shiro as an application security framework.
Check out the video for this presentation, as well as more training resources for Java here: http://marakana.com/forums/java/general/183.html
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. In this presentation Rob will start with an insecure application and incrementally Spring Security 4 to demonstrate how easily you can secure your application. Throughout the presentation, new features found in Spring Security 4 will be highlighted. Whether you are new to Spring Security or are wanting to learn what is new in Spring Security 4, this presentation is a must!
Caution: This is a dated presentation; uploaded for reference. While the principles remain valid, specifics may have changed.
This presentation was made for software developers in Chandigarh - as a part of the NULL & OWASP Chandigarh Chapter activities.
It covers the basics of secure software development and secure coding using OWASP Top 10 as a broad guide.
The security of an application is a continuous struggle between solid proactive controls and quality in SDLC versus human weakness and resource restrictions. As the pentester's experience confirms, unfortunatelly even in high-risk (e.g. banking) applications, developed by recognized vendors, the latter often wins - and we end up with critical vulnerabilities.
One of the primary reasons is lack of mechanisms enforcing secure code by default, as opposed to manual adding security per each function. Whenever the secure configuration is not default, there will almost inevitably be bugs, especially in complex systems. I will pinpoint what should be taken into consideration in the architecture and design process of the application. I will show solutions that impose security in ways difficult to circumvent unintentionally by creative developers. I will also share with the audience the pentester's (=attacker's) perspective, and a few clever tricks that made the pentest (=attack) painful, or just rendered the scenarios irrelevant.
The security of an application is a continuous struggle between solid proactive controls and quality in SDLC versus human weakness and resource restrictions. As the pentester's experience confirms, unfortunatelly even in high-risk (e.g. banking) applications, developed by recognized vendors, the latter often wins - and we end up with critical vulnerabilities.
One of the primary reasons is lack of mechanisms enforcing secure code by default, as opposed to manual adding security per each function. Whenever the secure configuration is not default, there will almost inevitably be bugs, especially in complex systems.
I will pinpoint what should be taken into consideration in the architecture and design process of the application. I will show solutions that impose security in ways difficult to circumvent unintentionally by creative developers. I will also share with the audience the pentester's (=attacker's) perspective, and a few clever tricks that made the pentest
(=attack) painful, or just rendered the scenarios irrelevant.
This talk walks through the basics of web security without focussing too much on the particular tools that you choose. The concepts are universal, although most examples will be in Perl. We'll also look at various attack vectors (SQL Injection, XSS, CSRF, and more) and see how you can avoid them. Whether you're an experienced web developer (we all need reminding) or just starting out, this talk can help avoid being the next easy harvest of The Bad Guys.
Application and Website Security -- Fundamental EditionDaniel Owens
This is the first presentation in the 200 level, specifically targeting developers with a more hardcore training program. This program includes numerous case studies and live demonstrations and is considered technical, but does not require a working knowledge of the languages discussed.
Securing Microservices using Play and Akka HTTPRafal Gancarz
Going down the microservices route makes a lot of things around creating and maintaining large systems easier but it comes at a cost too, particularly associated with challenges around security. While securing monolithic applications was a relatively well understood area, the same can't be said about microservice based architectures.
This presentation covers how implementing microservices affects the security of distributed systems, outlines pros and cons of several standards and common practices and offers practical suggestions for securing microservice based systems using Play and Akka HTTP.
10 Rules for Safer Code [Odoo Experience 2016]Olivier Dony
In this talk, we will cover the top 10 development mistakes that lead to security issues. Olivier Dony will go through all the security issues we have had over the past 3 years and give tips on how to avoid the traps for safer Odoo code.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
2. What we will talk about
• Server side JS injection
• “Use strict”
• Helmet
• Proper session management
• XSS attacks
• SQL and No-SQL injections
• RegEx Denial of Service
3. What we will talk about
• Cross-Site Request Forgery
• Rate Limiting
• Data Sanitisation
• Vulnerability testing
• Logging
• Filtering architecture
4. Server side JS injection (SSJS)
Could be a call in file system as well causing the
server to respond with private files and scripts…
eval()
5. How to prevent it
• Validate user input.
• Never use eval()-> JSON.parse() is much
safer
• setTimeout(), setInterval(),
Function() may have catastrophic results as
well
6. “Use strict”;
• At the beginning of every script
• Enables “strict mode”
• Does not allow some actions such as using a variable
without declaring it
• x = 5.2
• deleting objects, variables, functions etc.
• Limits eval() use cases
7. Helmet
• npm package
• Applies XSS protections
• Sets “Content-Security-Policy” header
• Prevents clickjacking
• Disables client-side caching
• It disables some sensitive HTTP Headers
• X-Powered-By (you can also change that to anything you like)
10. Change default error pages (404, 500 etc)
• There is no reason to hide “X-Powered-By” header if
we keep the default error pages of Express.
• The intruder can still understand that our server runs on
Express
// Handle 404
app.use(function(req, res) {
res.status(400);
res.render('404', {title: '404: File Not Found'});
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('500', {title:'500: Internal Server Error', error:
error});
});
11. Session Management and Credentials
• Passwords must always be hashed (bcrypt)
• Cookies management:
Prevents cookies from being
accessed by browser JS scripts
Cookies can only be configured over
secure HTTPS connections
app.use(express.cookieParser());
app.use(express.session({
secret: "s3Cur3",
cookie: {
httpOnly: true,
secure: true
}
}));
12. Session Management and Credentials
• ephemeral (boolean cookie property) : deletes the cookie when the
browser is closed. Very useful for apps that are being accessed by
public computers.
• Do not forget: Destroy session and cookies on logout
req.session.destroy(function() {
res.redirect("/");
});
13. XSS Attacks (Cross - Site Scripting)
“XSS attacks allows intruders to execute scripts in the
victims’ browser. In that way they can access cookies,
session tokens and other sensitive info or redirect
users to malicious sites. It is one of the most common
ways an intruder can take over a webpage.”
17. XSS Attacks (Cross - Site Scripting) - How to prevent it
• Data validation and sanitisation
• Cookie httpOnly: true
• Never insert untrusted data in HTML (tag names, in a JS script, in CSS
inline styling etc)
• HTML Escape data before inserting into HTML Element (ex: & -->
& < --> < etc)
• HTML escape JSON values in an HTML context and read the data
with JSON.parse
• “XSS” npm package
18. SQL injections
username = req.body.username;
password = req.body.password;
sql = 'SELECT * FROM Users WHERE Name ="' +
username+ '" AND Pass ="' + password + ‘"'
What if the malicious user type " or “"=" in username
and password fields ?
SELECT * FROM Users WHERE Name ="" or ""=""
AND Pass ="" or ""=""
OR ""="" is always true !
So the query returns all the rows of “Users” table
19. SQL injections - How to prevent it
• (Once again…) Data validation and sanitisation
• “sqlstring” npm package, it escapes user input
values.
var sql = SqlString.format('SELECT * FROM users WHERE
id = ?', [userId]);
• “sql-query-builder” npm package
query().select([users.id.as('User'), users.id.count(1
)]).from(users).join(posts)
.on(posts.user_id).equals(users.id)
.groupBy(users.id);
• Far better than string concatenated SQL queries
var sql = SqlString.format('SELECT * FROM users WHERE
id = ?', [userId]);
query().select([users.id.as('User'), users.id.count(
1)]).from(users).join(posts)
.on(posts.user_id).equals(users.id)
.groupBy(users.id);
20. No - SQL injections
app.post('/login', function (req, res) {
var user = req.body.user;
User input (req.body):
It returns all the users…
{
"user": {"$gt": ""},
"pass": {"$gt": ""}
}
app.post('/login', function (req, res) {
var user = req.body.user;
var pass = req.body.pass;
db.users.find({user: user, pass: pass});
});
21. No - SQL injections
• We have not set explicitly the query selector, so the
malicious user specified one for himself
db.users.find({user: {$in: [user]}, pass: {$in:
[pass]}});
db.users.find({user: { $in: [{ '$gt': '' }] },
pass: { $in: [{ '$gt': '' }] }});
• Now the query will return nothing.
• So we should always explicitly set the query selector!
• “mongoose” npm package - it escapes many of the
things mentioned above
db.users.find({user: {$in: [user]}, pass: {$in:
[pass]}});
db.users.find({user: { $in: [{ '$gt': '' }] },
pass: { $in: [{ '$gt': '' }] }});
22. RegEx Denial of Service
• Some Regular Expressions may be “unsafe” for some inputs
• Example : (a+)+ for input aaaaaaaaaaaaaaaaaaaaa!
• They may fall in exponential time complexity causing the
server to Denial of Service.
• npm package that helps us detect vulnerable RegExes:
“safe-regex”
var safe = require(‘safe-regex’);
var regex = new RegExp(‘(a+)+’);
console.log(safe(regex));
var safe = require(‘safe-regex’);
var regex = new RegExp(‘(a+)+’);
console.log(safe(regex));
23. Cross-Site Request Forgery
“Cross-Site Request Forgery (CSRF) is an attack that tricks the
victim into loading a page that contains a malicious request. It
is malicious in the sense that it inherits the identity and
privileges of the victim to perform an undesired function on the
victim’s behalf, like change the victim’s e-mail address, home
address, or password, or purchase something. CSRF attacks
generally target functions that cause a state change on the
server but can also be used to access sensitive data.”
Source: “Open Web Application Security Project”
24. Cross-Site Request Forgery - How to prevent it
• Synchronized csrf tokens
• npm package “csurf”
var csrf = require('csurf');
var app = express();
app.use(csrf());
app.use(function(req, res, next) {
res.locals._csrf = req.csrfToken();
next();
});
var csrf = require('csurf');
var app = express();
app.use(csrf());
app.use(function(req, res, next) {
res.locals._csrf = req.csrfToken();
next();
});
25. Cross-Site Request Forgery - How to prevent it
<html>
<form method="post" action=“changeEmail">
<input type="hidden" name="_csrf" value="_csrf">
<input type="email" name=“newEmail">
</form>
</html>
• csrf token is set when the user requests the page that contains a
form and expects the same csrf token when a POST request is
made. If the csrf tokens do not match or if the csrf token is
not in the form data, the POST request is not allowed
<html>
<form method="post" action=“changeEmail">
<input type="hidden" name="_csrf" value="_csrf">
<input type="email" name=“newEmail">
</form>
</html>
26. Rate Limiting
• “express-rate-limit” npm package
var RateLimit = require('express-rate-limit');
app.enable('trust proxy'); // only if you're behind a reverse proxy
var limiter = new RateLimit({
windowMs: 15*60*1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
delayMs: 0 // disable delaying -
full speed until the max limit is reached
});
app.use(limiter); // or app.use(‘/api/’limiter)
//many other properties such as delayAfter (number of reqs), custom
response message etc
Be careful : Static resources such as images, css / js scripts count for
requests as well if we serve them through our node server!
27. Data Sanitisation and Validation
• Must take place in every endpoint where the user
interacts with the server by submitting data.
• It protects us from most of the flaws mentioned above
• We are interested in checks and validations like “Is it
an email?”, “Is it an Integer?”, “Is it a telephone
number?”
• npm package: “express-validator”
28. Data Sanitisation and Validation
• “express-validator” allows us to create “check
schemas” for each endpoint in pure JSON.
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers,
params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
}
29. Data Sanitisation and Validation
• Many useful keys and functions such as isIn(),
exists(), isUUID(), isPostalCode(),
sanitizeBody(‘body_parameter_to_trim’)
.trim() etc.
• It also allows us to write custom validation and
sanitisation logics.
31. Vulnerability testing
• Retire.js CLI tool
• npm install -g retire
• retire
•The tool indicates any known vulnerable JS libraries used
in our node server
•“sqlmap”: python based pen-testing tool for sql injections
32. Logging
• Logging is critical during an attack and for
understanding “what went wrong” after an attack
• We must be sure that each and every request and
response to and from our server leaves a trace so
that we know “who” (user id) did it, “where it came
from” (IP address), “what he requested” (request
payload) and “what our server
responded” (response)
• This information must be stored in our database in
order to be able to be further examined.
33. Filtering architecture
• Custom middleware responsible for filtering and security,
applied in the “app level” (for each and every request)
• It handles data validation and sanitisation, logging,
injections detection etc.
• Endpoints white-list: An array with the known and used
endpoints of our server, if a user hits a non-white-listed
endpoint he will immediately get an HTTP 404 error
• In general: When a malicious request reaches the
middleware, the server will immediately respond with an
error code and the app router will never get “bothered”
34. Further reading and fun
• Open Web Application Security Project
• owasp.org
• NodeGoat
• https://github.com/OWASP/NodeGoat