From 55c49a0bf0a700361d3e8f599445f9912e78473d Mon Sep 17 00:00:00 2001 From: Joachim Nilsson Date: Tue, 7 Jan 2020 02:49:05 +0100 Subject: [PATCH] Sanitize job[:id] tuple read from UNIX socket using a regex This is a really tight check for a single "job[:id]" tuple, not much escapes it, Coverity should be a lot more happy about our addressing CWE-20 with this one. Signed-off-by: Joachim Nilsson --- src/util.c | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/src/util.c b/src/util.c index 9e95e8f8..59fd3d1c 100644 --- a/src/util.c +++ b/src/util.c @@ -24,6 +24,7 @@ #include "config.h" #include /* isprint() */ #include +#include #include #include #include @@ -159,29 +160,29 @@ char *uptime(long secs, char *buf, size_t len) return buf; } -/* Allowed characters in job/id/name */ -static int isallowed(int ch) -{ - return isprint(ch); -} - -/* Sanitize user input, make sure to NUL terminate. */ +/* + * Verify string argument is NUL terminated + * Verify string is a JOB[:ID], JOB and ID + * can both be string or number, or combo. + */ char *sanitize(char *arg, size_t len) { - size_t i = 0; + const char *regex = "[a-z0-9_]+[:]?[a-z0-9_]*"; + regex_t preg; + int rc; - while (i < len && isallowed(arg[i])) - i++; + if (strlen(arg) > len) + return NULL; - if (i + 1 < len) { - arg[i + 1] = 0; - return arg; - } + if (regcomp(&preg, regex, REG_ICASE | REG_EXTENDED)) + return NULL; - if (i > 0 && arg[i] == 0) - return arg; + rc = regexec(&preg, arg, 0, NULL, 0); + regfree(&preg); + if (rc) + return NULL; - return NULL; + return arg; } /*