e1000e: start network tx queue only when link is up
[linux-2.6-block.git] / net / netfilter / nf_conntrack_ftp.c
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  * (C) 2006-2012 Patrick McHardy <kaber@trash.net>
7  *
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.
11  */
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/module.h>
16 #include <linux/moduleparam.h>
17 #include <linux/netfilter.h>
18 #include <linux/ip.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>
24 #include <net/tcp.h>
25
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>
31
32 #define HELPER_NAME "ftp"
33
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);
39
40 /* This is slow, but it's simple. --RR */
41 static char *ftp_buffer;
42
43 static DEFINE_SPINLOCK(nf_ftp_lock);
44
45 #define MAX_PORTS 8
46 static u_int16_t ports[MAX_PORTS];
47 static unsigned int ports_c;
48 module_param_array(ports, ushort, &ports_c, 0400);
49
50 static bool loose;
51 module_param(loose, bool, 0600);
52
53 unsigned int (*nf_nat_ftp_hook)(struct sk_buff *skb,
54                                 enum ip_conntrack_info ctinfo,
55                                 enum nf_ct_ftp_type type,
56                                 unsigned int protoff,
57                                 unsigned int matchoff,
58                                 unsigned int matchlen,
59                                 struct nf_conntrack_expect *exp);
60 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
61
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 *);
70
71 static struct ftp_search {
72         const char *pattern;
73         size_t plen;
74         char skip;
75         char term;
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] = {
80                 {
81                         .pattern        = "PORT",
82                         .plen           = sizeof("PORT") - 1,
83                         .skip           = ' ',
84                         .term           = '\r',
85                         .ftptype        = NF_CT_FTP_PORT,
86                         .getnum         = try_rfc959,
87                 },
88                 {
89                         .pattern        = "EPRT",
90                         .plen           = sizeof("EPRT") - 1,
91                         .skip           = ' ',
92                         .term           = '\r',
93                         .ftptype        = NF_CT_FTP_EPRT,
94                         .getnum         = try_eprt,
95                 },
96         },
97         [IP_CT_DIR_REPLY] = {
98                 {
99                         .pattern        = "227 ",
100                         .plen           = sizeof("227 ") - 1,
101                         .ftptype        = NF_CT_FTP_PASV,
102                         .getnum         = try_rfc1123,
103                 },
104                 {
105                         .pattern        = "229 ",
106                         .plen           = sizeof("229 ") - 1,
107                         .skip           = '(',
108                         .term           = ')',
109                         .ftptype        = NF_CT_FTP_EPSV,
110                         .getnum         = try_epsv_response,
111                 },
112         },
113 };
114
115 static int
116 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
117 {
118         const char *end;
119         int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
120         if (ret > 0)
121                 return (int)(end - src);
122         return 0;
123 }
124
125 static int try_number(const char *data, size_t dlen, u_int32_t array[],
126                       int array_size, char sep, char term)
127 {
128         u_int32_t i, len;
129
130         memset(array, 0, sizeof(array[0])*array_size);
131
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';
136                 }
137                 else if (*data == sep)
138                         i++;
139                 else {
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)
144                                 return len;
145
146                         pr_debug("Char %u (got %u nums) `%u' unexpected\n",
147                                  len, i, *data);
148                         return 0;
149                 }
150         }
151         pr_debug("Failed to fill %u numbers separated by %c\n",
152                  array_size, sep);
153         return 0;
154 }
155
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)
160 {
161         int length;
162         u_int32_t array[6];
163
164         length = try_number(data, dlen, array, 6, ',', term);
165         if (length == 0)
166                 return 0;
167
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]);
171         return length;
172 }
173
174 /*
175  * From RFC 1123:
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.
183  */
184 static int try_rfc1123(const char *data, size_t dlen,
185                        struct nf_conntrack_man *cmd, char term,
186                        unsigned int *offset)
187 {
188         int i;
189         for (i = 0; i < dlen; i++)
190                 if (isdigit(data[i]))
191                         break;
192
193         if (i == dlen)
194                 return 0;
195
196         *offset += i;
197
198         return try_rfc959(data + i, dlen - i, cmd, 0, offset);
199 }
200
201 /* Grab port: number up to delimiter */
202 static int get_port(const char *data, int start, size_t dlen, char delim,
203                     __be16 *port)
204 {
205         u_int16_t tmp_port = 0;
206         int i;
207
208         for (i = start; i < dlen; i++) {
209                 /* Finished? */
210                 if (data[i] == delim) {
211                         if (tmp_port == 0)
212                                 break;
213                         *port = htons(tmp_port);
214                         pr_debug("get_port: return %d\n", tmp_port);
215                         return i + 1;
216                 }
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");
221                         break;
222                 }
223         }
224         return 0;
225 }
226
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)
230 {
231         char delim;
232         int length;
233
234         /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
235            then delimiter again. */
236         if (dlen <= 3) {
237                 pr_debug("EPRT: too short\n");
238                 return 0;
239         }
240         delim = data[0];
241         if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
242                 pr_debug("try_eprt: invalid delimiter.\n");
243                 return 0;
244         }
245
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");
249                 return 0;
250         }
251
252         pr_debug("EPRT: Got %c%c%c\n", delim, data[1], delim);
253
254         if (data[1] == '1') {
255                 u_int32_t array[4];
256
257                 /* Now we have IP address. */
258                 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
259                 if (length != 0)
260                         cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
261                                            | (array[2] << 8) | array[3]);
262         } else {
263                 /* Now we have IPv6 address. */
264                 length = get_ipv6_addr(data + 3, dlen - 3,
265                                        (struct in6_addr *)cmd->u3.ip6, delim);
266         }
267
268         if (length == 0)
269                 return 0;
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);
273 }
274
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)
279 {
280         char delim;
281
282         /* Three delimiters. */
283         if (dlen <= 3) return 0;
284         delim = data[0];
285         if (isdigit(delim) || delim < 33 || delim > 126 ||
286             data[1] != delim || data[2] != delim)
287                 return 0;
288
289         return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
290 }
291
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,
301                                       unsigned int *))
302 {
303         size_t i = plen;
304
305         pr_debug("find_pattern `%s': dlen = %zu\n", pattern, dlen);
306
307         if (dlen <= plen) {
308                 /* Short packet: try for partial? */
309                 if (strncasecmp(data, pattern, dlen) == 0)
310                         return -1;
311                 else return 0;
312         }
313
314         if (strncasecmp(data, pattern, plen) != 0)
315                 return 0;
316
317         pr_debug("Pattern matches!\n");
318         /* Now we've found the constant string, try to skip
319            to the 'skip' character */
320         if (skip) {
321                 for (i = plen; data[i] != skip; i++)
322                         if (i == dlen - 1) return -1;
323
324                 /* Skip over the last character */
325                 i++;
326         }
327
328         pr_debug("Skipped up to `%c'!\n", skip);
329
330         *numoff = i;
331         *numlen = getnum(data + i, dlen - i, cmd, term, numoff);
332         if (!*numlen)
333                 return -1;
334
335         pr_debug("Match succeeded!\n");
336         return 1;
337 }
338
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)
341 {
342         unsigned int i;
343
344         for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
345                 if (info->seq_aft_nl[dir][i] == seq)
346                         return 1;
347         return 0;
348 }
349
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,
353                           struct sk_buff *skb)
354 {
355         unsigned int i, oldest;
356
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)
360                         return;
361         }
362
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;
365         } else {
366                 if (before(info->seq_aft_nl[dir][0], info->seq_aft_nl[dir][1]))
367                         oldest = 0;
368                 else
369                         oldest = 1;
370
371                 if (after(nl_seq, info->seq_aft_nl[dir][oldest]))
372                         info->seq_aft_nl[dir][oldest] = nl_seq;
373         }
374 }
375
376 static int help(struct sk_buff *skb,
377                 unsigned int protoff,
378                 struct nf_conn *ct,
379                 enum ip_conntrack_info ctinfo)
380 {
381         unsigned int dataoff, datalen;
382         const struct tcphdr *th;
383         struct tcphdr _tcph;
384         const char *fb_ptr;
385         int ret;
386         u32 seq;
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 = {};
393         unsigned int i;
394         int found = 0, ends_in_nl;
395         typeof(nf_nat_ftp_hook) nf_nat_ftp;
396
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);
401                 return NF_ACCEPT;
402         }
403
404         th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
405         if (th == NULL)
406                 return NF_ACCEPT;
407
408         dataoff = protoff + th->doff * 4;
409         /* No data? */
410         if (dataoff >= skb->len) {
411                 pr_debug("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
412                          skb->len);
413                 return NF_ACCEPT;
414         }
415         datalen = skb->len - dataoff;
416
417         spin_lock_bh(&nf_ftp_lock);
418         fb_ptr = skb_header_pointer(skb, dataoff, datalen, ftp_buffer);
419         BUG_ON(fb_ptr == NULL);
420
421         ends_in_nl = (fb_ptr[datalen - 1] == '\n');
422         seq = ntohl(th->seq) + datalen;
423
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;
429                         goto skip_nl_seq;
430                 }
431
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]);
438                 ret = NF_ACCEPT;
439                 goto out_update_nl;
440         }
441
442 skip_nl_seq:
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,
447                sizeof(cmd.u3.all));
448
449         for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
450                 found = find_pattern(fb_ptr, datalen,
451                                      search[dir][i].pattern,
452                                      search[dir][i].plen,
453                                      search[dir][i].skip,
454                                      search[dir][i].term,
455                                      &matchoff, &matchlen,
456                                      &cmd,
457                                      search[dir][i].getnum);
458                 if (found) break;
459         }
460         if (found == -1) {
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
464                    this case. */
465                 nf_ct_helper_log(skb, ct, "partial matching of `%s'",
466                                  search[dir][i].pattern);
467                 ret = NF_DROP;
468                 goto out;
469         } else if (found == 0) { /* No match */
470                 ret = NF_ACCEPT;
471                 goto out_update_nl;
472         }
473
474         pr_debug("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
475                  matchlen, fb_ptr + matchoff,
476                  matchlen, ntohl(th->seq) + matchoff);
477
478         exp = nf_ct_expect_alloc(ct);
479         if (exp == NULL) {
480                 nf_ct_helper_log(skb, ct, "cannot alloc expectation");
481                 ret = NF_DROP;
482                 goto out;
483         }
484
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;
489
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
497                    NAT. */
498                 if (cmd.l3num == PF_INET) {
499                         pr_debug("NOT RECORDING: %pI4 != %pI4\n",
500                                  &cmd.u3.ip,
501                                  &ct->tuplehash[dir].tuple.src.u3.ip);
502                 } else {
503                         pr_debug("NOT RECORDING: %pI6 != %pI6\n",
504                                  cmd.u3.ip6,
505                                  ct->tuplehash[dir].tuple.src.u3.ip6);
506                 }
507
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). */
512                 if (!loose) {
513                         ret = NF_ACCEPT;
514                         goto out_put_expect;
515                 }
516                 daddr = &cmd.u3;
517         }
518
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);
522
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);
529         else {
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");
533                         ret = NF_DROP;
534                 } else
535                         ret = NF_ACCEPT;
536         }
537
538 out_put_expect:
539         nf_ct_expect_put(exp);
540
541 out_update_nl:
542         /* Now if this ends in \n, update ftp info.  Seq may have been
543          * adjusted by NAT code. */
544         if (ends_in_nl)
545                 update_nl_seq(ct, seq, ct_ftp_info, dir, skb);
546  out:
547         spin_unlock_bh(&nf_ftp_lock);
548         return ret;
549 }
550
551 static int nf_ct_ftp_from_nlattr(struct nlattr *attr, struct nf_conn *ct)
552 {
553         struct nf_ct_ftp_master *ftp = nfct_help_data(ct);
554
555         /* This conntrack has been injected from user-space, always pick up
556          * sequence tracking. Otherwise, the first FTP command after the
557          * failover breaks.
558          */
559         ftp->flags[IP_CT_DIR_ORIGINAL] |= NF_CT_FTP_SEQ_PICKUP;
560         ftp->flags[IP_CT_DIR_REPLY] |= NF_CT_FTP_SEQ_PICKUP;
561         return 0;
562 }
563
564 static struct nf_conntrack_helper ftp[MAX_PORTS * 2] __read_mostly;
565
566 static const struct nf_conntrack_expect_policy ftp_exp_policy = {
567         .max_expected   = 1,
568         .timeout        = 5 * 60,
569 };
570
571 static void __exit nf_conntrack_ftp_fini(void)
572 {
573         nf_conntrack_helpers_unregister(ftp, ports_c * 2);
574         kfree(ftp_buffer);
575 }
576
577 static int __init nf_conntrack_ftp_init(void)
578 {
579         int i, ret = 0;
580
581         NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nf_ct_ftp_master));
582
583         ftp_buffer = kmalloc(65536, GFP_KERNEL);
584         if (!ftp_buffer)
585                 return -ENOMEM;
586
587         if (ports_c == 0)
588                 ports[ports_c++] = FTP_PORT;
589
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);
601         }
602
603         ret = nf_conntrack_helpers_register(ftp, ports_c * 2);
604         if (ret < 0) {
605                 pr_err("failed to register helpers\n");
606                 kfree(ftp_buffer);
607                 return ret;
608         }
609
610         return 0;
611 }
612
613 module_init(nf_conntrack_ftp_init);
614 module_exit(nf_conntrack_ftp_fini);