1 /* $OpenBSD: auth2-pubkey.c,v 1.109 2021/07/23 03:37:52 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26 #include "includes.h"
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #ifdef HAVE_PATHS_H
35 # include <paths.h>
36 #endif
37 #include <pwd.h>
38 #include <signal.h>
39 #include <stdio.h>
40 #include <stdarg.h>
41 #include <string.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <limits.h>
45
46 #include "xmalloc.h"
47 #include "ssh.h"
48 #include "ssh2.h"
49 #include "packet.h"
50 #include "kex.h"
51 #include "sshbuf.h"
52 #include "log.h"
53 #include "misc.h"
54 #include "servconf.h"
55 #include "compat.h"
56 #include "sshkey.h"
57 #include "hostfile.h"
58 #include "auth.h"
59 #include "pathnames.h"
60 #include "uidswap.h"
61 #include "auth-options.h"
62 #include "canohost.h"
63 #ifdef GSSAPI
64 #include "ssh-gss.h"
65 #endif
66 #include "monitor_wrap.h"
67 #include "authfile.h"
68 #include "match.h"
69 #include "ssherr.h"
70 #include "channels.h" /* XXX for session.h */
71 #include "session.h" /* XXX for child_set_env(); refactor? */
72 #include "sk-api.h"
73
74 /* import */
75 extern ServerOptions options;
76
77 static char *
format_key(const struct sshkey * key)78 format_key(const struct sshkey *key)
79 {
80 char *ret, *fp = sshkey_fingerprint(key,
81 options.fingerprint_hash, SSH_FP_DEFAULT);
82
83 xasprintf(&ret, "%s %s", sshkey_type(key), fp);
84 free(fp);
85 return ret;
86 }
87
88 static int
userauth_pubkey(struct ssh * ssh)89 userauth_pubkey(struct ssh *ssh)
90 {
91 Authctxt *authctxt = ssh->authctxt;
92 struct passwd *pw = authctxt->pw;
93 struct sshbuf *b = NULL;
94 struct sshkey *key = NULL;
95 char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
96 u_char *pkblob = NULL, *sig = NULL, have_sig;
97 size_t blen, slen;
98 int r, pktype;
99 int req_presence = 0, req_verify = 0, authenticated = 0;
100 struct sshauthopt *authopts = NULL;
101 struct sshkey_sig_details *sig_details = NULL;
102
103 if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
104 (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
105 (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
106 fatal_fr(r, "parse packet");
107
108 if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
109 char *keystring;
110 struct sshbuf *pkbuf;
111
112 if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
113 fatal_f("sshbuf_from failed");
114 if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
115 fatal_f("sshbuf_dtob64 failed");
116 debug2_f("%s user %s %s public key %s %s",
117 authctxt->valid ? "valid" : "invalid", authctxt->user,
118 have_sig ? "attempting" : "querying", pkalg, keystring);
119 sshbuf_free(pkbuf);
120 free(keystring);
121 }
122
123 pktype = sshkey_type_from_name(pkalg);
124 if (pktype == KEY_UNSPEC) {
125 /* this is perfectly legal */
126 verbose_f("unsupported public key algorithm: %s", pkalg);
127 goto done;
128 }
129 if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
130 error_fr(r, "parse key");
131 goto done;
132 }
133 if (key == NULL) {
134 error_f("cannot decode key: %s", pkalg);
135 goto done;
136 }
137 if (key->type != pktype) {
138 error_f("type mismatch for decoded key "
139 "(received %d, expected %d)", key->type, pktype);
140 goto done;
141 }
142 if (sshkey_type_plain(key->type) == KEY_RSA &&
143 (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
144 logit("Refusing RSA key because client uses unsafe "
145 "signature scheme");
146 goto done;
147 }
148 if (auth2_key_already_used(authctxt, key)) {
149 logit("refusing previously-used %s key", sshkey_type(key));
150 goto done;
151 }
152 if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
153 logit_f("key type %s not in PubkeyAcceptedAlgorithms",
154 sshkey_ssh_name(key));
155 goto done;
156 }
157 if ((r = sshkey_check_cert_sigtype(key,
158 options.ca_sign_algorithms)) != 0) {
159 logit_fr(r, "certificate signature algorithm %s",
160 (key->cert == NULL || key->cert->signature_type == NULL) ?
161 "(null)" : key->cert->signature_type);
162 goto done;
163 }
164 key_s = format_key(key);
165 if (sshkey_is_cert(key))
166 ca_s = format_key(key->cert->signature_key);
167
168 if (have_sig) {
169 debug3_f("have %s signature for %s%s%s", pkalg, key_s,
170 ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
171 if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
172 (r = sshpkt_get_end(ssh)) != 0)
173 fatal_fr(r, "parse signature packet");
174 if ((b = sshbuf_new()) == NULL)
175 fatal_f("sshbuf_new failed");
176 if (ssh->compat & SSH_OLD_SESSIONID) {
177 if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
178 fatal_fr(r, "put old session id");
179 } else {
180 if ((r = sshbuf_put_stringb(b,
181 ssh->kex->session_id)) != 0)
182 fatal_fr(r, "put session id");
183 }
184 if (!authctxt->valid || authctxt->user == NULL) {
185 debug2_f("disabled because of invalid user");
186 goto done;
187 }
188 /* reconstruct packet */
189 xasprintf(&userstyle, "%s%s%s", authctxt->user,
190 authctxt->style ? ":" : "",
191 authctxt->style ? authctxt->style : "");
192 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
193 (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
194 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
195 (r = sshbuf_put_cstring(b, "publickey")) != 0 ||
196 (r = sshbuf_put_u8(b, have_sig)) != 0 ||
197 (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
198 (r = sshbuf_put_string(b, pkblob, blen)) != 0)
199 fatal_fr(r, "reconstruct packet");
200 #ifdef DEBUG_PK
201 sshbuf_dump(b, stderr);
202 #endif
203 /* test for correct signature */
204 authenticated = 0;
205 if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
206 PRIVSEP(sshkey_verify(key, sig, slen,
207 sshbuf_ptr(b), sshbuf_len(b),
208 (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
209 ssh->compat, &sig_details)) == 0) {
210 authenticated = 1;
211 }
212 if (authenticated == 1 && sig_details != NULL) {
213 auth2_record_info(authctxt, "signature count = %u",
214 sig_details->sk_counter);
215 debug_f("sk_counter = %u, sk_flags = 0x%02x",
216 sig_details->sk_counter, sig_details->sk_flags);
217 req_presence = (options.pubkey_auth_options &
218 PUBKEYAUTH_TOUCH_REQUIRED) ||
219 !authopts->no_require_user_presence;
220 if (req_presence && (sig_details->sk_flags &
221 SSH_SK_USER_PRESENCE_REQD) == 0) {
222 error("public key %s signature for %s%s from "
223 "%.128s port %d rejected: user presence "
224 "(authenticator touch) requirement "
225 "not met ", key_s,
226 authctxt->valid ? "" : "invalid user ",
227 authctxt->user, ssh_remote_ipaddr(ssh),
228 ssh_remote_port(ssh));
229 authenticated = 0;
230 goto done;
231 }
232 req_verify = (options.pubkey_auth_options &
233 PUBKEYAUTH_VERIFY_REQUIRED) ||
234 authopts->require_verify;
235 if (req_verify && (sig_details->sk_flags &
236 SSH_SK_USER_VERIFICATION_REQD) == 0) {
237 error("public key %s signature for %s%s from "
238 "%.128s port %d rejected: user "
239 "verification requirement not met ", key_s,
240 authctxt->valid ? "" : "invalid user ",
241 authctxt->user, ssh_remote_ipaddr(ssh),
242 ssh_remote_port(ssh));
243 authenticated = 0;
244 goto done;
245 }
246 }
247 auth2_record_key(authctxt, authenticated, key);
248 } else {
249 debug_f("test pkalg %s pkblob %s%s%s", pkalg, key_s,
250 ca_s == NULL ? "" : " CA ", ca_s == NULL ? "" : ca_s);
251
252 if ((r = sshpkt_get_end(ssh)) != 0)
253 fatal_fr(r, "parse packet");
254
255 if (!authctxt->valid || authctxt->user == NULL) {
256 debug2_f("disabled because of invalid user");
257 goto done;
258 }
259 /* XXX fake reply and always send PK_OK ? */
260 /*
261 * XXX this allows testing whether a user is allowed
262 * to login: if you happen to have a valid pubkey this
263 * message is sent. the message is NEVER sent at all
264 * if a user is not allowed to login. is this an
265 * issue? -markus
266 */
267 if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
268 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
269 != 0 ||
270 (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
271 (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
272 (r = sshpkt_send(ssh)) != 0 ||
273 (r = ssh_packet_write_wait(ssh)) != 0)
274 fatal_fr(r, "send packet");
275 authctxt->postponed = 1;
276 }
277 }
278 done:
279 if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
280 debug_f("key options inconsistent with existing");
281 authenticated = 0;
282 }
283 debug2_f("authenticated %d pkalg %s", authenticated, pkalg);
284
285 sshbuf_free(b);
286 sshauthopt_free(authopts);
287 sshkey_free(key);
288 free(userstyle);
289 free(pkalg);
290 free(pkblob);
291 free(key_s);
292 free(ca_s);
293 free(sig);
294 sshkey_sig_details_free(sig_details);
295 return authenticated;
296 }
297
298 static int
match_principals_option(const char * principal_list,struct sshkey_cert * cert)299 match_principals_option(const char *principal_list, struct sshkey_cert *cert)
300 {
301 char *result;
302 u_int i;
303
304 /* XXX percent_expand() sequences for authorized_principals? */
305
306 for (i = 0; i < cert->nprincipals; i++) {
307 if ((result = match_list(cert->principals[i],
308 principal_list, NULL)) != NULL) {
309 debug3("matched principal from key options \"%.100s\"",
310 result);
311 free(result);
312 return 1;
313 }
314 }
315 return 0;
316 }
317
318 /*
319 * Process a single authorized_principals format line. Returns 0 and sets
320 * authoptsp is principal is authorised, -1 otherwise. "loc" is used as a
321 * log preamble for file/line information.
322 */
323 static int
check_principals_line(struct ssh * ssh,char * cp,const struct sshkey_cert * cert,const char * loc,struct sshauthopt ** authoptsp)324 check_principals_line(struct ssh *ssh, char *cp, const struct sshkey_cert *cert,
325 const char *loc, struct sshauthopt **authoptsp)
326 {
327 u_int i, found = 0;
328 char *ep, *line_opts;
329 const char *reason = NULL;
330 struct sshauthopt *opts = NULL;
331
332 if (authoptsp != NULL)
333 *authoptsp = NULL;
334
335 /* Trim trailing whitespace. */
336 ep = cp + strlen(cp) - 1;
337 while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
338 *ep-- = '\0';
339
340 /*
341 * If the line has internal whitespace then assume it has
342 * key options.
343 */
344 line_opts = NULL;
345 if ((ep = strrchr(cp, ' ')) != NULL ||
346 (ep = strrchr(cp, '\t')) != NULL) {
347 for (; *ep == ' ' || *ep == '\t'; ep++)
348 ;
349 line_opts = cp;
350 cp = ep;
351 }
352 if ((opts = sshauthopt_parse(line_opts, &reason)) == NULL) {
353 debug("%s: bad principals options: %s", loc, reason);
354 auth_debug_add("%s: bad principals options: %s", loc, reason);
355 return -1;
356 }
357 /* Check principals in cert against those on line */
358 for (i = 0; i < cert->nprincipals; i++) {
359 if (strcmp(cp, cert->principals[i]) != 0)
360 continue;
361 debug3("%s: matched principal \"%.100s\"",
362 loc, cert->principals[i]);
363 found = 1;
364 }
365 if (found && authoptsp != NULL) {
366 *authoptsp = opts;
367 opts = NULL;
368 }
369 sshauthopt_free(opts);
370 return found ? 0 : -1;
371 }
372
373 static int
process_principals(struct ssh * ssh,FILE * f,const char * file,const struct sshkey_cert * cert,struct sshauthopt ** authoptsp)374 process_principals(struct ssh *ssh, FILE *f, const char *file,
375 const struct sshkey_cert *cert, struct sshauthopt **authoptsp)
376 {
377 char loc[256], *line = NULL, *cp, *ep;
378 size_t linesize = 0;
379 u_long linenum = 0;
380 u_int found_principal = 0;
381
382 if (authoptsp != NULL)
383 *authoptsp = NULL;
384
385 while (getline(&line, &linesize, f) != -1) {
386 linenum++;
387 /* Always consume entire input */
388 if (found_principal)
389 continue;
390
391 /* Skip leading whitespace. */
392 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
393 ;
394 /* Skip blank and comment lines. */
395 if ((ep = strchr(cp, '#')) != NULL)
396 *ep = '\0';
397 if (!*cp || *cp == '\n')
398 continue;
399
400 snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
401 if (check_principals_line(ssh, cp, cert, loc, authoptsp) == 0)
402 found_principal = 1;
403 }
404 free(line);
405 return found_principal;
406 }
407
408 /* XXX remove pw args here and elsewhere once ssh->authctxt is guaranteed */
409
410 static int
match_principals_file(struct ssh * ssh,struct passwd * pw,char * file,struct sshkey_cert * cert,struct sshauthopt ** authoptsp)411 match_principals_file(struct ssh *ssh, struct passwd *pw, char *file,
412 struct sshkey_cert *cert, struct sshauthopt **authoptsp)
413 {
414 FILE *f;
415 int success;
416
417 if (authoptsp != NULL)
418 *authoptsp = NULL;
419
420 temporarily_use_uid(pw);
421 debug("trying authorized principals file %s", file);
422 if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
423 restore_uid();
424 return 0;
425 }
426 success = process_principals(ssh, f, file, cert, authoptsp);
427 fclose(f);
428 restore_uid();
429 return success;
430 }
431
432 /*
433 * Checks whether principal is allowed in output of command.
434 * returns 1 if the principal is allowed or 0 otherwise.
435 */
436 static int
match_principals_command(struct ssh * ssh,struct passwd * user_pw,const struct sshkey * key,struct sshauthopt ** authoptsp)437 match_principals_command(struct ssh *ssh, struct passwd *user_pw,
438 const struct sshkey *key, struct sshauthopt **authoptsp)
439 {
440 struct passwd *runas_pw = NULL;
441 const struct sshkey_cert *cert = key->cert;
442 FILE *f = NULL;
443 int r, ok, found_principal = 0;
444 int i, ac = 0, uid_swapped = 0;
445 pid_t pid;
446 char *tmp, *username = NULL, *command = NULL, **av = NULL;
447 char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
448 char serial_s[32], uidstr[32];
449 void (*osigchld)(int);
450
451 if (authoptsp != NULL)
452 *authoptsp = NULL;
453 if (options.authorized_principals_command == NULL)
454 return 0;
455 if (options.authorized_principals_command_user == NULL) {
456 error("No user for AuthorizedPrincipalsCommand specified, "
457 "skipping");
458 return 0;
459 }
460
461 /*
462 * NB. all returns later this function should go via "out" to
463 * ensure the original SIGCHLD handler is restored properly.
464 */
465 osigchld = ssh_signal(SIGCHLD, SIG_DFL);
466
467 /* Prepare and verify the user for the command */
468 username = percent_expand(options.authorized_principals_command_user,
469 "u", user_pw->pw_name, (char *)NULL);
470 runas_pw = getpwnam(username);
471 if (runas_pw == NULL) {
472 error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
473 username, strerror(errno));
474 goto out;
475 }
476
477 /* Turn the command into an argument vector */
478 if (argv_split(options.authorized_principals_command,
479 &ac, &av, 0) != 0) {
480 error("AuthorizedPrincipalsCommand \"%s\" contains "
481 "invalid quotes", options.authorized_principals_command);
482 goto out;
483 }
484 if (ac == 0) {
485 error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
486 options.authorized_principals_command);
487 goto out;
488 }
489 if ((ca_fp = sshkey_fingerprint(cert->signature_key,
490 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
491 error_f("sshkey_fingerprint failed");
492 goto out;
493 }
494 if ((key_fp = sshkey_fingerprint(key,
495 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
496 error_f("sshkey_fingerprint failed");
497 goto out;
498 }
499 if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
500 error_fr(r, "sshkey_to_base64 failed");
501 goto out;
502 }
503 if ((r = sshkey_to_base64(key, &keytext)) != 0) {
504 error_fr(r, "sshkey_to_base64 failed");
505 goto out;
506 }
507 snprintf(serial_s, sizeof(serial_s), "%llu",
508 (unsigned long long)cert->serial);
509 snprintf(uidstr, sizeof(uidstr), "%llu",
510 (unsigned long long)user_pw->pw_uid);
511 for (i = 1; i < ac; i++) {
512 tmp = percent_expand(av[i],
513 "U", uidstr,
514 "u", user_pw->pw_name,
515 "h", user_pw->pw_dir,
516 "t", sshkey_ssh_name(key),
517 "T", sshkey_ssh_name(cert->signature_key),
518 "f", key_fp,
519 "F", ca_fp,
520 "k", keytext,
521 "K", catext,
522 "i", cert->key_id,
523 "s", serial_s,
524 (char *)NULL);
525 if (tmp == NULL)
526 fatal_f("percent_expand failed");
527 free(av[i]);
528 av[i] = tmp;
529 }
530 /* Prepare a printable command for logs, etc. */
531 command = argv_assemble(ac, av);
532
533 if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
534 ac, av, &f,
535 SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
536 runas_pw, temporarily_use_uid, restore_uid)) == 0)
537 goto out;
538
539 uid_swapped = 1;
540 temporarily_use_uid(runas_pw);
541
542 ok = process_principals(ssh, f, "(command)", cert, authoptsp);
543
544 fclose(f);
545 f = NULL;
546
547 if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
548 goto out;
549
550 /* Read completed successfully */
551 found_principal = ok;
552 out:
553 if (f != NULL)
554 fclose(f);
555 ssh_signal(SIGCHLD, osigchld);
556 for (i = 0; i < ac; i++)
557 free(av[i]);
558 free(av);
559 if (uid_swapped)
560 restore_uid();
561 free(command);
562 free(username);
563 free(ca_fp);
564 free(key_fp);
565 free(catext);
566 free(keytext);
567 return found_principal;
568 }
569
570 /*
571 * Check a single line of an authorized_keys-format file. Returns 0 if key
572 * matches, -1 otherwise. Will return key/cert options via *authoptsp
573 * on success. "loc" is used as file/line location in log messages.
574 */
575 static int
check_authkey_line(struct ssh * ssh,struct passwd * pw,struct sshkey * key,char * cp,const char * loc,struct sshauthopt ** authoptsp)576 check_authkey_line(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
577 char *cp, const char *loc, struct sshauthopt **authoptsp)
578 {
579 int want_keytype = sshkey_is_cert(key) ? KEY_UNSPEC : key->type;
580 struct sshkey *found = NULL;
581 struct sshauthopt *keyopts = NULL, *certopts = NULL, *finalopts = NULL;
582 char *key_options = NULL, *fp = NULL;
583 const char *reason = NULL;
584 int ret = -1;
585
586 if (authoptsp != NULL)
587 *authoptsp = NULL;
588
589 if ((found = sshkey_new(want_keytype)) == NULL) {
590 debug3_f("keytype %d failed", want_keytype);
591 goto out;
592 }
593
594 /* XXX djm: peek at key type in line and skip if unwanted */
595
596 if (sshkey_read(found, &cp) != 0) {
597 /* no key? check for options */
598 debug2("%s: check options: '%s'", loc, cp);
599 key_options = cp;
600 if (sshkey_advance_past_options(&cp) != 0) {
601 reason = "invalid key option string";
602 goto fail_reason;
603 }
604 skip_space(&cp);
605 if (sshkey_read(found, &cp) != 0) {
606 /* still no key? advance to next line*/
607 debug2("%s: advance: '%s'", loc, cp);
608 goto out;
609 }
610 }
611 /* Parse key options now; we need to know if this is a CA key */
612 if ((keyopts = sshauthopt_parse(key_options, &reason)) == NULL) {
613 debug("%s: bad key options: %s", loc, reason);
614 auth_debug_add("%s: bad key options: %s", loc, reason);
615 goto out;
616 }
617 /* Ignore keys that don't match or incorrectly marked as CAs */
618 if (sshkey_is_cert(key)) {
619 /* Certificate; check signature key against CA */
620 if (!sshkey_equal(found, key->cert->signature_key) ||
621 !keyopts->cert_authority)
622 goto out;
623 } else {
624 /* Plain key: check it against key found in file */
625 if (!sshkey_equal(found, key) || keyopts->cert_authority)
626 goto out;
627 }
628
629 /* We have a candidate key, perform authorisation checks */
630 if ((fp = sshkey_fingerprint(found,
631 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
632 fatal_f("fingerprint failed");
633
634 debug("%s: matching %s found: %s %s", loc,
635 sshkey_is_cert(key) ? "CA" : "key", sshkey_type(found), fp);
636
637 if (auth_authorise_keyopts(ssh, pw, keyopts,
638 sshkey_is_cert(key), loc) != 0) {
639 reason = "Refused by key options";
640 goto fail_reason;
641 }
642 /* That's all we need for plain keys. */
643 if (!sshkey_is_cert(key)) {
644 verbose("Accepted key %s %s found at %s",
645 sshkey_type(found), fp, loc);
646 finalopts = keyopts;
647 keyopts = NULL;
648 goto success;
649 }
650
651 /*
652 * Additional authorisation for certificates.
653 */
654
655 /* Parse and check options present in certificate */
656 if ((certopts = sshauthopt_from_cert(key)) == NULL) {
657 reason = "Invalid certificate options";
658 goto fail_reason;
659 }
660 if (auth_authorise_keyopts(ssh, pw, certopts, 0, loc) != 0) {
661 reason = "Refused by certificate options";
662 goto fail_reason;
663 }
664 if ((finalopts = sshauthopt_merge(keyopts, certopts, &reason)) == NULL)
665 goto fail_reason;
666
667 /*
668 * If the user has specified a list of principals as
669 * a key option, then prefer that list to matching
670 * their username in the certificate principals list.
671 */
672 if (keyopts->cert_principals != NULL &&
673 !match_principals_option(keyopts->cert_principals, key->cert)) {
674 reason = "Certificate does not contain an authorized principal";
675 goto fail_reason;
676 }
677 if (sshkey_cert_check_authority_now(key, 0, 0, 0,
678 keyopts->cert_principals == NULL ? pw->pw_name : NULL,
679 &reason) != 0)
680 goto fail_reason;
681
682 verbose("Accepted certificate ID \"%s\" (serial %llu) "
683 "signed by CA %s %s found at %s",
684 key->cert->key_id,
685 (unsigned long long)key->cert->serial,
686 sshkey_type(found), fp, loc);
687
688 success:
689 if (finalopts == NULL)
690 fatal_f("internal error: missing options");
691 if (authoptsp != NULL) {
692 *authoptsp = finalopts;
693 finalopts = NULL;
694 }
695 /* success */
696 ret = 0;
697 goto out;
698
699 fail_reason:
700 error("%s", reason);
701 auth_debug_add("%s", reason);
702 out:
703 free(fp);
704 sshauthopt_free(keyopts);
705 sshauthopt_free(certopts);
706 sshauthopt_free(finalopts);
707 sshkey_free(found);
708 return ret;
709 }
710
711 /*
712 * Checks whether key is allowed in authorized_keys-format file,
713 * returns 1 if the key is allowed or 0 otherwise.
714 */
715 static int
check_authkeys_file(struct ssh * ssh,struct passwd * pw,FILE * f,char * file,struct sshkey * key,struct sshauthopt ** authoptsp)716 check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f,
717 char *file, struct sshkey *key, struct sshauthopt **authoptsp)
718 {
719 char *cp, *line = NULL, loc[256];
720 size_t linesize = 0;
721 int found_key = 0;
722 u_long linenum = 0;
723
724 if (authoptsp != NULL)
725 *authoptsp = NULL;
726
727 while (getline(&line, &linesize, f) != -1) {
728 linenum++;
729 /* Always consume entire file */
730 if (found_key)
731 continue;
732
733 /* Skip leading whitespace, empty and comment lines. */
734 cp = line;
735 skip_space(&cp);
736 if (!*cp || *cp == '\n' || *cp == '#')
737 continue;
738 snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
739 if (check_authkey_line(ssh, pw, key, cp, loc, authoptsp) == 0)
740 found_key = 1;
741 }
742 free(line);
743 return found_key;
744 }
745
746 /* Authenticate a certificate key against TrustedUserCAKeys */
747 static int
user_cert_trusted_ca(struct ssh * ssh,struct passwd * pw,struct sshkey * key,struct sshauthopt ** authoptsp)748 user_cert_trusted_ca(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
749 struct sshauthopt **authoptsp)
750 {
751 char *ca_fp, *principals_file = NULL;
752 const char *reason;
753 struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
754 struct sshauthopt *final_opts = NULL;
755 int r, ret = 0, found_principal = 0, use_authorized_principals;
756
757 if (authoptsp != NULL)
758 *authoptsp = NULL;
759
760 if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
761 return 0;
762
763 if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
764 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
765 return 0;
766
767 if ((r = sshkey_in_file(key->cert->signature_key,
768 options.trusted_user_ca_keys, 1, 0)) != 0) {
769 debug2_fr(r, "CA %s %s is not listed in %s",
770 sshkey_type(key->cert->signature_key), ca_fp,
771 options.trusted_user_ca_keys);
772 goto out;
773 }
774 /*
775 * If AuthorizedPrincipals is in use, then compare the certificate
776 * principals against the names in that file rather than matching
777 * against the username.
778 */
779 if ((principals_file = authorized_principals_file(pw)) != NULL) {
780 if (match_principals_file(ssh, pw, principals_file,
781 key->cert, &principals_opts))
782 found_principal = 1;
783 }
784 /* Try querying command if specified */
785 if (!found_principal && match_principals_command(ssh, pw, key,
786 &principals_opts))
787 found_principal = 1;
788 /* If principals file or command is specified, then require a match */
789 use_authorized_principals = principals_file != NULL ||
790 options.authorized_principals_command != NULL;
791 if (!found_principal && use_authorized_principals) {
792 reason = "Certificate does not contain an authorized principal";
793 goto fail_reason;
794 }
795 if (use_authorized_principals && principals_opts == NULL)
796 fatal_f("internal error: missing principals_opts");
797 if (sshkey_cert_check_authority_now(key, 0, 1, 0,
798 use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
799 goto fail_reason;
800
801 /* Check authority from options in key and from principals file/cmd */
802 if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
803 reason = "Invalid certificate options";
804 goto fail_reason;
805 }
806 if (auth_authorise_keyopts(ssh, pw, cert_opts, 0, "cert") != 0) {
807 reason = "Refused by certificate options";
808 goto fail_reason;
809 }
810 if (principals_opts == NULL) {
811 final_opts = cert_opts;
812 cert_opts = NULL;
813 } else {
814 if (auth_authorise_keyopts(ssh, pw, principals_opts, 0,
815 "principals") != 0) {
816 reason = "Refused by certificate principals options";
817 goto fail_reason;
818 }
819 if ((final_opts = sshauthopt_merge(principals_opts,
820 cert_opts, &reason)) == NULL) {
821 fail_reason:
822 error("%s", reason);
823 auth_debug_add("%s", reason);
824 goto out;
825 }
826 }
827
828 /* Success */
829 verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
830 "%s CA %s via %s", key->cert->key_id,
831 (unsigned long long)key->cert->serial,
832 sshkey_type(key->cert->signature_key), ca_fp,
833 options.trusted_user_ca_keys);
834 if (authoptsp != NULL) {
835 *authoptsp = final_opts;
836 final_opts = NULL;
837 }
838 ret = 1;
839 out:
840 sshauthopt_free(principals_opts);
841 sshauthopt_free(cert_opts);
842 sshauthopt_free(final_opts);
843 free(principals_file);
844 free(ca_fp);
845 return ret;
846 }
847
848 /*
849 * Checks whether key is allowed in file.
850 * returns 1 if the key is allowed or 0 otherwise.
851 */
852 static int
user_key_allowed2(struct ssh * ssh,struct passwd * pw,struct sshkey * key,char * file,struct sshauthopt ** authoptsp)853 user_key_allowed2(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
854 char *file, struct sshauthopt **authoptsp)
855 {
856 FILE *f;
857 int found_key = 0;
858
859 if (authoptsp != NULL)
860 *authoptsp = NULL;
861
862 /* Temporarily use the user's uid. */
863 temporarily_use_uid(pw);
864
865 debug("trying public key file %s", file);
866 if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
867 found_key = check_authkeys_file(ssh, pw, f, file,
868 key, authoptsp);
869 fclose(f);
870 }
871
872 restore_uid();
873 return found_key;
874 }
875
876 /*
877 * Checks whether key is allowed in output of command.
878 * returns 1 if the key is allowed or 0 otherwise.
879 */
880 static int
user_key_command_allowed2(struct ssh * ssh,struct passwd * user_pw,struct sshkey * key,struct sshauthopt ** authoptsp)881 user_key_command_allowed2(struct ssh *ssh, struct passwd *user_pw,
882 struct sshkey *key, struct sshauthopt **authoptsp)
883 {
884 struct passwd *runas_pw = NULL;
885 FILE *f = NULL;
886 int r, ok, found_key = 0;
887 int i, uid_swapped = 0, ac = 0;
888 pid_t pid;
889 char *username = NULL, *key_fp = NULL, *keytext = NULL;
890 char uidstr[32], *tmp, *command = NULL, **av = NULL;
891 void (*osigchld)(int);
892
893 if (authoptsp != NULL)
894 *authoptsp = NULL;
895 if (options.authorized_keys_command == NULL)
896 return 0;
897 if (options.authorized_keys_command_user == NULL) {
898 error("No user for AuthorizedKeysCommand specified, skipping");
899 return 0;
900 }
901
902 /*
903 * NB. all returns later this function should go via "out" to
904 * ensure the original SIGCHLD handler is restored properly.
905 */
906 osigchld = ssh_signal(SIGCHLD, SIG_DFL);
907
908 /* Prepare and verify the user for the command */
909 username = percent_expand(options.authorized_keys_command_user,
910 "u", user_pw->pw_name, (char *)NULL);
911 runas_pw = getpwnam(username);
912 if (runas_pw == NULL) {
913 error("AuthorizedKeysCommandUser \"%s\" not found: %s",
914 username, strerror(errno));
915 goto out;
916 }
917
918 /* Prepare AuthorizedKeysCommand */
919 if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
920 SSH_FP_DEFAULT)) == NULL) {
921 error_f("sshkey_fingerprint failed");
922 goto out;
923 }
924 if ((r = sshkey_to_base64(key, &keytext)) != 0) {
925 error_fr(r, "sshkey_to_base64 failed");
926 goto out;
927 }
928
929 /* Turn the command into an argument vector */
930 if (argv_split(options.authorized_keys_command, &ac, &av, 0) != 0) {
931 error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
932 options.authorized_keys_command);
933 goto out;
934 }
935 if (ac == 0) {
936 error("AuthorizedKeysCommand \"%s\" yielded no arguments",
937 options.authorized_keys_command);
938 goto out;
939 }
940 snprintf(uidstr, sizeof(uidstr), "%llu",
941 (unsigned long long)user_pw->pw_uid);
942 for (i = 1; i < ac; i++) {
943 tmp = percent_expand(av[i],
944 "U", uidstr,
945 "u", user_pw->pw_name,
946 "h", user_pw->pw_dir,
947 "t", sshkey_ssh_name(key),
948 "f", key_fp,
949 "k", keytext,
950 (char *)NULL);
951 if (tmp == NULL)
952 fatal_f("percent_expand failed");
953 free(av[i]);
954 av[i] = tmp;
955 }
956 /* Prepare a printable command for logs, etc. */
957 command = argv_assemble(ac, av);
958
959 /*
960 * If AuthorizedKeysCommand was run without arguments
961 * then fall back to the old behaviour of passing the
962 * target username as a single argument.
963 */
964 if (ac == 1) {
965 av = xreallocarray(av, ac + 2, sizeof(*av));
966 av[1] = xstrdup(user_pw->pw_name);
967 av[2] = NULL;
968 /* Fix up command too, since it is used in log messages */
969 free(command);
970 xasprintf(&command, "%s %s", av[0], av[1]);
971 }
972
973 if ((pid = subprocess("AuthorizedKeysCommand", command,
974 ac, av, &f,
975 SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
976 runas_pw, temporarily_use_uid, restore_uid)) == 0)
977 goto out;
978
979 uid_swapped = 1;
980 temporarily_use_uid(runas_pw);
981
982 ok = check_authkeys_file(ssh, user_pw, f,
983 options.authorized_keys_command, key, authoptsp);
984
985 fclose(f);
986 f = NULL;
987
988 if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
989 goto out;
990
991 /* Read completed successfully */
992 found_key = ok;
993 out:
994 if (f != NULL)
995 fclose(f);
996 ssh_signal(SIGCHLD, osigchld);
997 for (i = 0; i < ac; i++)
998 free(av[i]);
999 free(av);
1000 if (uid_swapped)
1001 restore_uid();
1002 free(command);
1003 free(username);
1004 free(key_fp);
1005 free(keytext);
1006 return found_key;
1007 }
1008
1009 /*
1010 * Check whether key authenticates and authorises the user.
1011 */
1012 int
user_key_allowed(struct ssh * ssh,struct passwd * pw,struct sshkey * key,int auth_attempt,struct sshauthopt ** authoptsp)1013 user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
1014 int auth_attempt, struct sshauthopt **authoptsp)
1015 {
1016 u_int success = 0, i;
1017 char *file;
1018 struct sshauthopt *opts = NULL;
1019
1020 if (authoptsp != NULL)
1021 *authoptsp = NULL;
1022
1023 if (auth_key_is_revoked(key))
1024 return 0;
1025 if (sshkey_is_cert(key) &&
1026 auth_key_is_revoked(key->cert->signature_key))
1027 return 0;
1028
1029 for (i = 0; !success && i < options.num_authkeys_files; i++) {
1030 if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
1031 continue;
1032 file = expand_authorized_keys(
1033 options.authorized_keys_files[i], pw);
1034 success = user_key_allowed2(ssh, pw, key, file, &opts);
1035 free(file);
1036 if (!success) {
1037 sshauthopt_free(opts);
1038 opts = NULL;
1039 }
1040 }
1041 if (success)
1042 goto out;
1043
1044 if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0)
1045 goto out;
1046 sshauthopt_free(opts);
1047 opts = NULL;
1048
1049 if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0)
1050 goto out;
1051 sshauthopt_free(opts);
1052 opts = NULL;
1053
1054 out:
1055 if (success && authoptsp != NULL) {
1056 *authoptsp = opts;
1057 opts = NULL;
1058 }
1059 sshauthopt_free(opts);
1060 return success;
1061 }
1062
1063 Authmethod method_pubkey = {
1064 "publickey",
1065 userauth_pubkey,
1066 &options.pubkey_authentication
1067 };
1068