utils.js 9.3 KB

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