1 /*
2  *	libxt_time - iptables part for xt_time
3  *	Copyright © CC Computer Consultants GmbH, 2007
4  *	Contact: <jengelh@computergmbh.de>
5  *
6  *	libxt_time.c is free software; you can redistribute it and/or modify
7  *	it under the terms of the GNU General Public License as published by
8  *	the Free Software Foundation; either version 2 or 3 of the License.
9  *
10  *	Based on libipt_time.c.
11  */
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <time.h>
16 #include <linux/types.h>
17 #include <linux/netfilter/xt_time.h>
18 #include <xtables.h>
19 
20 enum {
21 	O_DATE_START = 0,
22 	O_DATE_STOP,
23 	O_TIME_START,
24 	O_TIME_STOP,
25 	O_TIME_CONTIGUOUS,
26 	O_MONTHDAYS,
27 	O_WEEKDAYS,
28 	O_LOCAL_TZ,
29 	O_UTC,
30 	O_KERNEL_TZ,
31 	F_LOCAL_TZ  = 1 << O_LOCAL_TZ,
32 	F_UTC       = 1 << O_UTC,
33 	F_KERNEL_TZ = 1 << O_KERNEL_TZ,
34 	F_TIME_CONTIGUOUS = 1 << O_TIME_CONTIGUOUS,
35 };
36 
37 static const char *const week_days[] = {
38 	NULL, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun",
39 };
40 
41 static const struct xt_option_entry time_opts[] = {
42 	{.name = "datestart", .id = O_DATE_START, .type = XTTYPE_STRING},
43 	{.name = "datestop", .id = O_DATE_STOP, .type = XTTYPE_STRING},
44 	{.name = "timestart", .id = O_TIME_START, .type = XTTYPE_STRING},
45 	{.name = "timestop", .id = O_TIME_STOP, .type = XTTYPE_STRING},
46 	{.name = "contiguous", .id = O_TIME_CONTIGUOUS, .type = XTTYPE_NONE},
47 	{.name = "weekdays", .id = O_WEEKDAYS, .type = XTTYPE_STRING,
48 	 .flags = XTOPT_INVERT},
49 	{.name = "monthdays", .id = O_MONTHDAYS, .type = XTTYPE_STRING,
50 	 .flags = XTOPT_INVERT},
51 	{.name = "localtz", .id = O_LOCAL_TZ, .type = XTTYPE_NONE,
52 	 .excl = F_UTC},
53 	{.name = "utc", .id = O_UTC, .type = XTTYPE_NONE,
54 	 .excl = F_LOCAL_TZ | F_KERNEL_TZ},
55 	{.name = "kerneltz", .id = O_KERNEL_TZ, .type = XTTYPE_NONE,
56 	 .excl = F_UTC},
57 	XTOPT_TABLEEND,
58 };
59 
time_help(void)60 static void time_help(void)
61 {
62 	printf(
63 "time match options:\n"
64 "    --datestart time     Start and stop time, to be given in ISO 8601\n"
65 "    --datestop time      (YYYY[-MM[-DD[Thh[:mm[:ss]]]]])\n"
66 "    --timestart time     Start and stop daytime (hh:mm[:ss])\n"
67 "    --timestop time      (between 00:00:00 and 23:59:59)\n"
68 "[!] --monthdays value    List of days on which to match, separated by comma\n"
69 "                         (Possible days: 1 to 31; defaults to all)\n"
70 "[!] --weekdays value     List of weekdays on which to match, sep. by comma\n"
71 "                         (Possible days: Mon,Tue,Wed,Thu,Fri,Sat,Sun or 1 to 7\n"
72 "                         Defaults to all weekdays.)\n"
73 "    --kerneltz           Work with the kernel timezone instead of UTC\n");
74 }
75 
time_init(struct xt_entry_match * m)76 static void time_init(struct xt_entry_match *m)
77 {
78 	struct xt_time_info *info = (void *)m->data;
79 
80 	/* By default, we match on every day, every daytime */
81 	info->monthdays_match = XT_TIME_ALL_MONTHDAYS;
82 	info->weekdays_match  = XT_TIME_ALL_WEEKDAYS;
83 	info->daytime_start   = XT_TIME_MIN_DAYTIME;
84 	info->daytime_stop    = XT_TIME_MAX_DAYTIME;
85 
86 	/* ...and have no date-begin or date-end boundary */
87 	info->date_start = 0;
88 	info->date_stop  = INT_MAX;
89 }
90 
time_parse_date(const char * s)91 static time_t time_parse_date(const char *s)
92 {
93 	unsigned int month = 1, day = 1, hour = 0, minute = 0, second = 0;
94 	unsigned int year;
95 	const char *os = s;
96 	struct tm tm;
97 	time_t ret;
98 	char *e;
99 
100 	year = strtoul(s, &e, 10);
101 	if ((*e != '-' && *e != '\0') || year < 1970 || year > 2038)
102 		goto out;
103 	if (*e == '\0')
104 		goto eval;
105 
106 	s = e + 1;
107 	month = strtoul(s, &e, 10);
108 	if ((*e != '-' && *e != '\0') || month > 12)
109 		goto out;
110 	if (*e == '\0')
111 		goto eval;
112 
113 	s = e + 1;
114 	day = strtoul(s, &e, 10);
115 	if ((*e != 'T' && *e != '\0') || day > 31)
116 		goto out;
117 	if (*e == '\0')
118 		goto eval;
119 
120 	s = e + 1;
121 	hour = strtoul(s, &e, 10);
122 	if ((*e != ':' && *e != '\0') || hour > 23)
123 		goto out;
124 	if (*e == '\0')
125 		goto eval;
126 
127 	s = e + 1;
128 	minute = strtoul(s, &e, 10);
129 	if ((*e != ':' && *e != '\0') || minute > 59)
130 		goto out;
131 	if (*e == '\0')
132 		goto eval;
133 
134 	s = e + 1;
135 	second = strtoul(s, &e, 10);
136 	if (*e != '\0' || second > 59)
137 		goto out;
138 
139  eval:
140 	tm.tm_year = year - 1900;
141 	tm.tm_mon  = month - 1;
142 	tm.tm_mday = day;
143 	tm.tm_hour = hour;
144 	tm.tm_min  = minute;
145 	tm.tm_sec  = second;
146 	tm.tm_isdst = 0;
147 	/*
148 	 * Offsetting, if any, is done by xt_time.ko,
149 	 * so we have to disable it here in userspace.
150 	 */
151 	setenv("TZ", "UTC", true);
152 	tzset();
153 	ret = mktime(&tm);
154 	if (ret >= 0)
155 		return ret;
156 	perror("mktime");
157 	xtables_error(OTHER_PROBLEM, "mktime returned an error");
158 
159  out:
160 	xtables_error(PARAMETER_PROBLEM, "Invalid date \"%s\" specified. Should "
161 	           "be YYYY[-MM[-DD[Thh[:mm[:ss]]]]]", os);
162 	return -1;
163 }
164 
time_parse_minutes(const char * s)165 static unsigned int time_parse_minutes(const char *s)
166 {
167 	unsigned int hour, minute, second = 0;
168 	char *e;
169 
170 	hour = strtoul(s, &e, 10);
171 	if (*e != ':' || hour > 23)
172 		goto out;
173 
174 	s = e + 1;
175 	minute = strtoul(s, &e, 10);
176 	if ((*e != ':' && *e != '\0') || minute > 59)
177 		goto out;
178 	if (*e == '\0')
179 		goto eval;
180 
181 	s = e + 1;
182 	second = strtoul(s, &e, 10);
183 	if (*e != '\0' || second > 59)
184 		goto out;
185 
186  eval:
187 	return 60 * 60 * hour + 60 * minute + second;
188 
189  out:
190 	xtables_error(PARAMETER_PROBLEM, "invalid time \"%s\" specified, "
191 	           "should be hh:mm[:ss] format and within the boundaries", s);
192 	return -1;
193 }
194 
my_strseg(char * buf,unsigned int buflen,const char ** arg,char delim)195 static const char *my_strseg(char *buf, unsigned int buflen,
196     const char **arg, char delim)
197 {
198 	const char *sep;
199 
200 	if (*arg == NULL || **arg == '\0')
201 		return NULL;
202 	sep = strchr(*arg, delim);
203 	if (sep == NULL) {
204 		snprintf(buf, buflen, "%s", *arg);
205 		*arg = NULL;
206 		return buf;
207 	}
208 	snprintf(buf, buflen, "%.*s", (unsigned int)(sep - *arg), *arg);
209 	*arg = sep + 1;
210 	return buf;
211 }
212 
time_parse_monthdays(const char * arg)213 static uint32_t time_parse_monthdays(const char *arg)
214 {
215 	char day[3], *err = NULL;
216 	uint32_t ret = 0;
217 	unsigned int i;
218 
219 	while (my_strseg(day, sizeof(day), &arg, ',') != NULL) {
220 		i = strtoul(day, &err, 0);
221 		if ((*err != ',' && *err != '\0') || i > 31)
222 			xtables_error(PARAMETER_PROBLEM,
223 			           "%s is not a valid day for --monthdays", day);
224 		ret |= 1 << i;
225 	}
226 
227 	return ret;
228 }
229 
time_parse_weekdays(const char * arg)230 static unsigned int time_parse_weekdays(const char *arg)
231 {
232 	char day[4], *err = NULL;
233 	unsigned int i, ret = 0;
234 	bool valid;
235 
236 	while (my_strseg(day, sizeof(day), &arg, ',') != NULL) {
237 		i = strtoul(day, &err, 0);
238 		if (*err == '\0') {
239 			if (i == 0)
240 				xtables_error(PARAMETER_PROBLEM,
241 				           "No, the week does NOT begin with Sunday.");
242 			ret |= 1 << i;
243 			continue;
244 		}
245 
246 		valid = false;
247 		for (i = 1; i < ARRAY_SIZE(week_days); ++i)
248 			if (strncmp(day, week_days[i], 2) == 0) {
249 				ret |= 1 << i;
250 				valid = true;
251 			}
252 
253 		if (!valid)
254 			xtables_error(PARAMETER_PROBLEM,
255 			           "%s is not a valid day specifier", day);
256 	}
257 
258 	return ret;
259 }
260 
time_count_weekdays(unsigned int weekdays_mask)261 static unsigned int time_count_weekdays(unsigned int weekdays_mask)
262 {
263 	unsigned int ret;
264 
265 	for (ret = 0; weekdays_mask; weekdays_mask >>= 1)
266 		ret += weekdays_mask & 1;
267 
268 	return ret;
269 }
270 
time_parse(struct xt_option_call * cb)271 static void time_parse(struct xt_option_call *cb)
272 {
273 	struct xt_time_info *info = cb->data;
274 
275 	xtables_option_parse(cb);
276 	switch (cb->entry->id) {
277 	case O_DATE_START:
278 		info->date_start = time_parse_date(cb->arg);
279 		break;
280 	case O_DATE_STOP:
281 		info->date_stop = time_parse_date(cb->arg);
282 		break;
283 	case O_TIME_START:
284 		info->daytime_start = time_parse_minutes(cb->arg);
285 		break;
286 	case O_TIME_STOP:
287 		info->daytime_stop = time_parse_minutes(cb->arg);
288 		break;
289 	case O_TIME_CONTIGUOUS:
290 		info->flags |= XT_TIME_CONTIGUOUS;
291 		break;
292 	case O_LOCAL_TZ:
293 		fprintf(stderr, "WARNING: --localtz is being replaced by "
294 		        "--kerneltz, since \"local\" is ambiguous. Note the "
295 		        "kernel timezone has caveats - "
296 		        "see manpage for details.\n");
297 		/* fallthrough */
298 	case O_KERNEL_TZ:
299 		info->flags |= XT_TIME_LOCAL_TZ;
300 		break;
301 	case O_MONTHDAYS:
302 		info->monthdays_match = time_parse_monthdays(cb->arg);
303 		if (cb->invert)
304 			info->monthdays_match ^= XT_TIME_ALL_MONTHDAYS;
305 		break;
306 	case O_WEEKDAYS:
307 		info->weekdays_match = time_parse_weekdays(cb->arg);
308 		if (cb->invert)
309 			info->weekdays_match ^= XT_TIME_ALL_WEEKDAYS;
310 		break;
311 	}
312 }
313 
time_print_date(time_t date,const char * command)314 static void time_print_date(time_t date, const char *command)
315 {
316 	struct tm *t;
317 
318 	/* If it is the default value, do not print it. */
319 	if (date == 0 || date == LONG_MAX)
320 		return;
321 
322 	t = gmtime(&date);
323 	if (command != NULL)
324 		/*
325 		 * Need a contiguous string (no whitespaces), hence using
326 		 * the ISO 8601 "T" variant.
327 		 */
328 		printf(" %s %04u-%02u-%02uT%02u:%02u:%02u",
329 		       command, t->tm_year + 1900, t->tm_mon + 1,
330 		       t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
331 	else
332 		printf(" %04u-%02u-%02u %02u:%02u:%02u",
333 		       t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
334 		       t->tm_hour, t->tm_min, t->tm_sec);
335 }
336 
time_print_monthdays(uint32_t mask,bool human_readable)337 static void time_print_monthdays(uint32_t mask, bool human_readable)
338 {
339 	unsigned int i, nbdays = 0;
340 
341 	printf(" ");
342 	for (i = 1; i <= 31; ++i)
343 		if (mask & (1u << i)) {
344 			if (nbdays++ > 0)
345 				printf(",");
346 			printf("%u", i);
347 			if (human_readable)
348 				switch (i % 10) {
349 					case 1:
350 						printf("st");
351 						break;
352 					case 2:
353 						printf("nd");
354 						break;
355 					case 3:
356 						printf("rd");
357 						break;
358 					default:
359 						printf("th");
360 						break;
361 				}
362 		}
363 }
364 
time_print_weekdays(unsigned int mask)365 static void time_print_weekdays(unsigned int mask)
366 {
367 	unsigned int i, nbdays = 0;
368 
369 	printf(" ");
370 	for (i = 1; i <= 7; ++i)
371 		if (mask & (1 << i)) {
372 			if (nbdays > 0)
373 				printf(",%s", week_days[i]);
374 			else
375 				printf("%s", week_days[i]);
376 			++nbdays;
377 		}
378 }
379 
divide_time(unsigned int fulltime,unsigned int * hours,unsigned int * minutes,unsigned int * seconds)380 static inline void divide_time(unsigned int fulltime, unsigned int *hours,
381     unsigned int *minutes, unsigned int *seconds)
382 {
383 	*seconds  = fulltime % 60;
384 	fulltime /= 60;
385 	*minutes  = fulltime % 60;
386 	*hours    = fulltime / 60;
387 }
388 
time_print(const void * ip,const struct xt_entry_match * match,int numeric)389 static void time_print(const void *ip, const struct xt_entry_match *match,
390                        int numeric)
391 {
392 	const struct xt_time_info *info = (const void *)match->data;
393 	unsigned int h, m, s;
394 
395 	printf(" TIME");
396 
397 	if (info->daytime_start != XT_TIME_MIN_DAYTIME ||
398 	    info->daytime_stop != XT_TIME_MAX_DAYTIME) {
399 		divide_time(info->daytime_start, &h, &m, &s);
400 		printf(" from %02u:%02u:%02u", h, m, s);
401 		divide_time(info->daytime_stop, &h, &m, &s);
402 		printf(" to %02u:%02u:%02u", h, m, s);
403 	}
404 	if (info->weekdays_match != XT_TIME_ALL_WEEKDAYS) {
405 		printf(" on");
406 		time_print_weekdays(info->weekdays_match);
407 	}
408 	if (info->monthdays_match != XT_TIME_ALL_MONTHDAYS) {
409 		printf(" on");
410 		time_print_monthdays(info->monthdays_match, true);
411 	}
412 	if (info->date_start != 0) {
413 		printf(" starting from");
414 		time_print_date(info->date_start, NULL);
415 	}
416 	if (info->date_stop != INT_MAX) {
417 		printf(" until date");
418 		time_print_date(info->date_stop, NULL);
419 	}
420 	if (!(info->flags & XT_TIME_LOCAL_TZ))
421 		printf(" UTC");
422 	if (info->flags & XT_TIME_CONTIGUOUS)
423 		printf(" contiguous");
424 }
425 
time_save(const void * ip,const struct xt_entry_match * match)426 static void time_save(const void *ip, const struct xt_entry_match *match)
427 {
428 	const struct xt_time_info *info = (const void *)match->data;
429 	unsigned int h, m, s;
430 
431 	if (info->daytime_start != XT_TIME_MIN_DAYTIME ||
432 	    info->daytime_stop != XT_TIME_MAX_DAYTIME) {
433 		divide_time(info->daytime_start, &h, &m, &s);
434 		printf(" --timestart %02u:%02u:%02u", h, m, s);
435 		divide_time(info->daytime_stop, &h, &m, &s);
436 		printf(" --timestop %02u:%02u:%02u", h, m, s);
437 	}
438 	if (info->monthdays_match != XT_TIME_ALL_MONTHDAYS) {
439 		printf(" --monthdays");
440 		time_print_monthdays(info->monthdays_match, false);
441 	}
442 	if (info->weekdays_match != XT_TIME_ALL_WEEKDAYS) {
443 		printf(" --weekdays");
444 		time_print_weekdays(info->weekdays_match);
445 	}
446 	time_print_date(info->date_start, "--datestart");
447 	time_print_date(info->date_stop, "--datestop");
448 	if (info->flags & XT_TIME_LOCAL_TZ)
449 		printf(" --kerneltz");
450 	if (info->flags & XT_TIME_CONTIGUOUS)
451 		printf(" --contiguous");
452 }
453 
time_check(struct xt_fcheck_call * cb)454 static void time_check(struct xt_fcheck_call *cb)
455 {
456 	const struct xt_time_info *info = (const void *) cb->data;
457 	if ((cb->xflags & F_TIME_CONTIGUOUS) &&
458 	     info->daytime_start < info->daytime_stop)
459 		xtables_error(PARAMETER_PROBLEM,
460 			"time: --contiguous only makes sense when stoptime is smaller than starttime");
461 }
462 
time_xlate(struct xt_xlate * xl,const struct xt_xlate_mt_params * params)463 static int time_xlate(struct xt_xlate *xl,
464 		      const struct xt_xlate_mt_params *params)
465 {
466 	const struct xt_time_info *info =
467 		(const struct xt_time_info *)params->match->data;
468 	unsigned int h, m, s,
469 		     i, sep, mask, count;
470 	time_t tt_start, tt_stop;
471 	struct tm *t_start, *t_stop;
472 
473 	if (info->date_start != 0 ||
474 	    info->date_stop != INT_MAX) {
475 		tt_start = (time_t) info->date_start;
476 		tt_stop = (time_t) info->date_stop;
477 
478 		xt_xlate_add(xl, "meta time ");
479 		t_start = gmtime(&tt_start);
480 		xt_xlate_add(xl, "\"%04u-%02u-%02u %02u:%02u:%02u\"",
481 			     t_start->tm_year + 1900, t_start->tm_mon + 1,
482 			     t_start->tm_mday, t_start->tm_hour,
483 			     t_start->tm_min, t_start->tm_sec);
484 		t_stop = gmtime(&tt_stop);
485 		xt_xlate_add(xl, "-\"%04u-%02u-%02u %02u:%02u:%02u\"",
486 			     t_stop->tm_year + 1900, t_stop->tm_mon + 1,
487 			     t_stop->tm_mday, t_stop->tm_hour,
488 			     t_stop->tm_min, t_stop->tm_sec);
489 	}
490 	if (info->daytime_start != XT_TIME_MIN_DAYTIME ||
491 	    info->daytime_stop != XT_TIME_MAX_DAYTIME) {
492 		divide_time(info->daytime_start, &h, &m, &s);
493 		xt_xlate_add(xl, " meta hour \"%02u:%02u:%02u\"", h, m, s);
494 		divide_time(info->daytime_stop, &h, &m, &s);
495 		xt_xlate_add(xl, "-\"%02u:%02u:%02u\"", h, m, s);
496 	}
497 	/* nft_time does not support --monthdays */
498 	if (info->monthdays_match != XT_TIME_ALL_MONTHDAYS)
499 		return 0;
500 	if (info->weekdays_match != XT_TIME_ALL_WEEKDAYS) {
501 		sep = 0;
502 		mask = info->weekdays_match;
503 		count = time_count_weekdays(mask);
504 
505 		xt_xlate_add(xl, " meta day ");
506 		if (count > 1)
507 			xt_xlate_add(xl, "{");
508 		for (i = 1; i <= 7; ++i)
509 			if (mask & (1 << i)) {
510 				if (sep)
511 					xt_xlate_add(xl, ",%u", i%7);
512 				else {
513 					xt_xlate_add(xl, "%u", i%7);
514 					++sep;
515 				}
516 			}
517 		if (count > 1)
518 			xt_xlate_add(xl, "}");
519 	}
520 
521 	return 1;
522 }
523 
524 static struct xtables_match time_match = {
525 	.name          = "time",
526 	.family        = NFPROTO_UNSPEC,
527 	.version       = XTABLES_VERSION,
528 	.size          = XT_ALIGN(sizeof(struct xt_time_info)),
529 	.userspacesize = XT_ALIGN(sizeof(struct xt_time_info)),
530 	.help          = time_help,
531 	.init          = time_init,
532 	.print         = time_print,
533 	.save          = time_save,
534 	.x6_parse      = time_parse,
535 	.x6_fcheck     = time_check,
536 	.x6_options    = time_opts,
537 	.xlate	       = time_xlate,
538 };
539 
_init(void)540 void _init(void)
541 {
542 	xtables_register_match(&time_match);
543 }
544