Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/dtor/input
[linux-drm-fsl-dcu.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         typeof(ip_nat_ftp_hook) ip_nat_ftp;
314
315         /* Until there's been traffic both ways, don't look in packets. */
316         if (ctinfo != IP_CT_ESTABLISHED
317             && ctinfo != IP_CT_ESTABLISHED+IP_CT_IS_REPLY) {
318                 DEBUGP("ftp: Conntrackinfo = %u\n", ctinfo);
319                 return NF_ACCEPT;
320         }
321
322         th = skb_header_pointer(*pskb, (*pskb)->nh.iph->ihl*4,
323                                 sizeof(_tcph), &_tcph);
324         if (th == NULL)
325                 return NF_ACCEPT;
326
327         dataoff = (*pskb)->nh.iph->ihl*4 + th->doff*4;
328         /* No data? */
329         if (dataoff >= (*pskb)->len) {
330                 DEBUGP("ftp: pskblen = %u\n", (*pskb)->len);
331                 return NF_ACCEPT;
332         }
333         datalen = (*pskb)->len - dataoff;
334
335         spin_lock_bh(&ip_ftp_lock);
336         fb_ptr = skb_header_pointer(*pskb, dataoff,
337                                     (*pskb)->len - dataoff, ftp_buffer);
338         BUG_ON(fb_ptr == NULL);
339
340         ends_in_nl = (fb_ptr[datalen - 1] == '\n');
341         seq = ntohl(th->seq) + datalen;
342
343         /* Look up to see if we're just after a \n. */
344         if (!find_nl_seq(ntohl(th->seq), ct_ftp_info, dir)) {
345                 /* Now if this ends in \n, update ftp info. */
346                 DEBUGP("ip_conntrack_ftp_help: wrong seq pos %s(%u) or %s(%u)\n",
347                        ct_ftp_info->seq_aft_nl[0][dir]
348                        old_seq_aft_nl_set ? "":"(UNSET) ", old_seq_aft_nl);
349                 ret = NF_ACCEPT;
350                 goto out_update_nl;
351         }
352
353         /* Initialize IP array to expected address (it's not mentioned
354            in EPSV responses) */
355         array[0] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 24) & 0xFF;
356         array[1] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 16) & 0xFF;
357         array[2] = (ntohl(ct->tuplehash[dir].tuple.src.ip) >> 8) & 0xFF;
358         array[3] = ntohl(ct->tuplehash[dir].tuple.src.ip) & 0xFF;
359
360         for (i = 0; i < ARRAY_SIZE(search[dir]); i++) {
361                 found = find_pattern(fb_ptr, (*pskb)->len - dataoff,
362                                      search[dir][i].pattern,
363                                      search[dir][i].plen,
364                                      search[dir][i].skip,
365                                      search[dir][i].term,
366                                      &matchoff, &matchlen,
367                                      array,
368                                      search[dir][i].getnum);
369                 if (found) break;
370         }
371         if (found == -1) {
372                 /* We don't usually drop packets.  After all, this is
373                    connection tracking, not packet filtering.
374                    However, it is necessary for accurate tracking in
375                    this case. */
376                 if (net_ratelimit())
377                         printk("conntrack_ftp: partial %s %u+%u\n",
378                                search[dir][i].pattern,
379                                ntohl(th->seq), datalen);
380                 ret = NF_DROP;
381                 goto out;
382         } else if (found == 0) { /* No match */
383                 ret = NF_ACCEPT;
384                 goto out_update_nl;
385         }
386
387         DEBUGP("conntrack_ftp: match `%s' (%u bytes at %u)\n",
388                fb_ptr + matchoff, matchlen, ntohl(th->seq) + matchoff);
389
390         /* Allocate expectation which will be inserted */
391         exp = ip_conntrack_expect_alloc(ct);
392         if (exp == NULL) {
393                 ret = NF_DROP;
394                 goto out;
395         }
396
397         /* We refer to the reverse direction ("!dir") tuples here,
398          * because we're expecting something in the other direction.
399          * Doesn't matter unless NAT is happening.  */
400         exp->tuple.dst.ip = ct->tuplehash[!dir].tuple.dst.ip;
401
402         if (htonl((array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3])
403             != ct->tuplehash[dir].tuple.src.ip) {
404                 /* Enrico Scholz's passive FTP to partially RNAT'd ftp
405                    server: it really wants us to connect to a
406                    different IP address.  Simply don't record it for
407                    NAT. */
408                 DEBUGP("conntrack_ftp: NOT RECORDING: %u,%u,%u,%u != %u.%u.%u.%u\n",
409                        array[0], array[1], array[2], array[3],
410                        NIPQUAD(ct->tuplehash[dir].tuple.src.ip));
411
412                 /* Thanks to Cristiano Lincoln Mattos
413                    <lincoln@cesar.org.br> for reporting this potential
414                    problem (DMZ machines opening holes to internal
415                    networks, or the packet filter itself). */
416                 if (!loose) {
417                         ret = NF_ACCEPT;
418                         goto out_put_expect;
419                 }
420                 exp->tuple.dst.ip = htonl((array[0] << 24) | (array[1] << 16)
421                                          | (array[2] << 8) | array[3]);
422         }
423
424         exp->tuple.src.ip = ct->tuplehash[!dir].tuple.src.ip;
425         exp->tuple.dst.u.tcp.port = htons(array[4] << 8 | array[5]);
426         exp->tuple.src.u.tcp.port = 0; /* Don't care. */
427         exp->tuple.dst.protonum = IPPROTO_TCP;
428         exp->mask = ((struct ip_conntrack_tuple)
429                 { { htonl(0xFFFFFFFF), { 0 } },
430                   { htonl(0xFFFFFFFF), { .tcp = { htons(0xFFFF) } }, 0xFF }});
431
432         exp->expectfn = NULL;
433         exp->flags = 0;
434
435         /* Now, NAT might want to mangle the packet, and register the
436          * (possibly changed) expectation itself. */
437         ip_nat_ftp = rcu_dereference(ip_nat_ftp_hook);
438         if (ip_nat_ftp)
439                 ret = ip_nat_ftp(pskb, ctinfo, search[dir][i].ftptype,
440                                  matchoff, matchlen, exp, &seq);
441         else {
442                 /* Can't expect this?  Best to drop packet now. */
443                 if (ip_conntrack_expect_related(exp) != 0)
444                         ret = NF_DROP;
445                 else
446                         ret = NF_ACCEPT;
447         }
448
449 out_put_expect:
450         ip_conntrack_expect_put(exp);
451
452 out_update_nl:
453         /* Now if this ends in \n, update ftp info.  Seq may have been
454          * adjusted by NAT code. */
455         if (ends_in_nl)
456                 update_nl_seq(seq, ct_ftp_info,dir, *pskb);
457  out:
458         spin_unlock_bh(&ip_ftp_lock);
459         return ret;
460 }
461
462 static struct ip_conntrack_helper ftp[MAX_PORTS];
463 static char ftp_names[MAX_PORTS][sizeof("ftp-65535")];
464
465 /* Not __exit: called from init() */
466 static void ip_conntrack_ftp_fini(void)
467 {
468         int i;
469         for (i = 0; i < ports_c; i++) {
470                 DEBUGP("ip_ct_ftp: unregistering helper for port %d\n",
471                                 ports[i]);
472                 ip_conntrack_helper_unregister(&ftp[i]);
473         }
474
475         kfree(ftp_buffer);
476 }
477
478 static int __init ip_conntrack_ftp_init(void)
479 {
480         int i, ret;
481         char *tmpname;
482
483         ftp_buffer = kmalloc(65536, GFP_KERNEL);
484         if (!ftp_buffer)
485                 return -ENOMEM;
486
487         if (ports_c == 0)
488                 ports[ports_c++] = FTP_PORT;
489
490         for (i = 0; i < ports_c; i++) {
491                 ftp[i].tuple.src.u.tcp.port = htons(ports[i]);
492                 ftp[i].tuple.dst.protonum = IPPROTO_TCP;
493                 ftp[i].mask.src.u.tcp.port = htons(0xFFFF);
494                 ftp[i].mask.dst.protonum = 0xFF;
495                 ftp[i].max_expected = 1;
496                 ftp[i].timeout = 5 * 60; /* 5 minutes */
497                 ftp[i].me = THIS_MODULE;
498                 ftp[i].help = help;
499
500                 tmpname = &ftp_names[i][0];
501                 if (ports[i] == FTP_PORT)
502                         sprintf(tmpname, "ftp");
503                 else
504                         sprintf(tmpname, "ftp-%d", ports[i]);
505                 ftp[i].name = tmpname;
506
507                 DEBUGP("ip_ct_ftp: registering helper for port %d\n",
508                                 ports[i]);
509                 ret = ip_conntrack_helper_register(&ftp[i]);
510
511                 if (ret) {
512                         ip_conntrack_ftp_fini();
513                         return ret;
514                 }
515         }
516         return 0;
517 }
518
519 module_init(ip_conntrack_ftp_init);
520 module_exit(ip_conntrack_ftp_fini);