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