inz

wpsess.javascript (raw)

  1. /*
  2.   Copyright 2016 Santtu Lakkala <inz@inz.fi>
  3.  
  4.   Permission is hereby granted, free of charge, to any person obtaining a copy
  5.   of this software and associated documentation files (the "Software"), to
  6.   deal in the Software without restriction, including without limitation the
  7.   rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8.   sell copies of the Software, and to permit persons to whom the Software is
  9.   furnished to do so, subject to the following conditions:
  10.  
  11.   The above copyright notice and this permission notice shall be included in
  12.   all copies or substantial portions of the Software.
  13.  
  14.   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15.   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16.   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17.   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18.   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19.   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20.   IN THE SOFTWARE.
  21. */
  22. (function (xprt) {
  23. var mysql = require('mysql');
  24. var crypto = require('crypto');
  25. var fs = require('fs');
  26. var groan = require('groan');
  27.  
  28. function Validator(conffile) {
  29. var conf_data = fs.readFileSync(conffile, { encoding: 'utf8' });
  30. var re = /define\s*\(\s*(?:'([^']+)'|"([^"]+)")\s*,\s*(?:'([^']+)'|"([^"]+)")\)/gm;
  31. var mtch;
  32.  
  33. var required_fields = [
  34. 'DB_HOST',
  35. 'DB_USER',
  36. 'DB_PASSWORD',
  37. 'DB_NAME',
  38. 'LOGGED_IN_KEY',
  39. 'LOGGED_IN_SALT',
  40. 'table_prefix'
  41. ];
  42.  
  43. this.config = {};
  44.  
  45. while ((mtch = re.exec(conf_data)))
  46. this.config[mtch[1] || mtch[2]] = mtch[3] || mtch[4];
  47. if ((mtch = conf_data.match(/(?:;|^|\n)\s*\$table_prefix\s*=\s*(['"])([a-zA-Z0-9_]+)\1/m)))
  48. this.config.table_prefix = mtch[2];
  49.  
  50. var missing = required_fields.filter((function (rf) { return !this.config.hasOwnProperty(rf); }).bind(this));
  51. if (missing.length > 0)
  52. throw new Error('Fields missing from config: ' + missing.join(', '))
  53.  
  54. this.c = mysql.createPool({
  55. connectionLimit: 10,
  56. host: this.config.DB_HOST,
  57. user: this.config.DB_USER,
  58. password: this.config.DB_PASSWORD,
  59. database: this.config.DB_NAME,
  60. insecureAuth: true
  61. });
  62.  
  63. if (!this.config.COOKIEHASH) {
  64. this.c.query('SELECT MD5(option_value) AS hash FROM ?? WHERE option_name = ?;', [this.config.table_prefix + 'options', 'siteurl'], (function (e, r, f) {
  65. this.config.COOKIEHASH = r[0].hash;
  66. }).bind(this));
  67. }
  68. }
  69.  
  70. Validator.prototype.cookieHash = function () {
  71. return this.config.COOKIEHASH;
  72. }
  73.  
  74. Validator.prototype.authenticate = function (cookies, cb) {
  75. var token;
  76. if ((token = cookies['wordpress_logged_in_' + this.cookieHash()]))
  77. this.validate(token, cb);
  78. else
  79. cb('No cookie', null);
  80. }
  81.  
  82. Validator.prototype.validate = function (token, cb) {
  83. var parts = token.split('|');
  84.  
  85. if (parts.length != 4) {
  86. cb('Invalid cookie', null);
  87. return;
  88. }
  89.  
  90. if (parts[1] * 1000 + 3600000 < new Date()) {
  91. cb('Expired session', null);
  92. return;
  93. }
  94.  
  95. this.c.query('SELECT SUBSTRING(u.user_pass, 9, 4) AS frag, m.meta_value AS tokens FROM ?? u LEFT JOIN ?? m ON u.ID = m.user_id WHERE u.user_login = ? AND m.meta_key = ?;', [this.config.table_prefix + 'users', this.config.table_prefix + 'usermeta', parts[0], 'session_tokens'], (function (e, r, f) {
  96. if (e || r.length == 0) {
  97. cb('User not found', null);
  98. return;
  99. }
  100. try {
  101. var hs_sha256 = crypto.createHash('sha256');
  102. hs_sha256.update(parts[2]);
  103. var tokendata = (groan(r[0].tokens) || {})[hs_sha256.digest('hex')];
  104.  
  105. if (parseInt(parts[1]) !== tokendata.expiration) {
  106. cb('Session data mismatch', null);
  107. return;
  108. }
  109. var hm_md5 = crypto.createHmac('md5', this.config.LOGGED_IN_KEY + this.config.LOGGED_IN_SALT);
  110. hm_md5.update(parts[0] + '|' + r[0].frag + '|' + parts[1] + '|' + parts[2]);
  111. var key = hm_md5.digest('hex');
  112. var hm_sha256 = crypto.createHmac('sha256', key);
  113. hm_sha256.update(parts[0] + '|' + parts[1] + '|' + parts[2]);
  114. } catch (e) {
  115. cb(e.message, null);
  116. return;
  117. }
  118.  
  119. if (parts[3] === hm_sha256.digest('hex'))
  120. cb(null, parts[0]);
  121. else
  122. cb('Cookie checksum mismatch', null);
  123. }).bind(this));
  124. };
  125. xprt.validator = Validator;
  126. })(this);
  127.