utils.js 9.4 KB

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