1 /* $NetBSD: match.c,v 1.17 2024/09/24 21:32:18 christos Exp $ */
2 /* $OpenBSD: match.c,v 1.45 2024/09/06 02:30:44 djm Exp $ */
3
4 /*
5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * All rights reserved
8 * Simple pattern matching, with '*' and '?' as wildcards.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 */
16 /*
17 * Copyright (c) 2000 Markus Friedl. All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
21 * are met:
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 #include "includes.h"
41 __RCSID("$NetBSD: match.c,v 1.17 2024/09/24 21:32:18 christos Exp $");
42 #include <sys/types.h>
43
44 #include <ctype.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49
50 #include "xmalloc.h"
51 #include "match.h"
52 #include "misc.h"
53
54 /*
55 * Returns true if the given string matches the pattern (which may contain ?
56 * and * as wildcards), and zero if it does not match.
57 */
58 int
match_pattern(const char * s,const char * pattern)59 match_pattern(const char *s, const char *pattern)
60 {
61 for (;;) {
62 /* If at end of pattern, accept if also at end of string. */
63 if (!*pattern)
64 return !*s;
65
66 if (*pattern == '*') {
67 /* Skip this and any consecutive asterisks. */
68 while (*pattern == '*')
69 pattern++;
70
71 /* If at end of pattern, accept immediately. */
72 if (!*pattern)
73 return 1;
74
75 /* If next character in pattern is known, optimize. */
76 if (*pattern != '?' && *pattern != '*') {
77 /*
78 * Look instances of the next character in
79 * pattern, and try to match starting from
80 * those.
81 */
82 for (; *s; s++)
83 if (*s == *pattern &&
84 match_pattern(s + 1, pattern + 1))
85 return 1;
86 /* Failed. */
87 return 0;
88 }
89 /*
90 * Move ahead one character at a time and try to
91 * match at each position.
92 */
93 for (; *s; s++)
94 if (match_pattern(s, pattern))
95 return 1;
96 /* Failed. */
97 return 0;
98 }
99 /*
100 * There must be at least one more character in the string.
101 * If we are at the end, fail.
102 */
103 if (!*s)
104 return 0;
105
106 /* Check if the next character of the string is acceptable. */
107 if (*pattern != '?' && *pattern != *s)
108 return 0;
109
110 /* Move to the next character, both in string and in pattern. */
111 s++;
112 pattern++;
113 }
114 /* NOTREACHED */
115 }
116
117 /*
118 * Tries to match the string against the
119 * comma-separated sequence of subpatterns (each possibly preceded by ! to
120 * indicate negation). Returns -1 if negation matches, 1 if there is
121 * a positive match, 0 if there is no match at all.
122 */
123 int
match_pattern_list(const char * string,const char * pattern,int dolower)124 match_pattern_list(const char *string, const char *pattern, int dolower)
125 {
126 char sub[1024];
127 int negated;
128 int got_positive;
129 u_int i, subi, len = strlen(pattern);
130
131 got_positive = 0;
132 for (i = 0; i < len;) {
133 /* Check if the subpattern is negated. */
134 if (pattern[i] == '!') {
135 negated = 1;
136 i++;
137 } else
138 negated = 0;
139
140 /*
141 * Extract the subpattern up to a comma or end. Convert the
142 * subpattern to lowercase.
143 */
144 for (subi = 0;
145 i < len && subi < sizeof(sub) - 1 && pattern[i] != ',';
146 subi++, i++)
147 sub[subi] = dolower && isupper((u_char)pattern[i]) ?
148 tolower((u_char)pattern[i]) : pattern[i];
149 /* If subpattern too long, return failure (no match). */
150 if (subi >= sizeof(sub) - 1)
151 return 0;
152
153 /* If the subpattern was terminated by a comma, then skip it. */
154 if (i < len && pattern[i] == ',')
155 i++;
156
157 /* Null-terminate the subpattern. */
158 sub[subi] = '\0';
159
160 /* Try to match the subpattern against the string. */
161 if (match_pattern(string, sub)) {
162 if (negated)
163 return -1; /* Negative */
164 else
165 got_positive = 1; /* Positive */
166 }
167 }
168
169 /*
170 * Return success if got a positive match. If there was a negative
171 * match, we have already returned -1 and never get here.
172 */
173 return got_positive;
174 }
175
176 /* Match a list representing users or groups. */
177 int
match_usergroup_pattern_list(const char * string,const char * pattern)178 match_usergroup_pattern_list(const char *string, const char *pattern)
179 {
180 /* Case sensitive match */
181 return match_pattern_list(string, pattern, 0);
182 }
183
184 /*
185 * Tries to match the host name (which must be in all lowercase) against the
186 * comma-separated sequence of subpatterns (each possibly preceded by ! to
187 * indicate negation). Returns -1 if negation matches, 1 if there is
188 * a positive match, 0 if there is no match at all.
189 */
190 int
match_hostname(const char * host,const char * pattern)191 match_hostname(const char *host, const char *pattern)
192 {
193 char *hostcopy = xstrdup(host);
194 int r;
195
196 lowercase(hostcopy);
197 r = match_pattern_list(hostcopy, pattern, 1);
198 free(hostcopy);
199 return r;
200 }
201
202 /*
203 * returns 0 if we get a negative match for the hostname or the ip
204 * or if we get no match at all. returns -1 on error, or 1 on
205 * successful match.
206 */
207 int
match_host_and_ip(const char * host,const char * ipaddr,const char * patterns)208 match_host_and_ip(const char *host, const char *ipaddr,
209 const char *patterns)
210 {
211 int mhost, mip;
212
213 if ((mip = addr_match_list(ipaddr, patterns)) == -2)
214 return -1; /* error in ipaddr match */
215 else if (host == NULL || ipaddr == NULL || mip == -1)
216 return 0; /* negative ip address match, or testing pattern */
217
218 /* negative hostname match */
219 if ((mhost = match_hostname(host, patterns)) == -1)
220 return 0;
221 /* no match at all */
222 if (mhost == 0 && mip == 0)
223 return 0;
224 return 1;
225 }
226
227 /*
228 * Match user, user@host_or_ip, user@host_or_ip_list against pattern.
229 * If user, host and ipaddr are all NULL then validate pattern/
230 * Returns -1 on invalid pattern, 0 on no match, 1 on match.
231 */
232 int
match_user(const char * user,const char * host,const char * ipaddr,const char * pattern)233 match_user(const char *user, const char *host, const char *ipaddr,
234 const char *pattern)
235 {
236 char *p, *pat;
237 int ret;
238
239 /* test mode */
240 if (user == NULL && host == NULL && ipaddr == NULL) {
241 if ((p = strrchr(pattern, '@')) != NULL &&
242 match_host_and_ip(NULL, NULL, p + 1) < 0)
243 return -1;
244 return 0;
245 }
246
247 if (user == NULL)
248 return 0; /* shouldn't happen */
249
250 if (strrchr(pattern, '@') == NULL)
251 return match_pattern(user, pattern);
252
253 pat = xstrdup(pattern);
254 p = strrchr(pat, '@');
255 *p++ = '\0';
256
257 if ((ret = match_pattern(user, pat)) == 1)
258 ret = match_host_and_ip(host, ipaddr, p);
259 free(pat);
260
261 return ret;
262 }
263
264 /*
265 * Returns first item from client-list that is also supported by server-list,
266 * caller must free the returned string.
267 */
268 #define MAX_PROP 40
269 #define SEP ","
270 char *
match_list(const char * client,const char * server,u_int * next)271 match_list(const char *client, const char *server, u_int *next)
272 {
273 char *sproposals[MAX_PROP];
274 char *c, *s, *p, *ret, *cp, *sp;
275 int i, j, nproposals;
276
277 c = cp = xstrdup(client);
278 s = sp = xstrdup(server);
279
280 for ((p = strsep(&sp, SEP)), i=0; p && *p != '\0';
281 (p = strsep(&sp, SEP)), i++) {
282 if (i < MAX_PROP)
283 sproposals[i] = p;
284 else
285 break;
286 }
287 nproposals = i;
288
289 for ((p = strsep(&cp, SEP)), i=0; p && *p != '\0';
290 (p = strsep(&cp, SEP)), i++) {
291 for (j = 0; j < nproposals; j++) {
292 if (strcmp(p, sproposals[j]) == 0) {
293 ret = xstrdup(p);
294 if (next != NULL)
295 *next = (cp == NULL) ?
296 strlen(c) : (u_int)(cp - c);
297 free(c);
298 free(s);
299 return ret;
300 }
301 }
302 }
303 if (next != NULL)
304 *next = strlen(c);
305 free(c);
306 free(s);
307 return NULL;
308 }
309
310 /*
311 * Filter proposal using pattern-list filter.
312 * "denylist" determines sense of filter:
313 * non-zero indicates that items matching filter should be excluded.
314 * zero indicates that only items matching filter should be included.
315 * returns NULL on allocation error, otherwise caller must free result.
316 */
317 static char *
filter_list(const char * proposal,const char * filter,int denylist)318 filter_list(const char *proposal, const char *filter, int denylist)
319 {
320 size_t len = strlen(proposal) + 1;
321 char *fix_prop = malloc(len);
322 char *orig_prop = strdup(proposal);
323 char *cp, *tmp;
324 int r;
325
326 if (fix_prop == NULL || orig_prop == NULL) {
327 free(orig_prop);
328 free(fix_prop);
329 return NULL;
330 }
331
332 tmp = orig_prop;
333 *fix_prop = '\0';
334 while ((cp = strsep(&tmp, ",")) != NULL) {
335 r = match_pattern_list(cp, filter, 0);
336 if ((denylist && r != 1) || (!denylist && r == 1)) {
337 if (*fix_prop != '\0')
338 strlcat(fix_prop, ",", len);
339 strlcat(fix_prop, cp, len);
340 }
341 }
342 free(orig_prop);
343 return fix_prop;
344 }
345
346 /*
347 * Filters a comma-separated list of strings, excluding any entry matching
348 * the 'filter' pattern list. Caller must free returned string.
349 */
350 char *
match_filter_denylist(const char * proposal,const char * filter)351 match_filter_denylist(const char *proposal, const char *filter)
352 {
353 return filter_list(proposal, filter, 1);
354 }
355
356 /*
357 * Filters a comma-separated list of strings, including only entries matching
358 * the 'filter' pattern list. Caller must free returned string.
359 */
360 char *
match_filter_allowlist(const char * proposal,const char * filter)361 match_filter_allowlist(const char *proposal, const char *filter)
362 {
363 return filter_list(proposal, filter, 0);
364 }
365