key.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2017 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').DiffieHellman;
  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' || this.type === 'curve25519') {
  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 curve = this.curve;
  151. var self = this;
  152. v.verify = function (signature, fmt) {
  153. if (Signature.isSignature(signature, [2, 0])) {
  154. if (signature.type !== self.type)
  155. return (false);
  156. if (signature.hashAlgorithm &&
  157. signature.hashAlgorithm !== hashAlgo)
  158. return (false);
  159. if (signature.curve && self.type === 'ecdsa' &&
  160. signature.curve !== curve)
  161. return (false);
  162. return (oldVerify(key, signature.toBuffer('asn1')));
  163. } else if (typeof (signature) === 'string' ||
  164. Buffer.isBuffer(signature)) {
  165. return (oldVerify(key, signature, fmt));
  166. /*
  167. * Avoid doing this on valid arguments, walking the prototype
  168. * chain can be quite slow.
  169. */
  170. } else if (Signature.isSignature(signature, [1, 0])) {
  171. throw (new Error('signature was created by too old ' +
  172. 'a version of sshpk and cannot be verified'));
  173. } else {
  174. throw (new TypeError('signature must be a string, ' +
  175. 'Buffer, or Signature object'));
  176. }
  177. };
  178. return (v);
  179. };
  180. Key.prototype.createDiffieHellman = function () {
  181. if (this.type === 'rsa')
  182. throw (new Error('RSA keys do not support Diffie-Hellman'));
  183. return (new DiffieHellman(this));
  184. };
  185. Key.prototype.createDH = Key.prototype.createDiffieHellman;
  186. Key.parse = function (data, format, options) {
  187. if (typeof (data) !== 'string')
  188. assert.buffer(data, 'data');
  189. if (format === undefined)
  190. format = 'auto';
  191. assert.string(format, 'format');
  192. if (typeof (options) === 'string')
  193. options = { filename: options };
  194. assert.optionalObject(options, 'options');
  195. if (options === undefined)
  196. options = {};
  197. assert.optionalString(options.filename, 'options.filename');
  198. if (options.filename === undefined)
  199. options.filename = '(unnamed)';
  200. assert.object(formats[format], 'formats[format]');
  201. try {
  202. var k = formats[format].read(data, options);
  203. if (k instanceof PrivateKey)
  204. k = k.toPublic();
  205. if (!k.comment)
  206. k.comment = options.filename;
  207. return (k);
  208. } catch (e) {
  209. if (e.name === 'KeyEncryptedError')
  210. throw (e);
  211. throw (new KeyParseError(options.filename, format, e));
  212. }
  213. };
  214. Key.isKey = function (obj, ver) {
  215. return (utils.isCompatible(obj, Key, ver));
  216. };
  217. /*
  218. * API versions for Key:
  219. * [1,0] -- initial ver, may take Signature for createVerify or may not
  220. * [1,1] -- added pkcs1, pkcs8 formats
  221. * [1,2] -- added auto, ssh-private, openssh formats
  222. * [1,3] -- added defaultHashAlgorithm
  223. * [1,4] -- added ed support, createDH
  224. * [1,5] -- first explicitly tagged version
  225. */
  226. Key.prototype._sshpkApiVersion = [1, 5];
  227. Key._oldVersionDetect = function (obj) {
  228. assert.func(obj.toBuffer);
  229. assert.func(obj.fingerprint);
  230. if (obj.createDH)
  231. return ([1, 4]);
  232. if (obj.defaultHashAlgorithm)
  233. return ([1, 3]);
  234. if (obj.formats['auto'])
  235. return ([1, 2]);
  236. if (obj.formats['pkcs1'])
  237. return ([1, 1]);
  238. return ([1, 0]);
  239. };