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