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);
16 use PMG
::API2
::ACMEPlugin
;
18 use base
qw(PVE::RESTHandler);
20 my $acme_account_dir = PMG
::CertHelpers
::acme_account_dir
();
22 sub first_typed_pem_entry
: prototype($$) {
23 my ($label, $data) = @_;
25 if ($data =~ /^(-----BEGIN \Q$label\E-----\n.*?\n-----END \Q$label\E-----)$/ms) {
31 sub pem_private_key
: prototype($) {
33 return first_typed_pem_entry
('PRIVATE KEY', $data);
36 sub pem_certificate
: prototype($) {
38 return first_typed_pem_entry
('CERTIFICATE', $data);
41 my sub restart_after_cert_update
: prototype($) {
45 print "Restarting pmgproxy\n";
46 PVE
::Tools
::run_command
(['systemctl', 'reload-or-restart', 'pmgproxy']);
48 my $cinfo = PMG
::ClusterConfig-
>new();
49 if (scalar(keys %{$cinfo->{ids
}})) {
50 print "Notify cluster about new fingerprint\n";
51 PMG
::Cluster
::trigger_update_fingerprints
($cinfo);
56 my sub update_cert
: prototype($$$$$) {
57 my ($type, $cert_path, $certificate, $force, $restart) = @_;
59 print "Setting custom certificate file $cert_path\n";
60 PMG
::CertHelpers
::set_cert_file
($certificate, $cert_path, $force);
62 restart_after_cert_update
($type) if $restart;
64 PMG
::CertHelpers
::cert_lock
(10, $code);
67 my sub set_smtp
: prototype($$) {
68 my ($on, $reload) = @_;
71 my $cfg = PMG
::Config-
>new();
72 if (!$cfg->get('mail', 'tls') != !$on) {
73 print "Rewriting postfix config\n";
74 $cfg->set('mail', 'tls', $on);
76 my $changed = $cfg->rewrite_config_postfix();
80 print "Reloading postfix\n";
81 PMG
::Utils
::service_cmd
('postfix', 'reload');
84 PMG
::Config
::lock_config
($code, "failed to reload postfix");
87 __PACKAGE__-
>register_method ({
91 permissions
=> { user
=> 'all' },
92 description
=> "Node index.",
94 additionalProperties
=> 0,
96 node
=> get_standard_option
('pve-node'),
105 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
112 { name
=> 'custom' },
114 { name
=> 'config' },
119 __PACKAGE__-
>register_method ({
123 permissions
=> { user
=> 'all' },
126 description
=> "Get information about the node's certificates.",
128 additionalProperties
=> 0,
130 node
=> get_standard_option
('pve-node'),
135 items
=> get_standard_option
('pve-certificate-info'),
141 for my $path (&PMG
::CertHelpers
::API_CERT
, &PMG
::CertHelpers
::SMTP_CERT
) {
143 my $info = PVE
::Certificate
::get_certificate_info
($path);
144 push @$res, $info if $info;
151 __PACKAGE__-
>register_method ({
152 name
=> 'custom_cert_index',
155 permissions
=> { user
=> 'all' },
156 description
=> "Certificate index.",
158 additionalProperties
=> 0,
160 node
=> get_standard_option
('pve-node'),
169 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
181 __PACKAGE__-
>register_method ({
182 name
=> 'upload_custom_cert',
183 path
=> 'custom/{type}',
185 permissions
=> { check
=> [ 'admin' ] },
186 description
=> 'Upload or update custom certificate chain and key.',
190 additionalProperties
=> 0,
192 node
=> get_standard_option
('pve-node'),
195 format
=> 'pem-certificate-chain',
196 description
=> 'PEM encoded certificate (chain).',
200 description
=> 'PEM encoded private key.',
201 format
=> 'pem-string',
204 type
=> get_standard_option
('pmg-certificate-type'),
207 description
=> 'Overwrite existing custom or ACME certificate files.',
213 description
=> 'Restart services.',
219 returns
=> get_standard_option
('pve-certificate-info'),
223 my $type = extract_param
($param, 'type'); # also used to know which service to restart
224 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
226 my $certs = extract_param
($param, 'certificates');
227 $certs = PVE
::Certificate
::strip_leading_text
($certs);
229 my $key = extract_param
($param, 'key');
231 $key = PVE
::Certificate
::strip_leading_text
($key);
232 $certs = "$key\n$certs";
234 my $private_key = pem_private_key
($certs);
235 if (!defined($private_key)) {
236 my $old = file_get_contents
($cert_path);
237 $private_key = pem_private_key
($old);
238 if (!defined($private_key)) {
240 'key' => "Attempted to upload custom certificate without (existing) key."
244 # copy the old certificate's key:
245 $certs = "$key\n$certs";
251 PMG
::CertHelpers
::cert_lock
(10, sub {
252 update_cert
($type, $cert_path, $certs, $param->{force
}, $param->{restart
});
255 if ($type eq 'smtp') {
256 set_smtp
(1, $param->{restart
});
262 __PACKAGE__-
>register_method ({
263 name
=> 'remove_custom_cert',
264 path
=> 'custom/{type}',
266 permissions
=> { check
=> [ 'admin' ] },
267 description
=> 'DELETE custom certificate chain and key.',
271 additionalProperties
=> 0,
273 node
=> get_standard_option
('pve-node'),
274 type
=> get_standard_option
('pmg-certificate-type'),
277 description
=> 'Restart pmgproxy.',
289 my $type = extract_param
($param, 'type');
290 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
293 print "Deleting custom certificate files\n";
295 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
297 if ($param->{restart
}) {
298 restart_after_cert_update
($type);
302 PMG
::CertHelpers
::cert_lock
(10, $code);
304 if ($type eq 'smtp') {
305 set_smtp
(0, $param->{restart
});
311 __PACKAGE__-
>register_method ({
312 name
=> 'acme_cert_index',
315 permissions
=> { user
=> 'all' },
316 description
=> "ACME Certificate index.",
318 additionalProperties
=> 0,
320 node
=> get_standard_option
('pve-node'),
329 links
=> [ { rel
=> 'child', href
=> "{type}" } ],
341 my $order_certificate = sub {
342 my ($acme, $acme_node_config) = @_;
344 my $plugins = PMG
::API2
::ACMEPlugin
::load_config
();
346 print "Placing ACME order\n";
347 my ($order_url, $order) = $acme->new_order([ sort keys %{$acme_node_config->{domains
}} ]);
348 print "Order URL: $order_url\n";
349 for my $auth_url (@{$order->{authorizations
}}) {
350 print "\nGetting authorization details from '$auth_url'\n";
351 my $auth = $acme->get_authorization($auth_url);
353 # force lower case, like get_acme_conf does
354 my $domain = lc($auth->{identifier
}->{value
});
355 if ($auth->{status
} eq 'valid') {
356 print "$domain is already validated!\n";
358 print "The validation for $domain is pending!\n";
360 my $domain_config = $acme_node_config->{domains
}->{$domain};
361 die "no config for domain '$domain'\n" if !$domain_config;
363 my $plugin_id = $domain_config->{plugin
};
365 my $plugin_cfg = $plugins->{ids
}->{$plugin_id};
366 die "plugin '$plugin_id' for domain '$domain' not found!\n"
370 plugin
=> $plugin_cfg,
371 alias
=> $domain_config->{alias
},
374 my $plugin = PVE
::ACME
::Challenge-
>lookup($plugin_cfg->{type
});
375 $plugin->setup($acme, $auth, $data);
377 print "Triggering validation\n";
379 die "no validation URL returned by plugin '$plugin_id' for domain '$domain'\n"
380 if !defined($data->{url
});
382 $acme->request_challenge_validation($data->{url
});
383 print "Sleeping for 5 seconds\n";
386 $auth = $acme->get_authorization($auth_url);
387 if ($auth->{status
} eq 'pending') {
388 print "Status is still 'pending', trying again in 10 seconds\n";
391 } elsif ($auth->{status
} eq 'valid') {
392 print "Status is 'valid', domain '$domain' OK!\n";
395 my $error = "validating challenge '$auth_url' failed - status: $auth->{status}";
396 for (@{$auth->{challenges
}}) {
397 $error .= ", $_->{error}->{detail}" if $_->{error
}->{detail
};
403 eval { $plugin->teardown($acme, $auth, $data) };
408 print "\nAll domains validated!\n";
409 print "\nCreating CSR\n";
410 # Currently we only support dns entries, so extract those from the order:
416 } $order->{identifiers
}->@*
418 die "DNS identifiers are required to generate a CSR.\n" if !scalar @$san;
419 my ($csr_der, $key) = PMG
::RS
::CSR
::generate_csr
($san, {});
421 my $finalize_error_cnt = 0;
422 print "Checking order status\n";
424 $order = $acme->get_order($order_url);
425 if ($order->{status
} eq 'pending') {
426 print "still pending, trying to finalize order\n";
428 # to be compatible with and without the order ready state we try to
429 # finalize even at the 'pending' state and give up after 5
430 # unsuccessful tries this can be removed when the letsencrypt api
431 # definitely has implemented the 'ready' state
433 $acme->finalize_order($order->{finalize
}, $csr_der);
436 die $err if $finalize_error_cnt >= 5;
438 $finalize_error_cnt++;
443 } elsif ($order->{status
} eq 'ready') {
444 print "Order is ready, finalizing order\n";
445 $acme->finalize_order($order->{finalize
}, $csr_der);
448 } elsif ($order->{status
} eq 'processing') {
449 print "still processing, trying again in 30 seconds\n";
452 } elsif ($order->{status
} eq 'valid') {
456 die "order status: $order->{status}\n";
459 print "\nDownloading certificate\n";
460 my $cert = $acme->get_certificate($order->{certificate
});
462 return ($cert, $key);
465 # Filter domains and raise an error if the list becomes empty.
466 my $filter_domains = sub {
467 my ($acme_config, $type) = @_;
469 my $domains = PMG
::NodeConfig
::filter_domains_by_type
($acme_config->{domains
}, $type);
472 raise
("No domains configured for type '$type'\n", 400);
475 $acme_config->{domains
} = $domains;
478 __PACKAGE__-
>register_method ({
479 name
=> 'new_acme_cert',
480 path
=> 'acme/{type}',
482 permissions
=> { check
=> [ 'admin' ] },
483 description
=> 'Order a new certificate from ACME-compatible CA.',
487 additionalProperties
=> 0,
489 node
=> get_standard_option
('pve-node'),
490 type
=> get_standard_option
('pmg-certificate-type'),
493 description
=> 'Overwrite existing custom certificate.',
505 my $type = extract_param
($param, 'type'); # also used to know which service to restart
506 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
507 raise_param_exc
({'force' => "Custom certificate exists but 'force' is not set."})
508 if !$param->{force
} && -e
$cert_path;
510 my $node_config = PMG
::NodeConfig
::load_config
();
511 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
512 raise
("ACME domain list in configuration is missing!", 400)
513 if !($acme_config && $acme_config->{domains
} && $acme_config->{domains
}->%*);
515 $filter_domains->($acme_config, $type);
517 my $rpcenv = PMG
::RESTEnvironment-
>get();
518 my $authuser = $rpcenv->get_user();
521 STDOUT-
>autoflush(1);
522 my $account = $acme_config->{account
};
523 my $account_file = "${acme_account_dir}/${account}";
524 die "ACME account config file '$account' does not exist.\n"
525 if ! -e
$account_file;
527 print "Loading ACME account details\n";
528 my $acme = PMG
::RS
::Acme-
>load($account_file);
530 my ($cert, $key) = $order_certificate->($acme, $acme_config);
531 my $certificate = "$key\n$cert";
533 update_cert
($type, $cert_path, $certificate, $param->{force
}, 1);
535 if ($type eq 'smtp') {
542 return $rpcenv->fork_worker("acmenewcert", undef, $authuser, $realcmd);
545 __PACKAGE__-
>register_method ({
546 name
=> 'renew_acme_cert',
547 path
=> 'acme/{type}',
549 permissions
=> { check
=> [ 'admin' ] },
550 description
=> "Renew existing certificate from CA.",
554 additionalProperties
=> 0,
556 node
=> get_standard_option
('pve-node'),
557 type
=> get_standard_option
('pmg-certificate-type'),
560 description
=> 'Force renewal even if expiry is more than 30 days away.',
572 my $type = extract_param
($param, 'type'); # also used to know which service to restart
573 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
575 raise
("No current (custom) certificate found, please order a new certificate!\n")
578 my $expires_soon = PVE
::Certificate
::check_expiry
($cert_path, time() + 30*24*60*60);
579 raise_param_exc
({'force' => "Certificate does not expire within the next 30 days, and 'force' is not set."})
580 if !$expires_soon && !$param->{force
};
582 my $node_config = PMG
::NodeConfig
::load_config
();
583 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
584 raise
("ACME domain list in configuration is missing!", 400)
585 if !$acme_config || !$acme_config->{domains
}->%*;
587 $filter_domains->($acme_config, $type);
589 my $rpcenv = PMG
::RESTEnvironment-
>get();
590 my $authuser = $rpcenv->get_user();
592 my $old_cert = PVE
::Tools
::file_get_contents
($cert_path);
595 STDOUT-
>autoflush(1);
596 my $account = $acme_config->{account
};
597 my $account_file = "${acme_account_dir}/${account}";
598 die "ACME account config file '$account' does not exist.\n"
599 if ! -e
$account_file;
601 print "Loading ACME account details\n";
602 my $acme = PMG
::RS
::Acme-
>load($account_file);
604 my ($cert, $key) = $order_certificate->($acme, $acme_config);
605 my $certificate = "$key\n$cert";
607 update_cert
($type, $cert_path, $certificate, 1, 1);
609 if (defined($old_cert)) {
610 print "Revoking old certificate\n";
612 $old_cert = pem_certificate
($old_cert)
613 or die "no certificate section found in '$cert_path'\n";
614 $acme->revoke_certificate($old_cert, undef);
616 warn "Revoke request to CA failed: $@" if $@;
620 return $rpcenv->fork_worker("acmerenew", undef, $authuser, $realcmd);
623 __PACKAGE__-
>register_method ({
624 name
=> 'revoke_acme_cert',
625 path
=> 'acme/{type}',
627 permissions
=> { check
=> [ 'admin' ] },
628 description
=> "Revoke existing certificate from CA.",
632 additionalProperties
=> 0,
634 node
=> get_standard_option
('pve-node'),
635 type
=> get_standard_option
('pmg-certificate-type'),
644 my $type = extract_param
($param, 'type'); # also used to know which service to restart
645 my $cert_path = PMG
::CertHelpers
::cert_path
($type);
647 my $node_config = PMG
::NodeConfig
::load_config
();
648 my $acme_config = PMG
::NodeConfig
::get_acme_conf
($node_config);
649 raise
("ACME domain list in configuration is missing!", 400)
650 if !$acme_config || !$acme_config->{domains
}->%*;
652 $filter_domains->($acme_config, $type);
654 my $rpcenv = PMG
::RESTEnvironment-
>get();
655 my $authuser = $rpcenv->get_user();
657 my $cert = PVE
::Tools
::file_get_contents
($cert_path);
658 $cert = pem_certificate
($cert)
659 or die "no certificate section found in '$cert_path'\n";
662 STDOUT-
>autoflush(1);
663 my $account = $acme_config->{account
};
664 my $account_file = "${acme_account_dir}/${account}";
665 die "ACME account config file '$account' does not exist.\n"
666 if ! -e
$account_file;
668 print "Loading ACME account details\n";
669 my $acme = PMG
::RS
::Acme-
>load($account_file);
671 print "Revoking old certificate\n";
672 eval { $acme->revoke_certificate($cert, undef) };
674 # is there a better check?
675 die "Revoke request to CA failed: $err" if $err !~ /"Certificate is expired"/;
679 print "Deleting certificate files\n";
681 PMG
::Ticket
::generate_api_cert
(0) if $type eq 'api';
683 restart_after_cert_update
($type);
686 PMG
::CertHelpers
::cert_lock
(10, $code);
688 if ($type eq 'smtp') {
693 return $rpcenv->fork_worker("acmerevoke", undef, $authuser, $realcmd);