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