Giter Club home page Giter Club logo

lusca's Introduction

lusca

Build Status NPM version

Web application security middleware.

Usage

var express = require('express'),
	app = express(),
	session = require('express-session'),
	lusca = require('lusca');

//this or other session management will be required
app.use(session({
	secret: 'abc',
	resave: true,
	saveUninitialized: true
}));

app.use(lusca({
    csrf: true,
    csp: { /* ... */},
    xframe: 'SAMEORIGIN',
    p3p: 'ABCDEF',
    hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
    xssProtection: true,
    nosniff: true,
    referrerPolicy: 'same-origin'
}));

Setting any value to false will disable it. Alternately, you can opt into methods one by one:

app.use(lusca.csrf());
app.use(lusca.csp({ /* ... */}));
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.p3p('ABCDEF'));
app.use(lusca.hsts({ maxAge: 31536000 }));
app.use(lusca.xssProtection(true));
app.use(lusca.nosniff());
app.use(lusca.referrerPolicy('same-origin'));

Please note that you must use express-session, cookie-session, their express 3.x alternatives, or other session object management in order to use lusca.

API

lusca.csrf(options)

  • key String - Optional. The name of the CSRF token added to the model. Defaults to _csrf.
  • secret String - Optional. The key to place on the session object which maps to the server side token. Defaults to _csrfSecret.
  • impl Function - Optional. Custom implementation to generate a token.
  • cookie String|Object - Optional. If set, a cookie with the name and/or options you provide will be set with the CSRF token. If the value is a string, it'll be used as the cookie name.
  • cookie.name String - Required if cookie is an object and angular is not true. The CSRF cookie name to set.
  • cookie.options Object - Optional. A valid Express cookie options object.
  • angular Boolean - Optional. Shorthand setting to set lusca up to use the default settings for CSRF validation according to the AngularJS docs. Can be used with cookie.options.
  • blocklist Array or String - Optional. Allows defining a set of routes that will not have csrf protection. All others will.
    Example configuration:
    blocklist: [{path: '/details', type: 'exact'}, {path: '/summary', type: 'startWith'}]
    //If match type is 'exact', route will get blocklisted only if it matches req.path exactly
    //If match type is 'startsWith', Lusca will check if req.path starts with the specified path
    
    For backwards compatiblity, following configuration is supported as well. It will be evaluated using the 'startsWith' match type.
    blocklist: '/details';
    blocklist: ['/details', '/summary'];
    
  • allowlist Array or String - Optional. Allows defining a set of routes that will have csrf protection. All others will not.
    Configuration is similar to blocklist config

Notes: The app can use either a blocklist or a allowlist, not both. By default, all post routes are allowlisted.

Enables Cross Site Request Forgery (CSRF) headers.

If enabled, the CSRF token must be in the payload when modifying data or you will receive a 403 Forbidden. To send the token you'll need to echo back the _csrf value you received from the previous request.

Furthermore, parsers must be registered before lusca.

lusca.csp(options)

  • options.policy String, Object, or an Array - Object definition of policy. Valid policies examples include:
    • {"default-src": "*"}
    • "referrer no-referrer"
    • [{ "img-src": "'self' http:" }, "block-all-mixed-content"]
  • options.reportOnly Boolean - Enable report only mode.
  • options.reportUri String - URI where to send the report data
  • options.styleNonce Boolean - Enable nonce for inline style-src, access from res.locals.nonce
  • options.scriptNonce Boolean - Enable nonce for inline script-src, access from res.locals.nonce

Enables Content Security Policy (CSP) headers.

Example Options

// Everything but images can only come from own domain (excluding subdomains)
{
  policy: {
    'default-src': '\'self\'',
    'img-src': '*'
  }
}

See the MDN CSP usage page for more information on available policy options.

lusca.xframe(value)

  • value String - Required. The value for the header, e.g. DENY, SAMEORIGIN or ALLOW-FROM uri.

Enables X-FRAME-OPTIONS headers to help prevent Clickjacking.

lusca.p3p(value)

  • value String - Required. The compact privacy policy.

Enables Platform for Privacy Preferences Project (P3P) headers.

lusca.hsts(options)

  • options.maxAge Number - Required. Number of seconds HSTS is in effect.
  • options.includeSubDomains Boolean - Optional. Applies HSTS to all subdomains of the host
  • options.preload Boolean - Optional. Adds preload flag

Enables HTTP Strict Transport Security for the host domain. The preload flag is required for HSTS domain submissions to Chrome's HSTS preload list.

lusca.xssProtection(options)

  • options.enabled Boolean - Optional. If the header is enabled or not (see header docs). Defaults to 1.
  • options.mode String - Optional. Mode to set on the header (see header docs). Defaults to block.

Enables X-XSS-Protection headers to help prevent cross site scripting (XSS) attacks in older IE browsers (IE8)

lusca.nosniff()

Enables X-Content-Type-Options header to prevent MIME-sniffing a response away from the declared content-type.

lusca.referrerPolicy(value)

  • value String - Optional. The value for the header, e.g. origin, same-origin, no-referrer. Defaults to `` (empty string).

Enables Referrer-Policy header to control the Referer header.

lusca's People

Contributors

alexsantos avatar amotmot avatar aredridel avatar bluelnkd avatar effrenus avatar fengmk2 avatar forbeslindesay avatar gabrielcsapo avatar geek avatar grawk avatar jasisk avatar jeffharrell avatar kumarrishav avatar lensam69 avatar linkrace avatar m0uneer avatar maxmil7 avatar mstuart avatar pvenkatakrishnan avatar relifeted avatar rragan avatar runk avatar sahat avatar shaunwarman avatar skoranga avatar suryagh avatar theel0ja avatar tlivings avatar totherik avatar turbomack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lusca's Issues

lusca with client-sesson fails

I was trying to use lusca with client-session library and it fails with the below error. Can you please share your views.

lusca requires req.session to be available in order to maintain state

Error: lusca requires req.session to be available in order to maintain state
at Object.create (/Users/msubbiah/sample/sessionapp/node_modules/lusca/lib/token.js:13:15)
at getCsrf (/Users/msubbiah/sample/sessionapp/node_modules/lusca/lib/csrf.js:34:22)
at checkCsrf (/Users/msubbiah/sample/sessionapp/node_modules/lusca/lib/csrf.js:57:20)
at Layer.handle as handle_request
at trim_prefix (/Users/msubbiah/sample/sessionapp/node_modules/express/lib/router/index.js:312:13)
at /Users/msubbiah/sample/sessionapp/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/Users/msubbiah/sample/sessionapp/node_modules/express/lib/router/index.js:330:12)
at next (/Users/msubbiah/sample/sessionapp/node_modules/express/lib/router/index.js:271:10)
at clientSession (/Users/msubbiah/sample/sessionapp/node_modules/client-sessions/lib/client-sessions.js:630:5)
at Layer.handle as handle_request

socket.io Content-Security-Policy Host

What is the recommended practice to define a sensible CSP to allow socket.io requests?

The host name may be known only upon receiving a request with the Host:, so I cannot configure the CSP string statically because 'self' does not apply to web sockets on the ws:// / wss:// protocols.

CSRF: Move from 10 Bytes to 9 or 12.

Currently, Lusca's CSRF module generates 10 bytes of random data. With Base64 conversion, session secrets include two equal sign characters. Is there a specific reason 10 bytes has been chosen? It would be possible to save two characters on every user session if the length was changed.

crypto.pseudoRandomBytes(LENGTH).toString('base64');

source

Further, it appears pseudoRandomBytes is now deprecated and it might be time to move to randomBytes (not sure if it's deprecated or just removed from the documentation now). Since session secrets by design must be cryptographically secure, I'm not sure why pseudoRandomBytes has been chosen.

PROPOSAL: Change line 18 of token.js (above) to use 12 bytes and use RandomBytes(cb);

Invalidate CSRF token

Hi
I am using krakenJS and enabled CSRF. Currently I am able to reuse the generated csrf token in one page to another page(With in the user session only)

I don't want to reuse the token even within the user session. Can I invalidate the token somehow?

Is there anyway to do it lusca?

Thanks in advance

K.Mugunthan.

CSRF Query

Why does lusca not try and get the csrf token(usually in body) from req.query also? There is no difference in the delivery of the correct csrf token as the cookie is the other half of the security.

Basic Security with Node, Express and Lusca

I am trying to build a basic Express app with some security protocols implemented using Lusca.

I am facing two issues. The first is with CSP (content security policy), for some reason when a violation is caught the browser doesn't carry out report-uri http://localhost:3000/r, and the network monitor gives a canceled status. Can someone explain the problem here?

vgizu

The second issue is with CSRF (cross-site request forgery), I keep getting an CSRF token missing error when I submit the form, I cannot tell why. How can I avoid having this error displayed and how can I validate the token itself? with sessions?

I have followed the docs very carefully, but with no luck. Here is my code:

var express    = require('express'),
    session    = require('express-session'),
    lusca      = require('lusca'),
    bodyParser = require('body-parser'),
    fs         = require('fs');
var app = express();

app.use(session({
    secret: 'abc',
    resave: true,
    saveUninitialized: true,
    cookie: { httpOnly: true }//, secure: true } // https only
}));

app.use(lusca({
    csrf: { secret: 'abc' },
    csp: {
        policy: { 'default-src': '\'self\'' },
        reportUri: 'http://localhost:3000/report'
    },
    xframe: 'DENY', // i never use frames, hence DENY instead of SAMEORIGN
    p3p: 'This is not a P3P policy.', // is this needed?
    //hsts: {maxAge: 31536000, preload: true}, // https only
    xssProtection: true,
    nosniff: true
    // any notes on these settings?
}));

app.disable('x-powered-by');

app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.json({ type: 'application/csp-report' }));
// are these two lines enough?

app.post('/r', (req, res) => {
    fs.writeFile('r/' + new Date().getTime() + '.json', '{ headers: ' + JSON.stringify(req.headers) + ', body: ' + JSON.stringify(req.body) + ' }');
    res.end();
});

app.get('/', (req, res) => {
    res.send('<form method="post">\
                <input type="hidden" name="_csrf" value="' + res.locals._csrf + '">\
                <input type="button" value="inline" onclick="alert(123);">\
                <input type="submit">\
              </form>');
});

app.post('/', (req, res) => {
    // is _csrf valid? how can i check?
});

app.listen(3000, () => { console.log('running ..'); });

req.csrfToken() not available anymore

Just wondering the thought process around not having req.csrfToken() available anymore.

I've been using version ~0.1.1 and it had this method. I think with the 1.0.0 release it was removed, and now you have to use req.session._csrf to get the token. Or am I thinking about this in the wrong way?

CSRF Hooks

Is there a way to hook into to when a CSRF returns 404? I'd like to check in on the IP of the originating server to see if I can just block them.

Hook up Travis-CI

I noticed Travis doesn't run builds on pull requests. I don't think I can add it because I'm not an admin on this repo. Can someone add it?

Express 4.* compatibility

Hi all,
i'm building an express 4.* application and I there are some incompatibilities with lusca due the changes made in the framework.

I've noticed that for using the csrf functionality you need to do the following changes to the express app:

var express = require('express'),
    session = require('express-session'),
    lusca = require('lusca'),
    app = express();

app.use(session({secret: 'my secret', key: 'sid', cookie: {secure: true}}));
app.use(lusca.csrf());

Can we update the readme to provide also infos about express 4.* compatibility?

Error: CSRF token mismatch

I'm having trouble getting CSRF working with HTTPS on AWS. I have it working fine locally, using a self-signed SSL certificate, but on the staging server behind a load balancer, I get Error: CSRF token mismatch. I am using Express, and Lusca is set up as below. _csrf is being sent in the POST body.

app.use(/^(?!.*\/res\/.*\/upload).*$/, lusca({
  csrf:   true,
  xframe: 'DENY',
  hsts:   {
    maxAge:            31536000,
    includeSubDomains: true,
    preload:           true,
  },
  xssProtection: true,
}));

Any idea what's going wrong?

Error: CSRF token missing

Hi guys,

after update lusca I got error :

Error: CSRF token missing

var csrfExclude = ['/webhooks']; // is not working any more ?

CSRF: Disable error log?

Is there a way to disable the error logging when a CSRF token missing is triggered? I guess someone is constantly trying to take advantage of my server my logs are flooded with

Error: CSRF token missing
data:    app.js:14113 -     at checkCsrf (/var/www/lovio/node_modules/lusca/lib/csrf.js:89:18)
data:    app.js:14113 -     at /var/www/lovio/node_modules/lusca/index.js:48:21
data:    app.js:14113 -     at xframe (/var/www/lovio/node_modules/lusca/lib/xframes.js:12:9)
data:    app.js:14113 -     at /var/www/lovio/node_modules/lusca/index.js:48:21
data:    app.js:14113 -     at xssProtection (/var/www/lovio/node_modules/lusca/lib/xssprotection.js:16:9)
data:    app.js:14113 -     at /var/www/lovio/node_modules/lusca/index.js:48:21
data:    app.js:14113 -     at lusca (/var/www/lovio/node_modules/lusca/index.js:53:9)
data:    app.js:14113 -     at Layer.handle [as handle_request] (/var/www/lovio/node_modules/express/lib/router/layer.js:95:5)
data:    app.js:14113 -     at trim_prefix (/var/www/lovio/node_modules/express/lib/router/index.js:312:13)
data:    app.js:14113 -     at /var/www/lovio/node_modules/express/lib/router/index.js:280:7
data:    app.js:14113 -     at Function.process_params (/var/www/lovio/node_modules/express/lib/router/index.js:330:12)
data:    app.js:14113 -     at next (/var/www/lovio/node_modules/express/lib/router/index.js:271:10)
data:    app.js:14113 -     at /var/www/lovio/node_modules/express-flash/lib/express-flash.js:31:7
data:    app.js:14113 -     at /var/www/lovio/node_modules/express-flash/node_modules/connect-flash/lib/flash.js:21:5
data:    app.js:14113 -     at /var/www/lovio/node_modules/express-flash/lib/express-flash.js:22:5
data:    app.js:14113 -     at Layer.handle [as handle_request] (/var/www/lovio/node_modules/express/lib/router/layer.js:95:5)
data:    app.js:14113 -     at trim_prefix (/var/www/lovio/node_modules/express/lib/router/index.js:312:13)
data:    app.js:14113 -     at /var/www/lovio/node_modules/express/lib/router/index.js:280:7
data:    app.js:14113 -     at Function.process_params (/var/www/lovio/node_modules/express/lib/router/index.js:330:12)
data:    app.js:14113 -     at next (/var/www/lovio/node_modules/express/lib/router/index.js:271:10)
data:    app.js:14113 -     at SessionStrategy.strategy.pass (/var/www/lovio/node_modules/passport/lib/middleware/authenticate.js:318:9)
data:    app.js:14113 -     at SessionStrategy.authenticate (/var/www/lovio/node_modules/passport/lib/strategies/session.js:67:10)

update tests and dependencies

Looks like it has been awhile since the tests and dependencies have been updated, node > 4 has a ton of syntax that could be leveraged to update this module.

Lusca and nginx best practices

I currently have an node express app behind an nginx load balancer.

I am curious to know what is the best practice when it comes to setting security policies such as CSP and http security headers such as HSTS? Should they be configured within my express.js application with lusca? Or is it best practice to configure them in nginx?

Does the lusca team recommend setting security in nginx or express application?

Features found in helmet, not in lusca?

I was just reviewing the features of helmetjs: https://www.npmjs.org/package/helmet

I see these features which don't appear to be a part of lusca. If that's true, are there plans to add them? Or perhaps is the recommended solution to simply use both lusca and helmet?

use postman in chrome found error : CSRF token missing

    app.use(lusca({
      csrf: {
        angular: true
      },
      xframe: 'SAMEORIGIN',
      hsts: {
        maxAge: 31536000, //1 year, in seconds
        includeSubDomains: true,
        preload: true
      },
      xssProtection: true
    }));

use postman in chrome found error : CSRF token missing

0.1.2 release

When are you planning to release the next version? Any estimates?

Lusca + Angular2 Problems

Anyone developing a lusca(+ krakenjs) back-end with a Angular 2 front-end. Currently I'm having an issue with a login screen. The krakenjs back-end runs on localhost:8000 and the Angular2 front-end runs on localhost:3000. When I send a POST request through the login screen to localhost:8000/login I get a CSFR token missing error. If I disable csfr, I get the error:

XMLHttpRequest cannot load http://localhost:8000/login. The request was redirected to 'http://localhost:8000/login', which is disallowed for cross-origin requests that require preflight.

Any ideas? Thanks

Update: Works on most browsers. Only Google Chrome gives this error.

REST API sessionless

Hi,

I got lusca for "free" from a scaffolding tool.
Sorry for perhaps asking a very stupid question but is it possible to have a RESTful endpoints which doesn't use cookies for sessions in express?

A way to defer the header setup

Hey all,

I was having problems between lusca and another code I was trying to integrated, specifically speaking, doing redirections based on some conditions like expired sessions with 401 status code.

Could be possible to do something to defer the headers for some urls or some conditions?

Consider adding SwitchUser behavior like Spring Framework

We're currently using Spring Framework + Spring Security or Groovy/Grails for apps but evaluating KrakenJS and trying out the PassportJS example. One piece missing I believe is the ability to assume a subordinate user role, but also switch back, which is a huge plus for Spring Security.

Since PassportJS is Authentication, and not Authorization, where best in KrakenJS stack would someone implement something similar to Spring's implementation of this functionality and is there any effort to add this with the current rewrite?

See: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/apidocs/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.html

See: http://grails-plugins.github.io/grails-spring-security-core/docs/manual.1273/guide/15%20Switch%20User.html

Is there the ability for CSRF token built into Kraken to not use session store.

The default csrf token solution from Lusca uses session store which seems to not work if you are running multiple processes (they don't share session store) and of course does not work if you run multiple hosts. Is using Redis the only solution? Is there a csrf solution that will not depend on session store? Maybe a cookie related token. It seems excessive to run Redis just to maintain sessions for a csrf token when we write state less apps.

Crypto could be improved for generating CSRF tokens

https://github.com/krakenjs/lusca/blob/master/lib/token.js#L18 in particular uses pseudoRandomBytes, which generates low quality output until warmed up.

Kraken should probably warm up randomBytes at app boot (not emitting the start event until it gets data) so that the PRNG is seeded well. At that point, pseudoRandomBytes is the same as randomBytes, and randomBytes will never block/throw anyway.

At https://github.com/krakenjs/lusca/blob/master/lib/token.js#L35, we generate and use a salt, but it's combined with the secret by appending, not HMAC, so it would possibly be extensible; that said, a salt should get us exactly nothing, and we should use a fully random token since we're just doing an equality check anyway. There's no use in salting to prevent a rainbow table, because nobody generates a rainbow table for random data anyway; that's for passphrases, not randomness.

Readme Update

Copied below straight out of the readme, and it's missing a closing parentheses. Just thought I'd point it out.

app.use(lusca.hsts({ maxAge: 31536000 });

how to allow bypass security from one route

How can i disallow the protection for 1 route im using openpay and webhooks
app.use(lusca({
csrf: {
angular: true
},
policy: {
'allow':'api/openpay/webook'
}
xframe: 'SAMEORIGIN',
hsts: {
maxAge: 31536000, //1 year, in seconds
includeSubDomains: true,
preload: true
},
xssProtection: true
}));

Error: CSRF token missing

Hi,
I am trying to integrate lusca in my application using Angular,Express and Node.
Please help me with the following issue
Error: CSRF token missing

Angular: Included a hidden input in a form to generate
content="b4XIZqlfDLlHQbfbk381gO0UupiLY8WYFAYw0="

node: Included session and cookie

var session = require('express-session'); 
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
  store: new MongoStore({ url: secrets.db, autoReconnect: true })
}));

var cookieParser = require('cookie-parser');
app.use(cookieParser());

app.use(lusca({
    csrf: true,
    csp: { /* ... */},
    xframe: 'SAMEORIGIN',
    p3p: 'ABCDEF',
    hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
    xssProtection: true
}));

Please help me debug why I get Error CSRF token missing on my node server.

Let me know if you need more details.

Thank You

Need separate csrf token creation function

For scenarios, where we need to disable CSRF for particular POST page, we wont be able to add CSRF token for the following request.

Either of the following enhancement would help

  1. If there is a separate function for CSRF token creation, in these scenarios where we disable csrf we can call this creation function for generating the token
  2. A way in csrf.js to disable validation for POST if application needs it

Remove "engineStrict" in preparation for npm 3+

Upon install:

npm WARN engineStrict Per-package engineStrict (found in package.json for lusca)
npm WARN engineStrict won't be used in npm 3+. Use the config setting `engine-strict` instead.

Error pages

Is there a way to present custom error pages such as a CSRF token mismatch to the user? Right now, express/lusca just prints the stack trace. Having a way to customize the template would be great.

p3p value unclear

What does p3p require for a value, is that a key? Or some kind of configuration value?

The link to the Microsoft page isn't very helpful, nor the W3C spec (unsure on how to interpret it).

IE and Safari block third-party cookies, by default causing csrf issues in iframe

Below is the stack trace:
[2015-05-19 13:53:55.581] - error: [corrId: 5d031de0fed19][cal] Error: CSRF token missing at csrf (/Users/swarman/Development/Source/pppluscpmnodeweb/node_modules/lusca/lib/csrf.js:53:18) at csrf (eval at createToggleWrapper (/Users/swarman/Development/Source/pppluscpmnodeweb/node_modules/kraken-js/node_modules/meddleware/index.js:133:51), <anonymous>:1:65) at Layer.handle [as handle_request] (/Users/swarman/Development/Source/pppluscpmnodeweb/node_modules/express/lib/router/layer.js:76:5) at trim_prefix (/Users/swarman/Development/Source/pppluscpmnodeweb/node_modules/express/lib/router/index.js:263:13)

It sounds like a http header needs to be present, but this sounds risky. Need to dive deeper.

How to get XSRF token before first post request

Hi,
I am trying to move authentication to my first loaded route -> '/' - the index page, and I have to send the post request twice because the XSRF token is missing. What should I change in the config of lusca?

app.use(lusca({
csrf: {
angular: true
},
xframe: 'SAMEORIGIN',
hsts: {
maxAge: 31536000, //1 year, in seconds
includeSubDomains: true,
preload: true
},
xssProtection: true
}));

Cannot read property '_csrfSecret' of undefined

Error when accessing / endpoint.

TypeError: Cannot read property '_csrfSecret' of undefined
   at Object.create (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/token.js:13:25)
   at csrf (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/csrf.js:28:32)
   at /Users/iradchenko/workspace/nycbb/node_modules/lusca/index.js:48:21
   at csp (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/csp.js:32:9)
   at /Users/iradchenko/workspace/nycbb/node_modules/lusca/index.js:48:21
   at hsts (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/hsts.js:24:9)
   at /Users/iradchenko/workspace/nycbb/node_modules/lusca/index.js:48:21
   at p3p (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/p3p.js:15:9)
   at /Users/iradchenko/workspace/nycbb/node_modules/lusca/index.js:48:21
   at xframe (/Users/iradchenko/workspace/nycbb/node_modules/lusca/lib/xframes.js:12:9)

My lusca options look like this:

app.use(lusca({
  csrf: true,
  csp: {
    policy: {
      'default-src': '\'self\''
    }
  },
  xframe: 'SAMEORIGIN',
  p3p: 'ABCDEF',
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true
  },
  xssProtection: true
}));

Can't pass _csrf parameter via file upload

I am not sure if I am setting this up correctly, but I can't seem to pass _csrf parameter via angularFileUpload module.

I am passing it like following.

        $upload.upload({
            url: '/import/dsbudget',
            data: {
                _csrf: '<%=_csrf%>', //doesn't work here.. let's add to exclusion
                docid: $scope.docid,
                importtype: $scope.importtype.name,
                fd: $scope.fd },
            file: $scope.file,
        })

When I try uploading my file, I get following error message.

Error: CSRF token mismatch
    at csrf (/usr/local/git/dsbudget/node_modules/lusca/lib/csrf.js:44:18)
    at Object.app.use.res.locals.user [as handle] (/usr/local/git/dsbudget/app.js:120:5)
    at next (/usr/local/git/dsbudget/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at /usr/local/git/dsbudget/node_modules/express-flash/lib/express-flash.js:31:7
    at /usr/local/git/dsbudget/node_modules/connect-flash/lib/flash.js:21:5
    at Object.handle (/usr/local/git/dsbudget/node_modules/express-flash/lib/express-flash.js:22:5)
    at next (/usr/local/git/dsbudget/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at SessionStrategy.strategy.pass (/usr/local/git/dsbudget/node_modules/passport/lib/middleware/authenticate.js:314:9)
    at /usr/local/git/dsbudget/node_modules/passport/lib/strategies/session.js:61:12
    at pass (/usr/local/git/dsbudget/node_modules/passport/lib/authenticator.js:333:31)
POST /import/dsbudget 403 15.011 ms - -

I see the token sent to my express server inside the HTTP request payload

------WebKitFormBoundarysf8AO9yhuSLqzp68
Content-Disposition: form-data; name="_csrf"

iLmmo4qZGQ5hNaRpGE7ZKlDWV37lcWvQQUI64=

I am guessing that CSRF is not made to receive the token this way?

Maybe CSP implementation is too naive?

X-Content-Security-Policy in Firefox < 23.0, IE 10 & 11
X-Webkit-CSP in Chrome < 25.0, Safari < 7.0

Although Content-Security-Policy (correct, according to the spec) is what the latest FF, Chrome and Safari are using, leaving out IE 10 & 11 seems kind of wrong. :)

To implement this, I think we'll have to resort to user-agent sniffing (ouch!)

Source: http://caniuse.com/contentsecuritypolicy

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.