]> granicus.if.org Git - linux-pam/blob - modules/pam_access/pam_access.c
Relevant BUGIDs: 415423
[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
45 #ifndef BROKEN_NETWORK_MATCH
46 # include <netdb.h>
47 # include <sys/socket.h>
48 #endif
49
50 /*
51  * here, we make definitions for the externally accessible functions
52  * in this file (these definitions are required for static modules
53  * but strongly encouraged generally) they are used to instruct the
54  * modules include file to define their prototypes.
55  */
56
57 #define PAM_SM_ACCOUNT
58
59 #include <security/_pam_macros.h>
60 #include <security/pam_modules.h>
61
62 int strcasecmp(const char *s1, const char *s2);
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 (char *, struct login_info *); 
153
154 static int list_match (char *, struct login_info *,
155                              match_func *);
156 static int user_match (char *, struct login_info *);
157 static int from_match (char *, struct login_info *);
158 static int string_match (char *, char *);
159
160 /* login_access - match username/group and host/tty with access control file */
161
162 static int login_access(struct login_info *item)
163 {
164     FILE   *fp;
165     char    line[BUFSIZ];
166     char   *perm;               /* becomes permission field */
167     char   *users;              /* becomes list of login names */
168     char   *froms;              /* becomes list of terminals or hosts */
169     int     match = NO;
170     int     end;
171     int     lineno = 0;         /* for diagnostics */
172
173     /*
174      * Process the table one line at a time and stop at the first match.
175      * Blank lines and lines that begin with a '#' character are ignored.
176      * Non-comment lines are broken at the ':' character. All fields are
177      * mandatory. The first field should be a "+" or "-" character. A
178      * non-existing table means no access control.
179      */
180
181     if ((fp = fopen(item->config_file, "r"))!=NULL) {
182         while (!match && fgets(line, sizeof(line), fp)) {
183             lineno++;
184             if (line[end = strlen(line) - 1] != '\n') {
185                 _log_err("%s: line %d: missing newline or line too long",
186                        item->config_file, lineno);
187                 continue;
188             }
189             if (line[0] == '#')
190                 continue;                       /* comment line */
191             while (end > 0 && isspace(line[end - 1]))
192                 end--;
193             line[end] = 0;                      /* strip trailing whitespace */
194             if (line[0] == 0)                   /* skip blank lines */
195                 continue;
196             if (!(perm = strtok(line, fs))
197                 || !(users = strtok((char *) 0, fs))
198                 || !(froms = strtok((char *) 0, fs))
199                 || strtok((char *) 0, fs)) {
200                 _log_err("%s: line %d: bad field count",
201                          item->config_file, lineno);
202                 continue;
203             }
204             if (perm[0] != '+' && perm[0] != '-') {
205                 _log_err("%s: line %d: bad first field",
206                          item->config_file, lineno);
207                 continue;
208             }
209             match = (list_match(froms, item, from_match)
210                      && list_match(users, item, user_match));
211         }
212         (void) fclose(fp);
213     } else if (errno != ENOENT) {
214         _log_err("cannot open %s: %m", item->config_file);
215     }
216     return (match == 0 || (line[0] == '+'));
217 }
218
219 /* list_match - match an item against a list of tokens with exceptions */
220
221 static int list_match(char *list, struct login_info *item, match_func *match_fn)
222 {
223     char   *tok;
224     int     match = NO;
225
226     /*
227      * Process tokens one at a time. We have exhausted all possible matches
228      * when we reach an "EXCEPT" token or the end of the list. If we do find
229      * a match, look for an "EXCEPT" list and recurse to determine whether
230      * the match is affected by any exceptions.
231      */
232
233     for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
234         if (strcasecmp(tok, "EXCEPT") == 0)     /* EXCEPT: give up */
235             break;
236         if ((match = (*match_fn) (tok, item)))  /* YES */
237             break;
238     }
239     /* Process exceptions to matches. */
240
241     if (match != NO) {
242         while ((tok = strtok((char *) 0, sep)) && strcasecmp(tok, "EXCEPT"))
243              /* VOID */ ;
244         if (tok == 0 || list_match((char *) 0, item, match_fn) == NO)
245             return (match);
246     }
247     return (NO);
248 }
249
250 /* myhostname - figure out local machine name */
251
252 static char * myhostname(void)
253 {
254     static char name[MAXHOSTNAMELEN + 1];
255
256     gethostname(name, MAXHOSTNAMELEN);
257     name[MAXHOSTNAMELEN] = 0;
258     return (name);
259 }
260
261 /* netgroup_match - match group against machine or user */
262
263 static int netgroup_match(char *group, char *machine, char *user)
264 {
265 #ifdef NIS
266     static char *mydomain = 0;
267
268     if (mydomain == 0)
269         yp_get_default_domain(&mydomain);
270     return (innetgr(group, machine, user, mydomain));
271 #else
272     _log_err("NIS netgroup support not configured");
273     return (NO);
274 #endif
275 }
276
277 /* user_match - match a username against one token */
278
279 static int user_match(char *tok, struct login_info *item)
280 {
281     char   *string = item->user->pw_name;
282     struct login_info fake_item;
283     struct group *group;
284     int     i;
285     char   *at;
286
287     /*
288      * If a token has the magic value "ALL" the match always succeeds.
289      * Otherwise, return YES if the token fully matches the username, if the
290      * token is a group that contains the username, or if the token is the
291      * name of the user's primary group.
292      */
293
294     if ((at = strchr(tok + 1, '@')) != 0) {     /* split user@host pattern */
295         *at = 0;
296         fake_item.from = myhostname();
297         return (user_match(tok, item) && from_match(at + 1, &fake_item));
298     } else if (tok[0] == '@') {                 /* netgroup */
299         return (netgroup_match(tok + 1, (char *) 0, string));
300     } else if (string_match(tok, string)) {     /* ALL or exact match */
301         return (YES);
302     } else if ((group = getgrnam(tok))) {       /* try group membership */
303         if (item->user->pw_gid == group->gr_gid)
304             return (YES);
305         for (i = 0; group->gr_mem[i]; i++)
306             if (strcasecmp(string, group->gr_mem[i]) == 0)
307                 return (YES);
308     }
309     return (NO);
310 }
311
312 /* from_match - match a host or tty against a list of tokens */
313
314 static int from_match(char *tok, struct login_info *item)
315 {
316     char   *string = item->from;
317     int     tok_len;
318     int     str_len;
319
320     /*
321      * If a token has the magic value "ALL" the match always succeeds. Return
322      * YES if the token fully matches the string. If the token is a domain
323      * name, return YES if it matches the last fields of the string. If the
324      * token has the magic value "LOCAL", return YES if the string does not
325      * contain a "." character. If the token is a network number, return YES
326      * if it matches the head of the string.
327      */
328
329     if (tok[0] == '@') {                        /* netgroup */
330         return (netgroup_match(tok + 1, string, (char *) 0));
331     } else if (string_match(tok, string)) {     /* ALL or exact match */
332         return (YES);
333     } else if (tok[0] == '.') {                 /* domain: match last fields */
334         if ((str_len = strlen(string)) > (tok_len = strlen(tok))
335             && strcasecmp(tok, string + str_len - tok_len) == 0)
336             return (YES);
337     } else if (strcasecmp(tok, "LOCAL") == 0) { /* local: no dots */
338         if (strchr(string, '.') == 0)
339             return (YES);
340 #ifdef BROKEN_NETWORK_MATCH
341     } else if (tok[(tok_len = strlen(tok)) - 1] == '.'  /* network */
342                && strncmp(tok, string, tok_len) == 0) {
343         return (YES);
344 #else /*  BROKEN_NETWORK_MATCH */
345     } else if (tok[(tok_len = strlen(tok)) - 1] == '.') {
346         /*
347            The code below does a more correct check if the address specified
348            by "string" starts from "tok".
349                                1998/01/27  Andrey V. Savochkin <saw@msu.ru>
350          */
351
352         struct hostent *h;
353         char hn[3+1+3+1+3+1+3+1+1];
354         int r;
355
356         h = gethostbyname(string);
357         if (h == NULL)
358             return (NO);
359         if (h->h_addrtype != AF_INET)
360             return (NO);
361         if (h->h_length != 4)
362             return (NO); /* only IPv4 addresses (SAW) */
363         r = snprintf(hn, sizeof(hn), "%u.%u.%u.%u.",
364                      (unsigned char)h->h_addr[0], (unsigned char)h->h_addr[1],
365                      (unsigned char)h->h_addr[2], (unsigned char)h->h_addr[3]);
366         if (r < 0 || r >= sizeof(hn))
367             return (NO);
368         if (!strncmp(tok, hn, tok_len))
369             return (YES);
370 #endif /*  BROKEN_NETWORK_MATCH */
371     }
372     return (NO);
373 }
374
375 /* string_match - match a string against one token */
376
377 static int string_match(char *tok, char *string)
378 {
379
380     /*
381      * If the token has the magic value "ALL" the match always succeeds.
382      * Otherwise, return YES if the token fully matches the string.
383      */
384
385     if (strcasecmp(tok, "ALL") == 0) {          /* all: always matches */
386         return (YES);
387     } else if (strcasecmp(tok, string) == 0) {  /* try exact match */
388         return (YES);
389     }
390     return (NO);
391 }
392
393 /* end of login_access.c */
394
395 int strcasecmp(const char *s1, const char *s2) 
396 {
397     while ((toupper(*s1)==toupper(*s2)) && (*s1) && (*s2)) {s1++; s2++;}
398     return(toupper(*s1)-toupper(*s2));
399 }
400
401 /* --- public account management functions --- */
402
403 PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh,int flags,int argc
404                      ,const char **argv)
405 {
406     struct login_info loginfo;
407     const char *user=NULL, *service=NULL;
408     char *from=NULL;
409     struct passwd *user_pw;
410
411     if ((pam_get_item(pamh, PAM_SERVICE, (const void **)&service)
412         != PAM_SUCCESS) || (service == NULL) || (*service == ' ')) {
413         _log_err("cannot find the service name");
414         return PAM_ABORT;
415     }
416
417     /* set username */
418
419     if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || user == NULL
420         || *user == '\0') {
421         _log_err("cannot determine the user's name");
422         return PAM_USER_UNKNOWN;
423     }
424
425     /* remote host name */
426
427     if (pam_get_item(pamh, PAM_RHOST, (const void **)&from)
428         != PAM_SUCCESS) {
429         _log_err("cannot find the remote host name");
430         return PAM_ABORT;
431     }
432
433     if ((from==NULL) || (*from=='\0')) {
434
435         /* local login, set tty name */
436
437         if (pam_get_item(pamh, PAM_TTY, (const void **)&from) != PAM_SUCCESS
438             || from == NULL) {
439             D(("PAM_TTY not set, probing stdin"));
440             from = ttyname(STDIN_FILENO);
441             if (from == NULL) {
442                 _log_err("couldn't get the tty name");
443                 return PAM_ABORT;
444              }
445             if (pam_set_item(pamh, PAM_TTY, from) != PAM_SUCCESS) {
446                 _log_err("couldn't set tty name");
447                 return PAM_ABORT;
448              }
449         }
450         if (strncmp("/dev/",from,5) == 0) {          /* strip leading /dev/ */
451             from += 5;
452         }
453
454     }
455
456     if ((user_pw=getpwnam(user))==NULL) return (PAM_USER_UNKNOWN);
457
458     /*
459      * Bundle up the arguments to avoid unnecessary clumsiness later on.
460      */
461     loginfo.user = user_pw;
462     loginfo.from = from;
463     loginfo.service = service;
464     loginfo.config_file = PAM_ACCESS_CONFIG;
465
466     /* parse the argument list */
467
468     if (!parse_args(&loginfo, argc, argv)) {
469         _log_err("failed to parse the module arguments");
470         return PAM_ABORT;
471     }
472
473     if (login_access(&loginfo)) {
474         return (PAM_SUCCESS);
475     } else {
476         _log_err("access denied for user `%s' from `%s'",user,from);
477         return (PAM_PERM_DENIED);
478     }
479 }
480
481 /* end of module definition */
482
483 #ifdef PAM_STATIC
484
485 /* static module data */
486
487 struct pam_module _pam_access_modstruct = {
488     "pam_access",
489     NULL,
490     NULL,
491     pam_sm_acct_mgmt,
492     NULL,
493     NULL,
494     NULL
495 };
496 #endif
497