auth2-pubkey.c revision 1.16
1/* $NetBSD: auth2-pubkey.c,v 1.16 2017/02/16 17:56:07 christos Exp $ */ 2/* $OpenBSD: auth2-pubkey.c,v 1.60 2016/11/30 02:57:40 djm Exp $ */ 3 4/* 5 * Copyright (c) 2000 Markus Friedl. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28#include "includes.h" 29__RCSID("$NetBSD: auth2-pubkey.c,v 1.16 2017/02/16 17:56:07 christos Exp $"); 30#include <sys/types.h> 31#include <sys/stat.h> 32#include <sys/wait.h> 33 34#include <errno.h> 35#include <fcntl.h> 36#include <paths.h> 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 "buffer.h" 51#include "log.h" 52#include "misc.h" 53#include "servconf.h" 54#include "compat.h" 55#include "key.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 "digest.h" 69 70#ifdef WITH_LDAP_PUBKEY 71#include "ldapauth.h" 72#endif 73 74#include "ssherr.h" 75#include "channels.h" /* XXX for session.h */ 76#include "session.h" /* XXX for child_set_env(); refactor? */ 77 78/* import */ 79extern ServerOptions options; 80extern u_char *session_id2; 81extern u_int session_id2_len; 82 83static int 84userauth_pubkey(Authctxt *authctxt) 85{ 86 Buffer b; 87 Key *key = NULL; 88 char *pkalg, *userstyle, *fp = NULL; 89 u_char *pkblob, *sig; 90 u_int alen, blen, slen; 91 int have_sig, pktype; 92 int authenticated = 0; 93 94 if (!authctxt->valid) { 95 debug2("%s: disabled because of invalid user", __func__); 96 return 0; 97 } 98 have_sig = packet_get_char(); 99 if (datafellows & SSH_BUG_PKAUTH) { 100 debug2("%s: SSH_BUG_PKAUTH", __func__); 101 /* no explicit pkalg given */ 102 pkblob = packet_get_string(&blen); 103 buffer_init(&b); 104 buffer_append(&b, pkblob, blen); 105 /* so we have to extract the pkalg from the pkblob */ 106 pkalg = buffer_get_string(&b, &alen); 107 buffer_free(&b); 108 } else { 109 pkalg = packet_get_string(&alen); 110 pkblob = packet_get_string(&blen); 111 } 112 pktype = key_type_from_name(pkalg); 113 if (pktype == KEY_UNSPEC) { 114 /* this is perfectly legal */ 115 logit("%s: unsupported public key algorithm: %s", 116 __func__, pkalg); 117 goto done; 118 } 119 key = key_from_blob(pkblob, blen); 120 if (key == NULL) { 121 error("%s: cannot decode key: %s", __func__, pkalg); 122 goto done; 123 } 124 if (key->type != pktype) { 125 error("%s: type mismatch for decoded key " 126 "(received %d, expected %d)", __func__, key->type, pktype); 127 goto done; 128 } 129 if (key_type_plain(key->type) == KEY_RSA && 130 (datafellows & SSH_BUG_RSASIGMD5) != 0) { 131 logit("Refusing RSA key because client uses unsafe " 132 "signature scheme"); 133 goto done; 134 } 135 fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT); 136 if (auth2_userkey_already_used(authctxt, key)) { 137 logit("refusing previously-used %s key", key_type(key)); 138 goto done; 139 } 140 if (match_pattern_list(sshkey_ssh_name(key), 141 options.pubkey_key_types, 0) != 1) { 142 logit("%s: key type %s not in PubkeyAcceptedKeyTypes", 143 __func__, sshkey_ssh_name(key)); 144 goto done; 145 } 146 147 if (have_sig) { 148 debug3("%s: have signature for %s %s", 149 __func__, sshkey_type(key), fp); 150 sig = packet_get_string(&slen); 151 packet_check_eom(); 152 buffer_init(&b); 153 if (datafellows & SSH_OLD_SESSIONID) { 154 buffer_append(&b, session_id2, session_id2_len); 155 } else { 156 buffer_put_string(&b, session_id2, session_id2_len); 157 } 158 /* reconstruct packet */ 159 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST); 160 xasprintf(&userstyle, "%s%s%s", authctxt->user, 161 authctxt->style ? ":" : "", 162 authctxt->style ? authctxt->style : ""); 163 buffer_put_cstring(&b, userstyle); 164 free(userstyle); 165 buffer_put_cstring(&b, 166 datafellows & SSH_BUG_PKSERVICE ? 167 "ssh-userauth" : 168 authctxt->service); 169 if (datafellows & SSH_BUG_PKAUTH) { 170 buffer_put_char(&b, have_sig); 171 } else { 172 buffer_put_cstring(&b, "publickey"); 173 buffer_put_char(&b, have_sig); 174 buffer_put_cstring(&b, pkalg); 175 } 176 buffer_put_string(&b, pkblob, blen); 177#ifdef DEBUG_PK 178 buffer_dump(&b); 179#endif 180 pubkey_auth_info(authctxt, key, NULL); 181 182 /* test for correct signature */ 183 authenticated = 0; 184 if (PRIVSEP(user_key_allowed(authctxt->pw, key, 1)) && 185 PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b), 186 buffer_len(&b))) == 1) { 187 authenticated = 1; 188 /* Record the successful key to prevent reuse */ 189 auth2_record_userkey(authctxt, key); 190 key = NULL; /* Don't free below */ 191 } 192 buffer_free(&b); 193 free(sig); 194 } else { 195 debug("%s: test whether pkalg/pkblob are acceptable for %s %s", 196 __func__, sshkey_type(key), fp); 197 packet_check_eom(); 198 199 /* XXX fake reply and always send PK_OK ? */ 200 /* 201 * XXX this allows testing whether a user is allowed 202 * to login: if you happen to have a valid pubkey this 203 * message is sent. the message is NEVER sent at all 204 * if a user is not allowed to login. is this an 205 * issue? -markus 206 */ 207 if (PRIVSEP(user_key_allowed(authctxt->pw, key, 0))) { 208 packet_start(SSH2_MSG_USERAUTH_PK_OK); 209 packet_put_string(pkalg, alen); 210 packet_put_string(pkblob, blen); 211 packet_send(); 212 packet_write_wait(); 213 authctxt->postponed = 1; 214 } 215 } 216 if (authenticated != 1) 217 auth_clear_options(); 218done: 219 debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg); 220 if (key != NULL) 221 key_free(key); 222 free(pkalg); 223 free(pkblob); 224 free(fp); 225 return authenticated; 226} 227 228void 229pubkey_auth_info(Authctxt *authctxt, const Key *key, const char *fmt, ...) 230{ 231 char *fp, *extra; 232 va_list ap; 233 int i; 234 235 extra = NULL; 236 if (fmt != NULL) { 237 va_start(ap, fmt); 238 i = vasprintf(&extra, fmt, ap); 239 va_end(ap); 240 if (i < 0 || extra == NULL) 241 fatal("%s: vasprintf failed", __func__); 242 } 243 244 if (key_is_cert(key)) { 245 fp = sshkey_fingerprint(key->cert->signature_key, 246 options.fingerprint_hash, SSH_FP_DEFAULT); 247 auth_info(authctxt, "%s ID %s (serial %llu) CA %s %s%s%s", 248 key_type(key), key->cert->key_id, 249 (unsigned long long)key->cert->serial, 250 key_type(key->cert->signature_key), 251 fp == NULL ? "(null)" : fp, 252 extra == NULL ? "" : ", ", extra == NULL ? "" : extra); 253 free(fp); 254 } else { 255 fp = sshkey_fingerprint(key, options.fingerprint_hash, 256 SSH_FP_DEFAULT); 257 auth_info(authctxt, "%s %s%s%s", key_type(key), 258 fp == NULL ? "(null)" : fp, 259 extra == NULL ? "" : ", ", extra == NULL ? "" : extra); 260 free(fp); 261 } 262 free(extra); 263} 264 265/* 266 * Splits 's' into an argument vector. Handles quoted string and basic 267 * escape characters (\\, \", \'). Caller must free the argument vector 268 * and its members. 269 */ 270static int 271split_argv(const char *s, int *argcp, char ***argvp) 272{ 273 int r = SSH_ERR_INTERNAL_ERROR; 274 int argc = 0, quote, i, j; 275 char *arg, **argv = xcalloc(1, sizeof(*argv)); 276 277 *argvp = NULL; 278 *argcp = 0; 279 280 for (i = 0; s[i] != '\0'; i++) { 281 /* Skip leading whitespace */ 282 if (s[i] == ' ' || s[i] == '\t') 283 continue; 284 285 /* Start of a token */ 286 quote = 0; 287 if (s[i] == '\\' && 288 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\')) 289 i++; 290 else if (s[i] == '\'' || s[i] == '"') 291 quote = s[i++]; 292 293 argv = xreallocarray(argv, (argc + 2), sizeof(*argv)); 294 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1); 295 argv[argc] = NULL; 296 297 /* Copy the token in, removing escapes */ 298 for (j = 0; s[i] != '\0'; i++) { 299 if (s[i] == '\\') { 300 if (s[i + 1] == '\'' || 301 s[i + 1] == '\"' || 302 s[i + 1] == '\\') { 303 i++; /* Skip '\' */ 304 arg[j++] = s[i]; 305 } else { 306 /* Unrecognised escape */ 307 arg[j++] = s[i]; 308 } 309 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t')) 310 break; /* done */ 311 else if (quote != 0 && s[i] == quote) 312 break; /* done */ 313 else 314 arg[j++] = s[i]; 315 } 316 if (s[i] == '\0') { 317 if (quote != 0) { 318 /* Ran out of string looking for close quote */ 319 r = SSH_ERR_INVALID_FORMAT; 320 goto out; 321 } 322 break; 323 } 324 } 325 /* Success */ 326 *argcp = argc; 327 *argvp = argv; 328 argc = 0; 329 argv = NULL; 330 r = 0; 331 out: 332 if (argc != 0 && argv != NULL) { 333 for (i = 0; i < argc; i++) 334 free(argv[i]); 335 free(argv); 336 } 337 return r; 338} 339 340/* 341 * Reassemble an argument vector into a string, quoting and escaping as 342 * necessary. Caller must free returned string. 343 */ 344static char * 345assemble_argv(int argc, char **argv) 346{ 347 int i, j, ws, r; 348 char c, *ret; 349 struct sshbuf *buf, *arg; 350 351 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL) 352 fatal("%s: sshbuf_new failed", __func__); 353 354 for (i = 0; i < argc; i++) { 355 ws = 0; 356 sshbuf_reset(arg); 357 for (j = 0; argv[i][j] != '\0'; j++) { 358 r = 0; 359 c = argv[i][j]; 360 switch (c) { 361 case ' ': 362 case '\t': 363 ws = 1; 364 r = sshbuf_put_u8(arg, c); 365 break; 366 case '\\': 367 case '\'': 368 case '"': 369 if ((r = sshbuf_put_u8(arg, '\\')) != 0) 370 break; 371 /* FALLTHROUGH */ 372 default: 373 r = sshbuf_put_u8(arg, c); 374 break; 375 } 376 if (r != 0) 377 fatal("%s: sshbuf_put_u8: %s", 378 __func__, ssh_err(r)); 379 } 380 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) || 381 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) || 382 (r = sshbuf_putb(buf, arg)) != 0 || 383 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0)) 384 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 385 } 386 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL) 387 fatal("%s: malloc failed", __func__); 388 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf)); 389 ret[sshbuf_len(buf)] = '\0'; 390 sshbuf_free(buf); 391 sshbuf_free(arg); 392 return ret; 393} 394 395/* 396 * Runs command in a subprocess. Returns pid on success and a FILE* to the 397 * subprocess' stdout or 0 on failure. 398 * NB. "command" is only used for logging. 399 */ 400static pid_t 401subprocess(const char *tag, struct passwd *pw, const char *command, 402 int ac, char **av, FILE **child) 403{ 404 FILE *f; 405 struct stat st; 406 int devnull, p[2], i; 407 pid_t pid; 408 char *cp, errmsg[512]; 409 u_int envsize; 410 char **child_env; 411 412 *child = NULL; 413 414 debug3("%s: %s command \"%s\" running as %s", __func__, 415 tag, command, pw->pw_name); 416 417 /* Verify the path exists and is safe-ish to execute */ 418 if (*av[0] != '/') { 419 error("%s path is not absolute", tag); 420 return 0; 421 } 422 temporarily_use_uid(pw); 423 if (stat(av[0], &st) < 0) { 424 error("Could not stat %s \"%s\": %s", tag, 425 av[0], strerror(errno)); 426 restore_uid(); 427 return 0; 428 } 429 if (auth_secure_path(av[0], &st, NULL, 0, 430 errmsg, sizeof(errmsg)) != 0) { 431 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg); 432 restore_uid(); 433 return 0; 434 } 435 436 /* 437 * Run the command; stderr is left in place, stdout is the 438 * authorized_keys output. 439 */ 440 if (pipe(p) != 0) { 441 error("%s: pipe: %s", tag, strerror(errno)); 442 restore_uid(); 443 return 0; 444 } 445 446 /* 447 * Don't want to call this in the child, where it can fatal() and 448 * run cleanup_exit() code. 449 */ 450 restore_uid(); 451 452 switch ((pid = fork())) { 453 case -1: /* error */ 454 error("%s: fork: %s", tag, strerror(errno)); 455 close(p[0]); 456 close(p[1]); 457 return 0; 458 case 0: /* child */ 459 /* Prepare a minimal environment for the child. */ 460 envsize = 5; 461 child_env = xcalloc(sizeof(*child_env), envsize); 462 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH); 463 child_set_env(&child_env, &envsize, "USER", pw->pw_name); 464 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name); 465 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir); 466 if ((cp = getenv("LANG")) != NULL) 467 child_set_env(&child_env, &envsize, "LANG", cp); 468 469 for (i = 0; i < NSIG; i++) 470 signal(i, SIG_DFL); 471 472 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 473 error("%s: open %s: %s", tag, _PATH_DEVNULL, 474 strerror(errno)); 475 _exit(1); 476 } 477 /* Keep stderr around a while longer to catch errors */ 478 if (dup2(devnull, STDIN_FILENO) == -1 || 479 dup2(p[1], STDOUT_FILENO) == -1) { 480 error("%s: dup2: %s", tag, strerror(errno)); 481 _exit(1); 482 } 483 if (closefrom(STDERR_FILENO + 1) == -1) { 484 error("closefrom: %s", strerror(errno)); 485 _exit(1); 486 } 487 488 /* Don't use permanently_set_uid() here to avoid fatal() */ 489 if (setgid(pw->pw_gid) == -1) { 490 error("setgid %u: %s", (u_int)pw->pw_gid, 491 strerror(errno)); 492 _exit(1); 493 } 494 if (setuid(pw->pw_uid) == -1) { 495 error("setuid %u: %s", (u_int)pw->pw_uid, 496 strerror(errno)); 497 _exit(1); 498 } 499 /* stdin is pointed to /dev/null at this point */ 500 if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) { 501 error("%s: dup2: %s", tag, strerror(errno)); 502 _exit(1); 503 } 504 505 execve(av[0], av, child_env); 506 error("%s exec \"%s\": %s", tag, command, strerror(errno)); 507 _exit(127); 508 default: /* parent */ 509 break; 510 } 511 512 close(p[1]); 513 if ((f = fdopen(p[0], "r")) == NULL) { 514 error("%s: fdopen: %s", tag, strerror(errno)); 515 close(p[0]); 516 /* Don't leave zombie child */ 517 kill(pid, SIGTERM); 518 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) 519 ; 520 return 0; 521 } 522 /* Success */ 523 debug3("%s: %s pid %ld", __func__, tag, (long)pid); 524 *child = f; 525 return pid; 526} 527 528/* Returns 0 if pid exited cleanly, non-zero otherwise */ 529static int 530exited_cleanly(pid_t pid, const char *tag, const char *cmd) 531{ 532 int status; 533 534 while (waitpid(pid, &status, 0) == -1) { 535 if (errno != EINTR) { 536 error("%s: waitpid: %s", tag, strerror(errno)); 537 return -1; 538 } 539 } 540 if (WIFSIGNALED(status)) { 541 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status)); 542 return -1; 543 } else if (WEXITSTATUS(status) != 0) { 544 error("%s %s failed, status %d", tag, cmd, WEXITSTATUS(status)); 545 return -1; 546 } 547 return 0; 548} 549 550static int 551match_principals_option(const char *principal_list, struct sshkey_cert *cert) 552{ 553 char *result; 554 u_int i; 555 556 /* XXX percent_expand() sequences for authorized_principals? */ 557 558 for (i = 0; i < cert->nprincipals; i++) { 559 if ((result = match_list(cert->principals[i], 560 principal_list, NULL)) != NULL) { 561 debug3("matched principal from key options \"%.100s\"", 562 result); 563 free(result); 564 return 1; 565 } 566 } 567 return 0; 568} 569 570static int 571process_principals(FILE *f, char *file, struct passwd *pw, 572 const struct sshkey_cert *cert) 573{ 574 char line[SSH_MAX_PUBKEY_BYTES], *cp, *ep, *line_opts; 575 u_long linenum = 0; 576 u_int i; 577 578 while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) { 579 /* Skip leading whitespace. */ 580 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 581 ; 582 /* Skip blank and comment lines. */ 583 if ((ep = strchr(cp, '#')) != NULL) 584 *ep = '\0'; 585 if (!*cp || *cp == '\n') 586 continue; 587 /* Trim trailing whitespace. */ 588 ep = cp + strlen(cp) - 1; 589 while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t')) 590 *ep-- = '\0'; 591 /* 592 * If the line has internal whitespace then assume it has 593 * key options. 594 */ 595 line_opts = NULL; 596 if ((ep = strrchr(cp, ' ')) != NULL || 597 (ep = strrchr(cp, '\t')) != NULL) { 598 for (; *ep == ' ' || *ep == '\t'; ep++) 599 ; 600 line_opts = cp; 601 cp = ep; 602 } 603 for (i = 0; i < cert->nprincipals; i++) { 604 if (strcmp(cp, cert->principals[i]) == 0) { 605 debug3("%s:%lu: matched principal \"%.100s\"", 606 file == NULL ? "(command)" : file, 607 linenum, cert->principals[i]); 608 if (auth_parse_options(pw, line_opts, 609 file, linenum) != 1) 610 continue; 611 return 1; 612 } 613 } 614 } 615 return 0; 616} 617 618static int 619match_principals_file(char *file, struct passwd *pw, struct sshkey_cert *cert) 620{ 621 FILE *f; 622 int success; 623 624 temporarily_use_uid(pw); 625 debug("trying authorized principals file %s", file); 626 if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) { 627 restore_uid(); 628 return 0; 629 } 630 success = process_principals(f, file, pw, cert); 631 fclose(f); 632 restore_uid(); 633 return success; 634} 635 636/* 637 * Checks whether principal is allowed in output of command. 638 * returns 1 if the principal is allowed or 0 otherwise. 639 */ 640static int 641match_principals_command(struct passwd *user_pw, const struct sshkey *key) 642{ 643 const struct sshkey_cert *cert = key->cert; 644 FILE *f = NULL; 645 int r, ok, found_principal = 0; 646 struct passwd *pw; 647 int i, ac = 0, uid_swapped = 0; 648 pid_t pid; 649 char *tmp, *username = NULL, *command = NULL, **av = NULL; 650 char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL; 651 char serial_s[16]; 652 void (*osigchld)(int); 653 654 if (options.authorized_principals_command == NULL) 655 return 0; 656 if (options.authorized_principals_command_user == NULL) { 657 error("No user for AuthorizedPrincipalsCommand specified, " 658 "skipping"); 659 return 0; 660 } 661 662 /* 663 * NB. all returns later this function should go via "out" to 664 * ensure the original SIGCHLD handler is restored properly. 665 */ 666 osigchld = signal(SIGCHLD, SIG_DFL); 667 668 /* Prepare and verify the user for the command */ 669 username = percent_expand(options.authorized_principals_command_user, 670 "u", user_pw->pw_name, (char *)NULL); 671 pw = getpwnam(username); 672 if (pw == NULL) { 673 error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s", 674 username, strerror(errno)); 675 goto out; 676 } 677 678 /* Turn the command into an argument vector */ 679 if (split_argv(options.authorized_principals_command, &ac, &av) != 0) { 680 error("AuthorizedPrincipalsCommand \"%s\" contains " 681 "invalid quotes", command); 682 goto out; 683 } 684 if (ac == 0) { 685 error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments", 686 command); 687 goto out; 688 } 689 if ((ca_fp = sshkey_fingerprint(cert->signature_key, 690 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) { 691 error("%s: sshkey_fingerprint failed", __func__); 692 goto out; 693 } 694 if ((key_fp = sshkey_fingerprint(key, 695 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) { 696 error("%s: sshkey_fingerprint failed", __func__); 697 goto out; 698 } 699 if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) { 700 error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); 701 goto out; 702 } 703 if ((r = sshkey_to_base64(key, &keytext)) != 0) { 704 error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); 705 goto out; 706 } 707 snprintf(serial_s, sizeof(serial_s), "%llu", 708 (unsigned long long)cert->serial); 709 for (i = 1; i < ac; i++) { 710 tmp = percent_expand(av[i], 711 "u", user_pw->pw_name, 712 "h", user_pw->pw_dir, 713 "t", sshkey_ssh_name(key), 714 "T", sshkey_ssh_name(cert->signature_key), 715 "f", key_fp, 716 "F", ca_fp, 717 "k", keytext, 718 "K", catext, 719 "i", cert->key_id, 720 "s", serial_s, 721 (char *)NULL); 722 if (tmp == NULL) 723 fatal("%s: percent_expand failed", __func__); 724 free(av[i]); 725 av[i] = tmp; 726 } 727 /* Prepare a printable command for logs, etc. */ 728 command = assemble_argv(ac, av); 729 730 if ((pid = subprocess("AuthorizedPrincipalsCommand", pw, command, 731 ac, av, &f)) == 0) 732 goto out; 733 734 uid_swapped = 1; 735 temporarily_use_uid(pw); 736 737 ok = process_principals(f, NULL, pw, cert); 738 739 if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command) != 0) 740 goto out; 741 742 /* Read completed successfully */ 743 found_principal = ok; 744 out: 745 if (f != NULL) 746 fclose(f); 747 signal(SIGCHLD, osigchld); 748 for (i = 0; i < ac; i++) 749 free(av[i]); 750 free(av); 751 if (uid_swapped) 752 restore_uid(); 753 free(command); 754 free(username); 755 free(ca_fp); 756 free(key_fp); 757 free(catext); 758 free(keytext); 759 return found_principal; 760} 761/* 762 * Checks whether key is allowed in authorized_keys-format file, 763 * returns 1 if the key is allowed or 0 otherwise. 764 */ 765static int 766check_authkeys_file(FILE *f, char *file, Key* key, struct passwd *pw) 767{ 768 char line[SSH_MAX_PUBKEY_BYTES]; 769 int found_key = 0; 770 u_long linenum = 0; 771 Key *found; 772#ifdef WITH_LDAP_PUBKEY 773 ldap_key_t * k; 774 unsigned int i = 0; 775#endif 776 777#ifdef WITH_LDAP_PUBKEY 778 found_key = 0; 779 /* allocate a new key type */ 780 found = key_new(key->type); 781 782 /* first check if the options is enabled, then try.. */ 783 if (options.lpk.on) { 784 debug("[LDAP] trying LDAP first uid=%s",pw->pw_name); 785 if (ldap_ismember(&options.lpk, pw->pw_name) > 0) { 786 if ((k = ldap_getuserkey(&options.lpk, pw->pw_name)) != NULL) { 787 /* Skip leading whitespace, empty and comment lines. */ 788 for (i = 0 ; i < k->num ; i++) { 789 /* dont forget if multiple keys to reset options */ 790 char *cp, *xoptions = NULL; 791 792 for (cp = (char *)k->keys[i]->bv_val; *cp == ' ' || *cp == '\t'; cp++) 793 ; 794 if (!*cp || *cp == '\n' || *cp == '#') 795 continue; 796 797 if (key_read(found, &cp) != 1) { 798 /* no key? check if there are options for this key */ 799 int quoted = 0; 800 debug2("[LDAP] user_key_allowed: check options: '%s'", cp); 801 xoptions = cp; 802 for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) { 803 if (*cp == '\\' && cp[1] == '"') 804 cp++; /* Skip both */ 805 else if (*cp == '"') 806 quoted = !quoted; 807 } 808 /* Skip remaining whitespace. */ 809 for (; *cp == ' ' || *cp == '\t'; cp++) 810 ; 811 if (key_read(found, &cp) != 1) { 812 debug2("[LDAP] user_key_allowed: advance: '%s'", cp); 813 /* still no key? advance to next line*/ 814 continue; 815 } 816 } 817 818 if (key_equal(found, key) && 819 auth_parse_options(pw, xoptions, file, linenum) == 1) { 820 found_key = 1; 821 debug("[LDAP] matching key found"); 822 char *fp = sshkey_fingerprint(found, SSH_FP_HASH_DEFAULT, SSH_FP_HEX); 823 verbose("[LDAP] Found matching %s key: %s", key_type(found), fp); 824 825 /* restoring memory */ 826 ldap_keys_free(k); 827 free(fp); 828 restore_uid(); 829 key_free(found); 830 return found_key; 831 break; 832 } 833 }/* end of LDAP for() */ 834 } else { 835 logit("[LDAP] no keys found for '%s'!", pw->pw_name); 836 } 837 } else { 838 logit("[LDAP] '%s' is not in '%s'", pw->pw_name, options.lpk.sgroup); 839 } 840 } 841#endif 842 843 found_key = 0; 844 845 found = NULL; 846 while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) { 847 char *cp, *key_options = NULL, *fp = NULL; 848 const char *reason = NULL; 849 850 if (found != NULL) 851 key_free(found); 852 found = key_new(key_is_cert(key) ? KEY_UNSPEC : key->type); 853 auth_clear_options(); 854 855 /* Skip leading whitespace, empty and comment lines. */ 856 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 857 ; 858 if (!*cp || *cp == '\n' || *cp == '#') 859 continue; 860 861 if (key_read(found, &cp) != 1) { 862 /* no key? check if there are options for this key */ 863 int quoted = 0; 864 debug2("user_key_allowed: check options: '%s'", cp); 865 key_options = cp; 866 for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) { 867 if (*cp == '\\' && cp[1] == '"') 868 cp++; /* Skip both */ 869 else if (*cp == '"') 870 quoted = !quoted; 871 } 872 /* Skip remaining whitespace. */ 873 for (; *cp == ' ' || *cp == '\t'; cp++) 874 ; 875 if (key_read(found, &cp) != 1) { 876 debug2("user_key_allowed: advance: '%s'", cp); 877 /* still no key? advance to next line*/ 878 continue; 879 } 880 } 881 if (key_is_cert(key)) { 882 if (!key_equal(found, key->cert->signature_key)) 883 continue; 884 if (auth_parse_options(pw, key_options, file, 885 linenum) != 1) 886 continue; 887 if (!key_is_cert_authority) 888 continue; 889 if ((fp = sshkey_fingerprint(found, 890 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 891 continue; 892 debug("matching CA found: file %s, line %lu, %s %s", 893 file, linenum, key_type(found), fp); 894 /* 895 * If the user has specified a list of principals as 896 * a key option, then prefer that list to matching 897 * their username in the certificate principals list. 898 */ 899 if (authorized_principals != NULL && 900 !match_principals_option(authorized_principals, 901 key->cert)) { 902 reason = "Certificate does not contain an " 903 "authorized principal"; 904 fail_reason: 905 free(fp); 906 error("%s", reason); 907 auth_debug_add("%s", reason); 908 continue; 909 } 910 if (key_cert_check_authority(key, 0, 0, 911 authorized_principals == NULL ? pw->pw_name : NULL, 912 &reason) != 0) 913 goto fail_reason; 914 if (auth_cert_options(key, pw, &reason) != 0) 915 goto fail_reason; 916 verbose("Accepted certificate ID \"%s\" (serial %llu) " 917 "signed by %s CA %s via %s", key->cert->key_id, 918 (unsigned long long)key->cert->serial, 919 key_type(found), fp, file); 920 free(fp); 921 found_key = 1; 922 break; 923 } else if (key_equal(found, key)) { 924 if (auth_parse_options(pw, key_options, file, 925 linenum) != 1) 926 continue; 927 if (key_is_cert_authority) 928 continue; 929 if ((fp = sshkey_fingerprint(found, 930 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 931 continue; 932 debug("matching key found: file %s, line %lu %s %s", 933 file, linenum, key_type(found), fp); 934 free(fp); 935 found_key = 1; 936 break; 937 } 938 } 939 if (found != NULL) 940 key_free(found); 941 if (!found_key) 942 debug2("key not found"); 943 return found_key; 944} 945 946/* Authenticate a certificate key against TrustedUserCAKeys */ 947static int 948user_cert_trusted_ca(struct passwd *pw, Key *key) 949{ 950 char *ca_fp, *principals_file = NULL; 951 const char *reason; 952 int ret = 0, found_principal = 0, use_authorized_principals; 953 954 if (!key_is_cert(key) || options.trusted_user_ca_keys == NULL) 955 return 0; 956 957 if ((ca_fp = sshkey_fingerprint(key->cert->signature_key, 958 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 959 return 0; 960 961 if (sshkey_in_file(key->cert->signature_key, 962 options.trusted_user_ca_keys, 1, 0) != 0) { 963 debug2("%s: CA %s %s is not listed in %s", __func__, 964 key_type(key->cert->signature_key), ca_fp, 965 options.trusted_user_ca_keys); 966 goto out; 967 } 968 /* 969 * If AuthorizedPrincipals is in use, then compare the certificate 970 * principals against the names in that file rather than matching 971 * against the username. 972 */ 973 if ((principals_file = authorized_principals_file(pw)) != NULL) { 974 if (match_principals_file(principals_file, pw, key->cert)) 975 found_principal = 1; 976 } 977 /* Try querying command if specified */ 978 if (!found_principal && match_principals_command(pw, key)) 979 found_principal = 1; 980 /* If principals file or command is specified, then require a match */ 981 use_authorized_principals = principals_file != NULL || 982 options.authorized_principals_command != NULL; 983 if (!found_principal && use_authorized_principals) { 984 reason = "Certificate does not contain an authorized principal"; 985 fail_reason: 986 error("%s", reason); 987 auth_debug_add("%s", reason); 988 goto out; 989 } 990 if (key_cert_check_authority(key, 0, 1, 991 use_authorized_principals ? NULL : pw->pw_name, &reason) != 0) 992 goto fail_reason; 993 if (auth_cert_options(key, pw, &reason) != 0) 994 goto fail_reason; 995 996 verbose("Accepted certificate ID \"%s\" (serial %llu) signed by " 997 "%s CA %s via %s", key->cert->key_id, 998 (unsigned long long)key->cert->serial, 999 key_type(key->cert->signature_key), ca_fp, 1000 options.trusted_user_ca_keys); 1001 ret = 1; 1002 1003 out: 1004 free(principals_file); 1005 free(ca_fp); 1006 return ret; 1007} 1008 1009/* 1010 * Checks whether key is allowed in file. 1011 * returns 1 if the key is allowed or 0 otherwise. 1012 */ 1013static int 1014user_key_allowed2(struct passwd *pw, Key *key, char *file) 1015{ 1016 FILE *f; 1017 int found_key = 0; 1018 1019 /* Temporarily use the user's uid. */ 1020 temporarily_use_uid(pw); 1021 1022 debug("trying public key file %s", file); 1023 if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) { 1024 found_key = check_authkeys_file(f, file, key, pw); 1025 fclose(f); 1026 } 1027 1028 restore_uid(); 1029 return found_key; 1030} 1031 1032/* 1033 * Checks whether key is allowed in output of command. 1034 * returns 1 if the key is allowed or 0 otherwise. 1035 */ 1036static int 1037user_key_command_allowed2(struct passwd *user_pw, Key *key) 1038{ 1039 FILE *f = NULL; 1040 int r, ok, found_key = 0; 1041 struct passwd *pw; 1042 int i, uid_swapped = 0, ac = 0; 1043 pid_t pid; 1044 char *username = NULL, *key_fp = NULL, *keytext = NULL; 1045 char *tmp, *command = NULL, **av = NULL; 1046 void (*osigchld)(int); 1047 1048 if (options.authorized_keys_command == NULL) 1049 return 0; 1050 if (options.authorized_keys_command_user == NULL) { 1051 error("No user for AuthorizedKeysCommand specified, skipping"); 1052 return 0; 1053 } 1054 1055 /* 1056 * NB. all returns later this function should go via "out" to 1057 * ensure the original SIGCHLD handler is restored properly. 1058 */ 1059 osigchld = signal(SIGCHLD, SIG_DFL); 1060 1061 /* Prepare and verify the user for the command */ 1062 username = percent_expand(options.authorized_keys_command_user, 1063 "u", user_pw->pw_name, (char *)NULL); 1064 pw = getpwnam(username); 1065 if (pw == NULL) { 1066 error("AuthorizedKeysCommandUser \"%s\" not found: %s", 1067 username, strerror(errno)); 1068 goto out; 1069 } 1070 1071 /* Prepare AuthorizedKeysCommand */ 1072 if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash, 1073 SSH_FP_DEFAULT)) == NULL) { 1074 error("%s: sshkey_fingerprint failed", __func__); 1075 goto out; 1076 } 1077 if ((r = sshkey_to_base64(key, &keytext)) != 0) { 1078 error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r)); 1079 goto out; 1080 } 1081 1082 /* Turn the command into an argument vector */ 1083 if (split_argv(options.authorized_keys_command, &ac, &av) != 0) { 1084 error("AuthorizedKeysCommand \"%s\" contains invalid quotes", 1085 command); 1086 goto out; 1087 } 1088 if (ac == 0) { 1089 error("AuthorizedKeysCommand \"%s\" yielded no arguments", 1090 command); 1091 goto out; 1092 } 1093 for (i = 1; i < ac; i++) { 1094 tmp = percent_expand(av[i], 1095 "u", user_pw->pw_name, 1096 "h", user_pw->pw_dir, 1097 "t", sshkey_ssh_name(key), 1098 "f", key_fp, 1099 "k", keytext, 1100 (char *)NULL); 1101 if (tmp == NULL) 1102 fatal("%s: percent_expand failed", __func__); 1103 free(av[i]); 1104 av[i] = tmp; 1105 } 1106 /* Prepare a printable command for logs, etc. */ 1107 command = assemble_argv(ac, av); 1108 1109 /* 1110 * If AuthorizedKeysCommand was run without arguments 1111 * then fall back to the old behaviour of passing the 1112 * target username as a single argument. 1113 */ 1114 if (ac == 1) { 1115 av = xreallocarray(av, ac + 2, sizeof(*av)); 1116 av[1] = xstrdup(user_pw->pw_name); 1117 av[2] = NULL; 1118 /* Fix up command too, since it is used in log messages */ 1119 free(command); 1120 xasprintf(&command, "%s %s", av[0], av[1]); 1121 } 1122 1123 if ((pid = subprocess("AuthorizedKeysCommand", pw, command, 1124 ac, av, &f)) == 0) 1125 goto out; 1126 1127 uid_swapped = 1; 1128 temporarily_use_uid(pw); 1129 1130 ok = check_authkeys_file(f, options.authorized_keys_command, key, pw); 1131 1132 if (exited_cleanly(pid, "AuthorizedKeysCommand", command) != 0) 1133 goto out; 1134 1135 /* Read completed successfully */ 1136 found_key = ok; 1137 out: 1138 if (f != NULL) 1139 fclose(f); 1140 signal(SIGCHLD, osigchld); 1141 for (i = 0; i < ac; i++) 1142 free(av[i]); 1143 free(av); 1144 if (uid_swapped) 1145 restore_uid(); 1146 free(command); 1147 free(username); 1148 free(key_fp); 1149 free(keytext); 1150 return found_key; 1151} 1152 1153/* 1154 * Check whether key authenticates and authorises the user. 1155 */ 1156int 1157user_key_allowed(struct passwd *pw, Key *key, int auth_attempt) 1158{ 1159 u_int success, i; 1160 char *file; 1161 1162 if (auth_key_is_revoked(key)) 1163 return 0; 1164 if (key_is_cert(key) && auth_key_is_revoked(key->cert->signature_key)) 1165 return 0; 1166 1167 success = user_cert_trusted_ca(pw, key); 1168 if (success) 1169 return success; 1170 1171 success = user_key_command_allowed2(pw, key); 1172 if (success > 0) 1173 return success; 1174 1175 for (i = 0; !success && i < options.num_authkeys_files; i++) { 1176 1177 if (strcasecmp(options.authorized_keys_files[i], "none") == 0) 1178 continue; 1179 file = expand_authorized_keys( 1180 options.authorized_keys_files[i], pw); 1181 1182 success = user_key_allowed2(pw, key, file); 1183 free(file); 1184 } 1185 1186 return success; 1187} 1188 1189/* Records a public key in the list of previously-successful keys */ 1190void 1191auth2_record_userkey(Authctxt *authctxt, struct sshkey *key) 1192{ 1193 struct sshkey **tmp; 1194 1195 if (authctxt->nprev_userkeys >= INT_MAX || 1196 (tmp = reallocarray(authctxt->prev_userkeys, 1197 authctxt->nprev_userkeys + 1, sizeof(*tmp))) == NULL) 1198 fatal("%s: reallocarray failed", __func__); 1199 authctxt->prev_userkeys = tmp; 1200 authctxt->prev_userkeys[authctxt->nprev_userkeys] = key; 1201 authctxt->nprev_userkeys++; 1202} 1203 1204/* Checks whether a key has already been used successfully for authentication */ 1205int 1206auth2_userkey_already_used(Authctxt *authctxt, struct sshkey *key) 1207{ 1208 u_int i; 1209 1210 for (i = 0; i < authctxt->nprev_userkeys; i++) { 1211 if (sshkey_equal_public(key, authctxt->prev_userkeys[i])) { 1212 return 1; 1213 } 1214 } 1215 return 0; 1216} 1217 1218Authmethod method_pubkey = { 1219 "publickey", 1220 userauth_pubkey, 1221 &options.pubkey_authentication 1222}; 1223