server.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. 'use strict';
  2. // Load modules
  3. const Boom = require('boom');
  4. const Hoek = require('hoek');
  5. const Cryptiles = require('cryptiles');
  6. const Crypto = require('./crypto');
  7. const Utils = require('./utils');
  8. // Declare internals
  9. const internals = {};
  10. // Hawk authentication
  11. /*
  12. req: node's HTTP request object or an object as follows:
  13. const request = {
  14. method: 'GET',
  15. url: '/resource/4?a=1&b=2',
  16. host: 'example.com',
  17. port: 8080,
  18. authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'
  19. };
  20. credentialsFunc: required function to lookup the set of Hawk credentials based on the provided credentials id.
  21. The credentials include the MAC key, MAC algorithm, and other attributes (such as username)
  22. needed by the application. This function is the equivalent of verifying the username and
  23. password in Basic authentication.
  24. const credentialsFunc = function (id, callback) {
  25. // Lookup credentials in database
  26. db.lookup(id, function (err, item) {
  27. if (err || !item) {
  28. return callback(err);
  29. }
  30. const credentials = {
  31. // Required
  32. key: item.key,
  33. algorithm: item.algorithm,
  34. // Application specific
  35. user: item.user
  36. };
  37. return callback(null, credentials);
  38. });
  39. };
  40. options: {
  41. hostHeaderName: optional header field name, used to override the default 'Host' header when used
  42. behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving
  43. the original (which is what the module must verify) in the 'x-forwarded-host' header field.
  44. Only used when passed a node Http.ServerRequest object.
  45. nonceFunc: optional nonce validation function. The function signature is function(key, nonce, ts, callback)
  46. where 'callback' must be called using the signature function(err).
  47. timestampSkewSec: optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds.
  48. Provides a +/- skew which means actual allowed window is double the number of seconds.
  49. localtimeOffsetMsec: optional local clock time offset express in a number of milliseconds (positive or negative).
  50. Defaults to 0.
  51. payload: optional payload for validation. The client calculates the hash value and includes it via the 'hash'
  52. header attribute. The server always ensures the value provided has been included in the request
  53. MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating
  54. a hash value over the entire payload (assuming it has already be normalized to the same format and
  55. encoding used by the client to calculate the hash on request). If the payload is not available at the time
  56. of authentication, the authenticatePayload() method can be used by passing it the credentials and
  57. attributes.hash returned in the authenticate callback.
  58. host: optional host name override. Only used when passed a node request object.
  59. port: optional port override. Only used when passed a node request object.
  60. }
  61. callback: function (err, credentials, artifacts) { }
  62. */
  63. exports.authenticate = function (req, credentialsFunc, options, callback) {
  64. callback = Hoek.nextTick(callback);
  65. // Default options
  66. options.nonceFunc = options.nonceFunc || internals.nonceFunc;
  67. options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
  68. // Application time
  69. const now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
  70. // Convert node Http request object to a request configuration object
  71. const request = Utils.parseRequest(req, options);
  72. if (request instanceof Error) {
  73. return callback(Boom.badRequest(request.message));
  74. }
  75. // Parse HTTP Authorization header
  76. const attributes = Utils.parseAuthorizationHeader(request.authorization);
  77. if (attributes instanceof Error) {
  78. return callback(attributes);
  79. }
  80. // Construct artifacts container
  81. const artifacts = {
  82. method: request.method,
  83. host: request.host,
  84. port: request.port,
  85. resource: request.url,
  86. ts: attributes.ts,
  87. nonce: attributes.nonce,
  88. hash: attributes.hash,
  89. ext: attributes.ext,
  90. app: attributes.app,
  91. dlg: attributes.dlg,
  92. mac: attributes.mac,
  93. id: attributes.id
  94. };
  95. // Verify required header attributes
  96. if (!attributes.id ||
  97. !attributes.ts ||
  98. !attributes.nonce ||
  99. !attributes.mac) {
  100. return callback(Boom.badRequest('Missing attributes'), null, artifacts);
  101. }
  102. // Fetch Hawk credentials
  103. credentialsFunc(attributes.id, (err, credentials) => {
  104. if (err) {
  105. return callback(err, credentials || null, artifacts);
  106. }
  107. if (!credentials) {
  108. return callback(Utils.unauthorized('Unknown credentials'), null, artifacts);
  109. }
  110. if (!credentials.key ||
  111. !credentials.algorithm) {
  112. return callback(Boom.internal('Invalid credentials'), credentials, artifacts);
  113. }
  114. if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
  115. return callback(Boom.internal('Unknown algorithm'), credentials, artifacts);
  116. }
  117. // Calculate MAC
  118. const mac = Crypto.calculateMac('header', credentials, artifacts);
  119. if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) {
  120. return callback(Utils.unauthorized('Bad mac'), credentials, artifacts);
  121. }
  122. // Check payload hash
  123. if (options.payload ||
  124. options.payload === '') {
  125. if (!attributes.hash) {
  126. return callback(Utils.unauthorized('Missing required payload hash'), credentials, artifacts);
  127. }
  128. const hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType);
  129. if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) {
  130. return callback(Utils.unauthorized('Bad payload hash'), credentials, artifacts);
  131. }
  132. }
  133. // Check nonce
  134. options.nonceFunc(credentials.key, attributes.nonce, attributes.ts, (err) => {
  135. if (err) {
  136. return callback(Utils.unauthorized('Invalid nonce'), credentials, artifacts);
  137. }
  138. // Check timestamp staleness
  139. if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
  140. const tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec);
  141. return callback(Utils.unauthorized('Stale timestamp', tsm), credentials, artifacts);
  142. }
  143. // Successful authentication
  144. return callback(null, credentials, artifacts);
  145. });
  146. });
  147. };
  148. // Authenticate payload hash - used when payload cannot be provided during authenticate()
  149. /*
  150. payload: raw request payload
  151. credentials: from authenticate callback
  152. artifacts: from authenticate callback
  153. contentType: req.headers['content-type']
  154. */
  155. exports.authenticatePayload = function (payload, credentials, artifacts, contentType) {
  156. const calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType);
  157. return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
  158. };
  159. // Authenticate payload hash - used when payload cannot be provided during authenticate()
  160. /*
  161. calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
  162. artifacts: from authenticate callback
  163. */
  164. exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
  165. return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
  166. };
  167. // Generate a Server-Authorization header for a given response
  168. /*
  169. credentials: {}, // Object received from authenticate()
  170. artifacts: {} // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored
  171. options: {
  172. ext: 'application-specific', // Application specific data sent via the ext attribute
  173. payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
  174. contentType: 'application/json', // Payload content-type (ignored if hash provided)
  175. hash: 'U4MKKSmiVxk37JCCrAVIjV=' // Pre-calculated payload hash
  176. }
  177. */
  178. exports.header = function (credentials, artifacts, options) {
  179. // Prepare inputs
  180. options = options || {};
  181. if (!artifacts ||
  182. typeof artifacts !== 'object' ||
  183. typeof options !== 'object') {
  184. return '';
  185. }
  186. artifacts = Hoek.clone(artifacts);
  187. delete artifacts.mac;
  188. artifacts.hash = options.hash;
  189. artifacts.ext = options.ext;
  190. // Validate credentials
  191. if (!credentials ||
  192. !credentials.key ||
  193. !credentials.algorithm) {
  194. // Invalid credential object
  195. return '';
  196. }
  197. if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
  198. return '';
  199. }
  200. // Calculate payload hash
  201. if (!artifacts.hash &&
  202. (options.payload || options.payload === '')) {
  203. artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
  204. }
  205. const mac = Crypto.calculateMac('response', credentials, artifacts);
  206. // Construct header
  207. let header = 'Hawk mac="' + mac + '"' +
  208. (artifacts.hash ? ', hash="' + artifacts.hash + '"' : '');
  209. if (artifacts.ext !== null &&
  210. artifacts.ext !== undefined &&
  211. artifacts.ext !== '') { // Other falsey values allowed
  212. header = header + ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
  213. }
  214. return header;
  215. };
  216. /*
  217. * Arguments and options are the same as authenticate() with the exception that the only supported options are:
  218. * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port'
  219. */
  220. // 1 2 3 4
  221. internals.bewitRegex = /^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/;
  222. exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
  223. callback = Hoek.nextTick(callback);
  224. // Application time
  225. const now = Utils.now(options.localtimeOffsetMsec);
  226. // Convert node Http request object to a request configuration object
  227. const request = Utils.parseRequest(req, options);
  228. if (request instanceof Error) {
  229. return callback(Boom.badRequest(request.message));
  230. }
  231. // Extract bewit
  232. if (request.url.length > Utils.limits.maxMatchLength) {
  233. return callback(Boom.badRequest('Resource path exceeds max length'));
  234. }
  235. const resource = request.url.match(internals.bewitRegex);
  236. if (!resource) {
  237. return callback(Utils.unauthorized());
  238. }
  239. // Bewit not empty
  240. if (!resource[3]) {
  241. return callback(Utils.unauthorized('Empty bewit'));
  242. }
  243. // Verify method is GET
  244. if (request.method !== 'GET' &&
  245. request.method !== 'HEAD') {
  246. return callback(Utils.unauthorized('Invalid method'));
  247. }
  248. // No other authentication
  249. if (request.authorization) {
  250. return callback(Boom.badRequest('Multiple authentications'));
  251. }
  252. // Parse bewit
  253. const bewitString = Hoek.base64urlDecode(resource[3]);
  254. if (bewitString instanceof Error) {
  255. return callback(Boom.badRequest('Invalid bewit encoding'));
  256. }
  257. // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
  258. const bewitParts = bewitString.split('\\');
  259. if (bewitParts.length !== 4) {
  260. return callback(Boom.badRequest('Invalid bewit structure'));
  261. }
  262. const bewit = {
  263. id: bewitParts[0],
  264. exp: parseInt(bewitParts[1], 10),
  265. mac: bewitParts[2],
  266. ext: bewitParts[3] || ''
  267. };
  268. if (!bewit.id ||
  269. !bewit.exp ||
  270. !bewit.mac) {
  271. return callback(Boom.badRequest('Missing bewit attributes'));
  272. }
  273. // Construct URL without bewit
  274. let url = resource[1];
  275. if (resource[4]) {
  276. url = url + resource[2] + resource[4];
  277. }
  278. // Check expiration
  279. if (bewit.exp * 1000 <= now) {
  280. return callback(Utils.unauthorized('Access expired'), null, bewit);
  281. }
  282. // Fetch Hawk credentials
  283. credentialsFunc(bewit.id, (err, credentials) => {
  284. if (err) {
  285. return callback(err, credentials || null, bewit.ext);
  286. }
  287. if (!credentials) {
  288. return callback(Utils.unauthorized('Unknown credentials'), null, bewit);
  289. }
  290. if (!credentials.key ||
  291. !credentials.algorithm) {
  292. return callback(Boom.internal('Invalid credentials'), credentials, bewit);
  293. }
  294. if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
  295. return callback(Boom.internal('Unknown algorithm'), credentials, bewit);
  296. }
  297. // Calculate MAC
  298. const mac = Crypto.calculateMac('bewit', credentials, {
  299. ts: bewit.exp,
  300. nonce: '',
  301. method: 'GET',
  302. resource: url,
  303. host: request.host,
  304. port: request.port,
  305. ext: bewit.ext
  306. });
  307. if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) {
  308. return callback(Utils.unauthorized('Bad mac'), credentials, bewit);
  309. }
  310. // Successful authentication
  311. return callback(null, credentials, bewit);
  312. });
  313. };
  314. /*
  315. * options are the same as authenticate() with the exception that the only supported options are:
  316. * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec'
  317. */
  318. exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
  319. callback = Hoek.nextTick(callback);
  320. // Default options
  321. options.nonceFunc = options.nonceFunc || internals.nonceFunc;
  322. options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds
  323. // Application time
  324. const now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
  325. // Validate authorization
  326. if (!authorization.id ||
  327. !authorization.ts ||
  328. !authorization.nonce ||
  329. !authorization.hash ||
  330. !authorization.mac) {
  331. return callback(Boom.badRequest('Invalid authorization'));
  332. }
  333. // Fetch Hawk credentials
  334. credentialsFunc(authorization.id, (err, credentials) => {
  335. if (err) {
  336. return callback(err, credentials || null);
  337. }
  338. if (!credentials) {
  339. return callback(Utils.unauthorized('Unknown credentials'));
  340. }
  341. if (!credentials.key ||
  342. !credentials.algorithm) {
  343. return callback(Boom.internal('Invalid credentials'), credentials);
  344. }
  345. if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
  346. return callback(Boom.internal('Unknown algorithm'), credentials);
  347. }
  348. // Construct artifacts container
  349. const artifacts = {
  350. ts: authorization.ts,
  351. nonce: authorization.nonce,
  352. host,
  353. port,
  354. hash: authorization.hash
  355. };
  356. // Calculate MAC
  357. const mac = Crypto.calculateMac('message', credentials, artifacts);
  358. if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) {
  359. return callback(Utils.unauthorized('Bad mac'), credentials);
  360. }
  361. // Check payload hash
  362. const hash = Crypto.calculatePayloadHash(message, credentials.algorithm);
  363. if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) {
  364. return callback(Utils.unauthorized('Bad message hash'), credentials);
  365. }
  366. // Check nonce
  367. options.nonceFunc(credentials.key, authorization.nonce, authorization.ts, (err) => {
  368. if (err) {
  369. return callback(Utils.unauthorized('Invalid nonce'), credentials);
  370. }
  371. // Check timestamp staleness
  372. if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
  373. return callback(Utils.unauthorized('Stale timestamp'), credentials);
  374. }
  375. // Successful authentication
  376. return callback(null, credentials);
  377. });
  378. });
  379. };
  380. internals.nonceFunc = function (key, nonce, ts, nonceCallback) {
  381. return nonceCallback(); // No validation
  382. };