1 http://git.ipfire.org/?p=people/ms/linux.git;a=shortlog;h=refs/heads/linux-3.10.y-layer7
3 diff --git a/include/linux/netfilter/xt_layer7.h b/include/linux/netfilter/xt_layer7.h
7 +++ b/include/linux/netfilter/xt_layer7.h
12 +#define MAX_PATTERN_LEN 8192
13 +#define MAX_PROTOCOL_LEN 256
15 +struct xt_layer7_info {
16 + char protocol[MAX_PROTOCOL_LEN];
17 + char pattern[MAX_PATTERN_LEN];
22 +#endif /* _XT_LAYER7_H */
23 diff --git a/include/net/netfilter/nf_conntrack.h b/include/net/netfilter/nf_conntrack.h
24 index 644d9c2..b226a8f 100644
25 --- a/include/net/netfilter/nf_conntrack.h
26 +++ b/include/net/netfilter/nf_conntrack.h
27 @@ -105,6 +105,22 @@ struct nf_conn {
31 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
32 + defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
35 + * e.g. "http". NULL before decision. "unknown" after decision
40 + * application layer data so far. NULL after match decision.
43 + unsigned int app_data_len;
47 /* Storage reserved for other modules, must be the last member */
48 union nf_conntrack_proto proto;
50 diff --git a/include/uapi/linux/netfilter/Kbuild b/include/uapi/linux/netfilter/Kbuild
51 index 4111577..a95e6b5 100644
52 --- a/include/uapi/linux/netfilter/Kbuild
53 +++ b/include/uapi/linux/netfilter/Kbuild
54 @@ -53,6 +53,7 @@ header-y += xt_hashlimit.h
55 header-y += xt_helper.h
56 header-y += xt_iprange.h
58 +header-y += xt_layer7.h
59 header-y += xt_length.h
60 header-y += xt_limit.h
62 diff --git a/net/netfilter/Kconfig b/net/netfilter/Kconfig
63 index 56d22ca..7827ba4 100644
64 --- a/net/netfilter/Kconfig
65 +++ b/net/netfilter/Kconfig
66 @@ -1011,6 +1011,26 @@ config NETFILTER_XT_MATCH_IPVS
70 +config NETFILTER_XT_MATCH_LAYER7
71 + tristate '"layer7" match support'
72 + depends on NETFILTER_XTABLES
73 + depends on NETFILTER_ADVANCED
74 + depends on NF_CONNTRACK
76 + Say Y if you want to be able to classify connections (and their
77 + packets) based on regular expression matching of their application
78 + layer data. This is one way to classify applications such as
79 + peer-to-peer filesharing systems that do not always use the same
82 + To compile it as a module, choose M here. If unsure, say N.
84 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
85 + bool 'Layer 7 debugging output'
86 + depends on NETFILTER_XT_MATCH_LAYER7
88 + Say Y to get lots of debugging output.
90 config NETFILTER_XT_MATCH_LENGTH
91 tristate '"length" match support'
92 depends on NETFILTER_ADVANCED
93 @@ -1205,6 +1225,12 @@ config NETFILTER_XT_MATCH_STATE
95 To compile it as a module, choose M here. If unsure, say N.
97 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
98 + bool 'Layer 7 debugging output'
99 + depends on NETFILTER_XT_MATCH_LAYER7
101 + Say Y to get lots of debugging output.
103 config NETFILTER_XT_MATCH_STATISTIC
104 tristate '"statistic" match support'
105 depends on NETFILTER_ADVANCED
106 diff --git a/net/netfilter/Makefile b/net/netfilter/Makefile
107 index a1abf87..acec24e 100644
108 --- a/net/netfilter/Makefile
109 +++ b/net/netfilter/Makefile
110 @@ -134,6 +134,7 @@ obj-$(CONFIG_NETFILTER_XT_MATCH_RECENT) += xt_recent.o
111 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
112 obj-$(CONFIG_NETFILTER_XT_MATCH_SOCKET) += xt_socket.o
113 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
114 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
115 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
116 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
117 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
118 diff --git a/net/netfilter/nf_conntrack_core.c b/net/netfilter/nf_conntrack_core.c
119 index 0283bae..cae3790 100644
120 --- a/net/netfilter/nf_conntrack_core.c
121 +++ b/net/netfilter/nf_conntrack_core.c
122 @@ -224,6 +224,13 @@ destroy_conntrack(struct nf_conntrack *nfct)
124 nf_ct_remove_expectations(ct);
126 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
127 + if(ct->layer7.app_proto)
128 + kfree(ct->layer7.app_proto);
129 + if(ct->layer7.app_data)
130 + kfree(ct->layer7.app_data);
133 /* We overload first tuple to link into unconfirmed or dying list.*/
134 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
135 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
136 diff --git a/net/netfilter/nf_conntrack_standalone.c b/net/netfilter/nf_conntrack_standalone.c
137 index bd700b4..5d045ca 100644
138 --- a/net/netfilter/nf_conntrack_standalone.c
139 +++ b/net/netfilter/nf_conntrack_standalone.c
140 @@ -240,6 +240,12 @@ static int ct_seq_show(struct seq_file *s, void *v)
141 if (ct_show_delta_time(s, ct))
144 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
145 + if(ct->layer7.app_proto &&
146 + seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
150 if (seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use)))
153 diff --git a/net/netfilter/regexp/regexp.c b/net/netfilter/regexp/regexp.c
155 index 0000000..9006988
157 +++ b/net/netfilter/regexp/regexp.c
160 + * regcomp and regexec -- regsub and regerror are elsewhere
161 + * @(#)regexp.c 1.3 of 18 April 87
163 + * Copyright (c) 1986 by University of Toronto.
164 + * Written by Henry Spencer. Not derived from licensed software.
166 + * Permission is granted to anyone to use this software for any
167 + * purpose on any computer system, and to redistribute it freely,
168 + * subject to the following restrictions:
170 + * 1. The author is not responsible for the consequences of use of
171 + * this software, no matter how awful, even if they arise
172 + * from defects in it.
174 + * 2. The origin of this software must not be misrepresented, either
175 + * by explicit claim or by omission.
177 + * 3. Altered versions must be plainly marked as such, and must not
178 + * be misrepresented as being the original software.
180 + * Beware that some of this code is subtly aware of the way operator
181 + * precedence is structured in regular expressions. Serious changes in
182 + * regular-expression syntax might require a total rethink.
184 + * This code was modified by Ethan Sommer to work within the kernel
185 + * (it now uses kmalloc etc..)
187 + * Modified slightly by Matthew Strait to use more modern C.
191 +#include "regmagic.h"
193 +/* added by ethan and matt. Lets it work in both kernel and user space.
194 +(So iptables can use it, for instance.) Yea, it goes both ways... */
196 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
198 + #define printk(format,args...) printf(format,##args)
201 +void regerror(char * s)
203 + printk("<3>Regexp: %s\n", s);
208 + * The "internal use only" fields in regexp.h are present to pass info from
209 + * compile to execute that permits the execute phase to run lots faster on
210 + * simple cases. They are:
212 + * regstart char that must begin a match; '\0' if none obvious
213 + * reganch is the match anchored (at beginning-of-line only)?
214 + * regmust string (pointer into program) that match must include, or NULL
215 + * regmlen length of regmust string
217 + * Regstart and reganch permit very fast decisions on suitable starting points
218 + * for a match, cutting down the work a lot. Regmust permits fast rejection
219 + * of lines that cannot possibly match. The regmust tests are costly enough
220 + * that regcomp() supplies a regmust only if the r.e. contains something
221 + * potentially expensive (at present, the only such thing detected is * or +
222 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
223 + * supplied because the test in regexec() needs it and regcomp() is computing
228 + * Structure for regexp "program". This is essentially a linear encoding
229 + * of a nondeterministic finite-state machine (aka syntax charts or
230 + * "railroad normal form" in parsing technology). Each node is an opcode
231 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
232 + * all nodes except BRANCH implement concatenation; a "next" pointer with
233 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
234 + * have one of the subtle syntax dependencies: an individual BRANCH (as
235 + * opposed to a collection of them) is never concatenated with anything
236 + * because of operator precedence.) The operand of some types of node is
237 + * a literal string; for others, it is a node leading into a sub-FSM. In
238 + * particular, the operand of a BRANCH node is the first node of the branch.
239 + * (NB this is *not* a tree structure: the tail of the branch connects
240 + * to the thing following the set of BRANCHes.) The opcodes are:
243 +/* definition number opnd? meaning */
244 +#define END 0 /* no End of program. */
245 +#define BOL 1 /* no Match "" at beginning of line. */
246 +#define EOL 2 /* no Match "" at end of line. */
247 +#define ANY 3 /* no Match any one character. */
248 +#define ANYOF 4 /* str Match any character in this string. */
249 +#define ANYBUT 5 /* str Match any character not in this string. */
250 +#define BRANCH 6 /* node Match this alternative, or the next... */
251 +#define BACK 7 /* no Match "", "next" ptr points backward. */
252 +#define EXACTLY 8 /* str Match this string. */
253 +#define NOTHING 9 /* no Match empty string. */
254 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
255 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
256 +#define OPEN 20 /* no Mark this point in input as start of #n. */
257 + /* OPEN+1 is number 1, etc. */
258 +#define CLOSE 30 /* no Analogous to OPEN. */
263 + * BRANCH The set of branches constituting a single choice are hooked
264 + * together with their "next" pointers, since precedence prevents
265 + * anything being concatenated to any individual branch. The
266 + * "next" pointer of the last BRANCH in a choice points to the
267 + * thing following the whole choice. This is also where the
268 + * final "next" pointer of each individual branch points; each
269 + * branch starts with the operand node of a BRANCH node.
271 + * BACK Normal "next" pointers all implicitly point forward; BACK
272 + * exists to make loop structures possible.
274 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
275 + * BRANCH structures using BACK. Simple cases (one character
276 + * per match) are implemented with STAR and PLUS for speed
277 + * and to minimize recursive plunges.
279 + * OPEN,CLOSE ...are numbered at compile time.
283 + * A node is one char of opcode followed by two chars of "next" pointer.
284 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
285 + * value is a positive offset from the opcode of the node containing it.
286 + * An operand, if any, simply follows the node. (Note that much of the
287 + * code generation knows about this implicit relationship.)
289 + * Using two bytes for the "next" pointer is vast overkill for most things,
290 + * but allows patterns to get big without disasters.
292 +#define OP(p) (*(p))
293 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
294 +#define OPERAND(p) ((p) + 3)
297 + * See regmagic.h for one further detail of program structure.
302 + * Utility definitions.
305 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
307 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
310 +#define FAIL(m) { regerror(m); return(NULL); }
311 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
312 +#define META "^$.[()|?+*\\"
315 + * Flags to be passed up and down.
317 +#define HASWIDTH 01 /* Known never to match null string. */
318 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
319 +#define SPSTART 04 /* Starts with * or +. */
320 +#define WORST 0 /* Worst case. */
323 + * Global work variables for regcomp().
325 +struct match_globals {
326 +char *reginput; /* String-input pointer. */
327 +char *regbol; /* Beginning of input, for ^ check. */
328 +char **regstartp; /* Pointer to startp array. */
329 +char **regendp; /* Ditto for endp. */
330 +char *regparse; /* Input-scan pointer. */
331 +int regnpar; /* () count. */
333 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
334 +long regsize; /* Code size. */
338 + * Forward declarations for regcomp()'s friends.
341 +#define STATIC static
343 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
344 +STATIC char *regbranch(struct match_globals *g, int *flagp);
345 +STATIC char *regpiece(struct match_globals *g, int *flagp);
346 +STATIC char *regatom(struct match_globals *g, int *flagp);
347 +STATIC char *regnode(struct match_globals *g, char op);
348 +STATIC char *regnext(struct match_globals *g, char *p);
349 +STATIC void regc(struct match_globals *g, char b);
350 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
351 +STATIC void regtail(struct match_globals *g, char *p, char *val);
352 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
355 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
362 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
363 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
364 + if (*scan1 == *scan2++)
372 + - regcomp - compile a regular expression into internal code
374 + * We can't allocate space until we know how big the compiled form will be,
375 + * but we can't compile it (and thus know how big it is) until we've got a
376 + * place to put the code. So we cheat: we compile it twice, once with code
377 + * generation turned off and size counting turned on, and once "for real".
378 + * This also means that we don't allocate space until we are sure that the
379 + * thing really will compile successfully, and we never have to move the
380 + * code and thus invalidate pointers into it. (Note that it has to be in
381 + * one piece because free() must be able to free it all.)
383 + * Beware that the optimization-preparation code in here knows about some
384 + * of the structure of the compiled regexp.
387 +regcomp(char *exp,int *patternsize)
389 + register regexp *r;
390 + register char *scan;
391 + register char *longest;
394 + struct match_globals g;
396 + /* commented out by ethan
397 + extern char *malloc();
401 + FAIL("NULL argument");
403 + /* First pass: determine size, legality. */
407 + g.regcode = &g.regdummy;
409 + if (reg(&g, 0, &flags) == NULL)
412 + /* Small enough for pointer-storage convention? */
413 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
414 + FAIL("regexp too big");
416 + /* Allocate space. */
417 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
418 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
420 + FAIL("out of space");
422 + /* Second pass: emit code. */
425 + g.regcode = r->program;
427 + if (reg(&g, 0, &flags) == NULL)
430 + /* Dig out information for optimizations. */
431 + r->regstart = '\0'; /* Worst-case defaults. */
435 + scan = r->program+1; /* First BRANCH. */
436 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
437 + scan = OPERAND(scan);
439 + /* Starting-point info. */
440 + if (OP(scan) == EXACTLY)
441 + r->regstart = *OPERAND(scan);
442 + else if (OP(scan) == BOL)
446 + * If there's something expensive in the r.e., find the
447 + * longest literal string that must appear and make it the
448 + * regmust. Resolve ties in favor of later strings, since
449 + * the regstart check works with the beginning of the r.e.
450 + * and avoiding duplication strengthens checking. Not a
451 + * strong reason, but sufficient in the absence of others.
453 + if (flags&SPSTART) {
456 + for (; scan != NULL; scan = regnext(&g, scan))
457 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
458 + longest = OPERAND(scan);
459 + len = strlen(OPERAND(scan));
461 + r->regmust = longest;
470 + - reg - regular expression, i.e. main body or parenthesized thing
472 + * Caller must absorb opening parenthesis.
474 + * Combining parenthesis handling with the base level of regular expression
475 + * is a trifle forced, but the need to tie the tails of the branches to what
476 + * follows makes it hard to avoid.
479 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
481 + register char *ret;
483 + register char *ender;
484 + register int parno = 0; /* 0 makes gcc happy */
487 + *flagp = HASWIDTH; /* Tentatively. */
489 + /* Make an OPEN node, if parenthesized. */
491 + if (g->regnpar >= NSUBEXP)
492 + FAIL("too many ()");
493 + parno = g->regnpar;
495 + ret = regnode(g, OPEN+parno);
499 + /* Pick up the branches, linking them together. */
500 + br = regbranch(g, &flags);
504 + regtail(g, ret, br); /* OPEN -> first. */
507 + if (!(flags&HASWIDTH))
508 + *flagp &= ~HASWIDTH;
509 + *flagp |= flags&SPSTART;
510 + while (*g->regparse == '|') {
512 + br = regbranch(g, &flags);
515 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
516 + if (!(flags&HASWIDTH))
517 + *flagp &= ~HASWIDTH;
518 + *flagp |= flags&SPSTART;
521 + /* Make a closing node, and hook it on the end. */
522 + ender = regnode(g, (paren) ? CLOSE+parno : END);
523 + regtail(g, ret, ender);
525 + /* Hook the tails of the branches to the closing node. */
526 + for (br = ret; br != NULL; br = regnext(g, br))
527 + regoptail(g, br, ender);
529 + /* Check for proper termination. */
530 + if (paren && *g->regparse++ != ')') {
531 + FAIL("unmatched ()");
532 + } else if (!paren && *g->regparse != '\0') {
533 + if (*g->regparse == ')') {
534 + FAIL("unmatched ()");
536 + FAIL("junk on end"); /* "Can't happen". */
544 + - regbranch - one alternative of an | operator
546 + * Implements the concatenation operator.
549 +regbranch(struct match_globals *g, int *flagp)
551 + register char *ret;
552 + register char *chain;
553 + register char *latest;
556 + *flagp = WORST; /* Tentatively. */
558 + ret = regnode(g, BRANCH);
560 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
561 + latest = regpiece(g, &flags);
562 + if (latest == NULL)
564 + *flagp |= flags&HASWIDTH;
565 + if (chain == NULL) /* First piece. */
566 + *flagp |= flags&SPSTART;
568 + regtail(g, chain, latest);
571 + if (chain == NULL) /* Loop ran zero times. */
572 + (void) regnode(g, NOTHING);
578 + - regpiece - something followed by possible [*+?]
580 + * Note that the branching code sequences used for ? and the general cases
581 + * of * and + are somewhat optimized: they use the same NOTHING node as
582 + * both the endmarker for their branch list and the body of the last branch.
583 + * It might seem that this node could be dispensed with entirely, but the
584 + * endmarker role is not redundant.
587 +regpiece(struct match_globals *g, int *flagp)
589 + register char *ret;
591 + register char *next;
594 + ret = regatom(g, &flags);
604 + if (!(flags&HASWIDTH) && op != '?')
605 + FAIL("*+ operand could be empty");
606 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
608 + if (op == '*' && (flags&SIMPLE))
609 + reginsert(g, STAR, ret);
610 + else if (op == '*') {
611 + /* Emit x* as (x&|), where & means "self". */
612 + reginsert(g, BRANCH, ret); /* Either x */
613 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
614 + regoptail(g, ret, ret); /* back */
615 + regtail(g, ret, regnode(g, BRANCH)); /* or */
616 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
617 + } else if (op == '+' && (flags&SIMPLE))
618 + reginsert(g, PLUS, ret);
619 + else if (op == '+') {
620 + /* Emit x+ as x(&|), where & means "self". */
621 + next = regnode(g, BRANCH); /* Either */
622 + regtail(g, ret, next);
623 + regtail(g, regnode(g, BACK), ret); /* loop back */
624 + regtail(g, next, regnode(g, BRANCH)); /* or */
625 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
626 + } else if (op == '?') {
627 + /* Emit x? as (x|) */
628 + reginsert(g, BRANCH, ret); /* Either x */
629 + regtail(g, ret, regnode(g, BRANCH)); /* or */
630 + next = regnode(g, NOTHING); /* null. */
631 + regtail(g, ret, next);
632 + regoptail(g, ret, next);
635 + if (ISMULT(*g->regparse))
636 + FAIL("nested *?+");
642 + - regatom - the lowest level
644 + * Optimization: gobbles an entire sequence of ordinary characters so that
645 + * it can turn them into a single node, which is smaller to store and
646 + * faster to run. Backslashed characters are exceptions, each becoming a
647 + * separate node; the code is simpler that way and it's not worth fixing.
650 +regatom(struct match_globals *g, int *flagp)
652 + register char *ret;
655 + *flagp = WORST; /* Tentatively. */
657 + switch (*g->regparse++) {
659 + ret = regnode(g, BOL);
662 + ret = regnode(g, EOL);
665 + ret = regnode(g, ANY);
666 + *flagp |= HASWIDTH|SIMPLE;
669 + register int class;
670 + register int classend;
672 + if (*g->regparse == '^') { /* Complement of range. */
673 + ret = regnode(g, ANYBUT);
676 + ret = regnode(g, ANYOF);
677 + if (*g->regparse == ']' || *g->regparse == '-')
678 + regc(g, *g->regparse++);
679 + while (*g->regparse != '\0' && *g->regparse != ']') {
680 + if (*g->regparse == '-') {
682 + if (*g->regparse == ']' || *g->regparse == '\0')
685 + class = UCHARAT(g->regparse-2)+1;
686 + classend = UCHARAT(g->regparse);
687 + if (class > classend+1)
688 + FAIL("invalid [] range");
689 + for (; class <= classend; class++)
694 + regc(g, *g->regparse++);
697 + if (*g->regparse != ']')
698 + FAIL("unmatched []");
700 + *flagp |= HASWIDTH|SIMPLE;
704 + ret = reg(g, 1, &flags);
707 + *flagp |= flags&(HASWIDTH|SPSTART);
712 + FAIL("internal urp"); /* Supposed to be caught earlier. */
717 + FAIL("?+* follows nothing");
720 + if (*g->regparse == '\0')
721 + FAIL("trailing \\");
722 + ret = regnode(g, EXACTLY);
723 + regc(g, *g->regparse++);
725 + *flagp |= HASWIDTH|SIMPLE;
729 + register char ender;
732 + len = my_strcspn((const char *)g->regparse, (const char *)META);
734 + FAIL("internal disaster");
735 + ender = *(g->regparse+len);
736 + if (len > 1 && ISMULT(ender))
737 + len--; /* Back off clear of ?+* operand. */
738 + *flagp |= HASWIDTH;
741 + ret = regnode(g, EXACTLY);
743 + regc(g, *g->regparse++);
755 + - regnode - emit a node
757 +static char * /* Location. */
758 +regnode(struct match_globals *g, char op)
760 + register char *ret;
761 + register char *ptr;
764 + if (ret == &g->regdummy) {
771 + *ptr++ = '\0'; /* Null "next" pointer. */
779 + - regc - emit (if appropriate) a byte of code
782 +regc(struct match_globals *g, char b)
784 + if (g->regcode != &g->regdummy)
791 + - reginsert - insert an operator in front of already-emitted operand
793 + * Means relocating the operand.
796 +reginsert(struct match_globals *g, char op, char* opnd)
798 + register char *src;
799 + register char *dst;
800 + register char *place;
802 + if (g->regcode == &g->regdummy) {
813 + place = opnd; /* Op node, where operand used to be. */
820 + - regtail - set the next-pointer at the end of a node chain
823 +regtail(struct match_globals *g, char *p, char *val)
825 + register char *scan;
826 + register char *temp;
827 + register int offset;
829 + if (p == &g->regdummy)
832 + /* Find last node. */
835 + temp = regnext(g, scan);
841 + if (OP(scan) == BACK)
842 + offset = scan - val;
844 + offset = val - scan;
845 + *(scan+1) = (offset>>8)&0377;
846 + *(scan+2) = offset&0377;
850 + - regoptail - regtail on operand of first argument; nop if operandless
853 +regoptail(struct match_globals *g, char *p, char *val)
855 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
856 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
858 + regtail(g, OPERAND(p), val);
862 + * regexec and friends
869 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
870 +STATIC int regmatch(struct match_globals *g, char *prog);
871 +STATIC int regrepeat(struct match_globals *g, char *p);
876 +STATIC char *regprop(char *op);
880 + - regexec - match a regexp against a string
883 +regexec(regexp *prog, char *string)
886 + struct match_globals g;
888 + /* Be paranoid... */
889 + if (prog == NULL || string == NULL) {
890 + printk("<3>Regexp: NULL parameter\n");
894 + /* Check validity of program. */
895 + if (UCHARAT(prog->program) != MAGIC) {
896 + printk("<3>Regexp: corrupted program\n");
900 + /* If there is a "must appear" string, look for it. */
901 + if (prog->regmust != NULL) {
903 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
904 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
905 + break; /* Found it. */
908 + if (s == NULL) /* Not present. */
912 + /* Mark beginning of line for ^ . */
915 + /* Simplest case: anchored match need be tried only once. */
917 + return(regtry(&g, prog, string));
919 + /* Messy cases: unanchored match. */
921 + if (prog->regstart != '\0')
922 + /* We know what char it must start with. */
923 + while ((s = strchr(s, prog->regstart)) != NULL) {
924 + if (regtry(&g, prog, s))
929 + /* We don't -- general case. */
931 + if (regtry(&g, prog, s))
933 + } while (*s++ != '\0');
940 + - regtry - try match at specific point
942 +static int /* 0 failure, 1 success */
943 +regtry(struct match_globals *g, regexp *prog, char *string)
946 + register char **sp;
947 + register char **ep;
949 + g->reginput = string;
950 + g->regstartp = prog->startp;
951 + g->regendp = prog->endp;
955 + for (i = NSUBEXP; i > 0; i--) {
959 + if (regmatch(g, prog->program + 1)) {
960 + prog->startp[0] = string;
961 + prog->endp[0] = g->reginput;
968 + - regmatch - main matching routine
970 + * Conceptually the strategy is simple: check to see whether the current
971 + * node matches, call self recursively to see whether the rest matches,
972 + * and then act accordingly. In practice we make some effort to avoid
973 + * recursion, in particular by going through "ordinary" nodes (that don't
974 + * need to know whether the rest of the match failed) by a loop instead of
977 +static int /* 0 failure, 1 success */
978 +regmatch(struct match_globals *g, char *prog)
980 + register char *scan = prog; /* Current node. */
981 + char *next; /* Next node. */
984 + if (scan != NULL && regnarrate)
985 + fprintf(stderr, "%s(\n", regprop(scan));
987 + while (scan != NULL) {
990 + fprintf(stderr, "%s...\n", regprop(scan));
992 + next = regnext(g, scan);
994 + switch (OP(scan)) {
996 + if (g->reginput != g->regbol)
1000 + if (*g->reginput != '\0')
1004 + if (*g->reginput == '\0')
1010 + register char *opnd;
1012 + opnd = OPERAND(scan);
1013 + /* Inline the first character, for speed. */
1014 + if (*opnd != *g->reginput)
1016 + len = strlen(opnd);
1017 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
1019 + g->reginput += len;
1023 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
1028 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1045 + register char *save;
1047 + no = OP(scan) - OPEN;
1048 + save = g->reginput;
1050 + if (regmatch(g, next)) {
1052 + * Don't set startp if some later
1053 + * invocation of the same parentheses
1056 + if (g->regstartp[no] == NULL)
1057 + g->regstartp[no] = save;
1074 + register char *save;
1076 + no = OP(scan) - CLOSE;
1077 + save = g->reginput;
1079 + if (regmatch(g, next)) {
1081 + * Don't set endp if some later
1082 + * invocation of the same parentheses
1085 + if (g->regendp[no] == NULL)
1086 + g->regendp[no] = save;
1093 + register char *save;
1095 + if (OP(next) != BRANCH) /* No choice. */
1096 + next = OPERAND(scan); /* Avoid recursion. */
1099 + save = g->reginput;
1100 + if (regmatch(g, OPERAND(scan)))
1102 + g->reginput = save;
1103 + scan = regnext(g, scan);
1104 + } while (scan != NULL && OP(scan) == BRANCH);
1112 + register char nextch;
1114 + register char *save;
1118 + * Lookahead to avoid useless match attempts
1119 + * when we know what character comes next.
1122 + if (OP(next) == EXACTLY)
1123 + nextch = *OPERAND(next);
1124 + min = (OP(scan) == STAR) ? 0 : 1;
1125 + save = g->reginput;
1126 + no = regrepeat(g, OPERAND(scan));
1127 + while (no >= min) {
1128 + /* If it could work, try it. */
1129 + if (nextch == '\0' || *g->reginput == nextch)
1130 + if (regmatch(g, next))
1132 + /* Couldn't or didn't -- back up. */
1134 + g->reginput = save + no;
1140 + return(1); /* Success! */
1143 + printk("<3>Regexp: memory corruption\n");
1152 + * We get here only if there's trouble -- normally "case END" is
1153 + * the terminating point.
1155 + printk("<3>Regexp: corrupted pointers\n");
1160 + - regrepeat - repeatedly match something simple, report how many
1163 +regrepeat(struct match_globals *g, char *p)
1165 + register int count = 0;
1166 + register char *scan;
1167 + register char *opnd;
1169 + scan = g->reginput;
1170 + opnd = OPERAND(p);
1173 + count = strlen(scan);
1177 + while (*opnd == *scan) {
1183 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1189 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1194 + default: /* Oh dear. Called inappropriately. */
1195 + printk("<3>Regexp: internal foulup\n");
1196 + count = 0; /* Best compromise. */
1199 + g->reginput = scan;
1205 + - regnext - dig the "next" pointer out of a node
1208 +regnext(struct match_globals *g, char *p)
1210 + register int offset;
1212 + if (p == &g->regdummy)
1219 + if (OP(p) == BACK)
1227 +STATIC char *regprop();
1230 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1236 + register char op = EXACTLY; /* Arbitrary non-END op. */
1237 + register char *next;
1238 + /* extern char *strchr(); */
1241 + s = r->program + 1;
1242 + while (op != END) { /* While that wasn't END last time... */
1244 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1245 + next = regnext(s);
1246 + if (next == NULL) /* Next ptr. */
1249 + printf("(%d)", (s-r->program)+(next-s));
1251 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1252 + /* Literal string, where present. */
1253 + while (*s != '\0') {
1262 + /* Header fields of interest. */
1263 + if (r->regstart != '\0')
1264 + printf("start `%c' ", r->regstart);
1266 + printf("anchored ");
1267 + if (r->regmust != NULL)
1268 + printf("must have \"%s\"", r->regmust);
1273 + - regprop - printable representation of opcode
1280 + static char buf[BUFLEN];
1324 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1336 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1346 + printk("<3>Regexp: corrupted opcode\n");
1350 + strncat(buf, p, BUFLEN-strlen(buf));
1356 diff --git a/net/netfilter/regexp/regexp.h b/net/netfilter/regexp/regexp.h
1357 new file mode 100644
1358 index 0000000..a72eba7
1360 +++ b/net/netfilter/regexp/regexp.h
1363 + * Definitions etc. for regexp(3) routines.
1365 + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
1366 + * not the System V one.
1374 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1375 +which contains a version of this library, says:
1378 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1379 + * will not work properly.
1382 +However, it looks rather like this library is limited to 10. If you think
1383 +otherwise, let us know.
1387 +typedef struct regexp {
1388 + char *startp[NSUBEXP];
1389 + char *endp[NSUBEXP];
1390 + char regstart; /* Internal use only. */
1391 + char reganch; /* Internal use only. */
1392 + char *regmust; /* Internal use only. */
1393 + int regmlen; /* Internal use only. */
1394 + char program[1]; /* Unwarranted chumminess with compiler. */
1397 +regexp * regcomp(char *exp, int *patternsize);
1398 +int regexec(regexp *prog, char *string);
1399 +void regsub(regexp *prog, char *source, char *dest);
1400 +void regerror(char *s);
1403 diff --git a/net/netfilter/regexp/regmagic.h b/net/netfilter/regexp/regmagic.h
1404 new file mode 100644
1405 index 0000000..5acf447
1407 +++ b/net/netfilter/regexp/regmagic.h
1410 + * The first byte of the regexp internal "program" is actually this magic
1411 + * number; the start node begins in the second byte.
1414 diff --git a/net/netfilter/regexp/regsub.c b/net/netfilter/regexp/regsub.c
1415 new file mode 100644
1416 index 0000000..339631f
1418 +++ b/net/netfilter/regexp/regsub.c
1422 + * @(#)regsub.c 1.3 of 2 April 86
1424 + * Copyright (c) 1986 by University of Toronto.
1425 + * Written by Henry Spencer. Not derived from licensed software.
1427 + * Permission is granted to anyone to use this software for any
1428 + * purpose on any computer system, and to redistribute it freely,
1429 + * subject to the following restrictions:
1431 + * 1. The author is not responsible for the consequences of use of
1432 + * this software, no matter how awful, even if they arise
1433 + * from defects in it.
1435 + * 2. The origin of this software must not be misrepresented, either
1436 + * by explicit claim or by omission.
1438 + * 3. Altered versions must be plainly marked as such, and must not
1439 + * be misrepresented as being the original software.
1442 + * This code was modified by Ethan Sommer to work within the kernel
1443 + * (it now uses kmalloc etc..)
1446 +#include "regexp.h"
1447 +#include "regmagic.h"
1448 +#include <linux/string.h>
1452 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1454 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
1458 +//void regerror(char * s)
1460 +// printk("regexp(3): %s", s);
1461 +// /* NOTREACHED */
1466 + - regsub - perform substitutions after a regexp match
1469 +regsub(regexp * prog, char * source, char * dest)
1471 + register char *src;
1472 + register char *dst;
1477 + /* Not necessary and gcc doesn't like it -MLS */
1478 + /*extern char *strncpy();*/
1480 + if (prog == NULL || source == NULL || dest == NULL) {
1481 + regerror("NULL parm to regsub");
1484 + if (UCHARAT(prog->program) != MAGIC) {
1485 + regerror("damaged regexp fed to regsub");
1491 + while ((c = *src++) != '\0') {
1494 + else if (c == '\\' && '0' <= *src && *src <= '9')
1495 + no = *src++ - '0';
1499 + if (no < 0) { /* Ordinary character. */
1500 + if (c == '\\' && (*src == '\\' || *src == '&'))
1503 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
1504 + len = prog->endp[no] - prog->startp[no];
1505 + (void) strncpy(dst, prog->startp[no], len);
1507 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
1508 + regerror("damaged match string");
1515 diff --git a/net/netfilter/xt_layer7.c b/net/netfilter/xt_layer7.c
1516 new file mode 100644
1517 index 0000000..1573e9d
1519 +++ b/net/netfilter/xt_layer7.c
1522 + Kernel module to match application layer (OSI layer 7) data in connections.
1524 + http://l7-filter.sf.net
1526 + (C) 2003-2009 Matthew Strait and Ethan Sommer.
1528 + This program is free software; you can redistribute it and/or
1529 + modify it under the terms of the GNU General Public License
1530 + as published by the Free Software Foundation; either version
1531 + 2 of the License, or (at your option) any later version.
1532 + http://www.gnu.org/licenses/gpl.txt
1534 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
1535 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
1536 + Ethan Sommer, Justin Levandoski.
1539 +#include <linux/spinlock.h>
1540 +#include <linux/version.h>
1541 +#include <net/ip.h>
1542 +#include <net/tcp.h>
1543 +#include <linux/module.h>
1544 +#include <linux/seq_file.h>
1545 +#include <linux/skbuff.h>
1546 +#include <linux/netfilter.h>
1547 +#include <net/netfilter/nf_conntrack.h>
1548 +#include <net/netfilter/nf_conntrack_core.h>
1549 +#include <net/netfilter/nf_conntrack_extend.h>
1550 +#include <net/netfilter/nf_conntrack_acct.h>
1551 +#include <linux/netfilter/x_tables.h>
1552 +#include <linux/netfilter/xt_layer7.h>
1553 +#include <linux/ctype.h>
1554 +#include <linux/proc_fs.h>
1556 +#include "regexp/regexp.c"
1558 +MODULE_LICENSE("GPL");
1559 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
1560 +MODULE_DESCRIPTION("iptables application layer match module");
1561 +MODULE_ALIAS("ipt_layer7");
1562 +MODULE_VERSION("2.21");
1564 +static int maxdatalen = 2048; // this is the default
1565 +module_param(maxdatalen, int, 0444);
1566 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
1567 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
1568 + #define DPRINTK(format,args...) printk(format,##args)
1570 + #define DPRINTK(format,args...)
1573 +/* Number of packets whose data we look at.
1574 +This can be modified through /proc/net/layer7_numpackets */
1575 +static int num_packets = 10;
1577 +static struct pattern_cache {
1578 + char * regex_string;
1580 + struct pattern_cache * next;
1581 +} * first_pattern_cache = NULL;
1583 +DEFINE_SPINLOCK(l7_lock);
1585 +static int total_acct_packets(struct nf_conn *ct)
1587 + struct nf_conn_counter *acct;
1589 + BUG_ON(ct == NULL);
1590 + acct = nf_conn_acct_find(ct);
1593 + return (atomic64_read(&acct[IP_CT_DIR_ORIGINAL].packets) + atomic64_read(&acct[IP_CT_DIR_REPLY].packets));
1596 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1597 +/* Converts an unfriendly string into a friendly one by
1598 +replacing unprintables with periods and all whitespace with " ". */
1599 +static char * friendly_print(unsigned char * s)
1601 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
1605 + if (net_ratelimit())
1606 + printk(KERN_ERR "layer7: out of memory in "
1607 + "friendly_print, bailing.\n");
1611 + for(i = 0; i < strlen(s); i++){
1612 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
1613 + else if(isspace(s[i])) f[i] = ' ';
1620 +static char dec2hex(int i)
1627 + return (i - 10 + 'a');
1630 + if (net_ratelimit())
1631 + printk("layer7: Problem in dec2hex\n");
1636 +static char * hex_print(unsigned char * s)
1638 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
1642 + if (net_ratelimit())
1643 + printk(KERN_ERR "layer7: out of memory in hex_print, "
1648 + for(i = 0; i < strlen(s); i++) {
1649 + g[i*3 ] = dec2hex(s[i]/16);
1650 + g[i*3 + 1] = dec2hex(s[i]%16);
1659 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
1660 +over again, it make sense to cache the results. */
1661 +static regexp * compile_and_cache(const char * regex_string,
1662 + const char * protocol)
1664 + struct pattern_cache * node = first_pattern_cache;
1665 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
1666 + struct pattern_cache * tmp;
1669 + while (node != NULL) {
1670 + if (!strcmp(node->regex_string, regex_string))
1671 + return node->pattern;
1673 + last_pattern_cache = node;/* points at the last non-NULL node */
1674 + node = node->next;
1677 + /* If we reach the end of the list, then we have not yet cached
1678 + the pattern for this regex. Let's do that now.
1679 + Be paranoid about running out of memory to avoid list corruption. */
1680 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
1683 + if (net_ratelimit())
1684 + printk(KERN_ERR "layer7: out of memory in "
1685 + "compile_and_cache, bailing.\n");
1689 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
1690 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
1693 + if(!tmp->regex_string || !tmp->pattern) {
1694 + if (net_ratelimit())
1695 + printk(KERN_ERR "layer7: out of memory in "
1696 + "compile_and_cache, bailing.\n");
1697 + kfree(tmp->regex_string);
1698 + kfree(tmp->pattern);
1703 + /* Ok. The new node is all ready now. */
1706 + if(first_pattern_cache == NULL) /* list is empty */
1707 + first_pattern_cache = node; /* make node the beginning */
1709 + last_pattern_cache->next = node; /* attach node to the end */
1711 + /* copy the string and compile the regex */
1712 + len = strlen(regex_string);
1713 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
1714 + node->pattern = regcomp((char *)regex_string, &len);
1715 + if ( !node->pattern ) {
1716 + if (net_ratelimit())
1717 + printk(KERN_ERR "layer7: Error compiling regexp "
1719 + regex_string, protocol);
1720 + /* pattern is now cached as NULL, so we won't try again. */
1723 + strcpy(node->regex_string, regex_string);
1724 + return node->pattern;
1727 +static int can_handle(const struct sk_buff *skb)
1729 + struct iphdr iphdr_tmp;
1730 + struct iphdr *iphdr;
1736 + offset = ((uintptr_t)ip_hdr(skb)) - ((uintptr_t)skb->data);
1738 + iphdr = skb_header_pointer(skb, offset, sizeof(*iphdr), &iphdr_tmp);
1742 + if (iphdr->protocol == IPPROTO_TCP ||
1743 + iphdr->protocol == IPPROTO_UDP ||
1744 + iphdr->protocol == IPPROTO_ICMP)
1750 +static int app_data_offset(const struct sk_buff *skb)
1753 + struct iphdr iphdr_tmp;
1754 + struct iphdr *iphdr;
1755 + struct tcphdr tcphdr_tmp;
1756 + struct tcphdr *tcphdr;
1761 + offset = ((uintptr_t)ip_hdr(skb)) - ((uintptr_t)skb->data);
1763 + iphdr = skb_header_pointer(skb, offset, sizeof(*iphdr), &iphdr_tmp);
1767 + offset += iphdr->ihl * 4;
1769 + if (iphdr->protocol == IPPROTO_TCP) {
1770 + tcphdr = skb_header_pointer(skb, offset, sizeof(*tcphdr),
1775 + offset += tcphdr->doff * 4;
1780 + if (iphdr->protocol == IPPROTO_UDP)
1781 + return offset + 8;
1783 + if (iphdr->protocol == IPPROTO_ICMP)
1784 + return offset + 8;
1786 + if (net_ratelimit())
1787 + pr_err(KERN_ERR "layer7: tried to handle unknown protocol!\n");
1789 + return offset + 8; /* something reasonable */
1792 +/* handles whether there's a match when we aren't appending data anymore */
1793 +static int match_no_append(struct nf_conn * conntrack,
1794 + struct nf_conn * master_conntrack,
1795 + enum ip_conntrack_info ctinfo,
1796 + enum ip_conntrack_info master_ctinfo,
1797 + const struct xt_layer7_info * info)
1799 + /* If we're in here, throw the app data away */
1800 + if(master_conntrack->layer7.app_data != NULL) {
1802 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1803 + if(!master_conntrack->layer7.app_proto) {
1805 + friendly_print(master_conntrack->layer7.app_data);
1807 + hex_print(master_conntrack->layer7.app_data);
1808 + DPRINTK("\nl7-filter gave up after %d bytes "
1809 + "(%d packets):\n%s\n",
1810 + strlen(f), total_acct_packets(master_conntrack), f);
1812 + DPRINTK("In hex: %s\n", g);
1817 + kfree(master_conntrack->layer7.app_data);
1818 + master_conntrack->layer7.app_data = NULL; /* don't free again */
1821 + if(master_conntrack->layer7.app_proto){
1822 + /* Here child connections set their .app_proto (for /proc) */
1823 + if(!conntrack->layer7.app_proto) {
1824 + conntrack->layer7.app_proto =
1825 + kmalloc(strlen(master_conntrack->layer7.app_proto)+1,
1827 + if(!conntrack->layer7.app_proto){
1828 + if (net_ratelimit())
1829 + printk(KERN_ERR "layer7: out of memory "
1830 + "in match_no_append, "
1834 + strcpy(conntrack->layer7.app_proto,
1835 + master_conntrack->layer7.app_proto);
1838 + return (!strcmp(master_conntrack->layer7.app_proto,
1842 + /* If not classified, set to "unknown" to distinguish from
1843 + connections that are still being tested. */
1844 + master_conntrack->layer7.app_proto =
1845 + kmalloc(strlen("unknown")+1, GFP_ATOMIC);
1846 + if(!master_conntrack->layer7.app_proto){
1847 + if (net_ratelimit())
1848 + printk(KERN_ERR "layer7: out of memory in "
1849 + "match_no_append, bailing.\n");
1852 + strcpy(master_conntrack->layer7.app_proto, "unknown");
1857 +/* add the new app data to the conntrack. Return number of bytes added. */
1858 +static int add_datastr(char *target, int offset, char *app_data, int len)
1860 + int length = 0, i;
1861 + if (!target) return 0;
1863 + /* Strip nulls. Make everything lower case (our regex lib doesn't
1864 + do case insensitivity). Add it to the end of the current data. */
1865 + for(i = 0; i < maxdatalen-offset-1 && i < len; i++) {
1866 + if(app_data[i] != '\0') {
1867 + /* the kernel version of tolower mungs 'upper ascii' */
1868 + target[length+offset] =
1869 + isascii(app_data[i])?
1870 + tolower(app_data[i]) : app_data[i];
1874 + target[length+offset] = '\0';
1879 +/* add the new app data to the buffer. Return number of bytes added. */
1880 +static int add_data(char *target, int offset, const struct sk_buff *skb)
1882 + int length, length_sum = 0;
1883 + int data_start = app_data_offset(skb);
1884 + int remaining = skb->len - data_start;
1889 + while ((offset < maxdatalen - 1) && (remaining > 0)) {
1890 + to_copy = min_t(int, remaining, sizeof(buf));
1892 + data = skb_header_pointer(skb, data_start, to_copy, buf);
1893 + length = add_datastr(target, offset, data, to_copy);
1895 + remaining -= to_copy;
1896 + data_start += to_copy;
1898 + length_sum += length;
1901 + return length_sum;
1904 +/* add the new app data to the conntrack. Return number of bytes added. */
1905 +static int add_data_conntrack(struct nf_conn *master_conntrack,
1906 + const struct sk_buff *skb)
1910 + length = add_data(master_conntrack->layer7.app_data,
1911 + master_conntrack->layer7.app_data_len, skb);
1912 + master_conntrack->layer7.app_data_len += length;
1917 +/* taken from drivers/video/modedb.c */
1918 +static int my_atoi(const char *s)
1925 + val = 10*val+(*s-'0');
1933 +static int layer7_numpackets_proc_show(struct seq_file *s, void *p) {
1934 + seq_printf(s, "%d\n", num_packets);
1939 +static int layer7_numpackets_proc_open(struct inode *inode, struct file *file) {
1940 + return single_open(file, layer7_numpackets_proc_show, NULL);
1943 +/* Read in num_packets from userland */
1944 +static ssize_t layer7_numpackets_write_proc(struct file* file, const char __user *buffer,
1945 + size_t count, loff_t *data) {
1947 + int new_num_packets;
1949 + if (copy_from_user(&value, buffer, sizeof(value)))
1952 + new_num_packets = my_atoi(value);
1954 + if ((new_num_packets < 1) || (new_num_packets > 99)) {
1955 + printk(KERN_WARNING "layer7: numpackets must be between 1 and 99\n");
1959 + num_packets = new_num_packets;
1964 +static bool match(const struct sk_buff *skbin, struct xt_action_param *par)
1966 + /* sidestep const without getting a compiler warning... */
1967 + struct sk_buff *skb = (struct sk_buff *)skbin;
1969 + const struct xt_layer7_info * info = par->matchinfo;
1971 + enum ip_conntrack_info master_ctinfo, ctinfo;
1972 + struct nf_conn *master_conntrack, *conntrack;
1973 + unsigned char *tmp_data;
1974 + unsigned int pattern_result;
1975 + regexp * comppattern;
1977 + /* Be paranoid/incompetent - lock the entire match function. */
1978 + spin_lock_bh(&l7_lock);
1980 + if (!can_handle(skbin)) {
1981 + DPRINTK("layer7: This is some protocol I can't handle.\n");
1982 + spin_unlock_bh(&l7_lock);
1983 + return info->invert;
1986 + /* Treat parent & all its children together as one connection, except
1987 + for the purpose of setting conntrack->layer7.app_proto in the actual
1988 + connection. This makes /proc/net/ip_conntrack more satisfying. */
1989 + conntrack = nf_ct_get(skbin, &ctinfo);
1990 + master_conntrack = nf_ct_get(skbin, &master_ctinfo);
1991 + if (!conntrack || !master_conntrack) {
1992 + DPRINTK("layer7: couldn't get conntrack.\n");
1993 + spin_unlock_bh(&l7_lock);
1994 + return info->invert;
1997 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
1998 + while (master_ct(master_conntrack) != NULL)
1999 + master_conntrack = master_ct(master_conntrack);
2001 + /* if we've classified it or seen too many packets */
2002 + if(!info->pkt && (total_acct_packets(master_conntrack) > num_packets ||
2003 + master_conntrack->layer7.app_proto)) {
2005 + pattern_result = match_no_append(conntrack, master_conntrack,
2006 + ctinfo, master_ctinfo, info);
2008 + /* skb->cb[0] == seen. Don't do things twice if there are
2009 + multiple l7 rules. I'm not sure that using cb for this purpose
2010 + is correct, even though it says "put your private variables
2011 + there". But it doesn't look like it is being used for anything
2012 + else in the skbs that make it here. */
2013 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
2015 + spin_unlock_bh(&l7_lock);
2016 + return (pattern_result ^ info->invert);
2019 + /* the return value gets checked later, when we're ready to use it */
2020 + comppattern = compile_and_cache(info->pattern, info->protocol);
2023 + tmp_data = kmalloc(maxdatalen, GFP_ATOMIC);
2025 + if (net_ratelimit())
2026 + printk(KERN_ERR "layer7: out of memory in match, bailing.\n");
2027 + return info->invert;
2030 + tmp_data[0] = '\0';
2031 + add_data(tmp_data, 0, skbin);
2032 + pattern_result = ((comppattern && regexec(comppattern, tmp_data)) ? 1 : 0);
2036 + spin_unlock_bh(&l7_lock);
2038 + return (pattern_result ^ info->invert);
2041 + /* On the first packet of a connection, allocate space for app data */
2042 + if(total_acct_packets(master_conntrack) == 1 && !skb->cb[0] &&
2043 + !master_conntrack->layer7.app_data){
2044 + master_conntrack->layer7.app_data =
2045 + kmalloc(maxdatalen, GFP_ATOMIC);
2046 + if(!master_conntrack->layer7.app_data){
2047 + if (net_ratelimit())
2048 + printk(KERN_ERR "layer7: out of memory in "
2049 + "match, bailing.\n");
2050 + spin_unlock_bh(&l7_lock);
2051 + return info->invert;
2054 + master_conntrack->layer7.app_data[0] = '\0';
2057 + /* Can be here, but unallocated, if numpackets is increased near
2058 + the beginning of a connection */
2059 + if(master_conntrack->layer7.app_data == NULL){
2060 + spin_unlock_bh(&l7_lock);
2061 + return info->invert; /* unmatched */
2066 + newbytes = add_data_conntrack(master_conntrack, skb);
2068 + if(newbytes == 0) { /* didn't add any data */
2070 + /* Didn't match before, not going to match now */
2071 + spin_unlock_bh(&l7_lock);
2072 + return info->invert;
2076 + /* If looking for "unknown", then never match. "Unknown" means that
2077 + we've given up; we're still trying with these packets. */
2078 + if(!strcmp(info->protocol, "unknown")) {
2079 + pattern_result = 0;
2080 + /* If looking for "unset", then always match. "Unset" means that we
2081 + haven't yet classified the connection. */
2082 + } else if(!strcmp(info->protocol, "unset")) {
2083 + pattern_result = 2;
2084 + DPRINTK("layer7: matched unset: not yet classified "
2085 + "(%d/%d packets)\n",
2086 + total_acct_packets(master_conntrack), num_packets);
2087 + /* If the regexp failed to compile, don't bother running it */
2088 + } else if(comppattern &&
2089 + regexec(comppattern, master_conntrack->layer7.app_data)){
2090 + DPRINTK("layer7: matched %s\n", info->protocol);
2091 + pattern_result = 1;
2092 + } else pattern_result = 0;
2094 + if(pattern_result == 1) {
2095 + master_conntrack->layer7.app_proto =
2096 + kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
2097 + if(!master_conntrack->layer7.app_proto){
2098 + if (net_ratelimit())
2099 + printk(KERN_ERR "layer7: out of memory in "
2100 + "match, bailing.\n");
2101 + spin_unlock_bh(&l7_lock);
2102 + return (pattern_result ^ info->invert);
2104 + strcpy(master_conntrack->layer7.app_proto, info->protocol);
2105 + } else if(pattern_result > 1) { /* cleanup from "unset" */
2106 + pattern_result = 1;
2109 + /* mark the packet seen */
2112 + spin_unlock_bh(&l7_lock);
2113 + return (pattern_result ^ info->invert);
2116 +// load nf_conntrack_ipv4
2117 +static int check(const struct xt_mtchk_param *par)
2119 + if (nf_ct_l3proto_try_module_get(par->match->family) < 0) {
2120 + printk(KERN_WARNING "can't load conntrack support for "
2121 + "proto=%d\n", par->match->family);
2128 +static void destroy(const struct xt_mtdtor_param *par)
2130 + nf_ct_l3proto_module_put(par->match->family);
2133 +static struct xt_match xt_layer7_match[] __read_mostly = {
2136 + .family = AF_INET,
2137 + .checkentry = check,
2139 + .destroy = destroy,
2140 + .matchsize = sizeof(struct xt_layer7_info),
2145 +static const struct file_operations layer7_numpackets_proc_fops = {
2146 + .owner = THIS_MODULE,
2147 + .open = layer7_numpackets_proc_open,
2149 + .llseek = seq_lseek,
2150 + .release = single_release,
2151 + .write = layer7_numpackets_write_proc,
2154 +static int __init xt_layer7_init(void)
2158 + // Register proc interface
2159 + proc_create_data("layer7_numpackets", 0644,
2160 + init_net.proc_net, &layer7_numpackets_proc_fops, NULL);
2162 + if(maxdatalen < 1) {
2163 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
2167 + /* This is not a hard limit. It's just here to prevent people from
2168 + bringing their slow machines to a grinding halt. */
2169 + else if(maxdatalen > 65536) {
2170 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
2172 + maxdatalen = 65536;
2174 + return xt_register_matches(xt_layer7_match,
2175 + ARRAY_SIZE(xt_layer7_match));
2178 +static void __exit xt_layer7_fini(void)
2180 + remove_proc_entry("layer7_numpackets", init_net.proc_net);
2181 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
2184 +module_init(xt_layer7_init);
2185 +module_exit(xt_layer7_fini);