openssh-cert.js 7.9 KB

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