xref: /linux/net/netfilter/nf_conntrack_ftp.c (revision 6e6f2b9b3375cc0e6b8567d31ae7d3b2d910582f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* FTP extension for connection tracking. */
3 
4 /* (C) 1999-2001 Paul `Rusty' Russell
5  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
6  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
7  * (C) 2006-2012 Patrick McHardy <kaber@trash.net>
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/netfilter.h>
15 #include <linux/ip.h>
16 #include <linux/slab.h>
17 #include <linux/ipv6.h>
18 #include <linux/ctype.h>
19 #include <linux/inet.h>
20 #include <net/checksum.h>
21 #include <net/tcp.h>
22 
23 #include <net/netfilter/nf_conntrack.h>
24 #include <net/netfilter/nf_conntrack_expect.h>
25 #include <net/netfilter/nf_conntrack_ecache.h>
26 #include <net/netfilter/nf_conntrack_helper.h>
27 #include <linux/netfilter/nf_conntrack_ftp.h>
28 
29 #define HELPER_NAME "ftp"
30 
31 MODULE_LICENSE("GPL");
32 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
33 MODULE_DESCRIPTION("ftp connection tracking helper");
34 MODULE_ALIAS("ip_conntrack_ftp");
35 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
36 static DEFINE_SPINLOCK(nf_ftp_lock);
37 
38 #define MAX_PORTS 8
39 static u_int16_t ports[MAX_PORTS];
40 static unsigned int ports_c;
41 module_param_array(ports, ushort, &ports_c, 0400);
42 
43 static bool loose;
44 module_param(loose, bool, 0600);
45 
46 nf_nat_ftp_hook_fn __rcu *nf_nat_ftp_hook;
47 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
48 
49 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
50 		      char, unsigned int *);
51 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
52 		       char, unsigned int *);
53 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
54 		    char, unsigned int *);
55 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
56 			     char, unsigned int *);
57 
58 static struct ftp_search {
59 	const char *pattern;
60 	size_t plen;
61 	char skip;
62 	char term;
63 	enum nf_ct_ftp_type ftptype;
64 	int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
65 } search[IP_CT_DIR_MAX][2] = {
66 	[IP_CT_DIR_ORIGINAL] = {
67 		{
68 			.pattern	= "PORT",
69 			.plen		= sizeof("PORT") - 1,
70 			.skip		= ' ',
71 			.term		= '\r',
72 			.ftptype	= NF_CT_FTP_PORT,
73 			.getnum		= try_rfc959,
74 		},
75 		{
76 			.pattern	= "EPRT",
77 			.plen		= sizeof("EPRT") - 1,
78 			.skip		= ' ',
79 			.term		= '\r',
80 			.ftptype	= NF_CT_FTP_EPRT,
81 			.getnum		= try_eprt,
82 		},
83 	},
84 	[IP_CT_DIR_REPLY] = {
85 		{
86 			.pattern	= "227 ",
87 			.plen		= sizeof("227 ") - 1,
88 			.ftptype	= NF_CT_FTP_PASV,
89 			.getnum		= try_rfc1123,
90 		},
91 		{
92 			.pattern	= "229 ",
93 			.plen		= sizeof("229 ") - 1,
94 			.skip		= '(',
95 			.term		= ')',
96 			.ftptype	= NF_CT_FTP_EPSV,
97 			.getnum		= try_epsv_response,
98 		},
99 	},
100 };
101 
102 static int
103 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
104 {
105 	const char *end;
106 	int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
107 	if (ret > 0)
108 		return (int)(end - src);
109 	return 0;
110 }
111 
112 static int try_number(const char *data, size_t dlen, u_int32_t array[],
113 		      int array_size, char sep, char term)
114 {
115 	u_int32_t i, len;
116 
117 	memset(array, 0, sizeof(array[0])*array_size);
118 
119 	/* Keep data pointing at next char. */
120 	for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
121 		if (*data >= '0' && *data <= '9') {
122 			array[i] = array[i]*10 + *data - '0';
123 		}
124 		else if (*data == sep)
125 			i++;
126 		else {
127 			/* Unexpected character; true if it's the
128 			   terminator (or we don't care about one)
129 			   and we're finished. */
130 			if ((*data == term || !term) && i == array_size - 1)
131 				return len;
132 
133 			pr_debug("Char %u (got %u nums) `%u' unexpected\n",
134 				 len, i, *data);
135 			return 0;
136 		}
137 	}
138 	pr_debug("Failed to fill %u numbers separated by %c\n",
139 		 array_size, sep);
140 	return 0;
141 }
142 
143 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
144 static int try_rfc959(const char *data, size_t dlen,
145 		      struct nf_conntrack_man *cmd, char term,
146 		      unsigned int *offset)
147 {
148 	int length;
149 	u_int32_t array[6];
150 
151 	length = try_number(data, dlen, array, 6, ',', term);
152 	if (length == 0)
153 		return 0;
154 
155 	cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
156 				    (array[2] << 8) | array[3]);
157 	cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
158 	return length;
159 }
160 
161 /*
162  * From RFC 1123:
163  * The format of the 227 reply to a PASV command is not
164  * well standardized.  In particular, an FTP client cannot
165  * assume that the parentheses shown on page 40 of RFC-959
166  * will be present (and in fact, Figure 3 on page 43 omits
167  * them).  Therefore, a User-FTP program that interprets
168  * the PASV reply must scan the reply for the first digit
169  * of the host and port numbers.
170  */
171 static int try_rfc1123(const char *data, size_t dlen,
172 		       struct nf_conntrack_man *cmd, char term,
173 		       unsigned int *offset)
174 {
175 	int i;
176 	for (i = 0; i < dlen; i++)
177 		if (isdigit(data[i]))
178 			break;
179 
180 	if (i == dlen)
181 		return 0;
182 
183 	*offset += i;
184 
185 	return try_rfc959(data + i, dlen - i, cmd, 0, offset);
186 }
187 
188 /* Grab port: number up to delimiter */
189 static int get_port(const char *data, int start, size_t dlen, char delim,
190 		    __be16 *port)
191 {
192 	u_int16_t tmp_port = 0;
193 	int i;
194 
195 	for (i = start; i < dlen; i++) {
196 		/* Finished? */
197 		if (data[i] == delim) {
198 			if (tmp_port == 0)
199 				break;
200 			*port = htons(tmp_port);
201 			pr_debug("get_port: return %d\n", tmp_port);
202 			return i + 1;
203 		}
204 		else if (data[i] >= '0' && data[i] <= '9')
205 			tmp_port = tmp_port*10 + data[i] - '0';
206 		else { /* Some other crap */
207 			pr_debug("get_port: invalid char.\n");
208 			break;
209 		}
210 	}
211 	return 0;
212 }
213 
214 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
215 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
216 		    char term, unsigned int *offset)
217 {
218 	char delim;
219 	int length;
220 
221 	/* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
222 	   then delimiter again. */
223 	if (dlen <= 3) {
224 		pr_debug("EPRT: too short\n");
225 		return 0;
226 	}
227 	delim = data[0];
228 	if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
229 		pr_debug("try_eprt: invalid delimiter.\n");
230 		return 0;
231 	}
232 
233 	if ((cmd->l3num == PF_INET && data[1] != '1') ||
234 	    (cmd->l3num == PF_INET6 && data[1] != '2')) {
235 		pr_debug("EPRT: invalid protocol number.\n");
236 		return 0;
237 	}
238 
239 	pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
240 
241 	if (data[1] == '1') {
242 		u_int32_t array[4];
243 
244 		/* Now we have IP address. */
245 		length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
246 		if (length != 0)
247 			cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
248 					   | (array[2] << 8) | array[3]);
249 	} else {
250 		/* Now we have IPv6 address. */
251 		length = get_ipv6_addr(data + 3, dlen - 3,
252 				       (struct in6_addr *)cmd->u3.ip6, delim);
253 	}
254 
255 	if (length == 0)
256 		return 0;
257 	pr_debug("EPRT: Got IP address!\n");
258 	/* Start offset includes initial "|1|", and trailing delimiter */
259 	return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
260 }
261 
262 /* Returns 0, or length of numbers: |||6446| */
263 static int try_epsv_response(const char *data, size_t dlen,
264 			     struct nf_conntrack_man *cmd, char term,
265 			     unsigned int *offset)
266 {
267 	char delim;
268 
269 	/* Three delimiters. */
270 	if (dlen <= 3) return 0;
271 	delim = data[0];
272 	if (isdigit(delim) || delim < 33 || delim > 126 ||
273 	    data[1] != delim || data[2] != delim)
274 		return 0;
275 
276 	return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
277 }
278 
279 /* Return 1 for match, 0 for accept, -1 for partial. */
280 static int find_pattern(const char *data, size_t dlen,
281 			const char *pattern, size_t plen,
282 			char skip, char term,
283 			unsigned int *numoff,
284 			unsigned int *numlen,
285 			struct nf_conntrack_man *cmd,
286 			int (*getnum)(const char *, size_t,
287 				      struct nf_conntrack_man *, char,
288 				      unsigned int *))
289 {
290 	size_t i = plen;
291 
292 	pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
293 
294 	if (dlen <= plen) {
295 		/* Short packet: try for partial? */
296 		if (strncasecmp(data, pattern, dlen) == 0)
297 			return -1;
298 		else return 0;
299 	}
300 
301 	if (strncasecmp(data, pattern, plen) != 0)
302 		return 0;
303 
304 	pr_debug("Pattern matches!\n");
305 	/* Now we've found the constant string, try to skip
306 	   to the 'skip' character */
307 	if (skip) {
308 		for (i = plen; data[i] != skip; i++)
309 			if (i == dlen - 1) return -1;
310 
311 		/* Skip over the last character */
312 		i++;
313 	}
314 
315 	pr_debug("Skipped up to 0x%hhx delimiter!\n", skip);
316 
317 	*numoff = i;
318 	*numlen = getnum(data + i, dlen - i, cmd, term, numoff);
319 	if (!*numlen)
320 		return -1;
321 
322 	pr_debug("Match succeeded!\n");
323 	return 1;
324 }
325 
326 /* Look up to see if we're just after a \n. */
327 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
328 {
329 	unsigned int i;
330 
331 	for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
332 		if (info->seq_aft_nl[dir][i] == seq)
333 			return 1;
334 	return 0;
335 }
336 
337 /* We don't update if it's older than what we have. */
338 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
339 			  struct nf_ct_ftp_master *info, int dir,
340 			  struct sk_buff *skb)
341 {
342 	unsigned int i, oldest;
343 
344 	/* Look for oldest: if we find exact match, we're done. */
345 	for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
346 		if (info->seq_aft_nl[dir][i] == nl_seq)
347 			return;
348 	}
349 
350 	if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
351 		info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
352 	} else {
353 		if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
354 			oldest = 0;
355 		else
356 			oldest = 1;
357 
358 		if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
359 			info->seq_aft_nl[dir][oldest] = nl_seq;
360 	}
361 }
362 
363 static int help(struct sk_buff *skb,
364 		unsigned int protoff,
365 		struct nf_conn *ct,
366 		enum ip_conntrack_info ctinfo)
367 {
368 	unsigned int dataoff, datalen;
369 	const struct tcphdr *th;
370 	struct tcphdr _tcph;
371 	const char *fb_ptr;
372 	int ret;
373 	u32 seq;
374 	int dir = CTINFO2DIR(ctinfo);
375 	unsigned int matchlen, matchoff;
376 	struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
377 	struct nf_conntrack_expect *exp;
378 	union nf_inet_addr *daddr;
379 	struct nf_conntrack_man cmd = {};
380 	unsigned int i;
381 	int found = 0, ends_in_nl;
382 	nf_nat_ftp_hook_fn *nf_nat_ftp;
383 
384 	/* Until there's been traffic both ways, don't look in packets. */
385 	if (ctinfo != IP_CT_ESTABLISHED &&
386 	    ctinfo != IP_CT_ESTABLISHED_REPLY) {
387 		pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
388 		return NF_ACCEPT;
389 	}
390 
391 	if (unlikely(skb_linearize(skb)))
392 		return NF_DROP;
393 
394 	th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
395 	if (th == NULL)
396 		return NF_ACCEPT;
397 
398 	dataoff = protoff + th->doff * 4;
399 	/* No data? */
400 	if (dataoff >= skb->len) {
401 		pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
402 			 skb->len);
403 		return NF_ACCEPT;
404 	}
405 	datalen = skb->len - dataoff;
406 
407 	/* seqadj (nat) uses ct->lock internally, nf_nat_ftp would cause deadlock */
408 	spin_lock_bh(&nf_ftp_lock);
409 	fb_ptr = skb->data + dataoff;
410 
411 	ends_in_nl = (fb_ptr[datalen - 1] == '\n');
412 	seq = ntohl(th->seq) + datalen;
413 
414 	/* Look up to see if we're just after a \n. */
415 	if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
416 		/* We're picking up this, clear flags and let it continue */
417 		if (unlikely(ct_ftp_info->flags[dir] & NF_CT_FTP_SEQ_PICKUP)) {
418 			ct_ftp_info->flags[dir] ^= NF_CT_FTP_SEQ_PICKUP;
419 			goto skip_nl_seq;
420 		}
421 
422 		/* Now if this ends in \n, update ftp info. */
423 		pr_debug("nf_conntrack_ftp: wrong seq pos %s(%u) or %s(%u)\n",
424 			 ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
425 			 ct_ftp_info->seq_aft_nl[dir][0],
426 			 ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
427 			 ct_ftp_info->seq_aft_nl[dir][1]);
428 		ret = NF_ACCEPT;
429 		goto out_update_nl;
430 	}
431 
432 skip_nl_seq:
433 	/* Initialize IP/IPv6 addr to expected address (it's not mentioned
434 	   in EPSV responses) */
435 	cmd.l3num = nf_ct_l3num(ct);
436 	memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
437 	       sizeof(cmd.u3.all));
438 
439 	for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
440 		found = find_pattern(fb_ptr, datalen,
441 				     search[dir][i].pattern,
442 				     search[dir][i].plen,
443 				     search[dir][i].skip,
444 				     search[dir][i].term,
445 				     &matchoff, &matchlen,
446 				     &cmd,
447 				     search[dir][i].getnum);
448 		if (found) break;
449 	}
450 	if (found == -1) {
451 		/* We don't usually drop packets.  After all, this is
452 		   connection tracking, not packet filtering.
453 		   However, it is necessary for accurate tracking in
454 		   this case. */
455 		nf_ct_helper_log(skb, ct, "partial matching of `%s'",
456 			         search[dir][i].pattern);
457 		ret = NF_DROP;
458 		goto out;
459 	} else if (found == 0) { /* No match */
460 		ret = NF_ACCEPT;
461 		goto out_update_nl;
462 	}
463 
464 	pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
465 		 matchlen, fb_ptr + matchoff,
466 		 matchlen, ntohl(th->seq) + matchoff);
467 
468 	exp = nf_ct_expect_alloc(ct);
469 	if (exp == NULL) {
470 		nf_ct_helper_log(skb, ct, "cannot alloc expectation");
471 		ret = NF_DROP;
472 		goto out;
473 	}
474 
475 	/* We refer to the reverse direction ("!dir") tuples here,
476 	 * because we're expecting something in the other direction.
477 	 * Doesn't matter unless NAT is happening.  */
478 	daddr = &ct->tuplehash[!dir].tuple.dst.u3;
479 
480 	/* Update the ftp info */
481 	if ((cmd.l3num == nf_ct_l3num(ct)) &&
482 	    memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
483 		     sizeof(cmd.u3.all))) {
484 		/* Enrico Scholz's passive FTP to partially RNAT'd ftp
485 		   server: it really wants us to connect to a
486 		   different IP address.  Simply don't record it for
487 		   NAT. */
488 		if (cmd.l3num == PF_INET) {
489 			pr_debug("NOT RECORDING: %pI4 != %pI4\n",
490 				 &cmd.u3.ip,
491 				 &ct->tuplehash[dir].tuple.src.u3.ip);
492 		} else {
493 			pr_debug("NOT RECORDING: %pI6 != %pI6\n",
494 				 cmd.u3.ip6,
495 				 ct->tuplehash[dir].tuple.src.u3.ip6);
496 		}
497 
498 		/* Thanks to Cristiano Lincoln Mattos
499 		   <lincoln@cesar.org.br> for reporting this potential
500 		   problem (DMZ machines opening holes to internal
501 		   networks, or the packet filter itself). */
502 		if (!loose) {
503 			ret = NF_ACCEPT;
504 			goto out_put_expect;
505 		}
506 		daddr = &cmd.u3;
507 	}
508 
509 	nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, cmd.l3num,
510 			  &ct->tuplehash[!dir].tuple.src.u3, daddr,
511 			  IPPROTO_TCP, NULL, &cmd.u.tcp.port);
512 
513 	/* Now, NAT might want to mangle the packet, and register the
514 	 * (possibly changed) expectation itself. */
515 	nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
516 	if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
517 		ret = nf_nat_ftp(skb, ctinfo, search[dir][i].ftptype,
518 				 protoff, matchoff, matchlen, exp);
519 	else {
520 		/* Can't expect this?  Best to drop packet now. */
521 		if (nf_ct_expect_related(exp, 0) != 0) {
522 			nf_ct_helper_log(skb, ct, "cannot add expectation");
523 			ret = NF_DROP;
524 		} else
525 			ret = NF_ACCEPT;
526 	}
527 
528 out_put_expect:
529 	nf_ct_expect_put(exp);
530 
531 out_update_nl:
532 	/* Now if this ends in \n, update ftp info.  Seq may have been
533 	 * adjusted by NAT code. */
534 	if (ends_in_nl)
535 		update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
536  out:
537 	spin_unlock_bh(&nf_ftp_lock);
538 	return ret;
539 }
540 
541 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
542 {
543 	struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
544 
545 	/* This conntrack has been injected from user-space, always pick up
546 	 * sequence tracking. Otherwise, the first FTP command after the
547 	 * failover breaks.
548 	 */
549 	ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
550 	ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
551 	return 0;
552 }
553 
554 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
555 
556 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
557 	.max_expected	= 1,
558 	.timeout	= 5 * 60,
559 };
560 
561 static void __exit nf_conntrack_ftp_fini(void)
562 {
563 	nf_conntrack_helpers_unregister(ftp, ports_c * 2);
564 }
565 
566 static int __init nf_conntrack_ftp_init(void)
567 {
568 	int i, ret = 0;
569 
570 	NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
571 
572 	if (ports_c == 0)
573 		ports[ports_c++] = FTP_PORT;
574 
575 	/* FIXME should be configurable whether IPv4 and IPv6 FTP connections
576 		 are tracked or not - YK */
577 	for (i = 0; i < ports_c; i++) {
578 		nf_ct_helper_init(&ftp[2 * i], AF_INET, IPPROTO_TCP,
579 				  HELPER_NAME, FTP_PORT, ports[i], ports[i],
580 				  &ftp_exp_policy, 0, help,
581 				  nf_ct_ftp_from_nlattr, THIS_MODULE);
582 		nf_ct_helper_init(&ftp[2 * i + 1], AF_INET6, IPPROTO_TCP,
583 				  HELPER_NAME, FTP_PORT, ports[i], ports[i],
584 				  &ftp_exp_policy, 0, help,
585 				  nf_ct_ftp_from_nlattr, THIS_MODULE);
586 	}
587 
588 	ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
589 	if (ret < 0) {
590 		pr_err("failed to register helpers\n");
591 		return ret;
592 	}
593 
594 	return 0;
595 }
596 
597 module_init(nf_conntrack_ftp_init);
598 module_exit(nf_conntrack_ftp_fini);
599