Annotation of src/usr.bin/ssh/auth.c, Revision 1.132
1.132 ! martijn 1: /* $OpenBSD: auth.c,v 1.131 2018/07/09 21:35:50 markus Exp $ */
1.1 markus 2: /*
1.19 deraadt 3: * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.9 deraadt 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.
1.1 markus 24: */
25:
1.62 stevesk 26: #include <sys/types.h>
27: #include <sys/stat.h>
1.114 djm 28: #include <sys/socket.h>
1.125 markus 29: #include <sys/wait.h>
1.22 markus 30:
1.70 stevesk 31: #include <errno.h>
1.79 dtucker 32: #include <fcntl.h>
1.77 djm 33: #include <login_cap.h>
1.61 stevesk 34: #include <paths.h>
1.68 stevesk 35: #include <pwd.h>
1.69 stevesk 36: #include <stdarg.h>
1.74 stevesk 37: #include <stdio.h>
1.72 stevesk 38: #include <string.h>
1.80 djm 39: #include <unistd.h>
1.109 deraadt 40: #include <limits.h>
1.114 djm 41: #include <netdb.h>
1.1 markus 42:
43: #include "xmalloc.h"
1.13 markus 44: #include "match.h"
1.14 markus 45: #include "groupaccess.h"
46: #include "log.h"
1.131 markus 47: #include "sshbuf.h"
1.106 millert 48: #include "misc.h"
1.1 markus 49: #include "servconf.h"
1.131 markus 50: #include "sshkey.h"
1.75 deraadt 51: #include "hostfile.h"
1.2 markus 52: #include "auth.h"
1.13 markus 53: #include "auth-options.h"
1.14 markus 54: #include "canohost.h"
1.24 markus 55: #include "uidswap.h"
1.42 markus 56: #include "packet.h"
1.75 deraadt 57: #ifdef GSSAPI
58: #include "ssh-gss.h"
59: #endif
1.85 djm 60: #include "authfile.h"
1.67 dtucker 61: #include "monitor_wrap.h"
1.107 djm 62: #include "authfile.h"
63: #include "ssherr.h"
1.103 djm 64: #include "compat.h"
1.126 djm 65: #include "channels.h"
1.2 markus 66:
1.1 markus 67: /* import */
68: extern ServerOptions options;
1.67 dtucker 69: extern int use_privsep;
1.126 djm 70: extern struct sshauthopt *auth_opts;
1.1 markus 71:
1.42 markus 72: /* Debugging messages */
1.131 markus 73: static struct sshbuf *auth_debug;
1.42 markus 74:
1.1 markus 75: /*
1.12 markus 76: * Check if the user is allowed to log in via ssh. If user is listed
77: * in DenyUsers or one of user's groups is listed in DenyGroups, false
78: * will be returned. If AllowUsers isn't empty and user isn't listed
79: * there, or if AllowGroups isn't empty and one of user's groups isn't
80: * listed there, false will be returned.
1.1 markus 81: * If the user's shell is not executable, false will be returned.
1.4 markus 82: * Otherwise true is returned.
1.1 markus 83: */
1.5 markus 84: int
1.1 markus 85: allowed_user(struct passwd * pw)
86: {
1.114 djm 87: struct ssh *ssh = active_state; /* XXX */
1.1 markus 88: struct stat st;
1.35 markus 89: const char *hostname = NULL, *ipaddr = NULL;
1.117 djm 90: int r;
1.60 djm 91: u_int i;
1.1 markus 92:
93: /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1.12 markus 94: if (!pw || !pw->pw_name)
1.1 markus 95: return 0;
96:
1.7 deraadt 97: /*
1.84 djm 98: * Deny if shell does not exist or is not executable unless we
99: * are chrooting.
1.7 deraadt 100: */
1.84 djm 101: if (options.chroot_directory == NULL ||
102: strcasecmp(options.chroot_directory, "none") == 0) {
103: char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
104: _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
105:
106: if (stat(shell, &st) != 0) {
107: logit("User %.100s not allowed because shell %.100s "
108: "does not exist", pw->pw_name, shell);
1.102 djm 109: free(shell);
1.84 djm 110: return 0;
111: }
112: if (S_ISREG(st.st_mode) == 0 ||
113: (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
114: logit("User %.100s not allowed because shell %.100s "
115: "is not executable", pw->pw_name, shell);
1.102 djm 116: free(shell);
1.84 djm 117: return 0;
118: }
1.102 djm 119: free(shell);
1.34 stevesk 120: }
1.1 markus 121:
1.58 dtucker 122: if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
123: options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1.114 djm 124: hostname = auth_get_canonical_hostname(ssh, options.use_dns);
125: ipaddr = ssh_remote_ipaddr(ssh);
1.35 markus 126: }
127:
1.1 markus 128: /* Return false if user is listed in DenyUsers */
129: if (options.num_deny_users > 0) {
1.119 dtucker 130: for (i = 0; i < options.num_deny_users; i++) {
1.117 djm 131: r = match_user(pw->pw_name, hostname, ipaddr,
132: options.deny_users[i]);
133: if (r < 0) {
134: fatal("Invalid DenyUsers pattern \"%.100s\"",
135: options.deny_users[i]);
1.118 djm 136: } else if (r != 0) {
1.57 dtucker 137: logit("User %.100s from %.100s not allowed "
138: "because listed in DenyUsers",
139: pw->pw_name, hostname);
1.1 markus 140: return 0;
1.34 stevesk 141: }
1.119 dtucker 142: }
1.1 markus 143: }
144: /* Return false if AllowUsers isn't empty and user isn't listed there */
145: if (options.num_allow_users > 0) {
1.117 djm 146: for (i = 0; i < options.num_allow_users; i++) {
147: r = match_user(pw->pw_name, hostname, ipaddr,
148: options.allow_users[i]);
149: if (r < 0) {
150: fatal("Invalid AllowUsers pattern \"%.100s\"",
151: options.allow_users[i]);
152: } else if (r == 1)
1.1 markus 153: break;
1.117 djm 154: }
1.1 markus 155: /* i < options.num_allow_users iff we break for loop */
1.34 stevesk 156: if (i >= options.num_allow_users) {
1.57 dtucker 157: logit("User %.100s from %.100s not allowed because "
158: "not listed in AllowUsers", pw->pw_name, hostname);
1.1 markus 159: return 0;
1.34 stevesk 160: }
1.1 markus 161: }
162: if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1.12 markus 163: /* Get the user's group access list (primary and supplementary) */
1.34 stevesk 164: if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
1.57 dtucker 165: logit("User %.100s from %.100s not allowed because "
166: "not in any group", pw->pw_name, hostname);
1.1 markus 167: return 0;
1.34 stevesk 168: }
1.1 markus 169:
1.12 markus 170: /* Return false if one of user's groups is listed in DenyGroups */
171: if (options.num_deny_groups > 0)
172: if (ga_match(options.deny_groups,
173: options.num_deny_groups)) {
174: ga_free();
1.57 dtucker 175: logit("User %.100s from %.100s not allowed "
176: "because a group is listed in DenyGroups",
177: pw->pw_name, hostname);
1.1 markus 178: return 0;
1.12 markus 179: }
1.1 markus 180: /*
1.12 markus 181: * Return false if AllowGroups isn't empty and one of user's groups
1.1 markus 182: * isn't listed there
183: */
1.12 markus 184: if (options.num_allow_groups > 0)
185: if (!ga_match(options.allow_groups,
186: options.num_allow_groups)) {
187: ga_free();
1.57 dtucker 188: logit("User %.100s from %.100s not allowed "
189: "because none of user's groups are listed "
190: "in AllowGroups", pw->pw_name, hostname);
1.1 markus 191: return 0;
1.12 markus 192: }
193: ga_free();
1.1 markus 194: }
195: /* We found no reason not to let this user try to log on... */
196: return 1;
1.13 markus 197: }
198:
1.122 djm 199: /*
200: * Formats any key left in authctxt->auth_method_key for inclusion in
201: * auth_log()'s message. Also includes authxtct->auth_method_info if present.
202: */
203: static char *
204: format_method_key(Authctxt *authctxt)
1.103 djm 205: {
1.122 djm 206: const struct sshkey *key = authctxt->auth_method_key;
207: const char *methinfo = authctxt->auth_method_info;
208: char *fp, *ret = NULL;
209:
210: if (key == NULL)
211: return NULL;
212:
1.131 markus 213: if (sshkey_is_cert(key)) {
1.122 djm 214: fp = sshkey_fingerprint(key->cert->signature_key,
215: options.fingerprint_hash, SSH_FP_DEFAULT);
216: xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s",
217: sshkey_type(key), key->cert->key_id,
218: (unsigned long long)key->cert->serial,
219: sshkey_type(key->cert->signature_key),
220: fp == NULL ? "(null)" : fp,
221: methinfo == NULL ? "" : ", ",
222: methinfo == NULL ? "" : methinfo);
223: free(fp);
224: } else {
225: fp = sshkey_fingerprint(key, options.fingerprint_hash,
226: SSH_FP_DEFAULT);
227: xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
228: fp == NULL ? "(null)" : fp,
229: methinfo == NULL ? "" : ", ",
230: methinfo == NULL ? "" : methinfo);
231: free(fp);
232: }
233: return ret;
1.103 djm 234: }
235:
236: void
1.98 djm 237: auth_log(Authctxt *authctxt, int authenticated, int partial,
1.103 djm 238: const char *method, const char *submethod)
1.13 markus 239: {
1.114 djm 240: struct ssh *ssh = active_state; /* XXX */
1.13 markus 241: void (*authlog) (const char *fmt,...) = verbose;
1.122 djm 242: const char *authmsg;
243: char *extra = NULL;
1.67 dtucker 244:
245: if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
246: return;
1.13 markus 247:
248: /* Raise logging level */
249: if (authenticated == 1 ||
250: !authctxt->valid ||
1.54 dtucker 251: authctxt->failures >= options.max_authtries / 2 ||
1.13 markus 252: strcmp(method, "password") == 0)
1.47 itojun 253: authlog = logit;
1.13 markus 254:
255: if (authctxt->postponed)
256: authmsg = "Postponed";
1.98 djm 257: else if (partial)
258: authmsg = "Partial";
1.13 markus 259: else
260: authmsg = authenticated ? "Accepted" : "Failed";
261:
1.122 djm 262: if ((extra = format_method_key(authctxt)) == NULL) {
263: if (authctxt->auth_method_info != NULL)
264: extra = xstrdup(authctxt->auth_method_info);
265: }
266:
1.116 markus 267: authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
1.13 markus 268: authmsg,
269: method,
1.98 djm 270: submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
1.56 markus 271: authctxt->valid ? "" : "invalid user ",
1.29 markus 272: authctxt->user,
1.114 djm 273: ssh_remote_ipaddr(ssh),
274: ssh_remote_port(ssh),
1.122 djm 275: extra != NULL ? ": " : "",
276: extra != NULL ? extra : "");
277:
278: free(extra);
1.105 djm 279: }
280:
281: void
282: auth_maxtries_exceeded(Authctxt *authctxt)
283: {
1.114 djm 284: struct ssh *ssh = active_state; /* XXX */
285:
1.110 djm 286: error("maximum authentication attempts exceeded for "
1.116 markus 287: "%s%.100s from %.200s port %d ssh2",
1.105 djm 288: authctxt->valid ? "" : "invalid user ",
289: authctxt->user,
1.114 djm 290: ssh_remote_ipaddr(ssh),
1.116 markus 291: ssh_remote_port(ssh));
1.110 djm 292: packet_disconnect("Too many authentication failures");
1.105 djm 293: /* NOTREACHED */
1.13 markus 294: }
295:
296: /*
1.17 markus 297: * Check whether root logins are disallowed.
1.13 markus 298: */
299: int
1.126 djm 300: auth_root_allowed(struct ssh *ssh, const char *method)
1.13 markus 301: {
1.17 markus 302: switch (options.permit_root_login) {
303: case PERMIT_YES:
1.13 markus 304: return 1;
1.17 markus 305: case PERMIT_NO_PASSWD:
1.112 deraadt 306: if (strcmp(method, "publickey") == 0 ||
307: strcmp(method, "hostbased") == 0 ||
1.113 djm 308: strcmp(method, "gssapi-with-mic") == 0)
1.17 markus 309: return 1;
310: break;
311: case PERMIT_FORCED_ONLY:
1.126 djm 312: if (auth_opts->force_command != NULL) {
1.47 itojun 313: logit("Root login accepted for forced command.");
1.17 markus 314: return 1;
315: }
316: break;
1.13 markus 317: }
1.114 djm 318: logit("ROOT LOGIN REFUSED FROM %.200s port %d",
319: ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.22 markus 320: return 0;
321: }
322:
323:
324: /*
325: * Given a template and a passwd structure, build a filename
326: * by substituting % tokenised options. Currently, %% becomes '%',
327: * %h becomes the home directory and %u the username.
328: *
329: * This returns a buffer allocated by xmalloc.
330: */
1.93 djm 331: char *
1.59 djm 332: expand_authorized_keys(const char *filename, struct passwd *pw)
1.22 markus 333: {
1.129 djm 334: char *file, uidstr[32], ret[PATH_MAX];
1.65 djm 335: int i;
1.22 markus 336:
1.129 djm 337: snprintf(uidstr, sizeof(uidstr), "%llu",
338: (unsigned long long)pw->pw_uid);
1.59 djm 339: file = percent_expand(filename, "h", pw->pw_dir,
1.129 djm 340: "u", pw->pw_name, "U", uidstr, (char *)NULL);
1.22 markus 341:
342: /*
343: * Ensure that filename starts anchored. If not, be backward
344: * compatible and prepend the '%h/'
345: */
1.59 djm 346: if (*file == '/')
347: return (file);
348:
1.65 djm 349: i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
350: if (i < 0 || (size_t)i >= sizeof(ret))
1.59 djm 351: fatal("expand_authorized_keys: path too long");
1.102 djm 352: free(file);
1.65 djm 353: return (xstrdup(ret));
1.22 markus 354: }
1.24 markus 355:
1.87 djm 356: char *
357: authorized_principals_file(struct passwd *pw)
358: {
1.111 djm 359: if (options.authorized_principals_file == NULL)
1.87 djm 360: return NULL;
361: return expand_authorized_keys(options.authorized_principals_file, pw);
362: }
363:
1.24 markus 364: /* return ok if key exists in sysfile or userfile */
365: HostStatus
1.121 markus 366: check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
1.24 markus 367: const char *sysfile, const char *userfile)
368: {
369: char *user_hostfile;
370: struct stat st;
1.30 stevesk 371: HostStatus host_status;
1.91 djm 372: struct hostkeys *hostkeys;
373: const struct hostkey_entry *found;
1.24 markus 374:
1.91 djm 375: hostkeys = init_hostkeys();
376: load_hostkeys(hostkeys, host, sysfile);
377: if (userfile != NULL) {
1.24 markus 378: user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
379: if (options.strict_modes &&
380: (stat(user_hostfile, &st) == 0) &&
381: ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
1.31 deraadt 382: (st.st_mode & 022) != 0)) {
1.47 itojun 383: logit("Authentication refused for %.100s: "
1.24 markus 384: "bad owner or modes for %.200s",
385: pw->pw_name, user_hostfile);
1.88 djm 386: auth_debug_add("Ignored %.200s: bad ownership or modes",
387: user_hostfile);
1.24 markus 388: } else {
389: temporarily_use_uid(pw);
1.91 djm 390: load_hostkeys(hostkeys, host, user_hostfile);
1.24 markus 391: restore_uid();
392: }
1.102 djm 393: free(user_hostfile);
1.24 markus 394: }
1.91 djm 395: host_status = check_key_in_hostkeys(hostkeys, key, &found);
396: if (host_status == HOST_REVOKED)
397: error("WARNING: revoked key for %s attempted authentication",
398: found->host);
399: else if (host_status == HOST_OK)
400: debug("%s: key for %s found at %s:%ld", __func__,
401: found->host, found->file, found->line);
402: else
403: debug("%s: key for host %s not found", __func__, host);
404:
405: free_hostkeys(hostkeys);
1.24 markus 406:
407: return host_status;
408: }
409:
1.87 djm 410: static FILE *
411: auth_openfile(const char *file, struct passwd *pw, int strict_modes,
412: int log_missing, char *file_type)
1.79 dtucker 413: {
414: char line[1024];
415: struct stat st;
416: int fd;
417: FILE *f;
418:
1.81 dtucker 419: if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
1.87 djm 420: if (log_missing || errno != ENOENT)
421: debug("Could not open %s '%s': %s", file_type, file,
1.81 dtucker 422: strerror(errno));
1.79 dtucker 423: return NULL;
1.81 dtucker 424: }
1.79 dtucker 425:
426: if (fstat(fd, &st) < 0) {
427: close(fd);
428: return NULL;
429: }
430: if (!S_ISREG(st.st_mode)) {
1.87 djm 431: logit("User %s %s %s is not a regular file",
432: pw->pw_name, file_type, file);
1.79 dtucker 433: close(fd);
434: return NULL;
435: }
436: unset_nonblock(fd);
437: if ((f = fdopen(fd, "r")) == NULL) {
438: close(fd);
439: return NULL;
440: }
1.90 djm 441: if (strict_modes &&
1.123 djm 442: safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
1.79 dtucker 443: fclose(f);
444: logit("Authentication refused: %s", line);
1.88 djm 445: auth_debug_add("Ignored %s: %s", file_type, line);
1.79 dtucker 446: return NULL;
447: }
448:
449: return f;
1.87 djm 450: }
451:
452:
453: FILE *
454: auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
455: {
456: return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
457: }
458:
459: FILE *
460: auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
461: {
462: return auth_openfile(file, pw, strict_modes, 0,
463: "authorized principals");
1.37 provos 464: }
465:
466: struct passwd *
467: getpwnamallow(const char *user)
468: {
1.114 djm 469: struct ssh *ssh = active_state; /* XXX */
1.38 provos 470: extern login_cap_t *lc;
471: auth_session_t *as;
1.37 provos 472: struct passwd *pw;
1.96 dtucker 473: struct connection_info *ci = get_connection_info(1, options.use_dns);
1.71 dtucker 474:
1.96 dtucker 475: ci->user = user;
476: parse_server_match_config(&options, ci);
1.120 djm 477: log_change_level(options.log_level);
1.124 djm 478: process_permitopen(ssh, &options);
1.37 provos 479:
480: pw = getpwnam(user);
1.45 stevesk 481: if (pw == NULL) {
1.114 djm 482: logit("Invalid user %.100s from %.100s port %d",
483: user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.45 stevesk 484: return (NULL);
485: }
486: if (!allowed_user(pw))
1.38 provos 487: return (NULL);
488: if ((lc = login_getclass(pw->pw_class)) == NULL) {
489: debug("unable to get login class: %s", user);
490: return (NULL);
491: }
492: if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
1.43 millert 493: auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
1.38 provos 494: debug("Approval failure for %s", user);
1.37 provos 495: pw = NULL;
1.38 provos 496: }
497: if (as != NULL)
498: auth_close(as);
1.41 markus 499: if (pw != NULL)
500: return (pwcopy(pw));
501: return (NULL);
1.85 djm 502: }
503:
504: /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
505: int
1.121 markus 506: auth_key_is_revoked(struct sshkey *key)
1.85 djm 507: {
1.107 djm 508: char *fp = NULL;
509: int r;
1.85 djm 510:
511: if (options.revoked_keys_file == NULL)
512: return 0;
1.108 djm 513: if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
514: SSH_FP_DEFAULT)) == NULL) {
1.107 djm 515: r = SSH_ERR_ALLOC_FAIL;
516: error("%s: fingerprint key: %s", __func__, ssh_err(r));
517: goto out;
518: }
519:
520: r = sshkey_check_revoked(key, options.revoked_keys_file);
521: switch (r) {
1.100 djm 522: case 0:
1.107 djm 523: break; /* not revoked */
524: case SSH_ERR_KEY_REVOKED:
525: error("Authentication key %s %s revoked by file %s",
526: sshkey_type(key), fp, options.revoked_keys_file);
527: goto out;
1.100 djm 528: default:
1.107 djm 529: error("Error checking authentication key %s %s in "
530: "revoked keys file %s: %s", sshkey_type(key), fp,
531: options.revoked_keys_file, ssh_err(r));
532: goto out;
1.100 djm 533: }
1.107 djm 534:
535: /* Success */
536: r = 0;
537:
538: out:
539: free(fp);
540: return r == 0 ? 0 : 1;
1.42 markus 541: }
542:
543: void
544: auth_debug_add(const char *fmt,...)
545: {
546: char buf[1024];
547: va_list args;
1.131 markus 548: int r;
1.42 markus 549:
1.131 markus 550: if (auth_debug == NULL)
1.42 markus 551: return;
552:
553: va_start(args, fmt);
554: vsnprintf(buf, sizeof(buf), fmt, args);
555: va_end(args);
1.131 markus 556: if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
557: fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
1.42 markus 558: }
559:
560: void
561: auth_debug_send(void)
562: {
1.131 markus 563: struct ssh *ssh = active_state; /* XXX */
1.42 markus 564: char *msg;
1.131 markus 565: int r;
1.42 markus 566:
1.131 markus 567: if (auth_debug == NULL)
1.42 markus 568: return;
1.131 markus 569: while (sshbuf_len(auth_debug) != 0) {
570: if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
571: fatal("%s: sshbuf_get_cstring: %s",
572: __func__, ssh_err(r));
573: ssh_packet_send_debug(ssh, "%s", msg);
1.102 djm 574: free(msg);
1.42 markus 575: }
576: }
577:
578: void
579: auth_debug_reset(void)
580: {
1.131 markus 581: if (auth_debug != NULL)
582: sshbuf_reset(auth_debug);
583: else if ((auth_debug = sshbuf_new()) == NULL)
584: fatal("%s: sshbuf_new failed", __func__);
1.49 markus 585: }
586:
587: struct passwd *
588: fakepw(void)
589: {
590: static struct passwd fake;
591:
592: memset(&fake, 0, sizeof(fake));
593: fake.pw_name = "NOUSER";
594: fake.pw_passwd =
1.51 djm 595: "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
1.49 markus 596: fake.pw_gecos = "NOUSER";
1.53 deraadt 597: fake.pw_uid = (uid_t)-1;
598: fake.pw_gid = (gid_t)-1;
1.49 markus 599: fake.pw_class = "";
600: fake.pw_dir = "/nonexist";
601: fake.pw_shell = "/nonexist";
602:
603: return (&fake);
1.114 djm 604: }
605:
606: /*
607: * Returns the remote DNS hostname as a string. The returned string must not
608: * be freed. NB. this will usually trigger a DNS query the first time it is
609: * called.
610: * This function does additional checks on the hostname to mitigate some
611: * attacks on legacy rhosts-style authentication.
612: * XXX is RhostsRSAAuthentication vulnerable to these?
613: * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
614: */
615:
616: static char *
617: remote_hostname(struct ssh *ssh)
618: {
619: struct sockaddr_storage from;
620: socklen_t fromlen;
621: struct addrinfo hints, *ai, *aitop;
622: char name[NI_MAXHOST], ntop2[NI_MAXHOST];
623: const char *ntop = ssh_remote_ipaddr(ssh);
624:
625: /* Get IP address of client. */
626: fromlen = sizeof(from);
627: memset(&from, 0, sizeof(from));
628: if (getpeername(ssh_packet_get_connection_in(ssh),
629: (struct sockaddr *)&from, &fromlen) < 0) {
630: debug("getpeername failed: %.100s", strerror(errno));
631: return strdup(ntop);
632: }
633:
634: debug3("Trying to reverse map address %.100s.", ntop);
635: /* Map the IP address to a host name. */
636: if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
637: NULL, 0, NI_NAMEREQD) != 0) {
638: /* Host name not found. Use ip address. */
639: return strdup(ntop);
640: }
641:
642: /*
643: * if reverse lookup result looks like a numeric hostname,
644: * someone is trying to trick us by PTR record like following:
645: * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
646: */
647: memset(&hints, 0, sizeof(hints));
648: hints.ai_socktype = SOCK_DGRAM; /*dummy*/
649: hints.ai_flags = AI_NUMERICHOST;
650: if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
651: logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
652: name, ntop);
653: freeaddrinfo(ai);
654: return strdup(ntop);
655: }
656:
657: /* Names are stored in lowercase. */
658: lowercase(name);
659:
660: /*
661: * Map it back to an IP address and check that the given
662: * address actually is an address of this host. This is
663: * necessary because anyone with access to a name server can
664: * define arbitrary names for an IP address. Mapping from
665: * name to IP address can be trusted better (but can still be
666: * fooled if the intruder has access to the name server of
667: * the domain).
668: */
669: memset(&hints, 0, sizeof(hints));
670: hints.ai_family = from.ss_family;
671: hints.ai_socktype = SOCK_STREAM;
672: if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
673: logit("reverse mapping checking getaddrinfo for %.700s "
1.115 dtucker 674: "[%s] failed.", name, ntop);
1.114 djm 675: return strdup(ntop);
676: }
677: /* Look for the address from the list of addresses. */
678: for (ai = aitop; ai; ai = ai->ai_next) {
679: if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
680: sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
681: (strcmp(ntop, ntop2) == 0))
682: break;
683: }
684: freeaddrinfo(aitop);
685: /* If we reached the end of the list, the address was not there. */
686: if (ai == NULL) {
687: /* Address not found for the host name. */
688: logit("Address %.100s maps to %.600s, but this does not "
1.115 dtucker 689: "map back to the address.", ntop, name);
1.114 djm 690: return strdup(ntop);
691: }
692: return strdup(name);
693: }
694:
695: /*
696: * Return the canonical name of the host in the other side of the current
697: * connection. The host name is cached, so it is efficient to call this
698: * several times.
699: */
700:
701: const char *
702: auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
703: {
704: static char *dnsname;
705:
706: if (!use_dns)
707: return ssh_remote_ipaddr(ssh);
708: else if (dnsname != NULL)
709: return dnsname;
710: else {
711: dnsname = remote_hostname(ssh);
712: return dnsname;
713: }
1.125 markus 714: }
715:
716: /*
1.132 ! martijn 717: * Runs command in a subprocess with a minimal environment.
1.125 markus 718: * Returns pid on success, 0 on failure.
719: * The child stdout and stderr maybe captured, left attached or sent to
720: * /dev/null depending on the contents of flags.
721: * "tag" is prepended to log messages.
722: * NB. "command" is only used for logging; the actual command executed is
723: * av[0].
724: */
725: pid_t
726: subprocess(const char *tag, struct passwd *pw, const char *command,
727: int ac, char **av, FILE **child, u_int flags)
728: {
729: FILE *f = NULL;
730: struct stat st;
731: int fd, devnull, p[2], i;
732: pid_t pid;
733: char *cp, errmsg[512];
734: u_int envsize;
735: char **child_env;
736:
737: if (child != NULL)
738: *child = NULL;
739:
740: debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
741: tag, command, pw->pw_name, flags);
742:
743: /* Check consistency */
744: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
745: (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
746: error("%s: inconsistent flags", __func__);
747: return 0;
748: }
749: if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
750: error("%s: inconsistent flags/output", __func__);
751: return 0;
752: }
753:
754: /*
755: * If executing an explicit binary, then verify the it exists
756: * and appears safe-ish to execute
757: */
758: if (*av[0] != '/') {
759: error("%s path is not absolute", tag);
760: return 0;
761: }
762: temporarily_use_uid(pw);
763: if (stat(av[0], &st) < 0) {
764: error("Could not stat %s \"%s\": %s", tag,
765: av[0], strerror(errno));
766: restore_uid();
767: return 0;
768: }
769: if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
770: error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
771: restore_uid();
772: return 0;
773: }
774: /* Prepare to keep the child's stdout if requested */
775: if (pipe(p) != 0) {
776: error("%s: pipe: %s", tag, strerror(errno));
777: restore_uid();
778: return 0;
779: }
780: restore_uid();
781:
782: switch ((pid = fork())) {
783: case -1: /* error */
784: error("%s: fork: %s", tag, strerror(errno));
785: close(p[0]);
786: close(p[1]);
787: return 0;
788: case 0: /* child */
789: /* Prepare a minimal environment for the child. */
790: envsize = 5;
791: child_env = xcalloc(sizeof(*child_env), envsize);
792: child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
793: child_set_env(&child_env, &envsize, "USER", pw->pw_name);
794: child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
795: child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
796: if ((cp = getenv("LANG")) != NULL)
797: child_set_env(&child_env, &envsize, "LANG", cp);
798:
799: for (i = 0; i < NSIG; i++)
800: signal(i, SIG_DFL);
801:
802: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
803: error("%s: open %s: %s", tag, _PATH_DEVNULL,
804: strerror(errno));
805: _exit(1);
806: }
807: if (dup2(devnull, STDIN_FILENO) == -1) {
808: error("%s: dup2: %s", tag, strerror(errno));
809: _exit(1);
810: }
811:
812: /* Set up stdout as requested; leave stderr in place for now. */
813: fd = -1;
814: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
815: fd = p[1];
816: else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
817: fd = devnull;
818: if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
819: error("%s: dup2: %s", tag, strerror(errno));
820: _exit(1);
821: }
822: closefrom(STDERR_FILENO + 1);
823:
824: /* Don't use permanently_set_uid() here to avoid fatal() */
825: if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
826: error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
827: strerror(errno));
828: _exit(1);
829: }
830: if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
831: error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
832: strerror(errno));
833: _exit(1);
834: }
835: /* stdin is pointed to /dev/null at this point */
836: if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
837: dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
838: error("%s: dup2: %s", tag, strerror(errno));
839: _exit(1);
840: }
841:
842: execve(av[0], av, child_env);
843: error("%s exec \"%s\": %s", tag, command, strerror(errno));
844: _exit(127);
845: default: /* parent */
846: break;
847: }
848:
849: close(p[1]);
850: if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
851: close(p[0]);
852: else if ((f = fdopen(p[0], "r")) == NULL) {
853: error("%s: fdopen: %s", tag, strerror(errno));
854: close(p[0]);
855: /* Don't leave zombie child */
856: kill(pid, SIGTERM);
857: while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
858: ;
859: return 0;
860: }
861: /* Success */
862: debug3("%s: %s pid %ld", __func__, tag, (long)pid);
863: if (child != NULL)
864: *child = f;
865: return pid;
1.126 djm 866: }
867:
868: /* These functions link key/cert options to the auth framework */
869:
870: /* Log sshauthopt options locally and (optionally) for remote transmission */
871: void
872: auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
873: {
874: int do_env = options.permit_user_env && opts->nenv > 0;
875: int do_permitopen = opts->npermitopen > 0 &&
876: (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1.130 djm 877: int do_permitlisten = opts->npermitlisten > 0 &&
878: (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1.126 djm 879: size_t i;
1.127 djm 880: char msg[1024], buf[64];
1.126 djm 881:
1.127 djm 882: snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1.126 djm 883: /* Try to keep this alphabetically sorted */
1.130 djm 884: snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1.126 djm 885: opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
886: opts->force_command == NULL ? "" : " command",
887: do_env ? " environment" : "",
1.127 djm 888: opts->valid_before == 0 ? "" : "expires",
1.126 djm 889: do_permitopen ? " permitopen" : "",
1.130 djm 890: do_permitlisten ? " permitlisten" : "",
1.126 djm 891: opts->permit_port_forwarding_flag ? " port-forwarding" : "",
892: opts->cert_principals == NULL ? "" : " principals",
893: opts->permit_pty_flag ? " pty" : "",
894: opts->force_tun_device == -1 ? "" : " tun=",
1.127 djm 895: opts->force_tun_device == -1 ? "" : buf,
1.126 djm 896: opts->permit_user_rc ? " user-rc" : "",
897: opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
898:
899: debug("%s: %s", loc, msg);
900: if (do_remote)
901: auth_debug_add("%s: %s", loc, msg);
902:
903: if (options.permit_user_env) {
904: for (i = 0; i < opts->nenv; i++) {
905: debug("%s: environment: %s", loc, opts->env[i]);
906: if (do_remote) {
907: auth_debug_add("%s: environment: %s",
908: loc, opts->env[i]);
909: }
910: }
911: }
912:
913: /* Go into a little more details for the local logs. */
1.127 djm 914: if (opts->valid_before != 0) {
915: format_absolute_time(opts->valid_before, buf, sizeof(buf));
916: debug("%s: expires at %s", loc, buf);
917: }
1.126 djm 918: if (opts->cert_principals != NULL) {
919: debug("%s: authorized principals: \"%s\"",
920: loc, opts->cert_principals);
921: }
922: if (opts->force_command != NULL)
923: debug("%s: forced command: \"%s\"", loc, opts->force_command);
1.130 djm 924: if (do_permitopen) {
1.126 djm 925: for (i = 0; i < opts->npermitopen; i++) {
926: debug("%s: permitted open: %s",
927: loc, opts->permitopen[i]);
1.130 djm 928: }
929: }
930: if (do_permitlisten) {
931: for (i = 0; i < opts->npermitlisten; i++) {
932: debug("%s: permitted listen: %s",
933: loc, opts->permitlisten[i]);
1.126 djm 934: }
935: }
936: }
937:
938: /* Activate a new set of key/cert options; merging with what is there. */
939: int
940: auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
941: {
942: struct sshauthopt *old = auth_opts;
943: const char *emsg = NULL;
944:
945: debug("%s: setting new authentication options", __func__);
946: if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
947: error("Inconsistent authentication options: %s", emsg);
948: return -1;
949: }
950: return 0;
951: }
952:
953: /* Disable forwarding, etc for the session */
954: void
955: auth_restrict_session(struct ssh *ssh)
956: {
957: struct sshauthopt *restricted;
958:
959: debug("%s: restricting session", __func__);
960:
961: /* A blank sshauthopt defaults to permitting nothing */
962: restricted = sshauthopt_new();
1.128 djm 963: restricted->permit_pty_flag = 1;
1.126 djm 964: restricted->restricted = 1;
965:
966: if (auth_activate_options(ssh, restricted) != 0)
967: fatal("%s: failed to restrict session", __func__);
968: sshauthopt_free(restricted);
969: }
970:
971: int
972: auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
973: struct sshauthopt *opts, int allow_cert_authority, const char *loc)
974: {
975: const char *remote_ip = ssh_remote_ipaddr(ssh);
976: const char *remote_host = auth_get_canonical_hostname(ssh,
977: options.use_dns);
1.127 djm 978: time_t now = time(NULL);
979: char buf[64];
1.126 djm 980:
1.127 djm 981: /*
982: * Check keys/principals file expiry time.
983: * NB. validity interval in certificate is handled elsewhere.
984: */
985: if (opts->valid_before && now > 0 &&
986: opts->valid_before < (uint64_t)now) {
987: format_absolute_time(opts->valid_before, buf, sizeof(buf));
988: debug("%s: entry expired at %s", loc, buf);
989: auth_debug_add("%s: entry expired at %s", loc, buf);
990: return -1;
991: }
1.126 djm 992: /* Consistency checks */
993: if (opts->cert_principals != NULL && !opts->cert_authority) {
994: debug("%s: principals on non-CA key", loc);
995: auth_debug_add("%s: principals on non-CA key", loc);
996: /* deny access */
997: return -1;
998: }
999: /* cert-authority flag isn't valid in authorized_principals files */
1000: if (!allow_cert_authority && opts->cert_authority) {
1001: debug("%s: cert-authority flag invalid here", loc);
1002: auth_debug_add("%s: cert-authority flag invalid here", loc);
1003: /* deny access */
1004: return -1;
1005: }
1006:
1007: /* Perform from= checks */
1008: if (opts->required_from_host_keys != NULL) {
1009: switch (match_host_and_ip(remote_host, remote_ip,
1010: opts->required_from_host_keys )) {
1011: case 1:
1012: /* Host name matches. */
1013: break;
1014: case -1:
1015: default:
1016: debug("%s: invalid from criteria", loc);
1017: auth_debug_add("%s: invalid from criteria", loc);
1018: /* FALLTHROUGH */
1019: case 0:
1020: logit("%s: Authentication tried for %.100s with "
1021: "correct key but not from a permitted "
1022: "host (host=%.200s, ip=%.200s, required=%.200s).",
1023: loc, pw->pw_name, remote_host, remote_ip,
1024: opts->required_from_host_keys);
1025: auth_debug_add("%s: Your host '%.200s' is not "
1026: "permitted to use this key for login.",
1027: loc, remote_host);
1028: /* deny access */
1029: return -1;
1030: }
1031: }
1032: /* Check source-address restriction from certificate */
1033: if (opts->required_from_host_cert != NULL) {
1034: switch (addr_match_cidr_list(remote_ip,
1035: opts->required_from_host_cert)) {
1036: case 1:
1037: /* accepted */
1038: break;
1039: case -1:
1040: default:
1041: /* invalid */
1042: error("%s: Certificate source-address invalid",
1043: loc);
1044: /* FALLTHROUGH */
1045: case 0:
1046: logit("%s: Authentication tried for %.100s with valid "
1047: "certificate but not from a permitted source "
1048: "address (%.200s).", loc, pw->pw_name, remote_ip);
1049: auth_debug_add("%s: Your address '%.200s' is not "
1050: "permitted to use this certificate for login.",
1051: loc, remote_ip);
1052: return -1;
1053: }
1054: }
1055: /*
1056: *
1057: * XXX this is spammy. We should report remotely only for keys
1058: * that are successful in actual auth attempts, and not PK_OK
1059: * tests.
1060: */
1061: auth_log_authopts(loc, opts, 1);
1062:
1063: return 0;
1.1 markus 1064: }