You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

347 lines
6.0 KiB

7 years ago
  1. /*!
  2. * proxy-addr
  3. * Copyright(c) 2014 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. 'use strict'
  7. /**
  8. * Module exports.
  9. */
  10. module.exports = proxyaddr;
  11. module.exports.all = alladdrs;
  12. module.exports.compile = compile;
  13. /**
  14. * Module dependencies.
  15. */
  16. var forwarded = require('forwarded');
  17. var ipaddr = require('ipaddr.js');
  18. /**
  19. * Variables.
  20. */
  21. var digitre = /^[0-9]+$/;
  22. var isip = ipaddr.isValid;
  23. var parseip = ipaddr.parse;
  24. /**
  25. * Pre-defined IP ranges.
  26. */
  27. var ipranges = {
  28. linklocal: ['169.254.0.0/16', 'fe80::/10'],
  29. loopback: ['127.0.0.1/8', '::1/128'],
  30. uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']
  31. };
  32. /**
  33. * Get all addresses in the request, optionally stopping
  34. * at the first untrusted.
  35. *
  36. * @param {Object} request
  37. * @param {Function|Array|String} [trust]
  38. * @api public
  39. */
  40. function alladdrs(req, trust) {
  41. // get addresses
  42. var addrs = forwarded(req);
  43. if (!trust) {
  44. // Return all addresses
  45. return addrs;
  46. }
  47. if (typeof trust !== 'function') {
  48. trust = compile(trust);
  49. }
  50. for (var i = 0; i < addrs.length - 1; i++) {
  51. if (trust(addrs[i], i)) continue;
  52. addrs.length = i + 1;
  53. }
  54. return addrs;
  55. }
  56. /**
  57. * Compile argument into trust function.
  58. *
  59. * @param {Array|String} val
  60. * @api private
  61. */
  62. function compile(val) {
  63. if (!val) {
  64. throw new TypeError('argument is required');
  65. }
  66. var trust = typeof val === 'string'
  67. ? [val]
  68. : val;
  69. if (!Array.isArray(trust)) {
  70. throw new TypeError('unsupported trust argument');
  71. }
  72. for (var i = 0; i < trust.length; i++) {
  73. val = trust[i];
  74. if (!ipranges.hasOwnProperty(val)) {
  75. continue;
  76. }
  77. // Splice in pre-defined range
  78. val = ipranges[val];
  79. trust.splice.apply(trust, [i, 1].concat(val));
  80. i += val.length - 1;
  81. }
  82. return compileTrust(compileRangeSubnets(trust));
  83. }
  84. /**
  85. * Compile `arr` elements into range subnets.
  86. *
  87. * @param {Array} arr
  88. * @api private
  89. */
  90. function compileRangeSubnets(arr) {
  91. var rangeSubnets = new Array(arr.length);
  92. for (var i = 0; i < arr.length; i++) {
  93. rangeSubnets[i] = parseipNotation(arr[i]);
  94. }
  95. return rangeSubnets;
  96. }
  97. /**
  98. * Compile range subnet array into trust function.
  99. *
  100. * @param {Array} rangeSubnets
  101. * @api private
  102. */
  103. function compileTrust(rangeSubnets) {
  104. // Return optimized function based on length
  105. var len = rangeSubnets.length;
  106. return len === 0
  107. ? trustNone
  108. : len === 1
  109. ? trustSingle(rangeSubnets[0])
  110. : trustMulti(rangeSubnets);
  111. }
  112. /**
  113. * Parse IP notation string into range subnet.
  114. *
  115. * @param {String} note
  116. * @api private
  117. */
  118. function parseipNotation(note) {
  119. var ip;
  120. var kind;
  121. var max;
  122. var pos = note.lastIndexOf('/');
  123. var range;
  124. ip = pos !== -1
  125. ? note.substring(0, pos)
  126. : note;
  127. if (!isip(ip)) {
  128. throw new TypeError('invalid IP address: ' + ip);
  129. }
  130. ip = parseip(ip);
  131. kind = ip.kind();
  132. max = kind === 'ipv6'
  133. ? 128
  134. : 32;
  135. range = pos !== -1
  136. ? note.substring(pos + 1, note.length)
  137. : max;
  138. if (typeof range !== 'number') {
  139. range = digitre.test(range)
  140. ? parseInt(range, 10)
  141. : isip(range)
  142. ? parseNetmask(range)
  143. : 0;
  144. }
  145. if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
  146. // Store as IPv4
  147. ip = ip.toIPv4Address();
  148. range = range <= max
  149. ? range - 96
  150. : range;
  151. }
  152. if (range <= 0 || range > max) {
  153. throw new TypeError('invalid range on address: ' + note);
  154. }
  155. return [ip, range];
  156. }
  157. /**
  158. * Parse netmask string into CIDR range.
  159. *
  160. * @param {String} note
  161. * @api private
  162. */
  163. function parseNetmask(netmask) {
  164. var ip = parseip(netmask);
  165. var parts;
  166. var size;
  167. switch (ip.kind()) {
  168. case 'ipv4':
  169. parts = ip.octets;
  170. size = 8;
  171. break;
  172. case 'ipv6':
  173. parts = ip.parts;
  174. size = 16;
  175. break;
  176. }
  177. var max = Math.pow(2, size) - 1;
  178. var part;
  179. var range = 0;
  180. for (var i = 0; i < parts.length; i++) {
  181. part = parts[i] & max;
  182. if (part === max) {
  183. range += size;
  184. continue;
  185. }
  186. while (part) {
  187. part = (part << 1) & max;
  188. range += 1;
  189. }
  190. break;
  191. }
  192. return range;
  193. }
  194. /**
  195. * Determine address of proxied request.
  196. *
  197. * @param {Object} request
  198. * @param {Function|Array|String} trust
  199. * @api public
  200. */
  201. function proxyaddr(req, trust) {
  202. if (!req) {
  203. throw new TypeError('req argument is required');
  204. }
  205. if (!trust) {
  206. throw new TypeError('trust argument is required');
  207. }
  208. var addrs = alladdrs(req, trust);
  209. var addr = addrs[addrs.length - 1];
  210. return addr;
  211. }
  212. /**
  213. * Static trust function to trust nothing.
  214. *
  215. * @api private
  216. */
  217. function trustNone() {
  218. return false;
  219. }
  220. /**
  221. * Compile trust function for multiple subnets.
  222. *
  223. * @param {Array} subnets
  224. * @api private
  225. */
  226. function trustMulti(subnets) {
  227. return function trust(addr) {
  228. if (!isip(addr)) return false;
  229. var ip = parseip(addr);
  230. var ipv4;
  231. var kind = ip.kind();
  232. var subnet;
  233. var subnetip;
  234. var subnetkind;
  235. var subnetrange;
  236. var trusted;
  237. for (var i = 0; i < subnets.length; i++) {
  238. subnet = subnets[i];
  239. subnetip = subnet[0];
  240. subnetkind = subnetip.kind();
  241. subnetrange = subnet[1];
  242. trusted = ip;
  243. if (kind !== subnetkind) {
  244. if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) {
  245. continue;
  246. }
  247. // Store addr as IPv4
  248. ipv4 = ipv4 || ip.toIPv4Address();
  249. trusted = ipv4;
  250. }
  251. if (trusted.match(subnetip, subnetrange)) return true;
  252. }
  253. return false;
  254. };
  255. }
  256. /**
  257. * Compile trust function for single subnet.
  258. *
  259. * @param {Object} subnet
  260. * @api private
  261. */
  262. function trustSingle(subnet) {
  263. var subnetip = subnet[0];
  264. var subnetkind = subnetip.kind();
  265. var subnetisipv4 = subnetkind === 'ipv4';
  266. var subnetrange = subnet[1];
  267. return function trust(addr) {
  268. if (!isip(addr)) return false;
  269. var ip = parseip(addr);
  270. var kind = ip.kind();
  271. return kind === subnetkind
  272. ? ip.match(subnetip, subnetrange)
  273. : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress()
  274. ? ip.toIPv4Address().match(subnetip, subnetrange)
  275. : false;
  276. };
  277. }