ACPI: Kconfig - depend on PM rather than selecting it
[sfrench/cifs-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/module.h>
12 #include <linux/netfilter.h>
13 #include <linux/ip.h>
14 #include <linux/ctype.h>
15 #include <net/checksum.h>
16 #include <net/tcp.h>
17
18 #include <linux/netfilter_ipv4/ip_conntrack_helper.h>
19 #include <linux/netfilter_ipv4/ip_conntrack_ftp.h>
20 #include <linux/moduleparam.h>
21
22 MODULE_LICENSE("GPL");
23 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
24 MODULE_DESCRIPTION("ftp connection tracking helper");
25
26 /* This is slow, but it's simple. --RR */
27 static char *ftp_buffer;
28 static DEFINE_SPINLOCK(ip_ftp_lock);
29
30 #define MAX_PORTS 8
31 static unsigned short ports[MAX_PORTS];
32 static int ports_c;
33 module_param_array(ports, ushort, &ports_c, 0400);
34
35 static int loose;
36 module_param(loose, bool, 0600);
37
38 unsigned int (*ip_nat_ftp_hook)(struct sk_buff **pskb,
39                                 enum ip_conntrack_info ctinfo,
40                                 enum ip_ct_ftp_type type,
41                                 unsigned int matchoff,
42                                 unsigned int matchlen,
43                                 struct ip_conntrack_expect *exp,
44                                 u32 *seq);
45 EXPORT_SYMBOL_GPL(ip_nat_ftp_hook);
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 const struct ftp_search {
58         const char *pattern;
59         size_t plen;
60         char skip;
61         char term;
62         enum ip_ct_ftp_type ftptype;
63         int (*getnum)(const char *, size_t, u_int32_t[], char);
64 } search[IP_CT_DIR_MAX][2] = {
65         [IP_CT_DIR_ORIGINAL] = {
66                 {
67                         .pattern        =  "PORT",
68                         .plen           = sizeof("PORT") - 1,
69                         .skip           = ' ',
70                         .term           = '\r',
71                         .ftptype        = IP_CT_FTP_PORT,
72                         .getnum         = try_rfc959,
73                 },
74                 {
75                         .pattern        = "EPRT",
76                         .plen           = sizeof("EPRT") - 1,
77                         .skip           = ' ',
78                         .term           = '\r',
79                         .ftptype        = IP_CT_FTP_EPRT,
80                         .getnum         = try_eprt,
81                 },
82         },
83         [IP_CT_DIR_REPLY] = {
84                 {
85                         .pattern        = "227 ",
86                         .plen           = sizeof("227 ") - 1,
87                         .skip           = '(',
88                         .term           = ')',
89                         .ftptype        = IP_CT_FTP_PASV,
90                         .getnum         = try_rfc959,
91                 },
92                 {
93                         .pattern        = "229 ",
94                         .plen           = sizeof("229 ") - 1,
95                         .skip           = '(',
96                         .term           = ')',
97                         .ftptype        = IP_CT_FTP_EPSV,
98                         .getnum         = try_epsv_response,
99                 },
100         },
101 };
102
103 static int try_number(const char *data, size_t dlen, u_int32_t array[],
104                       int array_size, char sep, char term)
105 {
106         u_int32_t i, len;
107
108         memset(array, 0, sizeof(array[0])*array_size);
109
110         /* Keep data pointing at next char. */
111         for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
112                 if (*data >= '0' && *data <= '9') {
113                         array[i] = array[i]*10 + *data - '0';
114                 }
115                 else if (*data == sep)
116                         i++;
117                 else {
118                         /* Unexpected character; true if it's the
119                            terminator and we're finished. */
120                         if (*data == term && i == array_size - 1)
121                                 return len;
122
123                         DEBUGP("Char %u (got %u nums) `%u' unexpected\n",
124                                len, i, *data);
125                         return 0;
126                 }
127         }
128         DEBUGP("Failed to fill %u numbers separated by %c\n", array_size, sep);
129
130         return 0;
131 }
132
133 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
134 static int try_rfc959(const char *data, size_t dlen, u_int32_t array[6],
135                        char term)
136 {
137         return try_number(data, dlen, array, 6, ',', term);
138 }
139
140 /* Grab port: number up to delimiter */
141 static int get_port(const char *data, int start, size_t dlen, char delim,
142                     u_int32_t array[2])
143 {
144         u_int16_t port = 0;
145         int i;
146
147         for (i = start; i < dlen; i++) {
148                 /* Finished? */
149                 if (data[i] == delim) {
150                         if (port == 0)
151                                 break;
152                         array[0] = port >> 8;
153                         array[1] = port;
154                         return i + 1;
155                 }
156                 else if (data[i] >= '0' && data[i] <= '9')
157                         port = port*10 + data[i] - '0';
158                 else /* Some other crap */
159                         break;
160         }
161         return 0;
162 }
163
164 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| */
165 static int try_eprt(const char *data, size_t dlen, u_int32_t array[6],
166                     char term)
167 {
168         char delim;
169         int length;
170
171         /* First character is delimiter, then "1" for IPv4, then
172            delimiter again. */
173         if (dlen <= 3) return 0;
174         delim = data[0];
175         if (isdigit(delim) || delim < 33 || delim > 126
176             || data[1] != '1' || data[2] != delim)
177                 return 0;
178
179         DEBUGP("EPRT: Got |1|!\n");
180         /* Now we have IP address. */
181         length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
182         if (length == 0)
183                 return 0;
184
185         DEBUGP("EPRT: Got IP address!\n");
186         /* Start offset includes initial "|1|", and trailing delimiter */
187         return get_port(data, 3 + length + 1, dlen, delim, array+4);
188 }
189
190 /* Returns 0, or length of numbers: |||6446| */
191 static int try_epsv_response(const char *data, size_t dlen, u_int32_t array[6],
192                              char term)
193 {
194         char delim;
195
196         /* Three delimiters. */
197         if (dlen <= 3) return 0;
198         delim = data[0];
199         if (isdigit(delim) || delim < 33 || delim > 126
200             || data[1] != delim || data[2] != delim)
201                 return 0;
202
203         return get_port(data, 3, dlen, delim, array+4);
204 }
205
206 /* Return 1 for match, 0 for accept, -1 for partial. */
207 static int find_pattern(const char *data, size_t dlen,
208                         const char *pattern, size_t plen,
209                         char skip, char term,
210                         unsigned int *numoff,
211                         unsigned int *numlen,
212                         u_int32_t array[6],
213                         int (*getnum)(const char *, size_t, u_int32_t[], char))
214 {
215         size_t i;
216
217         DEBUGP("find_pattern `%s': dlen = %u\n", pattern, dlen);
218         if (dlen == 0)
219                 return 0;
220
221         if (dlen <= plen) {
222                 /* Short packet: try for partial? */
223                 if (strnicmp(data, pattern, dlen) == 0)
224                         return -1;
225                 else return 0;
226         }
227
228         if (strnicmp(data, pattern, plen) != 0) {
229 #if 0
230                 size_t i;
231
232                 DEBUGP("ftp: string mismatch\n");
233                 for (i = 0; i < plen; i++) {
234                         DEBUGP("ftp:char %u `%c'(%u) vs `%c'(%u)\n",
235                                 i, data[i], data[i],
236                                 pattern[i], pattern[i]);
237                 }
238 #endif
239                 return 0;
240         }
241
242         DEBUGP("Pattern matches!\n");
243         /* Now we've found the constant string, try to skip
244            to the 'skip' character */
245         for (i = plen; data[i] != skip; i++)
246                 if (i == dlen - 1) return -1;
247
248         /* Skip over the last character */
249         i++;
250
251         DEBUGP("Skipped up to `%c'!\n", skip);
252
253         *numoff = i;
254         *numlen = getnum(data + i, dlen - i, array, term);
255         if (!*numlen)
256                 return -1;
257
258         DEBUGP("Match succeeded!\n");
259         return 1;
260 }
261
262 /* Look up to see if we're just after a \n. */
263 static int find_nl_seq(u32 seq, const struct ip_ct_ftp_master *info, int dir)
264 {
265         unsigned int i;
266
267         for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
268                 if (info->seq_aft_nl[dir][i] == seq)
269                         return 1;
270         return 0;
271 }
272
273 /* We don't update if it's older than what we have. */
274 static void update_nl_seq(u32 nl_seq, struct ip_ct_ftp_master *info, int dir,
275                           struct sk_buff *skb)
276 {
277         unsigned int i, oldest = NUM_SEQ_TO_REMEMBER;
278
279         /* Look for oldest: if we find exact match, we're done. */
280         for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
281                 if (info->seq_aft_nl[dir][i] == nl_seq)
282                         return;
283
284                 if (oldest == info->seq_aft_nl_num[dir]
285                     || before(info->seq_aft_nl[dir][i], oldest))
286                         oldest = i;
287         }
288
289         if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
290                 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
291                 ip_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
292         } else if (oldest != NUM_SEQ_TO_REMEMBER) {
293                 info->seq_aft_nl[dir][oldest] = nl_seq;
294                 ip_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
295         }
296 }
297
298 static int help(struct sk_buff **pskb,
299                 struct ip_conntrack *ct,
300                 enum ip_conntrack_info ctinfo)
301 {
302         unsigned int dataoff, datalen;
303         struct tcphdr _tcph, *th;
304         char *fb_ptr;
305         int ret;
306         u32 seq, array[6] = { 0 };
307         int dir = CTINFO2DIR(ctinfo);
308         unsigned int matchlen, matchoff;
309         struct ip_ct_ftp_master *ct_ftp_info = &ct->help.ct_ftp_info;
310         struct ip_conntrack_expect *exp;
311         unsigned int i;
312         int found = 0, ends_in_nl;
313
314         /* Until there's been traffic both ways, don't look in packets. */
315         if (ctinfo != IP_CT_ESTABLISHED
316             && ctinfo != IP_CT_ESTABLISHED+IP_CT_IS_REPLY) {
317                 DEBUGP("ftp: Conntrackinfo = %u\n", ctinfo);
318                 return NF_ACCEPT;
319         }
320
321         th = skb_header_pointer(*pskb, (*pskb)->nh.iph->ihl*4,
322                                 sizeof(_tcph), &_tcph);
323         if (th == NULL)
324                 return NF_ACCEPT;
325
326         dataoff = (*pskb)->nh.iph->ihl*4 + th->doff*4;
327         /* No data? */
328         if (dataoff >= (*pskb)->len) {
329                 DEBUGP("ftp: pskblen = %u\n", (*pskb)->len);
330                 return NF_ACCEPT;
331         }
332         datalen = (*pskb)->len - dataoff;
333
334         spin_lock_bh(&ip_ftp_lock);
335         fb_ptr = skb_header_pointer(*pskb, dataoff,
336                                     (*pskb)->len - dataoff, ftp_buffer);
337         BUG_ON(fb_ptr == NULL);
338
339         ends_in_nl = (fb_ptr[datalen - 1] == '\n');
340         seq = ntohl(th->seq) + datalen;
341
342         /* Look up to see if we're just after a \n. */
343         if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
344                 /* Now if this ends in \n, update ftp info. */
345                 DEBUGP("ip_conntrack_ftp_help: wrong seq pos %s(%u) or %s(%u)\n",
346                        ct_ftp_info->seq_aft_nl[0][dir] 
347                        old_seq_aft_nl_set ? "":"(UNSET) ", old_seq_aft_nl);
348                 ret = NF_ACCEPT;
349                 goto out_update_nl;
350         }
351
352         /* Initialize IP array to expected address (it's not mentioned
353            in EPSV responses) */
354         array[0] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 24) & 0xFF;
355         array[1] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 16) & 0xFF;
356         array[2] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 8) & 0xFF;
357         array[3] = ntohl(ct->tuplehash[dir].tuple.src.ip) & 0xFF;
358
359         for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
360                 found = find_pattern(fb_ptr, (*pskb)->len - dataoff,
361                                      search[dir][i].pattern,
362                                      search[dir][i].plen,
363                                      search[dir][i].skip,
364                                      search[dir][i].term,
365                                      &matchoff, &matchlen,
366                                      array,
367                                      search[dir][i].getnum);
368                 if (found) break;
369         }
370         if (found == -1) {
371                 /* We don't usually drop packets.  After all, this is
372                    connection tracking, not packet filtering.
373                    However, it is necessary for accurate tracking in
374                    this case. */
375                 if (net_ratelimit())
376                         printk("conntrack_ftp: partial %s %u+%u\n",
377                                search[dir][i].pattern,
378                                ntohl(th->seq), datalen);
379                 ret = NF_DROP;
380                 goto out;
381         } else if (found == 0) { /* No match */
382                 ret = NF_ACCEPT;
383                 goto out_update_nl;
384         }
385
386         DEBUGP("conntrack_ftp: match `%s' (%u bytes at %u)\n",
387                fb_ptr + matchoff, matchlen, ntohl(th->seq) + matchoff);
388                          
389         /* Allocate expectation which will be inserted */
390         exp = ip_conntrack_expect_alloc(ct);
391         if (exp == NULL) {
392                 ret = NF_DROP;
393                 goto out;
394         }
395
396         /* We refer to the reverse direction ("!dir") tuples here,
397          * because we're expecting something in the other direction.
398          * Doesn't matter unless NAT is happening.  */
399         exp->tuple.dst.ip = ct->tuplehash[!dir].tuple.dst.ip;
400
401         if (htonl((array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3])
402             != ct->tuplehash[dir].tuple.src.ip) {
403                 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
404                    server: it really wants us to connect to a
405                    different IP address.  Simply don't record it for
406                    NAT. */
407                 DEBUGP("conntrack_ftp: NOT RECORDING: %u,%u,%u,%u != %u.%u.%u.%u\n",
408                        array[0], array[1], array[2], array[3],
409                        NIPQUAD(ct->tuplehash[dir].tuple.src.ip));
410
411                 /* Thanks to Cristiano Lincoln Mattos
412                    <lincoln@cesar.org.br> for reporting this potential
413                    problem (DMZ machines opening holes to internal
414                    networks, or the packet filter itself). */
415                 if (!loose) {
416                         ret = NF_ACCEPT;
417                         goto out_put_expect;
418                 }
419                 exp->tuple.dst.ip = htonl((array[0] << 24) | (array[1] << 16)
420                                          | (array[2] << 8) | array[3]);
421         }
422
423         exp->tuple.src.ip = ct->tuplehash[!dir].tuple.src.ip;
424         exp->tuple.dst.u.tcp.port = htons(array[4] << 8 | array[5]);
425         exp->tuple.src.u.tcp.port = 0; /* Don't care. */
426         exp->tuple.dst.protonum = IPPROTO_TCP;
427         exp->mask = ((struct ip_conntrack_tuple)
428                 { { htonl(0xFFFFFFFF), { 0 } },
429                   { htonl(0xFFFFFFFF), { .tcp = { htons(0xFFFF) } }, 0xFF }});
430
431         exp->expectfn = NULL;
432         exp->flags = 0;
433
434         /* Now, NAT might want to mangle the packet, and register the
435          * (possibly changed) expectation itself. */
436         if (ip_nat_ftp_hook)
437                 ret = ip_nat_ftp_hook(pskb, ctinfo, search[dir][i].ftptype,
438                                       matchoff, matchlen, exp, &seq);
439         else {
440                 /* Can't expect this?  Best to drop packet now. */
441                 if (ip_conntrack_expect_related(exp) != 0)
442                         ret = NF_DROP;
443                 else
444                         ret = NF_ACCEPT;
445         }
446
447 out_put_expect:
448         ip_conntrack_expect_put(exp);
449
450 out_update_nl:
451         /* Now if this ends in \n, update ftp info.  Seq may have been
452          * adjusted by NAT code. */
453         if (ends_in_nl)
454                 update_nl_seq(seq, ct_ftp_info,dir, *pskb);
455  out:
456         spin_unlock_bh(&ip_ftp_lock);
457         return ret;
458 }
459
460 static struct ip_conntrack_helper ftp[MAX_PORTS];
461 static char ftp_names[MAX_PORTS][sizeof("ftp-65535")];
462
463 /* Not __exit: called from init() */
464 static void ip_conntrack_ftp_fini(void)
465 {
466         int i;
467         for (i = 0; i < ports_c; i++) {
468                 DEBUGP("ip_ct_ftp: unregistering helper for port %d\n",
469                                 ports[i]);
470                 ip_conntrack_helper_unregister(&ftp[i]);
471         }
472
473         kfree(ftp_buffer);
474 }
475
476 static int __init ip_conntrack_ftp_init(void)
477 {
478         int i, ret;
479         char *tmpname;
480
481         ftp_buffer = kmalloc(65536, GFP_KERNEL);
482         if (!ftp_buffer)
483                 return -ENOMEM;
484
485         if (ports_c == 0)
486                 ports[ports_c++] = FTP_PORT;
487
488         for (i = 0; i < ports_c; i++) {
489                 ftp[i].tuple.src.u.tcp.port = htons(ports[i]);
490                 ftp[i].tuple.dst.protonum = IPPROTO_TCP;
491                 ftp[i].mask.src.u.tcp.port = htons(0xFFFF);
492                 ftp[i].mask.dst.protonum = 0xFF;
493                 ftp[i].max_expected = 1;
494                 ftp[i].timeout = 5 * 60; /* 5 minutes */
495                 ftp[i].me = THIS_MODULE;
496                 ftp[i].help = help;
497
498                 tmpname = &ftp_names[i][0];
499                 if (ports[i] == FTP_PORT)
500                         sprintf(tmpname, "ftp");
501                 else
502                         sprintf(tmpname, "ftp-%d", ports[i]);
503                 ftp[i].name = tmpname;
504
505                 DEBUGP("ip_ct_ftp: registering helper for port %d\n", 
506                                 ports[i]);
507                 ret = ip_conntrack_helper_register(&ftp[i]);
508
509                 if (ret) {
510                         ip_conntrack_ftp_fini();
511                         return ret;
512                 }
513         }
514         return 0;
515 }
516
517 module_init(ip_conntrack_ftp_init);
518 module_exit(ip_conntrack_ftp_fini);