- patches.apparmor/remove_suid_new_case_in_2.6.22.diff: Merge fix.
[linux-flexiantxendom0-3.2.10.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  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  */
11
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/netfilter.h>
15 #include <linux/ip.h>
16 #include <linux/ipv6.h>
17 #include <linux/ctype.h>
18 #include <linux/inet.h>
19 #include <net/checksum.h>
20 #include <net/tcp.h>
21
22 #include <net/netfilter/nf_conntrack.h>
23 #include <net/netfilter/nf_conntrack_expect.h>
24 #include <net/netfilter/nf_conntrack_ecache.h>
25 #include <net/netfilter/nf_conntrack_helper.h>
26 #include <linux/netfilter/nf_conntrack_ftp.h>
27
28 MODULE_LICENSE("GPL");
29 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
30 MODULE_DESCRIPTION("ftp connection tracking helper");
31 MODULE_ALIAS("ip_conntrack_ftp");
32
33 /* This is slow, but it's simple. --RR */
34 static char *ftp_buffer;
35
36 static DEFINE_SPINLOCK(nf_ftp_lock);
37
38 #define MAX_PORTS 8
39 static u_int16_t ports[MAX_PORTS];
40 static unsigned int ports_c;
41 module_param_array(ports, ushort, &ports_c, 0400);
42
43 static int loose;
44 module_param(loose, bool, 0600);
45
46 unsigned int (*nf_nat_ftp_hook)(struct sk_buff **pskb,
47                                 enum ip_conntrack_info ctinfo,
48                                 enum nf_ct_ftp_type type,
49                                 unsigned int matchoff,
50                                 unsigned int matchlen,
51                                 struct nf_conntrack_expect *exp);
52 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
53
54 #if 0
55 #define DEBUGP printk
56 #else
57 #define DEBUGP(format, args...)
58 #endif
59
60 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *, char);
61 static int try_eprt(const char *, size_t, struct nf_conntrack_man *, char);
62 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
63                              char);
64
65 static struct ftp_search {
66         const char *pattern;
67         size_t plen;
68         char skip;
69         char term;
70         enum nf_ct_ftp_type ftptype;
71         int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char);
72 } search[IP_CT_DIR_MAX][2] = {
73         [IP_CT_DIR_ORIGINAL] = {
74                 {
75                         .pattern        = "PORT",
76                         .plen           = sizeof("PORT") - 1,
77                         .skip           = ' ',
78                         .term           = '\r',
79                         .ftptype        = NF_CT_FTP_PORT,
80                         .getnum         = try_rfc959,
81                 },
82                 {
83                         .pattern        = "EPRT",
84                         .plen           = sizeof("EPRT") - 1,
85                         .skip           = ' ',
86                         .term           = '\r',
87                         .ftptype        = NF_CT_FTP_EPRT,
88                         .getnum         = try_eprt,
89                 },
90         },
91         [IP_CT_DIR_REPLY] = {
92                 {
93                         .pattern        = "227 ",
94                         .plen           = sizeof("227 ") - 1,
95                         .skip           = '(',
96                         .term           = ')',
97                         .ftptype        = NF_CT_FTP_PASV,
98                         .getnum         = try_rfc959,
99                 },
100                 {
101                         .pattern        = "229 ",
102                         .plen           = sizeof("229 ") - 1,
103                         .skip           = '(',
104                         .term           = ')',
105                         .ftptype        = NF_CT_FTP_EPSV,
106                         .getnum         = try_epsv_response,
107                 },
108         },
109 };
110
111 static int
112 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
113 {
114         const char *end;
115         int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
116         if (ret > 0)
117                 return (int)(end - src);
118         return 0;
119 }
120
121 static int try_number(const char *data, size_t dlen, u_int32_t array[],
122                       int array_size, char sep, char term)
123 {
124         u_int32_t i, len;
125
126         memset(array, 0, sizeof(array[0])*array_size);
127
128         /* Keep data pointing at next char. */
129         for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
130                 if (*data >= '0' && *data <= '9') {
131                         array[i] = array[i]*10 + *data - '0';
132                 }
133                 else if (*data == sep)
134                         i++;
135                 else {
136                         /* Unexpected character; true if it's the
137                            terminator and we're finished. */
138                         if (*data == term && i == array_size - 1)
139                                 return len;
140
141                         DEBUGP("Char %u (got %u nums) `%u' unexpected\n",
142                                len, i, *data);
143                         return 0;
144                 }
145         }
146         DEBUGP("Failed to fill %u numbers separated by %c\n", array_size, sep);
147
148         return 0;
149 }
150
151 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
152 static int try_rfc959(const char *data, size_t dlen,
153                       struct nf_conntrack_man *cmd, char term)
154 {
155         int length;
156         u_int32_t array[6];
157
158         length = try_number(data, dlen, array, 6, ',', term);
159         if (length == 0)
160                 return 0;
161
162         cmd->u3.ip =  htonl((array[0] << 24) | (array[1] << 16) |
163                                     (array[2] << 8) | array[3]);
164         cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
165         return length;
166 }
167
168 /* Grab port: number up to delimiter */
169 static int get_port(const char *data, int start, size_t dlen, char delim,
170                     __be16 *port)
171 {
172         u_int16_t tmp_port = 0;
173         int i;
174
175         for (i = start; i < dlen; i++) {
176                 /* Finished? */
177                 if (data[i] == delim) {
178                         if (tmp_port == 0)
179                                 break;
180                         *port = htons(tmp_port);
181                         DEBUGP("get_port: return %d\n", tmp_port);
182                         return i + 1;
183                 }
184                 else if (data[i] >= '0' && data[i] <= '9')
185                         tmp_port = tmp_port*10 + data[i] - '0';
186                 else { /* Some other crap */
187                         DEBUGP("get_port: invalid char.\n");
188                         break;
189                 }
190         }
191         return 0;
192 }
193
194 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
195 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
196                     char term)
197 {
198         char delim;
199         int length;
200
201         /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
202            then delimiter again. */
203         if (dlen <= 3) {
204                 DEBUGP("EPRT: too short\n");
205                 return 0;
206         }
207         delim = data[0];
208         if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
209                 DEBUGP("try_eprt: invalid delimitter.\n");
210                 return 0;
211         }
212
213         if ((cmd->l3num == PF_INET && data[1] != '1') ||
214             (cmd->l3num == PF_INET6 && data[1] != '2')) {
215                 DEBUGP("EPRT: invalid protocol number.\n");
216                 return 0;
217         }
218
219         DEBUGP("EPRT: Got %c%c%c\n", delim, data[1], delim);
220
221         if (data[1] == '1') {
222                 u_int32_t array[4];
223
224                 /* Now we have IP address. */
225                 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
226                 if (length != 0)
227                         cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
228                                            | (array[2] << 8) | array[3]);
229         } else {
230                 /* Now we have IPv6 address. */
231                 length = get_ipv6_addr(data + 3, dlen - 3,
232                                        (struct in6_addr *)cmd->u3.ip6, delim);
233         }
234
235         if (length == 0)
236                 return 0;
237         DEBUGP("EPRT: Got IP address!\n");
238         /* Start offset includes initial "|1|", and trailing delimiter */
239         return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
240 }
241
242 /* Returns 0, or length of numbers: |||6446| */
243 static int try_epsv_response(const char *data, size_t dlen,
244                              struct nf_conntrack_man *cmd, char term)
245 {
246         char delim;
247
248         /* Three delimiters. */
249         if (dlen <= 3) return 0;
250         delim = data[0];
251         if (isdigit(delim) || delim < 33 || delim > 126
252             || data[1] != delim || data[2] != delim)
253                 return 0;
254
255         return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
256 }
257
258 /* Return 1 for match, 0 for accept, -1 for partial. */
259 static int find_pattern(const char *data, size_t dlen,
260                         const char *pattern, size_t plen,
261                         char skip, char term,
262                         unsigned int *numoff,
263                         unsigned int *numlen,
264                         struct nf_conntrack_man *cmd,
265                         int (*getnum)(const char *, size_t,
266                                       struct nf_conntrack_man *, char))
267 {
268         size_t i;
269
270         DEBUGP("find_pattern `%s': dlen = %u\n", pattern, dlen);
271         if (dlen == 0)
272                 return 0;
273
274         if (dlen <= plen) {
275                 /* Short packet: try for partial? */
276                 if (strnicmp(data, pattern, dlen) == 0)
277                         return -1;
278                 else return 0;
279         }
280
281         if (strnicmp(data, pattern, plen) != 0) {
282 #if 0
283                 size_t i;
284
285                 DEBUGP("ftp: string mismatch\n");
286                 for (i = 0; i < plen; i++) {
287                         DEBUGP("ftp:char %u `%c'(%u) vs `%c'(%u)\n",
288                                 i, data[i], data[i],
289                                 pattern[i], pattern[i]);
290                 }
291 #endif
292                 return 0;
293         }
294
295         DEBUGP("Pattern matches!\n");
296         /* Now we've found the constant string, try to skip
297            to the 'skip' character */
298         for (i = plen; data[i] != skip; i++)
299                 if (i == dlen - 1) return -1;
300
301         /* Skip over the last character */
302         i++;
303
304         DEBUGP("Skipped up to `%c'!\n", skip);
305
306         *numoff = i;
307         *numlen = getnum(data + i, dlen - i, cmd, term);
308         if (!*numlen)
309                 return -1;
310
311         DEBUGP("Match succeeded!\n");
312         return 1;
313 }
314
315 /* Look up to see if we're just after a \n. */
316 static int find_nl_seq(u32 seq, const struct nf_ct_ftp_master *info, int dir)
317 {
318         unsigned int i;
319
320         for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
321                 if (info->seq_aft_nl[dir][i] == seq)
322                         return 1;
323         return 0;
324 }
325
326 /* We don't update if it's older than what we have. */
327 static void update_nl_seq(u32 nl_seq, struct nf_ct_ftp_master *info, int dir,
328                           struct sk_buff *skb)
329 {
330         unsigned int i, oldest = NUM_SEQ_TO_REMEMBER;
331
332         /* Look for oldest: if we find exact match, we're done. */
333         for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
334                 if (info->seq_aft_nl[dir][i] == nl_seq)
335                         return;
336
337                 if (oldest == info->seq_aft_nl_num[dir] ||
338                     before(info->seq_aft_nl[dir][i],
339                            info->seq_aft_nl[dir][oldest]))
340                         oldest = i;
341         }
342
343         if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
344                 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
345                 nf_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
346         } else if (oldest != NUM_SEQ_TO_REMEMBER &&
347                    after(nl_seq, info->seq_aft_nl[dir][oldest])) {
348                 info->seq_aft_nl[dir][oldest] = nl_seq;
349                 nf_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
350         }
351 }
352
353 static int help(struct sk_buff **pskb,
354                 unsigned int protoff,
355                 struct nf_conn *ct,
356                 enum ip_conntrack_info ctinfo)
357 {
358         unsigned int dataoff, datalen;
359         struct tcphdr _tcph, *th;
360         char *fb_ptr;
361         int ret;
362         u32 seq;
363         int dir = CTINFO2DIR(ctinfo);
364         unsigned int matchlen, matchoff;
365         struct nf_ct_ftp_master *ct_ftp_info = &nfct_help(ct)->help.ct_ftp_info;
366         struct nf_conntrack_expect *exp;
367         struct nf_conntrack_man cmd = {};
368         unsigned int i;
369         int found = 0, ends_in_nl;
370         typeof(nf_nat_ftp_hook) nf_nat_ftp;
371
372         /* Until there's been traffic both ways, don't look in packets. */
373         if (ctinfo != IP_CT_ESTABLISHED
374             && ctinfo != IP_CT_ESTABLISHED+IP_CT_IS_REPLY) {
375                 DEBUGP("ftp: Conntrackinfo = %u\n", ctinfo);
376                 return NF_ACCEPT;
377         }
378
379         th = skb_header_pointer(*pskb, protoff, sizeof(_tcph), &_tcph);
380         if (th == NULL)
381                 return NF_ACCEPT;
382
383         dataoff = protoff + th->doff * 4;
384         /* No data? */
385         if (dataoff >= (*pskb)->len) {
386                 DEBUGP("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
387                         (*pskb)->len);
388                 return NF_ACCEPT;
389         }
390         datalen = (*pskb)->len - dataoff;
391
392         spin_lock_bh(&nf_ftp_lock);
393         fb_ptr = skb_header_pointer(*pskb, dataoff, datalen, ftp_buffer);
394         BUG_ON(fb_ptr == NULL);
395
396         ends_in_nl = (fb_ptr[datalen - 1] == '\n');
397         seq = ntohl(th->seq) + datalen;
398
399         /* Look up to see if we're just after a \n. */
400         if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
401                 /* Now if this ends in \n, update ftp info. */
402                 DEBUGP("nf_conntrack_ftp_help: wrong seq pos %s(%u) or %s(%u)\n",
403                        ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
404                        ct_ftp_info->seq_aft_nl[dir][0],
405                        ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
406                        ct_ftp_info->seq_aft_nl[dir][1]);
407                 ret = NF_ACCEPT;
408                 goto out_update_nl;
409         }
410
411         /* Initialize IP/IPv6 addr to expected address (it's not mentioned
412            in EPSV responses) */
413         cmd.l3num = ct->tuplehash[dir].tuple.src.l3num;
414         memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
415                sizeof(cmd.u3.all));
416
417         for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
418                 found = find_pattern(fb_ptr, datalen,
419                                      search[dir][i].pattern,
420                                      search[dir][i].plen,
421                                      search[dir][i].skip,
422                                      search[dir][i].term,
423                                      &matchoff, &matchlen,
424                                      &cmd,
425                                      search[dir][i].getnum);
426                 if (found) break;
427         }
428         if (found == -1) {
429                 /* We don't usually drop packets.  After all, this is
430                    connection tracking, not packet filtering.
431                    However, it is necessary for accurate tracking in
432                    this case. */
433                 if (net_ratelimit())
434                         printk("conntrack_ftp: partial %s %u+%u\n",
435                                search[dir][i].pattern,
436                                ntohl(th->seq), datalen);
437                 ret = NF_DROP;
438                 goto out;
439         } else if (found == 0) { /* No match */
440                 ret = NF_ACCEPT;
441                 goto out_update_nl;
442         }
443
444         DEBUGP("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
445                (int)matchlen, fb_ptr + matchoff,
446                matchlen, ntohl(th->seq) + matchoff);
447
448         exp = nf_conntrack_expect_alloc(ct);
449         if (exp == NULL) {
450                 ret = NF_DROP;
451                 goto out;
452         }
453
454         /* We refer to the reverse direction ("!dir") tuples here,
455          * because we're expecting something in the other direction.
456          * Doesn't matter unless NAT is happening.  */
457         exp->tuple.dst.u3 = ct->tuplehash[!dir].tuple.dst.u3;
458
459         /* Update the ftp info */
460         if ((cmd.l3num == ct->tuplehash[dir].tuple.src.l3num) &&
461             memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
462                      sizeof(cmd.u3.all))) {
463                 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
464                    server: it really wants us to connect to a
465                    different IP address.  Simply don't record it for
466                    NAT. */
467                 if (cmd.l3num == PF_INET) {
468                         DEBUGP("conntrack_ftp: NOT RECORDING: " NIPQUAD_FMT " != " NIPQUAD_FMT "\n",
469                                NIPQUAD(cmd.u3.ip),
470                                NIPQUAD(ct->tuplehash[dir].tuple.src.u3.ip));
471                 } else {
472                         DEBUGP("conntrack_ftp: NOT RECORDING: " NIP6_FMT " != " NIP6_FMT "\n",
473                                NIP6(*((struct in6_addr *)cmd.u3.ip6)),
474                                NIP6(*((struct in6_addr *)ct->tuplehash[dir]
475                                                         .tuple.src.u3.ip6)));
476                 }
477
478                 /* Thanks to Cristiano Lincoln Mattos
479                    <lincoln@cesar.org.br> for reporting this potential
480                    problem (DMZ machines opening holes to internal
481                    networks, or the packet filter itself). */
482                 if (!loose) {
483                         ret = NF_ACCEPT;
484                         goto out_put_expect;
485                 }
486                 memcpy(&exp->tuple.dst.u3, &cmd.u3.all,
487                        sizeof(exp->tuple.dst.u3));
488         }
489
490         exp->tuple.src.u3 = ct->tuplehash[!dir].tuple.src.u3;
491         exp->tuple.src.l3num = cmd.l3num;
492         exp->tuple.src.u.tcp.port = 0;
493         exp->tuple.dst.u.tcp.port = cmd.u.tcp.port;
494         exp->tuple.dst.protonum = IPPROTO_TCP;
495
496         exp->mask = (struct nf_conntrack_tuple)
497                     { .src = { .l3num = 0xFFFF,
498                                .u = { .tcp = { 0 }},
499                              },
500                       .dst = { .protonum = 0xFF,
501                                .u = { .tcp = { __constant_htons(0xFFFF) }},
502                              },
503                     };
504         if (cmd.l3num == PF_INET) {
505                 exp->mask.src.u3.ip = htonl(0xFFFFFFFF);
506                 exp->mask.dst.u3.ip = htonl(0xFFFFFFFF);
507         } else {
508                 memset(exp->mask.src.u3.ip6, 0xFF,
509                        sizeof(exp->mask.src.u3.ip6));
510                 memset(exp->mask.dst.u3.ip6, 0xFF,
511                        sizeof(exp->mask.src.u3.ip6));
512         }
513
514         exp->expectfn = NULL;
515         exp->helper = NULL;
516         exp->flags = 0;
517
518         /* Now, NAT might want to mangle the packet, and register the
519          * (possibly changed) expectation itself. */
520         nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
521         if (nf_nat_ftp && ct->status & IPS_NAT_MASK)
522                 ret = nf_nat_ftp(pskb, ctinfo, search[dir][i].ftptype,
523                                  matchoff, matchlen, exp);
524         else {
525                 /* Can't expect this?  Best to drop packet now. */
526                 if (nf_conntrack_expect_related(exp) != 0)
527                         ret = NF_DROP;
528                 else
529                         ret = NF_ACCEPT;
530         }
531
532 out_put_expect:
533         nf_conntrack_expect_put(exp);
534
535 out_update_nl:
536         /* Now if this ends in \n, update ftp info.  Seq may have been
537          * adjusted by NAT code. */
538         if (ends_in_nl)
539                 update_nl_seq(seq, ct_ftp_info, dir, *pskb);
540  out:
541         spin_unlock_bh(&nf_ftp_lock);
542         return ret;
543 }
544
545 static struct nf_conntrack_helper ftp[MAX_PORTS][2];
546 static char ftp_names[MAX_PORTS][2][sizeof("ftp-65535")];
547
548 /* don't make this __exit, since it's called from __init ! */
549 static void nf_conntrack_ftp_fini(void)
550 {
551         int i, j;
552         for (i = 0; i < ports_c; i++) {
553                 for (j = 0; j < 2; j++) {
554                         if (ftp[i][j].me == NULL)
555                                 continue;
556
557                         DEBUGP("nf_ct_ftp: unregistering helper for pf: %d "
558                                "port: %d\n",
559                                 ftp[i][j].tuple.src.l3num, ports[i]);
560                         nf_conntrack_helper_unregister(&ftp[i][j]);
561                 }
562         }
563
564         kfree(ftp_buffer);
565 }
566
567 static int __init nf_conntrack_ftp_init(void)
568 {
569         int i, j = -1, ret = 0;
570         char *tmpname;
571
572         ftp_buffer = kmalloc(65536, GFP_KERNEL);
573         if (!ftp_buffer)
574                 return -ENOMEM;
575
576         if (ports_c == 0)
577                 ports[ports_c++] = FTP_PORT;
578
579         /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
580                  are tracked or not - YK */
581         for (i = 0; i < ports_c; i++) {
582                 ftp[i][0].tuple.src.l3num = PF_INET;
583                 ftp[i][1].tuple.src.l3num = PF_INET6;
584                 for (j = 0; j < 2; j++) {
585                         ftp[i][j].tuple.src.u.tcp.port = htons(ports[i]);
586                         ftp[i][j].tuple.dst.protonum = IPPROTO_TCP;
587                         ftp[i][j].mask.src.l3num = 0xFFFF;
588                         ftp[i][j].mask.src.u.tcp.port = htons(0xFFFF);
589                         ftp[i][j].mask.dst.protonum = 0xFF;
590                         ftp[i][j].max_expected = 1;
591                         ftp[i][j].timeout = 5 * 60;     /* 5 Minutes */
592                         ftp[i][j].me = THIS_MODULE;
593                         ftp[i][j].help = help;
594                         tmpname = &ftp_names[i][j][0];
595                         if (ports[i] == FTP_PORT)
596                                 sprintf(tmpname, "ftp");
597                         else
598                                 sprintf(tmpname, "ftp-%d", ports[i]);
599                         ftp[i][j].name = tmpname;
600
601                         DEBUGP("nf_ct_ftp: registering helper for pf: %d "
602                                "port: %d\n",
603                                 ftp[i][j].tuple.src.l3num, ports[i]);
604                         ret = nf_conntrack_helper_register(&ftp[i][j]);
605                         if (ret) {
606                                 printk("nf_ct_ftp: failed to register helper "
607                                        " for pf: %d port: %d\n",
608                                         ftp[i][j].tuple.src.l3num, ports[i]);
609                                 nf_conntrack_ftp_fini();
610                                 return ret;
611                         }
612                 }
613         }
614
615         return 0;
616 }
617
618 module_init(nf_conntrack_ftp_init);
619 module_exit(nf_conntrack_ftp_fini);