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 	if (!fb_ptr) {
417 		spin_unlock_bh(&nf_ftp_lock);
418 		return NF_ACCEPT;
419 	}
420 
421 	ends_in_nl = (fb_ptr[datalen - 1] == '\n');
422 	seq = ntohl(th->seq) + datalen;
423 
424 	/* Look up to see if we're just after a \n. */
425 	if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
426 		/* We're picking up this, clear flags and let it continue */
427 		if (unlikely(ct_ftp_info->flags[dir] & NF_CT_FTP_SEQ_PICKUP)) {
428 			ct_ftp_info->flags[dir] ^= NF_CT_FTP_SEQ_PICKUP;
429 			goto skip_nl_seq;
430 		}
431 
432 		/* Now if this ends in \n, update ftp info. */
433 		pr_debug("nf_conntrack_ftp: wrong seq pos %s(%u) or %s(%u)\n",
434 			 ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
435 			 ct_ftp_info->seq_aft_nl[dir][0],
436 			 ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
437 			 ct_ftp_info->seq_aft_nl[dir][1]);
438 		ret = NF_ACCEPT;
439 		goto out_update_nl;
440 	}
441 
442 skip_nl_seq:
443 	/* Initialize IP/IPv6 addr to expected address (it's not mentioned
444 	   in EPSV responses) */
445 	cmd.l3num = nf_ct_l3num(ct);
446 	memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
447 	       sizeof(cmd.u3.all));
448 
449 	for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
450 		found = find_pattern(fb_ptr, datalen,
451 				     search[dir][i].pattern,
452 				     search[dir][i].plen,
453 				     search[dir][i].skip,
454 				     search[dir][i].term,
455 				     &matchoff, &matchlen,
456 				     &cmd,
457 				     search[dir][i].getnum);
458 		if (found) break;
459 	}
460 	if (found == -1) {
461 		/* We don't usually drop packets.  After all, this is
462 		   connection tracking, not packet filtering.
463 		   However, it is necessary for accurate tracking in
464 		   this case. */
465 		nf_ct_helper_log(skb, ct, "partial matching of `%s'",
466 			         search[dir][i].pattern);
467 		ret = NF_DROP;
468 		goto out;
469 	} else if (found == 0) { /* No match */
470 		ret = NF_ACCEPT;
471 		goto out_update_nl;
472 	}
473 
474 	pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
475 		 matchlen, fb_ptr + matchoff,
476 		 matchlen, ntohl(th->seq) + matchoff);
477 
478 	exp = nf_ct_expect_alloc(ct);
479 	if (exp == NULL) {
480 		nf_ct_helper_log(skb, ct, "cannot alloc expectation");
481 		ret = NF_DROP;
482 		goto out;
483 	}
484 
485 	/* We refer to the reverse direction ("!dir") tuples here,
486 	 * because we're expecting something in the other direction.
487 	 * Doesn't matter unless NAT is happening.  */
488 	daddr = &ct->tuplehash[!dir].tuple.dst.u3;
489 
490 	/* Update the ftp info */
491 	if ((cmd.l3num == nf_ct_l3num(ct)) &&
492 	    memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
493 		     sizeof(cmd.u3.all))) {
494 		/* Enrico Scholz's passive FTP to partially RNAT'd ftp
495 		   server: it really wants us to connect to a
496 		   different IP address.  Simply don't record it for
497 		   NAT. */
498 		if (cmd.l3num == PF_INET) {
499 			pr_debug("NOT RECORDING: %pI4 != %pI4\n",
500 				 &cmd.u3.ip,
501 				 &ct->tuplehash[dir].tuple.src.u3.ip);
502 		} else {
503 			pr_debug("NOT RECORDING: %pI6 != %pI6\n",
504 				 cmd.u3.ip6,
505 				 ct->tuplehash[dir].tuple.src.u3.ip6);
506 		}
507 
508 		/* Thanks to Cristiano Lincoln Mattos
509 		   <lincoln@cesar.org.br> for reporting this potential
510 		   problem (DMZ machines opening holes to internal
511 		   networks, or the packet filter itself). */
512 		if (!loose) {
513 			ret = NF_ACCEPT;
514 			goto out_put_expect;
515 		}
516 		daddr = &cmd.u3;
517 	}
518 
519 	nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, cmd.l3num,
520 			  &ct->tuplehash[!dir].tuple.src.u3, daddr,
521 			  IPPROTO_TCP, NULL, &cmd.u.tcp.port);
522 
523 	/* Now, NAT might want to mangle the packet, and register the
524 	 * (possibly changed) expectation itself. */
525 	nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
526 	if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
527 		ret = nf_nat_ftp(skb, ctinfo, search[dir][i].ftptype,
528 				 protoff, matchoff, matchlen, exp);
529 	else {
530 		/* Can't expect this?  Best to drop packet now. */
531 		if (nf_ct_expect_related(exp, 0) != 0) {
532 			nf_ct_helper_log(skb, ct, "cannot add expectation");
533 			ret = NF_DROP;
534 		} else
535 			ret = NF_ACCEPT;
536 	}
537 
538 out_put_expect:
539 	nf_ct_expect_put(exp);
540 
541 out_update_nl:
542 	/* Now if this ends in \n, update ftp info.  Seq may have been
543 	 * adjusted by NAT code. */
544 	if (ends_in_nl)
545 		update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
546  out:
547 	spin_unlock_bh(&nf_ftp_lock);
548 	return ret;
549 }
550 
551 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
552 {
553 	struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
554 
555 	/* This conntrack has been injected from user-space, always pick up
556 	 * sequence tracking. Otherwise, the first FTP command after the
557 	 * failover breaks.
558 	 */
559 	ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
560 	ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
561 	return 0;
562 }
563 
564 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
565 
566 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
567 	.max_expected	= 1,
568 	.timeout	= 5 * 60,
569 };
570 
571 static void __exit nf_conntrack_ftp_fini(void)
572 {
573 	nf_conntrack_helpers_unregister(ftp, ports_c * 2);
574 	kfree(ftp_buffer);
575 }
576 
577 static int __init nf_conntrack_ftp_init(void)
578 {
579 	int i, ret = 0;
580 
581 	NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
582 
583 	ftp_buffer = kmalloc(65536, GFP_KERNEL);
584 	if (!ftp_buffer)
585 		return -ENOMEM;
586 
587 	if (ports_c == 0)
588 		ports[ports_c++] = FTP_PORT;
589 
590 	/* FIXME should be configurable whether IPv4 and IPv6 FTP connections
591 		 are tracked or not - YK */
592 	for (i = 0; i < ports_c; i++) {
593 		nf_ct_helper_init(&ftp[2 * i], AF_INET, IPPROTO_TCP,
594 				  HELPER_NAME, FTP_PORT, ports[i], ports[i],
595 				  &ftp_exp_policy, 0, help,
596 				  nf_ct_ftp_from_nlattr, THIS_MODULE);
597 		nf_ct_helper_init(&ftp[2 * i + 1], AF_INET6, IPPROTO_TCP,
598 				  HELPER_NAME, FTP_PORT, ports[i], ports[i],
599 				  &ftp_exp_policy, 0, help,
600 				  nf_ct_ftp_from_nlattr, THIS_MODULE);
601 	}
602 
603 	ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
604 	if (ret < 0) {
605 		pr_err("failed to register helpers\n");
606 		kfree(ftp_buffer);
607 		return ret;
608 	}
609 
610 	return 0;
611 }
612 
613 module_init(nf_conntrack_ftp_init);
614 module_exit(nf_conntrack_ftp_fini);
615