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