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