1 diff --git a/include/linux/netfilter/xt_layer7.h b/include/linux/netfilter/xt_layer7.h
5 +++ b/include/linux/netfilter/xt_layer7.h
10 +#define MAX_PATTERN_LEN 8192
11 +#define MAX_PROTOCOL_LEN 256
13 +struct xt_layer7_info {
14 + char protocol[MAX_PROTOCOL_LEN];
15 + char pattern[MAX_PATTERN_LEN];
19 +#endif /* _XT_LAYER7_H */
20 diff --git a/include/net/netfilter/nf_conntrack.h b/include/net/netfilter/nf_conntrack.h
21 index d9d52c0..09389b6 100644
22 --- a/include/net/netfilter/nf_conntrack.h
23 +++ b/include/net/netfilter/nf_conntrack.h
24 @@ -120,6 +120,22 @@ struct nf_conn {
26 struct nf_ct_ext *ext;
28 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
29 + defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
32 + * e.g. "http". NULL before decision. "unknown" after decision
37 + * application layer data so far. NULL after match decision.
40 + unsigned int app_data_len;
44 /* Storage reserved for other modules, must be the last member */
45 union nf_conntrack_proto proto;
47 diff --git a/net/netfilter/Kconfig b/net/netfilter/Kconfig
48 index e8d56d9..ab4ae1d 100644
49 --- a/net/netfilter/Kconfig
50 +++ b/net/netfilter/Kconfig
51 @@ -1238,6 +1238,26 @@ config NETFILTER_XT_MATCH_L2TP
53 To compile it as a module, choose M here. If unsure, say N.
55 +config NETFILTER_XT_MATCH_LAYER7
56 + tristate '"layer7" match support'
57 + depends on NETFILTER_XTABLES
58 + depends on NETFILTER_ADVANCED
59 + depends on NF_CONNTRACK
61 + Say Y if you want to be able to classify connections (and their
62 + packets) based on regular expression matching of their application
63 + layer data. This is one way to classify applications such as
64 + peer-to-peer filesharing systems that do not always use the same
67 + To compile it as a module, choose M here. If unsure, say N.
69 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
70 + bool 'Layer 7 debugging output'
71 + depends on NETFILTER_XT_MATCH_LAYER7
73 + Say Y to get lots of debugging output.
75 config NETFILTER_XT_MATCH_LENGTH
76 tristate '"length" match support'
77 depends on NETFILTER_ADVANCED
78 diff --git a/net/netfilter/Makefile b/net/netfilter/Makefile
79 index c23c3c8..916b9d5 100644
80 --- a/net/netfilter/Makefile
81 +++ b/net/netfilter/Makefile
82 @@ -174,6 +174,7 @@ obj-$(CONFIG_NETFILTER_XT_MATCH_RECENT) += xt_recent.o
83 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
84 obj-$(CONFIG_NETFILTER_XT_MATCH_SOCKET) += xt_socket.o
85 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
86 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
87 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
88 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
89 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
90 diff --git a/net/netfilter/nf_conntrack_core.c b/net/netfilter/nf_conntrack_core.c
91 index 0f87e5d..1f355a0 100644
92 --- a/net/netfilter/nf_conntrack_core.c
93 +++ b/net/netfilter/nf_conntrack_core.c
94 @@ -406,6 +406,11 @@ destroy_conntrack(struct nf_conntrack *nfct)
96 nf_ct_remove_expectations(ct);
98 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
99 + if(ct->layer7.app_data)
100 + kfree(ct->layer7.app_data);
103 nf_ct_del_from_dying_or_unconfirmed_list(ct);
106 diff --git a/net/netfilter/nf_conntrack_standalone.c b/net/netfilter/nf_conntrack_standalone.c
107 index 5f446cd..92f29f9 100644
108 --- a/net/netfilter/nf_conntrack_standalone.c
109 +++ b/net/netfilter/nf_conntrack_standalone.c
110 @@ -274,6 +274,11 @@ static int ct_seq_show(struct seq_file *s, void *v)
111 ct_show_zone(s, ct, NF_CT_DEFAULT_ZONE_DIR);
112 ct_show_delta_time(s, ct);
114 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
115 + if(ct->layer7.app_proto)
116 + seq_printf(s, "l7proto=%s ", ct->layer7.app_proto);
119 seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use));
121 if (seq_has_overflowed(s))
122 diff --git a/net/netfilter/regexp/regexp.c b/net/netfilter/regexp/regexp.c
124 index 0000000..9006988
126 +++ b/net/netfilter/regexp/regexp.c
129 + * regcomp and regexec -- regsub and regerror are elsewhere
130 + * @(#)regexp.c 1.3 of 18 April 87
132 + * Copyright (c) 1986 by University of Toronto.
133 + * Written by Henry Spencer. Not derived from licensed software.
135 + * Permission is granted to anyone to use this software for any
136 + * purpose on any computer system, and to redistribute it freely,
137 + * subject to the following restrictions:
139 + * 1. The author is not responsible for the consequences of use of
140 + * this software, no matter how awful, even if they arise
141 + * from defects in it.
143 + * 2. The origin of this software must not be misrepresented, either
144 + * by explicit claim or by omission.
146 + * 3. Altered versions must be plainly marked as such, and must not
147 + * be misrepresented as being the original software.
149 + * Beware that some of this code is subtly aware of the way operator
150 + * precedence is structured in regular expressions. Serious changes in
151 + * regular-expression syntax might require a total rethink.
153 + * This code was modified by Ethan Sommer to work within the kernel
154 + * (it now uses kmalloc etc..)
156 + * Modified slightly by Matthew Strait to use more modern C.
160 +#include "regmagic.h"
162 +/* added by ethan and matt. Lets it work in both kernel and user space.
163 +(So iptables can use it, for instance.) Yea, it goes both ways... */
165 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
167 + #define printk(format,args...) printf(format,##args)
170 +void regerror(char * s)
172 + printk("<3>Regexp: %s\n", s);
177 + * The "internal use only" fields in regexp.h are present to pass info from
178 + * compile to execute that permits the execute phase to run lots faster on
179 + * simple cases. They are:
181 + * regstart char that must begin a match; '\0' if none obvious
182 + * reganch is the match anchored (at beginning-of-line only)?
183 + * regmust string (pointer into program) that match must include, or NULL
184 + * regmlen length of regmust string
186 + * Regstart and reganch permit very fast decisions on suitable starting points
187 + * for a match, cutting down the work a lot. Regmust permits fast rejection
188 + * of lines that cannot possibly match. The regmust tests are costly enough
189 + * that regcomp() supplies a regmust only if the r.e. contains something
190 + * potentially expensive (at present, the only such thing detected is * or +
191 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
192 + * supplied because the test in regexec() needs it and regcomp() is computing
197 + * Structure for regexp "program". This is essentially a linear encoding
198 + * of a nondeterministic finite-state machine (aka syntax charts or
199 + * "railroad normal form" in parsing technology). Each node is an opcode
200 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
201 + * all nodes except BRANCH implement concatenation; a "next" pointer with
202 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
203 + * have one of the subtle syntax dependencies: an individual BRANCH (as
204 + * opposed to a collection of them) is never concatenated with anything
205 + * because of operator precedence.) The operand of some types of node is
206 + * a literal string; for others, it is a node leading into a sub-FSM. In
207 + * particular, the operand of a BRANCH node is the first node of the branch.
208 + * (NB this is *not* a tree structure: the tail of the branch connects
209 + * to the thing following the set of BRANCHes.) The opcodes are:
212 +/* definition number opnd? meaning */
213 +#define END 0 /* no End of program. */
214 +#define BOL 1 /* no Match "" at beginning of line. */
215 +#define EOL 2 /* no Match "" at end of line. */
216 +#define ANY 3 /* no Match any one character. */
217 +#define ANYOF 4 /* str Match any character in this string. */
218 +#define ANYBUT 5 /* str Match any character not in this string. */
219 +#define BRANCH 6 /* node Match this alternative, or the next... */
220 +#define BACK 7 /* no Match "", "next" ptr points backward. */
221 +#define EXACTLY 8 /* str Match this string. */
222 +#define NOTHING 9 /* no Match empty string. */
223 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
224 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
225 +#define OPEN 20 /* no Mark this point in input as start of #n. */
226 + /* OPEN+1 is number 1, etc. */
227 +#define CLOSE 30 /* no Analogous to OPEN. */
232 + * BRANCH The set of branches constituting a single choice are hooked
233 + * together with their "next" pointers, since precedence prevents
234 + * anything being concatenated to any individual branch. The
235 + * "next" pointer of the last BRANCH in a choice points to the
236 + * thing following the whole choice. This is also where the
237 + * final "next" pointer of each individual branch points; each
238 + * branch starts with the operand node of a BRANCH node.
240 + * BACK Normal "next" pointers all implicitly point forward; BACK
241 + * exists to make loop structures possible.
243 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
244 + * BRANCH structures using BACK. Simple cases (one character
245 + * per match) are implemented with STAR and PLUS for speed
246 + * and to minimize recursive plunges.
248 + * OPEN,CLOSE ...are numbered at compile time.
252 + * A node is one char of opcode followed by two chars of "next" pointer.
253 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
254 + * value is a positive offset from the opcode of the node containing it.
255 + * An operand, if any, simply follows the node. (Note that much of the
256 + * code generation knows about this implicit relationship.)
258 + * Using two bytes for the "next" pointer is vast overkill for most things,
259 + * but allows patterns to get big without disasters.
261 +#define OP(p) (*(p))
262 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
263 +#define OPERAND(p) ((p) + 3)
266 + * See regmagic.h for one further detail of program structure.
271 + * Utility definitions.
274 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
276 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
279 +#define FAIL(m) { regerror(m); return(NULL); }
280 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
281 +#define META "^$.[()|?+*\\"
284 + * Flags to be passed up and down.
286 +#define HASWIDTH 01 /* Known never to match null string. */
287 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
288 +#define SPSTART 04 /* Starts with * or +. */
289 +#define WORST 0 /* Worst case. */
292 + * Global work variables for regcomp().
294 +struct match_globals {
295 +char *reginput; /* String-input pointer. */
296 +char *regbol; /* Beginning of input, for ^ check. */
297 +char **regstartp; /* Pointer to startp array. */
298 +char **regendp; /* Ditto for endp. */
299 +char *regparse; /* Input-scan pointer. */
300 +int regnpar; /* () count. */
302 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
303 +long regsize; /* Code size. */
307 + * Forward declarations for regcomp()'s friends.
310 +#define STATIC static
312 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
313 +STATIC char *regbranch(struct match_globals *g, int *flagp);
314 +STATIC char *regpiece(struct match_globals *g, int *flagp);
315 +STATIC char *regatom(struct match_globals *g, int *flagp);
316 +STATIC char *regnode(struct match_globals *g, char op);
317 +STATIC char *regnext(struct match_globals *g, char *p);
318 +STATIC void regc(struct match_globals *g, char b);
319 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
320 +STATIC void regtail(struct match_globals *g, char *p, char *val);
321 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
324 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
331 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
332 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
333 + if (*scan1 == *scan2++)
341 + - regcomp - compile a regular expression into internal code
343 + * We can't allocate space until we know how big the compiled form will be,
344 + * but we can't compile it (and thus know how big it is) until we've got a
345 + * place to put the code. So we cheat: we compile it twice, once with code
346 + * generation turned off and size counting turned on, and once "for real".
347 + * This also means that we don't allocate space until we are sure that the
348 + * thing really will compile successfully, and we never have to move the
349 + * code and thus invalidate pointers into it. (Note that it has to be in
350 + * one piece because free() must be able to free it all.)
352 + * Beware that the optimization-preparation code in here knows about some
353 + * of the structure of the compiled regexp.
356 +regcomp(char *exp,int *patternsize)
358 + register regexp *r;
359 + register char *scan;
360 + register char *longest;
363 + struct match_globals g;
365 + /* commented out by ethan
366 + extern char *malloc();
370 + FAIL("NULL argument");
372 + /* First pass: determine size, legality. */
376 + g.regcode = &g.regdummy;
378 + if (reg(&g, 0, &flags) == NULL)
381 + /* Small enough for pointer-storage convention? */
382 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
383 + FAIL("regexp too big");
385 + /* Allocate space. */
386 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
387 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
389 + FAIL("out of space");
391 + /* Second pass: emit code. */
394 + g.regcode = r->program;
396 + if (reg(&g, 0, &flags) == NULL)
399 + /* Dig out information for optimizations. */
400 + r->regstart = '\0'; /* Worst-case defaults. */
404 + scan = r->program+1; /* First BRANCH. */
405 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
406 + scan = OPERAND(scan);
408 + /* Starting-point info. */
409 + if (OP(scan) == EXACTLY)
410 + r->regstart = *OPERAND(scan);
411 + else if (OP(scan) == BOL)
415 + * If there's something expensive in the r.e., find the
416 + * longest literal string that must appear and make it the
417 + * regmust. Resolve ties in favor of later strings, since
418 + * the regstart check works with the beginning of the r.e.
419 + * and avoiding duplication strengthens checking. Not a
420 + * strong reason, but sufficient in the absence of others.
422 + if (flags&SPSTART) {
425 + for (; scan != NULL; scan = regnext(&g, scan))
426 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
427 + longest = OPERAND(scan);
428 + len = strlen(OPERAND(scan));
430 + r->regmust = longest;
439 + - reg - regular expression, i.e. main body or parenthesized thing
441 + * Caller must absorb opening parenthesis.
443 + * Combining parenthesis handling with the base level of regular expression
444 + * is a trifle forced, but the need to tie the tails of the branches to what
445 + * follows makes it hard to avoid.
448 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
450 + register char *ret;
452 + register char *ender;
453 + register int parno = 0; /* 0 makes gcc happy */
456 + *flagp = HASWIDTH; /* Tentatively. */
458 + /* Make an OPEN node, if parenthesized. */
460 + if (g->regnpar >= NSUBEXP)
461 + FAIL("too many ()");
462 + parno = g->regnpar;
464 + ret = regnode(g, OPEN+parno);
468 + /* Pick up the branches, linking them together. */
469 + br = regbranch(g, &flags);
473 + regtail(g, ret, br); /* OPEN -> first. */
476 + if (!(flags&HASWIDTH))
477 + *flagp &= ~HASWIDTH;
478 + *flagp |= flags&SPSTART;
479 + while (*g->regparse == '|') {
481 + br = regbranch(g, &flags);
484 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
485 + if (!(flags&HASWIDTH))
486 + *flagp &= ~HASWIDTH;
487 + *flagp |= flags&SPSTART;
490 + /* Make a closing node, and hook it on the end. */
491 + ender = regnode(g, (paren) ? CLOSE+parno : END);
492 + regtail(g, ret, ender);
494 + /* Hook the tails of the branches to the closing node. */
495 + for (br = ret; br != NULL; br = regnext(g, br))
496 + regoptail(g, br, ender);
498 + /* Check for proper termination. */
499 + if (paren && *g->regparse++ != ')') {
500 + FAIL("unmatched ()");
501 + } else if (!paren && *g->regparse != '\0') {
502 + if (*g->regparse == ')') {
503 + FAIL("unmatched ()");
505 + FAIL("junk on end"); /* "Can't happen". */
513 + - regbranch - one alternative of an | operator
515 + * Implements the concatenation operator.
518 +regbranch(struct match_globals *g, int *flagp)
520 + register char *ret;
521 + register char *chain;
522 + register char *latest;
525 + *flagp = WORST; /* Tentatively. */
527 + ret = regnode(g, BRANCH);
529 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
530 + latest = regpiece(g, &flags);
531 + if (latest == NULL)
533 + *flagp |= flags&HASWIDTH;
534 + if (chain == NULL) /* First piece. */
535 + *flagp |= flags&SPSTART;
537 + regtail(g, chain, latest);
540 + if (chain == NULL) /* Loop ran zero times. */
541 + (void) regnode(g, NOTHING);
547 + - regpiece - something followed by possible [*+?]
549 + * Note that the branching code sequences used for ? and the general cases
550 + * of * and + are somewhat optimized: they use the same NOTHING node as
551 + * both the endmarker for their branch list and the body of the last branch.
552 + * It might seem that this node could be dispensed with entirely, but the
553 + * endmarker role is not redundant.
556 +regpiece(struct match_globals *g, int *flagp)
558 + register char *ret;
560 + register char *next;
563 + ret = regatom(g, &flags);
573 + if (!(flags&HASWIDTH) && op != '?')
574 + FAIL("*+ operand could be empty");
575 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
577 + if (op == '*' && (flags&SIMPLE))
578 + reginsert(g, STAR, ret);
579 + else if (op == '*') {
580 + /* Emit x* as (x&|), where & means "self". */
581 + reginsert(g, BRANCH, ret); /* Either x */
582 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
583 + regoptail(g, ret, ret); /* back */
584 + regtail(g, ret, regnode(g, BRANCH)); /* or */
585 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
586 + } else if (op == '+' && (flags&SIMPLE))
587 + reginsert(g, PLUS, ret);
588 + else if (op == '+') {
589 + /* Emit x+ as x(&|), where & means "self". */
590 + next = regnode(g, BRANCH); /* Either */
591 + regtail(g, ret, next);
592 + regtail(g, regnode(g, BACK), ret); /* loop back */
593 + regtail(g, next, regnode(g, BRANCH)); /* or */
594 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
595 + } else if (op == '?') {
596 + /* Emit x? as (x|) */
597 + reginsert(g, BRANCH, ret); /* Either x */
598 + regtail(g, ret, regnode(g, BRANCH)); /* or */
599 + next = regnode(g, NOTHING); /* null. */
600 + regtail(g, ret, next);
601 + regoptail(g, ret, next);
604 + if (ISMULT(*g->regparse))
605 + FAIL("nested *?+");
611 + - regatom - the lowest level
613 + * Optimization: gobbles an entire sequence of ordinary characters so that
614 + * it can turn them into a single node, which is smaller to store and
615 + * faster to run. Backslashed characters are exceptions, each becoming a
616 + * separate node; the code is simpler that way and it's not worth fixing.
619 +regatom(struct match_globals *g, int *flagp)
621 + register char *ret;
624 + *flagp = WORST; /* Tentatively. */
626 + switch (*g->regparse++) {
628 + ret = regnode(g, BOL);
631 + ret = regnode(g, EOL);
634 + ret = regnode(g, ANY);
635 + *flagp |= HASWIDTH|SIMPLE;
638 + register int class;
639 + register int classend;
641 + if (*g->regparse == '^') { /* Complement of range. */
642 + ret = regnode(g, ANYBUT);
645 + ret = regnode(g, ANYOF);
646 + if (*g->regparse == ']' || *g->regparse == '-')
647 + regc(g, *g->regparse++);
648 + while (*g->regparse != '\0' && *g->regparse != ']') {
649 + if (*g->regparse == '-') {
651 + if (*g->regparse == ']' || *g->regparse == '\0')
654 + class = UCHARAT(g->regparse-2)+1;
655 + classend = UCHARAT(g->regparse);
656 + if (class > classend+1)
657 + FAIL("invalid [] range");
658 + for (; class <= classend; class++)
663 + regc(g, *g->regparse++);
666 + if (*g->regparse != ']')
667 + FAIL("unmatched []");
669 + *flagp |= HASWIDTH|SIMPLE;
673 + ret = reg(g, 1, &flags);
676 + *flagp |= flags&(HASWIDTH|SPSTART);
681 + FAIL("internal urp"); /* Supposed to be caught earlier. */
686 + FAIL("?+* follows nothing");
689 + if (*g->regparse == '\0')
690 + FAIL("trailing \\");
691 + ret = regnode(g, EXACTLY);
692 + regc(g, *g->regparse++);
694 + *flagp |= HASWIDTH|SIMPLE;
698 + register char ender;
701 + len = my_strcspn((const char *)g->regparse, (const char *)META);
703 + FAIL("internal disaster");
704 + ender = *(g->regparse+len);
705 + if (len > 1 && ISMULT(ender))
706 + len--; /* Back off clear of ?+* operand. */
707 + *flagp |= HASWIDTH;
710 + ret = regnode(g, EXACTLY);
712 + regc(g, *g->regparse++);
724 + - regnode - emit a node
726 +static char * /* Location. */
727 +regnode(struct match_globals *g, char op)
729 + register char *ret;
730 + register char *ptr;
733 + if (ret == &g->regdummy) {
740 + *ptr++ = '\0'; /* Null "next" pointer. */
748 + - regc - emit (if appropriate) a byte of code
751 +regc(struct match_globals *g, char b)
753 + if (g->regcode != &g->regdummy)
760 + - reginsert - insert an operator in front of already-emitted operand
762 + * Means relocating the operand.
765 +reginsert(struct match_globals *g, char op, char* opnd)
767 + register char *src;
768 + register char *dst;
769 + register char *place;
771 + if (g->regcode == &g->regdummy) {
782 + place = opnd; /* Op node, where operand used to be. */
789 + - regtail - set the next-pointer at the end of a node chain
792 +regtail(struct match_globals *g, char *p, char *val)
794 + register char *scan;
795 + register char *temp;
796 + register int offset;
798 + if (p == &g->regdummy)
801 + /* Find last node. */
804 + temp = regnext(g, scan);
810 + if (OP(scan) == BACK)
811 + offset = scan - val;
813 + offset = val - scan;
814 + *(scan+1) = (offset>>8)&0377;
815 + *(scan+2) = offset&0377;
819 + - regoptail - regtail on operand of first argument; nop if operandless
822 +regoptail(struct match_globals *g, char *p, char *val)
824 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
825 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
827 + regtail(g, OPERAND(p), val);
831 + * regexec and friends
838 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
839 +STATIC int regmatch(struct match_globals *g, char *prog);
840 +STATIC int regrepeat(struct match_globals *g, char *p);
845 +STATIC char *regprop(char *op);
849 + - regexec - match a regexp against a string
852 +regexec(regexp *prog, char *string)
855 + struct match_globals g;
857 + /* Be paranoid... */
858 + if (prog == NULL || string == NULL) {
859 + printk("<3>Regexp: NULL parameter\n");
863 + /* Check validity of program. */
864 + if (UCHARAT(prog->program) != MAGIC) {
865 + printk("<3>Regexp: corrupted program\n");
869 + /* If there is a "must appear" string, look for it. */
870 + if (prog->regmust != NULL) {
872 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
873 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
874 + break; /* Found it. */
877 + if (s == NULL) /* Not present. */
881 + /* Mark beginning of line for ^ . */
884 + /* Simplest case: anchored match need be tried only once. */
886 + return(regtry(&g, prog, string));
888 + /* Messy cases: unanchored match. */
890 + if (prog->regstart != '\0')
891 + /* We know what char it must start with. */
892 + while ((s = strchr(s, prog->regstart)) != NULL) {
893 + if (regtry(&g, prog, s))
898 + /* We don't -- general case. */
900 + if (regtry(&g, prog, s))
902 + } while (*s++ != '\0');
909 + - regtry - try match at specific point
911 +static int /* 0 failure, 1 success */
912 +regtry(struct match_globals *g, regexp *prog, char *string)
915 + register char **sp;
916 + register char **ep;
918 + g->reginput = string;
919 + g->regstartp = prog->startp;
920 + g->regendp = prog->endp;
924 + for (i = NSUBEXP; i > 0; i--) {
928 + if (regmatch(g, prog->program + 1)) {
929 + prog->startp[0] = string;
930 + prog->endp[0] = g->reginput;
937 + - regmatch - main matching routine
939 + * Conceptually the strategy is simple: check to see whether the current
940 + * node matches, call self recursively to see whether the rest matches,
941 + * and then act accordingly. In practice we make some effort to avoid
942 + * recursion, in particular by going through "ordinary" nodes (that don't
943 + * need to know whether the rest of the match failed) by a loop instead of
946 +static int /* 0 failure, 1 success */
947 +regmatch(struct match_globals *g, char *prog)
949 + register char *scan = prog; /* Current node. */
950 + char *next; /* Next node. */
953 + if (scan != NULL && regnarrate)
954 + fprintf(stderr, "%s(\n", regprop(scan));
956 + while (scan != NULL) {
959 + fprintf(stderr, "%s...\n", regprop(scan));
961 + next = regnext(g, scan);
963 + switch (OP(scan)) {
965 + if (g->reginput != g->regbol)
969 + if (*g->reginput != '\0')
973 + if (*g->reginput == '\0')
979 + register char *opnd;
981 + opnd = OPERAND(scan);
982 + /* Inline the first character, for speed. */
983 + if (*opnd != *g->reginput)
985 + len = strlen(opnd);
986 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
988 + g->reginput += len;
992 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
997 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1014 + register char *save;
1016 + no = OP(scan) - OPEN;
1017 + save = g->reginput;
1019 + if (regmatch(g, next)) {
1021 + * Don't set startp if some later
1022 + * invocation of the same parentheses
1025 + if (g->regstartp[no] == NULL)
1026 + g->regstartp[no] = save;
1043 + register char *save;
1045 + no = OP(scan) - CLOSE;
1046 + save = g->reginput;
1048 + if (regmatch(g, next)) {
1050 + * Don't set endp if some later
1051 + * invocation of the same parentheses
1054 + if (g->regendp[no] == NULL)
1055 + g->regendp[no] = save;
1062 + register char *save;
1064 + if (OP(next) != BRANCH) /* No choice. */
1065 + next = OPERAND(scan); /* Avoid recursion. */
1068 + save = g->reginput;
1069 + if (regmatch(g, OPERAND(scan)))
1071 + g->reginput = save;
1072 + scan = regnext(g, scan);
1073 + } while (scan != NULL && OP(scan) == BRANCH);
1081 + register char nextch;
1083 + register char *save;
1087 + * Lookahead to avoid useless match attempts
1088 + * when we know what character comes next.
1091 + if (OP(next) == EXACTLY)
1092 + nextch = *OPERAND(next);
1093 + min = (OP(scan) == STAR) ? 0 : 1;
1094 + save = g->reginput;
1095 + no = regrepeat(g, OPERAND(scan));
1096 + while (no >= min) {
1097 + /* If it could work, try it. */
1098 + if (nextch == '\0' || *g->reginput == nextch)
1099 + if (regmatch(g, next))
1101 + /* Couldn't or didn't -- back up. */
1103 + g->reginput = save + no;
1109 + return(1); /* Success! */
1112 + printk("<3>Regexp: memory corruption\n");
1121 + * We get here only if there's trouble -- normally "case END" is
1122 + * the terminating point.
1124 + printk("<3>Regexp: corrupted pointers\n");
1129 + - regrepeat - repeatedly match something simple, report how many
1132 +regrepeat(struct match_globals *g, char *p)
1134 + register int count = 0;
1135 + register char *scan;
1136 + register char *opnd;
1138 + scan = g->reginput;
1139 + opnd = OPERAND(p);
1142 + count = strlen(scan);
1146 + while (*opnd == *scan) {
1152 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1158 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1163 + default: /* Oh dear. Called inappropriately. */
1164 + printk("<3>Regexp: internal foulup\n");
1165 + count = 0; /* Best compromise. */
1168 + g->reginput = scan;
1174 + - regnext - dig the "next" pointer out of a node
1177 +regnext(struct match_globals *g, char *p)
1179 + register int offset;
1181 + if (p == &g->regdummy)
1188 + if (OP(p) == BACK)
1196 +STATIC char *regprop();
1199 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1205 + register char op = EXACTLY; /* Arbitrary non-END op. */
1206 + register char *next;
1207 + /* extern char *strchr(); */
1210 + s = r->program + 1;
1211 + while (op != END) { /* While that wasn't END last time... */
1213 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1214 + next = regnext(s);
1215 + if (next == NULL) /* Next ptr. */
1218 + printf("(%d)", (s-r->program)+(next-s));
1220 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1221 + /* Literal string, where present. */
1222 + while (*s != '\0') {
1231 + /* Header fields of interest. */
1232 + if (r->regstart != '\0')
1233 + printf("start `%c' ", r->regstart);
1235 + printf("anchored ");
1236 + if (r->regmust != NULL)
1237 + printf("must have \"%s\"", r->regmust);
1242 + - regprop - printable representation of opcode
1249 + static char buf[BUFLEN];
1293 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1305 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1315 + printk("<3>Regexp: corrupted opcode\n");
1319 + strncat(buf, p, BUFLEN-strlen(buf));
1325 diff --git a/net/netfilter/regexp/regexp.h b/net/netfilter/regexp/regexp.h
1326 new file mode 100644
1327 index 0000000..a72eba7
1329 +++ b/net/netfilter/regexp/regexp.h
1332 + * Definitions etc. for regexp(3) routines.
1334 + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
1335 + * not the System V one.
1343 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1344 +which contains a version of this library, says:
1347 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1348 + * will not work properly.
1351 +However, it looks rather like this library is limited to 10. If you think
1352 +otherwise, let us know.
1356 +typedef struct regexp {
1357 + char *startp[NSUBEXP];
1358 + char *endp[NSUBEXP];
1359 + char regstart; /* Internal use only. */
1360 + char reganch; /* Internal use only. */
1361 + char *regmust; /* Internal use only. */
1362 + int regmlen; /* Internal use only. */
1363 + char program[1]; /* Unwarranted chumminess with compiler. */
1366 +regexp * regcomp(char *exp, int *patternsize);
1367 +int regexec(regexp *prog, char *string);
1368 +void regsub(regexp *prog, char *source, char *dest);
1369 +void regerror(char *s);
1372 diff --git a/net/netfilter/regexp/regmagic.h b/net/netfilter/regexp/regmagic.h
1373 new file mode 100644
1374 index 0000000..5acf447
1376 +++ b/net/netfilter/regexp/regmagic.h
1379 + * The first byte of the regexp internal "program" is actually this magic
1380 + * number; the start node begins in the second byte.
1383 diff --git a/net/netfilter/regexp/regsub.c b/net/netfilter/regexp/regsub.c
1384 new file mode 100644
1385 index 0000000..339631f
1387 +++ b/net/netfilter/regexp/regsub.c
1391 + * @(#)regsub.c 1.3 of 2 April 86
1393 + * Copyright (c) 1986 by University of Toronto.
1394 + * Written by Henry Spencer. Not derived from licensed software.
1396 + * Permission is granted to anyone to use this software for any
1397 + * purpose on any computer system, and to redistribute it freely,
1398 + * subject to the following restrictions:
1400 + * 1. The author is not responsible for the consequences of use of
1401 + * this software, no matter how awful, even if they arise
1402 + * from defects in it.
1404 + * 2. The origin of this software must not be misrepresented, either
1405 + * by explicit claim or by omission.
1407 + * 3. Altered versions must be plainly marked as such, and must not
1408 + * be misrepresented as being the original software.
1411 + * This code was modified by Ethan Sommer to work within the kernel
1412 + * (it now uses kmalloc etc..)
1415 +#include "regexp.h"
1416 +#include "regmagic.h"
1417 +#include <linux/string.h>
1421 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1423 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
1427 +//void regerror(char * s)
1429 +// printk("regexp(3): %s", s);
1430 +// /* NOTREACHED */
1435 + - regsub - perform substitutions after a regexp match
1438 +regsub(regexp * prog, char * source, char * dest)
1440 + register char *src;
1441 + register char *dst;
1446 + /* Not necessary and gcc doesn't like it -MLS */
1447 + /*extern char *strncpy();*/
1449 + if (prog == NULL || source == NULL || dest == NULL) {
1450 + regerror("NULL parm to regsub");
1453 + if (UCHARAT(prog->program) != MAGIC) {
1454 + regerror("damaged regexp fed to regsub");
1460 + while ((c = *src++) != '\0') {
1463 + else if (c == '\\' && '0' <= *src && *src <= '9')
1464 + no = *src++ - '0';
1468 + if (no < 0) { /* Ordinary character. */
1469 + if (c == '\\' && (*src == '\\' || *src == '&'))
1472 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
1473 + len = prog->endp[no] - prog->startp[no];
1474 + (void) strncpy(dst, prog->startp[no], len);
1476 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
1477 + regerror("damaged match string");
1484 diff --git a/net/netfilter/xt_layer7.c b/net/netfilter/xt_layer7.c
1485 new file mode 100644
1486 index 0000000..ddf7fec
1488 +++ b/net/netfilter/xt_layer7.c
1491 + Kernel module to match application layer (OSI layer 7) data in connections.
1493 + http://l7-filter.sf.net
1495 + (C) 2003-2009 Matthew Strait and Ethan Sommer.
1497 + This program is free software; you can redistribute it and/or
1498 + modify it under the terms of the GNU General Public License
1499 + as published by the Free Software Foundation; either version
1500 + 2 of the License, or (at your option) any later version.
1501 + http://www.gnu.org/licenses/gpl.txt
1503 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
1504 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
1505 + Ethan Sommer, Justin Levandoski.
1508 +#include <linux/spinlock.h>
1509 +#include <linux/version.h>
1510 +#include <net/ip.h>
1511 +#include <net/tcp.h>
1512 +#include <linux/module.h>
1513 +#include <linux/skbuff.h>
1514 +#include <linux/netfilter.h>
1515 +#include <net/netfilter/nf_conntrack.h>
1516 +#include <net/netfilter/nf_conntrack_core.h>
1517 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
1518 +#include <net/netfilter/nf_conntrack_extend.h>
1519 +#include <net/netfilter/nf_conntrack_acct.h>
1521 +#include <linux/netfilter/x_tables.h>
1522 +#include <linux/netfilter/xt_layer7.h>
1523 +#include <linux/ctype.h>
1524 +#include <linux/proc_fs.h>
1526 +#include "regexp/regexp.c"
1528 +MODULE_LICENSE("GPL");
1529 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>, Arne Fitzenreiter <arne_f@ipfire.org>");
1530 +MODULE_DESCRIPTION("iptables application layer match module");
1531 +MODULE_ALIAS("ipt_layer7");
1532 +MODULE_VERSION("2.30");
1534 +static int maxdatalen = 2048; // this is the default
1535 +module_param(maxdatalen, int, 0444);
1536 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
1537 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
1538 + #define DPRINTK(format,args...) printk(format,##args)
1540 + #define DPRINTK(format,args...)
1543 +/* Number of packets whose data we look at.
1544 +This can be modified through /proc/net/layer7_numpackets */
1545 +static int num_packets = 10;
1547 +static struct pattern_cache {
1548 + char * regex_string;
1550 + struct pattern_cache * next;
1551 +} * first_pattern_cache = NULL;
1553 +static struct proto_cache {
1554 + char * proto_string;
1555 + struct proto_cache * next;
1556 +} * first_proto_cache = NULL;
1558 +DEFINE_SPINLOCK(l7_lock);
1560 +static int total_acct_packets(struct nf_conn *ct)
1562 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 26)
1563 + BUG_ON(ct == NULL);
1564 + return (ct->counters[IP_CT_DIR_ORIGINAL].packets + ct->counters[IP_CT_DIR_REPLY].packets);
1566 + struct nf_conn_counter *acct;
1568 + BUG_ON(ct == NULL);
1569 + acct = nf_conn_acct_find(ct);
1572 + return (atomic64_read(&acct[IP_CT_DIR_ORIGINAL].packets) + atomic64_read(&acct[IP_CT_DIR_REPLY].packets));
1576 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1577 +/* Converts an unfriendly string into a friendly one by
1578 +replacing unprintables with periods and all whitespace with " ". */
1579 +static char * friendly_print(unsigned char * s)
1581 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
1585 + if (net_ratelimit())
1586 + printk(KERN_ERR "layer7: out of memory in "
1587 + "friendly_print, bailing.\n");
1591 + for(i = 0; i < strlen(s); i++){
1592 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
1593 + else if(isspace(s[i])) f[i] = ' ';
1600 +static char dec2hex(int i)
1607 + return (i - 10 + 'a');
1610 + if (net_ratelimit())
1611 + printk("layer7: Problem in dec2hex\n");
1616 +static char * hex_print(unsigned char * s)
1618 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
1622 + if (net_ratelimit())
1623 + printk(KERN_ERR "layer7: out of memory in hex_print, "
1628 + for(i = 0; i < strlen(s); i++) {
1629 + g[i*3 ] = dec2hex(s[i]/16);
1630 + g[i*3 + 1] = dec2hex(s[i]%16);
1639 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
1640 +over again, it make sense to cache the results. */
1641 +static regexp * compile_and_cache(const char * regex_string,
1642 + const char * protocol)
1644 + struct pattern_cache * node = first_pattern_cache;
1645 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
1646 + struct pattern_cache * tmp;
1649 + while (node != NULL) {
1650 + if (!strcmp(node->regex_string, regex_string))
1651 + return node->pattern;
1653 + last_pattern_cache = node;/* points at the last non-NULL node */
1654 + node = node->next;
1657 + /* If we reach the end of the list, then we have not yet cached
1658 + the pattern for this regex. Let's do that now.
1659 + Be paranoid about running out of memory to avoid list corruption. */
1660 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
1663 + if (net_ratelimit())
1664 + printk(KERN_ERR "layer7: out of memory in "
1665 + "compile_and_cache, bailing.\n");
1669 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
1670 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
1673 + if(!tmp->regex_string || !tmp->pattern) {
1674 + if (net_ratelimit())
1675 + printk(KERN_ERR "layer7: out of memory in "
1676 + "compile_and_cache, bailing.\n");
1677 + kfree(tmp->regex_string);
1678 + kfree(tmp->pattern);
1683 + /* Ok. The new node is all ready now. */
1686 + if(first_pattern_cache == NULL) /* list is empty */
1687 + first_pattern_cache = node; /* make node the beginning */
1689 + last_pattern_cache->next = node; /* attach node to the end */
1691 + /* copy the string and compile the regex */
1692 + len = strlen(regex_string);
1693 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
1694 + node->pattern = regcomp((char *)regex_string, &len);
1695 + if ( !node->pattern ) {
1696 + if (net_ratelimit())
1697 + printk(KERN_ERR "layer7: Error compiling regexp "
1699 + regex_string, protocol);
1700 + /* pattern is now cached as NULL, so we won't try again. */
1703 + strcpy(node->regex_string, regex_string);
1704 + return node->pattern;
1707 +static char * get_protostr_ptr(const char * protocol)
1709 + struct proto_cache * node = first_proto_cache;
1710 + struct proto_cache * last_proto_cache = first_proto_cache;
1711 + struct proto_cache * tmp;
1713 + while (node != NULL) {
1714 + if (!strcmp(node->proto_string, protocol))
1715 + return node->proto_string;
1717 + last_proto_cache = node;/* points at the last non-NULL node */
1718 + node = node->next;
1721 + /* If we reach the end of the list, then we have not yet cached protocol
1722 + Be paranoid about running out of memory to avoid list corruption. */
1723 + tmp = kmalloc(sizeof(struct proto_cache), GFP_ATOMIC);
1726 + if (net_ratelimit())
1727 + printk(KERN_ERR "layer7: out of memory in "
1728 + "proto_cache add, bailing.\n");
1732 + tmp->proto_string = kmalloc(strlen(protocol) + 1 , GFP_ATOMIC);
1735 + if(!tmp->proto_string) {
1736 + if (net_ratelimit())
1737 + printk(KERN_ERR "layer7: out of memory in "
1738 + "proto_cache add, bailing.\n");
1739 + kfree(tmp->proto_string);
1744 + /* Ok. The new node is all ready now. */
1747 + if(first_proto_cache == NULL) /* list is empty */
1748 + first_proto_cache = node; /* make node the beginning */
1750 + last_proto_cache->next = node; /* attach node to the end */
1752 + strcpy(node->proto_string, protocol);
1753 + return node->proto_string;
1756 +static int can_handle(const struct sk_buff *skb)
1758 + if(!ip_hdr(skb)) /* not IP */
1760 + if(ip_hdr(skb)->protocol != IPPROTO_TCP &&
1761 + ip_hdr(skb)->protocol != IPPROTO_UDP &&
1762 + ip_hdr(skb)->protocol != IPPROTO_ICMP)
1767 +/* Returns offset the into the skb->data that the application data starts */
1768 +static int app_data_offset(const struct sk_buff *skb)
1770 + /* In case we are ported somewhere (ebtables?) where ip_hdr(skb)
1771 + isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
1772 + int ip_hl = 4*ip_hdr(skb)->ihl;
1774 + if( ip_hdr(skb)->protocol == IPPROTO_TCP ) {
1775 + /* 12 == offset into TCP header for the header length field.
1776 + Can't get this with skb->h.th->doff because the tcphdr
1777 + struct doesn't get set when routing (this is confirmed to be
1778 + true in Netfilter as well as QoS.) */
1779 + int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
1781 + return ip_hl + tcp_hl;
1782 + } else if( ip_hdr(skb)->protocol == IPPROTO_UDP ) {
1783 + return ip_hl + 8; /* UDP header is always 8 bytes */
1784 + } else if( ip_hdr(skb)->protocol == IPPROTO_ICMP ) {
1785 + return ip_hl + 8; /* ICMP header is 8 bytes */
1787 + if (net_ratelimit())
1788 + printk(KERN_ERR "layer7: tried to handle unknown "
1790 + return ip_hl + 8; /* something reasonable */
1794 +/* handles whether there's a match when we aren't appending data anymore */
1795 +static int match_no_append(struct nf_conn * conntrack,
1796 + struct nf_conn * master_conntrack,
1797 + enum ip_conntrack_info ctinfo,
1798 + enum ip_conntrack_info master_ctinfo,
1799 + const struct xt_layer7_info * info)
1801 + /* If we're in here, throw the app data away */
1802 + if(master_conntrack->layer7.app_data != NULL) {
1804 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1805 + if(!master_conntrack->layer7.app_proto) {
1807 + friendly_print(master_conntrack->layer7.app_data);
1809 + hex_print(master_conntrack->layer7.app_data);
1810 + DPRINTK("\nl7-filter gave up after %d bytes "
1811 + "(%d packets):\n%s\n",
1812 + strlen(f), total_acct_packets(master_conntrack), f);
1814 + DPRINTK("In hex: %s\n", g);
1819 + kfree(master_conntrack->layer7.app_data);
1820 + master_conntrack->layer7.app_data = NULL; /* don't free again */
1823 + if(master_conntrack->layer7.app_proto){
1824 + /* Here child connections set their .app_proto (for /proc) */
1825 + if(!conntrack->layer7.app_proto) {
1826 + conntrack->layer7.app_proto = master_conntrack->layer7.app_proto;
1829 + return (!strcmp(master_conntrack->layer7.app_proto,
1833 + /* If not classified, set to "unknown" to distinguish from
1834 + connections that are still being tested. */
1835 + master_conntrack->layer7.app_proto = get_protostr_ptr("unknown");
1840 +/* add the new app data to the conntrack. Return number of bytes added. */
1841 +static int add_data(struct nf_conn * master_conntrack,
1842 + char * app_data, int appdatalen)
1844 + int length = 0, i;
1845 + int oldlength = master_conntrack->layer7.app_data_len;
1847 + /* This is a fix for a race condition by Deti Fliegl. However, I'm not
1848 + clear on whether the race condition exists or whether this really
1849 + fixes it. I might just be being dense... Anyway, if it's not really
1850 + a fix, all it does is waste a very small amount of time. */
1851 + if(!master_conntrack->layer7.app_data) return 0;
1853 + /* Strip nulls. Make everything lower case (our regex lib doesn't
1854 + do case insensitivity). Add it to the end of the current data. */
1855 + for(i = 0; i < maxdatalen-oldlength-1 &&
1856 + i < appdatalen; i++) {
1857 + if(app_data[i] != '\0') {
1858 + /* the kernel version of tolower mungs 'upper ascii' */
1859 + master_conntrack->layer7.app_data[length+oldlength] =
1860 + isascii(app_data[i])?
1861 + tolower(app_data[i]) : app_data[i];
1866 + master_conntrack->layer7.app_data[length+oldlength] = '\0';
1867 + master_conntrack->layer7.app_data_len = length + oldlength;
1872 +/* taken from drivers/video/modedb.c */
1873 +static int my_atoi(const char *s)
1880 + val = 10*val+(*s-'0');
1888 +static int layer7_numpackets_proc_show(struct seq_file *s, void *p) {
1889 + seq_printf(s, "%d\n", num_packets);
1894 +static int layer7_numpackets_proc_open(struct inode *inode, struct file *file) {
1895 + return single_open(file, layer7_numpackets_proc_show, NULL);
1898 +/* Read in num_packets from userland */
1899 +static ssize_t layer7_numpackets_write_proc(struct file* file, const char __user *buffer,
1900 + size_t count, loff_t *data) {
1902 + int new_num_packets;
1904 + if (copy_from_user(&value, buffer, sizeof(value)))
1907 + new_num_packets = my_atoi(value);
1909 + if ((new_num_packets < 1) || (new_num_packets > 99)) {
1910 + printk(KERN_WARNING "layer7: numpackets must be between 1 and 99\n");
1914 + num_packets = new_num_packets;
1920 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35)
1921 +match(const struct sk_buff *skbin, struct xt_action_param *par)
1922 +#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
1923 +match(const struct sk_buff *skbin, const struct xt_match_param *par)
1925 +match(const struct sk_buff *skbin,
1926 + const struct net_device *in,
1927 + const struct net_device *out,
1928 + const struct xt_match *match,
1929 + const void *matchinfo,
1931 + unsigned int protoff,
1935 + /* sidestep const without getting a compiler warning... */
1936 + struct sk_buff * skb = (struct sk_buff *)skbin;
1938 + const struct xt_layer7_info * info =
1939 + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
1945 + enum ip_conntrack_info master_ctinfo, ctinfo;
1946 + struct nf_conn *master_conntrack, *conntrack;
1947 + unsigned char * app_data;
1948 + unsigned int pattern_result, appdatalen;
1949 + regexp * comppattern;
1951 + /* Be paranoid/incompetent - lock the entire match function. */
1952 + spin_lock_bh(&l7_lock);
1954 + if(!can_handle(skb)){
1955 + DPRINTK("layer7: This is some protocol I can't handle.\n");
1956 + spin_unlock_bh(&l7_lock);
1957 + return info->invert;
1960 + /* Treat parent & all its children together as one connection, except
1961 + for the purpose of setting conntrack->layer7.app_proto in the actual
1962 + connection. This makes /proc/net/ip_conntrack more satisfying. */
1963 + if(!(conntrack = nf_ct_get(skb, &ctinfo)) ||
1964 + !(master_conntrack=nf_ct_get(skb,&master_ctinfo))){
1965 + DPRINTK("layer7: couldn't get conntrack.\n");
1966 + spin_unlock_bh(&l7_lock);
1967 + return info->invert;
1970 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
1971 + while (master_ct(master_conntrack) != NULL)
1972 + master_conntrack = master_ct(master_conntrack);
1974 + /* if we've classified it or seen too many packets */
1975 + if(total_acct_packets(master_conntrack) > num_packets ||
1976 + master_conntrack->layer7.app_proto) {
1978 + pattern_result = match_no_append(conntrack, master_conntrack,
1979 + ctinfo, master_ctinfo, info);
1981 + /* skb->cb[0] == seen. Don't do things twice if there are
1982 + multiple l7 rules. I'm not sure that using cb for this purpose
1983 + is correct, even though it says "put your private variables
1984 + there". But it doesn't look like it is being used for anything
1985 + else in the skbs that make it here. */
1986 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
1988 + spin_unlock_bh(&l7_lock);
1989 + return (pattern_result ^ info->invert);
1992 + if(skb_is_nonlinear(skb)){
1993 + if(skb_linearize(skb) != 0){
1994 + if (net_ratelimit())
1995 + printk(KERN_ERR "layer7: failed to linearize "
1996 + "packet, bailing.\n");
1997 + spin_unlock_bh(&l7_lock);
1998 + return info->invert;
2002 + /* now that the skb is linearized, it's safe to set these. */
2003 + app_data = skb->data + app_data_offset(skb);
2004 + appdatalen = skb_tail_pointer(skb) - app_data;
2006 + /* the return value gets checked later, when we're ready to use it */
2007 + comppattern = compile_and_cache(info->pattern, info->protocol);
2009 + /* On the first packet of a connection, allocate space for app data */
2010 + if(total_acct_packets(master_conntrack) == 1 && !skb->cb[0] &&
2011 + !master_conntrack->layer7.app_data){
2012 + master_conntrack->layer7.app_data =
2013 + kmalloc(maxdatalen, GFP_ATOMIC);
2014 + if(!master_conntrack->layer7.app_data){
2015 + if (net_ratelimit())
2016 + printk(KERN_ERR "layer7: out of memory in "
2017 + "match, bailing.\n");
2018 + spin_unlock_bh(&l7_lock);
2019 + return info->invert;
2022 + master_conntrack->layer7.app_data[0] = '\0';
2025 + /* Can be here, but unallocated, if numpackets is increased near
2026 + the beginning of a connection */
2027 + if(master_conntrack->layer7.app_data == NULL){
2028 + spin_unlock_bh(&l7_lock);
2029 + return info->invert; /* unmatched */
2034 + newbytes = add_data(master_conntrack, app_data, appdatalen);
2035 + if(newbytes == 0) { /* didn't add any data */
2037 + /* Didn't match before, not going to match now */
2038 + spin_unlock_bh(&l7_lock);
2039 + return info->invert;
2043 + /* If looking for "unknown", then never match. "Unknown" means that
2044 + we've given up; we're still trying with these packets. */
2045 + if(!strcmp(info->protocol, "unknown")) {
2046 + pattern_result = 0;
2047 + /* If looking for "unset", then always match. "Unset" means that we
2048 + haven't yet classified the connection. */
2049 + } else if(!strcmp(info->protocol, "unset")) {
2050 + pattern_result = 2;
2051 + DPRINTK("layer7: matched unset: not yet classified "
2052 + "(%d/%d packets)\n",
2053 + total_acct_packets(master_conntrack), num_packets);
2054 + /* If the regexp failed to compile, don't bother running it */
2055 + } else if(comppattern &&
2056 + regexec(comppattern, master_conntrack->layer7.app_data)){
2057 + DPRINTK("layer7: matched %s\n", info->protocol);
2058 + pattern_result = 1;
2059 + } else pattern_result = 0;
2061 + if(pattern_result == 1) {
2062 + master_conntrack->layer7.app_proto=get_protostr_ptr(info->protocol);
2063 + } else if(pattern_result > 1) { /* cleanup from "unset" */
2064 + pattern_result = 1;
2067 + /* mark the packet seen */
2070 + spin_unlock_bh(&l7_lock);
2071 + return (pattern_result ^ info->invert);
2074 +// load nf_conntrack_ipv4
2075 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35)
2080 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
2081 +check(const struct xt_mtchk_param *par)
2083 + if (nf_ct_l3proto_try_module_get(par->match->family) < 0) {
2084 + printk(KERN_WARNING "can't load conntrack support for "
2085 + "proto=%d\n", par->match->family);
2087 +check(const char *tablename, const void *inf,
2088 + const struct xt_match *match, void *matchinfo,
2089 + unsigned int hook_mask)
2091 + if (nf_ct_l3proto_try_module_get(match->family) < 0) {
2092 + printk(KERN_WARNING "can't load conntrack support for "
2093 + "proto=%d\n", match->family);
2095 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35)
2107 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
2108 + static void destroy(const struct xt_mtdtor_param *par)
2110 + nf_ct_l3proto_module_put(par->match->family);
2113 + static void destroy(const struct xt_match *match, void *matchinfo)
2115 + nf_ct_l3proto_module_put(match->family);
2119 +static struct xt_match xt_layer7_match[] __read_mostly = {
2122 + .family = NFPROTO_IPV4,
2123 + .checkentry = check,
2125 + .destroy = destroy,
2126 + .matchsize = sizeof(struct xt_layer7_info),
2131 +static const struct file_operations layer7_numpackets_proc_fops = {
2132 + .owner = THIS_MODULE,
2133 + .open = layer7_numpackets_proc_open,
2135 + .llseek = seq_lseek,
2136 + .release = single_release,
2137 + .write = layer7_numpackets_write_proc,
2140 +static int __init xt_layer7_init(void)
2144 + // Register proc interface
2145 + proc_create_data("layer7_numpackets", 0644,
2146 + init_net.proc_net, &layer7_numpackets_proc_fops, NULL);
2148 + if(maxdatalen < 1) {
2149 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
2153 + /* This is not a hard limit. It's just here to prevent people from
2154 + bringing their slow machines to a grinding halt. */
2155 + else if(maxdatalen > 65536) {
2156 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
2158 + maxdatalen = 65536;
2160 + return xt_register_matches(xt_layer7_match,
2161 + ARRAY_SIZE(xt_layer7_match));
2164 +static void __exit xt_layer7_fini(void)
2166 + remove_proc_entry("layer7_numpackets", init_net.proc_net);
2167 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
2170 +module_init(xt_layer7_init);
2171 +module_exit(xt_layer7_fini);