General spring-cleaning. Most of the code is pretty nice now.
[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 const char *const acttab[] = {
84 #define DEFACT(tag, name) name,
85 ACTIONS(DEFACT)
86 #undef DEFACT
87 0
88 };
89
90 static void print_action(const struct action *act)
91 {
92 assert(act->act < A_LIMIT);
93 printf("%s", acttab[act->act]);
94 switch (act->act) {
95 case A_USER: {
96 int i;
97 unsigned m;
98 for (i = 0, m = 1; i < A_LIMIT; i++, m <<= 1)
99 if (act->u.user & m) printf(" %s", acttab[i]);
100 } break;
101 case A_LIE:
102 printf(" %s", act->u.lie);
103 break;
104 }
105 }
106
107 /* Print a policy rule to standard output. */
108 void print_policy(const struct policy *p)
109 {
110 print_sockpat(p->ao, &p->sp[L]); putchar(' ');
111 print_sockpat(p->ao, &p->sp[R]); putchar(' ');
112 print_action(&p->act); putchar('\n');
113 }
114
115 /*----- Matching ----------------------------------------------------------*/
116
117 /* Return true if the port matches the pattern. */
118 static int match_portpat(const struct portpat *pp, unsigned port)
119 { return (pp->lo <= port && port <= pp->hi); }
120
121 /* Return true if the socket matches the pattern. */
122 static int match_sockpat(const struct addrops *ao,
123 const struct sockpat *sp, const struct socket *s)
124 {
125 return (ao->match_addrpat(&sp->addr, &s->addr) &&
126 match_portpat(&sp->port, s->port));
127 }
128
129 /* Return true if the query matches the patterns in the policy rule. */
130 int match_policy(const struct policy *p, const struct query *q)
131 {
132 return ((!p->ao || p->ao == q->ao) &&
133 match_sockpat(q->ao, &p->sp[L], &q->s[L]) &&
134 match_sockpat(q->ao, &p->sp[R], &q->s[R]));
135 }
136
137 /*----- Parsing -----------------------------------------------------------*/
138
139 /* Advance FP to the next line. */
140 static void nextline(FILE *fp)
141 {
142 for (;;) {
143 int ch = getc(fp);
144 if (ch == '\n' || ch == EOF) break;
145 }
146 }
147
148 /* Scan a whitespace-separated token from FP, writing it to BUF. The token
149 * must fit in a buffer of size SZ, including a terminating null. Return
150 * an appropriate T_* error code.
151 */
152 static int scan(FILE *fp, char *buf, size_t sz)
153 {
154 int ch;
155
156 skip_ws:
157 /* Before we start grabbing a token proper, find out what's in store. */
158 ch = getc(fp);
159 switch (ch) {
160
161 case '\n':
162 newline:
163 /* Found a newline. Leave it where it is and report it. */
164 ungetc(ch, fp);
165 return (T_EOL);
166
167 case EOF:
168 eof:
169 /* Found end-of-file, or an I/O error. Return an appropriate code. */
170 return (ferror(fp) ? T_ERROR : T_EOF);
171
172 case '#':
173 /* Found a comment. Consume it, and continue appropriately: it must
174 * be terminated either by a newline or end-of-file.
175 */
176 for (;;) {
177 ch = getc(fp);
178 if (ch == '\n') goto newline;
179 else if (ch == EOF) goto eof;
180 }
181
182 default:
183 /* Whitespace means we just continue around. Anything else and we
184 * start snarfing.
185 */
186 if (isspace(ch)) goto skip_ws;
187 break;
188 }
189
190 for (;;) {
191
192 /* If there's buffer space left, store the character. */
193 if (sz) { *buf++ = ch; sz--; }
194
195 /* Get a new one, and find out what to do about it. */
196 ch = getc(fp);
197 switch (ch) {
198 case '\n':
199 ungetc(ch, fp);
200 goto done;
201 case EOF:
202 goto done;
203 default:
204 if (isspace(ch)) goto done;
205 break;
206 }
207 }
208
209 done:
210 /* If there's no space for a terminating null then report an error. */
211 if (!sz) return (T_ERROR);
212
213 /* All done. */
214 *buf++ = 0; sz--;
215 return (T_OK);
216 }
217
218 /* Parse an action name, storing the code in *ACT. Return an appropriate T_*
219 * code.
220 */
221 static int parse_actname(FILE *fp, unsigned *act)
222 {
223 char buf[32];
224 int t;
225 const char *const *p;
226
227 if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
228 for (p = acttab; *p; p++)
229 if (strcmp(buf, *p) == 0) { *act = p - acttab; return (0); }
230 return (T_ERROR);
231 }
232
233 /* Parse an action, returning a T_* code. */
234 static int parse_action(FILE *fp, struct action *act)
235 {
236 char buf[32];
237 int t;
238 unsigned a;
239 unsigned long m;
240
241 /* Collect the action name. */
242 if ((t = parse_actname(fp, &a)) != 0) return (t);
243
244 /* Parse parameters, if there are any. */
245 switch (a) {
246
247 case A_USER:
248 /* `user ACTION ACTION ...': store permitted actions in a bitmask. */
249 m = 0;
250 for (;;) {
251 if ((t = parse_actname(fp, &a)) != 0) break;
252 m |= (1 << a);
253 }
254 if (t != T_EOL && t != T_EOF) return (t);
255 act->act = A_USER;
256 act->u.user = m;
257 break;
258
259 case A_TOKEN:
260 case A_NAME:
261 case A_DENY:
262 case A_HIDE:
263 /* Dull actions which don't accept parameters. */
264 act->act = a;
265 break;
266
267 case A_LIE:
268 /* `lie NAME': store the string we're to report. */
269 if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
270 act->act = a;
271 act->u.lie = xstrdup(buf);
272 break;
273 }
274
275 /* Make sure we've reached the end of the line. */
276 t = scan(fp, buf, sizeof(buf));
277 if (t != T_EOF && t != T_EOL) {
278 free_action(act);
279 return (T_ERROR);
280 }
281
282 /* Done. */
283 return (0);
284 }
285
286 /* Parse an address pattern, writing it to AP. If the pattern has an
287 * identifiable address family, update *AOP to point to its operations table;
288 * if *AOP is already set to something different then report an error.
289 */
290 static int parse_addrpat(FILE *fp, const struct addrops **aop,
291 struct addrpat *ap)
292 {
293 char buf[64];
294 int t;
295 const struct addrops *ao;
296 long n;
297 char *delim;
298
299 /* Scan a token for the address pattern. */
300 if ((t = scan(fp, buf, sizeof(buf))) != 0) return (t);
301
302 /* If this is a wildcard, then leave everything as it is. */
303 if (strcmp(buf, "*") == 0) {
304 ap->len = 0;
305 return (T_OK);
306 }
307
308 /* Decide what kind of address this must be. A bit grim, sorry. */
309 if (strchr(buf, ':'))
310 ao = &addroptab[ADDR_IPV6];
311 else
312 ao = &addroptab[ADDR_IPV4];
313
314 /* Update the caller's idea of the address family in use. */
315 if (!*aop) *aop = ao;
316 else if (*aop != ao) return (T_ERROR);
317
318 /* See whether there's a prefix length. If so, clobber it. */
319 delim = strchr(buf, '/');
320 if (delim) *delim++ = 0;
321
322 /* Parse the address. */
323 if (!inet_pton(ao->af, buf, &ap->addr)) return (T_ERROR);
324
325 /* Parse the prefix length, or use the maximum one. */
326 if (!delim) n = ao->len;
327 else n = strtol(delim, 0, 10);
328 if (n < 0 || n > ao->len) return (T_ERROR);
329 ap->len = n;
330
331 /* Done. */
332 return (T_OK);
333 }
334
335 static int parse_portpat(FILE *fp, struct portpat *pp)
336 {
337 char buf[64];
338 int t;
339 long n;
340 char *delim;
341
342 /* Parse a token for the pattern. */
343 if ((t = scan(fp, buf, sizeof(buf))) != 0) return (T_ERROR);
344
345 /* If this is a wildcard, then we're done. */
346 if (strcmp(buf, "*") == 0) {
347 pp->lo = 0;
348 pp->hi = 65535;
349 return (T_OK);
350 }
351
352 /* Find a range delimiter. */
353 delim = strchr(buf, '-');
354 if (delim) *delim++ = 0;
355
356 /* Parse the only or low end of the range. */
357 n = strtol(buf, 0, 0);
358 if (n < 0 || n > 65535) return (T_ERROR);
359 pp->lo = n;
360
361 /* If there's no delimiter, then the high end is equal to the low end;
362 * otherwise, parse the high end.
363 */
364 if (!delim)
365 pp->hi = n;
366 else {
367 n = strtol(delim, 0, 0);
368 if (n < pp->lo || n > 65535) return (T_ERROR);
369 pp->hi = n;
370 }
371
372 /* Done. */
373 return (T_OK);
374 }
375
376 /* Parse a socket pattern, writing it to SP. */
377 static int parse_sockpat(FILE *fp, const struct addrops **aop,
378 struct sockpat *sp)
379 {
380 int t;
381
382 if ((t = parse_addrpat(fp, aop, &sp->addr)) != 0) return (t);
383 if ((t = parse_portpat(fp, &sp->port)) != 0) return (T_ERROR);
384 return (T_OK);
385 }
386
387 /* Parse a policy rule line, writing it to P. */
388 static int parse_policy(FILE *fp, struct policy *p)
389 {
390 int t;
391
392 p->ao = 0;
393 free_policy(p);
394
395 if ((t = parse_sockpat(fp, &p->ao, &p->sp[L])) != 0) goto fail;
396 if ((t = parse_sockpat(fp, &p->ao, &p->sp[R])) != 0) goto err;
397 if ((t = parse_action(fp, &p->act)) != 0) goto err;
398 return (0);
399
400 err:
401 t = T_ERROR;
402 fail:
403 free_policy(p);
404 return (t);
405 }
406
407 /* Open a policy file by NAME. The description WHAT and query Q are used for
408 * formatting error messages for the log.
409 */
410 int open_policy_file(struct policy_file *pf, const char *name,
411 const char *what, const struct query *q)
412 {
413 if ((pf->fp = fopen(name, "r")) == 0) {
414 logmsg(q, LOG_ERR, "failed to open %s `%s': %s",
415 what, name, strerror(errno));
416 return (-1);
417 }
418
419 pf->name = name;
420 pf->what = what;
421 pf->q = q;
422 pf->err = 0;
423 pf->lno = 0;
424 init_policy(&pf->p);
425 return (0);
426 }
427
428 /* Read a policy rule from the file, storing it in PF->p. Return one of the
429 * T_* codes.
430 */
431 int read_policy_file(struct policy_file *pf)
432 {
433 int t;
434
435 for (;;) {
436 pf->lno++;
437 t = parse_policy(pf->fp, &pf->p);
438 switch (t) {
439 case T_OK:
440 nextline(pf->fp);
441 return (0);
442 case T_ERROR:
443 logmsg(pf->q, LOG_ERR, "%s:%d: parse error in %s",
444 pf->name, pf->lno, pf->what);
445 pf->err = 1;
446 break;
447 case T_EOF:
448 if (ferror(pf->fp)) {
449 logmsg(pf->q, LOG_ERR, "failed to read %s `%s': %s",
450 pf->what, pf->name, strerror(errno));
451 }
452 return (-1);
453 case T_EOL:
454 nextline(pf->fp);
455 break;
456 default:
457 abort();
458 }
459 }
460 }
461
462 /* Close a policy file. It doesn't matter whether the file was completely
463 * read.
464 */
465 void close_policy_file(struct policy_file *pf)
466 {
467 fclose(pf->fp);
468 free_policy(&pf->p);
469 }
470
471 /* Load a policy file, writing a vector of records into PV. If the policy
472 * file has errors, then leave PV unchanged and return nonzero.
473 */
474 int load_policy_file(const char *file, policy_v *pv)
475 {
476 struct policy_file pf;
477 policy_v v = DA_INIT;
478
479 if (open_policy_file(&pf, file, "policy file", 0))
480 return (-1);
481 while (!read_policy_file(&pf)) {
482 DA_PUSH(&v, pf.p);
483 init_policy(&pf.p);
484 }
485 close_policy_file(&pf);
486 if (!pf.err) {
487 DA_DESTROY(pv);
488 *pv = v;
489 return (0);
490 } else {
491 DA_DESTROY(&v);
492 return (-1);
493 }
494 }
495
496 /*----- That's all, folks -------------------------------------------------*/