1 // SPDX-License-Identifier: GPL-2.0-only
2 /* FTP extension for connection tracking. */
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>
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/netfilter.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>
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>
29 #define HELPER_NAME "ftp"
31 MODULE_LICENSE("GPL");
32 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
33 MODULE_DESCRIPTION("ftp connection tracking helper");
34 MODULE_ALIAS("ip_conntrack_ftp");
35 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
37 /* This is slow, but it's simple. --RR */
38 static char *ftp_buffer;
40 static DEFINE_SPINLOCK(nf_ftp_lock);
43 static u_int16_t ports[MAX_PORTS];
44 static unsigned int ports_c;
45 module_param_array(ports, ushort, &ports_c, 0400);
48 module_param(loose, bool, 0600);
50 unsigned int (*nf_nat_ftp_hook)(struct sk_buff *skb,
51 enum ip_conntrack_info ctinfo,
52 enum nf_ct_ftp_type type,
54 unsigned int matchoff,
55 unsigned int matchlen,
56 struct nf_conntrack_expect *exp);
57 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
59 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
60 char, unsigned int *);
61 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
62 char, unsigned int *);
63 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
64 char, unsigned int *);
65 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
66 char, unsigned int *);
68 static struct ftp_search {
73 enum nf_ct_ftp_type ftptype;
74 int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
75 } search[IP_CT_DIR_MAX][2] = {
76 [IP_CT_DIR_ORIGINAL] = {
79 .plen = sizeof("PORT") - 1,
82 .ftptype = NF_CT_FTP_PORT,
87 .plen = sizeof("EPRT") - 1,
90 .ftptype = NF_CT_FTP_EPRT,
97 .plen = sizeof("227 ") - 1,
98 .ftptype = NF_CT_FTP_PASV,
99 .getnum = try_rfc1123,
103 .plen = sizeof("229 ") - 1,
106 .ftptype = NF_CT_FTP_EPSV,
107 .getnum = try_epsv_response,
113 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
116 int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
118 return (int)(end - src);
122 static int try_number(const char *data, size_t dlen, u_int32_t array[],
123 int array_size, char sep, char term)
127 memset(array, 0, sizeof(array[0])*array_size);
129 /* Keep data pointing at next char. */
130 for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
131 if (*data >= '0' && *data <= '9') {
132 array[i] = array[i]*10 + *data - '0';
134 else if (*data == sep)
137 /* Unexpected character; true if it's the
138 terminator (or we don't care about one)
139 and we're finished. */
140 if ((*data == term || !term) && i == array_size - 1)
143 pr_debug("Char %u (got %u nums) `%u' unexpected\n",
148 pr_debug("Failed to fill %u numbers separated by %c\n",
153 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
154 static int try_rfc959(const char *data, size_t dlen,
155 struct nf_conntrack_man *cmd, char term,
156 unsigned int *offset)
161 length = try_number(data, dlen, array, 6, ',', term);
165 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
166 (array[2] << 8) | array[3]);
167 cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
173 * The format of the 227 reply to a PASV command is not
174 * well standardized. In particular, an FTP client cannot
175 * assume that the parentheses shown on page 40 of RFC-959
176 * will be present (and in fact, Figure 3 on page 43 omits
177 * them). Therefore, a User-FTP program that interprets
178 * the PASV reply must scan the reply for the first digit
179 * of the host and port numbers.
181 static int try_rfc1123(const char *data, size_t dlen,
182 struct nf_conntrack_man *cmd, char term,
183 unsigned int *offset)
186 for (i = 0; i < dlen; i++)
187 if (isdigit(data[i]))
195 return try_rfc959(data + i, dlen - i, cmd, 0, offset);
198 /* Grab port: number up to delimiter */
199 static int get_port(const char *data, int start, size_t dlen, char delim,
202 u_int16_t tmp_port = 0;
205 for (i = start; i < dlen; i++) {
207 if (data[i] == delim) {
210 *port = htons(tmp_port);
211 pr_debug("get_port: return %d\n", tmp_port);
214 else if (data[i] >= '0' && data[i] <= '9')
215 tmp_port = tmp_port*10 + data[i] - '0';
216 else { /* Some other crap */
217 pr_debug("get_port: invalid char.\n");
224 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
225 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
226 char term, unsigned int *offset)
231 /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
232 then delimiter again. */
234 pr_debug("EPRT: too short\n");
238 if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
239 pr_debug("try_eprt: invalid delimiter.\n");
243 if ((cmd->l3num == PF_INET && data[1] != '1') ||
244 (cmd->l3num == PF_INET6 && data[1] != '2')) {
245 pr_debug("EPRT: invalid protocol number.\n");
249 pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
251 if (data[1] == '1') {
254 /* Now we have IP address. */
255 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
257 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
258 | (array[2] << 8) | array[3]);
260 /* Now we have IPv6 address. */
261 length = get_ipv6_addr(data + 3, dlen - 3,
262 (struct in6_addr *)cmd->u3.ip6, delim);
267 pr_debug("EPRT: Got IP address!\n");
268 /* Start offset includes initial "|1|", and trailing delimiter */
269 return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
272 /* Returns 0, or length of numbers: |||6446| */
273 static int try_epsv_response(const char *data, size_t dlen,
274 struct nf_conntrack_man *cmd, char term,
275 unsigned int *offset)
279 /* Three delimiters. */
280 if (dlen <= 3) return 0;
282 if (isdigit(delim) || delim < 33 || delim > 126 ||
283 data[1] != delim || data[2] != delim)
286 return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
289 /* Return 1 for match, 0 for accept, -1 for partial. */
290 static int find_pattern(const char *data, size_t dlen,
291 const char *pattern, size_t plen,
292 char skip, char term,
293 unsigned int *numoff,
294 unsigned int *numlen,
295 struct nf_conntrack_man *cmd,
296 int (*getnum)(const char *, size_t,
297 struct nf_conntrack_man *, char,
302 pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
305 /* Short packet: try for partial? */
306 if (strncasecmp(data, pattern, dlen) == 0)
311 if (strncasecmp(data, pattern, plen) != 0)
314 pr_debug("Pattern matches!\n");
315 /* Now we've found the constant string, try to skip
316 to the 'skip' character */
318 for (i = plen; data[i] != skip; i++)
319 if (i == dlen - 1) return -1;
321 /* Skip over the last character */
325 pr_debug("Skipped up to 0x%hhx delimiter!\n", skip);
328 *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
332 pr_debug("Match succeeded!\n");
336 /* Look up to see if we're just after a \n. */
337 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
341 for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
342 if (info->seq_aft_nl[dir][i] == seq)
347 /* We don't update if it's older than what we have. */
348 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
349 struct nf_ct_ftp_master *info, int dir,
352 unsigned int i, oldest;
354 /* Look for oldest: if we find exact match, we're done. */
355 for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
356 if (info->seq_aft_nl[dir][i] == nl_seq)
360 if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
361 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
363 if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
368 if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
369 info->seq_aft_nl[dir][oldest] = nl_seq;
373 static int help(struct sk_buff *skb,
374 unsigned int protoff,
376 enum ip_conntrack_info ctinfo)
378 unsigned int dataoff, datalen;
379 const struct tcphdr *th;
384 int dir = CTINFO2DIR(ctinfo);
385 unsigned int matchlen, matchoff;
386 struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
387 struct nf_conntrack_expect *exp;
388 union nf_inet_addr *daddr;
389 struct nf_conntrack_man cmd = {};
391 int found = 0, ends_in_nl;
392 typeof(nf_nat_ftp_hook) nf_nat_ftp;
394 /* Until there's been traffic both ways, don't look in packets. */
395 if (ctinfo != IP_CT_ESTABLISHED &&
396 ctinfo != IP_CT_ESTABLISHED_REPLY) {
397 pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
401 th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
405 dataoff = protoff + th->doff * 4;
407 if (dataoff >= skb->len) {
408 pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
412 datalen = skb->len - dataoff;
414 spin_lock_bh(&nf_ftp_lock);
415 fb_ptr = skb_header_pointer(skb, dataoff, datalen, ftp_buffer);
417 spin_unlock_bh(&nf_ftp_lock);
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) != 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);