key.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = Key;
  3. var assert = require('assert-plus');
  4. var algs = require('./algs');
  5. var crypto = require('crypto');
  6. var Fingerprint = require('./fingerprint');
  7. var Signature = require('./signature');
  8. var DiffieHellman = require('./dhe');
  9. var errs = require('./errors');
  10. var utils = require('./utils');
  11. var PrivateKey = require('./private-key');
  12. var edCompat;
  13. try {
  14. edCompat = require('./ed-compat');
  15. } catch (e) {
  16. /* Just continue through, and bail out if we try to use it. */
  17. }
  18. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  19. var KeyParseError = errs.KeyParseError;
  20. var formats = {};
  21. formats['auto'] = require('./formats/auto');
  22. formats['pem'] = require('./formats/pem');
  23. formats['pkcs1'] = require('./formats/pkcs1');
  24. formats['pkcs8'] = require('./formats/pkcs8');
  25. formats['rfc4253'] = require('./formats/rfc4253');
  26. formats['ssh'] = require('./formats/ssh');
  27. formats['ssh-private'] = require('./formats/ssh-private');
  28. formats['openssh'] = formats['ssh-private'];
  29. function Key(opts) {
  30. assert.object(opts, 'options');
  31. assert.arrayOfObject(opts.parts, 'options.parts');
  32. assert.string(opts.type, 'options.type');
  33. assert.optionalString(opts.comment, 'options.comment');
  34. var algInfo = algs.info[opts.type];
  35. if (typeof (algInfo) !== 'object')
  36. throw (new InvalidAlgorithmError(opts.type));
  37. var partLookup = {};
  38. for (var i = 0; i < opts.parts.length; ++i) {
  39. var part = opts.parts[i];
  40. partLookup[part.name] = part;
  41. }
  42. this.type = opts.type;
  43. this.parts = opts.parts;
  44. this.part = partLookup;
  45. this.comment = undefined;
  46. this.source = opts.source;
  47. /* for speeding up hashing/fingerprint operations */
  48. this._rfc4253Cache = opts._rfc4253Cache;
  49. this._hashCache = {};
  50. var sz;
  51. this.curve = undefined;
  52. if (this.type === 'ecdsa') {
  53. var curve = this.part.curve.data.toString();
  54. this.curve = curve;
  55. sz = algs.curves[curve].size;
  56. } else if (this.type === 'ed25519') {
  57. sz = 256;
  58. this.curve = 'curve25519';
  59. } else {
  60. var szPart = this.part[algInfo.sizePart];
  61. sz = szPart.data.length;
  62. sz = sz * 8 - utils.countZeros(szPart.data);
  63. }
  64. this.size = sz;
  65. }
  66. Key.formats = formats;
  67. Key.prototype.toBuffer = function (format, options) {
  68. if (format === undefined)
  69. format = 'ssh';
  70. assert.string(format, 'format');
  71. assert.object(formats[format], 'formats[format]');
  72. assert.optionalObject(options, 'options');
  73. if (format === 'rfc4253') {
  74. if (this._rfc4253Cache === undefined)
  75. this._rfc4253Cache = formats['rfc4253'].write(this);
  76. return (this._rfc4253Cache);
  77. }
  78. return (formats[format].write(this, options));
  79. };
  80. Key.prototype.toString = function (format, options) {
  81. return (this.toBuffer(format, options).toString());
  82. };
  83. Key.prototype.hash = function (algo) {
  84. assert.string(algo, 'algorithm');
  85. algo = algo.toLowerCase();
  86. if (algs.hashAlgs[algo] === undefined)
  87. throw (new InvalidAlgorithmError(algo));
  88. if (this._hashCache[algo])
  89. return (this._hashCache[algo]);
  90. var hash = crypto.createHash(algo).
  91. update(this.toBuffer('rfc4253')).digest();
  92. this._hashCache[algo] = hash;
  93. return (hash);
  94. };
  95. Key.prototype.fingerprint = function (algo) {
  96. if (algo === undefined)
  97. algo = 'sha256';
  98. assert.string(algo, 'algorithm');
  99. var opts = {
  100. type: 'key',
  101. hash: this.hash(algo),
  102. algorithm: algo
  103. };
  104. return (new Fingerprint(opts));
  105. };
  106. Key.prototype.defaultHashAlgorithm = function () {
  107. var hashAlgo = 'sha1';
  108. if (this.type === 'rsa')
  109. hashAlgo = 'sha256';
  110. if (this.type === 'dsa' && this.size > 1024)
  111. hashAlgo = 'sha256';
  112. if (this.type === 'ed25519')
  113. hashAlgo = 'sha512';
  114. if (this.type === 'ecdsa') {
  115. if (this.size <= 256)
  116. hashAlgo = 'sha256';
  117. else if (this.size <= 384)
  118. hashAlgo = 'sha384';
  119. else
  120. hashAlgo = 'sha512';
  121. }
  122. return (hashAlgo);
  123. };
  124. Key.prototype.createVerify = function (hashAlgo) {
  125. if (hashAlgo === undefined)
  126. hashAlgo = this.defaultHashAlgorithm();
  127. assert.string(hashAlgo, 'hash algorithm');
  128. /* ED25519 is not supported by OpenSSL, use a javascript impl. */
  129. if (this.type === 'ed25519' && edCompat !== undefined)
  130. return (new edCompat.Verifier(this, hashAlgo));
  131. if (this.type === 'curve25519')
  132. throw (new Error('Curve25519 keys are not suitable for ' +
  133. 'signing or verification'));
  134. var v, nm, err;
  135. try {
  136. nm = hashAlgo.toUpperCase();
  137. v = crypto.createVerify(nm);
  138. } catch (e) {
  139. err = e;
  140. }
  141. if (v === undefined || (err instanceof Error &&
  142. err.message.match(/Unknown message digest/))) {
  143. nm = 'RSA-';
  144. nm += hashAlgo.toUpperCase();
  145. v = crypto.createVerify(nm);
  146. }
  147. assert.ok(v, 'failed to create verifier');
  148. var oldVerify = v.verify.bind(v);
  149. var key = this.toBuffer('pkcs8');
  150. var self = this;
  151. v.verify = function (signature, fmt) {
  152. if (Signature.isSignature(signature, [2, 0])) {
  153. if (signature.type !== self.type)
  154. return (false);
  155. if (signature.hashAlgorithm &&
  156. signature.hashAlgorithm !== hashAlgo)
  157. return (false);
  158. return (oldVerify(key, signature.toBuffer('asn1')));
  159. } else if (typeof (signature) === 'string' ||
  160. Buffer.isBuffer(signature)) {
  161. return (oldVerify(key, signature, fmt));
  162. /*
  163. * Avoid doing this on valid arguments, walking the prototype
  164. * chain can be quite slow.
  165. */
  166. } else if (Signature.isSignature(signature, [1, 0])) {
  167. throw (new Error('signature was created by too old ' +
  168. 'a version of sshpk and cannot be verified'));
  169. } else {
  170. throw (new TypeError('signature must be a string, ' +
  171. 'Buffer, or Signature object'));
  172. }
  173. };
  174. return (v);
  175. };
  176. Key.prototype.createDiffieHellman = function () {
  177. if (this.type === 'rsa')
  178. throw (new Error('RSA keys do not support Diffie-Hellman'));
  179. return (new DiffieHellman(this));
  180. };
  181. Key.prototype.createDH = Key.prototype.createDiffieHellman;
  182. Key.parse = function (data, format, options) {
  183. if (typeof (data) !== 'string')
  184. assert.buffer(data, 'data');
  185. if (format === undefined)
  186. format = 'auto';
  187. assert.string(format, 'format');
  188. if (typeof (options) === 'string')
  189. options = { filename: options };
  190. assert.optionalObject(options, 'options');
  191. if (options === undefined)
  192. options = {};
  193. assert.optionalString(options.filename, 'options.filename');
  194. if (options.filename === undefined)
  195. options.filename = '(unnamed)';
  196. assert.object(formats[format], 'formats[format]');
  197. try {
  198. var k = formats[format].read(data, options);
  199. if (k instanceof PrivateKey)
  200. k = k.toPublic();
  201. if (!k.comment)
  202. k.comment = options.filename;
  203. return (k);
  204. } catch (e) {
  205. if (e.name === 'KeyEncryptedError')
  206. throw (e);
  207. throw (new KeyParseError(options.filename, format, e));
  208. }
  209. };
  210. Key.isKey = function (obj, ver) {
  211. return (utils.isCompatible(obj, Key, ver));
  212. };
  213. /*
  214. * API versions for Key:
  215. * [1,0] -- initial ver, may take Signature for createVerify or may not
  216. * [1,1] -- added pkcs1, pkcs8 formats
  217. * [1,2] -- added auto, ssh-private, openssh formats
  218. * [1,3] -- added defaultHashAlgorithm
  219. * [1,4] -- added ed support, createDH
  220. * [1,5] -- first explicitly tagged version
  221. */
  222. Key.prototype._sshpkApiVersion = [1, 5];
  223. Key._oldVersionDetect = function (obj) {
  224. assert.func(obj.toBuffer);
  225. assert.func(obj.fingerprint);
  226. if (obj.createDH)
  227. return ([1, 4]);
  228. if (obj.defaultHashAlgorithm)
  229. return ([1, 3]);
  230. if (obj.formats['auto'])
  231. return ([1, 2]);
  232. if (obj.formats['pkcs1'])
  233. return ([1, 1]);
  234. return ([1, 0]);
  235. };