-
Notifications
You must be signed in to change notification settings - Fork 0
/
letsencrypt.js
executable file
·652 lines (463 loc) · 16.9 KB
/
letsencrypt.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/*
The MIT License (MIT)
Copyright (c) 2016 Johan Zetterberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict";
var PORT = 8094; // Run the HTTP server on this port, witch need to be configured in a nginx config file:
/*
# Lets encrypt challange
location /.well-known/acme-challenge/ {
proxy_pass http://127.0.0.1:8094;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
*/
var CERT_BASE_PATH = "/path/to/cert/"; // path to certification files (used by nginx)
var KEYS_BASE_PATH = "/path/to/keys/"; // path to crypto keys! (used by nginx)
/*
sudo mkdir /tank/ssl/cert/ /tank/ssl/keys/ -p
sudo useradd -r -s /bin/false letsencrypt
sudo chown letsencrypt:letsencrypt /tank/ssl/cert/ /tank/ssl/keys/
sudo chmod 755 /tank/ssl/cert/
sudo chmod 750 /tank/ssl/keys/
Do I need to add nginx to letsencrypt group?
Usage: sudo -u letsencrypt node letsencrypt.js yourdomain.com
If no domain is supplied to the argument, all existing domains will be checked for expire date and automaticly renewed.
crontab "installation"
----------------------
crontab -u letsencrypt -e
45 7,19 * * * node /tank/nodejs/letsencrypt.js
Change the first value (minute 45), and hours 7,19 to a "random" value to somewhat ease the load on the ACME servers
*/
var MAX_EXPIRE_HOURS = 120; // Renew the certificate if it expires in less then
var ADMIN_EMAIL = "CHANGEME"; // Change this to your own e-mail address!
var ACME_URL = "https://acme-staging.api.letsencrypt.org/directory"; // Change this to production after testing!
/*
testing url= https://acme-staging.api.letsencrypt.org/directory
Do your tests before switching to
prod url= https://acme-v01.api.letsencrypt.org/directory
Remove letsencrypt-account.json (and recreate letsencrypt-acccount.key), as well as all created certificates, when switching to prod
sudo rm /tank/ssl/keys/letsencrypt-account.json
sudo rm /tank/ssl/keys/letsencrypt-account.key
*/
// Option flags
var revoke = false; // This is not implemented, but contributions are welcome! (call revoke-cert)
var logall = true; // If set to false, only writes to console log if it's "imporant""
var checkDomain; // The domain to check
for(var i=2; i<process.argv.length; i++) {
if(process.argv[i].substr(0, 1) != "-") checkDomain = process.argv[i].trim()
else if(process.argv[i] == "-silent") logall = false
else if(process.argv[i] == "-revoke") revoke = true // Not yet implemented
}
// Functions to manage ACME challenges
var challengeCache = {};
var challengeStore = {
set: function setChallenge(hostname, key, value, cb) {
log("challengeStore.set: hostname=" + hostname + " key=" + key + " value=" + value);
challengeCache[key] = value;
cb(null);
}
, get: function getChallengeAnswer(hostname, key, cb) {
log("challengeStore.get: hostname=" + hostname + " key=" + key);
cb(null, challengeCache[key]);
}
, remove: function removeChallenge(hostname, key, cb) {
log("challengeStore.remove: hostname=" + hostname + " key=" + key);
delete challengeCache[key];
cb(null);
}
};
// Functions to manage certificates
var certCache = {};
var certStore = {
set: function storeCertificate(hostname, certs, cb) {
log("certStore.set: hostname=" + hostname + " certs=" + certs);
if(certs == undefined) {
console.warn("certStore: certs is undefined!")
cb(null);
}
else {
certCache[hostname] = certs;
var counter = 0;
var countUntil = 2; // Wait until all two files has been created before calling callback function
/*
fs.writeFile("ca.pem", certs["ca"], function(err) {
if (err) throw err;
log("ca.pem created");
if(++counter==countUntil) cb(null);
});
fs.writeFile("cert.pem", certs["cert"], function(err) {
if (err) throw err;
log("cert.pem created");
if(++counter==countUntil) cb(null);
});
*/
fs.writeFile(KEYS_BASE_PATH + hostname + ".key", certs["key"], function(err) {
if (err) throw err;
log(hostname + ".key created");
if(++counter==countUntil) cb(null);
});
// Nginx needs both the cert and "ca" concatenated
fs.writeFile(CERT_BASE_PATH + hostname + ".crt", certs["cert"] + "\n" + certs["ca"], function(err) {
if (err) throw err;
log(hostname + ".crt created");
if(++counter==countUntil) cb(null);
});
}
}
, get: function retrieveCert(hostname, cb) {
log("certStore.get: hostname=" + hostname);
cb(null, certCache[hostname]);
}
, remove: function deleteCert(hostname, cb) {
log("certStore.remove: hostname=" + hostname);
delete certCache[hostname];
cb(null);
}
};
var fs = require("fs"); // Load nodeJS file library into the fs variable
// Check if account.key file exist
var accountKeyPath = KEYS_BASE_PATH + "letsencrypt-account.key"
try {
var ACCOUNT_KEY = fs.readFileSync(accountKeyPath);
}
catch(err) {
if(err.code=="ENOENT") {
log(accountKeyPath + " does not exist. Create it using:\nsudo sh -c 'openssl genrsa 4096 > " + accountKeyPath + "' && sudo chown letsencrypt:letsencrypt " + accountKeyPath + " && sudo chmod 700 " + accountKeyPath + "\n", true);
process.exit();
}
else throw err;
}
// Create a HTTP server to use for ACME challenges
var http = require('http');
var httpServer = http.createServer(acmeResponder);
function acmeResponder(req, res) {
var addr = req.url;
var ip = req.headers["x-real-ip"] ? req.headers["x-real-ip"] : req.connection.remoteAddress;
log("Request to " + addr + " from " + ip + "");
if (0 !== req.url.indexOf(LeCore.acmeChallengePrefix)) {
res.end('Hello World!');
return;
}
var key = req.url.slice(LeCore.acmeChallengePrefix.length);
var hostname = req.headers["x-host"] || req.hostname;
challengeStore.get(hostname, key, function (err, val) {
res.end(val || 'Error');
});
}
var http_server_running = false;
var LeCore = require('letiny-core'); // This is an important dependency (npm install letiny-core)
var accountJson = KEYS_BASE_PATH + "letsencrypt-account.json";
// Get the ACME URL's used to make commands like new-cert, new-reg and revoke-cert
var ACME_URLS;
log("Getting urls");
LeCore.getAcmeUrls(ACME_URL, function (err, urls) {
if(err) throw err;
log("Got urls: " + urls);
ACME_URLS = urls;
// Check if letsencrypt-account.json exist, if not, we have probably not registered. Remove this file (and account.key) when switching from staging to live/prod
try {
fs.readFileSync(accountJson)
}
catch(err) {
if(err.code=="ENOENT") {
// This means we have probably not registered. Register an account, then run the main function.
return registerNewAccount(main);
}
else throw err;
}
// If the read was successful
return main();
});
function main() {
if(checkDomain) {
checkNginxCnf(checkDomain, function(err) {
if(err) throw err;
checkCertRenewal(checkDomain, function(err, renewNeeded) {
if(err) throw err;
log("renewNeeded=" + renewNeeded);
if(renewNeeded) {
getCert(checkDomain, function(err, certs) {
if(err) throw err;
log(checkDomain + " renewed");
exit();
});
}
else return exit();
});
});
}
else {
// Check existing domains if they need renewal
fs.readdir(CERT_BASE_PATH, function listCerts(err, files) {
if(files == undefined) {
log("Did not find any (certiface) files in " + CERT_BASE_PATH, true);
process.exit();
}
var leftToCheck = files.length;
var errors = [];
if(leftToCheck == 0) log("No certificates found!", true)
else {
files.forEach(function checkFile(fileName) {
// Remove the .crt part from file name
var checkDomain = fileName.substring(0, fileName.length-4);
log("Checking " + checkDomain);
// Make sure the nginx config is ok
checkNginxCnf(checkDomain, function(err) {
if(err) {
log("Problem checking nginx configuration for " + checkDomain + "", true);
log(err.message, true);
errors.push(err);
doneCheck(checkDomain);
}
else {
checkCertRenewal(checkDomain, function(err, renewNeeded) {
if(err) {
log("Problem checking if " + checkDomain + " need renewal", true);
log(err.message, true);
errors.push(err);
doneCheck(checkDomain);
}
else {
if(renewNeeded) {
log("Needs renewal: " + checkDomain);
getCert(checkDomain, function(err, certs) {
if(err) {
log("Problem requesting certificate for " + checkDomain, true);
log(err.message, true);
errors.push(err);
}
else {
log(checkDomain + " renewed", true);
}
doneCheck(checkDomain);
});
}
else doneCheck(checkDomain);
}
});
}
});
});
}
function doneCheck(checkDomain) {
leftToCheck--;
log("Handled " + checkDomain + ". " + leftToCheck + " domains left to check.")
if(leftToCheck === 0) {
if(errors.length > 0) {
var messages = "";
for (var i=0; i<errors.length; i++) {
messages += errors[i].message + "\n";
}
throw new Error("One or more errors occured. Check the log file!\n" + messages);
}
exit();
}
}
});
}
}
function exit() {
// Close the server
if(http_server_running) {
httpServer.close();
log("Closed HTTP server")
}
}
function checkNginxCnf(checkDomain, callback) {
// Make sure it exist in nginx enabled sites and is configurated to redirect ACME challanges
var fs = require("fs");
var nginxCfgPath = "/etc/nginx/sites-enabled/" + checkDomain;
fs.readFile(nginxCfgPath, "utf8", function readNginxCnf(err, nginxCnf) {
if (err) {
if(err.code=="ENOENT") {
// Allow naked domain ...
var parts = checkDomain.match(/(.*)\.(.*)\.(.*)/);
if(parts) {
if(parts.length == 4) {
var subdomain = parts[1];
var domain = parts[2];
var tld = parts[3];
nginxCfgPath = "/etc/nginx/sites-enabled/" + domain + "." + tld;
log("Unable to find nginx config file for " + checkDomain + " checking " + domain + "." + tld + " instead ...");
fs.readFile(nginxCfgPath, "utf8", function readNginxCnfNaked(err, nginxCnf) {
if (err) {
if(err.code=="ENOENT") noNginxConfigFound();
else throw err;
}
else checkNginxCnfContent(nginxCnf);
});
}
else {
throw new Error("Expected parts.length=" + parts.length + " to be 4 ! parts=" + JSON.stringify(parts));
}
}
else noNginxConfigFound();
}
else throw err;
}
else checkNginxCnfContent(nginxCnf);
function checkNginxCnfContent(nginxCnf) {
// Why doesn't multi-line regex work??
//var acmeChallenge = new RegExp("location \/\.well-known\/acme-challenge\/ {\s+proxy_pass http:\/\/127\.0\.0\.1:" + PORT + ";", "img");
//var hasAcmeChallenge = nginxCnf.match(acmeChallenge);
var hasAcmeChallenge = nginxCnf.indexOf("location /.well-known/acme-challenge/") != -1 &&
nginxCnf.indexOf("proxy_pass http://127.0.0.1:" + PORT + ";") != -1;
var hasServerName = nginxCnf.match(new RegExp("server_name .*" + checkDomain));
//log("hasAcmeChallenge=" + hasAcmeChallenge);
if(hasAcmeChallenge && hasServerName) {
log("nginx config for " + checkDomain + " OK!");
if(callback) return callback(null);
}
else {
var err = new Error(checkDomain + " is not configured with /.well-known/acme-challenge");
if(callback) return callback(err)
else throw err;
}
}
function noNginxConfigFound() {
var err = new Error("No nginx configuration file for " + checkDomain + " exist! (" + nginxCfgPath + ")");
if(callback) return callback(err)
else throw err;
}
});
}
function checkCertRenewal(checkDomain, callback) {
// Check if the certificate exist, and if it needs to be renewed
if(callback == undefined) throw new Error("No callback defined in function argument");
var certPath = CERT_BASE_PATH + checkDomain + ".crt";
//log("Reading certPath=" + certPath + " ...");
fs.readFile(certPath, "utf8", function readCert(err, cert) {
if (err) {
if(err.code=="ENOENT") {
log(certPath + " does not exist! So it needs *renewal*", true);
return callback(null, true);
}
else {
log("Error reading certPath=" + certPath + " Error: " + err.message);
return callback(err);
}
}
// Check if it needs to be renewed
var ssl = require('ssl-utils');
ssl.checkCertificateExpiration(cert, function gotDate(err, expiry) {
//expiry is a Date instance
//log("expiry=" + expiry);
if(err) {
log("Error checking expire date for domain=" + checkDomain + " Errror: " + err.message);
callback(err);
}
else {
var remainingTime = expiry.getTime() - Date.now();
//log("remainingTime=" + remainingTime);
var remainingHours = Math.round(remainingTime / (1000 * 60 * 60));
//log(checkDomain + " remainingHours=" + remainingHours);
log(remainingHours + " hours left until " + checkDomain + " expires");
if(remainingHours < MAX_EXPIRE_HOURS) {
return callback(null, true);
}
else {
return callback(null, false);
}
}
});
});
}
function registerNewAccount(callback) {
// Registers a new lets encrypt account, that will be used for creating certificates
var LeCore = require('letiny-core');
LeCore.registerNewAccount(
{ newRegUrl: ACME_URLS.newReg
, email: ADMIN_EMAIL
, accountPrivateKeyPem: ACCOUNT_KEY
, agreeToTerms: function agreeToTerms(tosUrl, done) {
log("agreeToTerms: tosUrl=" + tosUrl);
// agree to the exact version of these terms
done(null, tosUrl);
}
}
, function registered(err, regr) {
if(err) throw err;
//log("regr=" + JSON.stringify(regr));
// This data might become useful later ... So lets save it
fs.writeFile(accountJson, JSON.stringify(regr, null, 2), function accountJsonCreated(err) {
if (err) throw err;
log(accountJson + " created");
if(callback) callback(null);
});
});
}
function getCert(domain, callback) {
var LeCore = require('letiny-core');
var domains = [domain]; // Needs to be an array
log("Getting certificate for domain=" + domain);
// Always create a new key (change the locks) when creating a new certificate
LeCore.leCrypto.generateRsaKeypair(2048, 65537, function (err, pems) {
if(err) throw err;
//log(pems);
var domainPrivateKeyPem = pems.privateKeyPem;
if(!http_server_running) { // Only start the server if it hasn't already started
http_server_running = true;
httpServer.listen(PORT, function () {
log('Started HTTP server on ' + this.address());
getCertificate();
});
}
else {
log("HTTP server already running");
getCertificate();
}
function getCertificate() {
LeCore.getCertificate(
{ newAuthzUrl: ACME_URLS.newAuthz
, newCertUrl: ACME_URLS.newCert
, domainPrivateKeyPem: domainPrivateKeyPem
, accountPrivateKeyPem: ACCOUNT_KEY
, domains: domains
, setChallenge: challengeStore.set
, removeChallenge: challengeStore.remove
}
, function (err, certs) {
if(err) {
log("Error getting certificate for domain=" + domain + " Error: " + err.message);
if(callback) callback(err)
else throw err;
}
else {
//log("certs=" + JSON.stringify(certs));
log("Received certificate for ... ");
// Note: you should save certs to disk (or db)
certStore.set(domains[0], certs, function (err) {
if(err) {
if(callback) callback(err)
else throw err;
}
else {
log("Files saved");
if(callback) callback(null, certs);
}
});
}
}
);
}
});
}
function log(msg, important) {
if(logall || important) console.log(msg);
}