| 1 | /** |
| 2 | * @description MeshCentral letsEncrypt module, uses ACME-Client to do all the work. |
| 3 | * @author Ylian Saint-Hilaire |
| 4 | * @copyright Intel Corporation 2018-2022 |
| 5 | * @license Apache-2.0 |
| 6 | * @version v0.0.2 |
| 7 | */ |
| 8 | |
| 9 | /*xjslint node: true */ |
| 10 | /*xjslint plusplus: true */ |
| 11 | /*xjslint maxlen: 256 */ |
| 12 | /*jshint node: true */ |
| 13 | /*jshint strict: false */ |
| 14 | /*jshint esversion: 6 */ |
| 15 | 'use strict'; |
| 16 | |
| 17 | // ACME-Client Implementation |
| 18 | var globalLetsEncrypt = null; |
| 19 | module.exports.CreateLetsEncrypt = function (parent) { |
| 20 | const acme = require('acme-client'); |
| 21 | |
| 22 | var obj = {}; |
| 23 | obj.fs = require('fs'); |
| 24 | obj.path = require('path'); |
| 25 | obj.parent = parent; |
| 26 | obj.forge = obj.parent.certificateOperations.forge; |
| 27 | obj.leDomains = null; |
| 28 | obj.challenges = {}; |
| 29 | obj.runAsProduction = false; |
| 30 | obj.redirWebServerHooked = false; |
| 31 | obj.zerossl = false; |
| 32 | obj.csr = null; |
| 33 | obj.configErr = null; |
| 34 | obj.configOk = false; |
| 35 | obj.pendingRequest = false; |
| 36 | |
| 37 | // Let's Encrypt debug logging |
| 38 | obj.log = function (str) { |
| 39 | parent.debug('cert', 'LE: ' + str); |
| 40 | var d = new Date(); |
| 41 | obj.events.push(d.toLocaleDateString() + ' ' + d.toLocaleTimeString() + ' - ' + str); |
| 42 | while (obj.events.length > 200) { obj.events.shift(); } // Keep only 200 last events. |
| 43 | } |
| 44 | obj.events = []; |
| 45 | |
| 46 | // Setup the certificate storage paths |
| 47 | obj.certPath = obj.path.join(obj.parent.datapath, 'letsencrypt-certs'); |
| 48 | try { obj.parent.fs.mkdirSync(obj.certPath); } catch (e) { } |
| 49 | |
| 50 | // Hook up GreenLock to the redirection server |
| 51 | if (obj.parent.config.settings.rediraliasport === 80) { obj.redirWebServerHooked = true; } |
| 52 | else if ((obj.parent.config.settings.rediraliasport == null) && (obj.parent.redirserver.port == 80)) { obj.redirWebServerHooked = true; } |
| 53 | |
| 54 | // Deal with HTTP challenges |
| 55 | function challengeCreateFn(authz, challenge, keyAuthorization) { if (challenge.type === 'http-01') { obj.challenges[challenge.token] = keyAuthorization; } } |
| 56 | function challengeRemoveFn(authz, challenge, keyAuthorization) { if (challenge.type === 'http-01') { delete obj.challenges[challenge.token]; } } |
| 57 | obj.challenge = function (token, hostname, func) { if (obj.challenges[token] != null) { obj.log("Succesful response to challenge."); } else { obj.log("Failed to respond to challenge, token: " + token + ", table: " + JSON.stringify(obj.challenges) + "."); } func(obj.challenges[token]); } |
| 58 | |
| 59 | // Get the current certificate |
| 60 | obj.getCertificate = function(certs, func) { |
| 61 | obj.runAsProduction = (obj.parent.config.letsencrypt.production === true); |
| 62 | obj.zerossl = ((typeof obj.parent.config.letsencrypt.zerossl == 'object') ? obj.parent.config.letsencrypt.zerossl : false); |
| 63 | obj.log("Getting certs from local store (" + (obj.runAsProduction ? "Production" : "Staging") + ")"); |
| 64 | if (certs.CommonName.indexOf('.') == -1) { obj.configErr = "Add \"cert\" value to settings in config.json before using Let's Encrypt."; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 65 | if (obj.parent.config.letsencrypt == null) { obj.configErr = "No Let's Encrypt configuration"; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 66 | if (obj.parent.config.letsencrypt.email == null) { obj.configErr = "Let's Encrypt email address not specified."; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 67 | if ((obj.parent.redirserver == null) || ((typeof obj.parent.config.settings.rediraliasport === 'number') && (obj.parent.config.settings.rediraliasport !== 80)) || ((obj.parent.config.settings.rediraliasport == null) && (obj.parent.redirserver.port !== 80))) { obj.configErr = "Redirection web server must be active on port 80 for Let's Encrypt to work."; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 68 | if (obj.redirWebServerHooked !== true) { obj.configErr = "Redirection web server not setup for Let's Encrypt to work."; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 69 | if ((obj.parent.config.letsencrypt.rsakeysize != null) && (obj.parent.config.letsencrypt.rsakeysize !== 2048) && (obj.parent.config.letsencrypt.rsakeysize !== 3072) && (obj.parent.config.letsencrypt.rsakeysize !== 4096)) { obj.configErr = "Invalid Let's Encrypt certificate key size, must be 2048, 3072 or 4096."; parent.addServerWarning(obj.configErr); obj.log("WARNING: " + obj.configErr); func(certs); return; } |
| 70 | if (obj.checkInterval == null) { obj.checkInterval = setInterval(obj.checkRenewCertificate, 86400000); } // Call certificate check every 24 hours. |
| 71 | obj.configOk = true; |
| 72 | |
| 73 | // Get the list of domains |
| 74 | obj.leDomains = [ certs.CommonName ]; |
| 75 | if (obj.parent.config.letsencrypt.names != null) { |
| 76 | if (typeof obj.parent.config.letsencrypt.names == 'string') { obj.parent.config.letsencrypt.names = obj.parent.config.letsencrypt.names.split(','); } |
| 77 | obj.parent.config.letsencrypt.names.map(function (s) { return s.trim(); }); // Trim each name |
| 78 | if ((typeof obj.parent.config.letsencrypt.names != 'object') || (obj.parent.config.letsencrypt.names.length == null)) { console.log("ERROR: Let's Encrypt names must be an array in config.json."); func(certs); return; } |
| 79 | obj.leDomains = obj.parent.config.letsencrypt.names; |
| 80 | } |
| 81 | |
| 82 | // Read TLS certificate from the configPath |
| 83 | var certFile = obj.path.join(obj.certPath, (obj.runAsProduction ? 'production.crt' : 'staging.crt')); |
| 84 | var keyFile = obj.path.join(obj.certPath, (obj.runAsProduction ? 'production.key' : 'staging.key')); |
| 85 | if (obj.fs.existsSync(certFile) && obj.fs.existsSync(keyFile)) { |
| 86 | obj.log("Reading certificate files"); |
| 87 | |
| 88 | // Read the certificate and private key |
| 89 | var certPem = obj.fs.readFileSync(certFile).toString('utf8'); |
| 90 | var cert = obj.forge.pki.certificateFromPem(certPem); |
| 91 | var keyPem = obj.fs.readFileSync(keyFile).toString('utf8'); |
| 92 | var key = obj.forge.pki.privateKeyFromPem(keyPem); |
| 93 | |
| 94 | // Decode the certificate common and alt names |
| 95 | obj.certNames = [cert.subject.getField('CN').value]; |
| 96 | var altNames = cert.getExtension('subjectAltName'); |
| 97 | if (altNames) { for (var i = 0; i < altNames.altNames.length; i++) { var acn = altNames.altNames[i].value.toLowerCase(); if (obj.certNames.indexOf(acn) == -1) { obj.certNames.push(acn); } } } |
| 98 | |
| 99 | // Decode the certificate expire time |
| 100 | obj.certExpire = cert.validity.notAfter; |
| 101 | |
| 102 | // Use this certificate when possible on any domain |
| 103 | if (obj.certNames.indexOf(certs.CommonName) >= 0) { |
| 104 | obj.log("Setting LE cert for default domain."); |
| 105 | certs.web.cert = certPem; |
| 106 | certs.web.key = keyPem; |
| 107 | //certs.web.ca = [results.pems.chain]; |
| 108 | } |
| 109 | for (var i in obj.parent.config.domains) { |
| 110 | if ((obj.parent.config.domains[i].dns != null) && (obj.parent.certificateOperations.compareCertificateNames(obj.certNames, obj.parent.config.domains[i].dns))) { |
| 111 | obj.log("Setting LE cert for domain " + i + "."); |
| 112 | certs.dns[i].cert = certPem; |
| 113 | certs.dns[i].key = keyPem; |
| 114 | //certs.dns[i].ca = [results.pems.chain]; |
| 115 | } |
| 116 | } |
| 117 | } else { |
| 118 | obj.log("No certificate files found"); |
| 119 | } |
| 120 | func(certs); |
| 121 | setTimeout(obj.checkRenewCertificate, 5000); // Hold 5 seconds and check if we need to request a certificate. |
| 122 | } |
| 123 | |
| 124 | // Check if we need to get a new certificate |
| 125 | // Return 0 = CertOK, 1 = Request:NoCert, 2 = Request:Expire, 3 = Request:MissingNames |
| 126 | obj.checkRenewCertificate = function () { |
| 127 | if (obj.pendingRequest == true) { obj.log("Request for certificate is in process."); return 4; } |
| 128 | if (obj.certNames == null) { |
| 129 | obj.log("Got no certificates, asking for one now."); |
| 130 | obj.requestCertificate(); |
| 131 | return 1; |
| 132 | } else { |
| 133 | // Look at the existing certificate to see if we need to renew it |
| 134 | var daysLeft = Math.floor((obj.certExpire - new Date()) / 86400000); |
| 135 | obj.log("Certificate has " + daysLeft + " day(s) left."); |
| 136 | if (daysLeft < 45) { |
| 137 | obj.log("Asking for new certificate because of expire time."); |
| 138 | obj.requestCertificate(); |
| 139 | return 2; |
| 140 | } else { |
| 141 | var missingDomain = false; |
| 142 | for (var i in obj.leDomains) { |
| 143 | if (obj.parent.certificateOperations.compareCertificateNames(obj.certNames, obj.leDomains[i]) == false) { |
| 144 | obj.log("Missing name \"" + obj.leDomains[i] + "\"."); |
| 145 | missingDomain = true; |
| 146 | } |
| 147 | } |
| 148 | if (missingDomain) { |
| 149 | obj.log("Asking for new certificate because of missing names."); |
| 150 | obj.requestCertificate(); |
| 151 | return 3; |
| 152 | } else { |
| 153 | obj.log("Certificate is ok."); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | return 0; |
| 158 | } |
| 159 | |
| 160 | obj.requestCertificate = function () { |
| 161 | if (obj.pendingRequest == true) return; |
| 162 | if (obj.configOk == false) { obj.log("Can't request cert, invalid configuration."); return; } |
| 163 | if (acme.forge == null) { obj.log("Forge not setup in ACME, unable to continue."); return; } |
| 164 | obj.pendingRequest = true; |
| 165 | |
| 166 | // Create a private key |
| 167 | obj.log("Generating private key..."); |
| 168 | acme.forge.createPrivateKey(obj.parent.config.letsencrypt.rsakeysize != null ? obj.parent.config.letsencrypt.rsakeysize : 2048).then(function (accountKey) { |
| 169 | |
| 170 | // Create the ACME client |
| 171 | obj.log("Setting up ACME client..."); |
| 172 | if (obj.zerossl) { |
| 173 | if (obj.zerossl.kid == "") { obj.log("EAB KID hasn't been set, invalid configuration."); return; } |
| 174 | if (obj.zerossl.hmackey == "") { obj.log("EAB HMAC KEY hasn't been set, invalid configuration."); return; } |
| 175 | obj.client = new acme.Client({ |
| 176 | directoryUrl: acme.directory.zerossl.production, |
| 177 | accountKey: accountKey, |
| 178 | externalAccountBinding: { |
| 179 | kid: obj.zerossl.kid, |
| 180 | hmacKey: obj.zerossl.hmackey |
| 181 | } |
| 182 | }); |
| 183 | } else if (obj.custom) { |
| 184 | if (obj.custom.kid == "") { obj.log("EAB KID hasn't been set, invalid configuration."); return; } |
| 185 | if (obj.custom.hmackey == "") { obj.log("EAB HMAC KEY hasn't been set, invalid configuration."); return; } |
| 186 | if (obj.custom.server == "") { obj.log("Custom ACME server URL hasn't been set, invalid configuration."); return; } |
| 187 | obj.client = new acme.Client({ |
| 188 | directoryUrl: obj.custom.server, |
| 189 | accountKey: accountKey, |
| 190 | externalAccountBinding: { |
| 191 | kid: obj.custom.kid, |
| 192 | hmacKey: obj.custom.hmackey |
| 193 | } |
| 194 | }); |
| 195 | } else { |
| 196 | obj.client = new acme.Client({ |
| 197 | directoryUrl: obj.runAsProduction ? acme.directory.letsencrypt.production : acme.directory.letsencrypt.staging, |
| 198 | accountKey: accountKey |
| 199 | }); |
| 200 | } |
| 201 | |
| 202 | // Create Certificate Request (CSR) |
| 203 | obj.log("Creating certificate request..."); |
| 204 | var certRequest = { commonName: obj.leDomains[0], keySize: obj.parent.config.letsencrypt.rsakeysize != null ? obj.parent.config.letsencrypt.rsakeysize : 2048 }; |
| 205 | if (obj.leDomains.length > 1) { certRequest.altNames = obj.leDomains; } |
| 206 | acme.forge.createCsr(certRequest).then(function (r) { |
| 207 | obj.csr = r[1]; |
| 208 | obj.tempPrivateKey = r[0]; |
| 209 | if(obj.zerossl) { |
| 210 | obj.log("Requesting certificate from ZeroSSL..."); |
| 211 | } else if(obj.custom) { |
| 212 | obj.log("Requesting certificate from Custom ACME server..."); |
| 213 | } else { |
| 214 | obj.log("Requesting certificate from Let's Encrypt..."); |
| 215 | } |
| 216 | obj.client.auto({ |
| 217 | csr: obj.csr, |
| 218 | email: obj.parent.config.letsencrypt.email, |
| 219 | termsOfServiceAgreed: true, |
| 220 | skipChallengeVerification: (obj.parent.config.letsencrypt.skipchallengeverification === true), |
| 221 | challengeCreateFn, |
| 222 | challengeRemoveFn |
| 223 | }).then(function (cert) { |
| 224 | obj.log("Got certificate."); |
| 225 | |
| 226 | // Save certificate and private key to PEM files |
| 227 | var certFile = obj.path.join(obj.certPath, (obj.runAsProduction ? 'production.crt' : 'staging.crt')); |
| 228 | var keyFile = obj.path.join(obj.certPath, (obj.runAsProduction ? 'production.key' : 'staging.key')); |
| 229 | obj.fs.writeFileSync(certFile, cert); |
| 230 | obj.fs.writeFileSync(keyFile, obj.tempPrivateKey); |
| 231 | delete obj.tempPrivateKey; |
| 232 | |
| 233 | // Cause a server restart |
| 234 | obj.log("Performing server restart..."); |
| 235 | obj.parent.performServerCertUpdate(); |
| 236 | }, function (err) { |
| 237 | obj.log("Failed to obtain certificate: " + err.message); |
| 238 | obj.pendingRequest = false; |
| 239 | delete obj.client; |
| 240 | }); |
| 241 | }, function (err) { |
| 242 | obj.log("Failed to generate certificate request: " + err.message); |
| 243 | obj.pendingRequest = false; |
| 244 | delete obj.client; |
| 245 | }); |
| 246 | }, function (err) { |
| 247 | obj.log("Failed to generate private key: " + err.message); |
| 248 | obj.pendingRequest = false; |
| 249 | delete obj.client; |
| 250 | }); |
| 251 | } |
| 252 | |
| 253 | // Return the status of this module |
| 254 | obj.getStats = function () { |
| 255 | var r = { |
| 256 | configOk: obj.configOk, |
| 257 | leDomains: obj.leDomains, |
| 258 | challenges: obj.challenges, |
| 259 | production: obj.runAsProduction, |
| 260 | webServer: obj.redirWebServerHooked, |
| 261 | certPath: obj.certPath, |
| 262 | skipChallengeVerification: (obj.parent.config.letsencrypt.skipchallengeverification == true) |
| 263 | }; |
| 264 | if (obj.configErr) { r.error = "WARNING: " + obj.configErr; } |
| 265 | if (obj.certExpire) { r.cert = 'Present'; r.daysLeft = Math.floor((obj.certExpire - new Date()) / 86400000); } else { r.cert = 'None'; } |
| 266 | return r; |
| 267 | } |
| 268 | |
| 269 | return obj; |
| 270 | } |