summaryrefslogtreecommitdiffstats
path: root/lib/util/regex.c
blob: 602f43b677ff5275c75f2d4051ce99f5d185ce0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*
 * SPDX-License-Identifier: ISC
 *
 * Copyright (c) 2023 Todd C. Miller <Todd.Miller@sudo.ws>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
 */

#include <config.h>

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <regex.h>

#include "sudo_compat.h"
#include "sudo_debug.h"
#include "sudo_util.h"
#include "sudo_gettext.h"

static char errbuf[1024];

/*
 * Parse a number between 0 and INT_MAX, handling escaped digits.
 * Returns the number on success or -1 on error.
 * Sets endp to the first non-matching character.
 */
static int
parse_num(const char *str, char **endp)
{
    debug_decl(check_pattern, SUDO_DEBUG_UTIL);
    const unsigned int lastval = INT_MAX / 10;
    const unsigned int remainder = INT_MAX % 10;
    unsigned int result = 0;
    unsigned char ch;

    while ((ch = *str++) != '\0') {
	if (ch == '\\' && isdigit((unsigned int)str[0]))
	    ch = *str++;
	else if (!isdigit(ch))
	    break;
	ch -= '0';
	if (result > lastval || (result == lastval && ch > remainder)) {
	    result = -1;
	    break;
	}
	result *= 10;
	result += ch;
    }
    *endp = (char *)(str - 1);

    debug_return_int(result);
}

/*
 * Check pattern for invalid repetition sequences.
 * This is implementation-specific behavior, not all regcomp(3) forbid them.
 * Glibc allows it but uses excessive memory for repeated '+' ops.
 */
static int
check_pattern(const char *pattern)
{
    debug_decl(check_pattern, SUDO_DEBUG_UTIL);
    const char *cp = pattern;
    int b1, b2 = 0;
    char ch, *ep, prev = '\0';

    while ((ch = *cp++) != '\0') {
	switch (ch) {
	case '\\':
	    if (*cp != '\0') {
		/* Skip escaped character. */
		cp++;
		prev = '\0';
		continue;
	    }
	    break;
	case '?':
	case '*':
	case '+':
	    if (prev == '?' || prev == '*' || prev == '+' || prev == '{' ) {
		/* Invalid repetition operator. */
		debug_return_int(REG_BADRPT);
	    }
	    break;
	case '{':
	    /*
	     * Try to match bound: {[0-9\\]*\?,[0-9\\]*}
	     * GNU libc supports escaped digits and commas.
	     */
	    b1 = parse_num(cp, &ep);
	    switch (ep[0]) {
	    case '\\':
		if (ep[1] != ',')
		    break;
		ep++;
		FALLTHROUGH;
	    case ',':
		cp = ep + 1;
		b2 = parse_num(cp, &ep);
		break;
	    }
	    cp = ep;
	    if (*cp == '}') {
		if (b1 < 0 || b1 > 255 || b2 < 0 || b2 > 255) {
		    /* Invalid bound value. */
		    debug_return_int(REG_BADBR);
		}
		if (prev == '?' || prev == '*' || prev == '+' || prev == '{' ) {
		    /* Invalid repetition operator. */
		    debug_return_int(REG_BADRPT);
		}
		/* Skip past '}', prev will be set to '{' below */
		cp++;
		break;
	    }
	    prev = '\0';
	    continue;
	}
	prev = ch;
    }

    debug_return_int(0);
}

/*
 * Wrapper around regcomp() that handles a regex starting with (?i).
 * Avoid using regex_t in the function args so we don't need to
 * include regex.h everywhere.
 */
bool
sudo_regex_compile_v1(void *v, const char *pattern, const char **errstr)
{
    int errcode, cflags = REG_EXTENDED|REG_NOSUB;
    regex_t *preg;
    char *copy = NULL;
    const char *cp;
    regex_t rebuf;
    debug_decl(regex_compile, SUDO_DEBUG_UTIL);

    /* Some callers just want to check the validity of the pattern. */
    preg = v ? v : &rebuf;

    /* Limit the length of regular expressions to avoid fuzzer issues. */
    if (strlen(pattern) > 1024) {
	*errstr = N_("regular expression too large");
	debug_return_bool(false);
    }

    /* Check for (?i) to enable case-insensitive matching. */
    cp = pattern[0] == '^' ? pattern + 1 : pattern;
    if (strncmp(cp, "(?i)", 4) == 0) {
	cflags |= REG_ICASE;
	copy = strdup(pattern + 4);
	if (copy == NULL) {
	    *errstr = N_("unable to allocate memory");
	    debug_return_bool(false);
	}
	if (pattern[0] == '^')
	    copy[0] = '^';
	pattern = copy;
    }

    errcode = check_pattern(pattern);
    if (errcode == 0)
	errcode = regcomp(preg, pattern, cflags);
    if (errcode == 0) {
	if (preg == &rebuf)
	    regfree(&rebuf);
    } else {
        regerror(errcode, preg, errbuf, sizeof(errbuf));
        *errstr = errbuf;
    }
    free(copy);

    debug_return_bool(errcode == 0);
}