correct bug number
[openssh-git.git] / auth.c
blobd62d8ff2235b2f6bfbea18e7c350d9ab265ac5e9
1 /*
2 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include "includes.h"
26 RCSID("$OpenBSD: auth.c,v 1.60 2005/06/17 02:44:32 djm Exp $");
28 #ifdef HAVE_LOGIN_H
29 #include <login.h>
30 #endif
31 #ifdef USE_SHADOW
32 #include <shadow.h>
33 #endif
35 #ifdef HAVE_LIBGEN_H
36 #include <libgen.h>
37 #endif
39 #include "xmalloc.h"
40 #include "match.h"
41 #include "groupaccess.h"
42 #include "log.h"
43 #include "servconf.h"
44 #include "auth.h"
45 #include "auth-options.h"
46 #include "canohost.h"
47 #include "buffer.h"
48 #include "bufaux.h"
49 #include "uidswap.h"
50 #include "misc.h"
51 #include "bufaux.h"
52 #include "packet.h"
53 #include "loginrec.h"
54 #include "monitor_wrap.h"
56 /* import */
57 extern ServerOptions options;
58 extern Buffer loginmsg;
60 /* Debugging messages */
61 Buffer auth_debug;
62 int auth_debug_init;
65 * Check if the user is allowed to log in via ssh. If user is listed
66 * in DenyUsers or one of user's groups is listed in DenyGroups, false
67 * will be returned. If AllowUsers isn't empty and user isn't listed
68 * there, or if AllowGroups isn't empty and one of user's groups isn't
69 * listed there, false will be returned.
70 * If the user's shell is not executable, false will be returned.
71 * Otherwise true is returned.
73 int
74 allowed_user(struct passwd * pw)
76 struct stat st;
77 const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
78 char *shell;
79 u_int i;
80 #ifdef USE_SHADOW
81 struct spwd *spw = NULL;
82 #endif
84 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
85 if (!pw || !pw->pw_name)
86 return 0;
88 #ifdef USE_SHADOW
89 if (!options.use_pam)
90 spw = getspnam(pw->pw_name);
91 #ifdef HAS_SHADOW_EXPIRE
92 if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
93 return 0;
94 #endif /* HAS_SHADOW_EXPIRE */
95 #endif /* USE_SHADOW */
97 /* grab passwd field for locked account check */
98 #ifdef USE_SHADOW
99 if (spw != NULL)
100 #ifdef HAVE_LIBIAF
101 passwd = get_iaf_password(pw);
102 #else
103 passwd = spw->sp_pwdp;
104 #endif /* HAVE_LIBIAF */
105 #else
106 passwd = pw->pw_passwd;
107 #endif
109 /* check for locked account */
110 if (!options.use_pam && passwd && *passwd) {
111 int locked = 0;
113 #ifdef LOCKED_PASSWD_STRING
114 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
115 locked = 1;
116 #endif
117 #ifdef LOCKED_PASSWD_PREFIX
118 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
119 strlen(LOCKED_PASSWD_PREFIX)) == 0)
120 locked = 1;
121 #endif
122 #ifdef LOCKED_PASSWD_SUBSTR
123 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
124 locked = 1;
125 #endif
126 if (locked) {
127 logit("User %.100s not allowed because account is locked",
128 pw->pw_name);
129 return 0;
134 * Get the shell from the password data. An empty shell field is
135 * legal, and means /bin/sh.
137 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
139 /* deny if shell does not exists or is not executable */
140 if (stat(shell, &st) != 0) {
141 logit("User %.100s not allowed because shell %.100s does not exist",
142 pw->pw_name, shell);
143 return 0;
145 if (S_ISREG(st.st_mode) == 0 ||
146 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
147 logit("User %.100s not allowed because shell %.100s is not executable",
148 pw->pw_name, shell);
149 return 0;
152 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
153 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
154 hostname = get_canonical_hostname(options.use_dns);
155 ipaddr = get_remote_ipaddr();
158 /* Return false if user is listed in DenyUsers */
159 if (options.num_deny_users > 0) {
160 for (i = 0; i < options.num_deny_users; i++)
161 if (match_user(pw->pw_name, hostname, ipaddr,
162 options.deny_users[i])) {
163 logit("User %.100s from %.100s not allowed "
164 "because listed in DenyUsers",
165 pw->pw_name, hostname);
166 return 0;
169 /* Return false if AllowUsers isn't empty and user isn't listed there */
170 if (options.num_allow_users > 0) {
171 for (i = 0; i < options.num_allow_users; i++)
172 if (match_user(pw->pw_name, hostname, ipaddr,
173 options.allow_users[i]))
174 break;
175 /* i < options.num_allow_users iff we break for loop */
176 if (i >= options.num_allow_users) {
177 logit("User %.100s from %.100s not allowed because "
178 "not listed in AllowUsers", pw->pw_name, hostname);
179 return 0;
182 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
183 /* Get the user's group access list (primary and supplementary) */
184 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
185 logit("User %.100s from %.100s not allowed because "
186 "not in any group", pw->pw_name, hostname);
187 return 0;
190 /* Return false if one of user's groups is listed in DenyGroups */
191 if (options.num_deny_groups > 0)
192 if (ga_match(options.deny_groups,
193 options.num_deny_groups)) {
194 ga_free();
195 logit("User %.100s from %.100s not allowed "
196 "because a group is listed in DenyGroups",
197 pw->pw_name, hostname);
198 return 0;
201 * Return false if AllowGroups isn't empty and one of user's groups
202 * isn't listed there
204 if (options.num_allow_groups > 0)
205 if (!ga_match(options.allow_groups,
206 options.num_allow_groups)) {
207 ga_free();
208 logit("User %.100s from %.100s not allowed "
209 "because none of user's groups are listed "
210 "in AllowGroups", pw->pw_name, hostname);
211 return 0;
213 ga_free();
216 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
217 if (!sys_auth_allowed_user(pw, &loginmsg))
218 return 0;
219 #endif
221 /* We found no reason not to let this user try to log on... */
222 return 1;
225 void
226 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
228 void (*authlog) (const char *fmt,...) = verbose;
229 char *authmsg;
231 /* Raise logging level */
232 if (authenticated == 1 ||
233 !authctxt->valid ||
234 authctxt->failures >= options.max_authtries / 2 ||
235 strcmp(method, "password") == 0)
236 authlog = logit;
238 if (authctxt->postponed)
239 authmsg = "Postponed";
240 else
241 authmsg = authenticated ? "Accepted" : "Failed";
243 authlog("%s %s for %s%.100s from %.200s port %d%s",
244 authmsg,
245 method,
246 authctxt->valid ? "" : "invalid user ",
247 authctxt->user,
248 get_remote_ipaddr(),
249 get_remote_port(),
250 info);
252 #ifdef CUSTOM_FAILED_LOGIN
253 if (authenticated == 0 && !authctxt->postponed &&
254 (strcmp(method, "password") == 0 ||
255 strncmp(method, "keyboard-interactive", 20) == 0 ||
256 strcmp(method, "challenge-response") == 0))
257 record_failed_login(authctxt->user,
258 get_canonical_hostname(options.use_dns), "ssh");
259 #endif
260 #ifdef SSH_AUDIT_EVENTS
261 if (authenticated == 0 && !authctxt->postponed) {
262 ssh_audit_event_t event;
264 debug3("audit failed auth attempt, method %s euid %d",
265 method, (int)geteuid());
267 * Because the auth loop is used in both monitor and slave,
268 * we must be careful to send each event only once and with
269 * enough privs to write the event.
271 event = audit_classify_auth(method);
272 switch(event) {
273 case SSH_AUTH_FAIL_NONE:
274 case SSH_AUTH_FAIL_PASSWD:
275 case SSH_AUTH_FAIL_KBDINT:
276 if (geteuid() == 0)
277 audit_event(event);
278 break;
279 case SSH_AUTH_FAIL_PUBKEY:
280 case SSH_AUTH_FAIL_HOSTBASED:
281 case SSH_AUTH_FAIL_GSSAPI:
283 * This is required to handle the case where privsep
284 * is enabled but it's root logging in, since
285 * use_privsep won't be cleared until after a
286 * successful login.
288 if (geteuid() == 0)
289 audit_event(event);
290 else
291 PRIVSEP(audit_event(event));
292 break;
293 default:
294 error("unknown authentication audit event %d", event);
297 #endif
301 * Check whether root logins are disallowed.
304 auth_root_allowed(char *method)
306 switch (options.permit_root_login) {
307 case PERMIT_YES:
308 return 1;
309 break;
310 case PERMIT_NO_PASSWD:
311 if (strcmp(method, "password") != 0)
312 return 1;
313 break;
314 case PERMIT_FORCED_ONLY:
315 if (forced_command) {
316 logit("Root login accepted for forced command.");
317 return 1;
319 break;
321 logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
322 return 0;
327 * Given a template and a passwd structure, build a filename
328 * by substituting % tokenised options. Currently, %% becomes '%',
329 * %h becomes the home directory and %u the username.
331 * This returns a buffer allocated by xmalloc.
333 static char *
334 expand_authorized_keys(const char *filename, struct passwd *pw)
336 char *file, *ret;
338 file = percent_expand(filename, "h", pw->pw_dir,
339 "u", pw->pw_name, (char *)NULL);
342 * Ensure that filename starts anchored. If not, be backward
343 * compatible and prepend the '%h/'
345 if (*file == '/')
346 return (file);
348 ret = xmalloc(MAXPATHLEN);
349 if (strlcpy(ret, pw->pw_dir, MAXPATHLEN) >= MAXPATHLEN ||
350 strlcat(ret, "/", MAXPATHLEN) >= MAXPATHLEN ||
351 strlcat(ret, file, MAXPATHLEN) >= MAXPATHLEN)
352 fatal("expand_authorized_keys: path too long");
354 xfree(file);
355 return (ret);
358 char *
359 authorized_keys_file(struct passwd *pw)
361 return expand_authorized_keys(options.authorized_keys_file, pw);
364 char *
365 authorized_keys_file2(struct passwd *pw)
367 return expand_authorized_keys(options.authorized_keys_file2, pw);
370 /* return ok if key exists in sysfile or userfile */
371 HostStatus
372 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
373 const char *sysfile, const char *userfile)
375 Key *found;
376 char *user_hostfile;
377 struct stat st;
378 HostStatus host_status;
380 /* Check if we know the host and its host key. */
381 found = key_new(key->type);
382 host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
384 if (host_status != HOST_OK && userfile != NULL) {
385 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
386 if (options.strict_modes &&
387 (stat(user_hostfile, &st) == 0) &&
388 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
389 (st.st_mode & 022) != 0)) {
390 logit("Authentication refused for %.100s: "
391 "bad owner or modes for %.200s",
392 pw->pw_name, user_hostfile);
393 } else {
394 temporarily_use_uid(pw);
395 host_status = check_host_in_hostfile(user_hostfile,
396 host, key, found, NULL);
397 restore_uid();
399 xfree(user_hostfile);
401 key_free(found);
403 debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
404 "ok" : "not found", host);
405 return host_status;
410 * Check a given file for security. This is defined as all components
411 * of the path to the file must be owned by either the owner of
412 * of the file or root and no directories must be group or world writable.
414 * XXX Should any specific check be done for sym links ?
416 * Takes an open file descriptor, the file name, a uid and and
417 * error buffer plus max size as arguments.
419 * Returns 0 on success and -1 on failure
422 secure_filename(FILE *f, const char *file, struct passwd *pw,
423 char *err, size_t errlen)
425 uid_t uid = pw->pw_uid;
426 char buf[MAXPATHLEN], homedir[MAXPATHLEN];
427 char *cp;
428 int comparehome = 0;
429 struct stat st;
431 if (realpath(file, buf) == NULL) {
432 snprintf(err, errlen, "realpath %s failed: %s", file,
433 strerror(errno));
434 return -1;
436 if (realpath(pw->pw_dir, homedir) != NULL)
437 comparehome = 1;
439 /* check the open file to avoid races */
440 if (fstat(fileno(f), &st) < 0 ||
441 (st.st_uid != 0 && st.st_uid != uid) ||
442 (st.st_mode & 022) != 0) {
443 snprintf(err, errlen, "bad ownership or modes for file %s",
444 buf);
445 return -1;
448 /* for each component of the canonical path, walking upwards */
449 for (;;) {
450 if ((cp = dirname(buf)) == NULL) {
451 snprintf(err, errlen, "dirname() failed");
452 return -1;
454 strlcpy(buf, cp, sizeof(buf));
456 debug3("secure_filename: checking '%s'", buf);
457 if (stat(buf, &st) < 0 ||
458 (st.st_uid != 0 && st.st_uid != uid) ||
459 (st.st_mode & 022) != 0) {
460 snprintf(err, errlen,
461 "bad ownership or modes for directory %s", buf);
462 return -1;
465 /* If are passed the homedir then we can stop */
466 if (comparehome && strcmp(homedir, buf) == 0) {
467 debug3("secure_filename: terminating check at '%s'",
468 buf);
469 break;
472 * dirname should always complete with a "/" path,
473 * but we can be paranoid and check for "." too
475 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
476 break;
478 return 0;
481 struct passwd *
482 getpwnamallow(const char *user)
484 #ifdef HAVE_LOGIN_CAP
485 extern login_cap_t *lc;
486 #ifdef BSD_AUTH
487 auth_session_t *as;
488 #endif
489 #endif
490 struct passwd *pw;
492 pw = getpwnam(user);
493 if (pw == NULL) {
494 logit("Invalid user %.100s from %.100s",
495 user, get_remote_ipaddr());
496 #ifdef CUSTOM_FAILED_LOGIN
497 record_failed_login(user,
498 get_canonical_hostname(options.use_dns), "ssh");
499 #endif
500 #ifdef SSH_AUDIT_EVENTS
501 audit_event(SSH_INVALID_USER);
502 #endif /* SSH_AUDIT_EVENTS */
503 return (NULL);
505 if (!allowed_user(pw))
506 return (NULL);
507 #ifdef HAVE_LOGIN_CAP
508 if ((lc = login_getclass(pw->pw_class)) == NULL) {
509 debug("unable to get login class: %s", user);
510 return (NULL);
512 #ifdef BSD_AUTH
513 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
514 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
515 debug("Approval failure for %s", user);
516 pw = NULL;
518 if (as != NULL)
519 auth_close(as);
520 #endif
521 #endif
522 if (pw != NULL)
523 return (pwcopy(pw));
524 return (NULL);
527 void
528 auth_debug_add(const char *fmt,...)
530 char buf[1024];
531 va_list args;
533 if (!auth_debug_init)
534 return;
536 va_start(args, fmt);
537 vsnprintf(buf, sizeof(buf), fmt, args);
538 va_end(args);
539 buffer_put_cstring(&auth_debug, buf);
542 void
543 auth_debug_send(void)
545 char *msg;
547 if (!auth_debug_init)
548 return;
549 while (buffer_len(&auth_debug)) {
550 msg = buffer_get_string(&auth_debug, NULL);
551 packet_send_debug("%s", msg);
552 xfree(msg);
556 void
557 auth_debug_reset(void)
559 if (auth_debug_init)
560 buffer_clear(&auth_debug);
561 else {
562 buffer_init(&auth_debug);
563 auth_debug_init = 1;
567 struct passwd *
568 fakepw(void)
570 static struct passwd fake;
572 memset(&fake, 0, sizeof(fake));
573 fake.pw_name = "NOUSER";
574 fake.pw_passwd =
575 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
576 fake.pw_gecos = "NOUSER";
577 fake.pw_uid = (uid_t)-1;
578 fake.pw_gid = (gid_t)-1;
579 #ifdef HAVE_PW_CLASS_IN_PASSWD
580 fake.pw_class = "";
581 #endif
582 fake.pw_dir = "/nonexist";
583 fake.pw_shell = "/nonexist";
585 return (&fake);