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