1 /* $NetBSD: auth.c,v 1.6 2012/12/12 17:42:39 christos Exp $ */ 2 /* $OpenBSD: auth.c,v 1.96 2012/05/13 01:42:32 dtucker Exp $ */ 3 /* 4 * Copyright (c) 2000 Markus Friedl. 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 __RCSID("$NetBSD: auth.c,v 1.6 2012/12/12 17:42:39 christos Exp $"); 29 #include <sys/types.h> 30 #include <sys/stat.h> 31 #include <sys/param.h> 32 33 #include <errno.h> 34 #include <fcntl.h> 35 #include <libgen.h> 36 #include <login_cap.h> 37 #include <paths.h> 38 #include <pwd.h> 39 #include <stdarg.h> 40 #include <stdio.h> 41 #include <string.h> 42 #include <unistd.h> 43 44 #include "xmalloc.h" 45 #include "match.h" 46 #include "groupaccess.h" 47 #include "log.h" 48 #include "buffer.h" 49 #include "servconf.h" 50 #include "key.h" 51 #include "hostfile.h" 52 #include "auth.h" 53 #include "auth-options.h" 54 #include "canohost.h" 55 #include "uidswap.h" 56 #include "misc.h" 57 #include "packet.h" 58 #ifdef GSSAPI 59 #include "ssh-gss.h" 60 #endif 61 #include "authfile.h" 62 #include "monitor_wrap.h" 63 64 #ifdef HAVE_LOGIN_CAP 65 #include <login_cap.h> 66 #endif 67 68 /* import */ 69 extern ServerOptions options; 70 extern int use_privsep; 71 72 /* Debugging messages */ 73 Buffer auth_debug; 74 int auth_debug_init; 75 76 /* 77 * Check if the user is allowed to log in via ssh. If user is listed 78 * in DenyUsers or one of user's groups is listed in DenyGroups, false 79 * will be returned. If AllowUsers isn't empty and user isn't listed 80 * there, or if AllowGroups isn't empty and one of user's groups isn't 81 * listed there, false will be returned. 82 * If the user's shell is not executable, false will be returned. 83 * Otherwise true is returned. 84 */ 85 int 86 allowed_user(struct passwd * pw) 87 { 88 #ifdef HAVE_LOGIN_CAP 89 extern login_cap_t *lc; 90 int match_name, match_ip; 91 char *cap_hlist, *hp; 92 #endif 93 struct stat st; 94 const char *hostname = NULL, *ipaddr = NULL; 95 u_int i; 96 97 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 98 if (!pw || !pw->pw_name) 99 return 0; 100 101 #ifdef HAVE_LOGIN_CAP 102 hostname = get_canonical_hostname(1); 103 ipaddr = get_remote_ipaddr(); 104 105 lc = login_getclass(pw->pw_class); 106 107 /* 108 * Check the deny list. 109 */ 110 cap_hlist = login_getcapstr(lc, "host.deny", NULL, NULL); 111 if (cap_hlist != NULL) { 112 hp = strtok(cap_hlist, ","); 113 while (hp != NULL) { 114 match_name = match_hostname(hostname, 115 hp, strlen(hp)); 116 match_ip = match_hostname(ipaddr, 117 hp, strlen(hp)); 118 /* 119 * Only a positive match here causes a "deny". 120 */ 121 if (match_name > 0 || match_ip > 0) { 122 free(cap_hlist); 123 login_close(lc); 124 return 0; 125 } 126 hp = strtok(NULL, ","); 127 } 128 free(cap_hlist); 129 } 130 131 /* 132 * Check the allow list. If the allow list exists, and the 133 * remote host is not in it, the user is implicitly denied. 134 */ 135 cap_hlist = login_getcapstr(lc, "host.allow", NULL, NULL); 136 if (cap_hlist != NULL) { 137 hp = strtok(cap_hlist, ","); 138 if (hp == NULL) { 139 /* Just in case there's an empty string... */ 140 free(cap_hlist); 141 login_close(lc); 142 return 0; 143 } 144 while (hp != NULL) { 145 match_name = match_hostname(hostname, 146 hp, strlen(hp)); 147 match_ip = match_hostname(ipaddr, 148 hp, strlen(hp)); 149 /* 150 * Negative match causes an immediate "deny". 151 * Positive match causes us to break out 152 * of the loop (allowing a fallthrough). 153 */ 154 if (match_name < 0 || match_ip < 0) { 155 free(cap_hlist); 156 login_close(lc); 157 return 0; 158 } 159 if (match_name > 0 || match_ip > 0) 160 break; 161 hp = strtok(NULL, ","); 162 } 163 free(cap_hlist); 164 if (hp == NULL) { 165 login_close(lc); 166 return 0; 167 } 168 } 169 170 login_close(lc); 171 #endif 172 173 #ifdef USE_PAM 174 if (!options.use_pam) { 175 #endif 176 /* 177 * password/account expiration. 178 */ 179 if (pw->pw_change || pw->pw_expire) { 180 struct timeval tv; 181 182 (void)gettimeofday(&tv, (struct timezone *)NULL); 183 if (pw->pw_expire) { 184 if (tv.tv_sec >= pw->pw_expire) { 185 logit("User %.100s not allowed because account has expired", 186 pw->pw_name); 187 return 0; /* expired */ 188 } 189 } 190 #ifdef _PASSWORD_CHGNOW 191 if (pw->pw_change == _PASSWORD_CHGNOW) { 192 logit("User %.100s not allowed because password needs to be changed", 193 pw->pw_name); 194 195 return 0; /* can't force password change (yet) */ 196 } 197 #endif 198 if (pw->pw_change) { 199 if (tv.tv_sec >= pw->pw_change) { 200 logit("User %.100s not allowed because password has expired", 201 pw->pw_name); 202 return 0; /* expired */ 203 } 204 } 205 } 206 #ifdef USE_PAM 207 } 208 #endif 209 210 /* 211 * Deny if shell does not exist or is not executable unless we 212 * are chrooting. 213 */ 214 /* 215 * XXX Should check to see if it is executable by the 216 * XXX requesting user. --thorpej 217 */ 218 if (options.chroot_directory == NULL || 219 strcasecmp(options.chroot_directory, "none") == 0) { 220 char *shell = xstrdup((pw->pw_shell[0] == '\0') ? 221 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */ 222 223 if (stat(shell, &st) != 0) { 224 logit("User %.100s not allowed because shell %.100s " 225 "does not exist", pw->pw_name, shell); 226 xfree(shell); 227 return 0; 228 } 229 if (S_ISREG(st.st_mode) == 0 || 230 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { 231 logit("User %.100s not allowed because shell %.100s " 232 "is not executable", pw->pw_name, shell); 233 xfree(shell); 234 return 0; 235 } 236 xfree(shell); 237 } 238 /* 239 * XXX Consider nuking {Allow,Deny}{Users,Groups}. We have the 240 * XXX login_cap(3) mechanism which covers all other types of 241 * XXX logins, too. 242 */ 243 244 if (options.num_deny_users > 0 || options.num_allow_users > 0 || 245 options.num_deny_groups > 0 || options.num_allow_groups > 0) { 246 hostname = get_canonical_hostname(options.use_dns); 247 ipaddr = get_remote_ipaddr(); 248 } 249 250 /* Return false if user is listed in DenyUsers */ 251 if (options.num_deny_users > 0) { 252 for (i = 0; i < options.num_deny_users; i++) 253 if (match_user(pw->pw_name, hostname, ipaddr, 254 options.deny_users[i])) { 255 logit("User %.100s from %.100s not allowed " 256 "because listed in DenyUsers", 257 pw->pw_name, hostname); 258 return 0; 259 } 260 } 261 /* Return false if AllowUsers isn't empty and user isn't listed there */ 262 if (options.num_allow_users > 0) { 263 for (i = 0; i < options.num_allow_users; i++) 264 if (match_user(pw->pw_name, hostname, ipaddr, 265 options.allow_users[i])) 266 break; 267 /* i < options.num_allow_users iff we break for loop */ 268 if (i >= options.num_allow_users) { 269 logit("User %.100s from %.100s not allowed because " 270 "not listed in AllowUsers", pw->pw_name, hostname); 271 return 0; 272 } 273 } 274 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { 275 /* Get the user's group access list (primary and supplementary) */ 276 if (ga_init(pw->pw_name, pw->pw_gid) == 0) { 277 logit("User %.100s from %.100s not allowed because " 278 "not in any group", pw->pw_name, hostname); 279 return 0; 280 } 281 282 /* Return false if one of user's groups is listed in DenyGroups */ 283 if (options.num_deny_groups > 0) 284 if (ga_match(options.deny_groups, 285 options.num_deny_groups)) { 286 ga_free(); 287 logit("User %.100s from %.100s not allowed " 288 "because a group is listed in DenyGroups", 289 pw->pw_name, hostname); 290 return 0; 291 } 292 /* 293 * Return false if AllowGroups isn't empty and one of user's groups 294 * isn't listed there 295 */ 296 if (options.num_allow_groups > 0) 297 if (!ga_match(options.allow_groups, 298 options.num_allow_groups)) { 299 ga_free(); 300 logit("User %.100s from %.100s not allowed " 301 "because none of user's groups are listed " 302 "in AllowGroups", pw->pw_name, hostname); 303 return 0; 304 } 305 ga_free(); 306 } 307 /* We found no reason not to let this user try to log on... */ 308 return 1; 309 } 310 311 void 312 auth_log(Authctxt *authctxt, int authenticated, const char *method, 313 const char *info) 314 { 315 void (*authlog) (const char *fmt,...) = verbose; 316 const char *authmsg; 317 318 if (use_privsep && !mm_is_monitor() && !authctxt->postponed) 319 return; 320 321 /* Raise logging level */ 322 if (authenticated == 1 || 323 !authctxt->valid || 324 authctxt->failures >= options.max_authtries / 2 || 325 strcmp(method, "password") == 0) 326 authlog = logit; 327 328 if (authctxt->postponed) 329 authmsg = "Postponed"; 330 else 331 authmsg = authenticated ? "Accepted" : "Failed"; 332 333 authlog("%s %s for %s%.100s from %.200s port %d%s", 334 authmsg, 335 method, 336 authctxt->valid ? "" : "invalid user ", 337 authctxt->user, 338 get_remote_ipaddr(), 339 get_remote_port(), 340 info); 341 } 342 343 /* 344 * Check whether root logins are disallowed. 345 */ 346 int 347 auth_root_allowed(const char *method) 348 { 349 switch (options.permit_root_login) { 350 case PERMIT_YES: 351 return 1; 352 case PERMIT_NO_PASSWD: 353 if (strcmp(method, "password") != 0) 354 return 1; 355 break; 356 case PERMIT_FORCED_ONLY: 357 if (forced_command) { 358 logit("Root login accepted for forced command."); 359 return 1; 360 } 361 break; 362 } 363 logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr()); 364 return 0; 365 } 366 367 368 /* 369 * Given a template and a passwd structure, build a filename 370 * by substituting % tokenised options. Currently, %% becomes '%', 371 * %h becomes the home directory and %u the username. 372 * 373 * This returns a buffer allocated by xmalloc. 374 */ 375 char * 376 expand_authorized_keys(const char *filename, struct passwd *pw) 377 { 378 char *file, ret[MAXPATHLEN]; 379 int i; 380 381 file = percent_expand(filename, "h", pw->pw_dir, 382 "u", pw->pw_name, (char *)NULL); 383 384 /* 385 * Ensure that filename starts anchored. If not, be backward 386 * compatible and prepend the '%h/' 387 */ 388 if (*file == '/') 389 return (file); 390 391 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file); 392 if (i < 0 || (size_t)i >= sizeof(ret)) 393 fatal("expand_authorized_keys: path too long"); 394 xfree(file); 395 return (xstrdup(ret)); 396 } 397 398 char * 399 authorized_principals_file(struct passwd *pw) 400 { 401 if (options.authorized_principals_file == NULL || 402 strcasecmp(options.authorized_principals_file, "none") == 0) 403 return NULL; 404 return expand_authorized_keys(options.authorized_principals_file, pw); 405 } 406 407 /* return ok if key exists in sysfile or userfile */ 408 HostStatus 409 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host, 410 const char *sysfile, const char *userfile) 411 { 412 char *user_hostfile; 413 struct stat st; 414 HostStatus host_status; 415 struct hostkeys *hostkeys; 416 const struct hostkey_entry *found; 417 418 hostkeys = init_hostkeys(); 419 load_hostkeys(hostkeys, host, sysfile); 420 if (userfile != NULL) { 421 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid); 422 if (options.strict_modes && 423 (stat(user_hostfile, &st) == 0) && 424 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) || 425 (st.st_mode & 022) != 0)) { 426 logit("Authentication refused for %.100s: " 427 "bad owner or modes for %.200s", 428 pw->pw_name, user_hostfile); 429 auth_debug_add("Ignored %.200s: bad ownership or modes", 430 user_hostfile); 431 } else { 432 temporarily_use_uid(pw); 433 load_hostkeys(hostkeys, host, user_hostfile); 434 restore_uid(); 435 } 436 xfree(user_hostfile); 437 } 438 host_status = check_key_in_hostkeys(hostkeys, key, &found); 439 if (host_status == HOST_REVOKED) 440 error("WARNING: revoked key for %s attempted authentication", 441 found->host); 442 else if (host_status == HOST_OK) 443 debug("%s: key for %s found at %s:%ld", __func__, 444 found->host, found->file, found->line); 445 else 446 debug("%s: key for host %s not found", __func__, host); 447 448 free_hostkeys(hostkeys); 449 450 return host_status; 451 } 452 453 454 /* 455 * Check a given file for security. This is defined as all components 456 * of the path to the file must be owned by either the owner of 457 * of the file or root and no directories must be group or world writable. 458 * 459 * XXX Should any specific check be done for sym links ? 460 * 461 * Takes an open file descriptor, the file name, a uid and and 462 * error buffer plus max size as arguments. 463 * 464 * Returns 0 on success and -1 on failure 465 */ 466 static int 467 secure_filename(FILE *f, const char *file, struct passwd *pw, 468 char *err, size_t errlen) 469 { 470 uid_t uid = pw->pw_uid; 471 char buf[MAXPATHLEN], homedir[MAXPATHLEN]; 472 char *cp; 473 int comparehome = 0; 474 struct stat st; 475 476 if (realpath(file, buf) == NULL) { 477 snprintf(err, errlen, "realpath %s failed: %s", file, 478 strerror(errno)); 479 return -1; 480 } 481 if (realpath(pw->pw_dir, homedir) != NULL) 482 comparehome = 1; 483 484 /* check the open file to avoid races */ 485 if (fstat(fileno(f), &st) < 0 || 486 (st.st_uid != 0 && st.st_uid != uid) || 487 (st.st_mode & 022) != 0) { 488 snprintf(err, errlen, "bad ownership or modes for file %s", 489 buf); 490 return -1; 491 } 492 493 /* for each component of the canonical path, walking upwards */ 494 for (;;) { 495 if ((cp = dirname(buf)) == NULL) { 496 snprintf(err, errlen, "dirname() failed"); 497 return -1; 498 } 499 strlcpy(buf, cp, sizeof(buf)); 500 501 if (stat(buf, &st) < 0 || 502 (st.st_uid != 0 && st.st_uid != uid) || 503 (st.st_mode & 022) != 0) { 504 snprintf(err, errlen, 505 "bad ownership or modes for directory %s", buf); 506 return -1; 507 } 508 509 /* If are past the homedir then we can stop */ 510 if (comparehome && strcmp(homedir, buf) == 0) 511 break; 512 513 /* 514 * dirname should always complete with a "/" path, 515 * but we can be paranoid and check for "." too 516 */ 517 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0)) 518 break; 519 } 520 return 0; 521 } 522 523 static FILE * 524 auth_openfile(const char *file, struct passwd *pw, int strict_modes, 525 int log_missing, const char *file_type) 526 { 527 char line[1024]; 528 struct stat st; 529 int fd; 530 FILE *f; 531 532 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) { 533 if (log_missing || errno != ENOENT) 534 debug("Could not open %s '%s': %s", file_type, file, 535 strerror(errno)); 536 return NULL; 537 } 538 539 if (fstat(fd, &st) < 0) { 540 close(fd); 541 return NULL; 542 } 543 if (!S_ISREG(st.st_mode)) { 544 logit("User %s %s %s is not a regular file", 545 pw->pw_name, file_type, file); 546 close(fd); 547 return NULL; 548 } 549 unset_nonblock(fd); 550 if ((f = fdopen(fd, "r")) == NULL) { 551 close(fd); 552 return NULL; 553 } 554 if (strict_modes && 555 secure_filename(f, file, pw, line, sizeof(line)) != 0) { 556 fclose(f); 557 logit("Authentication refused: %s", line); 558 auth_debug_add("Ignored %s: %s", file_type, line); 559 return NULL; 560 } 561 562 return f; 563 } 564 565 566 FILE * 567 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes) 568 { 569 return auth_openfile(file, pw, strict_modes, 1, "authorized keys"); 570 } 571 572 FILE * 573 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes) 574 { 575 return auth_openfile(file, pw, strict_modes, 0, 576 "authorized principals"); 577 } 578 579 struct passwd * 580 getpwnamallow(const char *user) 581 { 582 #ifdef HAVE_LOGIN_CAP 583 extern login_cap_t *lc; 584 #ifdef BSD_AUTH 585 auth_session_t *as; 586 #endif 587 #endif 588 struct passwd *pw; 589 struct connection_info *ci = get_connection_info(1, options.use_dns); 590 591 ci->user = user; 592 parse_server_match_config(&options, ci); 593 594 pw = getpwnam(user); 595 if (pw == NULL) { 596 logit("Invalid user %.100s from %.100s", 597 user, get_remote_ipaddr()); 598 return (NULL); 599 } 600 if (!allowed_user(pw)) 601 return (NULL); 602 #ifdef HAVE_LOGIN_CAP 603 if ((lc = login_getclass(pw->pw_class)) == NULL) { 604 debug("unable to get login class: %s", user); 605 return (NULL); 606 } 607 #ifdef BSD_AUTH 608 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 609 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 610 debug("Approval failure for %s", user); 611 pw = NULL; 612 } 613 if (as != NULL) 614 auth_close(as); 615 #endif 616 #endif 617 if (pw != NULL) 618 return (pwcopy(pw)); 619 return (NULL); 620 } 621 622 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 623 int 624 auth_key_is_revoked(Key *key) 625 { 626 char *key_fp; 627 628 if (options.revoked_keys_file == NULL) 629 return 0; 630 631 switch (key_in_file(key, options.revoked_keys_file, 0)) { 632 case 0: 633 /* key not revoked */ 634 return 0; 635 case -1: 636 /* Error opening revoked_keys_file: refuse all keys */ 637 error("Revoked keys file is unreadable: refusing public key " 638 "authentication"); 639 return 1; 640 case 1: 641 /* Key revoked */ 642 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX); 643 error("WARNING: authentication attempt with a revoked " 644 "%s key %s ", key_type(key), key_fp); 645 xfree(key_fp); 646 return 1; 647 } 648 fatal("key_in_file returned junk"); 649 } 650 651 void 652 auth_debug_add(const char *fmt,...) 653 { 654 char buf[1024]; 655 va_list args; 656 657 if (!auth_debug_init) 658 return; 659 660 va_start(args, fmt); 661 vsnprintf(buf, sizeof(buf), fmt, args); 662 va_end(args); 663 buffer_put_cstring(&auth_debug, buf); 664 } 665 666 void 667 auth_debug_send(void) 668 { 669 char *msg; 670 671 if (!auth_debug_init) 672 return; 673 while (buffer_len(&auth_debug)) { 674 msg = buffer_get_string(&auth_debug, NULL); 675 packet_send_debug("%s", msg); 676 xfree(msg); 677 } 678 } 679 680 void 681 auth_debug_reset(void) 682 { 683 if (auth_debug_init) 684 buffer_clear(&auth_debug); 685 else { 686 buffer_init(&auth_debug); 687 auth_debug_init = 1; 688 } 689 } 690 691 struct passwd * 692 fakepw(void) 693 { 694 static struct passwd fake; 695 static char nouser[] = "NOUSER"; 696 static char nonexist[] = "/nonexist"; 697 698 memset(&fake, 0, sizeof(fake)); 699 fake.pw_name = nouser; 700 fake.pw_passwd = __UNCONST( 701 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"); 702 fake.pw_gecos = nouser; 703 fake.pw_uid = (uid_t)-1; 704 fake.pw_gid = (gid_t)-1; 705 fake.pw_class = __UNCONST(""); 706 fake.pw_dir = nonexist; 707 fake.pw_shell = nonexist; 708 709 return (&fake); 710 } 711