aboutsummaryrefslogtreecommitdiffstats
path: root/client
blob: 838b1840fb33be188251c1be1568d8250065b818 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/perl -T

#----------------------------------------------------------------------
# ACME client written with process isolation and minimal privileges in mind
# Copyright © 2015-2017 Guilhem Moulin <guilhem@fripost.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#----------------------------------------------------------------------

use v5.14.2;
use strict;
use warnings;

# Usage: client COMMAND CONFIG_FD SOCKET_FD [ARGUMENTS]
#
# fdopen(3) the file descriptor SOCKET_FD (corresponding to the
# listening lacme-accountd socket), connect(2) to it to retrieve the
# account key's public parameters and later send data to be signed by
# the master component (using the account key).
#
# CONFIG_FD is a read-only file descriptor associated with the
# configuration file at pos 0.  (This is needed since this process
# doesn't know its name and might not have read access to it.)
#
# NOTE: one needs to chdir(2) to an appropriate ACME challenge directory
# before running this program, since challenge tokens are (on purpose)
# only written to the current directory.  If COMMAND is challenge-less,
# one should chdir(2) to the root directory "/" instead.
#
# NOTE: one should run this program as an unprivileged user:group such
# as "nobody:nogroup"; bind(2)'ing to a restricted UNIX socket (for
# instance own by another user and created with umask 0177) is not a
# problem since SOCKET_FD can be bound as root prior to the execve(2).

my $PROTOCOL_VERSION = 1;

use Errno 'EEXIST';
use Fcntl qw/O_CREAT O_EXCL O_WRONLY/;
use Digest::SHA qw/sha256 sha256_hex/;
use MIME::Base64 qw/encode_base64 encode_base64url/;

use LWP::UserAgent ();
use Types::Serialiser ();
use JSON ();

use Config::Tiny ();

# Clean up PATH
$ENV{PATH} = join ':', qw{/usr/bin /bin};
delete @ENV{qw/IFS CDPATH ENV BASH_ENV/};

my $COMMAND = shift @ARGV // die;

# Untaint and fdopen(3) the configuration file and listening socket
(shift @ARGV // die) =~ /\A(\d+)\z/ or die;
open (my $CONFFILE, '<&=', $1+0) or die "fdopen $1: $!";
(shift @ARGV // die) =~ /\A(\d+)\z/ or die;
open (my $S, '+<&=', $1+0) or die "fdopen $1: $!";


#############################################################################
# Read the protocol version and JSON Web Key (RFC 7517) from the
# lacme-accountd socket
#
die "Error: Invalid client version\n" unless
    $S->getline() =~ /\A(\d+) OK(?:.*)\r\n\z/ and $1 == $PROTOCOL_VERSION;
my $JWK = JSON::->new->decode($S->getline());
my $KID;

# JSON keys need to be sorted lexicographically (for instance in the thumbprint)
sub json() { JSON::->new->utf8->canonical(); }

my $JWK_thumbprint = encode_base64url(sha256(json()->encode($JWK)));
my $NONCE;


#############################################################################
# Parse configuration (already validated by the master) and create the
# LWP::UserAgent object
#

my $CONFIG = do {
    my $conf = do { local $/ = undef; <$CONFFILE> };
    close $CONFFILE or die "Can't close: $!";
    my $h = Config::Tiny::->read_string($conf) or die Config::Tiny::->errstr()."\n";
    $h->{_} //= {};
    $h->{client}->{$_} //= $h->{_}->{$_} foreach keys %{$h->{_}}; # add defaults
    $h->{client};
};
my $UA = do {
    my %args = %$CONFIG;
    my $verify = lc (delete $args{SSL_verify} // 'Yes') eq 'no' ? 0 : 1;
    my %ssl_opts = ( verify_hostname => $verify );
    $ssl_opts{$_} = $args{$_} foreach grep /^SSL_/, keys %args;
    LWP::UserAgent::->new( ssl_opts => \%ssl_opts );
} // die "Can't create LWP::UserAgent object";
$UA->default_header( 'Accept-Language' => 'en' );


#############################################################################
# Send an HTTP request to the ACME server.  If $json is defined, send
# its encoding as the request content, with "application/jose+json" as
# Content-Type.
#
sub request($$;$) {
    my ($method, $uri, $json) = @_;
    print STDERR "[$$] >>> $method $uri <<<\n" if $ENV{DEBUG};

    my $req = HTTP::Request::->new($method => $uri) or die "Can't $method $uri";
    if (defined $json) {
        $req->content_type('application/jose+json');
        $req->content(json()->encode($json));
    }
    my $r = $UA->request($req) or die "Can't $method $uri";
    $NONCE //= $r->header('Replay-Nonce'); # undef $NONCE if the header is missing
    print STDERR "[$$] >>> ", $r->status_line, "\n", $r->headers->as_string("\n") if $ENV{DEBUG};
    return $r;
}

# The request's Status Line; if the Content-Type is
# application/problem+json (RFC 7807), parse the decoded content as JSON
# and add the value of the 'detail' field to the Status Line.
sub request_status_line($) {
    my $r = shift;
    my $msg = $r->status_line;
    if (!$r->is_success() and $r->content_type() eq 'application/problem+json') {
        my $content = json()->decode($r->decoded_content());
        print STDERR json()->pretty->encode($content), "\n" if $ENV{DEBUG};
        $msg .= " (".$content->{detail}.")" if defined $content->{detail};
    }
    return $msg;
}

# Parse and return the request's decoded content as JSON; or print the
# Status Line and fail if the request failed.
# If $dump is set, also pretty-print the decoded content.
sub request_json_decode($;$$) {
    my $r = shift;
    my $dump = shift || $ENV{DEBUG};
    my $fh = shift // \*STDERR;
    die request_status_line($r), "\n" unless $r->is_success();
    my $content = $r->decoded_content();

    die "Content-Type: ".$r->content_type()." is not application/json\n"
        unless $r->content_type() eq 'application/json';

    my $json = json()->decode($content);
    print $fh (-t $fh ? (json()->pretty->encode($json)."\n") : $content)
        if $dump;
    return $json;
}


#############################################################################
# JSON-encode the hash reference $h and send it to the ACME server $uri
# encapsulated it in a JSON Web Signature (JWS).
# https://tools.ietf.org/html/draft-ietf-acme-acme-12
#
sub acme($@) {
    my $uri = shift;
    die "Missing nonce\n" unless defined $NONCE;

    # Produce the JSON Web Signature: RFC 7515 section 5
    my %header = ( alg => 'RS256', nonce => $NONCE, url => $uri );
    defined $KID ? ($header{kid} = $KID) : ($header{jwk} = $JWK);
    my $payload = encode_base64url(json()->encode({ @_ }));
    my $protected = encode_base64url(json()->encode(\%header));
    my $data = $protected .'.'. $payload;
    $S->printflush($data, "\r\n");
    my $sig = $S->getline();
    $sig =~ s/\r\n\z// or die;
    undef $NONCE; # consume the nonce

    # Flattened JSON Serialization, RFC 7515 section 7.2.2
    request(POST => $uri, {
        payload => $payload,
        protected => $protected,
        signature => $sig
    });
}

my $SERVER_URI = $CONFIG->{server} // 'https://acme-v02.api.letsencrypt.org/directory';

my %RES;
# Get the resource URI from the directory
sub acme_resource($%) {
    my $r = shift;
    unless (%RES) {
        # query the ACME directory to get resources URIs
        %RES = %{ request_json_decode(request(GET => $SERVER_URI)) };
        # send a HEAD request to the newNonce resource to get a fresh nonce
        die "Unknown resource 'newNonce'\n" unless defined $RES{newNonce};
        request(HEAD => $RES{newNonce});
    }
    my $uri = $RES{$r} // die "Unknown resource '$r'\n";
    acme($uri, @_);
}

# Set the key ID (registration URI)
sub set_kid(;$) {
    my $die = shift // 1;
    my $r = acme_resource('newAccount', onlyReturnExisting => Types::Serialiser::true );
    if ($r->is_success()) {
        $KID = $r->header('Location');
    } elsif ($die) {
        die request_status_line($r), "\n";
    }
}


#############################################################################
# account FLAGS [CONTACT ..]
#
if ($COMMAND eq 'account') {
    my $flags = shift @ARGV;

    my %h = ( contact => \@ARGV ) if @ARGV;
    $h{onlyReturnExisting}   = Types::Serialiser::true unless $flags & 0x01;
    $h{termsOfServiceAgreed} = Types::Serialiser::true if     $flags & 0x02;

    print STDERR "Requesting new registration ".(@ARGV ? ("for ".join(', ', @ARGV)) : "")."\n"
        if $flags & 0x01;

    my $r = acme_resource('newAccount', %h);
    # TODO: list account orders: https://github.com/letsencrypt/boulder/issues/3335

    if ($r->is_success()) {
        $KID = $r->header('Location');
        $r = acme($KID, %h);
        request_json_decode($r, 1, \*STDOUT)
            if $r->is_success() and $r->content_type() eq 'application/json';
    }

    print STDERR request_status_line($r), "\n"
        if !$r->is_success() or $ENV{DEBUG};
    exit ($r->is_success() ? 0 : 1);
}


#############################################################################
# newOrder AUTHZ [AUTHZ ..]
#   Read the CSR (in DER format) from STDIN, print the cert (in PEM format
#   to STDOUT)
#
elsif ($COMMAND eq 'newOrder') {
    die unless @ARGV;
    my $timeout = $CONFIG->{timeout} // 10;
    my $csr = do { local $/ = undef; <STDIN> };

    set_kid();
    my @identifiers = map {{ type => 'dns', value => $_ }} @ARGV;
    my $r = acme_resource('newOrder', identifiers => \@identifiers);
    my $order = request_json_decode($r);

    foreach (@{$order->{authorizations}}) {
        my $authz = request_json_decode(request(GET => $_));
        next unless $authz->{status} eq 'pending';

        my $identifier = $authz->{identifier}->{value};
        my ($challenge) = grep {$_->{type} eq 'http-01'} @{$authz->{challenges} // []};
        die "Missing 'http-01' challenge in server response for '$identifier'\n"
            unless defined $challenge;

        die "Invalid challenge token ".($challenge->{token} // '')."\n"
            # ensure we don't write outside the cwd
            unless ($challenge->{token} // '') =~ /\A[A-Za-z0-9_\-]+\z/;

        my $keyAuthorization = $challenge->{token}.'.'.$JWK_thumbprint;

        # serve $keyAuthorization at http://$domain/.well-known/acme-challenge/$challenge->{token}
        if (sysopen(my $fh, $challenge->{token}, O_CREAT|O_EXCL|O_WRONLY, 0644)) {
            $fh->print($keyAuthorization);
            $fh->close() or die "Can't close: $!";
        } elsif ($! == EEXIST) {
            print STDERR "WARNING: File exists: $challenge->{token}\n";
        } else {
            die "Can't open $challenge->{token}: $!";
        }

        $r = acme($challenge->{url});

        # poll until the status become 'valid'
        # XXX poll the order URL instead, to get the status of all
        # challenges at once
        # https://github.com/letsencrypt/boulder/issues/3530
        for ( my $i = 0, my $resp, my $status;
              $resp = request_json_decode($r),
              $status = $resp->{status} // 'pending',
              $status ne 'valid';
              $r = request('GET' => $challenge->{url})) {
            if (defined (my $problem = $resp->{error})) { # problem document (RFC 7807)
                my $msg = $problem->{status};
                $msg .= " " .$problem->{title}      if defined $problem->{title};
                $msg .= " (".$problem->{detail}.")" if defined $problem->{detail};
                die $msg, "\n";
            }
            die "Error: Invalid challenge for $identifier (status: ".$status.")\n"
                if $status ne 'pending';

            my $sleep = 1;
            if (defined (my $retry_after = $r->header('Retry-After'))) {
                print STDERR "Retrying after $retry_after seconds...\n";
                $sleep = $retry_after;
            }

            $i += $sleep;
            die "Timeout exceeded while waiting for challenges to pass ($identifier)\n"
                if $timeout > 0 and $i >= $timeout;
            sleep $sleep;
        }
    }

    $r = acme($order->{finalize}, csr => encode_base64url($csr));
    my $resp = request_json_decode($r);

    my $uri = $resp->{certificate};
    print STDERR "Certificate URI: $uri\n";

    # pool until the cert is available
    for (my $i = 0;;) {
        $r = request('GET' => $uri);
        die request_status_line($r), "\n" unless $r->is_success();
        last unless $r->code == 202; # Accepted
        my $retry_after = $r->header('Retry-After') // 1;
        print STDERR "Retrying after $retry_after seconds...\n";
        $i += $retry_after;
        die "Timeout exceeded while waiting for certificate\n" if $timeout > 0 and $i >= $timeout;
        sleep $retry_after;
    }

    # keep only the leaf certificate
    pipe my $rd, my $wd or die "Can't pipe: $!";
    my $pid = fork // die "Can't fork: $!";
    unless ($pid) {
        open STDIN, '<&', $rd or die "Can't dup: $!";
        exec qw/openssl x509 -outform PEM/ or die;
    }
    $rd->close() or die "Can't close: $!";
    $wd->print( $r->decoded_content() );
    $wd->close() or die "Can't close: $!";

    waitpid $pid => 0;
    die $? if $? > 0;
}


#############################################################################
# revokeCert
#   The certificate to revoke is passed (in DER format) to STDIN; this
#   is required since the ACME client might not have read access to the
#   X.509 file
#
elsif ($COMMAND eq 'revokeCert') {
    die if @ARGV;
    my $der = do { local $/ = undef; <STDIN> };
    close STDIN or die "Can't close: $!";

    # send a KID if the request is signed with the acccount key, otherwise send a JWK
    set_kid(0);

    my $r = acme_resource('revokeCert', certificate => encode_base64url($der));
    exit 0 if $r->is_success();
    die request_status_line($r), "\n";
}