From bfc4ab67951d23e393342416762113b077326779 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Thu, 18 Apr 2019 00:20:51 -0600 Subject: [PATCH 01/52] initial commit --- LICENSE | 375 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 9 ++ app.js | 59 ++++++++ index.html | 54 +++++++ lib/keypairs.js | 86 +++++++++++ 5 files changed, 583 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 app.js create mode 100644 index.html create mode 100644 lib/keypairs.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7007c8a --- /dev/null +++ b/LICENSE @@ -0,0 +1,375 @@ +Copyright 2017-present AJ ONeal + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered 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 new file mode 100644 index 0000000..891922c --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Bluecrypt™ Keypairs + +A port of [keypairs.js](https://git.coolaj86.com/coolaj86/keypairs.js) to the browser. + +* Keypairs + * Eckles (ECDSA) + * Rasha (RSA) + * X509 + * ASN1 diff --git a/app.js b/app.js new file mode 100644 index 0000000..968f38d --- /dev/null +++ b/app.js @@ -0,0 +1,59 @@ +(function () { +'use strict'; + +var Keypairs = window.Keypairs; + +function $(sel) { + return document.querySelector(sel); +} +function $$(sel) { + return Array.prototype.slice.call(document.querySelectorAll(sel)); +} + +function run() { + console.log('hello'); + + // Show different options for ECDSA vs RSA + $$('input[name="kty"]').forEach(function ($el) { + $el.addEventListener('change', function (ev) { + console.log(this); + console.log(ev); + if ("RSA" === ev.target.value) { + $('.js-rsa-opts').hidden = false; + $('.js-ec-opts').hidden = true; + } else { + $('.js-rsa-opts').hidden = true; + $('.js-ec-opts').hidden = false; + } + }); + }); + + // Generate a key on submit + $('form.js-keygen').addEventListener('submit', function (ev) { + ev.preventDefault(); + ev.stopPropagation(); + $('.js-loading').hidden = false; + $('.js-jwk').hidden = true; + $$('input').map(function ($el) { $el.disabled = true; }); + $$('button').map(function ($el) { $el.disabled = true; }); + var opts = { + kty: $('input[name="kty"]:checked').value + , namedCurve: $('input[name="ec-crv"]:checked').value + , modulusLength: $('input[name="rsa-len"]:checked').value + }; + console.log(opts); + Keypairs.generate(opts).then(function (results) { + $('.js-jwk').innerText = JSON.stringify(results, null, 2); + // + $('.js-loading').hidden = true; + $('.js-jwk').hidden = false; + $$('input').map(function ($el) { $el.disabled = false; }); + $$('button').map(function ($el) { $el.disabled = false; }); + }); + }); + + $('.js-generate').hidden = false; +} + +window.addEventListener('load', run); +}()); diff --git a/index.html b/index.html new file mode 100644 index 0000000..909a44a --- /dev/null +++ b/index.html @@ -0,0 +1,54 @@ + + + BlueCrypt + + +

BlueCrypt for the Browser

+

BlueCrypt is universal crypto for the browser. It's lightweight, fast, and based on native webcrypto. + This means it's easy-to-use crypto in kilobytes, not megabytes.

+ +

Keypair Generation

+
+

Key Type:

+
+ + + + +
+
+

EC Options:

+ + + + + +
+ + + + + +
 
+ + + + + diff --git a/lib/keypairs.js b/lib/keypairs.js new file mode 100644 index 0000000..bf530b8 --- /dev/null +++ b/lib/keypairs.js @@ -0,0 +1,86 @@ +/*global Promise*/ +(function (exports) { +'use strict'; + +var Keypairs = exports.Keypairs = {}; + +Keypairs._stance = "We take the stance that if you're knowledgeable enough to" + + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; +Keypairs._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support."; +Keypairs.generate = function (opts) { + var wcOpts = {}; + if (!opts) { + opts = {}; + } + if (!opts.kty) { + opts.kty = 'EC'; + } + + // ECDSA has only the P curves and an associated bitlength + if (/^EC/i.test(opts.kty)) { + wcOpts.name = 'ECDSA'; + if (!opts.namedCurve) { + opts.namedCurve = 'P-256'; + } + wcOpts.namedCurve = opts.namedCurve; // true for supported curves + if (/256/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-256'; + wcOpts.hash = { name: "SHA-256" }; + } else if (/384/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-384'; + wcOpts.hash = { name: "SHA-384" }; + } else { + return Promise.Reject(new Error("'" + wcOpts.namedCurve + "' is not an NIST approved ECDSA namedCurve. " + + " Please choose either 'P-256' or 'P-384'. " + + Keypairs._stance)); + } + } else if (/^RSA$/i.test(opts.kty)) { + // Support PSS? I don't think it's used for Let's Encrypt + wcOpts.name = 'RSASSA-PKCS1-v1_5'; + if (!opts.modulusLength) { + opts.modulusLength = 2048; + } + wcOpts.modulusLength = opts.modulusLength; + if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) { + // erring on the small side... for no good reason + wcOpts.hash = { name: "SHA-256" }; + } else if (wcOpts.modulusLength >= 3072 && wcOpts.modulusLength < 4096) { + wcOpts.hash = { name: "SHA-384" }; + } else if (wcOpts.modulusLength < 4097) { + wcOpts.hash = { name: "SHA-512" }; + } else { + // Public key thumbprints should be paired with a hash of similar length, + // so anything above SHA-512's keyspace would be left under-represented anyway. + return Promise.Reject(new Error("'" + wcOpts.modulusLength + "' is not within the safe and universally" + + " acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values" + + " divisible by 8 are allowed. " + Keypairs._stance)); + } + // TODO maybe allow this to be set to any of the standard values? + wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]); + } else { + return Promise.Reject(new Error("'" + opts.kty + "' is not a well-supported key type." + + Keypairs._universal + + " Please choose either 'EC' or 'RSA' keys.")); + } + + var extractable = true; + return window.crypto.subtle.generateKey( + wcOpts + , extractable + , [ 'sign', 'verify' ] + ).then(function (result) { + return window.crypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + // TODO remove + console.log('private jwk:'); + console.log(JSON.stringify(privJwk, null, 2)); + return { + privateKey: privJwk + }; + }); + }); +}; + +}(window)); From 692301e37d323bb37ba3284c3e069b2f30672757 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Thu, 18 Apr 2019 01:56:32 -0600 Subject: [PATCH 02/52] making headway --- app.js | 2 +- index.html | 2 + lib/acme.js | 699 +++++++++++++++++++++++++++++++++++++++++++ lib/ecdsa.js | 112 +++++++ lib/keypairs.js | 155 ++++++---- lib/keypairs.js.min2 | 86 ++++++ lib/rsa.js | 122 ++++++++ 7 files changed, 1111 insertions(+), 67 deletions(-) create mode 100644 lib/acme.js create mode 100644 lib/ecdsa.js create mode 100644 lib/keypairs.js.min2 create mode 100644 lib/rsa.js diff --git a/app.js b/app.js index 968f38d..d144211 100644 --- a/app.js +++ b/app.js @@ -41,7 +41,7 @@ function run() { , namedCurve: $('input[name="ec-crv"]:checked').value , modulusLength: $('input[name="rsa-len"]:checked').value }; - console.log(opts); + console.log('opts', opts); Keypairs.generate(opts).then(function (results) { $('.js-jwk').innerText = JSON.stringify(results, null, 2); // diff --git a/index.html b/index.html index 909a44a..575da3b 100644 --- a/index.html +++ b/index.html @@ -48,6 +48,8 @@
 
+ + diff --git a/lib/acme.js b/lib/acme.js new file mode 100644 index 0000000..4fba0fe --- /dev/null +++ b/lib/acme.js @@ -0,0 +1,699 @@ +/*global CSR*/ +// CSR takes a while to load after the page load +(function (exports) { +'use strict'; + +var BACME = exports.ACME = {}; +var webFetch = exports.fetch; +var Keypairs = exports.Keypairs; +var Promise = exports.Promise; + +var directoryUrl = 'https://acme-staging-v02.api.letsencrypt.org/directory'; +var directory; + +var nonceUrl; +var nonce; + +var accountKeypair; +var accountJwk; + +var accountUrl; + +BACME.challengePrefixes = { + 'http-01': '/.well-known/acme-challenge' +, 'dns-01': '_acme-challenge' +}; + +BACME._logHeaders = function (resp) { + console.log('Headers:'); + Array.from(resp.headers.entries()).forEach(function (h) { console.log(h[0] + ': ' + h[1]); }); +}; + +BACME._logBody = function (body) { + console.log('Body:'); + console.log(JSON.stringify(body, null, 2)); + console.log(''); +}; + +BACME.directory = function (opts) { + return webFetch(opts.directoryUrl || directoryUrl, { mode: 'cors' }).then(function (resp) { + BACME._logHeaders(resp); + return resp.json().then(function (reply) { + if (/error/.test(reply.type)) { + return Promise.reject(new Error(reply.detail || reply.type)); + } + directory = reply; + nonceUrl = directory.newNonce || 'https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce'; + accountUrl = directory.newAccount || 'https://acme-staging-v02.api.letsencrypt.org/acme/new-account'; + orderUrl = directory.newOrder || "https://acme-staging-v02.api.letsencrypt.org/acme/new-order"; + BACME._logBody(reply); + return reply; + }); + }); +}; + +BACME.nonce = function () { + return webFetch(nonceUrl, { mode: 'cors' }).then(function (resp) { + BACME._logHeaders(resp); + nonce = resp.headers.get('replay-nonce'); + console.log('Nonce:', nonce); + // resp.body is empty + return resp.headers.get('replay-nonce'); + }); +}; + +BACME.accounts = {}; + +// type = ECDSA +// bitlength = 256 +BACME.accounts.generateKeypair = function (opts) { + return BACME.generateKeypair(opts).then(function (result) { + accountKeypair = result; + + return webCrypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + + accountJwk = privJwk; + console.log('private jwk:'); + console.log(JSON.stringify(privJwk, null, 2)); + + return privJwk; + /* + return webCrypto.subtle.exportKey( + "pkcs8" + , result.privateKey + ).then(function (keydata) { + console.log('pkcs8:'); + console.log(Array.from(new Uint8Array(keydata))); + + return privJwk; + //return accountKeypair; + }); + */ + }); + }); +}; + +// json to url-safe base64 +BACME._jsto64 = function (json) { + return btoa(JSON.stringify(json)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); +}; + +var textEncoder = new TextEncoder(); + +BACME._importKey = function (jwk) { + var alg; // I think the 256 refers to the hash + var wcOpts = {}; + var extractable = true; // TODO make optionally false? + var priv = jwk; + var pub; + + // ECDSA + if (/^EC/i.test(jwk.kty)) { + wcOpts.name = 'ECDSA'; + wcOpts.namedCurve = jwk.crv; + alg = 'ES256'; + pub = { + crv: priv.crv + , kty: priv.kty + , x: priv.x + , y: priv.y + }; + if (!priv.d) { + priv = null; + } + } + + // RSA + if (/^RS/i.test(jwk.kty)) { + wcOpts.name = 'RSASSA-PKCS1-v1_5'; + wcOpts.hash = { name: "SHA-256" }; + alg = 'RS256'; + pub = { + e: priv.e + , kty: priv.kty + , n: priv.n + }; + if (!priv.p) { + priv = null; + } + } + + return window.crypto.subtle.importKey( + "jwk" + , pub + , wcOpts + , extractable + , [ "verify" ] + ).then(function (publicKey) { + function give(privateKey) { + return { + wcPub: publicKey + , wcKey: privateKey + , wcKeypair: { publicKey: publicKey, privateKey: privateKey } + , meta: { + alg: alg + , name: wcOpts.name + , hash: wcOpts.hash + } + , jwk: jwk + }; + } + if (!priv) { + return give(); + } + return window.crypto.subtle.importKey( + "jwk" + , priv + , wcOpts + , extractable + , [ "sign"/*, "verify"*/ ] + ).then(give); + }); +}; +BACME._sign = function (opts) { + var wcPrivKey = opts.abstractKey.wcKeypair.privateKey; + var wcOpts = opts.abstractKey.meta; + var alg = opts.abstractKey.meta.alg; // I think the 256 refers to the hash + var signHash; + + console.log('kty', opts.abstractKey.jwk.kty); + signHash = { name: "SHA-" + alg.replace(/[a-z]+/ig, '') }; + + var msg = textEncoder.encode(opts.protected64 + '.' + opts.payload64); + console.log('msg:', msg); + return window.crypto.subtle.sign( + { name: wcOpts.name, hash: signHash } + , wcPrivKey + , msg + ).then(function (signature) { + //console.log('sig1:', signature); + //console.log('sig2:', new Uint8Array(signature)); + //console.log('sig3:', Array.prototype.slice.call(new Uint8Array(signature))); + // convert buffer to urlsafe base64 + var sig64 = btoa(Array.prototype.map.call(new Uint8Array(signature), function (ch) { + return String.fromCharCode(ch); + }).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); + + console.log('[1] URL-safe Base64 Signature:'); + console.log(sig64); + + var signedMsg = { + protected: opts.protected64 + , payload: opts.payload64 + , signature: sig64 + }; + + console.log('Signed Base64 Msg:'); + console.log(JSON.stringify(signedMsg, null, 2)); + + return signedMsg; + }); +}; +// email = john.doe@gmail.com +// jwk = { ... } +// agree = true +BACME.accounts.sign = function (opts) { + + return BACME._importKey(opts.jwk).then(function (abstractKey) { + + var payloadJson = + { termsOfServiceAgreed: opts.agree + , onlyReturnExisting: false + , contact: opts.contacts || [ 'mailto:' + opts.email ] + }; + console.log('payload:'); + console.log(payloadJson); + var payload64 = BACME._jsto64( + payloadJson + ); + + var protectedJson = + { nonce: opts.nonce + , url: accountUrl + , alg: abstractKey.meta.alg + , jwk: null + }; + + if (/EC/i.test(opts.jwk.kty)) { + protectedJson.jwk = { + crv: opts.jwk.crv + , kty: opts.jwk.kty + , x: opts.jwk.x + , y: opts.jwk.y + }; + } else if (/RS/i.test(opts.jwk.kty)) { + protectedJson.jwk = { + e: opts.jwk.e + , kty: opts.jwk.kty + , n: opts.jwk.n + }; + } else { + return Promise.reject(new Error("[acme.accounts.sign] unsupported key type '" + opts.jwk.kty + "'")); + } + + console.log('protected:'); + console.log(protectedJson); + var protected64 = BACME._jsto64( + protectedJson + ); + + // Note: this function hashes before signing so send data, not the hash + return BACME._sign({ + abstractKey: abstractKey + , payload64: payload64 + , protected64: protected64 + }); + }); +}; + +var accountId; + +BACME.accounts.set = function (opts) { + nonce = null; + return window.fetch(accountUrl, { + mode: 'cors' + , method: 'POST' + , headers: { 'Content-Type': 'application/jose+json' } + , body: JSON.stringify(opts.signedAccount) + }).then(function (resp) { + BACME._logHeaders(resp); + nonce = resp.headers.get('replay-nonce'); + accountId = resp.headers.get('location'); + console.log('Next nonce:', nonce); + console.log('Location/kid:', accountId); + + if (!resp.headers.get('content-type')) { + console.log('Body: '); + + return { kid: accountId }; + } + + return resp.json().then(function (result) { + if (/^Error/i.test(result.detail)) { + return Promise.reject(new Error(result.detail)); + } + result.kid = accountId; + BACME._logBody(result); + + return result; + }); + }); +}; + +var orderUrl; + +BACME.orders = {}; + +// identifiers = [ { type: 'dns', value: 'example.com' }, { type: 'dns', value: '*.example.com' } ] +// signedAccount +BACME.orders.sign = function (opts) { + var payload64 = BACME._jsto64({ identifiers: opts.identifiers }); + + return BACME._importKey(opts.jwk).then(function (abstractKey) { + var protected64 = BACME._jsto64( + { nonce: nonce, alg: abstractKey.meta.alg/*'ES256'*/, url: orderUrl, kid: opts.kid } + ); + console.log('abstractKey:'); + console.log(abstractKey); + return BACME._sign({ + abstractKey: abstractKey + , payload64: payload64 + , protected64: protected64 + }).then(function (sig) { + if (!sig) { + throw new Error('sig is undefined... nonsense!'); + } + console.log('newsig', sig); + return sig; + }); + }); +}; + +var currentOrderUrl; +var authorizationUrls; +var finalizeUrl; + +BACME.orders.create = function (opts) { + nonce = null; + return window.fetch(orderUrl, { + mode: 'cors' + , method: 'POST' + , headers: { 'Content-Type': 'application/jose+json' } + , body: JSON.stringify(opts.signedOrder) + }).then(function (resp) { + BACME._logHeaders(resp); + currentOrderUrl = resp.headers.get('location'); + nonce = resp.headers.get('replay-nonce'); + console.log('Next nonce:', nonce); + + return resp.json().then(function (result) { + if (/^Error/i.test(result.detail)) { + return Promise.reject(new Error(result.detail)); + } + authorizationUrls = result.authorizations; + finalizeUrl = result.finalize; + BACME._logBody(result); + + result.url = currentOrderUrl; + return result; + }); + }); +}; + +BACME.challenges = {}; +BACME.challenges.all = function () { + var challenges = []; + + function next() { + if (!authorizationUrls.length) { + return challenges; + } + + return BACME.challenges.view().then(function (challenge) { + challenges.push(challenge); + return next(); + }); + } + + return next(); +}; +BACME.challenges.view = function () { + var authzUrl = authorizationUrls.pop(); + var token; + var challengeDomain; + var challengeUrl; + + return window.fetch(authzUrl, { + mode: 'cors' + }).then(function (resp) { + BACME._logHeaders(resp); + + return resp.json().then(function (result) { + // Note: select the challenge you wish to use + var challenge = result.challenges.slice(0).pop(); + token = challenge.token; + challengeUrl = challenge.url; + challengeDomain = result.identifier.value; + + BACME._logBody(result); + + return { + challenges: result.challenges + , expires: result.expires + , identifier: result.identifier + , status: result.status + , wildcard: result.wildcard + //, token: challenge.token + //, url: challenge.url + //, domain: result.identifier.value, + }; + }); + }); +}; + +var thumbprint; +var keyAuth; +var httpPath; +var dnsAuth; +var dnsRecord; + +BACME.thumbprint = function (opts) { + // https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk + + var accountJwk = opts.jwk; + var keys; + + if (/^EC/i.test(opts.jwk.kty)) { + keys = [ 'crv', 'kty', 'x', 'y' ]; + } else if (/^RS/i.test(opts.jwk.kty)) { + keys = [ 'e', 'kty', 'n' ]; + } + + var accountPublicStr = '{' + keys.map(function (key) { + return '"' + key + '":"' + accountJwk[key] + '"'; + }).join(',') + '}'; + + return window.crypto.subtle.digest( + { name: "SHA-256" } // SHA-256 is spec'd, non-optional + , textEncoder.encode(accountPublicStr) + ).then(function (hash) { + thumbprint = btoa(Array.prototype.map.call(new Uint8Array(hash), function (ch) { + return String.fromCharCode(ch); + }).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); + + console.log('Thumbprint:'); + console.log(opts); + console.log(accountPublicStr); + console.log(thumbprint); + + return thumbprint; + }); +}; + +// { token, thumbprint, challengeDomain } +BACME.challenges['http-01'] = function (opts) { + // The contents of the key authorization file + keyAuth = opts.token + '.' + opts.thumbprint; + + // Where the key authorization file goes + httpPath = 'http://' + opts.challengeDomain + '/.well-known/acme-challenge/' + opts.token; + + console.log("echo '" + keyAuth + "' > '" + httpPath + "'"); + + return { + path: httpPath + , value: keyAuth + }; +}; + +// { keyAuth } +BACME.challenges['dns-01'] = function (opts) { + console.log('opts.keyAuth for DNS:'); + console.log(opts.keyAuth); + return window.crypto.subtle.digest( + { name: "SHA-256", } + , textEncoder.encode(opts.keyAuth) + ).then(function (hash) { + dnsAuth = btoa(Array.prototype.map.call(new Uint8Array(hash), function (ch) { + return String.fromCharCode(ch); + }).join('')).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); + + dnsRecord = '_acme-challenge.' + opts.challengeDomain; + + console.log('DNS TXT Auth:'); + // The name of the record + console.log(dnsRecord); + // The TXT record value + console.log(dnsAuth); + + return { + type: 'TXT' + , host: dnsRecord + , answer: dnsAuth + }; + }); +}; + +var challengePollUrl; + +// { jwk, challengeUrl, accountId (kid) } +BACME.challenges.accept = function (opts) { + var payload64 = BACME._jsto64({}); + + return BACME._importKey(opts.jwk).then(function (abstractKey) { + var protected64 = BACME._jsto64( + { nonce: nonce, alg: abstractKey.meta.alg/*'ES256'*/, url: opts.challengeUrl, kid: opts.accountId } + ); + return BACME._sign({ + abstractKey: abstractKey + , payload64: payload64 + , protected64: protected64 + }); + }).then(function (signedAccept) { + + nonce = null; + return window.fetch( + opts.challengeUrl + , { mode: 'cors' + , method: 'POST' + , headers: { 'Content-Type': 'application/jose+json' } + , body: JSON.stringify(signedAccept) + } + ).then(function (resp) { + BACME._logHeaders(resp); + nonce = resp.headers.get('replay-nonce'); + console.log("ACCEPT NONCE:", nonce); + + return resp.json().then(function (reply) { + challengePollUrl = reply.url; + + console.log('Challenge ACK:'); + console.log(JSON.stringify(reply)); + return reply; + }); + }); + }); +}; + +BACME.challenges.check = function (opts) { + return window.fetch(opts.challengePollUrl, { mode: 'cors' }).then(function (resp) { + BACME._logHeaders(resp); + + return resp.json().then(function (reply) { + if (/error/.test(reply.type)) { + return Promise.reject(new Error(reply.detail || reply.type)); + } + challengePollUrl = reply.url; + + BACME._logBody(reply); + + return reply; + }); + }); +}; + +var domainKeypair; +var domainJwk; + +BACME.generateKeypair = function (opts) { + var wcOpts = {}; + + // ECDSA has only the P curves and an associated bitlength + if (/^EC/i.test(opts.type)) { + wcOpts.name = 'ECDSA'; + if (/256/.test(opts.bitlength)) { + wcOpts.namedCurve = 'P-256'; + } + } + + // RSA-PSS is another option, but I don't think it's used for Let's Encrypt + // I think the hash is only necessary for signing, not generation or import + if (/^RS/i.test(opts.type)) { + wcOpts.name = 'RSASSA-PKCS1-v1_5'; + wcOpts.modulusLength = opts.bitlength; + if (opts.bitlength < 2048) { + wcOpts.modulusLength = opts.bitlength * 8; + } + wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]); + wcOpts.hash = { name: "SHA-256" }; + } + var extractable = true; + return window.crypto.subtle.generateKey( + wcOpts + , extractable + , [ 'sign', 'verify' ] + ); +}; +BACME.domains = {}; +// TODO factor out from BACME.accounts.generateKeypair even more +BACME.domains.generateKeypair = function (opts) { + return BACME.generateKeypair(opts).then(function (result) { + domainKeypair = result; + + return window.crypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + + domainJwk = privJwk; + console.log('private jwk:'); + console.log(JSON.stringify(privJwk, null, 2)); + + return privJwk; + }); + }); +}; + +// { serverJwk, domains } +BACME.orders.generateCsr = function (opts) { + return BACME._importKey(opts.serverJwk).then(function (abstractKey) { + return Promise.resolve(CSR.generate({ keypair: abstractKey.wcKeypair, domains: opts.domains })); + }); +}; + +var certificateUrl; + +// { csr, jwk, finalizeUrl, accountId } +BACME.orders.finalize = function (opts) { + var payload64 = BACME._jsto64( + { csr: opts.csr } + ); + + return BACME._importKey(opts.jwk).then(function (abstractKey) { + var protected64 = BACME._jsto64( + { nonce: nonce, alg: abstractKey.meta.alg/*'ES256'*/, url: opts.finalizeUrl, kid: opts.accountId } + ); + return BACME._sign({ + abstractKey: abstractKey + , payload64: payload64 + , protected64: protected64 + }); + }).then(function (signedFinal) { + + nonce = null; + return window.fetch( + opts.finalizeUrl + , { mode: 'cors' + , method: 'POST' + , headers: { 'Content-Type': 'application/jose+json' } + , body: JSON.stringify(signedFinal) + } + ).then(function (resp) { + BACME._logHeaders(resp); + nonce = resp.headers.get('replay-nonce'); + + return resp.json().then(function (reply) { + if (/error/.test(reply.type)) { + return Promise.reject(new Error(reply.detail || reply.type)); + } + certificateUrl = reply.certificate; + BACME._logBody(reply); + + return reply; + }); + }); + }); +}; + +BACME.orders.receive = function (opts) { + return window.fetch( + opts.certificateUrl + , { mode: 'cors' + , method: 'GET' + } + ).then(function (resp) { + BACME._logHeaders(resp); + nonce = resp.headers.get('replay-nonce'); + + return resp.text().then(function (reply) { + BACME._logBody(reply); + + return reply; + }); + }); +}; + +BACME.orders.check = function (opts) { + return window.fetch( + opts.orderUrl + , { mode: 'cors' + , method: 'GET' + } + ).then(function (resp) { + BACME._logHeaders(resp); + + return resp.json().then(function (reply) { + if (/error/.test(reply.type)) { + return Promise.reject(new Error(reply.detail || reply.type)); + } + BACME._logBody(reply); + + return reply; + }); + }); +}; + +}(window)); diff --git a/lib/ecdsa.js b/lib/ecdsa.js new file mode 100644 index 0000000..dedc4fb --- /dev/null +++ b/lib/ecdsa.js @@ -0,0 +1,112 @@ +/*global Promise*/ +(function (exports) { +'use strict'; + +var EC = exports.Eckles = {}; +if ('undefined' !== typeof module) { module.exports = EC; } +var Enc = {}; +var textEncoder = new TextEncoder(); + +EC._stance = "We take the stance that if you're knowledgeable enough to" + + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; +EC._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support."; +EC.generate = function (opts) { + var wcOpts = {}; + if (!opts) { opts = {}; } + if (!opts.kty) { opts.kty = 'EC'; } + + // ECDSA has only the P curves and an associated bitlength + wcOpts.name = 'ECDSA'; + if (!opts.namedCurve) { + opts.namedCurve = 'P-256'; + } + wcOpts.namedCurve = opts.namedCurve; // true for supported curves + if (/256/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-256'; + wcOpts.hash = { name: "SHA-256" }; + } else if (/384/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-384'; + wcOpts.hash = { name: "SHA-384" }; + } else { + return Promise.Reject(new Error("'" + wcOpts.namedCurve + "' is not an NIST approved ECDSA namedCurve. " + + " Please choose either 'P-256' or 'P-384'. " + + EC._stance)); + } + + var extractable = true; + return window.crypto.subtle.generateKey( + wcOpts + , extractable + , [ 'sign', 'verify' ] + ).then(function (result) { + return window.crypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + return { + private: privJwk + , public: EC.neuter({ jwk: privJwk }) + }; + }); + }); +}; + +// Chopping off the private parts is now part of the public API. +// I thought it sounded a little too crude at first, but it really is the best name in every possible way. +EC.neuter = function (opts) { + // trying to find the best balance of an immutable copy with custom attributes + var jwk = {}; + Object.keys(opts.jwk).forEach(function (k) { + if ('undefined' === typeof opts.jwk[k]) { return; } + // ignore EC private parts + if ('d' === k) { return; } + jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k])); + }); + return jwk; +}; + +// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk +EC.__thumbprint = function (jwk) { + // Use the same entropy for SHA as for key + var alg = 'SHA-256'; + if (/384/.test(jwk.crv)) { + alg = 'SHA-384'; + } + return window.crypto.subtle.digest( + { name: alg } + , textEncoder.encode('{"crv":"' + jwk.crv + '","kty":"EC","x":"' + jwk.x + '","y":"' + jwk.y + '"}') + ).then(function (hash) { + return Enc.bufToUrlBase64(new Uint8Array(hash)); + }); +}; + +EC.thumbprint = function (opts) { + return Promise.resolve().then(function () { + var jwk; + if ('EC' === opts.kty) { + jwk = opts; + } else if (opts.jwk) { + jwk = opts.jwk; + } else { + return EC.import(opts).then(function (jwk) { + return EC.__thumbprint(jwk); + }); + } + return EC.__thumbprint(jwk); + }); +}; + +Enc.bufToUrlBase64 = function (u8) { + return Enc.bufToBase64(u8) + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +}; + +Enc.bufToBase64 = function (u8) { + var bin = ''; + u8.forEach(function (i) { + bin += String.fromCharCode(i); + }); + return btoa(bin); +}; + +}('undefined' !== typeof module ? module.exports : window)); diff --git a/lib/keypairs.js b/lib/keypairs.js index bf530b8..1f3196c 100644 --- a/lib/keypairs.js +++ b/lib/keypairs.js @@ -3,84 +3,107 @@ 'use strict'; var Keypairs = exports.Keypairs = {}; +var Rasha = exports.Rasha || require('rasha'); +var Eckles = exports.Eckles || require('eckles'); Keypairs._stance = "We take the stance that if you're knowledgeable enough to" + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; Keypairs._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support."; Keypairs.generate = function (opts) { - var wcOpts = {}; - if (!opts) { - opts = {}; - } - if (!opts.kty) { - opts.kty = 'EC'; - } - - // ECDSA has only the P curves and an associated bitlength + opts = opts || {}; + var p; + if (!opts.kty) { opts.kty = opts.type; } + if (!opts.kty) { opts.kty = 'EC'; } if (/^EC/i.test(opts.kty)) { - wcOpts.name = 'ECDSA'; - if (!opts.namedCurve) { - opts.namedCurve = 'P-256'; - } - wcOpts.namedCurve = opts.namedCurve; // true for supported curves - if (/256/.test(wcOpts.namedCurve)) { - wcOpts.namedCurve = 'P-256'; - wcOpts.hash = { name: "SHA-256" }; - } else if (/384/.test(wcOpts.namedCurve)) { - wcOpts.namedCurve = 'P-384'; - wcOpts.hash = { name: "SHA-384" }; - } else { - return Promise.Reject(new Error("'" + wcOpts.namedCurve + "' is not an NIST approved ECDSA namedCurve. " - + " Please choose either 'P-256' or 'P-384'. " - + Keypairs._stance)); - } + p = Eckles.generate(opts); } else if (/^RSA$/i.test(opts.kty)) { - // Support PSS? I don't think it's used for Let's Encrypt - wcOpts.name = 'RSASSA-PKCS1-v1_5'; - if (!opts.modulusLength) { - opts.modulusLength = 2048; - } - wcOpts.modulusLength = opts.modulusLength; - if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) { - // erring on the small side... for no good reason - wcOpts.hash = { name: "SHA-256" }; - } else if (wcOpts.modulusLength >= 3072 && wcOpts.modulusLength < 4096) { - wcOpts.hash = { name: "SHA-384" }; - } else if (wcOpts.modulusLength < 4097) { - wcOpts.hash = { name: "SHA-512" }; - } else { - // Public key thumbprints should be paired with a hash of similar length, - // so anything above SHA-512's keyspace would be left under-represented anyway. - return Promise.Reject(new Error("'" + wcOpts.modulusLength + "' is not within the safe and universally" - + " acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values" - + " divisible by 8 are allowed. " + Keypairs._stance)); - } - // TODO maybe allow this to be set to any of the standard values? - wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]); + p = Rasha.generate(opts); } else { return Promise.Reject(new Error("'" + opts.kty + "' is not a well-supported key type." + Keypairs._universal - + " Please choose either 'EC' or 'RSA' keys.")); + + " Please choose 'EC', or 'RSA' if you have good reason to.")); } - - var extractable = true; - return window.crypto.subtle.generateKey( - wcOpts - , extractable - , [ 'sign', 'verify' ] - ).then(function (result) { - return window.crypto.subtle.exportKey( - "jwk" - , result.privateKey - ).then(function (privJwk) { - // TODO remove - console.log('private jwk:'); - console.log(JSON.stringify(privJwk, null, 2)); - return { - privateKey: privJwk - }; + return p.then(function (pair) { + return Keypairs.thumbprint({ jwk: pair.public }).then(function (thumb) { + pair.private.kid = thumb; // maybe not the same id on the private key? + pair.public.kid = thumb; + return pair; }); }); }; -}(window)); + +// Chopping off the private parts is now part of the public API. +// I thought it sounded a little too crude at first, but it really is the best name in every possible way. +Keypairs.neuter = Keypairs._neuter = function (opts) { + // trying to find the best balance of an immutable copy with custom attributes + var jwk = {}; + Object.keys(opts.jwk).forEach(function (k) { + if ('undefined' === typeof opts.jwk[k]) { return; } + // ignore RSA and EC private parts + if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; } + jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k])); + }); + return jwk; +}; + +Keypairs.thumbprint = function (opts) { + return Promise.resolve().then(function () { + if (/EC/i.test(opts.jwk.kty)) { + return Eckles.thumbprint(opts); + } else { + return Rasha.thumbprint(opts); + } + }); +}; + +Keypairs.publish = function (opts) { + if ('object' !== typeof opts.jwk || !opts.jwk.kty) { throw new Error("invalid jwk: " + JSON.stringify(opts.jwk)); } + + // returns a copy + var jwk = Keypairs.neuter(opts); + + if (jwk.exp) { + jwk.exp = setTime(jwk.exp); + } else { + if (opts.exp) { jwk.exp = setTime(opts.exp); } + else if (opts.expiresIn) { jwk.exp = Math.round(Date.now()/1000) + opts.expiresIn; } + else if (opts.expiresAt) { jwk.exp = opts.expiresAt; } + } + if (!jwk.use && false !== jwk.use) { jwk.use = "sig"; } + + if (jwk.kid) { return Promise.resolve(jwk); } + return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) { jwk.kid = thumb; return jwk; }); +}; + +function setTime(time) { + if ('number' === typeof time) { return time; } + + var t = time.match(/^(\-?\d+)([dhms])$/i); + if (!t || !t[0]) { + throw new Error("'" + time + "' should be datetime in seconds or human-readable format (i.e. 3d, 1h, 15m, 30s"); + } + + var now = Math.round(Date.now()/1000); + var num = parseInt(t[1], 10); + var unit = t[2]; + var mult = 1; + switch(unit) { + // fancy fallthrough, what fun! + case 'd': + mult *= 24; + /*falls through*/ + case 'h': + mult *= 60; + /*falls through*/ + case 'm': + mult *= 60; + /*falls through*/ + case 's': + mult *= 1; + } + + return now + (mult * num); +} + +}('undefined' !== typeof module ? module.exports : window)); diff --git a/lib/keypairs.js.min2 b/lib/keypairs.js.min2 new file mode 100644 index 0000000..bf530b8 --- /dev/null +++ b/lib/keypairs.js.min2 @@ -0,0 +1,86 @@ +/*global Promise*/ +(function (exports) { +'use strict'; + +var Keypairs = exports.Keypairs = {}; + +Keypairs._stance = "We take the stance that if you're knowledgeable enough to" + + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; +Keypairs._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support."; +Keypairs.generate = function (opts) { + var wcOpts = {}; + if (!opts) { + opts = {}; + } + if (!opts.kty) { + opts.kty = 'EC'; + } + + // ECDSA has only the P curves and an associated bitlength + if (/^EC/i.test(opts.kty)) { + wcOpts.name = 'ECDSA'; + if (!opts.namedCurve) { + opts.namedCurve = 'P-256'; + } + wcOpts.namedCurve = opts.namedCurve; // true for supported curves + if (/256/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-256'; + wcOpts.hash = { name: "SHA-256" }; + } else if (/384/.test(wcOpts.namedCurve)) { + wcOpts.namedCurve = 'P-384'; + wcOpts.hash = { name: "SHA-384" }; + } else { + return Promise.Reject(new Error("'" + wcOpts.namedCurve + "' is not an NIST approved ECDSA namedCurve. " + + " Please choose either 'P-256' or 'P-384'. " + + Keypairs._stance)); + } + } else if (/^RSA$/i.test(opts.kty)) { + // Support PSS? I don't think it's used for Let's Encrypt + wcOpts.name = 'RSASSA-PKCS1-v1_5'; + if (!opts.modulusLength) { + opts.modulusLength = 2048; + } + wcOpts.modulusLength = opts.modulusLength; + if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) { + // erring on the small side... for no good reason + wcOpts.hash = { name: "SHA-256" }; + } else if (wcOpts.modulusLength >= 3072 && wcOpts.modulusLength < 4096) { + wcOpts.hash = { name: "SHA-384" }; + } else if (wcOpts.modulusLength < 4097) { + wcOpts.hash = { name: "SHA-512" }; + } else { + // Public key thumbprints should be paired with a hash of similar length, + // so anything above SHA-512's keyspace would be left under-represented anyway. + return Promise.Reject(new Error("'" + wcOpts.modulusLength + "' is not within the safe and universally" + + " acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values" + + " divisible by 8 are allowed. " + Keypairs._stance)); + } + // TODO maybe allow this to be set to any of the standard values? + wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]); + } else { + return Promise.Reject(new Error("'" + opts.kty + "' is not a well-supported key type." + + Keypairs._universal + + " Please choose either 'EC' or 'RSA' keys.")); + } + + var extractable = true; + return window.crypto.subtle.generateKey( + wcOpts + , extractable + , [ 'sign', 'verify' ] + ).then(function (result) { + return window.crypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + // TODO remove + console.log('private jwk:'); + console.log(JSON.stringify(privJwk, null, 2)); + return { + privateKey: privJwk + }; + }); + }); +}; + +}(window)); diff --git a/lib/rsa.js b/lib/rsa.js new file mode 100644 index 0000000..4ec7e07 --- /dev/null +++ b/lib/rsa.js @@ -0,0 +1,122 @@ +/*global Promise*/ +(function (exports) { +'use strict'; + +var RSA = exports.Rasha = {}; +if ('undefined' !== typeof module) { module.exports = RSA; } +var Enc = {}; +var textEncoder = new TextEncoder(); + +RSA._stance = "We take the stance that if you're knowledgeable enough to" + + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; +RSA._universal = "Bluecrypt only supports crypto with standard cross-browser and cross-platform support."; +RSA.generate = function (opts) { + var wcOpts = {}; + if (!opts) { opts = {}; } + if (!opts.kty) { opts.kty = 'RSA'; } + + // Support PSS? I don't think it's used for Let's Encrypt + wcOpts.name = 'RSASSA-PKCS1-v1_5'; + if (!opts.modulusLength) { + opts.modulusLength = 2048; + } + wcOpts.modulusLength = opts.modulusLength; + if (wcOpts.modulusLength >= 2048 && wcOpts.modulusLength < 3072) { + // erring on the small side... for no good reason + wcOpts.hash = { name: "SHA-256" }; + } else if (wcOpts.modulusLength >= 3072 && wcOpts.modulusLength < 4096) { + wcOpts.hash = { name: "SHA-384" }; + } else if (wcOpts.modulusLength < 4097) { + wcOpts.hash = { name: "SHA-512" }; + } else { + // Public key thumbprints should be paired with a hash of similar length, + // so anything above SHA-512's keyspace would be left under-represented anyway. + return Promise.Reject(new Error("'" + wcOpts.modulusLength + "' is not within the safe and universally" + + " acceptable range of 2048-4096. Typically you should pick 2048, 3072, or 4096, though other values" + + " divisible by 8 are allowed. " + RSA._stance)); + } + // TODO maybe allow this to be set to any of the standard values? + wcOpts.publicExponent = new Uint8Array([0x01, 0x00, 0x01]); + + var extractable = true; + return window.crypto.subtle.generateKey( + wcOpts + , extractable + , [ 'sign', 'verify' ] + ).then(function (result) { + return window.crypto.subtle.exportKey( + "jwk" + , result.privateKey + ).then(function (privJwk) { + return { + private: privJwk + , public: RSA.neuter({ jwk: privJwk }) + }; + }); + }); +}; + +// Chopping off the private parts is now part of the public API. +// I thought it sounded a little too crude at first, but it really is the best name in every possible way. +RSA.neuter = function (opts) { + // trying to find the best balance of an immutable copy with custom attributes + var jwk = {}; + Object.keys(opts.jwk).forEach(function (k) { + if ('undefined' === typeof opts.jwk[k]) { return; } + // ignore RSA private parts + if (-1 !== ['d', 'p', 'q', 'dp', 'dq', 'qi'].indexOf(k)) { return; } + jwk[k] = JSON.parse(JSON.stringify(opts.jwk[k])); + }); + return jwk; +}; + +// https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk +RSA.__thumbprint = function (jwk) { + // Use the same entropy for SHA as for key + var len = Math.floor(jwk.n.length * 0.75); + var alg = 'SHA-256'; + // TODO this may be a bug + // need to confirm that the padding is no more or less than 1 byte + if (len >= 511) { + alg = 'SHA-512'; + } else if (len >= 383) { + alg = 'SHA-384'; + } + return window.crypto.subtle.digest( + { name: alg } + , textEncoder.encode('{"e":"' + jwk.e + '","kty":"RSA","n":"' + jwk.n + '"}') + ).then(function (hash) { + return Enc.bufToUrlBase64(new Uint8Array(hash)); + }); +}; + +RSA.thumbprint = function (opts) { + return Promise.resolve().then(function () { + var jwk; + if ('EC' === opts.kty) { + jwk = opts; + } else if (opts.jwk) { + jwk = opts.jwk; + } else { + return RSA.import(opts).then(function (jwk) { + return RSA.__thumbprint(jwk); + }); + } + return RSA.__thumbprint(jwk); + }); +}; + +Enc.bufToUrlBase64 = function (u8) { + return Enc.bufToBase64(u8) + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +}; + +Enc.bufToBase64 = function (u8) { + var bin = ''; + u8.forEach(function (i) { + bin += String.fromCharCode(i); + }); + return btoa(bin); +}; + +}('undefined' !== typeof module ? module.exports : window)); From 66e2cb70a845dce619e112a7845896abe73c7537 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 19 Apr 2019 23:14:36 -0600 Subject: [PATCH 03/52] rename --- lib/{acme.js => browser-acme.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename lib/{acme.js => browser-acme.js} (100%) diff --git a/lib/acme.js b/lib/browser-acme.js similarity index 100% rename from lib/acme.js rename to lib/browser-acme.js From 959d2ff009639720f6a3bc26bf8b5550e01118a7 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Sat, 20 Apr 2019 00:09:36 -0600 Subject: [PATCH 04/52] begin node -> browser conversion --- index.html | 1 + lib/acme.js | 935 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 936 insertions(+) create mode 100644 lib/acme.js diff --git a/index.html b/index.html index 575da3b..ea6b027 100644 --- a/index.html +++ b/index.html @@ -51,6 +51,7 @@ + diff --git a/lib/acme.js b/lib/acme.js new file mode 100644 index 0000000..3e6fb96 --- /dev/null +++ b/lib/acme.js @@ -0,0 +1,935 @@ +// Copyright 2018-present 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/. */ +(function (exports) { +'use strict'; +/* globals Promise */ + +var ACME = exports.ACME = {}; +var Enc = exports.Enc || {}; +var Crypto = exports.Crypto || {}; + +ACME.formatPemChain = function formatPemChain(str) { + return str.trim().replace(/[\r\n]+/g, '\n').replace(/\-\n\-/g, '-\n\n-') + '\n'; +}; +ACME.splitPemChain = function splitPemChain(str) { + return str.trim().split(/[\r\n]{2,}/g).map(function (str) { + return str + '\n'; + }); +}; + + +// http-01: GET https://example.org/.well-known/acme-challenge/{{token}} => {{keyAuth}} +// dns-01: TXT _acme-challenge.example.org. => "{{urlSafeBase64(sha256(keyAuth))}}" +ACME.challengePrefixes = { + 'http-01': '/.well-known/acme-challenge' +, 'dns-01': '_acme-challenge' +}; +ACME.challengeTests = { + 'http-01': function (me, auth) { + var url = 'http://' + auth.hostname + ACME.challengePrefixes['http-01'] + '/' + auth.token; + return me._request({ method: 'GET', url: url }).then(function (resp) { + var err; + + // TODO limit the number of bytes that are allowed to be downloaded + if (auth.keyAuthorization === resp.body.toString('utf8').trim()) { + return true; + } + + err = new Error( + "Error: Failed HTTP-01 Pre-Flight / Dry Run.\n" + + "curl '" + url + "'\n" + + "Expected: '" + auth.keyAuthorization + "'\n" + + "Got: '" + resp.body + "'\n" + + "See https://git.coolaj86.com/coolaj86/acme-v2.js/issues/4" + ); + err.code = 'E_FAIL_DRY_CHALLENGE'; + return Promise.reject(err); + }); + } +, 'dns-01': function (me, auth) { + // remove leading *. on wildcard domains + return me.dig({ + type: 'TXT' + , name: auth.dnsHost + }).then(function (ans) { + var err; + + if (ans.answer.some(function (txt) { + return auth.dnsAuthorization === txt.data[0]; + })) { + return true; + } + + err = new Error( + "Error: Failed DNS-01 Pre-Flight Dry Run.\n" + + "dig TXT '" + auth.dnsHost + "' does not return '" + auth.dnsAuthorization + "'\n" + + "See https://git.coolaj86.com/coolaj86/acme-v2.js/issues/4" + ); + err.code = 'E_FAIL_DRY_CHALLENGE'; + return Promise.reject(err); + }); + } +}; + +ACME._directory = function (me) { + // GET-as-GET ok + return me._request({ method: 'GET', url: me.directoryUrl, json: true }); +}; +ACME._getNonce = function (me) { + // GET-as-GET, HEAD-as-HEAD ok + if (me._nonce) { return new Promise(function (resolve) { resolve(me._nonce); return; }); } + return me._request({ method: 'HEAD', url: me._directoryUrls.newNonce }).then(function (resp) { + me._nonce = resp.toJSON().headers['replay-nonce']; + return me._nonce; + }); +}; +// ACME RFC Section 7.3 Account Creation +/* + { + "protected": base64url({ + "alg": "ES256", + "jwk": {...}, + "nonce": "6S8IqOGY7eL2lsGoTZYifg", + "url": "https://example.com/acme/new-account" + }), + "payload": base64url({ + "termsOfServiceAgreed": true, + "onlyReturnExisting": false, + "contact": [ + "mailto:cert-admin@example.com", + "mailto:admin@example.com" + ] + }), + "signature": "RZPOnYoPs1PhjszF...-nh6X1qtOFPB519I" + } +*/ +ACME._registerAccount = function (me, options) { + if (me.debug) { console.debug('[acme-v2] accounts.create'); } + + return ACME._getNonce(me).then(function () { + return new Promise(function (resolve, reject) { + + function agree(tosUrl) { + var err; + if (me._tos !== tosUrl) { + err = new Error("You must agree to the ToS at '" + me._tos + "'"); + err.code = "E_AGREE_TOS"; + reject(err); + return; + } + + var jwk = me.RSA.exportPublicJwk(options.accountKeypair); + var contact; + if (options.contact) { + contact = options.contact.slice(0); + } else if (options.email) { + contact = [ 'mailto:' + options.email ]; + } + var body = { + termsOfServiceAgreed: tosUrl === me._tos + , onlyReturnExisting: false + , contact: contact + }; + if (options.externalAccount) { + // TODO is this really done by HMAC or is it arbitrary? + body.externalAccountBinding = me.RSA.signJws( + options.externalAccount.secret + , undefined + , { alg: "HS256" + , kid: options.externalAccount.id + , url: me._directoryUrls.newAccount + } + , Buffer.from(JSON.stringify(jwk)) + ); + } + var payload = JSON.stringify(body); + var jws = me.RSA.signJws( + options.accountKeypair + , undefined + , { nonce: me._nonce + , alg: (me._alg || 'RS256') + , url: me._directoryUrls.newAccount + , jwk: jwk + } + , Buffer.from(payload) + ); + + delete jws.header; + if (me.debug) { console.debug('[acme-v2] accounts.create JSON body:'); } + if (me.debug) { console.debug(jws); } + me._nonce = null; + return me._request({ + method: 'POST' + , url: me._directoryUrls.newAccount + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + var account = resp.body; + + if (2 !== Math.floor(resp.statusCode / 100)) { + throw new Error('account error: ' + JSON.stringify(body)); + } + + me._nonce = resp.toJSON().headers['replay-nonce']; + var location = resp.toJSON().headers.location; + // the account id url + me._kid = location; + if (me.debug) { console.debug('[DEBUG] new account location:'); } + if (me.debug) { console.debug(location); } + if (me.debug) { console.debug(resp.toJSON()); } + + /* + { + contact: ["mailto:jon@example.com"], + orders: "https://some-url", + status: 'valid' + } + */ + if (!account) { account = { _emptyResponse: true, key: {} }; } + // https://git.coolaj86.com/coolaj86/acme-v2.js/issues/8 + if (!account.key) { account.key = {}; } + account.key.kid = me._kid; + return account; + }).then(resolve, reject); + } + + if (me.debug) { console.debug('[acme-v2] agreeToTerms'); } + if (1 === options.agreeToTerms.length) { + // newer promise API + return options.agreeToTerms(me._tos).then(agree, reject); + } + else if (2 === options.agreeToTerms.length) { + // backwards compat cb API + return options.agreeToTerms(me._tos, function (err, tosUrl) { + if (!err) { agree(tosUrl); return; } + reject(err); + }); + } + else { + reject(new Error('agreeToTerms has incorrect function signature.' + + ' Should be fn(tos) { return Promise; }')); + } + }); + }); +}; +/* + POST /acme/new-order HTTP/1.1 + Host: example.com + Content-Type: application/jose+json + + { + "protected": base64url({ + "alg": "ES256", + "kid": "https://example.com/acme/acct/1", + "nonce": "5XJ1L3lEkMG7tR6pA00clA", + "url": "https://example.com/acme/new-order" + }), + "payload": base64url({ + "identifiers": [{"type:"dns","value":"example.com"}], + "notBefore": "2016-01-01T00:00:00Z", + "notAfter": "2016-01-08T00:00:00Z" + }), + "signature": "H6ZXtGjTZyUnPeKn...wEA4TklBdh3e454g" + } +*/ +ACME._getChallenges = function (me, options, auth) { + if (me.debug) { console.debug('\n[DEBUG] getChallenges\n'); } + // TODO POST-as-GET + return me._request({ method: 'GET', url: auth, json: true }).then(function (resp) { + return resp.body; + }); +}; +ACME._wait = function wait(ms) { + return new Promise(function (resolve) { + setTimeout(resolve, (ms || 1100)); + }); +}; + +ACME._testChallengeOptions = function () { + var chToken = ACME._prnd(16); + return [ + { + "type": "http-01", + "status": "pending", + "url": "https://acme-staging-v02.example.com/0", + "token": "test-" + chToken + "-0" + } + , { + "type": "dns-01", + "status": "pending", + "url": "https://acme-staging-v02.example.com/1", + "token": "test-" + chToken + "-1", + "_wildcard": true + } + , { + "type": "tls-sni-01", + "status": "pending", + "url": "https://acme-staging-v02.example.com/2", + "token": "test-" + chToken + "-2" + } + , { + "type": "tls-alpn-01", + "status": "pending", + "url": "https://acme-staging-v02.example.com/3", + "token": "test-" + chToken + "-3" + } + ]; +}; +ACME._testChallenges = function (me, options) { + if (me.skipChallengeTest) { + return Promise.resolve(); + } + + var CHECK_DELAY = 0; + return Promise.all(options.domains.map(function (identifierValue) { + // TODO we really only need one to pass, not all to pass + var challenges = ACME._testChallengeOptions(); + if (identifierValue.includes("*")) { + challenges = challenges.filter(function (ch) { return ch._wildcard; }); + } + + var challenge = ACME._chooseChallenge(options, { challenges: challenges }); + if (!challenge) { + // For example, wildcards require dns-01 and, if we don't have that, we have to bail + var enabled = options.challengeTypes.join(', ') || 'none'; + var suitable = challenges.map(function (r) { return r.type; }).join(', ') || 'none'; + return Promise.reject(new Error( + "None of the challenge types that you've enabled ( " + enabled + " )" + + " are suitable for validating the domain you've selected (" + identifierValue + ")." + + " You must enable one of ( " + suitable + " )." + )); + } + if ('dns-01' === challenge.type) { + // Give the nameservers a moment to propagate + CHECK_DELAY = 1.5 * 1000; + } + + return Promise.resolve().then(function () { + var results = { + identifier: { + type: "dns" + , value: identifierValue.replace(/^\*\./, '') + } + , challenges: [ challenge ] + , expires: new Date(Date.now() + (60 * 1000)).toISOString() + , wildcard: identifierValue.includes('*.') || undefined + }; + var dryrun = true; + var auth = ACME._challengeToAuth(me, options, results, challenge, dryrun); + return ACME._setChallenge(me, options, auth).then(function () { + return auth; + }); + }); + })).then(function (auths) { + return ACME._wait(CHECK_DELAY).then(function () { + return Promise.all(auths.map(function (auth) { + return ACME.challengeTests[auth.type](me, auth); + })); + }); + }); +}; +ACME._chooseChallenge = function(options, results) { + // For each of the challenge types that we support + var challenge; + options.challengeTypes.some(function (chType) { + // And for each of the challenge types that are allowed + return results.challenges.some(function (ch) { + // Check to see if there are any matches + if (ch.type === chType) { + challenge = ch; + return true; + } + }); + }); + + return challenge; +}; +ACME._challengeToAuth = function (me, options, request, challenge, dryrun) { + // we don't poison the dns cache with our dummy request + var dnsPrefix = ACME.challengePrefixes['dns-01']; + if (dryrun) { + dnsPrefix = dnsPrefix.replace('acme-challenge', 'greenlock-dryrun-' + ACME._prnd(4)); + } + + var auth = {}; + + // straight copy from the new order response + // { identifier, status, expires, challenges, wildcard } + Object.keys(request).forEach(function (key) { + auth[key] = request[key]; + }); + + // copy from the challenge we've chosen + // { type, status, url, token } + // (note the duplicate status overwrites the one above, but they should be the same) + Object.keys(challenge).forEach(function (key) { + // don't confused devs with the id url + auth[key] = challenge[key]; + }); + + // batteries-included helpers + auth.hostname = auth.identifier.value; + // because I'm not 100% clear if the wildcard identifier does or doesn't have the leading *. in all cases + auth.altname = ACME._untame(auth.identifier.value, auth.wildcard); + auth.thumbprint = me.RSA.thumbprint(options.accountKeypair); + // keyAuthorization = token || '.' || base64url(JWK_Thumbprint(accountKey)) + auth.keyAuthorization = challenge.token + '.' + auth.thumbprint; + // conflicts with ACME challenge id url is already in use, so we call this challengeUrl instead + auth.challengeUrl = 'http://' + auth.identifier.value + ACME.challengePrefixes['http-01'] + '/' + auth.token; + auth.dnsHost = dnsPrefix + '.' + auth.hostname.replace('*.', ''); + + return Crypto._sha('sha256', auth.keyAuthorization).then(function (hash) { + auth.dnsAuthorization = hash; + return auth; + }); +}; + +ACME._untame = function (name, wild) { + if (wild) { name = '*.' + name.replace('*.', ''); } + return name; +}; + +// https://tools.ietf.org/html/draft-ietf-acme-acme-10#section-7.5.1 +ACME._postChallenge = function (me, options, auth) { + var RETRY_INTERVAL = me.retryInterval || 1000; + var DEAUTH_INTERVAL = me.deauthWait || 10 * 1000; + var MAX_POLL = me.retryPoll || 8; + var MAX_PEND = me.retryPending || 4; + var count = 0; + + var altname = ACME._untame(auth.identifier.value, auth.wildcard); + + /* + POST /acme/authz/1234 HTTP/1.1 + Host: example.com + Content-Type: application/jose+json + + { + "protected": base64url({ + "alg": "ES256", + "kid": "https://example.com/acme/acct/1", + "nonce": "xWCM9lGbIyCgue8di6ueWQ", + "url": "https://example.com/acme/authz/1234" + }), + "payload": base64url({ + "status": "deactivated" + }), + "signature": "srX9Ji7Le9bjszhu...WTFdtujObzMtZcx4" + } + */ + function deactivate() { + var jws = me.RSA.signJws( + options.accountKeypair + , undefined + , { nonce: me._nonce, alg: (me._alg || 'RS256'), url: auth.url, kid: me._kid } + , Buffer.from(JSON.stringify({ "status": "deactivated" })) + ); + me._nonce = null; + return me._request({ + method: 'POST' + , url: auth.url + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + if (me.debug) { console.debug('[acme-v2.js] deactivate:'); } + if (me.debug) { console.debug(resp.headers); } + if (me.debug) { console.debug(resp.body); } + if (me.debug) { console.debug(); } + + me._nonce = resp.toJSON().headers['replay-nonce']; + if (me.debug) { console.debug('deactivate challenge: resp.body:'); } + if (me.debug) { console.debug(resp.body); } + return ACME._wait(DEAUTH_INTERVAL); + }); + } + + function pollStatus() { + if (count >= MAX_POLL) { + return Promise.reject(new Error( + "[acme-v2] stuck in bad pending/processing state for '" + altname + "'" + )); + } + + count += 1; + + if (me.debug) { console.debug('\n[DEBUG] statusChallenge\n'); } + // TODO POST-as-GET + return me._request({ method: 'GET', url: auth.url, json: true }).then(function (resp) { + if ('processing' === resp.body.status) { + if (me.debug) { console.debug('poll: again'); } + return ACME._wait(RETRY_INTERVAL).then(pollStatus); + } + + // This state should never occur + if ('pending' === resp.body.status) { + if (count >= MAX_PEND) { + return ACME._wait(RETRY_INTERVAL).then(deactivate).then(respondToChallenge); + } + if (me.debug) { console.debug('poll: again'); } + return ACME._wait(RETRY_INTERVAL).then(respondToChallenge); + } + + if ('valid' === resp.body.status) { + if (me.debug) { console.debug('poll: valid'); } + + try { + if (1 === options.removeChallenge.length) { + options.removeChallenge(auth).then(function () {}, function () {}); + } else if (2 === options.removeChallenge.length) { + options.removeChallenge(auth, function (err) { return err; }); + } else { + if (!ACME._removeChallengeWarn) { + console.warn("Please update to acme-v2 removeChallenge(options) or removeChallenge(options, cb)."); + console.warn("The API has been changed for compatibility with all ACME / Let's Encrypt challenge types."); + ACME._removeChallengeWarn = true; + } + options.removeChallenge(auth.request.identifier, auth.token, function () {}); + } + } catch(e) {} + return resp.body; + } + + var errmsg; + if (!resp.body.status) { + errmsg = "[acme-v2] (E_STATE_EMPTY) empty challenge state for '" + altname + "':"; + } + else if ('invalid' === resp.body.status) { + errmsg = "[acme-v2] (E_STATE_INVALID) challenge state for '" + altname + "': '" + resp.body.status + "'"; + } + else { + errmsg = "[acme-v2] (E_STATE_UKN) challenge state for '" + altname + "': '" + resp.body.status + "'"; + } + + return Promise.reject(new Error(errmsg)); + }); + } + + function respondToChallenge() { + var jws = me.RSA.signJws( + options.accountKeypair + , undefined + , { nonce: me._nonce, alg: (me._alg || 'RS256'), url: auth.url, kid: me._kid } + , Buffer.from(JSON.stringify({ })) + ); + me._nonce = null; + return me._request({ + method: 'POST' + , url: auth.url + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + if (me.debug) { console.debug('[acme-v2.js] challenge accepted!'); } + if (me.debug) { console.debug(resp.headers); } + if (me.debug) { console.debug(resp.body); } + if (me.debug) { console.debug(); } + + me._nonce = resp.toJSON().headers['replay-nonce']; + if (me.debug) { console.debug('respond to challenge: resp.body:'); } + if (me.debug) { console.debug(resp.body); } + return ACME._wait(RETRY_INTERVAL).then(pollStatus); + }); + } + + return respondToChallenge(); +}; +ACME._setChallenge = function (me, options, auth) { + return new Promise(function (resolve, reject) { + try { + if (1 === options.setChallenge.length) { + options.setChallenge(auth).then(resolve).catch(reject); + } else if (2 === options.setChallenge.length) { + options.setChallenge(auth, function (err) { + if(err) { reject(err); } else { resolve(); } + }); + } else { + var challengeCb = function(err) { + if(err) { reject(err); } else { resolve(); } + }; + // for backwards compat adding extra keys without changing params length + Object.keys(auth).forEach(function (key) { + challengeCb[key] = auth[key]; + }); + if (!ACME._setChallengeWarn) { + console.warn("Please update to acme-v2 setChallenge(options) or setChallenge(options, cb)."); + console.warn("The API has been changed for compatibility with all ACME / Let's Encrypt challenge types."); + ACME._setChallengeWarn = true; + } + options.setChallenge(auth.identifier.value, auth.token, auth.keyAuthorization, challengeCb); + } + } catch(e) { + reject(e); + } + }).then(function () { + // TODO: Do we still need this delay? Or shall we leave it to plugins to account for themselves? + var DELAY = me.setChallengeWait || 500; + if (me.debug) { console.debug('\n[DEBUG] waitChallengeDelay %s\n', DELAY); } + return ACME._wait(DELAY); + }); +}; +ACME._finalizeOrder = function (me, options, validatedDomains) { + if (me.debug) { console.debug('finalizeOrder:'); } + var csr = me.RSA.generateCsrWeb64(options.domainKeypair, validatedDomains); + var body = { csr: csr }; + var payload = JSON.stringify(body); + + function pollCert() { + var jws = me.RSA.signJws( + options.accountKeypair + , undefined + , { nonce: me._nonce, alg: (me._alg || 'RS256'), url: me._finalize, kid: me._kid } + , Buffer.from(payload) + ); + + if (me.debug) { console.debug('finalize:', me._finalize); } + me._nonce = null; + return me._request({ + method: 'POST' + , url: me._finalize + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + // https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.1.3 + // Possible values are: "pending" => ("invalid" || "ready") => "processing" => "valid" + me._nonce = resp.toJSON().headers['replay-nonce']; + + if (me.debug) { console.debug('order finalized: resp.body:'); } + if (me.debug) { console.debug(resp.body); } + + if ('valid' === resp.body.status) { + me._expires = resp.body.expires; + me._certificate = resp.body.certificate; + + return resp.body; // return order + } + + if ('processing' === resp.body.status) { + return ACME._wait().then(pollCert); + } + + if (me.debug) { console.debug("Error: bad status:\n" + JSON.stringify(resp.body, null, 2)); } + + if ('pending' === resp.body.status) { + return Promise.reject(new Error( + "Did not finalize order: status 'pending'." + + " Best guess: You have not accepted at least one challenge for each domain:\n" + + "Requested: '" + options.domains.join(', ') + "'\n" + + "Validated: '" + validatedDomains.join(', ') + "'\n" + + JSON.stringify(resp.body, null, 2) + )); + } + + if ('invalid' === resp.body.status) { + return Promise.reject(new Error( + "Did not finalize order: status 'invalid'." + + " Best guess: One or more of the domain challenges could not be verified" + + " (or the order was canceled).\n" + + "Requested: '" + options.domains.join(', ') + "'\n" + + "Validated: '" + validatedDomains.join(', ') + "'\n" + + JSON.stringify(resp.body, null, 2) + )); + } + + if ('ready' === resp.body.status) { + return Promise.reject(new Error( + "Did not finalize order: status 'ready'." + + " Hmmm... this state shouldn't be possible here. That was the last state." + + " This one should at least be 'processing'.\n" + + "Requested: '" + options.domains.join(', ') + "'\n" + + "Validated: '" + validatedDomains.join(', ') + "'\n" + + JSON.stringify(resp.body, null, 2) + "\n\n" + + "Please open an issue at https://git.coolaj86.com/coolaj86/acme-v2.js" + )); + } + + return Promise.reject(new Error( + "Didn't finalize order: Unhandled status '" + resp.body.status + "'." + + " This is not one of the known statuses...\n" + + "Requested: '" + options.domains.join(', ') + "'\n" + + "Validated: '" + validatedDomains.join(', ') + "'\n" + + JSON.stringify(resp.body, null, 2) + "\n\n" + + "Please open an issue at https://git.coolaj86.com/coolaj86/acme-v2.js" + )); + }); + } + + return pollCert(); +}; +ACME._getCertificate = function (me, options) { + if (me.debug) { console.debug('[acme-v2] DEBUG get cert 1'); } + + // Lot's of error checking to inform the user of mistakes + if (!(options.challengeTypes||[]).length) { + options.challengeTypes = Object.keys(options.challenges||{}); + } + if (!options.challengeTypes.length) { + options.challengeTypes = [ options.challengeType ].filter(Boolean); + } + if (options.challengeType) { + options.challengeTypes.sort(function (a, b) { + if (a === options.challengeType) { return -1; } + if (b === options.challengeType) { return 1; } + return 0; + }); + if (options.challengeType !== options.challengeTypes[0]) { + return Promise.reject(new Error("options.challengeType is '" + options.challengeType + "'," + + " which does not exist in the supplied types '" + options.challengeTypes.join(',') + "'")); + } + } + // TODO check that all challengeTypes are represented in challenges + if (!options.challengeTypes.length) { + return Promise.reject(new Error("options.challengeTypes (string array) must be specified" + + " (and in order of preferential priority).")); + } + if (!(options.domains && options.domains.length)) { + return Promise.reject(new Error("options.domains must be a list of string domain names," + + " with the first being the subject of the domain (or options.subject must specified).")); + } + + // It's just fine if there's no account, we'll go get the key id we need via the public key + if (!me._kid) { + if (options.accountKid || options.account && options.account.kid) { + me._kid = options.accountKid || options.account.kid; + } else { + //return Promise.reject(new Error("must include KeyID")); + // This is an idempotent request. It'll return the same account for the same public key. + return ACME._registerAccount(me, options).then(function () { + // start back from the top + return ACME._getCertificate(me, options); + }); + } + } + + // Do a little dry-run / self-test + return ACME._testChallenges(me, options).then(function () { + if (me.debug) { console.debug('[acme-v2] certificates.create'); } + return ACME._getNonce(me).then(function () { + var body = { + // raw wildcard syntax MUST be used here + identifiers: options.domains.sort(function (a, b) { + // the first in the list will be the subject of the certificate, I believe (and hope) + if (!options.subject) { return 0; } + if (options.subject === a) { return -1; } + if (options.subject === b) { return 1; } + return 0; + }).map(function (hostname) { + return { type: "dns", value: hostname }; + }) + //, "notBefore": "2016-01-01T00:00:00Z" + //, "notAfter": "2016-01-08T00:00:00Z" + }; + + var payload = JSON.stringify(body); + // determine the signing algorithm to use in protected header // TODO isn't that handled by the signer? + me._kty = (options.accountKeypair.privateKeyJwk && options.accountKeypair.privateKeyJwk.kty || 'RSA'); + me._alg = ('EC' === me._kty) ? 'ES256' : 'RS256'; // TODO vary with bitwidth of key (if not handled) + var jws = me.RSA.signJws( + options.accountKeypair + , undefined + , { nonce: me._nonce, alg: me._alg, url: me._directoryUrls.newOrder, kid: me._kid } + , Buffer.from(payload, 'utf8') + ); + + if (me.debug) { console.debug('\n[DEBUG] newOrder\n'); } + me._nonce = null; + return me._request({ + method: 'POST' + , url: me._directoryUrls.newOrder + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + me._nonce = resp.toJSON().headers['replay-nonce']; + var location = resp.toJSON().headers.location; + var setAuths; + var auths = []; + if (me.debug) { console.debug(location); } // the account id url + if (me.debug) { console.debug(resp.toJSON()); } + me._authorizations = resp.body.authorizations; + me._order = location; + me._finalize = resp.body.finalize; + //if (me.debug) console.debug('[DEBUG] finalize:', me._finalize); return; + + if (!me._authorizations) { + return Promise.reject(new Error( + "[acme-v2.js] authorizations were not fetched for '" + options.domains.join() + "':\n" + + JSON.stringify(resp.body) + )); + } + if (me.debug) { console.debug("[acme-v2] POST newOrder has authorizations"); } + setAuths = me._authorizations.slice(0); + + function setNext() { + var authUrl = setAuths.shift(); + if (!authUrl) { return; } + + return ACME._getChallenges(me, options, authUrl).then(function (results) { + // var domain = options.domains[i]; // results.identifier.value + + // If it's already valid, we're golden it regardless + if (results.challenges.some(function (ch) { return 'valid' === ch.status; })) { + return setNext(); + } + + var challenge = ACME._chooseChallenge(options, results); + if (!challenge) { + // For example, wildcards require dns-01 and, if we don't have that, we have to bail + return Promise.reject(new Error( + "Server didn't offer any challenge we can handle for '" + options.domains.join() + "'." + )); + } + + return ACME._challengeToAuth(me, options, results, challenge, false).then(function (auth) { + auths.push(auth); + return ACME._setChallenge(me, options, auth).then(setNext); + }); + }); + } + + function challengeNext() { + var auth = auths.shift(); + if (!auth) { return; } + return ACME._postChallenge(me, options, auth).then(challengeNext); + } + + // First we set every challenge + // Then we ask for each challenge to be checked + // Doing otherwise would potentially cause us to poison our own DNS cache with misses + return setNext().then(challengeNext).then(function () { + if (me.debug) { console.debug("[getCertificate] next.then"); } + var validatedDomains = body.identifiers.map(function (ident) { + return ident.value; + }); + + return ACME._finalizeOrder(me, options, validatedDomains); + }).then(function (order) { + if (me.debug) { console.debug('acme-v2: order was finalized'); } + // TODO POST-as-GET + return me._request({ method: 'GET', url: me._certificate, json: true }).then(function (resp) { + if (me.debug) { console.debug('acme-v2: csr submitted and cert received:'); } + // https://github.com/certbot/certbot/issues/5721 + var certsarr = ACME.splitPemChain(ACME.formatPemChain((resp.body||''))); + // cert, chain, fullchain, privkey, /*TODO, subject, altnames, issuedAt, expiresAt */ + var certs = { + expires: order.expires + , identifiers: order.identifiers + //, authorizations: order.authorizations + , cert: certsarr.shift() + //, privkey: privkeyPem + , chain: certsarr.join('\n') + }; + if (me.debug) { console.debug(certs); } + return certs; + }); + }); + }); + }); + }); +}; + +ACME.create = function create(me) { + if (!me) { me = {}; } + // me.debug = true; + me.challengePrefixes = ACME.challengePrefixes; + me.RSA = me.RSA || require('rsa-compat').RSA; + //me.Keypairs = me.Keypairs || require('keypairs'); + me.request = me.request || require('@coolaj86/urequest'); + if (!me.dig) { + me.dig = function (query) { + // TODO use digd.js + return new Promise(function (resolve, reject) { + var dns = require('dns'); + dns.resolveTxt(query.name, function (err, records) { + if (err) { reject(err); return; } + + resolve({ + answer: records.map(function (rr) { + return { + data: rr + }; + }) + }); + }); + }); + }; + } + me.promisify = me.promisify || require('util').promisify /*node v8+*/ || require('bluebird').promisify /*node v6*/; + + + if ('function' !== typeof me._request) { + // MUST have a User-Agent string (see node.js version) + me._request = function (opts) { + return window.fetch(opts.url, opts).then(function (resp) { + return resp.json().then(function (json) { + var headers = {}; + Array.from(resp.headers.entries()).forEach(function (h) { headers[h[0]] = h[1]; }); + return { headers: headers , body: json }; + }); + }); + }; + } + + me.init = function (_directoryUrl) { + me.directoryUrl = me.directoryUrl || _directoryUrl; + return ACME._directory(me).then(function (resp) { + me._directoryUrls = resp.body; + me._tos = me._directoryUrls.meta.termsOfService; + return me._directoryUrls; + }); + }; + me.accounts = { + create: function (options) { + return ACME._registerAccount(me, options); + } + }; + me.certificates = { + create: function (options) { + return ACME._getCertificate(me, options); + } + }; + return me; +}; + +ACME._toWebsafeBase64 = function (b64) { + return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g,""); +}; + +// In v8 this is crypto random, but we're just using it for pseudorandom +ACME._prnd = function (n) { + var rnd = ''; + while (rnd.length / 2 < n) { + var num = Math.random().toString().substr(2); + if (num.length % 2) { + num = '0' + num; + } + var pairs = num.match(/(..?)/g); + rnd += pairs.map(ACME._toHex).join(''); + } + return rnd.substr(0, n*2); +}; +ACME._toHex = function (pair) { + return parseInt(pair, 10).toString(16); +}; + +Enc.bufToUrlBase64 = function (u8) { + return Enc.bufToBase64(u8) + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +}; +Enc.bufToBase64 = function (u8) { + var bin = ''; + u8.forEach(function (i) { + bin += String.fromCharCode(i); + }); + return btoa(bin); +}; + +Crypto._sha = function (sha, str) { + var encoder = new TextEncoder(); + var data = encoder.encode(str); + sha = 'SHA-' + sha.replace(/^sha-?/i, ''); + return window.crypto.subtle.digest(sha, data).then(function (hash) { + return Enc.bufToUrlBase64(new Uint8Array(hash)); + }); +}; + +}('undefined' === typeof window ? module.exports : window)); From 3156229e2ca96ff24e5d345f1586e055dace61bc Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 26 Apr 2019 16:26:33 -0600 Subject: [PATCH 05/52] WIP acme accounts --- app.js | 9 +++ index.html | 23 +++++- lib/acme.js | 144 ++++++++++++++++++++----------------- lib/asn1-packer.js | 127 ++++++++++++++++++++++++++++++++ lib/asn1-parser.js | 161 +++++++++++++++++++++++++++++++++++++++++ lib/keypairs.js | 175 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 573 insertions(+), 66 deletions(-) create mode 100644 lib/asn1-packer.js create mode 100644 lib/asn1-parser.js diff --git a/app.js b/app.js index d144211..fcacb77 100644 --- a/app.js +++ b/app.js @@ -49,10 +49,19 @@ function run() { $('.js-jwk').hidden = false; $$('input').map(function ($el) { $el.disabled = false; }); $$('button').map(function ($el) { $el.disabled = false; }); + $('.js-toc-jwk').hidden = false; }); }); + $('form.js-acme-account').addEventListener('submit', function (ev) { + ev.preventDefault(); + ev.stopPropagation(); + $('.js-loading').hidden = false; + ACME.accounts.create + }); + $('.js-generate').hidden = false; + $('.js-create-account').hidden = false; } window.addEventListener('load', run); diff --git a/index.html b/index.html index ea6b027..da066a9 100644 --- a/index.html +++ b/index.html @@ -43,10 +43,29 @@ - + + +

ACME Account

+ -
 
+ + + + diff --git a/lib/acme.js b/lib/acme.js index 3e6fb96..afbedf4 100644 --- a/lib/acme.js +++ b/lib/acme.js @@ -7,6 +7,7 @@ /* globals Promise */ var ACME = exports.ACME = {}; +var Keypairs = exports.Keypairs || {}; var Enc = exports.Enc || {}; var Crypto = exports.Crypto || {}; @@ -120,79 +121,94 @@ ACME._registerAccount = function (me, options) { return; } - var jwk = me.RSA.exportPublicJwk(options.accountKeypair); - var contact; - if (options.contact) { - contact = options.contact.slice(0); - } else if (options.email) { - contact = [ 'mailto:' + options.email ]; + var jwk = options.accountKeypair.privateKeyJwk; + var p; + if (jwk) { + p = Promise.resolve({ private: jwk, public: Keypairs.neuter(jwk) }); + } else { + p = Keypairs.import({ pem: options.accountKeypair.privateKeyPem }); } - var body = { - termsOfServiceAgreed: tosUrl === me._tos - , onlyReturnExisting: false - , contact: contact - }; - if (options.externalAccount) { - // TODO is this really done by HMAC or is it arbitrary? - body.externalAccountBinding = me.RSA.signJws( - options.externalAccount.secret + return p.then(function (pair) { + if (pair.public.kid) { + pair = JSON.parse(JSON.stringify(pair)); + delete pair.public.kid; + delete pair.private.kid; + } + return pair; + }).then(function (pair) { + var contact; + if (options.contact) { + contact = options.contact.slice(0); + } else if (options.email) { + contact = [ 'mailto:' + options.email ]; + } + var body = { + termsOfServiceAgreed: tosUrl === me._tos + , onlyReturnExisting: false + , contact: contact + }; + if (options.externalAccount) { + body.externalAccountBinding = me.RSA.signJws( + // TODO is HMAC the standard, or is this arbitrary? + options.externalAccount.secret + , undefined + , { alg: options.externalAccount.alg || "HS256" + , kid: options.externalAccount.id + , url: me._directoryUrls.newAccount + } + , Buffer.from(JSON.stringify(pair.public)) + ); + } + var payload = JSON.stringify(body); + var jws = Keypairs.signJws( + options.accountKeypair , undefined - , { alg: "HS256" - , kid: options.externalAccount.id + , { nonce: me._nonce + , alg: (me._alg || 'RS256') , url: me._directoryUrls.newAccount + , jwk: pair.public } - , Buffer.from(JSON.stringify(jwk)) + , Buffer.from(payload) ); - } - var payload = JSON.stringify(body); - var jws = me.RSA.signJws( - options.accountKeypair - , undefined - , { nonce: me._nonce - , alg: (me._alg || 'RS256') + + delete jws.header; + if (me.debug) { console.debug('[acme-v2] accounts.create JSON body:'); } + if (me.debug) { console.debug(jws); } + me._nonce = null; + return me._request({ + method: 'POST' , url: me._directoryUrls.newAccount - , jwk: jwk - } - , Buffer.from(payload) - ); + , headers: { 'Content-Type': 'application/jose+json' } + , json: jws + }).then(function (resp) { + var account = resp.body; - delete jws.header; - if (me.debug) { console.debug('[acme-v2] accounts.create JSON body:'); } - if (me.debug) { console.debug(jws); } - me._nonce = null; - return me._request({ - method: 'POST' - , url: me._directoryUrls.newAccount - , headers: { 'Content-Type': 'application/jose+json' } - , json: jws - }).then(function (resp) { - var account = resp.body; + if (2 !== Math.floor(resp.statusCode / 100)) { + throw new Error('account error: ' + JSON.stringify(body)); + } - if (2 !== Math.floor(resp.statusCode / 100)) { - throw new Error('account error: ' + JSON.stringify(body)); - } + me._nonce = resp.toJSON().headers['replay-nonce']; + var location = resp.toJSON().headers.location; + // the account id url + me._kid = location; + if (me.debug) { console.debug('[DEBUG] new account location:'); } + if (me.debug) { console.debug(location); } + if (me.debug) { console.debug(resp.toJSON()); } - me._nonce = resp.toJSON().headers['replay-nonce']; - var location = resp.toJSON().headers.location; - // the account id url - me._kid = location; - if (me.debug) { console.debug('[DEBUG] new account location:'); } - if (me.debug) { console.debug(location); } - if (me.debug) { console.debug(resp.toJSON()); } - - /* - { - contact: ["mailto:jon@example.com"], - orders: "https://some-url", - status: 'valid' - } - */ - if (!account) { account = { _emptyResponse: true, key: {} }; } - // https://git.coolaj86.com/coolaj86/acme-v2.js/issues/8 - if (!account.key) { account.key = {}; } - account.key.kid = me._kid; - return account; - }).then(resolve, reject); + /* + { + contact: ["mailto:jon@example.com"], + orders: "https://some-url", + status: 'valid' + } + */ + if (!account) { account = { _emptyResponse: true, key: {} }; } + // https://git.coolaj86.com/coolaj86/acme-v2.js/issues/8 + if (!account.key) { account.key = {}; } + account.key.kid = me._kid; + return account; + }).then(resolve, reject); + }); } if (me.debug) { console.debug('[acme-v2] agreeToTerms'); } diff --git a/lib/asn1-packer.js b/lib/asn1-packer.js new file mode 100644 index 0000000..a57043c --- /dev/null +++ b/lib/asn1-packer.js @@ -0,0 +1,127 @@ +;(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; + +// +// Packer +// + +// Almost every ASN.1 type that's important for CSR +// can be represented generically with only a few rules. +exports.ASN1 = function ASN1(/*type, hexstrings...*/) { + var args = Array.prototype.slice.call(arguments); + var typ = args.shift(); + var str = args.join('').replace(/\s+/g, '').toLowerCase(); + var len = (str.length/2); + var lenlen = 0; + var hex = typ; + + // We can't have an odd number of hex chars + if (len !== Math.round(len)) { + throw new Error("invalid hex"); + } + + // The first byte of any ASN.1 sequence is the type (Sequence, Integer, etc) + // The second byte is either the size of the value, or the size of its size + + // 1. If the second byte is < 0x80 (128) it is considered the size + // 2. If it is > 0x80 then it describes the number of bytes of the size + // ex: 0x82 means the next 2 bytes describe the size of the value + // 3. The special case of exactly 0x80 is "indefinite" length (to end-of-file) + + if (len > 127) { + lenlen += 1; + while (len > 255) { + lenlen += 1; + len = len >> 8; + } + } + + if (lenlen) { hex += Enc.numToHex(0x80 + lenlen); } + return hex + Enc.numToHex(str.length/2) + str; +}; + +// The Integer type has some special rules +ASN1.UInt = function UINT() { + var str = Array.prototype.slice.call(arguments).join(''); + var first = parseInt(str.slice(0, 2), 16); + + // If the first byte is 0x80 or greater, the number is considered negative + // Therefore we add a '00' prefix if the 0x80 bit is set + if (0x80 & first) { str = '00' + str; } + + return ASN1('02', str); +}; + +// The Bit String type also has a special rule +ASN1.BitStr = function BITSTR() { + var str = Array.prototype.slice.call(arguments).join(''); + // '00' is a mask of how many bits of the next byte to ignore + return ASN1('03', '00' + str); +}; + +ASN1.pack = function (arr) { + var typ = Enc.numToHex(arr[0]); + var str = ''; + if (Array.isArray(arr[1])) { + arr[1].forEach(function (a) { + str += ASN1.pack(a); + }); + } else if ('string' === typeof arr[1]) { + str = arr[1]; + } else { + throw new Error("unexpected array"); + } + if ('03' === typ) { + return ASN1.BitStr(str); + } else if ('02' === typ) { + return ASN1.UInt(str); + } else { + return ASN1(typ, str); + } +}; +Object.keys(ASN1).forEach(function (k) { + exports.ASN1[k] = ASN1[k]; +}); +ASN1 = exports.ASN1; + +PEM.packBlock = function (opts) { + // TODO allow for headers? + return '-----BEGIN ' + opts.type + '-----\n' + + Enc.bufToBase64(opts.bytes).match(/.{1,64}/g).join('\n') + '\n' + + '-----END ' + opts.type + '-----' + ; +}; + +Enc.bufToBase64 = function (u8) { + var bin = ''; + u8.forEach(function (i) { + bin += String.fromCharCode(i); + }); + return btoa(bin); +}; + +Enc.hexToBuf = function (hex) { + var arr = []; + hex.match(/.{2}/g).forEach(function (h) { + arr.push(parseInt(h, 16)); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; + +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/asn1-parser.js b/lib/asn1-parser.js new file mode 100644 index 0000000..82f7cd0 --- /dev/null +++ b/lib/asn1-parser.js @@ -0,0 +1,161 @@ +// Copyright 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/. */ +;(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 +// + +// Although I've only seen 9 max in https certificates themselves, +// but each domain list could have up to 100 +ASN1.ELOOPN = 102; +ASN1.ELOOP = "uASN1.js Error: iterated over " + ASN1.ELOOPN + "+ elements (probably a malformed file)"; +// I've seen https certificates go 29 deep +ASN1.EDEEPN = 60; +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 der = str.split(/\n/).filter(function (line) { + return !/-----/.test(line); + }).join(''); + return { der: Enc.base64ToBuf(der) }; +}; + +Enc.base64ToBuf = function (b64) { + return Enc.binToBuf(atob(b64)); +}; +Enc.binToBuf = function (bin) { + var arr = bin.split('').map(function (ch) { + return ch.charCodeAt(0); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; +Enc.bufToHex = function (u8) { + var hex = []; + var i, h; + var len = (u8.byteLength || u8.length); + + for (i = 0; i < len; i += 1) { + h = u8[i].toString(16); + if (h.length % 2) { h = '0' + h; } + hex.push(h); + } + + return hex.join('').toLowerCase(); +}; +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/keypairs.js b/lib/keypairs.js index 1f3196c..1492954 100644 --- a/lib/keypairs.js +++ b/lib/keypairs.js @@ -5,6 +5,7 @@ var Keypairs = exports.Keypairs = {}; var Rasha = exports.Rasha || require('rasha'); var Eckles = exports.Eckles || require('eckles'); +var Enc = exports.Enc || {}; Keypairs._stance = "We take the stance that if you're knowledgeable enough to" + " properly and securely use non-standard crypto then you shouldn't need Bluecrypt anyway."; @@ -76,6 +77,163 @@ Keypairs.publish = function (opts) { return Keypairs.thumbprint({ jwk: jwk }).then(function (thumb) { jwk.kid = thumb; return jwk; }); }; +// JWT a.k.a. JWS with Claims using Compact Serialization +Keypairs.signJwt = function (opts) { + return Keypairs.thumbprint({ jwk: opts.jwk }).then(function (thumb) { + var header = opts.header || {}; + var claims = JSON.parse(JSON.stringify(opts.claims || {})); + header.typ = 'JWT'; + + if (!header.kid) { header.kid = thumb; } + if (!header.alg && opts.alg) { header.alg = opts.alg; } + if (!claims.iat && (false === claims.iat || false === opts.iat)) { + claims.iat = undefined; + } else if (!claims.iat) { + claims.iat = Math.round(Date.now()/1000); + } + + if (opts.exp) { + claims.exp = setTime(opts.exp); + } else if (!claims.exp && (false === claims.exp || false === opts.exp)) { + claims.exp = undefined; + } else if (!claims.exp) { + throw new Error("opts.claims.exp should be the expiration date as seconds, human form (i.e. '1h' or '15m') or false"); + } + + if (opts.iss) { claims.iss = opts.iss; } + if (!claims.iss && (false === claims.iss || false === opts.iss)) { + claims.iss = undefined; + } else if (!claims.iss) { + throw new Error("opts.claims.iss should be in the form of https://example.com/, a secure OIDC base url"); + } + + return Keypairs.signJws({ + jwk: opts.jwk + , pem: opts.pem + , protected: header + , header: undefined + , payload: claims + }).then(function (jws) { + return [ jws.protected, jws.payload, jws.signature ].join('.'); + }); + }); +}; + +Keypairs.signJws = function (opts) { + return Keypairs.thumbprint(opts).then(function (thumb) { + + function alg() { + if (!opts.jwk) { + throw new Error("opts.jwk must exist and must declare 'typ'"); + } + return ('RSA' === opts.jwk.kty) ? "RS256" : "ES256"; + } + + function sign(pem) { + var header = opts.header; + var protect = opts.protected; + var payload = opts.payload; + + // Compute JWS signature + var protectedHeader = ""; + // Because unprotected headers are allowed, regrettably... + // https://stackoverflow.com/a/46288694 + if (false !== protect) { + if (!protect) { protect = {}; } + if (!protect.alg) { protect.alg = alg(); } + // There's a particular request where Let's Encrypt explicitly doesn't use a kid + if (!protect.kid && false !== protect.kid) { protect.kid = thumb; } + protectedHeader = JSON.stringify(protect); + } + + // Not sure how to handle the empty case since ACME POST-as-GET must be empty + //if (!payload) { + // throw new Error("opts.payload should be JSON, string, or ArrayBuffer (it may be empty, but that must be explicit)"); + //} + // Trying to detect if it's a plain object (not Buffer, ArrayBuffer, Array, Uint8Array, etc) + if (payload && ('string' !== typeof payload) + && ('undefined' === typeof payload.byteLength) + && ('undefined' === typeof payload.byteLength) + ) { + payload = JSON.stringify(payload); + } + // Converting to a buffer, even if it was just converted to a string + if ('string' === typeof payload) { + payload = Enc.binToBuf(payload); + } + + // node specifies RSA-SHAxxx even when it's actually ecdsa (it's all encoded x509 shasums anyway) + var nodeAlg = "SHA" + (((protect||header).alg||'').replace(/^[^\d]+/, '')||'256'); + var protected64 = Enc.strToUrlBase64(protectedHeader); + var payload64 = Enc.bufToUrlBase64(payload); + var binsig = require('crypto') + .createSign(nodeAlg) + .update(protect ? (protected64 + "." + payload64) : payload64) + .sign(pem) + ; + if ('EC' === opts.jwk.kty) { + // ECDSA JWT signatures differ from "normal" ECDSA signatures + // https://tools.ietf.org/html/rfc7518#section-3.4 + binsig = convertIfEcdsa(binsig); + } + + var sig = binsig.toString('base64') + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=/g, '') + ; + + return { + header: header + , protected: protected64 || undefined + , payload: payload64 + , signature: sig + }; + } + + function convertIfEcdsa(binsig) { + // should have asn1 sequence header of 0x30 + if (0x30 !== binsig[0]) { throw new Error("Impossible EC SHA head marker"); } + var index = 2; // first ecdsa "R" header byte + var len = binsig[1]; + var lenlen = 0; + // Seek length of length if length is greater than 127 (i.e. two 512-bit / 64-byte R and S values) + if (0x80 & len) { + lenlen = len - 0x80; // should be exactly 1 + len = binsig[2]; // should be <= 130 (two 64-bit SHA-512s, plus padding) + index += lenlen; + } + // should be of BigInt type + if (0x02 !== binsig[index]) { throw new Error("Impossible EC SHA R marker"); } + index += 1; + + var rlen = binsig[index]; + var bits = 32; + if (rlen > 49) { + bits = 64; + } else if (rlen > 33) { + bits = 48; + } + var r = binsig.slice(index + 1, index + 1 + rlen).toString('hex'); + var slen = binsig[index + 1 + rlen + 1]; // skip header and read length + var s = binsig.slice(index + 1 + rlen + 1 + 1).toString('hex'); + if (2 *slen !== s.length) { throw new Error("Impossible EC SHA S length"); } + // There may be one byte of padding on either + while (r.length < 2*bits) { r = '00' + r; } + while (s.length < 2*bits) { s = '00' + s; } + if (2*(bits+1) === r.length) { r = r.slice(2); } + if (2*(bits+1) === s.length) { s = s.slice(2); } + return Enc.hexToBuf(r + s); + } + + if (opts.pem && opts.jwk) { + return sign(opts.pem); + } else { + return Keypairs.export({ jwk: opts.jwk }).then(sign); + } + }); +}; + function setTime(time) { if ('number' === typeof time) { return time; } @@ -106,4 +264,21 @@ function setTime(time) { return now + (mult * num); } +Enc.hexToBuf = function (hex) { + var arr = []; + hex.match(/.{2}/g).forEach(function (h) { + arr.push(parseInt(h, 16)); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; +Enc.strToUrlBase64 = function (str) { + return Enc.bufToUrlBase64(Enc.binToBuf(str)); +}; +Enc.binToBuf = function (bin) { + var arr = bin.split('').map(function (ch) { + return ch.charCodeAt(0); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; + }('undefined' !== typeof module ? module.exports : window)); From 10f817a51c78c7bcabbdd2e2f82f2a45a9f8fa4e Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 26 Apr 2019 16:36:19 -0600 Subject: [PATCH 06/52] WIP encoding --- lib/bluecrypt-encoding.js | 135 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 lib/bluecrypt-encoding.js diff --git a/lib/bluecrypt-encoding.js b/lib/bluecrypt-encoding.js new file mode 100644 index 0000000..d3f2292 --- /dev/null +++ b/lib/bluecrypt-encoding.js @@ -0,0 +1,135 @@ +(function (exports) { + +var Enc = exports.BluecryptEncoding = {}; + +Enc.bufToBin = function (buf) { + var bin = ''; + // cannot use .map() because Uint8Array would return only 0s + buf.forEach(function (ch) { + bin += String.fromCharCode(ch); + }); + return bin; +}; + +Enc.bufToHex = function toHex(u8) { + var hex = []; + var i, h; + var len = (u8.byteLength || u8.length); + + for (i = 0; i < len; i += 1) { + h = u8[i].toString(16); + if (h.length % 2) { h = '0' + h; } + hex.push(h); + } + + return hex.join('').toLowerCase(); +}; + +Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) { + var r = str % 4; + if (2 === r) { + str += '=='; + } else if (3 === r) { + str += '='; + } + return str.replace(/-/g, '+').replace(/_/g, '/'); +}; + +Enc.base64ToBuf = function (b64) { + return Enc.binToBuf(atob(b64)); +}; +Enc.binToBuf = function (bin) { + var arr = bin.split('').map(function (ch) { + return ch.charCodeAt(0); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; +Enc.bufToHex = function (u8) { + var hex = []; + var i, h; + var len = (u8.byteLength || u8.length); + + for (i = 0; i < len; i += 1) { + h = u8[i].toString(16); + if (h.length % 2) { h = '0' + h; } + hex.push(h); + } + + return hex.join('').toLowerCase(); +}; +Enc.numToHex = function (d) { + d = d.toString(16); + if (d.length % 2) { + return '0' + d; + } + return d; +}; + +Enc.bufToUrlBase64 = function (u8) { + return Enc.bufToBase64(u8) + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +}; + +Enc.bufToBase64 = function (u8) { + var bin = ''; + u8.forEach(function (i) { + bin += String.fromCharCode(i); + }); + return btoa(bin); +}; + +Enc.hexToBuf = function (hex) { + var arr = []; + hex.match(/.{2}/g).forEach(function (h) { + arr.push(parseInt(h, 16)); + }); + return 'undefined' !== typeof Uint8Array ? new Uint8Array(arr) : arr; +}; + +Enc.numToHex = function (d) { + d = d.toString(16); + if (d.length % 2) { + return '0' + d; + } + return d; +}; + + +// +// JWK to SSH (tested working) +// +Enc.base64ToHex = function (b64) { + var bin = atob(Enc.urlBase64ToBase64(b64)); + return Enc.binToHex(bin); +}; + +Enc.binToHex = function (bin) { + return bin.split('').map(function (ch) { + var h = ch.charCodeAt(0).toString(16); + if (h.length % 2) { h = '0' + h; } + return h; + }).join(''); +}; + +Enc.hexToBase64 = function (hex) { + return btoa(Enc.hexToBin(hex)); +}; + +Enc.hexToBin = function (hex) { + return hex.match(/.{2}/g).map(function (h) { + return String.fromCharCode(parseInt(h, 16)); + }).join(''); +}; + +Enc.urlBase64ToBase64 = function urlsafeBase64ToBase64(str) { + var r = str % 4; + if (2 === r) { + str += '=='; + } else if (3 === r) { + str += '='; + } + return str.replace(/-/g, '+').replace(/_/g, '/'); +}; + + +}('undefined' !== typeof exports ? module.exports : window )); From 2e0549af5ac3f2469464420cec1b0eb89688a377 Mon Sep 17 00:00:00 2001 From: lastlink Date: Fri, 26 Apr 2019 18:50:10 -0400 Subject: [PATCH 07/52] setup for browser --- lib/x509.js | 173 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 lib/x509.js diff --git a/lib/x509.js b/lib/x509.js new file mode 100644 index 0000000..63d1a7d --- /dev/null +++ b/lib/x509.js @@ -0,0 +1,173 @@ +'use strict'; +(function (exports) { + 'use strict'; + var x509 = exports.x509 = {}; + var ASN1 = exports.ASN1; + var Enc = exports.Enc; + + // 1.2.840.10045.3.1.7 + // prime256v1 (ANSI X9.62 named elliptic curve) + var OBJ_ID_EC = '06 08 2A8648CE3D030107'.replace(/\s+/g, '').toLowerCase(); + // 1.3.132.0.34 + // secp384r1 (SECG (Certicom) named elliptic curve) + var OBJ_ID_EC_384 = '06 05 2B81040022'.replace(/\s+/g, '').toLowerCase(); + // 1.2.840.10045.2.1 + // ecPublicKey (ANSI X9.62 public key type) + var OBJ_ID_EC_PUB = '06 07 2A8648CE3D0201'.replace(/\s+/g, '').toLowerCase(); + + x509.parseSec1 = function parseEcOnlyPrivkey(u8, jwk) { + var index = 7; + var len = 32; + var olen = OBJ_ID_EC.length / 2; + + if ("P-384" === jwk.crv) { + olen = OBJ_ID_EC_384.length / 2; + index = 8; + len = 48; + } + if (len !== u8[index - 1]) { + throw new Error("Unexpected bitlength " + len); + } + + // private part is d + var d = u8.slice(index, index + len); + // compression bit index + var ci = index + len + 2 + olen + 2 + 3; + var c = u8[ci]; + var x, y; + + if (0x04 === c) { + y = u8.slice(ci + 1 + len, ci + 1 + len + len); + } else if (0x02 !== c) { + throw new Error("not a supported EC private key"); + } + x = u8.slice(ci + 1, ci + 1 + len); + + return { + kty: jwk.kty + , crv: jwk.crv + , d: Enc.bufToUrlBase64(d) + //, dh: Enc.bufToHex(d) + , x: Enc.bufToUrlBase64(x) + //, xh: Enc.bufToHex(x) + , y: Enc.bufToUrlBase64(y) + //, yh: Enc.bufToHex(y) + }; + }; + + x509.parsePkcs8 = function parseEcPkcs8(u8, jwk) { + var index = 24 + (OBJ_ID_EC.length / 2); + var len = 32; + if ("P-384" === jwk.crv) { + index = 24 + (OBJ_ID_EC_384.length / 2) + 2; + len = 48; + } + + //console.log(index, u8.slice(index)); + if (0x04 !== u8[index]) { + //console.log(jwk); + throw new Error("privkey not found"); + } + var d = u8.slice(index + 2, index + 2 + len); + var ci = index + 2 + len + 5; + var xi = ci + 1; + var x = u8.slice(xi, xi + len); + var yi = xi + len; + var y; + if (0x04 === u8[ci]) { + y = u8.slice(yi, yi + len); + } else if (0x02 !== u8[ci]) { + throw new Error("invalid compression bit (expected 0x04 or 0x02)"); + } + + return { + kty: jwk.kty + , crv: jwk.crv + , d: Enc.bufToUrlBase64(d) + //, dh: Enc.bufToHex(d) + , x: Enc.bufToUrlBase64(x) + //, xh: Enc.bufToHex(x) + , y: Enc.bufToUrlBase64(y) + //, yh: Enc.bufToHex(y) + }; + }; + + x509.parseSpki = function parsePem(u8, jwk) { + var ci = 16 + OBJ_ID_EC.length / 2; + var len = 32; + + if ("P-384" === jwk.crv) { + ci = 16 + OBJ_ID_EC_384.length / 2; + len = 48; + } + + var c = u8[ci]; + var xi = ci + 1; + var x = u8.slice(xi, xi + len); + var yi = xi + len; + var y; + if (0x04 === c) { + y = u8.slice(yi, yi + len); + } else if (0x02 !== c) { + throw new Error("not a supported EC private key"); + } + + return { + kty: jwk.kty + , crv: jwk.crv + , x: Enc.bufToUrlBase64(x) + //, xh: Enc.bufToHex(x) + , y: Enc.bufToUrlBase64(y) + //, yh: Enc.bufToHex(y) + }; + }; + x509.parsePkix = x509.parseSpki; + + x509.packSec1 = function (jwk) { + var d = Enc.base64ToHex(jwk.d); + var x = Enc.base64ToHex(jwk.x); + var y = Enc.base64ToHex(jwk.y); + var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; + return Enc.hexToUint8( + ASN1('30' + , ASN1.UInt('01') + , ASN1('04', d) + , ASN1('A0', objId) + , ASN1('A1', ASN1.BitStr('04' + x + y))) + ); + }; + x509.packPkcs8 = function (jwk) { + var d = Enc.base64ToHex(jwk.d); + var x = Enc.base64ToHex(jwk.x); + var y = Enc.base64ToHex(jwk.y); + var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; + return Enc.hexToUint8( + ASN1('30' + , ASN1.UInt('00') + , ASN1('30' + , OBJ_ID_EC_PUB + , objId + ) + , ASN1('04' + , ASN1('30' + , ASN1.UInt('01') + , ASN1('04', d) + , ASN1('A1', ASN1.BitStr('04' + x + y))))) + ); + }; + x509.packSpki = function (jwk) { + var x = Enc.base64ToHex(jwk.x); + var y = Enc.base64ToHex(jwk.y); + var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; + return Enc.hexToUint8( + ASN1('30' + , ASN1('30' + , OBJ_ID_EC_PUB + , objId + ) + , ASN1.BitStr('04' + x + y)) + ); + }; + x509.packPkix = x509.packSpki; + +}('undefined' !== typeof module ? module.exports : window)); From 1b01c2c4132f3db552f32ad56d92f4670d6365db Mon Sep 17 00:00:00 2001 From: lastlink Date: Fri, 26 Apr 2019 23:27:08 -0400 Subject: [PATCH 08/52] working der generation --- app.js | 3 +++ index.html | 4 +++- lib/bluecrypt-encoding.js | 2 +- lib/x509.js | 6 +++--- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/app.js b/app.js index fcacb77..1738a2c 100644 --- a/app.js +++ b/app.js @@ -43,6 +43,9 @@ function run() { }; console.log('opts', opts); Keypairs.generate(opts).then(function (results) { + var der = x509.packPkcs8(results.private); + console.log(der) + // Pem.encode(x509.packPkcs8(privateJwk)) $('.js-jwk').innerText = JSON.stringify(results, null, 2); // $('.js-loading').hidden = true; diff --git a/index.html b/index.html index da066a9..0d35e9a 100644 --- a/index.html +++ b/index.html @@ -66,8 +66,10 @@ ACME Account Response
- + + + diff --git a/lib/bluecrypt-encoding.js b/lib/bluecrypt-encoding.js index d3f2292..7dc1073 100644 --- a/lib/bluecrypt-encoding.js +++ b/lib/bluecrypt-encoding.js @@ -1,6 +1,6 @@ (function (exports) { -var Enc = exports.BluecryptEncoding = {}; +var Enc = exports.Enc = {}; Enc.bufToBin = function (buf) { var bin = ''; diff --git a/lib/x509.js b/lib/x509.js index 63d1a7d..114375d 100644 --- a/lib/x509.js +++ b/lib/x509.js @@ -128,7 +128,7 @@ var x = Enc.base64ToHex(jwk.x); var y = Enc.base64ToHex(jwk.y); var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; - return Enc.hexToUint8( + return Enc.hexToBuf( ASN1('30' , ASN1.UInt('01') , ASN1('04', d) @@ -141,7 +141,7 @@ var x = Enc.base64ToHex(jwk.x); var y = Enc.base64ToHex(jwk.y); var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; - return Enc.hexToUint8( + return Enc.hexToBuf( ASN1('30' , ASN1.UInt('00') , ASN1('30' @@ -159,7 +159,7 @@ var x = Enc.base64ToHex(jwk.x); var y = Enc.base64ToHex(jwk.y); var objId = ('P-256' === jwk.crv) ? OBJ_ID_EC : OBJ_ID_EC_384; - return Enc.hexToUint8( + return Enc.hexToBuf( ASN1('30' , ASN1('30' , OBJ_ID_EC_PUB From 735ec948da2f15c9b0c269340270f82f3a3b66dd Mon Sep 17 00:00:00 2001 From: lastlink Date: Sat, 27 Apr 2019 00:02:57 -0400 Subject: [PATCH 09/52] working pem generation --- app.js | 8 ++++++-- index.html | 14 +++++++++++++ lib/ecdsa.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/app.js b/app.js index 1738a2c..097d710 100644 --- a/app.js +++ b/app.js @@ -44,15 +44,19 @@ function run() { console.log('opts', opts); Keypairs.generate(opts).then(function (results) { var der = x509.packPkcs8(results.private); - console.log(der) - // Pem.encode(x509.packPkcs8(privateJwk)) + var pem = Eckles.export({jwk:results.private}) + $('.js-jwk').innerText = JSON.stringify(results, null, 2); + $('.js-der').innerText = JSON.stringify(der, null, 2); + $('.js-input-pem').innerText = pem; // $('.js-loading').hidden = true; $('.js-jwk').hidden = false; $$('input').map(function ($el) { $el.disabled = false; }); $$('button').map(function ($el) { $el.disabled = false; }); $('.js-toc-jwk').hidden = false; + $('.js-toc-der').hidden = false; + $('.js-toc-pem').hidden = false; }); }); diff --git a/index.html b/index.html index 0d35e9a..d4fec55 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,12 @@ BlueCrypt +

BlueCrypt for the Browser

@@ -58,6 +64,14 @@ JWK Keypair
 
+ + -