Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

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