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