chiark / gitweb /
Makefile.am: Tweak `silent-rules' machinery.
[yaid] / policy.c
1 /* -*-c-*-
2  *
3  * Policy parsing and implementation
4  *
5  * (c) 2012 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Yet Another Ident Daemon (YAID).
11  *
12  * YAID is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * YAID is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with YAID; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "yaid.h"
30
31 /*----- Memory management -------------------------------------------------*/
32
33 /* Initialize a policy structure.  In this state, it doesn't actually have
34  * any resources allocated (so can be simply discarded) but it's safe to free
35  * (using `free_policy').
36  */
37 void init_policy(struct policy *p) { p->act.act = A_LIMIT; }
38
39 /* Free an action structure, resetting it to a safe state.  This function is
40  * idempotent.
41  */
42 static void free_action(struct action *a)
43 {
44   switch (a->act) {
45     case A_LIE:
46       xfree(a->u.lie);
47       break;
48   }
49   a->act = A_LIMIT;
50 }
51
52 /* Free a policy structure, resetting it to its freshly-initialized state.
53  * This function is idempotent.
54  */
55 void free_policy(struct policy *p)
56   { free_action(&p->act); }
57
58 /*----- Diagnostics -------------------------------------------------------*/
59
60 static void print_addrpat(const struct addrops *ao, const struct addrpat *ap)
61 {
62   char buf[ADDRLEN];
63
64   if (ap->len == 0)
65     putchar('*');
66   else {
67     printf("%s/%u",
68            inet_ntop(ao->af, &ap->addr, buf, sizeof(buf)),
69            ap->len);
70   }
71 }
72
73 static void print_portpat(const struct portpat *pp)
74 {
75   if (pp->lo == 0 && pp->hi == 65535) putchar('*');
76   else if (pp->lo == pp->hi) printf("%u", pp->lo);
77   else printf("%u-%u", pp->lo, pp->hi);
78 }
79
80 static void print_sockpat(const struct addrops *ao, const struct sockpat *sp)
81   { print_addrpat(ao, &sp->addr); putchar(' '); print_portpat(&sp->port); }
82
83 static void print_userpat(const struct userpat *up)
84 {
85   if (up->lo == up->hi) printf("%d", up->lo);
86   else printf("%u-%u", up->lo, up->hi);
87 }
88
89 static const char *const acttab[] = {
90 #define DEFACT(tag, name) name,
91   ACTIONS(DEFACT)
92 #undef DEFACT
93   0
94 };
95
96 static void print_action(const struct action *act)
97 {
98   assert(act->act < A_LIMIT);
99   printf("%s", acttab[act->act]);
100   switch (act->act) {
101     case A_USER: {
102       int i;
103       unsigned m;
104       for (i = 0, m = 1; i < A_LIMIT; i++, m <<= 1)
105         if (act->u.user & m) printf(" %s", acttab[i]);
106     } break;
107     case A_LIE:
108       printf(" %s", act->u.lie);
109       break;
110   }
111 }
112
113 /* Print a policy rule to standard output. */
114 void print_policy(const struct policy *p)
115 {
116   print_sockpat(p->ao, &p->sp[L]); putchar(' ');
117   print_sockpat(p->ao, &p->sp[R]); putchar(' ');
118   print_userpat(&p->up); putchar(' ');
119   print_action(&p->act); putchar('\n');
120 }
121
122 /*----- Matching ----------------------------------------------------------*/
123
124 /* Return true if the port matches the pattern. */
125 static int match_portpat(const struct portpat *pp, unsigned port)
126   { return (pp->lo <= port && port <= pp->hi); }
127
128 /* Return true if the socket matches the pattern. */
129 static int match_sockpat(const struct addrops *ao,
130                          const struct sockpat *sp, const struct socket *s)
131 {
132   return (ao->match_addrpat(&sp->addr, &s->addr) &&
133           match_portpat(&sp->port, s->port));
134 }
135
136 /* Return true if the uid matches the pattern. */
137 static int match_userpat(const struct userpat *up, uid_t u)
138   { unsigned uu = u; return (up->lo <= uu && uu <= up->hi); }
139
140 /* Return true if the query matches the patterns in the policy rule. */
141 int match_policy(const struct policy *p, const struct query *q)
142 {
143   return ((!p->ao || p->ao == q->ao) &&
144           match_sockpat(q->ao, &p->sp[L], &q->s[L]) &&
145           match_sockpat(q->ao, &p->sp[R], &q->s[R]) &&
146           match_userpat(&p->up, q->u.uid));
147 }
148
149 /*----- Parsing -----------------------------------------------------------*/
150
151 /* Advance FP to the next line. */
152 static void nextline(FILE *fp)
153 {
154   for (;;) {
155     int ch = getc(fp);
156     if (ch == '\n' || ch == EOF) break;
157   }
158 }
159
160 /* Scan a whitespace-separated token from FP, writing it to BUF.  The token
161  * must fit in a buffer of size SZ, including a terminating null.  Return
162  * an appropriate T_* error code.
163  */
164 static int scan(FILE *fp, char *buf, size_t sz)
165 {
166   int ch;
167
168 skip_ws:
169   /* Before we start grabbing a token proper, find out what's in store. */
170   ch = getc(fp);
171   switch (ch) {
172
173     case '\n':
174     newline:
175       /* Found a newline.  Leave it where it is and report it. */
176       ungetc(ch, fp);
177       return (T_EOL);
178
179     case EOF:
180     eof:
181       /* Found end-of-file, or an I/O error.  Return an appropriate code. */
182       return (ferror(fp) ? T_ERROR : T_EOF);
183
184     case '#':
185       /* Found a comment.  Consume it, and continue appropriately: it must
186        * be terminated either by a newline or end-of-file.
187        */
188       for (;;) {
189         ch = getc(fp);
190         if (ch == '\n') goto newline;
191         else if (ch == EOF) goto eof;
192       }
193
194     default:
195       /* Whitespace means we just continue around.  Anything else and we
196        * start snarfing.
197        */
198       if (isspace(ch)) goto skip_ws;
199       break;
200   }
201
202   for (;;) {
203
204     /* If there's buffer space left, store the character. */
205     if (sz) { *buf++ = ch; sz--; }
206
207     /* Get a new one, and find out what to do about it. */
208     ch = getc(fp);
209     switch (ch) {
210       case '\n':
211         ungetc(ch, fp);
212         goto done;
213       case EOF:
214         goto done;
215       default:
216         if (isspace(ch)) goto done;
217         break;
218     }
219   }
220
221 done:
222   /* If there's no space for a terminating null then report an error. */
223   if (!sz) return (T_ERROR);
224
225   /* All done. */
226   *buf++ = 0; sz--;
227   return (T_OK);
228 }
229
230 /* Parse an action name, storing the code in *ACT.  Return an appropriate T_*
231  * code.
232  */
233 static int parse_actname(FILE *fp, unsigned *act)
234 {
235   char buf[32];
236   int t;
237   const char *const *p;
238
239   if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
240   for (p = acttab; *p; p++)
241     if (strcmp(buf, *p) == 0) { *act = p - acttab; return (0); }
242   return (T_ERROR);
243 }
244
245 /* Parse an action, returning a T_* code. */
246 static int parse_action(FILE *fp, struct action *act)
247 {
248   char buf[32];
249   int t;
250   unsigned a;
251   unsigned long m;
252
253   /* Collect the action name. */
254   if ((t = parse_actname(fp, &a)) != 0) return (t);
255
256   /* Parse parameters, if there are any. */
257   switch (a) {
258
259     case A_USER:
260       /* `user ACTION ACTION ...': store permitted actions in a bitmask. */
261       m = 0;
262       for (;;) {
263         if ((t = parse_actname(fp, &a)) != 0) break;
264         if (a == A_USER) return (T_ERROR);
265         m |= (1 << a);
266       }
267       if (t != T_EOL && t != T_EOF) return (t);
268       act->act = A_USER;
269       act->u.user = m;
270       break;
271
272     case A_TOKEN:
273     case A_NAME:
274     case A_DENY:
275     case A_HIDE:
276       /* Dull actions which don't accept parameters. */
277       act->act = a;
278       break;
279
280     case A_LIE:
281       /* `lie NAME': store the string we're to report. */
282       if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
283       act->act = a;
284       act->u.lie = xstrdup(buf);
285       break;
286   }
287
288   /* Make sure we've reached the end of the line. */
289   t = scan(fp, buf, sizeof(buf));
290   if (t != T_EOF && t != T_EOL) {
291     free_action(act);
292     return (T_ERROR);
293   }
294
295   /* Done. */
296   return (0);
297 }
298
299 /* Parse an address pattern, writing it to AP.  If the pattern has an
300  * identifiable address family, update *AOP to point to its operations table;
301  * if *AOP is already set to something different then report an error.
302  */
303 static int parse_addrpat(FILE *fp, const struct addrops **aop,
304                          struct addrpat *ap)
305 {
306   char buf[64];
307   int t;
308   const struct addrops *ao;
309   long n;
310   char *delim;
311
312   /* Scan a token for the address pattern. */
313   if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
314
315   /* If this is a wildcard, then leave everything as it is. */
316   if (strcmp(buf, "*") == 0) {
317     ap->len = 0;
318     return (T_OK);
319   }
320
321   /* Decide what kind of address this must be.  A bit grim, sorry. */
322   if (strchr(buf, ':'))
323     ao = &addroptab[ADDR_IPV6];
324   else
325     ao = &addroptab[ADDR_IPV4];
326
327   /* Update the caller's idea of the address family in use. */
328   if (!*aop) *aop = ao;
329   else if (*aop != ao) return (T_ERROR);
330
331   /* See whether there's a prefix length.  If so, clobber it. */
332   delim = strchr(buf, '/');
333   if (delim) *delim++ = 0;
334
335   /* Parse the address. */
336   if (!inet_pton(ao->af, buf, &ap->addr)) return (T_ERROR);
337
338   /* Parse the prefix length, or use the maximum one. */
339   if (!delim) n = ao->len;
340   else n = strtol(delim, 0, 10);
341   if (n < 0 || n > ao->len) return (T_ERROR);
342   ap->len = n;
343
344   /* Done. */
345   return (T_OK);
346 }
347
348 static int parse_portpat(FILE *fp, struct portpat *pp)
349 {
350   char buf[64];
351   int t;
352   long n;
353   char *delim;
354
355   /* Parse a token for the pattern. */
356   if ((t = scan(fp, buf, sizeof(buf))) != 0) return (T_ERROR);
357
358   /* If this is a wildcard, then we're done. */
359   if (strcmp(buf, "*") == 0) {
360     pp->lo = 0;
361     pp->hi = 65535;
362     return (T_OK);
363   }
364
365   /* Find a range delimiter. */
366   delim = strchr(buf, '-');
367   if (delim) *delim++ = 0;
368
369   /* Parse the only or low end of the range. */
370   n = strtol(buf, 0, 0);
371   if (n < 0 || n > 65535) return (T_ERROR);
372   pp->lo = n;
373
374   /* If there's no delimiter, then the high end is equal to the low end;
375    * otherwise, parse the high end.
376    */
377   if (!delim)
378     pp->hi = n;
379   else {
380     n = strtol(delim, 0, 0);
381     if (n < pp->lo || n > 65535) return (T_ERROR);
382     pp->hi = n;
383   }
384
385   /* Done. */
386   return (T_OK);
387 }
388
389 /* Parse a socket pattern, writing it to SP. */
390 static int parse_sockpat(FILE *fp, const struct addrops **aop,
391                          struct sockpat *sp)
392 {
393   int t;
394
395   if ((t = parse_addrpat(fp, aop, &sp->addr)) != 0) return (t);
396   if ((t = parse_portpat(fp, &sp->port)) != 0) return (T_ERROR);
397   return (T_OK);
398 }
399
400 /* Parse a user pattern, writing it to UP. */
401 static int parse_userpat(FILE *fp, struct userpat *up)
402 {
403   struct passwd *pw;
404   char buf[32];
405   int t;
406   char *delim;
407
408   if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
409   if (!strcmp(buf, "*")) { up->lo = 0; up->hi = UINT_MAX; }
410   else if ((pw = getpwnam(buf)) != 0) up->lo = up->hi = pw->pw_uid;
411   else {
412     if ((delim = strchr(buf, '-')) != 0) *delim++ = 0;
413     up->lo = strtoul(buf, 0, 0);
414     if (!delim) up->hi = up->lo;
415     else if (!*delim) up->hi = UINT_MAX;
416     else up->hi = strtoul(delim, 0, 0);
417   }
418   return (0);
419 }
420
421 /* Parse a policy rule line, writing it to P. */
422 static int parse_policy(FILE *fp, struct policy *p)
423 {
424   int t;
425
426   p->ao = 0;
427   free_policy(p);
428
429   if ((t = parse_sockpat(fp, &p->ao, &p->sp[L])) != 0) goto fail;
430   if ((t = parse_sockpat(fp, &p->ao, &p->sp[R])) != 0) goto err;
431   if ((t = parse_userpat(fp, &p->up)) != 0) goto err;
432   if ((t = parse_action(fp, &p->act)) != 0) goto err;
433   return (0);
434
435 err:
436   t = T_ERROR;
437 fail:
438   free_policy(p);
439   return (t);
440 }
441
442 /* Open a policy file by NAME.  The description WHAT and query Q are used for
443  * formatting error messages for the log.
444  *
445  * This function is somewhat careful only to read from actual regular files,
446  * though (if the filesystem object identified by NAME is a symlink, say) it
447  * might open a device node or other exotic thing without reading it.  This
448  * is likely harmless, since we're running as an unprivileged user anyway.
449  */
450 int open_policy_file(struct policy_file *pf, const char *name,
451                      const char *what, const struct query *q, unsigned f)
452 {
453   struct stat st;
454
455   if ((pf->fp = fopen(name, "r")) == 0) {
456     if (errno != ENOENT || !(f & OPF_NOENTOK)) {
457       logmsg(q, LOG_ERR, "failed to open %s `%s': %s",
458              what, name, strerror(errno));
459     }
460     goto err_0;
461   }
462
463   if (fstat(fileno(pf->fp), &st)) {
464     logmsg(q, LOG_ERR, "failed to read information about %s `%s': %s",
465            what, name, strerror(errno));
466     goto err_1;
467   }
468   if (!S_ISREG(st.st_mode)) {
469     logmsg(q, LOG_ERR, "object `%s', used as %s, is not a regular file",
470            name, what);
471     goto err_1;
472   }
473
474   pf->name = name;
475   pf->what = what;
476   pf->q = q;
477   pf->err = 0;
478   pf->lno = 0;
479   init_policy(&pf->p);
480   return (0);
481
482 err_1:
483   fclose(pf->fp);
484 err_0:
485   return (-1);
486 }
487
488 /* Read a policy rule from the file, storing it in PF->p.  Return one of the
489  * T_* codes.
490  */
491 int read_policy_file(struct policy_file *pf)
492 {
493   int t;
494
495   for (;;) {
496     pf->lno++;
497     t = parse_policy(pf->fp, &pf->p);
498     switch (t) {
499       case T_OK:
500       case T_EOL:
501         nextline(pf->fp);
502         return (t);
503       case T_ERROR:
504         logmsg(pf->q, LOG_ERR, "%s:%d: parse error in %s",
505                pf->name, pf->lno, pf->what);
506         pf->err = 1;
507         return (t);
508       case T_EOF:
509         if (ferror(pf->fp)) {
510           logmsg(pf->q, LOG_ERR, "failed to read %s `%s': %s",
511                  pf->what, pf->name, strerror(errno));
512         }
513         return (t);
514       default:
515         abort();
516     }
517   }
518 }
519
520 /* Close a policy file.  It doesn't matter whether the file was completely
521  * read.
522  */
523 void close_policy_file(struct policy_file *pf)
524 {
525   fclose(pf->fp);
526   free_policy(&pf->p);
527 }
528
529 /* Load a policy file, writing a vector of records into PV.  If the policy
530  * file has errors, then leave PV unchanged and return nonzero.
531  */
532 int load_policy_file(const char *file, policy_v *pv)
533 {
534   struct policy_file pf;
535   policy_v v = DA_INIT;
536   int t = 0;
537
538   if (open_policy_file(&pf, file, "policy file", 0, 0))
539     return (-1);
540   while ((t = read_policy_file(&pf)) < T_EOF) {
541     if (t == T_OK) {
542       DA_PUSH(&v, pf.p);
543       init_policy(&pf.p);
544     }
545   }
546   close_policy_file(&pf);
547   if (!pf.err) {
548     DA_DESTROY(pv);
549     *pv = v;
550     return (0);
551   } else {
552     DA_DESTROY(&v);
553     return (-1);
554   }
555 }
556
557 /*----- That's all, folks -------------------------------------------------*/