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