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