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