Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /* FTP extension for connection tracking. */
0003 
0004 /* (C) 1999-2001 Paul `Rusty' Russell
0005  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
0006  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
0007  * (C) 2006-2012 Patrick McHardy <kaber@trash.net>
0008  */
0009 
0010 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0011 
0012 #include <linux/module.h>
0013 #include <linux/moduleparam.h>
0014 #include <linux/netfilter.h>
0015 #include <linux/ip.h>
0016 #include <linux/slab.h>
0017 #include <linux/ipv6.h>
0018 #include <linux/ctype.h>
0019 #include <linux/inet.h>
0020 #include <net/checksum.h>
0021 #include <net/tcp.h>
0022 
0023 #include <net/netfilter/nf_conntrack.h>
0024 #include <net/netfilter/nf_conntrack_expect.h>
0025 #include <net/netfilter/nf_conntrack_ecache.h>
0026 #include <net/netfilter/nf_conntrack_helper.h>
0027 #include <linux/netfilter/nf_conntrack_ftp.h>
0028 
0029 #define HELPER_NAME "ftp"
0030 
0031 MODULE_LICENSE("GPL");
0032 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
0033 MODULE_DESCRIPTION("ftp connection tracking helper");
0034 MODULE_ALIAS("ip_conntrack_ftp");
0035 MODULE_ALIAS_NFCT_HELPER(HELPER_NAME);
0036 static DEFINE_SPINLOCK(nf_ftp_lock);
0037 
0038 #define MAX_PORTS 8
0039 static u_int16_t ports[MAX_PORTS];
0040 static unsigned int ports_c;
0041 module_param_array(ports, ushort, &ports_c, 0400);
0042 
0043 static bool loose;
0044 module_param(loose, bool, 0600);
0045 
0046 unsigned int (*nf_nat_ftp_hook)(struct sk_buff *skb,
0047                 enum ip_conntrack_info ctinfo,
0048                 enum nf_ct_ftp_type type,
0049                 unsigned int protoff,
0050                 unsigned int matchoff,
0051                 unsigned int matchlen,
0052                 struct nf_conntrack_expect *exp);
0053 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
0054 
0055 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *,
0056               char, unsigned int *);
0057 static int try_rfc1123(const char *, size_t, struct nf_conntrack_man *,
0058                char, unsigned int *);
0059 static int try_eprt(const char *, size_t, struct nf_conntrack_man *,
0060             char, unsigned int *);
0061 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
0062                  char, unsigned int *);
0063 
0064 static struct ftp_search {
0065     const char *pattern;
0066     size_t plen;
0067     char skip;
0068     char term;
0069     enum nf_ct_ftp_type ftptype;
0070     int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char, unsigned int *);
0071 } search[IP_CT_DIR_MAX][2] = {
0072     [IP_CT_DIR_ORIGINAL] = {
0073         {
0074             .pattern    = "PORT",
0075             .plen       = sizeof("PORT") - 1,
0076             .skip       = ' ',
0077             .term       = '\r',
0078             .ftptype    = NF_CT_FTP_PORT,
0079             .getnum     = try_rfc959,
0080         },
0081         {
0082             .pattern    = "EPRT",
0083             .plen       = sizeof("EPRT") - 1,
0084             .skip       = ' ',
0085             .term       = '\r',
0086             .ftptype    = NF_CT_FTP_EPRT,
0087             .getnum     = try_eprt,
0088         },
0089     },
0090     [IP_CT_DIR_REPLY] = {
0091         {
0092             .pattern    = "227 ",
0093             .plen       = sizeof("227 ") - 1,
0094             .ftptype    = NF_CT_FTP_PASV,
0095             .getnum     = try_rfc1123,
0096         },
0097         {
0098             .pattern    = "229 ",
0099             .plen       = sizeof("229 ") - 1,
0100             .skip       = '(',
0101             .term       = ')',
0102             .ftptype    = NF_CT_FTP_EPSV,
0103             .getnum     = try_epsv_response,
0104         },
0105     },
0106 };
0107 
0108 static int
0109 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
0110 {
0111     const char *end;
0112     int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
0113     if (ret > 0)
0114         return (int)(end - src);
0115     return 0;
0116 }
0117 
0118 static int try_number(const char *data, size_t dlen, u_int32_t array[],
0119               int array_size, char sep, char term)
0120 {
0121     u_int32_t i, len;
0122 
0123     memset(array, 0, sizeof(array[0])*array_size);
0124 
0125     /* Keep data pointing at next char. */
0126     for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
0127         if (*data >= '0' && *data <= '9') {
0128             array[i] = array[i]*10 + *data - '0';
0129         }
0130         else if (*data == sep)
0131             i++;
0132         else {
0133             /* Unexpected character; true if it's the
0134                terminator (or we don't care about one)
0135                and we're finished. */
0136             if ((*data == term || !term) && i == array_size - 1)
0137                 return len;
0138 
0139             pr_debug("Char %u (got %u nums) `%u' unexpected\n",
0140                  len, i, *data);
0141             return 0;
0142         }
0143     }
0144     pr_debug("Failed to fill %u numbers separated by %c\n",
0145          array_size, sep);
0146     return 0;
0147 }
0148 
0149 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
0150 static int try_rfc959(const char *data, size_t dlen,
0151               struct nf_conntrack_man *cmd, char term,
0152               unsigned int *offset)
0153 {
0154     int length;
0155     u_int32_t array[6];
0156 
0157     length = try_number(data, dlen, array, 6, ',', term);
0158     if (length == 0)
0159         return 0;
0160 
0161     cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16) |
0162                     (array[2] << 8) | array[3]);
0163     cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
0164     return length;
0165 }
0166 
0167 /*
0168  * From RFC 1123:
0169  * The format of the 227 reply to a PASV command is not
0170  * well standardized.  In particular, an FTP client cannot
0171  * assume that the parentheses shown on page 40 of RFC-959
0172  * will be present (and in fact, Figure 3 on page 43 omits
0173  * them).  Therefore, a User-FTP program that interprets
0174  * the PASV reply must scan the reply for the first digit
0175  * of the host and port numbers.
0176  */
0177 static int try_rfc1123(const char *data, size_t dlen,
0178                struct nf_conntrack_man *cmd, char term,
0179                unsigned int *offset)
0180 {
0181     int i;
0182     for (i = 0; i < dlen; i++)
0183         if (isdigit(data[i]))
0184             break;
0185 
0186     if (i == dlen)
0187         return 0;
0188 
0189     *offset += i;
0190 
0191     return try_rfc959(data + i, dlen - i, cmd, 0, offset);
0192 }
0193 
0194 /* Grab port: number up to delimiter */
0195 static int get_port(const char *data, int start, size_t dlen, char delim,
0196             __be16 *port)
0197 {
0198     u_int16_t tmp_port = 0;
0199     int i;
0200 
0201     for (i = start; i < dlen; i++) {
0202         /* Finished? */
0203         if (data[i] == delim) {
0204             if (tmp_port == 0)
0205                 break;
0206             *port = htons(tmp_port);
0207             pr_debug("get_port: return %d\n", tmp_port);
0208             return i + 1;
0209         }
0210         else if (data[i] >= '0' && data[i] <= '9')
0211             tmp_port = tmp_port*10 + data[i] - '0';
0212         else { /* Some other crap */
0213             pr_debug("get_port: invalid char.\n");
0214             break;
0215         }
0216     }
0217     return 0;
0218 }
0219 
0220 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
0221 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
0222             char term, unsigned int *offset)
0223 {
0224     char delim;
0225     int length;
0226 
0227     /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
0228        then delimiter again. */
0229     if (dlen <= 3) {
0230         pr_debug("EPRT: too short\n");
0231         return 0;
0232     }
0233     delim = data[0];
0234     if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
0235         pr_debug("try_eprt: invalid delimiter.\n");
0236         return 0;
0237     }
0238 
0239     if ((cmd->l3num == PF_INET && data[1] != '1') ||
0240         (cmd->l3num == PF_INET6 && data[1] != '2')) {
0241         pr_debug("EPRT: invalid protocol number.\n");
0242         return 0;
0243     }
0244 
0245     pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
0246 
0247     if (data[1] == '1') {
0248         u_int32_t array[4];
0249 
0250         /* Now we have IP address. */
0251         length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
0252         if (length != 0)
0253             cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
0254                        | (array[2] << 8) | array[3]);
0255     } else {
0256         /* Now we have IPv6 address. */
0257         length = get_ipv6_addr(data + 3, dlen - 3,
0258                        (struct in6_addr *)cmd->u3.ip6, delim);
0259     }
0260 
0261     if (length == 0)
0262         return 0;
0263     pr_debug("EPRT: Got IP address!\n");
0264     /* Start offset includes initial "|1|", and trailing delimiter */
0265     return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
0266 }
0267 
0268 /* Returns 0, or length of numbers: |||6446| */
0269 static int try_epsv_response(const char *data, size_t dlen,
0270                  struct nf_conntrack_man *cmd, char term,
0271                  unsigned int *offset)
0272 {
0273     char delim;
0274 
0275     /* Three delimiters. */
0276     if (dlen <= 3) return 0;
0277     delim = data[0];
0278     if (isdigit(delim) || delim < 33 || delim > 126 ||
0279         data[1] != delim || data[2] != delim)
0280         return 0;
0281 
0282     return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
0283 }
0284 
0285 /* Return 1 for match, 0 for accept, -1 for partial. */
0286 static int find_pattern(const char *data, size_t dlen,
0287             const char *pattern, size_t plen,
0288             char skip, char term,
0289             unsigned int *numoff,
0290             unsigned int *numlen,
0291             struct nf_conntrack_man *cmd,
0292             int (*getnum)(const char *, size_t,
0293                       struct nf_conntrack_man *, char,
0294                       unsigned int *))
0295 {
0296     size_t i = plen;
0297 
0298     pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
0299 
0300     if (dlen <= plen) {
0301         /* Short packet: try for partial? */
0302         if (strncasecmp(data, pattern, dlen) == 0)
0303             return -1;
0304         else return 0;
0305     }
0306 
0307     if (strncasecmp(data, pattern, plen) != 0)
0308         return 0;
0309 
0310     pr_debug("Pattern matches!\n");
0311     /* Now we've found the constant string, try to skip
0312        to the 'skip' character */
0313     if (skip) {
0314         for (i = plen; data[i] != skip; i++)
0315             if (i == dlen - 1) return -1;
0316 
0317         /* Skip over the last character */
0318         i++;
0319     }
0320 
0321     pr_debug("Skipped up to 0x%hhx delimiter!\n", skip);
0322 
0323     *numoff = i;
0324     *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
0325     if (!*numlen)
0326         return -1;
0327 
0328     pr_debug("Match succeeded!\n");
0329     return 1;
0330 }
0331 
0332 /* Look up to see if we're just after a \n. */
0333 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
0334 {
0335     unsigned int i;
0336 
0337     for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
0338         if (info->seq_aft_nl[dir][i] == seq)
0339             return 1;
0340     return 0;
0341 }
0342 
0343 /* We don't update if it's older than what we have. */
0344 static void update_nl_seq(struct nf_conn *ct, u32 nl_seq,
0345               struct nf_ct_ftp_master *info, int dir,
0346               struct sk_buff *skb)
0347 {
0348     unsigned int i, oldest;
0349 
0350     /* Look for oldest: if we find exact match, we're done. */
0351     for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
0352         if (info->seq_aft_nl[dir][i] == nl_seq)
0353             return;
0354     }
0355 
0356     if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
0357         info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
0358     } else {
0359         if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
0360             oldest = 0;
0361         else
0362             oldest = 1;
0363 
0364         if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
0365             info->seq_aft_nl[dir][oldest] = nl_seq;
0366     }
0367 }
0368 
0369 static int help(struct sk_buff *skb,
0370         unsigned int protoff,
0371         struct nf_conn *ct,
0372         enum ip_conntrack_info ctinfo)
0373 {
0374     unsigned int dataoff, datalen;
0375     const struct tcphdr *th;
0376     struct tcphdr _tcph;
0377     const char *fb_ptr;
0378     int ret;
0379     u32 seq;
0380     int dir = CTINFO2DIR(ctinfo);
0381     unsigned int matchlen, matchoff;
0382     struct nf_ct_ftp_master *ct_ftp_info = nfct_help_data(ct);
0383     struct nf_conntrack_expect *exp;
0384     union nf_inet_addr *daddr;
0385     struct nf_conntrack_man cmd = {};
0386     unsigned int i;
0387     int found = 0, ends_in_nl;
0388     typeof(nf_nat_ftp_hook) nf_nat_ftp;
0389 
0390     /* Until there's been traffic both ways, don't look in packets. */
0391     if (ctinfo != IP_CT_ESTABLISHED &&
0392         ctinfo != IP_CT_ESTABLISHED_REPLY) {
0393         pr_debug("ftp: Conntrackinfo = %u\n", ctinfo);
0394         return NF_ACCEPT;
0395     }
0396 
0397     if (unlikely(skb_linearize(skb)))
0398         return NF_DROP;
0399 
0400     th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
0401     if (th == NULL)
0402         return NF_ACCEPT;
0403 
0404     dataoff = protoff + th->doff * 4;
0405     /* No data? */
0406     if (dataoff >= skb->len) {
0407         pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
0408              skb->len);
0409         return NF_ACCEPT;
0410     }
0411     datalen = skb->len - dataoff;
0412 
0413     /* seqadj (nat) uses ct->lock internally, nf_nat_ftp would cause deadlock */
0414     spin_lock_bh(&nf_ftp_lock);
0415     fb_ptr = skb->data + dataoff;
0416 
0417     ends_in_nl = (fb_ptr[datalen - 1] == '\n');
0418     seq = ntohl(th->seq) + datalen;
0419 
0420     /* Look up to see if we're just after a \n. */
0421     if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
0422         /* We're picking up this, clear flags and let it continue */
0423         if (unlikely(ct_ftp_info->flags[dir] & NF_CT_FTP_SEQ_PICKUP)) {
0424             ct_ftp_info->flags[dir] ^= NF_CT_FTP_SEQ_PICKUP;
0425             goto skip_nl_seq;
0426         }
0427 
0428         /* Now if this ends in \n, update ftp info. */
0429         pr_debug("nf_conntrack_ftp: wrong seq pos %s(%u) or %s(%u)\n",
0430              ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
0431              ct_ftp_info->seq_aft_nl[dir][0],
0432              ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
0433              ct_ftp_info->seq_aft_nl[dir][1]);
0434         ret = NF_ACCEPT;
0435         goto out_update_nl;
0436     }
0437 
0438 skip_nl_seq:
0439     /* Initialize IP/IPv6 addr to expected address (it's not mentioned
0440        in EPSV responses) */
0441     cmd.l3num = nf_ct_l3num(ct);
0442     memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
0443            sizeof(cmd.u3.all));
0444 
0445     for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
0446         found = find_pattern(fb_ptr, datalen,
0447                      search[dir][i].pattern,
0448                      search[dir][i].plen,
0449                      search[dir][i].skip,
0450                      search[dir][i].term,
0451                      &matchoff, &matchlen,
0452                      &cmd,
0453                      search[dir][i].getnum);
0454         if (found) break;
0455     }
0456     if (found == -1) {
0457         /* We don't usually drop packets.  After all, this is
0458            connection tracking, not packet filtering.
0459            However, it is necessary for accurate tracking in
0460            this case. */
0461         nf_ct_helper_log(skb, ct, "partial matching of `%s'",
0462                      search[dir][i].pattern);
0463         ret = NF_DROP;
0464         goto out;
0465     } else if (found == 0) { /* No match */
0466         ret = NF_ACCEPT;
0467         goto out_update_nl;
0468     }
0469 
0470     pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
0471          matchlen, fb_ptr + matchoff,
0472          matchlen, ntohl(th->seq) + matchoff);
0473 
0474     exp = nf_ct_expect_alloc(ct);
0475     if (exp == NULL) {
0476         nf_ct_helper_log(skb, ct, "cannot alloc expectation");
0477         ret = NF_DROP;
0478         goto out;
0479     }
0480 
0481     /* We refer to the reverse direction ("!dir") tuples here,
0482      * because we're expecting something in the other direction.
0483      * Doesn't matter unless NAT is happening.  */
0484     daddr = &ct->tuplehash[!dir].tuple.dst.u3;
0485 
0486     /* Update the ftp info */
0487     if ((cmd.l3num == nf_ct_l3num(ct)) &&
0488         memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
0489              sizeof(cmd.u3.all))) {
0490         /* Enrico Scholz's passive FTP to partially RNAT'd ftp
0491            server: it really wants us to connect to a
0492            different IP address.  Simply don't record it for
0493            NAT. */
0494         if (cmd.l3num == PF_INET) {
0495             pr_debug("NOT RECORDING: %pI4 != %pI4\n",
0496                  &cmd.u3.ip,
0497                  &ct->tuplehash[dir].tuple.src.u3.ip);
0498         } else {
0499             pr_debug("NOT RECORDING: %pI6 != %pI6\n",
0500                  cmd.u3.ip6,
0501                  ct->tuplehash[dir].tuple.src.u3.ip6);
0502         }
0503 
0504         /* Thanks to Cristiano Lincoln Mattos
0505            <lincoln@cesar.org.br> for reporting this potential
0506            problem (DMZ machines opening holes to internal
0507            networks, or the packet filter itself). */
0508         if (!loose) {
0509             ret = NF_ACCEPT;
0510             goto out_put_expect;
0511         }
0512         daddr = &cmd.u3;
0513     }
0514 
0515     nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, cmd.l3num,
0516               &ct->tuplehash[!dir].tuple.src.u3, daddr,
0517               IPPROTO_TCP, NULL, &cmd.u.tcp.port);
0518 
0519     /* Now, NAT might want to mangle the packet, and register the
0520      * (possibly changed) expectation itself. */
0521     nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
0522     if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
0523         ret = nf_nat_ftp(skb, ctinfo, search[dir][i].ftptype,
0524                  protoff, matchoff, matchlen, exp);
0525     else {
0526         /* Can't expect this?  Best to drop packet now. */
0527         if (nf_ct_expect_related(exp, 0) != 0) {
0528             nf_ct_helper_log(skb, ct, "cannot add expectation");
0529             ret = NF_DROP;
0530         } else
0531             ret = NF_ACCEPT;
0532     }
0533 
0534 out_put_expect:
0535     nf_ct_expect_put(exp);
0536 
0537 out_update_nl:
0538     /* Now if this ends in \n, update ftp info.  Seq may have been
0539      * adjusted by NAT code. */
0540     if (ends_in_nl)
0541         update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
0542  out:
0543     spin_unlock_bh(&nf_ftp_lock);
0544     return ret;
0545 }
0546 
0547 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
0548 {
0549     struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
0550 
0551     /* This conntrack has been injected from user-space, always pick up
0552      * sequence tracking. Otherwise, the first FTP command after the
0553      * failover breaks.
0554      */
0555     ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
0556     ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
0557     return 0;
0558 }
0559 
0560 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
0561 
0562 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
0563     .max_expected   = 1,
0564     .timeout    = 5 * 60,
0565 };
0566 
0567 static void __exit nf_conntrack_ftp_fini(void)
0568 {
0569     nf_conntrack_helpers_unregister(ftp, ports_c * 2);
0570 }
0571 
0572 static int __init nf_conntrack_ftp_init(void)
0573 {
0574     int i, ret = 0;
0575 
0576     NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
0577 
0578     if (ports_c == 0)
0579         ports[ports_c++] = FTP_PORT;
0580 
0581     /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
0582          are tracked or not - YK */
0583     for (i = 0; i < ports_c; i++) {
0584         nf_ct_helper_init(&ftp[2 * i], AF_INET, IPPROTO_TCP,
0585                   HELPER_NAME, FTP_PORT, ports[i], ports[i],
0586                   &ftp_exp_policy, 0, help,
0587                   nf_ct_ftp_from_nlattr, THIS_MODULE);
0588         nf_ct_helper_init(&ftp[2 * i + 1], AF_INET6, IPPROTO_TCP,
0589                   HELPER_NAME, FTP_PORT, ports[i], ports[i],
0590                   &ftp_exp_policy, 0, help,
0591                   nf_ct_ftp_from_nlattr, THIS_MODULE);
0592     }
0593 
0594     ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
0595     if (ret < 0) {
0596         pr_err("failed to register helpers\n");
0597         return ret;
0598     }
0599 
0600     return 0;
0601 }
0602 
0603 module_init(nf_conntrack_ftp_init);
0604 module_exit(nf_conntrack_ftp_fini);