1 /* $NetBSD: auth.c,v 1.3 2010/11/21 18:29:48 adam Exp $ */ 2 /* $OpenBSD: auth.c,v 1.89 2010/08/04 05:42:47 djm 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.3 2010/11/21 18:29:48 adam 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, char *method, char *info) 313 { 314 void (*authlog) (const char *fmt,...) = verbose; 315 char *authmsg; 316 317 if (use_privsep && !mm_is_monitor() && !authctxt->postponed) 318 return; 319 320 /* Raise logging level */ 321 if (authenticated == 1 || 322 !authctxt->valid || 323 authctxt->failures >= options.max_authtries / 2 || 324 strcmp(method, "password") == 0) 325 authlog = logit; 326 327 if (authctxt->postponed) 328 authmsg = "Postponed"; 329 else 330 authmsg = authenticated ? "Accepted" : "Failed"; 331 332 authlog("%s %s for %s%.100s from %.200s port %d%s", 333 authmsg, 334 method, 335 authctxt->valid ? "" : "invalid user ", 336 authctxt->user, 337 get_remote_ipaddr(), 338 get_remote_port(), 339 info); 340 } 341 342 /* 343 * Check whether root logins are disallowed. 344 */ 345 int 346 auth_root_allowed(char *method) 347 { 348 switch (options.permit_root_login) { 349 case PERMIT_YES: 350 return 1; 351 case PERMIT_NO_PASSWD: 352 if (strcmp(method, "password") != 0) 353 return 1; 354 break; 355 case PERMIT_FORCED_ONLY: 356 if (forced_command) { 357 logit("Root login accepted for forced command."); 358 return 1; 359 } 360 break; 361 } 362 logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr()); 363 return 0; 364 } 365 366 367 /* 368 * Given a template and a passwd structure, build a filename 369 * by substituting % tokenised options. Currently, %% becomes '%', 370 * %h becomes the home directory and %u the username. 371 * 372 * This returns a buffer allocated by xmalloc. 373 */ 374 static char * 375 expand_authorized_keys(const char *filename, struct passwd *pw) 376 { 377 char *file, ret[MAXPATHLEN]; 378 int i; 379 380 file = percent_expand(filename, "h", pw->pw_dir, 381 "u", pw->pw_name, (char *)NULL); 382 383 /* 384 * Ensure that filename starts anchored. If not, be backward 385 * compatible and prepend the '%h/' 386 */ 387 if (*file == '/') 388 return (file); 389 390 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file); 391 if (i < 0 || (size_t)i >= sizeof(ret)) 392 fatal("expand_authorized_keys: path too long"); 393 xfree(file); 394 return (xstrdup(ret)); 395 } 396 397 char * 398 authorized_keys_file(struct passwd *pw) 399 { 400 return expand_authorized_keys(options.authorized_keys_file, pw); 401 } 402 403 char * 404 authorized_keys_file2(struct passwd *pw) 405 { 406 return expand_authorized_keys(options.authorized_keys_file2, pw); 407 } 408 409 char * 410 authorized_principals_file(struct passwd *pw) 411 { 412 if (options.authorized_principals_file == NULL) 413 return NULL; 414 return expand_authorized_keys(options.authorized_principals_file, pw); 415 } 416 417 /* return ok if key exists in sysfile or userfile */ 418 HostStatus 419 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host, 420 const char *sysfile, const char *userfile) 421 { 422 Key *found; 423 char *user_hostfile; 424 struct stat st; 425 HostStatus host_status; 426 427 /* Check if we know the host and its host key. */ 428 found = key_new(key_is_cert(key) ? KEY_UNSPEC : key->type); 429 host_status = check_host_in_hostfile(sysfile, host, key, found, NULL); 430 431 if (host_status != HOST_OK && userfile != NULL) { 432 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid); 433 if (options.strict_modes && 434 (stat(user_hostfile, &st) == 0) && 435 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) || 436 (st.st_mode & 022) != 0)) { 437 logit("Authentication refused for %.100s: " 438 "bad owner or modes for %.200s", 439 pw->pw_name, user_hostfile); 440 auth_debug_add("Ignored %.200s: bad ownership or modes", 441 user_hostfile); 442 } else { 443 temporarily_use_uid(pw); 444 host_status = check_host_in_hostfile(user_hostfile, 445 host, key, found, NULL); 446 restore_uid(); 447 } 448 xfree(user_hostfile); 449 } 450 key_free(found); 451 452 debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ? 453 "ok" : "not found", host); 454 return host_status; 455 } 456 457 458 /* 459 * Check a given file for security. This is defined as all components 460 * of the path to the file must be owned by either the owner of 461 * of the file or root and no directories must be group or world writable. 462 * 463 * XXX Should any specific check be done for sym links ? 464 * 465 * Takes an open file descriptor, the file name, a uid and and 466 * error buffer plus max size as arguments. 467 * 468 * Returns 0 on success and -1 on failure 469 */ 470 static int 471 secure_filename(FILE *f, const char *file, struct passwd *pw, 472 char *err, size_t errlen) 473 { 474 uid_t uid = pw->pw_uid; 475 char buf[MAXPATHLEN], homedir[MAXPATHLEN]; 476 char *cp; 477 int comparehome = 0; 478 struct stat st; 479 480 if (realpath(file, buf) == NULL) { 481 snprintf(err, errlen, "realpath %s failed: %s", file, 482 strerror(errno)); 483 return -1; 484 } 485 if (realpath(pw->pw_dir, homedir) != NULL) 486 comparehome = 1; 487 488 /* check the open file to avoid races */ 489 if (fstat(fileno(f), &st) < 0 || 490 (st.st_uid != 0 && st.st_uid != uid) || 491 (st.st_mode & 022) != 0) { 492 snprintf(err, errlen, "bad ownership or modes for file %s", 493 buf); 494 return -1; 495 } 496 497 /* for each component of the canonical path, walking upwards */ 498 for (;;) { 499 if ((cp = dirname(buf)) == NULL) { 500 snprintf(err, errlen, "dirname() failed"); 501 return -1; 502 } 503 strlcpy(buf, cp, sizeof(buf)); 504 505 debug3("secure_filename: checking '%s'", buf); 506 if (stat(buf, &st) < 0 || 507 (st.st_uid != 0 && st.st_uid != uid) || 508 (st.st_mode & 022) != 0) { 509 snprintf(err, errlen, 510 "bad ownership or modes for directory %s", buf); 511 return -1; 512 } 513 514 /* If are past the homedir then we can stop */ 515 if (comparehome && strcmp(homedir, buf) == 0) { 516 debug3("secure_filename: terminating check at '%s'", 517 buf); 518 break; 519 } 520 /* 521 * dirname should always complete with a "/" path, 522 * but we can be paranoid and check for "." too 523 */ 524 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0)) 525 break; 526 } 527 return 0; 528 } 529 530 static FILE * 531 auth_openfile(const char *file, struct passwd *pw, int strict_modes, 532 int log_missing, char *file_type) 533 { 534 char line[1024]; 535 struct stat st; 536 int fd; 537 FILE *f; 538 539 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) { 540 if (log_missing || errno != ENOENT) 541 debug("Could not open %s '%s': %s", file_type, file, 542 strerror(errno)); 543 return NULL; 544 } 545 546 if (fstat(fd, &st) < 0) { 547 close(fd); 548 return NULL; 549 } 550 if (!S_ISREG(st.st_mode)) { 551 logit("User %s %s %s is not a regular file", 552 pw->pw_name, file_type, file); 553 close(fd); 554 return NULL; 555 } 556 unset_nonblock(fd); 557 if ((f = fdopen(fd, "r")) == NULL) { 558 close(fd); 559 return NULL; 560 } 561 if (options.strict_modes && 562 secure_filename(f, file, pw, line, sizeof(line)) != 0) { 563 fclose(f); 564 logit("Authentication refused: %s", line); 565 auth_debug_add("Ignored %s: %s", file_type, line); 566 return NULL; 567 } 568 569 return f; 570 } 571 572 573 FILE * 574 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes) 575 { 576 return auth_openfile(file, pw, strict_modes, 1, "authorized keys"); 577 } 578 579 FILE * 580 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes) 581 { 582 return auth_openfile(file, pw, strict_modes, 0, 583 "authorized principals"); 584 } 585 586 struct passwd * 587 getpwnamallow(const char *user) 588 { 589 #ifdef HAVE_LOGIN_CAP 590 extern login_cap_t *lc; 591 #ifdef BSD_AUTH 592 auth_session_t *as; 593 #endif 594 #endif 595 struct passwd *pw; 596 597 parse_server_match_config(&options, user, 598 get_canonical_hostname(options.use_dns), get_remote_ipaddr()); 599 600 pw = getpwnam(user); 601 if (pw == NULL) { 602 logit("Invalid user %.100s from %.100s", 603 user, get_remote_ipaddr()); 604 return (NULL); 605 } 606 if (!allowed_user(pw)) 607 return (NULL); 608 #ifdef HAVE_LOGIN_CAP 609 if ((lc = login_getclass(pw->pw_class)) == NULL) { 610 debug("unable to get login class: %s", user); 611 return (NULL); 612 } 613 #ifdef BSD_AUTH 614 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 615 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 616 debug("Approval failure for %s", user); 617 pw = NULL; 618 } 619 if (as != NULL) 620 auth_close(as); 621 #endif 622 #endif 623 if (pw != NULL) 624 return (pwcopy(pw)); 625 return (NULL); 626 } 627 628 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 629 int 630 auth_key_is_revoked(Key *key) 631 { 632 char *key_fp; 633 634 if (options.revoked_keys_file == NULL) 635 return 0; 636 637 switch (key_in_file(key, options.revoked_keys_file, 0)) { 638 case 0: 639 /* key not revoked */ 640 return 0; 641 case -1: 642 /* Error opening revoked_keys_file: refuse all keys */ 643 error("Revoked keys file is unreadable: refusing public key " 644 "authentication"); 645 return 1; 646 case 1: 647 /* Key revoked */ 648 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX); 649 error("WARNING: authentication attempt with a revoked " 650 "%s key %s ", key_type(key), key_fp); 651 xfree(key_fp); 652 return 1; 653 } 654 fatal("key_in_file returned junk"); 655 } 656 657 void 658 auth_debug_add(const char *fmt,...) 659 { 660 char buf[1024]; 661 va_list args; 662 663 if (!auth_debug_init) 664 return; 665 666 va_start(args, fmt); 667 vsnprintf(buf, sizeof(buf), fmt, args); 668 va_end(args); 669 buffer_put_cstring(&auth_debug, buf); 670 } 671 672 void 673 auth_debug_send(void) 674 { 675 char *msg; 676 677 if (!auth_debug_init) 678 return; 679 while (buffer_len(&auth_debug)) { 680 msg = buffer_get_string(&auth_debug, NULL); 681 packet_send_debug("%s", msg); 682 xfree(msg); 683 } 684 } 685 686 void 687 auth_debug_reset(void) 688 { 689 if (auth_debug_init) 690 buffer_clear(&auth_debug); 691 else { 692 buffer_init(&auth_debug); 693 auth_debug_init = 1; 694 } 695 } 696 697 struct passwd * 698 fakepw(void) 699 { 700 static struct passwd fake; 701 702 memset(&fake, 0, sizeof(fake)); 703 fake.pw_name = "NOUSER"; 704 fake.pw_passwd = 705 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"; 706 fake.pw_gecos = "NOUSER"; 707 fake.pw_uid = (uid_t)-1; 708 fake.pw_gid = (gid_t)-1; 709 fake.pw_class = ""; 710 fake.pw_dir = "/nonexist"; 711 fake.pw_shell = "/nonexist"; 712 713 return (&fake); 714 } 715