-
Notifications
You must be signed in to change notification settings - Fork 582
/
certhelper.php
executable file
·1597 lines (1456 loc) · 64.6 KB
/
certhelper.php
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/bin/php
<?php
/*
* Copyright (C) 2017-2019 Frank Wall
* Copyright (C) 2015 Deciso B.V.
* Copyright (C) 2010 Jim Pingle <jimp@pfsense.org>
* Copyright (C) 2008 Shrew Soft Inc. <mgrooms@shrew.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Hello. I am the spaghetti monster. Yummy.
// Use legacy code to manage certificates.
require_once("config.inc");
require_once("certs.inc");
require_once("legacy_bindings.inc");
require_once("interfaces.inc");
require_once("util.inc");
// Some stuff requires the almighty MVC framework.
use OPNsense\Core\Backend;
use OPNsense\Core\Config;
use OPNsense\Base;
use OPNsense\AcmeClient\AcmeClient;
$postponed_updates = array();
/* CLI arguments:
* -a (action)
* -c (certificate id, NOT the uuid)
* -A (all certificates)
* -C (cron, special rules apply when running as cronjob)
* -F (force, rewew/recreate)
* -S (staging)
*/
$options = getopt("a:c:ACFS");
// Simple validation
if (!isset($options["a"]) or (!isset($options["c"]) and !isset($options["A"]))) {
// ALL actions require either a certificate ID or the -A switch
echo "ERROR: not enough arguments\n";
exit(1);
}
if (($options["a"] == 'revoke') and !isset($options["c"])) {
echo "ERROR: option revoke requires a certificate ID\n";
exit(1);
}
// Cron mode
if (isset($options["C"])) {
// Automatically work on ALL certificates
$options["A"] = "";
}
// Run the specified action
switch ($options["a"]) {
case 'sign':
$result = cert_action_validator($options["c"]);
echo json_encode(array('status' => $result));
break;
case 'renew':
$result = cert_action_validator($options["c"]);
echo json_encode(array('status' => $result));
break;
case 'remove':
$result = cert_action_validator($options["c"]);
echo json_encode(array('status' => $result));
break;
case 'removekey':
$result = cert_action_validator($options["c"]);
echo json_encode(array('status' => $result));
break;
case 'revoke':
$result = cert_action_validator($options["c"]);
echo json_encode(array('status' => $result));
break;
default:
echo "ERROR: invalid argument specified\n";
log_error("invalid argument specified");
exit(1);
}
// Write certificate status updates to configuration
dump_postponed_updates();
// ALL certificate work starts here. First we do some common validation and
// make sure that everything is prepared for acme client to run.
// The actual issue/renew/revoke work is done by separate functions.
function cert_action_validator($opt_cert_id)
{
global $options;
$modelObj = new OPNsense\AcmeClient\AcmeClient();
// Store certs here after successful issue/renewal. Required for automations.
$restart_certs = array();
// Search for cert ID in configuration
$configObj = Config::getInstance()->object();
if (isset($configObj->OPNsense->AcmeClient->certificates) && $configObj->OPNsense->AcmeClient->certificates->count() > 0) {
foreach ($configObj->OPNsense->AcmeClient->certificates->children() as $certObj) {
// Extract cert ID
$cert_id = (string)$certObj->id;
if (empty($cert_id)) {
continue; // Cert is invalid, skip it.
}
// Either work with ALL certificates or check if cert ID matches
if (isset($options["A"]) or ((string)$cert_id == (string)$opt_cert_id)) {
// Ignore disabled certificates
if ($certObj->enabled == 0) {
// Always ignore disabled certs when working on ALL certs.
if (isset($options["A"])) {
continue; // skip to next item
}
// Allow only "revoke", "remove" and "removekey" for disabled certs.
if (!in_array($options["a"], ['remove','removekey','revoke'])) {
return(1); // Cert is disabled, skip it.
}
}
// Extract Account from referenced obj
$acctRef = (string)$certObj->account;
$acctObj = null;
$acctref_found = false;
foreach ($modelObj->getNodeByReference('accounts.account')->iterateItems() as $node) {
if ((string)$node->getAttributes()["uuid"] == $acctRef) {
$acctref_found = true;
$acctObj = $node;
break; // Match! Go ahead.
}
}
// Make sure we found the configured account
if ($acctref_found == true) {
// Ensure that this account was properly setup and registered.
$acct_result = run_acme_account_registration($acctObj, $certObj, $modelObj);
if (!$acct_result) {
// account registration OK
} else {
log_error("AcmeClient: account registration failed");
log_cert_acme_status($certObj, $modelObj, '400');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
} else {
log_error("AcmeClient: account not found");
log_cert_acme_status($certObj, $modelObj, '300');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
// Extract Validation Method from referenced obj
$valRef = (string)$certObj->validationMethod;
$valObj = null;
$ref_found = false;
foreach ($modelObj->getNodeByReference('validations.validation')->iterateItems() as $node) {
if ((string)$node->getAttributes()["uuid"] == $valRef) {
$ref_found = true;
$valObj = $node;
break; // Match! Go ahead.
}
}
// Cert is being removed from the GUI, delete all traces.
if ($options["a"] == "remove") {
// Start acme client to remove the certificate
$rev_result = remove_cert($certObj);
if (!$rev_result) {
log_error("AcmeClient: successfully removed acme.sh certificate configuration for " . (string)$certObj->name);
return(0); // Success!
} else {
log_error("AcmeClient: failed to remove acme.sh certificate configuration for " . (string)$certObj->name);
return(1);
}
}
// Remove private key
// NOTE: Although the user requested to remove the private key,
// we simply perform a full cert removal because without the
// matching private key the cert is useless.
if ($options["a"] == "removekey") {
// Start acme client to remove the certificate
$rev_result = remove_cert($certObj);
if (!$rev_result) {
log_error("AcmeClient: successfully removed the private key and reset certificate " . (string)$certObj->name);
// Reset certificate state, treat it like a new certificate.
log_cert_acme_status($certObj, $modelObj, '100');
return(0); // Success!
} else {
log_error("AcmeClient: failed to remove the private key and reset certificate " . (string)$certObj->name);
return(1);
}
}
// Make sure we found the configured validation method
if ($ref_found == true) {
// Was a revocation requested?
// NOTE: Revocation is not even considered when some elements have already been
// deleted from the GUI. It's likely that it would fail anyway.
if ($options["a"] == "revoke") {
// Start acme client to revoke the certificate
$rev_result = revoke_cert($certObj, $valObj, $acctObj);
if (!$rev_result) {
log_cert_acme_status($certObj, $modelObj, '250');
return(0); // Success!
} else {
// Revocation failure
log_error("AcmeClient: revocation for certificate failed");
log_cert_acme_status($certObj, $modelObj, '400');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
}
// Which validation method?
if ((string)$valObj->method == 'http01' or ((string)$valObj->method == 'dns01')) {
// Start acme client to issue or renew certificate
$val_result = run_acme_validation($certObj, $valObj, $acctObj);
if (!$val_result) {
log_error("AcmeClient: successfully issued/renewed certificate: " . (string)$certObj->name);
// Import certificate to Cert Manager
if (!import_certificate($certObj, $modelObj)) {
// Prepare certificate for automation
$restart_certs[] = $certObj;
log_cert_acme_status($certObj, $modelObj, '200');
} else {
log_error("AcmeClient: unable to import certificate: " . (string)$certObj->name);
log_cert_acme_status($certObj, $modelObj, '500');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
} elseif ($val_result == '99') {
// Renewal not required. Do nothing.
} else {
// validation failure
log_error("AcmeClient: validation for certificate failed: " . (string)$certObj->name);
log_cert_acme_status($certObj, $modelObj, '400');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
} else {
log_error("AcmeClient: invalid validation method specified: " . (string)$valObj->method);
log_cert_acme_status($certObj, $modelObj, '300');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
} else {
log_error("AcmeClient: validation method not found for cert " . $certObj->name);
log_cert_acme_status($certObj, $modelObj, '300');
if (isset($options["A"])) {
continue; // skip to next item
}
return(1);
}
// Work on ALL certificates?
if (!isset($options["A"])) {
break; // Stop after first match.
}
}
}
} else {
log_error("AcmeClient: no LE certificates found in configuration");
return(1);
}
// Run automations if an operation was successful.
if (!empty($restart_certs)) {
// Execute automations.
if (!run_restart_actions($restart_certs, $modelObj)) {
# Success.
} else {
log_error("AcmeClient: failed to execute some automations");
}
}
return(0);
}
// Prepare optional parameters for acme client
function eval_optional_acme_args()
{
global $options;
$configObj = Config::getInstance()->object();
$acme_args = array();
// Force certificate renewal?
$acme_args[] = isset($options["F"]) ? "--force" : null;
// Use LE staging environment?
$acme_args[] = $configObj->OPNsense->AcmeClient->settings->environment == "stg" ? "--staging" : null;
$acme_args[] = isset($options["S"]) ? "--staging" : null; // for debug purpose
// Set log level
switch ($configObj->OPNsense->AcmeClient->settings->logLevel) {
case "extended":
$acme_args[] = "--log-level 2";
case "debug":
$acme_args[] = "--debug";
case "debug2":
$acme_args[] = "--debug 2";
case "debug3":
$acme_args[] = "--debug 3";
default:
$acme_args[] = "--log-level 1";
}
// Remove empty and duplicate elements from array
return(array_unique(array_filter($acme_args)));
}
// Create account keys and register accounts, export/import them from/to filesystem/config.xml
function run_acme_account_registration($acctObj, $certObj, $modelObj)
{
global $options;
// Prepare optional parameters for acme-client
$acme_args = eval_optional_acme_args();
// Collect account information
$acme_env = (string)$modelObj->settings->environment;
$account_conf_dir = "/var/etc/acme-client/accounts/" . $acctObj->id . "_${acme_env}";
$account_conf_file = $account_conf_dir . "/account.conf";
$account_key_file = $account_conf_dir . "/account.key";
$account_json_file = $account_conf_dir . "/account.json";
$account_ca_file = $account_conf_dir . "/ca.conf";
$acme_conf = array();
$acme_conf[] = "CERT_HOME='/var/etc/acme-client/home'";
$acme_conf[] = "LOG_FILE='/var/log/acme.sh.log'";
$acme_conf[] = "ACCOUNT_KEY_PATH='" . $account_key_file . "'";
$acme_conf[] = "ACCOUNT_JSON_PATH='" . $account_json_file . "'";
$acme_conf[] = "CA_CONF='" . $account_ca_file . "'";
if (!empty((string)$acctObj->email)) {
$acme_conf[] = "ACCOUNT_EMAIL='" . (string)$acctObj->email . "'";
}
// Create account configuration file
if (!is_dir($account_conf_dir)) {
mkdir($account_conf_dir, 0700, true);
}
file_put_contents($account_conf_file, (string)implode("\n", $acme_conf) . "\n");
chmod($account_conf_file, 0600);
// Check if account key already exists
if (is_file($account_key_file)) {
// account key found
} else {
// Check if we have an account key in our configuration
if (!empty((string)$acctObj->key)) {
// Write key to disk
file_put_contents($account_key_file, (string)base64_decode((string)$acctObj->key));
chmod($account_key_file, 0600);
} else {
// Do not generate new key if a revocation was requested.
if ($options["a"] == "revoke") {
log_error("AcmeClient: account key not found, but a revocation was requested");
return(1);
}
// Let acme client generate a new account key
$acmecmd = "/usr/local/sbin/acme.sh "
. implode(" ", $acme_args) . " "
. "--createAccountKey "
. "--accountkeylength 4096 "
. "--home /var/etc/acme-client/home "
. "--accountconf " . $account_conf_file;
$result = mwexec($acmecmd);
// Check exit code
if (!($result)) {
// created a new account key
} else {
log_error("AcmeClient: failed to create a new account key");
return(1);
}
// Read account key
$account_key_content = @file_get_contents($account_key_file);
if ($account_key_content == false) {
log_error("AcmeClient: unable to read account key from file");
return(1);
}
// Import account key into config
$acctObj->key = base64_encode($account_key_content);
// serialize to config and save
$modelObj->serializeToConfig();
Config::getInstance()->save();
Config::getInstance()->forceReload();
}
}
// Check if account was already registered
if (!empty((string)$acctObj->lastUpdate)) {
// account key already registered
} else {
// Do not register new account if a revocation was requested.
if ($options["a"] == "revoke") {
log_error("AcmeClient: account not registered, but a revocation was requested");
return(1);
}
// Run acme client to register the account
$acmecmd = "/usr/local/sbin/acme.sh "
. implode(" ", $acme_args) . " "
. "--registeraccount "
. "--home /var/etc/acme-client/home "
. "--accountconf " . $account_conf_file;
$result = mwexec($acmecmd);
// Check exit code
if (!($result)) {
// registered a new account key
} else {
log_error("AcmeClient: failed to register a new account key");
return(1);
}
// Set update/create time in config
$acctObj->lastUpdate = time();
// serialize to config and save
$modelObj->serializeToConfig();
Config::getInstance()->save();
Config::getInstance()->forceReload();
}
return;
}
// Run acme client with HTTP-01 or DNS-01 validation to issue/renew certificate
function run_acme_validation($certObj, $valObj, $acctObj)
{
global $options;
// Required to run pre-defined commands.
$backend = new Backend();
$modelObj = new OPNsense\AcmeClient\AcmeClient();
// Collect account information
$acme_env = (string)$modelObj->settings->environment;
$account_conf_dir = "/var/etc/acme-client/accounts/" . $acctObj->id . "_${acme_env}";
$account_conf_file = $account_conf_dir . "/account.conf";
// Generate certificate filenames
$cert_id = (string)$certObj->id;
$cert_filename = "/var/etc/acme-client/certs/${cert_id}/cert.pem";
$cert_chain_filename = "/var/etc/acme-client/certs/${cert_id}/chain.pem";
$cert_fullchain_filename = "/var/etc/acme-client/certs/${cert_id}/fullchain.pem";
$key_filename = "/var/etc/acme-client/keys/${cert_id}/private.key";
// Setup our own ACME environment
$certdir = "/var/etc/acme-client/certs/${cert_id}";
$keydir = "/var/etc/acme-client/keys/${cert_id}";
$configdir = "/var/etc/acme-client/configs/${cert_id}";
foreach (array($certdir, $keydir, $configdir) as $dir) {
if (!is_dir($dir)) {
mkdir($dir, 0700, true);
}
}
// Preparation to run acme client
$acme_args = eval_optional_acme_args();
$proc_env = array(); // env variables for proc_open()
$proc_env['PATH'] = '/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/sbin:/usr/local/bin';
$proc_desc = array( // descriptor array for proc_open()
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$proc_pipes = array();
// Do we need to issue or renew the certificate?
if (!empty((string)$certObj->lastUpdate) and !isset($options["F"])) {
$acme_action = "renew";
} else {
// Default: Issue a new certificate.
// If "-F" is specified, forcefully re-issue the cert, no matter if it's required.
// NOTE: This is useful if altNames were changed or when switching
// from acme staging to acme production servers.
$acme_action = "issue";
}
// Calculate next renewal date
$last_update = !empty((string)$certObj->lastUpdate) ? (string)$certObj->lastUpdate : 0;
$renew_cert = false;
$current_time = new \DateTime();
$last_update_time = new \DateTime();
$last_update_time->setTimestamp($last_update);
$renew_interval = (string)$certObj->renewInterval;
$next_update = $last_update_time->add(new \DateInterval('P' . $renew_interval . 'D'));
// Check if it's time to renew the cert.
if (isset($options["F"]) or ($current_time >= $next_update)) {
$renew_cert = true;
} else {
// Renewal not yet required, report special code
return(99);
}
// Try HTTP-01 or DNS-01 validation?
$val_method = (string)$valObj->method;
$acme_validation = ""; // val.method as argument for acme.sh
$acme_hook_options = array(); // store addition arguments for acme.sh here
switch ($val_method) {
case 'http01':
$acme_validation = "--webroot /var/etc/acme-client/challenges ";
break;
case 'dns01':
$acme_validation = "--dns " . (string)$valObj->dns_service . " ";
break;
default:
log_error("AcmeClient: invalid validation method specified: " . (string)$valObj->method);
return(1);
}
// HTTP-01: setup OPNsense internal port forward
if (($val_method == 'http01') and ((string)$valObj->http_service == 'opnsense')) {
// Get configured HTTP port for local lighttpd server
$configObj = Config::getInstance()->object();
$local_http_port = $configObj->OPNsense->AcmeClient->settings->challengePort;
// Collect all IP addresses here, automatic port forward will be applied for each IP
$iplist = array();
// Add IP addresses from auto-discovery feature
if ($valObj->http_opn_autodiscovery == 1) {
$dnslist = explode(',', $certObj->altNames);
$dnslist[] = $certObj->name;
foreach ($dnslist as $fqdn) {
// NOTE: This may take some time.
$ip_found = gethostbyname("${fqdn}.");
if (!empty($ip_found)) {
$iplist[] = (string)$ip_found;
}
}
}
// Add IP addresses from user input
$additional_ip = (string)$valObj->http_opn_ipaddresses;
if (!empty($additional_ip)) {
foreach (explode(',', $additional_ip) as $ip) {
$iplist[] = $ip;
}
}
// Add IP address from chosen interface
if (!empty((string)$valObj->http_opn_interface)) {
$interface_ip = get_interface_ip((string)$valObj->http_opn_interface);
if (!empty($interface_ip)) {
$iplist[] = $interface_ip;
}
}
// Check wether IPv6 support is enabled
$configObj = Config::getInstance()->object();
if (isset($configObj->system->ipv6allow) && ($configObj->system->ipv6allow == "1")) {
$_ipv6_enabled = true;
} else {
$_ipv6_enabled = false;
}
// Generate rules for all IP addresses
$anchor_rules = "";
if (!empty($iplist)) {
$dedup_iplist = array_unique($iplist);
// Add one rule for every IP
foreach ($dedup_iplist as $ip) {
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
// IPv4
$_dst = '127.0.0.1';
$_family = 'inet';
log_error("AcmeClient: using IPv4 address: ${ip}");
} elseif (($_ipv6_enabled == true) && (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) {
// IPv6
$_dst = 'fe80::1';
$_family = 'inet6';
log_error("AcmeClient: using IPv6 address: ${ip}");
} else {
continue; // skip broken entries
}
$anchor_rules .= "rdr pass ${_family} proto tcp from any to ${ip} port 80 -> ${_dst} port ${local_http_port}\n";
}
} else {
log_error("AcmeClient: no IP addresses found to setup port forward");
return(1);
}
// Abort if no rules were generated
if (empty($anchor_rules)) {
log_error("AcmeClient: unable to setup a port forward (empty ruleset)");
return(1);
}
// Create temporary port forward to allow acme challenges to get through
$anchor_setup = "rdr-anchor \"acme-client\"\n";
file_put_contents("${configdir}/acme_anchor_setup", $anchor_setup);
chmod("${configdir}/acme_anchor_setup", 0600);
mwexec("/sbin/pfctl -f ${configdir}/acme_anchor_setup");
file_put_contents("${configdir}/acme_anchor_rules", $anchor_rules);
chmod("${configdir}/acme_anchor_rules", 0600);
mwexec("/sbin/pfctl -a acme-client -f ${configdir}/acme_anchor_rules");
}
// Prepare DNS-01 hooks
if ($val_method == 'dns01') {
// Some common stuff
$val_id = preg_replace("/[^a-zA-Z0-9]/", "", (string)$valObj->id);
$secret_key_filename = "${configdir}/secret.key";
$acme_args[] = '--dnssleep ' . $valObj->dns_sleep;
// Setup DNS hook:
// Set required env variables, write secrets to files, etc.
switch ((string)$valObj->dns_service) {
case 'dns_acmedns':
$proc_env['ACMEDNS_USERNAME'] = (string)$valObj->dns_acmedns_user;
$proc_env['ACMEDNS_PASSWORD'] = (string)$valObj->dns_acmedns_password;
$proc_env['ACMEDNS_SUBDOMAIN'] = (string)$valObj->dns_acmedns_subdomain;
$proc_env['ACMEDNS_UPDATE_URL'] = (string)$valObj->dns_acmedns_updateurl;
break;
case 'dns_ad':
$proc_env['AD_API_KEY'] = (string)$valObj->dns_ad_key;
break;
case 'dns_ali':
$proc_env['Ali_Key'] = (string)$valObj->dns_ali_key;
$proc_env['Ali_Secret'] = (string)$valObj->dns_ali_secret;
break;
case 'dns_autodns':
$proc_env['AUTODNS_USER'] = (string)$valObj->dns_autodns_user;
$proc_env['AUTODNS_PASSWORD'] = (string)$valObj->dns_autodns_password;
$proc_env['AUTODNS_CONTEXT'] = (string)$valObj->dns_autodns_context;
break;
case 'dns_aws':
$proc_env['AWS_ACCESS_KEY_ID'] = (string)$valObj->dns_aws_id;
$proc_env['AWS_SECRET_ACCESS_KEY'] = (string)$valObj->dns_aws_secret;
break;
case 'dns_azure':
$proc_env['AZUREDNS_SUBSCRIPTIONID'] = (string)$valObj->dns_azuredns_subscriptionid;
$proc_env['AZUREDNS_TENANTID'] = (string)$valObj->dns_azuredns_tenantid;
$proc_env['AZUREDNS_APPID'] = (string)$valObj->dns_azuredns_appid;
$proc_env['AZUREDNS_CLIENTSECRET'] = (string)$valObj->dns_azuredns_clientsecret;
break;
case 'dns_cf':
// Global API key (insecure)
$proc_env['CF_Key'] = (string)$valObj->dns_cf_key;
$proc_env['CF_Email'] = (string)$valObj->dns_cf_email;
// Restricted API token (recommended)
$proc_env['CF_Token'] = (string)$valObj->dns_cf_token;
$proc_env['CF_Account_ID'] = (string)$valObj->dns_cf_account_id;
break;
case 'dns_cloudns':
$proc_env['CLOUDNS_AUTH_ID'] = (string)$valObj->dns_cloudns_auth_id;
$proc_env['CLOUDNS_SUB_AUTH_ID'] = (string)$valObj->dns_cloudns_sub_auth_id;
$proc_env['CLOUDNS_AUTH_PASSWORD'] = (string)$valObj->dns_cloudns_auth_password;
break;
case 'dns_cx':
$proc_env['CX_Key'] = (string)$valObj->dns_cx_key;
$proc_env['CX_Secret'] = (string)$valObj->dns_cx_secret;
break;
case 'dns_cyon':
$proc_env['CY_Username'] = (string)$valObj->dns_cyon_user;
$proc_env['CY_Password'] = (string)$valObj->dns_cyon_user;
break;
case 'dns_da':
$proc_env['DA_Api'] = (string)$valObj->dns_da_key;
$proc_env['DA_Api_Insecure'] = (string)$valObj->dns_da_insecure;
break;
case 'dns_dgon':
$proc_env['DO_API_KEY'] = (string)$valObj->dns_dgon_key;
break;
case 'dns_dnsimple':
$proc_env['DNSimple_OAUTH_TOKEN'] = (string)$valObj->dns_dnsimple_token;
break;
case 'dns_do':
$proc_env['DO_PID'] = (string)$valObj->dns_do_pid;
$proc_env['DO_PW'] = (string)$valObj->dns_do_password;
break;
case 'dns_doapi':
$proc_env['DO_LETOKEN'] = (string)$valObj->dns_doapi_token;
break;
case 'dns_dp':
$proc_env['DP_Id'] = (string)$valObj->dns_dp_id;
$proc_env['DP_Key'] = (string)$valObj->dns_dp_key;
break;
case 'dns_dreamhost':
$proc_env['DH_API_KEY'] = (string)$valObj->dns_dh_key;
break;
case 'dns_duckdns':
$proc_env['DuckDNS_Token'] = (string)$valObj->dns_duckdns_token;
break;
case 'dns_dyn':
$proc_env['DYN_Customer'] = (string)$valObj->dns_dyn_customer;
$proc_env['DYN_Username'] = (string)$valObj->dns_dyn_user;
$proc_env['DYN_Password'] = (string)$valObj->dns_dyn_password;
break;
case 'dns_dynu':
$proc_env['Dynu_ClientId'] = (string)$valObj->dns_dynu_clientid;
$proc_env['Dynu_Secret'] = (string)$valObj->dns_dynu_secret;
break;
case 'dns_freedns':
$proc_env['FREEDNS_User'] = (string)$valObj->dns_freedns_user;
$proc_env['FREEDNS_Password'] = (string)$valObj->dns_freedns_password;
break;
case 'dns_gandi_livedns':
$proc_env['GANDI_LIVEDNS_KEY'] = (string)$valObj->dns_gandi_livedns_key;
break;
case 'dns_gcloud':
# Google Cloud SDK must be installed.
if ((string)$modelObj->isPluginInstalled('google-cloud-sdk') != "1") {
log_error("AcmeClient: Google Cloud SDK plugin is NOT installed. Please install os-google-cloud-sdk.");
return(1);
}
# We need a valid Google Cloud JSON key.
if (!empty((string)$valObj->dns_gcloud_key)) {
# Extract the gcloud project from the key data.
$_gcloud_data = json_decode((string)$valObj->dns_gcloud_key);
$gcloud_project = $_gcloud_data->project_id;
$gcloud_account = $_gcloud_data->client_email;
if (empty($gcloud_project)) {
log_error("AcmeClient: unable to extract project name from Google Cloud DNS JSON key");
return(1);
} else {
log_error("AcmeClient: Google Cloud DNS project name: ${gcloud_project}");
}
} else {
log_error("AcmeClient: no key for Google Cloud DNS was specified");
return(1);
}
# Preparations for gcloud CLI.
$gcloud_config = "acme-${val_id}";
$gcloud_key_file = "/tmp/acme_" . (string)$valObj->dns_service . "_${val_id}.json";
file_put_contents($gcloud_key_file, (string)$valObj->dns_gcloud_key);
chmod($gcloud_key_file, 0600);
$proc_env['CLOUDSDK_ACTIVE_CONFIG_NAME'] = $gcloud_config;
$proc_env['CLOUDSDK_CORE_PROJECT'] = $gcloud_project;
# Ensure that a working gcloud config exists.
run_shell_command("/usr/local/bin/gcloud config configurations create ${gcloud_config}", $proc_env);
run_shell_command("/usr/local/bin/gcloud config configurations activate ${gcloud_config}", $proc_env);
run_shell_command("/usr/local/bin/gcloud auth activate-service-account --key-file=${gcloud_key_file}", $proc_env);
run_shell_command("/usr/local/bin/gcloud config set account ${gcloud_account}", $proc_env);
run_shell_command("/usr/local/bin/gcloud config set project ${gcloud_project}", $proc_env);
break;
case 'dns_gd':
$proc_env['GD_Key'] = (string)$valObj->dns_gd_key;
$proc_env['GD_Secret'] = (string)$valObj->dns_gd_secret;
break;
case 'dns_gdnsdk':
$proc_env['GDNSDK_Username'] = (string)$valObj->dns_gdnsdk_user;
$proc_env['GDNSDK_Password'] = (string)$valObj->dns_gdnsdk_password;
break;
case 'dns_hostingde':
$proc_env['HOSTINGDE_ENDPOINT'] = (string)$valObj->dns_hostingde_server;
$proc_env['HOSTINGDE_APIKEY'] = (string)$valObj->dns_hostingde_apiKey;
break;
case 'dns_he':
$proc_env['HE_Username'] = (string)$valObj->dns_he_user;
$proc_env['HE_Password'] = (string)$valObj->dns_he_password;
break;
case 'dns_infoblox':
$proc_env['Infoblox_Creds'] = (string)$valObj->dns_infoblox_credentials;
$proc_env['Infoblox_Server'] = (string)$valObj->dns_infoblox_server;
break;
case 'dns_inwx':
$proc_env['INWX_User'] = (string)$valObj->dns_inwx_user;
$proc_env['INWX_Password'] = (string)$valObj->dns_inws_password;
break;
case 'dns_ispconfig':
$proc_env['ISPC_User'] = (string)$valObj->dns_ispconfig_user;
$proc_env['ISPC_Password'] = (string)$valObj->dns_ispconfig_password;
$proc_env['ISPC_Api'] = (string)$valObj->dns_ispconfig_api;
$proc_env['ISPC_Api_Insecure'] = (string)$valObj->dns_ispconfig_insecure;
break;
case 'dns_kinghost':
$proc_env['KINGHOST_username'] = (string)$valObj->dns_kinghost_username;
$proc_env['KINGHOST_Password'] = (string)$valObj->dns_kinghost_password;
break;
case 'dns_knot':
$proc_env['KNOT_SERVER'] = (string)$valObj->dns_knot_server;
$proc_env['KNOT_KEY'] = (string)$valObj->dns_knot_key;
break;
case 'dns_lexicon':
$proc_env['PROVIDER'] = (string)$valObj->dns_lexicon_provider;
$proc_env['LEXICON_' . strtoupper($proc_env['PROVIDER']) . '_USERNAME'] = (string)$valObj->dns_lexicon_user;
$proc_env['LEXICON_' . strtoupper($proc_env['PROVIDER']) . '_TOKEN'] = (string)$valObj->dns_lexicon_token;
if ((string)$valObj->dns_lexicon_provider == 'namesilo') {
// Namesilo applies changes to DNS records only every 15 minutes.
$acme_hook_options[] = "--dnssleep 960";
}
break;
case 'dns_linode':
$proc_env['LINODE_API_KEY'] = (string)$valObj->dns_linode_key;
// Linode can take up to 15 to update DNS records
$acme_hook_options[] = "--dnssleep 960";
break;
case 'dns_loopia':
$proc_env['LOOPIA_Api'] = (string)$valObj->dns_loopia_api;
$proc_env['LOOPIA_User'] = (string)$valObj->dns_loopia_user;
$proc_env['LOOPIA_Password'] = (string)$valObj->dns_loopia_password;
break;
case 'dns_lua':
$proc_env['LUA_Key'] = (string)$valObj->dns_lua_key;
$proc_env['LUA_Email'] = (string)$valObj->dns_lua_email;
break;
case 'dns_me':
$proc_env['ME_Key'] = (string)$valObj->dns_me_key;
$proc_env['ME_Secret'] = (string)$valObj->dns_me_secret;
break;
case 'dns_miab':
$proc_env['MIAB_Username'] = (string)$valObj->dns_miab_user;
$proc_env['MIAB_Password'] = (string)$valObj->dns_miab_password;
$proc_env['MIAB_Server'] = (string)$valObj->dns_miab_server;
break;
case 'dns_namecheap':
$proc_env['NAMECHEAP_USERNAME'] = (string)$valObj->dns_namecheap_user;
$proc_env['NAMECHEAP_API_KEY'] = (string)$valObj->dns_namecheap_api;
if (!empty((string)$valObj->dns_namecheap_sourceip)) {
$proc_env['NAMECHEAP_SOURCEIP'] = (string)$valObj->dns_namecheap_sourceip;
} else {
// Use a public service to get our source IP for Namecheap API
$proc_env['NAMECHEAP_SOURCEIP'] = 'https://ifconfig.co/ip';
}
break;
case 'dns_namecom':
$proc_env['Namecom_Username'] = (string)$valObj->dns_namecom_user;
$proc_env['Namecom_Token'] = (string)$valObj->dns_namecom_token;
break;
case 'dns_namesilo':
$proc_env['Namesilo_Key'] = (string)$valObj->dns_namesilo_key;
// Namesilo applies changes to DNS records only every 15 minutes.
$acme_hook_options[] = "--dnssleep 960";
break;
case 'dns_netcup':
$proc_env['NC_CID'] = (string)$valObj->dns_netcup_cid;
$proc_env['NC_Apikey'] = (string)$valObj->dns_netcup_key;
$proc_env['NC_Apipw'] = (string)$valObj->dns_netcup_pw;
// netcup applies changes to DNS records only every 10 minutes.
$acme_hook_options[] = "--dnssleep 600";
break;
case 'dns_nsone':
$proc_env['NS1_Key'] = (string)$valObj->dns_nsone_key;
break;
case 'dns_nsupdate':
// Write secret key to filesystem
$secret_key_data = (string)$valObj->dns_nsupdate_key . "\n";
file_put_contents($secret_key_filename, $secret_key_data);
$proc_env['NSUPDATE_KEY'] = $secret_key_filename;
$proc_env['NSUPDATE_SERVER'] = (string)$valObj->dns_nsupdate_server;
break;
case 'dns_opnsense':
# BIND plugin must be installed.
if ((string)$modelObj->isPluginInstalled('bind') != "1") {
log_error("AcmeClient: BIND plugin is NOT installed. Please install os-bind.");
return(1);
}
$proc_env['OPNs_Host'] = (string)$valObj->dns_opnsense_host;
$proc_env['OPNs_Port'] = (string)$valObj->dns_opnsense_port;
$proc_env['OPNs_Key'] = (string)$valObj->dns_opnsense_key;
$proc_env['OPNs_Token'] = (string)$valObj->dns_opnsense_token;
$proc_env['OPNs_Api_Insecure'] = (string)$valObj->dns_opnsense_insecure;
break;
case 'dns_ovh':
$proc_env['OVH_AK'] = (string)$valObj->dns_ovh_app_key;
$proc_env['OVH_AS'] = (string)$valObj->dns_ovh_app_secret;
$proc_env['OVH_CK'] = (string)$valObj->dns_ovh_consumer_key;
$proc_env['OVH_END_POINT'] = (string)$valObj->dns_ovh_endpoint;
break;
case 'dns_pdns':
$proc_env['PDNS_Url'] = (string)$valObj->dns_pdns_url;
$proc_env['PDNS_ServerId'] = (string)$valObj->dns_pdns_serverid;
$proc_env['PDNS_Token'] = (string)$valObj->dns_pdns_token;
break;
case 'dns_pleskxml':
$proc_env['pleskxml_user'] = (string)$valObj->dns_pleskxml_user;
$proc_env['pleskxml_pass'] = (string)$valObj->dns_pleskxml_pass;
$proc_env['pleskxml_uri'] = (string)$valObj->dns_pleskxml_uri;
break;
case 'dns_selectel':
$proc_env['SL_Key'] = (string)$valObj->dns_sl_key;
break;
case 'dns_servercow':
$proc_env['SERVERCOW_API_Username'] = (string)$valObj->dns_servercow_username;
$proc_env['SERVERCOW_API_Password'] = (string)$valObj->dns_servercow_password;
break;
case 'dns_unoeuro':
$proc_env['UNO_Key'] = (string)$valObj->dns_uno_key;
$proc_env['UNO_User'] = (string)$valObj->dns_uno_user;
break;
case 'dns_variomedia':
$proc_env['VARIOMEDIA_API_TOKEN'] = (string)$valObj->dns_variomedia_key;
break;
case 'dns_vscale':
$proc_env['VSCALE_API_KEY'] = (string)$valObj->dns_vscale_key;
break;
case 'dns_yandex':
$proc_env['PDD_Token'] = (string)$valObj->dns_yandex_token;
break;
case 'dns_zilore':
$proc_env['Zilore_Key'] = (string)$valObj->dns_zilore_key;
break;
case 'dns_zonomi':
$proc_env['ZM_Key'] = (string)$valObj->dns_zm_key;
break;
default:
log_error("AcmeClient: invalid DNS-01 service specified: " . (string)$valObj->dns_service);
return(1);
}
}
// Prepare altNames
$altnames = "";
// Main domain: Use DNS alias mode for domain validation?
// https://github.com/Neilpang/acme.sh/wiki/DNS-alias-mode
if ($val_method == 'dns01') {
switch ((string)$certObj->aliasmode) {
case 'automatic':
$name = "_acme-challenge." . ltrim((string)$certObj->name, '*.');
if ($dst = dns_get_record($name, DNS_CNAME)) {
$altnames .= "--domain-alias " . $dst[0]['target'] . " ";
}
break;
case 'domain':
$altnames .= "--domain-alias " . (string)$certObj->domainalias . " ";
break;
case 'challenge':
$altnames .= "--challenge-alias " . (string)$certObj->challengealias . " ";
break;
}
}
if (!empty((string)$certObj->altNames)) {
$_altnames = explode(",", (string)$certObj->altNames);
foreach (explode(",", (string)$certObj->altNames) as $altname) {
$altnames .= "--domain ${altname} ";
// altNames: Use DNS alias mode for domain validation?
// https://github.com/Neilpang/acme.sh/wiki/DNS-alias-mode
if ($val_method == 'dns01') {
switch ((string)$certObj->aliasmode) {
case 'automatic':
$name = "_acme-challenge." . ltrim($altname, '*.');
if ($dst = dns_get_record($name, DNS_CNAME)) {
$altnames .= "--domain-alias " . $dst[0]['target'] . " ";
}
break;
case 'domain':
$altnames .= "--domain-alias " . (string)$certObj->domainalias . " ";
break;
case 'challenge':
$altnames .= "--challenge-alias " . (string)$certObj->challengealias . " ";
break;
}
}
}
}
// Teach acme.sh about DNS API hook location
$proc_env['_SCRIPT_HOME'] = '/usr/local/share/examples/acme.sh';
// Get the chosen key length from xml and trim the parameter before passing to acme client
$key_length = (string) $certObj->keyLength;
$key_length = substr($key_length, 4);
if ($key_length == 'ec256' || $key_length == 'ec384') {
if ($acme_action == "renew") {