| 1 |
#!/usr/bin/perl -T |
| 2 |
|
| 3 |
#---------------------------------------------------------------------- |
| 4 |
# ACME client written with process isolation and minimal privileges in mind |
| 5 |
# Copyright © 2015-2021 Guilhem Moulin <[email protected]> |
| 6 |
# |
| 7 |
# This program is free software: you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# This program is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 19 |
#---------------------------------------------------------------------- |
| 20 |
|
| 21 |
use v5.14.2; |
| 22 |
use strict; |
| 23 |
use warnings; |
| 24 |
|
| 25 |
# Usage: client COMMAND CONFIG_FD SOCKET_FD [ARGUMENTS] |
| 26 |
# |
| 27 |
# fdopen(3) the file descriptor SOCKET_FD (corresponding to the |
| 28 |
# listening lacme-accountd socket), connect(2) to it to retrieve the |
| 29 |
# account key's public parameters and later send data to be signed by |
| 30 |
# the master component (using the account key). |
| 31 |
# |
| 32 |
# CONFIG_FD is a read-only file descriptor associated with the |
| 33 |
# configuration file at pos 0. (This is needed since this process |
| 34 |
# doesn't know its name and might not have read access to it.) |
| 35 |
# |
| 36 |
# NOTE: one needs to chdir(2) to an appropriate ACME challenge directory |
| 37 |
# before running this program, since challenge tokens are (on purpose) |
| 38 |
# only written to the current directory. If COMMAND is challenge-less, |
| 39 |
# one should chdir(2) to the root directory "/" instead. |
| 40 |
# |
| 41 |
# NOTE: one should run this program as an unprivileged user:group such |
| 42 |
# as "nobody:nogroup"; bind(2)'ing to a restricted UNIX socket (for |
| 43 |
# instance own by another user and created with umask 0177) is not a |
| 44 |
# problem since SOCKET_FD can be bound as root prior to the execve(2). |
| 45 |
|
| 46 |
our $VERSION = '0.8.3'; |
| 47 |
my $PROTOCOL_VERSION = 1; |
| 48 |
my $NAME = 'lacme-client'; |
| 49 |
|
| 50 |
use Errno 'EEXIST'; |
| 51 |
use Fcntl qw/O_CREAT O_EXCL O_WRONLY/; |
| 52 |
use Digest::SHA 'sha256'; |
| 53 |
use MIME::Base64 qw/encode_base64 encode_base64url/; |
| 54 |
|
| 55 |
use Date::Parse (); |
| 56 |
use LWP::UserAgent (); |
| 57 |
use JSON (); |
| 58 |
|
| 59 |
# Clean up PATH |
| 60 |
$ENV{PATH} = join ':', qw{/usr/bin /bin}; |
| 61 |
delete @ENV{qw/IFS CDPATH ENV BASH_ENV/}; |
| 62 |
|
| 63 |
my $COMMAND = shift @ARGV // die; |
| 64 |
|
| 65 |
# Untaint and fdopen(3) the configuration file and listening socket |
| 66 |
(shift @ARGV // die) =~ /\A(\d+)\z/ or die; |
| 67 |
open (my $CONFFILE, '<&=', $1+0) or die "fdopen $1: $!"; |
| 68 |
(shift @ARGV // die) =~ /\A(\d+)\z/ or die; |
| 69 |
open (my $S, '+<&=', $1+0) or die "fdopen $1: $!"; |
| 70 |
|
| 71 |
# JSON keys need to be sorted lexicographically (for instance in the thumbprint) |
| 72 |
sub json() { JSON::->new->utf8->canonical(); } |
| 73 |
|
| 74 |
|
| 75 |
############################################################################# |
| 76 |
# Read the protocol version and JSON Web Key (RFC 7517) from the |
| 77 |
# lacme-accountd socket |
| 78 |
# |
| 79 |
|
| 80 |
my ($JWK, $JWK_thumbprint, $ALG, $KID); |
| 81 |
do { |
| 82 |
my $greeting = $S->getline(); |
| 83 |
die "Error: Invalid client version\n" unless defined $greeting and |
| 84 |
$greeting =~ /\A(\d+) OK(?: (.*))?\r\n\z/ and $1 == $PROTOCOL_VERSION; |
| 85 |
if (defined (my $extra = $2)) { |
| 86 |
my $h = eval { JSON::->new->decode($extra) }; |
| 87 |
if ($@ or !defined $h) { |
| 88 |
print STDERR "Warning: Ignoring extra greeting data from accountd \"$extra\"\n"; |
| 89 |
} else { |
| 90 |
print STDERR "Received extra greeting data from accountd: $extra\n" if $ENV{DEBUG}; |
| 91 |
($JWK_thumbprint, $ALG, $KID) = @$h{qw/jwk-thumbprint alg kid/}; |
| 92 |
} |
| 93 |
} |
| 94 |
my $jwk_str = $S->getline() // die "Error: No JWK from lacme-accountd\n"; |
| 95 |
$JWK = JSON::->new->decode($jwk_str); |
| 96 |
$JWK_thumbprint //= encode_base64url(sha256(json()->encode($JWK))); # SHA-256 is hardcoded, see RFC 8555 sec. 8.1 |
| 97 |
$ALG //= "RS256"; |
| 98 |
}; |
| 99 |
|
| 100 |
|
| 101 |
############################################################################# |
| 102 |
# Parse configuration (already validated by the master) and create the |
| 103 |
# LWP::UserAgent object |
| 104 |
# |
| 105 |
|
| 106 |
my $CONFIG = do { |
| 107 |
my $conf = do { local $/ = undef; <$CONFFILE> }; |
| 108 |
JSON::->new->decode($conf); |
| 109 |
}; |
| 110 |
my $UA = do { |
| 111 |
my %args = %$CONFIG; |
| 112 |
my $verify = lc (delete $args{SSL_verify} // 'Yes') eq 'no' ? 0 : 1; |
| 113 |
my %ssl_opts = ( verify_hostname => $verify ); |
| 114 |
$ssl_opts{$_} = $args{$_} foreach grep /^SSL_/, keys %args; |
| 115 |
LWP::UserAgent::->new( agent => "$NAME/$VERSION", ssl_opts => \%ssl_opts ); |
| 116 |
} // die "Can't create LWP::UserAgent object"; |
| 117 |
$UA->default_header( 'Accept-Language' => 'en' ); |
| 118 |
my $NONCE; |
| 119 |
|
| 120 |
|
| 121 |
############################################################################# |
| 122 |
# Send an HTTP request to the ACME server. If $json is defined, send |
| 123 |
# its encoding as the request content, with "application/jose+json" as |
| 124 |
# Content-Type. |
| 125 |
# |
| 126 |
sub request($$;$) { |
| 127 |
my ($method, $uri, $json) = @_; |
| 128 |
print STDERR "[$$] >>> $method $uri <<<\n" if $ENV{DEBUG}; |
| 129 |
|
| 130 |
my $req = HTTP::Request::->new($method => $uri) or die "Can't $method $uri"; |
| 131 |
if (defined $json) { |
| 132 |
$req->content_type('application/jose+json'); |
| 133 |
$req->content(json()->encode($json)); |
| 134 |
} |
| 135 |
my $r = $UA->request($req) or die "Can't $method $uri"; |
| 136 |
$NONCE //= $r->header('Replay-Nonce'); # undef $NONCE if the header is missing |
| 137 |
print STDERR "[$$] >>> ", $r->status_line, "\n", $r->headers->as_string("\n") if $ENV{DEBUG}; |
| 138 |
return $r; |
| 139 |
} |
| 140 |
|
| 141 |
# The request's Status Line; if the Content-Type is |
| 142 |
# application/problem+json (RFC 7807), parse the decoded content as JSON |
| 143 |
# and add the value of the 'detail' field to the Status Line. |
| 144 |
sub request_status_line($) { |
| 145 |
my $r = shift; |
| 146 |
my $msg = $r->status_line; |
| 147 |
if (!$r->is_success() and $r->content_type() eq 'application/problem+json') { |
| 148 |
my $content = json()->decode($r->decoded_content()); |
| 149 |
print STDERR json()->pretty->encode($content), "\n" if $ENV{DEBUG}; |
| 150 |
$msg .= " (".$content->{detail}.")" if defined $content->{detail}; |
| 151 |
} |
| 152 |
return $msg; |
| 153 |
} |
| 154 |
|
| 155 |
# The request's Retry-After header (RFC 7231 sec. 7.1.3), converted to |
| 156 |
# waiting time in seconds. |
| 157 |
sub request_retry_after($) { |
| 158 |
my $r = shift; |
| 159 |
my $v = $r->header('Retry-After'); |
| 160 |
if (defined $v and $v !~ /\A\d+\z/) { |
| 161 |
$v = Date::Parse::str2time($v); |
| 162 |
if (defined $v) { |
| 163 |
$v = $v - time; |
| 164 |
undef $v if $v <= 0; |
| 165 |
} |
| 166 |
} |
| 167 |
return $v; |
| 168 |
} |
| 169 |
|
| 170 |
# Parse and return the request's decoded content as JSON; or print the |
| 171 |
# Status Line and fail if the request failed. |
| 172 |
# If $dump is set, also pretty-print the decoded content. |
| 173 |
sub request_json_decode($;$$) { |
| 174 |
my $r = shift; |
| 175 |
my $dump = shift || $ENV{DEBUG}; |
| 176 |
my $fh = shift // \*STDERR; |
| 177 |
die request_status_line($r), "\n" unless $r->is_success(); |
| 178 |
my $content = $r->decoded_content(); |
| 179 |
|
| 180 |
die "Content-Type: ".$r->content_type()." is not application/json\n" |
| 181 |
unless $r->content_type() eq 'application/json'; |
| 182 |
|
| 183 |
my $json = json()->decode($content); |
| 184 |
print $fh (-t $fh ? (json()->pretty->encode($json)."\n") : $content) |
| 185 |
if $dump; |
| 186 |
return $json; |
| 187 |
} |
| 188 |
|
| 189 |
|
| 190 |
############################################################################# |
| 191 |
# JSON-encode the hash reference $payload and send it to the ACME server |
| 192 |
# $url encapsulated it in a JSON Web Signature (JWS). $header MUST |
| 193 |
# contain either "jwk" (JSON Web Key) or "kid" per RFC 8555 sec. 6.2 |
| 194 |
# https://tools.ietf.org/html/rfc8555 |
| 195 |
# |
| 196 |
sub acme2($$;$) { |
| 197 |
my ($url, $header, $payload) = @_; |
| 198 |
|
| 199 |
# Produce the JSON Web Signature: RFC 7515 section 5 |
| 200 |
$header->{alg} = $ALG; |
| 201 |
$header->{nonce} = $NONCE // die "Missing nonce\n"; |
| 202 |
$header->{url} = $url; |
| 203 |
my $protected = encode_base64url(json()->encode($header)); |
| 204 |
$payload = defined $payload ? encode_base64url(json()->encode($payload)) : ""; |
| 205 |
|
| 206 |
$S->printflush($protected, ".", $payload, "\r\n"); |
| 207 |
my $sig = $S->getline() // die "Error: lost connection with lacme-accountd\n"; |
| 208 |
$sig =~ s/\r\n\z// or die; |
| 209 |
undef $NONCE; # consume the nonce |
| 210 |
|
| 211 |
# Flattened JSON Serialization, RFC 7515 section 7.2.2 |
| 212 |
request(POST => $url, { |
| 213 |
payload => $payload, |
| 214 |
protected => $protected, |
| 215 |
signature => $sig |
| 216 |
}); |
| 217 |
} |
| 218 |
|
| 219 |
# Like above, but always use "kid" |
| 220 |
sub acme($;$) { |
| 221 |
my ($url, $payload) = @_; |
| 222 |
die "Missing KID\n" unless defined $KID; |
| 223 |
acme2($url, {kid => $KID}, $payload) |
| 224 |
} |
| 225 |
|
| 226 |
my $SERVER_URI = $CONFIG->{server} // '@@acmeapi_server@@'; |
| 227 |
|
| 228 |
my %RES; |
| 229 |
# Get the resource URI from the directory |
| 230 |
sub acme_resource($%) { |
| 231 |
my $r = shift; |
| 232 |
my %payload = @_; |
| 233 |
my %protected; |
| 234 |
|
| 235 |
unless (%RES) { |
| 236 |
# query the ACME directory to get resources URIs |
| 237 |
%RES = %{ request_json_decode(request(GET => $SERVER_URI)) }; |
| 238 |
# send a HEAD request to the newNonce resource to get a fresh nonce |
| 239 |
die "Unknown resource 'newNonce'\n" unless defined $RES{newNonce}; |
| 240 |
request(HEAD => $RES{newNonce}); |
| 241 |
} |
| 242 |
my $uri = $RES{$r} // die "Unknown resource '$r'\n"; |
| 243 |
|
| 244 |
if ($r eq "newAccount" or ($r eq "revokeCert" and !defined $KID)) { |
| 245 |
# per RFC 8555 sec. 6.2 these requests MUST have a JWK |
| 246 |
print STDERR "Warning: lacme-accountd supplied an empty JWK; try removing 'keyid' ", |
| 247 |
"setting from lacme-accountd.conf if the ACME resource request fails.\n" |
| 248 |
unless %$JWK; |
| 249 |
return acme2($uri, {jwk => $JWK}, \%payload); |
| 250 |
} else { |
| 251 |
# per RFC 8555 sec. 6.2 all other requests MUST have a KID |
| 252 |
return acme($uri, \%payload); |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
# Set the key ID (registration URI) |
| 257 |
sub set_kid(;$) { |
| 258 |
my $die = shift // 1; |
| 259 |
return if defined $KID; # already set |
| 260 |
my $r = acme_resource('newAccount', onlyReturnExisting => JSON::true ); |
| 261 |
if ($r->is_success()) { |
| 262 |
$KID = $r->header('Location'); |
| 263 |
} elsif ($die) { |
| 264 |
die request_status_line($r), "\n"; |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
############################################################################# |
| 270 |
# account FLAGS [CONTACT ..] |
| 271 |
# |
| 272 |
if ($COMMAND eq 'account') { |
| 273 |
my $flags = shift @ARGV; |
| 274 |
|
| 275 |
my %h = ( contact => \@ARGV ) if @ARGV; |
| 276 |
$h{onlyReturnExisting} = JSON::true unless $flags & 0x01; |
| 277 |
$h{termsOfServiceAgreed} = JSON::true if $flags & 0x02; |
| 278 |
$h{status} = "deactivated" if $flags & 0x04; |
| 279 |
|
| 280 |
print STDERR "Requesting new registration ".(@ARGV ? ("for ".join(', ', @ARGV)) : "")."\n" |
| 281 |
if $flags & 0x01; |
| 282 |
|
| 283 |
my $r = acme_resource('newAccount', %h); |
| 284 |
# TODO: list account orders: https://github.com/letsencrypt/boulder/issues/3335 |
| 285 |
|
| 286 |
print STDERR "Terms of Service: $RES{meta}->{termsOfService}\n" |
| 287 |
if defined $RES{meta} and defined $RES{meta}->{termsOfService}; |
| 288 |
|
| 289 |
if ($r->is_success()) { |
| 290 |
$KID = $r->header('Location'); |
| 291 |
print STDERR "Key ID: $KID\n"; |
| 292 |
$r = acme($KID, \%h); |
| 293 |
request_json_decode($r, 1, \*STDOUT) |
| 294 |
if $r->is_success() and $r->content_type() eq 'application/json'; |
| 295 |
} |
| 296 |
|
| 297 |
print STDERR request_status_line($r), "\n" |
| 298 |
if !$r->is_success() or $ENV{DEBUG}; |
| 299 |
exit ($r->is_success() ? 0 : 1); |
| 300 |
} |
| 301 |
|
| 302 |
|
| 303 |
############################################################################# |
| 304 |
# newOrder AUTHZ [AUTHZ ..] |
| 305 |
# Read the CSR (in DER format) from STDIN, print the cert (in PEM format |
| 306 |
# to STDOUT) |
| 307 |
# |
| 308 |
elsif ($COMMAND eq 'newOrder') { |
| 309 |
die unless @ARGV; |
| 310 |
my $timeout = $CONFIG->{timeout} // 30; |
| 311 |
my $csr = do { local $/ = undef; <STDIN> }; |
| 312 |
|
| 313 |
set_kid(); |
| 314 |
my @identifiers = map {{ type => 'dns', value => $_ }} @ARGV; |
| 315 |
my $r = acme_resource('newOrder', identifiers => \@identifiers); |
| 316 |
my $order = request_json_decode($r); |
| 317 |
my $orderurl = $r->header('Location'); |
| 318 |
|
| 319 |
foreach (@{$order->{authorizations}}) { |
| 320 |
my $authz = request_json_decode(acme($_)); |
| 321 |
next unless $authz->{status} eq 'pending'; |
| 322 |
|
| 323 |
my $identifier = $authz->{identifier}->{value}; |
| 324 |
my ($challenge) = grep {$_->{type} eq 'http-01'} @{$authz->{challenges} // []}; |
| 325 |
die "Missing 'http-01' challenge in server response for '$identifier'\n" |
| 326 |
unless defined $challenge; |
| 327 |
|
| 328 |
die "Invalid challenge token ".($challenge->{token} // '')."\n" |
| 329 |
# ensure we don't write outside the cwd |
| 330 |
unless ($challenge->{token} // '') =~ /\A[A-Za-z0-9_\-]+\z/; |
| 331 |
|
| 332 |
my $keyAuthorization = $challenge->{token}.'.'.$JWK_thumbprint; |
| 333 |
|
| 334 |
# serve $keyAuthorization at http://$domain/.well-known/acme-challenge/$challenge->{token} |
| 335 |
if (sysopen(my $fh, $challenge->{token}, O_CREAT|O_EXCL|O_WRONLY)) { |
| 336 |
# note: the file is created mode 0666 minus umask restrictions |
| 337 |
$fh->print($keyAuthorization); |
| 338 |
$fh->close() or die "close: $!"; |
| 339 |
} elsif ($! == EEXIST) { |
| 340 |
print STDERR "Warning: File exists: $challenge->{token}\n"; |
| 341 |
} else { |
| 342 |
die "open($challenge->{token}): $!"; |
| 343 |
} |
| 344 |
my $r = acme($challenge->{url}, {}); |
| 345 |
request_json_decode($r); |
| 346 |
} |
| 347 |
|
| 348 |
# poll the order URL (to get the status of all challenges at once) |
| 349 |
# until the status become 'valid'; see RFC 8555 sec. 7.1.6 for the |
| 350 |
# the status change flow |
| 351 |
my $orderstr = join(', ', map {uc($_->{type}) .":". $_->{value}} @identifiers); |
| 352 |
my $certuri; |
| 353 |
for (my $i = 0, my $url = $orderurl, my $payload;;) { |
| 354 |
my $r = acme($url => $payload); |
| 355 |
my $resp = request_json_decode($r); |
| 356 |
if (defined (my $problem = $resp->{error})) { # problem document (RFC 7807) |
| 357 |
my $msg = $problem->{status}; |
| 358 |
$msg .= " " .$problem->{title} if defined $problem->{title}; |
| 359 |
$msg .= " (".$problem->{detail}.")" if defined $problem->{detail}; |
| 360 |
die $msg, "\n"; |
| 361 |
} |
| 362 |
my $status = $resp->{status}; |
| 363 |
if (!defined $status or $status eq "invalid") { |
| 364 |
die "Error: Invalid order $orderstr\n"; |
| 365 |
} elsif ($status eq "pending") { |
| 366 |
# keep retrying |
| 367 |
} elsif ($status eq "ready") { |
| 368 |
$url = $order->{finalize}; |
| 369 |
$payload = {csr => encode_base64url($csr)}; |
| 370 |
# retry after moving to "processing" or "valid" state |
| 371 |
next; |
| 372 |
} elsif ($status eq "processing") { |
| 373 |
$url = $orderurl; |
| 374 |
undef $payload; |
| 375 |
} elsif ($status eq "valid") { |
| 376 |
$certuri = $resp->{certificate} // |
| 377 |
die "Error: Missing \"certificate\" field in \"valid\" order\n"; |
| 378 |
last; |
| 379 |
} else { |
| 380 |
warn "Unknown order status: $status\n"; |
| 381 |
} |
| 382 |
|
| 383 |
my $retry_after = request_retry_after($r) // 1; |
| 384 |
print STDERR "Retrying after $retry_after seconds...\n"; |
| 385 |
$i += $retry_after; |
| 386 |
die "Timeout exceeded while waiting for challenges to pass ($orderstr)\n" |
| 387 |
if $timeout > 0 and $i >= $timeout; |
| 388 |
sleep $retry_after; |
| 389 |
} |
| 390 |
|
| 391 |
# poll until the cert is available |
| 392 |
print STDERR "Certificate URI: $certuri\n"; |
| 393 |
for (my $i = 0;;) { |
| 394 |
$r = acme($certuri); |
| 395 |
die request_status_line($r), "\n" unless $r->is_success(); |
| 396 |
last unless $r->code == 202; # Accepted |
| 397 |
my $retry_after = request_retry_after($r) // 1; |
| 398 |
print STDERR "Retrying after $retry_after seconds...\n"; |
| 399 |
$i += $retry_after; |
| 400 |
die "Timeout exceeded while waiting for certificate\n" if $timeout > 0 and $i >= $timeout; |
| 401 |
sleep $retry_after; |
| 402 |
} |
| 403 |
print $r->decoded_content(); |
| 404 |
} |
| 405 |
|
| 406 |
|
| 407 |
############################################################################# |
| 408 |
# revokeCert |
| 409 |
# The certificate to revoke is passed (in DER format) to STDIN; this |
| 410 |
# is needed since the ACME client might not have read access to the |
| 411 |
# X.509 file |
| 412 |
# |
| 413 |
elsif ($COMMAND eq 'revokeCert') { |
| 414 |
die if @ARGV; |
| 415 |
my $der = do { local $/ = undef; <STDIN> }; |
| 416 |
close STDIN or die "close: $!"; |
| 417 |
|
| 418 |
# RFC 8555 sec. 6.2: send a KID if the request is signed with the |
| 419 |
# acccount key, otherwise send a JWK |
| 420 |
# We have no way to know which of the account key or certificate key |
| 421 |
# is used, so we try to get a KID and fallback to sending the JWK |
| 422 |
set_kid(0); |
| 423 |
|
| 424 |
my $r = acme_resource('revokeCert', certificate => encode_base64url($der)); |
| 425 |
exit 0 if $r->is_success(); |
| 426 |
die request_status_line($r), "\n"; |
| 427 |
} |