utils.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = {
  3. bufferSplit: bufferSplit,
  4. addRSAMissing: addRSAMissing,
  5. calculateDSAPublic: calculateDSAPublic,
  6. calculateED25519Public: calculateED25519Public,
  7. calculateX25519Public: calculateX25519Public,
  8. mpNormalize: mpNormalize,
  9. mpDenormalize: mpDenormalize,
  10. ecNormalize: ecNormalize,
  11. countZeros: countZeros,
  12. assertCompatible: assertCompatible,
  13. isCompatible: isCompatible,
  14. opensslKeyDeriv: opensslKeyDeriv,
  15. opensshCipherInfo: opensshCipherInfo,
  16. publicFromPrivateECDSA: publicFromPrivateECDSA,
  17. zeroPadToLength: zeroPadToLength,
  18. writeBitString: writeBitString,
  19. readBitString: readBitString,
  20. pbkdf2: pbkdf2
  21. };
  22. var assert = require('assert-plus');
  23. var Buffer = require('safer-buffer').Buffer;
  24. var PrivateKey = require('./private-key');
  25. var Key = require('./key');
  26. var crypto = require('crypto');
  27. var algs = require('./algs');
  28. var asn1 = require('asn1');
  29. var ec = require('ecc-jsbn/lib/ec');
  30. var jsbn = require('jsbn').BigInteger;
  31. var nacl = require('tweetnacl');
  32. var MAX_CLASS_DEPTH = 3;
  33. function isCompatible(obj, klass, needVer) {
  34. if (obj === null || typeof (obj) !== 'object')
  35. return (false);
  36. if (needVer === undefined)
  37. needVer = klass.prototype._sshpkApiVersion;
  38. if (obj instanceof klass &&
  39. klass.prototype._sshpkApiVersion[0] == needVer[0])
  40. return (true);
  41. var proto = Object.getPrototypeOf(obj);
  42. var depth = 0;
  43. while (proto.constructor.name !== klass.name) {
  44. proto = Object.getPrototypeOf(proto);
  45. if (!proto || ++depth > MAX_CLASS_DEPTH)
  46. return (false);
  47. }
  48. if (proto.constructor.name !== klass.name)
  49. return (false);
  50. var ver = proto._sshpkApiVersion;
  51. if (ver === undefined)
  52. ver = klass._oldVersionDetect(obj);
  53. if (ver[0] != needVer[0] || ver[1] < needVer[1])
  54. return (false);
  55. return (true);
  56. }
  57. function assertCompatible(obj, klass, needVer, name) {
  58. if (name === undefined)
  59. name = 'object';
  60. assert.ok(obj, name + ' must not be null');
  61. assert.object(obj, name + ' must be an object');
  62. if (needVer === undefined)
  63. needVer = klass.prototype._sshpkApiVersion;
  64. if (obj instanceof klass &&
  65. klass.prototype._sshpkApiVersion[0] == needVer[0])
  66. return;
  67. var proto = Object.getPrototypeOf(obj);
  68. var depth = 0;
  69. while (proto.constructor.name !== klass.name) {
  70. proto = Object.getPrototypeOf(proto);
  71. assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
  72. name + ' must be a ' + klass.name + ' instance');
  73. }
  74. assert.strictEqual(proto.constructor.name, klass.name,
  75. name + ' must be a ' + klass.name + ' instance');
  76. var ver = proto._sshpkApiVersion;
  77. if (ver === undefined)
  78. ver = klass._oldVersionDetect(obj);
  79. assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
  80. name + ' must be compatible with ' + klass.name + ' klass ' +
  81. 'version ' + needVer[0] + '.' + needVer[1]);
  82. }
  83. var CIPHER_LEN = {
  84. 'des-ede3-cbc': { key: 24, iv: 8 },
  85. 'aes-128-cbc': { key: 16, iv: 16 },
  86. 'aes-256-cbc': { key: 32, iv: 16 }
  87. };
  88. var PKCS5_SALT_LEN = 8;
  89. function opensslKeyDeriv(cipher, salt, passphrase, count) {
  90. assert.buffer(salt, 'salt');
  91. assert.buffer(passphrase, 'passphrase');
  92. assert.number(count, 'iteration count');
  93. var clen = CIPHER_LEN[cipher];
  94. assert.object(clen, 'supported cipher');
  95. salt = salt.slice(0, PKCS5_SALT_LEN);
  96. var D, D_prev, bufs;
  97. var material = Buffer.alloc(0);
  98. while (material.length < clen.key + clen.iv) {
  99. bufs = [];
  100. if (D_prev)
  101. bufs.push(D_prev);
  102. bufs.push(passphrase);
  103. bufs.push(salt);
  104. D = Buffer.concat(bufs);
  105. for (var j = 0; j < count; ++j)
  106. D = crypto.createHash('md5').update(D).digest();
  107. material = Buffer.concat([material, D]);
  108. D_prev = D;
  109. }
  110. return ({
  111. key: material.slice(0, clen.key),
  112. iv: material.slice(clen.key, clen.key + clen.iv)
  113. });
  114. }
  115. /* See: RFC2898 */
  116. function pbkdf2(hashAlg, salt, iterations, size, passphrase) {
  117. var hkey = Buffer.alloc(salt.length + 4);
  118. salt.copy(hkey);
  119. var gen = 0, ts = [];
  120. var i = 1;
  121. while (gen < size) {
  122. var t = T(i++);
  123. gen += t.length;
  124. ts.push(t);
  125. }
  126. return (Buffer.concat(ts).slice(0, size));
  127. function T(I) {
  128. hkey.writeUInt32BE(I, hkey.length - 4);
  129. var hmac = crypto.createHmac(hashAlg, passphrase);
  130. hmac.update(hkey);
  131. var Ti = hmac.digest();
  132. var Uc = Ti;
  133. var c = 1;
  134. while (c++ < iterations) {
  135. hmac = crypto.createHmac(hashAlg, passphrase);
  136. hmac.update(Uc);
  137. Uc = hmac.digest();
  138. for (var x = 0; x < Ti.length; ++x)
  139. Ti[x] ^= Uc[x];
  140. }
  141. return (Ti);
  142. }
  143. }
  144. /* Count leading zero bits on a buffer */
  145. function countZeros(buf) {
  146. var o = 0, obit = 8;
  147. while (o < buf.length) {
  148. var mask = (1 << obit);
  149. if ((buf[o] & mask) === mask)
  150. break;
  151. obit--;
  152. if (obit < 0) {
  153. o++;
  154. obit = 8;
  155. }
  156. }
  157. return (o*8 + (8 - obit) - 1);
  158. }
  159. function bufferSplit(buf, chr) {
  160. assert.buffer(buf);
  161. assert.string(chr);
  162. var parts = [];
  163. var lastPart = 0;
  164. var matches = 0;
  165. for (var i = 0; i < buf.length; ++i) {
  166. if (buf[i] === chr.charCodeAt(matches))
  167. ++matches;
  168. else if (buf[i] === chr.charCodeAt(0))
  169. matches = 1;
  170. else
  171. matches = 0;
  172. if (matches >= chr.length) {
  173. var newPart = i + 1;
  174. parts.push(buf.slice(lastPart, newPart - matches));
  175. lastPart = newPart;
  176. matches = 0;
  177. }
  178. }
  179. if (lastPart <= buf.length)
  180. parts.push(buf.slice(lastPart, buf.length));
  181. return (parts);
  182. }
  183. function ecNormalize(buf, addZero) {
  184. assert.buffer(buf);
  185. if (buf[0] === 0x00 && buf[1] === 0x04) {
  186. if (addZero)
  187. return (buf);
  188. return (buf.slice(1));
  189. } else if (buf[0] === 0x04) {
  190. if (!addZero)
  191. return (buf);
  192. } else {
  193. while (buf[0] === 0x00)
  194. buf = buf.slice(1);
  195. if (buf[0] === 0x02 || buf[0] === 0x03)
  196. throw (new Error('Compressed elliptic curve points ' +
  197. 'are not supported'));
  198. if (buf[0] !== 0x04)
  199. throw (new Error('Not a valid elliptic curve point'));
  200. if (!addZero)
  201. return (buf);
  202. }
  203. var b = Buffer.alloc(buf.length + 1);
  204. b[0] = 0x0;
  205. buf.copy(b, 1);
  206. return (b);
  207. }
  208. function readBitString(der, tag) {
  209. if (tag === undefined)
  210. tag = asn1.Ber.BitString;
  211. var buf = der.readString(tag, true);
  212. assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' +
  213. 'not supported (0x' + buf[0].toString(16) + ')');
  214. return (buf.slice(1));
  215. }
  216. function writeBitString(der, buf, tag) {
  217. if (tag === undefined)
  218. tag = asn1.Ber.BitString;
  219. var b = Buffer.alloc(buf.length + 1);
  220. b[0] = 0x00;
  221. buf.copy(b, 1);
  222. der.writeBuffer(b, tag);
  223. }
  224. function mpNormalize(buf) {
  225. assert.buffer(buf);
  226. while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
  227. buf = buf.slice(1);
  228. if ((buf[0] & 0x80) === 0x80) {
  229. var b = Buffer.alloc(buf.length + 1);
  230. b[0] = 0x00;
  231. buf.copy(b, 1);
  232. buf = b;
  233. }
  234. return (buf);
  235. }
  236. function mpDenormalize(buf) {
  237. assert.buffer(buf);
  238. while (buf.length > 1 && buf[0] === 0x00)
  239. buf = buf.slice(1);
  240. return (buf);
  241. }
  242. function zeroPadToLength(buf, len) {
  243. assert.buffer(buf);
  244. assert.number(len);
  245. while (buf.length > len) {
  246. assert.equal(buf[0], 0x00);
  247. buf = buf.slice(1);
  248. }
  249. while (buf.length < len) {
  250. var b = Buffer.alloc(buf.length + 1);
  251. b[0] = 0x00;
  252. buf.copy(b, 1);
  253. buf = b;
  254. }
  255. return (buf);
  256. }
  257. function bigintToMpBuf(bigint) {
  258. var buf = Buffer.from(bigint.toByteArray());
  259. buf = mpNormalize(buf);
  260. return (buf);
  261. }
  262. function calculateDSAPublic(g, p, x) {
  263. assert.buffer(g);
  264. assert.buffer(p);
  265. assert.buffer(x);
  266. g = new jsbn(g);
  267. p = new jsbn(p);
  268. x = new jsbn(x);
  269. var y = g.modPow(x, p);
  270. var ybuf = bigintToMpBuf(y);
  271. return (ybuf);
  272. }
  273. function calculateED25519Public(k) {
  274. assert.buffer(k);
  275. var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k));
  276. return (Buffer.from(kp.publicKey));
  277. }
  278. function calculateX25519Public(k) {
  279. assert.buffer(k);
  280. var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k));
  281. return (Buffer.from(kp.publicKey));
  282. }
  283. function addRSAMissing(key) {
  284. assert.object(key);
  285. assertCompatible(key, PrivateKey, [1, 1]);
  286. var d = new jsbn(key.part.d.data);
  287. var buf;
  288. if (!key.part.dmodp) {
  289. var p = new jsbn(key.part.p.data);
  290. var dmodp = d.mod(p.subtract(1));
  291. buf = bigintToMpBuf(dmodp);
  292. key.part.dmodp = {name: 'dmodp', data: buf};
  293. key.parts.push(key.part.dmodp);
  294. }
  295. if (!key.part.dmodq) {
  296. var q = new jsbn(key.part.q.data);
  297. var dmodq = d.mod(q.subtract(1));
  298. buf = bigintToMpBuf(dmodq);
  299. key.part.dmodq = {name: 'dmodq', data: buf};
  300. key.parts.push(key.part.dmodq);
  301. }
  302. }
  303. function publicFromPrivateECDSA(curveName, priv) {
  304. assert.string(curveName, 'curveName');
  305. assert.buffer(priv);
  306. var params = algs.curves[curveName];
  307. var p = new jsbn(params.p);
  308. var a = new jsbn(params.a);
  309. var b = new jsbn(params.b);
  310. var curve = new ec.ECCurveFp(p, a, b);
  311. var G = curve.decodePointHex(params.G.toString('hex'));
  312. var d = new jsbn(mpNormalize(priv));
  313. var pub = G.multiply(d);
  314. pub = Buffer.from(curve.encodePointHex(pub), 'hex');
  315. var parts = [];
  316. parts.push({name: 'curve', data: Buffer.from(curveName)});
  317. parts.push({name: 'Q', data: pub});
  318. var key = new Key({type: 'ecdsa', curve: curve, parts: parts});
  319. return (key);
  320. }
  321. function opensshCipherInfo(cipher) {
  322. var inf = {};
  323. switch (cipher) {
  324. case '3des-cbc':
  325. inf.keySize = 24;
  326. inf.blockSize = 8;
  327. inf.opensslName = 'des-ede3-cbc';
  328. break;
  329. case 'blowfish-cbc':
  330. inf.keySize = 16;
  331. inf.blockSize = 8;
  332. inf.opensslName = 'bf-cbc';
  333. break;
  334. case 'aes128-cbc':
  335. case 'aes128-ctr':
  336. case 'aes128-gcm@openssh.com':
  337. inf.keySize = 16;
  338. inf.blockSize = 16;
  339. inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
  340. break;
  341. case 'aes192-cbc':
  342. case 'aes192-ctr':
  343. case 'aes192-gcm@openssh.com':
  344. inf.keySize = 24;
  345. inf.blockSize = 16;
  346. inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
  347. break;
  348. case 'aes256-cbc':
  349. case 'aes256-ctr':
  350. case 'aes256-gcm@openssh.com':
  351. inf.keySize = 32;
  352. inf.blockSize = 16;
  353. inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
  354. break;
  355. default:
  356. throw (new Error(
  357. 'Unsupported openssl cipher "' + cipher + '"'));
  358. }
  359. return (inf);
  360. }