openssh-cert.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Copyright 2017 Joyent, Inc.
  2. module.exports = {
  3. read: read,
  4. verify: verify,
  5. sign: sign,
  6. signAsync: signAsync,
  7. write: write,
  8. /* Internal private API */
  9. fromBuffer: fromBuffer,
  10. toBuffer: toBuffer
  11. };
  12. var assert = require('assert-plus');
  13. var SSHBuffer = require('../ssh-buffer');
  14. var crypto = require('crypto');
  15. var algs = require('../algs');
  16. var Key = require('../key');
  17. var PrivateKey = require('../private-key');
  18. var Identity = require('../identity');
  19. var rfc4253 = require('./rfc4253');
  20. var Signature = require('../signature');
  21. var utils = require('../utils');
  22. var Certificate = require('../certificate');
  23. function verify(cert, key) {
  24. /*
  25. * We always give an issuerKey, so if our verify() is being called then
  26. * there was no signature. Return false.
  27. */
  28. return (false);
  29. }
  30. var TYPES = {
  31. 'user': 1,
  32. 'host': 2
  33. };
  34. Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
  35. var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
  36. function read(buf, options) {
  37. if (Buffer.isBuffer(buf))
  38. buf = buf.toString('ascii');
  39. var parts = buf.trim().split(/[ \t\n]+/g);
  40. if (parts.length < 2 || parts.length > 3)
  41. throw (new Error('Not a valid SSH certificate line'));
  42. var algo = parts[0];
  43. var data = parts[1];
  44. data = new Buffer(data, 'base64');
  45. return (fromBuffer(data, algo));
  46. }
  47. function fromBuffer(data, algo, partial) {
  48. var sshbuf = new SSHBuffer({ buffer: data });
  49. var innerAlgo = sshbuf.readString();
  50. if (algo !== undefined && innerAlgo !== algo)
  51. throw (new Error('SSH certificate algorithm mismatch'));
  52. if (algo === undefined)
  53. algo = innerAlgo;
  54. var cert = {};
  55. cert.signatures = {};
  56. cert.signatures.openssh = {};
  57. cert.signatures.openssh.nonce = sshbuf.readBuffer();
  58. var key = {};
  59. var parts = (key.parts = []);
  60. key.type = getAlg(algo);
  61. var partCount = algs.info[key.type].parts.length;
  62. while (parts.length < partCount)
  63. parts.push(sshbuf.readPart());
  64. assert.ok(parts.length >= 1, 'key must have at least one part');
  65. var algInfo = algs.info[key.type];
  66. if (key.type === 'ecdsa') {
  67. var res = ECDSA_ALGO.exec(algo);
  68. assert.ok(res !== null);
  69. assert.strictEqual(res[1], parts[0].data.toString());
  70. }
  71. for (var i = 0; i < algInfo.parts.length; ++i) {
  72. parts[i].name = algInfo.parts[i];
  73. if (parts[i].name !== 'curve' &&
  74. algInfo.normalize !== false) {
  75. var p = parts[i];
  76. p.data = utils.mpNormalize(p.data);
  77. }
  78. }
  79. cert.subjectKey = new Key(key);
  80. cert.serial = sshbuf.readInt64();
  81. var type = TYPES[sshbuf.readInt()];
  82. assert.string(type, 'valid cert type');
  83. cert.signatures.openssh.keyId = sshbuf.readString();
  84. var principals = [];
  85. var pbuf = sshbuf.readBuffer();
  86. var psshbuf = new SSHBuffer({ buffer: pbuf });
  87. while (!psshbuf.atEnd())
  88. principals.push(psshbuf.readString());
  89. if (principals.length === 0)
  90. principals = ['*'];
  91. cert.subjects = principals.map(function (pr) {
  92. if (type === 'user')
  93. return (Identity.forUser(pr));
  94. else if (type === 'host')
  95. return (Identity.forHost(pr));
  96. throw (new Error('Unknown identity type ' + type));
  97. });
  98. cert.validFrom = int64ToDate(sshbuf.readInt64());
  99. cert.validUntil = int64ToDate(sshbuf.readInt64());
  100. cert.signatures.openssh.critical = sshbuf.readBuffer();
  101. cert.signatures.openssh.exts = sshbuf.readBuffer();
  102. /* reserved */
  103. sshbuf.readBuffer();
  104. var signingKeyBuf = sshbuf.readBuffer();
  105. cert.issuerKey = rfc4253.read(signingKeyBuf);
  106. /*
  107. * OpenSSH certs don't give the identity of the issuer, just their
  108. * public key. So, we use an Identity that matches anything. The
  109. * isSignedBy() function will later tell you if the key matches.
  110. */
  111. cert.issuer = Identity.forHost('**');
  112. var sigBuf = sshbuf.readBuffer();
  113. cert.signatures.openssh.signature =
  114. Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
  115. if (partial !== undefined) {
  116. partial.remainder = sshbuf.remainder();
  117. partial.consumed = sshbuf._offset;
  118. }
  119. return (new Certificate(cert));
  120. }
  121. function int64ToDate(buf) {
  122. var i = buf.readUInt32BE(0) * 4294967296;
  123. i += buf.readUInt32BE(4);
  124. var d = new Date();
  125. d.setTime(i * 1000);
  126. d.sourceInt64 = buf;
  127. return (d);
  128. }
  129. function dateToInt64(date) {
  130. if (date.sourceInt64 !== undefined)
  131. return (date.sourceInt64);
  132. var i = Math.round(date.getTime() / 1000);
  133. var upper = Math.floor(i / 4294967296);
  134. var lower = Math.floor(i % 4294967296);
  135. var buf = new Buffer(8);
  136. buf.writeUInt32BE(upper, 0);
  137. buf.writeUInt32BE(lower, 4);
  138. return (buf);
  139. }
  140. function sign(cert, key) {
  141. if (cert.signatures.openssh === undefined)
  142. cert.signatures.openssh = {};
  143. try {
  144. var blob = toBuffer(cert, true);
  145. } catch (e) {
  146. delete (cert.signatures.openssh);
  147. return (false);
  148. }
  149. var sig = cert.signatures.openssh;
  150. var hashAlgo = undefined;
  151. if (key.type === 'rsa' || key.type === 'dsa')
  152. hashAlgo = 'sha1';
  153. var signer = key.createSign(hashAlgo);
  154. signer.write(blob);
  155. sig.signature = signer.sign();
  156. return (true);
  157. }
  158. function signAsync(cert, signer, done) {
  159. if (cert.signatures.openssh === undefined)
  160. cert.signatures.openssh = {};
  161. try {
  162. var blob = toBuffer(cert, true);
  163. } catch (e) {
  164. delete (cert.signatures.openssh);
  165. done(e);
  166. return;
  167. }
  168. var sig = cert.signatures.openssh;
  169. signer(blob, function (err, signature) {
  170. if (err) {
  171. done(err);
  172. return;
  173. }
  174. try {
  175. /*
  176. * This will throw if the signature isn't of a
  177. * type/algo that can be used for SSH.
  178. */
  179. signature.toBuffer('ssh');
  180. } catch (e) {
  181. done(e);
  182. return;
  183. }
  184. sig.signature = signature;
  185. done();
  186. });
  187. }
  188. function write(cert, options) {
  189. if (options === undefined)
  190. options = {};
  191. var blob = toBuffer(cert);
  192. var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
  193. if (options.comment)
  194. out = out + ' ' + options.comment;
  195. return (out);
  196. }
  197. function toBuffer(cert, noSig) {
  198. assert.object(cert.signatures.openssh, 'signature for openssh format');
  199. var sig = cert.signatures.openssh;
  200. if (sig.nonce === undefined)
  201. sig.nonce = crypto.randomBytes(16);
  202. var buf = new SSHBuffer({});
  203. buf.writeString(getCertType(cert.subjectKey));
  204. buf.writeBuffer(sig.nonce);
  205. var key = cert.subjectKey;
  206. var algInfo = algs.info[key.type];
  207. algInfo.parts.forEach(function (part) {
  208. buf.writePart(key.part[part]);
  209. });
  210. buf.writeInt64(cert.serial);
  211. var type = cert.subjects[0].type;
  212. assert.notStrictEqual(type, 'unknown');
  213. cert.subjects.forEach(function (id) {
  214. assert.strictEqual(id.type, type);
  215. });
  216. type = TYPES[type];
  217. buf.writeInt(type);
  218. if (sig.keyId === undefined) {
  219. sig.keyId = cert.subjects[0].type + '_' +
  220. (cert.subjects[0].uid || cert.subjects[0].hostname);
  221. }
  222. buf.writeString(sig.keyId);
  223. var sub = new SSHBuffer({});
  224. cert.subjects.forEach(function (id) {
  225. if (type === TYPES.host)
  226. sub.writeString(id.hostname);
  227. else if (type === TYPES.user)
  228. sub.writeString(id.uid);
  229. });
  230. buf.writeBuffer(sub.toBuffer());
  231. buf.writeInt64(dateToInt64(cert.validFrom));
  232. buf.writeInt64(dateToInt64(cert.validUntil));
  233. if (sig.critical === undefined)
  234. sig.critical = new Buffer(0);
  235. buf.writeBuffer(sig.critical);
  236. if (sig.exts === undefined)
  237. sig.exts = new Buffer(0);
  238. buf.writeBuffer(sig.exts);
  239. /* reserved */
  240. buf.writeBuffer(new Buffer(0));
  241. sub = rfc4253.write(cert.issuerKey);
  242. buf.writeBuffer(sub);
  243. if (!noSig)
  244. buf.writeBuffer(sig.signature.toBuffer('ssh'));
  245. return (buf.toBuffer());
  246. }
  247. function getAlg(certType) {
  248. if (certType === 'ssh-rsa-cert-v01@openssh.com')
  249. return ('rsa');
  250. if (certType === 'ssh-dss-cert-v01@openssh.com')
  251. return ('dsa');
  252. if (certType.match(ECDSA_ALGO))
  253. return ('ecdsa');
  254. if (certType === 'ssh-ed25519-cert-v01@openssh.com')
  255. return ('ed25519');
  256. throw (new Error('Unsupported cert type ' + certType));
  257. }
  258. function getCertType(key) {
  259. if (key.type === 'rsa')
  260. return ('ssh-rsa-cert-v01@openssh.com');
  261. if (key.type === 'dsa')
  262. return ('ssh-dss-cert-v01@openssh.com');
  263. if (key.type === 'ecdsa')
  264. return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
  265. if (key.type === 'ed25519')
  266. return ('ssh-ed25519-cert-v01@openssh.com');
  267. throw (new Error('Unsupported key type ' + key.type));
  268. }