2 +++ b/include/linux/netfilter/xt_layer7.h
7 +#define MAX_PATTERN_LEN 8192
8 +#define MAX_PROTOCOL_LEN 256
10 +struct xt_layer7_info {
11 + char protocol[MAX_PROTOCOL_LEN];
13 + char pattern[MAX_PATTERN_LEN];
16 +#endif /* _XT_LAYER7_H */
17 --- a/include/net/netfilter/nf_conntrack.h
18 +++ b/include/net/netfilter/nf_conntrack.h
23 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
24 + defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
27 + * e.g. "http". NULL before decision. "unknown" after decision
32 + * application layer data so far. NULL after match decision.
35 + unsigned int app_data_len;
39 /* Storage reserved for other modules: */
40 union nf_conntrack_proto proto;
42 --- a/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4_compat.c
43 +++ b/net/ipv4/netfilter/nf_conntrack_l3proto_ipv4_compat.c
48 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
49 + if(ct->layer7.app_proto)
50 + if(seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
54 if (seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use)))
57 --- a/net/netfilter/Kconfig
58 +++ b/net/netfilter/Kconfig
61 To compile it as a module, choose M here. If unsure, say N.
63 +config NETFILTER_XT_MATCH_LAYER7
64 + tristate '"layer7" match support'
65 + depends on NETFILTER_XTABLES
66 + depends on IP_NF_CONNTRACK || NF_CONNTRACK
67 + depends on NF_CT_ACCT
69 + Say Y if you want to be able to classify connections (and their
70 + packets) based on regular expression matching of their application
71 + layer data. This is one way to classify applications such as
72 + peer-to-peer filesharing systems that do not always use the same
75 + To compile it as a module, choose M here. If unsure, say N.
77 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
78 + bool 'layer7 debugging output'
79 + depends on NETFILTER_XT_MATCH_LAYER7
81 + Say Y to get lots of debugging output.
84 config NETFILTER_XT_MATCH_STATISTIC
85 tristate '"statistic" match support'
86 depends on NETFILTER_XTABLES
87 --- a/net/netfilter/Makefile
88 +++ b/net/netfilter/Makefile
90 obj-$(CONFIG_NETFILTER_XT_MATCH_REALM) += xt_realm.o
91 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
92 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
93 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
94 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
95 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
96 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
97 --- a/net/netfilter/nf_conntrack_core.c
98 +++ b/net/netfilter/nf_conntrack_core.c
101 nf_ct_remove_expectations(ct);
103 + #if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
104 + if(ct->layer7.app_proto)
105 + kfree(ct->layer7.app_proto);
106 + if(ct->layer7.app_data)
107 + kfree(ct->layer7.app_data);
111 /* We overload first tuple to link into unconfirmed list. */
112 if (!nf_ct_is_confirmed(ct)) {
113 BUG_ON(list_empty(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list));
114 --- a/net/netfilter/nf_conntrack_standalone.c
115 +++ b/net/netfilter/nf_conntrack_standalone.c
120 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
121 + if(conntrack->layer7.app_proto)
122 + if(seq_printf(s, "l7proto=%s ",conntrack->layer7.app_proto))
125 if (seq_printf(s, "use=%u\n", atomic_read(&conntrack->ct_general.use)))
129 +++ b/net/netfilter/regexp/regexp.c
132 + * regcomp and regexec -- regsub and regerror are elsewhere
133 + * @(#)regexp.c 1.3 of 18 April 87
135 + * Copyright (c) 1986 by University of Toronto.
136 + * Written by Henry Spencer. Not derived from licensed software.
138 + * Permission is granted to anyone to use this software for any
139 + * purpose on any computer system, and to redistribute it freely,
140 + * subject to the following restrictions:
142 + * 1. The author is not responsible for the consequences of use of
143 + * this software, no matter how awful, even if they arise
144 + * from defects in it.
146 + * 2. The origin of this software must not be misrepresented, either
147 + * by explicit claim or by omission.
149 + * 3. Altered versions must be plainly marked as such, and must not
150 + * be misrepresented as being the original software.
152 + * Beware that some of this code is subtly aware of the way operator
153 + * precedence is structured in regular expressions. Serious changes in
154 + * regular-expression syntax might require a total rethink.
156 + * This code was modified by Ethan Sommer to work within the kernel
157 + * (it now uses kmalloc etc..)
159 + * Modified slightly by Matthew Strait to use more modern C.
163 +#include "regmagic.h"
165 +/* added by ethan and matt. Lets it work in both kernel and user space.
166 +(So iptables can use it, for instance.) Yea, it goes both ways... */
168 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
170 + #define printk(format,args...) printf(format,##args)
173 +void regerror(char * s)
175 + printk("<3>Regexp: %s\n", s);
180 + * The "internal use only" fields in regexp.h are present to pass info from
181 + * compile to execute that permits the execute phase to run lots faster on
182 + * simple cases. They are:
184 + * regstart char that must begin a match; '\0' if none obvious
185 + * reganch is the match anchored (at beginning-of-line only)?
186 + * regmust string (pointer into program) that match must include, or NULL
187 + * regmlen length of regmust string
189 + * Regstart and reganch permit very fast decisions on suitable starting points
190 + * for a match, cutting down the work a lot. Regmust permits fast rejection
191 + * of lines that cannot possibly match. The regmust tests are costly enough
192 + * that regcomp() supplies a regmust only if the r.e. contains something
193 + * potentially expensive (at present, the only such thing detected is * or +
194 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
195 + * supplied because the test in regexec() needs it and regcomp() is computing
200 + * Structure for regexp "program". This is essentially a linear encoding
201 + * of a nondeterministic finite-state machine (aka syntax charts or
202 + * "railroad normal form" in parsing technology). Each node is an opcode
203 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
204 + * all nodes except BRANCH implement concatenation; a "next" pointer with
205 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
206 + * have one of the subtle syntax dependencies: an individual BRANCH (as
207 + * opposed to a collection of them) is never concatenated with anything
208 + * because of operator precedence.) The operand of some types of node is
209 + * a literal string; for others, it is a node leading into a sub-FSM. In
210 + * particular, the operand of a BRANCH node is the first node of the branch.
211 + * (NB this is *not* a tree structure: the tail of the branch connects
212 + * to the thing following the set of BRANCHes.) The opcodes are:
215 +/* definition number opnd? meaning */
216 +#define END 0 /* no End of program. */
217 +#define BOL 1 /* no Match "" at beginning of line. */
218 +#define EOL 2 /* no Match "" at end of line. */
219 +#define ANY 3 /* no Match any one character. */
220 +#define ANYOF 4 /* str Match any character in this string. */
221 +#define ANYBUT 5 /* str Match any character not in this string. */
222 +#define BRANCH 6 /* node Match this alternative, or the next... */
223 +#define BACK 7 /* no Match "", "next" ptr points backward. */
224 +#define EXACTLY 8 /* str Match this string. */
225 +#define NOTHING 9 /* no Match empty string. */
226 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
227 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
228 +#define OPEN 20 /* no Mark this point in input as start of #n. */
229 + /* OPEN+1 is number 1, etc. */
230 +#define CLOSE 30 /* no Analogous to OPEN. */
235 + * BRANCH The set of branches constituting a single choice are hooked
236 + * together with their "next" pointers, since precedence prevents
237 + * anything being concatenated to any individual branch. The
238 + * "next" pointer of the last BRANCH in a choice points to the
239 + * thing following the whole choice. This is also where the
240 + * final "next" pointer of each individual branch points; each
241 + * branch starts with the operand node of a BRANCH node.
243 + * BACK Normal "next" pointers all implicitly point forward; BACK
244 + * exists to make loop structures possible.
246 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
247 + * BRANCH structures using BACK. Simple cases (one character
248 + * per match) are implemented with STAR and PLUS for speed
249 + * and to minimize recursive plunges.
251 + * OPEN,CLOSE ...are numbered at compile time.
255 + * A node is one char of opcode followed by two chars of "next" pointer.
256 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
257 + * value is a positive offset from the opcode of the node containing it.
258 + * An operand, if any, simply follows the node. (Note that much of the
259 + * code generation knows about this implicit relationship.)
261 + * Using two bytes for the "next" pointer is vast overkill for most things,
262 + * but allows patterns to get big without disasters.
264 +#define OP(p) (*(p))
265 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
266 +#define OPERAND(p) ((p) + 3)
269 + * See regmagic.h for one further detail of program structure.
274 + * Utility definitions.
277 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
279 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
282 +#define FAIL(m) { regerror(m); return(NULL); }
283 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
284 +#define META "^$.[()|?+*\\"
287 + * Flags to be passed up and down.
289 +#define HASWIDTH 01 /* Known never to match null string. */
290 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
291 +#define SPSTART 04 /* Starts with * or +. */
292 +#define WORST 0 /* Worst case. */
295 + * Global work variables for regcomp().
297 +struct match_globals {
298 +char *reginput; /* String-input pointer. */
299 +char *regbol; /* Beginning of input, for ^ check. */
300 +char **regstartp; /* Pointer to startp array. */
301 +char **regendp; /* Ditto for endp. */
302 +char *regparse; /* Input-scan pointer. */
303 +int regnpar; /* () count. */
305 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
306 +long regsize; /* Code size. */
310 + * Forward declarations for regcomp()'s friends.
313 +#define STATIC static
315 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
316 +STATIC char *regbranch(struct match_globals *g, int *flagp);
317 +STATIC char *regpiece(struct match_globals *g, int *flagp);
318 +STATIC char *regatom(struct match_globals *g, int *flagp);
319 +STATIC char *regnode(struct match_globals *g, char op);
320 +STATIC char *regnext(struct match_globals *g, char *p);
321 +STATIC void regc(struct match_globals *g, char b);
322 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
323 +STATIC void regtail(struct match_globals *g, char *p, char *val);
324 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
327 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
334 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
335 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
336 + if (*scan1 == *scan2++)
344 + - regcomp - compile a regular expression into internal code
346 + * We can't allocate space until we know how big the compiled form will be,
347 + * but we can't compile it (and thus know how big it is) until we've got a
348 + * place to put the code. So we cheat: we compile it twice, once with code
349 + * generation turned off and size counting turned on, and once "for real".
350 + * This also means that we don't allocate space until we are sure that the
351 + * thing really will compile successfully, and we never have to move the
352 + * code and thus invalidate pointers into it. (Note that it has to be in
353 + * one piece because free() must be able to free it all.)
355 + * Beware that the optimization-preparation code in here knows about some
356 + * of the structure of the compiled regexp.
359 +regcomp(char *exp,int *patternsize)
361 + register regexp *r;
362 + register char *scan;
363 + register char *longest;
366 + struct match_globals g;
368 + /* commented out by ethan
369 + extern char *malloc();
373 + FAIL("NULL argument");
375 + /* First pass: determine size, legality. */
379 + g.regcode = &g.regdummy;
381 + if (reg(&g, 0, &flags) == NULL)
384 + /* Small enough for pointer-storage convention? */
385 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
386 + FAIL("regexp too big");
388 + /* Allocate space. */
389 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
390 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
392 + FAIL("out of space");
394 + /* Second pass: emit code. */
397 + g.regcode = r->program;
399 + if (reg(&g, 0, &flags) == NULL)
402 + /* Dig out information for optimizations. */
403 + r->regstart = '\0'; /* Worst-case defaults. */
407 + scan = r->program+1; /* First BRANCH. */
408 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
409 + scan = OPERAND(scan);
411 + /* Starting-point info. */
412 + if (OP(scan) == EXACTLY)
413 + r->regstart = *OPERAND(scan);
414 + else if (OP(scan) == BOL)
418 + * If there's something expensive in the r.e., find the
419 + * longest literal string that must appear and make it the
420 + * regmust. Resolve ties in favor of later strings, since
421 + * the regstart check works with the beginning of the r.e.
422 + * and avoiding duplication strengthens checking. Not a
423 + * strong reason, but sufficient in the absence of others.
425 + if (flags&SPSTART) {
428 + for (; scan != NULL; scan = regnext(&g, scan))
429 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
430 + longest = OPERAND(scan);
431 + len = strlen(OPERAND(scan));
433 + r->regmust = longest;
442 + - reg - regular expression, i.e. main body or parenthesized thing
444 + * Caller must absorb opening parenthesis.
446 + * Combining parenthesis handling with the base level of regular expression
447 + * is a trifle forced, but the need to tie the tails of the branches to what
448 + * follows makes it hard to avoid.
451 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
453 + register char *ret;
455 + register char *ender;
456 + register int parno = 0; /* 0 makes gcc happy */
459 + *flagp = HASWIDTH; /* Tentatively. */
461 + /* Make an OPEN node, if parenthesized. */
463 + if (g->regnpar >= NSUBEXP)
464 + FAIL("too many ()");
465 + parno = g->regnpar;
467 + ret = regnode(g, OPEN+parno);
471 + /* Pick up the branches, linking them together. */
472 + br = regbranch(g, &flags);
476 + regtail(g, ret, br); /* OPEN -> first. */
479 + if (!(flags&HASWIDTH))
480 + *flagp &= ~HASWIDTH;
481 + *flagp |= flags&SPSTART;
482 + while (*g->regparse == '|') {
484 + br = regbranch(g, &flags);
487 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
488 + if (!(flags&HASWIDTH))
489 + *flagp &= ~HASWIDTH;
490 + *flagp |= flags&SPSTART;
493 + /* Make a closing node, and hook it on the end. */
494 + ender = regnode(g, (paren) ? CLOSE+parno : END);
495 + regtail(g, ret, ender);
497 + /* Hook the tails of the branches to the closing node. */
498 + for (br = ret; br != NULL; br = regnext(g, br))
499 + regoptail(g, br, ender);
501 + /* Check for proper termination. */
502 + if (paren && *g->regparse++ != ')') {
503 + FAIL("unmatched ()");
504 + } else if (!paren && *g->regparse != '\0') {
505 + if (*g->regparse == ')') {
506 + FAIL("unmatched ()");
508 + FAIL("junk on end"); /* "Can't happen". */
516 + - regbranch - one alternative of an | operator
518 + * Implements the concatenation operator.
521 +regbranch(struct match_globals *g, int *flagp)
523 + register char *ret;
524 + register char *chain;
525 + register char *latest;
528 + *flagp = WORST; /* Tentatively. */
530 + ret = regnode(g, BRANCH);
532 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
533 + latest = regpiece(g, &flags);
534 + if (latest == NULL)
536 + *flagp |= flags&HASWIDTH;
537 + if (chain == NULL) /* First piece. */
538 + *flagp |= flags&SPSTART;
540 + regtail(g, chain, latest);
543 + if (chain == NULL) /* Loop ran zero times. */
544 + (void) regnode(g, NOTHING);
550 + - regpiece - something followed by possible [*+?]
552 + * Note that the branching code sequences used for ? and the general cases
553 + * of * and + are somewhat optimized: they use the same NOTHING node as
554 + * both the endmarker for their branch list and the body of the last branch.
555 + * It might seem that this node could be dispensed with entirely, but the
556 + * endmarker role is not redundant.
559 +regpiece(struct match_globals *g, int *flagp)
561 + register char *ret;
563 + register char *next;
566 + ret = regatom(g, &flags);
576 + if (!(flags&HASWIDTH) && op != '?')
577 + FAIL("*+ operand could be empty");
578 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
580 + if (op == '*' && (flags&SIMPLE))
581 + reginsert(g, STAR, ret);
582 + else if (op == '*') {
583 + /* Emit x* as (x&|), where & means "self". */
584 + reginsert(g, BRANCH, ret); /* Either x */
585 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
586 + regoptail(g, ret, ret); /* back */
587 + regtail(g, ret, regnode(g, BRANCH)); /* or */
588 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
589 + } else if (op == '+' && (flags&SIMPLE))
590 + reginsert(g, PLUS, ret);
591 + else if (op == '+') {
592 + /* Emit x+ as x(&|), where & means "self". */
593 + next = regnode(g, BRANCH); /* Either */
594 + regtail(g, ret, next);
595 + regtail(g, regnode(g, BACK), ret); /* loop back */
596 + regtail(g, next, regnode(g, BRANCH)); /* or */
597 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
598 + } else if (op == '?') {
599 + /* Emit x? as (x|) */
600 + reginsert(g, BRANCH, ret); /* Either x */
601 + regtail(g, ret, regnode(g, BRANCH)); /* or */
602 + next = regnode(g, NOTHING); /* null. */
603 + regtail(g, ret, next);
604 + regoptail(g, ret, next);
607 + if (ISMULT(*g->regparse))
608 + FAIL("nested *?+");
614 + - regatom - the lowest level
616 + * Optimization: gobbles an entire sequence of ordinary characters so that
617 + * it can turn them into a single node, which is smaller to store and
618 + * faster to run. Backslashed characters are exceptions, each becoming a
619 + * separate node; the code is simpler that way and it's not worth fixing.
622 +regatom(struct match_globals *g, int *flagp)
624 + register char *ret;
627 + *flagp = WORST; /* Tentatively. */
629 + switch (*g->regparse++) {
631 + ret = regnode(g, BOL);
634 + ret = regnode(g, EOL);
637 + ret = regnode(g, ANY);
638 + *flagp |= HASWIDTH|SIMPLE;
641 + register int class;
642 + register int classend;
644 + if (*g->regparse == '^') { /* Complement of range. */
645 + ret = regnode(g, ANYBUT);
648 + ret = regnode(g, ANYOF);
649 + if (*g->regparse == ']' || *g->regparse == '-')
650 + regc(g, *g->regparse++);
651 + while (*g->regparse != '\0' && *g->regparse != ']') {
652 + if (*g->regparse == '-') {
654 + if (*g->regparse == ']' || *g->regparse == '\0')
657 + class = UCHARAT(g->regparse-2)+1;
658 + classend = UCHARAT(g->regparse);
659 + if (class > classend+1)
660 + FAIL("invalid [] range");
661 + for (; class <= classend; class++)
666 + regc(g, *g->regparse++);
669 + if (*g->regparse != ']')
670 + FAIL("unmatched []");
672 + *flagp |= HASWIDTH|SIMPLE;
676 + ret = reg(g, 1, &flags);
679 + *flagp |= flags&(HASWIDTH|SPSTART);
684 + FAIL("internal urp"); /* Supposed to be caught earlier. */
689 + FAIL("?+* follows nothing");
692 + if (*g->regparse == '\0')
693 + FAIL("trailing \\");
694 + ret = regnode(g, EXACTLY);
695 + regc(g, *g->regparse++);
697 + *flagp |= HASWIDTH|SIMPLE;
701 + register char ender;
704 + len = my_strcspn((const char *)g->regparse, (const char *)META);
706 + FAIL("internal disaster");
707 + ender = *(g->regparse+len);
708 + if (len > 1 && ISMULT(ender))
709 + len--; /* Back off clear of ?+* operand. */
710 + *flagp |= HASWIDTH;
713 + ret = regnode(g, EXACTLY);
715 + regc(g, *g->regparse++);
727 + - regnode - emit a node
729 +static char * /* Location. */
730 +regnode(struct match_globals *g, char op)
732 + register char *ret;
733 + register char *ptr;
736 + if (ret == &g->regdummy) {
743 + *ptr++ = '\0'; /* Null "next" pointer. */
751 + - regc - emit (if appropriate) a byte of code
754 +regc(struct match_globals *g, char b)
756 + if (g->regcode != &g->regdummy)
763 + - reginsert - insert an operator in front of already-emitted operand
765 + * Means relocating the operand.
768 +reginsert(struct match_globals *g, char op, char* opnd)
770 + register char *src;
771 + register char *dst;
772 + register char *place;
774 + if (g->regcode == &g->regdummy) {
785 + place = opnd; /* Op node, where operand used to be. */
792 + - regtail - set the next-pointer at the end of a node chain
795 +regtail(struct match_globals *g, char *p, char *val)
797 + register char *scan;
798 + register char *temp;
799 + register int offset;
801 + if (p == &g->regdummy)
804 + /* Find last node. */
807 + temp = regnext(g, scan);
813 + if (OP(scan) == BACK)
814 + offset = scan - val;
816 + offset = val - scan;
817 + *(scan+1) = (offset>>8)&0377;
818 + *(scan+2) = offset&0377;
822 + - regoptail - regtail on operand of first argument; nop if operandless
825 +regoptail(struct match_globals *g, char *p, char *val)
827 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
828 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
830 + regtail(g, OPERAND(p), val);
834 + * regexec and friends
841 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
842 +STATIC int regmatch(struct match_globals *g, char *prog);
843 +STATIC int regrepeat(struct match_globals *g, char *p);
848 +STATIC char *regprop(char *op);
852 + - regexec - match a regexp against a string
855 +regexec(regexp *prog, char *string)
858 + struct match_globals g;
860 + /* Be paranoid... */
861 + if (prog == NULL || string == NULL) {
862 + printk("<3>Regexp: NULL parameter\n");
866 + /* Check validity of program. */
867 + if (UCHARAT(prog->program) != MAGIC) {
868 + printk("<3>Regexp: corrupted program\n");
872 + /* If there is a "must appear" string, look for it. */
873 + if (prog->regmust != NULL) {
875 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
876 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
877 + break; /* Found it. */
880 + if (s == NULL) /* Not present. */
884 + /* Mark beginning of line for ^ . */
887 + /* Simplest case: anchored match need be tried only once. */
889 + return(regtry(&g, prog, string));
891 + /* Messy cases: unanchored match. */
893 + if (prog->regstart != '\0')
894 + /* We know what char it must start with. */
895 + while ((s = strchr(s, prog->regstart)) != NULL) {
896 + if (regtry(&g, prog, s))
901 + /* We don't -- general case. */
903 + if (regtry(&g, prog, s))
905 + } while (*s++ != '\0');
912 + - regtry - try match at specific point
914 +static int /* 0 failure, 1 success */
915 +regtry(struct match_globals *g, regexp *prog, char *string)
918 + register char **sp;
919 + register char **ep;
921 + g->reginput = string;
922 + g->regstartp = prog->startp;
923 + g->regendp = prog->endp;
927 + for (i = NSUBEXP; i > 0; i--) {
931 + if (regmatch(g, prog->program + 1)) {
932 + prog->startp[0] = string;
933 + prog->endp[0] = g->reginput;
940 + - regmatch - main matching routine
942 + * Conceptually the strategy is simple: check to see whether the current
943 + * node matches, call self recursively to see whether the rest matches,
944 + * and then act accordingly. In practice we make some effort to avoid
945 + * recursion, in particular by going through "ordinary" nodes (that don't
946 + * need to know whether the rest of the match failed) by a loop instead of
949 +static int /* 0 failure, 1 success */
950 +regmatch(struct match_globals *g, char *prog)
952 + register char *scan = prog; /* Current node. */
953 + char *next; /* Next node. */
956 + if (scan != NULL && regnarrate)
957 + fprintf(stderr, "%s(\n", regprop(scan));
959 + while (scan != NULL) {
962 + fprintf(stderr, "%s...\n", regprop(scan));
964 + next = regnext(g, scan);
966 + switch (OP(scan)) {
968 + if (g->reginput != g->regbol)
972 + if (*g->reginput != '\0')
976 + if (*g->reginput == '\0')
982 + register char *opnd;
984 + opnd = OPERAND(scan);
985 + /* Inline the first character, for speed. */
986 + if (*opnd != *g->reginput)
988 + len = strlen(opnd);
989 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
991 + g->reginput += len;
995 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
1000 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1017 + register char *save;
1019 + no = OP(scan) - OPEN;
1020 + save = g->reginput;
1022 + if (regmatch(g, next)) {
1024 + * Don't set startp if some later
1025 + * invocation of the same parentheses
1028 + if (g->regstartp[no] == NULL)
1029 + g->regstartp[no] = save;
1046 + register char *save;
1048 + no = OP(scan) - CLOSE;
1049 + save = g->reginput;
1051 + if (regmatch(g, next)) {
1053 + * Don't set endp if some later
1054 + * invocation of the same parentheses
1057 + if (g->regendp[no] == NULL)
1058 + g->regendp[no] = save;
1065 + register char *save;
1067 + if (OP(next) != BRANCH) /* No choice. */
1068 + next = OPERAND(scan); /* Avoid recursion. */
1071 + save = g->reginput;
1072 + if (regmatch(g, OPERAND(scan)))
1074 + g->reginput = save;
1075 + scan = regnext(g, scan);
1076 + } while (scan != NULL && OP(scan) == BRANCH);
1084 + register char nextch;
1086 + register char *save;
1090 + * Lookahead to avoid useless match attempts
1091 + * when we know what character comes next.
1094 + if (OP(next) == EXACTLY)
1095 + nextch = *OPERAND(next);
1096 + min = (OP(scan) == STAR) ? 0 : 1;
1097 + save = g->reginput;
1098 + no = regrepeat(g, OPERAND(scan));
1099 + while (no >= min) {
1100 + /* If it could work, try it. */
1101 + if (nextch == '\0' || *g->reginput == nextch)
1102 + if (regmatch(g, next))
1104 + /* Couldn't or didn't -- back up. */
1106 + g->reginput = save + no;
1112 + return(1); /* Success! */
1115 + printk("<3>Regexp: memory corruption\n");
1124 + * We get here only if there's trouble -- normally "case END" is
1125 + * the terminating point.
1127 + printk("<3>Regexp: corrupted pointers\n");
1132 + - regrepeat - repeatedly match something simple, report how many
1135 +regrepeat(struct match_globals *g, char *p)
1137 + register int count = 0;
1138 + register char *scan;
1139 + register char *opnd;
1141 + scan = g->reginput;
1142 + opnd = OPERAND(p);
1145 + count = strlen(scan);
1149 + while (*opnd == *scan) {
1155 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1161 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1166 + default: /* Oh dear. Called inappropriately. */
1167 + printk("<3>Regexp: internal foulup\n");
1168 + count = 0; /* Best compromise. */
1171 + g->reginput = scan;
1177 + - regnext - dig the "next" pointer out of a node
1180 +regnext(struct match_globals *g, char *p)
1182 + register int offset;
1184 + if (p == &g->regdummy)
1191 + if (OP(p) == BACK)
1199 +STATIC char *regprop();
1202 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1208 + register char op = EXACTLY; /* Arbitrary non-END op. */
1209 + register char *next;
1210 + /* extern char *strchr(); */
1213 + s = r->program + 1;
1214 + while (op != END) { /* While that wasn't END last time... */
1216 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1217 + next = regnext(s);
1218 + if (next == NULL) /* Next ptr. */
1221 + printf("(%d)", (s-r->program)+(next-s));
1223 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1224 + /* Literal string, where present. */
1225 + while (*s != '\0') {
1234 + /* Header fields of interest. */
1235 + if (r->regstart != '\0')
1236 + printf("start `%c' ", r->regstart);
1238 + printf("anchored ");
1239 + if (r->regmust != NULL)
1240 + printf("must have \"%s\"", r->regmust);
1245 + - regprop - printable representation of opcode
1252 + static char buf[BUFLEN];
1296 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1308 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1318 + printk("<3>Regexp: corrupted opcode\n");
1322 + strncat(buf, p, BUFLEN-strlen(buf));
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);
1373 +++ b/net/netfilter/regexp/regmagic.h
1376 + * The first byte of the regexp internal "program" is actually this magic
1377 + * number; the start node begins in the second byte.
1381 +++ b/net/netfilter/regexp/regsub.c
1385 + * @(#)regsub.c 1.3 of 2 April 86
1387 + * Copyright (c) 1986 by University of Toronto.
1388 + * Written by Henry Spencer. Not derived from licensed software.
1390 + * Permission is granted to anyone to use this software for any
1391 + * purpose on any computer system, and to redistribute it freely,
1392 + * subject to the following restrictions:
1394 + * 1. The author is not responsible for the consequences of use of
1395 + * this software, no matter how awful, even if they arise
1396 + * from defects in it.
1398 + * 2. The origin of this software must not be misrepresented, either
1399 + * by explicit claim or by omission.
1401 + * 3. Altered versions must be plainly marked as such, and must not
1402 + * be misrepresented as being the original software.
1405 + * This code was modified by Ethan Sommer to work within the kernel
1406 + * (it now uses kmalloc etc..)
1409 +#include "regexp.h"
1410 +#include "regmagic.h"
1411 +#include <linux/string.h>
1415 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1417 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
1421 +//void regerror(char * s)
1423 +// printk("regexp(3): %s", s);
1424 +// /* NOTREACHED */
1429 + - regsub - perform substitutions after a regexp match
1432 +regsub(regexp * prog, char * source, char * dest)
1434 + register char *src;
1435 + register char *dst;
1440 + /* Not necessary and gcc doesn't like it -MLS */
1441 + /*extern char *strncpy();*/
1443 + if (prog == NULL || source == NULL || dest == NULL) {
1444 + regerror("NULL parm to regsub");
1447 + if (UCHARAT(prog->program) != MAGIC) {
1448 + regerror("damaged regexp fed to regsub");
1454 + while ((c = *src++) != '\0') {
1457 + else if (c == '\\' && '0' <= *src && *src <= '9')
1458 + no = *src++ - '0';
1462 + if (no < 0) { /* Ordinary character. */
1463 + if (c == '\\' && (*src == '\\' || *src == '&'))
1466 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
1467 + len = prog->endp[no] - prog->startp[no];
1468 + (void) strncpy(dst, prog->startp[no], len);
1470 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
1471 + regerror("damaged match string");
1479 +++ b/net/netfilter/xt_layer7.c
1482 + Kernel module to match application layer (OSI layer 7) data in connections.
1484 + http://l7-filter.sf.net
1486 + (C) 2003, 2004, 2005, 2006, 2007 Matthew Strait and Ethan Sommer.
1488 + This program is free software; you can redistribute it and/or
1489 + modify it under the terms of the GNU General Public License
1490 + as published by the Free Software Foundation; either version
1491 + 2 of the License, or (at your option) any later version.
1492 + http://www.gnu.org/licenses/gpl.txt
1494 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
1495 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
1496 + Ethan Sommer, Justin Levandoski.
1499 +#include <linux/spinlock.h>
1500 +#include <net/ip.h>
1501 +#include <net/tcp.h>
1502 +#include <linux/module.h>
1503 +#include <linux/skbuff.h>
1504 +#include <linux/netfilter.h>
1505 +#include <net/netfilter/nf_conntrack.h>
1506 +#include <net/netfilter/nf_conntrack_core.h>
1507 +#include <linux/netfilter/x_tables.h>
1508 +#include <linux/netfilter/xt_layer7.h>
1509 +#include <net/netfilter/nf_conntrack_compat.h>
1510 +#include <linux/ctype.h>
1511 +#include <linux/proc_fs.h>
1513 +#include "regexp/regexp.c"
1515 +MODULE_LICENSE("GPL");
1516 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
1517 +MODULE_DESCRIPTION("iptables application layer match module");
1518 +MODULE_ALIAS("ipt_layer7");
1519 +MODULE_VERSION("2.16.1");
1521 +static int maxdatalen = 2048; // this is the default
1522 +module_param(maxdatalen, int, 0444);
1523 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
1524 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
1525 + #define DPRINTK(format,args...) printk(format,##args)
1527 + #define DPRINTK(format,args...)
1530 +#define TOTAL_PACKETS master_conntrack->counters[IP_CT_DIR_ORIGINAL].packets + \
1531 + master_conntrack->counters[IP_CT_DIR_REPLY].packets
1533 +/* Number of packets whose data we look at.
1534 +This can be modified through /proc/net/layer7_numpackets */
1535 +static int num_packets = 10;
1537 +static struct pattern_cache {
1538 + char * regex_string;
1540 + struct pattern_cache * next;
1541 +} * first_pattern_cache = NULL;
1543 +DEFINE_SPINLOCK(l7_lock);
1545 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1546 +/* Converts an unfriendly string into a friendly one by
1547 +replacing unprintables with periods and all whitespace with " ". */
1548 +static char * friendly_print(unsigned char * s)
1550 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
1554 + if (net_ratelimit())
1555 + printk(KERN_ERR "layer7: out of memory in "
1556 + "friendly_print, bailing.\n");
1560 + for(i = 0; i < strlen(s); i++){
1561 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
1562 + else if(isspace(s[i])) f[i] = ' ';
1569 +static char dec2hex(int i)
1573 + return (char)(i + '0');
1576 + return (char)(i - 10 + 'a');
1579 + if (net_ratelimit())
1580 + printk("Problem in dec2hex\n");
1585 +static char * hex_print(unsigned char * s)
1587 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
1591 + if (net_ratelimit())
1592 + printk(KERN_ERR "layer7: out of memory in hex_print, "
1597 + for(i = 0; i < strlen(s); i++) {
1598 + g[i*3 ] = dec2hex(s[i]/16);
1599 + g[i*3 + 1] = dec2hex(s[i]%16);
1608 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
1609 +over again, it make sense to cache the results. */
1610 +static regexp * compile_and_cache(char * regex_string, char * protocol)
1612 + struct pattern_cache * node = first_pattern_cache;
1613 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
1614 + struct pattern_cache * tmp;
1617 + while (node != NULL) {
1618 + if (!strcmp(node->regex_string, regex_string))
1619 + return node->pattern;
1621 + last_pattern_cache = node;/* points at the last non-NULL node */
1622 + node = node->next;
1625 + /* If we reach the end of the list, then we have not yet cached
1626 + the pattern for this regex. Let's do that now.
1627 + Be paranoid about running out of memory to avoid list corruption. */
1628 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
1631 + if (net_ratelimit())
1632 + printk(KERN_ERR "layer7: out of memory in "
1633 + "compile_and_cache, bailing.\n");
1637 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
1638 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
1641 + if(!tmp->regex_string || !tmp->pattern) {
1642 + if (net_ratelimit())
1643 + printk(KERN_ERR "layer7: out of memory in "
1644 + "compile_and_cache, bailing.\n");
1645 + kfree(tmp->regex_string);
1646 + kfree(tmp->pattern);
1651 + /* Ok. The new node is all ready now. */
1654 + if(first_pattern_cache == NULL) /* list is empty */
1655 + first_pattern_cache = node; /* make node the beginning */
1657 + last_pattern_cache->next = node; /* attach node to the end */
1659 + /* copy the string and compile the regex */
1660 + len = strlen(regex_string);
1661 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
1662 + node->pattern = regcomp(regex_string, &len);
1663 + if ( !node->pattern ) {
1664 + if (net_ratelimit())
1665 + printk(KERN_ERR "layer7: Error compiling regexp "
1667 + regex_string, protocol);
1668 + /* pattern is now cached as NULL, so we won't try again. */
1671 + strcpy(node->regex_string, regex_string);
1672 + return node->pattern;
1675 +static int can_handle(const struct sk_buff *skb)
1677 + if(!skb->nh.iph) /* not IP */
1679 + if(skb->nh.iph->protocol != IPPROTO_TCP &&
1680 + skb->nh.iph->protocol != IPPROTO_UDP &&
1681 + skb->nh.iph->protocol != IPPROTO_ICMP)
1686 +/* Returns offset the into the skb->data that the application data starts */
1687 +static int app_data_offset(const struct sk_buff *skb)
1689 + /* In case we are ported somewhere (ebtables?) where skb->nh.iph
1690 + isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
1691 + int ip_hl = 4*skb->nh.iph->ihl;
1693 + if( skb->nh.iph->protocol == IPPROTO_TCP ) {
1694 + /* 12 == offset into TCP header for the header length field.
1695 + Can't get this with skb->h.th->doff because the tcphdr
1696 + struct doesn't get set when routing (this is confirmed to be
1697 + true in Netfilter as well as QoS.) */
1698 + int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
1700 + return ip_hl + tcp_hl;
1701 + } else if( skb->nh.iph->protocol == IPPROTO_UDP ) {
1702 + return ip_hl + 8; /* UDP header is always 8 bytes */
1703 + } else if( skb->nh.iph->protocol == IPPROTO_ICMP ) {
1704 + return ip_hl + 8; /* ICMP header is 8 bytes */
1706 + if (net_ratelimit())
1707 + printk(KERN_ERR "layer7: tried to handle unknown "
1709 + return ip_hl + 8; /* something reasonable */
1713 +/* handles whether there's a match when we aren't appending data anymore */
1714 +static int match_no_append(struct nf_conn * conntrack,
1715 + struct nf_conn * master_conntrack,
1716 + enum ip_conntrack_info ctinfo,
1717 + enum ip_conntrack_info master_ctinfo,
1718 + struct xt_layer7_info * info)
1720 + /* If we're in here, throw the app data away */
1721 + if(master_conntrack->layer7.app_data != NULL) {
1723 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1724 + if(!master_conntrack->layer7.app_proto) {
1726 + friendly_print(master_conntrack->layer7.app_data);
1728 + hex_print(master_conntrack->layer7.app_data);
1729 + DPRINTK("\nl7-filter gave up after %d bytes "
1730 + "(%d packets):\n%s\n",
1731 + strlen(f), TOTAL_PACKETS, f);
1733 + DPRINTK("In hex: %s\n", g);
1738 + kfree(master_conntrack->layer7.app_data);
1739 + master_conntrack->layer7.app_data = NULL; /* don't free again */
1742 + if(master_conntrack->layer7.app_proto){
1743 + /* Here child connections set their .app_proto (for /proc) */
1744 + if(!conntrack->layer7.app_proto) {
1745 + conntrack->layer7.app_proto =
1746 + kmalloc(strlen(master_conntrack->layer7.app_proto)+1,
1748 + if(!conntrack->layer7.app_proto){
1749 + if (net_ratelimit())
1750 + printk(KERN_ERR "layer7: out of memory "
1751 + "in match_no_append, "
1755 + strcpy(conntrack->layer7.app_proto,
1756 + master_conntrack->layer7.app_proto);
1759 + return (!strcmp(master_conntrack->layer7.app_proto,
1763 + /* If not classified, set to "unknown" to distinguish from
1764 + connections that are still being tested. */
1765 + master_conntrack->layer7.app_proto =
1766 + kmalloc(strlen("unknown")+1, GFP_ATOMIC);
1767 + if(!master_conntrack->layer7.app_proto){
1768 + if (net_ratelimit())
1769 + printk(KERN_ERR "layer7: out of memory in "
1770 + "match_no_append, bailing.\n");
1773 + strcpy(master_conntrack->layer7.app_proto, "unknown");
1778 +/* add the new app data to the conntrack. Return number of bytes added. */
1779 +static int add_data(struct nf_conn * master_conntrack,
1780 + char * app_data, int appdatalen)
1782 + int length = 0, i;
1783 + int oldlength = master_conntrack->layer7.app_data_len;
1785 + /* This is a fix for a race condition by Deti Fliegl. However, I'm not
1786 + clear on whether the race condition exists or whether this really
1787 + fixes it. I might just be being dense... Anyway, if it's not really
1788 + a fix, all it does is waste a very small amount of time. */
1789 + if(!master_conntrack->layer7.app_data) return 0;
1791 + /* Strip nulls. Make everything lower case (our regex lib doesn't
1792 + do case insensitivity). Add it to the end of the current data. */
1793 + for(i = 0; i < maxdatalen-oldlength-1 &&
1794 + i < appdatalen; i++) {
1795 + if(app_data[i] != '\0') {
1796 + /* the kernel version of tolower mungs 'upper ascii' */
1797 + master_conntrack->layer7.app_data[length+oldlength] =
1798 + isascii(app_data[i])?
1799 + tolower(app_data[i]) : app_data[i];
1804 + master_conntrack->layer7.app_data[length+oldlength] = '\0';
1805 + master_conntrack->layer7.app_data_len = length + oldlength;
1810 +/* taken from drivers/video/modedb.c */
1811 +static int my_atoi(const char *s)
1818 + val = 10*val+(*s-'0');
1826 +/* write out num_packets to userland. */
1827 +static int layer7_read_proc(char* page, char ** start, off_t off, int count,
1828 + int* eof, void * data)
1830 + if(num_packets > 99 && net_ratelimit())
1831 + printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
1833 + page[0] = num_packets/10 + '0';
1834 + page[1] = num_packets%10 + '0';
1843 +/* Read in num_packets from userland */
1844 +static int layer7_write_proc(struct file* file, const char* buffer,
1845 + unsigned long count, void *data)
1847 + char * foo = kmalloc(count, GFP_ATOMIC);
1850 + if (net_ratelimit())
1851 + printk(KERN_ERR "layer7: out of memory, bailing. "
1852 + "num_packets unchanged.\n");
1856 + if(copy_from_user(foo, buffer, count)) {
1861 + num_packets = my_atoi(foo);
1864 + /* This has an arbitrary limit to make the math easier. I'm lazy.
1865 + But anyway, 99 is a LOT! If you want more, you're doing it wrong! */
1866 + if(num_packets > 99) {
1867 + printk(KERN_WARNING "layer7: num_packets can't be > 99.\n");
1869 + } else if(num_packets < 1) {
1870 + printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
1878 +match(const struct sk_buff *skbin,
1879 + const struct net_device *in,
1880 + const struct net_device *out,
1881 + const struct xt_match *match,
1882 + const void *matchinfo,
1884 + unsigned int protoff,
1887 + /* sidestep const without getting a compiler warning... */
1888 + struct sk_buff * skb = (struct sk_buff *)skbin;
1890 + struct xt_layer7_info * info = (struct xt_layer7_info *)matchinfo;
1891 + enum ip_conntrack_info master_ctinfo, ctinfo;
1892 + struct nf_conn *master_conntrack, *conntrack;
1893 + unsigned char * app_data;
1894 + unsigned int pattern_result, appdatalen;
1895 + regexp * comppattern;
1897 + /* Be paranoid/incompetent - lock the entire match function. */
1898 + spin_lock_bh(&l7_lock);
1900 + if(!can_handle(skb)){
1901 + DPRINTK("layer7: This is some protocol I can't handle.\n");
1902 + spin_unlock_bh(&l7_lock);
1903 + return info->invert;
1906 + /* Treat parent & all its children together as one connection, except
1907 + for the purpose of setting conntrack->layer7.app_proto in the actual
1908 + connection. This makes /proc/net/ip_conntrack more satisfying. */
1909 + if(!(conntrack = nf_ct_get((struct sk_buff *)skb, &ctinfo)) ||
1910 + !(master_conntrack=nf_ct_get((struct sk_buff *)skb,&master_ctinfo))){
1911 + DPRINTK("layer7: couldn't get conntrack.\n");
1912 + spin_unlock_bh(&l7_lock);
1913 + return info->invert;
1916 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
1917 + while (master_ct(master_conntrack) != NULL)
1918 + master_conntrack = master_ct(master_conntrack);
1920 + /* if we've classified it or seen too many packets */
1921 + if(TOTAL_PACKETS > num_packets ||
1922 + master_conntrack->layer7.app_proto) {
1924 + pattern_result = match_no_append(conntrack, master_conntrack,
1925 + ctinfo, master_ctinfo, info);
1927 + /* skb->cb[0] == seen. Don't do things twice if there are
1928 + multiple l7 rules. I'm not sure that using cb for this purpose
1929 + is correct, even though it says "put your private variables
1930 + there". But it doesn't look like it is being used for anything
1931 + else in the skbs that make it here. */
1932 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
1934 + spin_unlock_bh(&l7_lock);
1935 + return (pattern_result ^ info->invert);
1938 + if(skb_is_nonlinear(skb)){
1939 + if(skb_linearize(skb) != 0){
1940 + if (net_ratelimit())
1941 + printk(KERN_ERR "layer7: failed to linearize "
1942 + "packet, bailing.\n");
1943 + spin_unlock_bh(&l7_lock);
1944 + return info->invert;
1948 + /* now that the skb is linearized, it's safe to set these. */
1949 + app_data = skb->data + app_data_offset(skb);
1950 + appdatalen = skb->tail - app_data;
1952 + /* the return value gets checked later, when we're ready to use it */
1953 + comppattern = compile_and_cache(info->pattern, info->protocol);
1955 + /* On the first packet of a connection, allocate space for app data */
1956 + if(TOTAL_PACKETS == 1 && !skb->cb[0] &&
1957 + !master_conntrack->layer7.app_data){
1958 + master_conntrack->layer7.app_data =
1959 + kmalloc(maxdatalen, GFP_ATOMIC);
1960 + if(!master_conntrack->layer7.app_data){
1961 + if (net_ratelimit())
1962 + printk(KERN_ERR "layer7: out of memory in "
1963 + "match, bailing.\n");
1964 + spin_unlock_bh(&l7_lock);
1965 + return info->invert;
1968 + master_conntrack->layer7.app_data[0] = '\0';
1971 + /* Can be here, but unallocated, if numpackets is increased near
1972 + the beginning of a connection */
1973 + if(master_conntrack->layer7.app_data == NULL){
1974 + spin_unlock_bh(&l7_lock);
1975 + return (info->invert); /* unmatched */
1980 + newbytes = add_data(master_conntrack, app_data, appdatalen);
1982 + if(newbytes == 0) { /* didn't add any data */
1984 + /* Didn't match before, not going to match now */
1985 + spin_unlock_bh(&l7_lock);
1986 + return info->invert;
1990 + /* If looking for "unknown", then never match. "Unknown" means that
1991 + we've given up; we're still trying with these packets. */
1992 + if(!strcmp(info->protocol, "unknown")) {
1993 + pattern_result = 0;
1994 + /* If looking for "unset", then always match. "Unset" means that we
1995 + haven't yet classified the connection. */
1996 + } else if(!strcmp(info->protocol, "unset")) {
1997 + pattern_result = 2;
1998 + DPRINTK("layer7: matched unset: not yet classified "
1999 + "(%d/%d packets)\n", TOTAL_PACKETS, num_packets);
2000 + /* If the regexp failed to compile, don't bother running it */
2001 + } else if(comppattern &&
2002 + regexec(comppattern, master_conntrack->layer7.app_data)){
2003 + DPRINTK("layer7: matched %s\n", info->protocol);
2004 + pattern_result = 1;
2005 + } else pattern_result = 0;
2007 + if(pattern_result == 1) {
2008 + master_conntrack->layer7.app_proto =
2009 + kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
2010 + if(!master_conntrack->layer7.app_proto){
2011 + if (net_ratelimit())
2012 + printk(KERN_ERR "layer7: out of memory in "
2013 + "match, bailing.\n");
2014 + spin_unlock_bh(&l7_lock);
2015 + return (pattern_result ^ info->invert);
2017 + strcpy(master_conntrack->layer7.app_proto, info->protocol);
2018 + } else if(pattern_result > 1) { /* cleanup from "unset" */
2019 + pattern_result = 1;
2022 + /* mark the packet seen */
2025 + spin_unlock_bh(&l7_lock);
2026 + return (pattern_result ^ info->invert);
2029 +static int check(const char *tablename,
2031 + const struct xt_match *match,
2033 + unsigned int hook_mask)
2036 + // load nf_conntrack_ipv4
2037 + if (nf_ct_l3proto_try_module_get(match->family) < 0) {
2038 + printk(KERN_WARNING "can't load conntrack support for "
2039 + "proto=%d\n", match->family);
2046 +destroy(const struct xt_match *match, void *matchinfo)
2048 + nf_ct_l3proto_module_put(match->family);
2051 +static struct xt_match xt_layer7_match[] = {
2054 + .family = AF_INET,
2055 + .checkentry = check,
2057 + .destroy = destroy,
2058 + .matchsize = sizeof(struct xt_layer7_info),
2063 +static void layer7_cleanup_proc(void)
2065 + remove_proc_entry("layer7_numpackets", proc_net);
2068 +/* register the proc file */
2069 +static void layer7_init_proc(void)
2071 + struct proc_dir_entry* entry;
2072 + entry = create_proc_entry("layer7_numpackets", 0644, proc_net);
2073 + entry->read_proc = layer7_read_proc;
2074 + entry->write_proc = layer7_write_proc;
2077 +static int __init xt_layer7_init(void)
2081 + layer7_init_proc();
2082 + if(maxdatalen < 1) {
2083 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
2087 + /* This is not a hard limit. It's just here to prevent people from
2088 + bringing their slow machines to a grinding halt. */
2089 + else if(maxdatalen > 65536) {
2090 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
2092 + maxdatalen = 65536;
2094 + return xt_register_matches(xt_layer7_match,
2095 + ARRAY_SIZE(xt_layer7_match));
2098 +static void __exit xt_layer7_fini(void)
2100 + layer7_cleanup_proc();
2101 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
2104 +module_init(xt_layer7_init);
2105 +module_exit(xt_layer7_fini);