]> andersk Git - openssh.git/blob - auth.c
[configure.ac] Make sure -lcrypto is before -lsocket for sco3. ok mouring@
[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.51 2003/11/21 11:57:02 djm Exp $");
27
28 #ifdef HAVE_LOGIN_H
29 #include <login.h>
30 #endif
31 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
32 #include <shadow.h>
33 #endif /* defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) */
34
35 #ifdef HAVE_LIBGEN_H
36 #include <libgen.h>
37 #endif
38
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 "tildexpand.h"
51 #include "misc.h"
52 #include "bufaux.h"
53 #include "packet.h"
54
55 /* import */
56 extern ServerOptions options;
57 extern Buffer loginmsg;
58
59 /* Debugging messages */
60 Buffer auth_debug;
61 int auth_debug_init;
62
63 /*
64  * Check if the user is allowed to log in via ssh. If user is listed
65  * in DenyUsers or one of user's groups is listed in DenyGroups, false
66  * will be returned. If AllowUsers isn't empty and user isn't listed
67  * there, or if AllowGroups isn't empty and one of user's groups isn't
68  * listed there, false will be returned.
69  * If the user's shell is not executable, false will be returned.
70  * Otherwise true is returned.
71  */
72 int
73 allowed_user(struct passwd * pw)
74 {
75         struct stat st;
76         const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
77         char *shell;
78         int i;
79 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
80         struct spwd *spw = NULL;
81 #endif
82
83         /* Shouldn't be called if pw is NULL, but better safe than sorry... */
84         if (!pw || !pw->pw_name)
85                 return 0;
86
87 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
88         if (!options.use_pam)
89                 spw = getspnam(pw->pw_name);
90 #ifdef HAS_SHADOW_EXPIRE
91 #define DAY             (24L * 60 * 60) /* 1 day in seconds */
92         if (!options.use_pam && spw != NULL) {
93                 int disabled = 0;
94                 time_t today;
95
96                 today = time(NULL) / DAY;
97                 debug3("allowed_user: today %d sp_expire %d sp_lstchg %d"
98                     " sp_max %d", (int)today, (int)spw->sp_expire,
99                     (int)spw->sp_lstchg, (int)spw->sp_max);
100
101                 /*
102                  * We assume account and password expiration occurs the
103                  * day after the day specified.
104                  */
105                 if (spw->sp_expire != -1 && today > spw->sp_expire) {
106                         logit("Account %.100s has expired", pw->pw_name);
107                         return 0;
108                 }
109         }
110 #endif /* HAS_SHADOW_EXPIRE */
111 #endif /* defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) */
112
113         /* grab passwd field for locked account check */
114 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
115         if (spw != NULL)
116                 passwd = spw->sp_pwdp;
117 #else
118         passwd = pw->pw_passwd;
119 #endif
120
121         /* check for locked account */
122         if (!options.use_pam && passwd && *passwd) {
123                 int locked = 0;
124
125 #ifdef LOCKED_PASSWD_STRING
126                 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
127                          locked = 1;
128 #endif
129 #ifdef LOCKED_PASSWD_PREFIX
130                 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
131                     strlen(LOCKED_PASSWD_PREFIX)) == 0)
132                          locked = 1;
133 #endif
134 #ifdef LOCKED_PASSWD_SUBSTR
135                 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
136                         locked = 1;
137 #endif
138                 if (locked) {
139                         logit("User %.100s not allowed because account is locked",
140                             pw->pw_name);
141                         return 0;
142                 }
143         }
144
145         /*
146          * Get the shell from the password data.  An empty shell field is
147          * legal, and means /bin/sh.
148          */
149         shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
150
151         /* deny if shell does not exists or is not executable */
152         if (stat(shell, &st) != 0) {
153                 logit("User %.100s not allowed because shell %.100s does not exist",
154                     pw->pw_name, shell);
155                 return 0;
156         }
157         if (S_ISREG(st.st_mode) == 0 ||
158             (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
159                 logit("User %.100s not allowed because shell %.100s is not executable",
160                     pw->pw_name, shell);
161                 return 0;
162         }
163
164         if (options.num_deny_users > 0 || options.num_allow_users > 0) {
165                 hostname = get_canonical_hostname(options.use_dns);
166                 ipaddr = get_remote_ipaddr();
167         }
168
169         /* Return false if user is listed in DenyUsers */
170         if (options.num_deny_users > 0) {
171                 for (i = 0; i < options.num_deny_users; i++)
172                         if (match_user(pw->pw_name, hostname, ipaddr,
173                             options.deny_users[i])) {
174                                 logit("User %.100s not allowed because listed in DenyUsers",
175                                     pw->pw_name);
176                                 return 0;
177                         }
178         }
179         /* Return false if AllowUsers isn't empty and user isn't listed there */
180         if (options.num_allow_users > 0) {
181                 for (i = 0; i < options.num_allow_users; i++)
182                         if (match_user(pw->pw_name, hostname, ipaddr,
183                             options.allow_users[i]))
184                                 break;
185                 /* i < options.num_allow_users iff we break for loop */
186                 if (i >= options.num_allow_users) {
187                         logit("User %.100s not allowed because not listed in AllowUsers",
188                             pw->pw_name);
189                         return 0;
190                 }
191         }
192         if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
193                 /* Get the user's group access list (primary and supplementary) */
194                 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
195                         logit("User %.100s not allowed because not in any group",
196                             pw->pw_name);
197                         return 0;
198                 }
199
200                 /* Return false if one of user's groups is listed in DenyGroups */
201                 if (options.num_deny_groups > 0)
202                         if (ga_match(options.deny_groups,
203                             options.num_deny_groups)) {
204                                 ga_free();
205                                 logit("User %.100s not allowed because a group is listed in DenyGroups",
206                                     pw->pw_name);
207                                 return 0;
208                         }
209                 /*
210                  * Return false if AllowGroups isn't empty and one of user's groups
211                  * isn't listed there
212                  */
213                 if (options.num_allow_groups > 0)
214                         if (!ga_match(options.allow_groups,
215                             options.num_allow_groups)) {
216                                 ga_free();
217                                 logit("User %.100s not allowed because none of user's groups are listed in AllowGroups",
218                                     pw->pw_name);
219                                 return 0;
220                         }
221                 ga_free();
222         }
223
224 #ifdef WITH_AIXAUTHENTICATE
225         /*
226          * Don't check loginrestrictions() for root account (use
227          * PermitRootLogin to control logins via ssh), or if running as
228          * non-root user (since loginrestrictions will always fail).
229          */
230         if ((pw->pw_uid != 0) && (geteuid() == 0)) {
231                 char *msg;
232
233                 if (loginrestrictions(pw->pw_name, S_RLOGIN, NULL, &msg) != 0) {
234                         int loginrestrict_errno = errno;
235
236                         if (msg && *msg) {
237                                 buffer_append(&loginmsg, msg, strlen(msg));
238                                 aix_remove_embedded_newlines(msg);
239                                 logit("Login restricted for %s: %.100s",
240                                     pw->pw_name, msg);
241                         }
242                         /* Don't fail if /etc/nologin  set */
243                         if (!(loginrestrict_errno == EPERM &&
244                             stat(_PATH_NOLOGIN, &st) == 0))
245                                 return 0;
246                 }
247         }
248 #endif /* WITH_AIXAUTHENTICATE */
249
250         /* We found no reason not to let this user try to log on... */
251         return 1;
252 }
253
254 void
255 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
256 {
257         void (*authlog) (const char *fmt,...) = verbose;
258         char *authmsg;
259
260         /* Raise logging level */
261         if (authenticated == 1 ||
262             !authctxt->valid ||
263             authctxt->failures >= AUTH_FAIL_LOG ||
264             strcmp(method, "password") == 0)
265                 authlog = logit;
266
267         if (authctxt->postponed)
268                 authmsg = "Postponed";
269         else
270                 authmsg = authenticated ? "Accepted" : "Failed";
271
272         authlog("%s %s for %s%.100s from %.200s port %d%s",
273             authmsg,
274             method,
275             authctxt->valid ? "" : "illegal user ",
276             authctxt->user,
277             get_remote_ipaddr(),
278             get_remote_port(),
279             info);
280
281 #ifdef CUSTOM_FAILED_LOGIN
282         if (authenticated == 0 && strcmp(method, "password") == 0)
283                 record_failed_login(authctxt->user, "ssh");
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                 break;
297         case PERMIT_NO_PASSWD:
298                 if (strcmp(method, "password") != 0)
299                         return 1;
300                 break;
301         case PERMIT_FORCED_ONLY:
302                 if (forced_command) {
303                         logit("Root login accepted for forced command.");
304                         return 1;
305                 }
306                 break;
307         }
308         logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
309         return 0;
310 }
311
312
313 /*
314  * Given a template and a passwd structure, build a filename
315  * by substituting % tokenised options. Currently, %% becomes '%',
316  * %h becomes the home directory and %u the username.
317  *
318  * This returns a buffer allocated by xmalloc.
319  */
320 char *
321 expand_filename(const char *filename, struct passwd *pw)
322 {
323         Buffer buffer;
324         char *file;
325         const char *cp;
326
327         /*
328          * Build the filename string in the buffer by making the appropriate
329          * substitutions to the given file name.
330          */
331         buffer_init(&buffer);
332         for (cp = filename; *cp; cp++) {
333                 if (cp[0] == '%' && cp[1] == '%') {
334                         buffer_append(&buffer, "%", 1);
335                         cp++;
336                         continue;
337                 }
338                 if (cp[0] == '%' && cp[1] == 'h') {
339                         buffer_append(&buffer, pw->pw_dir, strlen(pw->pw_dir));
340                         cp++;
341                         continue;
342                 }
343                 if (cp[0] == '%' && cp[1] == 'u') {
344                         buffer_append(&buffer, pw->pw_name,
345                             strlen(pw->pw_name));
346                         cp++;
347                         continue;
348                 }
349                 buffer_append(&buffer, cp, 1);
350         }
351         buffer_append(&buffer, "\0", 1);
352
353         /*
354          * Ensure that filename starts anchored. If not, be backward
355          * compatible and prepend the '%h/'
356          */
357         file = xmalloc(MAXPATHLEN);
358         cp = buffer_ptr(&buffer);
359         if (*cp != '/')
360                 snprintf(file, MAXPATHLEN, "%s/%s", pw->pw_dir, cp);
361         else
362                 strlcpy(file, cp, MAXPATHLEN);
363
364         buffer_free(&buffer);
365         return file;
366 }
367
368 char *
369 authorized_keys_file(struct passwd *pw)
370 {
371         return expand_filename(options.authorized_keys_file, pw);
372 }
373
374 char *
375 authorized_keys_file2(struct passwd *pw)
376 {
377         return expand_filename(options.authorized_keys_file2, pw);
378 }
379
380 /* return ok if key exists in sysfile or userfile */
381 HostStatus
382 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
383     const char *sysfile, const char *userfile)
384 {
385         Key *found;
386         char *user_hostfile;
387         struct stat st;
388         HostStatus host_status;
389
390         /* Check if we know the host and its host key. */
391         found = key_new(key->type);
392         host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
393
394         if (host_status != HOST_OK && userfile != NULL) {
395                 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
396                 if (options.strict_modes &&
397                     (stat(user_hostfile, &st) == 0) &&
398                     ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
399                     (st.st_mode & 022) != 0)) {
400                         logit("Authentication refused for %.100s: "
401                             "bad owner or modes for %.200s",
402                             pw->pw_name, user_hostfile);
403                 } else {
404                         temporarily_use_uid(pw);
405                         host_status = check_host_in_hostfile(user_hostfile,
406                             host, key, found, NULL);
407                         restore_uid();
408                 }
409                 xfree(user_hostfile);
410         }
411         key_free(found);
412
413         debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
414             "ok" : "not found", host);
415         return host_status;
416 }
417
418
419 /*
420  * Check a given file for security. This is defined as all components
421  * of the path to the file must be owned by either the owner of
422  * of the file or root and no directories must be group or world writable.
423  *
424  * XXX Should any specific check be done for sym links ?
425  *
426  * Takes an open file descriptor, the file name, a uid and and
427  * error buffer plus max size as arguments.
428  *
429  * Returns 0 on success and -1 on failure
430  */
431 int
432 secure_filename(FILE *f, const char *file, struct passwd *pw,
433     char *err, size_t errlen)
434 {
435         uid_t uid = pw->pw_uid;
436         char buf[MAXPATHLEN], homedir[MAXPATHLEN];
437         char *cp;
438         int comparehome = 0;
439         struct stat st;
440
441         if (realpath(file, buf) == NULL) {
442                 snprintf(err, errlen, "realpath %s failed: %s", file,
443                     strerror(errno));
444                 return -1;
445         }
446         if (realpath(pw->pw_dir, homedir) != NULL)
447                 comparehome = 1;
448
449         /* check the open file to avoid races */
450         if (fstat(fileno(f), &st) < 0 ||
451             (st.st_uid != 0 && st.st_uid != uid) ||
452             (st.st_mode & 022) != 0) {
453                 snprintf(err, errlen, "bad ownership or modes for file %s",
454                     buf);
455                 return -1;
456         }
457
458         /* for each component of the canonical path, walking upwards */
459         for (;;) {
460                 if ((cp = dirname(buf)) == NULL) {
461                         snprintf(err, errlen, "dirname() failed");
462                         return -1;
463                 }
464                 strlcpy(buf, cp, sizeof(buf));
465
466                 debug3("secure_filename: checking '%s'", buf);
467                 if (stat(buf, &st) < 0 ||
468                     (st.st_uid != 0 && st.st_uid != uid) ||
469                     (st.st_mode & 022) != 0) {
470                         snprintf(err, errlen,
471                             "bad ownership or modes for directory %s", buf);
472                         return -1;
473                 }
474
475                 /* If are passed the homedir then we can stop */
476                 if (comparehome && strcmp(homedir, buf) == 0) {
477                         debug3("secure_filename: terminating check at '%s'",
478                             buf);
479                         break;
480                 }
481                 /*
482                  * dirname should always complete with a "/" path,
483                  * but we can be paranoid and check for "." too
484                  */
485                 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
486                         break;
487         }
488         return 0;
489 }
490
491 struct passwd *
492 getpwnamallow(const char *user)
493 {
494 #ifdef HAVE_LOGIN_CAP
495         extern login_cap_t *lc;
496 #ifdef BSD_AUTH
497         auth_session_t *as;
498 #endif
499 #endif
500         struct passwd *pw;
501
502         pw = getpwnam(user);
503         if (pw == NULL) {
504                 logit("Illegal user %.100s from %.100s",
505                     user, get_remote_ipaddr());
506 #ifdef CUSTOM_FAILED_LOGIN
507                 record_failed_login(user, "ssh");
508 #endif
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 = -1;
584         fake.pw_gid = -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.157382 seconds and 5 git commands to generate.