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