From 3668d337d7dc50875e71197129df4bd1ae3c0166 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Mon, 17 Dec 2018 00:22:46 -0700 Subject: [PATCH] =?UTF-8?q?v1.5.0:=20=F0=9F=92=AF=20parse=20HTTPS=20certif?= =?UTF-8?q?icate=20info=20in=20a=20focused,=20lightweight,=20zero-dependen?= =?UTF-8?q?cy=20library?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 388 +++++++++++++++++++++++++++++-- README.md | 62 +++-- bin/{certpem.js => cert-info.js} | 11 +- index.js | 123 +--------- lib/asn1-parser.js | 147 ++++++++++++ lib/cert-info.js | 106 +++++++++ package.json | 20 +- test.js | 6 +- 8 files changed, 686 insertions(+), 177 deletions(-) rename bin/{certpem.js => cert-info.js} (72%) create mode 100644 lib/asn1-parser.js create mode 100644 lib/cert-info.js diff --git a/LICENSE b/LICENSE index a7782bc..c212878 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,375 @@ -MIT License +Copyright 2016-2018 AJ ONeal -Copyright (c) 2016 Daplie, Inc +Mozilla Public License Version 2.0 +================================== -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +1. Definitions +-------------- -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md index 469d9bd..af581a5 100644 --- a/README.md +++ b/README.md @@ -1,51 +1,57 @@ -cert-info.js -============ +# [cert-info.js](https://git.coolaj86.com/coolaj86/cert-info.js) Read basic info from a cert.pem / x509 certificate. Used for [Greenlock.js](https://git.coolaj86.com/coolaj86/greenlock-express.js) -Install -======= +# Features + +| <175 lines of code | 1.7k gzipped | 4.4k minified | 8.8k with comments | + +* [x] Parses x.509 certificate schemas + * [x] DER/ASN.1 + * [x] PEM (base64-encoded DER) + * [x] Subject + * [x] SAN extension (altNames) + * [x] Issuance Date (notBefore) + * [x] Expiry Date (notAfter) +* [x] VanillaJS, **Zero Dependencies** + * [x] Node.js + * [ ] Browsers (built, publishing soon) + +# Install ```bash # bin -npm install --global certpem +npm install --global cert-info # node.js library -npm install --save certpem +npm install --save cert-info ``` -Usage -===== +# Usage -CLI ---- +## CLI For basic info (subject, altnames, issuedAt, expiresAt): ```bash -certpem /path/to/cert.pem +cert-info /path/to/cert.pem ``` -Output all info by passing `--debug` or use `--json` to see the basic info pretty-printed. - -node.js -------- +## node.js ```javascript 'use strict'; -var certpem = require('certpem').certpem +var certinfo = require('cert-info'); var cert = fs.readFile('cert.pem', 'ascii', function (err, certstr) { // basic info - console.info(certpem.info(certstr)); - - // way too much info - // (requires npm install --save node.extend@1) - console.info(certpem.debug(certstr)); + console.info(certinfo.info(certstr)); + // if you need to submit a bug report + console.info(certinfo.debug(certstr)); }); ``` @@ -53,13 +59,21 @@ Example output: ```javascript { - "subject": "localhost.daplie.com", + "subject": "localhost.example.com", "altnames": [ - "localhost.daplie.com" + "localhost.example.com" ], "issuedAt": 1465516800000, "expiresAt": 1499731199000 } ``` -With a few small changes this could also work in the browser (that's how its dependencies are designed). +With a few small changes this could also work in the browser +(it has no dependencies and all of the non-browser things are on the Enc object). + +# Legal + +[cert-info.js](https://git.coolaj86.com/coolaj86/cert-info.js) | +MPL-2.0 | +[Terms of Use](https://therootcompany.com/legal/#terms) | +[Privacy Policy](https://therootcompany.com/legal/#privacy) diff --git a/bin/certpem.js b/bin/cert-info.js similarity index 72% rename from bin/certpem.js rename to bin/cert-info.js index a5f556f..f524ba9 100755 --- a/bin/certpem.js +++ b/bin/cert-info.js @@ -1,8 +1,11 @@ #!/usr/bin/env node - +// Copyright 2016-2018 AJ ONeal. All rights reserved +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; -var certpem = require('../').certpem; +var certinfo = require('../'); var path = require('path'); var filepath = (process.cwd() + path.sep + 'cert.pem'); var debug = false; @@ -30,9 +33,9 @@ else { } if (debug) { - console.info(JSON.stringify(certpem.debug(cert), null, ' ')); + console.info(JSON.stringify(certinfo.debug(cert), null, ' ')); } else { - var c = certpem.info(cert); + var c = certinfo.info(cert); if (json) { console.info(JSON.stringify(c, null, ' ')); diff --git a/index.js b/index.js index 376f3ba..c1bb00c 100644 --- a/index.js +++ b/index.js @@ -1,120 +1,7 @@ +// Copyright 2016-2018 AJ ONeal. All rights reserved +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; -var certInfo = module.exports; -module.exports.certpem = certInfo; - -// ES5 version of mergeDeep -// https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge -/** - * Simple object check. - * @param item - * @returns {boolean} - */ -function isObject(item) { - return (item && typeof item === 'object' && !Array.isArray(item)); -} - -/** - * Deep merge two objects. - * @param target - * @param ...sources - */ -function merge(target) { - var sources = Array.prototype.slice.call(arguments); - sources.shift(); - if (!sources.length) { return target; } - var source = sources.shift(); - var obj; - - if (isObject(target) && isObject(source)) { - Object.keys(source).forEach(function (key) { - if (isObject(source[key])) { - if (!target[key]) { obj = {}; obj[key] = {}; Object.assign(target, obj); } - merge(target[key], source[key]); - } else { - obj = {}; obj[key] = source[key]; - Object.assign(target, obj); - } - }); - } - - sources.unshift(target); - return merge.apply(null, sources); -} - -var common = require("asn1js/org/pkijs/common"); -var _asn1js = require("asn1js"); -var _pkijs = require("pkijs"); -var _x509schema = require("pkijs/org/pkijs/x509_schema"); - -// #region Merging function/object declarations for ASN1js and PKIjs -var asn1js = merge(_asn1js, common); - -var x509schema = merge(_x509schema, asn1js); - -var pkijs_1 = merge(_pkijs, asn1js); -var pkijs = merge(pkijs_1, x509schema); - -// this is really memory expensive to do -// (about half of a megabyte of loaded code) -certInfo._pemToBinAb = function (pem) { - var b64 = pem.replace(/(-----(BEGIN|END) CERTIFICATE-----|[\n\r])/g, ''); - var buf = Buffer.from(b64, 'base64'); - var ab = new Uint8Array(buf).buffer; // WORKS - //var ab = buf.buffer // Doesn't work - - return ab; -}; -certInfo.debug = certInfo.getCertInfo = function (pem) { - var ab = module.exports._pemToBinAb(pem); - - var asn1 = pkijs.org.pkijs.fromBER(ab); - var certSimpl = new pkijs.org.pkijs.simpl.CERT({ schema: asn1.result }); - - return certSimpl; -}; - -certInfo.info = certInfo.getBasicInfo = function (pem) { - var c = certInfo.getCertInfo(pem); - var domains = []; - var sub; - - c.extensions.forEach(function (ext) { - if (ext.parsedValue && ext.parsedValue.altNames) { - ext.parsedValue.altNames.forEach(function (alt) { - domains.push(alt.Name); - }); - } - }); - - sub = c.subject.types_and_values[0].value.value_block.value || null; - - return { - subject: sub - , altnames: domains - // for debugging during console.log - // do not expect these values to be here - , _issuedAt: c.notBefore.value - , _expiresAt: c.notAfter.value - , issuedAt: new Date(c.notBefore.value).valueOf() - , expiresAt: new Date(c.notAfter.value).valueOf() - }; -}; - -certInfo.getCertInfoFromFile = function (pemFile) { - return require('fs').readFileSync(pemFile, 'ascii'); -}; - -/* -certInfo.testGetCertInfo = function (pathname) { - var path = require('path'); - var pemFile = pathname || path.join(__dirname, '..', 'tests', 'example.cert.pem'); - return certInfo.getCertInfo(certInfo.getCertInfoFromFile(pemFile)); -}; - -certInfo.testBasicCertInfo = function (pathname) { - var path = require('path'); - var pemFile = pathname || path.join(__dirname, '..', 'tests', 'example.cert.pem'); - return certInfo.getBasicInfo(certInfo.getCertInfoFromFile(pemFile)); -}; -*/ +module.exports = require('./lib/cert-info.js'); diff --git a/lib/asn1-parser.js b/lib/asn1-parser.js new file mode 100644 index 0000000..906347f --- /dev/null +++ b/lib/asn1-parser.js @@ -0,0 +1,147 @@ +// Copyright 2016-2018 AJ ONeal. All rights reserved +// https://git.coolaj86.com/coolaj86/asn1-parser.js +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +;(function (exports) { +'use strict'; + +if (!exports.ASN1) { exports.ASN1 = {}; } +if (!exports.Enc) { exports.Enc = {}; } +if (!exports.PEM) { exports.PEM = {}; } + +var ASN1 = exports.ASN1; +var Enc = exports.Enc; +var PEM = exports.PEM; + +// +// Parser +// + +ASN1.ELOOPN = 20; // I've seen 9 max in https certificates +ASN1.ELOOP = "uASN1.js Error: iterated over " + ASN1.ELOOPN + "+ elements (probably a malformed file)"; +ASN1.EDEEPN = 60; // I've seen 29 deep in https certificates +ASN1.EDEEP = "uASN1.js Error: element nested " + ASN1.EDEEPN + "+ layers deep (probably a malformed file)"; +// Container Types are Sequence 0x30, Container Array? (0xA0, 0xA1) +// Value Types are Boolean 0x01, Integer 0x02, Null 0x05, Object ID 0x06, String 0x0C, 0x16, 0x13, 0x1e Value Array? (0x82) +// Bit String (0x03) and Octet String (0x04) may be values or containers +// Sometimes Bit String is used as a container (RSA Pub Spki) +ASN1.CTYPES = [ 0x30, 0x31, 0xa0, 0xa1 ]; +ASN1.VTYPES = [ 0x01, 0x02, 0x05, 0x06, 0x0c, 0x82 ]; +ASN1.parse = function parseAsn1Helper(buf) { + //var ws = ' '; + function parseAsn1(buf, depth, eager) { + if (depth.length >= ASN1.EDEEPN) { throw new Error(ASN1.EDEEP); } + + var index = 2; // we know, at minimum, data starts after type (0) and lengthSize (1) + var asn1 = { type: buf[0], lengthSize: 0, length: buf[1] }; + var child; + var iters = 0; + var adjust = 0; + var adjustedLen; + + // Determine how many bytes the length uses, and what it is + if (0x80 & asn1.length) { + asn1.lengthSize = 0x7f & asn1.length; + // I think that buf->hex->int solves the problem of Endianness... not sure + asn1.length = parseInt(Enc.bufToHex(buf.slice(index, index + asn1.lengthSize)), 16); + index += asn1.lengthSize; + } + + // High-order bit Integers have a leading 0x00 to signify that they are positive. + // Bit Streams use the first byte to signify padding, which x.509 doesn't use. + if (0x00 === buf[index] && (0x02 === asn1.type || 0x03 === asn1.type)) { + // However, 0x00 on its own is a valid number + if (asn1.length > 1) { + index += 1; + adjust = -1; + } + } + adjustedLen = asn1.length + adjust; + + //console.warn(depth.join(ws) + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1); + + function parseChildren(eager) { + asn1.children = []; + //console.warn('1 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', 0); + while (iters < ASN1.ELOOPN && index < (2 + asn1.length + asn1.lengthSize)) { + iters += 1; + depth.length += 1; + child = parseAsn1(buf.slice(index, index + adjustedLen), depth, eager); + depth.length -= 1; + // The numbers don't match up exactly and I don't remember why... + // probably something with adjustedLen or some such, but the tests pass + index += (2 + child.lengthSize + child.length); + //console.warn('2 len:', (2 + asn1.lengthSize + asn1.length), 'idx:', index, 'clen:', (2 + child.lengthSize + child.length)); + if (index > (2 + asn1.lengthSize + asn1.length)) { + if (!eager) { console.error(JSON.stringify(asn1, ASN1._replacer, 2)); } + throw new Error("Parse error: child value length (" + child.length + + ") is greater than remaining parent length (" + (asn1.length - index) + + " = " + asn1.length + " - " + index + ")"); + } + asn1.children.push(child); + //console.warn(depth.join(ws) + '0x' + Enc.numToHex(asn1.type), index, 'len:', asn1.length, asn1); + } + if (index !== (2 + asn1.lengthSize + asn1.length)) { + //console.warn('index:', index, 'length:', (2 + asn1.lengthSize + asn1.length)); + throw new Error("premature end-of-file"); + } + if (iters >= ASN1.ELOOPN) { throw new Error(ASN1.ELOOP); } + + delete asn1.value; + return asn1; + } + + // Recurse into types that are _always_ containers + if (-1 !== ASN1.CTYPES.indexOf(asn1.type)) { return parseChildren(eager); } + + // Return types that are _always_ values + asn1.value = buf.slice(index, index + adjustedLen); + if (-1 !== ASN1.VTYPES.indexOf(asn1.type)) { return asn1; } + + // For ambigious / unknown types, recurse and return on failure + // (and return child array size to zero) + try { return parseChildren(true); } + catch(e) { asn1.children.length = 0; return asn1; } + } + + var asn1 = parseAsn1(buf, []); + var len = buf.byteLength || buf.length; + if (len !== 2 + asn1.lengthSize + asn1.length) { + throw new Error("Length of buffer does not match length of ASN.1 sequence."); + } + return asn1; +}; +ASN1._replacer = function (k, v) { + if ('type' === k) { return '0x' + Enc.numToHex(v); } + if (v && 'value' === k) { return '0x' + Enc.bufToHex(v.data || v); } + return v; +}; + +// don't replace the full parseBlock, if it exists +PEM.parseBlock = PEM.parseBlock || function (str) { + var b64 = str.split(/\n/).filter(function (line) { + return !/-----/.test(line); + }).join(''); + var der = Enc.base64ToBuf(b64); + return { bytes: der }; +}; + +Enc.base64ToBuf = function (b64) { + return Buffer.from(b64, 'base64'); +}; +Enc.binToBuf = function (bin) { + return Buffer.from(bin, 'binary'); +}; +Enc.bufToHex = function (u8) { + return Buffer.from(u8).toString('hex'); +}; +Enc.numToHex = function (d) { + d = d.toString(16); + if (d.length % 2) { + return '0' + d; + } + return d; +}; + +}('undefined' !== typeof window ? window : module.exports)); diff --git a/lib/cert-info.js b/lib/cert-info.js new file mode 100644 index 0000000..53f6a40 --- /dev/null +++ b/lib/cert-info.js @@ -0,0 +1,106 @@ +// Copyright 2016-2018 AJ ONeal. All rights reserved +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +var certInfo = module.exports; + +var ASN1 = require("./asn1-parser.js").ASN1; +var PEM = require("./asn1-parser.js").PEM; +var Enc = require("./asn1-parser.js").Enc; + +Enc.hexToBuf = function (hex) { + return Buffer.from(hex, 'hex'); +}; +Enc.bufToUtf8 = function (u8) { + return Buffer.from(u8).toString('utf8'); +}; + +certInfo.debug = certInfo.getCertInfo = function (pem) { + var bytes = PEM.parseBlock(pem).bytes; + return ASN1.parse(bytes); +}; + +certInfo.info = certInfo.getBasicInfo = function (pem) { + var c = certInfo.getCertInfo(pem); + // A cert has 3 parts: cert, signature meta, signature + if (c.children.length !== 3) { + throw new Error("doesn't look like a certificate: expected 3 parts of header"); + } + c = c.children[0]; + if (8 !== c.children.length) { + throw new Error("doesn't look like a certificate: expected 8 parts to certificate"); + } + // 0:0 value 2 + // 1 variable-length value + // 2:0 sha256 identifier 2:1 null + // 3 certificate of issuer C/O/OU/CN + // 4:0 notBefore 4:1 notAfter + var nbf = Enc.hexToBuf(c.children[4].children[0].value); + var exp = Enc.hexToBuf(c.children[4].children[1].value); + nbf = new Date(Date.UTC( + '20' + nbf.slice(0, 2) + , nbf.slice(2, 4) - 1 + , nbf.slice(4, 6) + , nbf.slice(6, 8) + , nbf.slice(8, 10) + , nbf.slice(10, 12) + )); + exp = new Date(Date.UTC( + '20' + exp.slice(0, 2) + , exp.slice(2, 4) - 1 + , exp.slice(4, 6) + , exp.slice(6, 8) + , exp.slice(8, 10) + , exp.slice(10, 12) + )); + // 5 the client C/O/OU/CN, etc + var sub = c.children[5].children.filter(function (set) { + if ('550403' === Enc.bufToHex(set.children[0].children[0].value)) { + return true; + } + }).map(function (set) { + return Enc.bufToUtf8(set.children[0].children[1].value); + })[0]; + // 6 public key + // 7 extensions + var domains = c.children[7].children[0].children.filter(function (seq) { + if ('551d11' === Enc.bufToHex(seq.children[0].value)) { + return true; + } + }).map(function (seq) { + return seq.children[1].children[0].children.map(function (name) { + return Enc.bufToUtf8(name.value); + }); + })[0]; + + return { + subject: sub + , altnames: domains + // for debugging during console.log + // do not expect these values to be here + , _issuedAt: nbf + , _expiresAt: exp + , issuedAt: nbf.valueOf() + , expiresAt: exp.valueOf() + }; +}; + +certInfo.getCertInfoFromFile = function (pemFile) { + return require('fs').readFileSync(pemFile, 'ascii'); +}; + +/* +certInfo.testGetCertInfo = function (pathname) { + var path = require('path'); + var pemFile = pathname || path.join(__dirname, '..', 'tests', 'example.cert.pem'); + return certInfo.getCertInfo(certInfo.getCertInfoFromFile(pemFile)); +}; + +certInfo.testBasicCertInfo = function (pathname) { + var path = require('path'); + var pemFile = pathname || path.join(__dirname, '..', 'tests', 'example.cert.pem'); + return certInfo.getBasicInfo(certInfo.getCertInfoFromFile(pemFile)); +}; +*/ diff --git a/package.json b/package.json index 1f30017..4f0fca4 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,13 @@ { - "name": "certpem", - "version": "1.1.2", + "name": "cert-info", + "version": "1.5.0", "description": "Read basic info (subject, altnames, expiresAt, issuedAt) from a cert.pem / x509 certificate (tls / ssl / https) ", "main": "index.js", + "author": "AJ ONeal (https://coolaj86.com/)", + "license": "MPL-2.0", + "homepage": "https://git.coolaj86.com/coolaj86/cert-info.js", "bin": { - "certpem": "bin/certpem.js" + "cert-info": "bin/cert-info.js" }, "scripts": { "test": "node test.js" @@ -27,18 +30,9 @@ "expired", "expires", "issued", - "at", - "asn1", - "pki" + "asn1" ], - "author": "AJ ONeal (https://coolaj86.com/)", - "license": "(MIT OR Apache-2.0)", "bugs": { "url": "https://git.coolaj86.com/coolaj86/cert-info.js/issues" - }, - "homepage": "https://git.coolaj86.com/coolaj86/cert-info.js", - "dependencies": { - "asn1js": "^1.2.12", - "pkijs": "^1.3.27" } } diff --git a/test.js b/test.js index 20e788f..09bf47c 100644 --- a/test.js +++ b/test.js @@ -1,3 +1,7 @@ +// Copyright 2016-2018 AJ ONeal. All rights reserved +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; -require('./bin/certpem.js'); +require('./bin/cert-info.js');