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