[
  {
    "path": ".dockerignore",
    "content": "target\nDockerfile\n.dockerignore\n.git\n.gitignore\n*.sw[op]\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [kpcyrd]\n"
  },
  {
    "path": ".github/workflows/rust.yml",
    "content": "name: Rust\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\nenv:\n  CARGO_TERM_COLOR: always\n\njobs:\n  build:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [macos-latest, windows-latest, ubuntu-latest]\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Build\n      run: cargo build --verbose --all-targets\n    - name: Run tests\n      run: cargo test --verbose\n    - name: Run integration test (smtp)\n      if: matrix.os == 'ubuntu-latest'\n      run: |\n        docker build -t authoscope-smtpd ci/smtp/\n        docker run --name authoscope-smtpd -d --rm -p 127.0.0.1:25:25 authoscope-smtpd\n\n        echo root@example.com:foo > /tmp/authoscope-smtp-input.txt\n        target/debug/authoscope -o authoscope-smtp-output.txt combo /tmp/authoscope-smtp-input.txt scripts/smtp.lua\n        docker stop authoscope-smtpd\n    - name: Verify integration test (smtp)\n      if: matrix.os == 'ubuntu-latest'\n      run: grep -q root@example.com authoscope-smtp-output.txt\n"
  },
  {
    "path": ".gitignore",
    "content": "\n/target/\n**/*.rs.bk\n*.txt\n*.sw[op]\n/docs/_build/\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"authoscope\"\nversion = \"0.8.1\"\ndescription = \"Scriptable network authentication cracker\"\nauthors = [\"kpcyrd <git@rxv.cc>\"]\nlicense = \"GPL-3.0\"\nrepository = \"https://github.com/kpcyrd/authoscope\"\ncategories = [\"command-line-utilities\"]\ndefault-run = \"authoscope\"\nreadme = \"README.md\"\nedition = \"2018\"\n\n[dependencies]\n#hlua = \"0.4\"\n#hlua-badtouch = { path=\"../hlua/hlua\" }\nhlua-badtouch = \"0.4.2\"\nlog = \"0.4\"\nenv_logger = \"0.9\"\npbr = \"1.0\"\nthreadpool = \"1.7\"\ncolored = \"2\"\nhumantime = \"2\"\nstructopt = \"0.3\"\nanyhow = \"1\"\ntime = \"0.3\"\natty = \"0.2\"\nrand = \"0.8\"\ngetch = \"0.3\"\ntoml = \"0.5\"\nnix = \"0.23\"\nserde = { version=\"1.0\", features=[\"derive\"] }\nserde_json = \"1.0\"\nbufstream = \"0.1.3\"\nregex = \"1.0.1\"\n\nmd-5 = \"0.10\"\nsha-1 = \"0.10\"\nsha2 = \"0.10\"\nsha3 = \"0.10\"\ndigest = \"0.10\"\nhmac = \"0.12\"\nbase64 = \"0.13\"\nbcrypt = \"0.12\"\n\nreqwest = { version=\"0.11\", features=[\"blocking\", \"json\"] }\nmysql = \"22\"\nldap3 = \"0.10\"\nkuchiki = \"0.8\"\ndirs = \"4\"\nnum-format = \"0.4.0\"\n\n[target.\"cfg(unix)\".dependencies]\ntermios = \"0.3\"\n\n[target.'cfg(target_os=\"linux\")'.dependencies]\nrlimit = \"0.7\"\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM rust:alpine3.15\nENV RUSTFLAGS=\"-C target-feature=-crt-static\"\nRUN apk add musl-dev openssl-dev\nWORKDIR /app\nCOPY . .\nRUN cargo build --release --locked --verbose\nRUN strip target/release/authoscope\n\nFROM alpine:3.15\nRUN apk add --no-cache libgcc openssl\nCOPY --from=0 /app/target/release/authoscope /usr/local/bin/authoscope\nENTRYPOINT [\"authoscope\"]\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": "# authoscope [![Crates.io][crates-img]][crates]\n\n[crates-img]:   https://img.shields.io/crates/v/authoscope.svg\n[crates]:       https://crates.io/crates/authoscope\n\nauthoscope is a scriptable network authentication cracker. While the space for\ncommon service bruteforce is already [very][ncrack] [well][hydra]\n[saturated][medusa], you may still end up writing your own python scripts when\ntesting credentials for web applications.\n\n[ncrack]: https://nmap.org/ncrack/\n[hydra]: https://github.com/vanhauser-thc/thc-hydra\n[medusa]: https://github.com/jmk-foofus/medusa\n\nThe scope of authoscope is specifically cracking custom services. This is done\nby writing scripts that are loaded into a lua runtime. Those scripts represent\na single service and provide a `verify(user, password)` function that returns\neither true or false. Concurrency, progress indication and reporting is\nmagically provided by the authoscope runtime.\n\n[![asciicast](https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ.png)](https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ)\n\n## Installation\n\n<a href=\"https://repology.org/project/authoscope/versions\"><img align=\"right\" src=\"https://repology.org/badge/vertical-allrepos/authoscope.svg\" alt=\"Packaging status\"></a>\n\nIf you are on an Arch Linux based system, use\n\n    pacman -S authoscope\n\nIf you are on Mac OSX, use\n\n    brew install authoscope\n\nTo build from source, make sure you have [rust](https://rustup.rs/) and `libssl-dev` installed and run\n\n    cargo install\n\nVerify your setup is complete with\n\n    authoscope --help\n\n### Debian\n1. Install essential build tools\n```\nsudo apt-get update && sudo apt-get dist-upgrade\nsudo apt-get install build-essential libssl-dev pkg-config\n```\n2. Install rust\n```\ncurl -sf -L https://static.rust-lang.org/rustup.sh | sh\nsource $HOME/.cargo/env\n```\n3. Install authoscope\n```\ncd /path/to/authoscope\ncargo install\n```\n\n## Scripting\n\nA simple script could look like this:\n\n```lua\ndescr = \"example.com\"\n\nfunction verify(user, password)\n    session = http_mksession()\n\n    -- get csrf token\n    req = http_request(session, 'GET', 'https://example.com/login', {})\n    resp = http_send(req)\n    if last_err() then return end\n\n    -- parse token from html\n    html = resp['text']\n    csrf = html_select(html, 'input[name=\"csrf\"]')\n    token = csrf[\"attrs\"][\"value\"]\n\n    -- send login\n    req = http_request(session, 'POST', 'https://example.com/login', {\n        form={\n            user=user,\n            password=password,\n            csrf=token\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n\n    -- search response for successful login\n    html = resp['text']\n    return html:find('Login successful') != nil\nend\n```\n\nPlease see the reference and [examples](/scripts) for all available functions.\nKeep in mind that you can use `print(x)` and `authoscope oneshot` to debug your\nscript.\n\n## Reference\n- [base64_decode](#base64_decode)\n- [base64_encode](#base64_encode)\n- [clear_err](#clear_err)\n- [execve](#execve)\n- [hex](#hex)\n- [hmac_md5](#hmac_md5)\n- [hmac_sha1](#hmac_sha1)\n- [hmac_sha2_256](#hmac_sha2_256)\n- [hmac_sha2_512](#hmac_sha2_512)\n- [hmac_sha3_256](#hmac_sha3_256)\n- [hmac_sha3_512](#hmac_sha3_512)\n- [html_select](#html_select)\n- [html_select_list](#html_select_list)\n- [http_basic_auth](#http_basic_auth)\n- [http_mksession](#http_mksession)\n- [http_request](#http_request)\n- [http_send](#http_send)\n- [json_decode](#json_decode)\n- [json_encode](#json_encode)\n- [last_err](#last_err)\n- [ldap_bind](#ldap_bind)\n- [ldap_escape](#ldap_escape)\n- [ldap_search_bind](#ldap_search_bind)\n- [md5](#md5)\n- [mysql_connect](#mysql_connect)\n- [mysql_query](#mysql_query)\n- [print](#print)\n- [rand](#rand)\n- [randombytes](#randombytes)\n- [sha1](#sha1)\n- [sha2_256](#sha2_256)\n- [sha2_512](#sha2_512)\n- [sha3_256](#sha3_256)\n- [sha3_512](#sha3_512)\n- [sleep](#sleep)\n- [sock_connect](#sock_connect)\n- [sock_send](#sock_send)\n- [sock_recv](#sock_recv)\n- [sock_sendline](#sock_sendline)\n- [sock_recvline](#sock_recvline)\n- [sock_recvall](#sock_recvall)\n- [sock_recvline_contains](#sock_recvline_contains)\n- [sock_recvline_regex](#sock_recvline_regex)\n- [sock_recvn](#sock_recvn)\n- [sock_recvuntil](#sock_recvuntil)\n- [sock_sendafter](#sock_sendafter)\n- [sock_newline](#sock_newline)\n- [Examples](/scripts)\n- [Configuration](#configuration)\n- [Wrapping python scripts](#wrapping-python-scripts)\n\n### base64_decode\nDecode a base64 string.\n```lua\nbase64_decode(\"ww==\")\n```\n\n### base64_encode\nEncode a binary array with base64.\n```lua\nbase64_encode(\"\\x00\\xff\")\n```\n\n### clear_err\nClear all recorded errors to prevent a requeue.\n```lua\nif last_err() then\n    clear_err()\n    return false\nelse\n    return true\nend\n```\n\n### execve\nExecute an external program. Returns the exit code.\n```lua\nexecve(\"myprog\", {\"arg1\", \"arg2\", \"--arg\", \"3\"})\n```\n\n### hex\nHex encode a list of bytes.\n```lua\nhex(\"\\x6F\\x68\\x61\\x69\\x0A\\x00\")\n```\n\n### hmac_md5\nCalculate an hmac with md5. Returns a binary array.\n```lua\nhmac_md5(\"secret\", \"my authenticated message\")\n```\n\n### hmac_sha1\nCalculate an hmac with sha1. Returns a binary array.\n```lua\nhmac_sha1(\"secret\", \"my authenticated message\")\n```\n\n### hmac_sha2_256\nCalculate an hmac with sha2_256. Returns a binary array.\n```lua\nhmac_sha2_256(\"secret\", \"my authenticated message\")\n```\n\n### hmac_sha2_512\nCalculate an hmac with sha2_512. Returns a binary array.\n```lua\nhmac_sha2_512(\"secret\", \"my authenticated message\")\n```\n\n### hmac_sha3_256\nCalculate an hmac with sha3_256. Returns a binary array.\n```lua\nhmac_sha3_256(\"secret\", \"my authenticated message\")\n```\n\n### hmac_sha3_512\nCalculate an hmac with sha3_512. Returns a binary array.\n```lua\nhmac_sha3_512(\"secret\", \"my authenticated message\")\n```\n\n### html_select\nParses an html document and returns the first element that matches the css\nselector. The return value is a table with `text` being the inner text and\n`attrs` being a table of the elements attributes.\n```lua\ncsrf = html_select(html, 'input[name=\"csrf\"]')\ntoken = csrf[\"attrs\"][\"value\"]\n```\n\n### html_select_list\nSame as [`html_select`](#html_select) but returns all matches instead of the\nfirst one.\n```lua\nhtml_select_list(html, 'input[name=\"csrf\"]')\n```\n\n### http_basic_auth\nSends a `GET` request with basic auth. Returns `true` if no `WWW-Authenticate`\nheader is set and the status code is not `401`.\n```lua\nhttp_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\n```\n\n### http_mksession\nCreate a session object. This is similar to `requests.Session` in\npython-requests and keeps track of cookies.\n```lua\nsession = http_mksession()\n```\n\n### http_request\nPrepares an http request. The first argument is the session reference and\ncookies from that session are copied into the request. After the request has\nbeen sent, the cookies from the response are copied back into the session.\n\nThe next arguments are the `method`, the `url` and additional options. Please\nnote that you still need to specify an empty table `{}` even if no options are\nset. The following options are available:\n\n- `query` - a map of query parameters that should be set on the url\n- `headers` - a map of headers that should be set\n- `basic_auth` - configure the basic auth header with `{\"user, \"password\"}`\n- `user_agent` - overwrite the default user agent with a string\n- `json` - the request body that should be json encoded\n- `form` - the request body that should be form encoded\n- `body` - the raw request body as string\n\n```lua\nreq = http_request(session, 'POST', 'https://httpbin.org/post', {\n    json={\n        user=user,\n        password=password,\n    }\n})\nresp = http_send(req)\nif last_err() then return end\nif resp[\"status\"] ~= 200 then return \"invalid status code\" end\n```\n\n### http_send\nSend the request that has been built with [`http_request`](#http_request).\nReturns a table with the following keys:\n\n- `status` - the http status code\n- `headers` - a table of headers\n- `text` - the response body as string\n\n```lua\nreq = http_request(session, 'POST', 'https://httpbin.org/post', {\n    json={\n        user=user,\n        password=password,\n    }\n})\nresp = http_send(req)\nif last_err() then return end\nif resp[\"status\"] ~= 200 then return \"invalid status code\" end\n```\n\n### json_decode\nDecode a lua value from a json string.\n```lua\njson_decode(\"{\\\"data\\\":{\\\"password\\\":\\\"fizz\\\",\\\"user\\\":\\\"bar\\\"},\\\"list\\\":[1,3,3,7]}\")\n```\n\n### json_encode\nEncode a lua value to a json string. Note that empty tables are encoded to an\nempty object `{}` instead of an empty list `[]`.\n```lua\nx = json_encode({\n    hello=\"world\",\n    almost_one=0.9999,\n    list={1,3,3,7},\n    data={\n        user=user,\n        password=password,\n        empty=nil\n    }\n})\n```\n\n### last_err\nReturns `nil` if no error has been recorded, returns a string otherwise.\n```lua\nif last_err() then return end\n```\n\n### ldap_bind\nConnect to an ldap server and try to authenticate with the given user.\n```lua\nldap_bind(\"ldaps://ldap.example.com/\",\n    \"cn=\\\"\" .. ldap_escape(user) .. \"\\\",ou=users,dc=example,dc=com\", password)\n```\n\n### ldap_escape\nEscape an attribute value in a relative distinguished name.\n```lua\nldap_escape(user)\n```\n\n### ldap_search_bind\nConnect to an ldap server, log into a search user, search for the target user\nand then try to authenticate with the first DN that was returned by the search.\n```lua\nldap_search_bind(\"ldaps://ldap.example.com/\",\n    -- the user we use to find the correct DN\n    \"cn=search_user,ou=users,dc=example,dc=com\", \"searchpw\",\n    -- base DN we search in\n    \"dc=example,dc=com\",\n    -- the user we test\n    user, password)\n```\n\n### md5\nHash a byte array with md5 and return the results as bytes.\n```lua\nhex(md5(\"\\x00\\xff\"))\n```\n\n### mysql_connect\nConnect to a mysql database and try to authenticate with the provided\ncredentials. Returns a mysql connection on success.\n```lua\nsock = mysql_connect(\"127.0.0.1\", 3306, user, password)\n```\n\n### mysql_query\nRun a query on a mysql connection. The 3rd parameter is for prepared\nstatements.\n```lua\nrows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {\n    foo='magic'\n})\n```\n\n### print\nPrints the value of a variable. Please note that this bypasses the regular\nwriter and may interfer with the progress bar. Only use this for debugging.\n```lua\nprint({\n    data={\n        user=user,\n        password=password\n    }\n})\n```\n\n### rand\nReturns a random `u32` with a minimum and maximum constraint. The return value\ncan be greater or equal to the minimum boundary, and always lower than the\nmaximum boundary. This function has not been reviewed for cryptographic\nsecurity.\n```lua\nrand(0, 256)\n```\n\n### randombytes\nGenerate the specified number of random bytes.\n```lua\nrandombytes(16)\n```\n\n### sha1\nHash a byte array with sha1 and return the results as bytes.\n```lua\nhex(sha1(\"\\x00\\xff\"))\n```\n\n### sha2_256\nHash a byte array with sha2_256 and return the results as bytes.\n```lua\nhex(sha2_256(\"\\x00\\xff\"))\n```\n\n### sha2_512\nHash a byte array with sha2_512 and return the results as bytes.\n```lua\nhex(sha2_512(\"\\x00\\xff\"))\n```\n\n### sha3_256\nHash a byte array with sha3_256 and return the results as bytes.\n```lua\nhex(sha3_256(\"\\x00\\xff\"))\n```\n\n### sha3_512\nHash a byte array with sha3_512 and return the results as bytes.\n```lua\nhex(sha3_512(\"\\x00\\xff\"))\n```\n\n### sleep\nPauses the thread for the specified number of seconds. This is mostly used to\ndebug concurrency.\n```lua\nsleep(3)\n```\n\n### sock_connect\nCreate a tcp connection.\n```lua\nsock = sock_connect(\"127.0.0.1\", 1337)\n```\n\n### sock_send\nSend data to the socket.\n```lua\nsock_send(sock, \"hello world\")\n```\n\n### sock_recv\nReceive up to 4096 bytes from the socket.\n```lua\nx = sock_recv(sock)\n```\n\n### sock_sendline\nSend a string to the socket. A newline is automatically appended to the string.\n```lua\nsock_sendline(sock, line)\n```\n\n### sock_recvline\nReceive a line from the socket. The line includes the newline.\n```lua\nx = sock_recvline(sock)\n```\n\n### sock_recvall\nReceive all data from the socket until EOF.\n```lua\nx = sock_recvall(sock)\n```\n\n### sock_recvline_contains\nReceive lines from the server until a line contains the needle, then return\nthis line.\n```lua\nx = sock_recvline_contains(sock, needle)\n```\n\n### sock_recvline_regex\nReceive lines from the server until a line matches the regex, then return this\nline.\n```lua\nx = sock_recvline_regex(sock, \"^250 \")\n```\n\n### sock_recvn\nReceive exactly n bytes from the socket.\n```lua\nx = sock_recvn(sock, 4)\n```\n\n### sock_recvuntil\nReceive until the needle is found, then return all data including the needle.\n```lua\nx = sock_recvuntil(sock, needle)\n```\n\n### sock_sendafter\nReceive until the needle is found, then write data to the socket.\n```lua\nsock_sendafter(sock, needle, data)\n```\n\n### sock_newline\nOverwrite the default `\\n` newline.\n```lua\nsock_newline(sock, \"\\r\\n\")\n```\n\n## Configuration\n\nYou can place a config file at `~/.config/authoscope.toml` to set some\ndefaults.\n\n### Global user agent\n\n```toml\n[runtime]\nuser_agent = \"w3m/0.5.3+git20180125\"\n```\n\n### RLIMIT_NOFILE\n\n```toml\n[runtime]\n# requires CAP_SYS_RESOURCE\n# sudo setcap 'CAP_SYS_RESOURCE=+ep' /usr/bin/authoscope\nrlimit_nofile = 64000\n```\n\n## Wrapping python scripts\n\nThe authoscope runtime is still very bare bones, so you might have to shell out\nto your regular python script occasionally. Your wrapper may look like this:\n\n```lua\ndescr = \"example.com\"\n\nfunction verify(user, password)\n    ret = execve(\"./docs/test.py\", {user, password})\n    if last_err() then return end\n\n    if ret == 2 then\n        return \"script signaled an exception\"\n    end\n\n    return ret == 0\nend\n```\n\nYour python script may look like this:\n\n```python\nimport sys\n\ntry:\n    if sys.argv[1] == \"foo\" and sys.argv[2] == \"bar\":\n        # correct credentials\n        sys.exit(0)\n    else:\n        # incorrect credentials\n        sys.exit(1)\nexcept:\n    # signal an exception\n    # this requeues the attempt instead of discarding it\n    sys.exit(2)\n```\n\n# License\n\nGPLv3+\n"
  },
  {
    "path": "ci/smtp/Dockerfile",
    "content": "FROM debian:stretch\nRUN apt-get update -qq \\\n    && apt-get install -yq opensmtpd\nRUN echo \"foo\" > /etc/mailname\nADD smtpd.conf /etc/smtpd.conf\nEXPOSE 25\nCMD [\"/usr/sbin/smtpd\", \"-d\"]\n"
  },
  {
    "path": "ci/smtp/smtpd.conf",
    "content": "# This is the smtpd server system-wide configuration file.\n# See smtpd.conf(5) for more information.\n\n# To accept external mail, replace with: listen on all\nlisten on 0.0.0.0\n\n# If you edit the file, you have to run \"smtpctl update table aliases\"\ntable aliases file:/etc/aliases\n\n# Uncomment the following to accept external mail for domain \"example.org\"\naccept from any for domain \"example.com\" alias <aliases> deliver to mbox\n\n#accept for local alias <aliases> deliver to mbox\naccept for any relay\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# User-friendly check for sphinx-build\nifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)\n$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)\nendif\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) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\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 \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\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\nclean:\n\trm -rf $(BUILDDIR)/*\n\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\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\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\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\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\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\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/ReadtheDocsTemplate.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhc\"\n\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/ReadtheDocsTemplate\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ReadtheDocsTemplate\"\n\t@echo \"# devhelp\"\n\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\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\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\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\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\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\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\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\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\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\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\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\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\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"
  },
  {
    "path": "docs/authoscope.1",
    "content": ".TH AUTHOSCOPE \"1\" \"August 2018\" \"authoscope 0.6.1\" \"User Commands\"\n.SH NAME\nauthoscope \\- scriptable network authentication cracker\n\n.SH SYNOPSIS\n.B authoscope\n[\\fB\\-nVh\\fR] command\n\n.SH DESCRIPTION\nauthoscope is a scriptable network authentication cracker. While the space for\ncommon service bruteforce is already very well saturated, you may still end up\nwriting your own python scripts when testing credentials for web applications.\n\nThe scope of authoscope is specifically cracking custom services. This is done\nby writing scripts that are loaded into a lua runtime. Those scripts represent\na single service and provide a `verify(user, password)` function that returns\neither true or false. Concurrency, progress indication and reporting is\nmagically provided by the authoscope runtime.\n\n.SH OPTIONS\n.TP\n\\fB\\-n\\fR, \\fB\\-\\-workers\\fR <workers>\nThe number of concurrent workers to run.\n.TP\n\\fB\\-o\\fR, \\fB\\-\\-output\\fR <output>\nWrite results to this file.\n.TP\n\\fB\\-v\\fR, \\fB\\-\\-verbose\\fR\nEnable verbose output.\n.TP\n\\fB\\-h\\fR, \\fB\\-\\-help\\fR\nPrints help information.\n.TP\n\\fB\\-V\\fR, \\fB\\-\\-version\\fR\nPrints version information.\n\n.SH SUBCOMMANDS\nPick one of the following subcommands.\n\n.SS Dictionary attack\n.LP\nTry each password for each user with every script.\n.RS\n\\fBauthoscope dict\\fR\n<\\fBusers\\fR>\n<\\fBpasswords\\fR>\n[\\fBscripts\\fR]...\n.RE\n\n.SS Credential confirmation\n.LP\nLoad a list of credentials with the format \\fBuser:password\\fR and verify them\nwith every script.\n.RS\n\\fBauthoscope creds\\fR\n<\\fBcredentials\\fR>\n[\\fBscripts\\fR]...\n.RE\n\n.SS Username enumeration\n.LP\nTakes a list of username and verifies they exist on the system. This is still\nexecuting the \\fBverify\\fR function with two arguments, but the password is set\nto \\fBnil\\fR. You may write a script that can do both by checking the password\nfor nil to detect in which mode the script is executed.\n.RS\n\\fBauthoscope enum\\fR\n<\\fBusers\\fR>\n[\\fBscripts\\fR]...\n.RE\n\n.SS Oneshot\n.LP\nTest a single username-password combination using a specific script. This\ncommand is also useful when developing a new script. If the password argument\nis omitted, the script is executed in enumerate mode. If you want to use this\ncommand in scripts, set \\-x so the exitcode is set to 2 if the credentials are\ninvalid.\n.RS\n\\fBauthoscope oneshot\\fR\n[\\fB\\-x\\fR]\n<\\fBscript\\fR>\n<\\fBuser\\fR>\n[\\fBpassword\\fR]\n\n.SH RUNTIME REFERENCE\nThe authoscope runtime provides a number of functions that can be used to test\ntarget systems.\n\n.SS base64_decode\n.LP\nDecode a base64 string.\n.RS\n.nf\n\\fBbase64_decode(\"ww==\")\\fP\n.fi\n.RE\n\n.SS base64_encode\n.LP\nEncode a binary array with base64.\n.RS\n.nf\n\\fBbase64_encode(\"\\\\x00\\\\xff\")\\fP\n.fi\n.RE\n\n.SS clear_err\n.LP\nClear all recorded errors to prevent a requeue.\n.RS\n.nf\n\\fBif last_err() then\n    clear_err()\n    return false\nelse\n    return true\nend\\fP\n.fi\n.RE\n\n.SS execve\n.LP\nExecute an external program. Returns the exit code.\n.RS\n.nf\n\\fBexecve(\"myprog\", {\"arg1\", \"arg2\", \"--arg\", \"3\"})\\fP\n.fi\n.RE\n\n.SS hex\n.LP\nHex encode a list of bytes.\n.RS\n.nf\n\\fBhex({0x6F, 0x68, 0x61, 0x69, 0x0A, 0x00})\\fR\n.fi\n.RE\n\n.SS hmac_md5\n.LP\nCalculate an hmac with md5. Returns a binary array.\n.RS\n.nf\n\\fBhmac_md5(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS hmac_sha1\n.LP\nCalculate an hmac with sha1. Returns a binary array.\n.RS\n.nf\n\\fBhmac_sha1(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS hmac_sha2_256\n.LP\nCalculate an hmac with sha2_256. Returns a binary array.\n.RS\n.nf\n\\fBhmac_sha2_256(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS hmac_sha2_512\n.LP\nCalculate an hmac with sha2_512. Returns a binary array.\n.RS\n.nf\n\\fBhmac_sha2_512(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS hmac_sha3_256\n.LP\nCalculate an hmac with sha3_256. Returns a binary array.\n.RS\n.nf\n\\fBhmac_sha3_256(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS hmac_sha3_512\n.LP\nCalculate an hmac with sha3_512. Returns a binary array.\n.RS\n.nf\n\\fBhmac_sha3_512(\"secret\", \"my authenticated message\")\\fR\n.fi\n.RE\n\n.SS html_select\n.LP\nParses an html document and returns the first element that matches the css\nselector. The return value is a table with \\fBtext\\fR being the inner text and\n\\fBattrs\\fR being a table of the elements attributes.\n.RS\n.nf\n\\fBcsrf = html_select(html, 'input[name=\"csrf\"]')\ntoken = csrf[\"attrs\"][\"value\"]\\fP\n.fi\n.RE\n\n.SS html_select_list\n.LP\nSame as \\fBhtml_select\\fP but returns all matches instead of the first one.\n.RS\n.nf\n\\fBhtml_select_list(html, 'input[name=\"csrf\"]')\\fP\n.fi\n.RE\n\n.SS http_basic_auth\n.LP\nSends a \\fBGET\\fR request with basic auth. Returns \\fBtrue\\fR if no\n\\fBWWW-Authenticate\\fR header is set and the status code is not \\fB401\\fR.\n.RS\n.nf\n\\fBhttp_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\\fP\n.fi\n.RE\n\n.SS http_mksession\n.LP\nCreate a session object. This is similar to \\fBrequests.Session\\fR in\npython-requests and keeps track of cookies.\n.RS\n.nf\n\\fBsession = http_mksession()\\fP\n.fi\n.RE\n\n.SS http_request\n.LP\nPrepares an http request. The first argument is the session reference and\ncookies from that session are copied into the request. After the request has\nbeen sent, the cookies from the response are copied back into the session.\n\nThe next arguments are the \\fBmethod\\fR, the \\fBurl\\fR and additional options. Please\nnote that you still need to specify an empty table \\fB{}\\fR even if no options are\nset. The following options are available:\n\n.nf\n- \\fBquery\\fR - a map of query parameters that should be set on the url\n- \\fBheaders\\fR - a map of headers that should be set\n- \\fBbasic_auth\\fR - configure the basic auth header with \\fB{\"user, \"password\"}\\fR\n- \\fBuser_agent\\fR - overwrite the default user agent with a string\n- \\fBjson\\fR - the request body that should be json encoded\n- \\fBform\\fR - the request body that should be form encoded\n- \\fBbody\\fR - the raw request body as string\n.fi\n.RS\n.nf\n\\fBreq = http_request(session, 'POST', 'https://httpbin.org/post', {\n    json={\n        user=user,\n        password=password,\n    }\n})\nresp = http_send(req)\nif last_err() then return end\nif resp[\"status\"] ~= 200 then return \"invalid status code\" end\\fP\n.fi\n.RE\n\n.SS http_send\n.LP\nSend the request that has been built with \\fBhttp_request\\fR.\nReturns a table with the following keys:\n\n.nf\n- \\fBstatus\\fR - the http status code\n- \\fBheaders\\fR - a table of headers\n- \\fBtext\\fR - the response body as string\n.fi\n.RS\n.nf\n\\fBreq = http_request(session, 'POST', 'https://httpbin.org/post', {\n    json={\n        user=user,\n        password=password,\n    }\n})\nresp = http_send(req)\nif last_err() then return end\nif resp[\"status\"] ~= 200 then return \"invalid status code\" end\\fP\n.fi\n.RE\n\n.SS json_decode\n.LP\nDecode a lua value from a json string.\n.RS\n.nf\n\\fBjson_decode(\"{\\\\\"data\\\\\":{\\\\\"password\\\\\":\\\\\"fizz\\\\\",\\\\\"user\\\\\":\\\\\"bar\\\\\"},\\\\\"list\\\\\":[1,3,3,7]}\")\\fP\n.fi\n.RE\n\n.SS json_encode\n.LP\nEncode a lua value to a json string. Note that empty tables are encoded to an\nempty object \\fB{}\\fR instead of an empty list \\fB[]\\fR.\n.RS\n.nf\n\\fBx = json_encode({\n    hello=\"world\",\n    almost_one=0.9999,\n    list={1,3,3,7},\n    data={\n        user=user,\n        password=password,\n        empty=nil\n    }\n})\\fP\n.fi\n.RE\n\n.SS last_err\n.LP\nReturns \\fBnil\\fR if no error has been recorded, returns a string otherwise.\n.RS\n.nf\n\\fBif last_err() then return end\\fP\n.fi\n.RE\n\n.SS ldap_bind\n.LP\nConnect to an ldap server and try to authenticate with the given user\n.RS\n.nf\n\\fBldap_bind(\"ldaps://ldap.example.com/\",\n    \"cn=\\\\\"\" .. ldap_escape(user) .. \"\\\\\",ou=users,dc=example,dc=com\", password)\\fP\n.fi\n.RE\n\n.SS ldap_escape\n.LP\nEscape an attribute value in a relative distinguished name.\n.RS\n.nf\n\\fBldap_escape(user)\\fP\n.fi\n.RE\n\n.SS ldap_search_bind\n.LP\nConnect to an ldap server, log into a search user, search for the target user\nand then try to authenticate with the first DN that was returned by the search.\n.RS\n.nf\n\\fBldap_search_bind(\"ldaps://ldap.example.com/\",\n    -- the user we use to find the correct DN\n    \"cn=search_user,ou=users,dc=example,dc=com\", \"searchpw\",\n    -- base DN we search in\n    \"dc=example,dc=com\",\n    -- the user we test\n    user, password)\\fP\n.fi\n.RE\n\n.SS md5\n.LP\nHash a byte array with md5 and return the results as bytes.\n.RS\n.nf\n\\fBhex(md5(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS mysql_connect\n.LP\nConnect to a mysql database and try to authenticate with the provided\ncredentials. Returns a mysql connection on success.\n.RS\n.nf\n\\fBsock = mysql_connect(\"127.0.0.1\", 3306, user, password)\\fP\n.fi\n.RE\n\n.SS mysql_query\n.LP\nRun a query on a mysql connection. The 3rd parameter is for prepared\nstatements.\n.RS\n.nf\n\\fBrows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {\n    foo='magic'\n})\\fP\n.fi\n.RE\n\n.SS print\n.LP\nPrints the value of a variable. Please note that this bypasses the regular\nwriter and may interfer with the progress bar. Only use this for debugging.\n.RS\n.nf\n\\fBprint({\n    data={\n        user=user,\n        password=password\n    }\n})\\fP\n.fi\n.RE\n\n.SS rand\n.LP\nReturns a random \\fBu32\\fP with a minimum and maximum constraint. The return value\ncan be greater or equal to the minimum boundary, and always lower than the\nmaximum boundary. This function has not been reviewed for cryptographic\nsecurity.\n.RS\n.nf\n\\fBrand(0, 256)\\fP\n.fi\n.RE\n\n.SS randombytes\n.LP\nGenerate the specified number of random bytes.\n.RS\n.nf\n\\fBrandombytes(16)\\fP\n.fi\n.RE\n\n.SS sha1\n.LP\nHash a byte array with sha1 and return the results as bytes.\n.RS\n.nf\n\\fBhex(sha1(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS sha2_256\n.LP\nHash a byte array with sha2_256 and return the results as bytes.\n.RS\n.nf\n\\fBhex(sha2_256(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS sha2_512\n.LP\nHash a byte array with sha2_512 and return the results as bytes.\n.RS\n.nf\n\\fBhex(sha2_512(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS sha3_256\n.LP\nHash a byte array with sha3_256 and return the results as bytes.\n.RS\n.nf\n\\fBhex(sha3_256(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS sha3_512\n.LP\nHash a byte array with sha3_512 and return the results as bytes.\n.RS\n.nf\n\\fBhex(sha3_512(\"\\\\x00\\\\xff\"))\\fP\n.fi\n.RE\n\n.SS sleep\n.LP\nPauses the thread for the specified number of seconds. This is mostly used to\ndebug concurrency.\n.RS\n.nf\n\\fBsleep(3)\\fP\n.fi\n.RE\n\n.SS sock_connect\n.LP\nCreate a tcp connection.\n.RS\n.nf\n\\fBsock = sock_connect(\"127.0.0.1\", 1337)\\fP\n.fi\n.RE\n\n.SS sock_send\n.LP\nSend data to the socket.\n.RS\n.nf\n\\fBsock_send(sock, \"hello world\")\\fP\n.fi\n.RE\n\n.SS sock_recv\n.LP\nReceive up to 4096 bytes from the socket.\n.RS\n.nf\n\\fBx = sock_recv(sock)\\fP\n.fi\n.RE\n\n.SS sock_sendline\n.LP\nSend a string to the socket. A newline is automatically appended to the string.\n.RS\n.nf\n\\fBsock_sendline(sock, line)\\fP\n.fi\n.RE\n\n.SS sock_recvline\n.LP\nReceive a line from the socket. The line includes the newline.\n.RS\n.nf\n\\fBx = sock_recvline(sock)\\fP\n.fi\n.RE\n\n.SS sock_recvall\n.LP\nReceive all data from the socket until EOF.\n.RS\n.nf\n\\fBx = sock_recvall(sock)\\fP\n.fi\n.RE\n\n.SS sock_recvline_contains\n.LP\nReceive lines from the server until a line contains the needle, then return\nthis line.\n.RS\n.nf\n\\fBx = sock_recvline_contains(sock, needle)\\fP\n.fi\n.RE\n\n.SS sock_recvline_regex\n.LP\nReceive lines from the server until a line matches the regex, then return this\nline.\n.RS\n.nf\n\\fBx = sock_recvline_regex(sock, \"^250 \")\\fP\n.fi\n.RE\n\n.SS sock_recvn\n.LP\nReceive exactly n bytes from the socket.\n.RS\n.nf\n\\fBx = sock_recvn(sock, 4)\\fP\n.fi\n.RE\n\n.SS sock_recvuntil\n.LP\nReceive until the needle is found, then return all data including the needle.\n.RS\n.nf\n\\fBx = sock_recvuntil(sock, needle)\\fP\n.fi\n.RE\n\n.SS sock_sendafter\n.LP\nReceive until the needle is found, then write data to the socket.\n.RS\n.nf\n\\fBsock_sendafter(sock, needle, data)\\fP\n.fi\n.RE\n\n.SS sock_newline\n.LP\nOverwrite the default `\\\\n` newline.\n.RS\n.nf\n\\fBsock_newline(sock, \"\\\\r\\\\n\")\\fP\n.fi\n.RE\n\n.SH SECURITY\nTo report a security issue please contact kpcyrd on ircs://irc.hackint.org.\n\n.SH \"SEE ALSO\"\nThe documentation at lua.org.\n\n.SH AUTHORS\nThis program was originally written and is currently maintained by kpcyrd.\nBugs and patches are welcome on github:\n.LP\n.RS\n.I https://github.com/kpcyrd/authoscope\n.RE\n"
  },
  {
    "path": "docs/conf.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Read the Docs Template documentation build configuration file, created by\n# sphinx-quickstart on Tue Aug 26 14:19:49 2014.\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\nimport sys\nimport os\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#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#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 of source filenames.\nsource_suffix = '.rst'\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'authoscope'\ncopyright = u'2018, kpcyrd'\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.\n#version = '1.0'\n# The full version, including alpha/beta/rc tags.\n#release = '1.0'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = 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#today = ''\n# Else, today_fmt is used as the format for a strftime call.\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.\nexclude_patterns = ['_build']\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\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#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#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\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.\nhtml_theme = 'default'\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#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.  If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\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#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\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\".\n#html_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#html_extra_path = []\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\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#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'ReadtheDocsTemplatedoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\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  ('index', 'authoscope.tex', u'authoscope Documentation',\n   u'kpcyrd', '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#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\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 = [\n    ('man', 'authoscope', u'Scriptable network authentication cracker',\n     [u'kpcyrd'], 1)\n]\n\n# If true, show URL addresses after external links.\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  ('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation',\n   u'Read the Docs', 'ReadtheDocsTemplate', 'One line description of project.',\n   'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False\n"
  },
  {
    "path": "docs/config.rst",
    "content": "Configuration\n=============\n\nYou can place a config file at ``~/.config/authoscope.toml`` to set some defaults.\n\nGlobal user agent\n-----------------\n\n.. code-block:: toml\n\n    [runtime]\n    user_agent = \"w3m/0.5.3+git20180125\"\n\nRLIMIT_NOFILE\n-------------\n\n.. code-block:: toml\n\n    [runtime]\n    # requires CAP_SYS_RESOURCE\n    # sudo setcap 'CAP_SYS_RESOURCE=+ep' /usr/bin/authoscope\n    rlimit_nofile = 64000\n"
  },
  {
    "path": "docs/index.rst",
    "content": "authoscope\n==========\n\nauthoscope (formerly badtouch) is a scriptable network authentication cracker.\nWhile the space for common service bruteforce is already very_ well_\nsaturated_, you may still end up writing your own python scripts when testing\ncredentials for web applications.\n\n.. _very: https://nmap.org/ncrack/\n.. _well: https://github.com/vanhauser-thc/thc-hydra\n.. _saturated: https://github.com/jmk-foofus/medusa\n\nThe scope of authoscope is specifically cracking custom services. This is done\nby writing scripts that are loaded into a lua runtime. Those scripts represent\na single service and provide a ``verify(user, password)`` function that returns\neither true or false. Concurrency, progress indication and reporting is\nmagically provided by the authoscope runtime.\n\n.. image:: https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ.png\n   :target: https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ\n\nGetting Started\n---------------\n\n.. toctree::\n   :maxdepth: 3\n   :glob:\n\n   install\n   usage\n   scripting\n   config\n"
  },
  {
    "path": "docs/install.rst",
    "content": "Installation\n============\n\nIf available, please prefer the package shipped by your linux distribution.\n\nArchlinux\n---------\n\n.. code-block:: bash\n\n    $ pacman -S authoscope\n\nMac OSX\n-------\n\n.. code-block:: bash\n\n    $ brew install authoscope\n\nDocker\n------\n\n.. code-block:: bash\n\n    $ docker run --rm kpcyrd/authoscope --help\n\nSource\n------\n\nTo build from source, make sure you have rust_ and ``libssl-dev`` installed.\n\n.. _rust: https://rustup.rs/\n\n.. code-block:: bash\n\n    $ git clone https://github.com/kpcyrd/authoscope\n    $ cd authoscope\n    $ cargo build\n"
  },
  {
    "path": "docs/make.bat",
    "content": "@ECHO OFF\r\n\r\nREM Command file for Sphinx documentation\r\n\r\nif \"%SPHINXBUILD%\" == \"\" (\r\n\tset SPHINXBUILD=sphinx-build\r\n)\r\nset BUILDDIR=_build\r\nset ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .\r\nset I18NSPHINXOPTS=%SPHINXOPTS% .\r\nif NOT \"%PAPER%\" == \"\" (\r\n\tset ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%\r\n\tset I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%\r\n)\r\n\r\nif \"%1\" == \"\" goto help\r\n\r\nif \"%1\" == \"help\" (\r\n\t:help\r\n\techo.Please use `make ^<target^>` where ^<target^> is one of\r\n\techo.  html       to make standalone HTML files\r\n\techo.  dirhtml    to make HTML files named index.html in directories\r\n\techo.  singlehtml to make a single large HTML file\r\n\techo.  pickle     to make pickle files\r\n\techo.  json       to make JSON files\r\n\techo.  htmlhelp   to make HTML files and a HTML help project\r\n\techo.  qthelp     to make HTML files and a qthelp project\r\n\techo.  devhelp    to make HTML files and a Devhelp project\r\n\techo.  epub       to make an epub\r\n\techo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\r\n\techo.  text       to make text files\r\n\techo.  man        to make manual pages\r\n\techo.  texinfo    to make Texinfo files\r\n\techo.  gettext    to make PO message catalogs\r\n\techo.  changes    to make an overview over all changed/added/deprecated items\r\n\techo.  xml        to make Docutils-native XML files\r\n\techo.  pseudoxml  to make pseudoxml-XML files for display purposes\r\n\techo.  linkcheck  to check all external links for integrity\r\n\techo.  doctest    to run all doctests embedded in the documentation if enabled\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"clean\" (\r\n\tfor /d %%i in (%BUILDDIR%\\*) do rmdir /q /s %%i\r\n\tdel /q /s %BUILDDIR%\\*\r\n\tgoto end\r\n)\r\n\r\n\r\n%SPHINXBUILD% 2> nul\r\nif errorlevel 9009 (\r\n\techo.\r\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\r\n\techo.installed, then set the SPHINXBUILD environment variable to point\r\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\r\n\techo.may add the Sphinx directory to PATH.\r\n\techo.\r\n\techo.If you don't have Sphinx installed, grab it from\r\n\techo.http://sphinx-doc.org/\r\n\texit /b 1\r\n)\r\n\r\nif \"%1\" == \"html\" (\r\n\t%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/html.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"dirhtml\" (\r\n\t%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"singlehtml\" (\r\n\t%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"pickle\" (\r\n\t%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can process the pickle files.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"json\" (\r\n\t%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can process the JSON files.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"htmlhelp\" (\r\n\t%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can run HTML Help Workshop with the ^\r\n.hhp project file in %BUILDDIR%/htmlhelp.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"qthelp\" (\r\n\t%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can run \"qcollectiongenerator\" with the ^\r\n.qhcp project file in %BUILDDIR%/qthelp, like this:\r\n\techo.^> qcollectiongenerator %BUILDDIR%\\qthelp\\complexity.qhcp\r\n\techo.To view the help file:\r\n\techo.^> assistant -collectionFile %BUILDDIR%\\qthelp\\complexity.ghc\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"devhelp\" (\r\n\t%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"epub\" (\r\n\t%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The epub file is in %BUILDDIR%/epub.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latex\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; the LaTeX files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latexpdf\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tcd %BUILDDIR%/latex\r\n\tmake all-pdf\r\n\tcd %BUILDDIR%/..\r\n\techo.\r\n\techo.Build finished; the PDF files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latexpdfja\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tcd %BUILDDIR%/latex\r\n\tmake all-pdf-ja\r\n\tcd %BUILDDIR%/..\r\n\techo.\r\n\techo.Build finished; the PDF files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"text\" (\r\n\t%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The text files are in %BUILDDIR%/text.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"man\" (\r\n\t%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The manual pages are in %BUILDDIR%/man.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"texinfo\" (\r\n\t%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"gettext\" (\r\n\t%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The message catalogs are in %BUILDDIR%/locale.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"changes\" (\r\n\t%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.The overview file is in %BUILDDIR%/changes.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"linkcheck\" (\r\n\t%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Link check complete; look for any errors in the above output ^\r\nor in %BUILDDIR%/linkcheck/output.txt.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"doctest\" (\r\n\t%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Testing of doctests in the sources finished, look at the ^\r\nresults in %BUILDDIR%/doctest/output.txt.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"xml\" (\r\n\t%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The XML files are in %BUILDDIR%/xml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"pseudoxml\" (\r\n\t%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.\r\n\tgoto end\r\n)\r\n\r\n:end\r\n"
  },
  {
    "path": "docs/man.rst",
    "content": "authoscope\n========\n\nauthoscope (formerly badtouch) is a scriptable network authentication cracker.\nWhile the space for common service bruteforce is already very well saturated,\nyou may still end up writing your own python scripts when testing credentials\nfor web applications.\n\nThe scope of authoscope is specifically cracking custom services. This is done\nby writing scripts that are loaded into a lua runtime. Those scripts represent\na single service and provide a ``verify(user, password)`` function that returns\neither true or false. Concurrency, progress indication and reporting is\nmagically provided by the authoscope runtime.\n\n.. toctree::\n   :maxdepth: 3\n   :glob:\n\n   usage\n   scripting\n   config\n"
  },
  {
    "path": "docs/scripting.rst",
    "content": "Scripting\n=========\n\nA simple script could look like this:\n\n.. code-block:: lua\n\n    descr = \"example.com\"\n\n    function verify(user, password)\n        session = http_mksession()\n\n        -- get csrf token\n        req = http_request(session, 'GET', 'https://example.com/login', {})\n        resp = http_send(req)\n        if last_err() then return end\n\n        -- parse token from html\n        html = resp['text']\n        csrf = html_select(html, 'input[name=\"csrf\"]')\n        token = csrf[\"attrs\"][\"value\"]\n\n        -- send login\n        req = http_request(session, 'POST', 'https://example.com/login', {\n            form={\n                user=user,\n                password=password,\n                csrf=token\n            }\n        })\n        resp = http_send(req)\n        if last_err() then return end\n\n        -- search response for successful login\n        html = resp['text']\n        return html:find('Login successful') ~= nil\n    end\n\nPlease see the reference and [examples](/scripts) for all available functions.\nKeep in mind that you can use `print(x)` and `authoscope oneshot` to debug your\nscript.\n\nbase64_decode\n-------------\n\nDecode a base64 string.\n\n.. code-block:: lua\n\n    base64_decode(\"ww==\")\n\nbase64_encode\n-------------\n\nEncode a binary array with base64.\n\n.. code-block:: lua\n\n    base64_encode(\"\\x00\\xff\")\n\nclear_err\n---------\n\nClear all recorded errors to prevent a requeue.\n\n.. code-block:: lua\n\n    if last_err() then\n        clear_err()\n        return false\n    else\n        return true\n    end\n\nexecve\n------\n\nExecute an external program. Returns the exit code.\n\n.. code-block:: lua\n\n    execve(\"myprog\", {\"arg1\", \"arg2\", \"--arg\", \"3\"})\n\nhex\n---\n\nHex encode a list of bytes.\n\n.. code-block:: lua\n\n    hex(\"\\x6F\\x68\\x61\\x69\\x0A\\x00\")\n\nhmac_md5\n--------\n\nCalculate an hmac with md5. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_md5(\"secret\", \"my authenticated message\")\n\nhmac_sha1\n---------\n\nCalculate an hmac with sha1. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_sha1(\"secret\", \"my authenticated message\")\n\nhmac_sha2_256\n-------------\n\nCalculate an hmac with sha2_256. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_sha2_256(\"secret\", \"my authenticated message\")\n\nhmac_sha2_512\n-------------\n\nCalculate an hmac with sha2_512. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_sha2_512(\"secret\", \"my authenticated message\")\n\nhmac_sha3_256\n-------------\n\nCalculate an hmac with sha3_256. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_sha3_256(\"secret\", \"my authenticated message\")\n\nhmac_sha3_512\n-------------\n\nCalculate an hmac with sha3_512. Returns a binary array.\n\n.. code-block:: lua\n\n    hmac_sha3_512(\"secret\", \"my authenticated message\")\n\nhtml_select\n-----------\n\nParses an html document and returns the first element that matches the css\nselector. The return value is a table with ``text`` being the inner text and\n``attrs`` being a table of the elements attributes.\n\n.. code-block:: lua\n\n    csrf = html_select(html, 'input[name=\"csrf\"]')\n    token = csrf[\"attrs\"][\"value\"]\n\nhtml_select_list\n----------------\n\nSame as html_select_ but returns all matches instead of the\nfirst one.\n\n.. code-block:: lua\n\n    html_select_list(html, 'input[name=\"csrf\"]')\n\nhttp_basic_auth\n---------------\n\nSends a ``GET`` request with basic auth. Returns ``true`` if no ``WWW-Authenticate``\nheader is set and the status code is not ``401``.\n\n.. code-block:: lua\n\n    http_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\n\nhttp_mksession\n--------------\n\nCreate a session object. This is similar to ``requests.Session`` in\npython-requests and keeps track of cookies.\n\n.. code-block:: lua\n\n    session = http_mksession()\n\nhttp_request\n------------\n\nPrepares an http request. The first argument is the session reference and\ncookies from that session are copied into the request. After the request has\nbeen sent, the cookies from the response are copied back into the session.\n\nThe next arguments are the ``method``, the ``url`` and additional options. Please\nnote that you still need to specify an empty table ``{}`` even if no options are\nset. The following options are available:\n\n- ``query`` - a map of query parameters that should be set on the url\n- ``headers`` - a map of headers that should be set\n- ``basic_auth`` - configure the basic auth header with ``{\"user, \"password\"}``\n- ``user_agent`` - overwrite the default user agent with a string\n- ``json`` - the request body that should be json encoded\n- ``form`` - the request body that should be form encoded\n- ``body`` - the raw request body as string\n\n.. code-block:: lua\n\n    req = http_request(session, 'POST', 'https://httpbin.org/post', {\n        json={\n            user=user,\n            password=password,\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n    if resp[\"status\"] ~= 200 then return \"invalid status code\" end\n\nhttp_send\n---------\n\nSend the request that has been built with http_request_. Returns a table with\nthe following keys:\n\n- ``status`` - the http status code\n- ``headers`` - a table of headers\n- ``text`` - the response body as string\n\n.. code-block:: lua\n\n    req = http_request(session, 'POST', 'https://httpbin.org/post', {\n        json={\n            user=user,\n            password=password,\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n    if resp[\"status\"] ~= 200 then return \"invalid status code\" end\n\njson_decode\n-----------\n\nDecode a lua value from a json string.\n\n.. code-block:: lua\n\n    json_decode(\"{\\\"data\\\":{\\\"password\\\":\\\"fizz\\\",\\\"user\\\":\\\"bar\\\"},\\\"list\\\":[1,3,3,7]}\")\n\njson_encode\n-----------\n\nEncode a lua value to a json string. Note that empty tables are encoded to an\nempty object ``{}`` instead of an empty list ``[]``.\n\n.. code-block:: lua\n\n    x = json_encode({\n        hello=\"world\",\n        almost_one=0.9999,\n        list={1,3,3,7},\n        data={\n            user=user,\n            password=password,\n            empty=nil\n        }\n    })\n\nlast_err\n--------\n\nReturns ``nil`` if no error has been recorded, returns a string otherwise.\n\n.. code-block:: lua\n\n    if last_err() then return end\n\nldap_bind\n---------\n\nConnect to an ldap server and try to authenticate with the given user.\n\n.. code-block:: lua\n\n    ldap_bind(\"ldaps://ldap.example.com/\",\n        \"cn=\\\"\" .. ldap_escape(user) .. \"\\\",ou=users,dc=example,dc=com\", password)\n\nldap_escape\n-----------\n\nEscape an attribute value in a relative distinguished name.\n\n.. code-block:: lua\n\n    ldap_escape(user)\n\nldap_search_bind\n----------------\n\nConnect to an ldap server, log into a search user, search for the target user\nand then try to authenticate with the first DN that was returned by the search.\n\n.. code-block:: lua\n\n    ldap_search_bind(\"ldaps://ldap.example.com/\",\n        -- the user we use to find the correct DN\n        \"cn=search_user,ou=users,dc=example,dc=com\", \"searchpw\",\n        -- base DN we search in\n        \"dc=example,dc=com\",\n        -- the user we test\n        user, password)\n\nmd5\n---\n\nHash a byte array with md5 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(md5(\"\\x00\\xff\"))\n\nmysql_connect\n-------------\n\nConnect to a mysql database and try to authenticate with the provided\ncredentials. Returns a mysql connection on success.\n\n.. code-block:: lua\n\n    sock = mysql_connect(\"127.0.0.1\", 3306, user, password)\n\nmysql_query\n-----------\n\nRun a query on a mysql connection. The 3rd parameter is for prepared\nstatements.\n\n.. code-block:: lua\n\n    rows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {\n        foo='magic'\n    })\n\nprint\n-----\n\nPrints the value of a variable. Please note that this bypasses the regular\nwriter and may interfer with the progress bar. Only use this for debugging.\n\n.. code-block:: lua\n\n    print({\n        data={\n            user=user,\n            password=password\n        }\n    })\n\nrand\n----\n\nReturns a random ``u32`` with a minimum and maximum constraint. The return\nvalue can be greater or equal to the minimum boundary, and always lower than\nthe maximum boundary. This function has not been reviewed for cryptographic\nsecurity.\n\n.. code-block:: lua\n\n    rand(0, 256)\n\nrandombytes\n-----------\n\nGenerate the specified number of random bytes.\n\n.. code-block:: lua\n\n    randombytes(16)\n\nsha1\n----\n\nHash a byte array with sha1 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(sha1(\"\\x00\\xff\"))\n\nsha2_256\n--------\n\nHash a byte array with sha2_256 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(sha2_256(\"\\x00\\xff\"))\n\nsha2_512\n--------\n\nHash a byte array with sha2_512 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(sha2_512(\"\\x00\\xff\"))\n\nsha3_256\n--------\n\nHash a byte array with sha3_256 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(sha3_256(\"\\x00\\xff\"))\n\nsha3_512\n--------\n\nHash a byte array with sha3_512 and return the results as bytes.\n\n.. code-block:: lua\n\n    hex(sha3_512(\"\\x00\\xff\"))\n\nsleep\n-----\n\nPauses the thread for the specified number of seconds. This is mostly used to\ndebug concurrency.\n\n.. code-block:: lua\n\n    sleep(3)\n\nsock_connect\n------------\n\nCreate a tcp connection.\n\n.. code-block:: lua\n\n    sock = sock_connect(\"127.0.0.1\", 1337)\n\nsock_send\n---------\n\nSend data to the socket.\n\n.. code-block:: lua\n\n    sock_send(sock, \"hello world\")\n\nsock_recv\n---------\n\nReceive up to 4096 bytes from the socket.\n\n.. code-block:: lua\n\n    x = sock_recv(sock)\n\nsock_sendline\n-------------\n\nSend a string to the socket. A newline is automatically appended to the string.\n\n.. code-block:: lua\n\n    sock_sendline(sock, line)\n\nsock_recvline\n-------------\n\nReceive a line from the socket. The line includes the newline.\n\n.. code-block:: lua\n\n    x = sock_recvline(sock)\n\nsock_recvall\n------------\n\nReceive all data from the socket until EOF.\n\n.. code-block:: lua\n\n    x = sock_recvall(sock)\n\nsock_recvline_contains\n----------------------\n\nReceive lines from the server until a line contains the needle, then return\nthis line.\n\n.. code-block:: lua\n\n    x = sock_recvline_contains(sock, needle)\n\nsock_recvline_regex\n-------------------\n\nReceive lines from the server until a line matches the regex, then return this\nline.\n\n.. code-block:: lua\n\n    x = sock_recvline_regex(sock, \"^250 \")\n\nsock_recvn\n----------\n\nReceive exactly n bytes from the socket.\n\n.. code-block:: lua\n\n    x = sock_recvn(sock, 4)\n\nsock_recvuntil\n--------------\n\nReceive until the needle is found, then return all data including the needle.\n\n.. code-block:: lua\n\n    x = sock_recvuntil(sock, needle)\n\nsock_sendafter\n--------------\n\nReceive until the needle is found, then write data to the socket.\n\n.. code-block:: lua\n\n    sock_sendafter(sock, needle, data)\n\nsock_newline\n------------\n\nOverwrite the default `\\n` newline.\n\n.. code-block:: lua\n\n    sock_newline(sock, \"\\r\\n\")\n\nWrapping python scripts\n-----------------------\n\nThe authoscope runtime is still very bare bones, so you might have to shell\nout to your regular python script occasionally. Your wrapper may look like this:\n\n.. code-block:: lua\n\n    descr = \"example.com\"\n\n    function verify(user, password)\n        ret = execve(\"./docs/test.py\", {user, password})\n        if last_err() then return end\n\n        if ret == 2 then\n            return \"script signaled an exception\"\n        end\n\n        return ret == 0\n    end\n\nYour python script may look like this:\n\n.. code-block:: python\n\n    import sys\n\n    try:\n        if sys.argv[1] == \"foo\" and sys.argv[2] == \"bar\":\n            # correct credentials\n            sys.exit(0)\n        else:\n            # incorrect credentials\n            sys.exit(1)\n    except:\n        # signal an exception\n        # this requeues the attempt instead of discarding it\n        sys.exit(2)\n"
  },
  {
    "path": "docs/test.sh",
    "content": "#!/bin/sh\necho $2 | grep -q \"buzz\"\n"
  },
  {
    "path": "docs/usage.rst",
    "content": "Usage\n========\n\nOptions\n-------\n\n.. code-block:: text\n\n    -n, --workers <workers>     The number of concurrent workers to run.\n    -o, --output <output>       Write results to this file.\n    -v, --verbose               Enable verbose output.\n    -h, --help                  Prints help information.\n    -V, --version               Prints version information.\n\nDictionary attack\n-----------------\n\nTry each password for each user with every script.\n\n.. code-block:: bash\n\n    authoscope dict <users> <passwords> [scripts]...\n\nCredential confirmation\n-----------------------\n\nLoad a list of credentials with the format ``user:password`` and verify them\nwith every script.\n\n.. code-block:: bash\n\n    authoscope creds <credentials> [scripts]...\n\nUsername enumeration\n--------------------\n\nTakes a list of username and verifies they exist on the system. This is still\nexecuting the ``verify`` function with two arguments, but the password is set\nto ``nil``. You may write a script that can do both by checking the password\nfor nil to detect in which mode the script is executed.\n\n.. code-block:: bash\n\n    authoscope enum <users> [scripts]...\n\nOneshot\n-------\n\nTest a single username-password combination using a specific script. This\ncommand is also useful when developing a new script. If the password argument\nis omitted, the script is executed in enumerate mode. If you want to use this\ncommand in scripts, set ``-x`` so the exitcode is set to 2 if the credentials\nare invalid.\n\n.. code-block:: bash\n\n    authoscope oneshot [-x] <script> <user> [password]\n"
  },
  {
    "path": "examples/README.md",
    "content": "These are small programs to benchmark some individual components.\n"
  },
  {
    "path": "examples/load-creds.rs",
    "content": "use std::env;\nuse std::time::Instant;\nuse authoscope::errors::*;\n\nfn main() -> Result<()> {\n    env_logger::init();\n\n    let path = env::args().nth(1)\n        .context(\"Missing argument\")?;\n\n    let start = Instant::now();\n\n    let creds = authoscope::utils::load_combolist(&path)\n        .context(\"Failed to load creds\")?;\n\n    let elapsed = start.elapsed();\n    let average = elapsed / creds.len() as u32;\n    println!(\"loaded {} records in {}, on average {}\",\n            creds.len(),\n            humantime::format_duration(elapsed),\n            humantime::format_duration(average),\n    );\n\n    Ok(())\n}\n"
  },
  {
    "path": "scripts/basic_auth.lua",
    "content": "descr = \"basic auth httpbin.org\"\n\nfunction verify(user, password)\n    return http_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\nend\n"
  },
  {
    "path": "scripts/benchmark.lua",
    "content": "descr = \"for benchmarking only\"\n\nfunction verify(user, password)\n    return false\nend\n"
  },
  {
    "path": "scripts/binary.lua",
    "content": "descr = \"binary\"\n\nfunction verify(user, password)\n    print(\"\\x00\\xff\")\n    print(hex(\"\\x00\\xff\"))\n    print(base64_encode(md5(\"\\x00\\xff\")))\n\n    return true\nend\n"
  },
  {
    "path": "scripts/cookies.lua",
    "content": "descr = \"http cookies\"\n\nfunction verify(user, password)\n    session = http_mksession()\n\n    -- set cookies\n    req = http_request(session, 'GET', 'https://httpbin.org/cookies/set', {\n        query={\n            fizz='buzz',\n            foo='; as=df'\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n\n    -- print(resp)\n    -- print(resp[\"headers\"][\"set-cookie\"])\n\n    -- check cookies have been setup\n    -- TODO: removing the {} causes a segfault\n    req = http_request(session, 'GET', 'https://httpbin.org/cookies', {})\n    resp = http_send(req)\n    if last_err() then return end\n    if resp['status'] ~= 200 then return 'invalid status code: ' .. resp['status'] end\n\n    json = json_decode(resp['text'])\n    if last_err() then return end\n    -- print(json)\n\n    if json['cookies']['foo'] ~= '; as=df' then\n        return 'Unexpected value for foo cookie'\n    end\n\n    if json['cookies']['fizz'] ~= 'buzz' then\n        return 'Unexpected value for fizz cookie'\n    end\n\n    return true\nend\n"
  },
  {
    "path": "scripts/error.lua",
    "content": "descr = \"always error\"\n\nfunction verify(user, password)\n    return \"this is an error\"\nend\n"
  },
  {
    "path": "scripts/execve.lua",
    "content": "descr = \"exec test.sh\"\n\nfunction verify(user, password)\n    return execve(\"./docs/test.sh\", {user, password}) == 0\nend\n"
  },
  {
    "path": "scripts/false.lua",
    "content": "descr = \"always false\"\n\nfunction verify(user, password)\n    return false\nend\n"
  },
  {
    "path": "scripts/http.lua",
    "content": "descr = \"http\"\n\nfunction verify(user, password)\n    session = http_mksession()\n\n    -- set cookies\n    req = http_request(session, 'GET', 'https://httpbin.org/anything', {\n        basic_auth={\"user\", \"password\"},\n        user_agent=\"some-agent/0.1\",\n        headers={\n            foo=\"bar\"\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n\n    json = json_decode(resp['text'])\n    if last_err() then return end\n    print(json)\n\n    return false\nend\n"
  },
  {
    "path": "scripts/json.lua",
    "content": "descr = \"json\"\n\nfunction verify(user, password)\n    x = json_encode({\n        hello=\"world\",\n        almost_one=0.9999,\n        list={1,3,3,7},\n        data={\n            user=user,\n            password=password,\n            empty=nil\n        }\n    })\n    print(x)\n\n    y = json_decode(x)\n    print(y)\n    print(y[\"data\"][\"user\"])\n\n    return true\nend\n\n"
  },
  {
    "path": "scripts/ldap.lua",
    "content": "descr = \"ldap\"\n\nfunction verify(user, password)\n    return ldap_bind(\"ldaps://ldap.example.com/\",\n        \"cn=\\\"\" .. ldap_escape(user) .. \"\\\",ou=users,dc=example,dc=com\", password)\nend\n"
  },
  {
    "path": "scripts/ldap_search.lua",
    "content": "descr = \"ldap w/ search\"\n\nfunction verify(user, password)\n    return ldap_search_bind(\"ldaps://ldap.example.com/\",\n        -- the user we use to find the correct DN\n        \"cn=search_user,ou=users,dc=example,dc=com\", \"searchpw\",\n        -- base DN we search in\n        \"dc=example,dc=com\",\n        -- the user we test\n        user, password)\nend\n"
  },
  {
    "path": "scripts/mysql-connect.lua",
    "content": "descr = \"local mysql\"\n\nfunction verify(user, password)\n    mysql_connect(\"127.0.0.1\", 3306, user, password)\n\n    if last_err() then\n        clear_err()\n        return false\n    else\n        return true\n    end\nend\n"
  },
  {
    "path": "scripts/mysql-query.lua",
    "content": "descr = \"local mysql query\"\n\nfunction verify(user, password)\n    sock = mysql_connect(\"127.0.0.1\", 3306, \"root\", \"my-secret-pw\")\n    if last_err() then return end\n\n    rows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {\n        foo='magic'\n    })\n    if last_err() then return end\n\n    if rows[1] then\n        print(rows[1])\n        return true\n    else\n        return false\n    end\nend\n"
  },
  {
    "path": "scripts/post.lua",
    "content": "descr = \"http post\"\n\nfunction verify(user, password)\n    session = http_mksession()\n\n    -- send login\n    req = http_request(session, 'POST', 'https://httpbin.org/post', {\n        json={\n            user=user,\n            password=password,\n        }\n    })\n    resp = http_send(req)\n    if last_err() then return end\n    if resp[\"status\"] ~= 200 then return \"invalid status code\" end\n\n    json = json_decode(resp['text'])\n    if last_err() then return end\n    print(json)\n\n    return true\nend\n"
  },
  {
    "path": "scripts/print.lua",
    "content": "descr = \"print\"\n\nfunction b64u(s)\n    s = s:gsub('%=', '')\n    s = s:gsub('%+', '-')\n    s = s:gsub('%/', '_')\n    return s\nend\n\nfunction verify(user, password)\n    print(\"user=\".. user ..\", password=\" .. password)\n    -- this is buggy with hlua 0.4.1\n    print({user, password})\n    print(b64u('as=+/=+/=+/df'))\n    print({\n        data={\n            user=user,\n            password=password\n        }\n    })\n    return true\nend\n"
  },
  {
    "path": "scripts/random-errors.lua",
    "content": "descr = \"random errors\"\n\nfunction verify(user, password)\n    if rand(0, 100) < 1 then\n        return \"random error\"\n    end\n\n    return false\nend\n"
  },
  {
    "path": "scripts/random.lua",
    "content": "descr = \"random\"\n\nfunction verify(user, password)\n    x = rand(0, 10000)\n    return x >= 9999\nend\n"
  },
  {
    "path": "scripts/sleep.lua",
    "content": "descr = \"sleepy zZz\"\n\nfunction verify(user, password)\n    sleep(1)\n    return true\nend\n"
  },
  {
    "path": "scripts/smtp.lua",
    "content": "descr = \"smtp enum\"\n\nfunction verify(user, password)\n    -- enumeration only, password is ignored\n    sock = sock_connect(\"127.0.0.1\", 25)\n    if last_err() then return end\n    sock_newline(sock, \"\\r\\n\")\n\n    -- get the banner\n    sock_recvline(sock)\n    if last_err() then return end\n\n    -- send ehlo\n    sock_sendline(sock, \"ehlo localhost\")\n    if last_err() then return end\n\n    -- read extensions\n    sock_recvline_regex(sock, \"^250 \")\n    if last_err() then return end\n\n    -- start delivering an email\n    sock_sendline(sock, \"MAIL FROM:<root>\")\n    if last_err() then return end\n\n    -- read reply\n    sock_recvline(sock)\n    if last_err() then return end\n    -- TODO: verify starts with \"250 \"\n\n    -- probe for user\n    sock_sendline(sock, \"RCPT TO:<\" .. user .. \">\")\n    if last_err() then return end\n\n    -- read reply\n    reply = sock_recvn(sock, 1)\n    if last_err() then return end\n\n    -- check it was successful\n    return reply == \"2\"\nend\n"
  },
  {
    "path": "scripts/str-find.lua",
    "content": "descr = \"str-find\"\n\nfunction verify(user, password)\n    text = \"You are currently logged in as 'foo', want to log out?\"\n    return text:find(user) ~= nil\nend\n"
  },
  {
    "path": "scripts/true.lua",
    "content": "descr = \"always true\"\n\nfunction verify(user, password)\n    return true\nend\n"
  },
  {
    "path": "src/args.rs",
    "content": "use crate::errors::*;\nuse std::io::stdout;\nuse std::path::PathBuf;\nuse structopt::StructOpt;\nuse structopt::clap::{AppSettings, Shell};\n\n#[derive(Debug, StructOpt)]\n#[structopt(global_settings = &[AppSettings::ColoredHelp])]\npub struct Args {\n    /// Verbose output\n    #[structopt(short=\"v\", long=\"verbose\",\n                global=true, parse(from_occurrences))]\n    pub verbose: u8,\n    /// Concurrent workers\n    #[structopt(short = \"n\", long = \"workers\", default_value = \"16\")]\n    pub workers: usize,\n    /// Write results to file\n    #[structopt(short = \"o\", long = \"output\")]\n    pub output: Option<String>,\n    #[structopt(subcommand)]\n    pub subcommand: SubCommand,\n}\n\n#[derive(Debug, StructOpt)]\npub enum SubCommand {\n    /// For each user try every password from a dictionary/wordlist\n    Dict(Dict),\n    /// Run a credential stuffing attack with a combolist\n    Combo(Combo),\n    /// For each user enumerate if an account exists with that name/email\n    Enum(Enum),\n    /// Run a script with a single username and password\n    Run(Run),\n    /// Verify a given input file is properly encoded and all entries have valid formatting\n    Fsck(Fsck),\n    Completions(Completions),\n}\n\n#[derive(Debug, StructOpt)]\npub struct Dict {\n    /// Username list path\n    pub users_path: PathBuf,\n    /// Password list path\n    pub passwords_path: PathBuf,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Combo {\n    /// Path to combolist\n    pub path: PathBuf,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Enum {\n    /// Username list path\n    pub users: String,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Run {\n    /// Script to run\n    pub script: String,\n    /// Username to test\n    pub user: String,\n    /// Password to test\n    pub password: Option<String>,\n    /// Set the exitcode to 2 if the credentials are invalid\n    #[structopt(short = \"x\", long = \"exitcode\")]\n    pub exitcode: bool,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Fsck {\n    /// Do not show invalid lines\n    #[structopt(short = \"q\", long = \"quiet\")]\n    pub quiet: bool,\n    /// Do not show valid lines\n    #[structopt(short = \"s\", long = \"silent\")]\n    pub silent: bool,\n    /// Require one colon per line\n    #[structopt(short = \"c\", long = \"colon\")]\n    pub require_colon: bool,\n    /// Files to read\n    pub paths: Vec<String>,\n}\n\n/// Generate shell completions\n#[derive(Debug, StructOpt)]\npub struct Completions {\n    #[structopt(possible_values=&Shell::variants())]\n    pub shell: Shell,\n}\n\nimpl Completions {\n    pub fn gen(&self) -> Result<()> {\n        Args::clap().gen_completions_to(\"authoscope\", self.shell, &mut stdout());\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/bin/badtouch.rs",
    "content": "use authoscope::args;\nuse authoscope::config::Config;\nuse authoscope::ctx::Script;\nuse authoscope::errors::*;\nuse authoscope::fsck;\nuse authoscope::keyboard::{Keyboard, Key};\nuse authoscope::pb::ProgressBar;\nuse authoscope::scheduler::{self, Scheduler, Attempt, Msg};\nuse authoscope::utils;\nuse colored::*;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::io::stdout;\nuse std::sync::Arc;\nuse std::thread;\nuse std::time::Instant;\nuse structopt::StructOpt;\nuse structopt::clap::{AppSettings, Shell};\n\n#[derive(Debug, StructOpt)]\n#[structopt(global_settings = &[AppSettings::ColoredHelp])]\npub struct Args {\n    /// Verbose output\n    #[structopt(short=\"v\", long=\"verbose\",\n                global=true, parse(from_occurrences))]\n    pub verbose: u8,\n    /// Concurrent workers\n    #[structopt(short = \"n\", long = \"workers\", default_value = \"16\")]\n    pub workers: usize,\n    /// Write results to file\n    #[structopt(short = \"o\", long = \"output\")]\n    pub output: Option<String>,\n    #[structopt(subcommand)]\n    pub subcommand: SubCommand,\n}\n\n#[derive(Debug, StructOpt)]\npub enum SubCommand {\n    /// Dictionary attack\n    #[structopt(name=\"dict\")]\n    Dict(Dict),\n    /// Credential confirmation attack\n    #[structopt(name=\"creds\")]\n    Creds(Creds),\n    /// Enumerate users\n    #[structopt(name=\"enum\")]\n    Enum(Enum),\n    /// Test a single username-password combination\n    #[structopt(name=\"oneshot\")]\n    Oneshot(Oneshot),\n    /// Verify and fix encoding of a list\n    #[structopt(name=\"fsck\")]\n    Fsck(Fsck),\n    Completions(Completions),\n}\n\n#[derive(Debug, StructOpt)]\npub struct Dict {\n    /// Username list path\n    pub users: String,\n    /// Password list path\n    pub passwords: String,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Creds {\n    /// Credential list path\n    pub creds: String,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Enum {\n    /// Username list path\n    pub users: String,\n    /// Scripts to run\n    #[structopt(required=true)]\n    pub scripts: Vec<String>,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Oneshot {\n    /// Script to run\n    pub script: String,\n    /// Username to test\n    pub user: String,\n    /// Password to test\n    pub password: Option<String>,\n    /// Set the exitcode to 2 if the credentials are invalid\n    #[structopt(short = \"x\", long = \"exitcode\")]\n    pub exitcode: bool,\n}\n\n#[derive(Debug, StructOpt)]\npub struct Fsck {\n    /// Do not show invalid lines\n    #[structopt(short = \"q\", long = \"quiet\")]\n    pub quiet: bool,\n    /// Do not show valid lines\n    #[structopt(short = \"s\", long = \"silent\")]\n    pub silent: bool,\n    /// Require one colon per line\n    #[structopt(short = \"c\", long = \"colon\")]\n    pub require_colon: bool,\n    /// Files to read\n    pub paths: Vec<String>,\n}\n\n/// Generate shell completions\n#[derive(Debug, StructOpt)]\npub struct Completions {\n    #[structopt(possible_values=&Shell::variants())]\n    pub shell: Shell,\n}\n\nimpl Completions {\n    pub fn gen(&self) -> Result<()> {\n        Args::clap().gen_completions_to(\"authoscope\", self.shell, &mut stdout());\n        Ok(())\n    }\n}\nenum Report {\n    Some(File),\n    None\n}\n\nimpl Report {\n    pub fn open(path: Option<String>) -> Result<Report> {\n        match path {\n            Some(path) => Ok(Report::Some(File::create(path)?)),\n            None => Ok(Report::None),\n        }\n    }\n\n    pub fn write_creds(&mut self, user: &str, password: &str, script: &str) -> Result<()> {\n        if let Report::Some(ref mut f) = *self {\n            writeln!(f, \"{}:{}:{}\", script, user, password)?;\n        }\n        Ok(())\n    }\n\n    pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {\n        if let Report::Some(ref mut f) = *self {\n            writeln!(f, \"{}:{}\", script, user)?;\n        }\n        Ok(())\n    }\n}\n\nmacro_rules! tinfof {\n    ($arg1:tt, $fmt:expr, $($arg:tt)*) => (\n        $arg1.bold().to_string() + \" \" + &(format!($fmt, $($arg)*).dimmed().to_string())\n    );\n}\n\nmacro_rules! tinfo {\n    ($arg1:tt, $fmt:expr, $($arg:tt)*) => (\n        println!(\"{}\", tinfof!($arg1, $fmt, $($arg)*));\n    );\n}\n\nfn setup_dictionary_attack(pool: &mut Scheduler, args: Dict, config: &Arc<Config>) -> Result<usize> {\n    let users = utils::load_list(&args.users)\n        .context(\"Failed to load users\")?;\n    tinfo!(\"[+]\", \"loaded {} users\", users.len());\n    let passwords = utils::load_list(&args.passwords)\n        .context(\"Failed to load passwords\")?;\n    tinfo!(\"[+]\", \"loaded {} passwords\", passwords.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = users.len() * passwords.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\", attempts, pool.max_count());\n\n    for user in &users {\n        for password in &passwords {\n            for script in &scripts {\n                let attempt = Attempt::new(user, password, script);\n                pool.run(attempt);\n            }\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn setup_credential_confirmation(pool: &mut Scheduler, args: Creds, config: &Arc<Config>) -> Result<usize> {\n    let creds = utils::load_combolist(&args.creds)?;\n    tinfo!(\"[+]\", \"loaded {} credentials\", creds.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = creds.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\", attempts, pool.max_count());\n\n    for cred in creds {\n        // TODO: optimization if we only have once script\n        for script in &scripts {\n            let attempt = Attempt::bytes(&cred, script);\n            pool.run(attempt);\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn setup_enum_attack(pool: &mut Scheduler, args: Enum, config: &Arc<Config>) -> Result<usize> {\n    let users = utils::load_list(&args.users)\n        .context(\"Failed to load users\")?;\n    tinfo!(\"[+]\", \"loaded {} users\", users.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = users.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\", attempts, pool.max_count());\n\n    for user in &users {\n        for script in &scripts {\n            let attempt = Attempt::enumerate(user, script);\n            pool.run(attempt);\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn run_oneshot(oneshot: Oneshot, config: Arc<Config>) -> Result<()> {\n    let script = Script::load(&oneshot.script, config)?;\n    let user = oneshot.user;\n\n    let valid = match oneshot.password {\n        Some(ref password) => script.run_creds(&user, password)?,\n        None => script.run_enum(&user)?,\n    };\n\n    if valid {\n        match oneshot.password {\n            Some(ref password) => println!(\"{}\", format_valid_creds(script.descr(), &user, password)),\n            None => println!(\"{}\", format_valid_enum(script.descr(), &user)),\n        }\n    } else if oneshot.exitcode {\n        std::process::exit(2);\n    }\n\n    Ok(())\n}\n\nfn format_valid_creds(script: &str, user: &str, password: &str) -> String {\n    format!(\"{} {}({}) => {:?}:{:?}\", \"[+]\".bold(), \"valid\".green(),\n        script.yellow(), user, password)\n}\n\nfn format_valid_enum(script: &str, user: &str) -> String {\n    format!(\"{} {}({}) => {:?}\", \"[+]\".bold(), \"valid\".green(),\n        script.yellow(), user)\n}\n\nfn main() -> Result<()> {\n    let args = Args::from_args();\n\n    let env = env_logger::Env::default();\n    let env = match args.verbose {\n        0 => env.filter_or(\"RUST_LOG\", \"warn\"),\n        1 => env.filter_or(\"RUST_LOG\", \"info\"),\n        _ => env.filter_or(\"RUST_LOG\", \"debug\"),\n    };\n    env_logger::init_from_env(env);\n\n    warn!(\"badtouch has been renamed to authoscope, please use the new binary name instead\");\n\n    if atty::isnt(atty::Stream::Stdout) {\n        colored::control::SHOULD_COLORIZE.set_override(false);\n    }\n\n    let config = Arc::new(Config::load()?);\n    #[cfg(target_os=\"linux\")]\n    authoscope::ulimit::set_nofile(&config)\n        .context(\"Failed to set RLIMIT_NOFILE\")?;\n\n    let mut pool = Scheduler::new(args.workers);\n    let mut report = Report::open(args.output)?;\n\n    let attempts = match args.subcommand {\n        SubCommand::Dict(dict) => setup_dictionary_attack(&mut pool, dict, &config)?,\n        SubCommand::Creds(creds) => setup_credential_confirmation(&mut pool, creds, &config)?,\n        SubCommand::Enum(enumerate) => setup_enum_attack(&mut pool, enumerate, &config)?,\n        SubCommand::Oneshot(oneshot) => return run_oneshot(oneshot, config),\n        SubCommand::Fsck(fsck) => return fsck::run_fsck(&args::Fsck {\n            paths: fsck.paths,\n            quiet: fsck.quiet,\n            require_colon: fsck.require_colon,\n            silent: fsck.silent,\n        }),\n        SubCommand::Completions(completions) => return completions.gen(),\n    };\n\n    let tx = pool.tx();\n    thread::spawn(move || {\n        let kb = Keyboard::new();\n        loop {\n            let key = kb.get();\n            tx.send(Msg::Key(key)).expect(\"failed to send key\");\n        }\n    });\n\n    let mut pb = ProgressBar::new(attempts as u64);\n    pb.print_help();\n    pb.tick();\n\n    pool.resume();\n    let start = Instant::now();\n\n    let mut valid = 0;\n    let mut retries = 0;\n    let mut expired = 0;\n    while pool.has_work() {\n        match pool.recv() {\n            Msg::Key(key) => {\n                match key {\n                    Key::H => pb.print_help(),\n                    Key::P => {\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), \"pausing threads\".dimmed()));\n                        pool.pause();\n                    },\n                    Key::R => {\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), \"resuming threads\".dimmed()));\n                        pool.resume();\n                    },\n                    Key::Plus => {\n                        let num = pool.incr();\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), format!(\"increased to {} threads\", num).dimmed()));\n                    },\n                    Key::Minus => {\n                        let num = pool.decr();\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), format!(\"decreased to {} threads\", num).dimmed()));\n                    },\n                }\n                pb.tick();\n            },\n            Msg::Attempt(mut attempt, result) => {\n                match result {\n                    Ok(is_valid) => {\n                        if is_valid {\n                            match attempt.creds {\n                                scheduler::Creds::Enum(_) => {\n                                    let user = attempt.user();\n                                    let script = attempt.script.descr();\n\n                                    pb.writeln(format_valid_enum(script, user));\n                                    report.write_enum(user, script)?;\n                                },\n                                _ => {\n                                    let user = attempt.user();\n                                    let password = attempt.password();\n                                    let script = attempt.script.descr();\n\n                                    pb.writeln(format_valid_creds(script, user, password));\n                                    report.write_creds(user, password, script)?;\n                                },\n                            };\n                            valid += 1;\n                        }\n                        pb.inc();\n                    },\n                    Err(err) => {\n                        pb.writeln(format!(\"{} {}({}, {}): {:?}\", \"[!]\".bold(), \"error\".red(), attempt.script.descr().yellow(), format!(\"{:?}:{:?}\", attempt.user(), attempt.password()).dimmed(), err));\n\n                        if attempt.ttl > 0 {\n                            // we have retries left\n                            retries += 1;\n                            attempt.ttl -= 1;\n                            pool.run(*attempt);\n                            pb.tick();\n                        } else {\n                            // giving up\n                            expired += 1;\n                            pb.inc();\n                        }\n                    }\n                };\n            },\n        }\n    }\n\n    let elapsed = start.elapsed();\n    let average = elapsed / attempts as u32;\n    pb.finish_replace(tinfof!(\"[+]\", \"found {} valid credentials with {} attempts and {} retries after {} and on average {} per attempt. {} attempts expired.\\n\",\n            valid, attempts, retries,\n            humantime::format_duration(elapsed),\n            humantime::format_duration(average),\n            expired,\n    ));\n\n    Keyboard::reset();\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/config.rs",
    "content": "use crate::errors::*;\nuse serde::{Serialize, Deserialize};\nuse std::fs::File;\nuse std::path::Path;\nuse std::io::prelude::*;\n\n#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]\npub struct Config {\n    #[serde(default)]\n    pub runtime: RuntimeConfig,\n}\n\n#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]\npub struct RuntimeConfig {\n    #[serde(default)]\n    pub user_agent: Option<String>,\n    #[serde(default)]\n    pub rlimit_nofile: Option<u64>,\n}\n\nimpl Config {\n    pub fn load() -> Result<Config> {\n        let home = dirs::home_dir()\n            .ok_or_else(|| format_err!(\"home folder not found\"))?;\n\n        for name in &[\"authoscope\", \"badtouch\"] {\n            let path = home.join(&format!(\".config/{}.toml\", name));\n            if path.exists() {\n                return Config::from_file(path);\n            }\n        }\n\n        Ok(Config::default())\n    }\n\n    #[inline]\n    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {\n        let mut file = File::open(path)?;\n\n        let mut buf = String::new();\n        file.read_to_string(&mut buf)?;\n\n        Config::try_from_str(&buf)\n    }\n\n    #[inline]\n    pub fn try_from_str(buf: &str) -> Result<Config> {\n        let config = toml::from_str(buf)?;\n        Ok(config)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn verify_empty() {\n        let config = Config::try_from_str(\"\").unwrap();\n        assert_eq!(config, Config::default());\n    }\n}\n"
  },
  {
    "path": "src/ctx.rs",
    "content": "use crate::hlua::{self, AnyLuaValue};\nuse crate::errors::*;\nuse crate::runtime;\n\nuse std::fs::File;\nuse std::sync::{Arc, Mutex};\nuse std::io::prelude::*;\nuse std::collections::HashMap;\nuse crate::http::{HttpSession,\n           HttpRequest,\n           RequestOptions};\nuse crate::config::Config;\nuse crate::sockets::Socket;\nuse crate::utils;\n\n#[derive(Debug, Clone)]\npub struct State {\n    config: Arc<Config>,\n    error: Arc<Mutex<Option<Error>>>,\n    http_sessions: Arc<Mutex<HashMap<String, HttpSession>>>,\n    mysql_sessions: Arc<Mutex<HashMap<String, Arc<Mutex<mysql::Conn>>>>>,\n    socket_sessions: Arc<Mutex<HashMap<String, Arc<Mutex<Socket>>>>>,\n}\n\nimpl State {\n    pub fn new(config: Arc<Config>) -> State {\n        State {\n            config,\n            error: Arc::new(Mutex::new(None)),\n            http_sessions: Arc::new(Mutex::new(HashMap::new())),\n            mysql_sessions: Arc::new(Mutex::new(HashMap::new())),\n            socket_sessions: Arc::new(Mutex::new(HashMap::new())),\n        }\n    }\n\n    pub fn last_error(&self) -> Option<String> {\n        let lock = self.error.lock().unwrap();\n        lock.as_ref().map(|err| err.to_string())\n    }\n\n    pub fn clear_error(&self) {\n        let mut lock = self.error.lock().unwrap();\n        *lock = None;\n    }\n\n    pub fn set_error<I: Into<Error>>(&self, err: I) -> Error {\n        let err = err.into();\n        let mut mtx = self.error.lock().unwrap();\n        let cp = err.to_string();\n        *mtx = Some(err);\n        format_err!(\"{}\", cp) // TODO: refactor\n    }\n\n    #[inline]\n    fn random_id(&self) -> String {\n        utils::random_string(16)\n    }\n\n    pub fn register_in_jar(&self, session: &str, cookies: Vec<(String, String)>) {\n        let mut mtx = self.http_sessions.lock().unwrap();\n        if let Some(session) = mtx.get_mut(session) {\n            session.cookies.register_in_jar(cookies);\n        }\n    }\n\n    pub fn http_mksession(&self) -> String {\n        let mut mtx = self.http_sessions.lock().unwrap();\n        let (id, session) = HttpSession::new();\n        mtx.insert(id.clone(), session);\n        id\n    }\n\n    pub fn http_request(&self, session_id: &str, method: String, url: String, options: RequestOptions) -> HttpRequest {\n        let mtx = self.http_sessions.lock().unwrap();\n        let session = mtx.get(session_id).expect(\"invalid session reference\"); // TODO\n\n        HttpRequest::new(&self.config, session, method, url, options)\n    }\n\n    pub fn mysql_register(&self, sock: mysql::Conn) -> String {\n        let mut mtx = self.mysql_sessions.lock().unwrap();\n        let id = self.random_id();\n\n        let sock = Arc::new(Mutex::new(sock));\n        mtx.insert(id.clone(), sock);\n\n        id\n    }\n\n    pub fn mysql_session(&self, id: &str) -> Arc<Mutex<mysql::Conn>> {\n        let mtx = self.mysql_sessions.lock().unwrap();\n        let sock = mtx.get(id).expect(\"invalid session reference\"); // TODO\n        sock.clone()\n    }\n\n    pub fn sock_connect(&self, host: &str, port: u16) -> Result<String> {\n        let mut mtx = self.socket_sessions.lock().unwrap();\n        let id = self.random_id();\n\n        let sock = Socket::connect(host, port)?;\n        mtx.insert(id.clone(), Arc::new(Mutex::new(sock)));\n\n        Ok(id)\n    }\n\n    pub fn get_sock(&self, id: &str)-> Arc<Mutex<Socket>> {\n        let mtx = self.socket_sessions.lock().unwrap();\n        let sock = mtx.get(id).expect(\"invalid session reference\"); // TODO\n        sock.clone()\n    }\n}\n\n\n#[derive(Debug, Clone)]\npub struct Script {\n    descr: String,\n    code: String,\n    config: Arc<Config>,\n}\n\nimpl Script {\n    pub fn load(path: &str, config: Arc<Config>) -> Result<Script> {\n        let mut file = File::open(path)?;\n        Script::load_from(&mut file, config)\n    }\n\n    pub fn load_from<R: Read>(mut src: R, config: Arc<Config>) -> Result<Script> {\n        let mut code = String::new();\n        src.read_to_string(&mut code)?;\n\n        let (mut lua, _) = Script::ctx(&config);\n        lua.execute::<()>(&code)?;\n\n        let descr = {\n            let descr: Result<_> = lua.get(\"descr\").ok_or_else(|| format_err!(\"descr undefined\"));\n            let descr: hlua::StringInLua<_> = descr?;\n            (*descr).to_owned()\n        };\n\n        {\n            let verify: Result<_> = lua.get(\"verify\").ok_or_else(|| format_err!(\"verify undefined\"));\n            let _: hlua::LuaFunction<_> = verify?;\n        };\n\n        Ok(Script {\n            descr,\n            code,\n            config,\n        })\n    }\n\n    fn ctx<'a>(config: &Arc<Config>) -> (hlua::Lua<'a>, State) {\n        let mut lua = hlua::Lua::new();\n        lua.open_string();\n        let state = State::new(config.clone());\n\n        runtime::base64_decode(&mut lua, state.clone());\n        runtime::base64_encode(&mut lua, state.clone());\n        runtime::bcrypt(&mut lua, state.clone());\n        runtime::bcrypt_verify(&mut lua, state.clone());\n        runtime::clear_err(&mut lua, state.clone());\n        runtime::execve(&mut lua, state.clone());\n        runtime::hex(&mut lua, state.clone());\n        runtime::hmac_md5(&mut lua, state.clone());\n        runtime::hmac_sha1(&mut lua, state.clone());\n        runtime::hmac_sha2_256(&mut lua, state.clone());\n        runtime::hmac_sha2_512(&mut lua, state.clone());\n        runtime::hmac_sha3_256(&mut lua, state.clone());\n        runtime::hmac_sha3_512(&mut lua, state.clone());\n        runtime::html_select(&mut lua, state.clone());\n        runtime::html_select_list(&mut lua, state.clone());\n        runtime::http_basic_auth(&mut lua, state.clone()); // TODO: deprecate?\n        runtime::http_mksession(&mut lua, state.clone());\n        runtime::http_request(&mut lua, state.clone());\n        runtime::http_send(&mut lua, state.clone());\n        runtime::json_decode(&mut lua, state.clone());\n        runtime::json_encode(&mut lua, state.clone());\n        runtime::last_err(&mut lua, state.clone());\n        runtime::ldap_bind(&mut lua, state.clone());\n        runtime::ldap_escape(&mut lua, state.clone());\n        runtime::ldap_search_bind(&mut lua, state.clone());\n        runtime::md5(&mut lua, state.clone());\n        runtime::mysql_connect(&mut lua, state.clone());\n        runtime::mysql_query(&mut lua, state.clone());\n        runtime::print(&mut lua, state.clone());\n        runtime::rand(&mut lua, state.clone());\n        runtime::randombytes(&mut lua, state.clone());\n        runtime::sha1(&mut lua, state.clone());\n        runtime::sha2_256(&mut lua, state.clone());\n        runtime::sha2_512(&mut lua, state.clone());\n        runtime::sha3_256(&mut lua, state.clone());\n        runtime::sha3_512(&mut lua, state.clone());\n        runtime::sleep(&mut lua, state.clone());\n        runtime::sock_connect(&mut lua, state.clone());\n        runtime::sock_send(&mut lua, state.clone());\n        runtime::sock_recv(&mut lua, state.clone());\n        runtime::sock_sendline(&mut lua, state.clone());\n        runtime::sock_recvline(&mut lua, state.clone());\n        runtime::sock_recvall(&mut lua, state.clone());\n        runtime::sock_recvline_contains(&mut lua, state.clone());\n        runtime::sock_recvline_regex(&mut lua, state.clone());\n        runtime::sock_recvn(&mut lua, state.clone());\n        runtime::sock_recvuntil(&mut lua, state.clone());\n        runtime::sock_sendafter(&mut lua, state.clone());\n        runtime::sock_newline(&mut lua, state.clone());\n\n        (lua, state)\n    }\n\n    #[inline]\n    pub fn descr(&self) -> &str {\n        self.descr.as_str()\n    }\n\n    /*\n    #[inline]\n    pub fn code(&self) -> &str {\n        self.code.as_str()\n    }\n    */\n\n    pub fn run_once(&self, user: AnyLuaValue, password: AnyLuaValue) -> Result<bool> {\n        debug!(\"executing {:?} with {:?}:{:?}\", self.descr(), user, password);\n\n        let (mut lua, state) = Script::ctx(&self.config);\n        lua.execute::<()>(&self.code)?;\n\n        let verify: Result<_> = lua.get(\"verify\").ok_or_else(|| format_err!(\"verify undefined\"));\n        let mut verify: hlua::LuaFunction<_> = verify?;\n\n        let result: hlua::AnyLuaValue = match verify.call_with_args((user, password)) {\n            Ok(res) => res,\n            Err(err) => {\n                bail!(\"execution failed: {:?}\", err);\n            },\n        };\n\n        if let Some(err) = state.error.lock().unwrap().take() {\n            return Err(err);\n        }\n\n        use crate::hlua::AnyLuaValue::*;\n        match result {\n            LuaBoolean(x) => Ok(x),\n            LuaString(x) => Err(format_err!(\"error: {:?}\", x)),\n            x => Err(format_err!(\"lua returned wrong type: {:?}\", x)),\n        }\n    }\n\n    #[inline]\n    pub fn run_creds(&self, user: &str, password: &str) -> Result<bool> {\n        let user = AnyLuaValue::LuaString(user.to_string());\n        let password = AnyLuaValue::LuaString(password.to_string());\n        self.run_once(user, password)\n    }\n\n    #[inline]\n    pub fn run_enum(&self, user: &str) -> Result<bool> {\n        let user = AnyLuaValue::LuaString(user.to_string());\n        let password = AnyLuaValue::LuaNil;\n        self.run_once(user, password)\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    fn empty_config() -> Arc<Config> {\n        Arc::new(Config::default())\n    }\n\n    #[test]\n    fn verify_false() {\n        let script = Script::load_from(r#\"\n        descr = \"verify_false\"\n\n        function verify(user, password)\n            return false\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"foo\", \"bar\").expect(\"test script failed\");\n        assert!(!result);\n    }\n\n    #[test]\n    fn verify_true() {\n        let script = Script::load_from(r#\"\n        descr = \"verify_false\"\n\n        function verify(user, password)\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"foo\", \"bar\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_record_error() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            json_decode(\"{{{{{{{{{{{{{{{{{{\")\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\");\n        assert!(result.is_err());\n    }\n\n    #[test]\n    fn verify_clear_recorded_error() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            json_decode(\"{{{{{{{{{{{{{{{{{{\")\n            clear_err()\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_sleep() {\n        let script = Script::load_from(r#\"\n        descr = \"slow script\"\n\n        function verify(user, password)\n            sleep(1)\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"foo\", \"bar\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_basic_auth_correct() {\n        let script = Script::load_from(r#\"\n        descr = \"basic auth httpbin.org\"\n\n        function verify(user, password)\n            return http_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"foo\", \"buzz\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_basic_auth_incorrect() {\n        let script = Script::load_from(r#\"\n        descr = \"basic auth httpbin.org\"\n\n        function verify(user, password)\n            return http_basic_auth(\"https://httpbin.org/basic-auth/foo/buzz\", user, password)\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"invalid\", \"wrong\").expect(\"test script failed\");\n        assert!(!result);\n    }\n\n    #[test]\n    fn verify_cookies() {\n        let script = Script::load_from(r#\"\n        descr = \"cookies httpbin.org\"\n\n        function verify(user, password)\n            session = http_mksession()\n\n            req = http_request(session, 'GET', 'https://httpbin.org/cookies/set/foo/; as=df', {})\n            resp = http_send(req)\n            if last_err() then return end\n\n            req = http_request(session, 'GET', 'https://httpbin.org/cookies/set/fizz/buzz', {})\n            resp = http_send(req)\n            if last_err() then return end\n\n            req = http_request(session, 'GET', 'https://httpbin.org/cookies', {})\n            resp = http_send(req)\n            if last_err() then return end\n\n            o = json_decode(resp['text'])\n            if last_err() then return end\n            print(o)\n\n            if o['cookies']['foo'] ~= '; as=df' then\n                return 'Unexpected value for foo cookie'\n            end\n\n            if o['cookies']['fizz'] ~= 'buzz' then\n                return 'Unexpected value for fizz cookie'\n            end\n\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"invalid\", \"wrong\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hex() {\n        let script = Script::load_from(r#\"\n        descr = \"hex test\"\n\n        function verify(user, password)\n            x = hex({0x6F, 0x68, 0x61, 0x69, 0x0A, 0x00})\n            return x == \"6f6861690a00\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hex_empty() {\n        let script = Script::load_from(r#\"\n        descr = \"hex test\"\n\n        function verify(user, password)\n            x = hex({})\n            return x == \"\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_json_encode() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            json_encode({\n                hello=\"world\",\n                almost_one=0.9999,\n                list={1,3,3,7},\n                data={\n                    user=user,\n                    password=password,\n                    empty=nil\n                }\n            })\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_json_encode_decode() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            x = json_encode({\n                hello=\"world\",\n                almost_one=0.9999,\n                list={1,3,3,7},\n                data={\n                    user=user,\n                    password=password,\n                    empty=nil\n                }\n            })\n            json_decode(x)\n\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_json_decode_valid() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            json_decode(\"{\\\"almost_one\\\":0.9999,\\\"data\\\":{\\\"password\\\":\\\"fizz\\\",\\\"user\\\":\\\"bar\\\"},\\\"hello\\\":\\\"world\\\",\\\"list\\\":[1,3,3,7]}\")\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_json_decode_invalid() {\n        let script = Script::load_from(r#\"\n        descr = \"json\"\n\n        function verify(user, password)\n            json_decode(\"{\\\"almost_one\\\":0.9999,\\\"data\\\":{\\\"password\\\":\\\"fizz\\\",\\\"user\\\":\\\"bar\\\"}}}}}}}}}\")\n            return true\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\");\n        assert!(result.is_err());\n    }\n\n    #[test]\n    fn verify_hmac_md5() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_md5\"\n\n        function verify(user, password)\n            x = hex(hmac_md5(\"foo\", \"bar\"))\n            -- print('md5: ' .. x)\n            return x == \"0c7a250281315ab863549f66cd8a3a53\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hmac_sha1() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_sha1\"\n\n        function verify(user, password)\n            x = hex(hmac_sha1(\"foo\", \"bar\"))\n            -- print('sha1: ' .. x)\n            return x == \"46b4ec586117154dacd49d664e5d63fdc88efb51\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hmac_sha2_256() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_sha2_256\"\n\n        function verify(user, password)\n            x = hex(hmac_sha2_256(\"foo\", \"bar\"))\n            -- print('sha2_256: ' .. x)\n            return x == \"f9320baf0249169e73850cd6156ded0106e2bb6ad8cab01b7bbbebe6d1065317\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hmac_sha2_512() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_sha2_512\"\n\n        function verify(user, password)\n            x = hex(hmac_sha2_512(\"foo\", \"bar\"))\n            -- print('sha2_512: ' .. x)\n            return x == \"114682914c5d017dfe59fdc804118b56a3a652a0b8870759cf9e792ed7426b08197076bf7d01640b1b0684df79e4b67e37485669e8ce98dbab60445f0db94fce\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hmac_sha3_256() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_sha3_256\"\n\n        function verify(user, password)\n            x = hex(hmac_sha3_256(\"foo\", \"bar\"))\n            -- print('sha3_256: ' .. x)\n            return x == \"a7dc3fbbd45078239f0cb321e6902375d22b505f2c48722eb7009e7da2574893\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_hmac_sha3_512() {\n        let script = Script::load_from(r#\"\n        descr = \"hmac_sha3_512\"\n\n        function verify(user, password)\n            x = hex(hmac_sha3_512(\"foo\", \"bar\"))\n            -- print('sha3_512: ' .. x)\n            return x == \"2da91b8227d106199fd06c5d8a6752796cf3c84dde5a427bd2aca384f0cffc19997e2584ed15c55542c2cb8918b987e2bcd9e77a9f3fdbb4dbea8a3d0136da2f\"\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"x\").expect(\"test script failed\");\n        assert!(result);\n    }\n\n    #[test]\n    fn verify_bcrypt_verify() {\n        let script = Script::load_from(r#\"\n        descr = \"bcrypt_verify\"\n\n        function verify(user, password)\n            return bcrypt_verify(password, \"$2a$12$ByUlHCHx3rxMsdQONpuFbulQqut6GQ/84I5EAUkCqTTI07JA7wUju\")\n        end\n        \"#.as_bytes(), empty_config()).unwrap();\n\n        let result = script.run_creds(\"x\", \"hunter2\").expect(\"test script failed\");\n        assert!(result);\n    }\n}\n"
  },
  {
    "path": "src/db/mod.rs",
    "content": "pub mod mysql;\n"
  },
  {
    "path": "src/db/mysql.rs",
    "content": "use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};\n\nuse std::collections::HashMap;\nuse crate::structs::LuaMap;\n\n\nimpl From<mysql::Params> for LuaMap {\n    fn from(params: mysql::Params) -> LuaMap {\n        match params {\n            mysql::Params::Empty => LuaMap::new(),\n            mysql::Params::Named(map) => {\n                map.into_iter()\n                    .map(|(k, v)| (AnyHashableLuaValue::LuaString(k), mysql_value_to_lua(v)))\n                    .collect::<HashMap<AnyHashableLuaValue, AnyLuaValue>>()\n                    .into()\n            },\n            mysql::Params::Positional(_) => unimplemented!(),\n        }\n    }\n}\n\nimpl From<LuaMap> for mysql::Params {\n    fn from(x: LuaMap) -> mysql::Params {\n        if x.is_empty() {\n            mysql::Params::Empty\n        } else {\n            let mut params = HashMap::default();\n\n            for (k, v) in x {\n                if let AnyHashableLuaValue::LuaString(k) = k {\n                    params.insert(k, lua_to_mysql_value(v));\n                } else {\n                    panic!(\"unsupported keys in map\");\n                }\n            }\n\n            mysql::Params::Named(params)\n        }\n    }\n}\n\nfn lua_to_mysql_value(value: AnyLuaValue) -> mysql::Value {\n    match value {\n        AnyLuaValue::LuaString(x) => mysql::Value::Bytes(x.into_bytes()),\n        AnyLuaValue::LuaAnyString(x) => mysql::Value::Bytes(x.0),\n        AnyLuaValue::LuaNumber(v) => if v % 1f64 == 0f64 {\n            mysql::Value::Int(v as i64)\n        } else {\n            mysql::Value::Float(v as f32)\n        },\n        AnyLuaValue::LuaBoolean(x) => mysql::Value::Int(if x { 1 } else { 0 }),\n        AnyLuaValue::LuaArray(_x) => unimplemented!(),\n        AnyLuaValue::LuaNil => mysql::Value::NULL,\n        AnyLuaValue::LuaOther => unimplemented!(),\n    }\n}\n\npub fn mysql_value_to_lua(value: mysql::Value) -> AnyLuaValue {\n    use mysql::Value::*;\n    match value {\n        NULL => AnyLuaValue::LuaNil,\n        Bytes(bytes) => AnyLuaValue::LuaString(String::from_utf8(bytes).unwrap()),\n        Int(i) => AnyLuaValue::LuaNumber(i as f64),\n        UInt(i) => AnyLuaValue::LuaNumber(i as f64),\n        Float(i) => AnyLuaValue::LuaNumber(i as f64),\n        Double(i) => AnyLuaValue::LuaNumber(i as f64),\n        Date(_, _, _, _, _, _, _) => unimplemented!(),\n        Time(_, _, _, _, _, _) => unimplemented!(),\n    }\n}\n"
  },
  {
    "path": "src/errors.rs",
    "content": "pub use anyhow::{anyhow, bail, format_err, Context, Error, Result};\npub use log::{trace, debug, info, warn, error};\n"
  },
  {
    "path": "src/fsck.rs",
    "content": "use crate::errors::Result;\nuse crate::args::Fsck;\n\nuse std::fs::File;\nuse std::io;\nuse std::io::BufReader;\nuse std::io::BufWriter;\nuse std::io::prelude::*;\nuse std::str;\n\n\nfn validate_file(path: &str, args: &Fsck) -> Result<()> {\n    let f = File::open(path)?;\n    let mut file = BufReader::new(&f);\n    let mut out = BufWriter::new(io::stdout());\n\n    let mut i = 0;\n    let mut buf = Vec::new();\n    const DELIM: u8 = b'\\n';\n\n    while 0 < file.read_until(DELIM, &mut buf)? {\n        /*\n        not removing the \\n so we don't have to append it later\n        if buf[buf.len() - 1] == DELIM {\n            buf.pop();\n        }\n        */\n        // TODO: remove empty lines?\n\n        match str::from_utf8(&buf) {\n            Ok(line) => {\n                if !args.require_colon || buf.iter().any(|x| *x == b':') {\n                    if !args.silent {\n                        out.write_all(line.as_bytes())?;\n                    }\n                } else if !args.quiet {\n                    eprintln!(\"Invalid(line {}): {:?}\",\n                        i,\n                        line);\n                }\n            },\n            Err(_) => {\n                if !args.quiet {\n                    eprintln!(\"Invalid(line {}): {:?} {:?}\",\n                        i,\n                        String::from_utf8_lossy(&buf),\n                        buf);\n                }\n            },\n        };\n\n        buf.clear();\n        i += 1;\n    }\n\n    // Close the BufWriter to flush it\n    let _ = out.into_inner()?;\n\n    Ok(())\n}\n\npub fn run_fsck(args: &Fsck) -> Result<()> {\n    for path in &args.paths {\n        validate_file(path, args)?;\n    }\n    Ok(())\n}\n"
  },
  {
    "path": "src/html.rs",
    "content": "use crate::errors::*;\n\nuse kuchiki::traits::TendrilSink;\nuse std::collections::HashMap;\nuse crate::hlua::AnyLuaValue;\nuse crate::structs::LuaMap;\n\n\n#[derive(Debug, PartialEq)]\npub struct Element {\n    attrs: HashMap<String, String>,\n    text: String,\n}\n\nimpl From<Element> for AnyLuaValue {\n    fn from(x: Element) -> AnyLuaValue {\n        let mut map = LuaMap::new();\n\n        map.insert_str(\"text\", x.text);\n        map.insert(\"attrs\", LuaMap::from(x.attrs));\n\n        map.into()\n    }\n}\n\nfn transform_element(entry: &kuchiki::NodeDataRef<kuchiki::ElementData>) -> Element {\n    let text = entry.text_contents();\n    let as_node = entry.as_node();\n\n    let mut attrs: HashMap<String, String> = HashMap::new();\n\n    if let Some(element) = as_node.as_element() {\n        for (k, v) in &element.attributes.borrow().map {\n            attrs.insert(k.local.to_string(), v.value.clone());\n        }\n    }\n\n    Element {\n        attrs,\n        text,\n    }\n}\n\npub fn html_select(html: &str, selector: &str) -> Result<Element> {\n    let doc = kuchiki::parse_html().one(html);\n    match doc.select_first(selector) {\n        Ok(x) => Ok(transform_element(&x)),\n        Err(_) => bail!(\"css selector failed\"),\n    }\n}\n\npub fn html_select_list(html: &str, selector: &str) -> Result<Vec<Element>> {\n    let doc = kuchiki::parse_html().one(html);\n\n    match doc.select(selector) {\n        Ok(x) => Ok(x.into_iter().map(|x| transform_element(&x)).collect()),\n        Err(_) => bail!(\"css selector failed\"),\n    }\n}\n\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_html_select() {\n        let elems = html_select(r#\"<html><div id=\"yey\">content</div></html>\"#, \"#yey\").unwrap();\n        assert_eq!(elems,\n            Element {\n                attrs: vec![(String::from(\"id\"), String::from(\"yey\"))].into_iter().collect(),\n                text: \"content\".into(),\n            }\n        );\n    }\n\n    #[test]\n    fn test_html_select_list() {\n        let elems = html_select_list(r#\"<html><div id=\"yey\">content</div></html>\"#, \"#yey\").unwrap();\n        assert_eq!(elems, vec![\n            Element {\n                attrs: vec![(String::from(\"id\"), String::from(\"yey\"))].into_iter().collect(),\n                text: \"content\".into(),\n            }\n        ]);\n    }\n}\n"
  },
  {
    "path": "src/http.rs",
    "content": "use crate::errors::*;\nuse crate::structs::LuaMap;\n\nuse reqwest::Method;\nuse reqwest::header::{HeaderName, HeaderValue, COOKIE, SET_COOKIE, USER_AGENT};\nuse reqwest::redirect;\nuse crate::hlua::AnyLuaValue;\nuse crate::json::LuaJsonValue;\nuse serde::{Serialize, Deserialize};\nuse std::collections::HashMap;\nuse std::ops::Deref;\nuse std::sync::Arc;\nuse crate::config::Config;\nuse crate::ctx::State;\nuse crate::utils;\n\n#[derive(Debug)]\npub struct HttpSession {\n    id: String,\n    pub cookies: CookieJar,\n}\n\nimpl HttpSession {\n    pub fn new() -> (String, HttpSession) {\n        let id = utils::random_string(16);\n        (id.clone(), HttpSession {\n            id,\n            cookies: CookieJar::default(),\n        })\n    }\n}\n\n#[derive(Debug, Default, Deserialize)]\npub struct RequestOptions {\n    query: Option<HashMap<String, String>>,\n    headers: Option<HashMap<String, String>>,\n    basic_auth: Option<(String, String)>,\n    user_agent: Option<String>,\n    json: Option<serde_json::Value>,\n    form: Option<serde_json::Value>,\n    body: Option<String>,\n}\n\nimpl RequestOptions {\n    pub fn try_from(x: AnyLuaValue) -> Result<RequestOptions> {\n        let x = LuaJsonValue::from(x);\n        let x = serde_json::from_value(x.into())?;\n        Ok(x)\n    }\n}\n\n#[derive(Debug, Default, Serialize, Deserialize)]\npub struct HttpRequest {\n    // reference to the HttpSession\n    session: String,\n    cookies: CookieJar,\n    method: String,\n    url: String,\n    query: Option<HashMap<String, String>>,\n    headers: Option<HashMap<String, String>>,\n    basic_auth: Option<(String, String)>,\n    user_agent: Option<String>,\n    body: Option<Body>,\n}\n\nimpl HttpRequest {\n    pub fn new(config: &Arc<Config>, session: &HttpSession, method: String, url: String, options: RequestOptions) -> HttpRequest {\n        let cookies = session.cookies.clone();\n\n        let user_agent = options.user_agent.or_else(|| config.runtime.user_agent.clone());\n\n        let mut request = HttpRequest {\n            session: session.id.clone(),\n            cookies,\n            method,\n            url,\n            query: options.query,\n            headers: options.headers,\n            basic_auth: options.basic_auth,\n            user_agent,\n            body: None,\n        };\n\n        if let Some(json) = options.json {\n            request.body = Some(Body::Json(json));\n        }\n\n        if let Some(form) = options.form {\n            request.body = Some(Body::Form(form));\n        }\n\n        if let Some(text) = options.body {\n            request.body = Some(Body::Raw(text));\n        }\n\n        request\n    }\n\n    pub fn send(&self, state: &State) -> Result<LuaMap> {\n        debug!(\"http send: {:?}\", self);\n\n        let client = reqwest::blocking::Client::builder()\n            .redirect(redirect::Policy::none()) // TODO: this should be configurable\n            .build().unwrap();\n        let method = self.method.parse::<Method>()\n                        .context(\"Invalid http method\")?;\n        let mut req = client.request(method, &self.url);\n\n        if let Some(cookies) = self.cookies.assemble_cookie_header() {\n            debug!(\"Adding cookies to request: {:?}\", cookies);\n            req = req.header(COOKIE, HeaderValue::from_str(&cookies)?);\n        }\n\n        if let Some(ref agent) = self.user_agent {\n            req = req.header(USER_AGENT, agent.as_str());\n        }\n\n        if let Some(ref auth) = self.basic_auth {\n            let &(ref user, ref password) = auth;\n            req = req.basic_auth(user, Some(password));\n        }\n\n        if let Some(ref headers) = self.headers {\n            for (k, v) in headers {\n                let k = HeaderName::from_bytes(k.as_bytes())?;\n                req = req.header(k, HeaderValue::from_str(v)?);\n            }\n        }\n\n        if let Some(ref query) = self.query {\n            req = req.query(query);\n        }\n\n        req = match self.body {\n            Some(Body::Raw(ref x))  => { req.body(x.clone()) },\n            Some(Body::Form(ref x)) => { req.form(x) },\n            Some(Body::Json(ref x)) => { req.json(x) },\n            None => req,\n        };\n\n        info!(\"http req: {:?}\", req);\n        let res = req.send()?;\n        info!(\"http res: {:?}\", res);\n\n        let mut resp = LuaMap::new();\n        let status = res.status();\n        resp.insert_num(\"status\", f64::from(status.as_u16()));\n\n        {\n            let cookies = res.headers().get_all(SET_COOKIE);\n            HttpRequest::register_cookies_on_state(&self.session, state, &cookies)\n                .context(\"Failed to process http response cookies\")?;\n        }\n\n        let mut headers = LuaMap::new();\n        for (name, value) in res.headers().iter() {\n            headers.insert_str(name.as_str().to_lowercase(), value.to_str()?);\n        }\n        resp.insert(\"headers\", headers);\n\n        if let Ok(text) = res.text() {\n            resp.insert_str(\"text\", text);\n        }\n\n        Ok(resp)\n    }\n\n    fn register_cookies_on_state(session: &str, state: &State, cookies: &reqwest::header::GetAll<HeaderValue>) -> Result<()> {\n        let mut jar = Vec::new();\n\n        for cookie in cookies.iter() {\n            let cookie = cookie.to_str()?;\n\n            let mut key = String::new();\n            let mut value = String::new();\n            let mut in_key = true;\n\n            for c in cookie.chars() {\n                match c {\n                    '=' if in_key => in_key = false,\n                    ';' => break,\n                    c if in_key => key.push(c),\n                    c => value.push(c),\n                }\n            }\n\n            jar.push((key, value));\n        }\n\n        state.register_in_jar(session, jar);\n\n        Ok(())\n    }\n}\n\nimpl HttpRequest {\n    pub fn try_from(x: AnyLuaValue) -> Result<HttpRequest> {\n        let x = LuaJsonValue::from(x);\n        let x = serde_json::from_value(x.into())?;\n        Ok(x)\n    }\n}\n\nimpl From<HttpRequest> for AnyLuaValue {\n    fn from(x: HttpRequest) -> AnyLuaValue {\n        let v = serde_json::to_value(&x).unwrap();\n        LuaJsonValue::from(v).into()\n    }\n}\n\n// see https://github.com/seanmonstar/reqwest/issues/14 for proper cookie jars\n// maybe change this to reqwest::header::Cookie\n#[derive(Debug, Default, Clone, Serialize, Deserialize)]\npub struct CookieJar(HashMap<String, String>);\n\nimpl CookieJar {\n    pub fn register_in_jar(&mut self, cookies: Vec<(String, String)>) {\n        for (key, value) in cookies {\n            self.0.insert(key, value);\n        }\n    }\n\n    pub fn assemble_cookie_header(&self) -> Option<String> {\n        if self.is_empty() {\n            return None;\n        }\n\n        let mut cookies: Vec<String> = Vec::new();\n        for (key, value) in self.iter() {\n            let value = if value.contains(' ') || value.contains(';') {\n                self.escape_cookie_value(value)\n            } else {\n                value.to_owned()\n            };\n\n            let cookie = format!(\"{}={}\", key, value);\n            debug!(\"Adding cookie: {:?}\", cookie);\n            cookies.push(cookie);\n        }\n\n        Some(cookies.join(\"; \"))\n    }\n\n    fn escape_cookie_value(&self, value: &str) -> String {\n        value.chars()\n            .fold(String::new(), |mut s, c| {\n                match c {\n                    ';' => s.push_str(\"\\\\073\"),\n                    c => s.push(c),\n                }\n                s\n            })\n    }\n}\n\nimpl Deref for CookieJar {\n    type Target = HashMap<String, String>;\n\n    fn deref(&self) -> &Self::Target {\n        &self.0\n    }\n}\n\n#[derive(Debug, Serialize, Deserialize)]\npub enum Body {\n    Raw(String), // TODO: maybe Vec<u8>\n    Form(serde_json::Value),\n    Json(serde_json::Value),\n}\n"
  },
  {
    "path": "src/json.rs",
    "content": "use crate::errors::*;\nuse crate::hlua::AnyLuaValue;\nuse serde_json::{self, Value, Number};\nuse std::collections::HashMap;\n\npub fn decode(x: &str) -> Result<AnyLuaValue> {\n    let v: Value = serde_json::from_str(x)\n        .context(\"deserialize failed\")?;\n    let v: LuaJsonValue = v.into();\n    Ok(v.into())\n}\n\npub fn encode(v: AnyLuaValue) -> Result<String> {\n    let v: LuaJsonValue = v.into();\n    let v: Value = v.into();\n    let s = serde_json::to_string(&v)\n        .context(\"Serialize failed\")?;\n    Ok(s)\n}\n\npub fn lua_array_is_list(array: &[(AnyLuaValue, AnyLuaValue)]) -> bool {\n    if !array.is_empty() {\n        let first = &array[0];\n        matches!(first.0, AnyLuaValue::LuaNumber(_))\n    } else {\n        // true // TODO: this breaks unserialize\n        false\n    }\n}\n\n#[derive(Debug)]\npub enum LuaJsonValue {\n    Null,\n    Bool(bool),\n    Number(Number),\n    String(String),\n    Array(Vec<LuaJsonValue>),\n    Object(HashMap<String, LuaJsonValue>),\n}\n\nimpl From<LuaJsonValue> for AnyLuaValue {\n    fn from(x: LuaJsonValue) -> AnyLuaValue {\n        match x {\n            LuaJsonValue::Null => AnyLuaValue::LuaNil,\n            LuaJsonValue::Bool(v) => AnyLuaValue::LuaBoolean(v),\n            // TODO: not sure if this might fail\n            LuaJsonValue::Number(v) => AnyLuaValue::LuaNumber(v.as_f64().unwrap()),\n            LuaJsonValue::String(v) => AnyLuaValue::LuaString(v),\n            LuaJsonValue::Array(v) => AnyLuaValue::LuaArray(v.into_iter().enumerate()\n                .map(|(i, x)| (AnyLuaValue::LuaNumber(i as f64), x.into()))\n                .collect()\n            ),\n            LuaJsonValue::Object(v) => AnyLuaValue::LuaArray(v.into_iter()\n                .map(|(k, v)| (AnyLuaValue::LuaString(k), v.into()))\n                .collect()\n            ),\n        }\n    }\n}\n\nimpl From<AnyLuaValue> for LuaJsonValue {\n    fn from(x: AnyLuaValue) -> LuaJsonValue {\n        match x {\n            AnyLuaValue::LuaNil => LuaJsonValue::Null,\n            AnyLuaValue::LuaBoolean(v) => LuaJsonValue::Bool(v),\n            AnyLuaValue::LuaString(v) => LuaJsonValue::String(v),\n            AnyLuaValue::LuaAnyString(v) => LuaJsonValue::Array(v.0.into_iter()\n                .map(|x| LuaJsonValue::Number(x.into()))\n                .collect()\n            ),\n            AnyLuaValue::LuaNumber(v) => {\n                // this is needed or every number is detected as float\n                LuaJsonValue::Number(if v % 1f64 == 0f64 {\n                    (v as u64).into()\n                } else {\n                    Number::from_f64(v).expect(\"invalid LuaJson::Number\")\n                })\n            },\n            AnyLuaValue::LuaArray(v) => {\n                if lua_array_is_list(&v) {\n                    LuaJsonValue::Array(v.into_iter()\n                        .map(|(_, v)| v.into())\n                        .collect()\n                    )\n                } else {\n                    LuaJsonValue::Object(v.into_iter()\n                        .filter_map(|(k, v)| match k {\n                            AnyLuaValue::LuaString(k) => Some((k, v.into())),\n                            _ => None,\n                        })\n                        .collect()\n                    )\n                }\n            },\n            AnyLuaValue::LuaOther => LuaJsonValue::Null,\n        }\n    }\n}\n\nimpl From<LuaJsonValue> for Value {\n    fn from(x: LuaJsonValue) -> Value {\n        match x {\n            LuaJsonValue::Null => Value::Null,\n            LuaJsonValue::Bool(v) => Value::Bool(v),\n            LuaJsonValue::Number(v) => Value::Number(v),\n            LuaJsonValue::String(v) => Value::String(v),\n            LuaJsonValue::Array(v) => Value::Array(v.into_iter()\n                .map(|x| x.into())\n                .collect()\n            ),\n            LuaJsonValue::Object(v) => Value::Object(v.into_iter()\n                .map(|(k, v)| (k, v.into()))\n                .collect()\n            ),\n        }\n    }\n}\n\nimpl From<Value> for LuaJsonValue {\n    fn from(x: Value) -> LuaJsonValue {\n        match x {\n            Value::Null => LuaJsonValue::Null,\n            Value::Bool(v) => LuaJsonValue::Bool(v),\n            Value::Number(v) => LuaJsonValue::Number(v),\n            Value::String(v) => LuaJsonValue::String(v),\n            Value::Array(v) => LuaJsonValue::Array(v.into_iter()\n                .map(|x| x.into())\n                .collect()\n            ),\n            Value::Object(v) => LuaJsonValue::Object(v.into_iter()\n                .map(|(k, v)| (k, v.into()))\n                .collect()\n            ),\n        }\n    }\n}\n"
  },
  {
    "path": "src/keyboard.rs",
    "content": "// use getch;\nuse getch::Getch;\n\n#[cfg(not(windows))]\nuse termios::{self, tcsetattr, ICANON, ECHO};\n\npub struct Keyboard {\n    getch: Getch,\n}\n\nimpl Default for Keyboard {\n    #[inline]\n    fn default() -> Keyboard {\n        let getch = Getch::new();\n\n        Keyboard {\n            getch,\n        }\n    }\n}\n\nimpl Keyboard {\n    #[inline]\n    pub fn new() -> Keyboard {\n        Keyboard::default()\n    }\n\n    pub fn get(&self) -> Key {\n        loop {\n            let key = self.getch.getch();\n            // println!(\"{:?}\", key);\n            match key {\n                Ok(112) => return Key::P,\n                Ok(114) => return Key::R,\n                Ok(43)  => return Key::Plus,\n                Ok(45)  => return Key::Minus,\n                Ok(104) => return Key::H,\n                _ => (),\n            }\n        }\n    }\n\n    // since the getch thread is orphaned, we have to cleanup manually\n    pub fn reset() {\n        #[cfg(not(windows))]\n        {\n            if let Ok(mut termios) = termios::Termios::from_fd(0) {\n                termios.c_lflag |= ICANON|ECHO;\n                tcsetattr(0,termios::TCSADRAIN, &termios).unwrap_or(());\n            }\n        }\n    }\n}\n\n#[derive(Debug)]\npub enum Key {\n    H,\n    P,\n    R,\n    Plus,\n    Minus,\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "#![allow(clippy::mutex_atomic)]\n\nuse hlua_badtouch as hlua;\n\npub mod args;\npub mod config;\npub mod ctx;\npub mod db;\npub mod errors;\npub mod fsck;\npub mod html;\npub mod http;\npub mod json;\npub mod keyboard;\npub mod pb;\npub mod runtime;\npub mod scheduler;\npub mod sockets;\npub mod structs;\n#[cfg(target_os=\"linux\")]\npub mod ulimit;\npub mod utils;\n"
  },
  {
    "path": "src/main.rs",
    "content": "use authoscope::args::{self, Args, SubCommand};\nuse authoscope::ctx::Script;\nuse authoscope::errors::*;\nuse authoscope::fsck;\nuse authoscope::utils;\nuse authoscope::config::Config;\nuse authoscope::pb::ProgressBar;\nuse authoscope::scheduler::{Scheduler, Attempt, Creds, Msg};\nuse authoscope::keyboard::{Keyboard, Key};\n\nuse colored::*;\nuse env_logger::Env;\nuse num_format::{Locale, ToFormattedString};\nuse std::thread;\nuse std::fs::File;\nuse std::sync::Arc;\nuse std::time::{Duration, Instant};\nuse std::io::prelude::*;\nuse structopt::StructOpt;\n\nenum Report {\n    Some(File),\n    None\n}\n\nimpl Report {\n    pub fn open(path: Option<String>) -> Result<Report> {\n        match path {\n            Some(path) => Ok(Report::Some(File::create(path)?)),\n            None => Ok(Report::None),\n        }\n    }\n\n    pub fn write_creds(&mut self, user: &str, password: &str, script: &str) -> Result<()> {\n        if let Report::Some(ref mut f) = *self {\n            writeln!(f, \"{}:{}:{}\", script, user, password)?;\n        }\n        Ok(())\n    }\n\n    pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {\n        if let Report::Some(ref mut f) = *self {\n            writeln!(f, \"{}:{}\", script, user)?;\n        }\n        Ok(())\n    }\n}\n\nmacro_rules! tinfof {\n    ($arg1:tt, $fmt:expr, $($arg:tt)*) => (\n        $arg1.bold().to_string() + \" \" + &(format!($fmt, $($arg)*).dimmed().to_string())\n    );\n}\n\nmacro_rules! tinfo {\n    ($arg1:tt, $fmt:expr, $($arg:tt)*) => (\n        println!(\"{}\", tinfof!($arg1, $fmt, $($arg)*));\n    );\n}\n\nfn setup_dictionary_attack(pool: &mut Scheduler, args: args::Dict, config: &Arc<Config>) -> Result<usize> {\n    let users = utils::load_list(&args.users_path)\n        .context(\"Failed to load users\")?;\n    tinfo!(\"[+]\", \"loaded {} users\", users.len());\n    let passwords = utils::load_list(&args.passwords_path)\n        .context(\"Failed to load passwords\")?;\n    tinfo!(\"[+]\", \"loaded {} passwords\", passwords.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = users.len() * passwords.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\",\n        attempts.to_formatted_string(&Locale::en),\n        pool.max_count());\n\n    for user in &users {\n        for password in &passwords {\n            for script in &scripts {\n                let attempt = Attempt::new(user, password, script);\n                pool.run(attempt);\n            }\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn setup_combolist_attack(pool: &mut Scheduler, args: args::Combo, config: &Arc<Config>) -> Result<usize> {\n    let creds = utils::load_combolist(&args.path)?;\n    tinfo!(\"[+]\", \"loaded {} credentials\", creds.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = creds.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\", attempts, pool.max_count());\n\n    for cred in creds {\n        // TODO: optimization if we only have once script\n        for script in &scripts {\n            let attempt = Attempt::bytes(&cred, script);\n            pool.run(attempt);\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn setup_enum_attack(pool: &mut Scheduler, args: args::Enum, config: &Arc<Config>) -> Result<usize> {\n    let users = utils::load_list(&args.users)\n        .context(\"Failed to load users\")?;\n    tinfo!(\"[+]\", \"loaded {} users\", users.len());\n    let scripts = utils::load_scripts(args.scripts, config)\n        .context(\"Failed to load scripts\")?;\n    tinfo!(\"[+]\", \"loaded {} scripts\", scripts.len());\n\n    let attempts = users.len() * scripts.len();\n    tinfo!(\"[*]\", \"submitting {} jobs to threadpool with {} workers\", attempts, pool.max_count());\n\n    for user in &users {\n        for script in &scripts {\n            let attempt = Attempt::enumerate(user, script);\n            pool.run(attempt);\n        }\n    }\n\n    Ok(attempts)\n}\n\nfn run_oneshot(oneshot: args::Run, config: Arc<Config>) -> Result<()> {\n    let script = Script::load(&oneshot.script, config)?;\n    let user = oneshot.user;\n\n    let valid = match oneshot.password {\n        Some(ref password) => script.run_creds(&user, password)?,\n        None => script.run_enum(&user)?,\n    };\n\n    if valid {\n        match oneshot.password {\n            Some(ref password) => println!(\"{}\", format_valid_creds(script.descr(), &user, password)),\n            None => println!(\"{}\", format_valid_enum(script.descr(), &user)),\n        }\n    } else if oneshot.exitcode {\n        std::process::exit(2);\n    }\n\n    Ok(())\n}\n\nfn format_valid_creds(script: &str, user: &str, password: &str) -> String {\n    format!(\"{} {}({}) => {:?}:{:?}\", \"[+]\".bold(), \"valid\".green(),\n        script.yellow(), user, password)\n}\n\nfn format_valid_enum(script: &str, user: &str) -> String {\n    format!(\"{} {}({}) => {:?}\", \"[+]\".bold(), \"valid\".green(),\n        script.yellow(), user)\n}\n\nfn log_filter(args: &Args) -> &'static str {\n    match args.verbose {\n        0 => \"warn\",\n        1 => \"info\",\n        _ => \"debug\",\n    }\n}\n\nfn main() -> Result<()> {\n    let args = Args::from_args();\n\n    env_logger::init_from_env(Env::default()\n        .default_filter_or(log_filter(&args)));\n\n    if atty::isnt(atty::Stream::Stdout) {\n        colored::control::SHOULD_COLORIZE.set_override(false);\n    }\n\n    let config = Arc::new(Config::load()?);\n    #[cfg(target_os=\"linux\")]\n    authoscope::ulimit::set_nofile(&config)\n        .context(\"Failed to set RLIMIT_NOFILE\")?;\n\n    let mut pool = Scheduler::new(args.workers);\n    let mut report = Report::open(args.output)?;\n\n    let attempts = match args.subcommand {\n        SubCommand::Dict(dict) => setup_dictionary_attack(&mut pool, dict, &config)?,\n        SubCommand::Combo(creds) => setup_combolist_attack(&mut pool, creds, &config)?,\n        SubCommand::Enum(enumerate) => setup_enum_attack(&mut pool, enumerate, &config)?,\n        SubCommand::Run(oneshot) => return run_oneshot(oneshot, config),\n        SubCommand::Fsck(fsck) => return fsck::run_fsck(&fsck),\n        SubCommand::Completions(completions) => return completions.gen(),\n    };\n\n    let tx = pool.tx();\n    thread::spawn(move || {\n        let kb = Keyboard::new();\n        loop {\n            let key = kb.get();\n            tx.send(Msg::Key(key)).expect(\"failed to send key\");\n        }\n    });\n\n    let mut pb = ProgressBar::new(attempts as u64);\n    pb.print_help();\n    pb.tick();\n\n    pool.resume();\n    let start = Instant::now();\n\n    let mut valid = 0;\n    let mut retries = 0;\n    let mut expired = 0;\n    while pool.has_work() {\n        match pool.recv() {\n            Msg::Key(key) => {\n                match key {\n                    Key::H => pb.print_help(),\n                    Key::P => {\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), \"pausing threads\".dimmed()));\n                        pool.pause();\n                    },\n                    Key::R => {\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), \"resuming threads\".dimmed()));\n                        pool.resume();\n                    },\n                    Key::Plus => {\n                        let num = pool.incr();\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), format!(\"increased to {} threads\", num).dimmed()));\n                    },\n                    Key::Minus => {\n                        let num = pool.decr();\n                        pb.writeln(format!(\"{} {}\", \"[*]\".bold(), format!(\"decreased to {} threads\", num).dimmed()));\n                    },\n                }\n                pb.tick();\n            },\n            Msg::Attempt(mut attempt, result) => {\n                match result {\n                    Ok(is_valid) => {\n                        if is_valid {\n                            match attempt.creds {\n                                Creds::Enum(_) => {\n                                    let user = attempt.user();\n                                    let script = attempt.script.descr();\n\n                                    pb.writeln(format_valid_enum(script, user));\n                                    report.write_enum(user, script)?;\n                                },\n                                _ => {\n                                    let user = attempt.user();\n                                    let password = attempt.password();\n                                    let script = attempt.script.descr();\n\n                                    pb.writeln(format_valid_creds(script, user, password));\n                                    report.write_creds(user, password, script)?;\n                                },\n                            };\n                            valid += 1;\n                        }\n                        pb.inc();\n                    },\n                    Err(err) => {\n                        pb.writeln(format!(\"{} {}({}, {}): {:?}\", \"[!]\".bold(), \"error\".red(), attempt.script.descr().yellow(), format!(\"{:?}:{:?}\", attempt.user(), attempt.password()).dimmed(), err));\n\n                        if attempt.ttl > 0 {\n                            // we have retries left\n                            retries += 1;\n                            attempt.ttl -= 1;\n                            pool.run(*attempt);\n                            pb.tick();\n                        } else {\n                            // giving up\n                            expired += 1;\n                            pb.inc();\n                        }\n                    }\n                };\n            },\n        }\n    }\n\n    // truncate precision\n    let elapsed = Duration::from_millis(start.elapsed().as_millis() as u64);\n\n    let average = elapsed / attempts as u32;\n    pb.finish_replace(tinfof!(\"[+]\", \"found {} valid credentials with {} attempts and {} retries after {} and on average {} per attempt. {} attempts expired.\\n\",\n            valid.to_formatted_string(&Locale::en),\n            attempts.to_formatted_string(&Locale::en),\n            retries.to_formatted_string(&Locale::en),\n            humantime::format_duration(elapsed),\n            humantime::format_duration(average),\n            expired.to_formatted_string(&Locale::en),\n    ));\n\n    Keyboard::reset();\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/pb.rs",
    "content": "// this file contains a wrapper around pbr to work around three things:\n//\n// - there is no function to write above the progress bar\n// - .draw() isn't exposed so we can't bypass the ratelimit in tick.\n//   This means we can't reliably redraw the graph after we wrote above it.\n//   We have to implement rate limiting in our wrapper to ensure we are\n//   able to bypass it when needed.\n// - using colored strings breaks pbr\n//\n// https://github.com/a8m/pb/pull/62\n\nuse colored::Colorize;\nuse std::fmt::Display;\nuse std::io::prelude::*;\nuse std::io::{self, Stdout};\nuse time::{self, Instant, Duration};\n\n\nmacro_rules! printfl {\n   ($w:expr, $($tt:tt)*) => {{\n        $w.write_all(&format!($($tt)*).as_bytes()).ok().expect(\"write_all() fail\");\n        $w.flush().ok().expect(\"flush() fail\");\n    }}\n}\n\npub struct ProgressBar {\n    pb: pbr::ProgressBar<Stdout>,\n    current: u64,\n    last_refresh_time: Instant,\n    max_refresh_rate: Option<time::Duration>,\n    atty: bool,\n}\n\nimpl ProgressBar {\n    #[inline]\n    pub fn new(total: u64) -> ProgressBar {\n        let mut pb = pbr::ProgressBar::new(total);\n        pb.format(\"(=> )\");\n\n        let now = Instant::now();\n        let refresh_rate = Duration::milliseconds(250);\n        let atty = atty::is(atty::Stream::Stdout);\n\n        ProgressBar {\n            pb,\n            current: 0,\n            last_refresh_time: now - refresh_rate,\n            max_refresh_rate: Some(refresh_rate),\n            atty,\n        }\n    }\n\n    #[inline]\n    pub fn draw(&mut self) {\n        if !self.atty {\n            return;\n        }\n\n        self.pb.tick()\n    }\n\n    #[inline]\n    pub fn print_help(&mut self) {\n        self.writeln(format!(\"{} {}\", \"[+]\".bold(),\n            \"[h] help, [p] pause, [r] resume, [+] increase threads, [-] decrease threads\".dimmed()));\n    }\n\n    #[inline]\n    pub fn writeln<T: Display>(&mut self, s: T) {\n        printfl!(io::stderr(), \"\\r\\x1B[2K{}\\n\", s);\n        self.draw()\n    }\n\n    #[inline]\n    pub fn tick(&mut self) {\n        let now = Instant::now();\n        if let Some(mrr) = self.max_refresh_rate {\n            if now - self.last_refresh_time < mrr {\n                return;\n            }\n        }\n\n        self.draw();\n\n        self.last_refresh_time = Instant::now();\n    }\n\n    #[inline]\n    pub fn inc(&mut self) {\n        if !self.atty {\n            return;\n        }\n\n        let now = Instant::now();\n        if let Some(mrr) = self.max_refresh_rate {\n            if now - self.last_refresh_time < mrr {\n                self.current += 1;\n                return;\n            }\n        }\n\n        self.pb.set(self.current);\n\n        self.last_refresh_time = Instant::now();\n    }\n\n    #[inline]\n    pub fn finish_replace<T: Display>(&self, s: T) {\n        if self.atty {\n            print!(\"\\r\\x1B[2K{}\", s);\n        } else {\n            print!(\"{}\", s);\n        }\n    }\n}\n"
  },
  {
    "path": "src/runtime.rs",
    "content": "use crate::hlua;\nuse crate::hlua::{AnyLuaValue, AnyHashableLuaValue, AnyLuaString};\nuse crate::hlua::AnyLuaValue::LuaString;\nuse crate::structs::LuaMap;\nuse crate::errors::*;\nuse crate::json;\nuse crate::db;\n\nuse digest::{\n    Digest,\n    block_buffer::Eager,\n    core_api::{BlockSizeUser, BufferKindUser, CoreProxy, FixedOutputCore, UpdateCore},\n    typenum::{IsLess, Le, NonZero, U256},\n    HashMarker, Mac,\n};\nuse hmac::Hmac;\nuse mysql::prelude::Queryable;\n\nuse reqwest::header::WWW_AUTHENTICATE;\nuse rand::RngCore;\n\nuse std::thread;\nuse std::time::Duration;\nuse std::process::Command;\nuse std::collections::HashMap;\nuse crate::ctx::State;\nuse crate::http::HttpRequest;\nuse crate::http::RequestOptions;\nuse crate::html;\n\n\nfn byte_array(bytes: AnyLuaValue) -> Result<Vec<u8>> {\n    match bytes {\n        AnyLuaValue::LuaAnyString(bytes) => Ok(bytes.0),\n        AnyLuaValue::LuaString(bytes) => Ok(bytes.into_bytes()),\n        AnyLuaValue::LuaArray(bytes) => {\n            Ok(bytes.into_iter()\n                .map(|num| match num.1 {\n                    AnyLuaValue::LuaNumber(num) if (0.0..=255.0).contains(&num) && (num % 1.0 == 0.0) =>\n                            Ok(num as u8),\n                    AnyLuaValue::LuaNumber(num) =>\n                            Err(format_err!(\"number is out of range: {:?}\", num)),\n                    _ => Err(format_err!(\"unexpected type: {:?}\", num)),\n                })\n                .collect::<Result<_>>()?)\n        },\n        _ => Err(format_err!(\"Invalid type: {:?}\", bytes)),\n    }\n}\n\nfn lua_bytes(bytes: &[u8]) -> AnyLuaValue {\n    let bytes = AnyLuaString(bytes.to_vec());\n    AnyLuaValue::LuaAnyString(bytes)\n}\n\npub fn base64_decode(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"base64_decode\", hlua::function1(move |bytes: String| -> Result<AnyLuaValue> {\n        base64::decode(&bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&bytes))\n    }))\n}\n\npub fn base64_encode(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"base64_encode\", hlua::function1(move |bytes: AnyLuaValue| -> Result<String> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| base64::encode(&bytes))\n    }))\n}\n\npub fn bcrypt(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"bcrypt\", hlua::function2(move |password: String, cost: u32| -> Result<String> {\n        bcrypt::hash(&password, cost)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn bcrypt_verify(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"bcrypt_verify\", hlua::function2(move |password: String, hashed: String| -> Result<bool> {\n        bcrypt::verify(&password, &hashed)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn clear_err(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"clear_err\", hlua::function0(move || {\n        state.clear_error()\n    }))\n}\n\npub fn execve(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"execve\", hlua::function2(move |prog: String, args: Vec<AnyLuaValue>| -> Result<i32> {\n        let args: Vec<_> = args.into_iter()\n                    .flat_map(|x| match x {\n                        LuaString(x) => Some(x),\n                        _ => None, // TODO: error\n                    })\n                    .collect();\n\n        let status = match Command::new(prog)\n                        .args(&args)\n                        .status()\n                        .context(\"Failed to spawn program\") {\n            Ok(status) => status,\n            Err(err) => return Err(state.set_error(err)),\n        };\n\n        let code = match status.code() {\n            Some(code) => code,\n            None => return Err(state.set_error(format_err!(\"Process didn't return exit code\"))),\n        };\n\n        Ok(code)\n    }))\n}\n\npub fn hex(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hex\", hlua::function1(move |bytes: AnyLuaValue| -> Result<String> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| {\n                let mut out = String::new();\n\n                for b in bytes {\n                    out += &format!(\"{:02x}\", b);\n                }\n\n                out\n            })\n    }))\n}\n\nfn hmac<D>(secret: AnyLuaValue, msg: AnyLuaValue) -> Result<AnyLuaValue>\n    where\n        D: CoreProxy,\n        D::Core: HashMarker\n            + UpdateCore\n            + FixedOutputCore\n            + BufferKindUser<BufferKind = Eager>\n            + Default\n            + Clone,\n        <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,\n        Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,\n{\n    let secret = byte_array(secret)?;\n    let msg = byte_array(msg)?;\n\n    let mut mac = match Hmac::<D>::new_from_slice(&secret) {\n        Ok(mac) => mac,\n        Err(_) => bail!(\"Invalid key length\"),\n    };\n    mac.update(&msg);\n    let result = mac.finalize();\n    Ok(lua_bytes(&result.into_bytes()))\n}\n\npub fn hmac_md5(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_md5\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<md5::Md5>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn hmac_sha1(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_sha1\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<sha1::Sha1>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn hmac_sha2_256(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_sha2_256\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<sha2::Sha256>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn hmac_sha2_512(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_sha2_512\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<sha2::Sha512>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn hmac_sha3_256(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_sha3_256\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<sha3::Sha3_256>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn hmac_sha3_512(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"hmac_sha3_512\", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {\n        hmac::<sha3::Sha3_512>(secret, msg)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn html_select(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"html_select\", hlua::function2(move |html: String, selector: String| -> Result<AnyLuaValue> {\n        html::html_select(&html, &selector)\n            .map_err(|err| state.set_error(err))\n            .map(|x| x.into())\n    }))\n}\n\npub fn html_select_list(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"html_select_list\", hlua::function2(move |html: String, selector: String| -> Result<Vec<AnyLuaValue>> {\n        html::html_select_list(&html, &selector)\n            .map_err(|err| state.set_error(err))\n            .map(|x| x.into_iter().map(|x| x.into()).collect())\n    }))\n}\n\npub fn http_basic_auth(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"http_basic_auth\", hlua::function3(move |url: String, user: String, password: String| -> Result<bool> {\n        let client = reqwest::blocking::Client::new();\n\n        client.get(&url)\n            .basic_auth(user, Some(password))\n            .send()\n            .context(\"http request failed\")\n            .map_err(|err| state.set_error(err))\n            .map(|response| {\n                info!(\"http_basic_auth: {:?}\", response);\n                response.headers().get(WWW_AUTHENTICATE).is_none() &&\n                    response.status() != reqwest::StatusCode::UNAUTHORIZED\n            })\n    }))\n}\n\npub fn http_mksession(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"http_mksession\", hlua::function0(move || -> String {\n        state.http_mksession()\n    }))\n}\n\npub fn http_request(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"http_request\", hlua::function4(move |session: String, method: String, url: String, options: AnyLuaValue| -> Result<AnyLuaValue> {\n        RequestOptions::try_from(options)\n            .context(\"Invalid request options\")\n            .map_err(|err| state.set_error(err))\n            .map(|options| {\n                state.http_request(&session, method, url, options).into()\n            })\n    }))\n}\n\npub fn http_send(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"http_send\", hlua::function1(move |request: AnyLuaValue| -> Result<HashMap<AnyHashableLuaValue, AnyLuaValue>> {\n        let req = match HttpRequest::try_from(request)\n                                .context(\"Invalid http request object\") {\n            Ok(req) => req,\n            Err(err) => return Err(state.set_error(err)),\n        };\n\n        req.send(&state)\n            .map_err(|err| state.set_error(err))\n            .map(|resp| resp.into())\n    }))\n}\n\npub fn json_decode(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"json_decode\", hlua::function1(move |x: String| -> Result<AnyLuaValue> {\n        json::decode(&x)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn json_encode(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"json_encode\", hlua::function1(move |x: AnyLuaValue| -> Result<String> {\n        json::encode(x)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn last_err(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"last_err\", hlua::function0(move || -> AnyLuaValue {\n        match state.last_error() {\n            Some(err) => AnyLuaValue::LuaString(err),\n            None => AnyLuaValue::LuaNil,\n        }\n    }))\n}\n\npub fn ldap_bind(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"ldap_bind\", hlua::function3(move |url: String, dn: String, password: String| -> Result<bool> {\n        let mut sock = match ldap3::LdapConn::new(&url)\n                        .context(\"ldap connection failed\") {\n            Ok(sock) => sock,\n            Err(err) => return Err(state.set_error(err)),\n        };\n\n        sock.simple_bind(&dn, &password)\n            .context(\"Fatal error during simple_bind\")\n            .map_err(|err| state.set_error(err))\n            .map(|result| {\n                debug!(\"ldap_bind: {:?}\", result);\n                result.success().is_ok()\n            })\n    }))\n}\n\npub fn ldap_escape(lua: &mut hlua::Lua, _: State) {\n    lua.set(\"ldap_escape\", hlua::function1(move |s: String| -> String {\n        ldap3::dn_escape(s).to_string()\n    }))\n}\n\npub fn ldap_search_bind(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"ldap_search_bind\", hlua::function6(move |url: String, search_user: String, search_pw: String, base_dn: String, user: String, password: String| -> Result<bool> {\n        let mut sock = ldap3::LdapConn::new(&url)\n            .context(\"ldap connection failed\")\n            .map_err(|err| state.set_error(err))?;\n\n\n        let result = sock.simple_bind(&search_user, &search_pw)\n            .context(\"Fatal error during simple_bind with search user\")\n            .map_err(|err| state.set_error(err))?;\n\n        if result.success().is_err() {\n            return Err(state.set_error(format_err!(\"Login with search user failed\")));\n        }\n\n        let search = format!(\"uid={}\", ldap3::dn_escape(user));\n        let result = sock.search(&base_dn, ldap3::Scope::Subtree, &search, vec![\"*\"])\n            .context(\"Fatal error during ldap search\")\n            .map_err(|err| state.set_error(err))?;\n\n        let entries = result.success()\n            .context(\"ldap search failed\")\n            .map(|result| result.0)\n            .map_err(|err| state.set_error(err))?;\n\n        // take the first result\n        if let Some(entry) = entries.into_iter().next() {\n            let entry = ldap3::SearchEntry::construct(entry);\n\n            // we got the DN, try to login\n            let result = sock.simple_bind(&entry.dn, &password)\n                .context(\"Fatal error during simple_bind\")\n                .map_err(|err| state.set_error(err))?;\n\n            // println!(\"{:?}\", result);\n\n            Ok(result.success().is_ok())\n        } else {\n            Ok(false)\n        }\n    }))\n}\n\npub fn md5(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"md5\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&md5::Md5::digest(&bytes)))\n    }))\n}\n\npub fn mysql_connect(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"mysql_connect\", hlua::function4(move |host: String, port: u16, user: String, password: String| -> Result<String> {\n        let builder = mysql::OptsBuilder::new()\n            .ip_or_hostname(Some(host))\n            .tcp_port(port)\n            .prefer_socket(false)\n            .user(Some(user))\n            .pass(Some(password));\n\n        mysql::Conn::new(builder)\n            .map_err(|err| state.set_error(err))\n            .map(|sock| state.mysql_register(sock))\n    }))\n}\n\npub fn mysql_query(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"mysql_query\", hlua::function3(move |session: String, query: String, params: HashMap<AnyHashableLuaValue, AnyLuaValue>| -> Result<Vec<AnyLuaValue>> {\n        let params = LuaMap::from(params);\n\n        let sock = state.mysql_session(&session);\n        let mut sock = sock.lock().unwrap();\n        let rows = sock.exec_iter(query, params)\n            .context(\"Failed to execute query\")\n            .map_err(|err| state.set_error(err))?;\n\n        let columns = rows.columns();\n        let mut columns_results = Vec::new();\n        for column in columns.as_ref() {\n            let column = column.name_str().to_string();\n            columns_results.push(column);\n        }\n\n        let mut result = Vec::new();\n        for row in rows {\n            let row = row?; // TODO: handle error\n\n            let mut map = LuaMap::new();\n            for (i, column) in columns_results.iter().enumerate() {\n                map.insert(column, db::mysql::mysql_value_to_lua(row[i].clone()));\n            }\n\n            result.push(map.into());\n        }\n\n        Ok(result)\n    }))\n}\n\nfn format_lua(out: &mut String, x: &AnyLuaValue) {\n    match *x {\n        AnyLuaValue::LuaNil => out.push_str(\"null\"),\n        AnyLuaValue::LuaString(ref x) => out.push_str(&format!(\"{:?}\", x)),\n        AnyLuaValue::LuaNumber(ref x) => out.push_str(&format!(\"{:?}\", x)),\n        AnyLuaValue::LuaAnyString(ref x) => out.push_str(&format!(\"{:?}\", x.0)),\n        AnyLuaValue::LuaBoolean(ref x) => out.push_str(&format!(\"{:?}\", x)),\n        AnyLuaValue::LuaArray(ref x) => {\n            out.push('{');\n            let mut first = true;\n\n            for &(ref k, ref v) in x {\n                if !first {\n                    out.push_str(\", \");\n                }\n\n                let mut key = String::new();\n                format_lua(&mut key, k);\n\n                let mut value = String::new();\n                format_lua(&mut value, v);\n\n                out.push_str(&format!(\"{}: {}\", key, value));\n\n                first = false;\n            }\n            out.push('}');\n        },\n        AnyLuaValue::LuaOther => out.push_str(\"LuaOther\"),\n    }\n}\n\npub fn print(lua: &mut hlua::Lua, _: State) {\n    // this function doesn't print to the terminal safely\n    // only use this for debugging\n    lua.set(\"print\", hlua::function1(move |val: AnyLuaValue| {\n        // println!(\"{:?}\", val);\n        let mut out = String::new();\n        format_lua(&mut out, &val);\n        println!(\"{}\", out);\n    }))\n}\n\npub fn rand(lua: &mut hlua::Lua, _: State) {\n    lua.set(\"rand\", hlua::function2(move |min: u32, max: u32| -> u32 {\n        let mut rng = rand::thread_rng();\n        (rng.next_u32() + min) % max\n    }))\n}\n\npub fn randombytes(lua: &mut hlua::Lua, _: State) {\n    lua.set(\"randombytes\", hlua::function1(move |num: u32| -> AnyLuaValue {\n        let mut x = vec![0; num as usize];\n        let mut rng = rand::thread_rng();\n        rng.fill_bytes(x.as_mut_slice());\n        lua_bytes(&x)\n    }))\n}\n\npub fn sha1(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sha1\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&sha1::Sha1::digest(&bytes)))\n    }))\n}\n\npub fn sha2_256(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sha2_256\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&sha2::Sha256::digest(&bytes)))\n    }))\n}\n\npub fn sha2_512(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sha2_512\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&sha2::Sha512::digest(&bytes)))\n    }))\n}\n\npub fn sha3_256(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sha3_256\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&sha3::Sha3_256::digest(&bytes)))\n    }))\n}\n\npub fn sha3_512(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sha3_512\", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {\n        byte_array(bytes)\n            .map_err(|err| state.set_error(err))\n            .map(|bytes| lua_bytes(&sha3::Sha3_512::digest(&bytes)))\n    }))\n}\n\npub fn sleep(lua: &mut hlua::Lua, _: State) {\n    lua.set(\"sleep\", hlua::function1(move |n: i32| {\n        thread::sleep(Duration::from_secs(n as u64));\n        0\n    }))\n}\n\npub fn sock_connect(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_connect\", hlua::function3(move |host: String, port: u16, _settings: AnyLuaValue| -> Result<String> {\n        state.sock_connect(&host, port)\n            .map_err(|err| state.set_error(err))\n    }))\n}\n\npub fn sock_send(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_send\", hlua::function2(move |sock: String, bytes: AnyLuaValue| -> Result<()> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let bytes = byte_array(bytes)\n            .map_err(|err| state.set_error(err))?;\n\n        sock.send(&bytes)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(())\n    }))\n}\n\npub fn sock_recv(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recv\", hlua::function1(move |sock: String| -> Result<AnyLuaValue> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let bytes = sock.recv()\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(lua_bytes(&bytes))\n    }))\n}\n\npub fn sock_sendline(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_sendline\", hlua::function2(move |sock: String, line: String| -> Result<()> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        sock.sendline(&line)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(())\n    }))\n}\n\npub fn sock_recvline(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvline\", hlua::function1(move |sock: String| -> Result<String> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let line = sock.recvline()\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(line)\n    }))\n}\n\npub fn sock_recvall(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvall\", hlua::function1(move |sock: String| -> Result<AnyLuaValue> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let bytes = sock.recvall()\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(lua_bytes(&bytes))\n    }))\n}\n\npub fn sock_recvline_contains(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvline_contains\", hlua::function2(move |sock: String, needle: String| -> Result<String> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let line = sock.recvline_contains(&needle)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(line)\n    }))\n}\n\npub fn sock_recvline_regex(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvline_regex\", hlua::function2(move |sock: String, regex: String| -> Result<String> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let line = sock.recvline_regex(&regex)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(line)\n    }))\n}\n\npub fn sock_recvn(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvn\", hlua::function2(move |sock: String, n: u32| -> Result<AnyLuaValue> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let bytes = sock.recvn(n)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(lua_bytes(&bytes))\n    }))\n}\n\npub fn sock_recvuntil(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_recvuntil\", hlua::function2(move |sock: String, delim: AnyLuaValue| -> Result<AnyLuaValue> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let delim = byte_array(delim)\n            .map_err(|err| state.set_error(err))?;\n\n        let bytes = sock.recvuntil(&delim)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(lua_bytes(&bytes))\n    }))\n}\n\npub fn sock_sendafter(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_sendafter\", hlua::function3(move |sock: String, delim: AnyLuaValue, bytes: AnyLuaValue| -> Result<()> {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        let delim = byte_array(delim)\n            .map_err(|err| state.set_error(err))?;\n\n        let bytes = byte_array(bytes)\n            .map_err(|err| state.set_error(err))?;\n\n        sock.sendafter(&delim, &bytes)\n            .map_err(|err| state.set_error(err))?;\n\n        Ok(())\n    }))\n}\n\npub fn sock_newline(lua: &mut hlua::Lua, state: State) {\n    lua.set(\"sock_newline\", hlua::function2(move |sock: String, newline: String| {\n        let sock = state.get_sock(&sock);\n        let mut sock = sock.lock().unwrap();\n\n        sock.newline(newline);\n    }))\n}\n"
  },
  {
    "path": "src/scheduler.rs",
    "content": "use std::str;\nuse crate::ctx::Script;\nuse threadpool::ThreadPool;\nuse crate::keyboard;\nuse crate::errors::Result;\nuse std::sync::{mpsc, Arc, Mutex, Condvar};\n\n#[derive(Debug)]\npub enum Creds {\n    Tuple((Arc<String>, Arc<String>)),\n    Bytes(Arc<Vec<u8>>),\n    Enum(Arc<String>),\n}\n\nimpl Creds {\n    // BEWARE: these functions are somewhat hot\n\n    #[inline]\n    pub fn user(&self) -> &str {\n        match *self {\n            Creds::Tuple((ref user, ref _password)) => user.as_str(),\n            Creds::Bytes(ref bytes) => {\n                // we already know it's valid\n\n                let idx = bytes.iter().position(|x| *x == b':').unwrap();\n                str::from_utf8(&bytes[..idx]).unwrap()\n            },\n            Creds::Enum(ref user) => user.as_str(),\n        }\n    }\n\n    #[inline]\n    pub fn password(&self) -> &str {\n        match *self {\n            Creds::Tuple((ref _user, ref password)) => password.as_str(),\n            Creds::Bytes(ref bytes) => {\n                // we already know it's valid\n\n                let idx = bytes.iter().position(|x| *x == b':').unwrap();\n                str::from_utf8(&bytes[idx+1..]).unwrap()\n            },\n            // TODO: empty string is technically not correct\n            Creds::Enum(_) => \"\",\n        }\n    }\n}\n\n#[derive(Debug)]\npub struct Attempt {\n    pub creds: Creds,\n    pub script: Arc<Script>,\n    pub ttl: u8,\n}\n\nimpl Attempt {\n    #[inline]\n    pub fn new(user: &Arc<String>, password: &Arc<String>, script: &Arc<Script>) -> Attempt {\n        Attempt {\n            creds: Creds::Tuple((user.clone(), password.clone())),\n            script: script.clone(),\n            ttl: 5,\n        }\n    }\n\n    #[inline]\n    pub fn bytes(bytes: &Arc<Vec<u8>>, script: &Arc<Script>) -> Attempt {\n        Attempt {\n            creds: Creds::Bytes(bytes.clone()),\n            script: script.clone(),\n            ttl: 5,\n        }\n    }\n\n    #[inline]\n    pub fn enumerate(user: &Arc<String>, script: &Arc<Script>) -> Attempt {\n        Attempt {\n            creds: Creds::Enum(user.clone()),\n            script: script.clone(),\n            ttl: 5,\n        }\n    }\n\n    #[inline]\n    pub fn user(&self) -> &str {\n        self.creds.user()\n    }\n\n    #[inline]\n    pub fn password(&self) -> &str {\n        self.creds.password()\n    }\n\n    #[inline]\n    pub fn run(self, tx: &mpsc::Sender<Msg>) {\n        let result = match self.creds {\n            Creds::Enum(_) => self.script.run_enum(self.user()),\n            _ => self.script.run_creds(self.user(), self.password()),\n        };\n        tx.send(Msg::Attempt(Box::new(self), result)).expect(\"failed to send result\");\n    }\n}\n\n#[derive(Debug)]\npub enum Msg {\n    Attempt(Box<Attempt>, Result<bool>),\n    Key(keyboard::Key),\n}\n\npub struct Scheduler {\n    pool: ThreadPool,\n    tx: mpsc::Sender<Msg>,\n    rx: mpsc::Receiver<Msg>,\n    num_threads: usize,\n    inflight: usize,\n    pause_trigger: Arc<(Mutex<bool>, Condvar)>,\n}\n\nimpl Scheduler {\n    #[inline]\n    pub fn new(workers: usize) -> Scheduler {\n        let (tx, rx) = mpsc::channel();\n        Scheduler {\n            pool: ThreadPool::new(workers),\n            tx,\n            rx,\n            num_threads: workers,\n            inflight: 0,\n            pause_trigger: Arc::new((Mutex::new(true), Condvar::new())),\n        }\n    }\n\n    #[inline]\n    pub fn pause(&mut self) {\n        let &(ref lock, _) = &*self.pause_trigger;\n        let mut paused = lock.lock().unwrap();\n        *paused = true;\n    }\n\n    #[inline]\n    pub fn resume(&mut self) {\n        let &(ref lock, ref cvar) = &*self.pause_trigger;\n        let mut paused = lock.lock().unwrap();\n        *paused = false;\n        cvar.notify_all();\n    }\n\n    #[inline]\n    pub fn incr(&mut self) -> usize {\n        self.num_threads += 1;\n        self.pool.set_num_threads(self.num_threads);\n        self.num_threads\n    }\n\n    #[inline]\n    pub fn decr(&mut self) -> usize {\n        if self.num_threads == 1 {\n            return self.num_threads;\n        }\n\n        self.num_threads -= 1;\n        self.pool.set_num_threads(self.num_threads);\n        self.num_threads\n    }\n\n    #[inline]\n    pub fn tx(&self) -> mpsc::Sender<Msg> {\n        self.tx.clone()\n    }\n\n    #[inline]\n    pub fn max_count(&self) -> usize {\n        self.pool.max_count()\n    }\n\n    #[inline]\n    pub fn has_work(&self) -> bool {\n        self.inflight > 0\n    }\n\n    #[inline]\n    pub fn run(&mut self, attempt: Attempt) {\n        let tx = self.tx.clone();\n        let pause_trigger = self.pause_trigger.clone();\n        self.inflight += 1;\n\n        self.pool.execute(move || {\n            // verify the pause trigger isn't enabled\n            // if it is locked, block until it is unlocked\n            let &(ref lock, ref cvar) = &*pause_trigger;\n            {\n                let mut paused = lock.lock().unwrap();\n                while *paused {\n                    paused = cvar.wait(paused).unwrap();\n                }\n            }\n            attempt.run(&tx);\n        });\n    }\n\n    #[inline]\n    pub fn recv(&mut self) -> Msg {\n        self.inflight -= 1;\n        self.rx.recv().unwrap()\n    }\n}\n"
  },
  {
    "path": "src/sockets.rs",
    "content": "use crate::errors::*;\n\nuse bufstream::BufStream;\nuse regex::Regex;\n\nuse std::str;\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufRead;\nuse std::net::TcpStream;\nuse std::net::ToSocketAddrs;\n\n\n#[derive(Debug)]\npub struct Socket {\n    stream: BufStream<TcpStream>,\n    newline: String,\n}\n\nimpl Socket {\n    pub fn connect(host: &str, port: u16) -> Result<Socket> {\n        let addrs = (host, port).to_socket_addrs()?;\n\n        let mut errors = Vec::new();\n\n        for addr in addrs {\n            debug!(\"connecting to {:?}\", addr);\n            match TcpStream::connect(&addr) {\n                Ok(socket) => {\n                    debug!(\"successfully connected to {:?}\", addr);\n                    let stream = BufStream::new(socket);\n\n                    return Ok(Socket {\n                        stream,\n                        newline: String::from(\"\\n\"),\n                    });\n                },\n                Err(err) => errors.push((addr, err)),\n            }\n        }\n\n        if errors.is_empty() {\n            bail!(\"no dns records found\");\n        } else {\n            bail!(\"couldn't connect: {:?}\", errors);\n        }\n    }\n\n    pub fn send(&mut self, data: &[u8]) -> Result<()> {\n        match str::from_utf8(data) {\n            Ok(data) => debug!(\"send: {:?}\", data),\n            Err(_) => debug!(\"send: {:?}\", data),\n        };\n        self.stream.write_all(data)?;\n        self.stream.flush()?;\n        Ok(())\n    }\n\n    pub fn recv(&mut self) -> Result<Vec<u8>> {\n        let mut buf = [0; 4096];\n        let n = self.stream.read(&mut buf)?;\n        let data = buf[..n].to_vec();\n        match str::from_utf8(&data) {\n            Ok(data) => debug!(\"recv: {:?}\", data),\n            Err(_) => debug!(\"recv: {:?}\", data),\n        };\n        Ok(data)\n    }\n\n    pub fn sendline(&mut self, line: &str) -> Result<()> {\n        let line = format!(\"{}{}\", line, self.newline);\n        self.send(line.as_bytes())\n    }\n\n    pub fn recvline(&mut self) -> Result<String> {\n        let needle = self.newline.clone();\n        let buf = self.recvuntil(needle.as_bytes())?;\n        let line = String::from_utf8(buf)\n            .context(\"Failed to decode utf8\")?;\n        Ok(line)\n    }\n\n    pub fn recvall(&mut self) -> Result<Vec<u8>> {\n        let mut buf = Vec::new();\n        self.stream.read_to_end(&mut buf)?;\n        match str::from_utf8(&buf) {\n            Ok(buf) => debug!(\"recvall: {:?}\", buf),\n            Err(_) => debug!(\"recvall: {:?}\", buf),\n        };\n        Ok(buf)\n    }\n\n    pub fn recvline_contains(&mut self, needle: &str) -> Result<String> {\n        loop {\n            let line = self.recvline()?;\n            if line.contains(needle) {\n                return Ok(line);\n            }\n        }\n    }\n\n    pub fn recvline_regex(&mut self, regex: &str) -> Result<String> {\n        let regex = Regex::new(regex)?;\n        loop {\n            let line = self.recvline()?;\n            if regex.is_match(&line) {\n                return Ok(line);\n            }\n        }\n    }\n\n    pub fn recvn(&mut self, n: u32) -> Result<Vec<u8>> {\n        let mut buf = vec![0; n as usize];\n        self.stream.read_exact(buf.as_mut_slice())?;\n        match str::from_utf8(&buf) {\n            Ok(buf) => debug!(\"recvn: {:?}\", buf),\n            Err(_) => debug!(\"recvn: {:?}\", buf),\n        };\n        Ok(buf.to_vec())\n    }\n\n    pub fn recvuntil(&mut self, delim: &[u8]) -> Result<Vec<u8>> {\n        let mut buf = Vec::new();\n\n        let delim_len = delim.len();\n\n        loop {\n            let (done, used) = {\n                let available = match self.stream.fill_buf() {\n                    Ok(n) => n,\n                    Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue,\n                    Err(e) => return Err(e.into())\n                };\n\n                match available.windows(delim_len).position(|window| window == delim) {\n                    Some(i) => {\n                        buf.extend_from_slice(&available[..i + delim_len]);\n                        (true, i + delim_len)\n                    }\n                    None => {\n                        buf.extend_from_slice(available);\n                        (false, available.len())\n                    }\n                }\n            };\n            self.stream.consume(used);\n\n            if done || used == 0 {\n                match str::from_utf8(&buf) {\n                    Ok(buf) => debug!(\"recvuntil: {:?}\", buf),\n                    Err(_) => debug!(\"recvuntil: {:?}\", buf),\n                };\n                return Ok(buf);\n            }\n        }\n    }\n\n    pub fn sendafter(&mut self, delim: &[u8], data: &[u8]) -> Result<()> {\n        self.recvuntil(delim)?;\n        self.send(data)\n    }\n\n    pub fn newline<I: Into<String>>(&mut self, delim: I) {\n        self.newline = delim.into();\n    }\n}\n"
  },
  {
    "path": "src/structs.rs",
    "content": "use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};\n\nuse std::collections;\nuse std::collections::HashMap;\n\n\n#[derive(Debug, Default)]\npub struct LuaMap(HashMap<AnyHashableLuaValue, AnyLuaValue>);\n\nimpl LuaMap {\n    #[inline]\n    pub fn new() -> LuaMap {\n        LuaMap::default()\n    }\n\n    #[inline]\n    pub fn is_empty(&self) -> bool {\n        self.0.is_empty()\n    }\n\n    #[inline]\n    pub fn insert<K: Into<String>, V: Into<AnyLuaValue>>(&mut self, k: K, v: V) {\n        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), v.into());\n    }\n\n    #[inline]\n    pub fn insert_str<K: Into<String>, V: Into<String>>(&mut self, k: K, v: V) {\n        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), AnyLuaValue::LuaString(v.into()));\n    }\n\n    #[inline]\n    pub fn insert_num<K: Into<String>>(&mut self, k: K, v: f64) {\n        self.0.insert(AnyHashableLuaValue::LuaString(k.into()), AnyLuaValue::LuaNumber(v));\n    }\n}\n\nimpl IntoIterator for LuaMap {\n    type Item = (AnyHashableLuaValue, AnyLuaValue);\n    type IntoIter = collections::hash_map::IntoIter<AnyHashableLuaValue, AnyLuaValue>;\n\n    fn into_iter(self) -> Self::IntoIter {\n        self.0.into_iter()\n    }\n}\n\nimpl From<HashMap<String, String>> for LuaMap {\n    fn from(x: HashMap<String, String>) -> LuaMap {\n        let mut map = LuaMap::new();\n        for (k, v) in x {\n            map.insert_str(k, v);\n        }\n        map\n    }\n}\n\nimpl From<HashMap<AnyHashableLuaValue, AnyLuaValue>> for LuaMap {\n    fn from(x: HashMap<AnyHashableLuaValue, AnyLuaValue>) -> LuaMap {\n        LuaMap(x)\n    }\n}\n\nimpl From<Vec<(AnyLuaValue, AnyLuaValue)>> for LuaMap {\n    fn from(x: Vec<(AnyLuaValue, AnyLuaValue)>) -> LuaMap {\n        let mut map = LuaMap::new();\n\n        for (k, v) in x {\n            // TODO: handle unknown types\n            if let AnyLuaValue::LuaString(k) = k {\n                map.insert(k, v);\n            }\n        }\n\n        map\n    }\n}\n\nimpl From<LuaMap> for HashMap<AnyHashableLuaValue, AnyLuaValue> {\n    fn from(x: LuaMap) -> HashMap<AnyHashableLuaValue, AnyLuaValue> {\n        x.0\n    }\n}\n\nimpl From<LuaMap> for AnyLuaValue {\n    fn from(x: LuaMap) -> AnyLuaValue {\n        AnyLuaValue::LuaArray(\n            x.into_iter()\n                .filter_map(|(k, v)| {\n                    match k {\n                        AnyHashableLuaValue::LuaString(x) => Some((AnyLuaValue::LuaString(x), v)),\n                        _ => None, // TODO: unknown types are discarded\n                    }\n                })\n                .collect()\n        )\n    }\n}\n"
  },
  {
    "path": "src/ulimit.rs",
    "content": "use rlimit::Resource;\nuse crate::errors::*;\nuse crate::config::Config;\n\n\npub fn set_nofile(config: &Config) -> Result<()> {\n    let (soft_limit, hard_limit) = rlimit::getrlimit(Resource::NOFILE)?;\n    debug!(\"soft_limit={:?}, hard_limit={:?}\", soft_limit, hard_limit);\n\n    let new_hard_limit = config.runtime.rlimit_nofile.unwrap_or(hard_limit);\n    info!(\"setting NOFILE limit to {:?}\", new_hard_limit);\n    rlimit::setrlimit(Resource::NOFILE, new_hard_limit, new_hard_limit)?;\n\n    let (soft_limit, hard_limit) = rlimit::getrlimit(Resource::NOFILE)?;\n    debug!(\"soft_limit={:?}, hard_limit={:?}\", soft_limit, hard_limit);\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/utils.rs",
    "content": "use crate::config::Config;\nuse crate::ctx;\nuse crate::errors::*;\nuse std::str;\nuse std::fs::{self, File};\nuse std::sync::Arc;\nuse std::io::{self, BufReader};\nuse std::io::prelude::*;\nuse std::iter;\nuse std::path::Path;\nuse rand::{Rng, thread_rng};\nuse rand::distributions::Alphanumeric;\n\npub fn random_string(len: usize) -> String {\n    let mut rng = thread_rng();\n    iter::repeat(())\n        .map(|()| rng.sample(Alphanumeric))\n        .map(char::from)\n        .take(len)\n        .collect()\n}\n\npub fn load_list<P: AsRef<Path>>(path: P) -> Result<Vec<Arc<String>>> {\n    let f = File::open(path)?;\n    let file = BufReader::new(&f);\n    let lines: io::Result<_> = file.lines()\n            .map(|x| x.map(Arc::new))\n            .collect();\n    Ok(lines?)\n}\n\npub fn load_combolist<P: AsRef<Path>>(path: P) -> Result<Vec<Arc<Vec<u8>>>> {\n    let f = File::open(path)?;\n    let mut file = BufReader::new(&f);\n\n    let mut creds = Vec::new();\n\n    let mut buf = Vec::new();\n    const DELIM: u8 = b'\\n';\n\n    while 0 < file.read_until(DELIM, &mut buf)? {\n        if buf[buf.len() - 1] == DELIM {\n            buf.pop();\n        }\n\n        // ensure line is valid utf8\n        str::from_utf8(&buf)\n            .context(\"Failed to decode utf8\")?;\n\n        if buf.iter().any(|x| *x == b':') {\n            creds.push(Arc::new(buf.clone()));\n        } else {\n            return Err(format_err!(\"Invalid list format: {:?}\", buf))\n        }\n\n        buf.clear();\n    }\n\n    Ok(creds)\n}\n\npub fn load_scripts(paths: Vec<String>, config: &Arc<Config>) -> Result<Vec<Arc<ctx::Script>>> {\n    let mut scripts = Vec::new();\n\n    for path in paths {\n        let meta = fs::metadata(&path)?;\n\n        if meta.is_dir() {\n            for path in fs::read_dir(path)? {\n                let path = path?.path();\n                let path = path.to_str().unwrap();\n                let script = Arc::new(ctx::Script::load(path, config.clone())?);\n                scripts.push(script);\n            }\n        } else {\n            let script = Arc::new(ctx::Script::load(&path, config.clone())?);\n            scripts.push(script);\n        }\n    }\n\n    Ok(scripts)\n}\n"
  }
]