1 package PMG
::API2
::Certificates
;
7 use PVE
::Exception
qw(raise raise_param_exc);
8 use PVE
::JSONSchema
qw(get_standard_option);
9 use PVE
::Tools
qw(extract_param file_get_contents file_set_contents);
15 use PMG
::API2
::ACMEPlugin
;
17 use base
qw(PVE::RESTHandler);
19 my $acme_account_dir = PMG
::CertHelpers
::acme_account_dir
();
21 sub first_typed_pem_entry
: prototype($$) {
22 my ($label, $data) = @_;
24 if ($data =~ /^(-----BEGIN \Q$label\E-----\n.*?\n-----END \Q$label\E-----)$/ms) {
30 sub pem_private_key
: prototype($) {
32 return first_typed_pem_entry
('PRIVATE KEY', $data);
35 sub pem_certificate
: prototype($) {
37 return first_typed_pem_entry
('CERTIFICATE', $data);
40 my sub restart_after_cert_update
: prototype($) {
44 print "Restarting pmgproxy\n";
45 PVE
::Tools
::run_command
(['systemctl', 'reload-or-restart', 'pmgproxy']);
49 my sub update_cert
: prototype($$$$$) {
50 my ($type, $cert_path, $certificate, $force, $restart) = @_;
52 print "Setting custom certificate file $cert_path\n";
53 PMG
::CertHelpers
::set_cert_file
($certificate, $cert_path, $force);
55 restart_after_cert_update
($type) if $restart;
57 PMG
::CertHelpers
::cert_lock
(10, $code);
60 my sub set_smtp
: prototype($$) {
61 my ($on, $reload) = @_;
64 my $cfg = PMG
::Config-
>new();
65 if (!$cfg->get('mail', 'tls') == !$on) {
69 print "Rewriting postfix config\n";
70 $cfg->set('mail', 'tls', $on);
72 my $changed = $cfg->rewrite_config_postfix();
74 if ($changed && $reload) {
75 print "Reloading postfix\n";
76 PMG
::Utils
::service_cmd
('postfix', 'reload');
79 PMG
::Config
::lock_config
($code, "failed to reload postfix");
82 __PACKAGE__-
>register_method ({
86 permissions
=> { user
=> 'all' },
87 description
=> "Node index.",
89 additionalProperties
=> 0,
91 node
=> get_standard_option
('pve-node'),
100 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
107 { name
=> 'custom' },
109 { name
=> 'config' },
114 __PACKAGE__-
>register_method ({
118 permissions
=> { user
=> 'all' },
121 description
=> "Get information about the node's certificates.",
123 additionalProperties
=> 0,
125 node
=> get_standard_option
('pve-node'),
130 items
=> get_standard_option
('pve-certificate-info'),
136 for my $path (&PMG
::CertHelpers
::API_CERT
, &PMG
::CertHelpers
::SMTP_CERT
) {
138 my $info = PVE
::Certificate
::get_certificate_info
($path);
139 push @$res, $info if $info;
146 __PACKAGE__-
>register_method ({
147 name
=> 'custom_cert_index',
150 permissions
=> { user
=> 'all' },
151 description
=> "Certificate index.",
153 additionalProperties
=> 0,
155 node
=> get_standard_option
('pve-node'),
164 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
176 __PACKAGE__-
>register_method ({
177 name
=> 'upload_custom_cert',
178 path
=> 'custom/{type}',
180 permissions
=> { check
=> [ 'admin' ] },
181 description
=> 'Upload or update custom certificate chain and key.',
185 additionalProperties
=> 0,
187 node
=> get_standard_option
('pve-node'),
190 format
=> 'pem-certificate-chain',
191 description
=> 'PEM encoded certificate (chain).',
195 description
=> 'PEM encoded private key.',
196 format
=> 'pem-string',
199 type
=> get_standard_option
('pmg-certificate-type'),
202 description
=> 'Overwrite existing custom or ACME certificate files.',
208 description
=> 'Restart services.',
214 returns
=> get_standard_option
('pve-certificate-info'),
218 my $type = extract_param
($param, 'type'); # also used to know which service to restart
219 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
221 my $certs = extract_param
($param, 'certificates');
222 $certs = PVE
::Certificate
::strip_leading_text
($certs);
224 my $key = extract_param
($param, 'key');
226 $key = PVE
::Certificate
::strip_leading_text
($key);
227 $certs = "$key\n$certs";
229 my $private_key = pem_private_key
($certs);
230 if (!defined($private_key)) {
231 my $old = file_get_contents
($cert_path);
232 $private_key = pem_private_key
($old);
233 if (!defined($private_key)) {
235 'key' => "Attempted to upload custom certificate without (existing) key."
239 # copy the old certificate's key:
240 $certs = "$key\n$certs";
246 PMG
::CertHelpers
::cert_lock
(10, sub {
247 update_cert
($type, $cert_path, $certs, $param->{force
}, $param->{restart
});
250 if ($type eq 'smtp') {
251 set_smtp
(1, $param->{restart
});
257 __PACKAGE__-
>register_method ({
258 name
=> 'remove_custom_cert',
259 path
=> 'custom/{type}',
261 permissions
=> { check
=> [ 'admin' ] },
262 description
=> 'DELETE custom certificate chain and key.',
266 additionalProperties
=> 0,
268 node
=> get_standard_option
('pve-node'),
269 type
=> get_standard_option
('pmg-certificate-type'),
272 description
=> 'Restart pmgproxy.',
284 my $type = extract_param
($param, 'type');
285 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
288 print "Deleting custom certificate files\n";
290 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
292 if ($param->{restart
}) {
293 restart_after_cert_update
($type);
297 PMG
::CertHelpers
::cert_lock
(10, $code);
299 if ($type eq 'smtp') {
300 set_smtp
(0, $param->{restart
});
306 __PACKAGE__-
>register_method ({
307 name
=> 'acme_cert_index',
310 permissions
=> { user
=> 'all' },
311 description
=> "ACME Certificate index.",
313 additionalProperties
=> 0,
315 node
=> get_standard_option
('pve-node'),
324 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
336 my $order_certificate = sub {
337 my ($acme, $acme_node_config) = @_;
339 my $plugins = PMG
::API2
::ACMEPlugin
::load_config
();
341 print "Placing ACME order\n";
342 my ($order_url, $order) = $acme->new_order([ sort keys %{$acme_node_config->{domains
}} ]);
343 print "Order URL: $order_url\n";
344 for my $auth_url (@{$order->{authorizations
}}) {
345 print "\nGetting authorization details from '$auth_url'\n";
346 my $auth = $acme->get_authorization($auth_url);
348 # force lower case, like get_acme_conf does
349 my $domain = lc($auth->{identifier
}->{value
});
350 if ($auth->{status
} eq 'valid') {
351 print "$domain is already validated!\n";
353 print "The validation for $domain is pending!\n";
355 my $domain_config = $acme_node_config->{domains
}->{$domain};
356 die "no config for domain '$domain'\n" if !$domain_config;
358 my $plugin_id = $domain_config->{plugin
};
360 my $plugin_cfg = $plugins->{ids
}->{$plugin_id};
361 die "plugin '$plugin_id' for domain '$domain' not found!\n"
365 plugin
=> $plugin_cfg,
366 alias
=> $domain_config->{alias
},
369 my $plugin = PVE
::ACME
::Challenge-
>lookup($plugin_cfg->{type
});
370 $plugin->setup($acme, $auth, $data);
372 print "Triggering validation\n";
374 die "no validation URL returned by plugin '$plugin_id' for domain '$domain'\n"
375 if !defined($data->{url
});
377 $acme->request_challenge_validation($data->{url
});
378 print "Sleeping for 5 seconds\n";
381 $auth = $acme->get_authorization($auth_url);
382 if ($auth->{status
} eq 'pending') {
383 print "Status is still 'pending', trying again in 10 seconds\n";
386 } elsif ($auth->{status
} eq 'valid') {
387 print "Status is 'valid', domain '$domain' OK!\n";
390 my $error = "validating challenge '$auth_url' failed - status: $auth->{status}";
391 for (@{$auth->{challenges
}}) {
392 $error .= ", $_->{error}->{detail}" if $_->{error
}->{detail
};
398 eval { $plugin->teardown($acme, $auth, $data) };
403 print "\nAll domains validated!\n";
404 print "\nCreating CSR\n";
405 # Currently we only support dns entries, so extract those from the order:
411 } $order->{identifiers
}->@*
413 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
414 my ($csr_der, $key) = PMG
::RS
::CSR
::generate_csr
($san, {});
416 my $finalize_error_cnt = 0;
417 print "Checking order status\n";
419 $order = $acme->get_order($order_url);
420 if ($order->{status
} eq 'pending') {
421 print "still pending, trying to finalize order\n";
423 # to be compatible with and without the order ready state we try to
424 # finalize even at the 'pending' state and give up after 5
425 # unsuccessful tries this can be removed when the letsencrypt api
426 # definitely has implemented the 'ready' state
428 $acme->finalize_order($order->{finalize
}, $csr_der);
431 die $err if $finalize_error_cnt >= 5;
433 $finalize_error_cnt++;
438 } elsif ($order->{status
} eq 'ready') {
439 print "Order is ready, finalizing order\n";
440 $acme->finalize_order($order->{finalize
}, $csr_der);
443 } elsif ($order->{status
} eq 'processing') {
444 print "still processing, trying again in 30 seconds\n";
447 } elsif ($order->{status
} eq 'valid') {
451 die "order status: $order->{status}\n";
454 print "\nDownloading certificate\n";
455 my $cert = $acme->get_certificate($order->{certificate
});
457 return ($cert, $key);
460 # Filter domains and raise an error if the list becomes empty.
461 my $filter_domains = sub {
462 my ($acme_config, $type) = @_;
464 my $domains = $acme_config->{domains
};
465 foreach my $domain (sort keys %$domains) {
466 my $entry = $domains->{$domain};
467 if (!(grep { $_ eq $type } PVE
::Tools
::split_list
($entry->{usage
}))) {
468 delete $domains->{$domain};
473 raise
("No domains configured for type '$type'\n", 400);
477 __PACKAGE__-
>register_method ({
478 name
=> 'new_acme_cert',
479 path
=> 'acme/{type}',
481 permissions
=> { check
=> [ 'admin' ] },
482 description
=> 'Order a new certificate from ACME-compatible CA.',
486 additionalProperties
=> 0,
488 node
=> get_standard_option
('pve-node'),
489 type
=> get_standard_option
('pmg-certificate-type'),
492 description
=> 'Overwrite existing custom certificate.',
504 my $type = extract_param
($param, 'type'); # also used to know which service to restart
505 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
506 raise_param_exc
({'force' => "Custom certificate exists but 'force' is not set."})
507 if !$param->{force
} && -e
$cert_path;
509 my $node_config = PMG
::NodeConfig
::load_config
();
510 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
511 raise
("ACME domain list in configuration is missing!", 400)
512 if !($acme_config && $acme_config->{domains
} && $acme_config->{domains
}->%*);
514 $filter_domains->($acme_config, $type);
516 my $rpcenv = PMG
::RESTEnvironment-
>get();
517 my $authuser = $rpcenv->get_user();
520 STDOUT-
>autoflush(1);
521 my $account = $acme_config->{account
};
522 my $account_file = "${acme_account_dir}/${account}";
523 die "ACME account config file '$account' does not exist.\n"
524 if ! -e
$account_file;
526 print "Loading ACME account details\n";
527 my $acme = PMG
::RS
::Acme-
>load($account_file);
529 my ($cert, $key) = $order_certificate->($acme, $acme_config);
530 my $certificate = "$key\n$cert";
532 update_cert
($type, $cert_path, $certificate, $param->{force
}, 1);
534 if ($type eq 'smtp') {
541 return $rpcenv->fork_worker("acmenewcert", undef, $authuser, $realcmd);
544 __PACKAGE__-
>register_method ({
545 name
=> 'renew_acme_cert',
546 path
=> 'acme/{type}',
548 permissions
=> { check
=> [ 'admin' ] },
549 description
=> "Renew existing certificate from CA.",
553 additionalProperties
=> 0,
555 node
=> get_standard_option
('pve-node'),
556 type
=> get_standard_option
('pmg-certificate-type'),
559 description
=> 'Force renewal even if expiry is more than 30 days away.',
571 my $type = extract_param
($param, 'type'); # also used to know which service to restart
572 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
574 raise
("No current (custom) certificate found, please order a new certificate!\n")
577 my $expires_soon = PVE
::Certificate
::check_expiry
($cert_path, time() + 30*24*60*60);
578 raise_param_exc
({'force' => "Certificate does not expire within the next 30 days, and 'force' is not set."})
579 if !$expires_soon && !$param->{force
};
581 my $node_config = PMG
::NodeConfig
::load_config
();
582 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
583 raise
("ACME domain list in configuration is missing!", 400)
584 if !$acme_config || !$acme_config->{domains
}->%*;
586 $filter_domains->($acme_config, $type);
588 my $rpcenv = PMG
::RESTEnvironment-
>get();
589 my $authuser = $rpcenv->get_user();
591 my $old_cert = PVE
::Tools
::file_get_contents
($cert_path);
594 STDOUT-
>autoflush(1);
595 my $account = $acme_config->{account
};
596 my $account_file = "${acme_account_dir}/${account}";
597 die "ACME account config file '$account' does not exist.\n"
598 if ! -e
$account_file;
600 print "Loading ACME account details\n";
601 my $acme = PMG
::RS
::Acme-
>load($account_file);
603 my ($cert, $key) = $order_certificate->($acme, $acme_config);
604 my $certificate = "$key\n$cert";
606 update_cert
($type, $cert_path, $certificate, 1, 1);
608 if (defined($old_cert)) {
609 print "Revoking old certificate\n";
610 eval { $acme->revoke_certificate($old_cert, undef) };
611 warn "Revoke request to CA failed: $@" if $@;
615 return $rpcenv->fork_worker("acmerenew", undef, $authuser, $realcmd);
618 __PACKAGE__-
>register_method ({
619 name
=> 'revoke_acme_cert',
620 path
=> 'acme/{type}',
622 permissions
=> { check
=> [ 'admin' ] },
623 description
=> "Revoke existing certificate from CA.",
627 additionalProperties
=> 0,
629 node
=> get_standard_option
('pve-node'),
630 type
=> get_standard_option
('pmg-certificate-type'),
639 my $type = extract_param
($param, 'type'); # also used to know which service to restart
640 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
642 my $node_config = PMG
::NodeConfig
::load_config
();
643 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
644 raise
("ACME domain list in configuration is missing!", 400)
645 if !$acme_config || !$acme_config->{domains
}->%*;
647 $filter_domains->($acme_config, $type);
649 my $rpcenv = PMG
::RESTEnvironment-
>get();
650 my $authuser = $rpcenv->get_user();
652 my $cert = PVE
::Tools
::file_get_contents
($cert_path);
653 $cert = pem_certificate
($cert)
654 or die "no certificate section found in '$cert_path'\n";
657 STDOUT-
>autoflush(1);
658 my $account = $acme_config->{account
};
659 my $account_file = "${acme_account_dir}/${account}";
660 die "ACME account config file '$account' does not exist.\n"
661 if ! -e
$account_file;
663 print "Loading ACME account details\n";
664 my $acme = PMG
::RS
::Acme-
>load($account_file);
666 print "Revoking old certificate\n";
667 eval { $acme->revoke_certificate($cert, undef) };
669 # is there a better check?
670 die "Revoke request to CA failed: $err" if $err !~ /"Certificate is expired"/;
674 print "Deleting certificate files\n";
676 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
678 restart_after_cert_update
($type);
681 PMG
::CertHelpers
::cert_lock
(10, $code);
683 if ($type eq 'smtp') {
688 return $rpcenv->fork_worker("acmerevoke", undef, $authuser, $realcmd);