openssh-cert.js 7.3 KB

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