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