9dccb40398890bb602580818988cf0e88fad0f70
[linux-2.6.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 <net/checksum.h>
25 #include <net/tcp.h>
26
27 #include <net/netfilter/nf_conntrack.h>
28 #include <net/netfilter/nf_conntrack_helper.h>
29 #include <linux/netfilter/nf_conntrack_ftp.h>
30
31 MODULE_LICENSE("GPL");
32 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
33 MODULE_DESCRIPTION("ftp connection tracking helper");
34
35 /* This is slow, but it's simple. --RR */
36 static char *ftp_buffer;
37
38 static DEFINE_SPINLOCK(nf_ftp_lock);
39
40 #define MAX_PORTS 8
41 static u_int16_t ports[MAX_PORTS];
42 static unsigned int ports_c;
43 module_param_array(ports, ushort, &ports_c, 0400);
44
45 static int loose;
46 module_param(loose, bool, 0600);
47
48 unsigned int (*nf_nat_ftp_hook)(struct sk_buff **pskb,
49                                 enum ip_conntrack_info ctinfo,
50                                 enum ip_ct_ftp_type type,
51                                 unsigned int matchoff,
52                                 unsigned int matchlen,
53                                 struct nf_conntrack_expect *exp,
54                                 u32 *seq);
55 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
56
57 #if 0
58 #define DEBUGP printk
59 #else
60 #define DEBUGP(format, args...)
61 #endif
62
63 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *, char);
64 static int try_eprt(const char *, size_t, struct nf_conntrack_man *, char);
65 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
66                              char);
67
68 static struct ftp_search {
69         const char *pattern;
70         size_t plen;
71         char skip;
72         char term;
73         enum ip_ct_ftp_type ftptype;
74         int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char);
75 } search[IP_CT_DIR_MAX][2] = {
76         [IP_CT_DIR_ORIGINAL] = {
77                 {
78                         .pattern        = "PORT",
79                         .plen           = sizeof("PORT") - 1,
80                         .skip           = ' ',
81                         .term           = '\r',
82                         .ftptype        = IP_CT_FTP_PORT,
83                         .getnum         = try_rfc959,
84                 },
85                 {
86                         .pattern        = "EPRT",
87                         .plen           = sizeof("EPRT") - 1,
88                         .skip           = ' ',
89                         .term           = '\r',
90                         .ftptype        = IP_CT_FTP_EPRT,
91                         .getnum         = try_eprt,
92                 },
93         },
94         [IP_CT_DIR_REPLY] = {
95                 {
96                         .pattern        = "227 ",
97                         .plen           = sizeof("227 ") - 1,
98                         .skip           = '(',
99                         .term           = ')',
100                         .ftptype        = IP_CT_FTP_PASV,
101                         .getnum         = try_rfc959,
102                 },
103                 {
104                         .pattern        = "229 ",
105                         .plen           = sizeof("229 ") - 1,
106                         .skip           = '(',
107                         .term           = ')',
108                         .ftptype        = IP_CT_FTP_EPSV,
109                         .getnum         = try_epsv_response,
110                 },
111         },
112 };
113
114 static int
115 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
116 {
117         int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), dst, term, &end);
118         if (ret > 0)
119                 return (int)(end - src);
120         return 0;
121 }
122
123 static int try_number(const char *data, size_t dlen, u_int32_t array[],
124                       int array_size, char sep, char term)
125 {
126         u_int32_t i, len;
127
128         memset(array, 0, sizeof(array[0])*array_size);
129
130         /* Keep data pointing at next char. */
131         for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
132                 if (*data >= '0' && *data <= '9') {
133                         array[i] = array[i]*10 + *data - '0';
134                 }
135                 else if (*data == sep)
136                         i++;
137                 else {
138                         /* Unexpected character; true if it's the
139                            terminator and we're finished. */
140                         if (*data == term && i == array_size - 1)
141                                 return len;
142
143                         DEBUGP("Char %u (got %u nums) `%u' unexpected\n",
144                                len, i, *data);
145                         return 0;
146                 }
147         }
148         DEBUGP("Failed to fill %u numbers separated by %c\n", array_size, sep);
149
150         return 0;
151 }
152
153 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
154 static int try_rfc959(const char *data, size_t dlen,
155                       struct nf_conntrack_man *cmd, char term)
156 {
157         int length;
158         u_int32_t array[6];
159
160         length = try_number(data, dlen, array, 6, ',', term);
161         if (length == 0)
162                 return 0;
163
164         cmd->u3.ip =  htonl((array[0] << 24) | (array[1] << 16) |
165                                     (array[2] << 8) | array[3]);
166         cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
167         return length;
168 }
169
170 /* Grab port: number up to delimiter */
171 static int get_port(const char *data, int start, size_t dlen, char delim,
172                     u_int16_t *port)
173 {
174         u_int16_t tmp_port = 0;
175         int i;
176
177         for (i = start; i < dlen; i++) {
178                 /* Finished? */
179                 if (data[i] == delim) {
180                         if (tmp_port == 0)
181                                 break;
182                         *port = htons(tmp_port);
183                         DEBUGP("get_port: return %d\n", tmp_port);
184                         return i + 1;
185                 }
186                 else if (data[i] >= '0' && data[i] <= '9')
187                         tmp_port = tmp_port*10 + data[i] - '0';
188                 else { /* Some other crap */
189                         DEBUGP("get_port: invalid char.\n");
190                         break;
191                 }
192         }
193         return 0;
194 }
195
196 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
197 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
198                     char term)
199 {
200         char delim;
201         int length;
202
203         /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
204            then delimiter again. */
205         if (dlen <= 3) {
206                 DEBUGP("EPRT: too short\n");
207                 return 0;
208         }
209         delim = data[0];
210         if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
211                 DEBUGP("try_eprt: invalid delimitter.\n");
212                 return 0;
213         }
214
215         if ((cmd->l3num == PF_INET && data[1] != '1') ||
216             (cmd->l3num == PF_INET6 && data[1] != '2')) {
217                 DEBUGP("EPRT: invalid protocol number.\n");
218                 return 0;
219         }
220
221         DEBUGP("EPRT: Got %c%c%c\n", delim, data[1], delim);
222
223         if (data[1] == '1') {
224                 u_int32_t array[4];
225
226                 /* Now we have IP address. */
227                 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
228                 if (length != 0)
229                         cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
230                                            | (array[2] << 8) | array[3]);
231         } else {
232                 /* Now we have IPv6 address. */
233                 length = get_ipv6_addr(data + 3, dlen - 3,
234                                        (struct in6_addr *)cmd->u3.ip6, delim);
235         }
236
237         if (length == 0)
238                 return 0;
239         DEBUGP("EPRT: Got IP address!\n");
240         /* Start offset includes initial "|1|", and trailing delimiter */
241         return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
242 }
243
244 /* Returns 0, or length of numbers: |||6446| */
245 static int try_epsv_response(const char *data, size_t dlen,
246                              struct nf_conntrack_man *cmd, char term)
247 {
248         char delim;
249
250         /* Three delimiters. */
251         if (dlen <= 3) return 0;
252         delim = data[0];
253         if (isdigit(delim) || delim < 33 || delim > 126
254             || data[1] != delim || data[2] != delim)
255                 return 0;
256
257         return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
258 }
259
260 /* Return 1 for match, 0 for accept, -1 for partial. */
261 static int find_pattern(const char *data, size_t dlen,
262                         const char *pattern, size_t plen,
263                         char skip, char term,
264                         unsigned int *numoff,
265                         unsigned int *numlen,
266                         struct nf_conntrack_man *cmd,
267                         int (*getnum)(const char *, size_t,
268                                       struct nf_conntrack_man *, char))
269 {
270         size_t i;
271
272         DEBUGP("find_pattern `%s': dlen = %u\n", pattern, dlen);
273         if (dlen == 0)
274                 return 0;
275
276         if (dlen <= plen) {
277                 /* Short packet: try for partial? */
278                 if (strnicmp(data, pattern, dlen) == 0)
279                         return -1;
280                 else return 0;
281         }
282
283         if (strnicmp(data, pattern, plen) != 0) {
284 #if 0
285                 size_t i;
286
287                 DEBUGP("ftp: string mismatch\n");
288                 for (i = 0; i < plen; i++) {
289                         DEBUGP("ftp:char %u `%c'(%u) vs `%c'(%u)\n",
290                                 i, data[i], data[i],
291                                 pattern[i], pattern[i]);
292                 }
293 #endif
294                 return 0;
295         }
296
297         DEBUGP("Pattern matches!\n");
298         /* Now we've found the constant string, try to skip
299            to the 'skip' character */
300         for (i = plen; data[i] != skip; i++)
301                 if (i == dlen - 1) return -1;
302
303         /* Skip over the last character */
304         i++;
305
306         DEBUGP("Skipped up to `%c'!\n", skip);
307
308         *numoff = i;
309         *numlen = getnum(data + i, dlen - i, cmd, term);
310         if (!*numlen)
311                 return -1;
312
313         DEBUGP("Match succeeded!\n");
314         return 1;
315 }
316
317 /* Look up to see if we're just after a \n. */
318 static int find_nl_seq(u32 seq, const struct ip_ct_ftp_master *info, int dir)
319 {
320         unsigned int i;
321
322         for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
323                 if (info->seq_aft_nl[dir][i] == seq)
324                         return 1;
325         return 0;
326 }
327
328 /* We don't update if it's older than what we have. */
329 static void update_nl_seq(u32 nl_seq, struct ip_ct_ftp_master *info, int dir,
330                           struct sk_buff *skb)
331 {
332         unsigned int i, oldest = NUM_SEQ_TO_REMEMBER;
333
334         /* Look for oldest: if we find exact match, we're done. */
335         for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
336                 if (info->seq_aft_nl[dir][i] == nl_seq)
337                         return;
338
339                 if (oldest == info->seq_aft_nl_num[dir]
340                     || before(info->seq_aft_nl[dir][i], oldest))
341                         oldest = i;
342         }
343
344         if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
345                 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
346                 nf_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
347         } else if (oldest != NUM_SEQ_TO_REMEMBER) {
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 ip_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
369         unsigned int i;
370         int found = 0, ends_in_nl;
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 = { 0xFFFF }},
502                              },
503                     };
504         if (cmd.l3num == PF_INET) {
505                 exp->mask.src.u3.ip = 0xFFFFFFFF;
506                 exp->mask.dst.u3.ip = 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->flags = 0;
516
517         /* Now, NAT might want to mangle the packet, and register the
518          * (possibly changed) expectation itself. */
519         if (nf_nat_ftp_hook)
520                 ret = nf_nat_ftp_hook(pskb, ctinfo, search[dir][i].ftptype,
521                                       matchoff, matchlen, exp, &seq);
522         else {
523                 /* Can't expect this?  Best to drop packet now. */
524                 if (nf_conntrack_expect_related(exp) != 0)
525                         ret = NF_DROP;
526                 else
527                         ret = NF_ACCEPT;
528         }
529
530 out_put_expect:
531         nf_conntrack_expect_put(exp);
532
533 out_update_nl:
534         /* Now if this ends in \n, update ftp info.  Seq may have been
535          * adjusted by NAT code. */
536         if (ends_in_nl)
537                 update_nl_seq(seq, ct_ftp_info, dir, *pskb);
538  out:
539         spin_unlock_bh(&nf_ftp_lock);
540         return ret;
541 }
542
543 static struct nf_conntrack_helper ftp[MAX_PORTS][2];
544 static char ftp_names[MAX_PORTS][2][sizeof("ftp-65535")];
545
546 /* don't make this __exit, since it's called from __init ! */
547 static void nf_conntrack_ftp_fini(void)
548 {
549         int i, j;
550         for (i = 0; i < ports_c; i++) {
551                 for (j = 0; j < 2; j++) {
552                         if (ftp[i][j].me == NULL)
553                                 continue;
554
555                         DEBUGP("nf_ct_ftp: unregistering helper for pf: %d "
556                                "port: %d\n",
557                                 ftp[i][j].tuple.src.l3num, ports[i]);
558                         nf_conntrack_helper_unregister(&ftp[i][j]);
559                 }
560         }
561
562         kfree(ftp_buffer);
563 }
564
565 static int __init nf_conntrack_ftp_init(void)
566 {
567         int i, j = -1, ret = 0;
568         char *tmpname;
569
570         ftp_buffer = kmalloc(65536, GFP_KERNEL);
571         if (!ftp_buffer)
572                 return -ENOMEM;
573
574         if (ports_c == 0)
575                 ports[ports_c++] = FTP_PORT;
576
577         /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
578                  are tracked or not - YK */
579         for (i = 0; i < ports_c; i++) {
580                 ftp[i][0].tuple.src.l3num = PF_INET;
581                 ftp[i][1].tuple.src.l3num = PF_INET6;
582                 for (j = 0; j < 2; j++) {
583                         ftp[i][j].tuple.src.u.tcp.port = htons(ports[i]);
584                         ftp[i][j].tuple.dst.protonum = IPPROTO_TCP;
585                         ftp[i][j].mask.src.u.tcp.port = 0xFFFF;
586                         ftp[i][j].mask.dst.protonum = 0xFF;
587                         ftp[i][j].max_expected = 1;
588                         ftp[i][j].timeout = 5 * 60;     /* 5 Minutes */
589                         ftp[i][j].me = THIS_MODULE;
590                         ftp[i][j].help = help;
591                         tmpname = &ftp_names[i][j][0];
592                         if (ports[i] == FTP_PORT)
593                                 sprintf(tmpname, "ftp");
594                         else
595                                 sprintf(tmpname, "ftp-%d", ports[i]);
596                         ftp[i][j].name = tmpname;
597
598                         DEBUGP("nf_ct_ftp: registering helper for pf: %d "
599                                "port: %d\n",
600                                 ftp[i][j].tuple.src.l3num, ports[i]);
601                         ret = nf_conntrack_helper_register(&ftp[i][j]);
602                         if (ret) {
603                                 printk("nf_ct_ftp: failed to register helper "
604                                        " for pf: %d port: %d\n",
605                                         ftp[i][j].tuple.src.l3num, ports[i]);
606                                 nf_conntrack_ftp_fini();
607                                 return ret;
608                         }
609                 }
610         }
611
612         return 0;
613 }
614
615 module_init(nf_conntrack_ftp_init);
616 module_exit(nf_conntrack_ftp_fini);