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