1 diff -urNp -x '*.orig' linux-4.14/include/linux/netfilter/xt_layer7.h linux-4.14/include/linux/netfilter/xt_layer7.h
2 --- linux-4.14/include/linux/netfilter/xt_layer7.h 1970-01-01 01:00:00.000000000 +0100
3 +++ linux-4.14/include/linux/netfilter/xt_layer7.h 2021-02-24 21:41:13.704927445 +0100
8 +#define MAX_PATTERN_LEN 8192
9 +#define MAX_PROTOCOL_LEN 256
11 +struct xt_layer7_info {
12 + char protocol[MAX_PROTOCOL_LEN];
13 + char pattern[MAX_PATTERN_LEN];
17 +#endif /* _XT_LAYER7_H */
18 diff -urNp -x '*.orig' linux-4.14/include/net/netfilter/nf_conntrack.h linux-4.14/include/net/netfilter/nf_conntrack.h
19 --- linux-4.14/include/net/netfilter/nf_conntrack.h 2021-02-24 21:41:05.891673154 +0100
20 +++ linux-4.14/include/net/netfilter/nf_conntrack.h 2021-02-24 21:41:13.704927445 +0100
21 @@ -96,6 +96,22 @@ struct nf_conn {
23 struct nf_ct_ext *ext;
25 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
26 + defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
29 + * e.g. "http". NULL before decision. "unknown" after decision
34 + * application layer data so far. NULL after match decision.
37 + unsigned int app_data_len;
41 /* Storage reserved for other modules, must be the last member */
42 union nf_conntrack_proto proto;
44 diff -urNp -x '*.orig' linux-4.14/net/netfilter/Kconfig linux-4.14/net/netfilter/Kconfig
45 --- linux-4.14/net/netfilter/Kconfig 2017-11-12 19:46:13.000000000 +0100
46 +++ linux-4.14/net/netfilter/Kconfig 2021-02-24 21:41:13.704927445 +0100
47 @@ -1478,6 +1478,27 @@ config NETFILTER_XT_MATCH_STATE
49 To compile it as a module, choose M here. If unsure, say N.
51 +config NETFILTER_XT_MATCH_LAYER7
52 + tristate '"layer7" match support'
53 + depends on NETFILTER_XTABLES
54 + depends on EXPERIMENTAL && (IP_NF_CONNTRACK || NF_CONNTRACK)
56 + Say Y if you want to be able to classify connections (and their
57 + packets) based on regular expression matching of their application
58 + layer data. This is one way to classify applications such as
59 + peer-to-peer filesharing systems that do not always use the same
62 + To compile it as a module, choose M here. If unsure, say N.
65 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
66 + bool 'Layer 7 debugging output'
67 + depends on NETFILTER_XT_MATCH_LAYER7
69 + Say Y to get lots of debugging output.
72 config NETFILTER_XT_MATCH_STATISTIC
73 tristate '"statistic" match support'
74 depends on NETFILTER_ADVANCED
75 diff -urNp -x '*.orig' linux-4.14/net/netfilter/Makefile linux-4.14/net/netfilter/Makefile
76 --- linux-4.14/net/netfilter/Makefile 2017-11-12 19:46:13.000000000 +0100
77 +++ linux-4.14/net/netfilter/Makefile 2021-02-24 21:41:13.704927445 +0100
78 @@ -180,6 +180,7 @@ obj-$(CONFIG_NETFILTER_XT_MATCH_RECENT)
79 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
80 obj-$(CONFIG_NETFILTER_XT_MATCH_SOCKET) += xt_socket.o
81 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
82 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
83 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
84 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
85 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
86 diff -urNp -x '*.orig' linux-4.14/net/netfilter/nf_conntrack_core.c linux-4.14/net/netfilter/nf_conntrack_core.c
87 --- linux-4.14/net/netfilter/nf_conntrack_core.c 2021-02-24 21:41:06.045004859 +0100
88 +++ linux-4.14/net/netfilter/nf_conntrack_core.c 2021-02-24 21:41:13.704927445 +0100
89 @@ -381,6 +381,14 @@ static void nf_ct_del_from_dying_or_unco
93 + #if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
94 + if(ct->layer7.app_proto)
95 + kfree(ct->layer7.app_proto);
96 + if(ct->layer7.app_data)
97 + kfree(ct->layer7.app_data);
101 /* We overload first tuple to link into unconfirmed or dying list.*/
102 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
104 diff -urNp -x '*.orig' linux-4.14/net/netfilter/nf_conntrack_standalone.c linux-4.14/net/netfilter/nf_conntrack_standalone.c
105 --- linux-4.14/net/netfilter/nf_conntrack_standalone.c 2021-02-24 21:41:06.048338158 +0100
106 +++ linux-4.14/net/netfilter/nf_conntrack_standalone.c 2021-02-24 21:41:13.704927445 +0100
107 @@ -353,6 +353,12 @@ static int ct_seq_show(struct seq_file *
108 ct_show_zone(s, ct, NF_CT_DEFAULT_ZONE_DIR);
109 ct_show_delta_time(s, ct);
111 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
112 + if(ct->layer7.app_proto &&
113 + seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
117 seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use));
119 if (seq_has_overflowed(s))
120 diff -urNp -x '*.orig' linux-4.14/net/netfilter/regexp/regexp.c linux-4.14/net/netfilter/regexp/regexp.c
121 --- linux-4.14/net/netfilter/regexp/regexp.c 1970-01-01 01:00:00.000000000 +0100
122 +++ linux-4.14/net/netfilter/regexp/regexp.c 2021-02-24 21:41:13.704927445 +0100
125 + * regcomp and regexec -- regsub and regerror are elsewhere
126 + * @(#)regexp.c 1.3 of 18 April 87
128 + * Copyright (c) 1986 by University of Toronto.
129 + * Written by Henry Spencer. Not derived from licensed software.
131 + * Permission is granted to anyone to use this software for any
132 + * purpose on any computer system, and to redistribute it freely,
133 + * subject to the following restrictions:
135 + * 1. The author is not responsible for the consequences of use of
136 + * this software, no matter how awful, even if they arise
137 + * from defects in it.
139 + * 2. The origin of this software must not be misrepresented, either
140 + * by explicit claim or by omission.
142 + * 3. Altered versions must be plainly marked as such, and must not
143 + * be misrepresented as being the original software.
145 + * Beware that some of this code is subtly aware of the way operator
146 + * precedence is structured in regular expressions. Serious changes in
147 + * regular-expression syntax might require a total rethink.
149 + * This code was modified by Ethan Sommer to work within the kernel
150 + * (it now uses kmalloc etc..)
152 + * Modified slightly by Matthew Strait to use more modern C.
156 +#include "regmagic.h"
158 +/* added by ethan and matt. Lets it work in both kernel and user space.
159 +(So iptables can use it, for instance.) Yea, it goes both ways... */
161 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
163 + #define printk(format,args...) printf(format,##args)
166 +void regerror(char * s)
168 + printk("<3>Regexp: %s\n", s);
173 + * The "internal use only" fields in regexp.h are present to pass info from
174 + * compile to execute that permits the execute phase to run lots faster on
175 + * simple cases. They are:
177 + * regstart char that must begin a match; '\0' if none obvious
178 + * reganch is the match anchored (at beginning-of-line only)?
179 + * regmust string (pointer into program) that match must include, or NULL
180 + * regmlen length of regmust string
182 + * Regstart and reganch permit very fast decisions on suitable starting points
183 + * for a match, cutting down the work a lot. Regmust permits fast rejection
184 + * of lines that cannot possibly match. The regmust tests are costly enough
185 + * that regcomp() supplies a regmust only if the r.e. contains something
186 + * potentially expensive (at present, the only such thing detected is * or +
187 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
188 + * supplied because the test in regexec() needs it and regcomp() is computing
193 + * Structure for regexp "program". This is essentially a linear encoding
194 + * of a nondeterministic finite-state machine (aka syntax charts or
195 + * "railroad normal form" in parsing technology). Each node is an opcode
196 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
197 + * all nodes except BRANCH implement concatenation; a "next" pointer with
198 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
199 + * have one of the subtle syntax dependencies: an individual BRANCH (as
200 + * opposed to a collection of them) is never concatenated with anything
201 + * because of operator precedence.) The operand of some types of node is
202 + * a literal string; for others, it is a node leading into a sub-FSM. In
203 + * particular, the operand of a BRANCH node is the first node of the branch.
204 + * (NB this is *not* a tree structure: the tail of the branch connects
205 + * to the thing following the set of BRANCHes.) The opcodes are:
208 +/* definition number opnd? meaning */
209 +#define END 0 /* no End of program. */
210 +#define BOL 1 /* no Match "" at beginning of line. */
211 +#define EOL 2 /* no Match "" at end of line. */
212 +#define ANY 3 /* no Match any one character. */
213 +#define ANYOF 4 /* str Match any character in this string. */
214 +#define ANYBUT 5 /* str Match any character not in this string. */
215 +#define BRANCH 6 /* node Match this alternative, or the next... */
216 +#define BACK 7 /* no Match "", "next" ptr points backward. */
217 +#define EXACTLY 8 /* str Match this string. */
218 +#define NOTHING 9 /* no Match empty string. */
219 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
220 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
221 +#define OPEN 20 /* no Mark this point in input as start of #n. */
222 + /* OPEN+1 is number 1, etc. */
223 +#define CLOSE 30 /* no Analogous to OPEN. */
228 + * BRANCH The set of branches constituting a single choice are hooked
229 + * together with their "next" pointers, since precedence prevents
230 + * anything being concatenated to any individual branch. The
231 + * "next" pointer of the last BRANCH in a choice points to the
232 + * thing following the whole choice. This is also where the
233 + * final "next" pointer of each individual branch points; each
234 + * branch starts with the operand node of a BRANCH node.
236 + * BACK Normal "next" pointers all implicitly point forward; BACK
237 + * exists to make loop structures possible.
239 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
240 + * BRANCH structures using BACK. Simple cases (one character
241 + * per match) are implemented with STAR and PLUS for speed
242 + * and to minimize recursive plunges.
244 + * OPEN,CLOSE ...are numbered at compile time.
248 + * A node is one char of opcode followed by two chars of "next" pointer.
249 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
250 + * value is a positive offset from the opcode of the node containing it.
251 + * An operand, if any, simply follows the node. (Note that much of the
252 + * code generation knows about this implicit relationship.)
254 + * Using two bytes for the "next" pointer is vast overkill for most things,
255 + * but allows patterns to get big without disasters.
257 +#define OP(p) (*(p))
258 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
259 +#define OPERAND(p) ((p) + 3)
262 + * See regmagic.h for one further detail of program structure.
267 + * Utility definitions.
270 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
272 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
275 +#define FAIL(m) { regerror(m); return(NULL); }
276 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
277 +#define META "^$.[()|?+*\\"
280 + * Flags to be passed up and down.
282 +#define HASWIDTH 01 /* Known never to match null string. */
283 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
284 +#define SPSTART 04 /* Starts with * or +. */
285 +#define WORST 0 /* Worst case. */
288 + * Global work variables for regcomp().
290 +struct match_globals {
291 +char *reginput; /* String-input pointer. */
292 +char *regbol; /* Beginning of input, for ^ check. */
293 +char **regstartp; /* Pointer to startp array. */
294 +char **regendp; /* Ditto for endp. */
295 +char *regparse; /* Input-scan pointer. */
296 +int regnpar; /* () count. */
298 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
299 +long regsize; /* Code size. */
303 + * Forward declarations for regcomp()'s friends.
306 +#define STATIC static
308 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
309 +STATIC char *regbranch(struct match_globals *g, int *flagp);
310 +STATIC char *regpiece(struct match_globals *g, int *flagp);
311 +STATIC char *regatom(struct match_globals *g, int *flagp);
312 +STATIC char *regnode(struct match_globals *g, char op);
313 +STATIC char *regnext(struct match_globals *g, char *p);
314 +STATIC void regc(struct match_globals *g, char b);
315 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
316 +STATIC void regtail(struct match_globals *g, char *p, char *val);
317 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
320 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
327 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
328 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
329 + if (*scan1 == *scan2++)
337 + - regcomp - compile a regular expression into internal code
339 + * We can't allocate space until we know how big the compiled form will be,
340 + * but we can't compile it (and thus know how big it is) until we've got a
341 + * place to put the code. So we cheat: we compile it twice, once with code
342 + * generation turned off and size counting turned on, and once "for real".
343 + * This also means that we don't allocate space until we are sure that the
344 + * thing really will compile successfully, and we never have to move the
345 + * code and thus invalidate pointers into it. (Note that it has to be in
346 + * one piece because free() must be able to free it all.)
348 + * Beware that the optimization-preparation code in here knows about some
349 + * of the structure of the compiled regexp.
352 +regcomp(char *exp,int *patternsize)
354 + register regexp *r;
355 + register char *scan;
356 + register char *longest;
359 + struct match_globals g;
361 + /* commented out by ethan
362 + extern char *malloc();
366 + FAIL("NULL argument");
368 + /* First pass: determine size, legality. */
372 + g.regcode = &g.regdummy;
374 + if (reg(&g, 0, &flags) == NULL)
377 + /* Small enough for pointer-storage convention? */
378 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
379 + FAIL("regexp too big");
381 + /* Allocate space. */
382 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
383 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
385 + FAIL("out of space");
387 + /* Second pass: emit code. */
390 + g.regcode = r->program;
392 + if (reg(&g, 0, &flags) == NULL)
395 + /* Dig out information for optimizations. */
396 + r->regstart = '\0'; /* Worst-case defaults. */
400 + scan = r->program+1; /* First BRANCH. */
401 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
402 + scan = OPERAND(scan);
404 + /* Starting-point info. */
405 + if (OP(scan) == EXACTLY)
406 + r->regstart = *OPERAND(scan);
407 + else if (OP(scan) == BOL)
411 + * If there's something expensive in the r.e., find the
412 + * longest literal string that must appear and make it the
413 + * regmust. Resolve ties in favor of later strings, since
414 + * the regstart check works with the beginning of the r.e.
415 + * and avoiding duplication strengthens checking. Not a
416 + * strong reason, but sufficient in the absence of others.
418 + if (flags&SPSTART) {
421 + for (; scan != NULL; scan = regnext(&g, scan))
422 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
423 + longest = OPERAND(scan);
424 + len = strlen(OPERAND(scan));
426 + r->regmust = longest;
435 + - reg - regular expression, i.e. main body or parenthesized thing
437 + * Caller must absorb opening parenthesis.
439 + * Combining parenthesis handling with the base level of regular expression
440 + * is a trifle forced, but the need to tie the tails of the branches to what
441 + * follows makes it hard to avoid.
444 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
446 + register char *ret;
448 + register char *ender;
449 + register int parno = 0; /* 0 makes gcc happy */
452 + *flagp = HASWIDTH; /* Tentatively. */
454 + /* Make an OPEN node, if parenthesized. */
456 + if (g->regnpar >= NSUBEXP)
457 + FAIL("too many ()");
458 + parno = g->regnpar;
460 + ret = regnode(g, OPEN+parno);
464 + /* Pick up the branches, linking them together. */
465 + br = regbranch(g, &flags);
469 + regtail(g, ret, br); /* OPEN -> first. */
472 + if (!(flags&HASWIDTH))
473 + *flagp &= ~HASWIDTH;
474 + *flagp |= flags&SPSTART;
475 + while (*g->regparse == '|') {
477 + br = regbranch(g, &flags);
480 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
481 + if (!(flags&HASWIDTH))
482 + *flagp &= ~HASWIDTH;
483 + *flagp |= flags&SPSTART;
486 + /* Make a closing node, and hook it on the end. */
487 + ender = regnode(g, (paren) ? CLOSE+parno : END);
488 + regtail(g, ret, ender);
490 + /* Hook the tails of the branches to the closing node. */
491 + for (br = ret; br != NULL; br = regnext(g, br))
492 + regoptail(g, br, ender);
494 + /* Check for proper termination. */
495 + if (paren && *g->regparse++ != ')') {
496 + FAIL("unmatched ()");
497 + } else if (!paren && *g->regparse != '\0') {
498 + if (*g->regparse == ')') {
499 + FAIL("unmatched ()");
501 + FAIL("junk on end"); /* "Can't happen". */
509 + - regbranch - one alternative of an | operator
511 + * Implements the concatenation operator.
514 +regbranch(struct match_globals *g, int *flagp)
516 + register char *ret;
517 + register char *chain;
518 + register char *latest;
521 + *flagp = WORST; /* Tentatively. */
523 + ret = regnode(g, BRANCH);
525 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
526 + latest = regpiece(g, &flags);
527 + if (latest == NULL)
529 + *flagp |= flags&HASWIDTH;
530 + if (chain == NULL) /* First piece. */
531 + *flagp |= flags&SPSTART;
533 + regtail(g, chain, latest);
536 + if (chain == NULL) /* Loop ran zero times. */
537 + (void) regnode(g, NOTHING);
543 + - regpiece - something followed by possible [*+?]
545 + * Note that the branching code sequences used for ? and the general cases
546 + * of * and + are somewhat optimized: they use the same NOTHING node as
547 + * both the endmarker for their branch list and the body of the last branch.
548 + * It might seem that this node could be dispensed with entirely, but the
549 + * endmarker role is not redundant.
552 +regpiece(struct match_globals *g, int *flagp)
554 + register char *ret;
556 + register char *next;
559 + ret = regatom(g, &flags);
569 + if (!(flags&HASWIDTH) && op != '?')
570 + FAIL("*+ operand could be empty");
571 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
573 + if (op == '*' && (flags&SIMPLE))
574 + reginsert(g, STAR, ret);
575 + else if (op == '*') {
576 + /* Emit x* as (x&|), where & means "self". */
577 + reginsert(g, BRANCH, ret); /* Either x */
578 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
579 + regoptail(g, ret, ret); /* back */
580 + regtail(g, ret, regnode(g, BRANCH)); /* or */
581 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
582 + } else if (op == '+' && (flags&SIMPLE))
583 + reginsert(g, PLUS, ret);
584 + else if (op == '+') {
585 + /* Emit x+ as x(&|), where & means "self". */
586 + next = regnode(g, BRANCH); /* Either */
587 + regtail(g, ret, next);
588 + regtail(g, regnode(g, BACK), ret); /* loop back */
589 + regtail(g, next, regnode(g, BRANCH)); /* or */
590 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
591 + } else if (op == '?') {
592 + /* Emit x? as (x|) */
593 + reginsert(g, BRANCH, ret); /* Either x */
594 + regtail(g, ret, regnode(g, BRANCH)); /* or */
595 + next = regnode(g, NOTHING); /* null. */
596 + regtail(g, ret, next);
597 + regoptail(g, ret, next);
600 + if (ISMULT(*g->regparse))
601 + FAIL("nested *?+");
607 + - regatom - the lowest level
609 + * Optimization: gobbles an entire sequence of ordinary characters so that
610 + * it can turn them into a single node, which is smaller to store and
611 + * faster to run. Backslashed characters are exceptions, each becoming a
612 + * separate node; the code is simpler that way and it's not worth fixing.
615 +regatom(struct match_globals *g, int *flagp)
617 + register char *ret;
620 + *flagp = WORST; /* Tentatively. */
622 + switch (*g->regparse++) {
624 + ret = regnode(g, BOL);
627 + ret = regnode(g, EOL);
630 + ret = regnode(g, ANY);
631 + *flagp |= HASWIDTH|SIMPLE;
634 + register int class;
635 + register int classend;
637 + if (*g->regparse == '^') { /* Complement of range. */
638 + ret = regnode(g, ANYBUT);
641 + ret = regnode(g, ANYOF);
642 + if (*g->regparse == ']' || *g->regparse == '-')
643 + regc(g, *g->regparse++);
644 + while (*g->regparse != '\0' && *g->regparse != ']') {
645 + if (*g->regparse == '-') {
647 + if (*g->regparse == ']' || *g->regparse == '\0')
650 + class = UCHARAT(g->regparse-2)+1;
651 + classend = UCHARAT(g->regparse);
652 + if (class > classend+1)
653 + FAIL("invalid [] range");
654 + for (; class <= classend; class++)
659 + regc(g, *g->regparse++);
662 + if (*g->regparse != ']')
663 + FAIL("unmatched []");
665 + *flagp |= HASWIDTH|SIMPLE;
669 + ret = reg(g, 1, &flags);
672 + *flagp |= flags&(HASWIDTH|SPSTART);
677 + FAIL("internal urp"); /* Supposed to be caught earlier. */
682 + FAIL("?+* follows nothing");
685 + if (*g->regparse == '\0')
686 + FAIL("trailing \\");
687 + ret = regnode(g, EXACTLY);
688 + regc(g, *g->regparse++);
690 + *flagp |= HASWIDTH|SIMPLE;
694 + register char ender;
697 + len = my_strcspn((const char *)g->regparse, (const char *)META);
699 + FAIL("internal disaster");
700 + ender = *(g->regparse+len);
701 + if (len > 1 && ISMULT(ender))
702 + len--; /* Back off clear of ?+* operand. */
703 + *flagp |= HASWIDTH;
706 + ret = regnode(g, EXACTLY);
708 + regc(g, *g->regparse++);
720 + - regnode - emit a node
722 +static char * /* Location. */
723 +regnode(struct match_globals *g, char op)
725 + register char *ret;
726 + register char *ptr;
729 + if (ret == &g->regdummy) {
736 + *ptr++ = '\0'; /* Null "next" pointer. */
744 + - regc - emit (if appropriate) a byte of code
747 +regc(struct match_globals *g, char b)
749 + if (g->regcode != &g->regdummy)
756 + - reginsert - insert an operator in front of already-emitted operand
758 + * Means relocating the operand.
761 +reginsert(struct match_globals *g, char op, char* opnd)
763 + register char *src;
764 + register char *dst;
765 + register char *place;
767 + if (g->regcode == &g->regdummy) {
778 + place = opnd; /* Op node, where operand used to be. */
785 + - regtail - set the next-pointer at the end of a node chain
788 +regtail(struct match_globals *g, char *p, char *val)
790 + register char *scan;
791 + register char *temp;
792 + register int offset;
794 + if (p == &g->regdummy)
797 + /* Find last node. */
800 + temp = regnext(g, scan);
806 + if (OP(scan) == BACK)
807 + offset = scan - val;
809 + offset = val - scan;
810 + *(scan+1) = (offset>>8)&0377;
811 + *(scan+2) = offset&0377;
815 + - regoptail - regtail on operand of first argument; nop if operandless
818 +regoptail(struct match_globals *g, char *p, char *val)
820 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
821 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
823 + regtail(g, OPERAND(p), val);
827 + * regexec and friends
834 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
835 +STATIC int regmatch(struct match_globals *g, char *prog);
836 +STATIC int regrepeat(struct match_globals *g, char *p);
841 +STATIC char *regprop(char *op);
845 + - regexec - match a regexp against a string
848 +regexec(regexp *prog, char *string)
851 + struct match_globals g;
853 + /* Be paranoid... */
854 + if (prog == NULL || string == NULL) {
855 + printk("<3>Regexp: NULL parameter\n");
859 + /* Check validity of program. */
860 + if (UCHARAT(prog->program) != MAGIC) {
861 + printk("<3>Regexp: corrupted program\n");
865 + /* If there is a "must appear" string, look for it. */
866 + if (prog->regmust != NULL) {
868 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
869 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
870 + break; /* Found it. */
873 + if (s == NULL) /* Not present. */
877 + /* Mark beginning of line for ^ . */
880 + /* Simplest case: anchored match need be tried only once. */
882 + return(regtry(&g, prog, string));
884 + /* Messy cases: unanchored match. */
886 + if (prog->regstart != '\0')
887 + /* We know what char it must start with. */
888 + while ((s = strchr(s, prog->regstart)) != NULL) {
889 + if (regtry(&g, prog, s))
894 + /* We don't -- general case. */
896 + if (regtry(&g, prog, s))
898 + } while (*s++ != '\0');
905 + - regtry - try match at specific point
907 +static int /* 0 failure, 1 success */
908 +regtry(struct match_globals *g, regexp *prog, char *string)
911 + register char **sp;
912 + register char **ep;
914 + g->reginput = string;
915 + g->regstartp = prog->startp;
916 + g->regendp = prog->endp;
920 + for (i = NSUBEXP; i > 0; i--) {
924 + if (regmatch(g, prog->program + 1)) {
925 + prog->startp[0] = string;
926 + prog->endp[0] = g->reginput;
933 + - regmatch - main matching routine
935 + * Conceptually the strategy is simple: check to see whether the current
936 + * node matches, call self recursively to see whether the rest matches,
937 + * and then act accordingly. In practice we make some effort to avoid
938 + * recursion, in particular by going through "ordinary" nodes (that don't
939 + * need to know whether the rest of the match failed) by a loop instead of
942 +static int /* 0 failure, 1 success */
943 +regmatch(struct match_globals *g, char *prog)
945 + register char *scan = prog; /* Current node. */
946 + char *next; /* Next node. */
949 + if (scan != NULL && regnarrate)
950 + fprintf(stderr, "%s(\n", regprop(scan));
952 + while (scan != NULL) {
955 + fprintf(stderr, "%s...\n", regprop(scan));
957 + next = regnext(g, scan);
959 + switch (OP(scan)) {
961 + if (g->reginput != g->regbol)
965 + if (*g->reginput != '\0')
969 + if (*g->reginput == '\0')
975 + register char *opnd;
977 + opnd = OPERAND(scan);
978 + /* Inline the first character, for speed. */
979 + if (*opnd != *g->reginput)
981 + len = strlen(opnd);
982 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
984 + g->reginput += len;
988 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
993 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1010 + register char *save;
1012 + no = OP(scan) - OPEN;
1013 + save = g->reginput;
1015 + if (regmatch(g, next)) {
1017 + * Don't set startp if some later
1018 + * invocation of the same parentheses
1021 + if (g->regstartp[no] == NULL)
1022 + g->regstartp[no] = save;
1039 + register char *save;
1041 + no = OP(scan) - CLOSE;
1042 + save = g->reginput;
1044 + if (regmatch(g, next)) {
1046 + * Don't set endp if some later
1047 + * invocation of the same parentheses
1050 + if (g->regendp[no] == NULL)
1051 + g->regendp[no] = save;
1058 + register char *save;
1060 + if (OP(next) != BRANCH) /* No choice. */
1061 + next = OPERAND(scan); /* Avoid recursion. */
1064 + save = g->reginput;
1065 + if (regmatch(g, OPERAND(scan)))
1067 + g->reginput = save;
1068 + scan = regnext(g, scan);
1069 + } while (scan != NULL && OP(scan) == BRANCH);
1077 + register char nextch;
1079 + register char *save;
1083 + * Lookahead to avoid useless match attempts
1084 + * when we know what character comes next.
1087 + if (OP(next) == EXACTLY)
1088 + nextch = *OPERAND(next);
1089 + min = (OP(scan) == STAR) ? 0 : 1;
1090 + save = g->reginput;
1091 + no = regrepeat(g, OPERAND(scan));
1092 + while (no >= min) {
1093 + /* If it could work, try it. */
1094 + if (nextch == '\0' || *g->reginput == nextch)
1095 + if (regmatch(g, next))
1097 + /* Couldn't or didn't -- back up. */
1099 + g->reginput = save + no;
1105 + return(1); /* Success! */
1108 + printk("<3>Regexp: memory corruption\n");
1117 + * We get here only if there's trouble -- normally "case END" is
1118 + * the terminating point.
1120 + printk("<3>Regexp: corrupted pointers\n");
1125 + - regrepeat - repeatedly match something simple, report how many
1128 +regrepeat(struct match_globals *g, char *p)
1130 + register int count = 0;
1131 + register char *scan;
1132 + register char *opnd;
1134 + scan = g->reginput;
1135 + opnd = OPERAND(p);
1138 + count = strlen(scan);
1142 + while (*opnd == *scan) {
1148 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1154 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1159 + default: /* Oh dear. Called inappropriately. */
1160 + printk("<3>Regexp: internal foulup\n");
1161 + count = 0; /* Best compromise. */
1164 + g->reginput = scan;
1170 + - regnext - dig the "next" pointer out of a node
1173 +regnext(struct match_globals *g, char *p)
1175 + register int offset;
1177 + if (p == &g->regdummy)
1184 + if (OP(p) == BACK)
1192 +STATIC char *regprop();
1195 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1201 + register char op = EXACTLY; /* Arbitrary non-END op. */
1202 + register char *next;
1203 + /* extern char *strchr(); */
1206 + s = r->program + 1;
1207 + while (op != END) { /* While that wasn't END last time... */
1209 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1210 + next = regnext(s);
1211 + if (next == NULL) /* Next ptr. */
1214 + printf("(%d)", (s-r->program)+(next-s));
1216 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1217 + /* Literal string, where present. */
1218 + while (*s != '\0') {
1227 + /* Header fields of interest. */
1228 + if (r->regstart != '\0')
1229 + printf("start `%c' ", r->regstart);
1231 + printf("anchored ");
1232 + if (r->regmust != NULL)
1233 + printf("must have \"%s\"", r->regmust);
1238 + - regprop - printable representation of opcode
1245 + static char buf[BUFLEN];
1289 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1301 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1311 + printk("<3>Regexp: corrupted opcode\n");
1315 + strncat(buf, p, BUFLEN-strlen(buf));
1321 diff -urNp -x '*.orig' linux-4.14/net/netfilter/regexp/regexp.h linux-4.14/net/netfilter/regexp/regexp.h
1322 --- linux-4.14/net/netfilter/regexp/regexp.h 1970-01-01 01:00:00.000000000 +0100
1323 +++ linux-4.14/net/netfilter/regexp/regexp.h 2021-02-24 21:41:13.704927445 +0100
1326 + * Definitions etc. for regexp(3) routines.
1328 + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
1329 + * not the System V one.
1337 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1338 +which contains a version of this library, says:
1341 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1342 + * will not work properly.
1345 +However, it looks rather like this library is limited to 10. If you think
1346 +otherwise, let us know.
1350 +typedef struct regexp {
1351 + char *startp[NSUBEXP];
1352 + char *endp[NSUBEXP];
1353 + char regstart; /* Internal use only. */
1354 + char reganch; /* Internal use only. */
1355 + char *regmust; /* Internal use only. */
1356 + int regmlen; /* Internal use only. */
1357 + char program[1]; /* Unwarranted chumminess with compiler. */
1360 +regexp * regcomp(char *exp, int *patternsize);
1361 +int regexec(regexp *prog, char *string);
1362 +void regsub(regexp *prog, char *source, char *dest);
1363 +void regerror(char *s);
1366 diff -urNp -x '*.orig' linux-4.14/net/netfilter/regexp/regmagic.h linux-4.14/net/netfilter/regexp/regmagic.h
1367 --- linux-4.14/net/netfilter/regexp/regmagic.h 1970-01-01 01:00:00.000000000 +0100
1368 +++ linux-4.14/net/netfilter/regexp/regmagic.h 2021-02-24 21:41:13.704927445 +0100
1371 + * The first byte of the regexp internal "program" is actually this magic
1372 + * number; the start node begins in the second byte.
1375 diff -urNp -x '*.orig' linux-4.14/net/netfilter/regexp/regsub.c linux-4.14/net/netfilter/regexp/regsub.c
1376 --- linux-4.14/net/netfilter/regexp/regsub.c 1970-01-01 01:00:00.000000000 +0100
1377 +++ linux-4.14/net/netfilter/regexp/regsub.c 2021-02-24 21:41:13.704927445 +0100
1381 + * @(#)regsub.c 1.3 of 2 April 86
1383 + * Copyright (c) 1986 by University of Toronto.
1384 + * Written by Henry Spencer. Not derived from licensed software.
1386 + * Permission is granted to anyone to use this software for any
1387 + * purpose on any computer system, and to redistribute it freely,
1388 + * subject to the following restrictions:
1390 + * 1. The author is not responsible for the consequences of use of
1391 + * this software, no matter how awful, even if they arise
1392 + * from defects in it.
1394 + * 2. The origin of this software must not be misrepresented, either
1395 + * by explicit claim or by omission.
1397 + * 3. Altered versions must be plainly marked as such, and must not
1398 + * be misrepresented as being the original software.
1401 + * This code was modified by Ethan Sommer to work within the kernel
1402 + * (it now uses kmalloc etc..)
1405 +#include "regexp.h"
1406 +#include "regmagic.h"
1407 +#include <linux/string.h>
1411 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1413 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
1417 +//void regerror(char * s)
1419 +// printk("regexp(3): %s", s);
1420 +// /* NOTREACHED */
1425 + - regsub - perform substitutions after a regexp match
1428 +regsub(regexp * prog, char * source, char * dest)
1430 + register char *src;
1431 + register char *dst;
1436 + /* Not necessary and gcc doesn't like it -MLS */
1437 + /*extern char *strncpy();*/
1439 + if (prog == NULL || source == NULL || dest == NULL) {
1440 + regerror("NULL parm to regsub");
1443 + if (UCHARAT(prog->program) != MAGIC) {
1444 + regerror("damaged regexp fed to regsub");
1450 + while ((c = *src++) != '\0') {
1453 + else if (c == '\\' && '0' <= *src && *src <= '9')
1454 + no = *src++ - '0';
1458 + if (no < 0) { /* Ordinary character. */
1459 + if (c == '\\' && (*src == '\\' || *src == '&'))
1462 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
1463 + len = prog->endp[no] - prog->startp[no];
1464 + (void) strncpy(dst, prog->startp[no], len);
1466 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
1467 + regerror("damaged match string");
1474 diff -urNp -x '*.orig' linux-4.14/net/netfilter/xt_layer7.c linux-4.14/net/netfilter/xt_layer7.c
1475 --- linux-4.14/net/netfilter/xt_layer7.c 1970-01-01 01:00:00.000000000 +0100
1476 +++ linux-4.14/net/netfilter/xt_layer7.c 2021-02-24 21:41:13.704927445 +0100
1479 + Kernel module to match application layer (OSI layer 7) data in connections.
1481 + http://l7-filter.sf.net
1483 + (C) 2003-2009 Matthew Strait and Ethan Sommer.
1485 + This program is free software; you can redistribute it and/or
1486 + modify it under the terms of the GNU General Public License
1487 + as published by the Free Software Foundation; either version
1488 + 2 of the License, or (at your option) any later version.
1489 + http://www.gnu.org/licenses/gpl.txt
1491 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
1492 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
1493 + Ethan Sommer, Justin Levandoski.
1496 +#include <linux/spinlock.h>
1497 +#include <linux/version.h>
1498 +#include <net/ip.h>
1499 +#include <net/tcp.h>
1500 +#include <linux/module.h>
1501 +#include <linux/skbuff.h>
1502 +#include <linux/netfilter.h>
1503 +#include <net/netfilter/nf_conntrack.h>
1504 +#include <net/netfilter/nf_conntrack_core.h>
1505 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
1506 +#include <net/netfilter/nf_conntrack_extend.h>
1507 +#include <net/netfilter/nf_conntrack_acct.h>
1509 +#include <linux/netfilter/x_tables.h>
1510 +#include <linux/netfilter/xt_layer7.h>
1511 +#include <linux/ctype.h>
1512 +#include <linux/proc_fs.h>
1514 +#include "regexp/regexp.c"
1516 +MODULE_LICENSE("GPL");
1517 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
1518 +MODULE_DESCRIPTION("iptables application layer match module");
1519 +MODULE_ALIAS("ipt_layer7");
1520 +MODULE_VERSION("2.21");
1522 +static int maxdatalen = 2048; // this is the default
1523 +module_param(maxdatalen, int, 0444);
1524 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
1525 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
1526 + #define DPRINTK(format,args...) printk(format,##args)
1528 + #define DPRINTK(format,args...)
1531 +/* Number of packets whose data we look at.
1532 +This can be modified through /proc/net/layer7_numpackets */
1533 +static int num_packets = 10;
1535 +static struct pattern_cache {
1536 + char * regex_string;
1538 + struct pattern_cache * next;
1539 +} * first_pattern_cache = NULL;
1541 +DEFINE_SPINLOCK(l7_lock);
1543 +static int total_acct_packets(struct nf_conn *ct)
1545 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 26)
1546 + BUG_ON(ct == NULL);
1547 + return (ct->counters[IP_CT_DIR_ORIGINAL].packets + ct->counters[IP_CT_DIR_REPLY].packets);
1549 + struct nf_conn_counter *acct;
1551 + BUG_ON(ct == NULL);
1552 + acct = nf_conn_acct_find(ct);
1555 + return (atomic64_read(&acct[IP_CT_DIR_ORIGINAL].packets) + atomic64_read(&acct[IP_CT_DIR_REPLY].packets));
1559 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1560 +/* Converts an unfriendly string into a friendly one by
1561 +replacing unprintables with periods and all whitespace with " ". */
1562 +static char * friendly_print(unsigned char * s)
1564 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
1568 + if (net_ratelimit())
1569 + printk(KERN_ERR "layer7: out of memory in "
1570 + "friendly_print, bailing.\n");
1574 + for(i = 0; i < strlen(s); i++){
1575 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
1576 + else if(isspace(s[i])) f[i] = ' ';
1583 +static char dec2hex(int i)
1590 + return (i - 10 + 'a');
1593 + if (net_ratelimit())
1594 + printk("layer7: Problem in dec2hex\n");
1599 +static char * hex_print(unsigned char * s)
1601 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
1605 + if (net_ratelimit())
1606 + printk(KERN_ERR "layer7: out of memory in hex_print, "
1611 + for(i = 0; i < strlen(s); i++) {
1612 + g[i*3 ] = dec2hex(s[i]/16);
1613 + g[i*3 + 1] = dec2hex(s[i]%16);
1622 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
1623 +over again, it make sense to cache the results. */
1624 +static regexp * compile_and_cache(const char * regex_string,
1625 + const char * protocol)
1627 + struct pattern_cache * node = first_pattern_cache;
1628 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
1629 + struct pattern_cache * tmp;
1632 + while (node != NULL) {
1633 + if (!strcmp(node->regex_string, regex_string))
1634 + return node->pattern;
1636 + last_pattern_cache = node;/* points at the last non-NULL node */
1637 + node = node->next;
1640 + /* If we reach the end of the list, then we have not yet cached
1641 + the pattern for this regex. Let's do that now.
1642 + Be paranoid about running out of memory to avoid list corruption. */
1643 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
1646 + if (net_ratelimit())
1647 + printk(KERN_ERR "layer7: out of memory in "
1648 + "compile_and_cache, bailing.\n");
1652 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
1653 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
1656 + if(!tmp->regex_string || !tmp->pattern) {
1657 + if (net_ratelimit())
1658 + printk(KERN_ERR "layer7: out of memory in "
1659 + "compile_and_cache, bailing.\n");
1660 + kfree(tmp->regex_string);
1661 + kfree(tmp->pattern);
1666 + /* Ok. The new node is all ready now. */
1669 + if(first_pattern_cache == NULL) /* list is empty */
1670 + first_pattern_cache = node; /* make node the beginning */
1672 + last_pattern_cache->next = node; /* attach node to the end */
1674 + /* copy the string and compile the regex */
1675 + len = strlen(regex_string);
1676 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
1677 + node->pattern = regcomp((char *)regex_string, &len);
1678 + if ( !node->pattern ) {
1679 + if (net_ratelimit())
1680 + printk(KERN_ERR "layer7: Error compiling regexp "
1682 + regex_string, protocol);
1683 + /* pattern is now cached as NULL, so we won't try again. */
1686 + strcpy(node->regex_string, regex_string);
1687 + return node->pattern;
1690 +static int can_handle(const struct sk_buff *skb)
1692 + if(!ip_hdr(skb)) /* not IP */
1694 + if(ip_hdr(skb)->protocol != IPPROTO_TCP &&
1695 + ip_hdr(skb)->protocol != IPPROTO_UDP &&
1696 + ip_hdr(skb)->protocol != IPPROTO_ICMP)
1701 +/* Returns offset the into the skb->data that the application data starts */
1702 +static int app_data_offset(const struct sk_buff *skb)
1704 + /* In case we are ported somewhere (ebtables?) where ip_hdr(skb)
1705 + isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
1706 + int ip_hl = 4*ip_hdr(skb)->ihl;
1708 + if( ip_hdr(skb)->protocol == IPPROTO_TCP ) {
1709 + /* 12 == offset into TCP header for the header length field.
1710 + Can't get this with skb->h.th->doff because the tcphdr
1711 + struct doesn't get set when routing (this is confirmed to be
1712 + true in Netfilter as well as QoS.) */
1713 + int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
1715 + return ip_hl + tcp_hl;
1716 + } else if( ip_hdr(skb)->protocol == IPPROTO_UDP ) {
1717 + return ip_hl + 8; /* UDP header is always 8 bytes */
1718 + } else if( ip_hdr(skb)->protocol == IPPROTO_ICMP ) {
1719 + return ip_hl + 8; /* ICMP header is 8 bytes */
1721 + if (net_ratelimit())
1722 + printk(KERN_ERR "layer7: tried to handle unknown "
1724 + return ip_hl + 8; /* something reasonable */
1728 +/* handles whether there's a match when we aren't appending data anymore */
1729 +static int match_no_append(struct nf_conn * conntrack,
1730 + struct nf_conn * master_conntrack,
1731 + enum ip_conntrack_info ctinfo,
1732 + enum ip_conntrack_info master_ctinfo,
1733 + const struct xt_layer7_info * info)
1735 + /* If we're in here, throw the app data away */
1736 + if(master_conntrack->layer7.app_data != NULL) {
1738 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
1739 + if(!master_conntrack->layer7.app_proto) {
1741 + friendly_print(master_conntrack->layer7.app_data);
1743 + hex_print(master_conntrack->layer7.app_data);
1744 + DPRINTK("\nl7-filter gave up after %d bytes "
1745 + "(%d packets):\n%s\n",
1746 + strlen(f), total_acct_packets(master_conntrack), f);
1748 + DPRINTK("In hex: %s\n", g);
1753 + kfree(master_conntrack->layer7.app_data);
1754 + master_conntrack->layer7.app_data = NULL; /* don't free again */
1757 + if(master_conntrack->layer7.app_proto){
1758 + /* Here child connections set their .app_proto (for /proc) */
1759 + if(!conntrack->layer7.app_proto) {
1760 + conntrack->layer7.app_proto =
1761 + kmalloc(strlen(master_conntrack->layer7.app_proto)+1,
1763 + if(!conntrack->layer7.app_proto){
1764 + if (net_ratelimit())
1765 + printk(KERN_ERR "layer7: out of memory "
1766 + "in match_no_append, "
1770 + strcpy(conntrack->layer7.app_proto,
1771 + master_conntrack->layer7.app_proto);
1774 + return (!strcmp(master_conntrack->layer7.app_proto,
1778 + /* If not classified, set to "unknown" to distinguish from
1779 + connections that are still being tested. */
1780 + master_conntrack->layer7.app_proto =
1781 + kmalloc(strlen("unknown")+1, GFP_ATOMIC);
1782 + if(!master_conntrack->layer7.app_proto){
1783 + if (net_ratelimit())
1784 + printk(KERN_ERR "layer7: out of memory in "
1785 + "match_no_append, bailing.\n");
1788 + strcpy(master_conntrack->layer7.app_proto, "unknown");
1793 +/* add the new app data to the conntrack. Return number of bytes added. */
1794 +static int add_data(struct nf_conn * master_conntrack,
1795 + char * app_data, int appdatalen)
1797 + int length = 0, i;
1798 + int oldlength = master_conntrack->layer7.app_data_len;
1800 + /* This is a fix for a race condition by Deti Fliegl. However, I'm not
1801 + clear on whether the race condition exists or whether this really
1802 + fixes it. I might just be being dense... Anyway, if it's not really
1803 + a fix, all it does is waste a very small amount of time. */
1804 + if(!master_conntrack->layer7.app_data) return 0;
1806 + /* Strip nulls. Make everything lower case (our regex lib doesn't
1807 + do case insensitivity). Add it to the end of the current data. */
1808 + for(i = 0; i < maxdatalen-oldlength-1 &&
1809 + i < appdatalen; i++) {
1810 + if(app_data[i] != '\0') {
1811 + /* the kernel version of tolower mungs 'upper ascii' */
1812 + master_conntrack->layer7.app_data[length+oldlength] =
1813 + isascii(app_data[i])?
1814 + tolower(app_data[i]) : app_data[i];
1819 + master_conntrack->layer7.app_data[length+oldlength] = '\0';
1820 + master_conntrack->layer7.app_data_len = length + oldlength;
1825 +/* taken from drivers/video/modedb.c */
1826 +static int my_atoi(const char *s)
1833 + val = 10*val+(*s-'0');
1841 +/* write out num_packets to userland. */
1842 +static int layer7_read_proc(char* page, char ** start, off_t off, int count,
1843 + int* eof, void * data)
1845 + if(num_packets > 99 && net_ratelimit())
1846 + printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
1848 + page[0] = num_packets/10 + '0';
1849 + page[1] = num_packets%10 + '0';
1858 +/* Read in num_packets from userland */
1859 +static int layer7_write_proc(struct file* file, const char* buffer,
1860 + unsigned long count, void *data)
1862 + char * foo = kmalloc(count, GFP_ATOMIC);
1865 + if (net_ratelimit())
1866 + printk(KERN_ERR "layer7: out of memory, bailing. "
1867 + "num_packets unchanged.\n");
1871 + if(copy_from_user(foo, buffer, count)) {
1876 + num_packets = my_atoi(foo);
1879 + /* This has an arbitrary limit to make the math easier. I'm lazy.
1880 + But anyway, 99 is a LOT! If you want more, you're doing it wrong! */
1881 + if(num_packets > 99) {
1882 + printk(KERN_WARNING "layer7: num_packets can't be > 99.\n");
1884 + } else if(num_packets < 1) {
1885 + printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
1893 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
1894 +match(const struct sk_buff *skbin, struct xt_action_param *par)
1896 +match(const struct sk_buff *skbin,
1897 + const struct net_device *in,
1898 + const struct net_device *out,
1899 + const struct xt_match *match,
1900 + const void *matchinfo,
1902 + unsigned int protoff,
1906 + /* sidestep const without getting a compiler warning... */
1907 + struct sk_buff * skb = (struct sk_buff *)skbin;
1909 + const struct xt_layer7_info * info =
1910 + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
1916 + enum ip_conntrack_info master_ctinfo, ctinfo;
1917 + struct nf_conn *master_conntrack, *conntrack;
1918 + unsigned char * app_data;
1919 + unsigned int pattern_result, appdatalen;
1920 + regexp * comppattern;
1922 + /* Be paranoid/incompetent - lock the entire match function. */
1923 + spin_lock_bh(&l7_lock);
1925 + if(!can_handle(skb)){
1926 + DPRINTK("layer7: This is some protocol I can't handle.\n");
1927 + spin_unlock_bh(&l7_lock);
1928 + return info->invert;
1931 + /* Treat parent & all its children together as one connection, except
1932 + for the purpose of setting conntrack->layer7.app_proto in the actual
1933 + connection. This makes /proc/net/ip_conntrack more satisfying. */
1934 + if(!(conntrack = nf_ct_get(skb, &ctinfo)) ||
1935 + !(master_conntrack=nf_ct_get(skb,&master_ctinfo))){
1936 + DPRINTK("layer7: couldn't get conntrack.\n");
1937 + spin_unlock_bh(&l7_lock);
1938 + return info->invert;
1941 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
1942 + while (master_ct(master_conntrack) != NULL)
1943 + master_conntrack = master_ct(master_conntrack);
1945 + /* if we've classified it or seen too many packets */
1946 + if(total_acct_packets(master_conntrack) > num_packets ||
1947 + master_conntrack->layer7.app_proto) {
1949 + pattern_result = match_no_append(conntrack, master_conntrack,
1950 + ctinfo, master_ctinfo, info);
1952 + /* skb->cb[0] == seen. Don't do things twice if there are
1953 + multiple l7 rules. I'm not sure that using cb for this purpose
1954 + is correct, even though it says "put your private variables
1955 + there". But it doesn't look like it is being used for anything
1956 + else in the skbs that make it here. */
1957 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
1959 + spin_unlock_bh(&l7_lock);
1960 + return (pattern_result ^ info->invert);
1963 + if(skb_is_nonlinear(skb)){
1964 + if(skb_linearize(skb) != 0){
1965 + if (net_ratelimit())
1966 + printk(KERN_ERR "layer7: failed to linearize "
1967 + "packet, bailing.\n");
1968 + spin_unlock_bh(&l7_lock);
1969 + return info->invert;
1973 + /* now that the skb is linearized, it's safe to set these. */
1974 + app_data = skb->data + app_data_offset(skb);
1975 + appdatalen = skb_tail_pointer(skb) - app_data;
1977 + /* the return value gets checked later, when we're ready to use it */
1978 + comppattern = compile_and_cache(info->pattern, info->protocol);
1980 + /* On the first packet of a connection, allocate space for app data */
1981 + if(total_acct_packets(master_conntrack) == 1 && !skb->cb[0] &&
1982 + !master_conntrack->layer7.app_data){
1983 + master_conntrack->layer7.app_data =
1984 + kmalloc(maxdatalen, GFP_ATOMIC);
1985 + if(!master_conntrack->layer7.app_data){
1986 + if (net_ratelimit())
1987 + printk(KERN_ERR "layer7: out of memory in "
1988 + "match, bailing.\n");
1989 + spin_unlock_bh(&l7_lock);
1990 + return info->invert;
1993 + master_conntrack->layer7.app_data[0] = '\0';
1996 + /* Can be here, but unallocated, if numpackets is increased near
1997 + the beginning of a connection */
1998 + if(master_conntrack->layer7.app_data == NULL){
1999 + spin_unlock_bh(&l7_lock);
2000 + return info->invert; /* unmatched */
2005 + newbytes = add_data(master_conntrack, app_data, appdatalen);
2007 + if(newbytes == 0) { /* didn't add any data */
2009 + /* Didn't match before, not going to match now */
2010 + spin_unlock_bh(&l7_lock);
2011 + return info->invert;
2015 + /* If looking for "unknown", then never match. "Unknown" means that
2016 + we've given up; we're still trying with these packets. */
2017 + if(!strcmp(info->protocol, "unknown")) {
2018 + pattern_result = 0;
2019 + /* If looking for "unset", then always match. "Unset" means that we
2020 + haven't yet classified the connection. */
2021 + } else if(!strcmp(info->protocol, "unset")) {
2022 + pattern_result = 2;
2023 + DPRINTK("layer7: matched unset: not yet classified "
2024 + "(%d/%d packets)\n",
2025 + total_acct_packets(master_conntrack), num_packets);
2026 + /* If the regexp failed to compile, don't bother running it */
2027 + } else if(comppattern &&
2028 + regexec(comppattern, master_conntrack->layer7.app_data)){
2029 + DPRINTK("layer7: matched %s\n", info->protocol);
2030 + pattern_result = 1;
2031 + } else pattern_result = 0;
2033 + if(pattern_result == 1) {
2034 + master_conntrack->layer7.app_proto =
2035 + kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
2036 + if(!master_conntrack->layer7.app_proto){
2037 + if (net_ratelimit())
2038 + printk(KERN_ERR "layer7: out of memory in "
2039 + "match, bailing.\n");
2040 + spin_unlock_bh(&l7_lock);
2041 + return (pattern_result ^ info->invert);
2043 + strcpy(master_conntrack->layer7.app_proto, info->protocol);
2044 + } else if(pattern_result > 1) { /* cleanup from "unset" */
2045 + pattern_result = 1;
2048 + /* mark the packet seen */
2051 + spin_unlock_bh(&l7_lock);
2052 + return (pattern_result ^ info->invert);
2055 +// load nf_conntrack_ipv4
2056 +static int check(const struct xt_mtchk_param *par)
2058 + if (nf_ct_l3proto_try_module_get(par->family) < 0) {
2059 + pr_info("can't load conntrack support for "
2060 + "proto=%d\n", par->family);
2067 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
2068 + static void destroy(const struct xt_mtdtor_param *par)
2070 + nf_ct_l3proto_module_put(par->family);
2073 + static void destroy(const struct xt_match *match, void *matchinfo)
2075 + nf_ct_l3proto_module_put(match->family);
2079 +static struct xt_match xt_layer7_match[] __read_mostly = {
2082 + .family = AF_INET,
2083 + .checkentry = check,
2085 + .destroy = destroy,
2086 + .matchsize = sizeof(struct xt_layer7_info),
2091 +static void layer7_cleanup_proc(void)
2093 + remove_proc_entry("layer7_numpackets", init_net.proc_net);
2096 +/* register the proc file */
2097 +static void layer7_init_proc(void)
2099 + struct proc_dir_entry* entry;
2100 + entry = create_proc_entry("layer7_numpackets", 0644, init_net.proc_net);
2101 + entry->read_proc = layer7_read_proc;
2102 + entry->write_proc = layer7_write_proc;
2105 +static int __init xt_layer7_init(void)
2109 + layer7_init_proc();
2110 + if(maxdatalen < 1) {
2111 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
2115 + /* This is not a hard limit. It's just here to prevent people from
2116 + bringing their slow machines to a grinding halt. */
2117 + else if(maxdatalen > 65536) {
2118 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
2120 + maxdatalen = 65536;
2122 + return xt_register_matches(xt_layer7_match,
2123 + ARRAY_SIZE(xt_layer7_match));
2126 +static void __exit xt_layer7_fini(void)
2128 + layer7_cleanup_proc();
2129 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
2132 +module_init(xt_layer7_init);
2133 +module_exit(xt_layer7_fini);