1 // SPDX-License-Identifier: GPL-2.0-only
2 /* FTP extension for connection tracking. */
4 /* (C) 1999-2001 Paul `Rusty' Russell
6 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
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");
33 MODULE_DESCRIPTION("ftp connection tracking helper");
34 MODULE_ALIAS("ip_conntrack_ftp");
35 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
36 static DEFINE_SPINLOCK(nf_ftp_lock);
39 static u_int16_t ports[MAX_PORTS];
40 static unsigned int ports_c;
41 module_param_array(ports, ushort, &ports_c, 0400);
44 module_param(loose, bool, 0600);
46 unsigned int (*nf_nat_ftp_hook)(struct sk_buff *skb,
47 enum ip_conntrack_info ctinfo,
48 enum nf_ct_ftp_type type,
50 unsigned int matchoff,
51 unsigned int matchlen,
52 struct nf_conntrack_expect *exp);
53 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
55 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
56 char, unsigned int *);
57 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
58 char, unsigned int *);
59 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
60 char, unsigned int *);
61 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
62 char, unsigned int *);
64 static struct ftp_search {
69 enum nf_ct_ftp_type ftptype;
70 int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
71 } search[IP_CT_DIR_MAX][2] = {
72 [IP_CT_DIR_ORIGINAL] = {
75 .plen = sizeof("PORT") - 1,
78 .ftptype = NF_CT_FTP_PORT,
83 .plen = sizeof("EPRT") - 1,
86 .ftptype = NF_CT_FTP_EPRT,
93 .plen = sizeof("227 ") - 1,
94 .ftptype = NF_CT_FTP_PASV,
95 .getnum = try_rfc1123,
99 .plen = sizeof("229 ") - 1,
102 .ftptype = NF_CT_FTP_EPSV,
103 .getnum = try_epsv_response,
109 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
112 int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
114 return (int)(end - src);
118 static int try_number(const char *data, size_t dlen, u_int32_t array[],
119 int array_size, char sep, char term)
123 memset(array, 0, sizeof(array[0])*array_size);
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';
130 else if (*data == sep)
133 /* Unexpected character; true if it's the
134 terminator (or we don't care about one)
135 and we're finished. */
136 if ((*data == term || !term) && i == array_size - 1)
139 pr_debug("Char %u (got %u nums) `%u' unexpected\n",
144 pr_debug("Failed to fill %u numbers separated by %c\n",
149 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
150 static int try_rfc959(const char *data, size_t dlen,
151 struct nf_conntrack_man *cmd, char term,
152 unsigned int *offset)
157 length = try_number(data, dlen, array, 6, ',', term);
161 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
162 (array[2] << 8) | array[3]);
163 cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
169 * The format of the 227 reply to a PASV command is not
170 * well standardized. In particular, an FTP client cannot
171 * assume that the parentheses shown on page 40 of RFC-959
172 * will be present (and in fact, Figure 3 on page 43 omits
173 * them). Therefore, a User-FTP program that interprets
174 * the PASV reply must scan the reply for the first digit
175 * of the host and port numbers.
177 static int try_rfc1123(const char *data, size_t dlen,
178 struct nf_conntrack_man *cmd, char term,
179 unsigned int *offset)
182 for (i = 0; i < dlen; i++)
183 if (isdigit(data[i]))
191 return try_rfc959(data + i, dlen - i, cmd, 0, offset);
194 /* Grab port: number up to delimiter */
195 static int get_port(const char *data, int start, size_t dlen, char delim,
198 u_int16_t tmp_port = 0;
201 for (i = start; i < dlen; i++) {
203 if (data[i] == delim) {
206 *port = htons(tmp_port);
207 pr_debug("get_port: return %d\n", tmp_port);
210 else if (data[i] >= '0' && data[i] <= '9')
211 tmp_port = tmp_port*10 + data[i] - '0';
212 else { /* Some other crap */
213 pr_debug("get_port: invalid char.\n");
220 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
221 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
222 char term, unsigned int *offset)
227 /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
228 then delimiter again. */
230 pr_debug("EPRT: too short\n");
234 if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
235 pr_debug("try_eprt: invalid delimiter.\n");
239 if ((cmd->l3num == PF_INET && data[1] != '1') ||
240 (cmd->l3num == PF_INET6 && data[1] != '2')) {
241 pr_debug("EPRT: invalid protocol number.\n");
245 pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
247 if (data[1] == '1') {
250 /* Now we have IP address. */
251 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
253 cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
254 | (array[2] << 8) | array[3]);
256 /* Now we have IPv6 address. */
257 length = get_ipv6_addr(data + 3, dlen - 3,
258 (struct in6_addr *)cmd->u3.ip6, delim);
263 pr_debug("EPRT: Got IP address!\n");
264 /* Start offset includes initial "|1|", and trailing delimiter */
265 return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
268 /* Returns 0, or length of numbers: |||6446| */
269 static int try_epsv_response(const char *data, size_t dlen,
270 struct nf_conntrack_man *cmd, char term,
271 unsigned int *offset)
275 /* Three delimiters. */
276 if (dlen <= 3) return 0;
278 if (isdigit(delim) || delim < 33 || delim > 126 ||
279 data[1] != delim || data[2] != delim)
282 return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
285 /* Return 1 for match, 0 for accept, -1 for partial. */
286 static int find_pattern(const char *data, size_t dlen,
287 const char *pattern, size_t plen,
288 char skip, char term,
289 unsigned int *numoff,
290 unsigned int *numlen,
291 struct nf_conntrack_man *cmd,
292 int (*getnum)(const char *, size_t,
293 struct nf_conntrack_man *, char,
298 pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
301 /* Short packet: try for partial? */
302 if (strncasecmp(data, pattern, dlen) == 0)
307 if (strncasecmp(data, pattern, plen) != 0)
310 pr_debug("Pattern matches!\n");
311 /* Now we've found the constant string, try to skip
312 to the 'skip' character */
314 for (i = plen; data[i] != skip; i++)
315 if (i == dlen - 1) return -1;
317 /* Skip over the last character */
321 pr_debug("Skipped up to 0x%hhx delimiter!\n", skip);
324 *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
328 pr_debug("Match succeeded!\n");
332 /* Look up to see if we're just after a \n. */
333 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
337 for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
338 if (info->seq_aft_nl[dir][i] == seq)
343 /* We don't update if it's older than what we have. */
344 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
345 struct nf_ct_ftp_master *info, int dir,
348 unsigned int i, oldest;
350 /* Look for oldest: if we find exact match, we're done. */
351 for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
352 if (info->seq_aft_nl[dir][i] == nl_seq)
356 if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
357 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
359 if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
364 if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
365 info->seq_aft_nl[dir][oldest] = nl_seq;
369 static int help(struct sk_buff *skb,
370 unsigned int protoff,
372 enum ip_conntrack_info ctinfo)
374 unsigned int dataoff, datalen;
375 const struct tcphdr *th;
380 int dir = CTINFO2DIR(ctinfo);
381 unsigned int matchlen, matchoff;
382 struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
383 struct nf_conntrack_expect *exp;
384 union nf_inet_addr *daddr;
385 struct nf_conntrack_man cmd = {};
387 int found = 0, ends_in_nl;
388 typeof(nf_nat_ftp_hook) nf_nat_ftp;
390 /* Until there's been traffic both ways, don't look in packets. */
391 if (ctinfo != IP_CT_ESTABLISHED &&
392 ctinfo != IP_CT_ESTABLISHED_REPLY) {
393 pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
397 if (unlikely(skb_linearize(skb)))
400 th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
404 dataoff = protoff + th->doff * 4;
406 if (dataoff >= skb->len) {
407 pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
411 datalen = skb->len - dataoff;
413 /* seqadj (nat) uses ct->lock internally, nf_nat_ftp would cause deadlock */
414 spin_lock_bh(&nf_ftp_lock);
415 fb_ptr = skb->data + dataoff;
417 ends_in_nl = (fb_ptr[datalen - 1] == '\n');
418 seq = ntohl(th->seq) + datalen;
420 /* Look up to see if we're just after a \n. */
421 if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
422 /* We're picking up this, clear flags and let it continue */
423 if (unlikely(ct_ftp_info->flags[dir] & NF_CT_FTP_SEQ_PICKUP)) {
424 ct_ftp_info->flags[dir] ^= NF_CT_FTP_SEQ_PICKUP;
428 /* Now if this ends in \n, update ftp info. */
429 pr_debug("nf_conntrack_ftp: wrong seq pos %s(%u) or %s(%u)\n",
430 ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
431 ct_ftp_info->seq_aft_nl[dir][0],
432 ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
433 ct_ftp_info->seq_aft_nl[dir][1]);
439 /* Initialize IP/IPv6 addr to expected address (it's not mentioned
440 in EPSV responses) */
441 cmd.l3num = nf_ct_l3num(ct);
442 memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
445 for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
446 found = find_pattern(fb_ptr, datalen,
447 search[dir][i].pattern,
451 &matchoff, &matchlen,
453 search[dir][i].getnum);
457 /* We don't usually drop packets. After all, this is
458 connection tracking, not packet filtering.
459 However, it is necessary for accurate tracking in
461 nf_ct_helper_log(skb, ct, "partial matching of `%s'",
462 search[dir][i].pattern);
465 } else if (found == 0) { /* No match */
470 pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
471 matchlen, fb_ptr + matchoff,
472 matchlen, ntohl(th->seq) + matchoff);
474 exp = nf_ct_expect_alloc(ct);
476 nf_ct_helper_log(skb, ct, "cannot alloc expectation");
481 /* We refer to the reverse direction ("!dir") tuples here,
482 * because we're expecting something in the other direction.
483 * Doesn't matter unless NAT is happening. */
484 daddr = &ct->tuplehash[!dir].tuple.dst.u3;
486 /* Update the ftp info */
487 if ((cmd.l3num == nf_ct_l3num(ct)) &&
488 memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
489 sizeof(cmd.u3.all))) {
490 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
491 server: it really wants us to connect to a
492 different IP address. Simply don't record it for
494 if (cmd.l3num == PF_INET) {
495 pr_debug("NOT RECORDING: %pI4 != %pI4\n",
497 &ct->tuplehash[dir].tuple.src.u3.ip);
499 pr_debug("NOT RECORDING: %pI6 != %pI6\n",
501 ct->tuplehash[dir].tuple.src.u3.ip6);
504 /* Thanks to Cristiano Lincoln Mattos
506 problem (DMZ machines opening holes to internal
507 networks, or the packet filter itself). */
515 nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, cmd.l3num,
516 &ct->tuplehash[!dir].tuple.src.u3, daddr,
517 IPPROTO_TCP, NULL, &cmd.u.tcp.port);
519 /* Now, NAT might want to mangle the packet, and register the
520 * (possibly changed) expectation itself. */
521 nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
522 if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
523 ret = nf_nat_ftp(skb, ctinfo, search[dir][i].ftptype,
524 protoff, matchoff, matchlen, exp);
526 /* Can't expect this? Best to drop packet now. */
527 if (nf_ct_expect_related(exp, 0) != 0) {
528 nf_ct_helper_log(skb, ct, "cannot add expectation");
535 nf_ct_expect_put(exp);
538 /* Now if this ends in \n, update ftp info. Seq may have been
539 * adjusted by NAT code. */
541 update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
543 spin_unlock_bh(&nf_ftp_lock);
547 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
549 struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
551 /* This conntrack has been injected from user-space, always pick up
552 * sequence tracking. Otherwise, the first FTP command after the
555 ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
556 ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
560 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
562 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
567 static void __exit nf_conntrack_ftp_fini(void)
569 nf_conntrack_helpers_unregister(ftp, ports_c * 2);
572 static int __init nf_conntrack_ftp_init(void)
576 NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
579 ports[ports_c++] = FTP_PORT;
581 /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
582 are tracked or not - YK */
583 for (i = 0; i < ports_c; i++) {
584 nf_ct_helper_init(&ftp[2 * i], AF_INET, IPPROTO_TCP,
585 HELPER_NAME, FTP_PORT, ports[i], ports[i],
586 &ftp_exp_policy, 0, help,
587 nf_ct_ftp_from_nlattr, THIS_MODULE);
588 nf_ct_helper_init(&ftp[2 * i + 1], AF_INET6, IPPROTO_TCP,
589 HELPER_NAME, FTP_PORT, ports[i], ports[i],
590 &ftp_exp_policy, 0, help,
591 nf_ct_ftp_from_nlattr, THIS_MODULE);
594 ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
596 pr_err("failed to register helpers\n");
603 module_init(nf_conntrack_ftp_init);
604 module_exit(nf_conntrack_ftp_fini);