[NETFILTER]: nf_conntrack: endian annotations
[linux-2.6.git] / net / netfilter / nf_conntrack_ftp.c
1 /* FTP extension for connection tracking. */
2
3 /* (C) 1999-2001 Paul `Rusty' Russell
4  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
5  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * 16 Dec 2003: Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
12  *      - enable working with Layer 3 protocol independent connection tracking.
13  *      - track EPRT and EPSV commands with IPv6 address.
14  *
15  * Derived from net/ipv4/netfilter/ip_conntrack_ftp.c
16  */
17
18 #include <linux/module.h>
19 #include <linux/moduleparam.h>
20 #include <linux/netfilter.h>
21 #include <linux/ip.h>
22 #include <linux/ipv6.h>
23 #include <linux/ctype.h>
24 #include <linux/inet.h>
25 #include <net/checksum.h>
26 #include <net/tcp.h>
27
28 #include <net/netfilter/nf_conntrack.h>
29 #include <net/netfilter/nf_conntrack_expect.h>
30 #include <net/netfilter/nf_conntrack_ecache.h>
31 #include <net/netfilter/nf_conntrack_helper.h>
32 #include <linux/netfilter/nf_conntrack_ftp.h>
33
34 MODULE_LICENSE("GPL");
35 MODULE_AUTHOR("Rusty Russell <rusty@rustcorp.com.au>");
36 MODULE_DESCRIPTION("ftp connection tracking helper");
37
38 /* This is slow, but it's simple. --RR */
39 static char *ftp_buffer;
40
41 static DEFINE_SPINLOCK(nf_ftp_lock);
42
43 #define MAX_PORTS 8
44 static u_int16_t ports[MAX_PORTS];
45 static unsigned int ports_c;
46 module_param_array(ports, ushort, &ports_c, 0400);
47
48 static int loose;
49 module_param(loose, bool, 0600);
50
51 unsigned int (*nf_nat_ftp_hook)(struct sk_buff **pskb,
52                                 enum ip_conntrack_info ctinfo,
53                                 enum ip_ct_ftp_type type,
54                                 unsigned int matchoff,
55                                 unsigned int matchlen,
56                                 struct nf_conntrack_expect *exp,
57                                 u32 *seq);
58 EXPORT_SYMBOL_GPL(nf_nat_ftp_hook);
59
60 #if 0
61 #define DEBUGP printk
62 #else
63 #define DEBUGP(format, args...)
64 #endif
65
66 static int try_rfc959(const char *, size_t, struct nf_conntrack_man *, char);
67 static int try_eprt(const char *, size_t, struct nf_conntrack_man *, char);
68 static int try_epsv_response(const char *, size_t, struct nf_conntrack_man *,
69                              char);
70
71 static struct ftp_search {
72         const char *pattern;
73         size_t plen;
74         char skip;
75         char term;
76         enum ip_ct_ftp_type ftptype;
77         int (*getnum)(const char *, size_t, struct nf_conntrack_man *, char);
78 } search[IP_CT_DIR_MAX][2] = {
79         [IP_CT_DIR_ORIGINAL] = {
80                 {
81                         .pattern        = "PORT",
82                         .plen           = sizeof("PORT") - 1,
83                         .skip           = ' ',
84                         .term           = '\r',
85                         .ftptype        = IP_CT_FTP_PORT,
86                         .getnum         = try_rfc959,
87                 },
88                 {
89                         .pattern        = "EPRT",
90                         .plen           = sizeof("EPRT") - 1,
91                         .skip           = ' ',
92                         .term           = '\r',
93                         .ftptype        = IP_CT_FTP_EPRT,
94                         .getnum         = try_eprt,
95                 },
96         },
97         [IP_CT_DIR_REPLY] = {
98                 {
99                         .pattern        = "227 ",
100                         .plen           = sizeof("227 ") - 1,
101                         .skip           = '(',
102                         .term           = ')',
103                         .ftptype        = IP_CT_FTP_PASV,
104                         .getnum         = try_rfc959,
105                 },
106                 {
107                         .pattern        = "229 ",
108                         .plen           = sizeof("229 ") - 1,
109                         .skip           = '(',
110                         .term           = ')',
111                         .ftptype        = IP_CT_FTP_EPSV,
112                         .getnum         = try_epsv_response,
113                 },
114         },
115 };
116
117 static int
118 get_ipv6_addr(const char *src, size_t dlen, struct in6_addr *dst, u_int8_t term)
119 {
120         const char *end;
121         int ret = in6_pton(src, min_t(size_t, dlen, 0xffff), (u8 *)dst, term, &end);
122         if (ret > 0)
123                 return (int)(end - src);
124         return 0;
125 }
126
127 static int try_number(const char *data, size_t dlen, u_int32_t array[],
128                       int array_size, char sep, char term)
129 {
130         u_int32_t i, len;
131
132         memset(array, 0, sizeof(array[0])*array_size);
133
134         /* Keep data pointing at next char. */
135         for (i = 0, len = 0; len < dlen && i < array_size; len++, data++) {
136                 if (*data >= '0' && *data <= '9') {
137                         array[i] = array[i]*10 + *data - '0';
138                 }
139                 else if (*data == sep)
140                         i++;
141                 else {
142                         /* Unexpected character; true if it's the
143                            terminator and we're finished. */
144                         if (*data == term && i == array_size - 1)
145                                 return len;
146
147                         DEBUGP("Char %u (got %u nums) `%u' unexpected\n",
148                                len, i, *data);
149                         return 0;
150                 }
151         }
152         DEBUGP("Failed to fill %u numbers separated by %c\n", array_size, sep);
153
154         return 0;
155 }
156
157 /* Returns 0, or length of numbers: 192,168,1,1,5,6 */
158 static int try_rfc959(const char *data, size_t dlen,
159                       struct nf_conntrack_man *cmd, char term)
160 {
161         int length;
162         u_int32_t array[6];
163
164         length = try_number(data, dlen, array, 6, ',', term);
165         if (length == 0)
166                 return 0;
167
168         cmd->u3.ip =  htonl((array[0] << 24) | (array[1] << 16) |
169                                     (array[2] << 8) | array[3]);
170         cmd->u.tcp.port = htons((array[4] << 8) | array[5]);
171         return length;
172 }
173
174 /* Grab port: number up to delimiter */
175 static int get_port(const char *data, int start, size_t dlen, char delim,
176                     __be16 *port)
177 {
178         u_int16_t tmp_port = 0;
179         int i;
180
181         for (i = start; i < dlen; i++) {
182                 /* Finished? */
183                 if (data[i] == delim) {
184                         if (tmp_port == 0)
185                                 break;
186                         *port = htons(tmp_port);
187                         DEBUGP("get_port: return %d\n", tmp_port);
188                         return i + 1;
189                 }
190                 else if (data[i] >= '0' && data[i] <= '9')
191                         tmp_port = tmp_port*10 + data[i] - '0';
192                 else { /* Some other crap */
193                         DEBUGP("get_port: invalid char.\n");
194                         break;
195                 }
196         }
197         return 0;
198 }
199
200 /* Returns 0, or length of numbers: |1|132.235.1.2|6275| or |2|3ffe::1|6275| */
201 static int try_eprt(const char *data, size_t dlen, struct nf_conntrack_man *cmd,
202                     char term)
203 {
204         char delim;
205         int length;
206
207         /* First character is delimiter, then "1" for IPv4 or "2" for IPv6,
208            then delimiter again. */
209         if (dlen <= 3) {
210                 DEBUGP("EPRT: too short\n");
211                 return 0;
212         }
213         delim = data[0];
214         if (isdigit(delim) || delim < 33 || delim > 126 || data[2] != delim) {
215                 DEBUGP("try_eprt: invalid delimitter.\n");
216                 return 0;
217         }
218
219         if ((cmd->l3num == PF_INET && data[1] != '1') ||
220             (cmd->l3num == PF_INET6 && data[1] != '2')) {
221                 DEBUGP("EPRT: invalid protocol number.\n");
222                 return 0;
223         }
224
225         DEBUGP("EPRT: Got %c%c%c\n", delim, data[1], delim);
226
227         if (data[1] == '1') {
228                 u_int32_t array[4];
229
230                 /* Now we have IP address. */
231                 length = try_number(data + 3, dlen - 3, array, 4, '.', delim);
232                 if (length != 0)
233                         cmd->u3.ip = htonl((array[0] << 24) | (array[1] << 16)
234                                            | (array[2] << 8) | array[3]);
235         } else {
236                 /* Now we have IPv6 address. */
237                 length = get_ipv6_addr(data + 3, dlen - 3,
238                                        (struct in6_addr *)cmd->u3.ip6, delim);
239         }
240
241         if (length == 0)
242                 return 0;
243         DEBUGP("EPRT: Got IP address!\n");
244         /* Start offset includes initial "|1|", and trailing delimiter */
245         return get_port(data, 3 + length + 1, dlen, delim, &cmd->u.tcp.port);
246 }
247
248 /* Returns 0, or length of numbers: |||6446| */
249 static int try_epsv_response(const char *data, size_t dlen,
250                              struct nf_conntrack_man *cmd, char term)
251 {
252         char delim;
253
254         /* Three delimiters. */
255         if (dlen <= 3) return 0;
256         delim = data[0];
257         if (isdigit(delim) || delim < 33 || delim > 126
258             || data[1] != delim || data[2] != delim)
259                 return 0;
260
261         return get_port(data, 3, dlen, delim, &cmd->u.tcp.port);
262 }
263
264 /* Return 1 for match, 0 for accept, -1 for partial. */
265 static int find_pattern(const char *data, size_t dlen,
266                         const char *pattern, size_t plen,
267                         char skip, char term,
268                         unsigned int *numoff,
269                         unsigned int *numlen,
270                         struct nf_conntrack_man *cmd,
271                         int (*getnum)(const char *, size_t,
272                                       struct nf_conntrack_man *, char))
273 {
274         size_t i;
275
276         DEBUGP("find_pattern `%s': dlen = %u\n", pattern, dlen);
277         if (dlen == 0)
278                 return 0;
279
280         if (dlen <= plen) {
281                 /* Short packet: try for partial? */
282                 if (strnicmp(data, pattern, dlen) == 0)
283                         return -1;
284                 else return 0;
285         }
286
287         if (strnicmp(data, pattern, plen) != 0) {
288 #if 0
289                 size_t i;
290
291                 DEBUGP("ftp: string mismatch\n");
292                 for (i = 0; i < plen; i++) {
293                         DEBUGP("ftp:char %u `%c'(%u) vs `%c'(%u)\n",
294                                 i, data[i], data[i],
295                                 pattern[i], pattern[i]);
296                 }
297 #endif
298                 return 0;
299         }
300
301         DEBUGP("Pattern matches!\n");
302         /* Now we've found the constant string, try to skip
303            to the 'skip' character */
304         for (i = plen; data[i] != skip; i++)
305                 if (i == dlen - 1) return -1;
306
307         /* Skip over the last character */
308         i++;
309
310         DEBUGP("Skipped up to `%c'!\n", skip);
311
312         *numoff = i;
313         *numlen = getnum(data + i, dlen - i, cmd, term);
314         if (!*numlen)
315                 return -1;
316
317         DEBUGP("Match succeeded!\n");
318         return 1;
319 }
320
321 /* Look up to see if we're just after a \n. */
322 static int find_nl_seq(u32 seq, const struct ip_ct_ftp_master *info, int dir)
323 {
324         unsigned int i;
325
326         for (i = 0; i < info->seq_aft_nl_num[dir]; i++)
327                 if (info->seq_aft_nl[dir][i] == seq)
328                         return 1;
329         return 0;
330 }
331
332 /* We don't update if it's older than what we have. */
333 static void update_nl_seq(u32 nl_seq, struct ip_ct_ftp_master *info, int dir,
334                           struct sk_buff *skb)
335 {
336         unsigned int i, oldest = NUM_SEQ_TO_REMEMBER;
337
338         /* Look for oldest: if we find exact match, we're done. */
339         for (i = 0; i < info->seq_aft_nl_num[dir]; i++) {
340                 if (info->seq_aft_nl[dir][i] == nl_seq)
341                         return;
342
343                 if (oldest == info->seq_aft_nl_num[dir]
344                     || before(info->seq_aft_nl[dir][i], oldest))
345                         oldest = i;
346         }
347
348         if (info->seq_aft_nl_num[dir] < NUM_SEQ_TO_REMEMBER) {
349                 info->seq_aft_nl[dir][info->seq_aft_nl_num[dir]++] = nl_seq;
350                 nf_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
351         } else if (oldest != NUM_SEQ_TO_REMEMBER) {
352                 info->seq_aft_nl[dir][oldest] = nl_seq;
353                 nf_conntrack_event_cache(IPCT_HELPINFO_VOLATILE, skb);
354         }
355 }
356
357 static int help(struct sk_buff **pskb,
358                 unsigned int protoff,
359                 struct nf_conn *ct,
360                 enum ip_conntrack_info ctinfo)
361 {
362         unsigned int dataoff, datalen;
363         struct tcphdr _tcph, *th;
364         char *fb_ptr;
365         int ret;
366         u32 seq;
367         int dir = CTINFO2DIR(ctinfo);
368         unsigned int matchlen, matchoff;
369         struct ip_ct_ftp_master *ct_ftp_info = &nfct_help(ct)->help.ct_ftp_info;
370         struct nf_conntrack_expect *exp;
371         struct nf_conntrack_man cmd = {};
372         unsigned int i;
373         int found = 0, ends_in_nl;
374         typeof(nf_nat_ftp_hook) nf_nat_ftp;
375
376         /* Until there's been traffic both ways, don't look in packets. */
377         if (ctinfo != IP_CT_ESTABLISHED
378             && ctinfo != IP_CT_ESTABLISHED+IP_CT_IS_REPLY) {
379                 DEBUGP("ftp: Conntrackinfo = %u\n", ctinfo);
380                 return NF_ACCEPT;
381         }
382
383         th = skb_header_pointer(*pskb, protoff, sizeof(_tcph), &_tcph);
384         if (th == NULL)
385                 return NF_ACCEPT;
386
387         dataoff = protoff + th->doff * 4;
388         /* No data? */
389         if (dataoff >= (*pskb)->len) {
390                 DEBUGP("ftp: dataoff(%u) >= skblen(%u)\n", dataoff,
391                         (*pskb)->len);
392                 return NF_ACCEPT;
393         }
394         datalen = (*pskb)->len - dataoff;
395
396         spin_lock_bh(&nf_ftp_lock);
397         fb_ptr = skb_header_pointer(*pskb, dataoff, datalen, ftp_buffer);
398         BUG_ON(fb_ptr == NULL);
399
400         ends_in_nl = (fb_ptr[datalen - 1] == '\n');
401         seq = ntohl(th->seq) + datalen;
402
403         /* Look up to see if we're just after a \n. */
404         if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
405                 /* Now if this ends in \n, update ftp info. */
406                 DEBUGP("nf_conntrack_ftp_help: wrong seq pos %s(%u) or %s(%u)\n",
407                        ct_ftp_info->seq_aft_nl_num[dir] > 0 ? "" : "(UNSET)",
408                        ct_ftp_info->seq_aft_nl[dir][0],
409                        ct_ftp_info->seq_aft_nl_num[dir] > 1 ? "" : "(UNSET)",
410                        ct_ftp_info->seq_aft_nl[dir][1]);
411                 ret = NF_ACCEPT;
412                 goto out_update_nl;
413         }
414
415         /* Initialize IP/IPv6 addr to expected address (it's not mentioned
416            in EPSV responses) */
417         cmd.l3num = ct->tuplehash[dir].tuple.src.l3num;
418         memcpy(cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
419                sizeof(cmd.u3.all));
420
421         for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
422                 found = find_pattern(fb_ptr, datalen,
423                                      search[dir][i].pattern,
424                                      search[dir][i].plen,
425                                      search[dir][i].skip,
426                                      search[dir][i].term,
427                                      &matchoff, &matchlen,
428                                      &cmd,
429                                      search[dir][i].getnum);
430                 if (found) break;
431         }
432         if (found == -1) {
433                 /* We don't usually drop packets.  After all, this is
434                    connection tracking, not packet filtering.
435                    However, it is necessary for accurate tracking in
436                    this case. */
437                 if (net_ratelimit())
438                         printk("conntrack_ftp: partial %s %u+%u\n",
439                                search[dir][i].pattern,
440                                ntohl(th->seq), datalen);
441                 ret = NF_DROP;
442                 goto out;
443         } else if (found == 0) { /* No match */
444                 ret = NF_ACCEPT;
445                 goto out_update_nl;
446         }
447
448         DEBUGP("conntrack_ftp: match `%.*s' (%u bytes at %u)\n",
449                (int)matchlen, fb_ptr + matchoff,
450                matchlen, ntohl(th->seq) + matchoff);
451
452         exp = nf_conntrack_expect_alloc(ct);
453         if (exp == NULL) {
454                 ret = NF_DROP;
455                 goto out;
456         }
457
458         /* We refer to the reverse direction ("!dir") tuples here,
459          * because we're expecting something in the other direction.
460          * Doesn't matter unless NAT is happening.  */
461         exp->tuple.dst.u3 = ct->tuplehash[!dir].tuple.dst.u3;
462
463         /* Update the ftp info */
464         if ((cmd.l3num == ct->tuplehash[dir].tuple.src.l3num) &&
465             memcmp(&cmd.u3.all, &ct->tuplehash[dir].tuple.src.u3.all,
466                      sizeof(cmd.u3.all))) {
467                 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
468                    server: it really wants us to connect to a
469                    different IP address.  Simply don't record it for
470                    NAT. */
471                 if (cmd.l3num == PF_INET) {
472                         DEBUGP("conntrack_ftp: NOT RECORDING: " NIPQUAD_FMT " != " NIPQUAD_FMT "\n",
473                                NIPQUAD(cmd.u3.ip),
474                                NIPQUAD(ct->tuplehash[dir].tuple.src.u3.ip));
475                 } else {
476                         DEBUGP("conntrack_ftp: NOT RECORDING: " NIP6_FMT " != " NIP6_FMT "\n",
477                                NIP6(*((struct in6_addr *)cmd.u3.ip6)),
478                                NIP6(*((struct in6_addr *)ct->tuplehash[dir]
479                                                         .tuple.src.u3.ip6)));
480                 }
481
482                 /* Thanks to Cristiano Lincoln Mattos
483                    <lincoln@cesar.org.br> for reporting this potential
484                    problem (DMZ machines opening holes to internal
485                    networks, or the packet filter itself). */
486                 if (!loose) {
487                         ret = NF_ACCEPT;
488                         goto out_put_expect;
489                 }
490                 memcpy(&exp->tuple.dst.u3, &cmd.u3.all,
491                        sizeof(exp->tuple.dst.u3));
492         }
493
494         exp->tuple.src.u3 = ct->tuplehash[!dir].tuple.src.u3;
495         exp->tuple.src.l3num = cmd.l3num;
496         exp->tuple.src.u.tcp.port = 0;
497         exp->tuple.dst.u.tcp.port = cmd.u.tcp.port;
498         exp->tuple.dst.protonum = IPPROTO_TCP;
499
500         exp->mask = (struct nf_conntrack_tuple)
501                     { .src = { .l3num = 0xFFFF,
502                                .u = { .tcp = { 0 }},
503                              },
504                       .dst = { .protonum = 0xFF,
505                                .u = { .tcp = { __constant_htons(0xFFFF) }},
506                              },
507                     };
508         if (cmd.l3num == PF_INET) {
509                 exp->mask.src.u3.ip = htonl(0xFFFFFFFF);
510                 exp->mask.dst.u3.ip = htonl(0xFFFFFFFF);
511         } else {
512                 memset(exp->mask.src.u3.ip6, 0xFF,
513                        sizeof(exp->mask.src.u3.ip6));
514                 memset(exp->mask.dst.u3.ip6, 0xFF,
515                        sizeof(exp->mask.src.u3.ip6));
516         }
517
518         exp->expectfn = NULL;
519         exp->flags = 0;
520
521         /* Now, NAT might want to mangle the packet, and register the
522          * (possibly changed) expectation itself. */
523         nf_nat_ftp = rcu_dereference(nf_nat_ftp_hook);
524         if (nf_nat_ftp)
525                 ret = nf_nat_ftp(pskb, ctinfo, search[dir][i].ftptype,
526                                  matchoff, matchlen, exp, &seq);
527         else {
528                 /* Can't expect this?  Best to drop packet now. */
529                 if (nf_conntrack_expect_related(exp) != 0)
530                         ret = NF_DROP;
531                 else
532                         ret = NF_ACCEPT;
533         }
534
535 out_put_expect:
536         nf_conntrack_expect_put(exp);
537
538 out_update_nl:
539         /* Now if this ends in \n, update ftp info.  Seq may have been
540          * adjusted by NAT code. */
541         if (ends_in_nl)
542                 update_nl_seq(seq, ct_ftp_info, dir, *pskb);
543  out:
544         spin_unlock_bh(&nf_ftp_lock);
545         return ret;
546 }
547
548 static struct nf_conntrack_helper ftp[MAX_PORTS][2];
549 static char ftp_names[MAX_PORTS][2][sizeof("ftp-65535")];
550
551 /* don't make this __exit, since it's called from __init ! */
552 static void nf_conntrack_ftp_fini(void)
553 {
554         int i, j;
555         for (i = 0; i < ports_c; i++) {
556                 for (j = 0; j < 2; j++) {
557                         if (ftp[i][j].me == NULL)
558                                 continue;
559
560                         DEBUGP("nf_ct_ftp: unregistering helper for pf: %d "
561                                "port: %d\n",
562                                 ftp[i][j].tuple.src.l3num, ports[i]);
563                         nf_conntrack_helper_unregister(&ftp[i][j]);
564                 }
565         }
566
567         kfree(ftp_buffer);
568 }
569
570 static int __init nf_conntrack_ftp_init(void)
571 {
572         int i, j = -1, ret = 0;
573         char *tmpname;
574
575         ftp_buffer = kmalloc(65536, GFP_KERNEL);
576         if (!ftp_buffer)
577                 return -ENOMEM;
578
579         if (ports_c == 0)
580                 ports[ports_c++] = FTP_PORT;
581
582         /* FIXME should be configurable whether IPv4 and IPv6 FTP connections
583                  are tracked or not - YK */
584         for (i = 0; i < ports_c; i++) {
585                 ftp[i][0].tuple.src.l3num = PF_INET;
586                 ftp[i][1].tuple.src.l3num = PF_INET6;
587                 for (j = 0; j < 2; j++) {
588                         ftp[i][j].tuple.src.u.tcp.port = htons(ports[i]);
589                         ftp[i][j].tuple.dst.protonum = IPPROTO_TCP;
590                         ftp[i][j].mask.src.l3num = 0xFFFF;
591                         ftp[i][j].mask.src.u.tcp.port = htons(0xFFFF);
592                         ftp[i][j].mask.dst.protonum = 0xFF;
593                         ftp[i][j].max_expected = 1;
594                         ftp[i][j].timeout = 5 * 60;     /* 5 Minutes */
595                         ftp[i][j].me = THIS_MODULE;
596                         ftp[i][j].help = help;
597                         tmpname = &ftp_names[i][j][0];
598                         if (ports[i] == FTP_PORT)
599                                 sprintf(tmpname, "ftp");
600                         else
601                                 sprintf(tmpname, "ftp-%d", ports[i]);
602                         ftp[i][j].name = tmpname;
603
604                         DEBUGP("nf_ct_ftp: registering helper for pf: %d "
605                                "port: %d\n",
606                                 ftp[i][j].tuple.src.l3num, ports[i]);
607                         ret = nf_conntrack_helper_register(&ftp[i][j]);
608                         if (ret) {
609                                 printk("nf_ct_ftp: failed to register helper "
610                                        " for pf: %d port: %d\n",
611                                         ftp[i][j].tuple.src.l3num, ports[i]);
612                                 nf_conntrack_ftp_fini();
613                                 return ret;
614                         }
615                 }
616         }
617
618         return 0;
619 }
620
621 module_init(nf_conntrack_ftp_init);
622 module_exit(nf_conntrack_ftp_fini);