├── .gitignore
├── LICENSE
├── README.md
├── connlabel.conf
├── docs
├── README.md
├── thesis_chapter_l7firewall.pdf
└── workflow.png
├── include
├── conntrack_helper.h
└── ndpi_helper.h
└── src
├── Makefile
├── conntrack_helper.c
├── ndpi_helper.c
├── nfqueue_test.c
└── tests
└── ndpi_helper_tests.c
/.gitignore:
--------------------------------------------------------------------------------
1 | *.swp
2 | RuleManager
3 | NdpiNfqueueFirewall
4 | RuleHelperTests
5 | NdpiHelperTests
6 | rules.db
7 |
8 |
9 | # Object files
10 | src/obj/*.o
11 |
12 | lib/*
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NdpiNfqFirewall
2 | It is a user-space deep packet inspection tool capable of detecting and blocking of 227 application protocols.
3 |
4 | ## Why
5 | So far there is a lack of open-source DPI tools that allow users to block packets coming from specific application.
6 | L7filter is outdated, openappid is slow and works only with Snort, so I created this one.
7 |
8 | ## Before you start
9 | NdpiNfqFirewall was created specificaly for a custom Linux-based OS with a patched core, therefore currently there are limitations when running on distributions with standard Linux core. Read [Limitations](#limitations) for details.
10 |
11 | This program is a PoC, so don't expect too much.
12 |
13 | ## Features
14 | 1. Processing packets from multiple queues (one queue per thread)
15 | 2. Detection of 227 supported protocols (full list can be found on [nDPI web page](http://www.ntop.org/products/deep-packet-inspection/ndpi/)).
16 | 3. Labeling connections for which the protocol detection has ended in Linux's connection tracking subsystem.
17 | 4. Periodic memory cleanup based on time flows have been idle.
18 | 5. Fully configurable parameters from the command line.
19 | 6. Printing packet header information and protocol to screen.
20 |
21 | ## Requirements
22 | - nDPI 2.0 (make sure it's 2.0, NdpiNfqFirewall is incompatible with later versions of nDPI)
23 | - libnetfilter_queue
24 | - libnetfilter_conntrack
25 |
26 | ## Installation
27 | - install libnetfilter_queue and libnetfilter_conntrack (for Ubuntu should be possible with `apt-get install`)
28 | - `git clone https://github.com/robingoth/nfq_ndpi_firewall.git`
29 | - `cd nfq_ndpi_firewall/lib`
30 | - download and compile nDPI like described [here](https://github.com/ntop/nDPI/blob/2.0-stable/INSTALL)
31 | - `cd /path-to-ndpi-nfq-firewall/src/`
32 | - `mkdir obj`
33 | - `make`
34 |
35 | ## Usage
36 | You can start with running `./NdpiNfqueueFirewall --help`.
37 | Normally you should start with copying [connlabel.conf](./connlabel.conf) file from this repository into `/etc/xtables/`.
38 | Then there are two options you have: single-queue and multi-queue.
39 |
40 | ### Single queue
41 | 1. Run `./NdpiNfqueueFirewall`
42 | 2. In another terminal run `iptables -I FORWARD -m connlabel ! --label NDPI_DETECTION_OVER -j NFQUEUE --queue-num 10`. I'm not going to explain how NFQ and CONNTRACK work, but the above command means "enqueue all packets from FORWARD chain that don't have NDPI_DETECTION_OVER label on a connection that they belong to".
43 |
44 | ### Multiple queues (4)
45 | 1. Run `./NdpiNfqueueFirewall -n 4`
46 | 2. In another terminal run `iptables -I FORWARD -m connlabel ! --label NDPI_DETECTION_OVER -j NFQUEUE --queue-balance 10:13`
47 |
48 | ### Manipulating packets
49 | After you have launched the program NdpiNfqFirewall will start labeling connections in connection tracking subsystem of Linux.
50 |
51 | For example, you can run `iptables -I FORWARD -m connlabel --label FACEBOOK -j DROP` in case you want to drop packets coming from facebook web site. You can substitute "FACEBOOK" with any other protocol from your *connlabel.conf* file.
52 |
53 | ## How does it work
54 | 
55 |
56 | You can also read a [chapter of my thesis](./docs/thesis_chapter_l7firewall.pdf) for more details.
57 |
58 | ## Limitations
59 | **CONNTRACK** supports only 128 unique labels, so for now NdpiNfqFirewall can label only 128 first protocols from [nDPI source files](https://github.com/ntop/nDPI/blob/2.0-stable/src/include/ndpi_protocol_ids.h).
60 |
61 | If you want to increase this number you have to patch your Linux core by changing *XT CONNLABEL MAXBIT* value in [include/uapi/linux/netfilter/xt_connlabel.h](https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/xt_connlabel.h) file to a higher one.
62 |
63 | ## Future work/features
64 | - Automated tests.
65 | - Recover NFQ socket connection in case it fails.
66 | - Bind to custom queues. Now queues start from 10 and end with 10+n-1 where *n* is number of queues
67 | - Possibility to choose a subset of protocols to be labeled. Instead of 128 first protocols from ndpi sources user should be able to choose any 128 protocols form the list.
68 |
69 | ## Contact developer
70 | Did you like it? Drop me an email (vlad.cherednychenko@gmail.com) if you started using it, have any questions or it inspired you to write a tool of your own.
71 |
--------------------------------------------------------------------------------
/connlabel.conf:
--------------------------------------------------------------------------------
1 | 0 NDPI_DETECTION_OVER
2 | 1 UNKNOWN
3 | 2 FTP_CONTROL
4 | 3 MAIL_POP
5 | 4 MAIL_SMTP
6 | 5 MAIL_IMAP
7 | 6 DNS
8 | 7 IPP
9 | 8 HTTP
10 | 9 MDNS
11 | 10 NTP
12 | 11 NETBIOS
13 | 12 NFS
14 | 13 SSDP
15 | 14 BGP
16 | 15 SNMP
17 | 16 XDMCP
18 | 17 SMB
19 | 18 SYSLOG
20 | 19 DHCP
21 | 20 POSTGRES
22 | 21 MYSQL
23 | 22 HOTMAIL
24 | 23 DIRECT_DOWNLOAD_LINK
25 | 24 MAIL_POPS
26 | 25 APPLEJUICE
27 | 26 DIRECTCONNECT
28 | 27 SOCRATES
29 | 28 COAP
30 | 29 VMWARE
31 | 30 MAIL_SMTPS
32 | 31 FILETOPIA
33 | 32 UBNTAC2
34 | 33 KONTIKI
35 | 34 OPENFT
36 | 35 FASTTRACK
37 | 36 GNUTELLA
38 | 37 EDONKEY
39 | 38 BITTORRENT
40 | 39 EPP
41 | 40 VI
42 | 41 LASH
43 | 42 GG
44 | 43 PEG
45 | 44 UICKTIME
46 | 45 EALMEDIA
47 | 46 INDOWSMEDIA
48 | 47 MS
49 | 48 XBOX
50 | 49 QQ
51 | 50 MOVE
52 | 51 RTSP
53 | 52 MAIL_IMAPS
54 | 53 ICECAST
55 | 54 PPLIVE
56 | 55 PPSTREAM
57 | 56 ZATTOO
58 | 57 SHOUTCAST
59 | 58 SOPCAST
60 | 59 TVANTS
61 | 60 TVUPLAYER
62 | 61 HTTP_DOWNLOAD
63 | 62 QQLIVE
64 | 63 THUNDER
65 | 64 SOULSEEK
66 | 65 SSL_NO_CERT
67 | 66 IRC
68 | 67 AYIYA
69 | 68 UNENCRYPTED_JABBER
70 | 69 MSN
71 | 70 OSCAR
72 | 71 YAHOO
73 | 72 BATTLEFIELD
74 | 73 QUAKE
75 | 74 IP_VRRP
76 | 75 STEAM
77 | 76 HALFLIFE2
78 | 77 WORLDOFWARCRAFT
79 | 78 TELNET
80 | 79 STUN
81 | 80 IP_IPSEC
82 | 81 IP_GRE
83 | 82 IP_ICMP
84 | 83 IP_IGMP
85 | 84 IP_EGP
86 | 85 IP_SCTP
87 | 86 IP_OSPF
88 | 87 IP_IP_IN_IP
89 | 88 RTP
90 | 89 RDP
91 | 90 VNC
92 | 91 PCANYWHERE
93 | 92 SSL
94 | 93 SSH
95 | 94 USENET
96 | 95 MGCP
97 | 96 IAX
98 | 97 TFTP
99 | 98 AFP
100 | 99 STEALTHNET
101 | 100 AIMINI
102 | 101 SIP
103 | 102 TRUPHONE
104 | 103 IP_ICMPV6
105 | 104 DHCPV6
106 | 105 ARMAGETRON
107 | 106 CROSSFIRE
108 | 107 DOFUS
109 | 108 FIESTA
110 | 109 FLORENSIA
111 | 110 GUILDWARS
112 | 111 HTTP_APPLICATION_ACTIVESYNC
113 | 112 KERBEROS
114 | 113 LDAP
115 | 114 MAPLESTORY
116 | 115 MSSQL_TDS
117 | 116 PPTP
118 | 117 WARCRAFT3
119 | 118 WORLD_OF_KUNG_FU
120 | 119 SLACK
121 | 120 FACEBOOK
122 | 121 TWITTER
123 | 122 DROPBOX
124 | 123 GMAIL
125 | 124 GOOGLE_MAPS
126 | 125 YOUTUBE
127 | 126 SKYPE
128 | 127 GOOGLE
129 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # Docs
2 |
--------------------------------------------------------------------------------
/docs/thesis_chapter_l7firewall.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/robingoth/nfq_ndpi_firewall/cf97c1e9a346263d7bf667b1b15dfb04156d92ca/docs/thesis_chapter_l7firewall.pdf
--------------------------------------------------------------------------------
/docs/workflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/robingoth/nfq_ndpi_firewall/cf97c1e9a346263d7bf667b1b15dfb04156d92ca/docs/workflow.png
--------------------------------------------------------------------------------
/include/conntrack_helper.h:
--------------------------------------------------------------------------------
1 | #ifndef CONNTRACK_HELPER_H_
2 | #define CONNTRACK_HELPER_H_
3 |
4 | int update_label(int src_ip, int dst_ip, unsigned short src_port, unsigned short dst_port, int master_proto_id, int app_proto_id, int proto_type);
5 |
6 | #endif // CONNTRACK_HELPER_H_
7 |
--------------------------------------------------------------------------------
/include/ndpi_helper.h:
--------------------------------------------------------------------------------
1 | #ifndef NDPI_HELPER_H_
2 | #define NDPI_HELPER_H_
3 |
4 | #include
5 |
6 | #define SIZEOF_FLOW_STRUCT (sizeof(struct ndpi_flow_struct))
7 | #define TICK_RESOLUTION 1000
8 |
9 | // Forward Declarations
10 | struct flow_info;
11 |
12 | // STRUCTS
13 | struct ndpi_workflow {
14 | int num_roots;
15 | int max_flows;
16 | int max_idle_flows;
17 | int flow_count;
18 |
19 | // root of the tree
20 | void **ndpi_flows_root;
21 |
22 | struct ndpi_detection_module_struct *ndpi_struct;
23 |
24 | // when the idle flows were last scanned in ms
25 | u_int64_t last_idle_scan;
26 | // timestamp equals to the timestamp of the last packet in ms
27 | u_int64_t timestamp;
28 | // maximum amount of time a flow can be idle
29 | int max_idle_time;
30 |
31 | // these 2 exist because idle flows cannot be deleted inline,
32 | // so they are added into a queue and deleted later
33 | unsigned int num_idle_flows;
34 | struct flow_info **idle_flows;
35 | int idle_scan_idx;
36 | };
37 |
38 | struct flow_info {
39 | struct ndpi_flow_struct *ndpi_flow;
40 |
41 | u_int32_t src_ip;
42 | u_int32_t dst_ip;
43 | u_int16_t src_port;
44 | u_int16_t dst_port;
45 |
46 | u_int32_t hash_value;
47 |
48 | int detection_completed;
49 | int label_set;
50 | int protocol;
51 |
52 | int packets;
53 |
54 | // result only
55 | ndpi_protocol detected_protocol;
56 |
57 | void *src_id;
58 | void *dst_id;
59 |
60 | u_int64_t last_seen;
61 |
62 | struct {
63 | char client_info[48], server_info[48];
64 | } ssh_ssl;
65 | };
66 |
67 | // FUNCTIONS
68 | struct ndpi_detection_module_struct *setup_detection();
69 |
70 | struct ndpi_proto detect_protocol(const unsigned char *packet,
71 | const unsigned short packetlen,
72 | struct timeval timestamp,
73 | struct ndpi_workflow *workflow);
74 |
75 | void free_idle_flows(struct ndpi_workflow *workflow);
76 |
77 | #endif // NDPI_HELPER_H_
78 |
--------------------------------------------------------------------------------
/src/Makefile:
--------------------------------------------------------------------------------
1 | # **********************************************************
2 | # * This file has to stay inside the src folder *
3 | # **********************************************************
4 |
5 | # directories with files
6 | INCDIR = ../include
7 | OBJDIR = obj
8 | LIBSDIR = ../lib
9 | NDPIDIR = $(LIBSDIR)/nDPI
10 | TESTSDIR = ./tests
11 |
12 | PROGRAMNAME = NdpiNfqueueFirewall
13 | NH_TESTS = NdpiHelperTests
14 |
15 | CC=gcc
16 | CFLAGS= -Wall -g -I$(INCDIR) -I$(NDPIDIR)/src/include $(LIBSDIR)/nDPI/lib/libndpi.a
17 | CFLAGS2 = -Wall -g -I$(INCDIR) -L/usr/local/lib
18 |
19 | TESTS_CFLAGS = -g -Wall -I$(INCDIR) -I$(NDPIDIR)/src/include -L/usr/local/lib $(LIBSDIR)/nDPI/lib/libndpi.a
20 | NH_WRAPS = -Wl,--wrap=set_ndpi_malloc,--wrap=set_ndpi_free,--wrap=set_ndpi_flow_malloc,--wrap=set_ndpi_flow_free,--wrap=ndpi_init_detection_module,--wrap=NDPI_BITMASK_SET_ALL,--wrap=ndpi_set_protocol_detection_bitmask2,--wrap=ndpi_detection_process_packet,--wrap=get_flow_info
21 |
22 | LIBS = -lndpi -lnetfilter_queue -lpthread -lnetfilter_conntrack -lnfnetlink
23 | TESTLIBS = -lcmocka
24 |
25 | _DEPS = ndpi_helper.h conntrack_helper.h
26 | # Replace all filenames in dependencies with a relative path
27 | DEPS = $(patsubst %, $(INCDIR)/%, $(_DEPS))
28 |
29 | _OBJS = nfqueue_test.o ndpi_helper.o conntrack_helper.o
30 | _OBJS_NH_TESTS = ndpi_helper_tests.o ndpi_helper.o
31 |
32 | # Replace all filenames in objects with a relative path
33 | OBJS = $(patsubst %, $(OBJDIR)/%, $(_OBJS))
34 | OBJS_NH_TESTS = $(patsubst %, $(OBJDIR)/%, $(_OBJS_NH_TESTS))
35 |
36 | $(OBJDIR)/%.o: %.c $(DEPS)
37 | $(CC) -c -o $@ $< $(CFLAGS)
38 |
39 | $(OBJDIR)/%.o: $(TESTSDIR)/%.c $(DEPS)
40 | $(CC) -c -o $@ $< $(TESTS_CFLAGS)
41 |
42 | all: $(PROGRAMNAME)
43 |
44 | $(PROGRAMNAME): $(OBJS)
45 | $(CC) -o $@ $^ $(CFLAGS) $(LIBS)
46 |
47 | $(NH_TESTS): $(OBJS_NH_TESTS)
48 | $(CC) -o $(TESTSDIR)/$@ $^ $(TESTS_CFLAGS) $(NH_WRAPS) $(TESTLIBS)
49 |
50 | test: $(NH_TESTS)
51 | $(TESTSDIR)/$(NH_TESTS)
52 |
53 | clean:
54 | rm -f $(OBJDIR)/*.o $(PROGRAMNAME) $(TESTSDIR)/$(NH_TESTS)
55 |
--------------------------------------------------------------------------------
/src/conntrack_helper.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include
8 | #include
9 |
10 | int update_label(int src_ip, int dst_ip, unsigned short src_port, unsigned short dst_port,
11 | int master_proto_id, int app_proto_id, int l4_proto)
12 | {
13 | struct nfct_bitmask *bitmask;
14 |
15 | int ret;
16 | struct nfct_handle *h;
17 | struct nf_conntrack *ct;
18 |
19 | ct = nfct_new();
20 | if (!ct) {
21 | perror("nfct_new\n");
22 | return -1;
23 | }
24 |
25 | h = nfct_open(CONNTRACK, 0);
26 | if (!h) {
27 | perror("nfct_open\n");
28 | nfct_destroy(ct);
29 | return -1;
30 | }
31 |
32 | nfct_set_attr_u8(ct, ATTR_L3PROTO, AF_INET);
33 | nfct_set_attr_u32(ct, ATTR_IPV4_SRC, src_ip);
34 | nfct_set_attr_u32(ct, ATTR_IPV4_DST, dst_ip);
35 |
36 | nfct_set_attr_u8(ct, ATTR_L4PROTO, l4_proto);
37 | nfct_set_attr_u16(ct, ATTR_PORT_SRC, src_port);
38 | nfct_set_attr_u16(ct, ATTR_PORT_DST, dst_port);
39 |
40 | bitmask = nfct_bitmask_new(127);
41 | nfct_bitmask_set_bit(bitmask, master_proto_id);
42 | nfct_bitmask_set_bit(bitmask, app_proto_id);
43 | nfct_bitmask_set_bit(bitmask, 0);
44 | nfct_set_attr(ct, ATTR_CONNLABELS, bitmask);
45 |
46 | ret = nfct_query(h, NFCT_Q_UPDATE, ct);
47 |
48 | nfct_close(h);
49 | nfct_destroy(ct);
50 |
51 | return ret;
52 | }
53 |
--------------------------------------------------------------------------------
/src/ndpi_helper.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | #include "ndpi_main.h"
5 | #include "ndpi_helper.h"
6 | #include "conntrack_helper.h"
7 |
8 | // forward declarations
9 | static void free_flow_partially(struct flow_info *flow);
10 |
11 | /*
12 | * Malloc wrapper function.
13 | */
14 | static void *malloc_wrapper(size_t size)
15 | {
16 | return malloc(size);
17 | }
18 |
19 | /*
20 | * Free wrapper function.
21 | */
22 | static void free_wrapper(void *freeable)
23 | {
24 | free(freeable);
25 | }
26 |
27 | /*
28 | * Sets function pointers needed for nDPI and
29 | * creates a nDPI structure.
30 | */
31 | struct ndpi_detection_module_struct *setup_detection()
32 | {
33 | NDPI_PROTOCOL_BITMASK all;
34 |
35 | set_ndpi_malloc(malloc_wrapper), set_ndpi_free(free_wrapper);
36 | set_ndpi_flow_malloc(NULL), set_ndpi_flow_free(NULL);
37 |
38 | struct ndpi_detection_module_struct *ndpi_struct = ndpi_init_detection_module();
39 |
40 | if (ndpi_struct == NULL) {
41 | NDPI_LOG(0, NULL, NDPI_LOG_ERROR, "global structure initialization failed\n");
42 | exit(1);
43 | }
44 |
45 | NDPI_BITMASK_SET_ALL(all);
46 | ndpi_set_protocol_detection_bitmask2(ndpi_struct, &all);
47 |
48 | return ndpi_struct;
49 | }
50 |
51 | /*
52 | * Compare two flows.
53 | * Needed for ndpi_tfind() and ndpi_tsearch().
54 | */
55 | static int ndpi_workflow_node_cmp(const void *a, const void *b) {
56 | struct flow_info *flow_a = (struct flow_info*)a;
57 | struct flow_info *flow_b = (struct flow_info*)b;
58 |
59 | if (flow_a->hash_value < flow_b->hash_value) {
60 | return(-1);
61 | } else if (flow_a->hash_value > flow_b->hash_value) {
62 | return(1);
63 | }
64 |
65 | /* Flows have the same hash */
66 |
67 | if (flow_a->protocol < flow_b->protocol) {
68 | return(-1);
69 | } else if (flow_a->protocol > flow_b->protocol) {
70 | return(1);
71 | }
72 |
73 | // if flows are equal return 0
74 | if(((flow_a->src_ip == flow_b->src_ip) &&
75 | (flow_a->src_port == flow_b->src_port) &&
76 | (flow_a->dst_ip == flow_b->dst_ip) &&
77 | (flow_a->dst_port == flow_b->dst_port)) ||
78 | ((flow_a->src_ip == flow_b->dst_ip) &&
79 | (flow_a->src_port == flow_b->dst_port) &&
80 | (flow_a->dst_ip == flow_b->src_ip) &&
81 | (flow_a->dst_port == flow_b->src_port))) {
82 | return(0);
83 | }
84 |
85 | if ((flow_a->src_ip < flow_b->src_ip) ||
86 | (flow_a->src_port < flow_b->src_port) ||
87 | (flow_a->dst_ip < flow_b->dst_ip) ||
88 | (flow_a->dst_port < flow_b->dst_port)) {
89 | return(-1);
90 | } else if ((flow_a->src_ip > flow_b->src_ip) ||
91 | (flow_a->src_port > flow_b->src_port) ||
92 | (flow_a->dst_ip > flow_b->dst_ip) ||
93 | (flow_a->dst_port > flow_b->dst_port)) {
94 | return(1);
95 | } else {
96 | printf("Something went wrong during flow comparison.\n");
97 | return 0; // should not be reached
98 | }
99 | }
100 |
101 | /*
102 | * Find an existing flow for a packet or create a new one.
103 | * Input arguments:
104 | * workflow - a structure set in main().
105 | * iph - IP header, set in detect_proto()
106 | * ipsize - packet size
107 | * src - nDPI specific structure used for detection
108 | * dst - nDPI specific structure used for detection
109 | * proto - TCP, UDP, etc.
110 | *
111 | * Returns a structure with the flow information
112 | */
113 | static struct flow_info *
114 | get_flow_info(struct ndpi_workflow *workflow, const struct ndpi_iphdr *iph,
115 | u_int16_t ipsize, struct ndpi_id_struct **src,
116 | struct ndpi_id_struct **dst, u_int8_t *proto)
117 | {
118 | struct flow_info flow;
119 | u_int32_t idx, l4_offset, hashval;
120 | int l4_packet_len;
121 | void *search_res;
122 | u_int8_t *l3, *l4;
123 |
124 | struct ndpi_tcphdr *tcph = NULL;
125 | struct ndpi_udphdr *udph = NULL;
126 | u_int16_t sport, dport;
127 |
128 | l4_offset = iph->ihl * 4;
129 | l3 = (u_int8_t*)iph;
130 |
131 | *proto = iph->protocol;
132 | l4 = ((u_int8_t *)l3 + l4_offset);
133 |
134 | l4_packet_len = ntohs(iph->tot_len) - (iph->ihl * 4);
135 |
136 | // determine source and destination port
137 | if (iph->protocol == IPPROTO_TCP && l4_packet_len >= 20) {
138 | tcph = (struct ndpi_tcphdr *)l4;
139 | sport = ntohs(tcph->source);
140 | dport = ntohs(tcph->dest);
141 | } else if (iph->protocol == IPPROTO_UDP && l4_packet_len >= 8) {
142 | udph = (struct ndpi_udphdr *)l4;
143 | sport = ntohs(udph->source);
144 | dport = ntohs(udph->dest);
145 | } else {
146 | // non tcp/udp protocols
147 | sport = dport = 0;
148 | }
149 |
150 | flow.protocol = iph->protocol;
151 | flow.src_ip = iph->saddr;
152 | flow.dst_ip = iph->daddr;
153 | flow.src_port = htons(sport);
154 | flow.dst_port = htons(dport);
155 |
156 | hashval = flow.protocol + flow.src_ip + flow.dst_ip + flow.src_port + flow.dst_port;
157 | flow.hash_value = hashval;
158 |
159 | idx = hashval % workflow->num_roots;
160 |
161 | // search for a flow in the tree
162 | search_res = ndpi_tfind(&flow, &workflow->ndpi_flows_root[idx], ndpi_workflow_node_cmp);
163 |
164 | if (search_res != NULL) {
165 | // flow was found
166 |
167 | struct flow_info *ret = *(struct flow_info**)search_res;
168 | if(ret->src_ip == iph->saddr &&
169 | ret->src_ip == iph->daddr &&
170 | ret->dst_port == htons(sport) &&
171 | ret->dst_port == htons(dport)) {
172 | *src = ret->src_id;
173 | *dst = ret->dst_id;
174 | } else {
175 | *src = ret->dst_id;
176 | *dst = ret->src_id;
177 | }
178 |
179 | return ret;
180 | } else {
181 | // create a new flow
182 |
183 | if (workflow->flow_count > workflow->max_flows) {
184 | printf("ERROR: max number of flows was exceeded.\n");
185 | return NULL;
186 | } else {
187 | struct flow_info *ret = malloc(sizeof(struct flow_info));
188 |
189 | if (ret == NULL) {
190 | printf("ERROR: cannot allocate new flow.\n");
191 | return NULL;
192 | } else {
193 | memset(ret, 0, sizeof(struct flow_info));
194 | }
195 |
196 | ret->protocol = iph->protocol;
197 | ret->src_ip = iph->saddr;
198 | ret->dst_ip = iph->daddr;
199 | ret->src_port = htons(sport);
200 | ret->dst_port = htons(dport);
201 | ret->hash_value = hashval;
202 |
203 |
204 | ret->ndpi_flow = ndpi_flow_malloc(SIZEOF_FLOW_STRUCT);
205 | if (ret->ndpi_flow == NULL) {
206 | printf("ERROR: not enough memory to create a new ndpi flow.\n");
207 | return NULL;
208 | }
209 | memset(ret->ndpi_flow, 0, SIZEOF_FLOW_STRUCT);
210 |
211 | ret->src_id = ndpi_flow_malloc(SIZEOF_ID_STRUCT);
212 | if (ret->src_id == NULL) {
213 | printf("ERROR: not enough memory to create a new src_id.\n");
214 | return NULL;
215 | }
216 | memset(ret->src_id, 0, SIZEOF_ID_STRUCT);
217 |
218 | ret->dst_id = ndpi_flow_malloc(SIZEOF_ID_STRUCT);
219 | if (ret->dst_id == NULL) {
220 | printf("ERROR: not enough memory to create a new dst_id.\n");
221 | return NULL;
222 | }
223 | memset(ret->dst_id, 0, SIZEOF_ID_STRUCT);
224 |
225 | // add new flow to the tree
226 | ndpi_tsearch(ret, &workflow->ndpi_flows_root[idx], ndpi_workflow_node_cmp);
227 | workflow->flow_count++;
228 |
229 | *src = ret->src_id;
230 | *dst = ret->dst_id;
231 |
232 | return ret;
233 | }
234 | }
235 | }
236 |
237 | /*
238 | * Free some information from the flow.
239 | */
240 | static void free_flow_partially(struct flow_info *flow) {
241 | if(flow->ndpi_flow != NULL) {
242 | ndpi_flow_free(flow->ndpi_flow);
243 | flow->ndpi_flow = NULL;
244 | }
245 |
246 | if(flow->src_id) {
247 | ndpi_free(flow->src_id);
248 | flow->src_id = NULL;
249 | }
250 |
251 | if(flow->dst_id) {
252 | ndpi_free(flow->dst_id);
253 | flow->dst_id = NULL;
254 | }
255 | }
256 |
257 | /*
258 | * Set SSH/SSL specific fields of flow
259 | */
260 | static void process_ndpi_collected_info(struct ndpi_workflow * workflow, struct flow_info *flow) {
261 | if (flow->ndpi_flow == NULL) {
262 | printf("ERROR: flow is NULL \n");
263 | exit(1);
264 | }
265 |
266 | if (flow->detected_protocol.app_protocol != NDPI_PROTOCOL_DNS) {
267 | /* SSH */
268 | if (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_SSH) {
269 | snprintf(flow->ssh_ssl.client_info, sizeof(flow->ssh_ssl.client_info), "%s",
270 | flow->ndpi_flow->protos.ssh.client_signature);
271 |
272 | snprintf(flow->ssh_ssl.server_info, sizeof(flow->ssh_ssl.server_info), "%s",
273 | flow->ndpi_flow->protos.ssh.server_signature);
274 | } else if ((flow->detected_protocol.app_protocol == NDPI_PROTOCOL_SSL) ||
275 | (flow->detected_protocol.master_protocol == NDPI_PROTOCOL_SSL)) {
276 | snprintf(flow->ssh_ssl.client_info, sizeof(flow->ssh_ssl.client_info), "%s",
277 | flow->ndpi_flow->protos.ssl.client_certificate);
278 |
279 | snprintf(flow->ssh_ssl.server_info, sizeof(flow->ssh_ssl.server_info), "%s",
280 | flow->ndpi_flow->protos.ssl.server_certificate);
281 | }
282 | }
283 |
284 | if (flow->detection_completed) {
285 | free_flow_partially(flow);
286 | }
287 | }
288 |
289 | /*
290 | * Traverses the tree to determine idle flows
291 | */
292 | static void node_walker(const void *node, ndpi_VISIT which, int depth, void *user_data)
293 | {
294 | struct flow_info *flow = *(struct flow_info **) node;
295 | struct ndpi_workflow *workflow = (struct ndpi_workflow *)user_data;
296 |
297 | if (workflow->num_idle_flows == workflow->max_idle_flows - 1) {
298 | return;
299 | }
300 |
301 | /* Avoid walking the same node multiple times */
302 | if ((which == ndpi_preorder) || (which == ndpi_leaf)) {
303 | if (flow->last_seen + workflow->max_idle_time < workflow->timestamp) {
304 | free_flow_partially(flow);
305 | workflow->flow_count--;
306 |
307 | workflow->idle_flows[workflow->num_idle_flows] = flow;
308 | workflow->num_idle_flows++;
309 | }
310 | }
311 | }
312 |
313 | /*
314 | * Deletes idle flows from memory
315 | */
316 | void free_idle_flows(struct ndpi_workflow *workflow)
317 | {
318 | int i = workflow->idle_scan_idx;
319 | ndpi_twalk(workflow->ndpi_flows_root[i], node_walker, workflow);
320 |
321 | while(workflow->num_idle_flows != 0) {
322 | workflow->num_idle_flows--;
323 |
324 | ndpi_tdelete(workflow->idle_flows[workflow->num_idle_flows],
325 | &workflow->ndpi_flows_root[i],
326 | ndpi_workflow_node_cmp);
327 | }
328 |
329 | workflow->idle_scan_idx++;
330 | if(workflow->idle_scan_idx == workflow->num_roots) {
331 | workflow->idle_scan_idx = 0;
332 | }
333 | }
334 |
335 |
336 | /*
337 | * Detect protocol.
338 | * Input arguments:
339 | * packet - pointer to a packet
340 | * packetlen - packet size
341 | * timestamp - timestamp of a packet
342 | * workflow - a structure set in main()
343 | *
344 | * Returns a structure containing master_proto, app_proto
345 | */
346 | struct ndpi_proto
347 | detect_protocol(const unsigned char *packet, const unsigned short packetlen,
348 | struct timeval timestamp, struct ndpi_workflow *workflow)
349 | {
350 | struct ndpi_iphdr *iph;
351 | struct ndpi_id_struct *src, *dst;
352 | struct ndpi_flow_struct *ndpi_flow = NULL;
353 | int ip_offset = 0;
354 | int ret = -1;
355 |
356 | u_int8_t ip_proto;
357 |
358 | u_int64_t tick = ((uint64_t) timestamp.tv_sec) * TICK_RESOLUTION +
359 | timestamp.tv_usec / (1000000 / TICK_RESOLUTION);
360 |
361 | iph = (struct ndpi_iphdr *) &packet[ip_offset];
362 |
363 | struct flow_info *flow;
364 |
365 | flow = get_flow_info(workflow, iph, packetlen, &src, &dst, &ip_proto);
366 |
367 | if(flow != NULL) {
368 | ndpi_flow = flow->ndpi_flow;
369 | flow->packets++;
370 | flow->last_seen = tick;
371 | } else {
372 | printf("ERROR: an error occured during get_flow_info.\n");
373 | exit(1);
374 | }
375 |
376 |
377 | if(flow->detection_completed == 0) {
378 | // attempt to detect a protocol
379 | flow->detected_protocol = ndpi_detection_process_packet(workflow->ndpi_struct,
380 | ndpi_flow, (uint8_t *)iph, packetlen, tick, src, dst);
381 | /* stop detection if protocol was determined or number of packets in the flow
382 | * has exceeded a specific value
383 | */
384 | if ((flow->detected_protocol.app_protocol != NDPI_PROTOCOL_UNKNOWN) ||
385 | ((ip_proto == IPPROTO_UDP) && (flow->packets > 8)) ||
386 | ((ip_proto == IPPROTO_TCP) && (flow->packets > 10))) {
387 |
388 | flow->detection_completed = 1;
389 |
390 | if (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_UNKNOWN) {
391 | flow->detected_protocol = ndpi_detection_giveup(workflow->ndpi_struct, flow->ndpi_flow);
392 | }
393 |
394 | process_ndpi_collected_info(workflow, flow);
395 | }
396 | }
397 |
398 | if ((flow->detection_completed == 1) && (flow->label_set == 0)) {
399 | // attempt to set connlabel
400 | if (flow->label_set == 0) {
401 | if ((ip_proto == IPPROTO_TCP) || (ip_proto == IPPROTO_UDP)) {
402 | if ((flow->detected_protocol.app_protocol < 128) &&
403 | (flow->detected_protocol.master_protocol < 128)) {
404 | //printf("flow is UDP, num of pkts = %d\n", flow->packets);
405 | ret = update_label(flow->src_ip, flow->dst_ip, flow->src_port, flow->dst_port,
406 | flow->detected_protocol.master_protocol + 1,
407 | flow->detected_protocol.app_protocol + 1, ip_proto);
408 | }
409 | }
410 |
411 | if (ret == 0) {
412 | flow->label_set = 1;
413 | }
414 | }
415 | }
416 |
417 | return flow->detected_protocol;
418 | }
419 |
420 | /*
421 | * For curious minds
422 | */
423 | void print_proto_names(struct ndpi_detection_module_struct *ndpi_struct)
424 | {
425 | int i = 0;
426 | for (i = 0; i <= 227; i++) {
427 | printf("%s\n", ndpi_get_proto_name(ndpi_struct, i));
428 | }
429 | }
430 |
--------------------------------------------------------------------------------
/src/nfqueue_test.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 |
15 | #include "ndpi_helper.h"
16 |
17 | #define VERSION 1.0
18 | #define BUFFERSIZE 65535
19 |
20 | struct q_data {
21 | int id;
22 | struct nfq_handle *handle;
23 | struct nfq_q_handle *q_handle;
24 | struct nfnl_handle *nh;
25 | struct ndpi_workflow *workflow;
26 | int fd;
27 | int sockfd;
28 | };
29 |
30 | // Globals
31 | pthread_mutex_t mutex, mutex_c, mutex_pt;
32 | int Quiet = 0;
33 | int NumQueues = 1;
34 | int NumRoots = 512;
35 | int MaxFlows = 200000000;
36 | int IdleScanPeriod = 100;
37 | int MaxIdleTime = 30000;
38 | int MaxIdleFlows = 1024;
39 |
40 | int Errors = 0;
41 |
42 | void t_printf(int tid, char *format, ...);
43 |
44 | void print_pkt (int tid, struct nfq_data *tb, struct nfqnl_msg_packet_hdr *pkt_hdr,
45 | char *src_ip, char *dst_ip, unsigned short src_port, unsigned short dst_port,
46 | char *master_protocol, char *app_protocol)
47 | {
48 | int id = 0;
49 | struct nfqnl_msg_packet_hw *hwph;
50 |
51 | t_printf(tid, "");
52 |
53 | id = ntohl(pkt_hdr->packet_id);
54 | printf("id=%u ", id);
55 |
56 | hwph = nfq_get_packet_hw(tb);
57 | if (hwph) {
58 | int i, hlen = ntohs(hwph->hw_addrlen);
59 |
60 | printf("he_src_addr=");
61 | for (i = 0; i < hlen-1; i++) {
62 | printf("%02x:", hwph->hw_addr[i]);
63 | }
64 | printf("%02x ", hwph->hw_addr[hlen - 1]);
65 | }
66 |
67 | printf("src=%s:%d dst=%s:%d\n", src_ip, src_port, dst_ip, dst_port);
68 | printf("proto = %s.%s.\n", master_protocol, app_protocol);
69 | }
70 |
71 | /*
72 | * Callback function called for each packet
73 | */
74 | static int cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg,
75 | struct nfq_data *nfa, void *data)
76 | {
77 | // read thread-specific data
78 | struct q_data *t_data = (struct q_data *)data;
79 |
80 | int id;
81 | struct ndpi_proto proto;
82 | char *app_proto; // e.g. Facebook
83 | char *master_proto; // e.g. HTTP
84 | unsigned char *packet_data;
85 |
86 | char src_ip[15], dst_ip[15];
87 |
88 | struct nfqnl_msg_packet_hdr *pkt_hdr = nfq_get_msg_packet_hdr(nfa);
89 | if (pkt_hdr) {
90 | id = ntohl(pkt_hdr->packet_id);
91 | } else {
92 | t_printf(t_data->id, "Packet header could not be retrieved.\n");
93 | return -1; //error code of nfq_set_verdict
94 | }
95 |
96 | struct timeval tv;
97 | int is_success = nfq_get_timestamp(nfa, &tv);
98 | // if the timestamp was not retrieved, set it to local time
99 | if (is_success != 0 || tv.tv_sec == 0) {
100 | memset(&tv, 0, sizeof(struct timeval));
101 | gettimeofday(&tv, NULL);
102 | }
103 |
104 | unsigned short payload_size;
105 | payload_size = nfq_get_payload(nfa, &packet_data);
106 |
107 | if (payload_size == -1) {
108 | t_printf(t_data->id, "Packet payload was not retrieved. Skipping current packet.\n");
109 | return -1;
110 | }
111 |
112 | // detect protocol
113 | proto = detect_protocol(packet_data, payload_size, tv, t_data->workflow);
114 | master_proto = ndpi_get_proto_name(t_data->workflow->ndpi_struct, proto.master_protocol);
115 | app_proto = ndpi_get_proto_name(t_data->workflow->ndpi_struct, proto.app_protocol);
116 |
117 | // determine source and destination
118 | struct iphdr *ip_info = (struct iphdr *)packet_data;
119 | char *src_ip_ptr = inet_ntoa(*((struct in_addr *)&(ip_info->saddr)));
120 | strncpy(src_ip, src_ip_ptr, sizeof(src_ip));
121 | char *dst_ip_ptr = inet_ntoa(*((struct in_addr *)&(ip_info->daddr)));
122 | strncpy(dst_ip, dst_ip_ptr, sizeof(dst_ip));
123 |
124 | unsigned short dst_port;
125 | unsigned short src_port;
126 | if (ip_info->protocol == IPPROTO_TCP) {
127 | struct tcphdr *tcp_info = (struct tcphdr *)(packet_data + sizeof(*ip_info));
128 | dst_port = ntohs(tcp_info->dest);
129 | src_port = ntohs(tcp_info->source);
130 | } else if (ip_info->protocol == IPPROTO_UDP) {
131 | struct udphdr *udp_info = (struct udphdr *)(packet_data + sizeof(*ip_info));
132 | dst_port = ntohs(udp_info->dest);
133 | src_port = ntohs(udp_info->source);
134 | } else {
135 | dst_port = src_port = 0;
136 | }
137 |
138 | if (!Quiet) {
139 | print_pkt(t_data->id, nfa, pkt_hdr, src_ip, dst_ip, src_port, dst_port,
140 | master_proto, app_proto);
141 | }
142 |
143 | // free idle flows
144 | t_data->workflow->timestamp = ((uint64_t) tv.tv_sec) * TICK_RESOLUTION +
145 | tv.tv_usec / (1000000 / TICK_RESOLUTION);
146 | if (t_data->workflow->last_idle_scan + IdleScanPeriod < t_data->workflow->timestamp) {
147 | t_data->workflow->last_idle_scan = t_data->workflow->timestamp;
148 | free_idle_flows(t_data->workflow);
149 | }
150 |
151 | // unlock happens in process_thread()
152 | pthread_mutex_lock(&mutex_c);
153 | return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
154 | }
155 |
156 | /*
157 | * Print wrapper for threads
158 | * Input arguments:
159 | * tid - thread id
160 | * format - string format like for printf()
161 | */
162 | void t_printf(int tid, char *format, ...)
163 | {
164 | va_list ap;
165 | va_start(ap, format);
166 | printf("Queue %d: ", tid);
167 | vfprintf(stdout, format, ap);
168 | va_end(ap);
169 | }
170 |
171 | void *process_thread(void *data)
172 | {
173 | ssize_t rv;
174 | int opt;
175 | char buf[BUFFERSIZE];
176 |
177 | // retrieve thread-specific data
178 | struct q_data *t_data = (struct q_data *)data;
179 |
180 | t_printf(t_data->id, "opening library handle\n");
181 | t_data->handle = nfq_open();
182 | if (!t_data->handle) {
183 | t_printf(t_data->id, "error during nfq_open()\n");
184 | exit(1);
185 | }
186 |
187 | t_printf(t_data->id, "unbinding existing nf_queue handler for AF_INET (if any)\n");
188 | if (nfq_unbind_pf(t_data->handle, AF_INET) < 0) {
189 | t_printf(t_data->id, "error during nfq_unbind_pf()\n");
190 | exit(1);
191 | }
192 |
193 |
194 | t_printf(t_data->id, "binding nfnetlink_queue as nf_queue handler for AF_INET\n");
195 | if (nfq_bind_pf(t_data->handle, AF_INET) < 0) {
196 | t_printf(t_data->id, "error during nfq_bind_pf()\n");
197 | exit(1);
198 | }
199 |
200 | t_printf(t_data->id, "binding this socket to queue '%d'\n", t_data->id);
201 | t_data->q_handle = nfq_create_queue(t_data->handle, t_data->id, &cb, (void *)t_data);
202 | if (!t_data->q_handle) {
203 | t_printf(t_data->id, "error during nfq_create_queue()\n");
204 | exit(1);
205 | }
206 |
207 | t_printf(t_data->id, "setting copy_packet mode\n");
208 | if (nfq_set_mode(t_data->q_handle, NFQNL_COPY_PACKET, 0xffff) < 0) {
209 | t_printf(t_data->id, "can't set packet_copy mode\n");
210 | exit(1);
211 | }
212 |
213 |
214 | t_data->fd = nfq_fd(t_data->handle);
215 | t_data->nh = nfq_nfnlh(t_data->handle);
216 | t_data->sockfd = nfnl_fd(t_data->nh);
217 |
218 | t_printf(t_data->id, "setting buffer size to %d\n", BUFFERSIZE);
219 | nfnl_rcvbufsiz(t_data->nh, BUFFERSIZE);
220 |
221 | // set socket option NETLINK_NO_ENOBUFS for performance improvement
222 | opt = 1;
223 | if (setsockopt(t_data->sockfd, SOL_NETLINK, NETLINK_NO_ENOBUFS,
224 | &opt, sizeof(int)) == -1) {
225 | printf("ERROR: Can't set netlink enobufs: %s", strerror(errno));
226 | exit(1);
227 | }
228 |
229 | // read packet and process it
230 | while (1) {
231 | rv = recv(t_data->fd, buf, BUFFERSIZE, 0);
232 | if (rv > 0) {
233 | pthread_mutex_lock(&mutex_pt);
234 | nfq_handle_packet(t_data->handle, buf, rv);
235 | pthread_mutex_unlock(&mutex_c);
236 | pthread_mutex_unlock(&mutex_pt);
237 | } else {
238 | if (rv < (ssize_t)-1 || rv > (ssize_t)BUFFERSIZE) {
239 | errno = EIO;
240 | break; /* out of the while (1) loop */
241 | }
242 |
243 | if (rv== (ssize_t)0) {
244 | break; /* No error, just netlink closed. Drop out. */
245 | }
246 |
247 | if (rv == (ssize_t)-1) {
248 | if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
249 | continue;
250 | } else {
251 | Errors++;
252 | printf("Errors = %d\n", Errors);
253 | break; /* Other errors drop out of the loop. */
254 | }
255 | }
256 | }
257 | }
258 |
259 | t_printf(t_data->id, "unbinding from queue %d\n", t_data->id);
260 | nfq_destroy_queue(t_data->q_handle);
261 |
262 | t_printf(t_data->id, "closing library handle\n");
263 | nfq_close(t_data->handle);
264 |
265 | pthread_exit(NULL);
266 | return NULL;
267 | }
268 |
269 | void display_help()
270 | {
271 | printf("NdpiNfqueueFirewall v.%.1f\n\n", VERSION);
272 |
273 | printf("Usage:\n");
274 | printf("NdpiNfqueueFirewall [ --option value ]...\n\n");
275 |
276 | printf("Options (default values in brackets):\n");
277 | printf("\t--num-queues\t\t-n\t\tNumber of queues to listen on.(1)\n");
278 | printf("\t--num-roots\t\t-r\t\tNumber of roots of a binary tree.(512)\n");
279 | printf("\t--max-flows\t\t-f\t\tMaximum number of flows.(200000000)\n");
280 | printf("\t--idle-scan-period\t-i\t\tTime period in milliseconds of scans for idle flows.(100ms)\n");
281 | printf("\t--max-idle-time\t\t-t\t\tMaximum amount of time in milliseconds a flow can be idle.(30000ms)\n");
282 | printf("\t--max-idle-flows\t-F\t\tMaximum number of idle flows.(1024)\n");
283 | printf("\t--quiet\t\t\t-q\t\tQuiet mode.\n");
284 | printf("\t--version\t\t-v\t\tDisplay version.\n");
285 | printf("\t--help\t\t\t-h\t\tDisplay help message.\n");
286 | }
287 |
288 | void print_setup(){
289 | printf("Configuration of this run is the following:\n");
290 | printf("\tnumber of queues \t %d\n", NumQueues);
291 | printf("\tnumber of roots \t %d\n", NumRoots);
292 | printf("\tmaximum flows \t\t %d\n", MaxFlows);
293 | printf("\tidle scan period \t %d\n", IdleScanPeriod);
294 | printf("\tmaximum idle time \t %d\n", MaxIdleTime);
295 | printf("\tmaximum idle flows \t %d\n", MaxIdleFlows);
296 | printf("\tquiet \t\t\t %d\n", Quiet);
297 | }
298 |
299 | int main(int argc, char **argv)
300 | {
301 | int rc;
302 | void *status;
303 |
304 | if (argc > 14) {
305 | printf("Error: Too many arguments.\n");
306 | display_help();
307 | exit(1);
308 | }
309 |
310 | if (argc == 2) {
311 | if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0)) {
312 | display_help();
313 | exit(0);
314 | } else if ((strcmp(argv[1], "-v") == 0) || (strcmp(argv[1], "--version") == 0)) {
315 | printf("NdpiNfqueueFirewall version %.1f\n", VERSION);
316 | exit(0);
317 | }
318 | }
319 |
320 | int a = 1;
321 | char *endptr;
322 | errno = 0;
323 | while (a < argc) {
324 | if ((strcmp(argv[a], "-n") == 0) || (strcmp(argv[a], "--num-queues") == 0)) {
325 | // set num queues
326 | NumQueues = strtoimax(argv[a + 1], &endptr, 10);
327 | if ((errno != 0) || (NumQueues <= 0)) {
328 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
329 | exit(1);
330 | }
331 | a += 2;
332 | } else if ((strcmp(argv[a], "-r") == 0) || (strcmp(argv[a], "--num-roots") == 0)) {
333 | // set num roots
334 | NumRoots = strtoimax(argv[a + 1], &endptr, 10);
335 | if ((errno != 0) || (NumRoots <= 0)) {
336 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
337 | exit(1);
338 | }
339 | a += 2;
340 | } else if ((strcmp(argv[a], "-f") == 0) || (strcmp(argv[a], "--max-flows") == 0)) {
341 | // set max flows
342 | MaxFlows = strtoimax(argv[a + 1], &endptr, 10);
343 | if ((errno != 0) || (MaxFlows <= 0)) {
344 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
345 | exit(1);
346 | }
347 | a += 2;
348 | } else if ((strcmp(argv[a], "-i") == 0) || (strcmp(argv[a], "--idle-scan-period") == 0)) {
349 | // set idle scan period
350 | IdleScanPeriod = strtoimax(argv[a + 1], &endptr, 10);
351 | if ((errno != 0) || (IdleScanPeriod <= 0)) {
352 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
353 | exit(1);
354 | }
355 | a += 2;
356 | } else if ((strcmp(argv[a], "-t") == 0) || (strcmp(argv[a], "--max-idle-time") == 0)) {
357 | // set max idle time
358 | MaxIdleTime = strtoimax(argv[a + 1], &endptr, 10);
359 | if ((errno != 0) || (MaxIdleTime <= 0)) {
360 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
361 | exit(1);
362 | }
363 | a += 2;
364 | } else if ((strcmp(argv[a], "-F") == 0) || (strcmp(argv[a], "--max-idle-flows") == 0)) {
365 | // set max idle flows
366 | MaxIdleFlows = strtoimax(argv[a + 1], &endptr, 10);
367 | if ((errno != 0) || (MaxIdleFlows <= 0)) {
368 | printf("ERROR: %s is not a valid value.\n", argv[a + 1]);
369 | exit(1);
370 | }
371 | a += 2;
372 | } else if ((strcmp(argv[a], "-q") == 0) || (strcmp(argv[a], "--quiet") == 0)) {
373 | Quiet = 1;
374 | a += 1;
375 | } else {
376 | printf("ERROR: %s is not a valid argument.\n", argv[a]);
377 | display_help();
378 | exit(1);
379 | }
380 | }
381 |
382 | print_setup();
383 |
384 | pthread_t threads[NumQueues];
385 |
386 | pthread_mutex_init(&mutex_c, NULL);
387 | pthread_mutex_init(&mutex_pt, NULL);
388 |
389 | struct q_data data[NumQueues];
390 |
391 | int i = 0;
392 | // prepare data for each thread
393 | for (i = 0; i < NumQueues; i++) {
394 | data[i].id = i + 10;
395 |
396 | struct ndpi_workflow *workflow = ndpi_calloc(1, sizeof(struct ndpi_workflow));
397 | if (workflow == NULL) {
398 | printf("ERROR: workflow initialization failed");
399 | exit(1);
400 | }
401 |
402 | workflow->num_roots = NumRoots;
403 | workflow->max_flows = MaxFlows;
404 | workflow->max_idle_time = MaxIdleTime;
405 |
406 | workflow->flow_count = 0;
407 |
408 | workflow->ndpi_flows_root = ndpi_calloc(workflow->num_roots, sizeof(void *));
409 | if (workflow->ndpi_flows_root == NULL) {
410 | printf("ERROR: ndpi_flows_root initialization failed");
411 | exit(1);
412 | }
413 |
414 | workflow->max_idle_flows = MaxIdleFlows;
415 | workflow->idle_flows = ndpi_calloc(MaxIdleFlows, sizeof(struct flow_info *));
416 | if (workflow->idle_flows == NULL) {
417 | printf("ERROR: idle_flows initialization failed");
418 | exit(1);
419 | }
420 |
421 | workflow->ndpi_struct = setup_detection();
422 |
423 | data[i].workflow = workflow;
424 | }
425 |
426 | // create threads
427 | for (i = 0; i < NumQueues; i++) {
428 | printf("Main: creating thread %d\n", i);
429 | rc = pthread_create(&threads[i], NULL, process_thread, &data[i]);
430 |
431 | if (rc) {
432 | printf("ERROR; return code from pthread_create() is %d\n", rc);
433 | exit(1);
434 | }
435 | }
436 |
437 | for (i = 0; i < NumQueues; i++) {
438 | rc = pthread_join(threads[i], &status);
439 | if (rc) {
440 | printf("ERROR; return code from pthread_join() is %d\n", rc);
441 | exit(1);
442 | }
443 |
444 | printf("Main: completed join with thread %d having a status of %ld\n", i, (long)status);
445 | }
446 |
447 | printf("Main: program completed. Exiting.\n");
448 |
449 | pthread_mutex_destroy(&mutex_c);
450 | pthread_mutex_destroy(&mutex_pt);
451 | pthread_exit(NULL);
452 | exit(0);
453 | }
454 |
--------------------------------------------------------------------------------
/src/tests/ndpi_helper_tests.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | #include "ndpi_helper.h"
10 | #include "ndpi_main.h"
11 |
12 | /* Wrap functions */
13 | void __wrap_set_ndpi_malloc()
14 | {
15 | // do nothing
16 | }
17 |
18 | void __wrap_set_ndpi_free()
19 | {
20 | // do nothing
21 | }
22 |
23 | void __wrap_set_ndpi_flow_malloc()
24 | {
25 | // do nothing
26 | }
27 |
28 | void __wrap_set_ndpi_flow_free()
29 | {
30 | // do nothing
31 | }
32 |
33 | struct ndpi_detection_module_struct *__wrap_ndpi_init_detection_module()
34 | {
35 | struct ndpi_detection_module_struct *ndpi_str = malloc(sizeof(struct ndpi_detection_module_struct));
36 |
37 | if(ndpi_str == NULL) {
38 | return NULL;
39 | } else {
40 | memset(ndpi_str, 0, sizeof(struct ndpi_detection_module_struct));
41 | return ndpi_str;
42 | }
43 | }
44 |
45 | void __wrap_NDPI_BITMASK_SET_ALL(){
46 | // do nothing
47 | }
48 |
49 | void __wrap_ndpi_set_protocol_detection_bitmask2()
50 | {
51 | // do nothing
52 | }
53 |
54 | ndpi_protocol __wrap_ndpi_detection_process_packet()
55 | {
56 | int master_protocol = mock_type(int);
57 | int app_protocol = mock_type(int);
58 | ndpi_protocol res = { master_protocol, app_protocol };
59 | return res;
60 | }
61 |
62 | struct flow_info *__wrap_get_flow_info()
63 | {
64 | struct flow_info *ret = malloc(sizeof(struct flow_info));
65 | if (ret == NULL) {
66 | printf("error during flow allocation");
67 | }
68 |
69 | return ret;
70 | }
71 |
72 | /********************/
73 |
74 | /* Tests */
75 |
76 | static void setup_detection_test_success(void **state)
77 | {
78 | (void) state; /* unused */
79 |
80 | struct ndpi_detection_module_struct *expected = malloc(sizeof(
81 | struct ndpi_detection_module_struct));
82 |
83 | if(expected == NULL) {
84 | printf("Malloc failed.");
85 | exit(1);
86 | } else {
87 | memset(expected, 0, sizeof(struct ndpi_detection_module_struct));
88 | }
89 |
90 | struct ndpi_detection_module_struct *actual = setup_detection();
91 |
92 | assert_memory_equal(expected, actual, sizeof(struct ndpi_detection_module_struct));
93 |
94 | free(expected);
95 | free(actual);
96 | }
97 |
98 | static void detect_protocol_test_success(void **state)
99 | {
100 | (void) state; /* unused */
101 |
102 | ndpi_protocol expected = { 23, 100 };
103 |
104 | will_return(__wrap_ndpi_detection_process_packet, 23);
105 | will_return(__wrap_ndpi_detection_process_packet, 100);
106 |
107 | const unsigned char *packet;
108 | const unsigned short packetlen = 10;
109 | struct timeval timestamp = { 100, 1000 };
110 |
111 | struct ndpi_detection_module_struct *ndpi_struct = malloc(sizeof(
112 | struct ndpi_detection_module_struct));
113 |
114 | if(ndpi_struct == NULL) {
115 | printf("Malloc failed.");
116 | exit(1);
117 | } else {
118 | memset(ndpi_struct, 0, sizeof(struct ndpi_detection_module_struct));
119 | }
120 |
121 | struct ndpi_workflow *workflow = ndpi_calloc(1, sizeof(struct ndpi_workflow));
122 | if (workflow == NULL) {
123 | printf("ERROR: workflow initialization failed");
124 | exit(1);
125 | }
126 |
127 | workflow->num_roots = 512;
128 | workflow->max_flows = 20000000;
129 | workflow->max_idle_time = 600;
130 |
131 | workflow->flow_count = 0;
132 |
133 | workflow->ndpi_flows_root = ndpi_calloc(workflow->num_roots, sizeof(void *));
134 | if (workflow->ndpi_flows_root == NULL) {
135 | printf("ERROR: ndpi_flows_root initialization failed");
136 | exit(1);
137 | }
138 |
139 | workflow->idle_flows = ndpi_calloc(10, sizeof(struct flow_info *));
140 | if (workflow->idle_flows == NULL) {
141 | printf("ERROR: idle_flows initialization failed");
142 | exit(1);
143 | }
144 |
145 | workflow->ndpi_struct = ndpi_struct;
146 |
147 | ndpi_protocol actual = detect_protocol(packet, packetlen, timestamp, workflow);
148 |
149 | assert_int_equal(expected.master_protocol, actual.master_protocol);
150 | assert_int_equal(expected.app_protocol, actual.app_protocol);
151 |
152 | free(ndpi_struct);
153 | free(workflow->idle_flows);
154 | free(workflow->ndpi_flows_root);
155 | free(workflow);
156 | }
157 |
158 | int main(void) {
159 | const struct CMUnitTest tests[] = {
160 | cmocka_unit_test(setup_detection_test_success),
161 | cmocka_unit_test(detect_protocol_test_success)
162 | };
163 |
164 | return cmocka_run_group_tests(tests, NULL, NULL);
165 | }
166 |
--------------------------------------------------------------------------------