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