]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/auth2-pubkey.c
zfs: merge openzfs/zfs@39be46f43
[FreeBSD/FreeBSD.git] / crypto / openssh / auth2-pubkey.c
1 /* $OpenBSD: auth2-pubkey.c,v 1.119 2023/07/27 22:25:17 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2010 Damien Miller.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "includes.h"
28
29 #include <sys/types.h>
30
31 #include <stdlib.h>
32 #include <errno.h>
33 #ifdef HAVE_PATHS_H
34 # include <paths.h>
35 #endif
36 #include <pwd.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <string.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <limits.h>
44
45 #include "xmalloc.h"
46 #include "ssh.h"
47 #include "ssh2.h"
48 #include "packet.h"
49 #include "kex.h"
50 #include "sshbuf.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "servconf.h"
54 #include "compat.h"
55 #include "sshkey.h"
56 #include "hostfile.h"
57 #include "auth.h"
58 #include "pathnames.h"
59 #include "uidswap.h"
60 #include "auth-options.h"
61 #include "canohost.h"
62 #ifdef GSSAPI
63 #include "ssh-gss.h"
64 #endif
65 #include "monitor_wrap.h"
66 #include "authfile.h"
67 #include "match.h"
68 #include "ssherr.h"
69 #include "channels.h" /* XXX for session.h */
70 #include "session.h" /* XXX for child_set_env(); refactor? */
71 #include "sk-api.h"
72
73 /* import */
74 extern ServerOptions options;
75
76 static char *
77 format_key(const struct sshkey *key)
78 {
79         char *ret, *fp = sshkey_fingerprint(key,
80             options.fingerprint_hash, SSH_FP_DEFAULT);
81
82         xasprintf(&ret, "%s %s", sshkey_type(key), fp);
83         free(fp);
84         return ret;
85 }
86
87 static int
88 userauth_pubkey(struct ssh *ssh, const char *method)
89 {
90         Authctxt *authctxt = ssh->authctxt;
91         struct passwd *pw = authctxt->pw;
92         struct sshbuf *b = NULL;
93         struct sshkey *key = NULL, *hostkey = NULL;
94         char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
95         u_char *pkblob = NULL, *sig = NULL, have_sig;
96         size_t blen, slen;
97         int hostbound, r, pktype;
98         int req_presence = 0, req_verify = 0, authenticated = 0;
99         struct sshauthopt *authopts = NULL;
100         struct sshkey_sig_details *sig_details = NULL;
101
102         hostbound = strcmp(method, "publickey-hostbound-v00@openssh.com") == 0;
103
104         if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
105             (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
106             (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
107                 fatal_fr(r, "parse %s packet", method);
108
109         /* hostbound auth includes the hostkey offered at initial KEX */
110         if (hostbound) {
111                 if ((r = sshpkt_getb_froms(ssh, &b)) != 0 ||
112                     (r = sshkey_fromb(b, &hostkey)) != 0)
113                         fatal_fr(r, "parse %s hostkey", method);
114                 if (ssh->kex->initial_hostkey == NULL)
115                         fatal_f("internal error: initial hostkey not recorded");
116                 if (!sshkey_equal(hostkey, ssh->kex->initial_hostkey))
117                         fatal_f("%s packet contained wrong host key", method);
118                 sshbuf_free(b);
119                 b = NULL;
120         }
121
122         if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
123                 char *keystring;
124                 struct sshbuf *pkbuf;
125
126                 if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
127                         fatal_f("sshbuf_from failed");
128                 if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
129                         fatal_f("sshbuf_dtob64 failed");
130                 debug2_f("%s user %s %s public key %s %s",
131                     authctxt->valid ? "valid" : "invalid", authctxt->user,
132                     have_sig ? "attempting" : "querying", pkalg, keystring);
133                 sshbuf_free(pkbuf);
134                 free(keystring);
135         }
136
137         pktype = sshkey_type_from_name(pkalg);
138         if (pktype == KEY_UNSPEC) {
139                 /* this is perfectly legal */
140                 verbose_f("unsupported public key algorithm: %s", pkalg);
141                 goto done;
142         }
143         if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
144                 error_fr(r, "parse key");
145                 goto done;
146         }
147         if (key == NULL) {
148                 error_f("cannot decode key: %s", pkalg);
149                 goto done;
150         }
151         if (key->type != pktype) {
152                 error_f("type mismatch for decoded key "
153                     "(received %d, expected %d)", key->type, pktype);
154                 goto done;
155         }
156         if (auth2_key_already_used(authctxt, key)) {
157                 logit("refusing previously-used %s key", sshkey_type(key));
158                 goto done;
159         }
160         if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
161                 logit_f("signature algorithm %s not in "
162                     "PubkeyAcceptedAlgorithms", pkalg);
163                 goto done;
164         }
165         if ((r = sshkey_check_cert_sigtype(key,
166             options.ca_sign_algorithms)) != 0) {
167                 logit_fr(r, "certificate signature algorithm %s",
168                     (key->cert == NULL || key->cert->signature_type == NULL) ?
169                     "(null)" : key->cert->signature_type);
170                 goto done;
171         }
172         if ((r = sshkey_check_rsa_length(key,
173             options.required_rsa_size)) != 0) {
174                 logit_r(r, "refusing %s key", sshkey_type(key));
175                 goto done;
176         }
177         key_s = format_key(key);
178         if (sshkey_is_cert(key))
179                 ca_s = format_key(key->cert->signature_key);
180
181         if (have_sig) {
182                 debug3_f("%s have %s signature for %s%s%s",
183                     method, pkalg, key_s,
184                     ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
185                 if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
186                     (r = sshpkt_get_end(ssh)) != 0)
187                         fatal_fr(r, "parse signature packet");
188                 if ((b = sshbuf_new()) == NULL)
189                         fatal_f("sshbuf_new failed");
190                 if (ssh->compat & SSH_OLD_SESSIONID) {
191                         if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
192                                 fatal_fr(r, "put old session id");
193                 } else {
194                         if ((r = sshbuf_put_stringb(b,
195                             ssh->kex->session_id)) != 0)
196                                 fatal_fr(r, "put session id");
197                 }
198                 if (!authctxt->valid || authctxt->user == NULL) {
199                         debug2_f("disabled because of invalid user");
200                         goto done;
201                 }
202                 /* reconstruct packet */
203                 xasprintf(&userstyle, "%s%s%s", authctxt->user,
204                     authctxt->style ? ":" : "",
205                     authctxt->style ? authctxt->style : "");
206                 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
207                     (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
208                     (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
209                     (r = sshbuf_put_cstring(b, method)) != 0 ||
210                     (r = sshbuf_put_u8(b, have_sig)) != 0 ||
211                     (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
212                     (r = sshbuf_put_string(b, pkblob, blen)) != 0)
213                         fatal_fr(r, "reconstruct %s packet", method);
214                 if (hostbound &&
215                     (r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
216                         fatal_fr(r, "reconstruct %s packet", method);
217 #ifdef DEBUG_PK
218                 sshbuf_dump(b, stderr);
219 #endif
220                 /* test for correct signature */
221                 authenticated = 0;
222                 if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
223                     PRIVSEP(sshkey_verify(key, sig, slen,
224                     sshbuf_ptr(b), sshbuf_len(b),
225                     (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
226                     ssh->compat, &sig_details)) == 0) {
227                         authenticated = 1;
228                 }
229                 if (authenticated == 1 && sig_details != NULL) {
230                         auth2_record_info(authctxt, "signature count = %u",
231                             sig_details->sk_counter);
232                         debug_f("sk_counter = %u, sk_flags = 0x%02x",
233                             sig_details->sk_counter, sig_details->sk_flags);
234                         req_presence = (options.pubkey_auth_options &
235                             PUBKEYAUTH_TOUCH_REQUIRED) ||
236                             !authopts->no_require_user_presence;
237                         if (req_presence && (sig_details->sk_flags &
238                             SSH_SK_USER_PRESENCE_REQD) == 0) {
239                                 error("public key %s signature for %s%s from "
240                                     "%.128s port %d rejected: user presence "
241                                     "(authenticator touch) requirement "
242                                     "not met ", key_s,
243                                     authctxt->valid ? "" : "invalid user ",
244                                     authctxt->user, ssh_remote_ipaddr(ssh),
245                                     ssh_remote_port(ssh));
246                                 authenticated = 0;
247                                 goto done;
248                         }
249                         req_verify = (options.pubkey_auth_options &
250                             PUBKEYAUTH_VERIFY_REQUIRED) ||
251                             authopts->require_verify;
252                         if (req_verify && (sig_details->sk_flags &
253                             SSH_SK_USER_VERIFICATION_REQD) == 0) {
254                                 error("public key %s signature for %s%s from "
255                                     "%.128s port %d rejected: user "
256                                     "verification requirement not met ", key_s,
257                                     authctxt->valid ? "" : "invalid user ",
258                                     authctxt->user, ssh_remote_ipaddr(ssh),
259                                     ssh_remote_port(ssh));
260                                 authenticated = 0;
261                                 goto done;
262                         }
263                 }
264                 auth2_record_key(authctxt, authenticated, key);
265         } else {
266                 debug_f("%s test pkalg %s pkblob %s%s%s", method, pkalg, key_s,
267                     ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
268
269                 if ((r = sshpkt_get_end(ssh)) != 0)
270                         fatal_fr(r, "parse packet");
271
272                 if (!authctxt->valid || authctxt->user == NULL) {
273                         debug2_f("disabled because of invalid user");
274                         goto done;
275                 }
276                 /* XXX fake reply and always send PK_OK ? */
277                 /*
278                  * XXX this allows testing whether a user is allowed
279                  * to login: if you happen to have a valid pubkey this
280                  * message is sent. the message is NEVER sent at all
281                  * if a user is not allowed to login. is this an
282                  * issue? -markus
283                  */
284                 if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
285                         if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
286                             != 0 ||
287                             (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
288                             (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
289                             (r = sshpkt_send(ssh)) != 0 ||
290                             (r = ssh_packet_write_wait(ssh)) != 0)
291                                 fatal_fr(r, "send packet");
292                         authctxt->postponed = 1;
293                 }
294         }
295 done:
296         if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
297                 debug_f("key options inconsistent with existing");
298                 authenticated = 0;
299         }
300         debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
301
302         sshbuf_free(b);
303         sshauthopt_free(authopts);
304         sshkey_free(key);
305         sshkey_free(hostkey);
306         free(userstyle);
307         free(pkalg);
308         free(pkblob);
309         free(key_s);
310         free(ca_s);
311         free(sig);
312         sshkey_sig_details_free(sig_details);
313         return authenticated;
314 }
315
316 static int
317 match_principals_file(struct passwd *pw, char *file,
318     struct sshkey_cert *cert, struct sshauthopt **authoptsp)
319 {
320         FILE *f;
321         int success;
322
323         if (authoptsp != NULL)
324                 *authoptsp = NULL;
325
326         temporarily_use_uid(pw);
327         debug("trying authorized principals file %s", file);
328         if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
329                 restore_uid();
330                 return 0;
331         }
332         success = auth_process_principals(f, file, cert, authoptsp);
333         fclose(f);
334         restore_uid();
335         return success;
336 }
337
338 /*
339  * Checks whether principal is allowed in output of command.
340  * returns 1 if the principal is allowed or 0 otherwise.
341  */
342 static int
343 match_principals_command(struct passwd *user_pw, const struct sshkey *key,
344     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
345 {
346         struct passwd *runas_pw = NULL;
347         const struct sshkey_cert *cert = key->cert;
348         FILE *f = NULL;
349         int r, ok, found_principal = 0;
350         int i, ac = 0, uid_swapped = 0;
351         pid_t pid;
352         char *tmp, *username = NULL, *command = NULL, **av = NULL;
353         char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
354         char serial_s[32], uidstr[32];
355         void (*osigchld)(int);
356
357         if (authoptsp != NULL)
358                 *authoptsp = NULL;
359         if (options.authorized_principals_command == NULL)
360                 return 0;
361         if (options.authorized_principals_command_user == NULL) {
362                 error("No user for AuthorizedPrincipalsCommand specified, "
363                     "skipping");
364                 return 0;
365         }
366
367         /*
368          * NB. all returns later this function should go via "out" to
369          * ensure the original SIGCHLD handler is restored properly.
370          */
371         osigchld = ssh_signal(SIGCHLD, SIG_DFL);
372
373         /* Prepare and verify the user for the command */
374         username = percent_expand(options.authorized_principals_command_user,
375             "u", user_pw->pw_name, (char *)NULL);
376         runas_pw = getpwnam(username);
377         if (runas_pw == NULL) {
378                 error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
379                     username, strerror(errno));
380                 goto out;
381         }
382
383         /* Turn the command into an argument vector */
384         if (argv_split(options.authorized_principals_command,
385             &ac, &av, 0) != 0) {
386                 error("AuthorizedPrincipalsCommand \"%s\" contains "
387                     "invalid quotes", options.authorized_principals_command);
388                 goto out;
389         }
390         if (ac == 0) {
391                 error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
392                     options.authorized_principals_command);
393                 goto out;
394         }
395         if ((ca_fp = sshkey_fingerprint(cert->signature_key,
396             options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
397                 error_f("sshkey_fingerprint failed");
398                 goto out;
399         }
400         if ((key_fp = sshkey_fingerprint(key,
401             options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
402                 error_f("sshkey_fingerprint failed");
403                 goto out;
404         }
405         if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
406                 error_fr(r, "sshkey_to_base64 failed");
407                 goto out;
408         }
409         if ((r = sshkey_to_base64(key, &keytext)) != 0) {
410                 error_fr(r, "sshkey_to_base64 failed");
411                 goto out;
412         }
413         snprintf(serial_s, sizeof(serial_s), "%llu",
414             (unsigned long long)cert->serial);
415         snprintf(uidstr, sizeof(uidstr), "%llu",
416             (unsigned long long)user_pw->pw_uid);
417         for (i = 1; i < ac; i++) {
418                 tmp = percent_expand(av[i],
419                     "C", conn_id,
420                     "D", rdomain,
421                     "U", uidstr,
422                     "u", user_pw->pw_name,
423                     "h", user_pw->pw_dir,
424                     "t", sshkey_ssh_name(key),
425                     "T", sshkey_ssh_name(cert->signature_key),
426                     "f", key_fp,
427                     "F", ca_fp,
428                     "k", keytext,
429                     "K", catext,
430                     "i", cert->key_id,
431                     "s", serial_s,
432                     (char *)NULL);
433                 if (tmp == NULL)
434                         fatal_f("percent_expand failed");
435                 free(av[i]);
436                 av[i] = tmp;
437         }
438         /* Prepare a printable command for logs, etc. */
439         command = argv_assemble(ac, av);
440
441         if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
442             ac, av, &f,
443             SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
444             runas_pw, temporarily_use_uid, restore_uid)) == 0)
445                 goto out;
446
447         uid_swapped = 1;
448         temporarily_use_uid(runas_pw);
449
450         ok = auth_process_principals(f, "(command)", cert, authoptsp);
451
452         fclose(f);
453         f = NULL;
454
455         if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
456                 goto out;
457
458         /* Read completed successfully */
459         found_principal = ok;
460  out:
461         if (f != NULL)
462                 fclose(f);
463         ssh_signal(SIGCHLD, osigchld);
464         for (i = 0; i < ac; i++)
465                 free(av[i]);
466         free(av);
467         if (uid_swapped)
468                 restore_uid();
469         free(command);
470         free(username);
471         free(ca_fp);
472         free(key_fp);
473         free(catext);
474         free(keytext);
475         return found_principal;
476 }
477
478 /* Authenticate a certificate key against TrustedUserCAKeys */
479 static int
480 user_cert_trusted_ca(struct passwd *pw, struct sshkey *key,
481     const char *remote_ip, const char *remote_host,
482     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
483 {
484         char *ca_fp, *principals_file = NULL;
485         const char *reason;
486         struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
487         struct sshauthopt *final_opts = NULL;
488         int r, ret = 0, found_principal = 0, use_authorized_principals;
489
490         if (authoptsp != NULL)
491                 *authoptsp = NULL;
492
493         if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
494                 return 0;
495
496         if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
497             options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
498                 return 0;
499
500         if ((r = sshkey_in_file(key->cert->signature_key,
501             options.trusted_user_ca_keys, 1, 0)) != 0) {
502                 debug2_fr(r, "CA %s %s is not listed in %s",
503                     sshkey_type(key->cert->signature_key), ca_fp,
504                     options.trusted_user_ca_keys);
505                 goto out;
506         }
507         /*
508          * If AuthorizedPrincipals is in use, then compare the certificate
509          * principals against the names in that file rather than matching
510          * against the username.
511          */
512         if ((principals_file = authorized_principals_file(pw)) != NULL) {
513                 if (match_principals_file(pw, principals_file,
514                     key->cert, &principals_opts))
515                         found_principal = 1;
516         }
517         /* Try querying command if specified */
518         if (!found_principal && match_principals_command(pw, key,
519             conn_id, rdomain, &principals_opts))
520                 found_principal = 1;
521         /* If principals file or command is specified, then require a match */
522         use_authorized_principals = principals_file != NULL ||
523             options.authorized_principals_command != NULL;
524         if (!found_principal && use_authorized_principals) {
525                 reason = "Certificate does not contain an authorized principal";
526                 goto fail_reason;
527         }
528         if (use_authorized_principals && principals_opts == NULL)
529                 fatal_f("internal error: missing principals_opts");
530         if (sshkey_cert_check_authority_now(key, 0, 1, 0,
531             use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
532                 goto fail_reason;
533
534         /* Check authority from options in key and from principals file/cmd */
535         if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
536                 reason = "Invalid certificate options";
537                 goto fail_reason;
538         }
539         if (auth_authorise_keyopts(pw, cert_opts, 0,
540             remote_ip, remote_host, "cert") != 0) {
541                 reason = "Refused by certificate options";
542                 goto fail_reason;
543         }
544         if (principals_opts == NULL) {
545                 final_opts = cert_opts;
546                 cert_opts = NULL;
547         } else {
548                 if (auth_authorise_keyopts(pw, principals_opts, 0,
549                     remote_ip, remote_host, "principals") != 0) {
550                         reason = "Refused by certificate principals options";
551                         goto fail_reason;
552                 }
553                 if ((final_opts = sshauthopt_merge(principals_opts,
554                     cert_opts, &reason)) == NULL) {
555  fail_reason:
556                         error("%s", reason);
557                         auth_debug_add("%s", reason);
558                         goto out;
559                 }
560         }
561
562         /* Success */
563         verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
564             "%s CA %s via %s", key->cert->key_id,
565             (unsigned long long)key->cert->serial,
566             sshkey_type(key->cert->signature_key), ca_fp,
567             options.trusted_user_ca_keys);
568         if (authoptsp != NULL) {
569                 *authoptsp = final_opts;
570                 final_opts = NULL;
571         }
572         ret = 1;
573  out:
574         sshauthopt_free(principals_opts);
575         sshauthopt_free(cert_opts);
576         sshauthopt_free(final_opts);
577         free(principals_file);
578         free(ca_fp);
579         return ret;
580 }
581
582 /*
583  * Checks whether key is allowed in file.
584  * returns 1 if the key is allowed or 0 otherwise.
585  */
586 static int
587 user_key_allowed2(struct passwd *pw, struct sshkey *key,
588     char *file, const char *remote_ip, const char *remote_host,
589     struct sshauthopt **authoptsp)
590 {
591         FILE *f;
592         int found_key = 0;
593
594         if (authoptsp != NULL)
595                 *authoptsp = NULL;
596
597         /* Temporarily use the user's uid. */
598         temporarily_use_uid(pw);
599
600         debug("trying public key file %s", file);
601         if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
602                 found_key = auth_check_authkeys_file(pw, f, file,
603                     key, remote_ip, remote_host, authoptsp);
604                 fclose(f);
605         }
606
607         restore_uid();
608         return found_key;
609 }
610
611 /*
612  * Checks whether key is allowed in output of command.
613  * returns 1 if the key is allowed or 0 otherwise.
614  */
615 static int
616 user_key_command_allowed2(struct passwd *user_pw, struct sshkey *key,
617     const char *remote_ip, const char *remote_host,
618     const char *conn_id, const char *rdomain, struct sshauthopt **authoptsp)
619 {
620         struct passwd *runas_pw = NULL;
621         FILE *f = NULL;
622         int r, ok, found_key = 0;
623         int i, uid_swapped = 0, ac = 0;
624         pid_t pid;
625         char *username = NULL, *key_fp = NULL, *keytext = NULL;
626         char uidstr[32], *tmp, *command = NULL, **av = NULL;
627         void (*osigchld)(int);
628
629         if (authoptsp != NULL)
630                 *authoptsp = NULL;
631         if (options.authorized_keys_command == NULL)
632                 return 0;
633         if (options.authorized_keys_command_user == NULL) {
634                 error("No user for AuthorizedKeysCommand specified, skipping");
635                 return 0;
636         }
637
638         /*
639          * NB. all returns later this function should go via "out" to
640          * ensure the original SIGCHLD handler is restored properly.
641          */
642         osigchld = ssh_signal(SIGCHLD, SIG_DFL);
643
644         /* Prepare and verify the user for the command */
645         username = percent_expand(options.authorized_keys_command_user,
646             "u", user_pw->pw_name, (char *)NULL);
647         runas_pw = getpwnam(username);
648         if (runas_pw == NULL) {
649                 error("AuthorizedKeysCommandUser \"%s\" not found: %s",
650                     username, strerror(errno));
651                 goto out;
652         }
653
654         /* Prepare AuthorizedKeysCommand */
655         if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
656             SSH_FP_DEFAULT)) == NULL) {
657                 error_f("sshkey_fingerprint failed");
658                 goto out;
659         }
660         if ((r = sshkey_to_base64(key, &keytext)) != 0) {
661                 error_fr(r, "sshkey_to_base64 failed");
662                 goto out;
663         }
664
665         /* Turn the command into an argument vector */
666         if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
667                 error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
668                     options.authorized_keys_command);
669                 goto out;
670         }
671         if (ac == 0) {
672                 error("AuthorizedKeysCommand \"%s\" yielded no arguments",
673                     options.authorized_keys_command);
674                 goto out;
675         }
676         snprintf(uidstr, sizeof(uidstr), "%llu",
677             (unsigned long long)user_pw->pw_uid);
678         for (i = 1; i < ac; i++) {
679                 tmp = percent_expand(av[i],
680                     "C", conn_id,
681                     "D", rdomain,
682                     "U", uidstr,
683                     "u", user_pw->pw_name,
684                     "h", user_pw->pw_dir,
685                     "t", sshkey_ssh_name(key),
686                     "f", key_fp,
687                     "k", keytext,
688                     (char *)NULL);
689                 if (tmp == NULL)
690                         fatal_f("percent_expand failed");
691                 free(av[i]);
692                 av[i] = tmp;
693         }
694         /* Prepare a printable command for logs, etc. */
695         command = argv_assemble(ac, av);
696
697         /*
698          * If AuthorizedKeysCommand was run without arguments
699          * then fall back to the old behaviour of passing the
700          * target username as a single argument.
701          */
702         if (ac == 1) {
703                 av = xreallocarray(av, ac + 2, sizeof(*av));
704                 av[1] = xstrdup(user_pw->pw_name);
705                 av[2] = NULL;
706                 /* Fix up command too, since it is used in log messages */
707                 free(command);
708                 xasprintf(&command, "%s %s", av[0], av[1]);
709         }
710
711         if ((pid = subprocess("AuthorizedKeysCommand", command,
712             ac, av, &f,
713             SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
714             runas_pw, temporarily_use_uid, restore_uid)) == 0)
715                 goto out;
716
717         uid_swapped = 1;
718         temporarily_use_uid(runas_pw);
719
720         ok = auth_check_authkeys_file(user_pw, f,
721             options.authorized_keys_command, key, remote_ip,
722             remote_host, authoptsp);
723
724         fclose(f);
725         f = NULL;
726
727         if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
728                 goto out;
729
730         /* Read completed successfully */
731         found_key = ok;
732  out:
733         if (f != NULL)
734                 fclose(f);
735         ssh_signal(SIGCHLD, osigchld);
736         for (i = 0; i < ac; i++)
737                 free(av[i]);
738         free(av);
739         if (uid_swapped)
740                 restore_uid();
741         free(command);
742         free(username);
743         free(key_fp);
744         free(keytext);
745         return found_key;
746 }
747
748 /*
749  * Check whether key authenticates and authorises the user.
750  */
751 int
752 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
753     int auth_attempt, struct sshauthopt **authoptsp)
754 {
755         u_int success = 0, i;
756         char *file, *conn_id;
757         struct sshauthopt *opts = NULL;
758         const char *rdomain, *remote_ip, *remote_host;
759
760         if (authoptsp != NULL)
761                 *authoptsp = NULL;
762
763         if (auth_key_is_revoked(key))
764                 return 0;
765         if (sshkey_is_cert(key) &&
766             auth_key_is_revoked(key->cert->signature_key))
767                 return 0;
768
769         if ((rdomain = ssh_packet_rdomain_in(ssh)) == NULL)
770                 rdomain = "";
771         remote_ip = ssh_remote_ipaddr(ssh);
772         remote_host = auth_get_canonical_hostname(ssh, options.use_dns);
773         xasprintf(&conn_id, "%s %d %s %d",
774             ssh_local_ipaddr(ssh), ssh_local_port(ssh),
775             remote_ip, ssh_remote_port(ssh));
776
777         for (i = 0; !success && i < options.num_authkeys_files; i++) {
778                 if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
779                         continue;
780                 file = expand_authorized_keys(
781                     options.authorized_keys_files[i], pw);
782                 success = user_key_allowed2(pw, key, file,
783                     remote_ip, remote_host, &opts);
784                 free(file);
785                 if (!success) {
786                         sshauthopt_free(opts);
787                         opts = NULL;
788                 }
789         }
790         if (success)
791                 goto out;
792
793         if ((success = user_cert_trusted_ca(pw, key, remote_ip, remote_host,
794             conn_id, rdomain, &opts)) != 0)
795                 goto out;
796         sshauthopt_free(opts);
797         opts = NULL;
798
799         if ((success = user_key_command_allowed2(pw, key, remote_ip,
800             remote_host, conn_id, rdomain, &opts)) != 0)
801                 goto out;
802         sshauthopt_free(opts);
803         opts = NULL;
804
805  out:
806         free(conn_id);
807         if (success && authoptsp != NULL) {
808                 *authoptsp = opts;
809                 opts = NULL;
810         }
811         sshauthopt_free(opts);
812         return success;
813 }
814
815 Authmethod method_pubkey = {
816         "publickey",
817         "publickey-hostbound-v00@openssh.com",
818         userauth_pubkey,
819         &options.pubkey_authentication
820 };