1 /* FTP extension for connection tracking. */
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>
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.
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 #include <linux/module.h>
16 #include <linux/moduleparam.h>
17 #include <linux/netfilter.h>
19 #include <linux/slab.h>
20 #include <linux/ipv6.h>
21 #include <linux/ctype.h>
22 #include <linux/inet.h>
23 #include <net/checksum.h>
26 #include <net/netfilter/nf_conntrack.h>
27 #include <net/netfilter/nf_conntrack_expect.h>
28 #include <net/netfilter/nf_conntrack_ecache.h>
29 #include <net/netfilter/nf_conntrack_helper.h>
30 #include <linux/netfilter/nf_conntrack_ftp.h>
32 #define HELPER_NAME "ftp"
34 MODULE_LICENSE("GPL");
35 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
36 MODULE_DESCRIPTION("ftp connection tracking helper");
37 MODULE_ALIAS("ip_conntrack_ftp");
38 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
40 /* This is slow, but it's simple. --RR */
41 static char *ftp_buffer;
43 static DEFINE_SPINLOCK(nf_ftp_lock);
46 static u_int16_t ports[MAX_PORTS];
47 static unsigned int ports_c;
48 module_param_array(ports, ushort, &ports_c, 0400);
51 module_param(loose, bool, 0600);
53 unsigned int (*nf_nat_ftp_hook)(struct sk_buff *skb,
54 enum ip_conntrack_info ctinfo,
55 enum nf_ct_ftp_type type,
57 unsigned int matchoff,
58 unsigned int matchlen,
59 struct nf_conntrack_expect *exp);
60 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
62 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
63 char, unsigned int *);
64 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
65 char, unsigned int *);
66 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
67 char, unsigned int *);
68 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
69 char, unsigned int *);
71 static struct ftp_search {
76 enum nf_ct_ftp_type ftptype;
77 int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
78 } search[IP_CT_DIR_MAX][2] = {
79 [IP_CT_DIR_ORIGINAL] = {
82 .plen = sizeof("PORT") - 1,
85 .ftptype = NF_CT_FTP_PORT,
90 .plen = sizeof("EPRT") - 1,
93 .ftptype = NF_CT_FTP_EPRT,
100 .plen = sizeof("227 ") - 1,
101 .ftptype = NF_CT_FTP_PASV,
102 .getnum = try_rfc1123,
106 .plen = sizeof("229 ") - 1,
109 .ftptype = NF_CT_FTP_EPSV,
110 .getnum = try_epsv_response,
116 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
119 int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
121 return (int)(end - src);
125 static int try_number(const char *data, size_t dlen, u_int32_t array[],
126 int array_size, char sep, char term)
130 memset(array, 0, sizeof(array[0])*array_size);
132 /* Keep data pointing at next char. */
133 for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
134 if (*data >= '0' && *data <= '9') {
135 array[i] = array[i]*10 + *data - '0';
137 else if (*data == sep)
140 /* Unexpected character; true if it's the
141 terminator (or we don't care about one)
142 and we're finished. */
143 if ((*data == term || !term) && i == array_size - 1)
146 pr_debug("Char %u (got %u nums) `%u' unexpected\n",
151 pr_debug("Failed to fill %u numbers separated by %c\n",
156 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
157 static int try_rfc959(const char *data, size_t dlen,
158 struct nf_conntrack_man *cmd, char term,
159 unsigned int *offset)
164 length = try_number(data, dlen, array, 6, ',', term);
168 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
169 (array[2] << 8) | array[3]);
170 cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
176 * The format of the 227 reply to a PASV command is not
177 * well standardized. In particular, an FTP client cannot
178 * assume that the parentheses shown on page 40 of RFC-959
179 * will be present (and in fact, Figure 3 on page 43 omits
180 * them). Therefore, a User-FTP program that interprets
181 * the PASV reply must scan the reply for the first digit
182 * of the host and port numbers.
184 static int try_rfc1123(const char *data, size_t dlen,
185 struct nf_conntrack_man *cmd, char term,
186 unsigned int *offset)
189 for (i = 0; i < dlen; i++)
190 if (isdigit(data[i]))
198 return try_rfc959(data + i, dlen - i, cmd, 0, offset);
201 /* Grab port: number up to delimiter */
202 static int get_port(const char *data, int start, size_t dlen, char delim,
205 u_int16_t tmp_port = 0;
208 for (i = start; i < dlen; i++) {
210 if (data[i] == delim) {
213 *port = htons(tmp_port);
214 pr_debug("get_port: return %d\n", tmp_port);
217 else if (data[i] >= '0' && data[i] <= '9')
218 tmp_port = tmp_port*10 + data[i] - '0';
219 else { /* Some other crap */
220 pr_debug("get_port: invalid char.\n");
227 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
228 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
229 char term, unsigned int *offset)
234 /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
235 then delimiter again. */
237 pr_debug("EPRT: too short\n");
241 if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
242 pr_debug("try_eprt: invalid delimiter.\n");
246 if ((cmd->l3num == PF_INET && data[1] != '1') ||
247 (cmd->l3num == PF_INET6 && data[1] != '2')) {
248 pr_debug("EPRT: invalid protocol number.\n");
252 pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
254 if (data[1] == '1') {
257 /* Now we have IP address. */
258 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
260 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
261 | (array[2] << 8) | array[3]);
263 /* Now we have IPv6 address. */
264 length = get_ipv6_addr(data + 3, dlen - 3,
265 (struct in6_addr *)cmd->u3.ip6, delim);
270 pr_debug("EPRT: Got IP address!\n");
271 /* Start offset includes initial "|1|", and trailing delimiter */
272 return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
275 /* Returns 0, or length of numbers: |||6446| */
276 static int try_epsv_response(const char *data, size_t dlen,
277 struct nf_conntrack_man *cmd, char term,
278 unsigned int *offset)
282 /* Three delimiters. */
283 if (dlen <= 3) return 0;
285 if (isdigit(delim) || delim < 33 || delim > 126 ||
286 data[1] != delim || data[2] != delim)
289 return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
292 /* Return 1 for match, 0 for accept, -1 for partial. */
293 static int find_pattern(const char *data, size_t dlen,
294 const char *pattern, size_t plen,
295 char skip, char term,
296 unsigned int *numoff,
297 unsigned int *numlen,
298 struct nf_conntrack_man *cmd,
299 int (*getnum)(const char *, size_t,
300 struct nf_conntrack_man *, char,
305 pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
308 /* Short packet: try for partial? */
309 if (strncasecmp(data, pattern, dlen) == 0)
314 if (strncasecmp(data, pattern, plen) != 0)
317 pr_debug("Pattern matches!\n");
318 /* Now we've found the constant string, try to skip
319 to the 'skip' character */
321 for (i = plen; data[i] != skip; i++)
322 if (i == dlen - 1) return -1;
324 /* Skip over the last character */
328 pr_debug("Skipped up to `%c'!\n", skip);
331 *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
335 pr_debug("Match succeeded!\n");
339 /* Look up to see if we're just after a \n. */
340 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
344 for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
345 if (info->seq_aft_nl[dir][i] == seq)
350 /* We don't update if it's older than what we have. */
351 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
352 struct nf_ct_ftp_master *info, int dir,
355 unsigned int i, oldest;
357 /* Look for oldest: if we find exact match, we're done. */
358 for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
359 if (info->seq_aft_nl[dir][i] == nl_seq)
363 if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
364 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
366 if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
371 if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
372 info->seq_aft_nl[dir][oldest] = nl_seq;
376 static int help(struct sk_buff *skb,
377 unsigned int protoff,
379 enum ip_conntrack_info ctinfo)
381 unsigned int dataoff, datalen;
382 const struct tcphdr *th;
387 int dir = CTINFO2DIR(ctinfo);
388 unsigned int uninitialized_var(matchlen), uninitialized_var(matchoff);
389 struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
390 struct nf_conntrack_expect *exp;
391 union nf_inet_addr *daddr;
392 struct nf_conntrack_man cmd = {};
394 int found = 0, ends_in_nl;
395 typeof(nf_nat_ftp_hook) nf_nat_ftp;
397 /* Until there's been traffic both ways, don't look in packets. */
398 if (ctinfo != IP_CT_ESTABLISHED &&
399 ctinfo != IP_CT_ESTABLISHED_REPLY) {
400 pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
404 th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
408 dataoff = protoff + th->doff * 4;
410 if (dataoff >= skb->len) {
411 pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
415 datalen = skb->len - dataoff;
417 spin_lock_bh(&nf_ftp_lock);
418 fb_ptr = skb_header_pointer(skb, dataoff, datalen, ftp_buffer);
419 BUG_ON(fb_ptr == NULL);
421 ends_in_nl = (fb_ptr[datalen - 1] == '\n');
422 seq = ntohl(th->seq) + datalen;
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;
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]);
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,
449 for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
450 found = find_pattern(fb_ptr, datalen,
451 search[dir][i].pattern,
455 &matchoff, &matchlen,
457 search[dir][i].getnum);
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
465 nf_ct_helper_log(skb, ct, "partial matching of `%s'",
466 search[dir][i].pattern);
469 } else if (found == 0) { /* No match */
474 pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
475 matchlen, fb_ptr + matchoff,
476 matchlen, ntohl(th->seq) + matchoff);
478 exp = nf_ct_expect_alloc(ct);
480 nf_ct_helper_log(skb, ct, "cannot alloc expectation");
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;
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
498 if (cmd.l3num == PF_INET) {
499 pr_debug("NOT RECORDING: %pI4 != %pI4\n",
501 &ct->tuplehash[dir].tuple.src.u3.ip);
503 pr_debug("NOT RECORDING: %pI6 != %pI6\n",
505 ct->tuplehash[dir].tuple.src.u3.ip6);
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). */
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);
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);
530 /* Can't expect this? Best to drop packet now. */
531 if (nf_ct_expect_related(exp) != 0) {
532 nf_ct_helper_log(skb, ct, "cannot add expectation");
539 nf_ct_expect_put(exp);
542 /* Now if this ends in \n, update ftp info. Seq may have been
543 * adjusted by NAT code. */
545 update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
547 spin_unlock_bh(&nf_ftp_lock);
551 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
553 struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
555 /* This conntrack has been injected from user-space, always pick up
556 * sequence tracking. Otherwise, the first FTP command after the
559 ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
560 ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
564 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
566 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
571 static void __exit nf_conntrack_ftp_fini(void)
573 nf_conntrack_helpers_unregister(ftp, ports_c * 2);
577 static int __init nf_conntrack_ftp_init(void)
581 NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
583 ftp_buffer = kmalloc(65536, GFP_KERNEL);
588 ports[ports_c++] = FTP_PORT;
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);
603 ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
605 pr_err("failed to register helpers\n");
613 module_init(nf_conntrack_ftp_init);
614 module_exit(nf_conntrack_ftp_fini);