]> granicus.if.org Git - linux-pam/blob - modules/pam_limits/pam_limits.c
Merge branch 'master' of ssh://git.fedorahosted.org/git/linux-pam into new_version
[linux-pam] / modules / pam_limits / pam_limits.c
1 /*
2  * pam_limits - impose resource limits when opening a user session
3  *
4  * 1.6 - modified for PLD (added process priority settings)
5  *       by Marcin Korzonek <mkorz@shadow.eu.org>
6  * 1.5 - Elliot Lee's "max system logins patch"
7  * 1.4 - addressed bug in configuration file parser
8  * 1.3 - modified the configuration file format
9  * 1.2 - added 'debug' and 'conf=' arguments
10  * 1.1 - added @group support
11  * 1.0 - initial release - Linux ONLY
12  *
13  * See end for Copyright information
14  */
15
16 #if !defined(linux) && !defined(__linux)
17 #warning THIS CODE IS KNOWN TO WORK ONLY ON LINUX !!!
18 #endif
19
20 #include "config.h"
21
22 #include <stdio.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <syslog.h>
29 #include <stdarg.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/resource.h>
33 #include <limits.h>
34 #include <glob.h>
35 #include <utmp.h>
36 #ifndef UT_USER  /* some systems have ut_name instead of ut_user */
37 #define UT_USER ut_user
38 #endif
39
40 #include <grp.h>
41 #include <pwd.h>
42 #include <locale.h>
43
44 #ifdef HAVE_LIBAUDIT
45 #include <libaudit.h>
46 #endif
47
48 /* Module defines */
49 #define LINE_LENGTH 1024
50
51 #define LIMITS_DEF_USER     0 /* limit was set by an user entry */
52 #define LIMITS_DEF_GROUP    1 /* limit was set by a group entry */
53 #define LIMITS_DEF_ALLGROUP 2 /* limit was set by a group entry */
54 #define LIMITS_DEF_ALL      3 /* limit was set by an all entry */
55 #define LIMITS_DEF_DEFAULT  4 /* limit was set by a default entry */
56 #define LIMITS_DEF_KERNEL   5 /* limit was set from /proc/1/limits */
57 #define LIMITS_DEF_NONE     6 /* this limit was not set yet */
58
59 #define LIMIT_RANGE_ERR    -1 /* error in specified uid/gid range */
60 #define LIMIT_RANGE_NONE    0 /* no range specified */
61 #define LIMIT_RANGE_ONE     1 /* exact uid/gid specified (:max_uid)*/
62 #define LIMIT_RANGE_MIN     2 /* only minimum uid/gid specified (min_uid:) */
63 #define LIMIT_RANGE_MM      3 /* both min and max uid/gid specified (min_uid:max_uid) */
64
65 static const char *limits_def_names[] = {
66        "USER",
67        "GROUP",
68        "ALLGROUP",
69        "ALL",
70        "DEFAULT",
71        "KERNEL",
72        "NONE",
73        NULL
74 };
75
76 struct user_limits_struct {
77     int supported;
78     int src_soft;
79     int src_hard;
80     struct rlimit limit;
81 };
82
83 /* internal data */
84 struct pam_limit_s {
85     int login_limit;     /* the max logins limit */
86     int login_limit_def; /* which entry set the login limit */
87     int flag_numsyslogins; /* whether to limit logins only for a
88                               specific user or to count all logins */
89     int priority;        /* the priority to run user process with */
90     struct user_limits_struct limits[RLIM_NLIMITS];
91     const char *conf_file;
92     int utmp_after_pam_call;
93     char login_group[LINE_LENGTH];
94 };
95
96 #define LIMIT_LOGIN RLIM_NLIMITS+1
97 #define LIMIT_NUMSYSLOGINS RLIM_NLIMITS+2
98
99 #define LIMIT_PRI RLIM_NLIMITS+3
100
101 #define LIMIT_SOFT  1
102 #define LIMIT_HARD  2
103
104 #define PAM_SM_SESSION
105
106 #include <security/pam_modules.h>
107 #include <security/_pam_macros.h>
108 #include <security/pam_modutil.h>
109 #include <security/pam_ext.h>
110
111 /* argument parsing */
112
113 #define PAM_DEBUG_ARG       0x0001
114 #define PAM_UTMP_EARLY      0x0004
115 #define PAM_NO_AUDIT        0x0008
116 #define PAM_SET_ALL         0x0010
117
118 /* Limits from globbed files. */
119 #define LIMITS_CONF_GLOB LIMITS_FILE_DIR
120
121 #define CONF_FILE (pl->conf_file != NULL)?pl->conf_file:LIMITS_FILE
122
123 static int
124 _pam_parse (const pam_handle_t *pamh, int argc, const char **argv,
125             struct pam_limit_s *pl)
126 {
127     int ctrl=0;
128
129     /* step through arguments */
130     for (ctrl=0; argc-- > 0; ++argv) {
131
132         /* generic options */
133
134         if (!strcmp(*argv,"debug")) {
135             ctrl |= PAM_DEBUG_ARG;
136         } else if (!strncmp(*argv,"conf=",5)) {
137             pl->conf_file = *argv+5;
138         } else if (!strcmp(*argv,"utmp_early")) {
139             ctrl |= PAM_UTMP_EARLY;
140         } else if (!strcmp(*argv,"noaudit")) {
141             ctrl |= PAM_NO_AUDIT;
142         } else if (!strcmp(*argv,"set_all")) {
143             ctrl |= PAM_SET_ALL;
144         } else {
145             pam_syslog(pamh, LOG_ERR, "unknown option: %s", *argv);
146         }
147     }
148
149     return ctrl;
150 }
151
152 static const char *
153 rlimit2str (int i)
154 {
155   switch (i) {
156   case RLIMIT_CPU:
157     return "cpu";
158     break;
159   case RLIMIT_FSIZE:
160     return "fsize";
161     break;
162   case RLIMIT_DATA:
163     return "data";
164     break;
165   case RLIMIT_STACK:
166     return "stack";
167     break;
168   case RLIMIT_CORE:
169     return "core";
170     break;
171   case RLIMIT_RSS:
172     return "rss";
173     break;
174   case RLIMIT_NPROC:
175     return "nproc";
176     break;
177   case RLIMIT_NOFILE:
178     return "nofile";
179     break;
180   case RLIMIT_MEMLOCK:
181     return "memlock";
182     break;
183 #ifdef RLIMIT_AS
184   case RLIMIT_AS:
185     return "as";
186     break;
187 #endif
188 #ifdef RLIMIT_LOCKS
189   case RLIMIT_LOCKS:
190     return "locks";
191     break;
192 #endif
193 #ifdef RLIMIT_SIGPENDING
194   case RLIMIT_SIGPENDING:
195     return "sigpending";
196     break;
197 #endif
198 #ifdef RLIMIT_MSGQUEUE
199   case RLIMIT_MSGQUEUE:
200     return "msgqueue";
201     break;
202 #endif
203 #ifdef RLIMIT_NICE
204   case RLIMIT_NICE:
205     return "nice";
206     break;
207 #endif
208 #ifdef RLIMIT_RTPRIO
209   case RLIMIT_RTPRIO:
210     return "rtprio";
211     break;
212 #endif
213   default:
214     return "UNKNOWN";
215     break;
216   }
217 }
218
219
220 #define LIMITED_OK 0 /* limit setting appeared to work */
221 #define LIMIT_ERR  1 /* error setting a limit */
222 #define LOGIN_ERR  2 /* too many logins err */
223
224 /* Counts the number of user logins and check against the limit*/
225 static int
226 check_logins (pam_handle_t *pamh, const char *name, int limit, int ctrl,
227               struct pam_limit_s *pl)
228 {
229     struct utmp *ut;
230     int count;
231
232     if (ctrl & PAM_DEBUG_ARG) {
233         pam_syslog(pamh, LOG_DEBUG,
234                    "checking logins for '%s' (maximum of %d)", name, limit);
235     }
236
237     if (limit < 0)
238         return 0; /* no limits imposed */
239     if (limit == 0) /* maximum 0 logins ? */ {
240         pam_syslog(pamh, LOG_WARNING, "No logins allowed for '%s'", name);
241         return LOGIN_ERR;
242     }
243
244     setutent();
245
246     /* Because there is no definition about when an application
247        actually adds a utmp entry, some applications bizarrely do the
248        utmp call before the have PAM authenticate them to the system:
249        you're logged it, sort of...? Anyway, you can use the
250        "utmp_early" module argument in your PAM config file to make
251        allowances for this sort of problem. (There should be a PAM
252        standard for this, since if a module wants to actually map a
253        username then any early utmp entry will be for the unmapped
254        name = broken.) */
255
256     if (ctrl & PAM_UTMP_EARLY) {
257         count = 0;
258     } else {
259         count = 1;
260     }
261
262     while((ut = getutent())) {
263 #ifdef USER_PROCESS
264         if (ut->ut_type != USER_PROCESS) {
265             continue;
266         }
267 #endif
268         if (ut->UT_USER[0] == '\0') {
269             continue;
270         }
271         if (!pl->flag_numsyslogins) {
272             if (((pl->login_limit_def == LIMITS_DEF_USER)
273                  || (pl->login_limit_def == LIMITS_DEF_GROUP)
274                  || (pl->login_limit_def == LIMITS_DEF_DEFAULT))
275                 && strncmp(name, ut->UT_USER, sizeof(ut->UT_USER)) != 0) {
276                 continue;
277             }
278             if ((pl->login_limit_def == LIMITS_DEF_ALLGROUP)
279                 && !pam_modutil_user_in_group_nam_nam(pamh, ut->UT_USER, pl->login_group)) {
280                 continue;
281             }
282         }
283         if (++count > limit) {
284             break;
285         }
286     }
287     endutent();
288     if (count > limit) {
289         if (name) {
290             pam_syslog(pamh, LOG_WARNING,
291                        "Too many logins (max %d) for %s", limit, name);
292         } else {
293             pam_syslog(pamh, LOG_WARNING, "Too many system logins (max %d)", limit);
294         }
295         return LOGIN_ERR;
296     }
297     return 0;
298 }
299
300 static const char *lnames[RLIM_NLIMITS] = {
301         [RLIMIT_CPU] = "Max cpu time",
302         [RLIMIT_FSIZE] = "Max file size",
303         [RLIMIT_DATA] = "Max data size",
304         [RLIMIT_STACK] = "Max stack size",
305         [RLIMIT_CORE] = "Max core file size",
306         [RLIMIT_RSS] = "Max resident set",
307         [RLIMIT_NPROC] = "Max processes",
308         [RLIMIT_NOFILE] = "Max open files",
309         [RLIMIT_MEMLOCK] = "Max locked memory",
310 #ifdef RLIMIT_AS
311         [RLIMIT_AS] = "Max address space",
312 #endif
313 #ifdef RLIMIT_LOCKS
314         [RLIMIT_LOCKS] = "Max file locks",
315 #endif
316 #ifdef RLIMIT_SIGPENDING
317         [RLIMIT_SIGPENDING] = "Max pending signals",
318 #endif
319 #ifdef RLIMIT_MSGQUEUE
320         [RLIMIT_MSGQUEUE] = "Max msgqueue size",
321 #endif
322 #ifdef RLIMIT_NICE
323         [RLIMIT_NICE] = "Max nice priority",
324 #endif
325 #ifdef RLIMIT_RTPRIO
326         [RLIMIT_RTPRIO] = "Max realtime priority",
327 #endif
328 #ifdef RLIMIT_RTTIME
329         [RLIMIT_RTTIME] = "Max realtime timeout",
330 #endif
331 };
332
333 static int str2rlimit(char *name) {
334     int i;
335     if (!name || *name == '\0')
336         return -1;
337     for(i = 0; i < RLIM_NLIMITS; i++) {
338         if (strcmp(name, lnames[i]) == 0) return i;
339     }
340     return -1;
341 }
342
343 static rlim_t str2rlim_t(char *value) {
344     unsigned long long rlimit = 0;
345
346     if (!value) return (rlim_t)rlimit;
347     if (strcmp(value, "unlimited") == 0) {
348         return RLIM_INFINITY;
349     }
350     rlimit = strtoull(value, NULL, 10);
351     return (rlim_t)rlimit;
352 }
353
354 #define LIMITS_SKIP_WHITESPACE { \
355         /* step backwards over spaces */ \
356         pos--; \
357         while (pos && line[pos] == ' ') pos--; \
358         if (!pos) continue; \
359         line[pos+1] = '\0'; \
360 }
361 #define LIMITS_MARK_ITEM(item) { \
362         /* step backwards over non-spaces */ \
363         pos--; \
364         while (pos && line[pos] != ' ') pos--; \
365         if (!pos) continue; \
366         item = line + pos + 1; \
367 }
368
369 static void parse_kernel_limits(pam_handle_t *pamh, struct pam_limit_s *pl, int ctrl)
370 {
371     int i, maxlen = 0;
372     FILE *limitsfile;
373     const char *proclimits = "/proc/1/limits";
374     char line[256];
375     char *units, *hard, *soft, *name;
376
377     if (!(limitsfile = fopen(proclimits, "r"))) {
378         pam_syslog(pamh, LOG_WARNING, "Could not read %s (%s), using PAM defaults", proclimits, strerror(errno));
379         return;
380     }
381
382     while (fgets(line, 256, limitsfile)) {
383         int pos = strlen(line);
384         if (pos < 2) continue;
385
386         /* drop trailing newline */
387         if (line[pos-1] == '\n') {
388             pos--;
389             line[pos] = '\0';
390         }
391
392         /* determine formatting boundry of limits report */
393         if (!maxlen && strncmp(line, "Limit", 5) == 0) {
394             maxlen = pos;
395             continue;
396         }
397
398         if (pos == maxlen) {
399             /* step backwards over "Units" name */
400             LIMITS_SKIP_WHITESPACE;
401             LIMITS_MARK_ITEM(units);
402         }
403         else {
404             units = "";
405         }
406
407         /* step backwards over "Hard Limit" value */
408         LIMITS_SKIP_WHITESPACE;
409         LIMITS_MARK_ITEM(hard);
410
411         /* step backwards over "Soft Limit" value */
412         LIMITS_SKIP_WHITESPACE;
413         LIMITS_MARK_ITEM(soft);
414
415         /* step backwards over name of limit */
416         LIMITS_SKIP_WHITESPACE;
417         name = line;
418
419         i = str2rlimit(name);
420         if (i < 0 || i >= RLIM_NLIMITS) {
421             if (ctrl & PAM_DEBUG_ARG)
422                 pam_syslog(pamh, LOG_DEBUG, "Unknown kernel rlimit '%s' ignored", name);
423             continue;
424         }
425         pl->limits[i].limit.rlim_cur = str2rlim_t(soft);
426         pl->limits[i].limit.rlim_max = str2rlim_t(hard);
427         pl->limits[i].src_soft = LIMITS_DEF_KERNEL;
428         pl->limits[i].src_hard = LIMITS_DEF_KERNEL;
429     }
430     fclose(limitsfile);
431 }
432
433 static int init_limits(pam_handle_t *pamh, struct pam_limit_s *pl, int ctrl)
434 {
435     int i;
436     int retval = PAM_SUCCESS;
437
438     D(("called."));
439
440     for(i = 0; i < RLIM_NLIMITS; i++) {
441         int r = getrlimit(i, &pl->limits[i].limit);
442         if (r == -1) {
443             pl->limits[i].supported = 0;
444             if (errno != EINVAL) {
445                 retval = !PAM_SUCCESS;
446             }
447         } else {
448             pl->limits[i].supported = 1;
449             pl->limits[i].src_soft = LIMITS_DEF_NONE;
450             pl->limits[i].src_hard = LIMITS_DEF_NONE;
451         }
452     }
453
454 #ifdef __linux__
455     if (ctrl & PAM_SET_ALL) {
456       parse_kernel_limits(pamh, pl, ctrl);
457
458       for(i = 0; i < RLIM_NLIMITS; i++) {
459         if (pl->limits[i].supported &&
460             (pl->limits[i].src_soft == LIMITS_DEF_NONE ||
461              pl->limits[i].src_hard == LIMITS_DEF_NONE)) {
462           pam_syslog(pamh, LOG_WARNING, "Did not find kernel RLIMIT for %s, using PAM default", rlimit2str(i));
463         }
464       }
465     }
466 #endif
467
468     errno = 0;
469     pl->priority = getpriority (PRIO_PROCESS, 0);
470     if (pl->priority == -1 && errno != 0)
471       retval = !PAM_SUCCESS;
472     pl->login_limit = -2;
473     pl->login_limit_def = LIMITS_DEF_NONE;
474
475     return retval;
476 }
477
478 static void
479 process_limit (const pam_handle_t *pamh, int source, const char *lim_type,
480                const char *lim_item, const char *lim_value,
481                int ctrl, struct pam_limit_s *pl)
482 {
483     int limit_item;
484     int limit_type = 0;
485     int int_value = 0;
486     rlim_t rlimit_value = 0;
487     char *endptr;
488     const char *value_orig = lim_value;
489
490     if (ctrl & PAM_DEBUG_ARG)
491          pam_syslog(pamh, LOG_DEBUG, "%s: processing %s %s %s for %s",
492                     __FUNCTION__, lim_type, lim_item, lim_value,
493                     limits_def_names[source]);
494
495     if (strcmp(lim_item, "cpu") == 0)
496         limit_item = RLIMIT_CPU;
497     else if (strcmp(lim_item, "fsize") == 0)
498         limit_item = RLIMIT_FSIZE;
499     else if (strcmp(lim_item, "data") == 0)
500         limit_item = RLIMIT_DATA;
501     else if (strcmp(lim_item, "stack") == 0)
502         limit_item = RLIMIT_STACK;
503     else if (strcmp(lim_item, "core") == 0)
504         limit_item = RLIMIT_CORE;
505     else if (strcmp(lim_item, "rss") == 0)
506         limit_item = RLIMIT_RSS;
507     else if (strcmp(lim_item, "nproc") == 0)
508         limit_item = RLIMIT_NPROC;
509     else if (strcmp(lim_item, "nofile") == 0)
510         limit_item = RLIMIT_NOFILE;
511     else if (strcmp(lim_item, "memlock") == 0)
512         limit_item = RLIMIT_MEMLOCK;
513 #ifdef RLIMIT_AS
514     else if (strcmp(lim_item, "as") == 0)
515         limit_item = RLIMIT_AS;
516 #endif /*RLIMIT_AS*/
517 #ifdef RLIMIT_LOCKS
518     else if (strcmp(lim_item, "locks") == 0)
519         limit_item = RLIMIT_LOCKS;
520 #endif
521 #ifdef RLIMIT_SIGPENDING
522     else if (strcmp(lim_item, "sigpending") == 0)
523         limit_item = RLIMIT_SIGPENDING;
524 #endif
525 #ifdef RLIMIT_MSGQUEUE
526     else if (strcmp(lim_item, "msgqueue") == 0)
527         limit_item = RLIMIT_MSGQUEUE;
528 #endif
529 #ifdef RLIMIT_NICE
530     else if (strcmp(lim_item, "nice") == 0)
531         limit_item = RLIMIT_NICE;
532 #endif
533 #ifdef RLIMIT_RTPRIO
534     else if (strcmp(lim_item, "rtprio") == 0)
535         limit_item = RLIMIT_RTPRIO;
536 #endif
537     else if (strcmp(lim_item, "maxlogins") == 0) {
538         limit_item = LIMIT_LOGIN;
539         pl->flag_numsyslogins = 0;
540     } else if (strcmp(lim_item, "maxsyslogins") == 0) {
541         limit_item = LIMIT_NUMSYSLOGINS;
542         pl->flag_numsyslogins = 1;
543     } else if (strcmp(lim_item, "priority") == 0) {
544         limit_item = LIMIT_PRI;
545     } else {
546         pam_syslog(pamh, LOG_DEBUG, "unknown limit item '%s'", lim_item);
547         return;
548     }
549
550     if (strcmp(lim_type,"soft")==0)
551         limit_type=LIMIT_SOFT;
552     else if (strcmp(lim_type, "hard")==0)
553         limit_type=LIMIT_HARD;
554     else if (strcmp(lim_type,"-")==0)
555         limit_type=LIMIT_SOFT | LIMIT_HARD;
556     else if (limit_item != LIMIT_LOGIN && limit_item != LIMIT_NUMSYSLOGINS) {
557         pam_syslog(pamh, LOG_DEBUG, "unknown limit type '%s'", lim_type);
558         return;
559     }
560         if (limit_item != LIMIT_PRI
561 #ifdef RLIMIT_NICE
562             && limit_item != RLIMIT_NICE
563 #endif
564             && (strcmp(lim_value, "-1") == 0
565                 || strcmp(lim_value, "-") == 0 || strcmp(lim_value, "unlimited") == 0
566                 || strcmp(lim_value, "infinity") == 0)) {
567                 int_value = -1;
568                 rlimit_value = RLIM_INFINITY;
569         } else if (limit_item == LIMIT_PRI || limit_item == LIMIT_LOGIN ||
570 #ifdef RLIMIT_NICE
571                 limit_item == RLIMIT_NICE ||
572 #endif
573                 limit_item == LIMIT_NUMSYSLOGINS) {
574                 long temp;
575                 temp = strtol (lim_value, &endptr, 10);
576                 temp = temp < INT_MAX ? temp : INT_MAX;
577                 int_value = temp > INT_MIN ? temp : INT_MIN;
578                 if (int_value == 0 && value_orig == endptr) {
579                         pam_syslog(pamh, LOG_DEBUG,
580                                    "wrong limit value '%s' for limit type '%s'",
581                                    lim_value, lim_type);
582             return;
583                 }
584         } else {
585 #ifdef __USE_FILE_OFFSET64
586                 rlimit_value = strtoull (lim_value, &endptr, 10);
587 #else
588                 rlimit_value = strtoul (lim_value, &endptr, 10);
589 #endif
590                 if (rlimit_value == 0 && value_orig == endptr) {
591                         pam_syslog(pamh, LOG_DEBUG,
592                                    "wrong limit value '%s' for limit type '%s'",
593                                    lim_value, lim_type);
594                         return;
595                 }
596         }
597
598     /* one more special case when limiting logins */
599     if ((source == LIMITS_DEF_ALL || source == LIMITS_DEF_ALLGROUP)
600                 && (limit_item != LIMIT_LOGIN)) {
601         if (ctrl & PAM_DEBUG_ARG)
602             pam_syslog(pamh, LOG_DEBUG,
603                        "'%%' domain valid for maxlogins type only");
604         return;
605     }
606
607     switch(limit_item) {
608         case RLIMIT_CPU:
609           if (rlimit_value != RLIM_INFINITY)
610             {
611               if (rlimit_value >= RLIM_INFINITY/60)
612                 rlimit_value = RLIM_INFINITY;
613               else
614                 rlimit_value *= 60;
615             }
616          break;
617         case RLIMIT_FSIZE:
618         case RLIMIT_DATA:
619         case RLIMIT_STACK:
620         case RLIMIT_CORE:
621         case RLIMIT_RSS:
622         case RLIMIT_MEMLOCK:
623 #ifdef RLIMIT_AS
624         case RLIMIT_AS:
625 #endif
626          if (rlimit_value != RLIM_INFINITY)
627            {
628              if (rlimit_value >= RLIM_INFINITY/1024)
629                rlimit_value = RLIM_INFINITY;
630              else
631                rlimit_value *= 1024;
632            }
633          break;
634 #ifdef RLIMIT_NICE
635         case RLIMIT_NICE:
636          if (int_value > 19)
637             int_value = 19;
638          if (int_value < -20)
639            int_value = -20;
640          rlimit_value = 20 - int_value;
641          break;
642 #endif
643     }
644
645     if ( (limit_item != LIMIT_LOGIN)
646          && (limit_item != LIMIT_NUMSYSLOGINS)
647          && (limit_item != LIMIT_PRI) ) {
648         if (limit_type & LIMIT_SOFT) {
649             if (pl->limits[limit_item].src_soft < source) {
650                 return;
651             } else {
652                 pl->limits[limit_item].limit.rlim_cur = rlimit_value;
653                 pl->limits[limit_item].src_soft = source;
654             }
655         }
656         if (limit_type & LIMIT_HARD) {
657             if (pl->limits[limit_item].src_hard < source) {
658                 return;
659             } else {
660                 pl->limits[limit_item].limit.rlim_max = rlimit_value;
661                 pl->limits[limit_item].src_hard = source;
662             }
663         }
664     } else {
665         /* recent kernels support negative priority limits (=raise priority) */
666
667         if (limit_item == LIMIT_PRI) {
668                 pl->priority = int_value;
669         } else {
670                 if (pl->login_limit_def < source) {
671                     return;
672                 } else {
673                     pl->login_limit = int_value;
674                     pl->login_limit_def = source;
675                 }
676         }
677     }
678     return;
679 }
680
681 static int
682 parse_uid_range(pam_handle_t *pamh, const char *domain,
683                 uid_t *min_uid, uid_t *max_uid)
684 {
685     const char *range = domain;
686     char *pmax;
687     char *endptr;
688     int rv = LIMIT_RANGE_MM;
689
690     if ((pmax=strchr(range, ':')) == NULL)
691         return LIMIT_RANGE_NONE;
692     ++pmax;
693
694     if (range[0] == '@' || range[0] == '%')
695         ++range;
696
697     if (range[0] == ':')
698         rv = LIMIT_RANGE_ONE;
699     else {
700             errno = 0;
701             *min_uid = strtoul (range, &endptr, 10);
702             if (errno != 0 || (range == endptr) || *endptr != ':') {
703                 pam_syslog(pamh, LOG_DEBUG,
704                            "wrong min_uid/gid value in '%s'", domain);
705                 return LIMIT_RANGE_ERR;
706             }
707     }
708
709     if (*pmax == '\0') {
710         if (rv == LIMIT_RANGE_ONE)
711             return LIMIT_RANGE_ERR;
712         else
713             return LIMIT_RANGE_MIN;
714     }
715
716     errno = 0;
717     *max_uid = strtoul (pmax, &endptr, 10);
718     if (errno != 0 || (pmax == endptr) || *endptr != '\0') {
719         pam_syslog(pamh, LOG_DEBUG,
720                    "wrong max_uid/gid value in '%s'", domain);
721         return LIMIT_RANGE_ERR;
722     }
723
724     if (rv == LIMIT_RANGE_ONE)
725         *min_uid = *max_uid;
726     return rv;
727 }
728
729 static int
730 parse_config_file(pam_handle_t *pamh, const char *uname, uid_t uid, gid_t gid,
731                              int ctrl, struct pam_limit_s *pl)
732 {
733     FILE *fil;
734     char buf[LINE_LENGTH];
735
736     /* check for the LIMITS_FILE */
737     if (ctrl & PAM_DEBUG_ARG)
738         pam_syslog(pamh, LOG_DEBUG, "reading settings from '%s'", CONF_FILE);
739     fil = fopen(CONF_FILE, "r");
740     if (fil == NULL) {
741         pam_syslog (pamh, LOG_WARNING,
742                     "cannot read settings from %s: %m", CONF_FILE);
743         return PAM_SERVICE_ERR;
744     }
745
746     /* start the show */
747     while (fgets(buf, LINE_LENGTH, fil) != NULL) {
748         char domain[LINE_LENGTH];
749         char ltype[LINE_LENGTH];
750         char item[LINE_LENGTH];
751         char value[LINE_LENGTH];
752         int i;
753         int rngtype;
754         size_t j;
755         char *tptr,*line;
756         uid_t min_uid = (uid_t)-1, max_uid = (uid_t)-1;
757
758         line = buf;
759         /* skip the leading white space */
760         while (*line && isspace(*line))
761             line++;
762
763         /* Rip off the comments */
764         tptr = strchr(line,'#');
765         if (tptr)
766             *tptr = '\0';
767         /* Rip off the newline char */
768         tptr = strchr(line,'\n');
769         if (tptr)
770             *tptr = '\0';
771         /* Anything left ? */
772         if (!strlen(line))
773             continue;
774
775         domain[0] = ltype[0] = item[0] = value[0] = '\0';
776
777         i = sscanf(line,"%s%s%s%s", domain, ltype, item, value);
778         D(("scanned line[%d]: domain[%s], ltype[%s], item[%s], value[%s]",
779            i, domain, ltype, item, value));
780
781         for(j=0; j < strlen(ltype); j++)
782             ltype[j]=tolower(ltype[j]);
783
784         if ((rngtype=parse_uid_range(pamh, domain, &min_uid, &max_uid)) < 0) {
785             pam_syslog(pamh, LOG_WARNING, "invalid uid range '%s' - skipped", domain);
786             continue;
787         }
788
789         if (i == 4) { /* a complete line */
790             for(j=0; j < strlen(item); j++)
791                 item[j]=tolower(item[j]);
792             for(j=0; j < strlen(value); j++)
793                 value[j]=tolower(value[j]);
794
795             if (strcmp(uname, domain) == 0) /* this user have a limit */
796                 process_limit(pamh, LIMITS_DEF_USER, ltype, item, value, ctrl, pl);
797             else if (domain[0]=='@') {
798                 if (ctrl & PAM_DEBUG_ARG) {
799                         pam_syslog(pamh, LOG_DEBUG,
800                                    "checking if %s is in group %s",
801                                    uname, domain + 1);
802                 }
803                 switch(rngtype) {
804                     case LIMIT_RANGE_NONE:
805                         if (pam_modutil_user_in_group_nam_nam(pamh, uname, domain+1))
806                             process_limit(pamh, LIMITS_DEF_GROUP, ltype, item, value, ctrl,
807                                           pl);
808                         break;
809                     case LIMIT_RANGE_ONE:
810                         if (pam_modutil_user_in_group_nam_gid(pamh, uname, (gid_t)max_uid))
811                             process_limit(pamh, LIMITS_DEF_GROUP, ltype, item, value, ctrl,
812                                   pl);
813                         break;
814                     case LIMIT_RANGE_MM:
815                         if (gid > (gid_t)max_uid)
816                             break;
817                         /* fallthrough */
818                     case LIMIT_RANGE_MIN:
819                         if (gid >= (gid_t)min_uid)
820                             process_limit(pamh, LIMITS_DEF_GROUP, ltype, item, value, ctrl,
821                                           pl);
822                 }
823             } else if (domain[0]=='%') {
824                 if (ctrl & PAM_DEBUG_ARG) {
825                         pam_syslog(pamh, LOG_DEBUG,
826                                    "checking if %s is in group %s",
827                                    uname, domain + 1);
828                 }
829                 switch(rngtype) {
830                     case LIMIT_RANGE_NONE:
831                         if (strcmp(domain,"%") == 0)
832                             process_limit(pamh, LIMITS_DEF_ALL, ltype, item, value, ctrl,
833                                           pl);
834                         else if (pam_modutil_user_in_group_nam_nam(pamh, uname, domain+1)) {
835                             strcpy(pl->login_group, domain+1);
836                             process_limit(pamh, LIMITS_DEF_ALLGROUP, ltype, item, value, ctrl,
837                                           pl);
838                         }
839                         break;
840                     case LIMIT_RANGE_ONE:
841                         if (pam_modutil_user_in_group_nam_gid(pamh, uname, (gid_t)max_uid)) {
842                             struct group *grp;
843                             grp = pam_modutil_getgrgid(pamh, (gid_t)max_uid);
844                             strncpy(pl->login_group, grp->gr_name, sizeof(pl->login_group));
845                             pl->login_group[sizeof(pl->login_group)-1] = '\0';
846                             process_limit(pamh, LIMITS_DEF_ALLGROUP, ltype, item, value, ctrl,
847                                           pl);
848                         }
849                         break;
850                     case LIMIT_RANGE_MIN:
851                     case LIMIT_RANGE_MM:
852                         pam_syslog(pamh, LOG_WARNING, "range unsupported for %%group matching - ignored");
853                 }
854             } else {
855                 switch(rngtype) {
856                     case LIMIT_RANGE_NONE:
857                         if (strcmp(domain, "*") == 0)
858                             process_limit(pamh, LIMITS_DEF_DEFAULT, ltype, item, value, ctrl,
859                                           pl);
860                         break;
861                     case LIMIT_RANGE_ONE:
862                         if (uid != max_uid)
863                             break;
864                         /* fallthrough */
865                     case LIMIT_RANGE_MM:
866                         if (uid > max_uid)
867                             break;
868                         /* fallthrough */
869                     case LIMIT_RANGE_MIN:
870                         if (uid >= min_uid)
871                             process_limit(pamh, LIMITS_DEF_USER, ltype, item, value, ctrl, pl);
872                 }
873             }
874         } else if (i == 2 && ltype[0] == '-') { /* Probably a no-limit line */
875             if (strcmp(uname, domain) == 0) {
876                 if (ctrl & PAM_DEBUG_ARG) {
877                     pam_syslog(pamh, LOG_DEBUG, "no limits for '%s'", uname);
878                 }
879             } else if (domain[0] == '@') {
880                 switch(rngtype) {
881                     case LIMIT_RANGE_NONE:
882                         if (!pam_modutil_user_in_group_nam_nam(pamh, uname, domain+1))
883                             continue; /* next line */
884                         break;
885                     case LIMIT_RANGE_ONE:
886                         if (!pam_modutil_user_in_group_nam_gid(pamh, uname, (gid_t)max_uid))
887                             continue; /* next line */
888                         break;
889                     case LIMIT_RANGE_MM:
890                         if (gid > (gid_t)max_uid)
891                             continue;  /* next line */
892                         /* fallthrough */
893                     case LIMIT_RANGE_MIN:
894                         if (gid < (gid_t)min_uid)
895                             continue;  /* next line */
896                 }
897                 if (ctrl & PAM_DEBUG_ARG) {
898                     pam_syslog(pamh, LOG_DEBUG,
899                                "no limits for '%s' in group '%s'",
900                                uname, domain+1);
901                 }
902             } else {
903                 switch(rngtype) {
904                     case LIMIT_RANGE_NONE:
905                         continue;  /* next line */
906                     case LIMIT_RANGE_ONE:
907                         if (uid != max_uid)
908                             continue;  /* next line */
909                         break;
910                     case LIMIT_RANGE_MM:
911                         if (uid > max_uid)
912                             continue;  /* next line */
913                         /* fallthrough */
914                     case LIMIT_RANGE_MIN:
915                         if (uid >= min_uid)
916                             break;
917                         continue;  /* next line */
918                 }
919                 if (ctrl & PAM_DEBUG_ARG) {
920                     pam_syslog(pamh, LOG_DEBUG, "no limits for '%s'", uname);
921                 }
922             }
923             fclose(fil);
924             return PAM_IGNORE;
925         } else {
926             pam_syslog(pamh, LOG_WARNING, "invalid line '%s' - skipped", line);
927         }
928     }
929     fclose(fil);
930     return PAM_SUCCESS;
931 }
932
933 static int setup_limits(pam_handle_t *pamh,
934                         const char *uname, uid_t uid, int ctrl,
935                         struct pam_limit_s *pl)
936 {
937     int i;
938     int status;
939     int retval = LIMITED_OK;
940
941     for (i=0, status=LIMITED_OK; i<RLIM_NLIMITS; i++) {
942       int res;
943
944         if (!pl->limits[i].supported) {
945             /* skip it if its not known to the system */
946             continue;
947         }
948         if (pl->limits[i].src_soft == LIMITS_DEF_NONE &&
949             pl->limits[i].src_hard == LIMITS_DEF_NONE) {
950             /* skip it if its not initialized */
951             continue;
952         }
953         if (pl->limits[i].limit.rlim_cur > pl->limits[i].limit.rlim_max)
954             pl->limits[i].limit.rlim_cur = pl->limits[i].limit.rlim_max;
955         res = setrlimit(i, &pl->limits[i].limit);
956         if (res != 0)
957           pam_syslog(pamh, LOG_ERR, "Could not set limit for '%s': %m",
958                      rlimit2str(i));
959         status |= res;
960     }
961
962     if (status) {
963         retval = LIMIT_ERR;
964     }
965
966     status = setpriority(PRIO_PROCESS, 0, pl->priority);
967     if (status != 0) {
968         pam_syslog(pamh, LOG_ERR, "Could not set limit for PRIO_PROCESS: %m");
969         retval = LIMIT_ERR;
970     }
971
972     if (uid == 0) {
973         D(("skip login limit check for uid=0"));
974     } else if (pl->login_limit > 0) {
975         if (check_logins(pamh, uname, pl->login_limit, ctrl, pl) == LOGIN_ERR) {
976 #ifdef HAVE_LIBAUDIT
977             if (!(ctrl & PAM_NO_AUDIT)) {
978                 pam_modutil_audit_write(pamh, AUDIT_ANOM_LOGIN_SESSIONS,
979                     "pam_limits", PAM_PERM_DENIED);
980                 /* ignore return value as we fail anyway */
981             }
982 #endif
983             retval |= LOGIN_ERR;
984         }
985     } else if (pl->login_limit == 0) {
986         retval |= LOGIN_ERR;
987     }
988
989     return retval;
990 }
991
992 /* now the session stuff */
993 PAM_EXTERN int
994 pam_sm_open_session (pam_handle_t *pamh, int flags UNUSED,
995                      int argc, const char **argv)
996 {
997     int retval;
998     int i;
999     int glob_rc;
1000     char *user_name;
1001     struct passwd *pwd;
1002     int ctrl;
1003     struct pam_limit_s plstruct;
1004     struct pam_limit_s *pl = &plstruct;
1005     glob_t globbuf;
1006     const char *oldlocale;
1007
1008     D(("called."));
1009
1010     memset(pl, 0, sizeof(*pl));
1011     memset(&globbuf, 0, sizeof(globbuf));
1012
1013     ctrl = _pam_parse(pamh, argc, argv, pl);
1014     retval = pam_get_item( pamh, PAM_USER, (void*) &user_name );
1015     if ( user_name == NULL || retval != PAM_SUCCESS ) {
1016         pam_syslog(pamh, LOG_CRIT, "open_session - error recovering username");
1017         return PAM_SESSION_ERR;
1018      }
1019
1020     pwd = pam_modutil_getpwnam(pamh, user_name);
1021     if (!pwd) {
1022         if (ctrl & PAM_DEBUG_ARG)
1023             pam_syslog(pamh, LOG_WARNING,
1024                        "open_session username '%s' does not exist", user_name);
1025         return PAM_USER_UNKNOWN;
1026     }
1027
1028     retval = init_limits(pamh, pl, ctrl);
1029     if (retval != PAM_SUCCESS) {
1030         pam_syslog(pamh, LOG_WARNING, "cannot initialize");
1031         return PAM_ABORT;
1032     }
1033
1034     retval = parse_config_file(pamh, pwd->pw_name, pwd->pw_uid, pwd->pw_gid, ctrl, pl);
1035     if (retval == PAM_IGNORE) {
1036         D(("the configuration file ('%s') has an applicable '<domain> -' entry", CONF_FILE));
1037         return PAM_SUCCESS;
1038     }
1039     if (retval != PAM_SUCCESS || pl->conf_file != NULL)
1040         /* skip reading limits.d if config file explicitely specified */
1041         goto out;
1042
1043     /* Read subsequent *.conf files, if they exist. */
1044
1045     /* set the LC_COLLATE so the sorting order doesn't depend
1046         on system locale */
1047
1048     oldlocale = setlocale(LC_COLLATE, "C");
1049     glob_rc = glob(LIMITS_CONF_GLOB, GLOB_ERR, NULL, &globbuf);
1050
1051     if (oldlocale != NULL)
1052         setlocale (LC_COLLATE, oldlocale);
1053
1054     if (!glob_rc) {
1055         /* Parse the *.conf files. */
1056         for (i = 0; globbuf.gl_pathv[i] != NULL; i++) {
1057             pl->conf_file = globbuf.gl_pathv[i];
1058             retval = parse_config_file(pamh, pwd->pw_name, pwd->pw_uid, pwd->pw_gid, ctrl, pl);
1059             if (retval == PAM_IGNORE) {
1060                 D(("the configuration file ('%s') has an applicable '<domain> -' entry", pl->conf_file));
1061                 globfree(&globbuf);
1062                 return PAM_SUCCESS;
1063             }
1064             if (retval != PAM_SUCCESS)
1065                 goto out;
1066         }
1067     }
1068
1069 out:
1070     globfree(&globbuf);
1071     if (retval != PAM_SUCCESS)
1072     {
1073         pam_syslog(pamh, LOG_WARNING, "error parsing the configuration file: '%s' ",CONF_FILE);
1074         return retval;
1075     }
1076
1077     retval = setup_limits(pamh, pwd->pw_name, pwd->pw_uid, ctrl, pl);
1078     if (retval & LOGIN_ERR)
1079         pam_error(pamh, _("Too many logins for '%s'."), pwd->pw_name);
1080     if (retval != LIMITED_OK) {
1081         return PAM_PERM_DENIED;
1082     }
1083
1084     return PAM_SUCCESS;
1085 }
1086
1087 PAM_EXTERN int
1088 pam_sm_close_session (pam_handle_t *pamh UNUSED, int flags UNUSED,
1089                       int argc UNUSED, const char **argv UNUSED)
1090 {
1091      /* nothing to do */
1092      return PAM_SUCCESS;
1093 }
1094
1095 #ifdef PAM_STATIC
1096
1097 /* static module data */
1098
1099 struct pam_module _pam_limits_modstruct = {
1100      "pam_limits",
1101      NULL,
1102      NULL,
1103      NULL,
1104      pam_sm_open_session,
1105      pam_sm_close_session,
1106      NULL
1107 };
1108 #endif
1109
1110 /*
1111  * Copyright (c) Cristian Gafton, 1996-1997, <gafton@redhat.com>
1112  *                                              All rights reserved.
1113  *
1114  * Redistribution and use in source and binary forms, with or without
1115  * modification, are permitted provided that the following conditions
1116  * are met:
1117  * 1. Redistributions of source code must retain the above copyright
1118  *    notice, and the entire permission notice in its entirety,
1119  *    including the disclaimer of warranties.
1120  * 2. Redistributions in binary form must reproduce the above copyright
1121  *    notice, this list of conditions and the following disclaimer in the
1122  *    documentation and/or other materials provided with the distribution.
1123  * 3. The name of the author may not be used to endorse or promote
1124  *    products derived from this software without specific prior
1125  *    written permission.
1126  *
1127  * ALTERNATIVELY, this product may be distributed under the terms of
1128  * the GNU Public License, in which case the provisions of the GPL are
1129  * required INSTEAD OF the above restrictions.  (This clause is
1130  * necessary due to a potential bad interaction between the GPL and
1131  * the restrictions contained in a BSD-style copyright.)
1132  *
1133  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
1134  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1135  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1136  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
1137  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1138  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1139  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1140  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
1141  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
1142  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
1143  * OF THE POSSIBILITY OF SUCH DAMAGE.
1144  */