x509.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. // Copyright 2017 Joyent, Inc.
  2. module.exports = {
  3. read: read,
  4. verify: verify,
  5. sign: sign,
  6. signAsync: signAsync,
  7. write: write
  8. };
  9. var assert = require('assert-plus');
  10. var asn1 = require('asn1');
  11. var Buffer = require('safer-buffer').Buffer;
  12. var algs = require('../algs');
  13. var utils = require('../utils');
  14. var Key = require('../key');
  15. var PrivateKey = require('../private-key');
  16. var pem = require('./pem');
  17. var Identity = require('../identity');
  18. var Signature = require('../signature');
  19. var Certificate = require('../certificate');
  20. var pkcs8 = require('./pkcs8');
  21. /*
  22. * This file is based on RFC5280 (X.509).
  23. */
  24. /* Helper to read in a single mpint */
  25. function readMPInt(der, nm) {
  26. assert.strictEqual(der.peek(), asn1.Ber.Integer,
  27. nm + ' is not an Integer');
  28. return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
  29. }
  30. function verify(cert, key) {
  31. var sig = cert.signatures.x509;
  32. assert.object(sig, 'x509 signature');
  33. var algParts = sig.algo.split('-');
  34. if (algParts[0] !== key.type)
  35. return (false);
  36. var blob = sig.cache;
  37. if (blob === undefined) {
  38. var der = new asn1.BerWriter();
  39. writeTBSCert(cert, der);
  40. blob = der.buffer;
  41. }
  42. var verifier = key.createVerify(algParts[1]);
  43. verifier.write(blob);
  44. return (verifier.verify(sig.signature));
  45. }
  46. function Local(i) {
  47. return (asn1.Ber.Context | asn1.Ber.Constructor | i);
  48. }
  49. function Context(i) {
  50. return (asn1.Ber.Context | i);
  51. }
  52. var SIGN_ALGS = {
  53. 'rsa-md5': '1.2.840.113549.1.1.4',
  54. 'rsa-sha1': '1.2.840.113549.1.1.5',
  55. 'rsa-sha256': '1.2.840.113549.1.1.11',
  56. 'rsa-sha384': '1.2.840.113549.1.1.12',
  57. 'rsa-sha512': '1.2.840.113549.1.1.13',
  58. 'dsa-sha1': '1.2.840.10040.4.3',
  59. 'dsa-sha256': '2.16.840.1.101.3.4.3.2',
  60. 'ecdsa-sha1': '1.2.840.10045.4.1',
  61. 'ecdsa-sha256': '1.2.840.10045.4.3.2',
  62. 'ecdsa-sha384': '1.2.840.10045.4.3.3',
  63. 'ecdsa-sha512': '1.2.840.10045.4.3.4',
  64. 'ed25519-sha512': '1.3.101.112'
  65. };
  66. Object.keys(SIGN_ALGS).forEach(function (k) {
  67. SIGN_ALGS[SIGN_ALGS[k]] = k;
  68. });
  69. SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
  70. SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
  71. var EXTS = {
  72. 'issuerKeyId': '2.5.29.35',
  73. 'altName': '2.5.29.17',
  74. 'basicConstraints': '2.5.29.19',
  75. 'keyUsage': '2.5.29.15',
  76. 'extKeyUsage': '2.5.29.37'
  77. };
  78. function read(buf, options) {
  79. if (typeof (buf) === 'string') {
  80. buf = Buffer.from(buf, 'binary');
  81. }
  82. assert.buffer(buf, 'buf');
  83. var der = new asn1.BerReader(buf);
  84. der.readSequence();
  85. if (Math.abs(der.length - der.remain) > 1) {
  86. throw (new Error('DER sequence does not contain whole byte ' +
  87. 'stream'));
  88. }
  89. var tbsStart = der.offset;
  90. der.readSequence();
  91. var sigOffset = der.offset + der.length;
  92. var tbsEnd = sigOffset;
  93. if (der.peek() === Local(0)) {
  94. der.readSequence(Local(0));
  95. var version = der.readInt();
  96. assert.ok(version <= 3,
  97. 'only x.509 versions up to v3 supported');
  98. }
  99. var cert = {};
  100. cert.signatures = {};
  101. var sig = (cert.signatures.x509 = {});
  102. sig.extras = {};
  103. cert.serial = readMPInt(der, 'serial');
  104. der.readSequence();
  105. var after = der.offset + der.length;
  106. var certAlgOid = der.readOID();
  107. var certAlg = SIGN_ALGS[certAlgOid];
  108. if (certAlg === undefined)
  109. throw (new Error('unknown signature algorithm ' + certAlgOid));
  110. der._offset = after;
  111. cert.issuer = Identity.parseAsn1(der);
  112. der.readSequence();
  113. cert.validFrom = readDate(der);
  114. cert.validUntil = readDate(der);
  115. cert.subjects = [Identity.parseAsn1(der)];
  116. der.readSequence();
  117. after = der.offset + der.length;
  118. cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
  119. der._offset = after;
  120. /* issuerUniqueID */
  121. if (der.peek() === Local(1)) {
  122. der.readSequence(Local(1));
  123. sig.extras.issuerUniqueID =
  124. buf.slice(der.offset, der.offset + der.length);
  125. der._offset += der.length;
  126. }
  127. /* subjectUniqueID */
  128. if (der.peek() === Local(2)) {
  129. der.readSequence(Local(2));
  130. sig.extras.subjectUniqueID =
  131. buf.slice(der.offset, der.offset + der.length);
  132. der._offset += der.length;
  133. }
  134. /* extensions */
  135. if (der.peek() === Local(3)) {
  136. der.readSequence(Local(3));
  137. var extEnd = der.offset + der.length;
  138. der.readSequence();
  139. while (der.offset < extEnd)
  140. readExtension(cert, buf, der);
  141. assert.strictEqual(der.offset, extEnd);
  142. }
  143. assert.strictEqual(der.offset, sigOffset);
  144. der.readSequence();
  145. after = der.offset + der.length;
  146. var sigAlgOid = der.readOID();
  147. var sigAlg = SIGN_ALGS[sigAlgOid];
  148. if (sigAlg === undefined)
  149. throw (new Error('unknown signature algorithm ' + sigAlgOid));
  150. der._offset = after;
  151. var sigData = der.readString(asn1.Ber.BitString, true);
  152. if (sigData[0] === 0)
  153. sigData = sigData.slice(1);
  154. var algParts = sigAlg.split('-');
  155. sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
  156. sig.signature.hashAlgorithm = algParts[1];
  157. sig.algo = sigAlg;
  158. sig.cache = buf.slice(tbsStart, tbsEnd);
  159. return (new Certificate(cert));
  160. }
  161. function readDate(der) {
  162. if (der.peek() === asn1.Ber.UTCTime) {
  163. return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
  164. } else if (der.peek() === asn1.Ber.GeneralizedTime) {
  165. return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
  166. } else {
  167. throw (new Error('Unsupported date format'));
  168. }
  169. }
  170. /* RFC5280, section 4.2.1.6 (GeneralName type) */
  171. var ALTNAME = {
  172. OtherName: Local(0),
  173. RFC822Name: Context(1),
  174. DNSName: Context(2),
  175. X400Address: Local(3),
  176. DirectoryName: Local(4),
  177. EDIPartyName: Local(5),
  178. URI: Context(6),
  179. IPAddress: Context(7),
  180. OID: Context(8)
  181. };
  182. /* RFC5280, section 4.2.1.12 (KeyPurposeId) */
  183. var EXTPURPOSE = {
  184. 'serverAuth': '1.3.6.1.5.5.7.3.1',
  185. 'clientAuth': '1.3.6.1.5.5.7.3.2',
  186. 'codeSigning': '1.3.6.1.5.5.7.3.3',
  187. /* See https://github.com/joyent/oid-docs/blob/master/root.md */
  188. 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
  189. 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
  190. };
  191. var EXTPURPOSE_REV = {};
  192. Object.keys(EXTPURPOSE).forEach(function (k) {
  193. EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
  194. });
  195. var KEYUSEBITS = [
  196. 'signature', 'identity', 'keyEncryption',
  197. 'encryption', 'keyAgreement', 'ca', 'crl'
  198. ];
  199. function readExtension(cert, buf, der) {
  200. der.readSequence();
  201. var after = der.offset + der.length;
  202. var extId = der.readOID();
  203. var id;
  204. var sig = cert.signatures.x509;
  205. sig.extras.exts = [];
  206. var critical;
  207. if (der.peek() === asn1.Ber.Boolean)
  208. critical = der.readBoolean();
  209. switch (extId) {
  210. case (EXTS.basicConstraints):
  211. der.readSequence(asn1.Ber.OctetString);
  212. der.readSequence();
  213. var bcEnd = der.offset + der.length;
  214. var ca = false;
  215. if (der.peek() === asn1.Ber.Boolean)
  216. ca = der.readBoolean();
  217. if (cert.purposes === undefined)
  218. cert.purposes = [];
  219. if (ca === true)
  220. cert.purposes.push('ca');
  221. var bc = { oid: extId, critical: critical };
  222. if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
  223. bc.pathLen = der.readInt();
  224. sig.extras.exts.push(bc);
  225. break;
  226. case (EXTS.extKeyUsage):
  227. der.readSequence(asn1.Ber.OctetString);
  228. der.readSequence();
  229. if (cert.purposes === undefined)
  230. cert.purposes = [];
  231. var ekEnd = der.offset + der.length;
  232. while (der.offset < ekEnd) {
  233. var oid = der.readOID();
  234. cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
  235. }
  236. /*
  237. * This is a bit of a hack: in the case where we have a cert
  238. * that's only allowed to do serverAuth or clientAuth (and not
  239. * the other), we want to make sure all our Subjects are of
  240. * the right type. But we already parsed our Subjects and
  241. * decided if they were hosts or users earlier (since it appears
  242. * first in the cert).
  243. *
  244. * So we go through and mutate them into the right kind here if
  245. * it doesn't match. This might not be hugely beneficial, as it
  246. * seems that single-purpose certs are not often seen in the
  247. * wild.
  248. */
  249. if (cert.purposes.indexOf('serverAuth') !== -1 &&
  250. cert.purposes.indexOf('clientAuth') === -1) {
  251. cert.subjects.forEach(function (ide) {
  252. if (ide.type !== 'host') {
  253. ide.type = 'host';
  254. ide.hostname = ide.uid ||
  255. ide.email ||
  256. ide.components[0].value;
  257. }
  258. });
  259. } else if (cert.purposes.indexOf('clientAuth') !== -1 &&
  260. cert.purposes.indexOf('serverAuth') === -1) {
  261. cert.subjects.forEach(function (ide) {
  262. if (ide.type !== 'user') {
  263. ide.type = 'user';
  264. ide.uid = ide.hostname ||
  265. ide.email ||
  266. ide.components[0].value;
  267. }
  268. });
  269. }
  270. sig.extras.exts.push({ oid: extId, critical: critical });
  271. break;
  272. case (EXTS.keyUsage):
  273. der.readSequence(asn1.Ber.OctetString);
  274. var bits = der.readString(asn1.Ber.BitString, true);
  275. var setBits = readBitField(bits, KEYUSEBITS);
  276. setBits.forEach(function (bit) {
  277. if (cert.purposes === undefined)
  278. cert.purposes = [];
  279. if (cert.purposes.indexOf(bit) === -1)
  280. cert.purposes.push(bit);
  281. });
  282. sig.extras.exts.push({ oid: extId, critical: critical,
  283. bits: bits });
  284. break;
  285. case (EXTS.altName):
  286. der.readSequence(asn1.Ber.OctetString);
  287. der.readSequence();
  288. var aeEnd = der.offset + der.length;
  289. while (der.offset < aeEnd) {
  290. switch (der.peek()) {
  291. case ALTNAME.OtherName:
  292. case ALTNAME.EDIPartyName:
  293. der.readSequence();
  294. der._offset += der.length;
  295. break;
  296. case ALTNAME.OID:
  297. der.readOID(ALTNAME.OID);
  298. break;
  299. case ALTNAME.RFC822Name:
  300. /* RFC822 specifies email addresses */
  301. var email = der.readString(ALTNAME.RFC822Name);
  302. id = Identity.forEmail(email);
  303. if (!cert.subjects[0].equals(id))
  304. cert.subjects.push(id);
  305. break;
  306. case ALTNAME.DirectoryName:
  307. der.readSequence(ALTNAME.DirectoryName);
  308. id = Identity.parseAsn1(der);
  309. if (!cert.subjects[0].equals(id))
  310. cert.subjects.push(id);
  311. break;
  312. case ALTNAME.DNSName:
  313. var host = der.readString(
  314. ALTNAME.DNSName);
  315. id = Identity.forHost(host);
  316. if (!cert.subjects[0].equals(id))
  317. cert.subjects.push(id);
  318. break;
  319. default:
  320. der.readString(der.peek());
  321. break;
  322. }
  323. }
  324. sig.extras.exts.push({ oid: extId, critical: critical });
  325. break;
  326. default:
  327. sig.extras.exts.push({
  328. oid: extId,
  329. critical: critical,
  330. data: der.readString(asn1.Ber.OctetString, true)
  331. });
  332. break;
  333. }
  334. der._offset = after;
  335. }
  336. var UTCTIME_RE =
  337. /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
  338. function utcTimeToDate(t) {
  339. var m = t.match(UTCTIME_RE);
  340. assert.ok(m, 'timestamps must be in UTC');
  341. var d = new Date();
  342. var thisYear = d.getUTCFullYear();
  343. var century = Math.floor(thisYear / 100) * 100;
  344. var year = parseInt(m[1], 10);
  345. if (thisYear % 100 < 50 && year >= 60)
  346. year += (century - 1);
  347. else
  348. year += century;
  349. d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
  350. d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
  351. if (m[6] && m[6].length > 0)
  352. d.setUTCSeconds(parseInt(m[6], 10));
  353. return (d);
  354. }
  355. var GTIME_RE =
  356. /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
  357. function gTimeToDate(t) {
  358. var m = t.match(GTIME_RE);
  359. assert.ok(m);
  360. var d = new Date();
  361. d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1,
  362. parseInt(m[3], 10));
  363. d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
  364. if (m[6] && m[6].length > 0)
  365. d.setUTCSeconds(parseInt(m[6], 10));
  366. return (d);
  367. }
  368. function zeroPad(n) {
  369. var s = '' + n;
  370. while (s.length < 2)
  371. s = '0' + s;
  372. return (s);
  373. }
  374. function dateToUTCTime(d) {
  375. var s = '';
  376. s += zeroPad(d.getUTCFullYear() % 100);
  377. s += zeroPad(d.getUTCMonth() + 1);
  378. s += zeroPad(d.getUTCDate());
  379. s += zeroPad(d.getUTCHours());
  380. s += zeroPad(d.getUTCMinutes());
  381. s += zeroPad(d.getUTCSeconds());
  382. s += 'Z';
  383. return (s);
  384. }
  385. function sign(cert, key) {
  386. if (cert.signatures.x509 === undefined)
  387. cert.signatures.x509 = {};
  388. var sig = cert.signatures.x509;
  389. sig.algo = key.type + '-' + key.defaultHashAlgorithm();
  390. if (SIGN_ALGS[sig.algo] === undefined)
  391. return (false);
  392. var der = new asn1.BerWriter();
  393. writeTBSCert(cert, der);
  394. var blob = der.buffer;
  395. sig.cache = blob;
  396. var signer = key.createSign();
  397. signer.write(blob);
  398. cert.signatures.x509.signature = signer.sign();
  399. return (true);
  400. }
  401. function signAsync(cert, signer, done) {
  402. if (cert.signatures.x509 === undefined)
  403. cert.signatures.x509 = {};
  404. var sig = cert.signatures.x509;
  405. var der = new asn1.BerWriter();
  406. writeTBSCert(cert, der);
  407. var blob = der.buffer;
  408. sig.cache = blob;
  409. signer(blob, function (err, signature) {
  410. if (err) {
  411. done(err);
  412. return;
  413. }
  414. sig.algo = signature.type + '-' + signature.hashAlgorithm;
  415. if (SIGN_ALGS[sig.algo] === undefined) {
  416. done(new Error('Invalid signing algorithm "' +
  417. sig.algo + '"'));
  418. return;
  419. }
  420. sig.signature = signature;
  421. done();
  422. });
  423. }
  424. function write(cert, options) {
  425. var sig = cert.signatures.x509;
  426. assert.object(sig, 'x509 signature');
  427. var der = new asn1.BerWriter();
  428. der.startSequence();
  429. if (sig.cache) {
  430. der._ensure(sig.cache.length);
  431. sig.cache.copy(der._buf, der._offset);
  432. der._offset += sig.cache.length;
  433. } else {
  434. writeTBSCert(cert, der);
  435. }
  436. der.startSequence();
  437. der.writeOID(SIGN_ALGS[sig.algo]);
  438. if (sig.algo.match(/^rsa-/))
  439. der.writeNull();
  440. der.endSequence();
  441. var sigData = sig.signature.toBuffer('asn1');
  442. var data = Buffer.alloc(sigData.length + 1);
  443. data[0] = 0;
  444. sigData.copy(data, 1);
  445. der.writeBuffer(data, asn1.Ber.BitString);
  446. der.endSequence();
  447. return (der.buffer);
  448. }
  449. function writeTBSCert(cert, der) {
  450. var sig = cert.signatures.x509;
  451. assert.object(sig, 'x509 signature');
  452. der.startSequence();
  453. der.startSequence(Local(0));
  454. der.writeInt(2);
  455. der.endSequence();
  456. der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
  457. der.startSequence();
  458. der.writeOID(SIGN_ALGS[sig.algo]);
  459. if (sig.algo.match(/^rsa-/))
  460. der.writeNull();
  461. der.endSequence();
  462. cert.issuer.toAsn1(der);
  463. der.startSequence();
  464. der.writeString(dateToUTCTime(cert.validFrom), asn1.Ber.UTCTime);
  465. der.writeString(dateToUTCTime(cert.validUntil), asn1.Ber.UTCTime);
  466. der.endSequence();
  467. var subject = cert.subjects[0];
  468. var altNames = cert.subjects.slice(1);
  469. subject.toAsn1(der);
  470. pkcs8.writePkcs8(der, cert.subjectKey);
  471. if (sig.extras && sig.extras.issuerUniqueID) {
  472. der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
  473. }
  474. if (sig.extras && sig.extras.subjectUniqueID) {
  475. der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
  476. }
  477. if (altNames.length > 0 || subject.type === 'host' ||
  478. (cert.purposes !== undefined && cert.purposes.length > 0) ||
  479. (sig.extras && sig.extras.exts)) {
  480. der.startSequence(Local(3));
  481. der.startSequence();
  482. var exts = [];
  483. if (cert.purposes !== undefined && cert.purposes.length > 0) {
  484. exts.push({
  485. oid: EXTS.basicConstraints,
  486. critical: true
  487. });
  488. exts.push({
  489. oid: EXTS.keyUsage,
  490. critical: true
  491. });
  492. exts.push({
  493. oid: EXTS.extKeyUsage,
  494. critical: true
  495. });
  496. }
  497. exts.push({ oid: EXTS.altName });
  498. if (sig.extras && sig.extras.exts)
  499. exts = sig.extras.exts;
  500. for (var i = 0; i < exts.length; ++i) {
  501. der.startSequence();
  502. der.writeOID(exts[i].oid);
  503. if (exts[i].critical !== undefined)
  504. der.writeBoolean(exts[i].critical);
  505. if (exts[i].oid === EXTS.altName) {
  506. der.startSequence(asn1.Ber.OctetString);
  507. der.startSequence();
  508. if (subject.type === 'host') {
  509. der.writeString(subject.hostname,
  510. Context(2));
  511. }
  512. for (var j = 0; j < altNames.length; ++j) {
  513. if (altNames[j].type === 'host') {
  514. der.writeString(
  515. altNames[j].hostname,
  516. ALTNAME.DNSName);
  517. } else if (altNames[j].type ===
  518. 'email') {
  519. der.writeString(
  520. altNames[j].email,
  521. ALTNAME.RFC822Name);
  522. } else {
  523. /*
  524. * Encode anything else as a
  525. * DN style name for now.
  526. */
  527. der.startSequence(
  528. ALTNAME.DirectoryName);
  529. altNames[j].toAsn1(der);
  530. der.endSequence();
  531. }
  532. }
  533. der.endSequence();
  534. der.endSequence();
  535. } else if (exts[i].oid === EXTS.basicConstraints) {
  536. der.startSequence(asn1.Ber.OctetString);
  537. der.startSequence();
  538. var ca = (cert.purposes.indexOf('ca') !== -1);
  539. var pathLen = exts[i].pathLen;
  540. der.writeBoolean(ca);
  541. if (pathLen !== undefined)
  542. der.writeInt(pathLen);
  543. der.endSequence();
  544. der.endSequence();
  545. } else if (exts[i].oid === EXTS.extKeyUsage) {
  546. der.startSequence(asn1.Ber.OctetString);
  547. der.startSequence();
  548. cert.purposes.forEach(function (purpose) {
  549. if (purpose === 'ca')
  550. return;
  551. if (KEYUSEBITS.indexOf(purpose) !== -1)
  552. return;
  553. var oid = purpose;
  554. if (EXTPURPOSE[purpose] !== undefined)
  555. oid = EXTPURPOSE[purpose];
  556. der.writeOID(oid);
  557. });
  558. der.endSequence();
  559. der.endSequence();
  560. } else if (exts[i].oid === EXTS.keyUsage) {
  561. der.startSequence(asn1.Ber.OctetString);
  562. /*
  563. * If we parsed this certificate from a byte
  564. * stream (i.e. we didn't generate it in sshpk)
  565. * then we'll have a ".bits" property on the
  566. * ext with the original raw byte contents.
  567. *
  568. * If we have this, use it here instead of
  569. * regenerating it. This guarantees we output
  570. * the same data we parsed, so signatures still
  571. * validate.
  572. */
  573. if (exts[i].bits !== undefined) {
  574. der.writeBuffer(exts[i].bits,
  575. asn1.Ber.BitString);
  576. } else {
  577. var bits = writeBitField(cert.purposes,
  578. KEYUSEBITS);
  579. der.writeBuffer(bits,
  580. asn1.Ber.BitString);
  581. }
  582. der.endSequence();
  583. } else {
  584. der.writeBuffer(exts[i].data,
  585. asn1.Ber.OctetString);
  586. }
  587. der.endSequence();
  588. }
  589. der.endSequence();
  590. der.endSequence();
  591. }
  592. der.endSequence();
  593. }
  594. /*
  595. * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
  596. * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
  597. * contents of the BitString tag, which is a count of unused bits followed by
  598. * the bits as a right-padded byte string.
  599. *
  600. * `bits` is the Buffer, `bitIndex` should contain an array of string names
  601. * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
  602. *
  603. * Returns an array of Strings, the names of the bits that were set to 1.
  604. */
  605. function readBitField(bits, bitIndex) {
  606. var bitLen = 8 * (bits.length - 1) - bits[0];
  607. var setBits = {};
  608. for (var i = 0; i < bitLen; ++i) {
  609. var byteN = 1 + Math.floor(i / 8);
  610. var bit = 7 - (i % 8);
  611. var mask = 1 << bit;
  612. var bitVal = ((bits[byteN] & mask) !== 0);
  613. var name = bitIndex[i];
  614. if (bitVal && typeof (name) === 'string') {
  615. setBits[name] = true;
  616. }
  617. }
  618. return (Object.keys(setBits));
  619. }
  620. /*
  621. * `setBits` is an array of strings, containing the names for each bit that
  622. * sould be set to 1. `bitIndex` is same as in `readBitField()`.
  623. *
  624. * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
  625. */
  626. function writeBitField(setBits, bitIndex) {
  627. var bitLen = bitIndex.length;
  628. var blen = Math.ceil(bitLen / 8);
  629. var unused = blen * 8 - bitLen;
  630. var bits = Buffer.alloc(1 + blen); // zero-filled
  631. bits[0] = unused;
  632. for (var i = 0; i < bitLen; ++i) {
  633. var byteN = 1 + Math.floor(i / 8);
  634. var bit = 7 - (i % 8);
  635. var mask = 1 << bit;
  636. var name = bitIndex[i];
  637. if (name === undefined)
  638. continue;
  639. var bitVal = (setBits.indexOf(name) !== -1);
  640. if (bitVal) {
  641. bits[byteN] |= mask;
  642. }
  643. }
  644. return (bits);
  645. }