No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / auth.c
blobb9fb5e75a0c886621337edb9f269f0c8050e0805
1 /* $NetBSD$ */
2 /* $OpenBSD: auth.c,v 1.80 2008/11/04 07:58:09 djm Exp $ */
3 /*
4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "includes.h"
28 __RCSID("$NetBSD: auth.c,v 1.28 2009/02/16 20:53:54 christos Exp $");
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/param.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <libgen.h>
36 #include <login_cap.h>
37 #include <paths.h>
38 #include <pwd.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
44 #include "xmalloc.h"
45 #include "match.h"
46 #include "groupaccess.h"
47 #include "log.h"
48 #include "buffer.h"
49 #include "servconf.h"
50 #include "key.h"
51 #include "hostfile.h"
52 #include "auth.h"
53 #include "auth-options.h"
54 #include "canohost.h"
55 #include "uidswap.h"
56 #include "misc.h"
57 #include "packet.h"
58 #ifdef GSSAPI
59 #include "ssh-gss.h"
60 #endif
61 #include "monitor_wrap.h"
63 #ifdef HAVE_LOGIN_CAP
64 #include <login_cap.h>
65 #endif
67 /* import */
68 extern ServerOptions options;
69 extern int use_privsep;
71 /* Debugging messages */
72 Buffer auth_debug;
73 int auth_debug_init;
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.
81 * If the user's shell is not executable, false will be returned.
82 * Otherwise true is returned.
84 int
85 allowed_user(struct passwd * pw)
87 #ifdef HAVE_LOGIN_CAP
88 extern login_cap_t *lc;
89 int match_name, match_ip;
90 char *cap_hlist, *hp;
91 #endif
92 struct stat st;
93 const char *hostname = NULL, *ipaddr = NULL;
94 char *shell;
95 u_int i;
97 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
98 if (!pw || !pw->pw_name)
99 return 0;
101 #ifdef HAVE_LOGIN_CAP
102 hostname = get_canonical_hostname(1);
103 ipaddr = get_remote_ipaddr();
105 lc = login_getclass(pw->pw_class);
108 * Check the deny list.
110 cap_hlist = login_getcapstr(lc, "host.deny", NULL, NULL);
111 if (cap_hlist != NULL) {
112 hp = strtok(cap_hlist, ",");
113 while (hp != NULL) {
114 match_name = match_hostname(hostname,
115 hp, strlen(hp));
116 match_ip = match_hostname(ipaddr,
117 hp, strlen(hp));
119 * Only a positive match here causes a "deny".
121 if (match_name > 0 || match_ip > 0) {
122 free(cap_hlist);
123 login_close(lc);
124 return 0;
126 hp = strtok(NULL, ",");
128 free(cap_hlist);
132 * Check the allow list. If the allow list exists, and the
133 * remote host is not in it, the user is implicitly denied.
135 cap_hlist = login_getcapstr(lc, "host.allow", NULL, NULL);
136 if (cap_hlist != NULL) {
137 hp = strtok(cap_hlist, ",");
138 if (hp == NULL) {
139 /* Just in case there's an empty string... */
140 free(cap_hlist);
141 login_close(lc);
142 return 0;
144 while (hp != NULL) {
145 match_name = match_hostname(hostname,
146 hp, strlen(hp));
147 match_ip = match_hostname(ipaddr,
148 hp, strlen(hp));
150 * Negative match causes an immediate "deny".
151 * Positive match causes us to break out
152 * of the loop (allowing a fallthrough).
154 if (match_name < 0 || match_ip < 0) {
155 free(cap_hlist);
156 login_close(lc);
157 return 0;
159 if (match_name > 0 || match_ip > 0)
160 break;
161 hp = strtok(NULL, ",");
163 free(cap_hlist);
164 if (hp == NULL) {
165 login_close(lc);
166 return 0;
170 login_close(lc);
171 #endif
173 #ifdef USE_PAM
174 if (!options.use_pam) {
175 #endif
177 * password/account expiration.
179 if (pw->pw_change || pw->pw_expire) {
180 struct timeval tv;
182 (void)gettimeofday(&tv, (struct timezone *)NULL);
183 if (pw->pw_expire) {
184 if (tv.tv_sec >= pw->pw_expire) {
185 logit("User %.100s not allowed because account has expired",
186 pw->pw_name);
187 return 0; /* expired */
190 #ifdef _PASSWORD_CHGNOW
191 if (pw->pw_change == _PASSWORD_CHGNOW) {
192 logit("User %.100s not allowed because password needs to be changed",
193 pw->pw_name);
195 return 0; /* can't force password change (yet) */
197 #endif
198 if (pw->pw_change) {
199 if (tv.tv_sec >= pw->pw_change) {
200 logit("User %.100s not allowed because password has expired",
201 pw->pw_name);
202 return 0; /* expired */
206 #ifdef USE_PAM
208 #endif
211 * Get the shell from the password data. An empty shell field is
212 * legal, and means /bin/sh.
214 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
216 /* deny if shell does not exists or is not executable */
218 * XXX Should check to see if it is executable by the
219 * XXX requesting user. --thorpej
221 if (stat(shell, &st) != 0) {
222 logit("User %.100s not allowed because shell %.100s does not exist",
223 pw->pw_name, shell);
224 return 0;
226 if (S_ISREG(st.st_mode) == 0 ||
227 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
228 logit("User %.100s not allowed because shell %.100s is not executable",
229 pw->pw_name, shell);
230 return 0;
233 * XXX Consider nuking {Allow,Deny}{Users,Groups}. We have the
234 * XXX login_cap(3) mechanism which covers all other types of
235 * XXX logins, too.
238 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
239 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
240 hostname = get_canonical_hostname(options.use_dns);
241 ipaddr = get_remote_ipaddr();
244 /* Return false if user is listed in DenyUsers */
245 if (options.num_deny_users > 0) {
246 for (i = 0; i < options.num_deny_users; i++)
247 if (match_user(pw->pw_name, hostname, ipaddr,
248 options.deny_users[i])) {
249 logit("User %.100s from %.100s not allowed "
250 "because listed in DenyUsers",
251 pw->pw_name, hostname);
252 return 0;
255 /* Return false if AllowUsers isn't empty and user isn't listed there */
256 if (options.num_allow_users > 0) {
257 for (i = 0; i < options.num_allow_users; i++)
258 if (match_user(pw->pw_name, hostname, ipaddr,
259 options.allow_users[i]))
260 break;
261 /* i < options.num_allow_users iff we break for loop */
262 if (i >= options.num_allow_users) {
263 logit("User %.100s from %.100s not allowed because "
264 "not listed in AllowUsers", pw->pw_name, hostname);
265 return 0;
268 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
269 /* Get the user's group access list (primary and supplementary) */
270 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
271 logit("User %.100s from %.100s not allowed because "
272 "not in any group", pw->pw_name, hostname);
273 return 0;
276 /* Return false if one of user's groups is listed in DenyGroups */
277 if (options.num_deny_groups > 0)
278 if (ga_match(options.deny_groups,
279 options.num_deny_groups)) {
280 ga_free();
281 logit("User %.100s from %.100s not allowed "
282 "because a group is listed in DenyGroups",
283 pw->pw_name, hostname);
284 return 0;
287 * Return false if AllowGroups isn't empty and one of user's groups
288 * isn't listed there
290 if (options.num_allow_groups > 0)
291 if (!ga_match(options.allow_groups,
292 options.num_allow_groups)) {
293 ga_free();
294 logit("User %.100s from %.100s not allowed "
295 "because none of user's groups are listed "
296 "in AllowGroups", pw->pw_name, hostname);
297 return 0;
299 ga_free();
301 /* We found no reason not to let this user try to log on... */
302 return 1;
305 void
306 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
308 void (*authlog) (const char *fmt,...) = verbose;
309 char *authmsg;
311 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
312 return;
314 /* Raise logging level */
315 if (authenticated == 1 ||
316 !authctxt->valid ||
317 authctxt->failures >= options.max_authtries / 2 ||
318 strcmp(method, "password") == 0)
319 authlog = logit;
321 if (authctxt->postponed)
322 authmsg = "Postponed";
323 else
324 authmsg = authenticated ? "Accepted" : "Failed";
326 authlog("%s %s for %s%.100s from %.200s port %d%s",
327 authmsg,
328 method,
329 authctxt->valid ? "" : "invalid user ",
330 authctxt->user,
331 get_remote_ipaddr(),
332 get_remote_port(),
333 info);
337 * Check whether root logins are disallowed.
340 auth_root_allowed(char *method)
342 switch (options.permit_root_login) {
343 case PERMIT_YES:
344 return 1;
345 case PERMIT_NO_PASSWD:
346 if (strcmp(method, "password") != 0)
347 return 1;
348 break;
349 case PERMIT_FORCED_ONLY:
350 if (forced_command) {
351 logit("Root login accepted for forced command.");
352 return 1;
354 break;
356 logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
357 return 0;
362 * Given a template and a passwd structure, build a filename
363 * by substituting % tokenised options. Currently, %% becomes '%',
364 * %h becomes the home directory and %u the username.
366 * This returns a buffer allocated by xmalloc.
368 static char *
369 expand_authorized_keys(const char *filename, struct passwd *pw)
371 char *file, ret[MAXPATHLEN];
372 int i;
374 file = percent_expand(filename, "h", pw->pw_dir,
375 "u", pw->pw_name, (char *)NULL);
378 * Ensure that filename starts anchored. If not, be backward
379 * compatible and prepend the '%h/'
381 if (*file == '/')
382 return (file);
384 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
385 if (i < 0 || (size_t)i >= sizeof(ret))
386 fatal("expand_authorized_keys: path too long");
387 xfree(file);
388 return (xstrdup(ret));
391 char *
392 authorized_keys_file(struct passwd *pw)
394 return expand_authorized_keys(options.authorized_keys_file, pw);
397 char *
398 authorized_keys_file2(struct passwd *pw)
400 return expand_authorized_keys(options.authorized_keys_file2, pw);
403 /* return ok if key exists in sysfile or userfile */
404 HostStatus
405 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
406 const char *sysfile, const char *userfile)
408 Key *found;
409 char *user_hostfile;
410 struct stat st;
411 HostStatus host_status;
413 /* Check if we know the host and its host key. */
414 found = key_new(key->type);
415 host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
417 if (host_status != HOST_OK && userfile != NULL) {
418 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
419 if (options.strict_modes &&
420 (stat(user_hostfile, &st) == 0) &&
421 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
422 (st.st_mode & 022) != 0)) {
423 logit("Authentication refused for %.100s: "
424 "bad owner or modes for %.200s",
425 pw->pw_name, user_hostfile);
426 } else {
427 temporarily_use_uid(pw);
428 host_status = check_host_in_hostfile(user_hostfile,
429 host, key, found, NULL);
430 restore_uid();
432 xfree(user_hostfile);
434 key_free(found);
436 debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
437 "ok" : "not found", host);
438 return host_status;
443 * Check a given file for security. This is defined as all components
444 * of the path to the file must be owned by either the owner of
445 * of the file or root and no directories must be group or world writable.
447 * XXX Should any specific check be done for sym links ?
449 * Takes an open file descriptor, the file name, a uid and and
450 * error buffer plus max size as arguments.
452 * Returns 0 on success and -1 on failure
454 static int
455 secure_filename(FILE *f, const char *file, struct passwd *pw,
456 char *err, size_t errlen)
458 uid_t uid = pw->pw_uid;
459 char buf[MAXPATHLEN], homedir[MAXPATHLEN];
460 char *cp;
461 int comparehome = 0;
462 struct stat st;
464 if (realpath(file, buf) == NULL) {
465 snprintf(err, errlen, "realpath %s failed: %s", file,
466 strerror(errno));
467 return -1;
469 if (realpath(pw->pw_dir, homedir) != NULL)
470 comparehome = 1;
472 /* check the open file to avoid races */
473 if (fstat(fileno(f), &st) < 0 ||
474 (st.st_uid != 0 && st.st_uid != uid) ||
475 (st.st_mode & 022) != 0) {
476 snprintf(err, errlen, "bad ownership or modes for file %s",
477 buf);
478 return -1;
481 /* for each component of the canonical path, walking upwards */
482 for (;;) {
483 if ((cp = dirname(buf)) == NULL) {
484 snprintf(err, errlen, "dirname() failed");
485 return -1;
487 strlcpy(buf, cp, sizeof(buf));
489 debug3("secure_filename: checking '%s'", buf);
490 if (stat(buf, &st) < 0 ||
491 (st.st_uid != 0 && st.st_uid != uid) ||
492 (st.st_mode & 022) != 0) {
493 snprintf(err, errlen,
494 "bad ownership or modes for directory %s", buf);
495 return -1;
498 /* If are passed the homedir then we can stop */
499 if (comparehome && strcmp(homedir, buf) == 0) {
500 debug3("secure_filename: terminating check at '%s'",
501 buf);
502 break;
505 * dirname should always complete with a "/" path,
506 * but we can be paranoid and check for "." too
508 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
509 break;
511 return 0;
514 FILE *
515 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
517 char line[1024];
518 struct stat st;
519 int fd;
520 FILE *f;
523 * Open the file containing the authorized keys
524 * Fail quietly if file does not exist
526 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1)
527 return NULL;
529 if (fstat(fd, &st) < 0) {
530 close(fd);
531 return NULL;
533 if (!S_ISREG(st.st_mode)) {
534 logit("User %s authorized keys %s is not a regular file",
535 pw->pw_name, file);
536 close(fd);
537 return NULL;
539 unset_nonblock(fd);
540 if ((f = fdopen(fd, "r")) == NULL) {
541 close(fd);
542 return NULL;
544 if (options.strict_modes &&
545 secure_filename(f, file, pw, line, sizeof(line)) != 0) {
546 fclose(f);
547 logit("Authentication refused: %s", line);
548 return NULL;
551 return f;
554 struct passwd *
555 getpwnamallow(const char *user)
557 #ifdef HAVE_LOGIN_CAP
558 extern login_cap_t *lc;
559 #ifdef BSD_AUTH
560 auth_session_t *as;
561 #endif
562 #endif
563 struct passwd *pw;
565 parse_server_match_config(&options, user,
566 get_canonical_hostname(options.use_dns), get_remote_ipaddr());
568 pw = getpwnam(user);
569 if (pw == NULL) {
570 logit("Invalid user %.100s from %.100s",
571 user, get_remote_ipaddr());
572 return (NULL);
574 if (!allowed_user(pw))
575 return (NULL);
576 #ifdef HAVE_LOGIN_CAP
577 if ((lc = login_getclass(pw->pw_class)) == NULL) {
578 debug("unable to get login class: %s", user);
579 return (NULL);
581 #ifdef BSD_AUTH
582 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
583 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
584 debug("Approval failure for %s", user);
585 pw = NULL;
587 if (as != NULL)
588 auth_close(as);
589 #endif
590 #endif
591 if (pw != NULL)
592 return (pwcopy(pw));
593 return (NULL);
596 void
597 auth_debug_add(const char *fmt,...)
599 char buf[1024];
600 va_list args;
602 if (!auth_debug_init)
603 return;
605 va_start(args, fmt);
606 vsnprintf(buf, sizeof(buf), fmt, args);
607 va_end(args);
608 buffer_put_cstring(&auth_debug, buf);
611 void
612 auth_debug_send(void)
614 char *msg;
616 if (!auth_debug_init)
617 return;
618 while (buffer_len(&auth_debug)) {
619 msg = buffer_get_string(&auth_debug, NULL);
620 packet_send_debug("%s", msg);
621 xfree(msg);
625 void
626 auth_debug_reset(void)
628 if (auth_debug_init)
629 buffer_clear(&auth_debug);
630 else {
631 buffer_init(&auth_debug);
632 auth_debug_init = 1;
636 struct passwd *
637 fakepw(void)
639 static struct passwd fake;
641 memset(&fake, 0, sizeof(fake));
642 fake.pw_name = "NOUSER";
643 fake.pw_passwd =
644 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
645 fake.pw_gecos = "NOUSER";
646 fake.pw_uid = (uid_t)-1;
647 fake.pw_gid = (gid_t)-1;
648 fake.pw_class = "";
649 fake.pw_dir = "/nonexist";
650 fake.pw_shell = "/nonexist";
652 return (&fake);