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