utils.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = {
  3. bufferSplit: bufferSplit,
  4. addRSAMissing: addRSAMissing,
  5. calculateDSAPublic: calculateDSAPublic,
  6. mpNormalize: mpNormalize,
  7. ecNormalize: ecNormalize,
  8. countZeros: countZeros,
  9. assertCompatible: assertCompatible,
  10. isCompatible: isCompatible,
  11. opensslKeyDeriv: opensslKeyDeriv,
  12. opensshCipherInfo: opensshCipherInfo
  13. };
  14. var assert = require('assert-plus');
  15. var PrivateKey = require('./private-key');
  16. var crypto = require('crypto');
  17. var MAX_CLASS_DEPTH = 3;
  18. function isCompatible(obj, klass, needVer) {
  19. if (obj === null || typeof (obj) !== 'object')
  20. return (false);
  21. if (needVer === undefined)
  22. needVer = klass.prototype._sshpkApiVersion;
  23. if (obj instanceof klass &&
  24. klass.prototype._sshpkApiVersion[0] == needVer[0])
  25. return (true);
  26. var proto = Object.getPrototypeOf(obj);
  27. var depth = 0;
  28. while (proto.constructor.name !== klass.name) {
  29. proto = Object.getPrototypeOf(proto);
  30. if (!proto || ++depth > MAX_CLASS_DEPTH)
  31. return (false);
  32. }
  33. if (proto.constructor.name !== klass.name)
  34. return (false);
  35. var ver = proto._sshpkApiVersion;
  36. if (ver === undefined)
  37. ver = klass._oldVersionDetect(obj);
  38. if (ver[0] != needVer[0] || ver[1] < needVer[1])
  39. return (false);
  40. return (true);
  41. }
  42. function assertCompatible(obj, klass, needVer, name) {
  43. if (name === undefined)
  44. name = 'object';
  45. assert.ok(obj, name + ' must not be null');
  46. assert.object(obj, name + ' must be an object');
  47. if (needVer === undefined)
  48. needVer = klass.prototype._sshpkApiVersion;
  49. if (obj instanceof klass &&
  50. klass.prototype._sshpkApiVersion[0] == needVer[0])
  51. return;
  52. var proto = Object.getPrototypeOf(obj);
  53. var depth = 0;
  54. while (proto.constructor.name !== klass.name) {
  55. proto = Object.getPrototypeOf(proto);
  56. assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
  57. name + ' must be a ' + klass.name + ' instance');
  58. }
  59. assert.strictEqual(proto.constructor.name, klass.name,
  60. name + ' must be a ' + klass.name + ' instance');
  61. var ver = proto._sshpkApiVersion;
  62. if (ver === undefined)
  63. ver = klass._oldVersionDetect(obj);
  64. assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
  65. name + ' must be compatible with ' + klass.name + ' klass ' +
  66. 'version ' + needVer[0] + '.' + needVer[1]);
  67. }
  68. var CIPHER_LEN = {
  69. 'des-ede3-cbc': { key: 7, iv: 8 },
  70. 'aes-128-cbc': { key: 16, iv: 16 }
  71. };
  72. var PKCS5_SALT_LEN = 8;
  73. function opensslKeyDeriv(cipher, salt, passphrase, count) {
  74. assert.buffer(salt, 'salt');
  75. assert.buffer(passphrase, 'passphrase');
  76. assert.number(count, 'iteration count');
  77. var clen = CIPHER_LEN[cipher];
  78. assert.object(clen, 'supported cipher');
  79. salt = salt.slice(0, PKCS5_SALT_LEN);
  80. var D, D_prev, bufs;
  81. var material = new Buffer(0);
  82. while (material.length < clen.key + clen.iv) {
  83. bufs = [];
  84. if (D_prev)
  85. bufs.push(D_prev);
  86. bufs.push(passphrase);
  87. bufs.push(salt);
  88. D = Buffer.concat(bufs);
  89. for (var j = 0; j < count; ++j)
  90. D = crypto.createHash('md5').update(D).digest();
  91. material = Buffer.concat([material, D]);
  92. D_prev = D;
  93. }
  94. return ({
  95. key: material.slice(0, clen.key),
  96. iv: material.slice(clen.key, clen.key + clen.iv)
  97. });
  98. }
  99. /* Count leading zero bits on a buffer */
  100. function countZeros(buf) {
  101. var o = 0, obit = 8;
  102. while (o < buf.length) {
  103. var mask = (1 << obit);
  104. if ((buf[o] & mask) === mask)
  105. break;
  106. obit--;
  107. if (obit < 0) {
  108. o++;
  109. obit = 8;
  110. }
  111. }
  112. return (o*8 + (8 - obit) - 1);
  113. }
  114. function bufferSplit(buf, chr) {
  115. assert.buffer(buf);
  116. assert.string(chr);
  117. var parts = [];
  118. var lastPart = 0;
  119. var matches = 0;
  120. for (var i = 0; i < buf.length; ++i) {
  121. if (buf[i] === chr.charCodeAt(matches))
  122. ++matches;
  123. else if (buf[i] === chr.charCodeAt(0))
  124. matches = 1;
  125. else
  126. matches = 0;
  127. if (matches >= chr.length) {
  128. var newPart = i + 1;
  129. parts.push(buf.slice(lastPart, newPart - matches));
  130. lastPart = newPart;
  131. matches = 0;
  132. }
  133. }
  134. if (lastPart <= buf.length)
  135. parts.push(buf.slice(lastPart, buf.length));
  136. return (parts);
  137. }
  138. function ecNormalize(buf, addZero) {
  139. assert.buffer(buf);
  140. if (buf[0] === 0x00 && buf[1] === 0x04) {
  141. if (addZero)
  142. return (buf);
  143. return (buf.slice(1));
  144. } else if (buf[0] === 0x04) {
  145. if (!addZero)
  146. return (buf);
  147. } else {
  148. while (buf[0] === 0x00)
  149. buf = buf.slice(1);
  150. if (buf[0] === 0x02 || buf[0] === 0x03)
  151. throw (new Error('Compressed elliptic curve points ' +
  152. 'are not supported'));
  153. if (buf[0] !== 0x04)
  154. throw (new Error('Not a valid elliptic curve point'));
  155. if (!addZero)
  156. return (buf);
  157. }
  158. var b = new Buffer(buf.length + 1);
  159. b[0] = 0x0;
  160. buf.copy(b, 1);
  161. return (b);
  162. }
  163. function mpNormalize(buf) {
  164. assert.buffer(buf);
  165. while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
  166. buf = buf.slice(1);
  167. if ((buf[0] & 0x80) === 0x80) {
  168. var b = new Buffer(buf.length + 1);
  169. b[0] = 0x00;
  170. buf.copy(b, 1);
  171. buf = b;
  172. }
  173. return (buf);
  174. }
  175. function bigintToMpBuf(bigint) {
  176. var buf = new Buffer(bigint.toByteArray());
  177. buf = mpNormalize(buf);
  178. return (buf);
  179. }
  180. function calculateDSAPublic(g, p, x) {
  181. assert.buffer(g);
  182. assert.buffer(p);
  183. assert.buffer(x);
  184. try {
  185. var bigInt = require('jsbn').BigInteger;
  186. } catch (e) {
  187. throw (new Error('To load a PKCS#8 format DSA private key, ' +
  188. 'the node jsbn library is required.'));
  189. }
  190. g = new bigInt(g);
  191. p = new bigInt(p);
  192. x = new bigInt(x);
  193. var y = g.modPow(x, p);
  194. var ybuf = bigintToMpBuf(y);
  195. return (ybuf);
  196. }
  197. function addRSAMissing(key) {
  198. assert.object(key);
  199. assertCompatible(key, PrivateKey, [1, 1]);
  200. try {
  201. var bigInt = require('jsbn').BigInteger;
  202. } catch (e) {
  203. throw (new Error('To write a PEM private key from ' +
  204. 'this source, the node jsbn lib is required.'));
  205. }
  206. var d = new bigInt(key.part.d.data);
  207. var buf;
  208. if (!key.part.dmodp) {
  209. var p = new bigInt(key.part.p.data);
  210. var dmodp = d.mod(p.subtract(1));
  211. buf = bigintToMpBuf(dmodp);
  212. key.part.dmodp = {name: 'dmodp', data: buf};
  213. key.parts.push(key.part.dmodp);
  214. }
  215. if (!key.part.dmodq) {
  216. var q = new bigInt(key.part.q.data);
  217. var dmodq = d.mod(q.subtract(1));
  218. buf = bigintToMpBuf(dmodq);
  219. key.part.dmodq = {name: 'dmodq', data: buf};
  220. key.parts.push(key.part.dmodq);
  221. }
  222. }
  223. function opensshCipherInfo(cipher) {
  224. var inf = {};
  225. switch (cipher) {
  226. case '3des-cbc':
  227. inf.keySize = 24;
  228. inf.blockSize = 8;
  229. inf.opensslName = 'des-ede3-cbc';
  230. break;
  231. case 'blowfish-cbc':
  232. inf.keySize = 16;
  233. inf.blockSize = 8;
  234. inf.opensslName = 'bf-cbc';
  235. break;
  236. case 'aes128-cbc':
  237. case 'aes128-ctr':
  238. case 'aes128-gcm@openssh.com':
  239. inf.keySize = 16;
  240. inf.blockSize = 16;
  241. inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
  242. break;
  243. case 'aes192-cbc':
  244. case 'aes192-ctr':
  245. case 'aes192-gcm@openssh.com':
  246. inf.keySize = 24;
  247. inf.blockSize = 16;
  248. inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
  249. break;
  250. case 'aes256-cbc':
  251. case 'aes256-ctr':
  252. case 'aes256-gcm@openssh.com':
  253. inf.keySize = 32;
  254. inf.blockSize = 16;
  255. inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
  256. break;
  257. default:
  258. throw (new Error(
  259. 'Unsupported openssl cipher "' + cipher + '"'));
  260. }
  261. return (inf);
  262. }