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];
12 + 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
19 @@ -118,6 +118,22 @@ struct nf_conn
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/netfilter/Kconfig
43 +++ b/net/netfilter/Kconfig
44 @@ -757,6 +757,27 @@ config NETFILTER_XT_MATCH_STATE
46 To compile it as a module, choose M here. If unsure, say N.
48 +config NETFILTER_XT_MATCH_LAYER7
49 + tristate '"layer7" match support'
50 + depends on NETFILTER_XTABLES
51 + depends on EXPERIMENTAL && (IP_NF_CONNTRACK || NF_CONNTRACK)
52 + depends on NF_CT_ACCT
54 + Say Y if you want to be able to classify connections (and their
55 + packets) based on regular expression matching of their application
56 + layer data. This is one way to classify applications such as
57 + peer-to-peer filesharing systems that do not always use the same
60 + To compile it as a module, choose M here. If unsure, say N.
62 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
63 + bool 'Layer 7 debugging output'
64 + depends on NETFILTER_XT_MATCH_LAYER7
66 + Say Y to get lots of debugging output.
69 config NETFILTER_XT_MATCH_STATISTIC
70 tristate '"statistic" match support'
71 depends on NETFILTER_XTABLES
72 --- a/net/netfilter/Makefile
73 +++ b/net/netfilter/Makefile
74 @@ -78,6 +78,7 @@ obj-$(CONFIG_NETFILTER_XT_MATCH_RATEEST)
75 obj-$(CONFIG_NETFILTER_XT_MATCH_REALM) += xt_realm.o
76 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
77 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
78 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
79 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
80 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
81 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
82 --- a/net/netfilter/nf_conntrack_core.c
83 +++ b/net/netfilter/nf_conntrack_core.c
84 @@ -206,6 +206,14 @@ destroy_conntrack(struct nf_conntrack *n
86 nf_ct_remove_expectations(ct);
88 + #if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
89 + if(ct->layer7.app_proto)
90 + kfree(ct->layer7.app_proto);
91 + if(ct->layer7.app_data)
92 + kfree(ct->layer7.app_data);
96 /* We overload first tuple to link into unconfirmed list. */
97 if (!nf_ct_is_confirmed(ct)) {
98 BUG_ON(hlist_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnode));
99 --- a/net/netfilter/nf_conntrack_standalone.c
100 +++ b/net/netfilter/nf_conntrack_standalone.c
101 @@ -162,6 +162,12 @@ static int ct_seq_show(struct seq_file *
105 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
106 + if(ct->layer7.app_proto &&
107 + seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
111 if (seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use)))
115 +++ b/net/netfilter/regexp/regexp.c
118 + * regcomp and regexec -- regsub and regerror are elsewhere
119 + * @(#)regexp.c 1.3 of 18 April 87
121 + * Copyright (c) 1986 by University of Toronto.
122 + * Written by Henry Spencer. Not derived from licensed software.
124 + * Permission is granted to anyone to use this software for any
125 + * purpose on any computer system, and to redistribute it freely,
126 + * subject to the following restrictions:
128 + * 1. The author is not responsible for the consequences of use of
129 + * this software, no matter how awful, even if they arise
130 + * from defects in it.
132 + * 2. The origin of this software must not be misrepresented, either
133 + * by explicit claim or by omission.
135 + * 3. Altered versions must be plainly marked as such, and must not
136 + * be misrepresented as being the original software.
138 + * Beware that some of this code is subtly aware of the way operator
139 + * precedence is structured in regular expressions. Serious changes in
140 + * regular-expression syntax might require a total rethink.
142 + * This code was modified by Ethan Sommer to work within the kernel
143 + * (it now uses kmalloc etc..)
145 + * Modified slightly by Matthew Strait to use more modern C.
149 +#include "regmagic.h"
151 +/* added by ethan and matt. Lets it work in both kernel and user space.
152 +(So iptables can use it, for instance.) Yea, it goes both ways... */
154 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
156 + #define printk(format,args...) printf(format,##args)
159 +void regerror(char * s)
161 + printk("<3>Regexp: %s\n", s);
166 + * The "internal use only" fields in regexp.h are present to pass info from
167 + * compile to execute that permits the execute phase to run lots faster on
168 + * simple cases. They are:
170 + * regstart char that must begin a match; '\0' if none obvious
171 + * reganch is the match anchored (at beginning-of-line only)?
172 + * regmust string (pointer into program) that match must include, or NULL
173 + * regmlen length of regmust string
175 + * Regstart and reganch permit very fast decisions on suitable starting points
176 + * for a match, cutting down the work a lot. Regmust permits fast rejection
177 + * of lines that cannot possibly match. The regmust tests are costly enough
178 + * that regcomp() supplies a regmust only if the r.e. contains something
179 + * potentially expensive (at present, the only such thing detected is * or +
180 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
181 + * supplied because the test in regexec() needs it and regcomp() is computing
186 + * Structure for regexp "program". This is essentially a linear encoding
187 + * of a nondeterministic finite-state machine (aka syntax charts or
188 + * "railroad normal form" in parsing technology). Each node is an opcode
189 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
190 + * all nodes except BRANCH implement concatenation; a "next" pointer with
191 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
192 + * have one of the subtle syntax dependencies: an individual BRANCH (as
193 + * opposed to a collection of them) is never concatenated with anything
194 + * because of operator precedence.) The operand of some types of node is
195 + * a literal string; for others, it is a node leading into a sub-FSM. In
196 + * particular, the operand of a BRANCH node is the first node of the branch.
197 + * (NB this is *not* a tree structure: the tail of the branch connects
198 + * to the thing following the set of BRANCHes.) The opcodes are:
201 +/* definition number opnd? meaning */
202 +#define END 0 /* no End of program. */
203 +#define BOL 1 /* no Match "" at beginning of line. */
204 +#define EOL 2 /* no Match "" at end of line. */
205 +#define ANY 3 /* no Match any one character. */
206 +#define ANYOF 4 /* str Match any character in this string. */
207 +#define ANYBUT 5 /* str Match any character not in this string. */
208 +#define BRANCH 6 /* node Match this alternative, or the next... */
209 +#define BACK 7 /* no Match "", "next" ptr points backward. */
210 +#define EXACTLY 8 /* str Match this string. */
211 +#define NOTHING 9 /* no Match empty string. */
212 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
213 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
214 +#define OPEN 20 /* no Mark this point in input as start of #n. */
215 + /* OPEN+1 is number 1, etc. */
216 +#define CLOSE 30 /* no Analogous to OPEN. */
221 + * BRANCH The set of branches constituting a single choice are hooked
222 + * together with their "next" pointers, since precedence prevents
223 + * anything being concatenated to any individual branch. The
224 + * "next" pointer of the last BRANCH in a choice points to the
225 + * thing following the whole choice. This is also where the
226 + * final "next" pointer of each individual branch points; each
227 + * branch starts with the operand node of a BRANCH node.
229 + * BACK Normal "next" pointers all implicitly point forward; BACK
230 + * exists to make loop structures possible.
232 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
233 + * BRANCH structures using BACK. Simple cases (one character
234 + * per match) are implemented with STAR and PLUS for speed
235 + * and to minimize recursive plunges.
237 + * OPEN,CLOSE ...are numbered at compile time.
241 + * A node is one char of opcode followed by two chars of "next" pointer.
242 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
243 + * value is a positive offset from the opcode of the node containing it.
244 + * An operand, if any, simply follows the node. (Note that much of the
245 + * code generation knows about this implicit relationship.)
247 + * Using two bytes for the "next" pointer is vast overkill for most things,
248 + * but allows patterns to get big without disasters.
250 +#define OP(p) (*(p))
251 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
252 +#define OPERAND(p) ((p) + 3)
255 + * See regmagic.h for one further detail of program structure.
260 + * Utility definitions.
263 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
265 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
268 +#define FAIL(m) { regerror(m); return(NULL); }
269 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
270 +#define META "^$.[()|?+*\\"
273 + * Flags to be passed up and down.
275 +#define HASWIDTH 01 /* Known never to match null string. */
276 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
277 +#define SPSTART 04 /* Starts with * or +. */
278 +#define WORST 0 /* Worst case. */
281 + * Global work variables for regcomp().
283 +struct match_globals {
284 +char *reginput; /* String-input pointer. */
285 +char *regbol; /* Beginning of input, for ^ check. */
286 +char **regstartp; /* Pointer to startp array. */
287 +char **regendp; /* Ditto for endp. */
288 +char *regparse; /* Input-scan pointer. */
289 +int regnpar; /* () count. */
291 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
292 +long regsize; /* Code size. */
296 + * Forward declarations for regcomp()'s friends.
299 +#define STATIC static
301 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
302 +STATIC char *regbranch(struct match_globals *g, int *flagp);
303 +STATIC char *regpiece(struct match_globals *g, int *flagp);
304 +STATIC char *regatom(struct match_globals *g, int *flagp);
305 +STATIC char *regnode(struct match_globals *g, char op);
306 +STATIC char *regnext(struct match_globals *g, char *p);
307 +STATIC void regc(struct match_globals *g, char b);
308 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
309 +STATIC void regtail(struct match_globals *g, char *p, char *val);
310 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
313 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
320 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
321 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
322 + if (*scan1 == *scan2++)
330 + - regcomp - compile a regular expression into internal code
332 + * We can't allocate space until we know how big the compiled form will be,
333 + * but we can't compile it (and thus know how big it is) until we've got a
334 + * place to put the code. So we cheat: we compile it twice, once with code
335 + * generation turned off and size counting turned on, and once "for real".
336 + * This also means that we don't allocate space until we are sure that the
337 + * thing really will compile successfully, and we never have to move the
338 + * code and thus invalidate pointers into it. (Note that it has to be in
339 + * one piece because free() must be able to free it all.)
341 + * Beware that the optimization-preparation code in here knows about some
342 + * of the structure of the compiled regexp.
345 +regcomp(char *exp,int *patternsize)
347 + register regexp *r;
348 + register char *scan;
349 + register char *longest;
352 + struct match_globals g;
354 + /* commented out by ethan
355 + extern char *malloc();
359 + FAIL("NULL argument");
361 + /* First pass: determine size, legality. */
365 + g.regcode = &g.regdummy;
367 + if (reg(&g, 0, &flags) == NULL)
370 + /* Small enough for pointer-storage convention? */
371 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
372 + FAIL("regexp too big");
374 + /* Allocate space. */
375 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
376 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
378 + FAIL("out of space");
380 + /* Second pass: emit code. */
383 + g.regcode = r->program;
385 + if (reg(&g, 0, &flags) == NULL)
388 + /* Dig out information for optimizations. */
389 + r->regstart = '\0'; /* Worst-case defaults. */
393 + scan = r->program+1; /* First BRANCH. */
394 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
395 + scan = OPERAND(scan);
397 + /* Starting-point info. */
398 + if (OP(scan) == EXACTLY)
399 + r->regstart = *OPERAND(scan);
400 + else if (OP(scan) == BOL)
404 + * If there's something expensive in the r.e., find the
405 + * longest literal string that must appear and make it the
406 + * regmust. Resolve ties in favor of later strings, since
407 + * the regstart check works with the beginning of the r.e.
408 + * and avoiding duplication strengthens checking. Not a
409 + * strong reason, but sufficient in the absence of others.
411 + if (flags&SPSTART) {
414 + for (; scan != NULL; scan = regnext(&g, scan))
415 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
416 + longest = OPERAND(scan);
417 + len = strlen(OPERAND(scan));
419 + r->regmust = longest;
428 + - reg - regular expression, i.e. main body or parenthesized thing
430 + * Caller must absorb opening parenthesis.
432 + * Combining parenthesis handling with the base level of regular expression
433 + * is a trifle forced, but the need to tie the tails of the branches to what
434 + * follows makes it hard to avoid.
437 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
439 + register char *ret;
441 + register char *ender;
442 + register int parno = 0; /* 0 makes gcc happy */
445 + *flagp = HASWIDTH; /* Tentatively. */
447 + /* Make an OPEN node, if parenthesized. */
449 + if (g->regnpar >= NSUBEXP)
450 + FAIL("too many ()");
451 + parno = g->regnpar;
453 + ret = regnode(g, OPEN+parno);
457 + /* Pick up the branches, linking them together. */
458 + br = regbranch(g, &flags);
462 + regtail(g, ret, br); /* OPEN -> first. */
465 + if (!(flags&HASWIDTH))
466 + *flagp &= ~HASWIDTH;
467 + *flagp |= flags&SPSTART;
468 + while (*g->regparse == '|') {
470 + br = regbranch(g, &flags);
473 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
474 + if (!(flags&HASWIDTH))
475 + *flagp &= ~HASWIDTH;
476 + *flagp |= flags&SPSTART;
479 + /* Make a closing node, and hook it on the end. */
480 + ender = regnode(g, (paren) ? CLOSE+parno : END);
481 + regtail(g, ret, ender);
483 + /* Hook the tails of the branches to the closing node. */
484 + for (br = ret; br != NULL; br = regnext(g, br))
485 + regoptail(g, br, ender);
487 + /* Check for proper termination. */
488 + if (paren && *g->regparse++ != ')') {
489 + FAIL("unmatched ()");
490 + } else if (!paren && *g->regparse != '\0') {
491 + if (*g->regparse == ')') {
492 + FAIL("unmatched ()");
494 + FAIL("junk on end"); /* "Can't happen". */
502 + - regbranch - one alternative of an | operator
504 + * Implements the concatenation operator.
507 +regbranch(struct match_globals *g, int *flagp)
509 + register char *ret;
510 + register char *chain;
511 + register char *latest;
514 + *flagp = WORST; /* Tentatively. */
516 + ret = regnode(g, BRANCH);
518 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
519 + latest = regpiece(g, &flags);
520 + if (latest == NULL)
522 + *flagp |= flags&HASWIDTH;
523 + if (chain == NULL) /* First piece. */
524 + *flagp |= flags&SPSTART;
526 + regtail(g, chain, latest);
529 + if (chain == NULL) /* Loop ran zero times. */
530 + (void) regnode(g, NOTHING);
536 + - regpiece - something followed by possible [*+?]
538 + * Note that the branching code sequences used for ? and the general cases
539 + * of * and + are somewhat optimized: they use the same NOTHING node as
540 + * both the endmarker for their branch list and the body of the last branch.
541 + * It might seem that this node could be dispensed with entirely, but the
542 + * endmarker role is not redundant.
545 +regpiece(struct match_globals *g, int *flagp)
547 + register char *ret;
549 + register char *next;
552 + ret = regatom(g, &flags);
562 + if (!(flags&HASWIDTH) && op != '?')
563 + FAIL("*+ operand could be empty");
564 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
566 + if (op == '*' && (flags&SIMPLE))
567 + reginsert(g, STAR, ret);
568 + else if (op == '*') {
569 + /* Emit x* as (x&|), where & means "self". */
570 + reginsert(g, BRANCH, ret); /* Either x */
571 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
572 + regoptail(g, ret, ret); /* back */
573 + regtail(g, ret, regnode(g, BRANCH)); /* or */
574 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
575 + } else if (op == '+' && (flags&SIMPLE))
576 + reginsert(g, PLUS, ret);
577 + else if (op == '+') {
578 + /* Emit x+ as x(&|), where & means "self". */
579 + next = regnode(g, BRANCH); /* Either */
580 + regtail(g, ret, next);
581 + regtail(g, regnode(g, BACK), ret); /* loop back */
582 + regtail(g, next, regnode(g, BRANCH)); /* or */
583 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
584 + } else if (op == '?') {
585 + /* Emit x? as (x|) */
586 + reginsert(g, BRANCH, ret); /* Either x */
587 + regtail(g, ret, regnode(g, BRANCH)); /* or */
588 + next = regnode(g, NOTHING); /* null. */
589 + regtail(g, ret, next);
590 + regoptail(g, ret, next);
593 + if (ISMULT(*g->regparse))
594 + FAIL("nested *?+");
600 + - regatom - the lowest level
602 + * Optimization: gobbles an entire sequence of ordinary characters so that
603 + * it can turn them into a single node, which is smaller to store and
604 + * faster to run. Backslashed characters are exceptions, each becoming a
605 + * separate node; the code is simpler that way and it's not worth fixing.
608 +regatom(struct match_globals *g, int *flagp)
610 + register char *ret;
613 + *flagp = WORST; /* Tentatively. */
615 + switch (*g->regparse++) {
617 + ret = regnode(g, BOL);
620 + ret = regnode(g, EOL);
623 + ret = regnode(g, ANY);
624 + *flagp |= HASWIDTH|SIMPLE;
627 + register int class;
628 + register int classend;
630 + if (*g->regparse == '^') { /* Complement of range. */
631 + ret = regnode(g, ANYBUT);
634 + ret = regnode(g, ANYOF);
635 + if (*g->regparse == ']' || *g->regparse == '-')
636 + regc(g, *g->regparse++);
637 + while (*g->regparse != '\0' && *g->regparse != ']') {
638 + if (*g->regparse == '-') {
640 + if (*g->regparse == ']' || *g->regparse == '\0')
643 + class = UCHARAT(g->regparse-2)+1;
644 + classend = UCHARAT(g->regparse);
645 + if (class > classend+1)
646 + FAIL("invalid [] range");
647 + for (; class <= classend; class++)
652 + regc(g, *g->regparse++);
655 + if (*g->regparse != ']')
656 + FAIL("unmatched []");
658 + *flagp |= HASWIDTH|SIMPLE;
662 + ret = reg(g, 1, &flags);
665 + *flagp |= flags&(HASWIDTH|SPSTART);
670 + FAIL("internal urp"); /* Supposed to be caught earlier. */
675 + FAIL("?+* follows nothing");
678 + if (*g->regparse == '\0')
679 + FAIL("trailing \\");
680 + ret = regnode(g, EXACTLY);
681 + regc(g, *g->regparse++);
683 + *flagp |= HASWIDTH|SIMPLE;
687 + register char ender;
690 + len = my_strcspn((const char *)g->regparse, (const char *)META);
692 + FAIL("internal disaster");
693 + ender = *(g->regparse+len);
694 + if (len > 1 && ISMULT(ender))
695 + len--; /* Back off clear of ?+* operand. */
696 + *flagp |= HASWIDTH;
699 + ret = regnode(g, EXACTLY);
701 + regc(g, *g->regparse++);
713 + - regnode - emit a node
715 +static char * /* Location. */
716 +regnode(struct match_globals *g, char op)
718 + register char *ret;
719 + register char *ptr;
722 + if (ret == &g->regdummy) {
729 + *ptr++ = '\0'; /* Null "next" pointer. */
737 + - regc - emit (if appropriate) a byte of code
740 +regc(struct match_globals *g, char b)
742 + if (g->regcode != &g->regdummy)
749 + - reginsert - insert an operator in front of already-emitted operand
751 + * Means relocating the operand.
754 +reginsert(struct match_globals *g, char op, char* opnd)
756 + register char *src;
757 + register char *dst;
758 + register char *place;
760 + if (g->regcode == &g->regdummy) {
771 + place = opnd; /* Op node, where operand used to be. */
778 + - regtail - set the next-pointer at the end of a node chain
781 +regtail(struct match_globals *g, char *p, char *val)
783 + register char *scan;
784 + register char *temp;
785 + register int offset;
787 + if (p == &g->regdummy)
790 + /* Find last node. */
793 + temp = regnext(g, scan);
799 + if (OP(scan) == BACK)
800 + offset = scan - val;
802 + offset = val - scan;
803 + *(scan+1) = (offset>>8)&0377;
804 + *(scan+2) = offset&0377;
808 + - regoptail - regtail on operand of first argument; nop if operandless
811 +regoptail(struct match_globals *g, char *p, char *val)
813 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
814 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
816 + regtail(g, OPERAND(p), val);
820 + * regexec and friends
827 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
828 +STATIC int regmatch(struct match_globals *g, char *prog);
829 +STATIC int regrepeat(struct match_globals *g, char *p);
834 +STATIC char *regprop(char *op);
838 + - regexec - match a regexp against a string
841 +regexec(regexp *prog, char *string)
844 + struct match_globals g;
846 + /* Be paranoid... */
847 + if (prog == NULL || string == NULL) {
848 + printk("<3>Regexp: NULL parameter\n");
852 + /* Check validity of program. */
853 + if (UCHARAT(prog->program) != MAGIC) {
854 + printk("<3>Regexp: corrupted program\n");
858 + /* If there is a "must appear" string, look for it. */
859 + if (prog->regmust != NULL) {
861 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
862 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
863 + break; /* Found it. */
866 + if (s == NULL) /* Not present. */
870 + /* Mark beginning of line for ^ . */
873 + /* Simplest case: anchored match need be tried only once. */
875 + return(regtry(&g, prog, string));
877 + /* Messy cases: unanchored match. */
879 + if (prog->regstart != '\0')
880 + /* We know what char it must start with. */
881 + while ((s = strchr(s, prog->regstart)) != NULL) {
882 + if (regtry(&g, prog, s))
887 + /* We don't -- general case. */
889 + if (regtry(&g, prog, s))
891 + } while (*s++ != '\0');
898 + - regtry - try match at specific point
900 +static int /* 0 failure, 1 success */
901 +regtry(struct match_globals *g, regexp *prog, char *string)
904 + register char **sp;
905 + register char **ep;
907 + g->reginput = string;
908 + g->regstartp = prog->startp;
909 + g->regendp = prog->endp;
913 + for (i = NSUBEXP; i > 0; i--) {
917 + if (regmatch(g, prog->program + 1)) {
918 + prog->startp[0] = string;
919 + prog->endp[0] = g->reginput;
926 + - regmatch - main matching routine
928 + * Conceptually the strategy is simple: check to see whether the current
929 + * node matches, call self recursively to see whether the rest matches,
930 + * and then act accordingly. In practice we make some effort to avoid
931 + * recursion, in particular by going through "ordinary" nodes (that don't
932 + * need to know whether the rest of the match failed) by a loop instead of
935 +static int /* 0 failure, 1 success */
936 +regmatch(struct match_globals *g, char *prog)
938 + register char *scan = prog; /* Current node. */
939 + char *next; /* Next node. */
942 + if (scan != NULL && regnarrate)
943 + fprintf(stderr, "%s(\n", regprop(scan));
945 + while (scan != NULL) {
948 + fprintf(stderr, "%s...\n", regprop(scan));
950 + next = regnext(g, scan);
952 + switch (OP(scan)) {
954 + if (g->reginput != g->regbol)
958 + if (*g->reginput != '\0')
962 + if (*g->reginput == '\0')
968 + register char *opnd;
970 + opnd = OPERAND(scan);
971 + /* Inline the first character, for speed. */
972 + if (*opnd != *g->reginput)
974 + len = strlen(opnd);
975 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
977 + g->reginput += len;
981 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
986 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1003 + register char *save;
1005 + no = OP(scan) - OPEN;
1006 + save = g->reginput;
1008 + if (regmatch(g, next)) {
1010 + * Don't set startp if some later
1011 + * invocation of the same parentheses
1014 + if (g->regstartp[no] == NULL)
1015 + g->regstartp[no] = save;
1032 + register char *save;
1034 + no = OP(scan) - CLOSE;
1035 + save = g->reginput;
1037 + if (regmatch(g, next)) {
1039 + * Don't set endp if some later
1040 + * invocation of the same parentheses
1043 + if (g->regendp[no] == NULL)
1044 + g->regendp[no] = save;
1051 + register char *save;
1053 + if (OP(next) != BRANCH) /* No choice. */
1054 + next = OPERAND(scan); /* Avoid recursion. */
1057 + save = g->reginput;
1058 + if (regmatch(g, OPERAND(scan)))
1060 + g->reginput = save;
1061 + scan = regnext(g, scan);
1062 + } while (scan != NULL && OP(scan) == BRANCH);
1070 + register char nextch;
1072 + register char *save;
1076 + * Lookahead to avoid useless match attempts
1077 + * when we know what character comes next.
1080 + if (OP(next) == EXACTLY)
1081 + nextch = *OPERAND(next);
1082 + min = (OP(scan) == STAR) ? 0 : 1;
1083 + save = g->reginput;
1084 + no = regrepeat(g, OPERAND(scan));
1085 + while (no >= min) {
1086 + /* If it could work, try it. */
1087 + if (nextch == '\0' || *g->reginput == nextch)
1088 + if (regmatch(g, next))
1090 + /* Couldn't or didn't -- back up. */
1092 + g->reginput = save + no;
1098 + return(1); /* Success! */
1101 + printk("<3>Regexp: memory corruption\n");
1110 + * We get here only if there's trouble -- normally "case END" is
1111 + * the terminating point.
1113 + printk("<3>Regexp: corrupted pointers\n");
1118 + - regrepeat - repeatedly match something simple, report how many
1121 +regrepeat(struct match_globals *g, char *p)
1123 + register int count = 0;
1124 + register char *scan;
1125 + register char *opnd;
1127 + scan = g->reginput;
1128 + opnd = OPERAND(p);
1131 + count = strlen(scan);
1135 + while (*opnd == *scan) {
1141 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1147 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1152 + default: /* Oh dear. Called inappropriately. */
1153 + printk("<3>Regexp: internal foulup\n");
1154 + count = 0; /* Best compromise. */
1157 + g->reginput = scan;
1163 + - regnext - dig the "next" pointer out of a node
1166 +regnext(struct match_globals *g, char *p)
1168 + register int offset;
1170 + if (p == &g->regdummy)
1177 + if (OP(p) == BACK)
1185 +STATIC char *regprop();
1188 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1194 + register char op = EXACTLY; /* Arbitrary non-END op. */
1195 + register char *next;
1196 + /* extern char *strchr(); */
1199 + s = r->program + 1;
1200 + while (op != END) { /* While that wasn't END last time... */
1202 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1203 + next = regnext(s);
1204 + if (next == NULL) /* Next ptr. */
1207 + printf("(%d)", (s-r->program)+(next-s));
1209 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1210 + /* Literal string, where present. */
1211 + while (*s != '\0') {
1220 + /* Header fields of interest. */
1221 + if (r->regstart != '\0')
1222 + printf("start `%c' ", r->regstart);
1224 + printf("anchored ");
1225 + if (r->regmust != NULL)
1226 + printf("must have \"%s\"", r->regmust);
1231 + - regprop - printable representation of opcode
1238 + static char buf[BUFLEN];
1282 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1294 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1304 + printk("<3>Regexp: corrupted opcode\n");
1308 + strncat(buf, p, BUFLEN-strlen(buf));
1315 +++ b/net/netfilter/regexp/regexp.h
1318 + * Definitions etc. for regexp(3) routines.
1320 + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
1321 + * not the System V one.
1329 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1330 +which contains a version of this library, says:
1333 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1334 + * will not work properly.
1337 +However, it looks rather like this library is limited to 10. If you think
1338 +otherwise, let us know.
1342 +typedef struct regexp {
1343 + char *startp[NSUBEXP];
1344 + char *endp[NSUBEXP];
1345 + char regstart; /* Internal use only. */
1346 + char reganch; /* Internal use only. */
1347 + char *regmust; /* Internal use only. */
1348 + int regmlen; /* Internal use only. */
1349 + char program[1]; /* Unwarranted chumminess with compiler. */
1352 +regexp * regcomp(char *exp, int *patternsize);
1353 +int regexec(regexp *prog, char *string);
1354 +void regsub(regexp *prog, char *source, char *dest);
1355 +void regerror(char *s);
1359 +++ b/net/netfilter/regexp/regmagic.h
1362 + * The first byte of the regexp internal "program" is actually this magic
1363 + * number; the start node begins in the second byte.
1367 +++ b/net/netfilter/regexp/regsub.c
1371 + * @(#)regsub.c 1.3 of 2 April 86
1373 + * Copyright (c) 1986 by University of Toronto.
1374 + * Written by Henry Spencer. Not derived from licensed software.
1376 + * Permission is granted to anyone to use this software for any
1377 + * purpose on any computer system, and to redistribute it freely,
1378 + * subject to the following restrictions:
1380 + * 1. The author is not responsible for the consequences of use of
1381 + * this software, no matter how awful, even if they arise
1382 + * from defects in it.
1384 + * 2. The origin of this software must not be misrepresented, either
1385 + * by explicit claim or by omission.
1387 + * 3. Altered versions must be plainly marked as such, and must not
1388 + * be misrepresented as being the original software.
1391 + * This code was modified by Ethan Sommer to work within the kernel
1392 + * (it now uses kmalloc etc..)
1395 +#include "regexp.h"
1396 +#include "regmagic.h"
1397 +#include <linux/string.h>
1401 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1403 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
1407 +//void regerror(char * s)
1409 +// printk("regexp(3): %s", s);
1410 +// /* NOTREACHED */
1415 + - regsub - perform substitutions after a regexp match
1418 +regsub(regexp * prog, char * source, char * dest)
1420 + register char *src;
1421 + register char *dst;
1426 + /* Not necessary and gcc doesn't like it -MLS */
1427 + /*extern char *strncpy();*/
1429 + if (prog == NULL || source == NULL || dest == NULL) {
1430 + regerror("NULL parm to regsub");
1433 + if (UCHARAT(prog->program) != MAGIC) {
1434 + regerror("damaged regexp fed to regsub");
1440 + while ((c = *src++) != '\0') {
1443 + else if (c == '\\' && '0' <= *src && *src <= '9')
1444 + no = *src++ - '0';
1448 + if (no < 0) { /* Ordinary character. */
1449 + if (c == '\\' && (*src == '\\' || *src == '&'))
1452 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
1453 + len = prog->endp[no] - prog->startp[no];
1454 + (void) strncpy(dst, prog->startp[no], len);
1456 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
1457 + regerror("damaged match string");
1465 +++ b/net/netfilter/xt_layer7.c
1468 + Kernel module to match application layer (OSI layer 7) data in connections.
1470 + http://l7-filter.sf.net
1472 + (C) 2003, 2004, 2005, 2006, 2007 Matthew Strait and Ethan Sommer.
1474 + This program is free software; you can redistribute it and/or
1475 + modify it under the terms of the GNU General Public License
1476 + as published by the Free Software Foundation; either version
1477 + 2 of the License, or (at your option) any later version.
1478 + http://www.gnu.org/licenses/gpl.txt
1480 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
1481 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
1482 + Ethan Sommer, Justin Levandoski.
1485 +#include <linux/spinlock.h>
1486 +#include <linux/version.h>
1487 +#include <net/ip.h>
1488 +#include <net/tcp.h>
1489 +#include <linux/module.h>
1490 +#include <linux/skbuff.h>
1491 +#include <linux/netfilter.h>
1492 +#include <net/netfilter/nf_conntrack.h>
1493 +#include <net/netfilter/nf_conntrack_core.h>
1494 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
1495 +#include <net/netfilter/nf_conntrack_extend.h>
1496 +#include <net/netfilter/nf_conntrack_acct.h>
1498 +#include <linux/netfilter/x_tables.h>
1499 +#include <linux/netfilter/xt_layer7.h>
1500 +#include <linux/ctype.h>
1501 +#include <linux/proc_fs.h>
1503 +#include "regexp/regexp.c"
1505 +MODULE_LICENSE("GPL");
1506 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
1507 +MODULE_DESCRIPTION("iptables application layer match module");
1508 +MODULE_ALIAS("ipt_layer7");
1509 +MODULE_VERSION("2.19");
1511 +static int maxdatalen = 2048; // this is the default
1512 +module_param(maxdatalen, int, 0444);
1513 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
1514 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
1515 + #define DPRINTK(format,args...) printk(format,##args)
1517 + #define DPRINTK(format,args...)
1520 +/* Number of packets whose data we look at.
1521 +This can be modified through /proc/net/layer7_numpackets */
1522 +static int num_packets = 10;
1524 +static struct pattern_cache {
1525 + char * regex_string;
1527 + struct pattern_cache * next;
1528 +} * first_pattern_cache = NULL;
1530 +DEFINE_SPINLOCK(l7_lock);
1532 +static int total_acct_packets(struct nf_conn *ct)
1534 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 26)
1535 + BUG_ON(ct == NULL);
1536 + return (ct->counters[IP_CT_DIR_ORIGINAL].packets + ct->counters[IP_CT_DIR_REPLY].packets);
1538 + struct nf_conn_counter *acct;
1540 + BUG_ON(ct == NULL);
1541 + acct = nf_conn_acct_find(ct);
1544 + return (acct[IP_CT_DIR_ORIGINAL].packets + acct[IP_CT_DIR_REPLY].packets);
1548 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1549 +/* Converts an unfriendly string into a friendly one by
1550 +replacing unprintables with periods and all whitespace with " ". */
1551 +static char * friendly_print(unsigned char * s)
1553 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
1557 + if (net_ratelimit())
1558 + printk(KERN_ERR "layer7: out of memory in "
1559 + "friendly_print, bailing.\n");
1563 + for(i = 0; i < strlen(s); i++){
1564 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
1565 + else if(isspace(s[i])) f[i] = ' ';
1572 +static char dec2hex(int i)
1579 + return (i - 10 + 'a');
1582 + if (net_ratelimit())
1583 + printk("layer7: Problem in dec2hex\n");
1588 +static char * hex_print(unsigned char * s)
1590 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
1594 + if (net_ratelimit())
1595 + printk(KERN_ERR "layer7: out of memory in hex_print, "
1600 + for(i = 0; i < strlen(s); i++) {
1601 + g[i*3 ] = dec2hex(s[i]/16);
1602 + g[i*3 + 1] = dec2hex(s[i]%16);
1611 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
1612 +over again, it make sense to cache the results. */
1613 +static regexp * compile_and_cache(const char * regex_string,
1614 + const char * protocol)
1616 + struct pattern_cache * node = first_pattern_cache;
1617 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
1618 + struct pattern_cache * tmp;
1621 + while (node != NULL) {
1622 + if (!strcmp(node->regex_string, regex_string))
1623 + return node->pattern;
1625 + last_pattern_cache = node;/* points at the last non-NULL node */
1626 + node = node->next;
1629 + /* If we reach the end of the list, then we have not yet cached
1630 + the pattern for this regex. Let's do that now.
1631 + Be paranoid about running out of memory to avoid list corruption. */
1632 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
1635 + if (net_ratelimit())
1636 + printk(KERN_ERR "layer7: out of memory in "
1637 + "compile_and_cache, bailing.\n");
1641 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
1642 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
1645 + if(!tmp->regex_string || !tmp->pattern) {
1646 + if (net_ratelimit())
1647 + printk(KERN_ERR "layer7: out of memory in "
1648 + "compile_and_cache, bailing.\n");
1649 + kfree(tmp->regex_string);
1650 + kfree(tmp->pattern);
1655 + /* Ok. The new node is all ready now. */
1658 + if(first_pattern_cache == NULL) /* list is empty */
1659 + first_pattern_cache = node; /* make node the beginning */
1661 + last_pattern_cache->next = node; /* attach node to the end */
1663 + /* copy the string and compile the regex */
1664 + len = strlen(regex_string);
1665 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
1666 + node->pattern = regcomp((char *)regex_string, &len);
1667 + if ( !node->pattern ) {
1668 + if (net_ratelimit())
1669 + printk(KERN_ERR "layer7: Error compiling regexp "
1671 + regex_string, protocol);
1672 + /* pattern is now cached as NULL, so we won't try again. */
1675 + strcpy(node->regex_string, regex_string);
1676 + return node->pattern;
1679 +static int can_handle(const struct sk_buff *skb)
1681 + if(!ip_hdr(skb)) /* not IP */
1683 + if(ip_hdr(skb)->protocol != IPPROTO_TCP &&
1684 + ip_hdr(skb)->protocol != IPPROTO_UDP &&
1685 + ip_hdr(skb)->protocol != IPPROTO_ICMP)
1690 +/* Returns offset the into the skb->data that the application data starts */
1691 +static int app_data_offset(const struct sk_buff *skb)
1693 + /* In case we are ported somewhere (ebtables?) where ip_hdr(skb)
1694 + isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
1695 + int ip_hl = 4*ip_hdr(skb)->ihl;
1697 + if( ip_hdr(skb)->protocol == IPPROTO_TCP ) {
1698 + /* 12 == offset into TCP header for the header length field.
1699 + Can't get this with skb->h.th->doff because the tcphdr
1700 + struct doesn't get set when routing (this is confirmed to be
1701 + true in Netfilter as well as QoS.) */
1702 + int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
1704 + return ip_hl + tcp_hl;
1705 + } else if( ip_hdr(skb)->protocol == IPPROTO_UDP ) {
1706 + return ip_hl + 8; /* UDP header is always 8 bytes */
1707 + } else if( ip_hdr(skb)->protocol == IPPROTO_ICMP ) {
1708 + return ip_hl + 8; /* ICMP header is 8 bytes */
1710 + if (net_ratelimit())
1711 + printk(KERN_ERR "layer7: tried to handle unknown "
1713 + return ip_hl + 8; /* something reasonable */
1717 +/* handles whether there's a match when we aren't appending data anymore */
1718 +static int match_no_append(struct nf_conn * conntrack,
1719 + struct nf_conn * master_conntrack,
1720 + enum ip_conntrack_info ctinfo,
1721 + enum ip_conntrack_info master_ctinfo,
1722 + const struct xt_layer7_info * info)
1724 + /* If we're in here, throw the app data away */
1725 + if(master_conntrack->layer7.app_data != NULL) {
1727 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1728 + if(!master_conntrack->layer7.app_proto) {
1730 + friendly_print(master_conntrack->layer7.app_data);
1732 + hex_print(master_conntrack->layer7.app_data);
1733 + DPRINTK("\nl7-filter gave up after %d bytes "
1734 + "(%d packets):\n%s\n",
1735 + strlen(f), total_acct_packets(master_conntrack), f);
1737 + DPRINTK("In hex: %s\n", g);
1742 + kfree(master_conntrack->layer7.app_data);
1743 + master_conntrack->layer7.app_data = NULL; /* don't free again */
1746 + if(master_conntrack->layer7.app_proto){
1747 + /* Here child connections set their .app_proto (for /proc) */
1748 + if(!conntrack->layer7.app_proto) {
1749 + conntrack->layer7.app_proto =
1750 + kmalloc(strlen(master_conntrack->layer7.app_proto)+1,
1752 + if(!conntrack->layer7.app_proto){
1753 + if (net_ratelimit())
1754 + printk(KERN_ERR "layer7: out of memory "
1755 + "in match_no_append, "
1759 + strcpy(conntrack->layer7.app_proto,
1760 + master_conntrack->layer7.app_proto);
1763 + return (!strcmp(master_conntrack->layer7.app_proto,
1767 + /* If not classified, set to "unknown" to distinguish from
1768 + connections that are still being tested. */
1769 + master_conntrack->layer7.app_proto =
1770 + kmalloc(strlen("unknown")+1, GFP_ATOMIC);
1771 + if(!master_conntrack->layer7.app_proto){
1772 + if (net_ratelimit())
1773 + printk(KERN_ERR "layer7: out of memory in "
1774 + "match_no_append, bailing.\n");
1777 + strcpy(master_conntrack->layer7.app_proto, "unknown");
1782 +/* add the new app data to the conntrack. Return number of bytes added. */
1783 +static int add_data(struct nf_conn * master_conntrack,
1784 + char * app_data, int appdatalen)
1786 + int length = 0, i;
1787 + int oldlength = master_conntrack->layer7.app_data_len;
1789 + /* This is a fix for a race condition by Deti Fliegl. However, I'm not
1790 + clear on whether the race condition exists or whether this really
1791 + fixes it. I might just be being dense... Anyway, if it's not really
1792 + a fix, all it does is waste a very small amount of time. */
1793 + if(!master_conntrack->layer7.app_data) return 0;
1795 + /* Strip nulls. Make everything lower case (our regex lib doesn't
1796 + do case insensitivity). Add it to the end of the current data. */
1797 + for(i = 0; i < maxdatalen-oldlength-1 &&
1798 + i < appdatalen; i++) {
1799 + if(app_data[i] != '\0') {
1800 + /* the kernel version of tolower mungs 'upper ascii' */
1801 + master_conntrack->layer7.app_data[length+oldlength] =
1802 + isascii(app_data[i])?
1803 + tolower(app_data[i]) : app_data[i];
1808 + master_conntrack->layer7.app_data[length+oldlength] = '\0';
1809 + master_conntrack->layer7.app_data_len = length + oldlength;
1814 +/* taken from drivers/video/modedb.c */
1815 +static int my_atoi(const char *s)
1822 + val = 10*val+(*s-'0');
1830 +/* write out num_packets to userland. */
1831 +static int layer7_read_proc(char* page, char ** start, off_t off, int count,
1832 + int* eof, void * data)
1834 + if(num_packets > 99 && net_ratelimit())
1835 + printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
1837 + page[0] = num_packets/10 + '0';
1838 + page[1] = num_packets%10 + '0';
1847 +/* Read in num_packets from userland */
1848 +static int layer7_write_proc(struct file* file, const char* buffer,
1849 + unsigned long count, void *data)
1851 + char * foo = kmalloc(count, GFP_ATOMIC);
1854 + if (net_ratelimit())
1855 + printk(KERN_ERR "layer7: out of memory, bailing. "
1856 + "num_packets unchanged.\n");
1860 + if(copy_from_user(foo, buffer, count)) {
1865 + num_packets = my_atoi(foo);
1868 + /* This has an arbitrary limit to make the math easier. I'm lazy.
1869 + But anyway, 99 is a LOT! If you want more, you're doing it wrong! */
1870 + if(num_packets > 99) {
1871 + printk(KERN_WARNING "layer7: num_packets can't be > 99.\n");
1873 + } else if(num_packets < 1) {
1874 + printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
1882 +match(const struct sk_buff *skbin,
1883 + const struct net_device *in,
1884 + const struct net_device *out,
1885 + const struct xt_match *match,
1886 + const void *matchinfo,
1888 + unsigned int protoff,
1891 + /* sidestep const without getting a compiler warning... */
1892 + struct sk_buff * skb = (struct sk_buff *)skbin;
1894 + const struct xt_layer7_info * info = matchinfo;
1895 + enum ip_conntrack_info master_ctinfo, ctinfo;
1896 + struct nf_conn *master_conntrack, *conntrack;
1897 + unsigned char * app_data;
1898 + unsigned int pattern_result, appdatalen;
1899 + regexp * comppattern;
1901 + /* Be paranoid/incompetent - lock the entire match function. */
1902 + spin_lock_bh(&l7_lock);
1904 + if(!can_handle(skb)){
1905 + DPRINTK("layer7: This is some protocol I can't handle.\n");
1906 + spin_unlock_bh(&l7_lock);
1907 + return info->invert;
1910 + /* Treat parent & all its children together as one connection, except
1911 + for the purpose of setting conntrack->layer7.app_proto in the actual
1912 + connection. This makes /proc/net/ip_conntrack more satisfying. */
1913 + if(!(conntrack = nf_ct_get(skb, &ctinfo)) ||
1914 + !(master_conntrack=nf_ct_get(skb,&master_ctinfo))){
1915 + DPRINTK("layer7: couldn't get conntrack.\n");
1916 + spin_unlock_bh(&l7_lock);
1917 + return info->invert;
1920 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
1921 + while (master_ct(master_conntrack) != NULL)
1922 + master_conntrack = master_ct(master_conntrack);
1924 + /* if we've classified it or seen too many packets */
1925 + if(total_acct_packets(master_conntrack) > num_packets ||
1926 + master_conntrack->layer7.app_proto) {
1928 + pattern_result = match_no_append(conntrack, master_conntrack,
1929 + ctinfo, master_ctinfo, info);
1931 + /* skb->cb[0] == seen. Don't do things twice if there are
1932 + multiple l7 rules. I'm not sure that using cb for this purpose
1933 + is correct, even though it says "put your private variables
1934 + there". But it doesn't look like it is being used for anything
1935 + else in the skbs that make it here. */
1936 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
1938 + spin_unlock_bh(&l7_lock);
1939 + return (pattern_result ^ info->invert);
1942 + if(skb_is_nonlinear(skb)){
1943 + if(skb_linearize(skb) != 0){
1944 + if (net_ratelimit())
1945 + printk(KERN_ERR "layer7: failed to linearize "
1946 + "packet, bailing.\n");
1947 + spin_unlock_bh(&l7_lock);
1948 + return info->invert;
1952 + /* now that the skb is linearized, it's safe to set these. */
1953 + app_data = skb->data + app_data_offset(skb);
1954 + appdatalen = skb_tail_pointer(skb) - app_data;
1956 + /* the return value gets checked later, when we're ready to use it */
1957 + comppattern = compile_and_cache(info->pattern, info->protocol);
1959 + /* On the first packet of a connection, allocate space for app data */
1960 + if(total_acct_packets(master_conntrack) == 1 && !skb->cb[0] &&
1961 + !master_conntrack->layer7.app_data){
1962 + master_conntrack->layer7.app_data =
1963 + kmalloc(maxdatalen, GFP_ATOMIC);
1964 + if(!master_conntrack->layer7.app_data){
1965 + if (net_ratelimit())
1966 + printk(KERN_ERR "layer7: out of memory in "
1967 + "match, bailing.\n");
1968 + spin_unlock_bh(&l7_lock);
1969 + return info->invert;
1972 + master_conntrack->layer7.app_data[0] = '\0';
1975 + /* Can be here, but unallocated, if numpackets is increased near
1976 + the beginning of a connection */
1977 + if(master_conntrack->layer7.app_data == NULL){
1978 + spin_unlock_bh(&l7_lock);
1979 + return (info->invert); /* unmatched */
1984 + newbytes = add_data(master_conntrack, app_data, appdatalen);
1986 + if(newbytes == 0) { /* didn't add any data */
1988 + /* Didn't match before, not going to match now */
1989 + spin_unlock_bh(&l7_lock);
1990 + return info->invert;
1994 + /* If looking for "unknown", then never match. "Unknown" means that
1995 + we've given up; we're still trying with these packets. */
1996 + if(!strcmp(info->protocol, "unknown")) {
1997 + pattern_result = 0;
1998 + /* If looking for "unset", then always match. "Unset" means that we
1999 + haven't yet classified the connection. */
2000 + } else if(!strcmp(info->protocol, "unset")) {
2001 + pattern_result = 2;
2002 + DPRINTK("layer7: matched unset: not yet classified "
2003 + "(%d/%d packets)\n", total_acct_packets(master_conntrack), num_packets);
2004 + /* If the regexp failed to compile, don't bother running it */
2005 + } else if(comppattern &&
2006 + regexec(comppattern, master_conntrack->layer7.app_data)){
2007 + DPRINTK("layer7: matched %s\n", info->protocol);
2008 + pattern_result = 1;
2009 + } else pattern_result = 0;
2011 + if(pattern_result == 1) {
2012 + master_conntrack->layer7.app_proto =
2013 + kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
2014 + if(!master_conntrack->layer7.app_proto){
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 (pattern_result ^ info->invert);
2021 + strcpy(master_conntrack->layer7.app_proto, info->protocol);
2022 + } else if(pattern_result > 1) { /* cleanup from "unset" */
2023 + pattern_result = 1;
2026 + /* mark the packet seen */
2029 + spin_unlock_bh(&l7_lock);
2030 + return (pattern_result ^ info->invert);
2033 +static bool check(const char *tablename,
2035 + const struct xt_match *match,
2037 + unsigned int hook_mask)
2040 + // load nf_conntrack_ipv4
2041 + if (nf_ct_l3proto_try_module_get(match->family) < 0) {
2042 + printk(KERN_WARNING "can't load conntrack support for "
2043 + "proto=%d\n", match->family);
2050 +destroy(const struct xt_match *match, void *matchinfo)
2052 + nf_ct_l3proto_module_put(match->family);
2055 +static struct xt_match xt_layer7_match[] __read_mostly = {
2058 + .family = AF_INET,
2059 + .checkentry = check,
2061 + .destroy = destroy,
2062 + .matchsize = sizeof(struct xt_layer7_info),
2067 +static void layer7_cleanup_proc(void)
2069 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)
2070 + remove_proc_entry("layer7_numpackets", proc_net);
2072 + remove_proc_entry("layer7_numpackets", init_net.proc_net);
2076 +/* register the proc file */
2077 +static void layer7_init_proc(void)
2079 + struct proc_dir_entry* entry;
2080 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,23)
2081 + entry = create_proc_entry("layer7_numpackets", 0644, proc_net);
2083 + entry = create_proc_entry("layer7_numpackets", 0644, init_net.proc_net);
2085 + entry->read_proc = layer7_read_proc;
2086 + entry->write_proc = layer7_write_proc;
2089 +static int __init xt_layer7_init(void)
2093 + layer7_init_proc();
2094 + if(maxdatalen < 1) {
2095 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
2099 + /* This is not a hard limit. It's just here to prevent people from
2100 + bringing their slow machines to a grinding halt. */
2101 + else if(maxdatalen > 65536) {
2102 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
2104 + maxdatalen = 65536;
2106 + return xt_register_matches(xt_layer7_match,
2107 + ARRAY_SIZE(xt_layer7_match));
2110 +static void __exit xt_layer7_fini(void)
2112 + layer7_cleanup_proc();
2113 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
2116 +module_init(xt_layer7_init);
2117 +module_exit(xt_layer7_fini);