]> andersk Git - openssh.git/blob - auth.c
- stevesk@cvs.openbsd.org 2006/02/08 12:15:27
[openssh.git] / auth.c
1 /*
2  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
3  *
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.
12  *
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.
23  */
24
25 #include "includes.h"
26 RCSID("$OpenBSD: auth.c,v 1.61 2006/02/08 12:15:27 stevesk Exp $");
27
28 #ifdef HAVE_PATHS_H
29 #  include <paths.h>
30 #endif
31 #ifdef HAVE_LOGIN_H
32 #include <login.h>
33 #endif
34 #ifdef USE_SHADOW
35 #include <shadow.h>
36 #endif
37
38 #ifdef HAVE_LIBGEN_H
39 #include <libgen.h>
40 #endif
41
42 #include "xmalloc.h"
43 #include "match.h"
44 #include "groupaccess.h"
45 #include "log.h"
46 #include "servconf.h"
47 #include "auth.h"
48 #include "auth-options.h"
49 #include "canohost.h"
50 #include "buffer.h"
51 #include "bufaux.h"
52 #include "uidswap.h"
53 #include "misc.h"
54 #include "bufaux.h"
55 #include "packet.h"
56 #include "loginrec.h"
57 #include "monitor_wrap.h"
58
59 /* import */
60 extern ServerOptions options;
61 extern Buffer loginmsg;
62
63 /* Debugging messages */
64 Buffer auth_debug;
65 int auth_debug_init;
66
67 /*
68  * Check if the user is allowed to log in via ssh. If user is listed
69  * in DenyUsers or one of user's groups is listed in DenyGroups, false
70  * will be returned. If AllowUsers isn't empty and user isn't listed
71  * there, or if AllowGroups isn't empty and one of user's groups isn't
72  * listed there, false will be returned.
73  * If the user's shell is not executable, false will be returned.
74  * Otherwise true is returned.
75  */
76 int
77 allowed_user(struct passwd * pw)
78 {
79         struct stat st;
80         const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
81         char *shell;
82         u_int i;
83 #ifdef USE_SHADOW
84         struct spwd *spw = NULL;
85 #endif
86
87         /* Shouldn't be called if pw is NULL, but better safe than sorry... */
88         if (!pw || !pw->pw_name)
89                 return 0;
90
91 #ifdef USE_SHADOW
92         if (!options.use_pam)
93                 spw = getspnam(pw->pw_name);
94 #ifdef HAS_SHADOW_EXPIRE
95         if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
96                 return 0;
97 #endif /* HAS_SHADOW_EXPIRE */
98 #endif /* USE_SHADOW */
99
100         /* grab passwd field for locked account check */
101 #ifdef USE_SHADOW
102         if (spw != NULL)
103 #if defined(HAVE_LIBIAF)  &&  !defined(BROKEN_LIBIAF)
104                 passwd = get_iaf_password(pw);
105 #else
106                 passwd = spw->sp_pwdp;
107 #endif /* HAVE_LIBIAF  && !BROKEN_LIBIAF */
108 #else
109         passwd = pw->pw_passwd;
110 #endif
111
112         /* check for locked account */
113         if (!options.use_pam && passwd && *passwd) {
114                 int locked = 0;
115
116 #ifdef LOCKED_PASSWD_STRING
117                 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
118                          locked = 1;
119 #endif
120 #ifdef LOCKED_PASSWD_PREFIX
121                 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
122                     strlen(LOCKED_PASSWD_PREFIX)) == 0)
123                          locked = 1;
124 #endif
125 #ifdef LOCKED_PASSWD_SUBSTR
126                 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
127                         locked = 1;
128 #endif
129 #if defined(HAVE_LIBIAF)  &&  !defined(BROKEN_LIBIAF)
130                 free(passwd);
131 #endif /* HAVE_LIBIAF  && !BROKEN_LIBIAF */
132                 if (locked) {
133                         logit("User %.100s not allowed because account is locked",
134                             pw->pw_name);
135                         return 0;
136                 }
137         }
138
139         /*
140          * Get the shell from the password data.  An empty shell field is
141          * legal, and means /bin/sh.
142          */
143         shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
144
145         /* deny if shell does not exists or is not executable */
146         if (stat(shell, &st) != 0) {
147                 logit("User %.100s not allowed because shell %.100s does not exist",
148                     pw->pw_name, shell);
149                 return 0;
150         }
151         if (S_ISREG(st.st_mode) == 0 ||
152             (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
153                 logit("User %.100s not allowed because shell %.100s is not executable",
154                     pw->pw_name, shell);
155                 return 0;
156         }
157
158         if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
159             options.num_deny_groups > 0 || options.num_allow_groups > 0) {
160                 hostname = get_canonical_hostname(options.use_dns);
161                 ipaddr = get_remote_ipaddr();
162         }
163
164         /* Return false if user is listed in DenyUsers */
165         if (options.num_deny_users > 0) {
166                 for (i = 0; i < options.num_deny_users; i++)
167                         if (match_user(pw->pw_name, hostname, ipaddr,
168                             options.deny_users[i])) {
169                                 logit("User %.100s from %.100s not allowed "
170                                     "because listed in DenyUsers",
171                                     pw->pw_name, hostname);
172                                 return 0;
173                         }
174         }
175         /* Return false if AllowUsers isn't empty and user isn't listed there */
176         if (options.num_allow_users > 0) {
177                 for (i = 0; i < options.num_allow_users; i++)
178                         if (match_user(pw->pw_name, hostname, ipaddr,
179                             options.allow_users[i]))
180                                 break;
181                 /* i < options.num_allow_users iff we break for loop */
182                 if (i >= options.num_allow_users) {
183                         logit("User %.100s from %.100s not allowed because "
184                             "not listed in AllowUsers", pw->pw_name, hostname);
185                         return 0;
186                 }
187         }
188         if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
189                 /* Get the user's group access list (primary and supplementary) */
190                 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
191                         logit("User %.100s from %.100s not allowed because "
192                             "not in any group", pw->pw_name, hostname);
193                         return 0;
194                 }
195
196                 /* Return false if one of user's groups is listed in DenyGroups */
197                 if (options.num_deny_groups > 0)
198                         if (ga_match(options.deny_groups,
199                             options.num_deny_groups)) {
200                                 ga_free();
201                                 logit("User %.100s from %.100s not allowed "
202                                     "because a group is listed in DenyGroups",
203                                     pw->pw_name, hostname);
204                                 return 0;
205                         }
206                 /*
207                  * Return false if AllowGroups isn't empty and one of user's groups
208                  * isn't listed there
209                  */
210                 if (options.num_allow_groups > 0)
211                         if (!ga_match(options.allow_groups,
212                             options.num_allow_groups)) {
213                                 ga_free();
214                                 logit("User %.100s from %.100s not allowed "
215                                     "because none of user's groups are listed "
216                                     "in AllowGroups", pw->pw_name, hostname);
217                                 return 0;
218                         }
219                 ga_free();
220         }
221
222 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
223         if (!sys_auth_allowed_user(pw, &loginmsg))
224                 return 0;
225 #endif
226
227         /* We found no reason not to let this user try to log on... */
228         return 1;
229 }
230
231 void
232 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
233 {
234         void (*authlog) (const char *fmt,...) = verbose;
235         char *authmsg;
236
237         /* Raise logging level */
238         if (authenticated == 1 ||
239             !authctxt->valid ||
240             authctxt->failures >= options.max_authtries / 2 ||
241             strcmp(method, "password") == 0)
242                 authlog = logit;
243
244         if (authctxt->postponed)
245                 authmsg = "Postponed";
246         else
247                 authmsg = authenticated ? "Accepted" : "Failed";
248
249         authlog("%s %s for %s%.100s from %.200s port %d%s",
250             authmsg,
251             method,
252             authctxt->valid ? "" : "invalid user ",
253             authctxt->user,
254             get_remote_ipaddr(),
255             get_remote_port(),
256             info);
257
258 #ifdef CUSTOM_FAILED_LOGIN
259         if (authenticated == 0 && !authctxt->postponed &&
260             (strcmp(method, "password") == 0 ||
261             strncmp(method, "keyboard-interactive", 20) == 0 ||
262             strcmp(method, "challenge-response") == 0))
263                 record_failed_login(authctxt->user,
264                     get_canonical_hostname(options.use_dns), "ssh");
265 #endif
266 #ifdef SSH_AUDIT_EVENTS
267         if (authenticated == 0 && !authctxt->postponed) {
268                 ssh_audit_event_t event;
269
270                 debug3("audit failed auth attempt, method %s euid %d",
271                     method, (int)geteuid());
272                 /*
273                  * Because the auth loop is used in both monitor and slave,
274                  * we must be careful to send each event only once and with
275                  * enough privs to write the event.
276                  */
277                 event = audit_classify_auth(method);
278                 switch(event) {
279                 case SSH_AUTH_FAIL_NONE:
280                 case SSH_AUTH_FAIL_PASSWD:
281                 case SSH_AUTH_FAIL_KBDINT:
282                         if (geteuid() == 0)
283                                 audit_event(event);
284                         break;
285                 case SSH_AUTH_FAIL_PUBKEY:
286                 case SSH_AUTH_FAIL_HOSTBASED:
287                 case SSH_AUTH_FAIL_GSSAPI:
288                         /*
289                          * This is required to handle the case where privsep
290                          * is enabled but it's root logging in, since
291                          * use_privsep won't be cleared until after a
292                          * successful login.
293                          */
294                         if (geteuid() == 0)
295                                 audit_event(event);
296                         else
297                                 PRIVSEP(audit_event(event));
298                         break;
299                 default:
300                         error("unknown authentication audit event %d", event);
301                 }
302         }
303 #endif
304 }
305
306 /*
307  * Check whether root logins are disallowed.
308  */
309 int
310 auth_root_allowed(char *method)
311 {
312         switch (options.permit_root_login) {
313         case PERMIT_YES:
314                 return 1;
315                 break;
316         case PERMIT_NO_PASSWD:
317                 if (strcmp(method, "password") != 0)
318                         return 1;
319                 break;
320         case PERMIT_FORCED_ONLY:
321                 if (forced_command) {
322                         logit("Root login accepted for forced command.");
323                         return 1;
324                 }
325                 break;
326         }
327         logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
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  */
339 static char *
340 expand_authorized_keys(const char *filename, struct passwd *pw)
341 {
342         char *file, *ret;
343
344         file = percent_expand(filename, "h", pw->pw_dir,
345             "u", pw->pw_name, (char *)NULL);
346
347         /*
348          * Ensure that filename starts anchored. If not, be backward
349          * compatible and prepend the '%h/'
350          */
351         if (*file == '/')
352                 return (file);
353
354         ret = xmalloc(MAXPATHLEN);
355         if (strlcpy(ret, pw->pw_dir, MAXPATHLEN) >= MAXPATHLEN ||
356             strlcat(ret, "/", MAXPATHLEN) >= MAXPATHLEN ||
357             strlcat(ret, file, MAXPATHLEN) >= MAXPATHLEN)
358                 fatal("expand_authorized_keys: path too long");
359
360         xfree(file);
361         return (ret);
362 }
363
364 char *
365 authorized_keys_file(struct passwd *pw)
366 {
367         return expand_authorized_keys(options.authorized_keys_file, pw);
368 }
369
370 char *
371 authorized_keys_file2(struct passwd *pw)
372 {
373         return expand_authorized_keys(options.authorized_keys_file2, pw);
374 }
375
376 /* return ok if key exists in sysfile or userfile */
377 HostStatus
378 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
379     const char *sysfile, const char *userfile)
380 {
381         Key *found;
382         char *user_hostfile;
383         struct stat st;
384         HostStatus host_status;
385
386         /* Check if we know the host and its host key. */
387         found = key_new(key->type);
388         host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
389
390         if (host_status != HOST_OK && userfile != NULL) {
391                 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
392                 if (options.strict_modes &&
393                     (stat(user_hostfile, &st) == 0) &&
394                     ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
395                     (st.st_mode & 022) != 0)) {
396                         logit("Authentication refused for %.100s: "
397                             "bad owner or modes for %.200s",
398                             pw->pw_name, user_hostfile);
399                 } else {
400                         temporarily_use_uid(pw);
401                         host_status = check_host_in_hostfile(user_hostfile,
402                             host, key, found, NULL);
403                         restore_uid();
404                 }
405                 xfree(user_hostfile);
406         }
407         key_free(found);
408
409         debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
410             "ok" : "not found", host);
411         return host_status;
412 }
413
414
415 /*
416  * Check a given file for security. This is defined as all components
417  * of the path to the file must be owned by either the owner of
418  * of the file or root and no directories must be group or world writable.
419  *
420  * XXX Should any specific check be done for sym links ?
421  *
422  * Takes an open file descriptor, the file name, a uid and and
423  * error buffer plus max size as arguments.
424  *
425  * Returns 0 on success and -1 on failure
426  */
427 int
428 secure_filename(FILE *f, const char *file, struct passwd *pw,
429     char *err, size_t errlen)
430 {
431         uid_t uid = pw->pw_uid;
432         char buf[MAXPATHLEN], homedir[MAXPATHLEN];
433         char *cp;
434         int comparehome = 0;
435         struct stat st;
436
437         if (realpath(file, buf) == NULL) {
438                 snprintf(err, errlen, "realpath %s failed: %s", file,
439                     strerror(errno));
440                 return -1;
441         }
442         if (realpath(pw->pw_dir, homedir) != NULL)
443                 comparehome = 1;
444
445         /* check the open file to avoid races */
446         if (fstat(fileno(f), &st) < 0 ||
447             (st.st_uid != 0 && st.st_uid != uid) ||
448             (st.st_mode & 022) != 0) {
449                 snprintf(err, errlen, "bad ownership or modes for file %s",
450                     buf);
451                 return -1;
452         }
453
454         /* for each component of the canonical path, walking upwards */
455         for (;;) {
456                 if ((cp = dirname(buf)) == NULL) {
457                         snprintf(err, errlen, "dirname() failed");
458                         return -1;
459                 }
460                 strlcpy(buf, cp, sizeof(buf));
461
462                 debug3("secure_filename: checking '%s'", buf);
463                 if (stat(buf, &st) < 0 ||
464                     (st.st_uid != 0 && st.st_uid != uid) ||
465                     (st.st_mode & 022) != 0) {
466                         snprintf(err, errlen,
467                             "bad ownership or modes for directory %s", buf);
468                         return -1;
469                 }
470
471                 /* If are passed the homedir then we can stop */
472                 if (comparehome && strcmp(homedir, buf) == 0) {
473                         debug3("secure_filename: terminating check at '%s'",
474                             buf);
475                         break;
476                 }
477                 /*
478                  * dirname should always complete with a "/" path,
479                  * but we can be paranoid and check for "." too
480                  */
481                 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
482                         break;
483         }
484         return 0;
485 }
486
487 struct passwd *
488 getpwnamallow(const char *user)
489 {
490 #ifdef HAVE_LOGIN_CAP
491         extern login_cap_t *lc;
492 #ifdef BSD_AUTH
493         auth_session_t *as;
494 #endif
495 #endif
496         struct passwd *pw;
497
498         pw = getpwnam(user);
499         if (pw == NULL) {
500                 logit("Invalid user %.100s from %.100s",
501                     user, get_remote_ipaddr());
502 #ifdef CUSTOM_FAILED_LOGIN
503                 record_failed_login(user,
504                     get_canonical_hostname(options.use_dns), "ssh");
505 #endif
506 #ifdef SSH_AUDIT_EVENTS
507                 audit_event(SSH_INVALID_USER);
508 #endif /* SSH_AUDIT_EVENTS */
509                 return (NULL);
510         }
511         if (!allowed_user(pw))
512                 return (NULL);
513 #ifdef HAVE_LOGIN_CAP
514         if ((lc = login_getclass(pw->pw_class)) == NULL) {
515                 debug("unable to get login class: %s", user);
516                 return (NULL);
517         }
518 #ifdef BSD_AUTH
519         if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
520             auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
521                 debug("Approval failure for %s", user);
522                 pw = NULL;
523         }
524         if (as != NULL)
525                 auth_close(as);
526 #endif
527 #endif
528         if (pw != NULL)
529                 return (pwcopy(pw));
530         return (NULL);
531 }
532
533 void
534 auth_debug_add(const char *fmt,...)
535 {
536         char buf[1024];
537         va_list args;
538
539         if (!auth_debug_init)
540                 return;
541
542         va_start(args, fmt);
543         vsnprintf(buf, sizeof(buf), fmt, args);
544         va_end(args);
545         buffer_put_cstring(&auth_debug, buf);
546 }
547
548 void
549 auth_debug_send(void)
550 {
551         char *msg;
552
553         if (!auth_debug_init)
554                 return;
555         while (buffer_len(&auth_debug)) {
556                 msg = buffer_get_string(&auth_debug, NULL);
557                 packet_send_debug("%s", msg);
558                 xfree(msg);
559         }
560 }
561
562 void
563 auth_debug_reset(void)
564 {
565         if (auth_debug_init)
566                 buffer_clear(&auth_debug);
567         else {
568                 buffer_init(&auth_debug);
569                 auth_debug_init = 1;
570         }
571 }
572
573 struct passwd *
574 fakepw(void)
575 {
576         static struct passwd fake;
577
578         memset(&fake, 0, sizeof(fake));
579         fake.pw_name = "NOUSER";
580         fake.pw_passwd =
581             "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
582         fake.pw_gecos = "NOUSER";
583         fake.pw_uid = (uid_t)-1;
584         fake.pw_gid = (gid_t)-1;
585 #ifdef HAVE_PW_CLASS_IN_PASSWD
586         fake.pw_class = "";
587 #endif
588         fake.pw_dir = "/nonexist";
589         fake.pw_shell = "/nonexist";
590
591         return (&fake);
592 }
This page took 0.091644 seconds and 5 git commands to generate.