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']);
47 my $cinfo = PMG
::ClusterConfig-
>new();
48 if (scalar(keys %{$cinfo->{ids
}})) {
49 print "Notify cluster about new fingerprint\n";
50 PMG
::Cluster
::trigger_update_fingerprints
($cinfo);
55 my sub update_cert
: prototype($$$$$) {
56 my ($type, $cert_path, $certificate, $force, $restart) = @_;
58 print "Setting custom certificate file $cert_path\n";
59 PMG
::CertHelpers
::set_cert_file
($certificate, $cert_path, $force);
61 restart_after_cert_update
($type) if $restart;
63 PMG
::CertHelpers
::cert_lock
(10, $code);
66 my sub set_smtp
: prototype($$) {
67 my ($on, $reload) = @_;
70 my $cfg = PMG
::Config-
>new();
71 if (!$cfg->get('mail', 'tls') == !$on) {
75 print "Rewriting postfix config\n";
76 $cfg->set('mail', 'tls', $on);
78 my $changed = $cfg->rewrite_config_postfix();
80 if ($changed && $reload) {
81 print "Reloading postfix\n";
82 PMG
::Utils
::service_cmd
('postfix', 'reload');
85 PMG
::Config
::lock_config
($code, "failed to reload postfix");
88 __PACKAGE__-
>register_method ({
92 permissions
=> { user
=> 'all' },
93 description
=> "Node index.",
95 additionalProperties
=> 0,
97 node
=> get_standard_option
('pve-node'),
106 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
113 { name
=> 'custom' },
115 { name
=> 'config' },
120 __PACKAGE__-
>register_method ({
124 permissions
=> { user
=> 'all' },
127 description
=> "Get information about the node's certificates.",
129 additionalProperties
=> 0,
131 node
=> get_standard_option
('pve-node'),
136 items
=> get_standard_option
('pve-certificate-info'),
142 for my $path (&PMG
::CertHelpers
::API_CERT
, &PMG
::CertHelpers
::SMTP_CERT
) {
144 my $info = PVE
::Certificate
::get_certificate_info
($path);
145 push @$res, $info if $info;
152 __PACKAGE__-
>register_method ({
153 name
=> 'custom_cert_index',
156 permissions
=> { user
=> 'all' },
157 description
=> "Certificate index.",
159 additionalProperties
=> 0,
161 node
=> get_standard_option
('pve-node'),
170 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
182 __PACKAGE__-
>register_method ({
183 name
=> 'upload_custom_cert',
184 path
=> 'custom/{type}',
186 permissions
=> { check
=> [ 'admin' ] },
187 description
=> 'Upload or update custom certificate chain and key.',
191 additionalProperties
=> 0,
193 node
=> get_standard_option
('pve-node'),
196 format
=> 'pem-certificate-chain',
197 description
=> 'PEM encoded certificate (chain).',
201 description
=> 'PEM encoded private key.',
202 format
=> 'pem-string',
205 type
=> get_standard_option
('pmg-certificate-type'),
208 description
=> 'Overwrite existing custom or ACME certificate files.',
214 description
=> 'Restart services.',
220 returns
=> get_standard_option
('pve-certificate-info'),
224 my $type = extract_param
($param, 'type'); # also used to know which service to restart
225 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
227 my $certs = extract_param
($param, 'certificates');
228 $certs = PVE
::Certificate
::strip_leading_text
($certs);
230 my $key = extract_param
($param, 'key');
232 $key = PVE
::Certificate
::strip_leading_text
($key);
233 $certs = "$key\n$certs";
235 my $private_key = pem_private_key
($certs);
236 if (!defined($private_key)) {
237 my $old = file_get_contents
($cert_path);
238 $private_key = pem_private_key
($old);
239 if (!defined($private_key)) {
241 'key' => "Attempted to upload custom certificate without (existing) key."
245 # copy the old certificate's key:
246 $certs = "$key\n$certs";
252 PMG
::CertHelpers
::cert_lock
(10, sub {
253 update_cert
($type, $cert_path, $certs, $param->{force
}, $param->{restart
});
256 if ($type eq 'smtp') {
257 set_smtp
(1, $param->{restart
});
263 __PACKAGE__-
>register_method ({
264 name
=> 'remove_custom_cert',
265 path
=> 'custom/{type}',
267 permissions
=> { check
=> [ 'admin' ] },
268 description
=> 'DELETE custom certificate chain and key.',
272 additionalProperties
=> 0,
274 node
=> get_standard_option
('pve-node'),
275 type
=> get_standard_option
('pmg-certificate-type'),
278 description
=> 'Restart pmgproxy.',
290 my $type = extract_param
($param, 'type');
291 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
294 print "Deleting custom certificate files\n";
296 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
298 if ($param->{restart
}) {
299 restart_after_cert_update
($type);
303 PMG
::CertHelpers
::cert_lock
(10, $code);
305 if ($type eq 'smtp') {
306 set_smtp
(0, $param->{restart
});
312 __PACKAGE__-
>register_method ({
313 name
=> 'acme_cert_index',
316 permissions
=> { user
=> 'all' },
317 description
=> "ACME Certificate index.",
319 additionalProperties
=> 0,
321 node
=> get_standard_option
('pve-node'),
330 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
342 my $order_certificate = sub {
343 my ($acme, $acme_node_config) = @_;
345 my $plugins = PMG
::API2
::ACMEPlugin
::load_config
();
347 print "Placing ACME order\n";
348 my ($order_url, $order) = $acme->new_order([ sort keys %{$acme_node_config->{domains
}} ]);
349 print "Order URL: $order_url\n";
350 for my $auth_url (@{$order->{authorizations
}}) {
351 print "\nGetting authorization details from '$auth_url'\n";
352 my $auth = $acme->get_authorization($auth_url);
354 # force lower case, like get_acme_conf does
355 my $domain = lc($auth->{identifier
}->{value
});
356 if ($auth->{status
} eq 'valid') {
357 print "$domain is already validated!\n";
359 print "The validation for $domain is pending!\n";
361 my $domain_config = $acme_node_config->{domains
}->{$domain};
362 die "no config for domain '$domain'\n" if !$domain_config;
364 my $plugin_id = $domain_config->{plugin
};
366 my $plugin_cfg = $plugins->{ids
}->{$plugin_id};
367 die "plugin '$plugin_id' for domain '$domain' not found!\n"
371 plugin
=> $plugin_cfg,
372 alias
=> $domain_config->{alias
},
375 my $plugin = PVE
::ACME
::Challenge-
>lookup($plugin_cfg->{type
});
376 $plugin->setup($acme, $auth, $data);
378 print "Triggering validation\n";
380 die "no validation URL returned by plugin '$plugin_id' for domain '$domain'\n"
381 if !defined($data->{url
});
383 $acme->request_challenge_validation($data->{url
});
384 print "Sleeping for 5 seconds\n";
387 $auth = $acme->get_authorization($auth_url);
388 if ($auth->{status
} eq 'pending') {
389 print "Status is still 'pending', trying again in 10 seconds\n";
392 } elsif ($auth->{status
} eq 'valid') {
393 print "Status is 'valid', domain '$domain' OK!\n";
396 my $error = "validating challenge '$auth_url' failed - status: $auth->{status}";
397 for (@{$auth->{challenges
}}) {
398 $error .= ", $_->{error}->{detail}" if $_->{error
}->{detail
};
404 eval { $plugin->teardown($acme, $auth, $data) };
409 print "\nAll domains validated!\n";
410 print "\nCreating CSR\n";
411 # Currently we only support dns entries, so extract those from the order:
417 } $order->{identifiers
}->@*
419 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
420 my ($csr_der, $key) = PMG
::RS
::CSR
::generate_csr
($san, {});
422 my $finalize_error_cnt = 0;
423 print "Checking order status\n";
425 $order = $acme->get_order($order_url);
426 if ($order->{status
} eq 'pending') {
427 print "still pending, trying to finalize order\n";
429 # to be compatible with and without the order ready state we try to
430 # finalize even at the 'pending' state and give up after 5
431 # unsuccessful tries this can be removed when the letsencrypt api
432 # definitely has implemented the 'ready' state
434 $acme->finalize_order($order->{finalize
}, $csr_der);
437 die $err if $finalize_error_cnt >= 5;
439 $finalize_error_cnt++;
444 } elsif ($order->{status
} eq 'ready') {
445 print "Order is ready, finalizing order\n";
446 $acme->finalize_order($order->{finalize
}, $csr_der);
449 } elsif ($order->{status
} eq 'processing') {
450 print "still processing, trying again in 30 seconds\n";
453 } elsif ($order->{status
} eq 'valid') {
457 die "order status: $order->{status}\n";
460 print "\nDownloading certificate\n";
461 my $cert = $acme->get_certificate($order->{certificate
});
463 return ($cert, $key);
466 # Filter domains and raise an error if the list becomes empty.
467 my $filter_domains = sub {
468 my ($acme_config, $type) = @_;
470 my $domains = $acme_config->{domains
};
471 foreach my $domain (sort keys %$domains) {
472 my $entry = $domains->{$domain};
473 if (!(grep { $_ eq $type } PVE
::Tools
::split_list
($entry->{usage
}))) {
474 delete $domains->{$domain};
479 raise
("No domains configured for type '$type'\n", 400);
483 __PACKAGE__-
>register_method ({
484 name
=> 'new_acme_cert',
485 path
=> 'acme/{type}',
487 permissions
=> { check
=> [ 'admin' ] },
488 description
=> 'Order a new certificate from ACME-compatible CA.',
492 additionalProperties
=> 0,
494 node
=> get_standard_option
('pve-node'),
495 type
=> get_standard_option
('pmg-certificate-type'),
498 description
=> 'Overwrite existing custom certificate.',
510 my $type = extract_param
($param, 'type'); # also used to know which service to restart
511 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
512 raise_param_exc
({'force' => "Custom certificate exists but 'force' is not set."})
513 if !$param->{force
} && -e
$cert_path;
515 my $node_config = PMG
::NodeConfig
::load_config
();
516 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
517 raise
("ACME domain list in configuration is missing!", 400)
518 if !($acme_config && $acme_config->{domains
} && $acme_config->{domains
}->%*);
520 $filter_domains->($acme_config, $type);
522 my $rpcenv = PMG
::RESTEnvironment-
>get();
523 my $authuser = $rpcenv->get_user();
526 STDOUT-
>autoflush(1);
527 my $account = $acme_config->{account
};
528 my $account_file = "${acme_account_dir}/${account}";
529 die "ACME account config file '$account' does not exist.\n"
530 if ! -e
$account_file;
532 print "Loading ACME account details\n";
533 my $acme = PMG
::RS
::Acme-
>load($account_file);
535 my ($cert, $key) = $order_certificate->($acme, $acme_config);
536 my $certificate = "$key\n$cert";
538 update_cert
($type, $cert_path, $certificate, $param->{force
}, 1);
540 if ($type eq 'smtp') {
547 return $rpcenv->fork_worker("acmenewcert", undef, $authuser, $realcmd);
550 __PACKAGE__-
>register_method ({
551 name
=> 'renew_acme_cert',
552 path
=> 'acme/{type}',
554 permissions
=> { check
=> [ 'admin' ] },
555 description
=> "Renew existing certificate from CA.",
559 additionalProperties
=> 0,
561 node
=> get_standard_option
('pve-node'),
562 type
=> get_standard_option
('pmg-certificate-type'),
565 description
=> 'Force renewal even if expiry is more than 30 days away.',
577 my $type = extract_param
($param, 'type'); # also used to know which service to restart
578 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
580 raise
("No current (custom) certificate found, please order a new certificate!\n")
583 my $expires_soon = PVE
::Certificate
::check_expiry
($cert_path, time() + 30*24*60*60);
584 raise_param_exc
({'force' => "Certificate does not expire within the next 30 days, and 'force' is not set."})
585 if !$expires_soon && !$param->{force
};
587 my $node_config = PMG
::NodeConfig
::load_config
();
588 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
589 raise
("ACME domain list in configuration is missing!", 400)
590 if !$acme_config || !$acme_config->{domains
}->%*;
592 $filter_domains->($acme_config, $type);
594 my $rpcenv = PMG
::RESTEnvironment-
>get();
595 my $authuser = $rpcenv->get_user();
597 my $old_cert = PVE
::Tools
::file_get_contents
($cert_path);
600 STDOUT-
>autoflush(1);
601 my $account = $acme_config->{account
};
602 my $account_file = "${acme_account_dir}/${account}";
603 die "ACME account config file '$account' does not exist.\n"
604 if ! -e
$account_file;
606 print "Loading ACME account details\n";
607 my $acme = PMG
::RS
::Acme-
>load($account_file);
609 my ($cert, $key) = $order_certificate->($acme, $acme_config);
610 my $certificate = "$key\n$cert";
612 update_cert
($type, $cert_path, $certificate, 1, 1);
614 if (defined($old_cert)) {
615 print "Revoking old certificate\n";
616 eval { $acme->revoke_certificate($old_cert, undef) };
617 warn "Revoke request to CA failed: $@" if $@;
621 return $rpcenv->fork_worker("acmerenew", undef, $authuser, $realcmd);
624 __PACKAGE__-
>register_method ({
625 name
=> 'revoke_acme_cert',
626 path
=> 'acme/{type}',
628 permissions
=> { check
=> [ 'admin' ] },
629 description
=> "Revoke existing certificate from CA.",
633 additionalProperties
=> 0,
635 node
=> get_standard_option
('pve-node'),
636 type
=> get_standard_option
('pmg-certificate-type'),
645 my $type = extract_param
($param, 'type'); # also used to know which service to restart
646 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
648 my $node_config = PMG
::NodeConfig
::load_config
();
649 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
650 raise
("ACME domain list in configuration is missing!", 400)
651 if !$acme_config || !$acme_config->{domains
}->%*;
653 $filter_domains->($acme_config, $type);
655 my $rpcenv = PMG
::RESTEnvironment-
>get();
656 my $authuser = $rpcenv->get_user();
658 my $cert = PVE
::Tools
::file_get_contents
($cert_path);
659 $cert = pem_certificate
($cert)
660 or die "no certificate section found in '$cert_path'\n";
663 STDOUT-
>autoflush(1);
664 my $account = $acme_config->{account
};
665 my $account_file = "${acme_account_dir}/${account}";
666 die "ACME account config file '$account' does not exist.\n"
667 if ! -e
$account_file;
669 print "Loading ACME account details\n";
670 my $acme = PMG
::RS
::Acme-
>load($account_file);
672 print "Revoking old certificate\n";
673 eval { $acme->revoke_certificate($cert, undef) };
675 # is there a better check?
676 die "Revoke request to CA failed: $err" if $err !~ /"Certificate is expired"/;
680 print "Deleting certificate files\n";
682 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
684 restart_after_cert_update
($type);
687 PMG
::CertHelpers
::cert_lock
(10, $code);
689 if ($type eq 'smtp') {
694 return $rpcenv->fork_worker("acmerevoke", undef, $authuser, $realcmd);