improve proxy trust with ip address list
Before adoption: this commit came in with the history the project adopted, so no landing records it.
closes #2099
authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parent 65f13c3 · Browse files · 9 files·+198 added−22 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+198 added−22 removed
- tests:+110 added−0 removed
- other:+88 added−22 removed
Provenance
- Commit
566720b- Tree
7e08ef2- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent
65f13c3
9 files changed+198 added−22 removed
modified:lib/application.js+8 added
6 unmodified lines7 , methods = require('methods')8 , middleware = require('./middleware')9 , debug = require('debug')('express:application')10 , locals = require('./utils').locals11+ , compileTrust = require('./utils').compileTrust12 , View = require('./view')13 , utils = connect.utils14 , deprecate = require('./utils').deprecate15 , http = require('http');32 unmodified lines48 this.enable('x-powered-by');49 this.enable('etag');50 this.set('env', process.env.NODE_ENV || 'development');51 this.set('subdomain offset', 2);52+ this.set('trust proxy', false);53 debug('booting in %s mode', this.get('env'));54 55 // implicit middleware56 this.use(connect.query());197 unmodified lines254 if (1 == arguments.length) {255 return this.settings[setting];256 } else {257 this.settings[setting] = val;258+259+ if (setting === 'trust proxy') {260+ debug('compile trust proxy %j', val);261+ this.set('trust proxy fn', compileTrust(val));262+ }263+264 return this;265 }266 };267 271 unmodified linesmodified:lib/request.js+41 added-22 removed
7 unmodified lines8 , connect = require('connect')9 , fresh = require('fresh')10 , parseRange = require('range-parser')11 , parse = require('parseurl')12+ , proxyaddr = require('proxy-addr')13 , mime = connect.mime;14 15 /**16 * Request prototype.320 unmodified lines337 338 /**339 * Return the protocol string "http" or "https"340 * when requested with TLS. When the "trust proxy"340- * setting is enabled the "X-Forwarded-Proto" header341- * field will be trusted. If you're running behind342- * a reverse proxy that supplies https for you this343- * may be enabled.341+ * setting trusts the socket address, the342+ * "X-Forwarded-Proto" header field will be trusted.343+ * If you're running behind a reverse proxy that344+ * supplies https for you this may be enabled.345 *346 * @return {String}347 * @api public348 */349 350 req.__defineGetter__('protocol', function(){350- var trustProxy = this.app.get('trust proxy');351- if (this.connection.encrypted) return 'https';352- if (!trustProxy) return 'http';351+ var trust = this.app.get('trust proxy fn');352+353+ if (!trust(this.connection.remoteAddress)) {354+ return this.connection.encrypted355+ ? 'https'356+ : 'http';357+ }358+359+ // Note: X-Forwarded-Proto is normally only ever a360+ // single value, but this is to be safe.361 var proto = this.get('X-Forwarded-Proto') || 'http';362 return proto.split(/\s*,\s*/)[0];363 });364 10 unmodified lines375 return 'https' == this.protocol;376 });377 378 /**371- * Return the remote address, or when372- * "trust proxy" is `true` return373- * the upstream addr.379+ * Return the remote address from the trusted proxy.380 *381+ * The is the remote address on the socket unless382+ * "trust proxy" is set.383+ *384 * @return {String}385 * @api public386 */387 388 req.__defineGetter__('ip', function(){380- return this.ips[0] || this.connection.remoteAddress;389+ var trust = this.app.get('trust proxy fn');390+ return proxyaddr(this, trust);391 });392 393 /**384- * When "trust proxy" is `true`, parse385- * the "X-Forwarded-For" ip address list.394+ * When "trust proxy" is set, trusted proxy addresses + client.395 *396 * For example if the value were "client, proxy1, proxy2"397 * you would receive the array `["client", "proxy1", "proxy2"]`389- * where "proxy2" is the furthest down-stream.398+ * where "proxy2" is the furthest down-stream and "proxy1" and399+ * "proxy2" were trusted.400 *401 * @return {Array}402 * @api public403 */404 405 req.__defineGetter__('ips', function(){396- var trustProxy = this.app.get('trust proxy');397- var val = this.get('X-Forwarded-For');398- return trustProxy && val399- ? val.split(/ *, */)400- : [];406+ var trust = this.app.get('trust proxy fn');407+ var addrs = proxyaddr.all(this, trust);408+ return addrs.slice(1).reverse();409 });410 411 /**412 * Return basic auth credentials.61 unmodified lines474 475 /**476 * Parse the "Host" header field hostname.477 *478+ * When the "trust proxy" setting trusts the socket479+ * address, the "X-Forwarded-Host" header field will480+ * be trusted.481+ *482 * @return {String}483 * @api public484 */485 486 req.__defineGetter__('host', function(){475- var trustProxy = this.app.get('trust proxy');476- var host = trustProxy && this.get('X-Forwarded-Host');477- host = host || this.get('Host');487+ var trust = this.app.get('trust proxy fn');488+ var host = this.get('X-Forwarded-Host');489+490+ if (!host || !trust(this.connection.remoteAddress)) {491+ host = this.get('Host');492+ }493+494 if (!host) return;495+496+ // IPv6 literal support497 var offset = host[0] === '['498 ? host.indexOf(']') + 1499 : 0;500 var index = host.indexOf(':', offset);501+502 return ~index503 ? host.substring(0, index)504 : host;505 });49 unmodified linesmodified:lib/utils.js+30 added
3 unmodified lines4 */5 6 var mime = require('connect').mime7 , deprecate = require('util').deprecate8+ , proxyaddr = require('proxy-addr')9 , crc32 = require('buffer-crc32');10 11 /**12 * toString ref.324 unmodified lines337 .replace(/([\/.])/g, '\\$1')338 .replace(/\*/g, '(.*)');339 return new RegExp('^' + path + '$', sensitive ? '' : 'i');340 }341+342+/**343+ * Compile "proxy trust" value to function.344+ *345+ * @param {Boolean|String|Number|Array|Function} val346+ * @return {Function}347+ * @api private348+ */349+350+exports.compileTrust = function(val) {351+ if (typeof val === 'function') return val;352+353+ if (val === true) {354+ // Support plain true/false355+ return function(){ return true };356+ }357+358+ if (typeof val === 'number') {359+ // Support trusting hop count360+ return function(a, i){ return i < val };361+ }362+363+ if (typeof val === 'string') {364+ // Support comma-separated values365+ val = val.split(/ *, */);366+ }367+368+ return proxyaddr.compile(val || []);369+}modified:test/req.host.js+65 added
67 unmodified lines686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713867 unmodified lines .post('/') .set('Host', '[::1]:3000') .expect('[::1]', done); })
describe('when "trust proxy" is enabled', function(){ it('should respect X-Forwarded-Host', function(done){ var app = express();
app.enable('trust proxy');
app.use(function(req, res){ res.end(req.host); });
request(app) .get('/') .set('Host', 'localhost') .set('X-Forwarded-Host', 'example.com') .expect('example.com', done); })
it('should ignore X-Forwarded-Host if socket addr not trusted', function(done){ var app = express();
app.set('trust proxy', '10.0.0.1');
app.use(function(req, res){ res.end(req.host); });
request(app) .get('/') .set('Host', 'localhost') .set('X-Forwarded-Host', 'example.com') .expect('localhost', done); })
it('should default to Host', function(done){ var app = express();
app.enable('trust proxy');
app.use(function(req, res){ res.end(req.host); });
request(app) .get('/') .set('Host', 'example.com') .expect('example.com', done); }) })
describe('when "trust proxy" is disabled', function(){ it('should ignore X-Forwarded-Host', function(done){ var app = express();
app.use(function(req, res){ res.end(req.host); });
request(app) .get('/') .set('Host', 'localhost') .set('X-Forwarded-Host', 'evil') .expect('localhost', done); }) }) })})modified:test/req.ip.js+15 added
18 unmodified lines192021222324252627282930313233343536373839404131 unmodified lines18 unmodified lines .get('/') .set('X-Forwarded-For', 'client, p1, p2') .expect('client', done); })
it('should return the addr after trusted proxy', function(done){ var app = express();
app.set('trust proxy', 2);
app.use(function(req, res, next){ res.send(req.ip); });
request(app) .get('/') .set('X-Forwarded-For', 'client, p1, p2') .expect('p1', done); }) })
describe('when "trust proxy" is disabled', function(){ it('should return the remote address', function(done){31 unmodified linesmodified:test/req.ips.js+15 added
18 unmodified lines19 .get('/')20 .set('X-Forwarded-For', 'client, p1, p2')21 .expect('["client","p1","p2"]', done);22 })23+24+ it('should stop at first untrusted', function(done){25+ var app = express();26+27+ app.set('trust proxy', 2);28+29+ app.use(function(req, res, next){30+ res.send(req.ips);31+ });32+33+ request(app)34+ .get('/')35+ .set('X-Forwarded-For', 'client, p1, p2')36+ .expect('["p1","p2"]', done);37+ })38 })39 40 describe('when "trust proxy" is disabled', function(){41 it('should return an empty array', function(done){29 unmodified linesmodified:test/req.protocol.js+15 added
30 unmodified lines31 .set('X-Forwarded-Proto', 'https')32 .expect('https', done);33 })34 35+ it('should ignore X-Forwarded-Proto if socket addr not trusted', function(done){36+ var app = express();37+38+ app.set('trust proxy', '10.0.0.1');39+40+ app.use(function(req, res){41+ res.end(req.protocol);42+ });43+44+ request(app)45+ .get('/')46+ .set('X-Forwarded-Proto', 'https')47+ .expect('http', done);48+ })49+50 it('should default to http', function(done){51 var app = express();52 53 app.enable('trust proxy');27 unmodified linesmodified:History.md+8 added
1 3.x2 ===3 4+ * proper proxy trust with `app.set('trust proxy', trust)`5+ - `app.set('trust proxy', 1)` trust first hop6+ - `app.set('trust proxy', 'loopback')` trust loopback addresses7+ - `app.set('trust proxy', '10.0.0.1')` trust single IP8+ - `app.set('trust proxy', '10.0.0.1/16')` trust subnet9+ - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list10+ - `app.set('trust proxy', false)` turn off11+ - `app.set('trust proxy', true)` trust everything12 * update connect to 2.16.113 - deprecate `res.headerSent` -- use `res.headersSent`14 - deprecate `res.on("header")` -- use on-headers module instead15 - json: use body-parser1322 unmodified linesmodified:package.json+1 added
37 unmodified lines38 "commander": "1.3.2",39 "methods": "1.0.0",40 "mkdirp": "0.5.0",41 "parseurl": "1.0.1",42+ "proxy-addr": "1.0.0",43 "range-parser": "1.0.0",44 "cookie": "0.1.2",45 "buffer-crc32": "0.2.1",46 "fresh": "0.2.2",41 unmodified lines