http://downloads.netgear.com/files/GPL/GPL_Source_V361j_DM111PSP_series_consumer_rele...
[bcm963xx.git] / kernel / linux / net / ipv4 / netfilter / ip_conntrack_ftp.c
1 /* FTP extension for IP connection tracking. */
2
3 /* (C) 1999-2001 Paul `Rusty' Russell  
4  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10
11 #include <linux/config.h>
12 #include <linux/module.h>
13 #include <linux/netfilter.h>
14 #include <linux/ip.h>
15 #include <linux/ctype.h>
16 #include <net/checksum.h>
17 #include <net/tcp.h>
18
19 #include <linux/netfilter_ipv4/lockhelp.h>
20 #include <linux/netfilter_ipv4/ip_conntrack_helper.h>
21 #include <linux/netfilter_ipv4/ip_conntrack_ftp.h>
22
23 MODULE_LICENSE("GPL");
24 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
25 MODULE_DESCRIPTION("ftp connection tracking helper");
26
27 /* This is slow, but it's simple. --RR */
28 //#if defined(CONFIG_MIPS_BRCM)
29 //static char ftp_buffer[16384];
30 //#else
31 //static char ftp_buffer[65536];
32 //#endif
33
34 static char ftp_buffer[4096];
35
36 DECLARE_LOCK(ip_ftp_lock);
37 struct module *ip_conntrack_ftp = THIS_MODULE;
38
39 #define MAX_PORTS 8
40 static int ports[MAX_PORTS];
41 static int ports_c;
42 MODULE_PARM(ports, "1-" __MODULE_STRING(MAX_PORTS) "i");
43
44 static int loose;
45 MODULE_PARM(loose, "i");
46
47 #if 0
48 #define DEBUGP printk
49 #else
50 #define DEBUGP(format, args...)
51 #endif
52
53 static int try_rfc959(const char *, size_t, u_int32_t [], char);
54 static int try_eprt(const char *, size_t, u_int32_t [], char);
55 static int try_epsv_response(const char *, size_t, u_int32_t [], char);
56
57 static struct ftp_search {
58         enum ip_conntrack_dir dir;
59         const char *pattern;
60         size_t plen;
61         char skip;
62         char term;
63         enum ip_ct_ftp_type ftptype;
64         int (*getnum)(const char *, size_t, u_int32_t[], char);
65 } search[] = {
66         {
67                 IP_CT_DIR_ORIGINAL,
68                 "PORT", sizeof("PORT") - 1, ' ', '\r',
69                 IP_CT_FTP_PORT,
70                 try_rfc959,
71         },
72         {
73                 IP_CT_DIR_REPLY,
74                 "227 ", sizeof("227 ") - 1, '(', ')',
75                 IP_CT_FTP_PASV,
76                 try_rfc959,
77         },
78         {
79                 IP_CT_DIR_ORIGINAL,
80                 "EPRT", sizeof("EPRT") - 1, ' ', '\r',
81                 IP_CT_FTP_EPRT,
82                 try_eprt,
83         },
84         {
85                 IP_CT_DIR_REPLY,
86                 "229 ", sizeof("229 ") - 1, '(', ')',
87                 IP_CT_FTP_EPSV,
88                 try_epsv_response,
89         },
90 };
91
92 static int try_number(const char *data, size_t dlen, u_int32_t array[],
93                       int array_size, char sep, char term)
94 {
95         u_int32_t i, len;
96
97         memset(array, 0, sizeof(array[0])*array_size);
98
99         /* Keep data pointing at next char. */
100         for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
101                 if (*data >= '0' && *data <= '9') {
102                         array[i] = array[i]*10 + *data - '0';
103                 }
104                 else if (*data == sep)
105                         i++;
106                 else {
107                         /* Unexpected character; true if it's the
108                            terminator and we're finished. */
109                         if (*data == term && i == array_size - 1)
110                                 return len;
111
112                         DEBUGP("Char %u (got %u nums) `%u' unexpected\n",
113                                len, i, *data);
114                         return 0;
115                 }
116         }
117         DEBUGP("Failed to fill %u numbers separated by %c\n", array_size, sep);
118
119         return 0;
120 }
121
122 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
123 static int try_rfc959(const char *data, size_t dlen, u_int32_t array[6],
124                        char term)
125 {
126         return try_number(data, dlen, array, 6, ',', term);
127 }
128
129 /* Grab port: number up to delimiter */
130 static int get_port(const char *data, int start, size_t dlen, char delim,
131                     u_int32_t array[2])
132 {
133         u_int16_t port = 0;
134         int i;
135
136         for (i = start; i < dlen; i++) {
137                 /* Finished? */
138                 if (data[i] == delim) {
139                         if (port == 0)
140                                 break;
141                         array[0] = port >> 8;
142                         array[1] = port;
143                         return i + 1;
144                 }
145                 else if (data[i] >= '0' && data[i] <= '9')
146                         port = port*10 + data[i] - '0';
147                 else /* Some other crap */
148                         break;
149         }
150         return 0;
151 }
152
153 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| */
154 static int try_eprt(const char *data, size_t dlen, u_int32_t array[6],
155                     char term)
156 {
157         char delim;
158         int length;
159
160         /* First character is delimiter, then "1" for IPv4, then
161            delimiter again. */
162         if (dlen <= 3) return 0;
163         delim = data[0];
164         if (isdigit(delim) || delim < 33 || delim > 126
165             || data[1] != '1' || data[2] != delim)
166                 return 0;
167
168         DEBUGP("EPRT: Got |1|!\n");
169         /* Now we have IP address. */
170         length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
171         if (length == 0)
172                 return 0;
173
174         DEBUGP("EPRT: Got IP address!\n");
175         /* Start offset includes initial "|1|", and trailing delimiter */
176         return get_port(data, 3 + length + 1, dlen, delim, array+4);
177 }
178
179 /* Returns 0, or length of numbers: |||6446| */
180 static int try_epsv_response(const char *data, size_t dlen, u_int32_t array[6],
181                              char term)
182 {
183         char delim;
184
185         /* Three delimiters. */
186         if (dlen <= 3) return 0;
187         delim = data[0];
188         if (isdigit(delim) || delim < 33 || delim > 126
189             || data[1] != delim || data[2] != delim)
190                 return 0;
191
192         return get_port(data, 3, dlen, delim, array+4);
193 }
194
195 /* Return 1 for match, 0 for accept, -1 for partial. */
196 static int find_pattern(const char *data, size_t dlen,
197                         const char *pattern, size_t plen,
198                         char skip, char term,
199                         unsigned int *numoff,
200                         unsigned int *numlen,
201                         u_int32_t array[6],
202                         int (*getnum)(const char *, size_t, u_int32_t[], char))
203 {
204         size_t i;
205
206         DEBUGP("find_pattern `%s': dlen = %u\n", pattern, dlen);
207         if (dlen == 0)
208                 return 0;
209
210         if (dlen <= plen) {
211                 /* Short packet: try for partial? */
212                 if (strnicmp(data, pattern, dlen) == 0)
213                         return -1;
214                 else return 0;
215         }
216
217         if (strnicmp(data, pattern, plen) != 0) {
218 #if 0
219                 size_t i;
220
221                 DEBUGP("ftp: string mismatch\n");
222                 for (i = 0; i < plen; i++) {
223                         DEBUGP("ftp:char %u `%c'(%u) vs `%c'(%u)\n",
224                                 i, data[i], data[i],
225                                 pattern[i], pattern[i]);
226                 }
227 #endif
228                 return 0;
229         }
230
231         DEBUGP("Pattern matches!\n");
232         /* Now we've found the constant string, try to skip
233            to the 'skip' character */
234         for (i = plen; data[i] != skip; i++)
235                 if (i == dlen - 1) return -1;
236
237         /* Skip over the last character */
238         i++;
239
240         DEBUGP("Skipped up to `%c'!\n", skip);
241
242         *numoff = i;
243         *numlen = getnum(data + i, dlen - i, array, term);
244         if (!*numlen)
245                 return -1;
246
247         DEBUGP("Match succeeded!\n");
248         return 1;
249 }
250
251 static int help(struct sk_buff *skb,
252                 struct ip_conntrack *ct,
253                 enum ip_conntrack_info ctinfo)
254 {
255         unsigned int dataoff, datalen;
256         struct tcphdr tcph;
257         u_int32_t old_seq_aft_nl;
258         int old_seq_aft_nl_set, ret;
259         u_int32_t array[6] = { 0 };
260         int dir = CTINFO2DIR(ctinfo);
261         unsigned int matchlen, matchoff;
262         struct ip_ct_ftp_master *ct_ftp_info = &ct->help.ct_ftp_info;
263         struct ip_conntrack_expect *exp;
264         struct ip_ct_ftp_expect *exp_ftp_info;
265
266         unsigned int i;
267         int found = 0;
268
269         /* Until there's been traffic both ways, don't look in packets. */
270         if (ctinfo != IP_CT_ESTABLISHED
271             && ctinfo != IP_CT_ESTABLISHED+IP_CT_IS_REPLY) {
272                 DEBUGP("ftp: Conntrackinfo = %u\n", ctinfo);
273                 return NF_ACCEPT;
274         }
275
276         if (skb_copy_bits(skb, skb->nh.iph->ihl*4, &tcph, sizeof(tcph)) != 0)
277                 return NF_ACCEPT;
278
279         dataoff = skb->nh.iph->ihl*4 + tcph.doff*4;
280         /* No data? */
281         if (dataoff >= skb->len) {
282                 DEBUGP("ftp: skblen = %u\n", skb->len);
283                 return NF_ACCEPT;
284         }
285         datalen = skb->len - dataoff;
286
287         LOCK_BH(&ip_ftp_lock);
288         skb_copy_bits(skb, dataoff, ftp_buffer, skb->len - dataoff);
289
290         old_seq_aft_nl_set = ct_ftp_info->seq_aft_nl_set[dir];
291         old_seq_aft_nl = ct_ftp_info->seq_aft_nl[dir];
292
293         DEBUGP("conntrack_ftp: datalen %u\n", datalen);
294         if (ftp_buffer[datalen - 1] == '\n') {
295                 DEBUGP("conntrack_ftp: datalen %u ends in \\n\n", datalen);
296                 if (!old_seq_aft_nl_set
297                     || after(ntohl(tcph.seq) + datalen, old_seq_aft_nl)) {
298                         DEBUGP("conntrack_ftp: updating nl to %u\n",
299                                ntohl(tcph.seq) + datalen);
300                         ct_ftp_info->seq_aft_nl[dir] = 
301                                                 ntohl(tcph.seq) + datalen;
302                         ct_ftp_info->seq_aft_nl_set[dir] = 1;
303                 }
304         }
305
306         if(!old_seq_aft_nl_set ||
307                         (ntohl(tcph.seq) != old_seq_aft_nl)) {
308                 DEBUGP("ip_conntrack_ftp_help: wrong seq pos %s(%u)\n",
309                        old_seq_aft_nl_set ? "":"(UNSET) ", old_seq_aft_nl);
310                 ret = NF_ACCEPT;
311                 goto out;
312         }
313
314         /* Initialize IP array to expected address (it's not mentioned
315            in EPSV responses) */
316         array[0] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 24) & 0xFF;
317         array[1] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 16) & 0xFF;
318         array[2] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 8) & 0xFF;
319         array[3] = ntohl(ct->tuplehash[dir].tuple.src.ip) & 0xFF;
320
321         for (i = 0; i < ARRAY_SIZE(search); i++) {
322                 if (search[i].dir != dir) continue;
323
324                 found = find_pattern(ftp_buffer, skb->len - dataoff,
325                                      search[i].pattern,
326                                      search[i].plen,
327                                      search[i].skip,
328                                      search[i].term,
329                                      &matchoff, &matchlen,
330                                      array,
331                                      search[i].getnum);
332                 if (found) break;
333         }
334         if (found == -1) {
335                 /* We don't usually drop packets.  After all, this is
336                    connection tracking, not packet filtering.
337                    However, it is necessary for accurate tracking in
338                    this case. */
339                 if (net_ratelimit())
340                         printk("conntrack_ftp: partial %s %u+%u\n",
341                                search[i].pattern,
342                                ntohl(tcph.seq), datalen);
343                 ret = NF_DROP;
344                 goto out;
345         } else if (found == 0) { /* No match */
346                 ret = NF_ACCEPT;
347                 goto out;
348         }
349
350         DEBUGP("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
351                (int)matchlen, data + matchoff,
352                matchlen, ntohl(tcph.seq) + matchoff);
353
354         /* Allocate expectation which will be inserted */
355         exp = ip_conntrack_expect_alloc();
356         if (exp == NULL) {
357                 ret = NF_ACCEPT;
358                 goto out;
359         }
360
361         exp_ftp_info = &exp->help.exp_ftp_info;
362
363         /* Update the ftp info */
364         if (htonl((array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3])
365             == ct->tuplehash[dir].tuple.src.ip) {
366                 exp->seq = ntohl(tcph.seq) + matchoff;
367                 exp_ftp_info->len = matchlen;
368                 exp_ftp_info->ftptype = search[i].ftptype;
369                 exp_ftp_info->port = array[4] << 8 | array[5];
370         } else {
371                 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
372                    server: it really wants us to connect to a
373                    different IP address.  Simply don't record it for
374                    NAT. */
375                 DEBUGP("conntrack_ftp: NOT RECORDING: %u,%u,%u,%u != %u.%u.%u.%u\n",
376                        array[0], array[1], array[2], array[3],
377                        NIPQUAD(ct->tuplehash[dir].tuple.src.ip));
378
379                 /* Thanks to Cristiano Lincoln Mattos
380                    <lincoln@cesar.org.br> for reporting this potential
381                    problem (DMZ machines opening holes to internal
382                    networks, or the packet filter itself). */
383                 if (!loose) {
384                         ret = NF_ACCEPT;
385                         goto out;
386                 }
387         }
388
389         exp->tuple = ((struct ip_conntrack_tuple)
390                 { { ct->tuplehash[!dir].tuple.src.ip,
391                     { 0 } },
392                   { htonl((array[0] << 24) | (array[1] << 16)
393                           | (array[2] << 8) | array[3]),
394                     { .tcp = { htons(array[4] << 8 | array[5]) } },
395                     IPPROTO_TCP }});
396         exp->mask = ((struct ip_conntrack_tuple)
397                 { { 0xFFFFFFFF, { 0 } },
398                   { 0xFFFFFFFF, { .tcp = { 0xFFFF } }, 0xFFFF }});
399
400         exp->expectfn = NULL;
401
402         /* Ignore failure; should only happen with NAT */
403         ip_conntrack_expect_related(exp, ct);
404         ret = NF_ACCEPT;
405  out:
406         UNLOCK_BH(&ip_ftp_lock);
407         return ret;
408 }
409
410 static struct ip_conntrack_helper ftp[MAX_PORTS];
411 static char ftp_names[MAX_PORTS][10];
412
413 /* Not __exit: called from init() */
414 static void fini(void)
415 {
416         int i;
417         for (i = 0; i < ports_c; i++) {
418                 DEBUGP("ip_ct_ftp: unregistering helper for port %d\n",
419                                 ports[i]);
420                 ip_conntrack_helper_unregister(&ftp[i]);
421         }
422 }
423
424 static int __init init(void)
425 {
426         int i, ret;
427         char *tmpname;
428
429         if (ports[0] == 0)
430                 ports[0] = FTP_PORT;
431
432         for (i = 0; (i < MAX_PORTS) && ports[i]; i++) {
433                 ftp[i].tuple.src.u.tcp.port = htons(ports[i]);
434                 ftp[i].tuple.dst.protonum = IPPROTO_TCP;
435                 ftp[i].mask.src.u.tcp.port = 0xFFFF;
436                 ftp[i].mask.dst.protonum = 0xFFFF;
437                 ftp[i].max_expected = 1;
438                 ftp[i].timeout = 0;
439                 ftp[i].flags = IP_CT_HELPER_F_REUSE_EXPECT;
440                 ftp[i].me = ip_conntrack_ftp;
441                 ftp[i].help = help;
442
443                 tmpname = &ftp_names[i][0];
444                 if (ports[i] == FTP_PORT)
445                         sprintf(tmpname, "ftp");
446                 else
447                         sprintf(tmpname, "ftp-%d", ports[i]);
448                 ftp[i].name = tmpname;
449
450                 DEBUGP("ip_ct_ftp: registering helper for port %d\n", 
451                                 ports[i]);
452                 ret = ip_conntrack_helper_register(&ftp[i]);
453
454                 if (ret) {
455                         fini();
456                         return ret;
457                 }
458                 ports_c++;
459         }
460         return 0;
461 }
462
463 PROVIDES_CONNTRACK(ftp);
464 EXPORT_SYMBOL(ip_ftp_lock);
465
466 module_init(init);
467 module_exit(fini);