10 use MIME
::Base64
qw(encode_base64url);
11 use File
::Path
qw(make_path);
13 use Digest
::SHA
qw(sha256 sha256_hex);
18 use Crypt
::OpenSSL
::RSA
;
26 use PVE
::ACME
::DNSChallenge
;
28 Crypt
::OpenSSL
::RSA-
>import_random_seed();
30 my $LETSENCRYPT_STAGING = 'https://acme-staging-v02.api.letsencrypt.org/directory';
32 ### ACME library (compatible with Let's Encrypt v2 API)
36 # 1) my $acme = PVE::ACME->new('path/to/account.json', 'API directory URL');
37 # 2) $acme->init(4096); # generate account key
38 # 4) my $tos_url = $acme->get_meta()->{termsOfService}; # optional, display if applicable
39 # 5) $acme->new_account($tos_url, contact => ['mailto:example@example.com']);
41 # 1) my $acme = PVE::ACME->new('path/to/account.json', 'API directory URL');
43 # 3) my ($order_url, $order) = $acme->new_order(['foo.example.com', 'bar.example.com']);
44 # 4) # repeat a-f for each $auth_url in $order->{authorizations}
45 # a) my $authorization = $acme->get_authorization($auth_url);
46 # b) # pick $challenge from $authorization->{challenges} according to desired type
47 # c) my $key_auth = $acme->key_authorization($challenge->{token});
48 # d) # setup challenge validation according to specification
49 # e) $acme->request_challenge_validation($challenge->{url});
50 # f) # poll $acme->get_authorization($auth_url) until status is 'valid'
51 # 5) # generate CSR in PEM format
52 # 6) $acme->finalize_order($order, $csr);
53 # 7) # poll $acme->get_order($order_url) until status is 'valid'
54 # 8) my $cert = $acme->get_certificate($order);
55 # 9) # $key is path to key file, $cert contains PEM-encoded certificate chain
57 # 1) my $acme = PVE::ACME->new('path/to/account.json', 'API directory URL');
59 # 3) $acme->revoke_certificate($cert);
62 sub encode
($) { # acme requires 'base64url' encoding
63 return encode_base64url
($_[0]);
66 sub tojs
($;%) { # shortcut for to_json with utf8=>1
67 my ($data, %data) = @_;
68 return to_json
($data, { utf8
=> 1, %data });
73 ($data) = ($data =~ /^(.*)$/s); # untaint from_json croaks on error anyways.
74 return from_json
($data);
78 my ($self, $msg, $dump, $noerr) = @_;
80 warn Dumper
($dump), "\n" if $self->{debug
} && $dump;
90 # $path: account JSON file
91 # $directory: the ACME directory URL used to find method URLs
93 my ($class, $path, $directory) = @_;
95 $directory //= $LETSENCRYPT_STAGING;
97 my $ua = LWP
::UserAgent-
>new();
99 $ua->agent('pve-acme/0.1');
100 $ua->protocols_allowed(['https']);
105 directory
=> $directory,
113 return bless $self, $class;
117 my ($self, $proxy) = @_;
119 $self->{ua
}->proxy('https', $proxy);
122 # RS256: PKCS#1 padding, no OAEP, SHA256
123 my $configure_key = sub {
125 $key->use_pkcs1_padding();
126 $key->use_sha256_hash();
129 # Create account key with $keybits bits
130 # use instead of load, overwrites existing account JSON file!
132 my ($self, $keybits) = @_;
133 die "Already have a key\n" if defined($self->{key
});
135 my $key = Crypt
::OpenSSL
::RSA-
>generate_key($keybits);
136 $configure_key->($key);
141 my @SAVED_VALUES = qw(location account tos debug directory);
142 # Serialize persistent parts of $self to $self->{path} as JSON
147 if (my $key = $self->{key
}) {
148 $keystr = $key->get_private_key_string();
151 for my $k (@SAVED_VALUES) {
152 my $v = $self->{$k} // next;
155 # pretty => 1 for readability
156 # canonical => 1 to reduce churn
157 file_set_contents
($self->{path
}, tojs
($o, pretty
=> 1, canonical
=> 1));
160 # Load serialized account JSON file into $self
163 return if $self->{loaded
};
165 my $raw = file_get_contents
($self->{path
});
166 if ($raw =~ m/^(.*)$/s) { $raw = $1; } # untaint
167 my $data = fromjs
($raw);
168 $self->{$_} = $data->{$_} for @SAVED_VALUES;
169 if (defined(my $keystr = $data->{key
})) {
170 my $key = Crypt
::OpenSSL
::RSA-
>new_private_key($keystr);
171 $configure_key->($key);
176 # The 'jwk' object needs the key type, key parameters and the usage,
177 # except for when we want to take the JWK-Thumbprint, then the usage
178 # must not be included.
180 my ($self, $pure) = @_;
181 my $key = $self->{key
}
182 or die "No key was generated yet\n";
183 my ($n, $e) = $key->get_key_parameters();
186 ($pure ?
() : (use => 'sig')), # for thumbprints
187 n
=> encode
($n->to_bin),
188 e
=> encode
($e->to_bin),
192 # The thumbprint is a sha256 hash of the lexicographically sorted (iow.
193 # canonical) condensed json string of the JWK object which gets base64url
197 my $jwk = $self->jwk(1); # $pure = 1
198 return encode
(sha256
(tojs
($jwk, canonical
=>1))); # canonical sorts
201 # A key authorization string in acme is a challenge token dot-connected with
202 # a JWK Thumbprint. You put the base64url encoded sha256-hash of this string
203 # into the DNS TXT record.
204 sub key_authorization
{
205 my ($self, $token) = @_;
206 return $token .'.'. $self->jwk_thumbprint();
209 # JWS signing using the RS256 alg (RSA/SHA256).
211 my ($self, $use_jwk, $data, $url) = @_;
212 my $key = $self->{key
}
213 or die "No key was generated yet\n";
215 my $payload = $data ne '' ? encode
(tojs
($data)) : $data;
217 if (!defined($self->{nonce
})) {
218 my $method = $self->_method('newNonce');
219 $self->do(GET
=> $method);
222 # The acme protocol requires the actual request URL be in the protected
223 # header. There is no unprotected header.
227 nonce
=> $self->{nonce
} // die "missing nonce\n"
230 # header contains either
231 # - kid, reference to account URL
233 # the latter is only allowed for
234 # - creating accounts (no account URL yet)
235 # - revoking certificates with the certificate key instead of account key
237 $protected->{jwk
} = $self->jwk();
239 $protected->{kid
} = $self->{location
};
242 $protected = encode
(tojs
($protected));
244 my $signdata = "$protected.$payload";
245 my $signature = encode
($key->sign($signdata));
248 protected
=> $protected,
250 signature
=> $signature,
255 my ($resp, $code, $plain) = @_;
257 die "expected code '$code', received '".$resp->code."'\n"
258 if $resp->code != $code;
260 return $plain ?
$resp->decoded_content : fromjs
($resp->decoded_content);
263 # Get the list of method URLs and query the directory if we have to.
266 if (my $methods = $self->{methods
}) {
269 my $r = $self->do(GET
=> $self->{directory
});
270 my $methods = __get_result
($r, 200);
271 $self->fatal("unable to decode methods returned by directory - $@", $r) if $@;
272 return ($self->{methods
} = $methods);
275 # Get a method, causing the directory to be queried first if necessary.
277 my ($self, $method) = @_;
278 my $methods = $self->__get_methods();
279 my $url = $methods->{$method}
280 or die "no such method: $method\n";
284 # Get $self->{account} with an error if we don't have one yet.
287 my $account = $self->{account
}
288 // die "no account loaded\n";
289 return wantarray ?
($account, $self->{location
}) : $account;
295 my $methods = $self->__get_methods();
296 if (my $meta = $methods->{meta
}) {
297 print("(meta): $_ : $meta->{$_}\n") for sort keys %$meta;
299 print("$_ : $methods->{$_}\n") for sort grep {$_ ne 'meta'} keys %$methods;
302 # return (optional) meta directory entry.
303 # this is public because it might contain the ToS, which should be displayed
304 # and agreed to before creating an account
307 my $methods = $self->__get_methods();
308 return $methods->{meta
};
311 # Common code between new_account and update_account
313 my ($self, $expected_code, $url, $new, %info) = @_;
317 my $r = $self->do(POST
=> $url, $req, $new);
319 my $account = __get_result
($r, $expected_code);
320 if (!defined($self->{location
})) {
321 my $account_url = $r->header('Location')
322 or die "did not receive an account URL\n";
323 $self->{location
} = $account_url;
325 $self->{account
} = $account;
328 $self->fatal("POST to '$url' failed - $@", $r) if $@;
329 return $self->{account
};
332 # Create a new account using data in %info.
333 # Optionally pass $tos_url to agree to the given Terms of Service
334 # POST to newAccount endpoint
335 # Expects a '201 Created' reply
336 # Saves and returns the account data
338 my ($self, $tos_url, %info) = @_;
339 my $url = $self->_method('newAccount');
342 $self->{tos
} = $tos_url;
343 $info{termsOfServiceAgreed
} = JSON
::true
;
346 return $self->__new_account(201, $url, 1, %info);
349 # Update existing account with new %info
350 # POST to account URL
351 # Expects a '200 OK' reply
352 # Saves and returns updated account data
354 my ($self, %info) = @_;
355 my (undef, $url) = $self->_account;
357 return $self->__new_account(200, $url, 0, %info);
360 # Retrieves existing account information
361 # POST to account URL with empty body!
362 # Expects a '200 OK' reply
363 # Saves and returns updated account data
366 return $self->update_account();
369 # Start a new order for one or more domains
370 # POST to newOrder endpoint
371 # Expects a '201 Created' reply
372 # returns order URL and parsed order object, including authorization and finalize URLs
374 my ($self, $domains) = @_;
376 my $url = $self->_method('newOrder');
378 identifiers
=> [ map { { type
=> 'dns', value
=> $_ } } @$domains ],
381 my $r = $self->do(POST
=> $url, $req);
382 my ($order_url, $order);
384 $order_url = $r->header('Location')
385 or die "did not receive an order URL\n";
386 $order = __get_result
($r, 201)
388 $self->fatal("POST to '$url' failed - $@", $r) if $@;
389 return ($order_url, $order);
392 # Finalize order after all challenges have been validated
393 # POST to order's finalize URL
394 # Expects a '200 OK' reply
395 # returns (potentially updated) order object
397 my ($self, $order, $csr) = @_;
402 my $r = $self->do(POST
=> $order->{finalize
}, $req);
403 my $return = eval { __get_result
($r, 200); };
404 $self->fatal("POST to '$order->{finalize}' failed - $@", $r) if $@;
409 # GET-as-POST to order URL
410 # Expects a '200 OK' reply
411 # returns order object
413 my ($self, $order_url) = @_;
414 my $r = $self->do(POST
=> $order_url, '');
415 my $return = eval { __get_result
($r, 200); };
416 $self->fatal("POST of '$order_url' failed - $@", $r) if $@;
420 # Gets authorization object
421 # GET-as-POST to authorization URL
422 # Expects a '200 OK' reply
423 # returns authorization object, including challenges array
424 sub get_authorization
{
425 my ($self, $auth_url) = @_;
427 my $r = $self->do(POST
=> $auth_url, '');
428 my $return = eval { __get_result
($r, 200); };
429 $self->fatal("POST of '$auth_url' failed - $@", $r) if $@;
433 # Deactivates existing authorization
434 # POST to authorization URL
435 # Expects a '200 OK' reply
436 # returns updated authorization object
437 sub deactivate_authorization
{
438 my ($self, $auth_url) = @_;
441 status
=> 'deactivated',
443 my $r = $self->do(POST
=> $auth_url, $req);
444 my $return = eval { __get_result
($r, 200); };
445 $self->fatal("POST to '$auth_url' failed - $@", $r) if $@;
450 # GET-as-POST to order's certificate URL
451 # if $root is specified, attempts to find a matching (alternate) chain
452 # Expects a '200 OK' reply
453 # returns certificate chain in PEM format
454 sub get_certificate
{
455 my ($self, $order, $root) = @_;
457 $self->fatal("no certificate URL available (yet?)", $order)
458 if !$order->{certificate
};
460 my $check_root = sub {
463 my @certs = PVE
::Certificate
::split_pem
($chain);
464 my $root_pem = $certs[-1];
466 my ($file, $fh) = PVE
::Tools
::tempfile_contents
($root_pem);
467 my $info = PVE
::Certificate
::get_certificate_info
($file);
469 return defined($info->{issuer
}) && $info->{issuer
} =~ m/\Q$root\E/i;
472 my $r = $self->do(POST
=> $order->{certificate
}, '');
475 my $res = __get_result
($r, 200, 1);
476 if ($root && !$check_root->($res)) {
477 # alternate chains if requested and default didn't match
479 my @links = $r->header('link');
480 for my $link (@links) {
481 if ($link =~ /^<(.*)>;rel="alternate"$/) {
483 my $chain = eval { __get_result
($self->do(POST
=> $url, ''), 200, 1); };
484 die "failed to retrieve alternate chain from '$url' - $@\n" if $@;
485 if ($check_root->($chain)) {
491 die "no matching alternate chain for '$root' returned by server\n"
495 if ($res =~ /^(-----BEGIN CERTIFICATE-----)(.+)(-----END CERTIFICATE-----)$/s) { # untaint
498 die "Server reply does not look like a PEM encoded certificate\n";
500 $self->fatal("POST of '$order->{certificate}' failed - $@", $r) if $@;
504 # Revoke given certificate
505 # POST to revokeCert endpoint
506 # currently only supports revokation with account key
507 # $certificate can either be PEM or DER encoded
508 # Expects a '200 OK' reply
509 sub revoke_certificate
{
510 my ($self, $certificate, $reason) = @_;
512 my $url = $self->_method('revokeCert');
514 if ($certificate =~ /^-----BEGIN CERTIFICATE-----/) {
515 $certificate = PVE
::Certificate
::pem_to_der
($certificate);
519 certificate
=> encode
($certificate),
520 reason
=> $reason // 0,
522 # TODO: set use_jwk if revoking with certificate key
523 my $r = $self->do(POST
=> $url, $req);
525 die "unexpected code $r->code\n" if $r->code != 200;
527 $self->fatal("POST to '$url' failed - $@", $r) if $@;
530 # Request validation of challenge
531 # POST to challenge URL
532 # call after validation has been setup
533 # returns (potentially updated) challenge object
534 sub request_challenge_validation
{
535 my ($self, $url) = @_;
537 my $r = $self->do(POST
=> $url, {});
538 my $return = eval { __get_result
($r, 200); };
539 $self->fatal("POST to '$url' failed - $@", $r) if $@;
543 # actually 'do' a $method request on $url
544 # $data: input for JWS, optional
545 # $use_jwk: use JWK instead of KID in JWD (see sub jws)
547 my ($self, $method, $url, $data, $use_jwk) = @_;
549 $self->fatal("Error: can't $method to empty URL") if !$url || $url eq '';
551 my $headers = HTTP
::Headers-
>new();
552 $headers->header('Content-Type' => 'application/jose+json');
553 my $content = defined($data) ?
$self->jws($use_jwk, $data, $url) : undef;
555 if (defined($content)) {
556 $content = tojs
($content);
557 $request = HTTP
::Request-
>new($method, $url, $headers, $content);
559 $request = HTTP
::Request-
>new($method, $url, $headers);
561 my $res = $self->{ua
}->request($request);
562 if (!$res->is_success) {
563 # check for nonce rejection
564 if ($res->code == 400 && $res->decoded_content) {
565 my $parsed_content = fromjs
($res->decoded_content);
566 if ($parsed_content->{type
} eq 'urn:ietf:params:acme:error:badNonce') {
567 warn("bad Nonce, retrying\n");
568 $self->{nonce
} = $res->header('Replay-Nonce');
569 return $self->do($method, $url, $data, $use_jwk);
572 $self->fatal("Error: $method to $url\n".$res->decoded_content, $res);
574 if (my $nonce = $res->header('Replay-Nonce')) {
575 $self->{nonce
} = $nonce;