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