]> granicus.if.org Git - linux-pam/blob - modules/pam_access/pam_access.c
Relevant BUGIDs:
[linux-pam] / modules / pam_access / pam_access.c
1 /* pam_access module */
2
3 /*
4  * Written by Alexei Nogin <alexei@nogin.dnttm.ru> 1997/06/15
5  * (I took login_access from logdaemon-5.6 and converted it to PAM
6  * using parts of pam_time code.)
7  *
8  ************************************************************************
9  * Copyright message from logdaemon-5.6 (original file name DISCLAIMER)
10  ************************************************************************
11  * Copyright 1995 by Wietse Venema. All rights reserved. Individual files
12  * may be covered by other copyrights (as noted in the file itself.)
13  *
14  * This material was originally written and compiled by Wietse Venema at
15  * Eindhoven University of Technology, The Netherlands, in 1990, 1991,
16  * 1992, 1993, 1994 and 1995.
17  *
18  * Redistribution and use in source and binary forms are permitted
19  * provided that this entire copyright notice is duplicated in all such
20  * copies.
21  *
22  * This software is provided "as is" and without any expressed or implied
23  * warranties, including, without limitation, the implied warranties of
24  * merchantibility and fitness for any particular purpose.
25  *************************************************************************
26  */
27
28 #include <security/_pam_aconf.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33
34 #include <stdarg.h>
35 #include <syslog.h>
36 #include <string.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <pwd.h>
40 #include <grp.h>
41 #include <errno.h>
42 #include <ctype.h>
43 #include <sys/utsname.h>
44 #include <rpcsvc/ypclnt.h>
45
46 #ifndef BROKEN_NETWORK_MATCH
47 # include <netdb.h>
48 # include <sys/socket.h>
49 #endif
50
51 /*
52  * here, we make definitions for the externally accessible functions
53  * in this file (these definitions are required for static modules
54  * but strongly encouraged generally) they are used to instruct the
55  * modules include file to define their prototypes.
56  */
57
58 #define PAM_SM_ACCOUNT
59
60 #include <security/_pam_macros.h>
61 #include <security/pam_modules.h>
62 #include <security/_pam_modutil.h>
63
64 /* login_access.c from logdaemon-5.6 with several changes by A.Nogin: */
65
66  /*
67   * This module implements a simple but effective form of login access
68   * control based on login names and on host (or domain) names, internet
69   * addresses (or network numbers), or on terminal line names in case of
70   * non-networked logins. Diagnostics are reported through syslog(3).
71   *
72   * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
73   */
74
75 #if !defined(MAXHOSTNAMELEN) || (MAXHOSTNAMELEN < 64)
76 #undef MAXHOSTNAMELEN
77 #define MAXHOSTNAMELEN 256
78 #endif
79
80 #ifdef DEFAULT_CONF_FILE
81 # define PAM_ACCESS_CONFIG DEFAULT_CONF_FILE
82 #else
83 # define PAM_ACCESS_CONFIG "/etc/security/access.conf"
84 #endif
85
86  /* Delimiters for fields and for lists of users, ttys or hosts. */
87
88 static const char *fs = ":";                    /* field separator */
89 static const char sep[] = ", \t";               /* list-element separator */
90
91  /* Constants to be used in assignments only, not in comparisons... */
92
93 #define YES             1
94 #define NO              0
95
96  /*
97   * A structure to bundle up all login-related information to keep the
98   * functional interfaces as generic as possible.
99   */
100 struct login_info {
101     struct passwd *user;
102     char   *from;
103     const char *config_file;
104     const char *service;
105 };
106
107 /* --- static functions for checking whether the user should be let in --- */
108
109 static void _log_err(const char *format, ... )
110 {
111     va_list args;
112
113     va_start(args, format);
114     openlog("pam_access", LOG_CONS|LOG_PID, LOG_AUTH);
115     vsyslog(LOG_ERR, format, args);
116     va_end(args);
117     closelog();
118 }
119
120 /* Parse module config arguments */
121
122 static int parse_args(struct login_info *loginfo, int argc, const char **argv)
123 {
124     int i;
125
126     for (i=0; i<argc; ++i) {
127         if (!strncmp("fieldsep=", argv[i], 9)) {
128
129             /* the admin wants to override the default field separators */
130             fs = argv[i]+9;
131
132         } else if (!strncmp("accessfile=", argv[i], 11)) {
133             FILE *fp = fopen(11 + argv[i], "r");
134
135             if (fp) {
136                 loginfo->config_file = 11 + argv[i];
137                 fclose(fp);
138             } else {
139                 _log_err("for service [%s] failed to open accessfile=[%s]"
140                          , loginfo->service, 11 + argv[i]);
141                 return 0;
142             }
143
144         } else {
145             _log_err("unrecognized option [%s]", argv[i]);
146         }
147     }
148
149     return 1;  /* OK */
150 }
151
152 typedef int match_func (pam_handle_t *, char *, struct login_info *);
153
154 static int list_match (pam_handle_t *, char *, struct login_info *,
155                        match_func *);
156 static int user_match (pam_handle_t *, char *, struct login_info *);
157 static int from_match (pam_handle_t *, char *, struct login_info *);
158 static int string_match (pam_handle_t *, char *, char *);
159
160 /* login_access - match username/group and host/tty with access control file */
161
162 static int
163 login_access (pam_handle_t *pamh, struct login_info *item)
164 {
165     FILE   *fp;
166     char    line[BUFSIZ];
167     char   *perm;               /* becomes permission field */
168     char   *users;              /* becomes list of login names */
169     char   *froms;              /* becomes list of terminals or hosts */
170     int     match = NO;
171     int     end;
172     int     lineno = 0;         /* for diagnostics */
173
174     /*
175      * Process the table one line at a time and stop at the first match.
176      * Blank lines and lines that begin with a '#' character are ignored.
177      * Non-comment lines are broken at the ':' character. All fields are
178      * mandatory. The first field should be a "+" or "-" character. A
179      * non-existing table means no access control.
180      */
181
182     if ((fp = fopen(item->config_file, "r"))!=NULL) {
183         while (!match && fgets(line, sizeof(line), fp)) {
184             lineno++;
185             if (line[end = strlen(line) - 1] != '\n') {
186                 _log_err("%s: line %d: missing newline or line too long",
187                        item->config_file, lineno);
188                 continue;
189             }
190             if (line[0] == '#')
191                 continue;                       /* comment line */
192             while (end > 0 && isspace(line[end - 1]))
193                 end--;
194             line[end] = 0;                      /* strip trailing whitespace */
195             if (line[0] == 0)                   /* skip blank lines */
196                 continue;
197             if (!(perm = strtok(line, fs))
198                 || !(users = strtok((char *) 0, fs))
199                 || !(froms = strtok((char *) 0, fs))
200                 || strtok((char *) 0, fs)) {
201                 _log_err("%s: line %d: bad field count",
202                          item->config_file, lineno);
203                 continue;
204             }
205             if (perm[0] != '+' && perm[0] != '-') {
206                 _log_err("%s: line %d: bad first field",
207                          item->config_file, lineno);
208                 continue;
209             }
210             match = (list_match(pamh, froms, item, from_match)
211                      && list_match(pamh, users, item, user_match));
212         }
213         (void) fclose(fp);
214     } else if (errno != ENOENT) {
215         _log_err("cannot open %s: %m", item->config_file);
216         return NO;
217     }
218     return (match == 0 || (line[0] == '+'));
219 }
220
221 /* list_match - match an item against a list of tokens with exceptions */
222
223 static int list_match(pam_handle_t *pamh,
224                       char *list, struct login_info *item, match_func *match_fn)
225 {
226     char   *tok;
227     int     match = NO;
228
229     /*
230      * Process tokens one at a time. We have exhausted all possible matches
231      * when we reach an "EXCEPT" token or the end of the list. If we do find
232      * a match, look for an "EXCEPT" list and recurse to determine whether
233      * the match is affected by any exceptions.
234      */
235
236     for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
237         if (strcasecmp(tok, "EXCEPT") == 0)     /* EXCEPT: give up */
238             break;
239         if ((match = (*match_fn) (pamh, tok, item)))    /* YES */
240             break;
241     }
242     /* Process exceptions to matches. */
243
244     if (match != NO) {
245         while ((tok = strtok((char *) 0, sep)) && strcasecmp(tok, "EXCEPT"))
246              /* VOID */ ;
247         if (tok == 0 || list_match(pamh, (char *) 0, item, match_fn) == NO)
248             return (match);
249     }
250     return (NO);
251 }
252
253 /* myhostname - figure out local machine name */
254
255 static char * myhostname(void)
256 {
257     static char name[MAXHOSTNAMELEN + 1];
258
259     if (gethostname(name, MAXHOSTNAMELEN) == 0) {
260       name[MAXHOSTNAMELEN] = 0;
261       return (name);
262     }
263     return NULL;
264 }
265
266 /* netgroup_match - match group against machine or user */
267
268 static int netgroup_match(char *group, char *machine, char *user)
269 {
270     static char *mydomain = NULL;
271
272     if (mydomain == 0)
273         yp_get_default_domain(&mydomain);
274     return (innetgr(group, machine, user, mydomain));
275 }
276
277 /* user_match - match a username against one token */
278
279 static int user_match(pam_handle_t *pamh, char *tok, struct login_info *item)
280 {
281     char   *string = item->user->pw_name;
282     struct login_info fake_item;
283     char   *at;
284
285     /*
286      * If a token has the magic value "ALL" the match always succeeds.
287      * Otherwise, return YES if the token fully matches the username, if the
288      * token is a group that contains the username, or if the token is the
289      * name of the user's primary group.
290      */
291
292     if ((at = strchr(tok + 1, '@')) != 0) {     /* split user@host pattern */
293         *at = 0;
294         fake_item.from = myhostname();
295         if (fake_item.from == NULL)
296           return NO;
297         return (user_match (pamh, tok, item) && from_match (pamh, at + 1, &fake_item));
298     } else if (tok[0] == '@') /* netgroup */
299         return (netgroup_match(tok + 1, (char *) 0, string));
300     else if (string_match (pamh, tok, string)) /* ALL or exact match */
301         return YES;
302     else if (_pammodutil_user_in_group_nam_nam (pamh, item->user->pw_name, tok))
303       /* try group membership */
304       return YES;
305
306     return NO;
307 }
308
309 /* from_match - match a host or tty against a list of tokens */
310
311 static int
312 from_match (pam_handle_t *pamh, char *tok, struct login_info *item)
313 {
314     char   *string = item->from;
315     int     tok_len;
316     int     str_len;
317
318     /*
319      * If a token has the magic value "ALL" the match always succeeds. Return
320      * YES if the token fully matches the string. If the token is a domain
321      * name, return YES if it matches the last fields of the string. If the
322      * token has the magic value "LOCAL", return YES if the string does not
323      * contain a "." character. If the token is a network number, return YES
324      * if it matches the head of the string.
325      */
326
327     if (tok[0] == '@') {                        /* netgroup */
328         return (netgroup_match(tok + 1, string, (char *) 0));
329     } else if (string_match (pamh, tok, string)) /* ALL or exact match */
330       return YES;
331     else if (tok[0] == '.') {                   /* domain: match last fields */
332         if ((str_len = strlen(string)) > (tok_len = strlen(tok))
333             && strcasecmp(tok, string + str_len - tok_len) == 0)
334             return (YES);
335     } else if (strcasecmp(tok, "LOCAL") == 0) { /* local: no dots */
336         if (strchr(string, '.') == 0)
337             return (YES);
338 #ifdef BROKEN_NETWORK_MATCH
339     } else if (tok[(tok_len = strlen(tok)) - 1] == '.'  /* network */
340                && strncmp(tok, string, tok_len) == 0) {
341         return (YES);
342 #else /*  BROKEN_NETWORK_MATCH */
343     } else if (tok[(tok_len = strlen(tok)) - 1] == '.') {
344         /*
345            The code below does a more correct check if the address specified
346            by "string" starts from "tok".
347                                1998/01/27  Andrey V. Savochkin <saw@msu.ru>
348          */
349
350         struct hostent *h;
351         char hn[3+1+3+1+3+1+3+1+1];
352         int r;
353
354         h = gethostbyname(string);
355         if (h == NULL)
356             return (NO);
357         if (h->h_addrtype != AF_INET)
358             return (NO);
359         if (h->h_length != 4)
360             return (NO); /* only IPv4 addresses (SAW) */
361         r = snprintf(hn, sizeof(hn), "%u.%u.%u.%u.",
362                      (unsigned char)h->h_addr[0], (unsigned char)h->h_addr[1],
363                      (unsigned char)h->h_addr[2], (unsigned char)h->h_addr[3]);
364         if (r < 0 || r >= sizeof(hn))
365             return (NO);
366         if (!strncmp(tok, hn, tok_len))
367             return (YES);
368 #endif /*  BROKEN_NETWORK_MATCH */
369     }
370     return (NO);
371 }
372
373 /* string_match - match a string against one token */
374
375 static int
376 string_match (pam_handle_t *pamh, char *tok, char *string)
377 {
378
379     /*
380      * If the token has the magic value "ALL" the match always succeeds.
381      * Otherwise, return YES if the token fully matches the string.
382      */
383
384     if (strcasecmp(tok, "ALL") == 0) {          /* all: always matches */
385         return (YES);
386     } else if (strcasecmp(tok, string) == 0) {  /* try exact match */
387         return (YES);
388     }
389     return (NO);
390 }
391
392 /* --- public account management functions --- */
393
394 PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh,int flags,int argc
395                      ,const char **argv)
396 {
397     struct login_info loginfo;
398     const char *user=NULL, *service=NULL;
399     char *from=NULL;
400     struct passwd *user_pw;
401
402     if ((pam_get_item(pamh, PAM_SERVICE, (const void **)&service)
403         != PAM_SUCCESS) || (service == NULL) || (*service == ' ')) {
404         _log_err("cannot find the service name");
405         return PAM_ABORT;
406     }
407
408     /* set username */
409
410     if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || user == NULL
411         || *user == '\0') {
412         _log_err("cannot determine the user's name");
413         return PAM_USER_UNKNOWN;
414     }
415
416     /* remote host name */
417
418     if (pam_get_item(pamh, PAM_RHOST, (const void **)&from)
419         != PAM_SUCCESS) {
420         _log_err("cannot find the remote host name");
421         return PAM_ABORT;
422     }
423
424     if ((from==NULL) || (*from=='\0')) {
425
426         /* local login, set tty name */
427
428         if (pam_get_item(pamh, PAM_TTY, (const void **)&from) != PAM_SUCCESS
429             || from == NULL) {
430             D(("PAM_TTY not set, probing stdin"));
431             from = ttyname(STDIN_FILENO);
432             if (from == NULL) {
433                 _log_err("couldn't get the tty name");
434                 return PAM_ABORT;
435              }
436             if (pam_set_item(pamh, PAM_TTY, from) != PAM_SUCCESS) {
437                 _log_err("couldn't set tty name");
438                 return PAM_ABORT;
439              }
440         }
441         if (strncmp("/dev/",from,5) == 0) {          /* strip leading /dev/ */
442             from += 5;
443         }
444
445     }
446
447     if ((user_pw=_pammodutil_getpwnam(pamh, user))==NULL) return (PAM_USER_UNKNOWN);
448
449     /*
450      * Bundle up the arguments to avoid unnecessary clumsiness later on.
451      */
452     loginfo.user = user_pw;
453     loginfo.from = from;
454     loginfo.service = service;
455     loginfo.config_file = PAM_ACCESS_CONFIG;
456
457     /* parse the argument list */
458
459     if (!parse_args(&loginfo, argc, argv)) {
460         _log_err("failed to parse the module arguments");
461         return PAM_ABORT;
462     }
463
464     if (login_access(pamh, &loginfo)) {
465         return (PAM_SUCCESS);
466     } else {
467         _log_err("access denied for user `%s' from `%s'",user,from);
468         return (PAM_PERM_DENIED);
469     }
470 }
471
472 /* end of module definition */
473
474 #ifdef PAM_STATIC
475
476 /* static module data */
477
478 struct pam_module _pam_access_modstruct = {
479     "pam_access",
480     NULL,
481     NULL,
482     pam_sm_acct_mgmt,
483     NULL,
484     NULL,
485     NULL
486 };
487 #endif