Debian Codegraph @

lacme-accountd

raw
1 #!/usr/bin/perl -T
2
3 #----------------------------------------------------------------------
4 # ACME client written with process isolation and minimal privileges in mind
5 # (account key manager)
6 # Copyright © 2015-2021 Guilhem Moulin <[email protected]>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <https://www.gnu.org/licenses/>.
20 #----------------------------------------------------------------------
21
22 use v5.14.2;
23 use strict;
24 use warnings;
25
26 our $VERSION = '0.8.4';
27 my $PROTOCOL_VERSION = 1;
28 my $NAME = 'lacme-accountd';
29
30 use Digest::SHA 'sha256';
31 use Errno 'EINTR';
32 use File::Basename 'dirname';
33 use Getopt::Long qw/:config posix_default no_ignore_case gnu_getopt auto_version/;
34 use MIME::Base64 qw/decode_base64url encode_base64url/;
35 use Socket qw/PF_UNIX SOCK_STREAM SHUT_RDWR/;
36
37 use Config::Tiny ();
38 use JSON ();
39
40 # Clean up PATH
41 $ENV{PATH} = join ':', qw{/usr/bin /bin};
42 delete @ENV{qw/IFS CDPATH ENV BASH_ENV/};
43
44 my ($SOCKNAME, $S, %OPTS);
45 $SIG{$_} = sub() { exit } foreach qw/INT TERM/; # run the END block upon SIGINT/SIGTERM
46
47
48 #############################################################################
49 # Parse and validate configuration
50 #
51 sub usage(;$$) {
52 my $rv = shift // 0;
53 if ($rv) {
54 my $msg = shift;
55 print STDERR $msg."\n" if defined $msg;
56 print STDERR "Try '$NAME --help' or consult the manpage for more information.\n";
57 }
58 else {
59 print STDERR "Usage: $NAME [--config=FILE] [--privkey=ARG] [--socket=PATH] [--quiet]\n"
60 ."Consult the manpage for more information.\n";
61 }
62 exit $rv;
63 }
64 usage(1) unless GetOptions(\%OPTS, qw/config=s privkey=s socket=s stdio quiet|q debug help|h/);
65 usage(0) if $OPTS{help};
66
67 my ($LOG, $LOGLEVEL);
68 my ($LOG_INFO, $LOG_VERBOSE, $LOG_DEBUG) = (0,1,2);
69 sub logmsg($@) {
70 my $lvl = shift;
71 if (defined $LOG and ($lvl <= $LOGLEVEL or $lvl <= $LOG_VERBOSE)) {
72 # --quiet flag hides verbose-level messages from the standard
73 # error but we add them to the logfile nonetheless
74 my $now = localtime;
75 $LOG->printflush("[", $now, "] ", @_, "\n") or warn "print: $!";
76 }
77 if ($lvl <= $LOGLEVEL) {
78 print STDERR @_, "\n" or warn "print: $!";
79 }
80 }
81 sub info(@) { logmsg($LOG_INFO => @_); }
82 sub error(@) {
83 my @msg = ("Error: ", @_);
84 info(@msg);
85 exit 255;
86 }
87 sub panic(@) {
88 my @loc = caller;
89 my @msg = ("PANIC at line $loc[2] in $loc[1]");
90 push @msg, ": ", @_ if @_;
91 info(@msg);
92 exit 255;
93 }
94
95 sub env_fallback($$) {
96 my $v = $ENV{ shift() };
97 return (defined $v and $v ne "") ? $v : shift;
98 }
99 sub spec_expand($) {
100 my $str = shift;
101 $str =~ s#%(.)# my $x =
102 $1 eq "C" ? ($< == 0 ? "@@localstatedir@@/cache" : env_fallback(XDG_CACHE_HOME => "$ENV{HOME}/.cache"))
103 : $1 eq "E" ? ($< == 0 ? "@@sysconfdir@@" : env_fallback(XDG_CONFIG_HOME => "$ENV{HOME}/.config"))
104 : $1 eq "g" ? (getgrgid((split /\s/,$()[0]))[0]
105 : $1 eq "G" ? $( =~ s/\s.*//r
106 : $1 eq "h" ? (getpwuid($<))[7]
107 : $1 eq "u" ? (getpwuid($<))[0]
108 : $1 eq "U" ? $<
109 : $1 eq "t" ? ($< == 0 ? "@@runstatedir@@" : $ENV{XDG_RUNTIME_DIR})
110 : $1 eq "T" ? env_fallback(TMPDIR => "/tmp")
111 : $1 eq "%" ? "%"
112 : error("\"$str\" has unknown specifier %$1");
113 error("Undefined expansion %$1 in \"$str\"") unless defined $x;
114 $x;
115 #ge;
116 return $str;
117 }
118
119 do {
120 my $conffile = spec_expand($OPTS{config} // "%E/lacme/$NAME.conf");
121
122 if (defined $OPTS{config} or -e $conffile) {
123 print STDERR "Using configuration file: $conffile\n" if $OPTS{debug};
124 my $h = Config::Tiny::->read($conffile) or error(Config::Tiny::->errstr());
125 my $h2 = delete $h->{_} // {};
126 if ((my $logfile = $h2->{logfile} // "") ne "") {
127 $logfile = spec_expand($logfile);
128 die "Invalid log file name\n" unless $logfile =~ /\A(\p{Print}+)\z/; # untaint
129 open $LOG, ">>", $1 or die "Can't open $1: $!"; # open ASAP (before config validation)
130 }
131 error("Invalid section(s): ".join(', ', keys %$h)) if %$h;
132 my %h = map { $_ => delete $h2->{$_} } qw/privkey gpg socket logfile keyid quiet/;
133 error("Unknown option(s): ".join(', ', keys %$h2)) if %$h2;
134 $h{quiet} = lc $h{quiet} eq 'yes' ? 1 : 0 if defined $h{quiet};
135 $OPTS{$_} //= $h{$_} foreach grep {defined $h{$_}} keys %h;
136 } else {
137 print STDERR "Ignoring missing configuration file at default location $conffile\n" if $OPTS{debug};
138 }
139
140 $LOGLEVEL = $OPTS{debug} ? $LOG_DEBUG : $OPTS{quiet} ? $LOG_INFO : $LOG_VERBOSE;
141 error("'privkey' is not specified") unless defined $OPTS{privkey};
142 };
143
144
145 #############################################################################
146 # Build the JSON Web Key (RFC 7517) from the account key's public parameters,
147 # and determine the signing method $SIGN.
148 #
149 my ($EXTRA_GREETING_STR, $JWK_STR, $SIGN);
150 if ($OPTS{privkey} =~ /\A(file|gpg):(\p{Print}+)\z/) {
151 my ($method, $filename) = ($1, spec_expand($2));
152 my ($fh, @command);
153 if ($method eq 'file') {
154 # generate with `openssl genpkey -algorithm RSA`
155 open $fh, '<', $filename or error("Can't open $filename: $!");
156 }
157 elsif ($method eq 'gpg') {
158 @command = split /\s+/, ($OPTS{gpg} // 'gpg --quiet');
159 open $fh, '-|', @command, qw/-o - --decrypt --/, $filename or panic("fork: $!");
160 }
161 else {
162 panic(); # impossible
163 }
164
165 my $str = do {local $/ = undef; <$fh>};
166 close $fh or ($! or !@command) ?
167 panic("close: $!") :
168 error("$command[0] exited with value ".($? >> 8));
169
170 require 'Crypt/OpenSSL/RSA.pm';
171 my $rsa = Crypt::OpenSSL::RSA->new_private_key($str);
172 undef $str;
173
174 error("$filename: Not a private key") unless $rsa->is_private();
175 error("$filename: Invalid key") unless $rsa->check_key();
176 $rsa->use_sha256_hash();
177 $rsa->use_pkcs1_padding(); # JWT RS256 uses PKCS#1 v1.5 signatures
178
179 require 'Crypt/OpenSSL/Bignum.pm';
180 my ($n, $e) = $rsa->get_key_parameters(); # don't include private params!
181 $_ = encode_base64url($_->to_bin()) foreach ($n, $e);
182
183 my %extra_greeting;
184 my %jwk = ( kty => 'RSA', n => $n, e => $e );
185 $extra_greeting{alg} = 'RS256'; # SHA256withRSA (RFC 7518 sec. A.1)
186 $SIGN = sub($) { $rsa->sign($_[0]) };
187
188 # use of SHA-256 digest in the thumbprint is hardcoded, see RFC 8555 sec. 8.1
189 $JWK_STR = JSON::->new->utf8->canonical->encode(\%jwk);
190 $extra_greeting{"jwk-thumbprint"} = encode_base64url(sha256($JWK_STR));
191
192 if ((my $kid = $OPTS{keyid} // "") ne "") {
193 $extra_greeting{kid} = $kid;
194 $JWK_STR = "{}";
195 }
196 $EXTRA_GREETING_STR = JSON::->new->encode(\%extra_greeting);
197 }
198 else {
199 error("Unsupported method: $OPTS{privkey}");
200 }
201
202
203 #############################################################################
204 # Create the server UNIX socket and bind(2) against it.
205 # NOTE: We don't use the abstract namespace so we can rely on the file
206 # permissions to keep other users out. (Also, OpenSSH 7.1 doesn't seem
207 # to support the abstract namespace.) The downside is that we have to
208 # delete the file manually.
209 #
210 unless (defined $OPTS{stdio}) {
211 my $sockname = spec_expand($OPTS{socket} // '%t/S.lacme');
212 $sockname = $sockname =~ /\A(\p{Print}+)\z/ ? $1 : error("Invalid socket name"); # untaint
213
214 # ensure we're the only user with write access to the parent dir
215 my $dirname = dirname($sockname);
216 my @stat = stat($dirname) or error("stat($dirname): $!");
217 error("Insecure permissions on $dirname") if ($stat[2] & 0022) != 0;
218
219 my $umask = umask(0177) // panic();
220
221 logmsg($LOG_VERBOSE => "Starting lacme Account Key Manager at $sockname");
222 socket(my $sock, PF_UNIX, SOCK_STREAM, 0) or panic("socket: $!");
223 my $sockaddr = Socket::sockaddr_un($sockname) // panic();
224 bind($sock, $sockaddr) or panic("bind: $!");
225
226 ($SOCKNAME, $S) = ($sockname, $sock);
227 listen($S, 1) or panic("listen: $!");
228
229 umask($umask) // panic();
230 };
231
232
233 #############################################################################
234 # For each new connection, send the protocol version and the account key's
235 # public parameters, then sign whatever comes in
236 #
237 sub conn($$$) {
238 my ($in, $out, $id) = @_;
239 $out->printflush( "$PROTOCOL_VERSION OK ", $EXTRA_GREETING_STR, "\r\n",
240 $JWK_STR, "\r\n" ) or warn "print: $!";
241
242 while (defined (my $data = $in->getline())) {
243 $data =~ s/\r\n\z// or panic();
244
245 # validate JWS Signing Input from RFC 7515:
246 # ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload))
247 my ($header, $payload) = split(/\./, $data, 2);
248 if (defined $header and $header =~ /\A[A-Za-z0-9\-_]+\z/) {
249 $header = decode_base64url($header);
250 } else {
251 info("[$id] NOSIGN [malformed JWS Protected Header]");
252 last;
253 }
254 if (defined $payload and $payload =~ /\A[A-Za-z0-9\-_]*\z/) {
255 # empty payloads are valid, and used for POST-as-GET (RFC 8555 sec. 6.3)
256 $payload = decode_base64url($payload);
257 } else {
258 info("[$id] NOSIGN [malformed JWS Payload]");
259 last;
260 }
261
262 my $req = "header=base64url($header) playload=base64url($payload)";
263
264 eval { $header = JSON::->new->decode($header); };
265 if ($@ or # couldn't decode (parse error)
266 # RFC 7515: not a JSON object
267 !defined($header) or ref($header) ne "HASH" or
268 # RFC 8555 sec. 6.2: the protected Header MUST include all these fields
269 grep !defined, @$header{qw/alg nonce url/} or
270 # RFC 8555 sec. 6.2: the protected header MUST include any of these fields
271 !grep defined, @$header{qw/jwk kid/}) {
272 info("[$id] NOSIGN [invalid JWS Protected Header] ", $req);
273 last;
274 }
275
276 my $sig = eval { $SIGN->($data) };
277 panic($@) if $@ or !defined $sig;
278 logmsg($LOG_VERBOSE => "[$id] SIGNED ", $req);
279 $out->printflush( encode_base64url($sig), "\r\n" ) or warn "print: $!";
280 }
281 }
282
283 if (defined $OPTS{stdio}) {
284 conn(\*STDIN, \*STDOUT, $$);
285 } else {
286 $SIG{PIPE} = 'IGNORE'; # ignore broken pipes
287 for (my $count = 0;; $count++) {
288 accept(my $conn, $S) or do {
289 next if $! == EINTR; # try again if accept(2) was interrupted by a signal
290 panic("accept: $!");
291 };
292 logmsg($LOG_VERBOSE => "[$count] Accepted new connection");
293 conn($conn, $conn, $count);
294 logmsg($LOG_VERBOSE => "[$count] Connection terminated");
295 $conn->close() or warn "close: $!";
296 }
297 }
298
299
300 #############################################################################
301 #
302 END {
303 if (defined $SOCKNAME and -S $SOCKNAME) {
304 logmsg($LOG_DEBUG => "Unlinking $SOCKNAME");
305 unlink $SOCKNAME or info("Error: unlink($SOCKNAME): $!");
306 }
307 if (defined $S) {
308 logmsg($LOG_VERBOSE => "Shutting down and closing lacme Account Key Manager");
309 shutdown($S, SHUT_RDWR) or info("Error: shutdown: $!");
310 close $S or info("Error: close: $!");
311 }
312 }