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